lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | 8059bcbd4cd139376ec001ffa2715b5694ccbcc1 | 0 | SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java | /*
* Copyright 2017, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.spine3.server.event;
import org.spine3.annotation.Internal;
import org.spine3.base.Event;
import org.spine3.base.EventId;
import org.spine3.base.Events;
import org.spine3.server.entity.AbstractEntity;
import java.util.Comparator;
/**
* Stores an event.
*
* <p>{@code EventEntity} is a Spine internal {@link org.spine3.server.entity.Entity Entity} type,
* which is not designed for the direct usage. Both API and behaviour of this class may are subjects
* of change.
*
* @author Alexander Yevsyukov
*/
@Internal
public class EventEntity extends AbstractEntity<EventId, Event> {
/**
* Compares event entities by timestamps of events.
*/
private static final Comparator<EventEntity> comparator = new Comparator<EventEntity>() {
@Override
public int compare(EventEntity e1, EventEntity e2) {
final Event event1 = e1.getState();
final Event event2 = e2.getState();
final int result = Events.eventComparator()
.compare(event1, event2);
return result;
}
};
EventEntity(EventId id) {
super(id);
}
EventEntity(Event event) {
this(event.getId());
updateState(event);
}
/**
* Returns comparator which sorts event entities chronologically.
*/
static Comparator<EventEntity> comparator() {
return comparator;
}
}
| server/src/main/java/org/spine3/server/event/EventEntity.java | /*
* Copyright 2017, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.spine3.server.event;
import org.spine3.base.Event;
import org.spine3.base.EventId;
import org.spine3.base.Events;
import org.spine3.server.entity.AbstractEntity;
import java.util.Comparator;
/**
* Stores an event.
*
* @author Alexander Yevsyukov
*/
class EventEntity extends AbstractEntity<EventId, Event> {
/**
* Compares event entities by timestamps of events.
*/
private static final Comparator<EventEntity> comparator = new Comparator<EventEntity>() {
@Override
public int compare(EventEntity e1, EventEntity e2) {
final Event event1 = e1.getState();
final Event event2 = e2.getState();
final int result = Events.eventComparator()
.compare(event1, event2);
return result;
}
};
EventEntity(EventId id) {
super(id);
}
EventEntity(Event event) {
this(event.getId());
updateState(event);
}
/**
* Returns comparator which sorts event entities chronologically.
*/
static Comparator<EventEntity> comparator() {
return comparator;
}
}
| Make EventEntity public.
| server/src/main/java/org/spine3/server/event/EventEntity.java | Make EventEntity public. |
|
Java | apache-2.0 | d4321470c3aa330f0c62dee4668a28e761234c99 | 0 | Bai-Jie/CoolTechnologies,Bai-Jie/CoolTechnologies,OptimalOrange/CoolTechnologies,OptimalOrange/CoolTechnologies | package com.optimalorange.cooltechnologies.ui.fragment;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.optimalorange.cooltechnologies.BuildConfig;
import com.optimalorange.cooltechnologies.R;
import com.optimalorange.cooltechnologies.network.DestroyFavoriteRequest;
import com.optimalorange.cooltechnologies.network.GetMyFavoriteRequest;
import com.optimalorange.cooltechnologies.network.NetworkChecker;
import com.optimalorange.cooltechnologies.network.VolleySingleton;
import com.optimalorange.cooltechnologies.storage.DefaultSharedPreferencesSingleton;
import com.optimalorange.cooltechnologies.ui.LoginableBaseActivity;
import com.optimalorange.cooltechnologies.ui.entity.Empty;
import com.optimalorange.cooltechnologies.ui.entity.Favorite;
import com.optimalorange.cooltechnologies.ui.entity.FavoriteFooter;
import com.optimalorange.cooltechnologies.ui.entity.Loading;
import com.optimalorange.cooltechnologies.ui.viewholder.RecyclerEmptyViewHolder;
import com.optimalorange.cooltechnologies.ui.viewholder.RecyclerFavoriteFooterViewHolder;
import com.optimalorange.cooltechnologies.ui.viewholder.RecyclerFavoriteViewHolder;
import com.optimalorange.cooltechnologies.ui.viewholder.RecyclerLoadingViewHolder;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import gq.baijie.classbasedviewadapter.android.adapter.ClassBasedRecyclerViewAdapter;
import gq.baijie.classbasedviewadapter.android.adapter.DataSet;
import gq.baijie.classbasedviewadapter.android.adapter.ViewHolderFactoryRegister;
/**
* Created by WANGZHENGZE on 2014/11/20.
* 收藏
*/
//TODO set click listener
public class FavoriteFragment extends SwipeRefreshFragment {
private static final String DEFAULT_CATEGORY_LABEL = "科技";
private String mYoukuClientId;
private VolleySingleton mVolleySingleton;
private DefaultSharedPreferencesSingleton mDefaultSharedPreferencesSingleton;
private NetworkChecker mNetworkChecker;
private boolean mIsCreated = false;
private List<Loading> mLoadingDataSet;
private FavoritesDataSet mFavoritesDataSet;
private final ClassBasedRecyclerViewAdapter adapter = new ClassBasedRecyclerViewAdapter();
private ViewHolder vh;
private final LoginableBaseActivity.OnLoginStatusChangeListener mOnLoginStatusChangeListener =
new LoginableBaseActivity.OnLoginStatusChangeListener() {
@Override
public void onLoginStatusChanged(boolean hasLoggedIn) {
if (hasLoggedIn) {
setRefreshable(true);
onRefresh();
} else {
setRefreshable(false);
}
}
};
private void initState() {
Loading loading = new Loading();
Empty empty = new Empty();
FavoriteFooter haveMoreFooter = new FavoriteFooter();
FavoriteFooter noMoreFooter = new FavoriteFooter();
loading.hint = getString(R.string.favorite_new_loading);
empty.hint = getString(R.string.favorite_no_fav);
haveMoreFooter.hint = getString(R.string.favorite_view_more);
noMoreFooter.hint = getString(R.string.favorite_view_more_last);
haveMoreFooter.listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
getJsonData();
}
};
mLoadingDataSet = Collections.singletonList(loading);
mFavoritesDataSet = new FavoritesDataSet();
mFavoritesDataSet.empty = empty;
mFavoritesDataSet.haveMoreFooter = haveMoreFooter;
mFavoritesDataSet.noMoreFooter = noMoreFooter;
final ViewHolderFactoryRegister register = adapter.getRegister();
register.registerViewHolderFactory(new RecyclerLoadingViewHolder.Factory());
register.registerViewHolderFactory(new RecyclerEmptyViewHolder.Factory());
register.registerViewHolderFactory(new RecyclerFavoriteViewHolder.Factory());
register.registerViewHolderFactory(new RecyclerFavoriteFooterViewHolder.Factory());
adapter.setDataSet(mLoadingDataSet);
adapter.notifyDataSetChanged();
}
public void resetState() {
adapter.setDataSet(mLoadingDataSet);
adapter.notifyDataSetChanged();
mFavoritesDataSet.unsetFavorites();
}
public void addFavorites(Favorites added) {
if (mFavoritesDataSet.favorites != null) {
mFavoritesDataSet.addFavorites(added, adapter);
} else {
final Favorites newFavorites = new Favorites(new ArrayList<Favorite>());
newFavorites.add(added);
mFavoritesDataSet.favorites = newFavorites;
adapter.setDataSet(mFavoritesDataSet);
adapter.notifyDataSetChanged();
}
}
public void removeFavorites(int position) {
if (mFavoritesDataSet.favorites == null) {
throw new IllegalStateException("");
}
mFavoritesDataSet.remove(position, adapter);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mVolleySingleton = VolleySingleton.getInstance(getActivity());
mYoukuClientId = getString(R.string.youku_client_id);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNetworkChecker = NetworkChecker.newInstance(getActivity());
initState();
}
@Override
protected View onCreateChildView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_favorite, container, false);
vh = new ViewHolder(rootView);
return rootView;
}
@Override
public void onRefresh() {
getNewData();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mDefaultSharedPreferencesSingleton =
DefaultSharedPreferencesSingleton.getInstance(getActivity());
((LoginableBaseActivity) getActivity())
.addLoginStatusChangeListener(mOnLoginStatusChangeListener);
if (((LoginableBaseActivity) getActivity()).hasLoggedIn()) {
setRefreshable(true);
} else {
setRefreshable(false);
}
vh.favorites.setVisibility(View.GONE);
vh.favorites.setLayoutManager(new LinearLayoutManager(vh.favorites.getContext()));
vh.favorites.setAdapter(adapter);
getNewData();
mIsCreated = true;
}
@Override
public void onResume() {
super.onResume();
MobclickAgent.onPageStart(getClass().getSimpleName());
}
@Override
public void onPause() {
MobclickAgent.onPageEnd(getClass().getSimpleName());
super.onPause();
}
@Override
public void onDestroyView() {
((LoginableBaseActivity) getActivity())
.removeLoginStatusChangeListener(mOnLoginStatusChangeListener);
vh.favorites.setAdapter(null);
vh = null;
super.onDestroyView();
}
@Override
public void onDestroy() {
mNetworkChecker = null;
super.onDestroy();
}
private void getNewData() {
resetState();
getJsonData();
}
//TODO 避免重复发送
public void getJsonData() {
if (vh.favorites.getVisibility() == View.GONE) {
setHint(R.string.favorite_new_loading);
}
if (mDefaultSharedPreferencesSingleton.hasLoggedIn()) {
if (!mNetworkChecker.isConnected()) {
setHint(R.string.favorite_hint_no_net);
return;
}
String token = mDefaultSharedPreferencesSingleton.retrieveString("access_token", "");
int nextPage;
if (mFavoritesDataSet.favorites == null) {
nextPage = 1;
} else {
nextPage = mFavoritesDataSet.favorites.getCurrentPage() + 1;
}
mVolleySingleton.addToRequestQueue(buildGetMyFavoriteRequest(token, nextPage, 10));
} else {
setHint(R.string.favorite_hint_no_login);
}
}
private void setHint(int res) {
vh.mainHint.setText(getString(res));
vh.mainHint.setVisibility(View.VISIBLE);
vh.favorites.setVisibility(View.GONE);
vh.mainHint.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getNewData();
}
});
}
private void hideHint() {
vh.mainHint.setVisibility(View.GONE);
vh.favorites.setVisibility(View.VISIBLE);
}
@Override
protected boolean canChildScrollUp() {
return vh.favorites.getVisibility() == View.VISIBLE &&
vh.favorites.canScrollVertically(-1);
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
//显示的时候判断有没有走onCreated,没有判断是否有列表,没有则刷新列表。
if (isVisibleToUser) {
if (mIsCreated) {
mIsCreated = false;
} else {
if (vh.favorites.getVisibility() == View.GONE) {
getNewData();
}
}
}
}
//TODO add delete feathure on UI
private void sendDeleteRequest(String id, final int index) {
if (!mNetworkChecker.isConnected()) {
Toast.makeText(getActivity(), R.string.favorite_delete_no_net, Toast.LENGTH_SHORT)
.show();
return;
}
String token = mDefaultSharedPreferencesSingleton.retrieveString("access_token", "");
if (!mDefaultSharedPreferencesSingleton.hasLoggedIn()) {
Toast.makeText(getActivity(), R.string.favorite_delete_no_login, Toast.LENGTH_SHORT)
.show();
return;
}
mVolleySingleton.addToRequestQueue(buildDestroyFavoriteRequest(token, id, index));
}
private GetMyFavoriteRequest buildGetMyFavoriteRequest(String token, int page, int count) {
final GetMyFavoriteRequestHandler handler =
new GetMyFavoriteRequestHandler(new WeakReference<>(this));
return new GetMyFavoriteRequest.Builder()
.setClient_id(mYoukuClientId)
.setAccess_token(token)
.setPage(page)
.setCount(count)
.setResponseListener(handler)
.setErrorListener(handler)
.build();
}
/**
* 创建取消收藏的请求
*/
private DestroyFavoriteRequest buildDestroyFavoriteRequest(
String token, String videoId, int videoIndexInListView) {
final DestroyFavoriteRequestHandler handler = new DestroyFavoriteRequestHandler(
videoIndexInListView, new WeakReference<>(getContext()), new WeakReference<>(this));
return new DestroyFavoriteRequest.Builder()
.setClient_id(mYoukuClientId)
.setVideo_id(videoId)
.setAccess_token(token)
.setResponseListener(handler)
.setErrorListener(handler)
.build();
}
private static class GetMyFavoriteRequestHandler
implements Response.Listener<JSONObject>, Response.ErrorListener {
private final WeakReference<FavoriteFragment> mOwner;
private GetMyFavoriteRequestHandler(WeakReference<FavoriteFragment> owner) {
mOwner = owner;
}
@Override
public void onErrorResponse(VolleyError error) {
new RuntimeException(error).printStackTrace();
//TODO stop refreshing & change hint
}
@Override
public void onResponse(JSONObject response) {
final FavoriteFragment owner = mOwner.get();
if (owner != null) {
try {
doHandle(response, owner);
} catch (JSONException e) {
e.printStackTrace();
}
//TODO stop refreshing & change hint
owner.setRefreshing(false);
}
}
private static void doHandle(JSONObject response, FavoriteFragment owner)
throws JSONException {
owner.hideHint();
owner.addFavorites(convertToFavoriteInfo(response));
}
private static Favorites convertToFavoriteInfo(JSONObject jsonObject)
throws JSONException {
JSONArray videoArray = jsonObject.getJSONArray("videos");
Favorites favorites = new Favorites(convertNeededVideos(videoArray));
favorites.setCurrentReadCountIncludingUnneeded(videoArray.length());
favorites.setTotal(jsonObject.getInt("total"));
favorites.setCurrentPage(jsonObject.getInt("page"));
return favorites;
}
private static List<Favorite> convertNeededVideos(JSONArray videoArray)
throws JSONException {
List<Favorite> result = new LinkedList<>();
for (int i = 0; i < videoArray.length(); i++) {
JSONObject itemObject = videoArray.getJSONObject(i);
if (itemObject.getString("category").equals(DEFAULT_CATEGORY_LABEL)) {
result.add(convertToFavorite(itemObject));
}
}
return result;
}
private static Favorite convertToFavorite(JSONObject jsonObject) throws JSONException {
Favorite result = new Favorite();
result.title = jsonObject.getString("title");
result.link = jsonObject.getString("link");
result.thumbnail = jsonObject.getString("thumbnail");
result.duration = jsonObject.getString("duration");
result.videoId = jsonObject.getString("id");
return result;
}
}
private static class DestroyFavoriteRequestHandler
implements Response.Listener<JSONObject>, Response.ErrorListener {
private final int mVideoIndexInListView;
private final WeakReference<Context> mContextWeakReference;
private final WeakReference<FavoriteFragment> mOwner;
private DestroyFavoriteRequestHandler(
int videoIndexInListView,
WeakReference<Context> contextWeakReference,
WeakReference<FavoriteFragment> owner) {
mVideoIndexInListView = videoIndexInListView;
mContextWeakReference = contextWeakReference;
mOwner = owner;
}
@Override
public void onErrorResponse(VolleyError error) {
final Context context = mContextWeakReference.get();
if (context != null) {
final String message = context.getString(R.string.favorite_delete_fail);
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onResponse(JSONObject response) {
final Context context = mContextWeakReference.get();
final FavoriteFragment owner = mOwner.get();
if (owner != null) {
owner.removeFavorites(mVideoIndexInListView);
}
if (context != null) {
final String message = context.getString(R.string.favorite_delete_success);
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
}
private static class FavoritesDataSet implements DataSet {
@Nullable
private Favorites favorites;
private Empty empty;
private FavoriteFooter haveMoreFooter;
private FavoriteFooter noMoreFooter;
@NonNull
private Favorites getNonNullFavorites() {
if (favorites != null) {
return favorites;
} else {
throw new IllegalStateException("haven't init FavoritesDataSet");
}
}
@Override
public int size() {
return getNonNullFavorites().getInterestingFavorites().size() + 1;
}
@Override
public Object get(int position) {
final List<Favorite> interestingFavorites =
getNonNullFavorites().getInterestingFavorites();
if (position < interestingFavorites.size()) {
return interestingFavorites.get(position);
} else {
if (!getNonNullFavorites().isEmpty()) {
return getFavoriteFooter(position);
} else {
return empty;
}
}
}
private FavoriteFooter getFavoriteFooter(int position) {
if (BuildConfig.DEBUG) {
// This if block will be auto deleted when release
if (position != getNonNullFavorites().getInterestingFavorites().size()) { //NOPMD
throw new IllegalStateException();
}
}
if (!getNonNullFavorites().allRead()) {
return haveMoreFooter;
} else {
return noMoreFooter;
}
}
public void unsetFavorites() {
favorites = null;
}
public void addFavorites(Favorites added, RecyclerView.Adapter adapter) {
Favorites nonNullFavorites = getNonNullFavorites();
if (nonNullFavorites.isEmpty()) {
nonNullFavorites.add(added);
adapter.notifyDataSetChanged();
} else {
final int sizeBeforeAdd = nonNullFavorites.getInterestingFavorites().size();
nonNullFavorites.add(added);
adapter.notifyItemRangeInserted(
sizeBeforeAdd, added.getInterestingFavorites().size());
if (nonNullFavorites.allRead()) {
// footer改为noMoreFooter
adapter.notifyItemChanged(nonNullFavorites.getInterestingFavorites().size());
}
}
}
public void remove(int position, RecyclerView.Adapter adapter) {
Favorites nonNullFavorites = getNonNullFavorites();
nonNullFavorites.remove(position);
if (nonNullFavorites.isEmpty()) {
adapter.notifyDataSetChanged();
} else {
adapter.notifyItemRemoved(position);
}
}
}
private static class Favorites {
private int total;
private int currentPage;
private int currentReadCountIncludingUnneeded;
@NonNull
private final List<Favorite> interestingFavorites;
public Favorites(@NonNull List<Favorite> interestingFavorites) {
this.interestingFavorites = interestingFavorites;
}
public boolean allRead() {
if (BuildConfig.DEBUG) {
// This if block will be auto deleted when release
if (currentReadCountIncludingUnneeded > total) { //NOPMD
throw new AssertionError("currentReadCountIncludingUnneeded > total");
}
}
return currentReadCountIncludingUnneeded >= total;
}
public boolean isEmpty() {
if (total == 0) {
return true;
} else {
if (BuildConfig.DEBUG) {
// This if block will be auto deleted when release
if (total < 0) { //NOPMD
throw new AssertionError("total < 0");
}
}
// ------------------------- test this trick -----------------------
return allRead() && getInterestingFavorites().isEmpty();
}
}
@NonNull
public List<Favorite> getInterestingFavorites() {
return Collections.unmodifiableList(interestingFavorites);
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public void setCurrentReadCountIncludingUnneeded(int currentReadCountIncludingUnneeded) {
this.currentReadCountIncludingUnneeded = currentReadCountIncludingUnneeded;
}
public void setTotal(int total) {
this.total = total;
}
//TODO check currentPage + 1 != added.currentPage?
//TODO check total != added.total?
//TODO check illegal argument
//TODO check state
public void add(Favorites added) {
total = added.total;
currentPage = added.currentPage;
currentReadCountIncludingUnneeded += added.currentReadCountIncludingUnneeded;
interestingFavorites.addAll(added.getInterestingFavorites());
}
//TODO check illegal argument
//TODO check state
public void remove(int index) {
total--;
currentReadCountIncludingUnneeded--;
interestingFavorites.remove(index);
}
}
static class ViewHolder {
RecyclerView favorites;
TextView mainHint;
private ViewHolder(View root) {
favorites = (RecyclerView) root.findViewById(R.id.favorites);
mainHint = (TextView) root.findViewById(R.id.main_hint);
}
}
}
| app/src/main/java/com/optimalorange/cooltechnologies/ui/fragment/FavoriteFragment.java | package com.optimalorange.cooltechnologies.ui.fragment;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.optimalorange.cooltechnologies.BuildConfig;
import com.optimalorange.cooltechnologies.R;
import com.optimalorange.cooltechnologies.network.DestroyFavoriteRequest;
import com.optimalorange.cooltechnologies.network.GetMyFavoriteRequest;
import com.optimalorange.cooltechnologies.network.NetworkChecker;
import com.optimalorange.cooltechnologies.network.VolleySingleton;
import com.optimalorange.cooltechnologies.storage.DefaultSharedPreferencesSingleton;
import com.optimalorange.cooltechnologies.ui.LoginableBaseActivity;
import com.optimalorange.cooltechnologies.ui.entity.Empty;
import com.optimalorange.cooltechnologies.ui.entity.Favorite;
import com.optimalorange.cooltechnologies.ui.entity.FavoriteFooter;
import com.optimalorange.cooltechnologies.ui.entity.Loading;
import com.optimalorange.cooltechnologies.ui.viewholder.RecyclerEmptyViewHolder;
import com.optimalorange.cooltechnologies.ui.viewholder.RecyclerFavoriteFooterViewHolder;
import com.optimalorange.cooltechnologies.ui.viewholder.RecyclerFavoriteViewHolder;
import com.optimalorange.cooltechnologies.ui.viewholder.RecyclerLoadingViewHolder;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import gq.baijie.classbasedviewadapter.android.adapter.ClassBasedRecyclerViewAdapter;
import gq.baijie.classbasedviewadapter.android.adapter.DataSet;
import gq.baijie.classbasedviewadapter.android.adapter.ViewHolderFactoryRegister;
/**
* Created by WANGZHENGZE on 2014/11/20.
* 收藏
*/
//TODO set click listener
public class FavoriteFragment extends SwipeRefreshFragment {
private static final String DEFAULT_CATEGORY_LABEL = "科技";
private String mYoukuClientId;
private VolleySingleton mVolleySingleton;
private DefaultSharedPreferencesSingleton mDefaultSharedPreferencesSingleton;
private NetworkChecker mNetworkChecker;
private boolean mIsCreated = false;
private List<Loading> mLoadingDataSet;
private FavoritesDataSet mFavoritesDataSet;
private final ClassBasedRecyclerViewAdapter adapter = new ClassBasedRecyclerViewAdapter();
private ViewHolder vh;
private final LoginableBaseActivity.OnLoginStatusChangeListener mOnLoginStatusChangeListener =
new LoginableBaseActivity.OnLoginStatusChangeListener() {
@Override
public void onLoginStatusChanged(boolean hasLoggedIn) {
if (hasLoggedIn) {
setRefreshable(true);
onRefresh();
} else {
setRefreshable(false);
}
}
};
private void initState() {
Loading loading = new Loading();
Empty empty = new Empty();
FavoriteFooter haveMoreFooter = new FavoriteFooter();
FavoriteFooter noMoreFooter = new FavoriteFooter();
loading.hint = getString(R.string.favorite_new_loading);
empty.hint = getString(R.string.favorite_no_fav);
haveMoreFooter.hint = getString(R.string.favorite_view_more);
noMoreFooter.hint = getString(R.string.favorite_view_more_last);
haveMoreFooter.listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
getJsonData();
}
};
mLoadingDataSet = Collections.singletonList(loading);
mFavoritesDataSet = new FavoritesDataSet();
mFavoritesDataSet.empty = empty;
mFavoritesDataSet.haveMoreFooter = haveMoreFooter;
mFavoritesDataSet.noMoreFooter = noMoreFooter;
final ViewHolderFactoryRegister register = adapter.getRegister();
register.registerViewHolderFactory(new RecyclerLoadingViewHolder.Factory());
register.registerViewHolderFactory(new RecyclerEmptyViewHolder.Factory());
register.registerViewHolderFactory(new RecyclerFavoriteViewHolder.Factory());
register.registerViewHolderFactory(new RecyclerFavoriteFooterViewHolder.Factory());
adapter.setDataSet(mLoadingDataSet);
adapter.notifyDataSetChanged();
}
public void resetState() {
adapter.setDataSet(mLoadingDataSet);
adapter.notifyDataSetChanged();
mFavoritesDataSet.unsetFavorites();
}
public void addFavorites(Favorites added) {
if (mFavoritesDataSet.favorites != null) {
mFavoritesDataSet.addFavorites(added, adapter);
} else {
final Favorites newFavorites = new Favorites(new ArrayList<Favorite>());
newFavorites.add(added);
mFavoritesDataSet.favorites = newFavorites;
adapter.setDataSet(mFavoritesDataSet);
adapter.notifyDataSetChanged();
}
}
public void removeFavorites(int position) {
if (mFavoritesDataSet.favorites == null) {
throw new IllegalStateException("");
}
mFavoritesDataSet.remove(position, adapter);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mVolleySingleton = VolleySingleton.getInstance(getActivity());
mYoukuClientId = getString(R.string.youku_client_id);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNetworkChecker = NetworkChecker.newInstance(getActivity());
initState();
}
@Override
protected View onCreateChildView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_favorite, container, false);
vh = new ViewHolder(rootView);
return rootView;
}
@Override
public void onRefresh() {
getNewData();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mDefaultSharedPreferencesSingleton =
DefaultSharedPreferencesSingleton.getInstance(getActivity());
((LoginableBaseActivity) getActivity())
.addLoginStatusChangeListener(mOnLoginStatusChangeListener);
if (((LoginableBaseActivity) getActivity()).hasLoggedIn()) {
setRefreshable(true);
} else {
setRefreshable(false);
}
vh.favorites.setVisibility(View.GONE);
vh.favorites.setLayoutManager(new LinearLayoutManager(vh.favorites.getContext()));
vh.favorites.setAdapter(adapter);
getNewData();
mIsCreated = true;
}
@Override
public void onResume() {
super.onResume();
MobclickAgent.onPageStart(getClass().getSimpleName());
}
@Override
public void onPause() {
MobclickAgent.onPageEnd(getClass().getSimpleName());
super.onPause();
}
@Override
public void onDestroyView() {
((LoginableBaseActivity) getActivity())
.removeLoginStatusChangeListener(mOnLoginStatusChangeListener);
vh.favorites.setAdapter(null);
vh = null;
super.onDestroyView();
}
@Override
public void onDestroy() {
mNetworkChecker = null;
super.onDestroy();
}
private void getNewData() {
resetState();
getJsonData();
}
//TODO 避免重复发送
public void getJsonData() {
if (vh.favorites.getVisibility() == View.GONE) {
setHint(R.string.favorite_new_loading);
}
if (mDefaultSharedPreferencesSingleton.hasLoggedIn()) {
if (!mNetworkChecker.isConnected()) {
setHint(R.string.favorite_hint_no_net);
return;
}
String token = mDefaultSharedPreferencesSingleton.retrieveString("access_token", "");
int nextPage;
if (mFavoritesDataSet.favorites == null) {
nextPage = 1;
} else {
nextPage = mFavoritesDataSet.favorites.getCurrentPage() + 1;
}
mVolleySingleton.addToRequestQueue(buildGetMyFavoriteRequest(token, nextPage, 10));
} else {
setHint(R.string.favorite_hint_no_login);
}
}
private void setHint(int res) {
vh.mainHint.setText(getString(res));
vh.mainHint.setVisibility(View.VISIBLE);
vh.favorites.setVisibility(View.GONE);
vh.mainHint.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getNewData();
}
});
}
private void hideHint() {
vh.mainHint.setVisibility(View.GONE);
vh.favorites.setVisibility(View.VISIBLE);
}
@Override
protected boolean canChildScrollUp() {
return vh.favorites.getVisibility() == View.VISIBLE &&
vh.favorites.canScrollVertically(-1);
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
//显示的时候判断有没有走onCreated,没有判断是否有列表,没有则刷新列表。
if (isVisibleToUser) {
if (mIsCreated) {
mIsCreated = false;
} else {
if (vh.favorites.getVisibility() == View.GONE) {
getNewData();
}
}
}
}
//TODO add delete feathure on UI
private void sendDeleteRequest(String id, final int index) {
if (!mNetworkChecker.isConnected()) {
Toast.makeText(getActivity(), R.string.favorite_delete_no_net, Toast.LENGTH_SHORT)
.show();
return;
}
String token = mDefaultSharedPreferencesSingleton.retrieveString("access_token", "");
if (!mDefaultSharedPreferencesSingleton.hasLoggedIn()) {
Toast.makeText(getActivity(), R.string.favorite_delete_no_login, Toast.LENGTH_SHORT)
.show();
return;
}
mVolleySingleton.addToRequestQueue(buildDestroyFavoriteRequest(token, id, index));
}
private GetMyFavoriteRequest buildGetMyFavoriteRequest(String token, int page, int count) {
final GetMyFavoriteRequestHandler handler =
new GetMyFavoriteRequestHandler(new WeakReference<>(this));
return new GetMyFavoriteRequest.Builder()
.setClient_id(mYoukuClientId)
.setAccess_token(token)
.setPage(page)
.setCount(count)
.setResponseListener(handler)
.setErrorListener(handler)
.build();
}
/**
* 创建取消收藏的请求
*/
private DestroyFavoriteRequest buildDestroyFavoriteRequest(
String token, String videoId, int videoIndexInListView) {
final DestroyFavoriteRequestHandler handler = new DestroyFavoriteRequestHandler(
videoIndexInListView, new WeakReference<>(getContext()), new WeakReference<>(this));
return new DestroyFavoriteRequest.Builder()
.setClient_id(mYoukuClientId)
.setVideo_id(videoId)
.setAccess_token(token)
.setResponseListener(handler)
.setErrorListener(handler)
.build();
}
private static class GetMyFavoriteRequestHandler
implements Response.Listener<JSONObject>, Response.ErrorListener {
private final WeakReference<FavoriteFragment> mOwner;
private GetMyFavoriteRequestHandler(WeakReference<FavoriteFragment> owner) {
mOwner = owner;
}
@Override
public void onErrorResponse(VolleyError error) {
new RuntimeException(error).printStackTrace();
//TODO stop refreshing & change hint
}
@Override
public void onResponse(JSONObject response) {
final FavoriteFragment owner = mOwner.get();
if (owner != null) {
try {
doHandle(response, owner);
} catch (JSONException e) {
e.printStackTrace();
}
//TODO stop refreshing & change hint
owner.setRefreshing(false);
}
}
private static void doHandle(JSONObject response, FavoriteFragment owner)
throws JSONException {
owner.hideHint();
owner.addFavorites(convertToFavoriteInfo(response));
}
private static Favorites convertToFavoriteInfo(JSONObject jsonObject)
throws JSONException {
JSONArray videoArray = jsonObject.getJSONArray("videos");
Favorites favorites = new Favorites(convertNeededVideos(videoArray));
favorites.setCurrentReadCountIncludingUnneeded(videoArray.length());
favorites.setTotal(jsonObject.getInt("total"));
favorites.setCurrentPage(jsonObject.getInt("page"));
return favorites;
}
private static List<Favorite> convertNeededVideos(JSONArray videoArray)
throws JSONException {
List<Favorite> result = new LinkedList<>();
for (int i = 0; i < videoArray.length(); i++) {
JSONObject itemObject = videoArray.getJSONObject(i);
if (itemObject.getString("category").equals(DEFAULT_CATEGORY_LABEL)) {
result.add(convertToFavorite(itemObject));
}
}
return result;
}
private static Favorite convertToFavorite(JSONObject jsonObject) throws JSONException {
Favorite result = new Favorite();
result.title = jsonObject.getString("title");
result.link = jsonObject.getString("link");
result.thumbnail = jsonObject.getString("thumbnail");
result.duration = jsonObject.getString("duration");
result.videoId = jsonObject.getString("id");
return result;
}
}
private static class DestroyFavoriteRequestHandler
implements Response.Listener<JSONObject>, Response.ErrorListener {
private final int mVideoIndexInListView;
private final WeakReference<Context> mContextWeakReference;
private final WeakReference<FavoriteFragment> mOwner;
private DestroyFavoriteRequestHandler(
int videoIndexInListView,
WeakReference<Context> contextWeakReference,
WeakReference<FavoriteFragment> owner) {
mVideoIndexInListView = videoIndexInListView;
mContextWeakReference = contextWeakReference;
mOwner = owner;
}
@Override
public void onErrorResponse(VolleyError error) {
final Context context = mContextWeakReference.get();
if (context != null) {
final String message = context.getString(R.string.favorite_delete_fail);
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onResponse(JSONObject response) {
final Context context = mContextWeakReference.get();
final FavoriteFragment owner = mOwner.get();
if (owner != null) {
owner.removeFavorites(mVideoIndexInListView);
}
if (context != null) {
final String message = context.getString(R.string.favorite_delete_success);
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
}
private static class FavoritesDataSet implements DataSet {
@Nullable
private Favorites favorites;
private Empty empty;
private FavoriteFooter haveMoreFooter;
private FavoriteFooter noMoreFooter;
@NonNull
private Favorites getNonNullFavorites() {
if (favorites != null) {
return favorites;
} else {
throw new IllegalStateException("haven't init FavoritesDataSet");
}
}
@Override
public int size() {
return getNonNullFavorites().getInterestingFavorites().size() + 1;
}
@Override
public Object get(int position) {
final List<Favorite> interestingFavorites =
getNonNullFavorites().getInterestingFavorites();
if (position < interestingFavorites.size()) {
return interestingFavorites.get(position);
} else {
if (!getNonNullFavorites().isEmpty()) {
return getFavoriteFooter(position);
} else {
return empty;
}
}
}
private FavoriteFooter getFavoriteFooter(int position) {
if (BuildConfig.DEBUG) {
// This if block will be auto deleted when release
if (position != getNonNullFavorites().getInterestingFavorites().size()) { //NOPMD
throw new IllegalStateException();
}
}
if (!getNonNullFavorites().allRead()) {
return haveMoreFooter;
} else {
return noMoreFooter;
}
}
public void unsetFavorites() {
favorites = null;
}
public void addFavorites(Favorites added, RecyclerView.Adapter adapter) {
Favorites nonNullFavorites = getNonNullFavorites();
if (nonNullFavorites.isEmpty()) {
nonNullFavorites.add(added);
adapter.notifyDataSetChanged();
} else {
final int sizeBeforeAdd = nonNullFavorites.getInterestingFavorites().size();
nonNullFavorites.add(added);
adapter.notifyItemRangeInserted(
sizeBeforeAdd, added.getInterestingFavorites().size());
if (nonNullFavorites.allRead()) {
// footer改为noMoreFooter
adapter.notifyItemChanged(nonNullFavorites.getInterestingFavorites().size());
}
}
}
public void remove(int position, RecyclerView.Adapter adapter) {
Favorites nonNullFavorites = getNonNullFavorites();
nonNullFavorites.remove(position);
if (nonNullFavorites.isEmpty()) {
adapter.notifyDataSetChanged();
} else {
adapter.notifyItemRemoved(position);
}
}
}
private static class Favorites {
private int total;
private int currentPage;
private int currentReadCountIncludingUnneeded;
@NonNull
private final List<Favorite> interestingFavorites;
public Favorites(@NonNull List<Favorite> interestingFavorites) {
this.interestingFavorites = interestingFavorites;
}
public boolean allRead() {
return currentReadCountIncludingUnneeded == total;
}
public boolean isEmpty() {
if (total == 0) {
return true;
} else {
if (BuildConfig.DEBUG) {
// This if block will be auto deleted when release
if (total < 0) { //NOPMD
throw new AssertionError("total < 0");
}
}
// ------------------------- test this trick -----------------------
return allRead() && getInterestingFavorites().isEmpty();
}
}
@NonNull
public List<Favorite> getInterestingFavorites() {
return Collections.unmodifiableList(interestingFavorites);
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public void setCurrentReadCountIncludingUnneeded(int currentReadCountIncludingUnneeded) {
this.currentReadCountIncludingUnneeded = currentReadCountIncludingUnneeded;
}
public void setTotal(int total) {
this.total = total;
}
//TODO check currentPage + 1 != added.currentPage?
//TODO check total != added.total?
//TODO check illegal argument
//TODO check state
public void add(Favorites added) {
total = added.total;
currentPage = added.currentPage;
currentReadCountIncludingUnneeded += added.currentReadCountIncludingUnneeded;
interestingFavorites.addAll(added.getInterestingFavorites());
}
//TODO check illegal argument
//TODO check state
public void remove(int index) {
total--;
currentReadCountIncludingUnneeded--;
interestingFavorites.remove(index);
}
}
static class ViewHolder {
RecyclerView favorites;
TextView mainHint;
private ViewHolder(View root) {
favorites = (RecyclerView) root.findViewById(R.id.favorites);
mainHint = (TextView) root.findViewById(R.id.main_hint);
}
}
}
| 尝试提高allRead()的容错性
| app/src/main/java/com/optimalorange/cooltechnologies/ui/fragment/FavoriteFragment.java | 尝试提高allRead()的容错性 |
|
Java | apache-2.0 | a8896c39964d9a15efb58a3019cdff2119428453 | 0 | google/ExoPlayer,google/ExoPlayer,androidx/media,google/ExoPlayer,androidx/media,androidx/media | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.google.android.exoplayer2.demo;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.JsonReader;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.MediaItem.ClippingConfiguration;
import com.google.android.exoplayer2.MediaMetadata;
import com.google.android.exoplayer2.RenderersFactory;
import com.google.android.exoplayer2.offline.DownloadService;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DataSourceInputStream;
import com.google.android.exoplayer2.upstream.DataSourceUtil;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.Util;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/** An activity for selecting from a list of media samples. */
public class SampleChooserActivity extends AppCompatActivity
implements DownloadTracker.Listener, OnChildClickListener {
private static final String TAG = "SampleChooserActivity";
private static final String GROUP_POSITION_PREFERENCE_KEY = "sample_chooser_group_position";
private static final String CHILD_POSITION_PREFERENCE_KEY = "sample_chooser_child_position";
private String[] uris;
private boolean useExtensionRenderers;
private DownloadTracker downloadTracker;
private SampleAdapter sampleAdapter;
private MenuItem preferExtensionDecodersMenuItem;
private ExpandableListView sampleListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_chooser_activity);
sampleAdapter = new SampleAdapter();
sampleListView = findViewById(R.id.sample_list);
sampleListView.setAdapter(sampleAdapter);
sampleListView.setOnChildClickListener(this);
Intent intent = getIntent();
String dataUri = intent.getDataString();
if (dataUri != null) {
uris = new String[] {dataUri};
} else {
ArrayList<String> uriList = new ArrayList<>();
AssetManager assetManager = getAssets();
try {
for (String asset : assetManager.list("")) {
if (asset.endsWith(".exolist.json")) {
uriList.add("asset:///" + asset);
}
}
} catch (IOException e) {
Toast.makeText(getApplicationContext(), R.string.sample_list_load_error, Toast.LENGTH_LONG)
.show();
}
uris = new String[uriList.size()];
uriList.toArray(uris);
Arrays.sort(uris);
}
useExtensionRenderers = DemoUtil.useExtensionRenderers();
downloadTracker = DemoUtil.getDownloadTracker(/* context= */ this);
loadSample();
startDownloadService();
}
/** Start the download service if it should be running but it's not currently. */
private void startDownloadService() {
// Starting the service in the foreground causes notification flicker if there is no scheduled
// action. Starting it in the background throws an exception if the app is in the background too
// (e.g. if device screen is locked).
try {
DownloadService.start(this, DemoDownloadService.class);
} catch (IllegalStateException e) {
DownloadService.startForeground(this, DemoDownloadService.class);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.sample_chooser_menu, menu);
preferExtensionDecodersMenuItem = menu.findItem(R.id.prefer_extension_decoders);
preferExtensionDecodersMenuItem.setVisible(useExtensionRenderers);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
item.setChecked(!item.isChecked());
return true;
}
@Override
public void onStart() {
super.onStart();
downloadTracker.addListener(this);
sampleAdapter.notifyDataSetChanged();
}
@Override
public void onStop() {
downloadTracker.removeListener(this);
super.onStop();
}
@Override
public void onDownloadsChanged() {
sampleAdapter.notifyDataSetChanged();
}
@Override
public void onRequestPermissionsResult(
int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length == 0) {
// Empty results are triggered if a permission is requested while another request was already
// pending and can be safely ignored in this case.
return;
}
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
loadSample();
} else {
Toast.makeText(getApplicationContext(), R.string.sample_list_load_error, Toast.LENGTH_LONG)
.show();
finish();
}
}
private void loadSample() {
checkNotNull(uris);
for (int i = 0; i < uris.length; i++) {
Uri uri = Uri.parse(uris[i]);
if (Util.maybeRequestReadExternalStoragePermission(this, uri)) {
return;
}
}
SampleListLoader loaderTask = new SampleListLoader();
loaderTask.execute(uris);
}
private void onPlaylistGroups(final List<PlaylistGroup> groups, boolean sawError) {
if (sawError) {
Toast.makeText(getApplicationContext(), R.string.sample_list_load_error, Toast.LENGTH_LONG)
.show();
}
sampleAdapter.setPlaylistGroups(groups);
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int groupPosition = preferences.getInt(GROUP_POSITION_PREFERENCE_KEY, /* defValue= */ -1);
int childPosition = preferences.getInt(CHILD_POSITION_PREFERENCE_KEY, /* defValue= */ -1);
// Clear the group and child position if either are unset or if either are out of bounds.
if (groupPosition != -1
&& childPosition != -1
&& groupPosition < groups.size()
&& childPosition < groups.get(groupPosition).playlists.size()) {
sampleListView.expandGroup(groupPosition); // shouldExpandGroup does not work without this.
sampleListView.setSelectedChild(groupPosition, childPosition, /* shouldExpandGroup= */ true);
}
}
@Override
public boolean onChildClick(
ExpandableListView parent, View view, int groupPosition, int childPosition, long id) {
// Save the selected item first to be able to restore it if the tested code crashes.
SharedPreferences.Editor prefEditor = getPreferences(MODE_PRIVATE).edit();
prefEditor.putInt(GROUP_POSITION_PREFERENCE_KEY, groupPosition);
prefEditor.putInt(CHILD_POSITION_PREFERENCE_KEY, childPosition);
prefEditor.apply();
PlaylistHolder playlistHolder = (PlaylistHolder) view.getTag();
Intent intent = new Intent(this, PlayerActivity.class);
intent.putExtra(
IntentUtil.PREFER_EXTENSION_DECODERS_EXTRA,
isNonNullAndChecked(preferExtensionDecodersMenuItem));
IntentUtil.addToIntent(playlistHolder.mediaItems, intent);
startActivity(intent);
return true;
}
private void onSampleDownloadButtonClicked(PlaylistHolder playlistHolder) {
int downloadUnsupportedStringId = getDownloadUnsupportedStringId(playlistHolder);
if (downloadUnsupportedStringId != 0) {
Toast.makeText(getApplicationContext(), downloadUnsupportedStringId, Toast.LENGTH_LONG)
.show();
} else {
RenderersFactory renderersFactory =
DemoUtil.buildRenderersFactory(
/* context= */ this, isNonNullAndChecked(preferExtensionDecodersMenuItem));
downloadTracker.toggleDownload(
getSupportFragmentManager(), playlistHolder.mediaItems.get(0), renderersFactory);
}
}
private int getDownloadUnsupportedStringId(PlaylistHolder playlistHolder) {
if (playlistHolder.mediaItems.size() > 1) {
return R.string.download_playlist_unsupported;
}
MediaItem.LocalConfiguration localConfiguration =
checkNotNull(playlistHolder.mediaItems.get(0).localConfiguration);
if (localConfiguration.adsConfiguration != null) {
return R.string.download_ads_unsupported;
}
String scheme = localConfiguration.uri.getScheme();
if (!("http".equals(scheme) || "https".equals(scheme))) {
return R.string.download_scheme_unsupported;
}
return 0;
}
private static boolean isNonNullAndChecked(@Nullable MenuItem menuItem) {
// Temporary workaround for layouts that do not inflate the options menu.
return menuItem != null && menuItem.isChecked();
}
private final class SampleListLoader extends AsyncTask<String, Void, List<PlaylistGroup>> {
private boolean sawError;
@Override
protected List<PlaylistGroup> doInBackground(String... uris) {
List<PlaylistGroup> result = new ArrayList<>();
Context context = getApplicationContext();
DataSource dataSource = DemoUtil.getDataSourceFactory(context).createDataSource();
for (String uri : uris) {
DataSpec dataSpec = new DataSpec(Uri.parse(uri));
InputStream inputStream = new DataSourceInputStream(dataSource, dataSpec);
try {
readPlaylistGroups(new JsonReader(new InputStreamReader(inputStream, "UTF-8")), result);
} catch (Exception e) {
Log.e(TAG, "Error loading sample list: " + uri, e);
sawError = true;
} finally {
DataSourceUtil.closeQuietly(dataSource);
}
}
return result;
}
@Override
protected void onPostExecute(List<PlaylistGroup> result) {
onPlaylistGroups(result, sawError);
}
private void readPlaylistGroups(JsonReader reader, List<PlaylistGroup> groups)
throws IOException {
reader.beginArray();
while (reader.hasNext()) {
readPlaylistGroup(reader, groups);
}
reader.endArray();
}
private void readPlaylistGroup(JsonReader reader, List<PlaylistGroup> groups)
throws IOException {
String groupName = "";
ArrayList<PlaylistHolder> playlistHolders = new ArrayList<>();
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
switch (name) {
case "name":
groupName = reader.nextString();
break;
case "samples":
reader.beginArray();
while (reader.hasNext()) {
playlistHolders.add(readEntry(reader, false));
}
reader.endArray();
break;
case "_comment":
reader.nextString(); // Ignore.
break;
default:
throw new IOException("Unsupported name: " + name, /* cause= */ null);
}
}
reader.endObject();
PlaylistGroup group = getGroup(groupName, groups);
group.playlists.addAll(playlistHolders);
}
private PlaylistHolder readEntry(JsonReader reader, boolean insidePlaylist) throws IOException {
Uri uri = null;
String extension = null;
String title = null;
ArrayList<PlaylistHolder> children = null;
Uri subtitleUri = null;
String subtitleMimeType = null;
String subtitleLanguage = null;
UUID drmUuid = null;
String drmLicenseUri = null;
ImmutableMap<String, String> drmLicenseRequestHeaders = ImmutableMap.of();
boolean drmSessionForClearContent = false;
boolean drmMultiSession = false;
boolean drmForceDefaultLicenseUri = false;
MediaItem.ClippingConfiguration.Builder clippingConfiguration =
new ClippingConfiguration.Builder();
MediaItem.Builder mediaItem = new MediaItem.Builder();
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
switch (name) {
case "name":
title = reader.nextString();
break;
case "uri":
uri = Uri.parse(reader.nextString());
break;
case "extension":
extension = reader.nextString();
break;
case "clip_start_position_ms":
clippingConfiguration.setStartPositionMs(reader.nextLong());
break;
case "clip_end_position_ms":
clippingConfiguration.setEndPositionMs(reader.nextLong());
break;
case "ad_tag_uri":
mediaItem.setAdsConfiguration(
new MediaItem.AdsConfiguration.Builder(Uri.parse(reader.nextString())).build());
break;
case "drm_scheme":
drmUuid = Util.getDrmUuid(reader.nextString());
break;
case "drm_license_uri":
case "drm_license_url": // For backward compatibility only.
drmLicenseUri = reader.nextString();
break;
case "drm_key_request_properties":
Map<String, String> requestHeaders = new HashMap<>();
reader.beginObject();
while (reader.hasNext()) {
requestHeaders.put(reader.nextName(), reader.nextString());
}
reader.endObject();
drmLicenseRequestHeaders = ImmutableMap.copyOf(requestHeaders);
break;
case "drm_session_for_clear_content":
drmSessionForClearContent = reader.nextBoolean();
break;
case "drm_multi_session":
drmMultiSession = reader.nextBoolean();
break;
case "drm_force_default_license_uri":
drmForceDefaultLicenseUri = reader.nextBoolean();
break;
case "subtitle_uri":
subtitleUri = Uri.parse(reader.nextString());
break;
case "subtitle_mime_type":
subtitleMimeType = reader.nextString();
break;
case "subtitle_language":
subtitleLanguage = reader.nextString();
break;
case "playlist":
checkState(!insidePlaylist, "Invalid nesting of playlists");
children = new ArrayList<>();
reader.beginArray();
while (reader.hasNext()) {
children.add(readEntry(reader, /* insidePlaylist= */ true));
}
reader.endArray();
break;
default:
throw new IOException("Unsupported attribute name: " + name, /* cause= */ null);
}
}
reader.endObject();
if (children != null) {
List<MediaItem> mediaItems = new ArrayList<>();
for (int i = 0; i < children.size(); i++) {
mediaItems.addAll(children.get(i).mediaItems);
}
return new PlaylistHolder(title, mediaItems);
} else {
@Nullable
String adaptiveMimeType =
Util.getAdaptiveMimeTypeForContentType(Util.inferContentType(uri, extension));
mediaItem
.setUri(uri)
.setMediaMetadata(new MediaMetadata.Builder().setTitle(title).build())
.setMimeType(adaptiveMimeType)
.setClippingConfiguration(clippingConfiguration.build());
if (drmUuid != null) {
mediaItem.setDrmConfiguration(
new MediaItem.DrmConfiguration.Builder(drmUuid)
.setLicenseUri(drmLicenseUri)
.setLicenseRequestHeaders(drmLicenseRequestHeaders)
.forceSessionsForAudioAndVideoTracks(drmSessionForClearContent)
.setMultiSession(drmMultiSession)
.setForceDefaultLicenseUri(drmForceDefaultLicenseUri)
.build());
} else {
checkState(drmLicenseUri == null, "drm_uuid is required if drm_license_uri is set.");
checkState(
drmLicenseRequestHeaders.isEmpty(),
"drm_uuid is required if drm_key_request_properties is set.");
checkState(
!drmSessionForClearContent,
"drm_uuid is required if drm_session_for_clear_content is set.");
checkState(!drmMultiSession, "drm_uuid is required if drm_multi_session is set.");
checkState(
!drmForceDefaultLicenseUri,
"drm_uuid is required if drm_force_default_license_uri is set.");
}
if (subtitleUri != null) {
MediaItem.SubtitleConfiguration subtitleConfiguration =
new MediaItem.SubtitleConfiguration.Builder(subtitleUri)
.setMimeType(
checkNotNull(
subtitleMimeType,
"subtitle_mime_type is required if subtitle_uri is set."))
.setLanguage(subtitleLanguage)
.build();
mediaItem.setSubtitleConfigurations(ImmutableList.of(subtitleConfiguration));
}
return new PlaylistHolder(title, Collections.singletonList(mediaItem.build()));
}
}
private PlaylistGroup getGroup(String groupName, List<PlaylistGroup> groups) {
for (int i = 0; i < groups.size(); i++) {
if (Objects.equal(groupName, groups.get(i).title)) {
return groups.get(i);
}
}
PlaylistGroup group = new PlaylistGroup(groupName);
groups.add(group);
return group;
}
}
private final class SampleAdapter extends BaseExpandableListAdapter implements OnClickListener {
private List<PlaylistGroup> playlistGroups;
public SampleAdapter() {
playlistGroups = Collections.emptyList();
}
public void setPlaylistGroups(List<PlaylistGroup> playlistGroups) {
this.playlistGroups = playlistGroups;
notifyDataSetChanged();
}
@Override
public PlaylistHolder getChild(int groupPosition, int childPosition) {
return getGroup(groupPosition).playlists.get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(
int groupPosition,
int childPosition,
boolean isLastChild,
View convertView,
ViewGroup parent) {
View view = convertView;
if (view == null) {
view = getLayoutInflater().inflate(R.layout.sample_list_item, parent, false);
View downloadButton = view.findViewById(R.id.download_button);
downloadButton.setOnClickListener(this);
downloadButton.setFocusable(false);
}
initializeChildView(view, getChild(groupPosition, childPosition));
return view;
}
@Override
public int getChildrenCount(int groupPosition) {
return getGroup(groupPosition).playlists.size();
}
@Override
public PlaylistGroup getGroup(int groupPosition) {
return playlistGroups.get(groupPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(
int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view =
getLayoutInflater()
.inflate(android.R.layout.simple_expandable_list_item_1, parent, false);
}
((TextView) view).setText(getGroup(groupPosition).title);
return view;
}
@Override
public int getGroupCount() {
return playlistGroups.size();
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
@Override
public void onClick(View view) {
onSampleDownloadButtonClicked((PlaylistHolder) view.getTag());
}
private void initializeChildView(View view, PlaylistHolder playlistHolder) {
view.setTag(playlistHolder);
TextView sampleTitle = view.findViewById(R.id.sample_title);
sampleTitle.setText(playlistHolder.title);
boolean canDownload = getDownloadUnsupportedStringId(playlistHolder) == 0;
boolean isDownloaded =
canDownload && downloadTracker.isDownloaded(playlistHolder.mediaItems.get(0));
ImageButton downloadButton = view.findViewById(R.id.download_button);
downloadButton.setTag(playlistHolder);
downloadButton.setColorFilter(
canDownload ? (isDownloaded ? 0xFF42A5F5 : 0xFFBDBDBD) : 0xFF666666);
downloadButton.setImageResource(
isDownloaded ? R.drawable.ic_download_done : R.drawable.ic_download);
}
}
private static final class PlaylistHolder {
public final String title;
public final List<MediaItem> mediaItems;
private PlaylistHolder(String title, List<MediaItem> mediaItems) {
checkArgument(!mediaItems.isEmpty());
this.title = title;
this.mediaItems = Collections.unmodifiableList(new ArrayList<>(mediaItems));
}
}
private static final class PlaylistGroup {
public final String title;
public final List<PlaylistHolder> playlists;
public PlaylistGroup(String title) {
this.title = title;
this.playlists = new ArrayList<>();
}
}
}
| demos/main/src/main/java/com/google/android/exoplayer2/demo/SampleChooserActivity.java | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.google.android.exoplayer2.demo;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.JsonReader;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.MediaItem.ClippingConfiguration;
import com.google.android.exoplayer2.MediaMetadata;
import com.google.android.exoplayer2.RenderersFactory;
import com.google.android.exoplayer2.offline.DownloadService;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DataSourceInputStream;
import com.google.android.exoplayer2.upstream.DataSourceUtil;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.Util;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/** An activity for selecting from a list of media samples. */
public class SampleChooserActivity extends AppCompatActivity
implements DownloadTracker.Listener, OnChildClickListener {
private static final String TAG = "SampleChooserActivity";
private static final String GROUP_POSITION_PREFERENCE_KEY = "sample_chooser_group_position";
private static final String CHILD_POSITION_PREFERENCE_KEY = "sample_chooser_child_position";
private String[] uris;
private boolean useExtensionRenderers;
private DownloadTracker downloadTracker;
private SampleAdapter sampleAdapter;
private MenuItem preferExtensionDecodersMenuItem;
private ExpandableListView sampleListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_chooser_activity);
sampleAdapter = new SampleAdapter();
sampleListView = findViewById(R.id.sample_list);
sampleListView.setAdapter(sampleAdapter);
sampleListView.setOnChildClickListener(this);
Intent intent = getIntent();
String dataUri = intent.getDataString();
if (dataUri != null) {
uris = new String[] {dataUri};
} else {
ArrayList<String> uriList = new ArrayList<>();
AssetManager assetManager = getAssets();
try {
for (String asset : assetManager.list("")) {
if (asset.endsWith(".exolist.json")) {
uriList.add("asset:///" + asset);
}
}
} catch (IOException e) {
Toast.makeText(getApplicationContext(), R.string.sample_list_load_error, Toast.LENGTH_LONG)
.show();
}
uris = new String[uriList.size()];
uriList.toArray(uris);
Arrays.sort(uris);
}
useExtensionRenderers = DemoUtil.useExtensionRenderers();
downloadTracker = DemoUtil.getDownloadTracker(/* context= */ this);
loadSample();
startDownloadService();
}
/** Start the download service if it should be running but it's not currently. */
private void startDownloadService() {
// Starting the service in the foreground causes notification flicker if there is no scheduled
// action. Starting it in the background throws an exception if the app is in the background too
// (e.g. if device screen is locked).
try {
DownloadService.start(this, DemoDownloadService.class);
} catch (IllegalStateException e) {
DownloadService.startForeground(this, DemoDownloadService.class);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.sample_chooser_menu, menu);
preferExtensionDecodersMenuItem = menu.findItem(R.id.prefer_extension_decoders);
preferExtensionDecodersMenuItem.setVisible(useExtensionRenderers);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
item.setChecked(!item.isChecked());
return true;
}
@Override
public void onStart() {
super.onStart();
downloadTracker.addListener(this);
sampleAdapter.notifyDataSetChanged();
}
@Override
public void onStop() {
downloadTracker.removeListener(this);
super.onStop();
}
@Override
public void onDownloadsChanged() {
sampleAdapter.notifyDataSetChanged();
}
@Override
public void onRequestPermissionsResult(
int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length == 0) {
// Empty results are triggered if a permission is requested while another request was already
// pending and can be safely ignored in this case.
return;
}
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
loadSample();
} else {
Toast.makeText(getApplicationContext(), R.string.sample_list_load_error, Toast.LENGTH_LONG)
.show();
finish();
}
}
private void loadSample() {
checkNotNull(uris);
for (int i = 0; i < uris.length; i++) {
Uri uri = Uri.parse(uris[i]);
if (Util.maybeRequestReadExternalStoragePermission(this, uri)) {
return;
}
}
SampleListLoader loaderTask = new SampleListLoader();
loaderTask.execute(uris);
}
private void onPlaylistGroups(final List<PlaylistGroup> groups, boolean sawError) {
if (sawError) {
Toast.makeText(getApplicationContext(), R.string.sample_list_load_error, Toast.LENGTH_LONG)
.show();
}
sampleAdapter.setPlaylistGroups(groups);
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int groupPosition = preferences.getInt(GROUP_POSITION_PREFERENCE_KEY, /* defValue= */ -1);
int childPosition = preferences.getInt(CHILD_POSITION_PREFERENCE_KEY, /* defValue= */ -1);
// Clear the group and child position if either are unset or if either are out of bounds.
if (groupPosition != -1
&& childPosition != -1
&& groupPosition < groups.size()
&& childPosition < groups.get(groupPosition).playlists.size()) {
sampleListView.expandGroup(groupPosition); // shouldExpandGroup does not work without this.
sampleListView.setSelectedChild(groupPosition, childPosition, /* shouldExpandGroup= */ true);
}
}
@Override
public boolean onChildClick(
ExpandableListView parent, View view, int groupPosition, int childPosition, long id) {
// Save the selected item first to be able to restore it if the tested code crashes.
SharedPreferences.Editor prefEditor = getPreferences(MODE_PRIVATE).edit();
prefEditor.putInt(GROUP_POSITION_PREFERENCE_KEY, groupPosition);
prefEditor.putInt(CHILD_POSITION_PREFERENCE_KEY, childPosition);
prefEditor.apply();
PlaylistHolder playlistHolder = (PlaylistHolder) view.getTag();
Intent intent = new Intent(this, PlayerActivity.class);
intent.putExtra(
IntentUtil.PREFER_EXTENSION_DECODERS_EXTRA,
isNonNullAndChecked(preferExtensionDecodersMenuItem));
IntentUtil.addToIntent(playlistHolder.mediaItems, intent);
startActivity(intent);
return true;
}
private void onSampleDownloadButtonClicked(PlaylistHolder playlistHolder) {
int downloadUnsupportedStringId = getDownloadUnsupportedStringId(playlistHolder);
if (downloadUnsupportedStringId != 0) {
Toast.makeText(getApplicationContext(), downloadUnsupportedStringId, Toast.LENGTH_LONG)
.show();
} else {
RenderersFactory renderersFactory =
DemoUtil.buildRenderersFactory(
/* context= */ this, isNonNullAndChecked(preferExtensionDecodersMenuItem));
downloadTracker.toggleDownload(
getSupportFragmentManager(), playlistHolder.mediaItems.get(0), renderersFactory);
}
}
private int getDownloadUnsupportedStringId(PlaylistHolder playlistHolder) {
if (playlistHolder.mediaItems.size() > 1) {
return R.string.download_playlist_unsupported;
}
MediaItem.LocalConfiguration localConfiguration =
checkNotNull(playlistHolder.mediaItems.get(0).localConfiguration);
if (localConfiguration.adsConfiguration != null) {
return R.string.download_ads_unsupported;
}
String scheme = localConfiguration.uri.getScheme();
if (!("http".equals(scheme) || "https".equals(scheme))) {
return R.string.download_scheme_unsupported;
}
return 0;
}
private static boolean isNonNullAndChecked(@Nullable MenuItem menuItem) {
// Temporary workaround for layouts that do not inflate the options menu.
return menuItem != null && menuItem.isChecked();
}
private final class SampleListLoader extends AsyncTask<String, Void, List<PlaylistGroup>> {
private boolean sawError;
@Override
protected List<PlaylistGroup> doInBackground(String... uris) {
List<PlaylistGroup> result = new ArrayList<>();
Context context = getApplicationContext();
DataSource dataSource = DemoUtil.getDataSourceFactory(context).createDataSource();
for (String uri : uris) {
DataSpec dataSpec = new DataSpec(Uri.parse(uri));
InputStream inputStream = new DataSourceInputStream(dataSource, dataSpec);
try {
readPlaylistGroups(new JsonReader(new InputStreamReader(inputStream, "UTF-8")), result);
} catch (Exception e) {
Log.e(TAG, "Error loading sample list: " + uri, e);
sawError = true;
} finally {
DataSourceUtil.closeQuietly(dataSource);
}
}
return result;
}
@Override
protected void onPostExecute(List<PlaylistGroup> result) {
onPlaylistGroups(result, sawError);
}
private void readPlaylistGroups(JsonReader reader, List<PlaylistGroup> groups)
throws IOException {
reader.beginArray();
while (reader.hasNext()) {
readPlaylistGroup(reader, groups);
}
reader.endArray();
}
private void readPlaylistGroup(JsonReader reader, List<PlaylistGroup> groups)
throws IOException {
String groupName = "";
ArrayList<PlaylistHolder> playlistHolders = new ArrayList<>();
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
switch (name) {
case "name":
groupName = reader.nextString();
break;
case "samples":
reader.beginArray();
while (reader.hasNext()) {
playlistHolders.add(readEntry(reader, false));
}
reader.endArray();
break;
case "_comment":
reader.nextString(); // Ignore.
break;
default:
throw new IOException("Unsupported name: " + name, /* cause= */ null);
}
}
reader.endObject();
PlaylistGroup group = getGroup(groupName, groups);
group.playlists.addAll(playlistHolders);
}
private PlaylistHolder readEntry(JsonReader reader, boolean insidePlaylist) throws IOException {
Uri uri = null;
String extension = null;
String title = null;
ArrayList<PlaylistHolder> children = null;
Uri subtitleUri = null;
String subtitleMimeType = null;
String subtitleLanguage = null;
UUID drmUuid = null;
String drmLicenseUri = null;
ImmutableMap<String, String> drmLicenseRequestHeaders = ImmutableMap.of();
boolean drmSessionForClearContent = false;
boolean drmMultiSession = false;
boolean drmForceDefaultLicenseUri = false;
MediaItem.ClippingConfiguration.Builder clippingConfiguration =
new ClippingConfiguration.Builder();
MediaItem.Builder mediaItem = new MediaItem.Builder();
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
switch (name) {
case "name":
title = reader.nextString();
break;
case "uri":
uri = Uri.parse(reader.nextString());
break;
case "extension":
extension = reader.nextString();
break;
case "clip_start_position_ms":
clippingConfiguration.setStartPositionMs(reader.nextLong());
break;
case "clip_end_position_ms":
clippingConfiguration.setEndPositionMs(reader.nextLong());
break;
case "ad_tag_uri":
mediaItem.setAdsConfiguration(
new MediaItem.AdsConfiguration.Builder(Uri.parse(reader.nextString())).build());
break;
case "drm_scheme":
drmUuid = Util.getDrmUuid(reader.nextString());
break;
case "drm_license_uri":
case "drm_license_url": // For backward compatibility only.
drmLicenseUri = reader.nextString();
break;
case "drm_key_request_properties":
Map<String, String> requestHeaders = new HashMap<>();
reader.beginObject();
while (reader.hasNext()) {
requestHeaders.put(reader.nextName(), reader.nextString());
}
reader.endObject();
drmLicenseRequestHeaders = ImmutableMap.copyOf(requestHeaders);
break;
case "drm_session_for_clear_content":
drmSessionForClearContent = reader.nextBoolean();
break;
case "drm_multi_session":
drmMultiSession = reader.nextBoolean();
break;
case "drm_force_default_license_uri":
drmForceDefaultLicenseUri = reader.nextBoolean();
break;
case "subtitle_uri":
subtitleUri = Uri.parse(reader.nextString());
break;
case "subtitle_mime_type":
subtitleMimeType = reader.nextString();
break;
case "subtitle_language":
subtitleLanguage = reader.nextString();
break;
case "playlist":
checkState(!insidePlaylist, "Invalid nesting of playlists");
children = new ArrayList<>();
reader.beginArray();
while (reader.hasNext()) {
children.add(readEntry(reader, /* insidePlaylist= */ true));
}
reader.endArray();
break;
default:
throw new IOException("Unsupported attribute name: " + name, /* cause= */ null);
}
}
reader.endObject();
if (children != null) {
List<MediaItem> mediaItems = new ArrayList<>();
for (int i = 0; i < children.size(); i++) {
mediaItems.addAll(children.get(i).mediaItems);
}
return new PlaylistHolder(title, mediaItems);
} else {
@Nullable
String adaptiveMimeType =
Util.getAdaptiveMimeTypeForContentType(Util.inferContentType(uri, extension));
mediaItem
.setUri(uri)
.setMediaMetadata(new MediaMetadata.Builder().setTitle(title).build())
.setMimeType(adaptiveMimeType)
.setClippingConfiguration(clippingConfiguration.build());
if (drmUuid != null) {
mediaItem.setDrmConfiguration(
new MediaItem.DrmConfiguration.Builder(drmUuid)
.setLicenseUri(drmLicenseUri)
.setLicenseRequestHeaders(drmLicenseRequestHeaders)
.forceSessionsForAudioAndVideoTracks(drmSessionForClearContent)
.setMultiSession(drmMultiSession)
.setForceDefaultLicenseUri(drmForceDefaultLicenseUri)
.build());
} else {
checkState(drmLicenseUri == null, "drm_uuid is required if drm_license_uri is set.");
checkState(
drmLicenseRequestHeaders.isEmpty(),
"drm_uuid is required if drm_key_request_properties is set.");
checkState(
!drmSessionForClearContent,
"drm_uuid is required if drm_session_for_clear_content is set.");
checkState(!drmMultiSession, "drm_uuid is required if drm_multi_session is set.");
checkState(
!drmForceDefaultLicenseUri,
"drm_uuid is required if drm_force_default_license_uri is set.");
}
if (subtitleUri != null) {
MediaItem.SubtitleConfiguration subtitleConfiguration =
new MediaItem.SubtitleConfiguration.Builder(subtitleUri)
.setMimeType(
checkNotNull(
subtitleMimeType,
"subtitle_mime_type is required if subtitle_uri is set."))
.setLanguage(subtitleLanguage)
.build();
mediaItem.setSubtitleConfigurations(ImmutableList.of(subtitleConfiguration));
}
return new PlaylistHolder(title, Collections.singletonList(mediaItem.build()));
}
}
private PlaylistGroup getGroup(String groupName, List<PlaylistGroup> groups) {
for (int i = 0; i < groups.size(); i++) {
if (Util.areEqual(groupName, groups.get(i).title)) {
return groups.get(i);
}
}
PlaylistGroup group = new PlaylistGroup(groupName);
groups.add(group);
return group;
}
}
private final class SampleAdapter extends BaseExpandableListAdapter implements OnClickListener {
private List<PlaylistGroup> playlistGroups;
public SampleAdapter() {
playlistGroups = Collections.emptyList();
}
public void setPlaylistGroups(List<PlaylistGroup> playlistGroups) {
this.playlistGroups = playlistGroups;
notifyDataSetChanged();
}
@Override
public PlaylistHolder getChild(int groupPosition, int childPosition) {
return getGroup(groupPosition).playlists.get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(
int groupPosition,
int childPosition,
boolean isLastChild,
View convertView,
ViewGroup parent) {
View view = convertView;
if (view == null) {
view = getLayoutInflater().inflate(R.layout.sample_list_item, parent, false);
View downloadButton = view.findViewById(R.id.download_button);
downloadButton.setOnClickListener(this);
downloadButton.setFocusable(false);
}
initializeChildView(view, getChild(groupPosition, childPosition));
return view;
}
@Override
public int getChildrenCount(int groupPosition) {
return getGroup(groupPosition).playlists.size();
}
@Override
public PlaylistGroup getGroup(int groupPosition) {
return playlistGroups.get(groupPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(
int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view =
getLayoutInflater()
.inflate(android.R.layout.simple_expandable_list_item_1, parent, false);
}
((TextView) view).setText(getGroup(groupPosition).title);
return view;
}
@Override
public int getGroupCount() {
return playlistGroups.size();
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
@Override
public void onClick(View view) {
onSampleDownloadButtonClicked((PlaylistHolder) view.getTag());
}
private void initializeChildView(View view, PlaylistHolder playlistHolder) {
view.setTag(playlistHolder);
TextView sampleTitle = view.findViewById(R.id.sample_title);
sampleTitle.setText(playlistHolder.title);
boolean canDownload = getDownloadUnsupportedStringId(playlistHolder) == 0;
boolean isDownloaded =
canDownload && downloadTracker.isDownloaded(playlistHolder.mediaItems.get(0));
ImageButton downloadButton = view.findViewById(R.id.download_button);
downloadButton.setTag(playlistHolder);
downloadButton.setColorFilter(
canDownload ? (isDownloaded ? 0xFF42A5F5 : 0xFFBDBDBD) : 0xFF666666);
downloadButton.setImageResource(
isDownloaded ? R.drawable.ic_download_done : R.drawable.ic_download);
}
}
private static final class PlaylistHolder {
public final String title;
public final List<MediaItem> mediaItems;
private PlaylistHolder(String title, List<MediaItem> mediaItems) {
checkArgument(!mediaItems.isEmpty());
this.title = title;
this.mediaItems = Collections.unmodifiableList(new ArrayList<>(mediaItems));
}
}
private static final class PlaylistGroup {
public final String title;
public final List<PlaylistHolder> playlists;
public PlaylistGroup(String title) {
this.title = title;
this.playlists = new ArrayList<>();
}
}
}
| Switch the demo app from Util.areEqual to Guava's Objects.equals
Util.areEqual will not be part of the stable API.
PiperOrigin-RevId: 437723080
| demos/main/src/main/java/com/google/android/exoplayer2/demo/SampleChooserActivity.java | Switch the demo app from Util.areEqual to Guava's Objects.equals |
|
Java | apache-2.0 | d0881e4e9d2bfff434d33554092a718f2f0eac85 | 0 | naver/yobi,Limseunghwan/oss,bloodybear/yona,violetag/demo,Limseunghwan/oss,Limseunghwan/oss,violetag/demo,ihoneymon/yobi,ahb0327/yobi,brainagenet/yobi,oolso/yobi,ihoneymon/yobi,oolso/yobi,ChangsungKim/TestRepository01,ahb0327/yobi,doortts/forked-for-history,ChangsungKim/TestRepository01,brainagenet/yobi,doortts/forked-for-history,yona-projects/yona,doortts/fork-yobi,doortts/fork-yobi,doortts/fork-yobi,yona-projects/yona,ihoneymon/yobi,yona-projects/yona,bloodybear/yona,doortts/forked-for-history,brainagenet/yobi,naver/yobi,ahb0327/yobi,bloodybear/yona,oolso/yobi,yona-projects/yona,bloodybear/yona,doortts/fork-yobi,naver/yobi | package utils;
import java.net.UnknownHostException;
import java.util.List;
import org.apache.commons.lang.StringUtils;
public class Url {
/**
* Create url with given <code>pathSegments</code> and configured scheme, hostname and port.
*
* @param pathSegments List of path segments to construct the path.
*
* @return <code>String</code> containing the created URL
*/
public static String create(List<String> pathSegments) {
try {
return create(pathSegments, java.net.InetAddress.getLocalHost().getHostAddress());
} catch (UnknownHostException e) {
return create(pathSegments, "localhost");
}
}
/**
* Create url with given <code>pathSegments</code> and configured scheme, hostname and port.
*
* If hostname is not configured, use defaultHostport as hostname and port.
*
* @param pathSegments List of path segments to construct the path.
* @param defaultHostport
*
* @return <code>String</code> containing the created URL
*
*/
public static String create(List<String> pathSegments, String defaultHostport) {
return create(pathSegments, defaultHostport, "http");
}
/**
* Create url with given <code>pathSegments</code> and configured scheme, hostname and port.
*
* If scheme is not configured, use defaultScheme as the scheme.
* If hostname is not configured, use defaultHostport as the hostname and the port.
*
* @param pathSegments List of path segments to construct the path.
* @param defaultHostport
* @param defaultScheme
*
* @return <code>String</code> containing the created URL
*
*/
public static String create(List<String> pathSegments, String defaultHostport, String defaultScheme) {
String path = "/" + StringUtils.join(pathSegments, "/");
return Config.getScheme(defaultScheme) + "://" + Config.getHostport(defaultHostport) + path;
}
} | app/utils/Url.java | package utils;
import java.util.List;
import org.apache.commons.lang.StringUtils;
public class Url {
/**
* Create url with given <code>pathSegments</code> and configured scheme, hostname and port.
*
* @param pathSegments List of path segments to construct the path.
*
* @return <code>String</code> containing the created URL
*/
public static String create(List<String> pathSegments) {
return create(pathSegments, "localhost");
}
/**
* Create url with given <code>pathSegments</code> and configured scheme, hostname and port.
*
* If hostname is not configured, use defaultHostport as hostname and port.
*
* @param pathSegments List of path segments to construct the path.
* @param defaultHostport
*
* @return <code>String</code> containing the created URL
*
*/
public static String create(List<String> pathSegments, String defaultHostport) {
return create(pathSegments, defaultHostport, "http");
}
/**
* Create url with given <code>pathSegments</code> and configured scheme, hostname and port.
*
* If scheme is not configured, use defaultScheme as the scheme.
* If hostname is not configured, use defaultHostport as the hostname and the port.
*
* @param pathSegments List of path segments to construct the path.
* @param defaultHostport
* @param defaultScheme
*
* @return <code>String</code> containing the created URL
*
*/
public static String create(List<String> pathSegments, String defaultHostport, String defaultScheme) {
String path = "/" + StringUtils.join(pathSegments, "/");
return Config.getScheme(defaultScheme) + "://" + Config.getHostport(defaultHostport) + path;
}
} | utils: Better guess for default hostname.
Url.create considers INetAddress.getLocalHost.getHostAddress
as a default hostname.
| app/utils/Url.java | utils: Better guess for default hostname. |
|
Java | apache-2.0 | b141d21dce773c81ab277560cdb98beadfdc100a | 0 | chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.transport;
import java.io.IOException;
import java.util.Timer;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.activemq.command.KeepAliveInfo;
import org.apache.activemq.command.WireFormatInfo;
import org.apache.activemq.thread.SchedulerTimerTask;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Used to make sure that commands are arriving periodically from the peer of
* the transport.
*
* @version $Revision$
*/
public class InactivityMonitor extends TransportFilter {
private static final Log LOG = LogFactory.getLog(InactivityMonitor.class);
private static final ThreadPoolExecutor ASYNC_TASKS;
private static int CHECKER_COUNTER;
private static Timer READ_CHECK_TIMER;
private static Timer WRITE_CHECK_TIMER;
private WireFormatInfo localWireFormatInfo;
private WireFormatInfo remoteWireFormatInfo;
private final AtomicBoolean monitorStarted = new AtomicBoolean(false);
private final AtomicBoolean commandSent = new AtomicBoolean(false);
private final AtomicBoolean inSend = new AtomicBoolean(false);
private final AtomicBoolean commandReceived = new AtomicBoolean(true);
private final AtomicBoolean inReceive = new AtomicBoolean(false);
private SchedulerTimerTask writeCheckerTask;
private SchedulerTimerTask readCheckerTask;
private long readCheckTime;
private long writeCheckTime;
private final Runnable readChecker = new Runnable() {
long lastRunTime;
public void run() {
long now = System.currentTimeMillis();
long elapsed = (now-lastRunTime);
if( lastRunTime != 0 && LOG.isDebugEnabled() ) {
LOG.debug(""+elapsed+" ms elapsed since last read check.");
}
// Perhaps the timer executed a read check late.. and then executes
// the next read check on time which causes the time elapsed between
// read checks to be small..
// If less than 90% of the read check Time elapsed then abort this readcheck.
if( elapsed < (readCheckTime * 9 / 10) ) {
LOG.debug("Aborting read check.. Not enough time elapsed since last read check.");
return;
}
lastRunTime = now;
readCheck();
}
};
private final Runnable writeChecker = new Runnable() {
long lastRunTime;
public void run() {
long now = System.currentTimeMillis();
if( lastRunTime != 0 && LOG.isDebugEnabled() ) {
LOG.debug(""+(now-lastRunTime)+" ms elapsed since last write check.");
}
lastRunTime = now;
writeCheck();
}
};
public InactivityMonitor(Transport next) {
super(next);
}
public void stop() throws Exception {
stopMonitorThreads();
next.stop();
}
final void writeCheck() {
if (inSend.get()) {
if (LOG.isTraceEnabled()) {
LOG.trace("A send is in progress");
}
return;
}
if (!commandSent.get()) {
if(LOG.isTraceEnabled()) {
LOG.trace("No message sent since last write check, sending a KeepAliveInfo");
}
ASYNC_TASKS.execute(new Runnable() {
public void run() {
try {
oneway(new KeepAliveInfo());
} catch (IOException e) {
onException(e);
}
};
});
} else {
if (LOG.isTraceEnabled()) {
LOG.trace("Message sent since last write check, resetting flag");
}
}
commandSent.set(false);
}
final void readCheck() {
if (inReceive.get()) {
if (LOG.isTraceEnabled()) {
LOG.trace("A receive is in progress");
}
return;
}
if (!commandReceived.get()) {
if (LOG.isDebugEnabled()) {
LOG.debug("No message received since last read check for " + toString() + "! Throwing InactivityIOException.");
}
// TODO: use a thread pool for this..
ASYNC_TASKS.execute(new Runnable() {
public void run() {
onException(new InactivityIOException("Channel was inactive for too long: "+next.getRemoteAddress()));
};
});
} else {
if (LOG.isTraceEnabled()) {
LOG.trace("Message received since last read check, resetting flag: ");
}
}
commandReceived.set(false);
}
public void onCommand(Object command) {
commandReceived.set(true);
inReceive.set(true);
try {
if (command.getClass() == WireFormatInfo.class) {
synchronized (this) {
IOException error=null;
remoteWireFormatInfo = (WireFormatInfo)command;
try {
startMonitorThreads();
} catch (IOException e) {
error = e;
}
if( error!=null ) {
onException(error);
}
}
}
synchronized (readChecker) {
transportListener.onCommand(command);
}
} finally {
inReceive.set(false);
}
}
public void oneway(Object o) throws IOException {
// Disable inactivity monitoring while processing a command.
inSend.set(true);
try {
if (o.getClass() == WireFormatInfo.class) {
synchronized (this) {
localWireFormatInfo = (WireFormatInfo)o;
startMonitorThreads();
}
}
synchronized (writeChecker) {
next.oneway(o);
}
} finally {
commandSent.set(true);
inSend.set(false);
}
}
public void onException(IOException error) {
if (monitorStarted.get()) {
stopMonitorThreads();
}
transportListener.onException(error);
}
private synchronized void startMonitorThreads() throws IOException {
if (monitorStarted.get()) {
return;
}
if (localWireFormatInfo == null) {
return;
}
if (remoteWireFormatInfo == null) {
return;
}
readCheckTime = Math.min(localWireFormatInfo.getMaxInactivityDuration(), remoteWireFormatInfo.getMaxInactivityDuration());
if (readCheckTime > 0) {
monitorStarted.set(true);
writeCheckerTask = new SchedulerTimerTask(writeChecker);
readCheckerTask = new SchedulerTimerTask(readChecker);
writeCheckTime = readCheckTime/3;
synchronized( InactivityMonitor.class ) {
if( CHECKER_COUNTER == 0 ) {
READ_CHECK_TIMER = new Timer("InactivityMonitor ReadCheck");
WRITE_CHECK_TIMER = new Timer("InactivityMonitor WriteCheck");
}
CHECKER_COUNTER++;
WRITE_CHECK_TIMER.scheduleAtFixedRate(writeCheckerTask, writeCheckTime,writeCheckTime);
READ_CHECK_TIMER.scheduleAtFixedRate(readCheckerTask, readCheckTime,readCheckTime);
}
}
}
/**
*
*/
private synchronized void stopMonitorThreads() {
if (monitorStarted.compareAndSet(true, false)) {
readCheckerTask.cancel();
writeCheckerTask.cancel();
synchronized( InactivityMonitor.class ) {
WRITE_CHECK_TIMER.purge();
READ_CHECK_TIMER.purge();
CHECKER_COUNTER--;
if(CHECKER_COUNTER==0) {
WRITE_CHECK_TIMER.cancel();
READ_CHECK_TIMER.cancel();
WRITE_CHECK_TIMER = null;
READ_CHECK_TIMER = null;
}
}
}
}
static {
ASYNC_TASKS = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 10, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ThreadFactory() {
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "InactivityMonitor Async Task: "+runnable);
thread.setDaemon(true);
return thread;
}
});
}
}
| activemq-core/src/main/java/org/apache/activemq/transport/InactivityMonitor.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.transport;
import java.io.IOException;
import java.util.Timer;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.activemq.command.KeepAliveInfo;
import org.apache.activemq.command.WireFormatInfo;
import org.apache.activemq.thread.SchedulerTimerTask;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Used to make sure that commands are arriving periodically from the peer of
* the transport.
*
* @version $Revision$
*/
public class InactivityMonitor extends TransportFilter {
private static final Log LOG = LogFactory.getLog(InactivityMonitor.class);
private static final ThreadPoolExecutor ASYNC_TASKS;
private static int CHECKER_COUNTER;
private static Timer READ_CHECK_TIMER;
private static Timer WRITE_CHECK_TIMER;
private WireFormatInfo localWireFormatInfo;
private WireFormatInfo remoteWireFormatInfo;
private final AtomicBoolean monitorStarted = new AtomicBoolean(false);
private final AtomicBoolean commandSent = new AtomicBoolean(false);
private final AtomicBoolean inSend = new AtomicBoolean(false);
private final AtomicBoolean commandReceived = new AtomicBoolean(true);
private final AtomicBoolean inReceive = new AtomicBoolean(false);
private SchedulerTimerTask writeCheckerTask;
private SchedulerTimerTask readCheckerTask;
private final Runnable readChecker = new Runnable() {
long lastRunTime;
public void run() {
long now = System.currentTimeMillis();
if( lastRunTime != 0 && LOG.isDebugEnabled() ) {
LOG.debug(""+(now-lastRunTime)+" ms elapsed since last read check.");
}
lastRunTime = now;
readCheck();
}
};
private final Runnable writeChecker = new Runnable() {
long lastRunTime;
public void run() {
long now = System.currentTimeMillis();
if( lastRunTime != 0 && LOG.isDebugEnabled() ) {
LOG.debug(""+(now-lastRunTime)+" ms elapsed since last write check.");
}
lastRunTime = now;
writeCheck();
}
};
public InactivityMonitor(Transport next) {
super(next);
}
public void stop() throws Exception {
stopMonitorThreads();
next.stop();
}
final void writeCheck() {
if (inSend.get()) {
if (LOG.isTraceEnabled()) {
LOG.trace("A send is in progress");
}
return;
}
if (!commandSent.get()) {
if(LOG.isTraceEnabled()) {
LOG.trace("No message sent since last write check, sending a KeepAliveInfo");
}
ASYNC_TASKS.execute(new Runnable() {
public void run() {
try {
oneway(new KeepAliveInfo());
} catch (IOException e) {
onException(e);
}
};
});
} else {
if (LOG.isTraceEnabled()) {
LOG.trace("Message sent since last write check, resetting flag");
}
}
commandSent.set(false);
}
final void readCheck() {
if (inReceive.get()) {
if (LOG.isTraceEnabled()) {
LOG.trace("A receive is in progress");
}
return;
}
if (!commandReceived.get()) {
if (LOG.isDebugEnabled()) {
LOG.debug("No message received since last read check for " + toString() + "! Throwing InactivityIOException.");
}
// TODO: use a thread pool for this..
ASYNC_TASKS.execute(new Runnable() {
public void run() {
onException(new InactivityIOException("Channel was inactive for too long: "+next.getRemoteAddress()));
};
});
} else {
if (LOG.isTraceEnabled()) {
LOG.trace("Message received since last read check, resetting flag: ");
}
}
commandReceived.set(false);
}
public void onCommand(Object command) {
commandReceived.set(true);
inReceive.set(true);
try {
if (command.getClass() == WireFormatInfo.class) {
synchronized (this) {
IOException error=null;
remoteWireFormatInfo = (WireFormatInfo)command;
try {
startMonitorThreads();
} catch (IOException e) {
error = e;
}
if( error!=null ) {
onException(error);
}
}
}
synchronized (readChecker) {
transportListener.onCommand(command);
}
} finally {
inReceive.set(false);
}
}
public void oneway(Object o) throws IOException {
// Disable inactivity monitoring while processing a command.
inSend.set(true);
try {
if (o.getClass() == WireFormatInfo.class) {
synchronized (this) {
localWireFormatInfo = (WireFormatInfo)o;
startMonitorThreads();
}
}
synchronized (writeChecker) {
next.oneway(o);
}
} finally {
commandSent.set(true);
inSend.set(false);
}
}
public void onException(IOException error) {
if (monitorStarted.get()) {
stopMonitorThreads();
}
transportListener.onException(error);
}
private synchronized void startMonitorThreads() throws IOException {
if (monitorStarted.get()) {
return;
}
if (localWireFormatInfo == null) {
return;
}
if (remoteWireFormatInfo == null) {
return;
}
long checkTime = Math.min(localWireFormatInfo.getMaxInactivityDuration(), remoteWireFormatInfo.getMaxInactivityDuration());
if (checkTime > 0) {
monitorStarted.set(true);
writeCheckerTask = new SchedulerTimerTask(writeChecker);
readCheckerTask = new SchedulerTimerTask(readChecker);
long writeCheckTime = checkTime/3;
synchronized( InactivityMonitor.class ) {
if( CHECKER_COUNTER == 0 ) {
READ_CHECK_TIMER = new Timer("InactivityMonitor ReadCheck");
WRITE_CHECK_TIMER = new Timer("InactivityMonitor WriteCheck");
}
CHECKER_COUNTER++;
WRITE_CHECK_TIMER.scheduleAtFixedRate(writeCheckerTask, writeCheckTime,writeCheckTime);
READ_CHECK_TIMER.scheduleAtFixedRate(readCheckerTask, checkTime,checkTime);
}
}
}
/**
*
*/
private synchronized void stopMonitorThreads() {
if (monitorStarted.compareAndSet(true, false)) {
readCheckerTask.cancel();
writeCheckerTask.cancel();
synchronized( InactivityMonitor.class ) {
WRITE_CHECK_TIMER.purge();
READ_CHECK_TIMER.purge();
CHECKER_COUNTER--;
if(CHECKER_COUNTER==0) {
WRITE_CHECK_TIMER.cancel();
READ_CHECK_TIMER.cancel();
WRITE_CHECK_TIMER = null;
READ_CHECK_TIMER = null;
}
}
}
}
static {
ASYNC_TASKS = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 10, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ThreadFactory() {
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "InactivityMonitor Async Task: "+runnable);
thread.setDaemon(true);
return thread;
}
});
}
}
| Gaurd against too many read checks happening back to back.
git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@629859 13f79535-47bb-0310-9956-ffa450edef68
| activemq-core/src/main/java/org/apache/activemq/transport/InactivityMonitor.java | Gaurd against too many read checks happening back to back. |
|
Java | apache-2.0 | 1c2aaa8faf2f57c2098a7404f055f323e79c4e22 | 0 | spotify/apollo,rouzwawi/apollo,spotify/apollo,rouzwawi/apollo,rouzwawi/apollo,rouzwawi/apollo,spotify/apollo,spotify/apollo | /*
* -\-\-
* Spotify Apollo Entity Middleware
* --
* Copyright (C) 2013 - 2016 Spotify AB
* --
* 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.spotify.apollo.entity;
import com.spotify.apollo.Response;
import com.spotify.apollo.Status;
import com.spotify.apollo.route.AsyncHandler;
import com.spotify.apollo.route.Middleware;
import com.spotify.apollo.route.SyncHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import okio.ByteString;
import static java.util.concurrent.CompletableFuture.completedFuture;
/**
* A factory for creating middlewares that can be used to create routes that deal directly
* with an api entity.
*
* A {@link EntityCodec} is used to define how to go between a {@link ByteString} and the
* entity type used in your route handlers.
*/
class CodecEntityMiddleware implements EntityMiddleware {
private static final Logger LOG = LoggerFactory.getLogger(CodecEntityMiddleware.class);
private static final String CONTENT_TYPE = "Content-Type";
private static final String DEFAULT_CONTENT_TYPE = "application/json";
private final EntityCodec codec;
private final String contentType;
CodecEntityMiddleware(EntityCodec codec) {
this(codec, DEFAULT_CONTENT_TYPE);
}
CodecEntityMiddleware(EntityCodec codec, String contentType) {
this.codec = Objects.requireNonNull(codec);
this.contentType = Objects.requireNonNull(contentType);
}
@Override
public <R> Middleware<SyncHandler<R>, SyncHandler<Response<ByteString>>>
serializerDirect(Class<? extends R> entityClass) {
return inner -> inner
.map(this::ensureResponse)
.map(serialize(entityClass));
}
@Override
public <R> Middleware<SyncHandler<Response<R>>, SyncHandler<Response<ByteString>>>
serializerResponse(Class<? extends R> entityClass) {
return inner -> inner.map(serialize(entityClass));
}
@Override
public <R> Middleware<AsyncHandler<R>, AsyncHandler<Response<ByteString>>>
asyncSerializerDirect(Class<? extends R> entityClass) {
return inner -> inner
.map(this::ensureResponse)
.map(serialize(entityClass));
}
@Override
public <R> Middleware<AsyncHandler<Response<R>>, AsyncHandler<Response<ByteString>>>
asyncSerializerResponse(Class<? extends R> entityClass) {
return inner -> inner.map(serialize(entityClass));
}
@Override
public <E> Middleware<EntityHandler<E, ?>, SyncHandler<Response<ByteString>>>
direct(Class<? extends E> entityClass) {
return inner ->
deserialize(entityClass)
.flatMap(r -> ctx -> mapPayload(r, inner.invoke(ctx)))
.map(serialize(entityClass));
}
@Override
public <E> Middleware<EntityResponseHandler<E, ?>, SyncHandler<Response<ByteString>>>
response(Class<? extends E> entityClass) {
return inner ->
deserialize(entityClass)
.flatMap(r -> ctx -> flatMapPayload(r, inner.invoke(ctx)))
.map(serialize(entityClass));
}
@Override
public <E> Middleware<EntityAsyncHandler<E, ?>, AsyncHandler<Response<ByteString>>> asyncDirect(
Class<? extends E> entityClass) {
return inner ->
Middleware.syncToAsync(deserialize(entityClass))
.flatMap(r -> ctx -> asyncMapPayload(r, inner.invoke(ctx)))
.map(serialize(entityClass));
}
@Override
public <E> Middleware<EntityAsyncResponseHandler<E, ?>, AsyncHandler<Response<ByteString>>>
asyncResponse(Class<? extends E> entityClass) {
return inner ->
Middleware.syncToAsync(deserialize(entityClass))
.flatMap(r -> ctx -> asyncFlatMapPayload(r, inner.invoke(ctx)))
.map(serialize(entityClass));
}
private <E> SyncHandler<Response<E>> deserialize(Class<? extends E> entityClass) {
return requestContext -> {
final Optional<ByteString> payloadOpt = requestContext.request().payload();
if (!payloadOpt.isPresent()) {
return Response.forStatus(
Status.BAD_REQUEST
.withReasonPhrase("Missing payload"));
}
final E entity;
try {
final ByteString byteString = payloadOpt.get();
entity = codec.read(byteString.toByteArray(), entityClass);
} catch (IOException e) {
LOG.warn("error", e);
return Response.forStatus(
Status.BAD_REQUEST
.withReasonPhrase("Payload parsing failed: " + e.getMessage()));
}
return Response.forPayload(entity);
};
}
private <E> Function<Response<E>, Response<ByteString>> serialize(Class<? extends E> entityClass) {
return response -> {
final Optional<E> entityOpt = response.payload();
if (!entityOpt.isPresent()) {
//noinspection unchecked
return (Response<ByteString>) response;
}
final ByteString bytes;
try {
bytes = ByteString.of(codec.write(entityOpt.get(), entityClass));
} catch (IOException e) {
LOG.error("error", e);
return Response.forStatus(
Status.INTERNAL_SERVER_ERROR
.withReasonPhrase("Payload serialization failed: " + e.getMessage()));
}
return response.withPayload(bytes)
.withHeader(CONTENT_TYPE, contentType);
};
}
private <E> Response<E> ensureResponse(E response) {
if (response instanceof Response) {
//noinspection unchecked
return (Response<E>) response;
}
return Response.forPayload(response);
}
private <E, R> Response<R> mapPayload(
Response<E> in,
Function<? super E, ? extends R> fn) {
//noinspection unchecked
return (in.payload().map(fn).isPresent())
? in.withPayload(in.payload().map(fn).get())
: (Response<R>) in;
}
private <E, R> Response<R> flatMapPayload(
Response<E> in,
Function<? super E, ? extends Response<? extends R>> fn) {
//noinspection unchecked
return (in.payload().isPresent())
? (Response<R>) fn.apply(in.payload().get()).withHeaders(in.headers())
: (Response<R>) in;
}
private <E, R> CompletionStage<Response<R>> asyncMapPayload(
Response<E> in,
Function<? super E, ? extends CompletionStage<? extends R>> fn) {
//noinspection unchecked
return (in.payload().isPresent())
? fn.apply(in.payload().get()).thenApply(in::withPayload)
: completedFuture((Response<R>) in);
}
private <E, R> CompletionStage<Response<R>> asyncFlatMapPayload(
Response<E> in,
Function<? super E, ? extends CompletionStage<? extends Response<? extends R>>> fn) {
//noinspection unchecked
return (in.payload().isPresent())
? fn.apply(in.payload().get()).thenApply(ret -> (Response<R>) ret.withHeaders(in.headers()))
: completedFuture((Response<R>) in);
}
}
| apollo-entity/src/main/java/com/spotify/apollo/entity/CodecEntityMiddleware.java | /*
* -\-\-
* Spotify Apollo Entity Middleware
* --
* Copyright (C) 2013 - 2016 Spotify AB
* --
* 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.spotify.apollo.entity;
import com.spotify.apollo.Response;
import com.spotify.apollo.Status;
import com.spotify.apollo.route.AsyncHandler;
import com.spotify.apollo.route.Middleware;
import com.spotify.apollo.route.SyncHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import okio.ByteString;
import static java.util.concurrent.CompletableFuture.completedFuture;
/**
* A factory for creating middlewares that can be used to jackson the routes that deal directly
* with an api entity.
*/
class CodecEntityMiddleware implements EntityMiddleware {
private static final Logger LOG = LoggerFactory.getLogger(CodecEntityMiddleware.class);
private static final String CONTENT_TYPE = "Content-Type";
private static final String DEFAULT_CONTENT_TYPE = "application/json";
private final EntityCodec codec;
private final String contentType;
CodecEntityMiddleware(EntityCodec codec) {
this(codec, DEFAULT_CONTENT_TYPE);
}
CodecEntityMiddleware(EntityCodec codec, String contentType) {
this.codec = Objects.requireNonNull(codec);
this.contentType = Objects.requireNonNull(contentType);
}
@Override
public <R> Middleware<SyncHandler<R>, SyncHandler<Response<ByteString>>>
serializerDirect(Class<? extends R> entityClass) {
return inner -> inner
.map(this::ensureResponse)
.map(serialize(entityClass));
}
@Override
public <R> Middleware<SyncHandler<Response<R>>, SyncHandler<Response<ByteString>>>
serializerResponse(Class<? extends R> entityClass) {
return inner -> inner.map(serialize(entityClass));
}
@Override
public <R> Middleware<AsyncHandler<R>, AsyncHandler<Response<ByteString>>>
asyncSerializerDirect(Class<? extends R> entityClass) {
return inner -> inner
.map(this::ensureResponse)
.map(serialize(entityClass));
}
@Override
public <R> Middleware<AsyncHandler<Response<R>>, AsyncHandler<Response<ByteString>>>
asyncSerializerResponse(Class<? extends R> entityClass) {
return inner -> inner.map(serialize(entityClass));
}
@Override
public <E> Middleware<EntityHandler<E, ?>, SyncHandler<Response<ByteString>>>
direct(Class<? extends E> entityClass) {
return inner ->
deserialize(entityClass)
.flatMap(r -> ctx -> mapPayload(r, inner.invoke(ctx)))
.map(serialize(entityClass));
}
@Override
public <E> Middleware<EntityResponseHandler<E, ?>, SyncHandler<Response<ByteString>>>
response(Class<? extends E> entityClass) {
return inner ->
deserialize(entityClass)
.flatMap(r -> ctx -> flatMapPayload(r, inner.invoke(ctx)))
.map(serialize(entityClass));
}
@Override
public <E> Middleware<EntityAsyncHandler<E, ?>, AsyncHandler<Response<ByteString>>> asyncDirect(
Class<? extends E> entityClass) {
return inner ->
Middleware.syncToAsync(deserialize(entityClass))
.flatMap(r -> ctx -> asyncMapPayload(r, inner.invoke(ctx)))
.map(serialize(entityClass));
}
@Override
public <E> Middleware<EntityAsyncResponseHandler<E, ?>, AsyncHandler<Response<ByteString>>>
asyncResponse(Class<? extends E> entityClass) {
return inner ->
Middleware.syncToAsync(deserialize(entityClass))
.flatMap(r -> ctx -> asyncFlatMapPayload(r, inner.invoke(ctx)))
.map(serialize(entityClass));
}
private <E> SyncHandler<Response<E>> deserialize(Class<? extends E> entityClass) {
return requestContext -> {
final Optional<ByteString> payloadOpt = requestContext.request().payload();
if (!payloadOpt.isPresent()) {
return Response.forStatus(
Status.BAD_REQUEST
.withReasonPhrase("Missing payload"));
}
final E entity;
try {
final ByteString byteString = payloadOpt.get();
entity = codec.read(byteString.toByteArray(), entityClass);
} catch (IOException e) {
LOG.warn("error", e);
return Response.forStatus(
Status.BAD_REQUEST
.withReasonPhrase("Payload parsing failed: " + e.getMessage()));
}
return Response.forPayload(entity);
};
}
private <E> Function<Response<E>, Response<ByteString>> serialize(Class<? extends E> entityClass) {
return response -> {
final Optional<E> entityOpt = response.payload();
if (!entityOpt.isPresent()) {
//noinspection unchecked
return (Response<ByteString>) response;
}
final ByteString bytes;
try {
bytes = ByteString.of(codec.write(entityOpt.get(), entityClass));
} catch (IOException e) {
LOG.error("error", e);
return Response.forStatus(
Status.INTERNAL_SERVER_ERROR
.withReasonPhrase("Payload serialization failed: " + e.getMessage()));
}
return response.withPayload(bytes)
.withHeader(CONTENT_TYPE, contentType);
};
}
private <E> Response<E> ensureResponse(E response) {
if (response instanceof Response) {
//noinspection unchecked
return (Response<E>) response;
}
return Response.forPayload(response);
}
private <E, R> Response<R> mapPayload(
Response<E> in,
Function<? super E, ? extends R> fn) {
//noinspection unchecked
return (in.payload().map(fn).isPresent())
? in.withPayload(in.payload().map(fn).get())
: (Response<R>) in;
}
private <E, R> Response<R> flatMapPayload(
Response<E> in,
Function<? super E, ? extends Response<? extends R>> fn) {
//noinspection unchecked
return (in.payload().isPresent())
? (Response<R>) fn.apply(in.payload().get()).withHeaders(in.headers())
: (Response<R>) in;
}
private <E, R> CompletionStage<Response<R>> asyncMapPayload(
Response<E> in,
Function<? super E, ? extends CompletionStage<? extends R>> fn) {
//noinspection unchecked
return (in.payload().isPresent())
? fn.apply(in.payload().get()).thenApply(in::withPayload)
: completedFuture((Response<R>) in);
}
private <E, R> CompletionStage<Response<R>> asyncFlatMapPayload(
Response<E> in,
Function<? super E, ? extends CompletionStage<? extends Response<? extends R>>> fn) {
//noinspection unchecked
return (in.payload().isPresent())
? fn.apply(in.payload().get()).thenApply(ret -> (Response<R>) ret.withHeaders(in.headers()))
: completedFuture((Response<R>) in);
}
}
| fix javadoc comment
| apollo-entity/src/main/java/com/spotify/apollo/entity/CodecEntityMiddleware.java | fix javadoc comment |
|
Java | apache-2.0 | cf2f082c6484b52520a782a68115351d28999bf4 | 0 | oasisfeng/condom | /*
* Copyright (C) 2017 Oasis Feng. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* 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.oasisfeng.condom;
import android.Manifest.permission;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.ComponentInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.UserHandle;
import android.provider.Settings;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.test.InstrumentationRegistry;
import org.junit.Assume;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.ParametersAreNonnullByDefault;
import static android.content.Intent.FLAG_RECEIVER_REGISTERED_ONLY;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.HONEYCOMB_MR1;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static android.os.Build.VERSION_CODES.N;
import static android.os.Build.VERSION_CODES.O;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
@ParametersAreNonnullByDefault
public class CondomContextBlockingTest {
@Test public void testSelfTargeted() {
final TestContext context = new TestContext();
final CondomContext condom = CondomContext.wrap(context, TAG), dry_condom = CondomContext.wrap(context, TAG, new CondomOptions().setDryRun(true));
// Self-targeting test
final String self_pkg = condom.getPackageName();
final Intent[] self_targeted_intents = new Intent[] {
intent().setPackage(self_pkg),
intent().setComponent(new ComponentName(self_pkg, "X"))
};
for (final Context context2test : new Context[] {condom, condom.getApplicationContext(), dry_condom, dry_condom.getApplicationContext()})
with(self_targeted_intents, allBroadcastAndServiceApis(context2test), context.EXPECT_BASE_CALLED, context.expectFlags(0));
}
@Test public void testPreventNone() {
final TestContext context = new TestContext();
final CondomOptions options = new CondomOptions().preventServiceInBackgroundPackages(false).preventBroadcastToBackgroundPackages(false);
final CondomContext condom = CondomContext.wrap(context, TAG, options), dry_condom = CondomContext.wrap(context, TAG, options.setDryRun(true));
//noinspection deprecation, intentional test for deprecated method
condom.preventWakingUpStoppedPackages(false);
//noinspection deprecation
dry_condom.preventWakingUpStoppedPackages(false);
for (final Context context2test : new Context[] {condom, condom.getApplicationContext(), dry_condom, dry_condom.getApplicationContext()})
with(ALL_SORT_OF_INTENTS, allBroadcastAndServiceApis(context2test), context.EXPECT_BASE_CALLED, context.expectFlags(0));
}
@Test public void testPreventWakingUpStoppedPackages_IncludingDryRun() {
final Intent[] intents_with_inc_stop = ALL_SORT_OF_INTENTS.clone();
for (int i = 0; i < intents_with_inc_stop.length; i++)
intents_with_inc_stop[i] = new Intent(intents_with_inc_stop[i]).addFlags(FLAG_INCLUDE_STOPPED_PACKAGES);
final TestContext context = new TestContext();
final CondomOptions options = new CondomOptions().preventBroadcastToBackgroundPackages(false).preventServiceInBackgroundPackages(false);
final CondomContext condom = CondomContext.wrap(context, TAG, options), dry_condom = CondomContext.wrap(context, TAG, options.setDryRun(true));
for (final Context context2test : new Context[] {condom, condom.getApplicationContext()})
with(intents_with_inc_stop, allBroadcastAndServiceApis(context2test), context.EXPECT_BASE_CALLED, context.expectFlags(FLAG_EXCLUDE_STOPPED_PACKAGES));
for (final Context context2test : new Context[] {dry_condom, dry_condom.getApplicationContext()})
with(intents_with_inc_stop, allBroadcastAndServiceApis(context2test), context.EXPECT_BASE_CALLED, context.expectFlags(FLAG_INCLUDE_STOPPED_PACKAGES));
}
@Test public void testPreventBroadcastToBackgroundPackages() {
final TestContext context = new TestContext();
final CondomOptions options = new CondomOptions().preventBroadcastToBackgroundPackages(true);
final CondomContext condom = CondomContext.wrap(context, TAG, options), dry_condom = CondomContext.wrap(context, TAG, options.setDryRun(true));
final int extra_flag = SDK_INT >= N ? CondomCore.FLAG_RECEIVER_EXCLUDE_BACKGROUND : FLAG_RECEIVER_REGISTERED_ONLY;
for (final Context context2test : new Context[] {condom, condom.getApplicationContext()})
with(ALL_SORT_OF_INTENTS, allBroadcastApis(context2test), context.EXPECT_BASE_CALLED, context.expectFlags(FLAG_EXCLUDE_STOPPED_PACKAGES | extra_flag));
for (final Context context2test : new Context[] {dry_condom, dry_condom.getApplicationContext()})
with(ALL_SORT_OF_INTENTS, allBroadcastApis(context2test), context.EXPECT_BASE_CALLED, context.expectFlags(0));
}
@Test public void testPreventServiceInBackgroundPackages() {
Assume.assumeTrue(SDK_INT < O);
final TestContext context = new TestContext();
context.mTestingBackgroundUid = true;
final CondomOptions options = new CondomOptions().preventServiceInBackgroundPackages(true).preventBroadcastToBackgroundPackages(false);
final CondomContext condom = CondomContext.wrap(context, TAG, options), dry_condom = CondomContext.wrap(context, TAG, options.setDryRun(true));
for (final Context context2test : new Context[] {condom, condom.getApplicationContext()}) {
final List<ResolveInfo> services = context2test.getPackageManager().queryIntentServices(intent(), 0);
assertEquals(3, services.size());
context.assertBaseCalled();
final ResolveInfo resolve = context2test.getPackageManager().resolveService(intent(), 0);
assertEquals("non.bg.service", resolve.serviceInfo.packageName);
context.assertBaseCalled();
}
for (final Context context2test : new Context[] {dry_condom, dry_condom.getApplicationContext()}) {
final List<ResolveInfo> services = context2test.getPackageManager().queryIntentServices(intent(), 0);
assertEquals(4, services.size());
context.assertBaseCalled();
assertEquals(7777777, context2test.getPackageManager().resolveService(intent(), 0).serviceInfo.applicationInfo.uid);
context.assertBaseCalled();
}
}
@Test public void testContentProviderOutboundJudge() {
final TestContext context = new TestContext();
final CondomOptions options = new CondomOptions().setOutboundJudge(new OutboundJudge() { @Override public boolean shouldAllow(final OutboundType type, final @Nullable Intent intent, final String target_pkg) {
final String settings_pkg = InstrumentationRegistry.getTargetContext().getPackageManager().resolveContentProvider(Settings.System.CONTENT_URI.getAuthority(), 0).packageName;
return ! settings_pkg.equals(target_pkg);
}});
final CondomContext condom = CondomContext.wrap(context, TAG, options), dry_condom = CondomContext.wrap(context, TAG, options.setDryRun(true));
for (final Context context2test : new Context[] {condom, condom.getApplicationContext()}) {
assertNull(context2test.getPackageManager().resolveContentProvider(Settings.AUTHORITY, 0));
assertNull(context2test.getContentResolver().acquireContentProviderClient(Settings.System.CONTENT_URI));
}
for (final Context context2test : new Context[] {dry_condom, dry_condom.getApplicationContext()}) {
assertNotNull(context2test.getPackageManager().resolveContentProvider(Settings.AUTHORITY, 0));
assertNotNull(context2test.getContentResolver().acquireContentProviderClient(Settings.System.CONTENT_URI));
}
}
@Test public void testContentProvider() {
final TestContext context = new TestContext();
final CondomContext condom = CondomContext.wrap(context, TAG), dry_condom = CondomContext.wrap(context, TAG, new CondomOptions().setDryRun(true));
// Regular provider access
final String android_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
assertNotNull(android_id);
for (final Context context2test : new Context[] {condom, condom.getApplicationContext(), dry_condom, dry_condom.getApplicationContext()}) {
final String condom_android_id = Settings.Secure.getString(context2test.getContentResolver(), Settings.Secure.ANDROID_ID);
assertEquals(android_id, condom_android_id);
}
context.mTestingStoppedProvider = true;
for (final Context context2test : new Context[] {condom, condom.getApplicationContext()}) {
// Prevent stopped packages,
assertNull(context2test.getPackageManager().resolveContentProvider(TEST_AUTHORITY, 0));
assertNull(context2test.getContentResolver().acquireContentProviderClient(TEST_CONTENT_URI));
// Providers in system package should not be blocked.
assertNotNull(context2test.getPackageManager().resolveContentProvider(Settings.AUTHORITY, 0));
assertNotNull(context2test.getContentResolver().acquireContentProviderClient(Settings.System.CONTENT_URI));
}
for (final Context context2test : new Context[] {dry_condom, dry_condom.getApplicationContext()}) {
assertNotNull(context2test.getPackageManager().resolveContentProvider(TEST_AUTHORITY, 0));
assertNotNull(context2test.getContentResolver().acquireContentProviderClient(TEST_CONTENT_URI));
}
context.mTestingStoppedProvider = false;
}
private static final String TEST_AUTHORITY = "com.oasisfeng.condom.test";
private static final Uri TEST_CONTENT_URI = Uri.parse("content://" + TEST_AUTHORITY + "/");
public static class TestProvider extends ContentProvider {
@Override public boolean onCreate() { return true; }
@Nullable @Override public Cursor query(@NonNull final Uri uri, @Nullable final String[] strings, @Nullable final String s, @Nullable final String[] strings1, @Nullable final String s1) { return null; }
@Nullable @Override public String getType(@NonNull final Uri uri) { return null; }
@Nullable @Override public Uri insert(@NonNull final Uri uri, @Nullable final ContentValues contentValues) { return null; }
@Override public int delete(@NonNull final Uri uri, @Nullable final String s, @Nullable final String[] strings) { return 0; }
@Override public int update(@NonNull final Uri uri, @Nullable final ContentValues contentValues, @Nullable final String s, @Nullable final String[] strings) { return 0; }
}
@Test public void testOutboundJudge() {
final TestContext context = new TestContext();
final CondomOptions options = new CondomOptions().setOutboundJudge(new OutboundJudge() {
@Override public boolean shouldAllow(final OutboundType type, final @Nullable Intent intent, final String target_pkg) {
mNumOutboundJudgeCalled.incrementAndGet();
return ! DISALLOWED_PACKAGE.equals(target_pkg);
}
});
final CondomContext condom = CondomContext.wrap(context, TAG, options), dry_condom = CondomContext.wrap(context, TAG, options.setDryRun(true));
final Runnable EXPECT_OUTBOUND_JUDGE_REFUSAL = new Runnable() { @Override public void run() {
context.assertBaseNotCalled();
assertOutboundJudgeCalled(1);
}};
final Runnable EXPECT_OUTBOUND_JUDGE_PASS = new Runnable() { @Override public void run() {
context.assertBaseCalled();
assertOutboundJudgeCalled(1);
}};
for (final Context context2test : new Context[] {condom, condom.getApplicationContext()})
with(DISALLOWED_INTENTS, allBroadcastApis(context2test), EXPECT_OUTBOUND_JUDGE_REFUSAL);
for (final Context context2test : new Context[] {dry_condom, dry_condom.getApplicationContext()})
with(DISALLOWED_INTENTS, allBroadcastApis(context2test), EXPECT_OUTBOUND_JUDGE_PASS);
for (final Context context2test : new Context[] {condom, condom.getApplicationContext(), dry_condom, dry_condom.getApplicationContext()})
with(ALLOWED_INTENTS, allBroadcastApis(context2test), EXPECT_OUTBOUND_JUDGE_PASS);
final PackageManager pm = condom.getPackageManager(), dry_pm = dry_condom.getPackageManager();
assertNull(pm.resolveService(intent().setPackage(DISALLOWED_PACKAGE), 0));
context.assertBaseNotCalled();
assertOutboundJudgeCalled(1);
assertNotNull(dry_pm.resolveService(intent().setPackage(DISALLOWED_PACKAGE), 0));
context.assertBaseCalled();
assertOutboundJudgeCalled(1);
assertEquals(1, pm.queryIntentServices(intent(), 0).size());
context.assertBaseCalled();
assertOutboundJudgeCalled(2);
assertEquals(2, dry_pm.queryIntentServices(intent(), 0).size());
context.assertBaseCalled();
assertOutboundJudgeCalled(2);
assertEquals(1, pm.queryBroadcastReceivers(intent(), 0).size());
context.assertBaseCalled();
assertOutboundJudgeCalled(2);
assertEquals(2, dry_pm.queryBroadcastReceivers(intent(), 0).size());
context.assertBaseCalled();
assertOutboundJudgeCalled(2);
condom.sendBroadcast(intent());
context.assertBaseCalled();
assertOutboundJudgeCalled(0);
dry_condom.sendBroadcast(intent());
context.assertBaseCalled();
assertOutboundJudgeCalled(0);
}
private static void with(final Intent[] intents, final Consumer<Intent>[] tests, final Runnable... expectations) {
for (final Intent intent : intents)
for (final Consumer<Intent> test : tests) {
test.accept(intent);
for (final Runnable expectation : expectations) expectation.run();
}
}
private static Intent intent() { return new Intent("com.example.TEST").addFlags(INTENT_FLAGS); }
private static final UserHandle USER = SDK_INT >= JELLY_BEAN_MR1 ? android.os.Process.myUserHandle() : null;
private static final int INTENT_FLAGS = Intent.FLAG_DEBUG_LOG_RESOLUTION | Intent.FLAG_FROM_BACKGROUND; // Just random flags to verify flags preservation.
private static final ServiceConnection SERVICE_CONNECTION = new ServiceConnection() {
@Override public void onServiceConnected(final ComponentName name, final IBinder service) {}
@Override public void onServiceDisconnected(final ComponentName name) {}
};
private static final String DISALLOWED_PACKAGE = "a.b.c";
private static final String ALLOWED_PACKAGE = "x.y.z";
private static final ComponentName DISALLOWED_COMPONENT = new ComponentName(DISALLOWED_PACKAGE, "A");
private static final ComponentName ALLOWED_COMPONENT = new ComponentName(ALLOWED_PACKAGE, "A");
private static final int FLAG_EXCLUDE_STOPPED_PACKAGES = SDK_INT >= HONEYCOMB_MR1 ? Intent.FLAG_EXCLUDE_STOPPED_PACKAGES : 0;
private static final int FLAG_INCLUDE_STOPPED_PACKAGES = SDK_INT >= HONEYCOMB_MR1 ? Intent.FLAG_INCLUDE_STOPPED_PACKAGES : 0;
private static final Intent[] ALL_SORT_OF_INTENTS = new Intent[] {
intent(),
intent().setPackage(ALLOWED_PACKAGE),
intent().setPackage(DISALLOWED_PACKAGE),
intent().setComponent(ALLOWED_COMPONENT),
intent().setComponent(DISALLOWED_COMPONENT),
};
private static final Intent[] ALLOWED_INTENTS = new Intent[] {
intent().setPackage(ALLOWED_PACKAGE),
intent().setComponent(ALLOWED_COMPONENT),
};
private static final Intent[] DISALLOWED_INTENTS = new Intent[] {
intent().setPackage(DISALLOWED_PACKAGE),
intent().setComponent(DISALLOWED_COMPONENT),
};
private static Consumer<Intent>[] allBroadcastAndServiceApis(final Context condom) {
final Consumer<Intent>[] broadcast_apis = allBroadcastApis(condom);
final Consumer<Intent>[] service_apis = allServiceApis(condom);
final Consumer<Intent>[] all = Arrays.copyOf(broadcast_apis, broadcast_apis.length + service_apis.length);
System.arraycopy(service_apis, 0, all, broadcast_apis.length, service_apis.length);
return all;
}
private static Consumer<Intent>[] allBroadcastApis(final Context condom) {
final List<Consumer<Intent>> tests = new ArrayList<>();
tests.add(new Consumer<Intent>() { @Override public void accept(final Intent intent) { condom.sendBroadcast(intent); }});
tests.add(new Consumer<Intent>() { @Override public void accept(final Intent intent) { condom.sendBroadcast(intent, permission.DUMP); }});
tests.add(new Consumer<Intent>() { @Override public void accept(final Intent intent) { condom.sendOrderedBroadcast(intent, permission.DUMP); }});
tests.add(new Consumer<Intent>() { @Override public void accept(final Intent intent) { condom.sendOrderedBroadcast(intent, permission.DUMP, null, null, 0, null, null); }});
tests.add(new Consumer<Intent>() { @Override public void accept(final Intent intent) { condom.sendStickyBroadcast(intent); }});
tests.add(new Consumer<Intent>() { @Override public void accept(final Intent intent) { condom.sendStickyOrderedBroadcast(intent, null, null, 0, null, null); }});
if (SDK_INT >= JELLY_BEAN_MR1) {
tests.add(new Consumer<Intent>() { @TargetApi(JELLY_BEAN_MR1) @Override public void accept(final Intent intent) { condom.sendBroadcastAsUser(intent, USER); }});
tests.add(new Consumer<Intent>() { @TargetApi(JELLY_BEAN_MR1) @Override public void accept(final Intent intent) { condom.sendBroadcastAsUser(intent, USER, null); }});
tests.add(new Consumer<Intent>() { @TargetApi(JELLY_BEAN_MR1) @Override public void accept(final Intent intent) { condom.sendStickyBroadcastAsUser(intent, USER); }});
tests.add(new Consumer<Intent>() { @TargetApi(JELLY_BEAN_MR1) @Override public void accept(final Intent intent) { condom.sendOrderedBroadcastAsUser(intent, USER, null, null, null, 0, null, null); }});
tests.add(new Consumer<Intent>() { @TargetApi(JELLY_BEAN_MR1) @Override public void accept(final Intent intent) { condom.sendStickyOrderedBroadcastAsUser(intent, USER,null, null, 0, null, null); }});
}
tests.add(new Consumer<Intent>() { @Override public void accept(final Intent intent) { condom.getPackageManager().queryBroadcastReceivers(intent, 0); }});
//noinspection unchecked
return tests.toArray(new Consumer[tests.size()]);
}
@SuppressWarnings("unchecked") private static Consumer<Intent>[] allServiceApis(final Context condom) {
return new Consumer[] {
new Consumer<Intent>() { @Override public void accept(final Intent intent) {
condom.startService(intent);
}}, new Consumer<Intent>() { @Override public void accept(final Intent intent) {
condom.bindService(intent, SERVICE_CONNECTION, 0);
}}
};
}
private void assertOutboundJudgeCalled(final int count) { assertEquals(count, mNumOutboundJudgeCalled.getAndSet(0)); }
private final AtomicInteger mNumOutboundJudgeCalled = new AtomicInteger();
private static final String TAG = "Test";
private class TestContext extends ContextWrapper {
@CallSuper void check(final Intent intent) {
assertBaseNotCalled();
mBaseCalled = true;
mIntentFlags = intent.getFlags();
}
@Override public ComponentName startService(final Intent intent) { check(intent); return null; }
@Override public boolean bindService(final Intent intent, final ServiceConnection c, final int f) { check(intent); return false; }
@Override public void sendBroadcast(final Intent intent) { check(intent); }
@Override public void sendBroadcast(final Intent intent, final String p) { check(intent); }
@Override public void sendBroadcastAsUser(final Intent intent, final UserHandle user) { check(intent); }
@Override public void sendBroadcastAsUser(final Intent intent, final UserHandle user, final String receiverPermission) { check(intent); }
@Override public void sendStickyBroadcast(final Intent intent) { check(intent); }
@Override public void sendStickyBroadcastAsUser(final Intent intent, final UserHandle u) { check(intent); }
@Override public void sendOrderedBroadcast(final Intent intent, final String p) { check(intent); }
@Override public void sendOrderedBroadcast(final Intent intent, final String p, final BroadcastReceiver r, final Handler s, final int c, final String d, final Bundle e) { check(intent); }
@Override public void sendOrderedBroadcastAsUser(final Intent intent, final UserHandle u, final String p, final BroadcastReceiver r, final Handler s, final int c, final String d, final Bundle e) { check(intent); }
@Override public void sendStickyOrderedBroadcast(final Intent intent, final BroadcastReceiver r, final Handler s, final int c, final String d, final Bundle e) { check(intent); }
@Override public void sendStickyOrderedBroadcastAsUser(final Intent intent, final UserHandle u, final BroadcastReceiver r, final Handler s, final int c, final String d, final Bundle e) { check(intent); }
@Override public PackageManager getPackageManager() {
return new PackageManagerWrapper(InstrumentationRegistry.getTargetContext().getPackageManager()) {
@Override public ResolveInfo resolveService(final Intent intent, final int flags) {
check(intent);
return buildResolveInfo(DISALLOWED_PACKAGE, true, 7777777); // Must be consistent with the first entry from queryIntentServices().
}
@Override public List<ResolveInfo> queryIntentServices(final Intent intent, final int flags) {
check(intent);
final List<ResolveInfo> resolves = new ArrayList<>();
if (mTestingBackgroundUid) {
final ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
Assume.assumeTrue(am != null);
final List<ActivityManager.RunningServiceInfo> services = am.getRunningServices(32);
if (services != null) for (final ActivityManager.RunningServiceInfo service : services) {
if (service.pid == 0 || service.uid == android.os.Process.myUid()) continue;
resolves.add(buildResolveInfo(DISALLOWED_PACKAGE, true, 7777777)); // Simulate a background UID.
resolves.add(buildResolveInfo("non.bg.service", true, service.uid));
break;
}
}
resolves.add(buildResolveInfo(ALLOWED_PACKAGE, true, android.os.Process.myUid()));
resolves.add(buildResolveInfo(DISALLOWED_PACKAGE, true, android.os.Process.myUid()));
return resolves;
}
@Override public List<ResolveInfo> queryBroadcastReceivers(final Intent intent, final int flags) {
check(intent);
final List<ResolveInfo> resolves = new ArrayList<>();
resolves.add(buildResolveInfo(ALLOWED_PACKAGE, false, android.os.Process.myUid()));
resolves.add(buildResolveInfo(DISALLOWED_PACKAGE, false, android.os.Process.myUid()));
return resolves;
}
@Override public ProviderInfo resolveContentProvider(final String name, final int flags) {
final ProviderInfo info = super.resolveContentProvider(name, flags);
if (info != null && mTestingStoppedProvider) {
if (getPackageName().equals(info.packageName)) info.packageName += ".dummy"; // To simulate a package other than current one.
info.applicationInfo.flags |= ApplicationInfo.FLAG_STOPPED;
}
return info;
}
private ResolveInfo buildResolveInfo(final String pkg, final boolean service_or_receiver, final int uid) {
final ResolveInfo r = new ResolveInfo() { @Override public String toString() { return "ResolveInfo{test}"; } };
final ComponentInfo info = service_or_receiver ? (r.serviceInfo = new ServiceInfo()) : (r.activityInfo = new ActivityInfo());
info.packageName = pkg;
info.applicationInfo = new ApplicationInfo();
info.applicationInfo.packageName = pkg;
info.applicationInfo.uid = uid;
return r;
}
};
}
@Override public Context getApplicationContext() { return this; }
void assertBaseCalled() { assertTrue(mBaseCalled); mBaseCalled = false; }
void assertBaseNotCalled() { assertFalse(mBaseCalled); }
Runnable expectFlags(final int flags) {
return new Runnable() { @Override public void run() {
assertEquals(flags | INTENT_FLAGS, mIntentFlags);
}};
}
TestContext() { super((InstrumentationRegistry.getTargetContext())); }
boolean mTestingBackgroundUid;
boolean mTestingStoppedProvider;
private int mIntentFlags;
private boolean mBaseCalled;
final Runnable EXPECT_BASE_CALLED = new Runnable() { @Override public void run() { assertBaseCalled(); } };
}
private interface Consumer<T> { void accept(T t); }
}
| library/src/androidTest/java/com/oasisfeng/condom/CondomContextBlockingTest.java | /*
* Copyright (C) 2017 Oasis Feng. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* 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.oasisfeng.condom;
import android.Manifest.permission;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.ComponentInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.UserHandle;
import android.provider.Settings;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.test.InstrumentationRegistry;
import org.junit.Assume;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.ParametersAreNonnullByDefault;
import static android.content.Intent.FLAG_RECEIVER_REGISTERED_ONLY;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.HONEYCOMB_MR1;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static android.os.Build.VERSION_CODES.N;
import static android.os.Build.VERSION_CODES.O;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
@ParametersAreNonnullByDefault
public class CondomContextBlockingTest {
@Test public void testSelfTargeted() {
final TestContext context = new TestContext();
final CondomContext condom = CondomContext.wrap(context, TAG), dry_condom = CondomContext.wrap(context, TAG, new CondomOptions().setDryRun(true));
// Self-targeting test
final String self_pkg = condom.getPackageName();
final Intent[] self_targeted_intents = new Intent[] {
intent().setPackage(self_pkg),
intent().setComponent(new ComponentName(self_pkg, "X"))
};
with(self_targeted_intents, allBroadcastApis(condom), context.EXPECT_BASE_CALLED, context.expectFlags(0));
with(self_targeted_intents, allServiceApis(condom), context.EXPECT_BASE_CALLED, context.expectFlags(0));
with(self_targeted_intents, allBroadcastApis(dry_condom), context.EXPECT_BASE_CALLED, context.expectFlags(0));
with(self_targeted_intents, allServiceApis(dry_condom), context.EXPECT_BASE_CALLED, context.expectFlags(0));
}
@Test public void testPreventNone() {
final TestContext context = new TestContext();
final CondomOptions options = new CondomOptions().preventServiceInBackgroundPackages(false).preventBroadcastToBackgroundPackages(false);
final CondomContext condom = CondomContext.wrap(context, TAG, options), dry_condom = CondomContext.wrap(context, TAG, options.setDryRun(true));
//noinspection deprecation, intentional test for deprecated method
condom.preventWakingUpStoppedPackages(false);
//noinspection deprecation
dry_condom.preventWakingUpStoppedPackages(false);
with(ALL_SORT_OF_INTENTS, allBroadcastApis(condom), context.EXPECT_BASE_CALLED, context.expectFlags(0));
with(ALL_SORT_OF_INTENTS, allServiceApis(condom), context.EXPECT_BASE_CALLED, context.expectFlags(0));
with(ALL_SORT_OF_INTENTS, allBroadcastApis(dry_condom), context.EXPECT_BASE_CALLED, context.expectFlags(0));
with(ALL_SORT_OF_INTENTS, allServiceApis(dry_condom), context.EXPECT_BASE_CALLED, context.expectFlags(0));
}
@Test public void testPreventWakingUpStoppedPackages_IncludingDryRun() {
final Intent[] intents_with_inc_stop = ALL_SORT_OF_INTENTS.clone();
for (int i = 0; i < intents_with_inc_stop.length; i++)
intents_with_inc_stop[i] = new Intent(intents_with_inc_stop[i]).addFlags(FLAG_INCLUDE_STOPPED_PACKAGES);
final TestContext context = new TestContext();
final CondomOptions options = new CondomOptions().preventBroadcastToBackgroundPackages(false).preventServiceInBackgroundPackages(false);
final CondomContext condom = CondomContext.wrap(context, TAG, options), dry_condom = CondomContext.wrap(context, TAG, options.setDryRun(true));
with(intents_with_inc_stop, allBroadcastApis(condom), context.EXPECT_BASE_CALLED, context.expectFlags(FLAG_EXCLUDE_STOPPED_PACKAGES));
with(intents_with_inc_stop, allServiceApis(condom), context.EXPECT_BASE_CALLED, context.expectFlags(FLAG_EXCLUDE_STOPPED_PACKAGES));
with(intents_with_inc_stop, allBroadcastApis(dry_condom), context.EXPECT_BASE_CALLED, context.expectFlags(FLAG_INCLUDE_STOPPED_PACKAGES));
with(intents_with_inc_stop, allServiceApis(dry_condom), context.EXPECT_BASE_CALLED, context.expectFlags(FLAG_INCLUDE_STOPPED_PACKAGES));
}
@Test public void testPreventBroadcastToBackgroundPackages() {
final TestContext context = new TestContext();
final CondomOptions options = new CondomOptions().preventBroadcastToBackgroundPackages(true);
final CondomContext condom = CondomContext.wrap(context, TAG, options), dry_condom = CondomContext.wrap(context, TAG, options.setDryRun(true));
final int extra_flag = SDK_INT >= N ? CondomCore.FLAG_RECEIVER_EXCLUDE_BACKGROUND : FLAG_RECEIVER_REGISTERED_ONLY;
with(ALL_SORT_OF_INTENTS, allBroadcastApis(condom), context.EXPECT_BASE_CALLED, context.expectFlags(FLAG_EXCLUDE_STOPPED_PACKAGES | extra_flag));
with(ALL_SORT_OF_INTENTS, allBroadcastApis(dry_condom), context.EXPECT_BASE_CALLED, context.expectFlags(0));
}
@Test public void testPreventServiceInBackgroundPackages() {
Assume.assumeTrue(SDK_INT < O);
final TestContext context = new TestContext();
context.mTestingBackgroundUid = true;
final CondomOptions options = new CondomOptions().preventServiceInBackgroundPackages(true).preventBroadcastToBackgroundPackages(false);
final CondomContext condom = CondomContext.wrap(context, TAG, options), dry_condom = CondomContext.wrap(context, TAG, options.setDryRun(true));
List<ResolveInfo> services = condom.getPackageManager().queryIntentServices(intent(), 0);
assertEquals(3, services.size());
context.assertBaseCalled();
services = dry_condom.getPackageManager().queryIntentServices(intent(), 0);
assertEquals(4, services.size());
context.assertBaseCalled();
final ResolveInfo resolve = condom.getPackageManager().resolveService(intent(), 0);
assertEquals("non.bg.service", resolve.serviceInfo.packageName);
context.assertBaseCalled();
assertEquals(7777777, dry_condom.getPackageManager().resolveService(intent(), 0).serviceInfo.applicationInfo.uid);
context.assertBaseCalled();
}
@Test public void testContentProviderOutboundJudge() {
final TestContext context = new TestContext();
final CondomOptions options = new CondomOptions().setOutboundJudge(new OutboundJudge() { @Override public boolean shouldAllow(final OutboundType type, final @Nullable Intent intent, final String target_pkg) {
final String settings_pkg = InstrumentationRegistry.getTargetContext().getPackageManager().resolveContentProvider(Settings.System.CONTENT_URI.getAuthority(), 0).packageName;
return ! settings_pkg.equals(target_pkg);
}});
final CondomContext condom = CondomContext.wrap(context, TAG, options), dry_condom = CondomContext.wrap(context, TAG, options.setDryRun(true));
assertNull(condom.getPackageManager().resolveContentProvider(Settings.AUTHORITY, 0));
assertNotNull(dry_condom.getPackageManager().resolveContentProvider(Settings.AUTHORITY, 0));
assertNull(condom.getContentResolver().acquireContentProviderClient(Settings.System.CONTENT_URI));
assertNotNull(dry_condom.getContentResolver().acquireContentProviderClient(Settings.System.CONTENT_URI));
}
@Test public void testContentProvider() {
final TestContext context = new TestContext();
final CondomContext condom = CondomContext.wrap(context, TAG), dry_condom = CondomContext.wrap(context, TAG, new CondomOptions().setDryRun(true));
// Regular provider access
final String android_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
assertNotNull(android_id);
final String condom_android_id = Settings.Secure.getString(condom.getContentResolver(), Settings.Secure.ANDROID_ID);
assertEquals(android_id, condom_android_id);
final String dry_android_id = Settings.Secure.getString(dry_condom.getContentResolver(), Settings.Secure.ANDROID_ID);
assertEquals(android_id, dry_android_id);
context.mTestingStoppedProvider = true;
// Prevent stopped packages,
assertNull(condom.getPackageManager().resolveContentProvider(TEST_AUTHORITY, 0));
assertNotNull(dry_condom.getPackageManager().resolveContentProvider(TEST_AUTHORITY, 0));
assertNull(condom.getContentResolver().acquireContentProviderClient(TEST_CONTENT_URI));
assertNotNull(dry_condom.getContentResolver().acquireContentProviderClient(TEST_CONTENT_URI));
// Providers in system package should not be blocked.
assertNotNull(condom.getPackageManager().resolveContentProvider(Settings.AUTHORITY, 0));
assertNotNull(dry_condom.getPackageManager().resolveContentProvider(Settings.AUTHORITY, 0));
assertNotNull(condom.getContentResolver().acquireContentProviderClient(Settings.System.CONTENT_URI));
assertNotNull(dry_condom.getContentResolver().acquireContentProviderClient(Settings.System.CONTENT_URI));
context.mTestingStoppedProvider = false;
}
private static final String TEST_AUTHORITY = "com.oasisfeng.condom.test";
private static final Uri TEST_CONTENT_URI = Uri.parse("content://" + TEST_AUTHORITY + "/");
public static class TestProvider extends ContentProvider {
@Override public boolean onCreate() { return true; }
@Nullable @Override public Cursor query(@NonNull final Uri uri, @Nullable final String[] strings, @Nullable final String s, @Nullable final String[] strings1, @Nullable final String s1) { return null; }
@Nullable @Override public String getType(@NonNull final Uri uri) { return null; }
@Nullable @Override public Uri insert(@NonNull final Uri uri, @Nullable final ContentValues contentValues) { return null; }
@Override public int delete(@NonNull final Uri uri, @Nullable final String s, @Nullable final String[] strings) { return 0; }
@Override public int update(@NonNull final Uri uri, @Nullable final ContentValues contentValues, @Nullable final String s, @Nullable final String[] strings) { return 0; }
}
@Test public void testOutboundJudge() {
final TestContext context = new TestContext();
final CondomOptions options = new CondomOptions().setOutboundJudge(new OutboundJudge() {
@Override public boolean shouldAllow(final OutboundType type, final @Nullable Intent intent, final String target_pkg) {
mNumOutboundJudgeCalled.incrementAndGet();
return ! DISALLOWED_PACKAGE.equals(target_pkg);
}
});
final CondomContext condom = CondomContext.wrap(context, TAG, options), dry_condom = CondomContext.wrap(context, TAG, options.setDryRun(true));
final PackageManager pm = condom.getPackageManager(), dry_pm = dry_condom.getPackageManager();
final Runnable EXPECT_OUTBOUND_JUDGE_REFUSAL = new Runnable() { @Override public void run() {
context.assertBaseNotCalled();
assertOutboundJudgeCalled(1);
}};
final Runnable EXPECT_OUTBOUND_JUDGE_PASS = new Runnable() { @Override public void run() {
context.assertBaseCalled();
assertOutboundJudgeCalled(1);
}};
with(DISALLOWED_INTENTS, allBroadcastApis(condom), EXPECT_OUTBOUND_JUDGE_REFUSAL);
with(ALLOWED_INTENTS, allBroadcastApis(condom), EXPECT_OUTBOUND_JUDGE_PASS);
with(DISALLOWED_INTENTS, allBroadcastApis(dry_condom), EXPECT_OUTBOUND_JUDGE_PASS);
with(ALLOWED_INTENTS, allBroadcastApis(dry_condom), EXPECT_OUTBOUND_JUDGE_PASS);
assertNull(pm.resolveService(intent().setPackage(DISALLOWED_PACKAGE), 0));
context.assertBaseNotCalled();
assertOutboundJudgeCalled(1);
assertNotNull(dry_pm.resolveService(intent().setPackage(DISALLOWED_PACKAGE), 0));
context.assertBaseCalled();
assertOutboundJudgeCalled(1);
assertEquals(1, pm.queryIntentServices(intent(), 0).size());
context.assertBaseCalled();
assertOutboundJudgeCalled(2);
assertEquals(2, dry_pm.queryIntentServices(intent(), 0).size());
context.assertBaseCalled();
assertOutboundJudgeCalled(2);
assertEquals(1, pm.queryBroadcastReceivers(intent(), 0).size());
context.assertBaseCalled();
assertOutboundJudgeCalled(2);
assertEquals(2, dry_pm.queryBroadcastReceivers(intent(), 0).size());
context.assertBaseCalled();
assertOutboundJudgeCalled(2);
condom.sendBroadcast(intent());
context.assertBaseCalled();
assertOutboundJudgeCalled(0);
dry_condom.sendBroadcast(intent());
context.assertBaseCalled();
assertOutboundJudgeCalled(0);
}
private static void with(final Intent[] intents, final Consumer<Intent>[] tests, final Runnable... expectations) {
for (final Intent intent : intents)
for (final Consumer<Intent> test : tests) {
test.accept(intent);
for (final Runnable expectation : expectations) expectation.run();
}
}
private static Intent intent() { return new Intent("com.example.TEST").addFlags(INTENT_FLAGS); }
private static final UserHandle USER = SDK_INT >= JELLY_BEAN_MR1 ? android.os.Process.myUserHandle() : null;
private static final int INTENT_FLAGS = Intent.FLAG_DEBUG_LOG_RESOLUTION | Intent.FLAG_FROM_BACKGROUND; // Just random flags to verify flags preservation.
private static final ServiceConnection SERVICE_CONNECTION = new ServiceConnection() {
@Override public void onServiceConnected(final ComponentName name, final IBinder service) {}
@Override public void onServiceDisconnected(final ComponentName name) {}
};
private static final String DISALLOWED_PACKAGE = "a.b.c";
private static final String ALLOWED_PACKAGE = "x.y.z";
private static final ComponentName DISALLOWED_COMPONENT = new ComponentName(DISALLOWED_PACKAGE, "A");
private static final ComponentName ALLOWED_COMPONENT = new ComponentName(ALLOWED_PACKAGE, "A");
private static final int FLAG_EXCLUDE_STOPPED_PACKAGES = SDK_INT >= HONEYCOMB_MR1 ? Intent.FLAG_EXCLUDE_STOPPED_PACKAGES : 0;
private static final int FLAG_INCLUDE_STOPPED_PACKAGES = SDK_INT >= HONEYCOMB_MR1 ? Intent.FLAG_INCLUDE_STOPPED_PACKAGES : 0;
private static final Intent[] ALL_SORT_OF_INTENTS = new Intent[] {
intent(),
intent().setPackage(ALLOWED_PACKAGE),
intent().setPackage(DISALLOWED_PACKAGE),
intent().setComponent(ALLOWED_COMPONENT),
intent().setComponent(DISALLOWED_COMPONENT),
};
private static final Intent[] ALLOWED_INTENTS = new Intent[] {
intent().setPackage(ALLOWED_PACKAGE),
intent().setComponent(ALLOWED_COMPONENT),
};
private static final Intent[] DISALLOWED_INTENTS = new Intent[] {
intent().setPackage(DISALLOWED_PACKAGE),
intent().setComponent(DISALLOWED_COMPONENT),
};
private static Consumer<Intent>[] allBroadcastApis(final CondomContext condom) {
final List<Consumer<Intent>> tests = new ArrayList<>();
tests.add(new Consumer<Intent>() { @Override public void accept(final Intent intent) { condom.sendBroadcast(intent); }});
tests.add(new Consumer<Intent>() { @Override public void accept(final Intent intent) { condom.sendBroadcast(intent, permission.DUMP); }});
tests.add(new Consumer<Intent>() { @Override public void accept(final Intent intent) { condom.sendOrderedBroadcast(intent, permission.DUMP); }});
tests.add(new Consumer<Intent>() { @Override public void accept(final Intent intent) { condom.sendOrderedBroadcast(intent, permission.DUMP, null, null, 0, null, null); }});
tests.add(new Consumer<Intent>() { @Override public void accept(final Intent intent) { condom.sendStickyBroadcast(intent); }});
tests.add(new Consumer<Intent>() { @Override public void accept(final Intent intent) { condom.sendStickyOrderedBroadcast(intent, null, null, 0, null, null); }});
if (SDK_INT >= JELLY_BEAN_MR1) {
tests.add(new Consumer<Intent>() { @TargetApi(JELLY_BEAN_MR1) @Override public void accept(final Intent intent) { condom.sendBroadcastAsUser(intent, USER); }});
tests.add(new Consumer<Intent>() { @TargetApi(JELLY_BEAN_MR1) @Override public void accept(final Intent intent) { condom.sendBroadcastAsUser(intent, USER, null); }});
tests.add(new Consumer<Intent>() { @TargetApi(JELLY_BEAN_MR1) @Override public void accept(final Intent intent) { condom.sendStickyBroadcastAsUser(intent, USER); }});
tests.add(new Consumer<Intent>() { @TargetApi(JELLY_BEAN_MR1) @Override public void accept(final Intent intent) { condom.sendOrderedBroadcastAsUser(intent, USER, null, null, null, 0, null, null); }});
tests.add(new Consumer<Intent>() { @TargetApi(JELLY_BEAN_MR1) @Override public void accept(final Intent intent) { condom.sendStickyOrderedBroadcastAsUser(intent, USER,null, null, 0, null, null); }});
}
tests.add(new Consumer<Intent>() { @Override public void accept(final Intent intent) { condom.getPackageManager().queryBroadcastReceivers(intent, 0); }});
//noinspection unchecked
return tests.toArray(new Consumer[tests.size()]);
}
@SuppressWarnings("unchecked") private static Consumer<Intent>[] allServiceApis(final CondomContext condom) {
return new Consumer[] {
new Consumer<Intent>() { @Override public void accept(final Intent intent) {
condom.startService(intent);
}}, new Consumer<Intent>() { @Override public void accept(final Intent intent) {
condom.bindService(intent, SERVICE_CONNECTION, 0);
}}
};
}
private void assertOutboundJudgeCalled(final int count) { assertEquals(count, mNumOutboundJudgeCalled.getAndSet(0)); }
private final AtomicInteger mNumOutboundJudgeCalled = new AtomicInteger();
private static final String TAG = "Test";
private class TestContext extends ContextWrapper {
@CallSuper void check(final Intent intent) {
assertBaseNotCalled();
mBaseCalled = true;
mIntentFlags = intent.getFlags();
}
@Override public ComponentName startService(final Intent intent) { check(intent); return null; }
@Override public boolean bindService(final Intent intent, final ServiceConnection c, final int f) { check(intent); return false; }
@Override public void sendBroadcast(final Intent intent) { check(intent); }
@Override public void sendBroadcast(final Intent intent, final String p) { check(intent); }
@Override public void sendBroadcastAsUser(final Intent intent, final UserHandle user) { check(intent); }
@Override public void sendBroadcastAsUser(final Intent intent, final UserHandle user, final String receiverPermission) { check(intent); }
@Override public void sendStickyBroadcast(final Intent intent) { check(intent); }
@Override public void sendStickyBroadcastAsUser(final Intent intent, final UserHandle u) { check(intent); }
@Override public void sendOrderedBroadcast(final Intent intent, final String p) { check(intent); }
@Override public void sendOrderedBroadcast(final Intent intent, final String p, final BroadcastReceiver r, final Handler s, final int c, final String d, final Bundle e) { check(intent); }
@Override public void sendOrderedBroadcastAsUser(final Intent intent, final UserHandle u, final String p, final BroadcastReceiver r, final Handler s, final int c, final String d, final Bundle e) { check(intent); }
@Override public void sendStickyOrderedBroadcast(final Intent intent, final BroadcastReceiver r, final Handler s, final int c, final String d, final Bundle e) { check(intent); }
@Override public void sendStickyOrderedBroadcastAsUser(final Intent intent, final UserHandle u, final BroadcastReceiver r, final Handler s, final int c, final String d, final Bundle e) { check(intent); }
@Override public PackageManager getPackageManager() {
return new PackageManagerWrapper(InstrumentationRegistry.getTargetContext().getPackageManager()) {
@Override public ResolveInfo resolveService(final Intent intent, final int flags) {
check(intent);
return buildResolveInfo(DISALLOWED_PACKAGE, true, 7777777); // Must be consistent with the first entry from queryIntentServices().
}
@Override public List<ResolveInfo> queryIntentServices(final Intent intent, final int flags) {
check(intent);
final List<ResolveInfo> resolves = new ArrayList<>();
if (mTestingBackgroundUid) {
final ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
final List<ActivityManager.RunningServiceInfo> services = am.getRunningServices(32);
if (services != null) for (final ActivityManager.RunningServiceInfo service : services) {
if (service.pid == 0 || service.uid == android.os.Process.myUid()) continue;
resolves.add(buildResolveInfo(DISALLOWED_PACKAGE, true, 7777777)); // Simulate a background UID.
resolves.add(buildResolveInfo("non.bg.service", true, service.uid));
break;
}
}
resolves.add(buildResolveInfo(ALLOWED_PACKAGE, true, android.os.Process.myUid()));
resolves.add(buildResolveInfo(DISALLOWED_PACKAGE, true, android.os.Process.myUid()));
return resolves;
}
@Override public List<ResolveInfo> queryBroadcastReceivers(final Intent intent, final int flags) {
check(intent);
final List<ResolveInfo> resolves = new ArrayList<>();
resolves.add(buildResolveInfo(ALLOWED_PACKAGE, false, android.os.Process.myUid()));
resolves.add(buildResolveInfo(DISALLOWED_PACKAGE, false, android.os.Process.myUid()));
return resolves;
}
@Override public ProviderInfo resolveContentProvider(final String name, final int flags) {
final ProviderInfo info = super.resolveContentProvider(name, flags);
if (info != null && mTestingStoppedProvider) {
if (getPackageName().equals(info.packageName)) info.packageName += ".dummy"; // To simulate a package other than current one.
info.applicationInfo.flags |= ApplicationInfo.FLAG_STOPPED;
}
return info;
}
private ResolveInfo buildResolveInfo(final String pkg, final boolean service_or_receiver, final int uid) {
final ResolveInfo r = new ResolveInfo() { @Override public String toString() { return "ResolveInfo{test}"; } };
final ComponentInfo info = service_or_receiver ? (r.serviceInfo = new ServiceInfo()) : (r.activityInfo = new ActivityInfo());
info.packageName = pkg;
info.applicationInfo = new ApplicationInfo();
info.applicationInfo.packageName = pkg;
info.applicationInfo.uid = uid;
return r;
}
};
}
void assertBaseCalled() { assertTrue(mBaseCalled); mBaseCalled = false; }
void assertBaseNotCalled() { assertFalse(mBaseCalled); }
Runnable expectFlags(final int flags) {
return new Runnable() { @Override public void run() {
assertEquals(flags | INTENT_FLAGS, mIntentFlags);
}};
}
TestContext() { super((InstrumentationRegistry.getTargetContext())); }
boolean mTestingBackgroundUid;
boolean mTestingStoppedProvider;
private int mIntentFlags;
private boolean mBaseCalled;
final Runnable EXPECT_BASE_CALLED = new Runnable() { @Override public void run() { assertBaseCalled(); } };
}
private interface Consumer<T> { void accept(T t); }
}
| UPDATE: CondomContextBlockingTest with application context of CondomContext.
| library/src/androidTest/java/com/oasisfeng/condom/CondomContextBlockingTest.java | UPDATE: CondomContextBlockingTest with application context of CondomContext. |
|
Java | apache-2.0 | aa1be2e31329cc1d0c3d828ee09046f9c9514a4e | 0 | nssales/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,DevStreet/FinanceAnalytics,nssales/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,nssales/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,DevStreet/FinanceAnalytics,jeorme/OG-Platform,codeaudit/OG-Platform | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.livedata.server;
import static org.testng.AssertJUnit.assertEquals;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.opengamma.id.ExternalScheme;
/**
* Test.
*/
@Test(groups = "unit")
public class ReconnectManagerTest {
@Test
public void reconnection() throws Exception {
MockLiveDataServer server = new MockLiveDataServer(ExternalScheme.of("BLOOMBERG_BUID"));
ReconnectManager manager = new ReconnectManager(server, 20);
try {
server.subscribe("foo");
Assert.fail("Not connected yet");
} catch (RuntimeException e) {
// ok
}
manager.start();
assertEquals(0, server.getNumConnections());
server.connect();
assertEquals(1, server.getNumConnections());
server.subscribe("foo");
assertEquals(1, server.getActualSubscriptions().size());
Thread.sleep(50); // shouldn't reconnect
assertEquals(1, server.getNumConnections());
assertEquals(0, server.getNumDisconnections());
manager.stop();
server.disconnect();
assertEquals(1, server.getNumDisconnections());
assertEquals(1, server.getNumConnections());
Thread.sleep(1000);
manager.start(); // should reconnect and reestablish subscriptions
Thread.sleep(1000);
assertEquals(1, server.getNumDisconnections());
assertEquals(2, server.getNumConnections());
assertEquals(2, server.getActualSubscriptions().size());
}
}
| projects/OG-LiveData/tests/unit/com/opengamma/livedata/server/ReconnectManagerTest.java | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.livedata.server;
import static org.testng.AssertJUnit.assertEquals;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.opengamma.id.ExternalScheme;
/**
* Test.
*/
@Test(groups = "unit")
public class ReconnectManagerTest {
@Test
public void reconnection() throws Exception {
MockLiveDataServer server = new MockLiveDataServer(ExternalScheme.of("BLOOMBERG_BUID"));
ReconnectManager manager = new ReconnectManager(server, 20);
try {
server.subscribe("foo");
Assert.fail("Not connected yet");
} catch (RuntimeException e) {
// ok
}
manager.start();
assertEquals(0, server.getNumConnections());
server.connect();
assertEquals(1, server.getNumConnections());
server.subscribe("foo");
assertEquals(1, server.getActualSubscriptions().size());
Thread.sleep(50); // shouldn't reconnect
assertEquals(1, server.getNumConnections());
assertEquals(0, server.getNumDisconnections());
manager.stop();
server.disconnect();
assertEquals(1, server.getNumDisconnections());
assertEquals(1, server.getNumConnections());
manager.start();
Thread.sleep(50); // should reconnect and reestablish subscriptions
assertEquals(1, server.getNumDisconnections());
assertEquals(2, server.getNumConnections());
assertEquals(2, server.getActualSubscriptions().size());
}
}
| Harden ReconnectManager test
| projects/OG-LiveData/tests/unit/com/opengamma/livedata/server/ReconnectManagerTest.java | Harden ReconnectManager test |
|
Java | apache-2.0 | 92400b9bc351e2322a67495148bc33838ef377c6 | 0 | quadrama/DramaNLP,quadrama/DramaNLP,quadrama/DramaNLP | package de.unistuttgart.quadrama.io.tei;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.collection.CollectionException;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.util.CasUtil;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.cas.FSArray;
import org.apache.uima.jcas.cas.StringArray;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import de.unistuttgart.ims.drama.api.Act;
import de.unistuttgart.ims.drama.api.ActHeading;
import de.unistuttgart.ims.drama.api.Author;
import de.unistuttgart.ims.drama.api.CastFigure;
import de.unistuttgart.ims.drama.api.DiscourseEntity;
import de.unistuttgart.ims.drama.api.Drama;
import de.unistuttgart.ims.drama.api.DramatisPersonae;
import de.unistuttgart.ims.drama.api.Figure;
import de.unistuttgart.ims.drama.api.FrontMatter;
import de.unistuttgart.ims.drama.api.MainMatter;
import de.unistuttgart.ims.drama.api.Mention;
import de.unistuttgart.ims.drama.api.Scene;
import de.unistuttgart.ims.drama.api.SceneHeading;
import de.unistuttgart.ims.drama.api.Speaker;
import de.unistuttgart.ims.drama.api.Speech;
import de.unistuttgart.ims.drama.api.StageDirection;
import de.unistuttgart.ims.drama.api.Translator;
import de.unistuttgart.ims.drama.api.Utterance;
import de.unistuttgart.ims.uima.io.xml.ArrayUtil;
import de.unistuttgart.ims.uima.io.xml.GenericXmlReader;
import de.unistuttgart.ims.uimautil.AnnotationUtil;
import de.unistuttgart.quadrama.io.core.AbstractDramaUrlReader;
public class QuaDramAReader extends AbstractDramaUrlReader {
public static final String PARAM_STRICT = "strict";
public static final String PARAM_TEI_COMPAT = "TEI compatibility";
@ConfigurationParameter(name = PARAM_STRICT, mandatory = false, defaultValue = "false")
boolean strict = false;
@ConfigurationParameter(name = PARAM_TEI_COMPAT, mandatory = false, defaultValue = "false")
boolean teiCompatibility = false;
@Override
public void getNext(final JCas jcas, InputStream file, Drama drama) throws IOException, CollectionException {
Map<String, Integer> entityIds = new HashMap<String, Integer>();
entityIds.put("__dummy__", -1);
GenericXmlReader<Drama> gxr = new GenericXmlReader<Drama>(Drama.class);
gxr.setTextRootSelector(teiCompatibility ? null : "TEI > text");
gxr.setPreserveWhitespace(teiCompatibility);
// title
gxr.addGlobalRule("fileDesc > titleStmt > title:first-child", (d, e) -> d.setDocumentTitle(e.text()));
// id
gxr.addGlobalRule("idno[type=QUADRAMA-ID]", (d, e) -> d.setDocumentId(e.text()));
// author
gxr.addGlobalRule("fileDesc > titleStmt > author", Author.class, (author, e) -> {
author.setName(e.text());
if (e.hasAttr("key"))
author.setPnd(e.attr("key").replace("pnd:", ""));
});
// translator
gxr.addGlobalRule("sourceDesc editor[role=translator]", Translator.class, (transl, e) -> {
transl.setName(e.text());
if (e.hasAttr("key"))
transl.setPnd(e.attr("key").replace("pnd:", ""));
});
// date printed
gxr.addGlobalRule("date[type=print][when]", (d, e) -> d.setDatePrinted(getYear(e.attr("when"))));
// date written
gxr.addGlobalRule("date[type=written][when]", (d, e) -> d.setDateWritten(getYear(e.attr("when"))));
// date premiere
gxr.addGlobalRule("date[type=premiere][when]", (d, e) -> d.setDatePremiere(getYear(e.attr("when"))));
gxr.addRule("front", FrontMatter.class);
gxr.addRule("body", MainMatter.class);
// Segmentation
gxr.addRule("div[type=prologue]", Act.class, (a, e) -> a.setRegular(false));
gxr.addRule("div[type=act]", Act.class, (a, e) -> a.setRegular(true));
gxr.addRule("div[type=act] > div > desc > title", ActHeading.class);
gxr.addRule("div[type=act] > div > head", ActHeading.class);
gxr.addRule("div[type=scene]", Scene.class, (a, e) -> a.setRegular(true));
gxr.addRule("div[type=scene] > div > desc > title", SceneHeading.class);
// Dramatis Personae
gxr.addRule("body castList castItem", Figure.class);
gxr.addRule("div[type=Dramatis_Personae]", DramatisPersonae.class);
Map<String, String> xmlAlias = new HashMap<String, String>();
gxr.addGlobalRule("particDesc > listPerson > person", CastFigure.class, (cf, e) -> {
Set<String> nameList = new HashSet<String>();
Set<String> xmlIdList = new HashSet<String>();
if (e.hasAttr("xml:id"))
xmlIdList.add(e.attr("xml:id"));
if (e.hasAttr("sex"))
cf.setGender(e.attr("sex"));
if (e.hasAttr("age"))
cf.setAge(e.attr("age"));
// gather names
Elements nameElements = e.select("persName");
for (int j = 0; j < nameElements.size(); j++) {
nameList.add(nameElements.get(j).text());
if (nameElements.get(j).hasAttr("xml:id")) {
xmlIdList.add(nameElements.get(j).attr("xml:id"));
xmlAlias.put(nameElements.get(j).attr("xml:id"), e.attr("xml:id"));
}
}
for (TextNode tn : e.textNodes()) {
if (tn.text().trim().length() > 0)
nameList.add(tn.text().trim());
}
cf.setXmlId(ArrayUtil.toStringArray(jcas, xmlIdList));
cf.setNames(ArrayUtil.toStringArray(jcas, nameList));
cf.setDisplayName(e.attr("xml:id"));
if (!entityIds.containsKey(ArrayUtil.toStringArray(jcas, xmlIdList).get(0))) {
entityIds.put(ArrayUtil.toStringArray(jcas, xmlIdList).get(0), Collections.max(entityIds.values()) + 1);
}
cf.setId(entityIds.get(ArrayUtil.toStringArray(jcas, xmlIdList).get(0)));
});
gxr.addRule("speaker", Speaker.class);
gxr.addRule("stage", StageDirection.class);
gxr.addRule("l > hi", StageDirection.class);
gxr.addRule("p > hi", StageDirection.class);
gxr.addRule("ab > hi", StageDirection.class);
gxr.addRule("l", Speech.class);
gxr.addRule("p", Speech.class);
gxr.addRule("ab", Speech.class);
gxr.addRule("sp", Utterance.class, (u, e) -> {
Collection<Speaker> speakers = JCasUtil.selectCovered(Speaker.class, u);
for (Speaker sp : speakers) {
String[] whos = e.attr("who").split(" ");
sp.setXmlId(new StringArray(jcas, whos.length));
sp.setCastFigure(new FSArray(jcas, whos.length));
for (int i = 0; i < whos.length; i++) {
String xmlid = whos[i].substring(1);
sp.setXmlId(i, xmlid);
if (xmlAlias.containsKey(xmlid))
xmlid = xmlAlias.get(xmlid);
if (gxr.exists(xmlid)) {
sp.setCastFigure(i, (CastFigure) gxr.getAnnotation(xmlid).getValue());
u.setCastFigure((CastFigure) gxr.getAnnotation(xmlid).getValue());
}
}
}
});
gxr.addRule("text *[xml:id]", DiscourseEntity.class, (de, e) -> {
de.setDisplayName(e.attr("xml:id"));
String[] splitted = null;
splitted = e.attr("xml:id").split(" ");
de.setXmlId(ArrayUtil.toStringArray(jcas, splitted));
for (int i = 0; i < splitted.length; i++) {
if (!entityIds.containsKey(splitted[i])) {
entityIds.put(splitted[i], Collections.max(entityIds.values()) + 1);
}
de.setId(entityIds.get(splitted[i]));
}
});
Map<String, DiscourseEntity> fallbackEntities = new HashMap<String, DiscourseEntity>();
gxr.addRule("rs", Mention.class, (m, e) -> {
if (e.hasAttr("ref") || e.hasAttr("xml:id")) {
String[] splitted = null;
if (e.hasAttr("ref")) {
splitted = e.attr("ref").split(" ");
String[] temp = new String[splitted.length];
for (int i = 0; i < splitted.length; i++) {
temp[i] = splitted[i].substring(1);
}
splitted = temp;
} else if (e.hasAttr("xml:id")) {
splitted = e.attr("xml:id").split(" ");
}
if (e.hasAttr("func")) {
if (e.attr("func").equals("and")) {
// default
} else if (e.attr("func").equals("or")) {
splitted = getRandomEntity(splitted);
} else {
// Should be handled by XMLSchema
}
}
// gather names
Set<String> nameList = new HashSet<String>();
for (TextNode tn : e.textNodes()) {
if (tn.text().trim().length() > 0)
nameList.add(tn.text().trim());
}
DiscourseEntity de = null;
if (splitted.length > 1) {
if (fallbackEntities.containsKey(String.join("_", splitted))) {
de = fallbackEntities.get(String.join("_", splitted));
} else {
de = m.getCAS().createFS(CasUtil.getType(m.getCAS(), DiscourseEntity.class));
de.addToIndexes();
String displayName = String.join("_", splitted);
de.setDisplayName(displayName);
de.setXmlId(ArrayUtil.toStringArray(jcas, splitted));
if (!entityIds.containsKey(displayName)) {
entityIds.put(displayName, Collections.max(entityIds.values()) + 1);
}
de.setId(entityIds.get(displayName));
FSArray arr = new FSArray(jcas, splitted.length);
DiscourseEntity deMember = null;
for (int i = 0; i < splitted.length; i++) {
if (gxr.exists(splitted[i])) {
FeatureStructure fs = gxr.getAnnotation(splitted[i]).getValue();
if (fs instanceof DiscourseEntity) {
deMember = (DiscourseEntity) fs;
arr.set(i, deMember);
}
} else {
deMember = m.getCAS().createFS(CasUtil.getType(m.getCAS(), DiscourseEntity.class));
deMember.addToIndexes();
String displayNameMember = splitted[i];
deMember.setDisplayName(displayNameMember);
deMember.setXmlId(ArrayUtil.toStringArray(jcas, splitted[i]));
if (!entityIds.containsKey(displayNameMember)) {
entityIds.put(displayNameMember, Collections.max(entityIds.values()) + 1);
}
deMember.setId(entityIds.get(displayNameMember));
arr.set(i, deMember);
}
}
de.setEntityGroup(arr);
fallbackEntities.put(displayName, de);
}
m.setSurfaceString(ArrayUtil.toStringArray(jcas, m.getCoveredText().split(" ")));
m.setEntity(de);
} else {
if (gxr.exists(splitted[0])) {
FeatureStructure fs = gxr.getAnnotation(splitted[0]).getValue();
if (fs instanceof DiscourseEntity)
de = (DiscourseEntity) fs;
}
if (fallbackEntities.containsKey(splitted[0]))
de = fallbackEntities.get(splitted[0]);
if (de == null) {
de = m.getCAS().createFS(CasUtil.getType(m.getCAS(), DiscourseEntity.class));
de.addToIndexes();
de.setDisplayName(splitted[0]);
de.setXmlId(ArrayUtil.toStringArray(jcas, splitted));
if (!entityIds.containsKey(splitted[0])) {
entityIds.put(splitted[0], Collections.max(entityIds.values()) + 1);
}
de.setId(entityIds.get(splitted[0]));
fallbackEntities.put(splitted[0], de);
}
m.setSurfaceString(ArrayUtil.toStringArray(jcas, m.getCoveredText().split(" ")));
m.setEntity(de);
}
}
});
gxr.read(jcas, file);
try {
AnnotationUtil.trim(new ArrayList<Figure>(JCasUtil.select(jcas, Figure.class)));
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
AnnotationUtil.trim(new ArrayList<Speech>(JCasUtil.select(jcas, Speech.class)));
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
AnnotationUtil.trim(new ArrayList<Speaker>(JCasUtil.select(jcas, Speaker.class)));
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
AnnotationUtil.trim(new ArrayList<Utterance>(JCasUtil.select(jcas, Utterance.class)));
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
AnnotationUtil.trim(new ArrayList<Scene>(JCasUtil.select(jcas, Scene.class)));
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
AnnotationUtil.trim(new ArrayList<Act>(JCasUtil.select(jcas, Act.class)));
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
AnnotationUtil.trim(new ArrayList<StageDirection>(JCasUtil.select(jcas, StageDirection.class)));
} catch (ArrayIndexOutOfBoundsException e) {
}
AnnotationUtil.trim(new ArrayList<Mention>(JCasUtil.select(jcas, Mention.class)));
}
int getYear(String s) {
Pattern p = Pattern.compile("\\d\\d\\d\\d");
Matcher m = p.matcher(s);
if (m.find()) {
return Integer.valueOf(m.group());
} else
return 0;
}
public static String[] getRandomEntity(String[] array) {
int seed = 42;
String[] newArray = new String[1];
int rnd = new Random(seed).nextInt(array.length);
newArray[0] = array[rnd];
return newArray;
}
}
| de.unistuttgart.ims.drama.io.core/src/main/java/de/unistuttgart/quadrama/io/tei/QuaDramAReader.java | package de.unistuttgart.quadrama.io.tei;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.collection.CollectionException;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.util.CasUtil;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.cas.FSArray;
import org.apache.uima.jcas.cas.StringArray;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import de.unistuttgart.ims.drama.api.Act;
import de.unistuttgart.ims.drama.api.ActHeading;
import de.unistuttgart.ims.drama.api.Author;
import de.unistuttgart.ims.drama.api.CastFigure;
import de.unistuttgart.ims.drama.api.DiscourseEntity;
import de.unistuttgart.ims.drama.api.Drama;
import de.unistuttgart.ims.drama.api.DramatisPersonae;
import de.unistuttgart.ims.drama.api.Figure;
import de.unistuttgart.ims.drama.api.FrontMatter;
import de.unistuttgart.ims.drama.api.MainMatter;
import de.unistuttgart.ims.drama.api.Mention;
import de.unistuttgart.ims.drama.api.Scene;
import de.unistuttgart.ims.drama.api.SceneHeading;
import de.unistuttgart.ims.drama.api.Speaker;
import de.unistuttgart.ims.drama.api.Speech;
import de.unistuttgart.ims.drama.api.StageDirection;
import de.unistuttgart.ims.drama.api.Translator;
import de.unistuttgart.ims.drama.api.Utterance;
import de.unistuttgart.ims.uima.io.xml.ArrayUtil;
import de.unistuttgart.ims.uima.io.xml.GenericXmlReader;
import de.unistuttgart.ims.uimautil.AnnotationUtil;
import de.unistuttgart.quadrama.io.core.AbstractDramaUrlReader;
public class QuaDramAReader extends AbstractDramaUrlReader {
public static final String PARAM_STRICT = "strict";
public static final String PARAM_TEI_COMPAT = "TEI compatibility";
@ConfigurationParameter(name = PARAM_STRICT, mandatory = false, defaultValue = "false")
boolean strict = false;
@ConfigurationParameter(name = PARAM_TEI_COMPAT, mandatory = false, defaultValue = "false")
boolean teiCompatibility = false;
@Override
public void getNext(final JCas jcas, InputStream file, Drama drama) throws IOException, CollectionException {
Map<String, Integer> entityIds = new HashMap<String, Integer>();
entityIds.put("__dummy__", -1);
GenericXmlReader<Drama> gxr = new GenericXmlReader<Drama>(Drama.class);
gxr.setTextRootSelector(teiCompatibility ? null : "TEI > text");
gxr.setPreserveWhitespace(teiCompatibility);
// title
// gxr.addAction("titleStmt > title:first-child", Drama.class, (d, e) ->
// d.setDocumentTitle(e.text()));
gxr.addGlobalRule("fileDesc > titleStmt > title:first-child", (d, e) -> d.setDocumentTitle(e.text()));
// id
gxr.addGlobalRule("idno[type=QUADRAMA-ID]", (d, e) -> d.setDocumentId(e.text()));
// author
gxr.addGlobalRule("fileDesc > titleStmt > author", Author.class, (author, e) -> {
author.setName(e.text());
if (e.hasAttr("key"))
author.setPnd(e.attr("key").replace("pnd:", ""));
});
// translator
gxr.addGlobalRule("sourceDesc > editor[role=translator]", Translator.class, (transl, e) -> {
transl.setName(e.text());
if (e.hasAttr("key"))
transl.setPnd(e.attr("key").replace("pnd:", ""));
});
// date printed
gxr.addGlobalRule("date[type=print][when]", (d, e) -> d.setDatePrinted(getYear(e.attr("when"))));
// date written
gxr.addGlobalRule("date[type=written][when]", (d, e) -> d.setDateWritten(getYear(e.attr("when"))));
// date premiere
gxr.addGlobalRule("date[type=premiere][when]", (d, e) -> d.setDatePremiere(getYear(e.attr("when"))));
gxr.addRule("front", FrontMatter.class);
gxr.addRule("body", MainMatter.class);
// Segmentation
gxr.addRule("div[type=prologue]", Act.class, (a, e) -> a.setRegular(false));
gxr.addRule("div[type=act]", Act.class, (a, e) -> a.setRegular(true));
gxr.addRule("div[type=act] > div > desc > title", ActHeading.class);
gxr.addRule("div[type=act] > div > head", ActHeading.class);
gxr.addRule("div[type=scene]", Scene.class, (a, e) -> a.setRegular(true));
gxr.addRule("div[type=scene] > div > desc > title", SceneHeading.class);
// Dramatis Personae
gxr.addRule("body castList castItem", Figure.class);
gxr.addRule("div[type=Dramatis_Personae]", DramatisPersonae.class);
Map<String, String> xmlAlias = new HashMap<String, String>();
gxr.addGlobalRule("particDesc > listPerson > person", CastFigure.class, (cf, e) -> {
Set<String> nameList = new HashSet<String>();
Set<String> xmlIdList = new HashSet<String>();
if (e.hasAttr("xml:id"))
xmlIdList.add(e.attr("xml:id"));
if (e.hasAttr("sex"))
cf.setGender(e.attr("sex"));
if (e.hasAttr("age"))
cf.setAge(e.attr("age"));
// gather names
Elements nameElements = e.select("persName");
for (int j = 0; j < nameElements.size(); j++) {
nameList.add(nameElements.get(j).text());
if (nameElements.get(j).hasAttr("xml:id")) {
xmlIdList.add(nameElements.get(j).attr("xml:id"));
xmlAlias.put(nameElements.get(j).attr("xml:id"), e.attr("xml:id"));
}
}
for (TextNode tn : e.textNodes()) {
if (tn.text().trim().length() > 0)
nameList.add(tn.text().trim());
}
cf.setXmlId(ArrayUtil.toStringArray(jcas, xmlIdList));
cf.setNames(ArrayUtil.toStringArray(jcas, nameList));
cf.setDisplayName(e.attr("xml:id"));
if (!entityIds.containsKey(ArrayUtil.toStringArray(jcas, xmlIdList).get(0))) {
entityIds.put(ArrayUtil.toStringArray(jcas, xmlIdList).get(0), Collections.max(entityIds.values()) + 1);
}
cf.setId(entityIds.get(ArrayUtil.toStringArray(jcas, xmlIdList).get(0)));
});
gxr.addRule("speaker", Speaker.class);
gxr.addRule("stage", StageDirection.class);
gxr.addRule("l > hi", StageDirection.class);
gxr.addRule("p > hi", StageDirection.class);
gxr.addRule("ab > hi", StageDirection.class);
gxr.addRule("l", Speech.class);
gxr.addRule("p", Speech.class);
gxr.addRule("ab", Speech.class);
gxr.addRule("sp", Utterance.class, (u, e) -> {
Collection<Speaker> speakers = JCasUtil.selectCovered(Speaker.class, u);
for (Speaker sp : speakers) {
String[] whos = e.attr("who").split(" ");
sp.setXmlId(new StringArray(jcas, whos.length));
sp.setCastFigure(new FSArray(jcas, whos.length));
for (int i = 0; i < whos.length; i++) {
String xmlid = whos[i].substring(1);
sp.setXmlId(i, xmlid);
if (xmlAlias.containsKey(xmlid))
xmlid = xmlAlias.get(xmlid);
if (gxr.exists(xmlid)) {
sp.setCastFigure(i, (CastFigure) gxr.getAnnotation(xmlid).getValue());
u.setCastFigure((CastFigure) gxr.getAnnotation(xmlid).getValue());
}
}
}
});
gxr.addRule("text *[xml:id]", DiscourseEntity.class, (de, e) -> {
de.setDisplayName(e.attr("xml:id"));
String[] splitted = null;
splitted = e.attr("xml:id").split(" ");
de.setXmlId(ArrayUtil.toStringArray(jcas, splitted));
for (int i = 0; i < splitted.length; i++) {
if (!entityIds.containsKey(splitted[i])) {
entityIds.put(splitted[i], Collections.max(entityIds.values()) + 1);
}
de.setId(entityIds.get(splitted[i]));
}
});
Map<String, DiscourseEntity> fallbackEntities = new HashMap<String, DiscourseEntity>();
gxr.addRule("rs", Mention.class, (m, e) -> {
if (e.hasAttr("ref") || e.hasAttr("xml:id")) {
String[] splitted = null;
if (e.hasAttr("ref")) {
splitted = e.attr("ref").split(" ");
String[] temp = new String[splitted.length];
for (int i = 0; i < splitted.length; i++) {
temp[i] = splitted[i].substring(1);
}
splitted = temp;
} else if (e.hasAttr("xml:id")) {
splitted = e.attr("xml:id").split(" ");
}
if (e.hasAttr("func")) {
if (e.attr("func").equals("and")) {
// default
} else if (e.attr("func").equals("or")) {
splitted = getRandomEntity(splitted);
} else {
// Should be handled by XMLSchema
}
}
// gather names
Set<String> nameList = new HashSet<String>();
for (TextNode tn : e.textNodes()) {
if (tn.text().trim().length() > 0)
nameList.add(tn.text().trim());
}
DiscourseEntity de = null;
if (splitted.length > 1) {
if (fallbackEntities.containsKey(String.join("_", splitted))) {
de = fallbackEntities.get(String.join("_", splitted));
} else {
de = m.getCAS().createFS(CasUtil.getType(m.getCAS(), DiscourseEntity.class));
de.addToIndexes();
String displayName = String.join("_", splitted);
de.setDisplayName(displayName);
de.setXmlId(ArrayUtil.toStringArray(jcas, splitted));
if (!entityIds.containsKey(displayName)) {
entityIds.put(displayName, Collections.max(entityIds.values()) + 1);
}
de.setId(entityIds.get(displayName));
FSArray arr = new FSArray(jcas, splitted.length);
DiscourseEntity deMember = null;
for (int i = 0; i < splitted.length; i++) {
if (gxr.exists(splitted[i])) {
FeatureStructure fs = gxr.getAnnotation(splitted[i]).getValue();
if (fs instanceof DiscourseEntity) {
deMember = (DiscourseEntity) fs;
arr.set(i, deMember);
}
} else {
deMember = m.getCAS().createFS(CasUtil.getType(m.getCAS(), DiscourseEntity.class));
deMember.addToIndexes();
String displayNameMember = splitted[i];
deMember.setDisplayName(displayNameMember);
deMember.setXmlId(ArrayUtil.toStringArray(jcas, splitted[i]));
if (!entityIds.containsKey(displayNameMember)) {
entityIds.put(displayNameMember, Collections.max(entityIds.values()) + 1);
}
deMember.setId(entityIds.get(displayNameMember));
arr.set(i, deMember);
}
}
de.setEntityGroup(arr);
fallbackEntities.put(displayName, de);
}
m.setSurfaceString(ArrayUtil.toStringArray(jcas, m.getCoveredText().split(" ")));
m.setEntity(de);
} else {
if (gxr.exists(splitted[0])) {
FeatureStructure fs = gxr.getAnnotation(splitted[0]).getValue();
if (fs instanceof DiscourseEntity)
de = (DiscourseEntity) fs;
}
if (fallbackEntities.containsKey(splitted[0]))
de = fallbackEntities.get(splitted[0]);
if (de == null) {
de = m.getCAS().createFS(CasUtil.getType(m.getCAS(), DiscourseEntity.class));
de.addToIndexes();
de.setDisplayName(splitted[0]);
de.setXmlId(ArrayUtil.toStringArray(jcas, splitted));
if (!entityIds.containsKey(splitted[0])) {
entityIds.put(splitted[0], Collections.max(entityIds.values()) + 1);
}
de.setId(entityIds.get(splitted[0]));
fallbackEntities.put(splitted[0], de);
}
m.setSurfaceString(ArrayUtil.toStringArray(jcas, m.getCoveredText().split(" ")));
m.setEntity(de);
}
}
});
gxr.read(jcas, file);
try {
AnnotationUtil.trim(new ArrayList<Figure>(JCasUtil.select(jcas, Figure.class)));
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
AnnotationUtil.trim(new ArrayList<Speech>(JCasUtil.select(jcas, Speech.class)));
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
AnnotationUtil.trim(new ArrayList<Speaker>(JCasUtil.select(jcas, Speaker.class)));
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
AnnotationUtil.trim(new ArrayList<Utterance>(JCasUtil.select(jcas, Utterance.class)));
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
AnnotationUtil.trim(new ArrayList<Scene>(JCasUtil.select(jcas, Scene.class)));
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
AnnotationUtil.trim(new ArrayList<Act>(JCasUtil.select(jcas, Act.class)));
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
AnnotationUtil.trim(new ArrayList<StageDirection>(JCasUtil.select(jcas, StageDirection.class)));
} catch (ArrayIndexOutOfBoundsException e) {
}
AnnotationUtil.trim(new ArrayList<Mention>(JCasUtil.select(jcas, Mention.class)));
}
int getYear(String s) {
Pattern p = Pattern.compile("\\d\\d\\d\\d");
Matcher m = p.matcher(s);
if (m.find()) {
return Integer.valueOf(m.group());
} else
return 0;
}
public static String[] getRandomEntity(String[] array) {
int seed = 42;
String[] newArray = new String[1];
int rnd = new Random(seed).nextInt(array.length);
newArray[0] = array[rnd];
return newArray;
}
}
| Fix extraction of translator
| de.unistuttgart.ims.drama.io.core/src/main/java/de/unistuttgart/quadrama/io/tei/QuaDramAReader.java | Fix extraction of translator |
|
Java | apache-2.0 | 8169f6d480c7b28114f8835f855b13ab70319dba | 0 | gradle/gradle,gstevey/gradle,gradle/gradle,lsmaira/gradle,blindpirate/gradle,lsmaira/gradle,robinverduijn/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,robinverduijn/gradle,lsmaira/gradle,lsmaira/gradle,gstevey/gradle,robinverduijn/gradle,gradle/gradle,gstevey/gradle,lsmaira/gradle,robinverduijn/gradle,robinverduijn/gradle,gstevey/gradle,gstevey/gradle,blindpirate/gradle,lsmaira/gradle,blindpirate/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,lsmaira/gradle,lsmaira/gradle,blindpirate/gradle,robinverduijn/gradle,blindpirate/gradle,lsmaira/gradle,lsmaira/gradle,gradle/gradle,robinverduijn/gradle,gradle/gradle,gstevey/gradle,gradle/gradle,gstevey/gradle,gstevey/gradle,robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle | subprojects/tooling-api/src/main/java/org/gradle/tooling/model/eclipse/EclipseTask.java | /*
* Copyright 2011 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 org.gradle.tooling.model.eclipse;
import org.gradle.tooling.model.Task;
/**
* Deprecated because Gradle tasks are not associated with Eclipse projects.
*
* @deprecated Use {@link EclipseProject#getGradleProject()} to determine the associated Gradle project for an Eclipse project,
* then use {@link org.gradle.tooling.model.GradleProject#getTasks()} to determine the tasks for the Gradle project.
*/
@Deprecated
public interface EclipseTask extends Task {
/**
* {@inheritDoc}
*/
EclipseProject getProject();
}
| Removed deprecated and unused EclipseTask tooling api model.
| subprojects/tooling-api/src/main/java/org/gradle/tooling/model/eclipse/EclipseTask.java | Removed deprecated and unused EclipseTask tooling api model. |
||
Java | apache-2.0 | 9e23fe5929e667fa170496586328ac10fe5d970c | 0 | RobotPajamas/Blueteeth,RobotPajamas/Blueteeth,RobotPajamas/Blueteeth,RobotPajamas/Blueteeth | blueteeth/src/main/kotlin/com/robotpajamas/blueteeth/BlueteethResponse.java | package com.robotpajamas.blueteeth;
// TODO: Fill this out from https://android.googlesource.com/platform/external/bluetooth/bluedroid/+/android-4.3_r1.1/stack/include/gatt_api.h
// TODO: Expose underlying GATT errors
public enum BlueteethResponse {
NO_ERROR,
NOT_CONNECTED,
BUSY,
ERROR
}
| Removed another unused file
| blueteeth/src/main/kotlin/com/robotpajamas/blueteeth/BlueteethResponse.java | Removed another unused file |
||
Java | apache-2.0 | 2a597d9aae975a810cf911a69e88946740c477f9 | 0 | brianchen2012/syncope,brianchen2012/syncope,brianchen2012/syncope | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.syncope.core.persistence.dao.impl;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import javax.persistence.Query;
import javax.persistence.TemporalType;
import javax.validation.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.syncope.client.search.AttributeCond;
import org.syncope.client.search.SyncopeUserCond;
import org.syncope.client.search.MembershipCond;
import org.syncope.client.search.NodeCond;
import org.syncope.client.search.ResourceCond;
import org.syncope.core.persistence.beans.user.SyncopeUser;
import org.syncope.core.persistence.beans.user.UAttrValue;
import org.syncope.core.persistence.beans.user.USchema;
import org.syncope.core.persistence.dao.SchemaDAO;
import org.syncope.core.persistence.dao.UserDAO;
import org.syncope.core.persistence.dao.UserSearchDAO;
import org.syncope.types.SchemaType;
@Repository
public class UserSearchDAOImpl extends AbstractDAOImpl implements UserSearchDAO {
static final private String EMPTY_ATTR_QUERY = "SELECT user_id FROM user_search_attr WHERE 1=2";
@Autowired
private UserDAO userDAO;
@Autowired
private SchemaDAO schemaDAO;
public UserSearchDAOImpl() {
super();
}
private String getAdminRolesFilter(final Set<Long> adminRoles) {
final StringBuilder adminRolesFilter = new StringBuilder();
if (adminRoles == null || adminRoles.isEmpty()) {
adminRolesFilter.append("SELECT syncopeUser_id AS user_id ").append("FROM Membership");
} else {
adminRolesFilter.append("SELECT syncopeUser_id AS user_id ").append("FROM Membership M1 ").append(
"WHERE syncopeRole_id IN (");
adminRolesFilter.append("SELECT syncopeRole_id ").append("FROM Membership M2 ").append(
"WHERE M2.syncopeUser_id=M1.syncopeUser_id ").append("AND syncopeRole_id NOT IN (");
adminRolesFilter.append("SELECT id AS syncopeRole_id FROM SyncopeRole");
boolean firstRole = true;
for (Long adminRoleId : adminRoles) {
if (firstRole) {
adminRolesFilter.append(" WHERE");
firstRole = false;
} else {
adminRolesFilter.append(" OR");
}
adminRolesFilter.append(" id=").append(adminRoleId);
}
adminRolesFilter.append("))");
}
return adminRolesFilter.toString();
}
@Override
public int count(final Set<Long> adminRoles, final NodeCond searchCondition) {
List<Object> parameters = Collections.synchronizedList(new ArrayList<Object>());
// 1. get the query string from the search condition
StringBuilder queryString = getQuery(searchCondition, parameters);
// 2. take into account administrative roles
queryString.insert(0, "SELECT u.user_id FROM (");
queryString.append(") u WHERE user_id NOT IN (");
queryString.append(getAdminRolesFilter(adminRoles)).append(")");
// 3. prepare the COUNT query
queryString.insert(0, "SELECT COUNT(user_id) FROM (");
queryString.append(") count_user_id");
Query countQuery = entityManager.createNativeQuery(queryString.toString());
fillWithParameters(countQuery, parameters);
LOG.debug("Native count query\n{}\nwith parameters\n{}", queryString.toString(), parameters);
int result = ((Number) countQuery.getSingleResult()).intValue();
LOG.debug("Native count query result: {}", result);
return result;
}
@Override
public List<SyncopeUser> search(final NodeCond searchCondition) {
return search(null, searchCondition, -1, -1);
}
@Override
public List<SyncopeUser> search(final Set<Long> adminRoles, final NodeCond searchCondition) {
return search(adminRoles, searchCondition, -1, -1);
}
@Override
public List<SyncopeUser> search(final Set<Long> adminRoles, final NodeCond searchCondition, final int page,
final int itemsPerPage) {
List<SyncopeUser> result = Collections.EMPTY_LIST;
LOG.debug("Search condition:\n{}", searchCondition);
if (!searchCondition.checkValidity()) {
LOG.error("Invalid search condition:\n{}", searchCondition);
} else {
try {
result = doSearch(adminRoles, searchCondition, page, itemsPerPage);
} catch (Throwable t) {
LOG.error("While searching users", t);
}
}
return result;
}
@Override
public boolean matches(final SyncopeUser user, final NodeCond searchCondition) {
List<Object> parameters = Collections.synchronizedList(new ArrayList<Object>());
// 1. get the query string from the search condition
StringBuilder queryString = getQuery(searchCondition, parameters);
// 2. take into account the passed user
queryString.insert(0, "SELECT u.user_id FROM (");
queryString.append(") u WHERE user_id=?").append(setParameter(parameters, user.getId()));
// 3. prepare the search query
Query query = entityManager.createNativeQuery(queryString.toString());
// 4. populate the search query with parameter values
fillWithParameters(query, parameters);
// 5. executes query
List<SyncopeUser> result = query.getResultList();
return !result.isEmpty();
}
private int setParameter(final List<Object> parameters, final Object parameter) {
int key;
synchronized (parameters) {
parameters.add(parameter);
key = parameters.size();
}
return key;
}
private void fillWithParameters(final Query query, final List<Object> parameters) {
for (int i = 0; i < parameters.size(); i++) {
if (parameters.get(i) instanceof Date) {
query.setParameter(i + 1, (Date) parameters.get(i), TemporalType.TIMESTAMP);
} else if (parameters.get(i) instanceof Boolean) {
query.setParameter(i + 1, ((Boolean) parameters.get(i))
? 1
: 0);
} else {
query.setParameter(i + 1, parameters.get(i));
}
}
}
private List<SyncopeUser> doSearch(final Set<Long> adminRoles, final NodeCond nodeCond, final int page,
final int itemsPerPage) {
List<Object> parameters = Collections.synchronizedList(new ArrayList<Object>());
// 1. get the query string from the search condition
final StringBuilder queryString = getQuery(nodeCond, parameters);
// 2. take into account administrative roles
if (queryString.charAt(0) == '(') {
queryString.insert(0, "SELECT u.user_id FROM ");
queryString.append(" u WHERE user_id NOT IN (");
} else {
queryString.insert(0, "SELECT u.user_id FROM (");
queryString.append(") u WHERE user_id NOT IN (");
}
queryString.append(getAdminRolesFilter(adminRoles)).append(")");
// 3. prepare the search query
final Query query = entityManager.createNativeQuery(queryString.toString());
// page starts from 1, while setFirtResult() starts from 0
query.setFirstResult(itemsPerPage * (page <= 0
? 0
: page - 1));
if (itemsPerPage >= 0) {
query.setMaxResults(itemsPerPage);
}
// 4. populate the search query with parameter values
fillWithParameters(query, parameters);
LOG.debug("Native query\n{}\nwith parameters\n{}", queryString.toString(), parameters);
// 5. Prepare the result (avoiding duplicates - set)
final Set<Number> userIds = new HashSet<Number>();
final List resultList = query.getResultList();
//fix for HHH-5902 - bug hibernate
if (resultList != null) {
for (Object userId : resultList) {
if (userId instanceof Object[]) {
userIds.add((Number) ((Object[]) userId)[0]);
} else {
userIds.add((Number) userId);
}
}
}
final List<SyncopeUser> result = new ArrayList<SyncopeUser>(userIds.size());
SyncopeUser user;
for (Object userId : userIds) {
user = userDAO.find(((Number) userId).longValue());
if (user == null) {
LOG.error("Could not find user with id {}, " + "even though returned by the native query", userId);
} else {
result.add(user);
}
}
return result;
}
private StringBuilder getQuery(final NodeCond nodeCond, final List<Object> parameters) {
StringBuilder query = new StringBuilder();
switch (nodeCond.getType()) {
case LEAF:
case NOT_LEAF:
if (nodeCond.getMembershipCond() != null) {
query.append(getQuery(nodeCond.getMembershipCond(), nodeCond.getType() == NodeCond.Type.NOT_LEAF,
parameters));
}
if (nodeCond.getResourceCond() != null) {
query.append(getQuery(nodeCond.getResourceCond(), nodeCond.getType() == NodeCond.Type.NOT_LEAF,
parameters));
}
if (nodeCond.getAttributeCond() != null) {
query.append(getQuery(nodeCond.getAttributeCond(), nodeCond.getType() == NodeCond.Type.NOT_LEAF,
parameters));
}
if (nodeCond.getSyncopeUserCond() != null) {
query.append(getQuery(nodeCond.getSyncopeUserCond(), nodeCond.getType() == NodeCond.Type.NOT_LEAF,
parameters));
}
break;
case AND:
query.append(getQuery(nodeCond.getLeftNodeCond(), parameters)).append(" AND user_id IN ( ").append(
getQuery(nodeCond.getRightNodeCond(), parameters).append(")"));
break;
case OR:
query.append("(").append(getQuery(nodeCond.getLeftNodeCond(), parameters)).append(" UNION ").append(
getQuery(nodeCond.getRightNodeCond(), parameters).append(")"));
break;
default:
}
return query;
}
private String getQuery(final MembershipCond cond, final boolean not, final List<Object> parameters) {
StringBuilder query = new StringBuilder("SELECT DISTINCT user_id FROM user_search WHERE ");
if (not) {
query.append("user_id NOT IN (");
} else {
query.append("user_id IN (");
}
query.append("SELECT DISTINCT user_id ").append("FROM user_search_membership WHERE ");
if (cond.getRoleId() != null) {
query.append("role_id=?").append(setParameter(parameters, cond.getRoleId()));
} else if (cond.getRoleName() != null) {
query.append("role_name=?").append(setParameter(parameters, cond.getRoleName()));
}
query.append(")");
return query.toString();
}
private String getQuery(final ResourceCond cond, final boolean not, final List<Object> parameters) {
final StringBuilder query = new StringBuilder("SELECT DISTINCT user_id FROM user_search WHERE ");
if (not) {
query.append("user_id NOT IN (");
} else {
query.append("user_id IN (");
}
query.append("SELECT DISTINCT user_id ").append("FROM user_search_resource WHERE ");
query.append("resource_name=?").append(setParameter(parameters, cond.getResourceName()));
query.append(")");
return query.toString();
}
private void fillAttributeQuery(final StringBuilder query, final UAttrValue attrValue, final USchema schema,
final AttributeCond cond, final boolean not, final List<Object> parameters) {
String column = (cond instanceof SyncopeUserCond)
? cond.getSchema()
: "' AND " + getFieldName(schema.getType());
switch (cond.getType()) {
case ISNULL:
query.append(column).append(not
? " IS NOT NULL"
: " IS NULL");
break;
case ISNOTNULL:
query.append(column).append(not
? " IS NULL"
: " IS NOT NULL");
break;
case LIKE:
if (schema.getType() == SchemaType.String || schema.getType() == SchemaType.Enum) {
query.append(column);
if (not) {
query.append(" NOT ");
}
query.append(" LIKE '").append(cond.getExpression()).append("'");
} else {
if (!(cond instanceof SyncopeUserCond)) {
query.append("' AND");
}
query.append(" 1=2");
LOG.error("LIKE is only compatible with string schemas");
}
break;
case EQ:
query.append(column);
if (not) {
query.append("<>");
} else {
query.append("=");
}
query.append("?").append(setParameter(parameters, attrValue.getValue()));
break;
case GE:
query.append(column);
if (not) {
query.append("<");
} else {
query.append(">=");
}
query.append("?").append(setParameter(parameters, attrValue.getValue()));
break;
case GT:
query.append(column);
if (not) {
query.append("<=");
} else {
query.append(">");
}
query.append("?").append(setParameter(parameters, attrValue.getValue()));
break;
case LE:
query.append(column);
if (not) {
query.append(">");
} else {
query.append("<=");
}
query.append("?").append(setParameter(parameters, attrValue.getValue()));
break;
case LT:
query.append(column);
if (not) {
query.append(">=");
} else {
query.append("<");
}
query.append("?").append(setParameter(parameters, attrValue.getValue()));
break;
default:
}
}
private String getFieldName(final SchemaType type) {
String result;
switch (type) {
case Boolean:
result = "booleanvalue";
break;
case Date:
result = "datevalue";
break;
case Double:
result = "doublevalue";
break;
case Long:
result = "longvalue";
break;
case String:
case Enum:
result = "stringvalue";
break;
default:
result = null;
}
return result;
}
private String getQuery(final AttributeCond cond, final boolean not, final List<Object> parameters) {
USchema schema = schemaDAO.find(cond.getSchema(), USchema.class);
if (schema == null) {
LOG.warn("Ignoring invalid schema '{}'", cond.getSchema());
return EMPTY_ATTR_QUERY;
}
UAttrValue attrValue = new UAttrValue();
try {
if (cond.getType() != AttributeCond.Type.LIKE && cond.getType() != AttributeCond.Type.ISNULL
&& cond.getType() != AttributeCond.Type.ISNOTNULL) {
schema.getValidator().validate(cond.getExpression(), attrValue);
}
} catch (ValidationException e) {
LOG.error("Could not validate expression '" + cond.getExpression() + "'", e);
return EMPTY_ATTR_QUERY;
}
StringBuilder query = new StringBuilder("SELECT DISTINCT user_id FROM user_search_attr WHERE ").append(
"schema_name='").append(schema.getName());
fillAttributeQuery(query, attrValue, schema, cond, not, parameters);
return query.toString();
}
private String getQuery(final SyncopeUserCond cond, final boolean not, final List<Object> parameters) {
Field syncopeUserClassField = null;
// loop over SyncopeUser class and all superclasses searching for field
for (Class<?> i = SyncopeUser.class; syncopeUserClassField == null && i != Object.class;) {
try {
syncopeUserClassField = i.getDeclaredField(cond.getSchema());
} catch (Exception ignore) {
// ignore exception
LOG.debug("Field '{}' not found on class '{}'", new String[]{cond.getSchema(), i.getSimpleName()},
ignore);
} finally {
i = i.getSuperclass();
}
}
if (syncopeUserClassField == null) {
LOG.warn("Ignoring invalid schema '{}'", cond.getSchema());
return EMPTY_ATTR_QUERY;
}
USchema schema = new USchema();
schema.setName(syncopeUserClassField.getName());
for (SchemaType type : SchemaType.values()) {
if (syncopeUserClassField.getType().getName().equals(type.getClassName())) {
schema.setType(type);
}
}
UAttrValue attrValue = new UAttrValue();
try {
if (cond.getType() != AttributeCond.Type.LIKE && cond.getType() != AttributeCond.Type.ISNULL
&& cond.getType() != AttributeCond.Type.ISNOTNULL) {
schema.getValidator().validate(cond.getExpression(), attrValue);
}
} catch (ValidationException e) {
LOG.error("Could not validate expression '" + cond.getExpression() + "'", e);
return EMPTY_ATTR_QUERY;
}
final StringBuilder query = new StringBuilder("SELECT DISTINCT user_id FROM user_search WHERE ");
fillAttributeQuery(query, attrValue, schema, cond, not, parameters);
return query.toString();
}
}
| core/src/main/java/org/syncope/core/persistence/dao/impl/UserSearchDAOImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.syncope.core.persistence.dao.impl;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import javax.persistence.Query;
import javax.persistence.TemporalType;
import javax.validation.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.syncope.client.search.AttributeCond;
import org.syncope.client.search.SyncopeUserCond;
import org.syncope.client.search.MembershipCond;
import org.syncope.client.search.NodeCond;
import org.syncope.client.search.ResourceCond;
import org.syncope.core.persistence.beans.user.SyncopeUser;
import org.syncope.core.persistence.beans.user.UAttrValue;
import org.syncope.core.persistence.beans.user.USchema;
import org.syncope.core.persistence.dao.SchemaDAO;
import org.syncope.core.persistence.dao.UserDAO;
import org.syncope.core.persistence.dao.UserSearchDAO;
import org.syncope.types.SchemaType;
@Repository
public class UserSearchDAOImpl extends AbstractDAOImpl implements UserSearchDAO {
static final private String EMPTY_ATTR_QUERY = "SELECT user_id FROM user_search_attr WHERE 1=2";
@Autowired
private UserDAO userDAO;
@Autowired
private SchemaDAO schemaDAO;
public UserSearchDAOImpl() {
super();
}
private String getAdminRolesFilter(final Set<Long> adminRoles) {
final StringBuilder adminRolesFilter = new StringBuilder();
if (adminRoles == null || adminRoles.isEmpty()) {
adminRolesFilter.append("SELECT syncopeUser_id AS user_id ").append("FROM Membership");
} else {
adminRolesFilter.append("SELECT syncopeUser_id AS user_id ").append("FROM Membership M1 ").append(
"WHERE syncopeRole_id IN (");
adminRolesFilter.append("SELECT syncopeRole_id ").append("FROM Membership M2 ").append(
"WHERE M2.syncopeUser_id=M1.syncopeUser_id ").append("AND syncopeRole_id NOT IN (");
adminRolesFilter.append("SELECT id AS syncopeRole_id FROM SyncopeRole");
boolean firstRole = true;
for (Long adminRoleId : adminRoles) {
if (firstRole) {
adminRolesFilter.append(" WHERE");
firstRole = false;
} else {
adminRolesFilter.append(" OR");
}
adminRolesFilter.append(" id=").append(adminRoleId);
}
adminRolesFilter.append("))");
}
return adminRolesFilter.toString();
}
@Override
public int count(final Set<Long> adminRoles, final NodeCond searchCondition) {
List<Object> parameters = Collections.synchronizedList(new ArrayList<Object>());
// 1. get the query string from the search condition
StringBuilder queryString = getQuery(searchCondition, parameters);
// 2. take into account administrative roles
queryString.insert(0, "SELECT u.user_id FROM (");
queryString.append(") u WHERE user_id NOT IN (");
queryString.append(getAdminRolesFilter(adminRoles)).append(")");
// 3. prepare the COUNT query
queryString.insert(0, "SELECT COUNT(user_id) FROM (");
queryString.append(") count_user_id");
Query countQuery = entityManager.createNativeQuery(queryString.toString());
fillWithParameters(countQuery, parameters);
LOG.debug("Native count query\n{}\nwith parameters\n{}", queryString.toString(), parameters);
int result = ((Number) countQuery.getSingleResult()).intValue();
LOG.debug("Native count query result: {}", result);
return result;
}
@Override
public List<SyncopeUser> search(final NodeCond searchCondition) {
return search(null, searchCondition, -1, -1);
}
@Override
public List<SyncopeUser> search(final Set<Long> adminRoles, final NodeCond searchCondition) {
return search(adminRoles, searchCondition, -1, -1);
}
@Override
public List<SyncopeUser> search(final Set<Long> adminRoles, final NodeCond searchCondition, final int page,
final int itemsPerPage) {
List<SyncopeUser> result = Collections.EMPTY_LIST;
LOG.debug("Search condition:\n{}", searchCondition);
if (!searchCondition.checkValidity()) {
LOG.error("Invalid search condition:\n{}", searchCondition);
} else {
try {
result = doSearch(adminRoles, searchCondition, page, itemsPerPage);
} catch (Throwable t) {
LOG.error("While searching users", t);
}
}
return result;
}
@Override
public boolean matches(final SyncopeUser user, final NodeCond searchCondition) {
List<Object> parameters = Collections.synchronizedList(new ArrayList<Object>());
// 1. get the query string from the search condition
StringBuilder queryString = getQuery(searchCondition, parameters);
// 2. take into account the passed user
queryString.insert(0, "SELECT u.user_id FROM (");
queryString.append(") u WHERE user_id=?").append(setParameter(parameters, user.getId()));
// 3. prepare the search query
Query query = entityManager.createNativeQuery(queryString.toString());
// 4. populate the search query with parameter values
fillWithParameters(query, parameters);
// 5. executes query
List<SyncopeUser> result = query.getResultList();
return !result.isEmpty();
}
private int setParameter(final List<Object> parameters, final Object parameter) {
int key;
synchronized (parameters) {
parameters.add(parameter);
key = parameters.size();
}
return key;
}
private void fillWithParameters(final Query query, final List<Object> parameters) {
for (int i = 0; i < parameters.size(); i++) {
if (parameters.get(i) instanceof Date) {
query.setParameter(i + 1, (Date) parameters.get(i), TemporalType.TIMESTAMP);
} else if (parameters.get(i) instanceof Boolean) {
query.setParameter(i + 1, ((Boolean) parameters.get(i))
? 1
: 0);
} else {
query.setParameter(i + 1, parameters.get(i));
}
}
}
private List<SyncopeUser> doSearch(final Set<Long> adminRoles, final NodeCond nodeCond, final int page,
final int itemsPerPage) {
List<Object> parameters = Collections.synchronizedList(new ArrayList<Object>());
// 1. get the query string from the search condition
final StringBuilder queryString = getQuery(nodeCond, parameters);
// 2. take into account administrative roles
if (queryString.charAt(0) == '(') {
queryString.insert(0, "SELECT u.user_id FROM ");
queryString.append(" u WHERE user_id NOT IN (");
} else {
queryString.insert(0, "SELECT u.user_id FROM (");
queryString.append(") u WHERE user_id NOT IN (");
}
queryString.append(getAdminRolesFilter(adminRoles)).append(")");
// 3. prepare the search query
final Query query = entityManager.createNativeQuery(queryString.toString());
// page starts from 1, while setFirtResult() starts from 0
query.setFirstResult(itemsPerPage * (page <= 0
? 0
: page - 1));
if (itemsPerPage >= 0) {
query.setMaxResults(itemsPerPage);
}
// 4. populate the search query with parameter values
fillWithParameters(query, parameters);
LOG.debug("Native query\n{}\nwith parameters\n{}", queryString.toString(), parameters);
// 5. Prepare the result (avoiding duplicates - set)
final Set<Number> userIds = new HashSet<Number>();
final List resultList = query.getResultList();
//fix for HHH-5902 - bug hibernate
if (resultList != null) {
for (Object userId : resultList) {
if (userId instanceof Object[]) {
userIds.add((Number) ((Object[]) userId)[0]);
} else {
userIds.add((Number) userId);
}
}
}
final List<SyncopeUser> result = new ArrayList<SyncopeUser>(userIds.size());
SyncopeUser user;
for (Object userId : userIds) {
user = userDAO.find(((Number) userId).longValue());
if (user == null) {
LOG.error("Could not find user with id {}, " + "even though returned by the native query", userId);
} else {
result.add(user);
}
}
return result;
}
private StringBuilder getQuery(final NodeCond nodeCond, final List<Object> parameters) {
StringBuilder query = new StringBuilder();
switch (nodeCond.getType()) {
case LEAF:
case NOT_LEAF:
if (nodeCond.getMembershipCond() != null) {
query.append(getQuery(nodeCond.getMembershipCond(), nodeCond.getType() == NodeCond.Type.NOT_LEAF,
parameters));
}
if (nodeCond.getResourceCond() != null) {
query.append(getQuery(nodeCond.getResourceCond(), nodeCond.getType() == NodeCond.Type.NOT_LEAF,
parameters));
}
if (nodeCond.getAttributeCond() != null) {
query.append(getQuery(nodeCond.getAttributeCond(), nodeCond.getType() == NodeCond.Type.NOT_LEAF,
parameters));
}
if (nodeCond.getSyncopeUserCond() != null) {
query.append(getQuery(nodeCond.getSyncopeUserCond(), nodeCond.getType() == NodeCond.Type.NOT_LEAF,
parameters));
}
break;
case AND:
query.append(getQuery(nodeCond.getLeftNodeCond(), parameters)).append(" AND user_id IN ( ").append(
getQuery(nodeCond.getRightNodeCond(), parameters).append(")"));
break;
case OR:
query.append("(").append(getQuery(nodeCond.getLeftNodeCond(), parameters)).append(" UNION ").append(
getQuery(nodeCond.getRightNodeCond(), parameters).append(")"));
break;
default:
}
return query;
}
private String getQuery(final MembershipCond cond, final boolean not, final List<Object> parameters) {
StringBuilder query = new StringBuilder("SELECT DISTINCT user_id FROM user_search WHERE ");
if (not) {
query.append("user_id NOT IN (");
} else {
query.append("user_id IN (");
}
query.append("SELECT DISTINCT user_id ").append("FROM user_search_membership WHERE ");
if (cond.getRoleId() != null) {
query.append("role_id=?").append(setParameter(parameters, cond.getRoleId()));
} else if (cond.getRoleName() != null) {
query.append("role_name=?").append(setParameter(parameters, cond.getRoleName()));
}
query.append(")");
return query.toString();
}
private String getQuery(final ResourceCond cond, final boolean not, final List<Object> parameters) {
final StringBuilder query = new StringBuilder("SELECT DISTINCT user_id FROM user_search WHERE ");
if (not) {
query.append("user_id NOT IN (");
} else {
query.append("user_id IN (");
}
query.append("SELECT DISTINCT user_id ").append("FROM user_search_resource WHERE ");
query.append("resource_name=?").append(setParameter(parameters, cond.getResourceName()));
query.append(")");
return query.toString();
}
private void fillAttributeQuery(final StringBuilder query, final UAttrValue attrValue, final USchema schema,
final AttributeCond cond, final boolean not, final List<Object> parameters) {
String column = (cond instanceof SyncopeUserCond)
? cond.getSchema()
: "' AND " + getFieldName(schema.getType());
switch (cond.getType()) {
case ISNULL:
query.append(column).append(not
? " IS NOT NULL"
: " IS NULL");
break;
case ISNOTNULL:
query.append(column).append(not
? " IS NULL"
: " IS NOT NULL");
break;
case LIKE:
if (schema.getType() == SchemaType.String || schema.getType() == SchemaType.Enum) {
query.append(column);
if (not) {
query.append(" NOT ");
}
query.append(" LIKE ");
if (!(cond instanceof SyncopeUserCond)) {
query.append('\'');
}
query.append(cond.getExpression()).append("'");
} else {
if (!(cond instanceof SyncopeUserCond)) {
query.append("' AND");
}
query.append(" 1=2");
LOG.error("LIKE is only compatible with string schemas");
}
break;
case EQ:
query.append(column);
if (not) {
query.append("<>");
} else {
query.append("=");
}
query.append("?").append(setParameter(parameters, attrValue.getValue()));
break;
case GE:
query.append(column);
if (not) {
query.append("<");
} else {
query.append(">=");
}
query.append("?").append(setParameter(parameters, attrValue.getValue()));
break;
case GT:
query.append(column);
if (not) {
query.append("<=");
} else {
query.append(">");
}
query.append("?").append(setParameter(parameters, attrValue.getValue()));
break;
case LE:
query.append(column);
if (not) {
query.append(">");
} else {
query.append("<=");
}
query.append("?").append(setParameter(parameters, attrValue.getValue()));
break;
case LT:
query.append(column);
if (not) {
query.append(">=");
} else {
query.append("<");
}
query.append("?").append(setParameter(parameters, attrValue.getValue()));
break;
default:
}
}
private String getFieldName(final SchemaType type) {
String result;
switch (type) {
case Boolean:
result = "booleanvalue";
break;
case Date:
result = "datevalue";
break;
case Double:
result = "doublevalue";
break;
case Long:
result = "longvalue";
break;
case String:
case Enum:
result = "stringvalue";
break;
default:
result = null;
}
return result;
}
private String getQuery(final AttributeCond cond, final boolean not, final List<Object> parameters) {
USchema schema = schemaDAO.find(cond.getSchema(), USchema.class);
if (schema == null) {
LOG.warn("Ignoring invalid schema '{}'", cond.getSchema());
return EMPTY_ATTR_QUERY;
}
UAttrValue attrValue = new UAttrValue();
try {
if (cond.getType() != AttributeCond.Type.LIKE && cond.getType() != AttributeCond.Type.ISNULL
&& cond.getType() != AttributeCond.Type.ISNOTNULL) {
schema.getValidator().validate(cond.getExpression(), attrValue);
}
} catch (ValidationException e) {
LOG.error("Could not validate expression '" + cond.getExpression() + "'", e);
return EMPTY_ATTR_QUERY;
}
StringBuilder query = new StringBuilder("SELECT DISTINCT user_id FROM user_search_attr WHERE ").append(
"schema_name='").append(schema.getName());
fillAttributeQuery(query, attrValue, schema, cond, not, parameters);
return query.toString();
}
private String getQuery(final SyncopeUserCond cond, final boolean not, final List<Object> parameters) {
Field syncopeUserClassField = null;
// loop over SyncopeUser class and all superclasses searching for field
for (Class<?> i = SyncopeUser.class; syncopeUserClassField == null && i != Object.class;) {
try {
syncopeUserClassField = i.getDeclaredField(cond.getSchema());
} catch (Exception ignore) {
// ignore exception
LOG.debug("Field '{}' not found on class '{}'", new String[] { cond.getSchema(), i.getSimpleName() },
ignore);
} finally {
i = i.getSuperclass();
}
}
if (syncopeUserClassField == null) {
LOG.warn("Ignoring invalid schema '{}'", cond.getSchema());
return EMPTY_ATTR_QUERY;
}
USchema schema = new USchema();
schema.setName(syncopeUserClassField.getName());
for (SchemaType type : SchemaType.values()) {
if (syncopeUserClassField.getType().getName().equals(type.getClassName())) {
schema.setType(type);
}
}
UAttrValue attrValue = new UAttrValue();
try {
if (cond.getType() != AttributeCond.Type.LIKE && cond.getType() != AttributeCond.Type.ISNULL
&& cond.getType() != AttributeCond.Type.ISNOTNULL) {
schema.getValidator().validate(cond.getExpression(), attrValue);
}
} catch (ValidationException e) {
LOG.error("Could not validate expression '" + cond.getExpression() + "'", e);
return EMPTY_ATTR_QUERY;
}
final StringBuilder query = new StringBuilder("SELECT DISTINCT user_id FROM user_search WHERE ");
fillAttributeQuery(query, attrValue, schema, cond, not, parameters);
return query.toString();
}
}
| SYNCOPE-46 Add single quote to user search
git-svn-id: 51e9c0635e05060c2a7639df764e0b3ebb09013f@1303857 13f79535-47bb-0310-9956-ffa450edef68
| core/src/main/java/org/syncope/core/persistence/dao/impl/UserSearchDAOImpl.java | SYNCOPE-46 Add single quote to user search |
|
Java | apache-2.0 | 57da1a2231c4bf217e255df8c32337188a16ff5c | 0 | wcmc-its/ReCiter,wcmc-its/ReCiter | /*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 reciter.engine;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reciter.algorithm.cluster.Clusterer;
import reciter.algorithm.cluster.ReCiterClusterer;
import reciter.algorithm.cluster.model.ReCiterCluster;
import reciter.algorithm.cluster.model.ReCiterCluster.MeshTermCount;
import reciter.algorithm.cluster.targetauthor.ClusterSelector;
import reciter.algorithm.cluster.targetauthor.ReCiterClusterSelector;
import reciter.algorithm.evidence.StrategyContext;
import reciter.algorithm.evidence.article.mesh.MeshMajorStrategyContext;
import reciter.algorithm.evidence.article.mesh.strategy.MeshMajorStrategy;
import reciter.algorithm.evidence.targetauthor.TargetAuthorStrategyContext;
import reciter.algorithm.evidence.targetauthor.affiliation.AffiliationStrategyContext;
import reciter.algorithm.evidence.targetauthor.affiliation.strategy.CommonAffiliationStrategy;
import reciter.algorithm.evidence.targetauthor.degree.DegreeStrategyContext;
import reciter.algorithm.evidence.targetauthor.degree.strategy.DegreeType;
import reciter.algorithm.evidence.targetauthor.degree.strategy.YearDiscrepancyStrategy;
import reciter.algorithm.evidence.targetauthor.department.DepartmentStrategyContext;
import reciter.algorithm.evidence.targetauthor.department.strategy.DepartmentStringMatchStrategy;
import reciter.algorithm.evidence.targetauthor.email.EmailStrategyContext;
import reciter.algorithm.evidence.targetauthor.email.strategy.EmailStringMatchStrategy;
import reciter.algorithm.evidence.targetauthor.knownrelationship.KnownRelationshipStrategyContext;
import reciter.algorithm.evidence.targetauthor.knownrelationship.strategy.KnownRelationshipStrategy;
import reciter.algorithm.evidence.targetauthor.scopus.ScopusStrategyContext;
import reciter.algorithm.evidence.targetauthor.scopus.strategy.ScopusCommonAffiliation;
import reciter.algorithm.util.ArticleTranslator;
import reciter.engine.analysis.ReCiterFeature;
import reciter.engine.analysis.ReCiterFeatureGenerator;
import reciter.engine.erroranalysis.Analysis;
import reciter.model.article.ReCiterArticle;
import reciter.model.article.ReCiterArticleMeshHeading;
import reciter.model.identity.Identity;
import reciter.model.pubmed.PubMedArticle;
import reciter.model.scopus.ScopusArticle;
public class ReCiterEngine implements Engine {
private static final Logger slf4jLogger = LoggerFactory.getLogger(ReCiterEngine.class);
@Override
public List<Feature> generateFeature(EngineParameters parameters) {
Identity identity = parameters.getIdentity();
List<PubMedArticle> pubMedArticles = parameters.getPubMedArticles();
List<ScopusArticle> scopusArticles = parameters.getScopusArticles();
Map<Long, ScopusArticle> map = new HashMap<>();
for (ScopusArticle scopusArticle : scopusArticles) {
map.put(scopusArticle.getPubmedId(), scopusArticle);
}
List<ReCiterArticle> reCiterArticles = new ArrayList<>();
for (PubMedArticle pubMedArticle : pubMedArticles) {
long pmid = pubMedArticle.getMedlinecitation().getMedlinecitationpmid().getPmid();
if (map.containsKey(pmid)) {
reCiterArticles.add(ArticleTranslator.translate(pubMedArticle, map.get(pmid)));
} else {
reCiterArticles.add(ArticleTranslator.translate(pubMedArticle, null));
}
}
Analysis.assignGoldStandard(reCiterArticles, parameters.getKnownPmids());
List<Feature> features = new ArrayList<>();
for (ReCiterArticle reCiterArticle : reCiterArticles) {
Feature feature = new Feature();
feature.setPmid(reCiterArticle.getArticleId());
feature.setIsGoldStandard(reCiterArticle.getGoldStandard());
TargetAuthorStrategyContext emailStrategyContext = new EmailStrategyContext(new EmailStringMatchStrategy());
emailStrategyContext.populateFeature(reCiterArticle, identity, feature);
TargetAuthorStrategyContext departmentStringMatchStrategyContext = new DepartmentStrategyContext(new DepartmentStringMatchStrategy());
departmentStringMatchStrategyContext.populateFeature(reCiterArticle, identity, feature);
TargetAuthorStrategyContext grantCoauthorStrategyContext = new KnownRelationshipStrategyContext(new KnownRelationshipStrategy());
grantCoauthorStrategyContext.populateFeature(reCiterArticle, identity, feature);
TargetAuthorStrategyContext affiliationStrategyContext = new AffiliationStrategyContext(new CommonAffiliationStrategy());
affiliationStrategyContext.populateFeature(reCiterArticle, identity, feature);
TargetAuthorStrategyContext scopusStrategyContext = new ScopusStrategyContext(new ScopusCommonAffiliation());
scopusStrategyContext.populateFeature(reCiterArticle, identity, feature);
features.add(feature);
}
return features;
}
@Override
public EngineOutput run(EngineParameters parameters, StrategyParameters strategyParameters) {
Identity identity = parameters.getIdentity();
List<PubMedArticle> pubMedArticles = parameters.getPubMedArticles();
List<ScopusArticle> scopusArticles = parameters.getScopusArticles();
Map<Long, ScopusArticle> map = new HashMap<>();
for (ScopusArticle scopusArticle : scopusArticles) {
map.put(scopusArticle.getPubmedId(), scopusArticle);
}
/*List<ReCiterArticle> reCiterArticles = new ArrayList<>();
for (PubMedArticle pubMedArticle : pubMedArticles) {
long pmid = pubMedArticle.getMedlinecitation().getMedlinecitationpmid().getPmid();
if (map.containsKey(pmid)) {
reCiterArticles.add(ArticleTranslator.translate(pubMedArticle, map.get(pmid)));
} else {
reCiterArticles.add(ArticleTranslator.translate(pubMedArticle, null));
}
}*/
List<ReCiterArticle> reCiterArticles = parameters.getReciterArticles();
Analysis.assignGoldStandard(reCiterArticles, parameters.getKnownPmids());
// Perform Phase 1 clustering.
Clusterer clusterer = new ReCiterClusterer(identity, reCiterArticles);
// int seedSize = ((Double) (parameters.getKnownPmids().size() * 1.0)).intValue();
// Set<Long> initialSeed = new HashSet<Long>();
// slf4jLogger.info("Initial seed size=[" + seedSize + "].");
// int taken = 0;
// for (long pmid : parameters.getKnownPmids()) {
// if (taken < seedSize) {
// initialSeed.add(pmid);
// } else {
// break;
// }
// taken++;
// }
// if (!initialSeed.isEmpty()) {
// clusterer.cluster(initialSeed);
// } else {
// clusterer.cluster();
// }
clusterer.cluster();
slf4jLogger.info("Phase 1 Clustering result");
slf4jLogger.info(clusterer.toString());
// Perform Phase 2 clusters selection.
ClusterSelector clusterSelector = new ReCiterClusterSelector(clusterer.getClusters(), identity, strategyParameters);
clusterSelector.runSelectionStrategy(clusterer.getClusters(), identity);
slf4jLogger.info(clusterSelector.getSelectedClusterIds().size() +"Size");
// Perform Mesh Heading recall improvement.
// Use MeSH major to improve recall after phase two (https://github.com/wcmc-its/ReCiter/issues/131)
List<ReCiterArticle> selectedArticles = new ArrayList<>();
for (long id : clusterSelector.getSelectedClusterIds()) {
selectedArticles.addAll(clusterer.getClusters().get(id).getArticleCluster());
}
StrategyContext meshMajorStrategyContext = new MeshMajorStrategyContext(new MeshMajorStrategy(selectedArticles, EngineParameters.getMeshCountMap()));
clusterSelector.handleNonSelectedClusters((MeshMajorStrategyContext) meshMajorStrategyContext, clusterer.getClusters(), identity);
StrategyContext bachelorsYearDiscrepancyStrategyContext = new DegreeStrategyContext(new YearDiscrepancyStrategy(DegreeType.BACHELORS));
StrategyContext doctoralYearDiscrepancyStrategyContext = new DegreeStrategyContext(new YearDiscrepancyStrategy(DegreeType.DOCTORAL));
clusterSelector.handleStrategyContext(bachelorsYearDiscrepancyStrategyContext, clusterer.getClusters(), identity);
clusterSelector.handleStrategyContext(doctoralYearDiscrepancyStrategyContext, clusterer.getClusters(), identity);
Analysis analysis = Analysis.performAnalysis(clusterer, clusterSelector, parameters.getKnownPmids());
slf4jLogger.info(clusterer.toString());
slf4jLogger.info("Analysis for uid=[" + identity.getUid() + "]");
slf4jLogger.info("Precision=" + analysis.getPrecision());
slf4jLogger.info("Recall=" + analysis.getRecall());
double accuracy = (analysis.getPrecision() + analysis.getRecall()) / 2;
slf4jLogger.info("Accuracy=" + accuracy);
slf4jLogger.info("True Positive List [" + analysis.getTruePositiveList().size() + "]: " + analysis.getTruePositiveList());
slf4jLogger.info("True Negative List: [" + analysis.getTrueNegativeList().size() + "]: " + analysis.getTrueNegativeList());
slf4jLogger.info("False Positive List: [" + analysis.getFalsePositiveList().size() + "]: " + analysis.getFalsePositiveList());
slf4jLogger.info("False Negative List: [" + analysis.getFalseNegativeList().size() + "]: " + analysis.getFalseNegativeList());
slf4jLogger.info("\n");
for (ReCiterArticle reCiterArticle : reCiterArticles) {
slf4jLogger.info(reCiterArticle.getArticleId() + ": " + reCiterArticle.getClusterInfo());
}
// add mesh major to analysis
// for each cluster, count the number of MeSH terms
for (ReCiterCluster cluster : clusterer.getClusters().values()) {
Map<String, Long> meshCount = new HashMap<>();
for (ReCiterArticle reCiterArticle : cluster.getArticleCluster()) {
// calculate correct author.
reCiterArticle.setCorrectAuthor(identity);
List<ReCiterArticleMeshHeading> meshHeadings = reCiterArticle.getMeshHeadings();
for (ReCiterArticleMeshHeading meshHeading : meshHeadings) {
String descriptorName = meshHeading.getDescriptorName().getDescriptorName();
if (MeshMajorStrategy.isMeshMajor(meshHeading)) { // check if this is a mesh major. (i.e., An article A may say mesh
if (!meshCount.containsKey(descriptorName)) {
meshCount.put(descriptorName, 1L);
} else {
long count = meshCount.get(descriptorName);
meshCount.put(descriptorName, ++count);
}
}
}
}
List<MeshTermCount> meshTermCounts = new ArrayList<>(meshCount.size());
for (Map.Entry<String, Long> entry : meshCount.entrySet()) {
MeshTermCount meshTermCount = new MeshTermCount();
meshTermCount.setMesh(entry.getKey());
meshTermCount.setCount(entry.getValue());
meshTermCounts.add(meshTermCount);
}
cluster.setMeshTermCounts(meshTermCounts);
}
// Evidence - Gold standard is used to refine judgment of ReCiter
if (strategyParameters.isUseGoldStandardEvidence()) {
Set<Long> selectedClusterIds = clusterSelector.getSelectedClusterIds();
List<ReCiterArticle> goldStandardArticles = new ArrayList<>();
for (ReCiterCluster cluster : clusterer.getClusters().values()) {
if (selectedClusterIds.contains(cluster.getClusterID())) {
Iterator<ReCiterArticle> itr = cluster.getArticleCluster().iterator();
while (itr.hasNext()) {
ReCiterArticle reCiterArticle = itr.next();
if (reCiterArticle.getGoldStandard() == 0) {
goldStandardArticles.add(reCiterArticle);
}
itr.remove();
}
}
}
if (!goldStandardArticles.isEmpty()) {
ReCiterCluster rejectedCluster = new ReCiterCluster();
for (ReCiterArticle reject : goldStandardArticles) {
rejectedCluster.add(reject);
}
clusterer.getClusters().put(rejectedCluster.getClusterID(), rejectedCluster);
}
}
EngineOutput engineOutput = new EngineOutput();
engineOutput.setAnalysis(analysis);
List<ReCiterCluster> reCiterClusters = new ArrayList<>();
for (ReCiterCluster cluster : clusterer.getClusters().values()) {
// set cluster's selected field to true if this cluster has been selected.
if (clusterSelector.getSelectedClusterIds().contains(cluster.getClusterID())) {
cluster.setSelected(true);
}
reCiterClusters.add(cluster);
}
engineOutput.setReCiterClusters(reCiterClusters);
ReCiterFeatureGenerator reCiterFeatureGenerator = new ReCiterFeatureGenerator();
ReCiterFeature reCiterFeature = reCiterFeatureGenerator.computeFeatures("test", clusterer, clusterSelector, parameters.getKnownPmids(), parameters.getRejectedPmids(), analysis);
engineOutput.setReCiterFeature(reCiterFeature);
return engineOutput;
}
}
| src/main/java/reciter/engine/ReCiterEngine.java | /*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 reciter.engine;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reciter.algorithm.cluster.Clusterer;
import reciter.algorithm.cluster.ReCiterClusterer;
import reciter.algorithm.cluster.model.ReCiterCluster;
import reciter.algorithm.cluster.model.ReCiterCluster.MeshTermCount;
import reciter.algorithm.cluster.targetauthor.ClusterSelector;
import reciter.algorithm.cluster.targetauthor.ReCiterClusterSelector;
import reciter.algorithm.evidence.StrategyContext;
import reciter.algorithm.evidence.article.mesh.MeshMajorStrategyContext;
import reciter.algorithm.evidence.article.mesh.strategy.MeshMajorStrategy;
import reciter.algorithm.evidence.targetauthor.TargetAuthorStrategyContext;
import reciter.algorithm.evidence.targetauthor.affiliation.AffiliationStrategyContext;
import reciter.algorithm.evidence.targetauthor.affiliation.strategy.CommonAffiliationStrategy;
import reciter.algorithm.evidence.targetauthor.degree.DegreeStrategyContext;
import reciter.algorithm.evidence.targetauthor.degree.strategy.DegreeType;
import reciter.algorithm.evidence.targetauthor.degree.strategy.YearDiscrepancyStrategy;
import reciter.algorithm.evidence.targetauthor.department.DepartmentStrategyContext;
import reciter.algorithm.evidence.targetauthor.department.strategy.DepartmentStringMatchStrategy;
import reciter.algorithm.evidence.targetauthor.email.EmailStrategyContext;
import reciter.algorithm.evidence.targetauthor.email.strategy.EmailStringMatchStrategy;
import reciter.algorithm.evidence.targetauthor.knownrelationship.KnownRelationshipStrategyContext;
import reciter.algorithm.evidence.targetauthor.knownrelationship.strategy.KnownRelationshipStrategy;
import reciter.algorithm.evidence.targetauthor.scopus.ScopusStrategyContext;
import reciter.algorithm.evidence.targetauthor.scopus.strategy.ScopusCommonAffiliation;
import reciter.algorithm.util.ArticleTranslator;
import reciter.engine.analysis.ReCiterFeature;
import reciter.engine.analysis.ReCiterFeatureGenerator;
import reciter.engine.erroranalysis.Analysis;
import reciter.model.article.ReCiterArticle;
import reciter.model.article.ReCiterArticleMeshHeading;
import reciter.model.identity.Identity;
import reciter.model.pubmed.PubMedArticle;
import reciter.model.scopus.ScopusArticle;
public class ReCiterEngine implements Engine {
private static final Logger slf4jLogger = LoggerFactory.getLogger(ReCiterEngine.class);
@Override
public List<Feature> generateFeature(EngineParameters parameters) {
Identity identity = parameters.getIdentity();
List<PubMedArticle> pubMedArticles = parameters.getPubMedArticles();
List<ScopusArticle> scopusArticles = parameters.getScopusArticles();
Map<Long, ScopusArticle> map = new HashMap<>();
for (ScopusArticle scopusArticle : scopusArticles) {
map.put(scopusArticle.getPubmedId(), scopusArticle);
}
List<ReCiterArticle> reCiterArticles = new ArrayList<>();
for (PubMedArticle pubMedArticle : pubMedArticles) {
long pmid = pubMedArticle.getMedlinecitation().getMedlinecitationpmid().getPmid();
if (map.containsKey(pmid)) {
reCiterArticles.add(ArticleTranslator.translate(pubMedArticle, map.get(pmid)));
} else {
reCiterArticles.add(ArticleTranslator.translate(pubMedArticle, null));
}
}
Analysis.assignGoldStandard(reCiterArticles, parameters.getKnownPmids());
List<Feature> features = new ArrayList<>();
for (ReCiterArticle reCiterArticle : reCiterArticles) {
Feature feature = new Feature();
feature.setPmid(reCiterArticle.getArticleId());
feature.setIsGoldStandard(reCiterArticle.getGoldStandard());
TargetAuthorStrategyContext emailStrategyContext = new EmailStrategyContext(new EmailStringMatchStrategy());
emailStrategyContext.populateFeature(reCiterArticle, identity, feature);
TargetAuthorStrategyContext departmentStringMatchStrategyContext = new DepartmentStrategyContext(new DepartmentStringMatchStrategy());
departmentStringMatchStrategyContext.populateFeature(reCiterArticle, identity, feature);
TargetAuthorStrategyContext grantCoauthorStrategyContext = new KnownRelationshipStrategyContext(new KnownRelationshipStrategy());
grantCoauthorStrategyContext.populateFeature(reCiterArticle, identity, feature);
TargetAuthorStrategyContext affiliationStrategyContext = new AffiliationStrategyContext(new CommonAffiliationStrategy());
affiliationStrategyContext.populateFeature(reCiterArticle, identity, feature);
TargetAuthorStrategyContext scopusStrategyContext = new ScopusStrategyContext(new ScopusCommonAffiliation());
scopusStrategyContext.populateFeature(reCiterArticle, identity, feature);
features.add(feature);
}
return features;
}
@Override
public EngineOutput run(EngineParameters parameters, StrategyParameters strategyParameters) {
Identity identity = parameters.getIdentity();
List<PubMedArticle> pubMedArticles = parameters.getPubMedArticles();
List<ScopusArticle> scopusArticles = parameters.getScopusArticles();
Map<Long, ScopusArticle> map = new HashMap<>();
for (ScopusArticle scopusArticle : scopusArticles) {
map.put(scopusArticle.getPubmedId(), scopusArticle);
}
/*List<ReCiterArticle> reCiterArticles = new ArrayList<>();
for (PubMedArticle pubMedArticle : pubMedArticles) {
long pmid = pubMedArticle.getMedlinecitation().getMedlinecitationpmid().getPmid();
if (map.containsKey(pmid)) {
reCiterArticles.add(ArticleTranslator.translate(pubMedArticle, map.get(pmid)));
} else {
reCiterArticles.add(ArticleTranslator.translate(pubMedArticle, null));
}
}*/
List<ReCiterArticle> reCiterArticles = parameters.getReciterArticles();
Analysis.assignGoldStandard(reCiterArticles, parameters.getKnownPmids());
// Perform Phase 1 clustering.
Clusterer clusterer = new ReCiterClusterer(identity, reCiterArticles);
// int seedSize = ((Double) (parameters.getKnownPmids().size() * 1.0)).intValue();
// Set<Long> initialSeed = new HashSet<Long>();
// slf4jLogger.info("Initial seed size=[" + seedSize + "].");
// int taken = 0;
// for (long pmid : parameters.getKnownPmids()) {
// if (taken < seedSize) {
// initialSeed.add(pmid);
// } else {
// break;
// }
// taken++;
// }
// if (!initialSeed.isEmpty()) {
// clusterer.cluster(initialSeed);
// } else {
// clusterer.cluster();
// }
clusterer.cluster();
slf4jLogger.info("Phase 1 Clustering result");
slf4jLogger.info(clusterer.toString());
// Perform Phase 2 clusters selection.
ClusterSelector clusterSelector = new ReCiterClusterSelector(clusterer.getClusters(), identity, strategyParameters);
clusterSelector.runSelectionStrategy(clusterer.getClusters(), identity);
slf4jLogger.info(clusterSelector.getSelectedClusterIds().size() +"Size");
// Perform Mesh Heading recall improvement.
// Use MeSH major to improve recall after phase two (https://github.com/wcmc-its/ReCiter/issues/131)
List<ReCiterArticle> selectedArticles = new ArrayList<>();
for (long id : clusterSelector.getSelectedClusterIds()) {
selectedArticles.addAll(clusterer.getClusters().get(id).getArticleCluster());
}
StrategyContext meshMajorStrategyContext = new MeshMajorStrategyContext(new MeshMajorStrategy(selectedArticles, EngineParameters.getMeshCountMap()));
clusterSelector.handleNonSelectedClusters((MeshMajorStrategyContext) meshMajorStrategyContext, clusterer.getClusters(), identity);
StrategyContext bachelorsYearDiscrepancyStrategyContext = new DegreeStrategyContext(new YearDiscrepancyStrategy(DegreeType.BACHELORS));
StrategyContext doctoralYearDiscrepancyStrategyContext = new DegreeStrategyContext(new YearDiscrepancyStrategy(DegreeType.DOCTORAL));
clusterSelector.handleStrategyContext(bachelorsYearDiscrepancyStrategyContext, clusterer.getClusters(), identity);
clusterSelector.handleStrategyContext(doctoralYearDiscrepancyStrategyContext, clusterer.getClusters(), identity);
Analysis analysis = Analysis.performAnalysis(clusterer, clusterSelector, parameters.getKnownPmids());
slf4jLogger.info(clusterer.toString());
slf4jLogger.info("Analysis for uid=[" + identity.getUid() + "]");
slf4jLogger.info("Precision=" + analysis.getPrecision());
slf4jLogger.info("Recall=" + analysis.getRecall());
double accuracy = (analysis.getPrecision() + analysis.getRecall()) / 2;
slf4jLogger.info("Accuracy=" + accuracy);
slf4jLogger.info("True Positive List [" + analysis.getTruePositiveList().size() + "]: " + analysis.getTruePositiveList());
slf4jLogger.info("True Negative List: [" + analysis.getTrueNegativeList().size() + "]: " + analysis.getTrueNegativeList());
slf4jLogger.info("False Positive List: [" + analysis.getFalsePositiveList().size() + "]: " + analysis.getFalsePositiveList());
slf4jLogger.info("False Negative List: [" + analysis.getFalseNegativeList().size() + "]: " + analysis.getFalseNegativeList());
slf4jLogger.info("\n");
for (ReCiterArticle reCiterArticle : reCiterArticles) {
slf4jLogger.info(reCiterArticle.getArticleId() + ": " + reCiterArticle.getClusterInfo());
}
// add mesh major to analysis
// for each cluster, count the number of MeSH terms
for (ReCiterCluster cluster : clusterer.getClusters().values()) {
Map<String, Long> meshCount = new HashMap<>();
for (ReCiterArticle reCiterArticle : cluster.getArticleCluster()) {
// calculate correct author.
reCiterArticle.setCorrectAuthor(identity);
List<ReCiterArticleMeshHeading> meshHeadings = reCiterArticle.getMeshHeadings();
for (ReCiterArticleMeshHeading meshHeading : meshHeadings) {
String descriptorName = meshHeading.getDescriptorName().getDescriptorName();
if (MeshMajorStrategy.isMeshMajor(meshHeading)) { // check if this is a mesh major. (i.e., An article A may say mesh
if (!meshCount.containsKey(descriptorName)) {
meshCount.put(descriptorName, 1L);
} else {
long count = meshCount.get(descriptorName);
meshCount.put(descriptorName, ++count);
}
}
}
}
List<MeshTermCount> meshTermCounts = new ArrayList<>(meshCount.size());
for (Map.Entry<String, Long> entry : meshCount.entrySet()) {
MeshTermCount meshTermCount = new MeshTermCount();
meshTermCount.setMesh(entry.getKey());
meshTermCount.setCount(entry.getValue());
meshTermCounts.add(meshTermCount);
}
cluster.setMeshTermCounts(meshTermCounts);
}
// Evidence - Gold standard is used to refine judgment of ReCiter
if (strategyParameters.isUseGoldStandardEvidence()) {
Set<Long> selectedClusterIds = clusterSelector.getSelectedClusterIds();
List<ReCiterArticle> goldStandardArticles = new ArrayList<>();
for (ReCiterCluster cluster : clusterer.getClusters().values()) {
if (selectedClusterIds.contains(cluster.getClusterID())) {
Iterator<ReCiterArticle> itr = cluster.getArticleCluster().iterator();
while (itr.hasNext()) {
ReCiterArticle reCiterArticle = itr.next();
if (reCiterArticle.getGoldStandard() == 0) {
goldStandardArticles.add(reCiterArticle);
}
itr.remove();
}
}
}
if (!goldStandardArticles.isEmpty()) {
ReCiterCluster rejectedCluster = new ReCiterCluster();
for (ReCiterArticle reject : goldStandardArticles) {
rejectedCluster.add(reject);
}
clusterer.getClusters().put(rejectedCluster.getClusterID(), rejectedCluster);
}
}
EngineOutput engineOutput = new EngineOutput();
engineOutput.setAnalysis(analysis);
List<ReCiterCluster> reCiterClusters = new ArrayList<>();
for (ReCiterCluster cluster : clusterer.getClusters().values()) {
// set cluster's selected field to true if this cluster has been selected.
if (clusterSelector.getSelectedClusterIds().contains(cluster.getClusterID())) {
cluster.setSelected(true);
}
reCiterClusters.add(cluster);
}
engineOutput.setReCiterClusters(reCiterClusters);
ReCiterFeatureGenerator reCiterFeatureGenerator = new ReCiterFeatureGenerator();
ReCiterFeature reCiterFeature = reCiterFeatureGenerator.computeFeatures("test", clusterer, clusterSelector, parameters.getKnownPmids(), analysis);
engineOutput.setReCiterFeature(reCiterFeature);
return engineOutput;
}
}
| Added rejectedPmid to compute function | src/main/java/reciter/engine/ReCiterEngine.java | Added rejectedPmid to compute function |
|
Java | apache-2.0 | 8c6f9111e7a37d6ff1ee47d85b54482a5578fa19 | 0 | SurveyMan/SMPy,SurveyMan/SMPy | package system.mturk.generators;
import com.googlecode.htmlcompressor.compressor.HtmlCompressor;
import csv.CSVLexer;
import csv.CSVParser;
import org.apache.log4j.Logger;
import survey.*;
import system.Library;
import system.mturk.MturkLibrary;
import utils.Gensym;
import utils.Slurpie;
import java.io.*;
import java.net.MalformedURLException;
import java.util.Arrays;
public class HTML {
private static final Logger LOGGER = Logger.getLogger("system.mturk");
public static String htmlFileName = "";
public static final String[] IMAGE = {"jpg", "jpeg", "png"};
public static final String[] VIDEO = {"ogv", "ogg", "mp4"};
public static final String[] AUDIO = {"oga", "wav", "mp3"};
public static final String[] PAGE = {"html", "htm"};
private static String getMediaTag(String ext) {
ext = ext.toLowerCase();
if (Arrays.asList(VIDEO).contains(ext))
return "video";
else if (Arrays.asList(AUDIO).contains(ext))
return "audio";
else if (Arrays.asList(PAGE).contains(ext))
return "page";
else if (Arrays.asList(IMAGE).contains(ext))
return "image";
else return "";
}
protected static String stringify(Component c) throws SurveyException {
if (c instanceof StringComponent)
return CSVLexer.xmlChars2HTML(((StringComponent) c).data);
else {
String url = CSVLexer.xmlChars2HTML(((URLComponent) c).data.toExternalForm());
String ext = url.substring(url.lastIndexOf(".")+1);
String tag = getMediaTag(ext);
if (tag.equals(""))
return String.format("<embed src=\"%s\" id=\"%s\">", url, c.cid);
else if (tag.equals("page"))
return "";
else if (tag.equals("image"))
return String.format("<img src=\"%s\" id=\"%s\" />", url, c.cid);
else return String.format("<%1$s controls preload=\"none\" src=\"%2$s\" type=\"%1$s/%3$s\" id=\"%4$s\"></%1$s>", tag, url, ext, c.cid);
}
}
private static String stringify(Question q) throws SurveyException, MalformedURLException {
StringBuilder retval = new StringBuilder();
for (Component c : q.data)
retval.append(String.format("%s <br />\r\n"
, stringify(c)));
retval.append("<p></p>");
boolean skip = MturkLibrary.props.getProperty("canskip", "").equals("true");
retval.append(String.format("<br><input type=\"button\" value=\"Prev\" id=\"prev_%1$s\" onclick=\"showPrevQuestion('%1$s')\" %2$s>", q.quid, skip?"":"hidden"));
retval.append(String.format("<input type=\"button\" value=\"Next\" id=\"next_%1$s\" %2$s >"
, q.quid
, (skip || q.freetext || !(q.freetext || q.exclusive || q.ordered || q.perturb )) ?
String.format("onclick=\"showNextQuestion('%s')\"", q.quid) :
"hidden"));
if (!skip) retval.append(String.format("<input type=\"submit\" id=\"submit_%s\">", q.quid));
return retval.toString();
}
private static String stringify(Survey survey) throws SurveyException, MalformedURLException {
StringBuilder retval = new StringBuilder();
Question[] questions = survey.getQuestionsByIndex();
for (int i = 0; i < questions.length; i++)
retval.append(String.format("<div name=\"question\" id=\"%s\">%s%s</div>"
, questions[i].quid
, stringify(questions[i])
, (MturkLibrary.props.getProperty("canskip","").equals("true") && i==questions.length-1) ?
String.format("<input type=\"submit\" id=\"submit_%s\">", questions[i].quid) : ""));
return retval.toString();
}
private static String stringifyPreview(Component c) throws SurveyException {
String baseString = stringify(c);
return String.format("<div id=\"preview\" %s>%s</div>"
, (c instanceof URLComponent) ? String.format("onload=\"loadPreview();\""
, "#preview"
, ((URLComponent) c).data.toExternalForm())
: ""
, (c instanceof StringComponent) ? CSVLexer.htmlChars2XML(baseString) : "");
}
public static void spitHTMLToFile(String html, Survey survey) throws IOException {
htmlFileName = String.format("%s%slogs%s%s_%s_%s.html"
, (new File("")).getAbsolutePath()
, Library.fileSep
, Library.fileSep
, survey.sourceName
, survey.sid
, Library.TIME);
BufferedWriter bw = new BufferedWriter(new FileWriter(htmlFileName));
bw.write(html);
bw.close();
}
public static String getHTMLString(Survey survey) throws SurveyException{
String html = "";
try {
Component preview = CSVParser.parseComponent(CSVParser.stripQuots(MturkLibrary.props.getProperty("splashpage", "").trim()).trim());
html = String.format(Slurpie.slurp(MturkLibrary.HTMLSKELETON)
, survey.encoding
, JS.getJSString(survey, preview)
, stringifyPreview(preview)
, stringify(survey)
, MturkLibrary.EXTERNAL_HIT);
} catch (FileNotFoundException ex) {
LOGGER.fatal(ex);
System.exit(-1);
} catch (IOException ex) {
LOGGER.fatal(ex);
System.exit(-1);
}
try{
spitHTMLToFile(html, survey);
} catch (IOException io) {
LOGGER.warn(io);
}
return html;
//return (new HtmlCompressor()).compress(html);
}
}
class UnknownMediaExtension extends SurveyException {
public UnknownMediaExtension(String msg){
super(String.format("Unknown media extension (%s).", msg));
}
}
| src/main/java/system/mturk/generators/HTML.java | package system.mturk.generators;
import com.googlecode.htmlcompressor.compressor.HtmlCompressor;
import csv.CSVLexer;
import csv.CSVParser;
import org.apache.log4j.Logger;
import survey.*;
import system.Library;
import system.mturk.MturkLibrary;
import utils.Gensym;
import utils.Slurpie;
import java.io.*;
import java.net.MalformedURLException;
import java.util.Arrays;
public class HTML {
private static final Logger LOGGER = Logger.getLogger("system.mturk");
public static String htmlFileName = "";
public static final String[] IMAGE = {"jpg"};
public static final String[] VIDEO = {"ogv", "ogg", "mp4"};
public static final String[] AUDIO = {"oga", "wav", "mp3"};
public static final String[] PAGE = {"html", "htm"};
private static String getMediaTag(String ext) {
if (Arrays.asList(VIDEO).contains(ext))
return "video";
else if (Arrays.asList(AUDIO).contains(ext))
return "audio";
else if (Arrays.asList(PAGE).contains(ext))
return "page";
else if (Arrays.asList(IMAGE).contains(ext))
return "image";
else return "";
}
protected static String stringify(Component c) throws SurveyException {
if (c instanceof StringComponent)
return CSVLexer.xmlChars2HTML(((StringComponent) c).data);
else {
String url = CSVLexer.xmlChars2HTML(((URLComponent) c).data.toExternalForm());
String ext = url.substring(url.lastIndexOf(".")+1);
String tag = getMediaTag(ext);
if (tag.equals(""))
return String.format("<embed src=\"%s\" id=\"%s\">", url, c.cid);
else if (tag.equals("page"))
return "";
else if (tag.equals("image"))
return String.format("<img src=\"%s\" id=\"%s\" />", url, c.cid);
else return String.format("<%1$s controls preload=\"none\" src=\"%2$s\" type=\"%1$s/%3$s\" id=\"%4$s\"></%1$s>", tag, url, ext, c.cid);
}
}
private static String stringify(Question q) throws SurveyException, MalformedURLException {
StringBuilder retval = new StringBuilder();
for (Component c : q.data)
retval.append(String.format("%s <br />\r\n"
, stringify(c)));
retval.append("<p></p>");
boolean skip = MturkLibrary.props.getProperty("canskip", "").equals("true");
retval.append(String.format("<br><input type=\"button\" value=\"Prev\" id=\"prev_%1$s\" onclick=\"showPrevQuestion('%1$s')\" %2$s>", q.quid, skip?"":"hidden"));
retval.append(String.format("<input type=\"button\" value=\"Next\" id=\"next_%1$s\" %2$s >"
, q.quid
, (skip || q.freetext || !(q.freetext || q.exclusive || q.ordered || q.perturb )) ?
String.format("onclick=\"showNextQuestion('%s')\"", q.quid) :
"hidden"));
if (!skip) retval.append(String.format("<input type=\"submit\" id=\"submit_%s\">", q.quid));
return retval.toString();
}
private static String stringify(Survey survey) throws SurveyException, MalformedURLException {
StringBuilder retval = new StringBuilder();
Question[] questions = survey.getQuestionsByIndex();
for (int i = 0; i < questions.length; i++)
retval.append(String.format("<div name=\"question\" id=\"%s\">%s%s</div>"
, questions[i].quid
, stringify(questions[i])
, (MturkLibrary.props.getProperty("canskip","").equals("true") && i==questions.length-1) ?
String.format("<input type=\"submit\" id=\"submit_%s\">", questions[i].quid) : ""));
return retval.toString();
}
private static String stringifyPreview(Component c) throws SurveyException {
String baseString = stringify(c);
return String.format("<div id=\"preview\" %s>%s</div>"
, (c instanceof URLComponent) ? String.format("onload=\"loadPreview();\""
, "#preview"
, ((URLComponent) c).data.toExternalForm())
: ""
, (c instanceof StringComponent) ? CSVLexer.htmlChars2XML(baseString) : "");
}
public static void spitHTMLToFile(String html, Survey survey) throws IOException {
htmlFileName = String.format("%s%slogs%s%s_%s_%s.html"
, (new File("")).getAbsolutePath()
, Library.fileSep
, Library.fileSep
, survey.sourceName
, survey.sid
, Library.TIME);
BufferedWriter bw = new BufferedWriter(new FileWriter(htmlFileName));
bw.write(html);
bw.close();
}
public static String getHTMLString(Survey survey) throws SurveyException{
String html = "";
try {
Component preview = CSVParser.parseComponent(CSVParser.stripQuots(MturkLibrary.props.getProperty("splashpage", "").trim()).trim());
html = String.format(Slurpie.slurp(MturkLibrary.HTMLSKELETON)
, survey.encoding
, JS.getJSString(survey, preview)
, stringifyPreview(preview)
, stringify(survey)
, MturkLibrary.EXTERNAL_HIT);
} catch (FileNotFoundException ex) {
LOGGER.fatal(ex);
System.exit(-1);
} catch (IOException ex) {
LOGGER.fatal(ex);
System.exit(-1);
}
try{
spitHTMLToFile(html, survey);
} catch (IOException io) {
LOGGER.warn(io);
}
return html;
//return (new HtmlCompressor()).compress(html);
}
}
class UnknownMediaExtension extends SurveyException {
public UnknownMediaExtension(String msg){
super(String.format("Unknown media extension (%s).", msg));
}
}
| updated media tag check to handle upper and lower case
| src/main/java/system/mturk/generators/HTML.java | updated media tag check to handle upper and lower case |
|
Java | apache-2.0 | db01d3ea378e6c6da545aa8d64f7f3d73ea925ed | 0 | tvbarthel/BlurDialogFragment,bobxie/BlurDialogFragment,vamsirajendra/BlurDialogFragment,MaTriXy/BlurDialogFragment,liuzwei/BlurDialogFragment,peterdocter/BlurDialogFragment,skyfe79/BlurDialogFragment,zh-kevin/BlurDialogFragment,gk23/BlurDialogFragment,flyou/BlurDialogFragment,ajju4455/BlurDialogFragment,tommytcchan/BlurDialogFragment,Sshah88/BlurDialogFragment,liyi828328/BlurDialogFragment,yulongxiao/BlurDialogFragment,simple88/BlurDialogFragment,kzganesan/BlurDialogFragment,wangkang0627/BlurDialogFragment | package fr.tvbarthel.lib.blurdialogfragment;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
/**
* Encapsulate the whole behaviour to provide a blur effect on a DialogFragment.
* <p/>
* All the screen behind the dialog will be blurred except the action bar.
* <p/>
* Simply linked all methods to the matching lifecycle ones.
*/
class BlurDialogEngine {
/**
* Since image is going to be blurred, we don't care about resolution.
* Down scale factor to reduce blurring time and memory allocation.
*/
static final float DEFAULT_BLUR_DOWN_SCALE_FACTOR = 4.0f;
/**
* Radius used to blur the background
*/
static final int DEFAULT_BLUR_RADIUS = 8;
/**
* Default dimming policy.
*/
static final boolean DEFAULT_DIMMING_POLICY = false;
/**
* Default debug policy.
*/
static final boolean DEFAULT_DEBUG_POLICY = false;
/**
* Log cat
*/
private static final String TAG = BlurDialogEngine.class.getSimpleName();
/**
* Image view used to display blurred background.
*/
private ImageView mBlurredBackgroundView;
/**
* Layout params used to add blurred background.
*/
private FrameLayout.LayoutParams mBlurredBackgroundLayoutParams;
/**
* Task used to capture screen and blur it.
*/
private BlurAsyncTask mBluringTask;
/**
* Used to enable or disable debug mod.
*/
private boolean mDebugEnable = false;
/**
* Factor used to down scale background. High quality isn't necessary
* since the background will be blurred.
*/
private float mDownScaleFactor = DEFAULT_BLUR_DOWN_SCALE_FACTOR;
/**
* Radius used for fast blur algorithm.
*/
private int mBlurRadius = DEFAULT_BLUR_RADIUS;
/**
* Holding activity.
*/
private Activity mHoldingActivity;
/**
* Allow to use a toolbar without set it as action bar.
*/
private Toolbar mToolbar;
/**
* Duration used to animate in and out the blurred image.
* <p/>
* In milli.
*/
private int mAnimationDuration;
/**
* Constructor.
*
* @param holdingActivity activity which holds the DialogFragment.
*/
public BlurDialogEngine(Activity holdingActivity) {
mHoldingActivity = holdingActivity;
mAnimationDuration = holdingActivity.getResources().getInteger(R.integer.blur_dialog_animation_duration);
}
/**
* Resume the engine.
*
* @param retainedInstance use getRetainInstance.
*/
public void onResume(boolean retainedInstance) {
if (mBlurredBackgroundView == null || retainedInstance) {
mBluringTask = new BlurAsyncTask();
mBluringTask.execute();
}
}
/**
* Must be linked to the original lifecycle.
*/
public void onDismiss() {
//remove blurred background and clear memory, could be null if dismissed before blur effect
//processing ends
if (mBlurredBackgroundView != null) {
mBlurredBackgroundView
.animate()
.alpha(0f)
.setDuration(mAnimationDuration)
.setInterpolator(new AccelerateInterpolator())
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
removeBlurredView();
}
@Override
public void onAnimationCancel(Animator animation) {
super.onAnimationCancel(animation);
removeBlurredView();
}
}).start();
}
//cancel async task
mBluringTask.cancel(true);
mBluringTask = null;
}
/**
* Must be linked to the original lifecycle.
*/
public void onDestroy() {
mHoldingActivity = null;
}
/**
* Enable / disable debug mode.
* <p/>
* LogCat and graphical information directly on blurred screen.
*
* @param enable true to display log in LogCat.
*/
public void debug(boolean enable) {
mDebugEnable = enable;
}
/**
* Apply custom down scale factor.
* <p/>
* By default down scale factor is set to
* {@link BlurDialogEngine#DEFAULT_BLUR_DOWN_SCALE_FACTOR}
* <p/>
* Higher down scale factor will increase blurring speed but reduce final rendering quality.
*
* @param factor customized down scale factor, must be at least 1.0 ( no down scale applied )
*/
public void setDownScaleFactor(float factor) {
if (factor >= 1.0f) {
mDownScaleFactor = factor;
} else {
mDownScaleFactor = 1.0f;
}
}
/**
* Apply custom blur radius.
* <p/>
* By default blur radius is set to
* {@link BlurDialogEngine#DEFAULT_BLUR_RADIUS}
*
* @param radius custom radius used to blur.
*/
public void setBlurRadius(int radius) {
if (radius >= 0) {
mBlurRadius = radius;
} else {
mBlurRadius = 0;
}
}
/**
* Set a toolbar which isn't set as action bar.
*
* @param toolbar toolbar.
*/
public void setToolbar(Toolbar toolbar) {
mToolbar = toolbar;
}
/**
* Blur the given bitmap and add it to the activity.
*
* @param bkg should be a bitmap of the background.
* @param view background view.
*/
private void blur(Bitmap bkg, View view) {
long startMs = System.currentTimeMillis();
//define layout params to the previous imageView in order to match its parent
mBlurredBackgroundLayoutParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
);
//overlay used to build scaled preview and blur background
Bitmap overlay = null;
//evaluate top offset due to action bar
int actionBarHeight = getActionBarHeight();
//evaluate top offset due to status bar
int statusBarHeight = 0;
if ((mHoldingActivity.getWindow().getAttributes().flags
& WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0) {
//not in fullscreen mode
statusBarHeight = getStatusBarHeight();
}
final int topOffset = actionBarHeight + statusBarHeight;
final int bottomOffset = getNavigationBarOffset();
//add offset to the source boundaries since we don't want to blur actionBar pixels
Rect srcRect = new Rect(
0,
topOffset,
bkg.getWidth(),
bkg.getHeight() - bottomOffset
);
//in order to keep the same ratio as the one which will be used for rendering, also
//add the offset to the overlay.
double height = Math.ceil((view.getHeight() - topOffset - bottomOffset) / mDownScaleFactor);
double width = Math.ceil((view.getWidth() * height / (view.getHeight() - topOffset - bottomOffset)));
overlay = Bitmap.createBitmap((int) width, (int) height, Bitmap.Config.RGB_565);
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
|| mHoldingActivity instanceof ActionBarActivity) {
//add offset as top margin since actionBar height must also considered when we display
// the blurred background. Don't want to draw on the actionBar.
mBlurredBackgroundLayoutParams.setMargins(0, actionBarHeight, 0, 0);
mBlurredBackgroundLayoutParams.gravity = Gravity.TOP;
}
} catch (NoClassDefFoundError e) {
// no dependency to appcompat, that means no additional top offset due to actionBar.
mBlurredBackgroundLayoutParams.setMargins(0, 0, 0, 0);
}
// check if status bar is translucent.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
&& isStatusBarTranslucent()) {
// add the status bar height as top margin.
mBlurredBackgroundLayoutParams.setMargins(0
, mBlurredBackgroundLayoutParams.topMargin + statusBarHeight, 0, 0);
}
//scale and draw background view on the canvas overlay
Canvas canvas = new Canvas(overlay);
Paint paint = new Paint();
paint.setFlags(Paint.FILTER_BITMAP_FLAG);
//build drawing destination boundaries
final RectF destRect = new RectF(0, 0, overlay.getWidth(), overlay.getHeight());
//draw background from source area in source background to the destination area
// on the overlay
canvas.drawBitmap(bkg, srcRect, destRect, paint);
//apply fast blur on overlay
overlay = FastBlurHelper.doBlur(overlay, mBlurRadius, true);
if (mDebugEnable) {
String blurTime = (System.currentTimeMillis() - startMs) + " ms";
//display information in LogCat
Log.d(TAG, "Radius : " + mBlurRadius);
Log.d(TAG, "Down Scale Factor : " + mDownScaleFactor);
Log.d(TAG, "Blurred achieved in : " + blurTime);
Log.d(TAG, "Allocation : " + bkg.getRowBytes() + "ko (screen capture) + "
+ overlay.getRowBytes() + "ko (FastBlur)");
//display blurring time directly on screen
Rect bounds = new Rect();
Canvas canvas1 = new Canvas(overlay);
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
paint.setTextSize(20.0f);
paint.getTextBounds(blurTime, 0, blurTime.length(), bounds);
canvas1.drawText(blurTime, 2, bounds.height(), paint);
}
//set bitmap in an image view for final rendering
mBlurredBackgroundView = new ImageView(mHoldingActivity);
mBlurredBackgroundView.setScaleType(ImageView.ScaleType.CENTER_CROP);
mBlurredBackgroundView.setImageDrawable(new BitmapDrawable(mHoldingActivity.getResources(), overlay));
}
/**
* Retrieve action bar height.
*
* @return action bar height in px.
*/
private int getActionBarHeight() {
int actionBarHeight = 0;
try {
if (mToolbar != null) {
actionBarHeight = mToolbar.getHeight();
} else if (mHoldingActivity instanceof ActionBarActivity) {
ActionBar supportActionBar
= ((ActionBarActivity) mHoldingActivity).getSupportActionBar();
if (supportActionBar != null) {
actionBarHeight = supportActionBar.getHeight();
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
android.app.ActionBar actionBar = mHoldingActivity.getActionBar();
if (actionBar != null) {
actionBarHeight = actionBar.getHeight();
}
}
} catch (NoClassDefFoundError e) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
android.app.ActionBar actionBar = mHoldingActivity.getActionBar();
if (actionBar != null) {
actionBarHeight = actionBar.getHeight();
}
}
}
return actionBarHeight;
}
/**
* retrieve status bar height in px
*
* @return status bar height in px
*/
private int getStatusBarHeight() {
int result = 0;
int resourceId = mHoldingActivity.getResources()
.getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = mHoldingActivity.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
/**
* Retrieve offset introduce by the navigation bar.
*
* @return bottom offset due to navigation bar.
*/
private int getNavigationBarOffset() {
int result = 0;
Resources resources = mHoldingActivity.getResources();
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP
&& resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
result = resources.getDimensionPixelSize(resourceId);
}
}
return result;
}
/**
* Used to check if the status bar is translucent.
*
* @return true if the status bar is translucent.
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
private boolean isStatusBarTranslucent() {
TypedValue typedValue = new TypedValue();
int[] attribute = new int[]{android.R.attr.windowTranslucentStatus};
TypedArray array = mHoldingActivity.obtainStyledAttributes(typedValue.resourceId, attribute);
return array.getBoolean(0, false);
}
/**
* Removed the blurred view from the view hierarchy.
*/
private void removeBlurredView() {
if (mBlurredBackgroundView != null) {
ViewGroup parent = (ViewGroup) mBlurredBackgroundView.getParent();
if (parent != null) {
parent.removeView(mBlurredBackgroundView);
}
mBlurredBackgroundView = null;
}
}
/**
* Async task used to process blur out of ui thread
*/
private class BlurAsyncTask extends AsyncTask<Void, Void, Void> {
private Bitmap mBackground;
private View mBackgroundView;
@Override
protected void onPreExecute() {
super.onPreExecute();
mBackgroundView = mHoldingActivity.getWindow().getDecorView();
//retrieve background view, must be achieved on ui thread since
//only the original thread that created a view hierarchy can touch its views.
Rect rect = new Rect();
mBackgroundView.getWindowVisibleDisplayFrame(rect);
mBackgroundView.destroyDrawingCache();
mBackgroundView.setDrawingCacheEnabled(true);
mBackgroundView.buildDrawingCache(true);
mBackground = mBackgroundView.getDrawingCache(true);
/**
* After rotation, the DecorView has no height and no width. Therefore
* .getDrawingCache() return null. That's why we have to force measure and layout.
*/
if (mBackground == null) {
mBackgroundView.measure(
View.MeasureSpec.makeMeasureSpec(rect.width(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(rect.height(), View.MeasureSpec.EXACTLY)
);
mBackgroundView.layout(0, 0, mBackgroundView.getMeasuredWidth(),
mBackgroundView.getMeasuredHeight());
mBackgroundView.destroyDrawingCache();
mBackgroundView.setDrawingCacheEnabled(true);
mBackgroundView.buildDrawingCache(true);
mBackground = mBackgroundView.getDrawingCache(true);
}
}
@Override
protected Void doInBackground(Void... params) {
//process to the blue
blur(mBackground, mBackgroundView);
//clear memory
mBackground.recycle();
mBackgroundView.destroyDrawingCache();
mBackgroundView.setDrawingCacheEnabled(false);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mBlurredBackgroundView.setAlpha(0f);
mHoldingActivity.getWindow().addContentView(
mBlurredBackgroundView,
mBlurredBackgroundLayoutParams
);
mBlurredBackgroundView
.animate()
.alpha(1f)
.setDuration(mAnimationDuration)
.setInterpolator(new LinearInterpolator())
.start();
mBackgroundView = null;
mBackground = null;
}
}
}
| lib/src/main/java/fr/tvbarthel/lib/blurdialogfragment/BlurDialogEngine.java | package fr.tvbarthel.lib.blurdialogfragment;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
/**
* Encapsulate the whole behaviour to provide a blur effect on a DialogFragment.
* <p/>
* All the screen behind the dialog will be blurred except the action bar.
* <p/>
* Simply linked all methods to the matching lifecycle ones.
*/
class BlurDialogEngine {
/**
* Since image is going to be blurred, we don't care about resolution.
* Down scale factor to reduce blurring time and memory allocation.
*/
static final float DEFAULT_BLUR_DOWN_SCALE_FACTOR = 4.0f;
/**
* Radius used to blur the background
*/
static final int DEFAULT_BLUR_RADIUS = 8;
/**
* Default dimming policy.
*/
static final boolean DEFAULT_DIMMING_POLICY = false;
/**
* Default debug policy.
*/
static final boolean DEFAULT_DEBUG_POLICY = false;
/**
* Log cat
*/
private static final String TAG = BlurDialogEngine.class.getSimpleName();
/**
* Image view used to display blurred background.
*/
private ImageView mBlurredBackgroundView;
/**
* Layout params used to add blurred background.
*/
private FrameLayout.LayoutParams mBlurredBackgroundLayoutParams;
/**
* Task used to capture screen and blur it.
*/
private BlurAsyncTask mBluringTask;
/**
* Used to enable or disable debug mod.
*/
private boolean mDebugEnable = false;
/**
* Factor used to down scale background. High quality isn't necessary
* since the background will be blurred.
*/
private float mDownScaleFactor = DEFAULT_BLUR_DOWN_SCALE_FACTOR;
/**
* Radius used for fast blur algorithm.
*/
private int mBlurRadius = DEFAULT_BLUR_RADIUS;
/**
* Holding activity.
*/
private Activity mHoldingActivity;
/**
* Allow to use a toolbar without set it as action bar.
*/
private Toolbar mToolbar;
/**
* Duration used to animate in and out the blurred image.
* <p/>
* In milli.
*/
private int mAnimationDuration;
/**
* Constructor.
*
* @param holdingActivity activity which holds the DialogFragment.
*/
public BlurDialogEngine(Activity holdingActivity) {
mHoldingActivity = holdingActivity;
mAnimationDuration = holdingActivity.getResources().getInteger(R.integer.blur_dialog_animation_duration);
}
/**
* Resume the engine.
*
* @param retainedInstance use getRetainInstance.
*/
public void onResume(boolean retainedInstance) {
if (mBlurredBackgroundView == null || retainedInstance) {
mBluringTask = new BlurAsyncTask();
mBluringTask.execute();
}
}
/**
* Must be linked to the original lifecycle.
*/
public void onDismiss() {
//remove blurred background and clear memory, could be null if dismissed before blur effect
//processing ends
if (mBlurredBackgroundView != null) {
mBlurredBackgroundView
.animate()
.alpha(0f)
.setDuration(mAnimationDuration)
.setInterpolator(new AccelerateInterpolator())
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
removeBlurredView();
}
@Override
public void onAnimationCancel(Animator animation) {
super.onAnimationCancel(animation);
removeBlurredView();
}
}).start();
}
//cancel async task
mBluringTask.cancel(true);
mBluringTask = null;
}
/**
* Must be linked to the original lifecycle.
*/
public void onDestroy() {
mHoldingActivity = null;
}
/**
* Enable / disable debug mode.
* <p/>
* LogCat and graphical information directly on blurred screen.
*
* @param enable true to display log in LogCat.
*/
public void debug(boolean enable) {
mDebugEnable = enable;
}
/**
* Apply custom down scale factor.
* <p/>
* By default down scale factor is set to
* {@link BlurDialogEngine#DEFAULT_BLUR_DOWN_SCALE_FACTOR}
* <p/>
* Higher down scale factor will increase blurring speed but reduce final rendering quality.
*
* @param factor customized down scale factor, must be at least 1.0 ( no down scale applied )
*/
public void setDownScaleFactor(float factor) {
if (factor >= 1.0f) {
mDownScaleFactor = factor;
} else {
mDownScaleFactor = 1.0f;
}
}
/**
* Apply custom blur radius.
* <p/>
* By default blur radius is set to
* {@link BlurDialogEngine#DEFAULT_BLUR_RADIUS}
*
* @param radius custom radius used to blur.
*/
public void setBlurRadius(int radius) {
if (radius >= 0) {
mBlurRadius = radius;
} else {
mBlurRadius = 0;
}
}
/**
* Set a toolbar which isn't set as action bar.
*
* @param toolbar toolbar.
*/
public void setToolbar(Toolbar toolbar) {
mToolbar = toolbar;
}
/**
* Blur the given bitmap and add it to the activity.
*
* @param bkg should be a bitmap of the background.
* @param view background view.
*/
private void blur(Bitmap bkg, View view) {
long startMs = System.currentTimeMillis();
//define layout params to the previous imageView in order to match its parent
mBlurredBackgroundLayoutParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
);
//overlay used to build scaled preview and blur background
Bitmap overlay = null;
//evaluate top offset due to action bar
int actionBarHeight = getActionBarHeight();
//evaluate top offset due to status bar
int statusBarHeight = 0;
if ((mHoldingActivity.getWindow().getAttributes().flags
& WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0) {
//not in fullscreen mode
statusBarHeight = getStatusBarHeight();
}
final int topOffset = actionBarHeight + statusBarHeight;
final int bottomOffset = getNavigationBarOffset();
//add offset to the source boundaries since we don't want to blur actionBar pixels
Rect srcRect = new Rect(
0,
topOffset,
bkg.getWidth(),
bkg.getHeight() - bottomOffset
);
//in order to keep the same ratio as the one which will be used for rendering, also
//add the offset to the overlay.
double height = Math.ceil((view.getHeight() - topOffset - bottomOffset) / mDownScaleFactor);
double width = Math.ceil((view.getWidth() * height / (view.getHeight() - topOffset - bottomOffset)));
overlay = Bitmap.createBitmap((int) width, (int) height, Bitmap.Config.RGB_565);
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
|| mHoldingActivity instanceof ActionBarActivity) {
//add offset as top margin since actionBar height must also considered when we display
// the blurred background. Don't want to draw on the actionBar.
mBlurredBackgroundLayoutParams.setMargins(0, actionBarHeight, 0, 0);
mBlurredBackgroundLayoutParams.gravity = Gravity.TOP;
}
} catch (NoClassDefFoundError e) {
// no dependency to appcompat, that means no additional top offset due to actionBar.
mBlurredBackgroundLayoutParams.setMargins(0, 0, 0, 0);
}
// check if status bar is translucent.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
&& isStatusBarTranslucent()) {
// add the status bar height as top margin.
mBlurredBackgroundLayoutParams.setMargins(0
, mBlurredBackgroundLayoutParams.topMargin + statusBarHeight, 0, 0);
}
//scale and draw background view on the canvas overlay
Canvas canvas = new Canvas(overlay);
Paint paint = new Paint();
paint.setFlags(Paint.FILTER_BITMAP_FLAG);
//build drawing destination boundaries
final RectF destRect = new RectF(0, 0, overlay.getWidth(), overlay.getHeight());
//draw background from source area in source background to the destination area
// on the overlay
canvas.drawBitmap(bkg, srcRect, destRect, paint);
//apply fast blur on overlay
overlay = FastBlurHelper.doBlur(overlay, mBlurRadius, false);
if (mDebugEnable) {
String blurTime = (System.currentTimeMillis() - startMs) + " ms";
//display information in LogCat
Log.d(TAG, "Radius : " + mBlurRadius);
Log.d(TAG, "Down Scale Factor : " + mDownScaleFactor);
Log.d(TAG, "Blurred achieved in : " + blurTime);
Log.d(TAG, "Allocation : " + bkg.getRowBytes() + "ko (screen capture) + "
+ overlay.getRowBytes() + "ko (FastBlur)");
//display blurring time directly on screen
Rect bounds = new Rect();
Canvas canvas1 = new Canvas(overlay);
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
paint.setTextSize(20.0f);
paint.getTextBounds(blurTime, 0, blurTime.length(), bounds);
canvas1.drawText(blurTime, 2, bounds.height(), paint);
}
//set bitmap in an image view for final rendering
mBlurredBackgroundView = new ImageView(mHoldingActivity);
mBlurredBackgroundView.setScaleType(ImageView.ScaleType.CENTER_CROP);
mBlurredBackgroundView.setImageDrawable(new BitmapDrawable(mHoldingActivity.getResources(), overlay));
}
/**
* Retrieve action bar height.
*
* @return action bar height in px.
*/
private int getActionBarHeight() {
int actionBarHeight = 0;
try {
if (mToolbar != null) {
actionBarHeight = mToolbar.getHeight();
} else if (mHoldingActivity instanceof ActionBarActivity) {
ActionBar supportActionBar
= ((ActionBarActivity) mHoldingActivity).getSupportActionBar();
if (supportActionBar != null) {
actionBarHeight = supportActionBar.getHeight();
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
android.app.ActionBar actionBar = mHoldingActivity.getActionBar();
if (actionBar != null) {
actionBarHeight = actionBar.getHeight();
}
}
} catch (NoClassDefFoundError e) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
android.app.ActionBar actionBar = mHoldingActivity.getActionBar();
if (actionBar != null) {
actionBarHeight = actionBar.getHeight();
}
}
}
return actionBarHeight;
}
/**
* retrieve status bar height in px
*
* @return status bar height in px
*/
private int getStatusBarHeight() {
int result = 0;
int resourceId = mHoldingActivity.getResources()
.getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = mHoldingActivity.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
/**
* Retrieve offset introduce by the navigation bar.
*
* @return bottom offset due to navigation bar.
*/
private int getNavigationBarOffset() {
int result = 0;
Resources resources = mHoldingActivity.getResources();
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP
&& resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
result = resources.getDimensionPixelSize(resourceId);
}
}
return result;
}
/**
* Used to check if the status bar is translucent.
*
* @return true if the status bar is translucent.
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
private boolean isStatusBarTranslucent() {
TypedValue typedValue = new TypedValue();
int[] attribute = new int[]{android.R.attr.windowTranslucentStatus};
TypedArray array = mHoldingActivity.obtainStyledAttributes(typedValue.resourceId, attribute);
return array.getBoolean(0, false);
}
/**
* Removed the blurred view from the view hierarchy.
*/
private void removeBlurredView() {
if (mBlurredBackgroundView != null) {
ViewGroup parent = (ViewGroup) mBlurredBackgroundView.getParent();
if (parent != null) {
parent.removeView(mBlurredBackgroundView);
}
mBlurredBackgroundView = null;
}
}
/**
* Async task used to process blur out of ui thread
*/
private class BlurAsyncTask extends AsyncTask<Void, Void, Void> {
private Bitmap mBackground;
private View mBackgroundView;
@Override
protected void onPreExecute() {
super.onPreExecute();
mBackgroundView = mHoldingActivity.getWindow().getDecorView();
//retrieve background view, must be achieved on ui thread since
//only the original thread that created a view hierarchy can touch its views.
Rect rect = new Rect();
mBackgroundView.getWindowVisibleDisplayFrame(rect);
mBackgroundView.destroyDrawingCache();
mBackgroundView.setDrawingCacheEnabled(true);
mBackgroundView.buildDrawingCache(true);
mBackground = mBackgroundView.getDrawingCache(true);
/**
* After rotation, the DecorView has no height and no width. Therefore
* .getDrawingCache() return null. That's why we have to force measure and layout.
*/
if (mBackground == null) {
mBackgroundView.measure(
View.MeasureSpec.makeMeasureSpec(rect.width(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(rect.height(), View.MeasureSpec.EXACTLY)
);
mBackgroundView.layout(0, 0, mBackgroundView.getMeasuredWidth(),
mBackgroundView.getMeasuredHeight());
mBackgroundView.destroyDrawingCache();
mBackgroundView.setDrawingCacheEnabled(true);
mBackgroundView.buildDrawingCache(true);
mBackground = mBackgroundView.getDrawingCache(true);
}
}
@Override
protected Void doInBackground(Void... params) {
//process to the blue
blur(mBackground, mBackgroundView);
//clear memory
mBackground.recycle();
mBackgroundView.destroyDrawingCache();
mBackgroundView.setDrawingCacheEnabled(false);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mBlurredBackgroundView.setAlpha(0f);
mHoldingActivity.getWindow().addContentView(
mBlurredBackgroundView,
mBlurredBackgroundLayoutParams
);
mBlurredBackgroundView
.animate()
.alpha(1f)
.setDuration(mAnimationDuration)
.setInterpolator(new LinearInterpolator())
.start();
mBackgroundView = null;
mBackground = null;
}
}
}
| Re-use the same bitmap and prevent from re-allocating a second bitmap
| lib/src/main/java/fr/tvbarthel/lib/blurdialogfragment/BlurDialogEngine.java | Re-use the same bitmap and prevent from re-allocating a second bitmap |
|
Java | apache-2.0 | 50213a0aede8eaa383a0af558d2cb14ce563aeb1 | 0 | xtern/ignite,endian675/ignite,andrey-kuznetsov/ignite,SomeFire/ignite,voipp/ignite,endian675/ignite,SharplEr/ignite,xtern/ignite,daradurvs/ignite,chandresh-pancholi/ignite,sk0x50/ignite,samaitra/ignite,apache/ignite,NSAmelchev/ignite,ilantukh/ignite,apache/ignite,amirakhmedov/ignite,nizhikov/ignite,voipp/ignite,SharplEr/ignite,psadusumilli/ignite,alexzaitzev/ignite,daradurvs/ignite,alexzaitzev/ignite,apache/ignite,voipp/ignite,SharplEr/ignite,StalkXT/ignite,BiryukovVA/ignite,StalkXT/ignite,voipp/ignite,ptupitsyn/ignite,voipp/ignite,daradurvs/ignite,ascherbakoff/ignite,psadusumilli/ignite,andrey-kuznetsov/ignite,nizhikov/ignite,shroman/ignite,chandresh-pancholi/ignite,irudyak/ignite,vladisav/ignite,vladisav/ignite,daradurvs/ignite,SomeFire/ignite,SomeFire/ignite,shroman/ignite,irudyak/ignite,ptupitsyn/ignite,psadusumilli/ignite,ptupitsyn/ignite,SharplEr/ignite,chandresh-pancholi/ignite,alexzaitzev/ignite,daradurvs/ignite,StalkXT/ignite,SomeFire/ignite,xtern/ignite,andrey-kuznetsov/ignite,irudyak/ignite,BiryukovVA/ignite,StalkXT/ignite,amirakhmedov/ignite,vladisav/ignite,NSAmelchev/ignite,ilantukh/ignite,samaitra/ignite,BiryukovVA/ignite,samaitra/ignite,xtern/ignite,sk0x50/ignite,daradurvs/ignite,nizhikov/ignite,shroman/ignite,NSAmelchev/ignite,NSAmelchev/ignite,nizhikov/ignite,andrey-kuznetsov/ignite,shroman/ignite,SomeFire/ignite,BiryukovVA/ignite,ilantukh/ignite,endian675/ignite,shroman/ignite,NSAmelchev/ignite,ascherbakoff/ignite,psadusumilli/ignite,voipp/ignite,andrey-kuznetsov/ignite,chandresh-pancholi/ignite,BiryukovVA/ignite,SharplEr/ignite,samaitra/ignite,xtern/ignite,SharplEr/ignite,sk0x50/ignite,SomeFire/ignite,ilantukh/ignite,SharplEr/ignite,NSAmelchev/ignite,alexzaitzev/ignite,alexzaitzev/ignite,amirakhmedov/ignite,endian675/ignite,StalkXT/ignite,ptupitsyn/ignite,apache/ignite,sk0x50/ignite,SomeFire/ignite,andrey-kuznetsov/ignite,andrey-kuznetsov/ignite,SharplEr/ignite,endian675/ignite,shroman/ignite,ilantukh/ignite,SomeFire/ignite,voipp/ignite,vladisav/ignite,samaitra/ignite,ilantukh/ignite,alexzaitzev/ignite,xtern/ignite,andrey-kuznetsov/ignite,vladisav/ignite,sk0x50/ignite,ascherbakoff/ignite,chandresh-pancholi/ignite,nizhikov/ignite,BiryukovVA/ignite,BiryukovVA/ignite,amirakhmedov/ignite,xtern/ignite,nizhikov/ignite,sk0x50/ignite,nizhikov/ignite,BiryukovVA/ignite,daradurvs/ignite,amirakhmedov/ignite,voipp/ignite,ptupitsyn/ignite,sk0x50/ignite,BiryukovVA/ignite,nizhikov/ignite,psadusumilli/ignite,alexzaitzev/ignite,samaitra/ignite,daradurvs/ignite,sk0x50/ignite,ascherbakoff/ignite,NSAmelchev/ignite,samaitra/ignite,ptupitsyn/ignite,StalkXT/ignite,irudyak/ignite,SharplEr/ignite,xtern/ignite,ilantukh/ignite,NSAmelchev/ignite,daradurvs/ignite,andrey-kuznetsov/ignite,endian675/ignite,voipp/ignite,chandresh-pancholi/ignite,samaitra/ignite,ascherbakoff/ignite,shroman/ignite,amirakhmedov/ignite,chandresh-pancholi/ignite,apache/ignite,StalkXT/ignite,irudyak/ignite,NSAmelchev/ignite,irudyak/ignite,apache/ignite,alexzaitzev/ignite,apache/ignite,chandresh-pancholi/ignite,BiryukovVA/ignite,ilantukh/ignite,daradurvs/ignite,ascherbakoff/ignite,irudyak/ignite,ascherbakoff/ignite,amirakhmedov/ignite,vladisav/ignite,samaitra/ignite,vladisav/ignite,irudyak/ignite,SomeFire/ignite,ilantukh/ignite,ptupitsyn/ignite,samaitra/ignite,psadusumilli/ignite,irudyak/ignite,SomeFire/ignite,apache/ignite,amirakhmedov/ignite,StalkXT/ignite,shroman/ignite,endian675/ignite,ascherbakoff/ignite,psadusumilli/ignite,sk0x50/ignite,ptupitsyn/ignite,chandresh-pancholi/ignite,amirakhmedov/ignite,nizhikov/ignite,alexzaitzev/ignite,psadusumilli/ignite,apache/ignite,endian675/ignite,ptupitsyn/ignite,ptupitsyn/ignite,vladisav/ignite,StalkXT/ignite,ascherbakoff/ignite,shroman/ignite,ilantukh/ignite,xtern/ignite,shroman/ignite,andrey-kuznetsov/ignite | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.ml.nn.trainers.distributed;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.ignite.Ignite;
import org.apache.ignite.Ignition;
import org.apache.ignite.lang.IgniteBiTuple;
import org.apache.ignite.ml.math.Matrix;
import org.apache.ignite.ml.math.Vector;
import org.apache.ignite.ml.math.functions.IgniteDifferentiableVectorToDoubleFunction;
import org.apache.ignite.ml.math.functions.IgniteFunction;
import org.apache.ignite.ml.math.functions.IgniteSupplier;
import org.apache.ignite.ml.math.util.MatrixUtil;
import org.apache.ignite.ml.optimization.LossFunctions;
import org.apache.ignite.ml.nn.MultilayerPerceptron;
import org.apache.ignite.ml.optimization.SmoothParametrized;
import org.apache.ignite.ml.optimization.updatecalculators.ParameterUpdateCalculator;
import org.apache.ignite.ml.optimization.updatecalculators.RPropParameterUpdate;
import org.apache.ignite.ml.optimization.updatecalculators.RPropUpdateCalculator;
import org.apache.ignite.ml.trainers.group.GroupTrainerCacheKey;
import org.apache.ignite.ml.trainers.group.MetaoptimizerGroupTrainer;
import org.apache.ignite.ml.trainers.group.ResultAndUpdates;
import org.apache.ignite.ml.trainers.group.UpdatesStrategy;
import org.apache.ignite.ml.trainers.group.chain.EntryAndContext;
import org.apache.ignite.ml.util.Utils;
/**
* Update-based distributed training of MLP.
*
* @param <U> Type of update.
*/
public class MLPGroupUpdateTrainer<U extends Serializable> extends
MetaoptimizerGroupTrainer<MLPGroupUpdateTrainerLocalContext,
Void,
MLPGroupTrainingCacheValue,
U,
MultilayerPerceptron,
U,
MultilayerPerceptron,
AbstractMLPGroupUpdateTrainerInput,
MLPGroupUpdateTrainingContext<U>,
ArrayList<U>,
MLPGroupUpdateTrainingLoopData<U>,
U> {
/**
* Loss function.
*/
private final IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> loss;
/**
* Error tolerance.
*/
private final double tolerance;
/**
* Maximal count of global steps.
*/
private final int maxGlobalSteps;
/**
* Synchronize updates between networks every syncPeriod steps.
*/
private final int syncPeriod;
/**
* Function used to reduce updates from different networks (for example, averaging of gradients of all networks).
*/
private final IgniteFunction<List<U>, U> allUpdatesReducer;
/**
* Function used to reduce updates in one training (for example, sum all sequential gradient updates to get one
* gradient update).
*/
private final IgniteFunction<List<U>, U> locStepUpdatesReducer;
/**
* Updates calculator.
*/
private final ParameterUpdateCalculator<? super MultilayerPerceptron, U> updateCalculator;
/**
* Default maximal count of global steps.
*/
private static final int DEFAULT_MAX_GLOBAL_STEPS = 30;
/**
* Default sync rate.
*/
private static final int DEFAULT_SYNC_RATE = 5;
/**
* Default all updates reducer.
*/
private static final IgniteFunction<List<RPropParameterUpdate>, RPropParameterUpdate>
DEFAULT_ALL_UPDATES_REDUCER = RPropParameterUpdate::avg;
/**
* Default local steps updates reducer.
*/
private static final IgniteFunction<List<RPropParameterUpdate>, RPropParameterUpdate>
DEFAULT_LOCAL_STEP_UPDATES_REDUCER = RPropParameterUpdate::sumLocal;
/**
* Default update calculator.
*/
private static final ParameterUpdateCalculator<SmoothParametrized, RPropParameterUpdate>
DEFAULT_UPDATE_CALCULATOR = new RPropUpdateCalculator();
/**
* Default loss function.
*/
private static final IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> DEFAULT_LOSS
= LossFunctions.MSE;
/**
* Construct instance of this class with given parameters.
*
* @param loss Loss function.
* @param ignite Ignite instance.
* @param tolerance Error tolerance.
*/
public MLPGroupUpdateTrainer(int maxGlobalSteps,
int syncPeriod,
IgniteFunction<List<U>, U> allUpdatesReducer,
IgniteFunction<List<U>, U> locStepUpdatesReducer,
ParameterUpdateCalculator<? super MultilayerPerceptron, U> updateCalculator,
IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> loss,
Ignite ignite, double tolerance) {
super(new MLPMetaoptimizer<>(allUpdatesReducer), MLPCache.getOrCreate(ignite), ignite);
this.maxGlobalSteps = maxGlobalSteps;
this.syncPeriod = syncPeriod;
this.allUpdatesReducer = allUpdatesReducer;
this.locStepUpdatesReducer = locStepUpdatesReducer;
this.updateCalculator = updateCalculator;
this.loss = loss;
this.tolerance = tolerance;
}
/**
* Get default {@link MLPGroupUpdateTrainer}.
*
* @param ignite Ignite instance.
* @return Default {@link MLPGroupUpdateTrainer}.
*/
public static MLPGroupUpdateTrainer<RPropParameterUpdate> getDefault(Ignite ignite) {
return new MLPGroupUpdateTrainer<>(DEFAULT_MAX_GLOBAL_STEPS, DEFAULT_SYNC_RATE, DEFAULT_ALL_UPDATES_REDUCER,
DEFAULT_LOCAL_STEP_UPDATES_REDUCER, DEFAULT_UPDATE_CALCULATOR, DEFAULT_LOSS, ignite, 0.01);
}
/** {@inheritDoc} */
@Override protected void init(AbstractMLPGroupUpdateTrainerInput data, UUID trainingUUID) {
super.init(data, trainingUUID);
MLPGroupUpdateTrainerDataCache.getOrCreate(ignite).put(trainingUUID, new MLPGroupUpdateTrainingData<>(
updateCalculator,
syncPeriod,
locStepUpdatesReducer,
data.batchSupplier(),
loss,
tolerance
));
}
/** {@inheritDoc} */
@Override protected IgniteFunction<GroupTrainerCacheKey<Void>, ResultAndUpdates<U>> distributedInitializer(
AbstractMLPGroupUpdateTrainerInput data) {
MultilayerPerceptron initPerceptron = data.mdl();
// For each key put initial network into the cache.
return key -> {
Ignite ignite = Ignition.localIgnite();
U initUpdate = updateCalculator.init(initPerceptron, loss);
return ResultAndUpdates.of(initUpdate).updateCache(MLPCache.getOrCreate(ignite), key,
new MLPGroupTrainingCacheValue(initPerceptron));
};
}
/** {@inheritDoc} */
@Override protected IgniteFunction<EntryAndContext<Void, MLPGroupTrainingCacheValue,
MLPGroupUpdateTrainingContext<U>>, MLPGroupUpdateTrainingLoopData<U>> trainingLoopStepDataExtractor() {
return entryAndContext -> {
MLPGroupUpdateTrainingContext<U> ctx = entryAndContext.context();
Map.Entry<GroupTrainerCacheKey<Void>, MLPGroupTrainingCacheValue> entry = entryAndContext.entry();
MLPGroupUpdateTrainingData<U> data = ctx.data();
return new MLPGroupUpdateTrainingLoopData<>(entry.getValue().perceptron(),
data.updateCalculator(), data.stepsCnt(), data.updateReducer(), ctx.previousUpdate(), entry.getKey(),
data.batchSupplier(), data.loss(), data.tolerance());
};
}
/** {@inheritDoc} */
@Override protected IgniteSupplier<Stream<GroupTrainerCacheKey<Void>>> keysToProcessInTrainingLoop(
MLPGroupUpdateTrainerLocalContext locCtx) {
int trainingsCnt = locCtx.parallelTrainingsCnt();
UUID uuid = locCtx.trainingUUID();
return () -> MLPCache.allKeys(trainingsCnt, uuid);
}
/** {@inheritDoc} */
@Override protected IgniteSupplier<MLPGroupUpdateTrainingContext<U>> remoteContextExtractor(U prevUpdate,
MLPGroupUpdateTrainerLocalContext ctx) {
UUID uuid = ctx.trainingUUID();
return () -> {
MLPGroupUpdateTrainingData<U> data = MLPGroupUpdateTrainerDataCache.getOrCreate(Ignition.localIgnite()).get(uuid);
return new MLPGroupUpdateTrainingContext<>(data, prevUpdate);
};
}
/** {@inheritDoc} */
@Override protected IgniteFunction<MLPGroupUpdateTrainingLoopData<U>, ResultAndUpdates<U>> dataProcessor() {
return data -> {
MultilayerPerceptron mlp = data.mlp();
// Apply previous update.
MultilayerPerceptron newMlp = updateCalculator.update(mlp, data.previousUpdate());
MultilayerPerceptron mlpCp = Utils.copy(newMlp);
ParameterUpdateCalculator<? super MultilayerPerceptron, U> updateCalculator = data.updateCalculator();
IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> loss = data.loss();
// ParameterUpdateCalculator API to have proper way to setting loss.
updateCalculator.init(mlpCp, loss);
// Generate new update.
int steps = data.stepsCnt();
List<U> updates = new ArrayList<>(steps);
U curUpdate = data.previousUpdate();
for (int i = 0; i < steps; i++) {
IgniteBiTuple<Matrix, Matrix> batch = data.batchSupplier().get();
Matrix input = batch.get1();
Matrix truth = batch.get2();
int batchSize = truth.columnSize();
curUpdate = updateCalculator.calculateNewUpdate(mlpCp, curUpdate, i, input, truth);
mlpCp = updateCalculator.update(mlpCp, curUpdate);
updates.add(curUpdate);
Matrix predicted = mlpCp.apply(input);
double err = MatrixUtil.zipFoldByColumns(predicted, truth, (predCol, truthCol) ->
loss.apply(truthCol).apply(predCol)).sum() / batchSize;
if (err < data.tolerance())
break;
}
U accumulatedUpdate = data.getUpdateReducer().apply(updates);
return new ResultAndUpdates<>(accumulatedUpdate).
updateCache(MLPCache.getOrCreate(Ignition.localIgnite()), data.key(),
new MLPGroupTrainingCacheValue(newMlp));
};
}
/** {@inheritDoc} */
@Override protected MLPGroupUpdateTrainerLocalContext<U> initialLocalContext(
AbstractMLPGroupUpdateTrainerInput data, UUID trainingUUID) {
return new MLPGroupUpdateTrainerLocalContext<>(trainingUUID, maxGlobalSteps, allUpdatesReducer,
data.trainingsCount());
}
/** {@inheritDoc} */
@Override protected IgniteSupplier<Stream<GroupTrainerCacheKey<Void>>> finalResultKeys(U data,
MLPGroupUpdateTrainerLocalContext locCtx) {
UUID uuid = locCtx.trainingUUID();
int trainingsCnt = locCtx.parallelTrainingsCnt();
return () -> MLPCache.allKeys(trainingsCnt, uuid);
}
/** {@inheritDoc} */
@Override protected IgniteSupplier<MLPGroupUpdateTrainingContext<U>> extractContextForFinalResultCreation(U data,
MLPGroupUpdateTrainerLocalContext locCtx) {
return () -> null;
}
/** {@inheritDoc} */
@Override protected IgniteFunction<EntryAndContext<Void, MLPGroupTrainingCacheValue,
MLPGroupUpdateTrainingContext<U>>, ResultAndUpdates<MultilayerPerceptron>> finalResultsExtractor() {
return context -> ResultAndUpdates.of(context.entry().getValue().perceptron());
}
/** {@inheritDoc} */
@Override protected IgniteFunction<List<MultilayerPerceptron>, MultilayerPerceptron> finalResultsReducer() {
// Just take any of MLPs since they will be in the same state.
return mlps -> mlps.stream().filter(Objects::nonNull).findFirst().orElse(null);
}
/** {@inheritDoc} */
@Override protected MultilayerPerceptron mapFinalResult(MultilayerPerceptron res,
MLPGroupUpdateTrainerLocalContext locCtx) {
return res;
}
/** {@inheritDoc} */
@Override protected void cleanup(MLPGroupUpdateTrainerLocalContext locCtx) {
MLPGroupUpdateTrainerDataCache.getOrCreate(ignite).remove(locCtx.trainingUUID());
Set<GroupTrainerCacheKey<Void>> toRmv = MLPCache.allKeys(locCtx.parallelTrainingsCnt(), locCtx.trainingUUID()).collect(Collectors.toSet());
MLPCache.getOrCreate(ignite).removeAll(toRmv);
}
/**
* Create new {@link MLPGroupUpdateTrainer} with new maxGlobalSteps value.
*
* @param maxGlobalSteps New maxGlobalSteps value.
* @return New {@link MLPGroupUpdateTrainer} with new maxGlobalSteps value.
*/
public MLPGroupUpdateTrainer<U> withMaxGlobalSteps(int maxGlobalSteps) {
return new MLPGroupUpdateTrainer<>(maxGlobalSteps, syncPeriod, allUpdatesReducer, locStepUpdatesReducer,
updateCalculator, loss, ignite, tolerance);
}
/**
* Create new {@link MLPGroupUpdateTrainer} with new syncPeriod value.
*
* @param syncPeriod New syncPeriod value.
* @return New {@link MLPGroupUpdateTrainer} with new syncPeriod value.
*/
public MLPGroupUpdateTrainer<U> withSyncPeriod(int syncPeriod) {
return new MLPGroupUpdateTrainer<>(maxGlobalSteps, syncPeriod
, allUpdatesReducer, locStepUpdatesReducer, updateCalculator, loss, ignite, tolerance);
}
/**
* Create new {@link MLPGroupUpdateTrainer} with new tolerance.
*
* @param tolerance New tolerance value.
* @return New {@link MLPGroupUpdateTrainer} with new tolerance value.
*/
public MLPGroupUpdateTrainer<U> withTolerance(double tolerance) {
return new MLPGroupUpdateTrainer<>(maxGlobalSteps, syncPeriod, allUpdatesReducer, locStepUpdatesReducer,
updateCalculator, loss, ignite, tolerance);
}
/**
* Create new {@link MLPGroupUpdateTrainer} with new update strategy.
*
* @param stgy New update strategy.
* @return New {@link MLPGroupUpdateTrainer} with new tolerance value.
*/
public <U1 extends Serializable> MLPGroupUpdateTrainer<U1> withUpdateStrategy(UpdatesStrategy<? super MultilayerPerceptron, U1> stgy) {
return new MLPGroupUpdateTrainer<>(maxGlobalSteps, syncPeriod, stgy.allUpdatesReducer(), stgy.locStepUpdatesReducer(),
stgy.getUpdatesCalculator(), loss, ignite, tolerance);
}
}
| modules/ml/src/main/java/org/apache/ignite/ml/nn/trainers/distributed/MLPGroupUpdateTrainer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.ml.nn.trainers.distributed;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Stream;
import org.apache.ignite.Ignite;
import org.apache.ignite.Ignition;
import org.apache.ignite.lang.IgniteBiTuple;
import org.apache.ignite.ml.math.Matrix;
import org.apache.ignite.ml.math.Vector;
import org.apache.ignite.ml.math.functions.IgniteDifferentiableVectorToDoubleFunction;
import org.apache.ignite.ml.math.functions.IgniteFunction;
import org.apache.ignite.ml.math.functions.IgniteSupplier;
import org.apache.ignite.ml.math.util.MatrixUtil;
import org.apache.ignite.ml.optimization.LossFunctions;
import org.apache.ignite.ml.nn.MultilayerPerceptron;
import org.apache.ignite.ml.optimization.SmoothParametrized;
import org.apache.ignite.ml.optimization.updatecalculators.ParameterUpdateCalculator;
import org.apache.ignite.ml.optimization.updatecalculators.RPropParameterUpdate;
import org.apache.ignite.ml.optimization.updatecalculators.RPropUpdateCalculator;
import org.apache.ignite.ml.trainers.group.GroupTrainerCacheKey;
import org.apache.ignite.ml.trainers.group.MetaoptimizerGroupTrainer;
import org.apache.ignite.ml.trainers.group.ResultAndUpdates;
import org.apache.ignite.ml.trainers.group.UpdatesStrategy;
import org.apache.ignite.ml.trainers.group.chain.EntryAndContext;
import org.apache.ignite.ml.util.Utils;
/**
* Update-based distributed training of MLP.
*
* @param <U> Type of update.
*/
public class MLPGroupUpdateTrainer<U extends Serializable> extends
MetaoptimizerGroupTrainer<MLPGroupUpdateTrainerLocalContext,
Void,
MLPGroupTrainingCacheValue,
U,
MultilayerPerceptron,
U,
MultilayerPerceptron,
AbstractMLPGroupUpdateTrainerInput,
MLPGroupUpdateTrainingContext<U>,
ArrayList<U>,
MLPGroupUpdateTrainingLoopData<U>,
U> {
/**
* Loss function.
*/
private final IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> loss;
/**
* Error tolerance.
*/
private final double tolerance;
/**
* Maximal count of global steps.
*/
private final int maxGlobalSteps;
/**
* Synchronize updates between networks every syncPeriod steps.
*/
private final int syncPeriod;
/**
* Function used to reduce updates from different networks (for example, averaging of gradients of all networks).
*/
private final IgniteFunction<List<U>, U> allUpdatesReducer;
/**
* Function used to reduce updates in one training (for example, sum all sequential gradient updates to get one
* gradient update).
*/
private final IgniteFunction<List<U>, U> locStepUpdatesReducer;
/**
* Updates calculator.
*/
private final ParameterUpdateCalculator<? super MultilayerPerceptron, U> updateCalculator;
/**
* Default maximal count of global steps.
*/
private static final int DEFAULT_MAX_GLOBAL_STEPS = 30;
/**
* Default sync rate.
*/
private static final int DEFAULT_SYNC_RATE = 5;
/**
* Default all updates reducer.
*/
private static final IgniteFunction<List<RPropParameterUpdate>, RPropParameterUpdate>
DEFAULT_ALL_UPDATES_REDUCER = RPropParameterUpdate::avg;
/**
* Default local steps updates reducer.
*/
private static final IgniteFunction<List<RPropParameterUpdate>, RPropParameterUpdate>
DEFAULT_LOCAL_STEP_UPDATES_REDUCER = RPropParameterUpdate::sumLocal;
/**
* Default update calculator.
*/
private static final ParameterUpdateCalculator<SmoothParametrized, RPropParameterUpdate>
DEFAULT_UPDATE_CALCULATOR = new RPropUpdateCalculator();
/**
* Default loss function.
*/
private static final IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> DEFAULT_LOSS
= LossFunctions.MSE;
/**
* Construct instance of this class with given parameters.
*
* @param loss Loss function.
* @param ignite Ignite instance.
* @param tolerance Error tolerance.
*/
public MLPGroupUpdateTrainer(int maxGlobalSteps,
int syncPeriod,
IgniteFunction<List<U>, U> allUpdatesReducer,
IgniteFunction<List<U>, U> locStepUpdatesReducer,
ParameterUpdateCalculator<? super MultilayerPerceptron, U> updateCalculator,
IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> loss,
Ignite ignite, double tolerance) {
super(new MLPMetaoptimizer<>(allUpdatesReducer), MLPCache.getOrCreate(ignite), ignite);
this.maxGlobalSteps = maxGlobalSteps;
this.syncPeriod = syncPeriod;
this.allUpdatesReducer = allUpdatesReducer;
this.locStepUpdatesReducer = locStepUpdatesReducer;
this.updateCalculator = updateCalculator;
this.loss = loss;
this.tolerance = tolerance;
}
/**
* Get default {@link MLPGroupUpdateTrainer}.
*
* @param ignite Ignite instance.
* @return Default {@link MLPGroupUpdateTrainer}.
*/
public static MLPGroupUpdateTrainer<RPropParameterUpdate> getDefault(Ignite ignite) {
return new MLPGroupUpdateTrainer<>(DEFAULT_MAX_GLOBAL_STEPS, DEFAULT_SYNC_RATE, DEFAULT_ALL_UPDATES_REDUCER,
DEFAULT_LOCAL_STEP_UPDATES_REDUCER, DEFAULT_UPDATE_CALCULATOR, DEFAULT_LOSS, ignite, 0.01);
}
/** {@inheritDoc} */
@Override protected void init(AbstractMLPGroupUpdateTrainerInput data, UUID trainingUUID) {
super.init(data, trainingUUID);
MLPGroupUpdateTrainerDataCache.getOrCreate(ignite).put(trainingUUID, new MLPGroupUpdateTrainingData<>(
updateCalculator,
syncPeriod,
locStepUpdatesReducer,
data.batchSupplier(),
loss,
tolerance
));
}
/** {@inheritDoc} */
@Override protected IgniteFunction<GroupTrainerCacheKey<Void>, ResultAndUpdates<U>> distributedInitializer(
AbstractMLPGroupUpdateTrainerInput data) {
MultilayerPerceptron initPerceptron = data.mdl();
// For each key put initial network into the cache.
return key -> {
Ignite ignite = Ignition.localIgnite();
U initUpdate = updateCalculator.init(initPerceptron, loss);
return ResultAndUpdates.of(initUpdate).updateCache(MLPCache.getOrCreate(ignite), key,
new MLPGroupTrainingCacheValue(initPerceptron));
};
}
/** {@inheritDoc} */
@Override protected IgniteFunction<EntryAndContext<Void, MLPGroupTrainingCacheValue,
MLPGroupUpdateTrainingContext<U>>, MLPGroupUpdateTrainingLoopData<U>> trainingLoopStepDataExtractor() {
return entryAndContext -> {
MLPGroupUpdateTrainingContext<U> ctx = entryAndContext.context();
Map.Entry<GroupTrainerCacheKey<Void>, MLPGroupTrainingCacheValue> entry = entryAndContext.entry();
MLPGroupUpdateTrainingData<U> data = ctx.data();
return new MLPGroupUpdateTrainingLoopData<>(entry.getValue().perceptron(),
data.updateCalculator(), data.stepsCnt(), data.updateReducer(), ctx.previousUpdate(), entry.getKey(),
data.batchSupplier(), data.loss(), data.tolerance());
};
}
/** {@inheritDoc} */
@Override protected IgniteSupplier<Stream<GroupTrainerCacheKey<Void>>> keysToProcessInTrainingLoop(
MLPGroupUpdateTrainerLocalContext locCtx) {
int trainingsCnt = locCtx.parallelTrainingsCnt();
UUID uuid = locCtx.trainingUUID();
return () -> MLPCache.allKeys(trainingsCnt, uuid);
}
/** {@inheritDoc} */
@Override protected IgniteSupplier<MLPGroupUpdateTrainingContext<U>> remoteContextExtractor(U prevUpdate,
MLPGroupUpdateTrainerLocalContext ctx) {
UUID uuid = ctx.trainingUUID();
return () -> {
MLPGroupUpdateTrainingData<U> data = MLPGroupUpdateTrainerDataCache.getOrCreate(Ignition.localIgnite()).get(uuid);
return new MLPGroupUpdateTrainingContext<>(data, prevUpdate);
};
}
/** {@inheritDoc} */
@Override protected IgniteFunction<MLPGroupUpdateTrainingLoopData<U>, ResultAndUpdates<U>> dataProcessor() {
return data -> {
MultilayerPerceptron mlp = data.mlp();
// Apply previous update.
MultilayerPerceptron newMlp = updateCalculator.update(mlp, data.previousUpdate());
MultilayerPerceptron mlpCp = Utils.copy(newMlp);
ParameterUpdateCalculator<? super MultilayerPerceptron, U> updateCalculator = data.updateCalculator();
IgniteFunction<Vector, IgniteDifferentiableVectorToDoubleFunction> loss = data.loss();
// ParameterUpdateCalculator API to have proper way to setting loss.
updateCalculator.init(mlpCp, loss);
// Generate new update.
int steps = data.stepsCnt();
List<U> updates = new ArrayList<>(steps);
U curUpdate = data.previousUpdate();
for (int i = 0; i < steps; i++) {
IgniteBiTuple<Matrix, Matrix> batch = data.batchSupplier().get();
Matrix input = batch.get1();
Matrix truth = batch.get2();
int batchSize = truth.columnSize();
curUpdate = updateCalculator.calculateNewUpdate(mlpCp, curUpdate, i, input, truth);
mlpCp = updateCalculator.update(mlpCp, curUpdate);
updates.add(curUpdate);
Matrix predicted = mlpCp.apply(input);
double err = MatrixUtil.zipFoldByColumns(predicted, truth, (predCol, truthCol) ->
loss.apply(truthCol).apply(predCol)).sum() / batchSize;
if (err < data.tolerance())
break;
}
U accumulatedUpdate = data.getUpdateReducer().apply(updates);
return new ResultAndUpdates<>(accumulatedUpdate).
updateCache(MLPCache.getOrCreate(Ignition.localIgnite()), data.key(),
new MLPGroupTrainingCacheValue(newMlp));
};
}
/** {@inheritDoc} */
@Override protected MLPGroupUpdateTrainerLocalContext<U> initialLocalContext(
AbstractMLPGroupUpdateTrainerInput data, UUID trainingUUID) {
return new MLPGroupUpdateTrainerLocalContext<>(trainingUUID, maxGlobalSteps, allUpdatesReducer,
data.trainingsCount());
}
/** {@inheritDoc} */
@Override protected IgniteSupplier<Stream<GroupTrainerCacheKey<Void>>> finalResultKeys(U data,
MLPGroupUpdateTrainerLocalContext locCtx) {
UUID uuid = locCtx.trainingUUID();
int trainingsCnt = locCtx.parallelTrainingsCnt();
return () -> MLPCache.allKeys(trainingsCnt, uuid);
}
/** {@inheritDoc} */
@Override protected IgniteSupplier<MLPGroupUpdateTrainingContext<U>> extractContextForFinalResultCreation(U data,
MLPGroupUpdateTrainerLocalContext locCtx) {
return () -> null;
}
/** {@inheritDoc} */
@Override protected IgniteFunction<EntryAndContext<Void, MLPGroupTrainingCacheValue,
MLPGroupUpdateTrainingContext<U>>, ResultAndUpdates<MultilayerPerceptron>> finalResultsExtractor() {
return context -> ResultAndUpdates.of(context.entry().getValue().perceptron());
}
/** {@inheritDoc} */
@Override protected IgniteFunction<List<MultilayerPerceptron>, MultilayerPerceptron> finalResultsReducer() {
// Just take any of MLPs since they will be in the same state.
return mlps -> mlps.stream().filter(Objects::nonNull).findFirst().orElse(null);
}
/** {@inheritDoc} */
@Override protected MultilayerPerceptron mapFinalResult(MultilayerPerceptron res,
MLPGroupUpdateTrainerLocalContext locCtx) {
return res;
}
/** {@inheritDoc} */
@Override protected void cleanup(MLPGroupUpdateTrainerLocalContext locCtx) {
}
/**
* Create new {@link MLPGroupUpdateTrainer} with new maxGlobalSteps value.
*
* @param maxGlobalSteps New maxGlobalSteps value.
* @return New {@link MLPGroupUpdateTrainer} with new maxGlobalSteps value.
*/
public MLPGroupUpdateTrainer<U> withMaxGlobalSteps(int maxGlobalSteps) {
return new MLPGroupUpdateTrainer<>(maxGlobalSteps, syncPeriod, allUpdatesReducer, locStepUpdatesReducer,
updateCalculator, loss, ignite, tolerance);
}
/**
* Create new {@link MLPGroupUpdateTrainer} with new syncPeriod value.
*
* @param syncPeriod New syncPeriod value.
* @return New {@link MLPGroupUpdateTrainer} with new syncPeriod value.
*/
public MLPGroupUpdateTrainer<U> withSyncPeriod(int syncPeriod) {
return new MLPGroupUpdateTrainer<>(maxGlobalSteps, syncPeriod
, allUpdatesReducer, locStepUpdatesReducer, updateCalculator, loss, ignite, tolerance);
}
/**
* Create new {@link MLPGroupUpdateTrainer} with new tolerance.
*
* @param tolerance New tolerance value.
* @return New {@link MLPGroupUpdateTrainer} with new tolerance value.
*/
public MLPGroupUpdateTrainer<U> withTolerance(double tolerance) {
return new MLPGroupUpdateTrainer<>(maxGlobalSteps, syncPeriod, allUpdatesReducer, locStepUpdatesReducer,
updateCalculator, loss, ignite, tolerance);
}
/**
* Create new {@link MLPGroupUpdateTrainer} with new update strategy.
*
* @param stgy New update strategy.
* @return New {@link MLPGroupUpdateTrainer} with new tolerance value.
*/
public <U1 extends Serializable> MLPGroupUpdateTrainer<U1> withUpdateStrategy(UpdatesStrategy<? super MultilayerPerceptron, U1> stgy) {
return new MLPGroupUpdateTrainer<>(maxGlobalSteps, syncPeriod, stgy.allUpdatesReducer(), stgy.locStepUpdatesReducer(),
stgy.getUpdatesCalculator(), loss, ignite, tolerance);
}
}
| IGNITE-7375: Right cleanup after training.
this closes #3478
| modules/ml/src/main/java/org/apache/ignite/ml/nn/trainers/distributed/MLPGroupUpdateTrainer.java | IGNITE-7375: Right cleanup after training. |
|
Java | apache-2.0 | 636c328801f8ca1eaba4f049b20eb0cbf1ad25a8 | 0 | kabir/xnio,fl4via/xnio,xnio/xnio,stuartwdouglas/xnio,xnio/xnio,fl4via/xnio,panossot/xnio,panossot/xnio,dmlloyd/xnio,kabir/xnio | /*
* JBoss, Home of Professional Open Source
* Copyright 2008, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.xnio;
import java.io.IOException;
import java.io.Closeable;
import java.io.InterruptedIOException;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CancellationException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.ZipFile;
import java.nio.channels.Channel;
import java.nio.channels.Selector;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.DatagramSocket;
import org.jboss.xnio.channels.StreamChannel;
import org.jboss.xnio.log.Logger;
import java.util.logging.Handler;
/**
* General I/O utility methods.
*
* @apiviz.exclude
*/
public final class IoUtils {
private static final Executor NULL_EXECUTOR = new Executor() {
private final String string = String.format("null executor <%s>", Integer.toHexString(hashCode()));
public void execute(final Runnable command) {
// no operation
}
public String toString() {
return string;
}
};
private static final Executor DIRECT_EXECUTOR = new Executor() {
private final String string = String.format("direct executor <%s>", Integer.toHexString(hashCode()));
public void execute(final Runnable command) {
command.run();
}
public String toString() {
return string;
}
};
private static final IoHandler<Channel> NULL_HANDLER = new IoHandler<Channel>() {
private final String string = String.format("null handler <%s>", Integer.toHexString(hashCode()));
public void handleOpened(final Channel channel) {
}
public void handleReadable(final Channel channel) {
}
public void handleWritable(final Channel channel) {
}
public void handleClosed(final Channel channel) {
}
public String toString() {
return string;
}
};
private static final IoHandlerFactory<Channel> NULL_HANDLER_FACTORY = new IoHandlerFactory<Channel>() {
private final String string = String.format("null handler factory <%s>", Integer.toHexString(hashCode()));
public IoHandler<Channel> createHandler() {
return NULL_HANDLER;
}
public String toString() {
return string;
}
};
private static final Closeable NULL_CLOSEABLE = new Closeable() {
private final String string = String.format("null closeable <%s>", Integer.toHexString(hashCode()));
public void close() throws IOException {
// no operation
}
public String toString() {
return string;
}
};
private IoUtils() {}
/**
* Create a persistent connection using a channel source. The provided handler will handle the connection. The {@code reconnectExecutor} will
* be used to execute a reconnect task in the event that the connection fails or is lost or terminated. If you wish
* to impose a time delay on reconnect, use the {@link org.jboss.xnio.IoUtils#delayedExecutor(java.util.concurrent.ScheduledExecutorService, long, java.util.concurrent.TimeUnit) delayedExecutor()} method
* to create a delayed executor. If you do not want to auto-reconnect use the {@link org.jboss.xnio.IoUtils#nullExecutor()} method to
* create a null executor. If you want auto-reconnect to take place immediately, use the {@link IoUtils#directExecutor()} method
* to create a direct executor.
*
* @param channelSource the client to connect on
* @param handler the handler for the connection
* @param reconnectExecutor the executor that should execute the reconnect task
* @param <T> the channel type
* @return a handle which can be used to terminate the connection
*/
public static <T extends StreamChannel> Closeable createConnection(final ChannelSource<T> channelSource, final IoHandler<? super T> handler, final Executor reconnectExecutor) {
final Connection<T> connection = new Connection<T>(channelSource, handler, reconnectExecutor);
connection.connect();
return connection;
}
/**
* Create a delayed executor. This is an executor that executes tasks after a given time delay with the help of the
* provided {@code ScheduledExecutorService}. To get an executor for this method, use one of the methods on the
* {@link java.util.concurrent.Executors} class.
*
* @param scheduledExecutorService the executor service to use to schedule the task
* @param delay the time delay before reconnect
* @param unit the unit of time to use
* @return an executor that delays execution
*/
public static Executor delayedExecutor(final ScheduledExecutorService scheduledExecutorService, final long delay, final TimeUnit unit) {
return new Executor() {
public void execute(final Runnable command) {
scheduledExecutorService.schedule(command, delay, unit);
}
};
}
/**
* Get the direct executor. This is an executor that executes the provided task in the same thread.
*
* @return a direct executor
*/
public static Executor directExecutor() {
return DIRECT_EXECUTOR;
}
/**
* Get the null executor. This is an executor that never actually executes the provided task.
*
* @return a null executor
*/
public static Executor nullExecutor() {
return NULL_EXECUTOR;
}
/**
* Get a closeable executor wrapper for an {@code ExecutorService}. The given timeout is used to determine how long
* the {@code close()} method will wait for a clean shutdown before the executor is shut down forcefully.
*
* @param executorService the executor service
* @param timeout the timeout
* @param unit the unit for the timeout
* @return a new closeable executor
*/
public static CloseableExecutor closeableExecutor(final ExecutorService executorService, final long timeout, final TimeUnit unit) {
return new CloseableExecutor() {
public void close() throws IOException {
executorService.shutdown();
try {
if (executorService.awaitTermination(timeout, unit)) {
return;
}
executorService.shutdownNow();
throw new IOException("Executor did not shut down cleanly (killed)");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
executorService.shutdownNow();
throw new InterruptedIOException("Interrupted while awaiting executor shutdown");
}
}
public void execute(final Runnable command) {
executorService.execute(command);
}
};
}
/**
* Get the null closeable. This is a simple {@code Closeable} instance that does nothing when its {@code close()}
* method is invoked.
*
* @return the null closeable
*/
public static Closeable nullCloseable() {
return NULL_CLOSEABLE;
}
/**
* Get the null handler. This is a handler whose handler methods all return without taking any action.
*
* @return the null handler
*/
public static IoHandler<Channel> nullHandler() {
return NULL_HANDLER;
}
/**
* Get the null handler factory. This is a handler factory that returns the null handler.
*
* @return the null handler factory
*/
public static IoHandlerFactory<Channel> nullHandlerFactory() {
return NULL_HANDLER_FACTORY;
}
/**
* Get a singleton handler factory that returns the given handler one time only.
*
* @param handler the handler to return
* @return a singleton handler factory
*/
public static <T extends Channel> IoHandlerFactory<T> singletonHandlerFactory(final IoHandler<T> handler) {
final AtomicReference<IoHandler<T>> reference = new AtomicReference<IoHandler<T>>(handler);
return new IoHandlerFactory<T>() {
public IoHandler<? super T> createHandler() {
final IoHandler<T> handler = reference.getAndSet(null);
if (handler == null) {
throw new IllegalStateException("Handler already taken from singleton handler factory");
}
return handler;
}
};
}
private static final Logger closeLog = Logger.getLogger("org.jboss.xnio.safe-close");
/**
* Close a resource, logging an error if an error occurs.
*
* @param resource the resource to close
*/
public static void safeClose(final Closeable resource) {
try {
if (resource != null) {
resource.close();
}
} catch (Throwable t) {
closeLog.trace(t, "Closing resource failed");
}
}
/**
* Close a resource, logging an error if an error occurs.
*
* @param resource the resource to close
*/
public static void safeClose(final Socket resource) {
try {
if (resource != null) {
resource.close();
}
} catch (Throwable t) {
closeLog.trace(t, "Closing resource failed");
}
}
/**
* Close a resource, logging an error if an error occurs.
*
* @param resource the resource to close
*/
public static void safeClose(final DatagramSocket resource) {
try {
if (resource != null) {
resource.close();
}
} catch (Throwable t) {
closeLog.trace(t, "Closing resource failed");
}
}
/**
* Close a resource, logging an error if an error occurs.
*
* @param resource the resource to close
*/
public static void safeClose(final Selector resource) {
try {
if (resource != null) {
resource.close();
}
} catch (Throwable t) {
closeLog.trace(t, "Closing resource failed");
}
}
/**
* Close a resource, logging an error if an error occurs.
*
* @param resource the resource to close
*/
public static void safeClose(final ServerSocket resource) {
try {
if (resource != null) {
resource.close();
}
} catch (Throwable t) {
closeLog.trace(t, "Closing resource failed");
}
}
/**
* Close a resource, logging an error if an error occurs.
*
* @param resource the resource to close
*/
public static void safeClose(final ZipFile resource) {
try {
if (resource != null) {
resource.close();
}
} catch (Throwable t) {
closeLog.trace(t, "Closing resource failed");
}
}
/**
* Close a resource, logging an error if an error occurs.
*
* @param resource the resource to close
*/
public static void safeClose(final Handler resource) {
try {
if (resource != null) {
resource.close();
}
} catch (Throwable t) {
closeLog.trace(t, "Closing resource failed");
}
}
/**
* Close a future resource, logging an error if an error occurs. Attempts to cancel the operation if it is
* still in progress.
*
* @param futureResource the resource to close
*/
public static void safeClose(final IoFuture<? extends Closeable> futureResource) {
futureResource.cancel().addNotifier(closingNotifier(), null);
}
private static final IoFuture.Notifier<Object, Closeable> ATTACHMENT_CLOSING_NOTIFIER = new IoFuture.Notifier<Object, Closeable>() {
public void notify(final IoFuture<?> future, final Closeable attachment) {
IoUtils.safeClose(attachment);
}
};
private static final IoFuture.Notifier<Closeable, Void> CLOSING_NOTIFIER = new IoFuture.HandlingNotifier<Closeable, Void>() {
public void handleDone(final Closeable result, final Void attachment) {
IoUtils.safeClose(result);
}
};
/**
* Get a notifier that closes the attachment.
*
* @return a notifier which will close its attachment
*/
public static IoFuture.Notifier<Object, Closeable> attachmentClosingNotifier() {
return ATTACHMENT_CLOSING_NOTIFIER;
}
/**
* Get a notifier that closes the result.
*
* @return a notifier which will close the result of the operation (if successful)
*/
public static IoFuture.Notifier<Closeable, Void> closingNotifier() {
return CLOSING_NOTIFIER;
}
/**
* Get a notifier that runs the supplied action.
*
* @param runnable the notifier type
* @param <T> the future type (not used)
* @return a notifier which will run the given command
*/
public static <T> IoFuture.Notifier<T, Void> runnableNotifier(final Runnable runnable) {
return new IoFuture.Notifier<T, Void>() {
public void notify(final IoFuture<? extends T> future, final Void attachment) {
runnable.run();
}
};
}
/**
* Get a {@code java.util.concurrent}-style {@code Future} instance wrapper for an {@code IoFuture} instance.
*
* @param ioFuture the {@code IoFuture} to wrap
* @return a {@code Future}
*/
public static <T> Future<T> getFuture(final IoFuture<T> ioFuture) {
return new Future<T>() {
public boolean cancel(final boolean mayInterruptIfRunning) {
ioFuture.cancel();
return ioFuture.await() == IoFuture.Status.CANCELLED;
}
public boolean isCancelled() {
return ioFuture.getStatus() == IoFuture.Status.CANCELLED;
}
public boolean isDone() {
return ioFuture.getStatus() == IoFuture.Status.DONE;
}
public T get() throws InterruptedException, ExecutionException {
try {
return ioFuture.getInterruptibly();
} catch (IOException e) {
throw new ExecutionException(e);
}
}
public T get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
try {
if (ioFuture.awaitInterruptibly(timeout, unit) == IoFuture.Status.WAITING) {
throw new TimeoutException("Operation timed out");
}
return ioFuture.getInterruptibly();
} catch (IOException e) {
throw new ExecutionException(e);
}
}
public String toString() {
return String.format("java.util.concurrent.Future wrapper <%s> for %s", Integer.toHexString(hashCode()), ioFuture);
}
};
}
private static final IoFuture.Notifier<Object, CountDownLatch> COUNT_DOWN_NOTIFIER = new IoFuture.Notifier<Object, CountDownLatch>() {
public void notify(final IoFuture<?> future, final CountDownLatch latch) {
latch.countDown();
}
};
public static void awaitAll(IoFuture<?>... futures) {
final int len = futures.length;
final CountDownLatch cdl = new CountDownLatch(len);
for (IoFuture<?> future : futures) {
future.addNotifier(COUNT_DOWN_NOTIFIER, cdl);
}
boolean intr = false;
try {
while (cdl.getCount() > 0L) {
try {
cdl.await();
} catch (InterruptedException e) {
intr = true;
}
}
} finally {
if (intr) {
Thread.currentThread().interrupt();
}
}
}
public static void awaitAllInterruptibly(IoFuture<?>... futures) throws InterruptedException {
final int len = futures.length;
final CountDownLatch cdl = new CountDownLatch(len);
for (IoFuture<?> future : futures) {
future.addNotifier(COUNT_DOWN_NOTIFIER, cdl);
}
cdl.await();
}
/**
* Create an {@code IoFuture} which wraps another {@code IoFuture}, but returns a different type.
*
* @param parent the original {@code IoFuture}
* @param type the class of the new {@code IoFuture}
* @param <I> the type of the original result
* @param <O> the type of the wrapped result
* @return a wrapper {@code IoFuture}
*/
public static <I, O> IoFuture<O> cast(final IoFuture<I> parent, final Class<O> type) {
return new CastingIoFuture<O, I>(parent, type);
}
// nested classes
private static final Logger connLog = Logger.getLogger("org.jboss.xnio.connection");
private static final class Connection<T extends StreamChannel> implements Closeable {
private final ChannelSource<T> channelSource;
private final IoHandler<? super T> handler;
private final Executor reconnectExecutor;
private volatile boolean stopFlag = false;
private volatile IoFuture<T> currentFuture;
private final NotifierImpl<?> notifier = new NotifierImpl<Void>();
private final HandlerImpl handlerWrapper = new HandlerImpl();
private final ReconnectTask reconnectTask = new ReconnectTask();
private Connection(final ChannelSource<T> channelSource, final IoHandler<? super T> handler, final Executor reconnectExecutor) {
this.channelSource = channelSource;
this.handler = handler;
this.reconnectExecutor = reconnectExecutor;
}
private void connect() {
closeLog.trace("Establishing connection");
final IoFuture<T> ioFuture = channelSource.open(handlerWrapper);
ioFuture.addNotifier(notifier, null);
currentFuture = ioFuture;
}
public void close() throws IOException {
stopFlag = true;
final IoFuture<T> future = currentFuture;
if (future != null) {
future.cancel();
}
}
public String toString() {
return String.format("persistent connection <%s> via %s", Integer.toHexString(hashCode()), channelSource);
}
private final class NotifierImpl<A> extends IoFuture.HandlingNotifier<T, A> {
public void handleCancelled(final A attachment) {
connLog.trace("Connection cancelled");
}
public void handleFailed(final IOException exception, final A attachment) {
connLog.trace(exception, "Connection failed");
}
public void handleDone(final T result, final A attachment) {
connLog.trace("Connection established");
}
public void notify(final IoFuture<? extends T> future, final A attachment) {
super.notify(future, attachment);
if (! stopFlag) {
reconnectExecutor.execute(reconnectTask);
}
return;
}
}
private final class HandlerImpl implements IoHandler<T> {
public void handleOpened(final T channel) {
handler.handleOpened(channel);
}
public void handleReadable(final T channel) {
handler.handleReadable(channel);
}
public void handleWritable(final T channel) {
handler.handleWritable(channel);
}
public void handleClosed(final T channel) {
try {
connLog.trace("Connection closed");
if (! stopFlag) {
reconnectExecutor.execute(reconnectTask);
}
} finally {
handler.handleClosed(channel);
}
}
public String toString() {
return String.format("persistent connection handler <%s> wrapping %s", Integer.toHexString(hashCode()), handler);
}
}
private final class ReconnectTask implements Runnable {
public void run() {
if (! stopFlag) {
connect();
}
}
public String toString() {
return String.format("reconnect task <%s> for %s", Integer.toHexString(hashCode()), Connection.this);
}
}
}
private static class CastingIoFuture<O, I> implements IoFuture<O> {
private final IoFuture<I> parent;
private final Class<O> type;
private CastingIoFuture(final IoFuture<I> parent, final Class<O> type) {
this.parent = parent;
this.type = type;
}
public IoFuture<O> cancel() {
parent.cancel();
return this;
}
public Status getStatus() {
return parent.getStatus();
}
public Status await() {
return parent.await();
}
public Status await(final long time, final TimeUnit timeUnit) {
return parent.await(time, timeUnit);
}
public Status awaitInterruptibly() throws InterruptedException {
return parent.awaitInterruptibly();
}
public Status awaitInterruptibly(final long time, final TimeUnit timeUnit) throws InterruptedException {
return parent.awaitInterruptibly(time, timeUnit);
}
public O get() throws IOException, CancellationException {
return type.cast(parent.get());
}
public O getInterruptibly() throws IOException, InterruptedException, CancellationException {
return type.cast(parent.getInterruptibly());
}
public IOException getException() throws IllegalStateException {
return parent.getException();
}
public <A> IoFuture<O> addNotifier(final Notifier<? super O, A> notifier, final A attachment) {
parent.<A>addNotifier(new Notifier<I, A>() {
public void notify(final IoFuture<? extends I> future, final A attachment) {
notifier.notify((IoFuture<O>)CastingIoFuture.this, attachment);
}
}, attachment);
return this;
}
}
}
| api/src/main/java/org/jboss/xnio/IoUtils.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2008, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.xnio;
import java.io.IOException;
import java.io.Closeable;
import java.io.InterruptedIOException;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CancellationException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.ZipFile;
import java.nio.channels.Channel;
import java.nio.channels.Selector;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.DatagramSocket;
import org.jboss.xnio.channels.StreamChannel;
import org.jboss.xnio.log.Logger;
import java.util.logging.Handler;
/**
* General I/O utility methods.
*
* @apiviz.exclude
*/
public final class IoUtils {
private static final Executor NULL_EXECUTOR = new Executor() {
private final String string = String.format("null executor <%s>", Integer.toHexString(hashCode()));
public void execute(final Runnable command) {
// no operation
}
public String toString() {
return string;
}
};
private static final Executor DIRECT_EXECUTOR = new Executor() {
private final String string = String.format("direct executor <%s>", Integer.toHexString(hashCode()));
public void execute(final Runnable command) {
command.run();
}
public String toString() {
return string;
}
};
private static final IoHandler<Channel> NULL_HANDLER = new IoHandler<Channel>() {
private final String string = String.format("null handler <%s>", Integer.toHexString(hashCode()));
public void handleOpened(final Channel channel) {
}
public void handleReadable(final Channel channel) {
}
public void handleWritable(final Channel channel) {
}
public void handleClosed(final Channel channel) {
}
public String toString() {
return string;
}
};
private static final IoHandlerFactory<Channel> NULL_HANDLER_FACTORY = new IoHandlerFactory<Channel>() {
private final String string = String.format("null handler factory <%s>", Integer.toHexString(hashCode()));
public IoHandler<Channel> createHandler() {
return NULL_HANDLER;
}
public String toString() {
return string;
}
};
private static final Closeable NULL_CLOSEABLE = new Closeable() {
private final String string = String.format("null closeable <%s>", Integer.toHexString(hashCode()));
public void close() throws IOException {
// no operation
}
public String toString() {
return string;
}
};
private IoUtils() {}
/**
* Create a persistent connection using a channel source. The provided handler will handle the connection. The {@code reconnectExecutor} will
* be used to execute a reconnect task in the event that the connection fails or is lost or terminated. If you wish
* to impose a time delay on reconnect, use the {@link org.jboss.xnio.IoUtils#delayedExecutor(java.util.concurrent.ScheduledExecutorService, long, java.util.concurrent.TimeUnit) delayedExecutor()} method
* to create a delayed executor. If you do not want to auto-reconnect use the {@link org.jboss.xnio.IoUtils#nullExecutor()} method to
* create a null executor. If you want auto-reconnect to take place immediately, use the {@link IoUtils#directExecutor()} method
* to create a direct executor.
*
* @param channelSource the client to connect on
* @param handler the handler for the connection
* @param reconnectExecutor the executor that should execute the reconnect task
* @param <T> the channel type
* @return a handle which can be used to terminate the connection
*/
public static <T extends StreamChannel> Closeable createConnection(final ChannelSource<T> channelSource, final IoHandler<? super T> handler, final Executor reconnectExecutor) {
final Connection<T> connection = new Connection<T>(channelSource, handler, reconnectExecutor);
connection.connect();
return connection;
}
/**
* Create a delayed executor. This is an executor that executes tasks after a given time delay with the help of the
* provided {@code ScheduledExecutorService}. To get an executor for this method, use one of the methods on the
* {@link java.util.concurrent.Executors} class.
*
* @param scheduledExecutorService the executor service to use to schedule the task
* @param delay the time delay before reconnect
* @param unit the unit of time to use
* @return an executor that delays execution
*/
public static Executor delayedExecutor(final ScheduledExecutorService scheduledExecutorService, final long delay, final TimeUnit unit) {
return new Executor() {
public void execute(final Runnable command) {
scheduledExecutorService.schedule(command, delay, unit);
}
};
}
/**
* Get the direct executor. This is an executor that executes the provided task in the same thread.
*
* @return a direct executor
*/
public static Executor directExecutor() {
return DIRECT_EXECUTOR;
}
/**
* Get the null executor. This is an executor that never actually executes the provided task.
*
* @return a null executor
*/
public static Executor nullExecutor() {
return NULL_EXECUTOR;
}
/**
* Get a closeable executor wrapper for an {@code ExecutorService}. The given timeout is used to determine how long
* the {@code close()} method will wait for a clean shutdown before the executor is shut down forcefully.
*
* @param executorService the executor service
* @param timeout the timeout
* @param unit the unit for the timeout
* @return a new closeable executor
*/
public static CloseableExecutor closeableExecutor(final ExecutorService executorService, final long timeout, final TimeUnit unit) {
return new CloseableExecutor() {
public void close() throws IOException {
executorService.shutdown();
try {
if (executorService.awaitTermination(timeout, unit)) {
return;
}
executorService.shutdownNow();
throw new IOException("Executor did not shut down cleanly (killed)");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
executorService.shutdownNow();
throw new InterruptedIOException("Interrupted while awaiting executor shutdown");
}
}
public void execute(final Runnable command) {
executorService.execute(command);
}
};
}
/**
* Get the null closeable. This is a simple {@code Closeable} instance that does nothing when its {@code close()}
* method is invoked.
*
* @return the null closeable
*/
public static Closeable nullCloseable() {
return NULL_CLOSEABLE;
}
/**
* Get the null handler. This is a handler whose handler methods all return without taking any action.
*
* @return the null handler
*/
public static IoHandler<Channel> nullHandler() {
return NULL_HANDLER;
}
/**
* Get the null handler factory. This is a handler factory that returns the null handler.
*
* @return the null handler factory
*/
public static IoHandlerFactory<Channel> nullHandlerFactory() {
return NULL_HANDLER_FACTORY;
}
/**
* Get a singleton handler factory that returns the given handler one time only.
*
* @param handler the handler to return
* @return a singleton handler factory
*/
public static <T extends Channel> IoHandlerFactory<T> singletonHandlerFactory(final IoHandler<T> handler) {
final AtomicReference<IoHandler<T>> reference = new AtomicReference<IoHandler<T>>(handler);
return new IoHandlerFactory<T>() {
public IoHandler<? super T> createHandler() {
final IoHandler<T> handler = reference.getAndSet(null);
if (handler == null) {
throw new IllegalStateException("Handler already taken from singleton handler factory");
}
return handler;
}
};
}
private static final Logger closeLog = Logger.getLogger("org.jboss.xnio.safe-close");
/**
* Close a resource, logging an error if an error occurs.
*
* @param resource the resource to close
*/
public static void safeClose(final Closeable resource) {
try {
if (resource != null) {
resource.close();
}
} catch (Throwable t) {
closeLog.trace(t, "Closing resource failed");
}
}
/**
* Close a resource, logging an error if an error occurs.
*
* @param resource the resource to close
*/
public static void safeClose(final Socket resource) {
try {
if (resource != null) {
resource.close();
}
} catch (Throwable t) {
closeLog.trace(t, "Closing resource failed");
}
}
/**
* Close a resource, logging an error if an error occurs.
*
* @param resource the resource to close
*/
public static void safeClose(final DatagramSocket resource) {
try {
if (resource != null) {
resource.close();
}
} catch (Throwable t) {
closeLog.trace(t, "Closing resource failed");
}
}
/**
* Close a resource, logging an error if an error occurs.
*
* @param resource the resource to close
*/
public static void safeClose(final Selector resource) {
try {
if (resource != null) {
resource.close();
}
} catch (Throwable t) {
closeLog.trace(t, "Closing resource failed");
}
}
/**
* Close a resource, logging an error if an error occurs.
*
* @param resource the resource to close
*/
public static void safeClose(final ServerSocket resource) {
try {
if (resource != null) {
resource.close();
}
} catch (Throwable t) {
closeLog.trace(t, "Closing resource failed");
}
}
/**
* Close a resource, logging an error if an error occurs.
*
* @param resource the resource to close
*/
public static void safeClose(final ZipFile resource) {
try {
if (resource != null) {
resource.close();
}
} catch (Throwable t) {
closeLog.trace(t, "Closing resource failed");
}
}
/**
* Close a resource, logging an error if an error occurs.
*
* @param resource the resource to close
*/
public static void safeClose(final Handler resource) {
try {
if (resource != null) {
resource.close();
}
} catch (Throwable t) {
closeLog.trace(t, "Closing resource failed");
}
}
/**
* Close a future resource, logging an error if an error occurs. Attempts to cancel the operation if it is
* still in progress.
*
* @param futureResource the resource to close
*/
public static void safeClose(final IoFuture<? extends Closeable> futureResource) {
futureResource.addNotifier(closingNotifier(), null).cancel();
}
private static final IoFuture.Notifier<Object, Closeable> ATTACHMENT_CLOSING_NOTIFIER = new IoFuture.Notifier<Object, Closeable>() {
public void notify(final IoFuture<?> future, final Closeable attachment) {
IoUtils.safeClose(attachment);
}
};
private static final IoFuture.Notifier<Closeable, Void> CLOSING_NOTIFIER = new IoFuture.HandlingNotifier<Closeable, Void>() {
public void handleDone(final Closeable result, final Void attachment) {
IoUtils.safeClose(result);
}
};
/**
* Get a notifier that closes the attachment.
*
* @return a notifier which will close its attachment
*/
public static IoFuture.Notifier<Object, Closeable> attachmentClosingNotifier() {
return ATTACHMENT_CLOSING_NOTIFIER;
}
/**
* Get a notifier that closes the result.
*
* @return a notifier which will close the result of the operation (if successful)
*/
public static IoFuture.Notifier<Closeable, Void> closingNotifier() {
return CLOSING_NOTIFIER;
}
/**
* Get a notifier that runs the supplied action.
*
* @param runnable the notifier type
* @param <T> the future type (not used)
* @return a notifier which will run the given command
*/
public static <T> IoFuture.Notifier<T, Void> runnableNotifier(final Runnable runnable) {
return new IoFuture.Notifier<T, Void>() {
public void notify(final IoFuture<? extends T> future, final Void attachment) {
runnable.run();
}
};
}
/**
* Get a {@code java.util.concurrent}-style {@code Future} instance wrapper for an {@code IoFuture} instance.
*
* @param ioFuture the {@code IoFuture} to wrap
* @return a {@code Future}
*/
public static <T> Future<T> getFuture(final IoFuture<T> ioFuture) {
return new Future<T>() {
public boolean cancel(final boolean mayInterruptIfRunning) {
ioFuture.cancel();
return ioFuture.await() == IoFuture.Status.CANCELLED;
}
public boolean isCancelled() {
return ioFuture.getStatus() == IoFuture.Status.CANCELLED;
}
public boolean isDone() {
return ioFuture.getStatus() == IoFuture.Status.DONE;
}
public T get() throws InterruptedException, ExecutionException {
try {
return ioFuture.getInterruptibly();
} catch (IOException e) {
throw new ExecutionException(e);
}
}
public T get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
try {
if (ioFuture.awaitInterruptibly(timeout, unit) == IoFuture.Status.WAITING) {
throw new TimeoutException("Operation timed out");
}
return ioFuture.getInterruptibly();
} catch (IOException e) {
throw new ExecutionException(e);
}
}
public String toString() {
return String.format("java.util.concurrent.Future wrapper <%s> for %s", Integer.toHexString(hashCode()), ioFuture);
}
};
}
private static final IoFuture.Notifier<Object, CountDownLatch> COUNT_DOWN_NOTIFIER = new IoFuture.Notifier<Object, CountDownLatch>() {
public void notify(final IoFuture<?> future, final CountDownLatch latch) {
latch.countDown();
}
};
public static void awaitAll(IoFuture<?>... futures) {
final int len = futures.length;
final CountDownLatch cdl = new CountDownLatch(len);
for (IoFuture<?> future : futures) {
future.addNotifier(COUNT_DOWN_NOTIFIER, cdl);
}
boolean intr = false;
try {
while (cdl.getCount() > 0L) {
try {
cdl.await();
} catch (InterruptedException e) {
intr = true;
}
}
} finally {
if (intr) {
Thread.currentThread().interrupt();
}
}
}
public static void awaitAllInterruptibly(IoFuture<?>... futures) throws InterruptedException {
final int len = futures.length;
final CountDownLatch cdl = new CountDownLatch(len);
for (IoFuture<?> future : futures) {
future.addNotifier(COUNT_DOWN_NOTIFIER, cdl);
}
cdl.await();
}
/**
* Create an {@code IoFuture} which wraps another {@code IoFuture}, but returns a different type.
*
* @param parent the original {@code IoFuture}
* @param type the class of the new {@code IoFuture}
* @param <I> the type of the original result
* @param <O> the type of the wrapped result
* @return a wrapper {@code IoFuture}
*/
public static <I, O> IoFuture<O> cast(final IoFuture<I> parent, final Class<O> type) {
return new CastingIoFuture<O, I>(parent, type);
}
// nested classes
private static final Logger connLog = Logger.getLogger("org.jboss.xnio.connection");
private static final class Connection<T extends StreamChannel> implements Closeable {
private final ChannelSource<T> channelSource;
private final IoHandler<? super T> handler;
private final Executor reconnectExecutor;
private volatile boolean stopFlag = false;
private volatile IoFuture<T> currentFuture;
private final NotifierImpl<?> notifier = new NotifierImpl<Void>();
private final HandlerImpl handlerWrapper = new HandlerImpl();
private final ReconnectTask reconnectTask = new ReconnectTask();
private Connection(final ChannelSource<T> channelSource, final IoHandler<? super T> handler, final Executor reconnectExecutor) {
this.channelSource = channelSource;
this.handler = handler;
this.reconnectExecutor = reconnectExecutor;
}
private void connect() {
closeLog.trace("Establishing connection");
final IoFuture<T> ioFuture = channelSource.open(handlerWrapper);
ioFuture.addNotifier(notifier, null);
currentFuture = ioFuture;
}
public void close() throws IOException {
stopFlag = true;
final IoFuture<T> future = currentFuture;
if (future != null) {
future.cancel();
}
}
public String toString() {
return String.format("persistent connection <%s> via %s", Integer.toHexString(hashCode()), channelSource);
}
private final class NotifierImpl<A> extends IoFuture.HandlingNotifier<T, A> {
public void handleCancelled(final A attachment) {
connLog.trace("Connection cancelled");
}
public void handleFailed(final IOException exception, final A attachment) {
connLog.trace(exception, "Connection failed");
}
public void handleDone(final T result, final A attachment) {
connLog.trace("Connection established");
}
public void notify(final IoFuture<? extends T> future, final A attachment) {
super.notify(future, attachment);
if (! stopFlag) {
reconnectExecutor.execute(reconnectTask);
}
return;
}
}
private final class HandlerImpl implements IoHandler<T> {
public void handleOpened(final T channel) {
handler.handleOpened(channel);
}
public void handleReadable(final T channel) {
handler.handleReadable(channel);
}
public void handleWritable(final T channel) {
handler.handleWritable(channel);
}
public void handleClosed(final T channel) {
try {
connLog.trace("Connection closed");
if (! stopFlag) {
reconnectExecutor.execute(reconnectTask);
}
} finally {
handler.handleClosed(channel);
}
}
public String toString() {
return String.format("persistent connection handler <%s> wrapping %s", Integer.toHexString(hashCode()), handler);
}
}
private final class ReconnectTask implements Runnable {
public void run() {
if (! stopFlag) {
connect();
}
}
public String toString() {
return String.format("reconnect task <%s> for %s", Integer.toHexString(hashCode()), Connection.this);
}
}
}
private static class CastingIoFuture<O, I> implements IoFuture<O> {
private final IoFuture<I> parent;
private final Class<O> type;
private CastingIoFuture(final IoFuture<I> parent, final Class<O> type) {
this.parent = parent;
this.type = type;
}
public IoFuture<O> cancel() {
parent.cancel();
return this;
}
public Status getStatus() {
return parent.getStatus();
}
public Status await() {
return parent.await();
}
public Status await(final long time, final TimeUnit timeUnit) {
return parent.await(time, timeUnit);
}
public Status awaitInterruptibly() throws InterruptedException {
return parent.awaitInterruptibly();
}
public Status awaitInterruptibly(final long time, final TimeUnit timeUnit) throws InterruptedException {
return parent.awaitInterruptibly(time, timeUnit);
}
public O get() throws IOException, CancellationException {
return type.cast(parent.get());
}
public O getInterruptibly() throws IOException, InterruptedException, CancellationException {
return type.cast(parent.getInterruptibly());
}
public IOException getException() throws IllegalStateException {
return parent.getException();
}
public <A> IoFuture<O> addNotifier(final Notifier<? super O, A> notifier, final A attachment) {
parent.<A>addNotifier(new Notifier<I, A>() {
public void notify(final IoFuture<? extends I> future, final A attachment) {
notifier.notify((IoFuture<O>)CastingIoFuture.this, attachment);
}
}, attachment);
return this;
}
}
}
| Order of ops change
| api/src/main/java/org/jboss/xnio/IoUtils.java | Order of ops change |
|
Java | apache-2.0 | 432a6dd98396bd53062b1ba29896f4ee64b61b99 | 0 | MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim | /*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.lema.verification.lpn;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import edu.utah.ece.async.ibiosim.dataModels.util.GlobalConstants;
import edu.utah.ece.async.lema.verification.timed_state_exploration.octagon.Equivalence;
import edu.utah.ece.async.lema.verification.timed_state_exploration.zoneProject.IntervalPair;
import edu.utah.ece.async.lema.verification.timed_state_exploration.zoneProject.LPNContAndRate;
import edu.utah.ece.async.lema.verification.timed_state_exploration.zoneProject.LPNContinuousPair;
import java.lang.Math;
/**
*
*
* @author
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class ExprTree {
String op;
char isit; // b=Boolean, i=Integer, c=Continuous, n=Number, t=Truth value,
// w=bitWise, a=Arithmetic, r=Relational, l=Logical
double lvalue, uvalue;
String variable;
double real;
boolean logical;
ExprTree r1, r2;
private String tokvalue = "";
private int position = 0;
public int token = 0;
ExprTree newresult;
private ArrayList<String> booleanSignals, integerSignals, continuousSignals;
private LPN lhpn;
public String expression;
public ExprTree() {
}
/**
* This constructor is used in PlatuGrammar.g to convert LPNs from USF to LhpnFile.
* All LPNs from USF use integer variables only. So only integer signals are dealt with here.
* @param expression
*/
public ExprTree(String expression) {
this.expression = expression;
booleanSignals = new ArrayList<String>();
integerSignals = new ArrayList<String>();
continuousSignals = new ArrayList<String>();
// intexpr_gettok(expression);
// intexpr_L(expression);
}
public ExprTree(LPN lhpn) {
this.lhpn = lhpn;
String[] bools = lhpn.getBooleanVars();
String[] conts = lhpn.getContVars();
String[] ints = lhpn.getIntVars();
booleanSignals = new ArrayList<String>();
integerSignals = new ArrayList<String>();
continuousSignals = new ArrayList<String>();
for (int j = 0; j < bools.length; j++) {
booleanSignals.add(bools[j]);
}
for (int j = 0; j < conts.length; j++) {
continuousSignals.add(conts[j]);
}
for (int j = 0; j < ints.length; j++) {
integerSignals.add(ints[j]);
}
}
public ExprTree(Abstraction abstraction) {
this.lhpn = abstraction;
String[] bools = abstraction.getBooleanVars();
String[] conts = abstraction.getContVars();
String[] ints = abstraction.getIntVars();
booleanSignals = new ArrayList<String>();
integerSignals = new ArrayList<String>();
continuousSignals = new ArrayList<String>();
for (int j = 0; j < bools.length; j++) {
booleanSignals.add(bools[j]);
}
for (int j = 0; j < conts.length; j++) {
continuousSignals.add(conts[j]);
}
for (int j = 0; j < ints.length; j++) {
integerSignals.add(ints[j]);
}
}
// public ExprTree(Transition transition) {
// }
ExprTree(char willbe, int lNV, int uNV, String var) {
op = "";
r1 = null;
r2 = null;
isit = willbe;
if ((isit == 'b') || (isit == 't'))
logical = true;
else
logical = false;
uvalue = uNV;
lvalue = lNV;
variable = var;
real = 0;
}
public ExprTree(ExprTree nr1, ExprTree nr2, String nop, char willbe) {
op = nop;
r1 = nr1;
r2 = nr2;
isit = willbe;
if ((isit == 'r') || (isit == 'l')) {
logical = true;
uvalue = 1;
lvalue = 0;
} else {
logical = false;
uvalue = INFIN;
lvalue = -INFIN;
}
variable = null;
}
public ExprTree(ExprTree source) {
if (source.op != null) {
op = source.op;
}
isit = source.isit;
lvalue = source.lvalue;
uvalue = source.uvalue;
if (source.variable != null) {
variable = source.variable;
}
real = source.real;
logical = source.logical;
if (source.r1 != null) {
r1 = source.r1;
}
if (source.r2 != null) {
r2 = source.r2;
}
if (source.tokvalue != null) {
tokvalue = source.tokvalue;
}
position = source.position;
token = source.token;
if (source.newresult != null) {
newresult = source.newresult;
}
if (source.booleanSignals != null) {
booleanSignals = source.booleanSignals;
}
if (source.integerSignals != null) {
integerSignals = source.integerSignals;
}
if (source.continuousSignals != null) {
continuousSignals = source.continuousSignals;
}
if (source.lhpn != null) {
lhpn = source.lhpn;
}
}
/**
* This constructor takes a list of variables names.
* Each variable name is either an actual LPN discrete integer variable name, or
* a variable that is created during the Markovian analysis of nested properties.
* @param varNameList
*/
public ExprTree(ArrayList<String> varNameList) {
booleanSignals = new ArrayList<String>();
continuousSignals = new ArrayList<String>();
integerSignals = new ArrayList<String>();
for (int j = 0; j < varNameList.size(); j++) {
integerSignals.add(varNameList.get(j));
}
}
public int intexpr_gettok(String expr) {
char c;
boolean readword;
boolean readnum;
boolean readsci;
boolean readsign;
readword = false;
readnum = false;
readsci = false;
readsign = false;
tokvalue = "";
while (position < expr.length()) {
c = expr.charAt(position);
position++;
switch (c) {
case '(':
case ')':
case '[':
case ']':
case ',':
case '~':
case '|':
case '&':
case '*':
case '^':
case '/':
case '%':
case '=':
case '<':
case '>':
if ((!readword) && (!readnum) && (!readsci)) {
return (c);
}
position--;
return (WORD);
case '+':
case '-':
if ((readsci) && (!readnum) && (readsign)) {
tokvalue += c;
readsign = false;
break;
}
if ((readsci) && (!readnum) && (!readsign)) {
return -1;
} else if ((!readword) && (!readnum) && (!readsci)) {
return (c);
} else {
position--;
return (WORD);
}
case ' ':
if (readword) {
return (WORD);
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (!readword) {
readnum = true;
}
tokvalue += c;
break;
case '.':
if (readsci) {
return -1;
} else if (!readword) {
readnum = true;
}
tokvalue += c;
break;
case 'E':
case 'e':
if (readsci) {
return -1;
} else if (readnum) {
readsci = true;
readnum = false;
readsign = true;
tokvalue += c;
break;
} /*else if (!readword){ // TODO: had to remove to make exponential parse but does scientific notation still work?
return -1;
}*/
default:
if ((readnum) || (readsci)) {
return -1;
}
readword = true;
tokvalue += c;
break;
}
}
if ((!readword) && (!readnum)) {
return (END_OF_STRING);
} else if (readword || readnum) {
return (WORD);
}
return -1;
}
public void intexpr_U(String expr) {
double temp;
switch (token) {
case WORD:
if (tokvalue.toLowerCase().equals("and")) {
token = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
token = intexpr_gettok(expr);
intexpr_R(expr);
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = ((int) (this).lvalue)
& ((int) newresult.lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "&", 'w');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("or")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (int) (this).lvalue
| (int) newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "|", 'w');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("xor")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (int) (this).lvalue
^ (int) newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "X", 'w');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("min")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = Math.min((this).lvalue, newresult.lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "m", 'a');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("max")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = Math.max((this).lvalue, newresult.lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "M", 'a');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("idiv")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = Math
.floor((this).lvalue / newresult.lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "i", 'a');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("bit")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
(this).lvalue = ((int) (this).lvalue >> (int) newresult.lvalue) & 1;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "[]", 'l');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("floor")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((this).isit == 'n') || ((this).isit == 't')
&& ((this).lvalue == (this).uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = Math.floor((this).lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), null, "f", 'a');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("ceil")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((this).isit == 'n') || ((this).isit == 't')
&& ((this).lvalue == (this).uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = Math.ceil((this).lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), null, "c", 'a');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("not")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((this).isit == 'n') || ((this).isit == 't')
&& ((this).lvalue == (this).uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = ~(int) (this).lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), null, "~", 'w');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("int")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_L(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((this).isit == 'n') || ((this).isit == 't')) {
// DO NOTHING
} else {
setNodeValues((this), null, "INT", 'l');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("uniform")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), newresult, "uniform", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("normal")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), newresult, "normal", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("gamma")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), newresult, "gamma", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("lognormal")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), newresult, "lognormal", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("binomial")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), newresult, "binomial", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("exponential")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "exponential", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("chisq")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "chisq", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("laplace")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "laplace", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("cauchy")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "cauchy", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("rayleigh")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "rayleigh", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("poisson")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "poisson", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("bernoulli")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "bernoulli", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("rate")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "rate", 'a');
(token) = intexpr_gettok(expr);
} else if ((tokvalue.equals("true")) || tokvalue.equals("TRUE")) {
setVarValues('t', 1, 1, null);
(token) = intexpr_gettok(expr);
} else if ((tokvalue.equals("maybe")) || tokvalue.equals("MAYBE")) {
setVarValues('t', 0, 1, null);
(token) = intexpr_gettok(expr);
}
else if (tokvalue.equals("t") && !booleanSignals.contains(tokvalue) && !integerSignals.contains(tokvalue)
&& !continuousSignals.contains(tokvalue)) {
setVarValues('t', 1, 1, null);
(token) = intexpr_gettok(expr);
}
else if (tokvalue.equals("T") && !booleanSignals.contains(tokvalue) && !integerSignals.contains(tokvalue)
&& !continuousSignals.contains(tokvalue)) {
setVarValues('t', 1, 1, null);
(token) = intexpr_gettok(expr);
}
else if ((tokvalue.equals("false")) || tokvalue.equals("FALSE")) {
setVarValues('t', 0, 0, null);
(token) = intexpr_gettok(expr);
}
else if (tokvalue.equals("f") && !booleanSignals.contains(tokvalue) && !integerSignals.contains(tokvalue)
&& !continuousSignals.contains(tokvalue)) {
setVarValues('t', 0, 0, null);
(token) = intexpr_gettok(expr);
}
else if (tokvalue.equals("F") && !booleanSignals.contains(tokvalue) && !integerSignals.contains(tokvalue)
&& !continuousSignals.contains(tokvalue)) {
setVarValues('t', 0, 0, null);
(token) = intexpr_gettok(expr);
} else if ((tokvalue.toLowerCase().equals("unknown"))) {
setVarValues('t', 0, 1, null);
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("inf")) {
setVarValues('n', INFIN, INFIN, null);
token = intexpr_gettok(expr);
} else {
// do boolean lookup here!!!
if (booleanSignals.contains(tokvalue)) {
setVarValues('b', 0, 1, tokvalue);
(token) = intexpr_gettok(expr);
return;
}
else if (integerSignals.contains(tokvalue)) {
setVarValues('i', -INFIN, INFIN, tokvalue);
(token) = intexpr_gettok(expr);
return;
}
else if (continuousSignals.contains(tokvalue)) {
setVarValues('c', -INFIN, INFIN, tokvalue);
(token) = intexpr_gettok(expr);
return;
}
if (tokvalue.equals("")) {
throw new IllegalArgumentException(String.format(
"U1:ERROR(%s): Expected a ID, Number, or a (\n",
tokvalue));
} else if ((tokvalue.charAt(0)) > ('9')
|| ((tokvalue.charAt(0)) < '0')) {
throw new IllegalArgumentException(String.format(
"U1:ERROR(%s): Expected a ID, Number, or a (\n",
tokvalue));
}
temp = Double.parseDouble(tokvalue);
setVarValues('n', temp, temp, null);
token = intexpr_gettok(expr);
}
break;
case '(':
(token) = intexpr_gettok(expr);
intexpr_L(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
(token) = intexpr_gettok(expr);
break;
default:
throw new IllegalArgumentException("U2:ERROR: Expected a ID, Number, or a (\n");
}
}
public void intexpr_T(String expr) {
switch (token) {
case WORD:
case '(':
intexpr_U(expr);
break;
case '-':
(token) = intexpr_gettok(expr);
intexpr_U(expr);
// simplify if operands are static
if ((((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = -((this).lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), null, "U-", 'a');
}
break;
default:
throw new IllegalArgumentException("T:ERROR: Expected a ID, Number, (, or -\n");
}
}
public void intexpr_C(String expr) {
newresult = new ExprTree(this);
switch (token) {
case '*':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_W(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (this).lvalue * newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "*", 'a');
}
intexpr_C(expr);
break;
// case '^':
// (token) = intexpr_gettok(expr);
// newresult.token = token;
// newresult.tokvalue = tokvalue;
// newresult.position = position;
// newresult.intexpr_T(expr);
// token = newresult.token;
// position = newresult.position;
// // simplify if operands are static
// if (((newresult.isit == 'n') || (newresult.isit == 't'))
// && (((this).isit == 'n') || ((this).isit == 't'))
// && ((this).lvalue == (this).uvalue)
// && (newresult.lvalue == newresult.uvalue)
// && ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
// && (newresult.lvalue != INFIN)
// && (newresult.lvalue != -INFIN)) {
// (this).isit = 'n';
// (this).lvalue = Math.pow(lvalue, newresult.lvalue);
// (this).uvalue = (this).lvalue;
// } else {
// setNodeValues((this), newresult, "^", 'a');
// }
// intexpr_C(expr);
// break;
case '/':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_W(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (this).lvalue / newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "/", 'a');
}
intexpr_C(expr);
break;
case '%':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_W(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (this).lvalue % newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "%", 'a');
}
intexpr_C(expr);
break;
case '+':
case '-':
case ')':
case '[':
case ']':
case '|':
case '&':
case '=':
case '<':
case '>':
case ',':
case IMPLIES:
case END_OF_STRING:
break;
case '(':
case WORD:
newresult.intexpr_W(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (this).lvalue * newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "*", 'a');
}
intexpr_C(expr);
break;
default:
throw new IllegalArgumentException("ERROR: Expected a * or /\n");
}
}
public void intexpr_V(String expr) {
newresult = new ExprTree(this);
switch (token) {
case '^':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_T(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = Math.pow(lvalue, newresult.lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "^", 'a');
}
intexpr_V(expr);
break;
case '*':
case '/':
case '%':
case '-':
case ')':
case '[':
case ']':
case '|':
case '&':
case '=':
case '<':
case '>':
case ',':
case IMPLIES:
case END_OF_STRING:
break;
case '(':
case WORD:
newresult.intexpr_T(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (this).lvalue * newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "*", 'a');
}
intexpr_V(expr);
break;
default:
throw new IllegalArgumentException("ERROR: Expected a * or /\n");
}
}
public void intexpr_B(String expr) {
newresult = new ExprTree(this);
switch (token) {
case '+':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_S(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (this).lvalue + newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "+", 'a');
}
intexpr_B(expr);
break;
case '-':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_S(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (this).lvalue - newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "-", 'a');
}
intexpr_B(expr);
break;
case ')':
case '[':
case ']':
case '|':
case '&':
case '=':
case '<':
case '>':
case ',':
case IMPLIES:
case END_OF_STRING:
break;
default:
throw new IllegalArgumentException("ERROR: Expected a + or -\n");
}
}
public void intexpr_S(String expr) {
switch (token) {
case WORD:
case '(':
case '-':
intexpr_W(expr);
intexpr_C(expr);
break;
default:
throw new IllegalArgumentException("S:ERROR: Expected a ID, Number, (, or -\n");
}
}
public void intexpr_W(String expr) {
switch (token) {
case WORD:
case '(':
case '-':
intexpr_T(expr);
intexpr_V(expr);
break;
default:
throw new IllegalArgumentException("S:ERROR: Expected a ID, Number, (, or -\n");
}
}
public void intexpr_R(String expr) {
switch (token) {
case WORD:
case '(':
case '-':
intexpr_S(expr);
intexpr_B(expr);
break;
default:
throw new IllegalArgumentException("R:ERROR: Expected a ID, Number, (, or -\n");
}
}
public void intexpr_P(String expr) {
newresult = new ExprTree(this);
//int spos, i;
String ineq = "";
String comp;
switch (token) {
case '=':
//spos = position;
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
tokvalue = newresult.tokvalue;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if (this.lvalue == newresult.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
} else {
if ((this).isit == 'c') {
comp = variable;
// comp += "=";
//// int paren = 0;
//// for (i = spos; i < position; i++) {
//// if (expr.charAt(i) == '(')
//// paren++;
//// if (expr.charAt(i) == ')')
//// paren--;
//// ineq = ineq + expr.charAt(i);
//// }
// comp += ineq;
if (booleanSignals.contains(comp)) {
this.isit = 'b';
this.variable = comp;
this.lvalue = 0;
this.uvalue = 1;
return;
}
booleanSignals.add(comp);
this.isit = 'b';
this.variable = comp;
this.lvalue = 0;
this.uvalue = 1;
return;
}
setNodeValues((this), newresult, "==", 'r');
}
break;
case '>':
//spos = position;
(token) = intexpr_gettok(expr);
newresult.token = token;
if ((token) == '=') {
//spos = position;
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
tokvalue = newresult.tokvalue;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if ((this).lvalue >= newresult.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, ">=", 'r');
}
} else {
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
tokvalue = newresult.tokvalue;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if ((this).lvalue > newresult.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, ">", 'r');
}
}
break;
case '<':
//spos = position;
(token) = intexpr_gettok(expr);
if ((token) == '=') {
//spos = position;
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
tokvalue = newresult.tokvalue;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if ((this).lvalue <= newresult.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "<=", 'r');
}
} else {
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
tokvalue = newresult.tokvalue;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if ((this).lvalue < newresult.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "<", 'r');
}
}
break;
case '[':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
tokvalue = newresult.tokvalue;
position = newresult.position;
if ((token) != ']') {
throw new IllegalArgumentException("ERROR: Expected a ]\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
(this).lvalue = (((int) (this).lvalue) >> ((int) newresult.lvalue)) & 1;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "[]", 'l');
}
(token) = intexpr_gettok(expr);
break;
case '&':
case '|':
case ')':
case IMPLIES:
case END_OF_STRING:
break;
default:
throw new IllegalArgumentException("ERROR: Expected a [, =, <, or >\n");
}
}
public void intexpr_O(String expr) {
switch (token) {
case WORD:
case '(':
case '-':
intexpr_R(expr);
intexpr_P(expr);
break;
default:
throw new IllegalArgumentException("O:ERROR: Expected a ID, Number, or a (\n");
}
}
public void intexpr_N(String expr) {
switch (token) {
case WORD:
case '-':
case '(':
intexpr_O(expr);
break;
case '~':
(token) = intexpr_gettok(expr);
intexpr_O(expr);
// simplify if operands are static
if ((((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)) {
(this).isit = 't';
if (this.lvalue == 1) {
this.lvalue = 0;
} else {
this.lvalue = 1;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), null, "!", 'l');
}
break;
default:
throw new IllegalArgumentException("N:ERROR: Expected a ID, Number, (, or -\n");
}
}
public void intexpr_E(String expr) {
newresult = new ExprTree(this);
switch (token) {
case '&':
token = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_N(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if ((this.lvalue == 0) || (newresult.lvalue == 0)) {
this.lvalue = 0;
} else {
this.lvalue = 1;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "&&", 'l');
}
intexpr_E(expr);
break;
case '|':
case ')':
case IMPLIES:
case END_OF_STRING:
break;
default:
throw new IllegalArgumentException(String.format("ERROR(%c): Expected an &\n", (token)));
}
}
public void intexpr_D(String expr) {
newresult = new ExprTree(this);
switch (token) {
case '|':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_M(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if (this.lvalue != 0 || newresult.lvalue != 0) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "||", 'l');
}
intexpr_D(expr);
break;
case ')':
case END_OF_STRING:
break;
case IMPLIES:
(token) = intexpr_gettok(expr);
intexpr_M(expr);
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if (this.lvalue != 0 || newresult.lvalue == 0) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues(this, newresult, "->", 'l');
}
intexpr_D(expr);
break;
default:
throw new IllegalArgumentException("ERROR: Expected an | or ->\n");
}
}
public void intexpr_M(String expr) {
switch (token) {
case WORD:
case '(':
case '~':
case '-':
intexpr_N(expr);
intexpr_E(expr);
break;
default:
throw new IllegalArgumentException("M: ERROR: Expected a ID, Number, (, or -\n");
}
}
public void intexpr_L(String expr) {
switch (token) {
case WORD:
case '(':
case '~':
case '-':
intexpr_M(expr);
intexpr_D(expr);
break;
default:
throw new IllegalArgumentException("L:ERROR: Expected a ID, Number, (, or -\n");
}
}
@Override
public String toString() {
String result = "";
result = getElement("LHPN");
return result;
}
public String toString(String type) {
String result = "";
result = getElement(type);
return result;
}
public String toString(String type, String lhpnSbml) {
String result = "";
result = getElement(lhpnSbml);
if (type.equals("continuous") || type.equals("integer")) {
if (isit == 't') {
if (uvalue == 0) {
result = "0";
} else {
result = "1";
}
}
} else {
if (isit == 'n') {
if (uvalue == 0) {
result = "false";
} else {
result = "true";
}
}
}
return result;
}
public boolean implies(ExprTree expr) {
if (isEqual(expr)) {
return true;
}
if (expr.isit == 'l' && expr.op.equals("||")) {
if (implies(expr.r1) || implies(expr.r2)) {
return true;
}
} else if (expr.isit == 'l' && expr.op.equals("&&")) {
if (implies(expr.r1) && implies(expr.r2)) {
return true;
}
}
switch (isit) {
case 't': // Truth value
if (uvalue == 1 && lvalue == 1) {
return false;
} else if (uvalue == 0 && lvalue == 0) {
return true;
} else {
return false;
}
case 'r': // Relational
if (op.contains(">")) {
if (expr.isit == 'r' && expr.op.contains(">")) {
if (r2.lvalue > expr.r2.uvalue) {
return true;
} else if (r2.lvalue == expr.r2.uvalue
&& op.length() >= expr.op.length()) {
return true;
}
}
} else if (op.contains("<")) {
if (expr.isit == 'r' && expr.op.contains("<")) {
if (r2.lvalue < expr.r2.uvalue) {
return true;
} else if (r2.lvalue == expr.r2.uvalue
&& op.length() >= expr.op.length()) {
return true;
}
}
}
return false;
case 'l': // Logical
if (op.equals("&&")) {
if (expr.isit == 'b') {
if (r1.implies(expr) || r2.implies(expr)) {
return true;
}
}
} else if (op.equals("||")) {
if (expr.isit == 'b') {
if (r1.implies(expr) && r2.implies(expr)) {
return true;
}
}
}
return false;
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
case 'n': // Number
case 'w': // bitWise
case 'a': // Arithmetic
default:
return false;
}
}
public boolean containsVar(String var) {
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
if (variable.equals(var))
return true;
return false;
case 'r': // Relational
case 'l': // Logical
case 'a': // Arithmetic
case 'w': // bitWise
if (r1 != null) {
if (r1.containsVar(var)) {
return true;
}
}
if (r2 != null) {
if (r2.containsVar(var)) {
return true;
}
}
return false;
case 'n': // Number
case 't': // Truth value
default:
return false;
}
}
public ArrayList<String> getVars() {
ArrayList<String> vars = new ArrayList<String>();
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
if (!vars.contains(variable))
vars.add(variable);
break;
case 'r': // Relational
case 'l': // Logical
case 'a': // Arithmetic
case 'w': // bitWise
if (r1 != null)
vars.addAll(r1.getVars());
if (r2 != null)
vars.addAll(r2.getVars());
break;
case 'n': // Number
case 't': // Truth value
default:
break;
}
return vars;
}
/**
* Returns a list of the continuous variable's names that are
* contained in this ExprTree.
* @return
* The list of name of the continuous variables in this
* ExprTree.
*/
public ArrayList<String> getContVars() {
ArrayList<String> vars = new ArrayList<String>();
switch (isit) {
//case 'b': // Boolean
//case 'i': // Integer
case 'c': // Continuous
if (!vars.contains(variable))
vars.add(variable);
break;
case 'r': // Relational
case 'l': // Logical
case 'a': // Arithmetic
case 'w': // bitWise
if (r1 != null)
vars.addAll(r1.getVars());
if (r2 != null)
vars.addAll(r2.getVars());
break;
case 'n': // Number
case 't': // Truth value
default:
break;
}
return vars;
}
public void scaleVals(Double scaleFactor) { // SB
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
break;
case 'r': // Relational
case 'l': // Logical
case 'a': // Arithmetic
case 'w': // bitWise
if (r1 != null)
r1.scaleVals(scaleFactor);
if (r2 != null)
r2.scaleVals(scaleFactor);
break;
case 'n': // Number
variable = String
.valueOf((int) (Double.parseDouble(variable) * scaleFactor));
break;
case 't': // Truth value
default:
break;
}
}
public boolean containsCont() {
switch (isit) {
case 'b': // Boolean
case 't': // Truth value
return false;
case 'i': // Integer
case 'c': // Continuous
case 'r': // Relational
case 'a': // Arithmetic
case 'n': // Number
return true;
case 'l': // Logical
case 'w': // bitWise
boolean r1cont = false,
r2cont = false;
if (r1 != null)
r1cont = r1.containsCont();
if (r2 != null)
r2cont = r2.containsCont();
return (r1cont || r2cont);
}
return false;
}
/**
* This method will return true if the
* expression tree contains a continuous variable.
* This is difference from containsCont() which
* will return true if there is an integer,
* relational, arithmetic or number.
* @return
* True if this ExprTree continuous a
* continuous variable.
*/
public boolean containsExactlyCont() {
switch (isit) {
// These are leaf nodes that we are not looking for.
case 'b': // Boolean
case 't': // Truth value
case 'i': // Integer
case 'n': // Number
return false;
// This is what we are looking for.
case 'c': // Continuous
return true;
// The subexpression may contain a continuous variable
// so need to check further.
case 'a': // Arithmetic
case 'r': // Relational
case 'l': // Logical
case 'w': // bitWise
boolean r1cont = false,
r2cont = false;
if (r1 != null)
r1cont = r1.containsExactlyCont();
if (r2 != null)
r2cont = r2.containsExactlyCont();
return (r1cont || r2cont);
}
return false;
}
public void replace(String var, String type, ExprTree e) {
if (this == e) {
return;
}
boolean simplify = false;
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
if (variable.equals(var)) {
if (e.isit == 'a' || e.isit == 'r' || e.isit == 'l'
|| e.isit == 'w') {
setNodeValues(e.r1, e.r2, e.op, e.isit);
} else {
setVarValues(e.isit, e.lvalue, e.uvalue, e.variable);
}
}
return;
case 'w': // bitWise
case 'l': // Logical
case 'r': // Relational
case 'a': // Arithmetic
if (r1 != null || r2 != null) {
if (r1 != null)
r1.replace(var, type, e);
if (r2 != null)
r2.replace(var, type, e);
break;
}
// simplify if operands are static
if (op.equals("&&")) {
if ((r1.isit == 'n') || (r1.isit == 't')) {
if (r1.lvalue == 0) {
setVarValues('t', 0.0, 0.0, null);
simplify = true;
} else {
if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w'
|| r2.isit == 'r') {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
} else {
setVarValues(r2.isit, r2.lvalue, r2.uvalue,
r2.variable);
}
}
} else if (((r2).isit == 'n') || ((r2).isit == 't')) {
if (r2.lvalue == 0) {
setVarValues('t', 0.0, 0.0, null);
simplify = true;
} else {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue,
r1.variable);
}
}
}
} else if (op.equals("||")) {
if ((r1.isit == 'n') || (r1.isit == 't')) {
if (r1.lvalue == 1) {
setVarValues('t', 1.0, 1.0, null);
simplify = true;
} else {
if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w'
|| r2.isit == 'r') {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
} else {
setVarValues(r2.isit, r2.lvalue, r2.uvalue,
r2.variable);
}
}
} else if (((r2).isit == 'n') || ((r2).isit == 't')) {
if (r2.lvalue == 1) {
setVarValues('t', 1.0, 1.0, null);
simplify = true;
} else {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue,
r1.variable);
}
}
} else if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if (r1.lvalue != 0 || r2.lvalue != 0) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("->")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if (r1.lvalue != 0 || r2.lvalue == 0) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("!")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 't';
if (r1.lvalue == 1) {
this.lvalue = 0;
} else {
this.lvalue = 1;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("==")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if (r1.lvalue == r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals(">=")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue >= r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals(">")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue > r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("<=")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue <= r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("<")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue < r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("&")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = ((int) (r1).lvalue) & ((int) r2.lvalue);
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("|")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (int) (r1).lvalue | (int) r2.lvalue;
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("X")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (int) (r1).lvalue ^ (int) r2.lvalue;
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("m")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = Math.min((r1).lvalue, r2.lvalue);
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("M")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = Math.max((r1).lvalue, r2.lvalue);
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("i")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = Math.floor((r1).lvalue / (r2).lvalue);
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("f")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = Math.floor((r1).lvalue);
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("c")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = Math.ceil((r1).lvalue);
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("~")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = ~(int) (r1).lvalue;
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("[]")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
(this).lvalue = (((int) (r1).lvalue) >> ((int) r2.lvalue)) & 1;
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("U-")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = -((r1).lvalue);
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("*")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue * r2.lvalue;
(this).uvalue = (this).lvalue;
}
} else if (op.equals("/")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue / r2.lvalue;
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("%")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue % r2.lvalue;
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("+")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue + r2.lvalue;
(this).uvalue = (this).lvalue;
} else if ((r1.isit == 'n') || (r1.isit == 't')) {
if (r1.lvalue == 0 && r1.uvalue == 0) {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
}
} else if (((r2).isit == 'n') || ((r2).isit == 't')) {
if (r2.lvalue == 0 && r2.uvalue == 0) {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
}
}
} else if (op.equals("-")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue - r2.lvalue;
(this).uvalue = (this).lvalue;
simplify = true;
}
}
break;
case 't': // Truth value
if (lvalue != 0 && uvalue != 0) {
lvalue = 1;
uvalue = 1;
} else if (lvalue != 0 || uvalue != 0) {
lvalue = 0;
uvalue = 1;
}
return;
case 'n': // Number
break;
}
if (simplify) {
if (type.equals("integer") || type.equals("continuous")) {
isit = 'n';
} else {
isit = 't';
if (lvalue != 0 && uvalue != 0) {
lvalue = 1;
uvalue = 1;
} else if (lvalue != 0 || uvalue != 0) {
lvalue = 0;
uvalue = 1;
}
}
}
}
public void replaceVar(String var1, String var2) {
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
if (variable.equals(var1)) {
variable = var2;
}
return;
case 'w': // bitWise
case 'l': // Logical
case 'r': // Relational
case 'a': // Arithmetic
if (r1 != null)
r1.replaceVar(var1, var2);
if (r2 != null)
r2.replaceVar(var1, var2);
break;
case 't': // Truth value
case 'n': // Number
break;
}
}
public char getChange(HashMap<String, String> variables) {
switch (isit) {
case 'b': // Boolean
if (variables.containsKey(variable)) {
if (variables.get(variable).toString().toLowerCase().equals("false"))
return 'F';
if (variables.get(variable).toString().toLowerCase().equals("true"))
return 'T';
return 'X';
}
return 'U';
case 't': // Truth value
/*
if (uvalue == 0)
return 'F';
else if (lvalue == 1)
return 'T';
*/
return 'U';
case 'l': // Logical
if (op.equals("||")) {
if (r1.getChange(variables) == 'T'
|| r2.getChange(variables) == 'T') {
return 'T';
} else if (r1.getChange(variables) == 'X'
|| r2.getChange(variables) == 'X') {
return 'X';
} else if (r1.getChange(variables) == 't') {
if (r2.getChange(variables) == 'f') {
return 'X';
}
return 't';
} else if (r2.getChange(variables) == 't') {
if (r1.getChange(variables) == 'f') {
return 'X';
}
return 't';
} else if (r1.getChange(variables) == 'f'
|| r2.getChange(variables) == 'f') {
return 'f';
} else if (r1.getChange(variables) == 'F') {
if (r2.getChange(variables) == 'F') {
return 'F';
}
return 'f';
} else if (r2.getChange(variables) == 'F') {
return 'f';
}
return 'U';
} else if (op.equals("&&")) {
if (r1.getChange(variables) == 'F'
|| r2.getChange(variables) == 'F') {
return 'F';
} else if (r1.getChange(variables) == 'X'
|| r2.getChange(variables) == 'X') {
return 'X';
} else if (r1.getChange(variables) == 'f') {
if (r2.getChange(variables) == 't') {
return 'X';
}
return 'f';
} else if (r2.getChange(variables) == 'f') {
if (r1.getChange(variables) == 't') {
return 'X';
}
return 'f';
} else if (r1.getChange(variables) == 't'
|| r2.getChange(variables) == 't') {
return 't';
} else if (r1.getChange(variables) == 'T') {
if (r2.getChange(variables) == 'T') {
return 'T';
}
return 't';
} else if (r2.getChange(variables) == 'T') {
return 't';
}
return 'U';
} else if (op.equals("!")) {
if (r1.getChange(variables) == 'T') {
return 'F';
} else if (r1.getChange(variables) == 'F') {
return 'T';
} else if (r1.getChange(variables) == 't') {
return 'f';
} else if (r1.getChange(variables) == 'f') {
return 't';
}
return r1.getChange(variables);
} else if (op.equals("->")) {
if (r1.getChange(variables) == 'T'
|| r2.getChange(variables) == 'F') {
return 'T';
} else if (r1.getChange(variables) == 'X'
|| r2.getChange(variables) == 'X') {
return 'X';
} else if (r1.getChange(variables) == 't') {
if (r2.getChange(variables) == 't') {
return 'X';
}
return 't';
} else if (r2.getChange(variables) == 'f') {
if (r1.getChange(variables) == 'f') {
return 'X';
}
return 't';
} else if (r1.getChange(variables) == 'f') {
return 'f';
} else if (r2.getChange(variables) == 't') {
return 'f';
} else if (r1.getChange(variables) == 'F') {
if (r2.getChange(variables) == 'T') {
return 'F';
}
return 'f';
} else if (r2.getChange(variables) == 'T') {
return 'f';
}
return 'U';
}
break;
case 'r': // Relational
boolean flag = false;
for (String var : getVars()) {
if (variables.containsKey(var)) {
flag = true;
break;
}
}
if (!flag) {
return 'U';
}
if (op.equals("==")) {
if (r1.evaluateExpr(variables) == r2.evaluateExpr(variables)) {
return 'T';
} else if (new Double(r1.evaluateExpr(variables))
.equals(Double.NaN)
|| new Double(r2.evaluateExpr(variables))
.equals(Double.NaN)) {
return 'X';
}
return 'F';
} else if (op.equals(">=")) {
if (r1.evaluateExpr(variables) >= r2.evaluateExpr(variables)) {
return 'T';
} else if (new Double(r2.evaluateExpr(variables))
.equals(Double.NaN)
|| new Double(r1.evaluateExpr(variables))
.equals(Double.NaN)) {
return 'X';
}
return 'F';
} else if (op.equals("<=")) {
if (r1.evaluateExpr(variables) <= r2.evaluateExpr(variables)) {
return 'T';
} else if (new Double(r1.evaluateExpr(variables))
.equals(Double.NaN)
|| new Double(r2.evaluateExpr(variables))
.equals(Double.NaN)) {
return 'X';
}
return 'F';
} else if (op.equals(">")) {
if (r1.evaluateExpr(variables) > r2.evaluateExpr(variables)) {
return 'T';
} else if (new Double(r1.evaluateExpr(variables))
.equals(Double.NaN)
|| new Double(r2.evaluateExpr(variables))
.equals(Double.NaN)) {
return 'X';
}
return 'F';
} else if (op.equals("<")) {
if (r1.evaluateExpr(variables) < r2.evaluateExpr(variables)) {
return 'T';
} else if (new Double(r1.evaluateExpr(variables))
.equals(Double.NaN)
|| new Double(r2.evaluateExpr(variables))
.equals(Double.NaN)) {
return 'X';
}
return 'F';
}
return 'X';
case 'i': // Integer
if (variables.containsKey(variable)) {
try {
if (Integer.parseInt(variables.get(variable)) == 0.0) {
return 'F';
}
return 'T';
} catch (Exception e) {
return 'X';
}
}
return 'U';
case 'c': // Continuous
return 'X';
case 'n': // Number
if (uvalue == 0.0 && lvalue == 0.0) {
return 'F';
}
return 'T';
}
return 'X';
}
public boolean becomesFalse(HashMap<String, String> variables) {
switch (isit) {
case 'b': // Boolean
if (variables.containsKey(variable))
if (variables.get(variable).toString().toLowerCase().equals(
"false"))
return true;
return false;
case 't': // Truth value
if (lvalue == 0)
return true;
return false;
case 'l': // Logical
if (op.equals("||")) {
if (r1.becomesFalse(variables) && r2.becomesFalse(variables)) {
return true;
}
return false;
} else if (op.equals("&&")) {
if ((r1.becomesFalse(variables) && !r2.becomesTrue(variables))
|| (!r1.becomesTrue(variables) && r2
.becomesFalse(variables)))
return true;
return false;
} else if (op.equals("==")) {
if (!(r1.isEqual(r2) || r1.evaluateExpr(variables) == r2
.evaluateExpr(variables)))
return true;
return false;
} else if (op.equals("!")) {
if (r1.becomesTrue(variables))
return true;
return false;
} else if (op.equals("->")) {
if (r1.becomesFalse(variables) || r2.becomesTrue(variables)) {
return true;
}
return false;
} else if (op.equals("[]")) {
if (!(evaluateExpr(variables) == 0.0)) {
return true;
}
return false;
}
break;
case 'w': // bitWise
if (op.equals("&")) {
if (!(evaluateExpr(variables) == 0.0)) {
return true;
}
return false;
} else if (op.equals("|")) {
if (!(evaluateExpr(variables) == 0.0)) {
return true;
}
return false;
} else if (op.equals("X")) {
if (!(evaluateExpr(variables) == 0.0)) {
return true;
}
return false;
} else if (op.equals("~")) {
if (!(evaluateExpr(variables) == 0.0)) {
return true;
}
return false;
}
break;
case 'r': // Relational
if (r1.isit == 'i') {
if (!variables.containsKey(r1.variable)) {
return false;
}
if (op.equals("==")) {
if (r1.evaluateExpr(variables) == r2
.evaluateExpr(variables)) {
return false;
}
return true;
} else if (op.equals(">=")) {
if (r1.evaluateExpr(variables) >= r2
.evaluateExpr(variables)) {
return false;
}
return true;
} else if (op.equals("<=")) {
if (r1.evaluateExpr(variables) <= r2
.evaluateExpr(variables)) {
return false;
}
return true;
} else if (op.equals(">")) {
if (r1.evaluateExpr(variables) > r2.evaluateExpr(variables)) {
return false;
}
return true;
} else if (op.equals("<")) {
if (r1.evaluateExpr(variables) < r2.evaluateExpr(variables)) {
return false;
}
return true;
}
return true;
}
return true;
case 'i': // Integer
if (variables.containsKey(variable)) {
if (Integer.parseInt(variables.get(variable)) == 0.0) {
return true;
}
return false;
}
return false;
case 'c': // Continuous
return true;
case 'a': // Arithmetic
boolean contains = false;
for (String s : getVars()) {
if (variables.containsKey(s)) {
contains = true;
break;
}
}
if (!contains) {
return false;
}
if (!(evaluateExpr(variables) == 0.0)) {
return false;
}
return true;
case 'n': // Number
if (uvalue == 0.0 && lvalue == 0.0) {
return true;
}
return false;
}
return false;
}
public boolean becomesTrue(HashMap<String, String> variables) {
switch (isit) {
case 'b': // Boolean
if (variables.containsKey(variable)) {
if (variables.get(variable).toString().matches("[\\d[\\.]]+")) {
if (Double.parseDouble(variables.get(variable).toString()) != 0) {
return true;
}
}
if (variables.get(variable).toString().toLowerCase().equals(
"true"))
return true;
}
return false;
case 'i': // Integer
if (variables.containsKey(variable)) {
if (!variables.get(variable).equals("0.0")) {
return true;
}
}
return false;
case 'c': // Continuous
return true;
case 'n': // Number
case 't': // Truth value
if (uvalue != 0)
return true;
return false;
case 'l': // Logical
if (op.equals("||")) {
if (r1.becomesTrue(variables) || r2.becomesTrue(variables))
return true;
return false;
} else if (op.equals("&&")) {
if ((r1.becomesTrue(variables) && !r2.becomesFalse(variables))
|| (!r1.becomesFalse(variables) && r2
.becomesTrue(variables)))
return true;
return false;
} else if (op.equals("==")) {
if (r1.isEqual(r2, variables)
|| r1.evaluateExpr(variables) == r2
.evaluateExpr(variables))
return true;
return false;
} else if (op.equals("!")) {
if (r1.becomesFalse(variables))
return true;
return false;
} else if (op.equals("->")) {
if (r1.becomesTrue(variables) || r2.becomesFalse(variables)) {
return true;
}
return false;
}
break;
case 'w': // bitWise
if (op.equals("&")) {
if (evaluateExpr(variables) == 0.0) {
return false;
}
return true;
} else if (op.equals("|")) {
if (evaluateExpr(variables) == 0.0) {
return false;
}
return true;
} else if (op.equals("X")) {
if (evaluateExpr(variables) == 0.0) {
return false;
}
return true;
} else if (op.equals("~")) {
if (evaluateExpr(variables) == 0.0) {
return false;
}
return true;
} else if (op.equals("[]")) {
if (evaluateExpr(variables) == 0.0) {
return false;
}
return true;
}
break;
case 'r': // Relational
if (r1.isit == 'i') {
if (!variables.containsKey(r1.variable)) {
return false;
}
if (op.equals("==")) {
if (!(r1.evaluateExpr(variables) == r2
.evaluateExpr(variables))) {
return false;
}
return true;
} else if (op.equals(">=")) {
if (!(r1.evaluateExpr(variables) >= r2
.evaluateExpr(variables))) {
return false;
}
return true;
} else if (op.equals("<=")) {
if (!(r1.evaluateExpr(variables) <= r2
.evaluateExpr(variables))) {
return false;
}
return true;
} else if (op.equals(">")) {
if (!(r1.evaluateExpr(variables) > r2
.evaluateExpr(variables))) {
return false;
}
return true;
} else if (op.equals("<")) {
if (!(r1.evaluateExpr(variables) < r2
.evaluateExpr(variables))) {
return false;
}
return true;
}
return true;
}
return true;
case 'a': // Arithmetic
boolean contains = false;
for (String s : getVars()) {
if (variables.containsKey(s)) {
contains = true;
break;
}
}
if (!contains) {
return false;
}
if (!(evaluateExpr(variables) != 0.0)) {
return false;
}
return true;
}
return true;
}
public String getElement(String type) {
boolean sbmlFlag;
sbmlFlag = type.equals("SBML");
Boolean verilog = type.equalsIgnoreCase("Verilog");
String result = "";
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
if (!sbmlFlag) {
result = variable;
} else {
if (isit == 'b') {
result = "eq(" + variable + ",1)";
} else {
result = variable;
}
}
break;
case 'n': // Number
// long term solution: create initial assignment
// short term solution: initialize all inf, -inf, [-inf, inf] to 0
// initialize [l,u] to (l+u)/2
Double tempuval = uvalue;
Double templval = lvalue;
if ((uvalue == lvalue) || tempuval.toString().equals("")) {
if (lvalue == INFIN) {
result = "inf";
} else if (lvalue == -INFIN) {
result = "-inf";
} else {
if (tempuval % 1 == 0) {
int tempval = (int) (tempuval / 1);
result = new Integer(tempval).toString();
} else {
result = tempuval.toString();
}
}
} else {
String lval;
if (lvalue == INFIN) {
lval = "inf";
} else if (lvalue == -INFIN) {
lval = "-inf";
} else {
if (tempuval % 1 == 0) {
int tempval = (int) (templval / 1);
lval = new Integer(tempval).toString();
} else {
lval = templval.toString();
}
}
String uval;
if (uvalue == INFIN) {
uval = "inf";
} else if (uvalue == -INFIN) {
uval = "-inf";
} else {
if (tempuval % 1 == 0) {
int tempval = (int) (tempuval / 1);
uval = new Integer(tempval).toString();
} else {
uval = tempuval.toString();
}
}
if (verilog) {
result = "uniform(" + lval + "," + uval + ")";
} else {
result = "uniform(" + lval + "," + uval + ")";
}
}
break;
case 't': // Truth value
if (uvalue == 0 && lvalue == 0) {
if (verilog)
result = "0";
else
result = "false";
} else if (uvalue == 1 && lvalue == 1) {
if (verilog)
result = "1";
else
result = "true";
} else {
if (sbmlFlag)
result = "true";
else
result = "UNKNOWN";
}
break;
case 'w': // bitWise
if (op.equals("&")) {
if (r1 != null && r2 != null) {
if (sbmlFlag) {
result = "BITAND(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
} else if (verilog) {
result = r1.getElement(type) + "&"
+ r2.getElement(type);
} else {
result = "and(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
} else if (op.equals("|")) {
if (r1 != null && r2 != null) {
if (sbmlFlag) {
result = "BITOR(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
} else if (verilog) {
result = r1.getElement(type) + "|"
+ r2.getElement(type);
} else {
result = "or(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
} else if (op.equals("!")) {
if (r1 != null && r2 != null) {
if (sbmlFlag) {
result = "BITNOT(" + r1.getElement(type) + ")";
} else if (verilog) {
result = "~" + r1.getElement(type);
} else {
result = "not(" + r1.getElement(type) + ")";
}
}
} else if (op.equals("X")) {
if (r1 != null && r2 != null) {
if (sbmlFlag) {
result = "XOR(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
} else if (verilog) {
result = r1.getElement(type) + "^"
+ r2.getElement(type);
} else {
result = "exor(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
}
break;
case 'a': // Arithmetic
case 'r': // Relational
case 'l': // Logical
if (op.equals("!")) {
if (r1 != null) {
if (r1.isit == 'b' || r1.isit == 'i' || r1.isit == 'c'
|| r1.isit == 'n' || r1.isit == 't') {
if (sbmlFlag) {
result = "not(" + r1.getElement(type) + ")";
} else if (verilog) {
result = "!" + r1.getElement(type);
} else {
result = "~" + r1.getElement(type);
}
} else {
if (sbmlFlag) {
result = "not(" + r1.getElement(type) + ")";
} else if (verilog) {
result = "!" + "(" + r1.getElement(type) + ")";
} else {
result = "~" + "(" + r1.getElement(type) + ")";
}
}
}
break;
}
if (op.equals("&&")) {
if (r1.isit == 'r'
|| (r1.isit == 'l' && r1.op.equals("||"))) {
if (r1 != null) {
if (sbmlFlag) {
result = "and(" + r1.getElement(type) + ",";
} else if (verilog) {
result = "(" + r1.getElement(type) + ")&&";
} else {
result = "(" + r1.getElement(type) + ")";
}
}
} else {
if (r1 != null) {
if (sbmlFlag) {
result = "and(" + r1.getElement(type) + ",";
} else if (verilog) {
result = r1.getElement(type) + "&&";
} else {
result = r1.getElement(type);
}
}
}
if (!sbmlFlag && !verilog) {
result = result + "&";
}
if (r2.isit == 'r'
|| (r2.isit == 'l' && r2.op.equals("||"))) {
if (r2 != null) {
if (sbmlFlag) {
result = result + r2.getElement(type) + ")";
} else {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
} else {
if (r2 != null) {
if (sbmlFlag) {
result = result + r2.getElement(type) + ")";
} else {
result = result + r2.getElement(type);
}
}
}
} else if (op.equals("||")) {
if (r1.isit == 'r') {
if (r1 != null) {
if (sbmlFlag) {
result = "or(" + r1.getElement(type) + ",";
} else if (verilog) {
result = "(" + r1.getElement(type) + ")||";
} else {
result = "(" + r1.getElement(type) + ")";
}
}
} else {
if (r1 != null) {
if (sbmlFlag) {
result = "or(" + r1.getElement(type) + ",";
} else if (verilog) {
result = r1.getElement(type) + "||";
} else {
result = r1.getElement(type);
}
}
}
if (!sbmlFlag && !verilog) {
result = result + "|";
}
if (r2.isit == 'r') {
if (r2 != null) {
if (sbmlFlag) {
result = result + r2.getElement(type) + ")";
} else {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
} else {
if (r2 != null) {
if (sbmlFlag) {
result = result + r2.getElement(type) + ")";
} else {
result = result + r2.getElement(type);
}
}
}
} else if (op.equals("f")) {
if (r1 != null) {
if (r1.isit == 'n') {
result = new Integer((int) Math.floor(r1.lvalue))
.toString();
} else {
if (sbmlFlag) {
result = "floor(" + r1.getElement(type) + ")";
} else if (verilog) {
result = "$floor(" + r1.getElement(type) + ")";
} else {
result = "floor(" + r1.getElement(type) + ")";
}
}
}
} else if (op.equals("c")) {
if (r1 != null) {
if (r1.isit == 'n') {
result = new Integer((int) Math.ceil(r1.lvalue))
.toString();
} else {
if (sbmlFlag) {
result = "ceil(" + r1.getElement(type) + ")";
} else if (verilog) {
result = "$ceil(" + r1.getElement(type) + ")";
} else {
result = "ceil(" + r1.getElement(type) + ")";
}
}
}
} else if (op.equals("m")) {
if (r1 != null && r2 != null) {
if (r1.isit == 'n' && r2.isit == 'n') {
if (r1.lvalue < r2.lvalue) {
result = r1.getElement(type);
} else {
result = r2.getElement(type);
}
} else {
if (sbmlFlag) {
result = "piecewise(" + r1.getElement(type)
+ ",leq(" + r1.getElement(type) + ","
+ r2.getElement(type) + "),"
+ r2.getElement(type) + ")";
//} else if (verilog) {
//result = "min(" + r1.getElement(type) + ","
// + r2.getElement(type) + ")";
} else if (verilog) {
result = "("+r1.getElement(type) +"<"+r2.getElement(type) +"?"+r1.getElement(type) +":"+r2.getElement(type) +")";
} else {
result = "min(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
}
} else if (op.equals("M")) {
if (r1 != null && r2 != null) {
if (r1.isit == 'n' && r2.isit == 'n') {
if (r1.lvalue > r2.lvalue) {
result = r1.getElement(type);
} else {
result = r2.getElement(type);
}
} else {
if (sbmlFlag) {
result = "piecewise(" + r1.getElement(type)
+ ",geq(" + r1.getElement(type) + ","
+ r2.getElement(type) + "),"
+ r2.getElement(type) + ")";
//} else if (verilog) {
//result = "max(" + r1.getElement(type) + ","
//+ r2.getElement(type) + ")";
} else if (verilog) {
result = "("+r1.getElement(type) +">"+r2.getElement(type) +"?"+r1.getElement(type) +":"+r2.getElement(type) +")";
} else {
result = "max(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
}
} else if (op.equals("i")) {
if (r1 != null && r2 != null) {
if (sbmlFlag) {
result = "floor(" + r1.getElement(type) + "/"
+ r2.getElement(type) + ")";
} else if (verilog) {
result = "floor(" + r1.getElement(type) + "/"
+ r2.getElement(type) + ")";
} else {
result = "idiv(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
} else if (op.equals("uniform")) {
if (r1 != null && r2 != null) {
if (verilog) {
result = "uniform(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
} else {
result = "uniform(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
} // TODO: Add verilog functions for other distributions
else if (op.equals("[]")) {
if (r1 != null && r2 != null) {
result = "BIT(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
} else if (op.equals("normal")) {
if (r1 != null && r2 != null) {
result = "normal(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
} else if (op.equals("gamma")) {
if (r1 != null && r2 != null) {
result = "gamma(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
} else if (op.equals("lognormal")) {
if (r1 != null && r2 != null) {
result = "lognormal(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
} else if (op.equals("binomial")) {
if (r1 != null && r2 != null) {
result = "binomial(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
} else if (op.equals("exponential")) {
if (r1 != null) {
result = "exponential(" + r1.getElement(type) + ")";
}
} else if (op.equals("chisq")) {
if (r1 != null) {
result = "chisq(" + r1.getElement(type) + ")";
}
} else if (op.equals("laplace")) {
if (r1 != null) {
result = "laplace(" + r1.getElement(type) + ")";
}
} else if (op.equals("cauchy")) {
if (r1 != null) {
result = "cauchy(" + r1.getElement(type) + ")";
}
} else if (op.equals("rayleigh")) {
if (r1 != null) {
result = "rayleigh(" + r1.getElement(type) + ")";
}
} else if (op.equals("poisson")) {
if (r1 != null) {
result = "poisson(" + r1.getElement(type) + ")";
}
} else if (op.equals("bernoulli")) {
if (r1 != null) {
result = "bernoulli(" + r1.getElement(type) + ")";
}
} else if (op.equals("rate")) {
if (r1 != null) {
result = "rate(" + r1.getElement(type) + ")";
}
} else if (op.equals("INT")) {
if (r1 != null) {
if (sbmlFlag) {
result = "piecewise(1," + r1.getElement(type)
+ ",0 )";
} else {
result = "INT(" + r1.getElement(type) + ")";
}
}
} else if (op.equals("==")) {
if (r1 != null) {
if (sbmlFlag) {
result = "eq(" + r1.getElement(type) + ",";
} else if (verilog) {
result = r1.getElement(type) + "==";
} else {
result = r1.getElement(type);
}
}
if (!sbmlFlag && !verilog) {
result = result + "=";
}
if (r2 != null) {
if (sbmlFlag) {
result = result + r2.getElement(type) + ")";
} else {
result = result + r2.getElement(type);
}
}
} else if (op.equals("+")) {
if (r1.isit == 'n' && r1.lvalue >= 0 && r2.isit == 'a'
&& r2.op.equals("uniform")) {
ExprTree tempUniform = new ExprTree(r2);
r1.setNodeValues(r1, tempUniform.r1, "+", 'a');
r2.setNodeValues(r1, tempUniform.r2, "+", 'a');
isit = 'a';
op = "uniform";
} else if (r1.isit == 'a' && r1.op.equals("uniform")
&& r2.isit == 'n' && r2.lvalue >= 0) {
ExprTree tempUniform = new ExprTree(r1);
r1.setNodeValues(r2, tempUniform.r1, "+", 'a');
r2.setNodeValues(r2, tempUniform.r2, "+", 'a');
isit = 'a';
op = "uniform";
} else {
try {
String r1String = r1.getElement(type);
String r2String = r2.getElement(type);
result = new Float(Float.parseFloat(r1String)
+ Float.parseFloat(r2String)).toString();
} catch (NumberFormatException e) {
if (r1.isit == 'b'
|| r1.isit == 'i'
|| r1.isit == 'c'
|| r1.isit == 'n'
|| r1.isit == 't'
|| (r1.isit == 'a' && (r1.op.equals("+")
|| r1.op.equals("-")
|| r1.op.equals("*")
|| r1.op.equals("/") || r1.op
.equals("^")))) {
if (r1 != null) {
result = r1.getElement(type);
}
} else {
if (r1 != null) {
result = "(" + r1.getElement(type) + ")";
}
}
result = result + "+";
if (r2.isit == 'b'
|| r2.isit == 'i'
|| r2.isit == 'c'
|| r2.isit == 'n'
|| r2.isit == 't'
|| (r2.isit == 'a' && (r2.op.equals("+")
|| r2.op.equals("-")
|| r2.op.equals("*")
|| r2.op.equals("/") || r2.op
.equals("^")))) {
if (r2 != null) {
result = result + r2.getElement(type);
}
} else {
if (r2 != null) {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
}
}
} else if (op.equals("-")) {
if (r1.isit == 'a' && r1.op.equals("uniform")
&& r2.isit == 'n' && r2.lvalue >= 0) {
ExprTree tempUniform = new ExprTree(r1);
r1.setNodeValues(tempUniform.r1, r2, "-", 'a');
r2.setNodeValues(tempUniform.r2, r2, "-", 'a');
isit = 'a';
op = "uniform";
} else {
try {
String r1String = r1.getElement(type);
String r2String = r2.getElement(type);
result = new Float(Float.parseFloat(r1String)
- Float.parseFloat(r2String)).toString();
} catch (NumberFormatException e) {
if (r1.isit == 'b'
|| r1.isit == 'i'
|| r1.isit == 'c'
|| r1.isit == 'n'
|| r1.isit == 't'
|| (r1.isit == 'a' && (r1.op.equals("+")
|| r1.op.equals("-")
|| r1.op.equals("*")
|| r1.op.equals("/") || r1.op
.equals("^")))) {
if (r1 != null) {
result = r1.getElement(type);
}
} else {
if (r1 != null) {
result = "(" + r1.getElement(type) + ")";
}
}
result = result + "-";
if (r2.isit == 'b'
|| r2.isit == 'i'
|| r2.isit == 'c'
|| r2.isit == 'n'
|| r2.isit == 't'
|| (r2.isit == 'a' && (r2.op.equals("-")
|| r2.op.equals("*")
|| r2.op.equals("/") || r2.op
.equals("^")))) {
if (r2 != null) {
result = result + r2.getElement(type);
}
} else {
if (r2 != null) {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
}
}
} else if (op.equals("*")) {
if (r1.isit == 'n' && r1.lvalue >= 0 && r2.isit == 'a'
&& r2.op.equals("uniform")) {
ExprTree tempUniform = new ExprTree(r2);
r1.setNodeValues(r1, tempUniform.r1, "*", 'a');
r2.setNodeValues(r1, tempUniform.r2, "*", 'a');
isit = 'a';
op = "uniform";
} else if (r1.isit == 'a' && r1.op.equals("uniform")
&& r2.isit == 'n' && r2.lvalue >= 0) {
ExprTree tempUniform = new ExprTree(r1);
r1.setNodeValues(r2, tempUniform.r1, "*", 'a');
r2.setNodeValues(r2, tempUniform.r2, "*", 'a');
isit = 'a';
op = "uniform";
} else {
try {
String r1String = r1.getElement(type);
String r2String = r2.getElement(type);
result = new Float(Float.parseFloat(r1String)
* Float.parseFloat(r2String)).toString();
} catch (NumberFormatException e) {
if (r1.isit == 'b'
|| r1.isit == 'i'
|| r1.isit == 'c'
|| r1.isit == 'n'
|| r1.isit == 't'
|| (r1.isit == 'a' && (r1.op.equals("*")
|| r1.op.equals("/") || r1.op
.equals("^")))) {
if (r1 != null) {
result = r1.getElement(type);
}
} else {
if (r1 != null) {
result = "(" + r1.getElement(type) + ")";
}
}
result = result + "*";
if (r2.isit == 'b'
|| r2.isit == 'i'
|| r2.isit == 'c'
|| r2.isit == 'n'
|| r2.isit == 't'
|| (r2.isit == 'a' && (r2.op.equals("*")
|| r2.op.equals("/") || r2.op
.equals("^")))) {
if (r2 != null) {
result = result + r2.getElement(type);
}
} else {
if (r2 != null) {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
}
}
} else if (op.equals("/")) {
if (r1.isit == 'a' && r1.op.equals("uniform")
&& r2.isit == 'n' && r2.lvalue >= 0) {
ExprTree tempUniform = new ExprTree(r1);
r1.setNodeValues(tempUniform.r1, r2, "/", 'a');
r2.setNodeValues(tempUniform.r2, r2, "/", 'a');
isit = 'a';
op = "uniform";
} else {
try {
String r1String = r1.getElement(type);
String r2String = r2.getElement(type);
result = new Float(Float.parseFloat(r1String)
/ Float.parseFloat(r2String)).toString();
} catch (NumberFormatException e) {
if (r1.isit == 'b'
|| r1.isit == 'i'
|| r1.isit == 'c'
|| r1.isit == 'n'
|| r1.isit == 't'
|| (r1.isit == 'a' && (r1.op.equals("*")
|| r1.op.equals("/") || r1.op
.equals("^")))) {
if (r1 != null) {
result = r1.getElement(type);
}
} else {
if (r1 != null) {
result = "(" + r1.getElement(type) + ")";
}
}
result = result + "/";
if (r2.isit == 'b'
|| r2.isit == 'i'
|| r2.isit == 'c'
|| r2.isit == 'n'
|| r2.isit == 't'
|| (r2.isit == 'a' && (r2.op.equals("/") || r2.op
.equals("^")))) {
if (r2 != null) {
result = result + r2.getElement(type);
}
} else {
if (r2 != null) {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
}
}
} else if (op.equals("^")) {
try {
String r1String = r1.getElement(type);
String r2String = r2.getElement(type);
result = new Integer(Integer.parseInt(r1String)
^ Integer.parseInt(r2String)).toString();
} catch (NumberFormatException e) {
if (r1.isit == 'b'
|| r1.isit == 'i'
|| r1.isit == 'c'
|| r1.isit == 'n'
|| r1.isit == 't'
|| (r1.isit == 'a' && (r1.op.equals("*")
|| r1.op.equals("/") || r1.op
.equals("^")))) {
if (r1 != null) {
result = "(" + r1.getElement(type) + ")";
}
} else {
if (r1 != null) {
result = "(" + r1.getElement(type) + ")";
}
}
if (type.equals("prism")) result = "pow(" + result + ",";
else result = result + "^";
if (r2.isit == 'b'
|| r2.isit == 'i'
|| r2.isit == 'c'
|| r2.isit == 'n'
|| r2.isit == 't'
|| (r2.isit == 'a' && (r2.op.equals("/") || r2.op
.equals("^")))) {
if (r2 != null) {
result = result + "(" + r2.getElement(type)
+ ")";
}
} else {
if (r2 != null) {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
if (type.equals("prism")) result = result + ")";
}
}
// relational ops: geq, leq, gt, lt
// mod
else {
if (!sbmlFlag) {
if (r1 != null) {
if (r1.isit == 'b' || r1.isit == 'i'
|| r1.isit == 'c' || r1.isit == 'n'
|| r1.isit == 't') {
result = r1.getElement(type);
} else {
result = "(" + r1.getElement(type) + ")";
}
}
result = result + op;
if (r2 != null) {
if (r2.isit == 'b' || r2.isit == 'i'
|| r2.isit == 'c' || r2.isit == 'n'
|| r2.isit == 't') {
result = result + r2.getElement(type);
} else {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
}
if (sbmlFlag) {
if (op.equals("<=")) {
if (r1 != null && r2 != null) {
result = "leq(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
if (op.equals(">=")) {
if (r1 != null && r2 != null) {
result = "geq(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
if (op.equals(">")) {
if (r1 != null && r2 != null) {
result = "gt(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
if (op.equals("<")) {
if (r1 != null && r2 != null) {
result = "lt(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
if (op.equals("%")) {
if (r1 != null && r2 != null) {
result = "mod(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
}
}
}
return result;
}
public ExprTree minimizeUniforms() {
if (r1 != null) {
r1.minimizeUniforms();
}
if (r2 != null) {
r2.minimizeUniforms();
}
if (isit == 'a' && op.equals("m")) {
if (r1.isit == 'n' && r2.isit == 'n') {
isit = 'n';
if (r1.lvalue < r2.lvalue) {
lvalue = r1.lvalue;
} else {
lvalue = r2.lvalue;
}
r1 = null;
r2 = null;
} else if (r1.isit == 'a' && r1.op.equals("uniform")
&& r2.isit == 'a' && r2.op.equals("uniform")) {
ExprTree l1 = r1.r1;
ExprTree l2 = r2.r1;
ExprTree u1 = r1.r2;
ExprTree u2 = r2.r2;
op = "uniform";
r1.op = "m";
r2.op = "m";
r1.r1 = l1;
r1.r2 = l2;
r2.r1 = u1;
r2.r2 = u2;
}
}
if (isit == 'a' && op.equals("M")) {
if (r1.isit == 'n' && r2.isit == 'n') {
isit = 'n';
if (r1.lvalue < r2.lvalue) {
lvalue = r2.lvalue;
} else {
lvalue = r1.lvalue;
}
r1 = null;
r2 = null;
} else if (r1.isit == 'a' && r1.op.equals("uniform")
&& r2.isit == 'a' && r2.op.equals("uniform")) {
ExprTree l1 = r1.r1;
ExprTree l2 = r2.r1;
ExprTree u1 = r1.r2;
ExprTree u2 = r2.r2;
op = "uniform";
r1.op = "M";
r2.op = "M";
r1.r1 = l1;
r1.r2 = l2;
r2.r1 = u1;
r2.r2 = u2;
}
}
if (isit == 'a' && op.equals("+")) {
if (r1.isit == 'a' && r1.op.equals("uniform") && r2.isit == 'a'
&& r2.op.equals("uniform")) {
ExprTree l1 = r1.r1;
ExprTree l2 = r2.r1;
ExprTree u1 = r1.r2;
ExprTree u2 = r2.r2;
op = "uniform";
r1.op = "+";
r2.op = "+";
r1.r1 = l1;
r1.r2 = l2;
r2.r1 = u1;
r2.r2 = u2;
}
}
if (isit == 'a' && op.equals("-")) {
if (r1.isit == 'a' && r1.op.equals("uniform") && r2.isit == 'a'
&& r2.op.equals("uniform")) {
ExprTree l1 = r1.r1;
ExprTree l2 = r2.r1;
ExprTree u1 = r1.r2;
ExprTree u2 = r2.r2;
op = "uniform";
r1.op = "+";
r2.op = "+";
r1.r1 = l1;
r1.r2 = u2;
r2.r1 = u1;
r2.r2 = l2;
}
}
if (isit == 'a' && op.equals("c")) {
if (r1.isit == 'a' && r1.op.equals("uniform")) {
ExprTree l1 = r1.r1;
ExprTree u1 = r1.r2;
op = "uniform";
r1 = new ExprTree(l1, null, "c", 'a');
r2 = new ExprTree(u1, null, "c", 'a');
}
}
if (isit == 'a' && op.equals("f")) {
if (r1.isit == 'a' && r1.op.equals("uniform")) {
ExprTree l1 = r1.r1;
ExprTree u1 = r1.r2;
op = "uniform";
r1 = new ExprTree(l1, null, "f", 'a');
r2 = new ExprTree(u1, null, "f", 'a');
}
}
if (isit == 'a' && op.equals("uniform")) {
if (r1.isit == 'a' && r1.op.equals("uniform")) {
r1 = r1.r1;
}
if (r2.isit == 'a' && r2.op.equals("uniform")) {
r2 = r2.r2;
}
}
return this;
}
public boolean isEqual(ExprTree expr) {
if (isit == expr.isit) {
boolean same = false;
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
if (variable.equals(expr.variable)) {
same = true;
}
break;
case 'n': // Number
case 't': // Truth value
if (uvalue == expr.uvalue && lvalue == expr.lvalue) {
same = true;
}
break;
case 'w': // bitWise
case 'a': // Arithmetic
case 'r': // Relational
case 'l': // Logical
if (op.equals(expr.op)) {
same = true;
}
}
if (same) {
boolean r1Same = false, r2Same = false;
if (r1 == null) {
if (expr.r1 == null) {
r1Same = true;
}
} else if (r1.isEqual(expr.r1)) {
r1Same = true;
}
if (r2 == null) {
if (expr.r2 == null) {
r2Same = true;
}
} else if (r2.isEqual(expr.r2)) {
r2Same = true;
}
if (r1Same && r2Same) {
return true;
}
}
}
return false;
}
private boolean isEqual(ExprTree expr, HashMap<String, String> variables) {
if (isit == expr.isit) {
boolean same = false;
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
if (variables.containsKey(variable)) {
if (variables.containsKey(expr.variable)) {
if (variables.get(variable).equals(
variables.get(expr.variable)))
same = true;
}
} else if (variable.equals(expr.variable)) {
same = true;
}
break;
case 'n': // Number
case 't': // Truth value
if (uvalue == expr.uvalue && lvalue == expr.lvalue) {
same = true;
} else if (variables.containsKey(expr.variable)) {
if (uvalue == lvalue) {
if (uvalue == 1.0
&& variables.get(expr.variable).toLowerCase()
.equals("true"))
same = true;
else if (uvalue == 0.0
&& variables.get(expr.variable).toLowerCase()
.equals("false"))
same = true;
}
}
break;
case 'w': // bitWise
case 'a': // Arithmetic
case 'r': // Relational
case 'l': // Logical
if (op.equals(expr.op)) {
same = true;
}
}
if (same) {
boolean r1Same = false, r2Same = false;
if (r1 == null) {
if (expr.r1 == null) {
r1Same = true;
}
} else if (r1.isEqual(expr.r1)) {
r1Same = true;
}
if (r2 == null) {
if (expr.r2 == null) {
r2Same = true;
}
} else if (r2.isEqual(expr.r2)) {
r2Same = true;
}
if (r1Same && r2Same) {
return true;
}
}
}
return false;
}
private void setVarValues(char willbe, double lNV, double uNV, String var) {
op = "";
r1 = null;
r2 = null;
isit = willbe;
if ((isit == 'b') || (isit == 't'))
logical = true;
else
logical = false;
uvalue = uNV;
lvalue = lNV;
variable = var;
real = 0;
}
public void setNodeValues(ExprTree nr1, ExprTree nr2, String nop,
char willbe) {
ExprTree r1temp = null, r2temp = null;
if (nr1 != null) {
r1temp = new ExprTree(nr1);
}
if (nr2 != null) {
r2temp = new ExprTree(nr2);
}
r1 = r1temp;
r2 = r2temp;
op = nop;
isit = willbe;
if ((isit == 'r') || (isit == 'l')) {
logical = true;
uvalue = 1;
lvalue = 0;
} else {
logical = false;
uvalue = INFIN;
lvalue = -INFIN;
}
variable = null;
// simplify if operands are static
if (isit == 'a' || isit == 'r' || isit == 'l' || isit == 'w') {
if (op.equals("&&")) {
if ((r1.isit == 'n') || (r1.isit == 't')) {
if (r1.lvalue == 0) {
setVarValues('t', 0.0, 0.0, null);
} else {
if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w'
|| r2.isit == 'r') {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
} else {
setVarValues(r2.isit, r2.lvalue, r2.uvalue,
r2.variable);
}
}
} else if (((r2).isit == 'n') || ((r2).isit == 't')) {
if (r2.lvalue == 0) {
setVarValues('t', 0.0, 0.0, null);
} else {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue,
r1.variable);
}
}
} else if (r1.equals(r2)) {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable);
}
} else {
ExprTree notE = new ExprTree(this);
notE.setNodeValues((this), null, "!", 'l');
if (r1.equals(notE) || notE.equals(r1)) {
setVarValues('t', 0.0, 0.0, null);
}
}
} else if (op.equals("||")) {
if ((r1.isit == 'n') || (r1.isit == 't')) {
if (r1.lvalue != 0) {
setVarValues('t', 1.0, 1.0, null);
} else {
if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w'
|| r2.isit == 'r') {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
} else {
setVarValues(r2.isit, r2.lvalue, r2.uvalue,
r2.variable);
}
}
} else if (((r2).isit == 'n') || ((r2).isit == 't')) {
if (r2.lvalue != 0) {
setVarValues('t', 1.0, 1.0, null);
} else {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue,
r1.variable);
}
}
} else if (r1.equals(r2)) {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable);
}
} else {
ExprTree notE = new ExprTree(this);
notE.setNodeValues((this), null, "!", 'l');
if (r1.equals(notE) || notE.equals(r1)) {
setVarValues('t', 1.0, 1.0, null);
}
}
} else if (op.equals("->")) {
if (r1.isit == 'n' || r1.isit == 't') {
if (r1.lvalue != 0) {
if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w'
|| r2.isit == 'r') {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
} else {
setVarValues(r2.isit, r2.lvalue, r2.uvalue,
r2.variable);
}
} else if (r1.uvalue == 0) {
setVarValues('t', 1.0, 1.0, null);
}
} else if (r2.isit == 't' || r2.isit == 'n') {
if (r2.lvalue != 0) {
setVarValues('t', 1.0, 1.0, null);
} else if (r2.uvalue == 0) {
ExprTree notE = new ExprTree(r2);
notE.setNodeValues((this), null, "!", 'l');
setNodeValues(notE.r1, notE.r2, notE.op, notE.isit);
}
}
} else if (op.equals("!")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 't';
if (r1.lvalue == 1) {
this.lvalue = 0;
} else {
this.lvalue = 1;
}
(this).uvalue = (this).lvalue;
}
} else if (op.equals("==")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if (r1.lvalue == r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
}
} else if (op.equals(">=")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue >= r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
}
} else if (op.equals(">")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue > r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
}
} else if (op.equals("<=")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue <= r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
}
} else if (op.equals("<")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue < r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
}
} else if (op.equals("&")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = ((int) (r1).lvalue) & ((int) r2.lvalue);
(this).uvalue = (this).lvalue;
}
} else if (op.equals("|")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (int) (r1).lvalue | (int) r2.lvalue;
(this).uvalue = (this).lvalue;
}
} else if (isit == 'w' && op.equals("X")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (int) (r1).lvalue ^ (int) r2.lvalue;
(this).uvalue = (this).lvalue;
}
} else if (op.equals("m")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = Math.min((r1).lvalue, r2.lvalue);
(this).uvalue = (this).lvalue;
}
} else if (op.equals("M")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = Math.max((r1).lvalue, r2.lvalue);
(this).uvalue = (this).lvalue;
}
} else if (op.equals("i")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = Math.floor((r1).lvalue / r2.lvalue);
(this).uvalue = (this).lvalue;
}
} else if (op.equals("f")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = Math.floor((r1).lvalue);
(this).uvalue = (this).lvalue;
}
} else if (op.equals("c")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = Math.ceil((r1).lvalue);
(this).uvalue = (this).lvalue;
}
} else if (op.equals("~")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = ~(int) (r1).lvalue;
(this).uvalue = (this).lvalue;
}
} else if (op.equals("[]")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
(this).lvalue = (((int) (r1).lvalue) >> ((int) r2.lvalue)) & 1;
(this).uvalue = (this).lvalue;
}
} else if (op.equals("U-")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = -((r1).lvalue);
(this).uvalue = (this).lvalue;
}
} else if (op.equals("*")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue * r2.lvalue;
(this).uvalue = (this).lvalue;
} else if (r1.isit == 'n' || r1.isit == 't') {
if (r1.lvalue == 0 && r1.uvalue == 0) {
setVarValues('t', 0.0, 0.0, null);
} else if (r1.lvalue == 1 && r1.uvalue == 1) {
if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w'
|| r2.isit == 'r') {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
} else {
setVarValues(r2.isit, r2.lvalue, r2.uvalue,
r2.variable);
}
}
} else if (r2.isit == 'n' || r2.isit == 't') {
if (r2.lvalue == 0 && r2.uvalue == 0) {
setVarValues('t', 0.0, 0.0, null);
} else if (r2.lvalue == 1 && r2.uvalue == 1) {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue,
r1.variable);
}
}
}
} else if (op.equals("/")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue / r2.lvalue;
(this).uvalue = (this).lvalue;
} else if ((r1.isit == 'n' || r1.isit == 't') && r1.uvalue == 0
&& r1.lvalue == 0) {
setVarValues('n', 0.0, 0.0, null);
} else if ((r2.isit == 'n' || r2.isit == 't') && r2.lvalue == 1
&& r2.uvalue == 1) {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable);
}
}
} else if (op.equals("%")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue % r2.lvalue;
(this).uvalue = (this).lvalue;
} else if ((r2.isit == 'n' || r2.isit == 't')
&& r2.lvalue == 1.0 && r2.uvalue == 1.0) {
setVarValues('n', 0.0, 0.0, null);
} else if ((r1.isit == 'n' || r1.isit == 't')
&& r1.lvalue == 1.0 && r1.uvalue == 1.0) {
setVarValues('n', 1.0, 1.0, null);
}
} else if (op.equals("+")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue + r2.lvalue;
(this).uvalue = (this).lvalue;
} else if ((r1.isit == 'n' || r1.isit == 't') && r1.lvalue == 0
&& r1.uvalue == 0) {
if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w'
|| r2.isit == 'r') {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
} else {
setVarValues(r2.isit, r2.lvalue, r2.uvalue, r2.variable);
}
} else if ((r2.isit == 'n' || r2.isit == 't') && r2.lvalue == 0
&& r2.uvalue == 0) {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable);
}
}
} else if (op.equals("-")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue - r2.lvalue;
(this).uvalue = (this).lvalue;
} else if ((r1.isit == 'n' || r1.isit == 't') && r1.lvalue == 0
&& r1.uvalue == 0) {
setNodeValues(r2, null, "U-", 'a');
} else if ((r2.isit == 'n' || r2.isit == 't') && r2.lvalue == 0
&& r2.uvalue == 0) {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable);
}
}
}
}
}
public double evaluateExpr(HashMap<String, String> variables) {
double left;
double right;
switch (isit) {
case 'b': // Boolean
if (variables != null) {
if (!variables.containsKey(variable)
|| variables.get(variable).toLowerCase().equals(
"unknown"))
return Double.NaN;
if (variables.get(variable).toLowerCase().equals("true") ||
variables.get(variable).equals("1")) {
return 1.0;
}
return 0.0;
}
return Double.NaN;
case 'c': // Continuous
return Double.NaN;
case 'i': // Integer
if (variables != null) {
try {
return Double.parseDouble(variables.get(variable));
} catch (Exception e) {
return Double.NaN;
}
}
return Double.NaN;
case 'n': // Number
if (uvalue == lvalue) {
return uvalue;
}
return ((uvalue - lvalue) * new java.util.Random().nextDouble())
+ lvalue;
case 't': // Truth value
if (uvalue == 1 && lvalue == 1) {
return 1.0;
} else if (uvalue == 0 && lvalue == 0) {
return 0.0;
} else {
return Double.NaN;
}
case 'w': // bitWise
if (r1 != null) {
left = r1.evaluateExpr(variables);
} else {
left = Double.NaN;
}
if (r2 != null) {
right = r2.evaluateExpr(variables);
} else {
right = Double.NaN;
}
if (op.equals("&")) {
return ((int) left) & ((int) right);
} else if (op.equals("|")) {
return ((int) left) | ((int) right);
} else if (op.equals("!")) {
return ~((int) left);
} else if (op.equals("X")) {
return ((int) left) ^ ((int) right);
}
break;
case 'a': // Arithmetic
case 'r': // Relational
case 'l': // Logical
if (op.equals("!")) {
if (r1 != null) {
if (r1.evaluateExpr(variables) == 1.0) {
return 0.0;
} else if (r1.evaluateExpr(variables) == 0.0) {
return 1.0;
} else {
return Double.NaN;
}
} else if (r2 != null) {
if (r2.evaluateExpr(variables) == 1.0) {
return 0.0;
} else if (r2.evaluateExpr(variables) == 0.0) {
return 1.0;
} else {
return Double.NaN;
}
} else {
return Double.NaN;
}
}
if (r1 != null) {
left = r1.evaluateExpr(variables);
} else {
left = Double.NaN;
}
if (r2 != null) {
right = r2.evaluateExpr(variables);
} else {
right = Double.NaN;
}
if (op.equals("&&")) {
if (left == 1.0 && right == 1.0) {
return 1.0;
} else if (left == 0.0 || right == 0.0) {
return 0.0;
} else
return Double.NaN;
} else if (op.equals("||")) {
if (left == 1.0 || right == 1.0) {
return 1.0;
} else if (left == 0.0 && right == 0.0) {
return 0.0;
} else
return Double.NaN;
} else if (op.equals("==")) {
if (left == Double.NaN || right == Double.NaN) {
return Double.NaN;
} else if (left == right) {
return 1.0;
} else if (left != right) {
return 0.0;
} else {
return Double.NaN;
}
} else if (op.equals("->")) {
if (left == 0.0 && (right == 1.0 || right == 0.0)) {
return 1.0;
} else if (left == 1.0 && right == 1.0) {
return 1.0;
} else if (left == 1.0 && right == 0.0) {
return 0.0;
} else {
return Double.NaN;
}
} else if (op.equals("+")) {
return left + right;
} else if (op.equals("-")) {
return left - right;
} else if (op.equals("*")) {
return left * right;
} else if (op.equals("/")) {
return left / right;
} else if (op.equals("%")) {
return left % right;
} else if (op.equals("^")) {
return Math.pow(left, right);
} else if (op.equals("[]")) {
return (((int) left) >> ((int) right)) & 1;
} else if (op.equals("f")) {
return Math.floor(left);
} else if (op.equals("c")) {
return Math.ceil(left);
} else if (op.equals("m")) {
return Math.min(left, right);
} else if (op.equals("M")) {
return Math.max(left, right);
} else if (op.equals("i")) {
return ((int) left) / ((int) right);
} else if (op.equals("uniform")) {
return Double.NaN;
} else if (op.equals("normal")) {
return Double.NaN;
} else if (op.equals("gamma")) {
return Double.NaN;
} else if (op.equals("lognormal")) {
return Double.NaN;
} else if (op.equals("binomial")) {
return Double.NaN;
} else if (op.equals("exponential")) {
return Double.NaN;
} else if (op.equals("chisq")) {
return Double.NaN;
} else if (op.equals("laplace")) {
return Double.NaN;
} else if (op.equals("cauchy")) {
return Double.NaN;
} else if (op.equals("rayleigh")) {
return Double.NaN;
} else if (op.equals("poisson")) {
return Double.NaN;
} else if (op.equals("bernoulli")) {
return Double.NaN;
} else if (op.equals("rate")) {
return Double.parseDouble(variables.get(r1.variable+"_" + GlobalConstants.RATE));
} else if (op.equals("INT")) {
return ((int) left);
} else if (op.equals("<")) {
if (left < right) {
return 1.0;
} else if (left >= right) {
return 0.0;
} else {
return Double.NaN;
}
} else if (op.equals(">")) {
if (left > right) {
return 1.0;
} else if (left <= right) {
return 0.0;
} else {
return Double.NaN;
}
} else if (op.equals("<=")) {
if (left <= right) {
return 1.0;
} else if (left > right) {
return 0.0;
} else {
return Double.NaN;
}
} else if (op.equals(">=")) {
if (left >= right) {
return 1.0;
} else if (left < right) {
return 0.0;
} else {
return Double.NaN;
}
} else {
return Double.NaN;
}
}
return Double.NaN;
}
private static final int WORD = 1;
private static final int IMPLIES = 7;
private static final int END_OF_STRING = 2;
private static final int INFIN = 2147483647;
public String getOp()
{
return op;
}
public ExprTree getLeftChild()
{
return r1;
}
public ExprTree getRightChild()
{
return r2;
}
@Override
public ExprTree clone(){
ExprTree ET = new ExprTree(); // ET phone home.
ET.op = op;
ET.isit = isit;
ET.lvalue = lvalue;
ET.uvalue = uvalue;
ET.variable = variable;
ET.real = real;
ET.logical = logical;
ET.r1 = r1 != null ? r1.clone() : null;
ET.r2 = r2 != null ? r2.clone() : null;
ET.tokvalue = tokvalue;
ET.position = position;
ET.token = token;
ET.newresult = newresult != null ? newresult.clone() : null;
//private ArrayList<String> booleanSignals, integerSignals, continuousSignals;
ET.booleanSignals = (ArrayList<String>) booleanSignals.clone();
ET.integerSignals = (ArrayList<String>) integerSignals.clone();
ET.continuousSignals = continuousSignals;
ET.lhpn = lhpn;
ET.expression = expression;
return ET;
}
/*
* Performs the same operation as this.clone except it does not copy the parsing information.
*/
public ExprTree shallowclone(){
ExprTree ET = new ExprTree(); // ET phone home.
ET.op = op;
ET.isit = isit;
ET.lvalue = lvalue;
ET.uvalue = uvalue;
ET.variable = variable;
ET.real = real;
ET.logical = logical;
ET.r1 = r1 != null ? r1.shallowclone() : null;
ET.r2 = r2 != null ? r2.shallowclone() : null;
//private ArrayList<String> booleanSignals, integerSignals, continuousSignals;
ET.booleanSignals = (ArrayList<String>) booleanSignals.clone();
ET.integerSignals = (ArrayList<String>) integerSignals.clone();
ET.continuousSignals = continuousSignals;
ET.lhpn = lhpn;
ET.expression = expression;
return ET;
}
public ExprTree getExprTree() {
token = this.intexpr_gettok(expression);
this.intexpr_L(expression);
return this;
}
public void setIntegerSignals(Set<String> signalSet) {
for (String s : signalSet) {
integerSignals.add(s);
}
}
/**
* Evaluates an expression tree involving ranges.
* Note: if no continuous variables are present, both z and continuousValues can be null.
* If continuous variables are present, then at least one must be non-null. Finally, if
* z is non-null, then the values will be taken from z and continuousValues will not be consulted.
* @param variables
* The values of the variables.
* @param z
* The zone containing the continuous variables.
* @param continuousValues
* The continuous variables along with their values.
* @return
* The range of values for the expression tree.
*/
public IntervalPair evaluateExprBound(HashMap<String, String> variables, Equivalence z,
// HashMap<LPNContinuousPair, IntervalPair> continuousValues){
HashMap<LPNContAndRate, IntervalPair> continuousValues){
/*
* The code for this method was modified from atacs/src/lhpnrsg.c.
*/
// void exprsn::eval(lhpnStateADT cur_state,int nevents){
// char log_val;
// int tl1,tl2,tu1,tu2,i,j,k;
// int preciser = 1;
//
int lBound, uBound;
// If lBound and uBound are never set, then return "don't know".
lBound = -INFIN;
uBound = INFIN;
IntervalPair r1Range,r2Range = null;
if(!op.equals("")){
// if (op!=""){
// //printf("%s, eval left child\n",op.c_str());
// r1->eval(cur_state,nevents);
// if ((r1->lvalue == -INFIN)||(r1->uvalue == INFIN)){
// lvalue = -INFIN;
// uvalue = INFIN;
// return;
// }
r1Range = r1.evaluateExprBound(variables, z, continuousValues);
if ((r1Range.get_LowerBound() == -INFIN) || (r1Range.get_UpperBound() == INFIN)){
return new IntervalPair(-INFIN, INFIN);
}
// if (r2){
// //printf("eval right child\n");
// r2->eval(cur_state,nevents);
// if ((r2->lvalue == -INFIN)||(r2->uvalue == INFIN)){
// lvalue = -INFIN;
// uvalue = INFIN;
// return;
// }
// }
if(r2 != null){
r2Range = r2.evaluateExprBound(variables, z, continuousValues);
if ((r2Range.get_LowerBound() == - INFIN) || (r1Range.get_UpperBound() == INFIN)){
return new IntervalPair(-INFIN, INFIN);
}
} else {
r2Range = new IntervalPair(-INFIN, INFIN);
}
// if (op=="||"){
// // logical OR
// if (r1->logical){
// tl1 = r1->lvalue;
// tu1 = r1->uvalue;
// }
if( op.equals("||")){
Boolean tl1, tu1, tl2, tu2;
// logical OR
if(r1.logical){
tl1 = r1Range.get_LowerBound() != 0; // false if value is zero and true otherwise
tu1 = r1Range.get_UpperBound() != 0; // false if value is zero and true otherwise
}
else{ // convert numeric r1 to boolean
// else{//convert numeric r1 to boolean
// if ((r1->lvalue == 0)&&(r1->uvalue == 0)){//false
// tl1 = tu1 = 0;
// }
if((r1Range.get_LowerBound() == 0) && (r1Range.get_UpperBound() == 0)){ // false
tl1 = tu1 = false;
}
// else if ((r1->lvalue < 0)&&(r1->uvalue < 0)||
// (r1->lvalue > 0)&&(r1->uvalue > 0)){//true
// tl1 = tu1 = 1;
// }
else if (((r1Range.get_LowerBound() < 0) && (r1Range.get_UpperBound() < 0)) ||
((r1Range.get_LowerBound() > 0) && (r1Range.get_UpperBound() > 0))){ // true
tl1 = tu1 = true;
}
// else{
// tl1 = 0;
// tu1 = 1;
// }
// }
else{
tl1 = false;
tu1 = true;
}
}
// if (r2->logical){
// tl2 = r2->lvalue;
// tu2 = r2->uvalue;
// }
if(r2.logical){ // Note : r2Range can only be set if r2 was non-null.
tl2 = r2Range.get_LowerBound() != 0; // False if value is zero and true otherwise.
tu2 = r2Range.get_UpperBound() != 0; // False if value is zero and true otherwise.
}
else{// convert numeric r2 to boolean
// else{//convert numeric r2 to boolean
// if ((r2->lvalue == 0)&&(r2->uvalue == 0)){//false
// tl2 = tu2 = 0;
// }
if((r2Range.get_LowerBound() == 0) && (r2Range.get_UpperBound() == 0)){// false
tl2 = tu2 = false;
}
// else if ((r2->lvalue < 0)&&(r2->uvalue < 0)||
// (r2->lvalue > 0)&&(r2->uvalue > 0)){//true
// tl2 = tu2 = 1;
// }
else if (((r2Range.get_LowerBound() < 0) && (r2Range.get_UpperBound() < 0)) ||
((r2Range.get_LowerBound() > 0) && (r2Range.get_UpperBound() > 0))){ // true
tl2 = tu2 = true;
}
// else{
// tl2 = 0;
// tu2 = 1;
// }
// }
else{
tl2 = false;
tu2 = true;
}
}
// lvalue = tl1 || tl2;
// uvalue = tu1 || tu2;
// lBound = tl1 || lt2;
// uBound = tu1 || tu2;
lBound = (tl1 || tl2) ? 1 : 0; // Poor man casting from boolean to int.
uBound = (tu1 || tu2) ? 1 : 0;
}
// }else if(op=="&&"){
// // logical AND
else if (op.equals("&&")){ // logical AND
Boolean tl1, tu1, tl2, tu2;
// if (r1->logical){
// tl1 = r1->lvalue;
// tu1 = r1->uvalue;
// }
if(r1.logical){
tl1 = r1Range.get_LowerBound() != 0; // false if value is zero and true otherwise
tu1 = r1Range.get_UpperBound() != 0; // false if value is zero and true otherwise
}
// else{//convert numeric r1 to boolean
// if ((r1->lvalue == 0)&&(r1->uvalue == 0)){//false
// tl1 = tu1 = 0;
// }
else{ // convert number r1 to boolean
if((r1Range.get_LowerBound() == 0) && (r1Range.get_UpperBound() == 0)){ // false
tl1 = tu1 = false;
}
// else if ((r1->lvalue < 0)&&(r1->uvalue < 0)||
// (r1->lvalue > 0)&&(r1->uvalue > 0)){//true
// tl1 = tu1 = 1;
// }
else if (((r1Range.get_LowerBound() < 0) && (r1Range.get_UpperBound() < 0)) ||
((r1Range.get_LowerBound() > 0) && (r1Range.get_UpperBound() > 0))){ // true
tl1 = tu1 = true;
}
// else{
// tl1 = 0;
// tu1 = 1;
// }
// }
else{
tl1 = false;
tu1 = true;
}
}
// if (r2->logical){
// tl2 = r2->lvalue;
// tu2 = r2->uvalue;
// }
// else{//convert numeric r2 to boolean
if(r2.logical){ // Note : r2Range can only be set if r2 was non-null.
tl2 = r2Range.get_LowerBound() != 0; // False if value is zero and true otherwise.
tu2 = r2Range.get_UpperBound() != 0; // False if value is zero and true otherwise.
}
else{// convert numeric r2 to boolean
// if ((r2->lvalue == 0)&&(r2->uvalue == 0)){//false
// tl2 = tu2 = 0;
// }
if((r2Range.get_LowerBound() == 0) && (r2Range.get_UpperBound() == 0)){// false
tl2 = tu2 = false;
}
// else if ((r2->lvalue < 0)&&(r2->uvalue < 0)||
// (r2->lvalue > 0)&&(r2->uvalue > 0)){//true
// tl2 = tu2 = 1;
// }
else if (((r2Range.get_LowerBound() < 0) && (r2Range.get_UpperBound() < 0)) ||
((r2Range.get_LowerBound() > 0) && (r2Range.get_UpperBound() > 0))){ // true
tl2 = tu2 = true;
}
// else{
// tl2 = 0;
// tu2 = 1;
// }
// }
else{
tl2 = false;
tu2 = true;
}
}
// lvalue = tl1 && tl2;
// uvalue = tu1 && tu2;
lBound = (tl1 && tl2) ? 1 : 0; // Poor man casting from boolean to int.
uBound = (tu1 && tu2) ? 1 : 0; // Or clever way; depends on how you look at it.
// #ifdef __LHPN_EVAL__
// printf("and: [%d,%d](%c)&[%d,%d](%c) = [%d,%d]\n",r1->lvalue,
// r1->uvalue,r1->isit,r2->lvalue,r2->uvalue,r2->isit,lvalue,uvalue);
// #endif
}
// }else if(op=="->"){
// // implication operator
else if(op.equals("->")){ // Implication operator.
Boolean tl1, tu1, tl2, tu2;
// if (r1->logical){
// tl1 = r1->lvalue;
// tu1 = r1->uvalue;
// }
// else{//convert numeric r1 to boolean
// if ((r1->lvalue == 0)&&(r1->uvalue == 0)){//false
// tl1 = tu1 = 0;
// }
// else if ((r1->lvalue < 0)&&(r1->uvalue < 0)||
// (r1->lvalue > 0)&&(r1->uvalue > 0)){//true
// tl1 = tu1 = 1;
// }
// else{
// tl1 = 0;
// tu1 = 1;
// }
// }
BooleanPair lowerBounds = logicalConversion(r1, r1Range);
tl1 = lowerBounds.get_lower();
tu1 = lowerBounds.get_upper();
// if (r2->logical){
// tl2 = r2->lvalue;
// tu2 = r2->uvalue;
// }
// else{//convert numeric r2 to boolean
// if ((r2->lvalue == 0)&&(r2->uvalue == 0)){//false
// tl2 = tu2 = 0;
// }
// else if ((r2->lvalue < 0)&&(r2->uvalue < 0)||
// (r2->lvalue > 0)&&(r2->uvalue > 0)){//true
// tl2 = tu2 = 1;
// }
// else{
// tl2 = 0;
// tu2 = 1;
// }
// }
// lvalue = tl1 || !tl2;
// uvalue = tu1 || !tu2;
BooleanPair upperBounds = logicalConversion(r2, r2Range);
tl2 = upperBounds.get_lower();
tu2 = upperBounds.get_upper();
lBound = (tl1 || !tl2) ? 1 : 0; // Poor man casting from boolean to int.
uBound = (tu1 || !tu2) ? 1 : 0; // Or clever way; depends on how you look at it.
}
// }else if(op=="!"){
// // logical NOT
else if(op.equals("!")){
Boolean tl1, tu1;
BooleanPair bounds = logicalConversion(r1, r1Range);
tl1 = bounds.get_lower();
tu1 = bounds.get_upper();
// if (r1->logical){
// tl1 = r1->lvalue;
// tu1 = r1->uvalue;
// }
// else{//convert numeric r1 to boolean
// if ((r1->lvalue == 0)&&(r1->uvalue == 0)){//false
// tl1 = tu1 = 0;
// }
// else if ((r1->lvalue < 0)&&(r1->uvalue < 0)||
// (r1->lvalue > 0)&&(r1->uvalue > 0)){//true
// tl1 = tu1 = 1;
// }
// else{
// tl1 = 0;
// tu1 = 1;
// }
// }
// if (tl1 == tu1){
// lvalue = 1- tl1;
// uvalue = 1- tl1;
// }
if(tl1 == tu1){
lBound = !tl1 ? 1 : 0;
uBound = !tl1 ? 1 : 0;
}
// #ifdef __LHPN_EVAL__
// printf("not: [%d,%d](%c) = [%d,%d]\n",r1->lvalue,
// r1->uvalue,r1->isit,lvalue,uvalue);
// #endif
// //printf("negation: ~[%d,%d] = [%d,%d]\n",r1->lvalue,r1->uvalue,
// // lvalue,uvalue);
}
// }else if(op=="=="){
// // "equality" operator
else if (op.equals("==")){ //"equality" operator.
// // true if same point value
// if ((r1->lvalue == r1->uvalue) && (r2->lvalue == r2->uvalue) &&
// (r1->lvalue == r2->uvalue))
// lvalue = uvalue = 1;
// true if same point value.
if((r1Range.get_LowerBound() == r1Range.get_UpperBound()) &&
(r2Range.get_LowerBound() == r2Range.get_UpperBound()) &&
(r1Range.get_LowerBound() == r2Range.get_UpperBound())){
lBound = uBound = 1;
}
// // false if no overlap
// else if ((r1->lvalue > r2->uvalue)||(r2->lvalue > r1->uvalue))
// lvalue = uvalue = 0;
// false if no overlap
else if ((r1Range.get_LowerBound() > r2Range.get_UpperBound()) ||
(r2Range.get_LowerBound() > r1Range.get_UpperBound())){
lBound = uBound = 0;
}
// // maybe if overlap
// else{
// lvalue = 0;
// uvalue = 1;
// }
// maybe if overlap
else{
lBound = 0;
uBound = 1;
}
// #ifdef __LHPN_EVAL__
// printf("[%d,%d]==[%d,%d]=[%d,%d]\n",r1->lvalue,r1->uvalue ,r2->lvalue,r2->uvalue,lvalue,uvalue);
// #endif
}
else if(op.equals(">")){// "greater than" operator
// }else if(op==">"){
// // "greater than" operator
// //true if lower1 > upper2
// if (r1->lvalue > r2->uvalue)
// lvalue = uvalue = 1;
// true if lower1 > upper2
if( r1Range.get_LowerBound() > r2Range.get_UpperBound()){
lBound = uBound = 1;
}
// //false if lower2 >= upper1
// else if (r2->lvalue >= r1->uvalue)
// lvalue = uvalue = 0;
// false if lower 2 >= upper1
else if (r2Range.get_LowerBound() >= r1Range.get_UpperBound()){
lBound = uBound = 0;
}
// // maybe if overlap
// else{
// lvalue = 0;
// uvalue = 1;
// }
// maybe, if overlap
else {
lBound = 0;
uBound = 1;
}
}
// }else if(op==">="){
// // "greater than or equal" operator
else if (op.equals(">=")){
// //true if lower1 >= upper2
// if (r1->lvalue >= r2->uvalue)
// lvalue = uvalue = 1;
// true if lower1 >= upper2
if(r1Range.get_LowerBound() >= r2Range.get_UpperBound()){
lBound = uBound = 1;
}
// //false if lower2 > upper1
// else if (r2->lvalue > r1->uvalue)
// lvalue = uvalue = 0;
// false if lower2 > upper1
else if (r2Range.get_LowerBound() > r1Range.get_UpperBound()){
lBound = uBound = 0;
}
// // maybe if overlap
// else{
// lvalue = 0;
// uvalue = 1;
// }
// maybe if overlap
else {
lBound = 0;
uBound = 1;
}
}
// }else if(op=="<"){
// // "less than" operator
else if (op.equals("<")){// "less than" operator.
// //true if lower2 > upper1
// if (r2->lvalue > r1->uvalue)
// lvalue = uvalue = 1;
// true if lower2 > upper1
if(r2Range.get_LowerBound() > r1Range.get_UpperBound()){
lBound = uBound = 1;
}
// //false if lower1 >= upper2
// else if (r1->lvalue >= r2->uvalue)
// lvalue = uvalue = 0;
// false if lower1 >= upper2
else if (r1Range.get_LowerBound() >= r2Range.get_UpperBound()){
lBound = uBound = 0;
}
// // maybe if overlap
// else{
// lvalue = 0;
// uvalue = 1;
// }
// maybe if overlap
else{
lBound = 0;
uBound = 1;
}
}
// }else if(op=="<="){
// // "less than or equal" operator
else if (op.equals("<=")){// "less than or equal" operator
// //true if lower2 >= upper1
// if (r2->lvalue >= r1->uvalue)
// lvalue = uvalue = 1;
// true if lower2 >= upper1
if(r2Range.get_LowerBound() >= r1Range.get_UpperBound()){
lBound = uBound = 1;
}
// //false if lower1 > upper2
// else if (r1->lvalue > r2->uvalue)
// lvalue = uvalue = 0;
// false if lower1 > upper2
else if (r1Range.get_LowerBound() > r2Range.get_UpperBound()){
lBound = uBound =0;
}
// // maybe if overlap
// else{
// lvalue = 0;
// uvalue = 1;
// }
// maybe if overlap
else {
lBound = 0;
uBound = 1;
}
// #ifdef __LHPN_EVAL__
// printf("[%d,%d]<=[%d,%d]=[%d,%d]\n",r1->lvalue,r1->uvalue ,r2->lvalue,r2->uvalue,lvalue,uvalue);
// #endif
}
// }else if(op=="[]"){//NEEDS WORK
// // bit extraction operator
else if (op.equals("[]")){ // Apparently needs work.
// // Only extract if both are point values.
// if ((r1->lvalue == r1->uvalue)&&(r2->lvalue == r2->uvalue)){
// lvalue = uvalue = (r1->lvalue >> r2->uvalue) & 1;
// }
if( (r1Range.get_LowerBound() == r1Range.get_UpperBound()) &&
(r2Range.get_LowerBound() == r2Range.get_UpperBound())){
lBound = uBound =
(r1Range.get_LowerBound() >> r2Range.get_UpperBound()) & 1;
}
// else {
// if (!preciser)
// {
// lvalue = 0;
// uvalue = 1;
// }
// else {
// uvalue = 0;
// lvalue = 1;
// for (i = r1->lvalue;i<=r1->uvalue;i++)
// for (j = r2->lvalue;j<=r2->uvalue;j++){
// k = (i >> j) & 1;
// lvalue &= k;
// uvalue |= k;
// if (lvalue < uvalue)
// return;
// }
// }
// }
else{
// Not doing the !preciser part.
uBound = 0;
lBound = 1;
for (int i = r1Range.get_LowerBound(); i<r1Range.get_UpperBound();
i++){
for (int j = r2Range.get_LowerBound();
j<r2Range.get_UpperBound(); j++){
int k = (i >> j) & 1;
lBound &= k;
uBound |= k;
if(lBound < uBound){
return new IntervalPair(lBound, uBound);
}
}
}
}
}
// }else if(op=="+"){
// lvalue = r1->lvalue + r2->lvalue;
// uvalue = r1->uvalue + r2->uvalue;
else if (op.equals("+")){
lBound = r1Range.get_LowerBound() + r2Range.get_LowerBound();
uBound = r1Range.get_UpperBound() + r2Range.get_UpperBound();
}
// }else if(op=="-"){
// lvalue = r1->lvalue - r2->uvalue;
// uvalue = r1->uvalue - r2->lvalue;
else if (op.equals("-")){
lBound = r1Range.get_LowerBound() - r2Range.get_LowerBound();
uBound = r1Range.get_UpperBound() - r2Range.get_UpperBound();
}
// }else if(op=="*"){
// tl1 = r1->lvalue * r2->lvalue;
// tl2 = r1->uvalue * r2->uvalue;
// tu1 = r1->lvalue * r2->uvalue;
// tu2 = r1->uvalue * r2->lvalue;
// lvalue = min(min(min(tl1,tl2),tu1),tu2);
// uvalue = max(max(max(tl1,tl2),tu1),tu2);
else if (op.equals("*")){
int tl1, tl2, tu1, tu2;
tl1 = r1Range.get_LowerBound() * r2Range.get_LowerBound();
tl2 = r1Range.get_UpperBound() * r2Range.get_UpperBound();
tu1 = r1Range.get_LowerBound() * r2Range.get_UpperBound();
tu2 = r1Range.get_UpperBound() * r2Range.get_LowerBound();
lBound = Math.min(Math.min(Math.min(tl1, tl2), tu1), tu2);
uBound = Math.max(Math.max(Math.max(tl1, tl2), tu1), tu2);
}
// }else if(op=="^"){
// tl1 = pow((double)r1->lvalue,(double)r2->lvalue);
// tl2 = pow((double)r1->uvalue,(double)r2->uvalue);
// tu1 = pow((double)r1->lvalue,(double)r2->uvalue);
// tu2 = pow((double)r1->uvalue,(double)r2->lvalue);
// lvalue = min(min(min(tl1,tl2),tu1),tu2);
// uvalue = max(max(max(tl1,tl2),tu1),tu2);
else if (op.equals("^")){
double tl1, tl2, tu1, tu2;
tl1 = Math.pow(r1Range.get_LowerBound(), r2Range.get_LowerBound());
tl2 = Math.pow(r1Range.get_UpperBound(), r2Range.get_UpperBound());
tu1 = Math.pow(r1Range.get_LowerBound(), r2Range.get_UpperBound());
tu2 = Math.pow(r1Range.get_UpperBound(), r2Range.get_LowerBound());
lBound = (int) Math.min(Math.min(Math.min(tl1, tl2), tu1), tu2);
uBound = (int) Math.max(Math.max(Math.max(tl1, tl2), tu1), tu2);
}
// }else if(op=="u"){
// lvalue = r1->lvalue;
// uvalue = r2->uvalue;
else if (op.equals("uniform")){
lBound = r1Range.get_LowerBound();
uBound = r2Range.get_UpperBound();
}
else if (op.equals("rate")){
LPNContinuousPair lcPair = new LPNContinuousPair(r1.lhpn.getLpnIndex(),
lhpn.getContVarIndex(r1.variable));
lBound = z.getCurrentRate(lcPair);
uBound = z.getCurrentRate(lcPair);
}
// }else if(op=="/"){
// //ropughly integer division.
// //DON"T KNOW WHAT FLOATING POINT PART IS!!!!!
// tl1 = floor(r1->lvalue / r2->lvalue);
// tl2 = floor(r1->uvalue / r2->uvalue);
// tu1 = floor(r1->lvalue / r2->uvalue);
// tu2 = floor(r1->uvalue / r2->lvalue);
// lvalue = min(min(min(tl1,tl2),tu1),tu2);
// tl1 = ceil(r1->lvalue / r2->lvalue);
// tl2 = ceil(r1->uvalue / r2->uvalue);
// tu1 = ceil(r1->lvalue / r2->uvalue);
// tu2 = ceil(r1->uvalue / r2->lvalue);
// uvalue = max(max(max(tl1,tl2),tu1),tu2);
else if (op.equals("/")){ // roughly integer division.
// STILL DON'T KNOW WHAT FLOATING POINT PART IS !!!! :) !!!!
double tl1, tl2, tu1, tu2;
tl1 = Math.floor(((double)r1Range.get_LowerBound()) / r2Range.get_LowerBound());
tl2 = Math.floor(((double)r1Range.get_UpperBound()) / r2Range.get_UpperBound());
tu1 = Math.floor(((double)r1Range.get_LowerBound()) / r2Range.get_UpperBound());
tu2 = Math.floor(((double)r1Range.get_UpperBound()) / r2Range.get_LowerBound());
lBound = (int) Math.min(Math.min(Math.min(tl1, tl2), tu1), tu2);
tl1 = Math.ceil(((double)r1Range.get_LowerBound()) / r2Range.get_LowerBound());
tl2 = Math.ceil(((double)r1Range.get_UpperBound()) / r2Range.get_UpperBound());
tu1 = Math.ceil(((double)r1Range.get_LowerBound()) / r2Range.get_UpperBound());
tu2 = Math.ceil(((double)r1Range.get_UpperBound()) / r2Range.get_LowerBound());
uBound = (int) Math.max(Math.max(Math.max(tl1, tl2), tu1), tu2);
}
// }else if(op=="%"){//NEEDS WORK
else if (op.equals("%")){// STILL NEEDS WORK.
// if (!preciser){
// // Only calculate if both are point values.
// if ((r1->lvalue == r1->uvalue)&&(r2->lvalue == r2->uvalue)){
// lvalue = uvalue = r1->lvalue % r2->uvalue;
// }
// else{
// lvalue = min(0,max(-(max(abs(r2->lvalue),abs(r2->lvalue))-1),r1->lvalue));
// uvalue = max(0,min(max(abs(r2->lvalue),abs(r2->uvalue))-1,r1->uvalue));
// }
// }
// else{
// uvalue = -INFIN;
// lvalue = INFIN;
// for (i = r1->lvalue;i<=r1->uvalue;i++)
// for (j = r2->lvalue;j<=r2->uvalue;j++){
// k = i%j;
// if (k < lvalue)
// lvalue = k;
// if (k > uvalue)
// uvalue = k;
// }
// }
// Not doing the !precier part.
lBound = -INFIN;
uBound = INFIN;
for (int i = r1Range.get_LowerBound(); i <= r1Range.get_UpperBound(); i++){
for ( int j = r2Range.get_LowerBound(); j <= r2Range.get_UpperBound(); j++){
int k = i%j;
if(k < lBound){
lBound = k;
}
if( k > uBound){
uBound = k;
}
}
}
}
// }else if(op=="U-"){
// lvalue = -(r1->uvalue);
// uvalue = -(r1->lvalue);
else if (op.equals("U-")){
lBound = -1 * r1Range.get_UpperBound();
uBound = -1 * (r1Range.get_LowerBound());
}
// }else if(op=="INT"){
// lvalue = r1->lvalue;
// uvalue = r1->uvalue;
else if (op.equals("INT")){
lBound = r1Range.get_LowerBound();
uBound = r1Range.get_UpperBound();
}
// }else if(op=="BOOL"){
// if ((r1->lvalue == 0)&& (r1->uvalue == 0))
// lvalue = uvalue = 0;
// else if (((r1->lvalue > 0) && (r1->uvalue > 0))||
// ((r1->lvalue < 0) && (r1->uvalue < 0)))
// lvalue = uvalue = 1;
// else {
// lvalue = 0;
// uvalue = 1;
// }
else if(op.equals("BOOL")){
if( (r1Range.get_LowerBound() == 0) && (r1Range.get_UpperBound() == 0)){
lBound = uBound =0;
}
else if ((r1Range.get_LowerBound() > 0) && (r1Range.get_UpperBound() > 0) ||
(r1Range.get_LowerBound() < 0) && (r1Range.get_UpperBound() < 0)){
lBound = uBound =1 ;
}
else{
lBound = 0;
uBound = 1;
}
}
// }else if(op=="&"){
else if(op.equals("&")){
// if ((r1->lvalue!=r1->uvalue)||(r2->lvalue!=r2->uvalue)) {
if((r1Range.get_LowerBound() != r1Range.get_UpperBound()) ||
(r2Range.get_LowerBound() != r2Range.get_UpperBound())){
// if (!preciser){
// lvalue = min(r1->lvalue+r2->lvalue,0);
// uvalue = max((r1->uvalue),(r2->uvalue));
// }
// else{
// uvalue = -INFIN;
// lvalue = INFIN;
// for (i = r1->lvalue;i<=r1->uvalue;i++)
// for (j = r2->lvalue;j<=r2->uvalue;j++){
// k = i&j;
// if (k < lvalue)
// lvalue = k;
// if (k > uvalue)
// uvalue = k;
// }
// }
// }
// Not doing the !preciser part.
uBound = -INFIN;
lBound = INFIN;
for( int i=r1Range.get_LowerBound(); i<=r1Range.get_UpperBound(); i++){
for(int j=r2Range.get_LowerBound(); j<=r2Range.get_UpperBound(); j++){
int k = i&j;
if (k < lBound){
lBound =k;
}
if( k > uBound){
uBound = k;
}
}
}
}
// else {
// lvalue = (r1->lvalue & r2->lvalue);
// uvalue = (r1->lvalue & r2->lvalue);
// }
else {
lBound = (r1Range.get_LowerBound() & r2Range.get_LowerBound());
uBound = (r1Range.get_LowerBound() & r2Range.get_LowerBound());
}
// #ifdef __LHPN_EVAL__
// printf("BITWISE AND: [%d,%d](%c)&[%d,%d](%c) = [%d,%d]\n",r1->lvalue,
// r1->uvalue,r1->isit,r2->lvalue,r2->uvalue,r2->isit,lvalue,uvalue);
// #endif
}
// }else if(op=="|"){
else if (op.equals("|")){
// if ((r1->lvalue!=r1->uvalue)||(r2->lvalue!=r2->uvalue)) {
// lvalue = min(r1->lvalue,r2->lvalue);
// uvalue = max(r1->uvalue + r2->uvalue,-1);
// } else {
// lvalue = (r1->lvalue | r2->lvalue);
// uvalue = (r1->lvalue | r2->lvalue);
// }
if((r1Range.get_LowerBound() != r1Range.get_UpperBound()) ||
(r2Range.get_LowerBound() != r2Range.get_UpperBound())){
lBound = Math.min(r1Range.get_LowerBound(), r2Range.get_LowerBound());
uBound = Math.max(r1Range.get_UpperBound() + r2Range.get_UpperBound(), -1);
}
else {
lBound = (r1Range.get_LowerBound() | r2Range.get_LowerBound());
uBound = (r1Range.get_LowerBound() | r2Range.get_LowerBound());
}
}
// }else if(op=="m"){
// lvalue = min(r1->lvalue,r2->lvalue);
// uvalue = min(r1->uvalue,r2->uvalue);
else if(op.equals("m")){
lBound = Math.min(r1Range.get_LowerBound(), r2Range.get_LowerBound());
uBound = Math.min(r1Range.get_UpperBound(), r2Range.get_UpperBound());
}
// }else if(op=="M"){
// lvalue = max(r1->lvalue,r2->lvalue);
// uvalue = max(r1->uvalue,r2->uvalue);
else if (op.equals("M")){
lBound = Math.max(r1Range.get_LowerBound(), r2Range.get_LowerBound());
uBound = Math.max(r1Range.get_UpperBound(), r2Range.get_UpperBound());
}
// }else if(op=="i"){
// tl1 = r1->lvalue / r2->lvalue;
// tl2 = r1->uvalue / r2->uvalue;
// tu1 = r1->lvalue / r2->uvalue;
// tu2 = r1->uvalue / r2->lvalue;
// lvalue = min(min(min(tl1,tl2),tu1),tu2);
// uvalue = max(max(max(tl1,tl2),tu1),tu2);
else if (op.equals("i")){
int tl1, tl2, tu1, tu2;
tl1 = r1Range.get_LowerBound() / r2Range.get_LowerBound();
tl2 = r1Range.get_UpperBound() / r2Range.get_UpperBound();
tu1 = r1Range.get_LowerBound() / r2Range.get_UpperBound();
tu2 = r1Range.get_UpperBound() / r2Range.get_LowerBound();
lBound = Math.min(Math.min(Math.min(tl1, tl2), tu1), tu2);
uBound = Math.max(Math.max(Math.max(tl1, tl2), tu1), tu2);
}
// }else if(op=="X"){
// lvalue = min(min(r1->lvalue-r2->uvalue,r2->lvalue-r1->uvalue),0);
// uvalue = max(max(r1->uvalue + r2->uvalue,-(r1->lvalue + r2->lvalue)),-1);
else if(op.equals("X")){
lBound = Math.min(Math.min(r1Range.get_LowerBound()-r2Range.get_UpperBound(),
r2Range.get_LowerBound()-r1Range.get_UpperBound()), 0);
uBound = Math.max(Math.max(r1Range.get_UpperBound()+r2Range.get_UpperBound(),
r2Range.get_LowerBound()+r1Range.get_LowerBound()), -1);
}
//// }else if(op=="floor"){
//// lvalue = floor(r1->lvalue);
//// uvalue = floor(r1->uvalue);
//// }else if(op=="round"){
//// lvalue = round(r1->lvalue);
//// uvalue = round(r1->uvalue);
//// }else if(op=="ceil"){
//// lvalue = ceil(r1->lvalue);
//// uvalue = ceil(r1->uvalue);
// }else if(op=="~"){
// //bitwise negation operator (1's complement)
// lvalue = -((r1->uvalue)+1);
// uvalue = -((r1->lvalue)+1);
// }
else if (op.equals("~")){
// bitwise negation operator (1's complement)
lBound = -1*(r1Range.get_LowerBound());
uBound = -1*(r1Range.get_UpperBound());
}
// }else if(isit == 'd'){
// for (i = 1;i<cur_state->z->size;i++){
// if (cur_state->z->curClocks[i].enabled == index){
// lvalue = cur_state->r->bound[cur_state->z->curClocks[i].enabled-nevents].lower;
// uvalue = cur_state->r->bound[cur_state->z->curClocks[i].enabled-nevents].upper;
// #ifdef __LHPN_EVAL__
// printf("lv=%d,uv=%d,index=%d,i=%d\n",lvalue, uvalue,index,i);
// #endif
// break;
// }
// }
// Not present in the current implementation. These are 'i'.
// else if (isit == 'd'){
// //Check what this is before doing it.
// }
// }else{
}
else{
// if ((isit == 'i')||(isit == 'c')){
if(isit == 'i'){
// for (i = 1;i<cur_state->z->size;i++){
// if (cur_state->z->curClocks[i].enabled == index){
// if (i>=cur_state->z->dbmEnd){
// lvalue = -1*(cur_state->z->matrix[0][i]);
// uvalue = cur_state->z->matrix[i][0];
// }
// Get the value of the variable from the passed HashMap and convert it as appropriate.
String sV = variables.get(variable); // sV for "string value"
if(sV != null){
int tmp = Integer.parseInt(sV);
// Currently the platu.state does not support integer ranges.
lBound = uBound = tmp;
}
else{
lBound = -INFIN;
uBound = INFIN;
}
// else{// uses lower rate bound for both????
// lvalue = -1*(cur_state->z->matrix[0][i])*
// cur_state->r->bound[cur_state->z->curClocks[i].enabled-nevents].current;
// uvalue = cur_state->z->matrix[i][0]*
// cur_state->r->bound[cur_state->z->curClocks[i].enabled-nevents].current;
// }
// #ifdef __LHPN_EVAL__
// printf("lv=%d,uv=%d,index=%d,i=%d\n",lvalue, uvalue,index,i);
// #endif
// break;
// }
// }
}
else if(isit == 'c'){
// if(z != null){
// return z.getContinuousBounds(variable, lhpn);
// }
// else{
// return continuousValues.get(new LPNContinuousPair(lhpn.getLpnIndex(),
// lhpn.getContVarIndex(variable)));
// }
LPNContinuousPair lcPair = new LPNContinuousPair(lhpn.getLpnIndex(),
lhpn.getContVarIndex(variable));
IntervalPair result = null;
if(continuousValues != null){
result = continuousValues.get(new LPNContAndRate(lcPair));
}
if(result != null){
return result;
}
return z.getContinuousBounds(variable, lhpn);
}
else if (isit == 'b'){
// }else if (isit == 'b'){
// log_val = cur_state->m->state[index];
// if (log_val == '1'){
// lvalue = 1;
// uvalue = 1;
// } else if (log_val == 'X'){
// lvalue = 0;
// uvalue = 1;
// } else if (log_val == '0'){
// lvalue = 0;
// uvalue = 0;
// }
// #ifdef __LHPN_EVAL__
// printf("successful lookup of boolean %d,%c[%d,%d]\n",index,
// cur_state->m->state[index],lvalue,uvalue);
// #endif
// Get the value of the variable from the passed HashMap and convert it as appropriate.
String sV = variables.get(variable); // sV for "string value"
if(sV != null){
int tmp = (sV.toLowerCase().equals("true") || sV.equals("1")) ? 1 : 0;
// Currently the platu.state does not support boolean ranges.
lBound = uBound = tmp;
}
else{
lBound = 0;
uBound = 1;
}
}
else if(isit == 'n'){
// }else if ((isit == 'n')||(isit == 't')){
// // values already stored, no need to evaluate!
// }
// }
lBound = uBound = (int) lvalue;
// if (uvalue == lvalue) {
// return uvalue;
// } else {
// return ((uvalue - lvalue) * new java.util.Random().nextDouble())
// + lvalue;
// }
}
else if ((isit == 't')){
// Should be fine to use the lvalue and uvalue.
lBound = (int) lvalue;
uBound = (int) uvalue;
// // Get the value of the variable from the passed HashMap and convert it as appropriate.
// String sV = variables.get(variable); // sV for "string value"
//
// if(sV != null){
// lBound = uBound = 1;
// }
// else{
// lBound = 0;
// uBound = 1;
// }
}
// };
}
// TODO : need to return an appropriate value when the operation is "".
return new IntervalPair(lBound, uBound);
}
/**
* Converts an integer range for an expression tree representing a logical into
* a boolean pair.
* @param expr
* An expression tree.
* @param range
* The integer range.
* @return
* The range converted to a boolean pair if expr.logical is true and range is non-null.
*/
private BooleanPair logicalConversion(ExprTree expr, IntervalPair range){
Boolean lower, upper;
if( range != null && expr.logical){ // Note : range can only be set if range is non-null.
lower = range.get_LowerBound() != 0; // False if value is zero and true otherwise.
upper = range.get_UpperBound() != 0; // False if value is zero and true otherwise.
}
else{
if (range!=null) {
if((range.get_LowerBound() == 0) && (range.get_UpperBound() == 0)){// false
lower = upper = false;
}
else if (((range.get_LowerBound() < 0) && (range.get_UpperBound() < 0)) ||
((range.get_LowerBound() > 0) && (range.get_UpperBound() > 0))){ // true
lower = upper = true;
}
else{
lower = false;
upper = true;
}
} else {
lower = false;
upper = true;
}
}
return new BooleanPair(lower, upper);
}
//------------------------------- Inner Class -------------------------------------
private class BooleanPair {
private Boolean _lower;
private Boolean _upper;
public BooleanPair(Boolean lower, Boolean upper) {
super();
this._lower = lower;
this._upper = upper;
}
public Boolean get_lower() {
return _lower;
}
// public void set_lower(Boolean lower) {
// this._lower = lower;
// }
public Boolean get_upper() {
return _upper;
}
// public void set_upper(Boolean upper) {
// this._upper = upper;
// }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((_lower == null) ? 0 : _lower.hashCode());
result = prime * result + ((_upper == null) ? 0 : _upper.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof BooleanPair))
return false;
BooleanPair other = (BooleanPair) obj;
if (_lower == null) {
if (other._lower != null)
return false;
} else if (!_lower.equals(other._lower))
return false;
if (_upper == null) {
if (other._upper != null)
return false;
} else if (!_upper.equals(other._upper))
return false;
return true;
}
@Override
public String toString() {
return "BooleanPair [lower=" + _lower + ", upper=" + _upper + "]";
}
}
} | verification/src/main/java/edu/utah/ece/async/lema/verification/lpn/ExprTree.java | /*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.lema.verification.lpn;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import edu.utah.ece.async.ibiosim.dataModels.util.GlobalConstants;
import edu.utah.ece.async.lema.verification.timed_state_exploration.octagon.Equivalence;
import edu.utah.ece.async.lema.verification.timed_state_exploration.zoneProject.IntervalPair;
import edu.utah.ece.async.lema.verification.timed_state_exploration.zoneProject.LPNContAndRate;
import edu.utah.ece.async.lema.verification.timed_state_exploration.zoneProject.LPNContinuousPair;
import java.lang.Math;
/**
*
*
* @author
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class ExprTree {
String op;
char isit; // b=Boolean, i=Integer, c=Continuous, n=Number, t=Truth value,
// w=bitWise, a=Arithmetic, r=Relational, l=Logical
double lvalue, uvalue;
String variable;
double real;
boolean logical;
ExprTree r1, r2;
private String tokvalue = "";
private int position = 0;
public int token = 0;
ExprTree newresult;
private ArrayList<String> booleanSignals, integerSignals, continuousSignals;
private LPN lhpn;
public String expression;
public ExprTree() {
}
/**
* This constructor is used in PlatuGrammar.g to convert LPNs from USF to LhpnFile.
* All LPNs from USF use integer variables only. So only integer signals are dealt with here.
* @param expression
*/
public ExprTree(String expression) {
this.expression = expression;
booleanSignals = new ArrayList<String>();
integerSignals = new ArrayList<String>();
continuousSignals = new ArrayList<String>();
// intexpr_gettok(expression);
// intexpr_L(expression);
}
public ExprTree(LPN lhpn) {
this.lhpn = lhpn;
String[] bools = lhpn.getBooleanVars();
String[] conts = lhpn.getContVars();
String[] ints = lhpn.getIntVars();
booleanSignals = new ArrayList<String>();
integerSignals = new ArrayList<String>();
continuousSignals = new ArrayList<String>();
for (int j = 0; j < bools.length; j++) {
booleanSignals.add(bools[j]);
}
for (int j = 0; j < conts.length; j++) {
continuousSignals.add(conts[j]);
}
for (int j = 0; j < ints.length; j++) {
integerSignals.add(ints[j]);
}
}
public ExprTree(Abstraction abstraction) {
this.lhpn = abstraction;
String[] bools = abstraction.getBooleanVars();
String[] conts = abstraction.getContVars();
String[] ints = abstraction.getIntVars();
booleanSignals = new ArrayList<String>();
integerSignals = new ArrayList<String>();
continuousSignals = new ArrayList<String>();
for (int j = 0; j < bools.length; j++) {
booleanSignals.add(bools[j]);
}
for (int j = 0; j < conts.length; j++) {
continuousSignals.add(conts[j]);
}
for (int j = 0; j < ints.length; j++) {
integerSignals.add(ints[j]);
}
}
// public ExprTree(Transition transition) {
// }
ExprTree(char willbe, int lNV, int uNV, String var) {
op = "";
r1 = null;
r2 = null;
isit = willbe;
if ((isit == 'b') || (isit == 't'))
logical = true;
else
logical = false;
uvalue = uNV;
lvalue = lNV;
variable = var;
real = 0;
}
public ExprTree(ExprTree nr1, ExprTree nr2, String nop, char willbe) {
op = nop;
r1 = nr1;
r2 = nr2;
isit = willbe;
if ((isit == 'r') || (isit == 'l')) {
logical = true;
uvalue = 1;
lvalue = 0;
} else {
logical = false;
uvalue = INFIN;
lvalue = -INFIN;
}
variable = null;
}
public ExprTree(ExprTree source) {
if (source.op != null) {
op = source.op;
}
isit = source.isit;
lvalue = source.lvalue;
uvalue = source.uvalue;
if (source.variable != null) {
variable = source.variable;
}
real = source.real;
logical = source.logical;
if (source.r1 != null) {
r1 = source.r1;
}
if (source.r2 != null) {
r2 = source.r2;
}
if (source.tokvalue != null) {
tokvalue = source.tokvalue;
}
position = source.position;
token = source.token;
if (source.newresult != null) {
newresult = source.newresult;
}
if (source.booleanSignals != null) {
booleanSignals = source.booleanSignals;
}
if (source.integerSignals != null) {
integerSignals = source.integerSignals;
}
if (source.continuousSignals != null) {
continuousSignals = source.continuousSignals;
}
if (source.lhpn != null) {
lhpn = source.lhpn;
}
}
/**
* This constructor takes a list of variables names.
* Each variable name is either an actual LPN discrete integer variable name, or
* a variable that is created during the Markovian analysis of nested properties.
* @param varNameList
*/
public ExprTree(ArrayList<String> varNameList) {
booleanSignals = new ArrayList<String>();
continuousSignals = new ArrayList<String>();
integerSignals = new ArrayList<String>();
for (int j = 0; j < varNameList.size(); j++) {
integerSignals.add(varNameList.get(j));
}
}
public int intexpr_gettok(String expr) {
char c;
boolean readword;
boolean readnum;
boolean readsci;
boolean readsign;
readword = false;
readnum = false;
readsci = false;
readsign = false;
tokvalue = "";
while (position < expr.length()) {
c = expr.charAt(position);
position++;
switch (c) {
case '(':
case ')':
case '[':
case ']':
case ',':
case '~':
case '|':
case '&':
case '*':
case '^':
case '/':
case '%':
case '=':
case '<':
case '>':
if ((!readword) && (!readnum) && (!readsci)) {
return (c);
}
position--;
return (WORD);
case '+':
case '-':
if ((readsci) && (!readnum) && (readsign)) {
tokvalue += c;
readsign = false;
break;
}
if ((readsci) && (!readnum) && (!readsign)) {
return -1;
} else if ((!readword) && (!readnum) && (!readsci)) {
return (c);
} else {
position--;
return (WORD);
}
case ' ':
if (readword) {
return (WORD);
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (!readword) {
readnum = true;
}
tokvalue += c;
break;
case '.':
if (readsci) {
return -1;
} else if (!readword) {
readnum = true;
}
tokvalue += c;
break;
case 'E':
case 'e':
if (readsci) {
return -1;
} else if (readnum) {
readsci = true;
readnum = false;
readsign = true;
tokvalue += c;
break;
} /*else if (!readword){ // TODO: had to remove to make exponential parse but does scientific notation still work?
return -1;
}*/
default:
if ((readnum) || (readsci)) {
return -1;
}
readword = true;
tokvalue += c;
break;
}
}
if ((!readword) && (!readnum)) {
return (END_OF_STRING);
} else if (readword || readnum) {
return (WORD);
}
return -1;
}
public void intexpr_U(String expr) {
double temp;
switch (token) {
case WORD:
if (tokvalue.toLowerCase().equals("and")) {
token = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
token = intexpr_gettok(expr);
intexpr_R(expr);
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = ((int) (this).lvalue)
& ((int) newresult.lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "&", 'w');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("or")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (int) (this).lvalue
| (int) newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "|", 'w');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("xor")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (int) (this).lvalue
^ (int) newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "X", 'w');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("min")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = Math.min((this).lvalue, newresult.lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "m", 'a');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("max")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = Math.max((this).lvalue, newresult.lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "M", 'a');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("idiv")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = Math
.floor((this).lvalue / newresult.lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "i", 'a');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("bit")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
(this).lvalue = ((int) (this).lvalue >> (int) newresult.lvalue) & 1;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "[]", 'l');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("floor")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((this).isit == 'n') || ((this).isit == 't')
&& ((this).lvalue == (this).uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = Math.floor((this).lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), null, "f", 'a');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("ceil")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((this).isit == 'n') || ((this).isit == 't')
&& ((this).lvalue == (this).uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = Math.ceil((this).lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), null, "c", 'a');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("not")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((this).isit == 'n') || ((this).isit == 't')
&& ((this).lvalue == (this).uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = ~(int) (this).lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), null, "~", 'w');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("int")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_L(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
// simplify if operands are static
if (((this).isit == 'n') || ((this).isit == 't')) {
// DO NOTHING
} else {
setNodeValues((this), null, "INT", 'l');
}
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("uniform")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), newresult, "uniform", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("normal")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), newresult, "normal", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("gamma")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), newresult, "gamma", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("lognormal")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), newresult, "lognormal", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("binomial")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ',') {
throw new IllegalArgumentException("ERROR: Expected a ,\n");
}
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
position = newresult.position;
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), newresult, "binomial", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("exponential")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "exponential", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("chisq")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "chisq", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("laplace")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "laplace", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("cauchy")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "cauchy", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("rayleigh")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "rayleigh", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("poisson")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "poisson", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("bernoulli")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "bernoulli", 'a');
(token) = intexpr_gettok(expr);
} else if (tokvalue.equals("rate")) {
(token) = intexpr_gettok(expr);
if ((token) != '(') {
throw new IllegalArgumentException("ERROR: Expected a (\n");
}
(token) = intexpr_gettok(expr);
intexpr_R(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
setNodeValues((this), null, "rate", 'a');
(token) = intexpr_gettok(expr);
} else if ((tokvalue.equals("true")) || tokvalue.equals("TRUE")) {
setVarValues('t', 1, 1, null);
(token) = intexpr_gettok(expr);
} else if ((tokvalue.equals("maybe")) || tokvalue.equals("MAYBE")) {
setVarValues('t', 0, 1, null);
(token) = intexpr_gettok(expr);
}
else if (tokvalue.equals("t") && !booleanSignals.contains(tokvalue) && !integerSignals.contains(tokvalue)
&& !continuousSignals.contains(tokvalue)) {
setVarValues('t', 1, 1, null);
(token) = intexpr_gettok(expr);
}
else if (tokvalue.equals("T") && !booleanSignals.contains(tokvalue) && !integerSignals.contains(tokvalue)
&& !continuousSignals.contains(tokvalue)) {
setVarValues('t', 1, 1, null);
(token) = intexpr_gettok(expr);
}
else if ((tokvalue.equals("false")) || tokvalue.equals("FALSE")) {
setVarValues('t', 0, 0, null);
(token) = intexpr_gettok(expr);
}
else if (tokvalue.equals("f") && !booleanSignals.contains(tokvalue) && !integerSignals.contains(tokvalue)
&& !continuousSignals.contains(tokvalue)) {
setVarValues('t', 0, 0, null);
(token) = intexpr_gettok(expr);
}
else if (tokvalue.equals("F") && !booleanSignals.contains(tokvalue) && !integerSignals.contains(tokvalue)
&& !continuousSignals.contains(tokvalue)) {
setVarValues('t', 0, 0, null);
(token) = intexpr_gettok(expr);
} else if ((tokvalue.toLowerCase().equals("unknown"))) {
setVarValues('t', 0, 1, null);
(token) = intexpr_gettok(expr);
} else if (tokvalue.toLowerCase().equals("inf")) {
setVarValues('n', INFIN, INFIN, null);
token = intexpr_gettok(expr);
} else {
// do boolean lookup here!!!
if (booleanSignals.contains(tokvalue)) {
setVarValues('b', 0, 1, tokvalue);
(token) = intexpr_gettok(expr);
return;
}
else if (integerSignals.contains(tokvalue)) {
setVarValues('i', -INFIN, INFIN, tokvalue);
(token) = intexpr_gettok(expr);
return;
}
else if (continuousSignals.contains(tokvalue)) {
setVarValues('c', -INFIN, INFIN, tokvalue);
(token) = intexpr_gettok(expr);
return;
}
if (tokvalue.equals("")) {
throw new IllegalArgumentException(String.format(
"U1:ERROR(%s): Expected a ID, Number, or a (\n",
tokvalue));
} else if ((tokvalue.charAt(0)) > ('9')
|| ((tokvalue.charAt(0)) < '0')) {
throw new IllegalArgumentException(String.format(
"U1:ERROR(%s): Expected a ID, Number, or a (\n",
tokvalue));
}
temp = Double.parseDouble(tokvalue);
setVarValues('n', temp, temp, null);
token = intexpr_gettok(expr);
}
break;
case '(':
(token) = intexpr_gettok(expr);
intexpr_L(expr);
if ((token) != ')') {
throw new IllegalArgumentException("ERROR: Expected a )\n");
}
(token) = intexpr_gettok(expr);
break;
default:
throw new IllegalArgumentException("U2:ERROR: Expected a ID, Number, or a (\n");
}
}
public void intexpr_T(String expr) {
switch (token) {
case WORD:
case '(':
intexpr_U(expr);
break;
case '-':
(token) = intexpr_gettok(expr);
intexpr_U(expr);
// simplify if operands are static
if ((((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = -((this).lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), null, "U-", 'a');
}
break;
default:
throw new IllegalArgumentException("T:ERROR: Expected a ID, Number, (, or -\n");
}
}
public void intexpr_C(String expr) {
newresult = new ExprTree(this);
switch (token) {
case '*':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_T(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (this).lvalue * newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "*", 'a');
}
intexpr_C(expr);
break;
case '^':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_T(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = Math.pow(lvalue, newresult.lvalue);
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "^", 'a');
}
intexpr_C(expr);
break;
case '/':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_T(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (this).lvalue / newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "/", 'a');
}
intexpr_C(expr);
break;
case '%':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_T(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (this).lvalue % newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "%", 'a');
}
intexpr_C(expr);
break;
case '+':
case '-':
case ')':
case '[':
case ']':
case '|':
case '&':
case '=':
case '<':
case '>':
case ',':
case IMPLIES:
case END_OF_STRING:
break;
case '(':
case WORD:
newresult.intexpr_T(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (this).lvalue * newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "*", 'a');
}
intexpr_C(expr);
break;
default:
throw new IllegalArgumentException("ERROR: Expected a * or /\n");
}
}
public void intexpr_B(String expr) {
newresult = new ExprTree(this);
switch (token) {
case '+':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_S(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (this).lvalue + newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "+", 'a');
}
intexpr_B(expr);
break;
case '-':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_S(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 'n';
(this).lvalue = (this).lvalue - newresult.lvalue;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "-", 'a');
}
intexpr_B(expr);
break;
case ')':
case '[':
case ']':
case '|':
case '&':
case '=':
case '<':
case '>':
case ',':
case IMPLIES:
case END_OF_STRING:
break;
default:
throw new IllegalArgumentException("ERROR: Expected a + or -\n");
}
}
public void intexpr_S(String expr) {
switch (token) {
case WORD:
case '(':
case '-':
intexpr_T(expr);
intexpr_C(expr);
break;
default:
throw new IllegalArgumentException("S:ERROR: Expected a ID, Number, (, or -\n");
}
}
public void intexpr_R(String expr) {
switch (token) {
case WORD:
case '(':
case '-':
intexpr_S(expr);
intexpr_B(expr);
break;
default:
throw new IllegalArgumentException("R:ERROR: Expected a ID, Number, (, or -\n");
}
}
public void intexpr_P(String expr) {
newresult = new ExprTree(this);
//int spos, i;
String ineq = "";
String comp;
switch (token) {
case '=':
//spos = position;
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
tokvalue = newresult.tokvalue;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if (this.lvalue == newresult.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
} else {
if ((this).isit == 'c') {
comp = variable;
// comp += "=";
//// int paren = 0;
//// for (i = spos; i < position; i++) {
//// if (expr.charAt(i) == '(')
//// paren++;
//// if (expr.charAt(i) == ')')
//// paren--;
//// ineq = ineq + expr.charAt(i);
//// }
// comp += ineq;
if (booleanSignals.contains(comp)) {
this.isit = 'b';
this.variable = comp;
this.lvalue = 0;
this.uvalue = 1;
return;
}
booleanSignals.add(comp);
this.isit = 'b';
this.variable = comp;
this.lvalue = 0;
this.uvalue = 1;
return;
}
setNodeValues((this), newresult, "==", 'r');
}
break;
case '>':
//spos = position;
(token) = intexpr_gettok(expr);
newresult.token = token;
if ((token) == '=') {
//spos = position;
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
tokvalue = newresult.tokvalue;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if ((this).lvalue >= newresult.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, ">=", 'r');
}
} else {
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
tokvalue = newresult.tokvalue;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if ((this).lvalue > newresult.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, ">", 'r');
}
}
break;
case '<':
//spos = position;
(token) = intexpr_gettok(expr);
if ((token) == '=') {
//spos = position;
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
tokvalue = newresult.tokvalue;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if ((this).lvalue <= newresult.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "<=", 'r');
}
} else {
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
tokvalue = newresult.tokvalue;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN)
&& ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if ((this).lvalue < newresult.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "<", 'r');
}
}
break;
case '[':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_R(expr);
token = newresult.token;
tokvalue = newresult.tokvalue;
position = newresult.position;
if ((token) != ']') {
throw new IllegalArgumentException("ERROR: Expected a ]\n");
}
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
(this).lvalue = (((int) (this).lvalue) >> ((int) newresult.lvalue)) & 1;
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "[]", 'l');
}
(token) = intexpr_gettok(expr);
break;
case '&':
case '|':
case ')':
case IMPLIES:
case END_OF_STRING:
break;
default:
throw new IllegalArgumentException("ERROR: Expected a [, =, <, or >\n");
}
}
public void intexpr_O(String expr) {
switch (token) {
case WORD:
case '(':
case '-':
intexpr_R(expr);
intexpr_P(expr);
break;
default:
throw new IllegalArgumentException("O:ERROR: Expected a ID, Number, or a (\n");
}
}
public void intexpr_N(String expr) {
switch (token) {
case WORD:
case '-':
case '(':
intexpr_O(expr);
break;
case '~':
(token) = intexpr_gettok(expr);
intexpr_O(expr);
// simplify if operands are static
if ((((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)) {
(this).isit = 't';
if (this.lvalue == 1) {
this.lvalue = 0;
} else {
this.lvalue = 1;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), null, "!", 'l');
}
break;
default:
throw new IllegalArgumentException("N:ERROR: Expected a ID, Number, (, or -\n");
}
}
public void intexpr_E(String expr) {
newresult = new ExprTree(this);
switch (token) {
case '&':
token = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_N(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if ((this.lvalue == 0) || (newresult.lvalue == 0)) {
this.lvalue = 0;
} else {
this.lvalue = 1;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "&&", 'l');
}
intexpr_E(expr);
break;
case '|':
case ')':
case IMPLIES:
case END_OF_STRING:
break;
default:
throw new IllegalArgumentException(String.format("ERROR(%c): Expected an &\n", (token)));
}
}
public void intexpr_D(String expr) {
newresult = new ExprTree(this);
switch (token) {
case '|':
(token) = intexpr_gettok(expr);
newresult.token = token;
newresult.tokvalue = tokvalue;
newresult.position = position;
newresult.intexpr_M(expr);
token = newresult.token;
position = newresult.position;
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if (this.lvalue != 0 || newresult.lvalue != 0) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues((this), newresult, "||", 'l');
}
intexpr_D(expr);
break;
case ')':
case END_OF_STRING:
break;
case IMPLIES:
(token) = intexpr_gettok(expr);
intexpr_M(expr);
// simplify if operands are static
if (((newresult.isit == 'n') || (newresult.isit == 't'))
&& (((this).isit == 'n') || ((this).isit == 't'))
&& ((this).lvalue == (this).uvalue)
&& (newresult.lvalue == newresult.uvalue)
&& ((this).lvalue != INFIN) && ((this).lvalue != -INFIN)
&& (newresult.lvalue != INFIN)
&& (newresult.lvalue != -INFIN)) {
(this).isit = 't';
if (this.lvalue != 0 || newresult.lvalue == 0) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
} else {
setNodeValues(this, newresult, "->", 'l');
}
intexpr_D(expr);
break;
default:
throw new IllegalArgumentException("ERROR: Expected an | or ->\n");
}
}
public void intexpr_M(String expr) {
switch (token) {
case WORD:
case '(':
case '~':
case '-':
intexpr_N(expr);
intexpr_E(expr);
break;
default:
throw new IllegalArgumentException("M: ERROR: Expected a ID, Number, (, or -\n");
}
}
public void intexpr_L(String expr) {
switch (token) {
case WORD:
case '(':
case '~':
case '-':
intexpr_M(expr);
intexpr_D(expr);
break;
default:
throw new IllegalArgumentException("L:ERROR: Expected a ID, Number, (, or -\n");
}
}
@Override
public String toString() {
String result = "";
result = getElement("LHPN");
return result;
}
public String toString(String type) {
String result = "";
result = getElement(type);
return result;
}
public String toString(String type, String lhpnSbml) {
String result = "";
result = getElement(lhpnSbml);
if (type.equals("continuous") || type.equals("integer")) {
if (isit == 't') {
if (uvalue == 0) {
result = "0";
} else {
result = "1";
}
}
} else {
if (isit == 'n') {
if (uvalue == 0) {
result = "false";
} else {
result = "true";
}
}
}
return result;
}
public boolean implies(ExprTree expr) {
if (isEqual(expr)) {
return true;
}
if (expr.isit == 'l' && expr.op.equals("||")) {
if (implies(expr.r1) || implies(expr.r2)) {
return true;
}
} else if (expr.isit == 'l' && expr.op.equals("&&")) {
if (implies(expr.r1) && implies(expr.r2)) {
return true;
}
}
switch (isit) {
case 't': // Truth value
if (uvalue == 1 && lvalue == 1) {
return false;
} else if (uvalue == 0 && lvalue == 0) {
return true;
} else {
return false;
}
case 'r': // Relational
if (op.contains(">")) {
if (expr.isit == 'r' && expr.op.contains(">")) {
if (r2.lvalue > expr.r2.uvalue) {
return true;
} else if (r2.lvalue == expr.r2.uvalue
&& op.length() >= expr.op.length()) {
return true;
}
}
} else if (op.contains("<")) {
if (expr.isit == 'r' && expr.op.contains("<")) {
if (r2.lvalue < expr.r2.uvalue) {
return true;
} else if (r2.lvalue == expr.r2.uvalue
&& op.length() >= expr.op.length()) {
return true;
}
}
}
return false;
case 'l': // Logical
if (op.equals("&&")) {
if (expr.isit == 'b') {
if (r1.implies(expr) || r2.implies(expr)) {
return true;
}
}
} else if (op.equals("||")) {
if (expr.isit == 'b') {
if (r1.implies(expr) && r2.implies(expr)) {
return true;
}
}
}
return false;
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
case 'n': // Number
case 'w': // bitWise
case 'a': // Arithmetic
default:
return false;
}
}
public boolean containsVar(String var) {
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
if (variable.equals(var))
return true;
return false;
case 'r': // Relational
case 'l': // Logical
case 'a': // Arithmetic
case 'w': // bitWise
if (r1 != null) {
if (r1.containsVar(var)) {
return true;
}
}
if (r2 != null) {
if (r2.containsVar(var)) {
return true;
}
}
return false;
case 'n': // Number
case 't': // Truth value
default:
return false;
}
}
public ArrayList<String> getVars() {
ArrayList<String> vars = new ArrayList<String>();
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
if (!vars.contains(variable))
vars.add(variable);
break;
case 'r': // Relational
case 'l': // Logical
case 'a': // Arithmetic
case 'w': // bitWise
if (r1 != null)
vars.addAll(r1.getVars());
if (r2 != null)
vars.addAll(r2.getVars());
break;
case 'n': // Number
case 't': // Truth value
default:
break;
}
return vars;
}
/**
* Returns a list of the continuous variable's names that are
* contained in this ExprTree.
* @return
* The list of name of the continuous variables in this
* ExprTree.
*/
public ArrayList<String> getContVars() {
ArrayList<String> vars = new ArrayList<String>();
switch (isit) {
//case 'b': // Boolean
//case 'i': // Integer
case 'c': // Continuous
if (!vars.contains(variable))
vars.add(variable);
break;
case 'r': // Relational
case 'l': // Logical
case 'a': // Arithmetic
case 'w': // bitWise
if (r1 != null)
vars.addAll(r1.getVars());
if (r2 != null)
vars.addAll(r2.getVars());
break;
case 'n': // Number
case 't': // Truth value
default:
break;
}
return vars;
}
public void scaleVals(Double scaleFactor) { // SB
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
break;
case 'r': // Relational
case 'l': // Logical
case 'a': // Arithmetic
case 'w': // bitWise
if (r1 != null)
r1.scaleVals(scaleFactor);
if (r2 != null)
r2.scaleVals(scaleFactor);
break;
case 'n': // Number
variable = String
.valueOf((int) (Double.parseDouble(variable) * scaleFactor));
break;
case 't': // Truth value
default:
break;
}
}
public boolean containsCont() {
switch (isit) {
case 'b': // Boolean
case 't': // Truth value
return false;
case 'i': // Integer
case 'c': // Continuous
case 'r': // Relational
case 'a': // Arithmetic
case 'n': // Number
return true;
case 'l': // Logical
case 'w': // bitWise
boolean r1cont = false,
r2cont = false;
if (r1 != null)
r1cont = r1.containsCont();
if (r2 != null)
r2cont = r2.containsCont();
return (r1cont || r2cont);
}
return false;
}
/**
* This method will return true if the
* expression tree contains a continuous variable.
* This is difference from containsCont() which
* will return true if there is an integer,
* relational, arithmetic or number.
* @return
* True if this ExprTree continuous a
* continuous variable.
*/
public boolean containsExactlyCont() {
switch (isit) {
// These are leaf nodes that we are not looking for.
case 'b': // Boolean
case 't': // Truth value
case 'i': // Integer
case 'n': // Number
return false;
// This is what we are looking for.
case 'c': // Continuous
return true;
// The subexpression may contain a continuous variable
// so need to check further.
case 'a': // Arithmetic
case 'r': // Relational
case 'l': // Logical
case 'w': // bitWise
boolean r1cont = false,
r2cont = false;
if (r1 != null)
r1cont = r1.containsExactlyCont();
if (r2 != null)
r2cont = r2.containsExactlyCont();
return (r1cont || r2cont);
}
return false;
}
public void replace(String var, String type, ExprTree e) {
if (this == e) {
return;
}
boolean simplify = false;
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
if (variable.equals(var)) {
if (e.isit == 'a' || e.isit == 'r' || e.isit == 'l'
|| e.isit == 'w') {
setNodeValues(e.r1, e.r2, e.op, e.isit);
} else {
setVarValues(e.isit, e.lvalue, e.uvalue, e.variable);
}
}
return;
case 'w': // bitWise
case 'l': // Logical
case 'r': // Relational
case 'a': // Arithmetic
if (r1 != null || r2 != null) {
if (r1 != null)
r1.replace(var, type, e);
if (r2 != null)
r2.replace(var, type, e);
break;
}
// simplify if operands are static
if (op.equals("&&")) {
if ((r1.isit == 'n') || (r1.isit == 't')) {
if (r1.lvalue == 0) {
setVarValues('t', 0.0, 0.0, null);
simplify = true;
} else {
if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w'
|| r2.isit == 'r') {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
} else {
setVarValues(r2.isit, r2.lvalue, r2.uvalue,
r2.variable);
}
}
} else if (((r2).isit == 'n') || ((r2).isit == 't')) {
if (r2.lvalue == 0) {
setVarValues('t', 0.0, 0.0, null);
simplify = true;
} else {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue,
r1.variable);
}
}
}
} else if (op.equals("||")) {
if ((r1.isit == 'n') || (r1.isit == 't')) {
if (r1.lvalue == 1) {
setVarValues('t', 1.0, 1.0, null);
simplify = true;
} else {
if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w'
|| r2.isit == 'r') {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
} else {
setVarValues(r2.isit, r2.lvalue, r2.uvalue,
r2.variable);
}
}
} else if (((r2).isit == 'n') || ((r2).isit == 't')) {
if (r2.lvalue == 1) {
setVarValues('t', 1.0, 1.0, null);
simplify = true;
} else {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue,
r1.variable);
}
}
} else if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if (r1.lvalue != 0 || r2.lvalue != 0) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("->")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if (r1.lvalue != 0 || r2.lvalue == 0) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("!")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 't';
if (r1.lvalue == 1) {
this.lvalue = 0;
} else {
this.lvalue = 1;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("==")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if (r1.lvalue == r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals(">=")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue >= r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals(">")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue > r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("<=")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue <= r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("<")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue < r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("&")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = ((int) (r1).lvalue) & ((int) r2.lvalue);
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("|")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (int) (r1).lvalue | (int) r2.lvalue;
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("X")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (int) (r1).lvalue ^ (int) r2.lvalue;
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("m")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = Math.min((r1).lvalue, r2.lvalue);
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("M")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = Math.max((r1).lvalue, r2.lvalue);
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("i")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = Math.floor((r1).lvalue / (r2).lvalue);
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("f")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = Math.floor((r1).lvalue);
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("c")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = Math.ceil((r1).lvalue);
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("~")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = ~(int) (r1).lvalue;
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("[]")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
(this).lvalue = (((int) (r1).lvalue) >> ((int) r2.lvalue)) & 1;
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("U-")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = -((r1).lvalue);
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("*")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue * r2.lvalue;
(this).uvalue = (this).lvalue;
}
} else if (op.equals("/")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue / r2.lvalue;
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("%")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue % r2.lvalue;
(this).uvalue = (this).lvalue;
simplify = true;
}
} else if (op.equals("+")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue + r2.lvalue;
(this).uvalue = (this).lvalue;
} else if ((r1.isit == 'n') || (r1.isit == 't')) {
if (r1.lvalue == 0 && r1.uvalue == 0) {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
}
} else if (((r2).isit == 'n') || ((r2).isit == 't')) {
if (r2.lvalue == 0 && r2.uvalue == 0) {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
}
}
} else if (op.equals("-")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue - r2.lvalue;
(this).uvalue = (this).lvalue;
simplify = true;
}
}
break;
case 't': // Truth value
if (lvalue != 0 && uvalue != 0) {
lvalue = 1;
uvalue = 1;
} else if (lvalue != 0 || uvalue != 0) {
lvalue = 0;
uvalue = 1;
}
return;
case 'n': // Number
break;
}
if (simplify) {
if (type.equals("integer") || type.equals("continuous")) {
isit = 'n';
} else {
isit = 't';
if (lvalue != 0 && uvalue != 0) {
lvalue = 1;
uvalue = 1;
} else if (lvalue != 0 || uvalue != 0) {
lvalue = 0;
uvalue = 1;
}
}
}
}
public void replaceVar(String var1, String var2) {
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
if (variable.equals(var1)) {
variable = var2;
}
return;
case 'w': // bitWise
case 'l': // Logical
case 'r': // Relational
case 'a': // Arithmetic
if (r1 != null)
r1.replaceVar(var1, var2);
if (r2 != null)
r2.replaceVar(var1, var2);
break;
case 't': // Truth value
case 'n': // Number
break;
}
}
public char getChange(HashMap<String, String> variables) {
switch (isit) {
case 'b': // Boolean
if (variables.containsKey(variable)) {
if (variables.get(variable).toString().toLowerCase().equals("false"))
return 'F';
if (variables.get(variable).toString().toLowerCase().equals("true"))
return 'T';
return 'X';
}
return 'U';
case 't': // Truth value
/*
if (uvalue == 0)
return 'F';
else if (lvalue == 1)
return 'T';
*/
return 'U';
case 'l': // Logical
if (op.equals("||")) {
if (r1.getChange(variables) == 'T'
|| r2.getChange(variables) == 'T') {
return 'T';
} else if (r1.getChange(variables) == 'X'
|| r2.getChange(variables) == 'X') {
return 'X';
} else if (r1.getChange(variables) == 't') {
if (r2.getChange(variables) == 'f') {
return 'X';
}
return 't';
} else if (r2.getChange(variables) == 't') {
if (r1.getChange(variables) == 'f') {
return 'X';
}
return 't';
} else if (r1.getChange(variables) == 'f'
|| r2.getChange(variables) == 'f') {
return 'f';
} else if (r1.getChange(variables) == 'F') {
if (r2.getChange(variables) == 'F') {
return 'F';
}
return 'f';
} else if (r2.getChange(variables) == 'F') {
return 'f';
}
return 'U';
} else if (op.equals("&&")) {
if (r1.getChange(variables) == 'F'
|| r2.getChange(variables) == 'F') {
return 'F';
} else if (r1.getChange(variables) == 'X'
|| r2.getChange(variables) == 'X') {
return 'X';
} else if (r1.getChange(variables) == 'f') {
if (r2.getChange(variables) == 't') {
return 'X';
}
return 'f';
} else if (r2.getChange(variables) == 'f') {
if (r1.getChange(variables) == 't') {
return 'X';
}
return 'f';
} else if (r1.getChange(variables) == 't'
|| r2.getChange(variables) == 't') {
return 't';
} else if (r1.getChange(variables) == 'T') {
if (r2.getChange(variables) == 'T') {
return 'T';
}
return 't';
} else if (r2.getChange(variables) == 'T') {
return 't';
}
return 'U';
} else if (op.equals("!")) {
if (r1.getChange(variables) == 'T') {
return 'F';
} else if (r1.getChange(variables) == 'F') {
return 'T';
} else if (r1.getChange(variables) == 't') {
return 'f';
} else if (r1.getChange(variables) == 'f') {
return 't';
}
return r1.getChange(variables);
} else if (op.equals("->")) {
if (r1.getChange(variables) == 'T'
|| r2.getChange(variables) == 'F') {
return 'T';
} else if (r1.getChange(variables) == 'X'
|| r2.getChange(variables) == 'X') {
return 'X';
} else if (r1.getChange(variables) == 't') {
if (r2.getChange(variables) == 't') {
return 'X';
}
return 't';
} else if (r2.getChange(variables) == 'f') {
if (r1.getChange(variables) == 'f') {
return 'X';
}
return 't';
} else if (r1.getChange(variables) == 'f') {
return 'f';
} else if (r2.getChange(variables) == 't') {
return 'f';
} else if (r1.getChange(variables) == 'F') {
if (r2.getChange(variables) == 'T') {
return 'F';
}
return 'f';
} else if (r2.getChange(variables) == 'T') {
return 'f';
}
return 'U';
}
break;
case 'r': // Relational
boolean flag = false;
for (String var : getVars()) {
if (variables.containsKey(var)) {
flag = true;
break;
}
}
if (!flag) {
return 'U';
}
if (op.equals("==")) {
if (r1.evaluateExpr(variables) == r2.evaluateExpr(variables)) {
return 'T';
} else if (new Double(r1.evaluateExpr(variables))
.equals(Double.NaN)
|| new Double(r2.evaluateExpr(variables))
.equals(Double.NaN)) {
return 'X';
}
return 'F';
} else if (op.equals(">=")) {
if (r1.evaluateExpr(variables) >= r2.evaluateExpr(variables)) {
return 'T';
} else if (new Double(r2.evaluateExpr(variables))
.equals(Double.NaN)
|| new Double(r1.evaluateExpr(variables))
.equals(Double.NaN)) {
return 'X';
}
return 'F';
} else if (op.equals("<=")) {
if (r1.evaluateExpr(variables) <= r2.evaluateExpr(variables)) {
return 'T';
} else if (new Double(r1.evaluateExpr(variables))
.equals(Double.NaN)
|| new Double(r2.evaluateExpr(variables))
.equals(Double.NaN)) {
return 'X';
}
return 'F';
} else if (op.equals(">")) {
if (r1.evaluateExpr(variables) > r2.evaluateExpr(variables)) {
return 'T';
} else if (new Double(r1.evaluateExpr(variables))
.equals(Double.NaN)
|| new Double(r2.evaluateExpr(variables))
.equals(Double.NaN)) {
return 'X';
}
return 'F';
} else if (op.equals("<")) {
if (r1.evaluateExpr(variables) < r2.evaluateExpr(variables)) {
return 'T';
} else if (new Double(r1.evaluateExpr(variables))
.equals(Double.NaN)
|| new Double(r2.evaluateExpr(variables))
.equals(Double.NaN)) {
return 'X';
}
return 'F';
}
return 'X';
case 'i': // Integer
if (variables.containsKey(variable)) {
try {
if (Integer.parseInt(variables.get(variable)) == 0.0) {
return 'F';
}
return 'T';
} catch (Exception e) {
return 'X';
}
}
return 'U';
case 'c': // Continuous
return 'X';
case 'n': // Number
if (uvalue == 0.0 && lvalue == 0.0) {
return 'F';
}
return 'T';
}
return 'X';
}
public boolean becomesFalse(HashMap<String, String> variables) {
switch (isit) {
case 'b': // Boolean
if (variables.containsKey(variable))
if (variables.get(variable).toString().toLowerCase().equals(
"false"))
return true;
return false;
case 't': // Truth value
if (lvalue == 0)
return true;
return false;
case 'l': // Logical
if (op.equals("||")) {
if (r1.becomesFalse(variables) && r2.becomesFalse(variables)) {
return true;
}
return false;
} else if (op.equals("&&")) {
if ((r1.becomesFalse(variables) && !r2.becomesTrue(variables))
|| (!r1.becomesTrue(variables) && r2
.becomesFalse(variables)))
return true;
return false;
} else if (op.equals("==")) {
if (!(r1.isEqual(r2) || r1.evaluateExpr(variables) == r2
.evaluateExpr(variables)))
return true;
return false;
} else if (op.equals("!")) {
if (r1.becomesTrue(variables))
return true;
return false;
} else if (op.equals("->")) {
if (r1.becomesFalse(variables) || r2.becomesTrue(variables)) {
return true;
}
return false;
} else if (op.equals("[]")) {
if (!(evaluateExpr(variables) == 0.0)) {
return true;
}
return false;
}
break;
case 'w': // bitWise
if (op.equals("&")) {
if (!(evaluateExpr(variables) == 0.0)) {
return true;
}
return false;
} else if (op.equals("|")) {
if (!(evaluateExpr(variables) == 0.0)) {
return true;
}
return false;
} else if (op.equals("X")) {
if (!(evaluateExpr(variables) == 0.0)) {
return true;
}
return false;
} else if (op.equals("~")) {
if (!(evaluateExpr(variables) == 0.0)) {
return true;
}
return false;
}
break;
case 'r': // Relational
if (r1.isit == 'i') {
if (!variables.containsKey(r1.variable)) {
return false;
}
if (op.equals("==")) {
if (r1.evaluateExpr(variables) == r2
.evaluateExpr(variables)) {
return false;
}
return true;
} else if (op.equals(">=")) {
if (r1.evaluateExpr(variables) >= r2
.evaluateExpr(variables)) {
return false;
}
return true;
} else if (op.equals("<=")) {
if (r1.evaluateExpr(variables) <= r2
.evaluateExpr(variables)) {
return false;
}
return true;
} else if (op.equals(">")) {
if (r1.evaluateExpr(variables) > r2.evaluateExpr(variables)) {
return false;
}
return true;
} else if (op.equals("<")) {
if (r1.evaluateExpr(variables) < r2.evaluateExpr(variables)) {
return false;
}
return true;
}
return true;
}
return true;
case 'i': // Integer
if (variables.containsKey(variable)) {
if (Integer.parseInt(variables.get(variable)) == 0.0) {
return true;
}
return false;
}
return false;
case 'c': // Continuous
return true;
case 'a': // Arithmetic
boolean contains = false;
for (String s : getVars()) {
if (variables.containsKey(s)) {
contains = true;
break;
}
}
if (!contains) {
return false;
}
if (!(evaluateExpr(variables) == 0.0)) {
return false;
}
return true;
case 'n': // Number
if (uvalue == 0.0 && lvalue == 0.0) {
return true;
}
return false;
}
return false;
}
public boolean becomesTrue(HashMap<String, String> variables) {
switch (isit) {
case 'b': // Boolean
if (variables.containsKey(variable)) {
if (variables.get(variable).toString().matches("[\\d[\\.]]+")) {
if (Double.parseDouble(variables.get(variable).toString()) != 0) {
return true;
}
}
if (variables.get(variable).toString().toLowerCase().equals(
"true"))
return true;
}
return false;
case 'i': // Integer
if (variables.containsKey(variable)) {
if (!variables.get(variable).equals("0.0")) {
return true;
}
}
return false;
case 'c': // Continuous
return true;
case 'n': // Number
case 't': // Truth value
if (uvalue != 0)
return true;
return false;
case 'l': // Logical
if (op.equals("||")) {
if (r1.becomesTrue(variables) || r2.becomesTrue(variables))
return true;
return false;
} else if (op.equals("&&")) {
if ((r1.becomesTrue(variables) && !r2.becomesFalse(variables))
|| (!r1.becomesFalse(variables) && r2
.becomesTrue(variables)))
return true;
return false;
} else if (op.equals("==")) {
if (r1.isEqual(r2, variables)
|| r1.evaluateExpr(variables) == r2
.evaluateExpr(variables))
return true;
return false;
} else if (op.equals("!")) {
if (r1.becomesFalse(variables))
return true;
return false;
} else if (op.equals("->")) {
if (r1.becomesTrue(variables) || r2.becomesFalse(variables)) {
return true;
}
return false;
}
break;
case 'w': // bitWise
if (op.equals("&")) {
if (evaluateExpr(variables) == 0.0) {
return false;
}
return true;
} else if (op.equals("|")) {
if (evaluateExpr(variables) == 0.0) {
return false;
}
return true;
} else if (op.equals("X")) {
if (evaluateExpr(variables) == 0.0) {
return false;
}
return true;
} else if (op.equals("~")) {
if (evaluateExpr(variables) == 0.0) {
return false;
}
return true;
} else if (op.equals("[]")) {
if (evaluateExpr(variables) == 0.0) {
return false;
}
return true;
}
break;
case 'r': // Relational
if (r1.isit == 'i') {
if (!variables.containsKey(r1.variable)) {
return false;
}
if (op.equals("==")) {
if (!(r1.evaluateExpr(variables) == r2
.evaluateExpr(variables))) {
return false;
}
return true;
} else if (op.equals(">=")) {
if (!(r1.evaluateExpr(variables) >= r2
.evaluateExpr(variables))) {
return false;
}
return true;
} else if (op.equals("<=")) {
if (!(r1.evaluateExpr(variables) <= r2
.evaluateExpr(variables))) {
return false;
}
return true;
} else if (op.equals(">")) {
if (!(r1.evaluateExpr(variables) > r2
.evaluateExpr(variables))) {
return false;
}
return true;
} else if (op.equals("<")) {
if (!(r1.evaluateExpr(variables) < r2
.evaluateExpr(variables))) {
return false;
}
return true;
}
return true;
}
return true;
case 'a': // Arithmetic
boolean contains = false;
for (String s : getVars()) {
if (variables.containsKey(s)) {
contains = true;
break;
}
}
if (!contains) {
return false;
}
if (!(evaluateExpr(variables) != 0.0)) {
return false;
}
return true;
}
return true;
}
public String getElement(String type) {
boolean sbmlFlag;
sbmlFlag = type.equals("SBML");
Boolean verilog = type.equalsIgnoreCase("Verilog");
String result = "";
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
if (!sbmlFlag) {
result = variable;
} else {
if (isit == 'b') {
result = "eq(" + variable + ",1)";
} else {
result = variable;
}
}
break;
case 'n': // Number
// long term solution: create initial assignment
// short term solution: initialize all inf, -inf, [-inf, inf] to 0
// initialize [l,u] to (l+u)/2
Double tempuval = uvalue;
Double templval = lvalue;
if ((uvalue == lvalue) || tempuval.toString().equals("")) {
if (lvalue == INFIN) {
result = "inf";
} else if (lvalue == -INFIN) {
result = "-inf";
} else {
if (tempuval % 1 == 0) {
int tempval = (int) (tempuval / 1);
result = new Integer(tempval).toString();
} else {
result = tempuval.toString();
}
}
} else {
String lval;
if (lvalue == INFIN) {
lval = "inf";
} else if (lvalue == -INFIN) {
lval = "-inf";
} else {
if (tempuval % 1 == 0) {
int tempval = (int) (templval / 1);
lval = new Integer(tempval).toString();
} else {
lval = templval.toString();
}
}
String uval;
if (uvalue == INFIN) {
uval = "inf";
} else if (uvalue == -INFIN) {
uval = "-inf";
} else {
if (tempuval % 1 == 0) {
int tempval = (int) (tempuval / 1);
uval = new Integer(tempval).toString();
} else {
uval = tempuval.toString();
}
}
if (verilog) {
result = "uniform(" + lval + "," + uval + ")";
} else {
result = "uniform(" + lval + "," + uval + ")";
}
}
break;
case 't': // Truth value
if (uvalue == 0 && lvalue == 0) {
if (verilog)
result = "0";
else
result = "false";
} else if (uvalue == 1 && lvalue == 1) {
if (verilog)
result = "1";
else
result = "true";
} else {
if (sbmlFlag)
result = "true";
else
result = "UNKNOWN";
}
break;
case 'w': // bitWise
if (op.equals("&")) {
if (r1 != null && r2 != null) {
if (sbmlFlag) {
result = "BITAND(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
} else if (verilog) {
result = r1.getElement(type) + "&"
+ r2.getElement(type);
} else {
result = "and(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
} else if (op.equals("|")) {
if (r1 != null && r2 != null) {
if (sbmlFlag) {
result = "BITOR(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
} else if (verilog) {
result = r1.getElement(type) + "|"
+ r2.getElement(type);
} else {
result = "or(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
} else if (op.equals("!")) {
if (r1 != null && r2 != null) {
if (sbmlFlag) {
result = "BITNOT(" + r1.getElement(type) + ")";
} else if (verilog) {
result = "~" + r1.getElement(type);
} else {
result = "not(" + r1.getElement(type) + ")";
}
}
} else if (op.equals("X")) {
if (r1 != null && r2 != null) {
if (sbmlFlag) {
result = "XOR(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
} else if (verilog) {
result = r1.getElement(type) + "^"
+ r2.getElement(type);
} else {
result = "exor(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
}
break;
case 'a': // Arithmetic
case 'r': // Relational
case 'l': // Logical
if (op.equals("!")) {
if (r1 != null) {
if (r1.isit == 'b' || r1.isit == 'i' || r1.isit == 'c'
|| r1.isit == 'n' || r1.isit == 't') {
if (sbmlFlag) {
result = "not(" + r1.getElement(type) + ")";
} else if (verilog) {
result = "!" + r1.getElement(type);
} else {
result = "~" + r1.getElement(type);
}
} else {
if (sbmlFlag) {
result = "not(" + r1.getElement(type) + ")";
} else if (verilog) {
result = "!" + "(" + r1.getElement(type) + ")";
} else {
result = "~" + "(" + r1.getElement(type) + ")";
}
}
}
break;
}
if (op.equals("&&")) {
if (r1.isit == 'r'
|| (r1.isit == 'l' && r1.op.equals("||"))) {
if (r1 != null) {
if (sbmlFlag) {
result = "and(" + r1.getElement(type) + ",";
} else if (verilog) {
result = "(" + r1.getElement(type) + ")&&";
} else {
result = "(" + r1.getElement(type) + ")";
}
}
} else {
if (r1 != null) {
if (sbmlFlag) {
result = "and(" + r1.getElement(type) + ",";
} else if (verilog) {
result = r1.getElement(type) + "&&";
} else {
result = r1.getElement(type);
}
}
}
if (!sbmlFlag && !verilog) {
result = result + "&";
}
if (r2.isit == 'r'
|| (r2.isit == 'l' && r2.op.equals("||"))) {
if (r2 != null) {
if (sbmlFlag) {
result = result + r2.getElement(type) + ")";
} else {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
} else {
if (r2 != null) {
if (sbmlFlag) {
result = result + r2.getElement(type) + ")";
} else {
result = result + r2.getElement(type);
}
}
}
} else if (op.equals("||")) {
if (r1.isit == 'r') {
if (r1 != null) {
if (sbmlFlag) {
result = "or(" + r1.getElement(type) + ",";
} else if (verilog) {
result = "(" + r1.getElement(type) + ")||";
} else {
result = "(" + r1.getElement(type) + ")";
}
}
} else {
if (r1 != null) {
if (sbmlFlag) {
result = "or(" + r1.getElement(type) + ",";
} else if (verilog) {
result = r1.getElement(type) + "||";
} else {
result = r1.getElement(type);
}
}
}
if (!sbmlFlag && !verilog) {
result = result + "|";
}
if (r2.isit == 'r') {
if (r2 != null) {
if (sbmlFlag) {
result = result + r2.getElement(type) + ")";
} else {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
} else {
if (r2 != null) {
if (sbmlFlag) {
result = result + r2.getElement(type) + ")";
} else {
result = result + r2.getElement(type);
}
}
}
} else if (op.equals("f")) {
if (r1 != null) {
if (r1.isit == 'n') {
result = new Integer((int) Math.floor(r1.lvalue))
.toString();
} else {
if (sbmlFlag) {
result = "floor(" + r1.getElement(type) + ")";
} else if (verilog) {
result = "$floor(" + r1.getElement(type) + ")";
} else {
result = "floor(" + r1.getElement(type) + ")";
}
}
}
} else if (op.equals("c")) {
if (r1 != null) {
if (r1.isit == 'n') {
result = new Integer((int) Math.ceil(r1.lvalue))
.toString();
} else {
if (sbmlFlag) {
result = "ceil(" + r1.getElement(type) + ")";
} else if (verilog) {
result = "$ceil(" + r1.getElement(type) + ")";
} else {
result = "ceil(" + r1.getElement(type) + ")";
}
}
}
} else if (op.equals("m")) {
if (r1 != null && r2 != null) {
if (r1.isit == 'n' && r2.isit == 'n') {
if (r1.lvalue < r2.lvalue) {
result = r1.getElement(type);
} else {
result = r2.getElement(type);
}
} else {
if (sbmlFlag) {
result = "piecewise(" + r1.getElement(type)
+ ",leq(" + r1.getElement(type) + ","
+ r2.getElement(type) + "),"
+ r2.getElement(type) + ")";
//} else if (verilog) {
//result = "min(" + r1.getElement(type) + ","
// + r2.getElement(type) + ")";
} else if (verilog) {
result = "("+r1.getElement(type) +"<"+r2.getElement(type) +"?"+r1.getElement(type) +":"+r2.getElement(type) +")";
} else {
result = "min(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
}
} else if (op.equals("M")) {
if (r1 != null && r2 != null) {
if (r1.isit == 'n' && r2.isit == 'n') {
if (r1.lvalue > r2.lvalue) {
result = r1.getElement(type);
} else {
result = r2.getElement(type);
}
} else {
if (sbmlFlag) {
result = "piecewise(" + r1.getElement(type)
+ ",geq(" + r1.getElement(type) + ","
+ r2.getElement(type) + "),"
+ r2.getElement(type) + ")";
//} else if (verilog) {
//result = "max(" + r1.getElement(type) + ","
//+ r2.getElement(type) + ")";
} else if (verilog) {
result = "("+r1.getElement(type) +">"+r2.getElement(type) +"?"+r1.getElement(type) +":"+r2.getElement(type) +")";
} else {
result = "max(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
}
} else if (op.equals("i")) {
if (r1 != null && r2 != null) {
if (sbmlFlag) {
result = "floor(" + r1.getElement(type) + "/"
+ r2.getElement(type) + ")";
} else if (verilog) {
result = "floor(" + r1.getElement(type) + "/"
+ r2.getElement(type) + ")";
} else {
result = "idiv(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
} else if (op.equals("uniform")) {
if (r1 != null && r2 != null) {
if (verilog) {
result = "uniform(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
} else {
result = "uniform(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
} // TODO: Add verilog functions for other distributions
else if (op.equals("[]")) {
if (r1 != null && r2 != null) {
result = "BIT(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
} else if (op.equals("normal")) {
if (r1 != null && r2 != null) {
result = "normal(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
} else if (op.equals("gamma")) {
if (r1 != null && r2 != null) {
result = "gamma(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
} else if (op.equals("lognormal")) {
if (r1 != null && r2 != null) {
result = "lognormal(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
} else if (op.equals("binomial")) {
if (r1 != null && r2 != null) {
result = "binomial(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
} else if (op.equals("exponential")) {
if (r1 != null) {
result = "exponential(" + r1.getElement(type) + ")";
}
} else if (op.equals("chisq")) {
if (r1 != null) {
result = "chisq(" + r1.getElement(type) + ")";
}
} else if (op.equals("laplace")) {
if (r1 != null) {
result = "laplace(" + r1.getElement(type) + ")";
}
} else if (op.equals("cauchy")) {
if (r1 != null) {
result = "cauchy(" + r1.getElement(type) + ")";
}
} else if (op.equals("rayleigh")) {
if (r1 != null) {
result = "rayleigh(" + r1.getElement(type) + ")";
}
} else if (op.equals("poisson")) {
if (r1 != null) {
result = "poisson(" + r1.getElement(type) + ")";
}
} else if (op.equals("bernoulli")) {
if (r1 != null) {
result = "bernoulli(" + r1.getElement(type) + ")";
}
} else if (op.equals("rate")) {
if (r1 != null) {
result = "rate(" + r1.getElement(type) + ")";
}
} else if (op.equals("INT")) {
if (r1 != null) {
if (sbmlFlag) {
result = "piecewise(1," + r1.getElement(type)
+ ",0 )";
} else {
result = "INT(" + r1.getElement(type) + ")";
}
}
} else if (op.equals("==")) {
if (r1 != null) {
if (sbmlFlag) {
result = "eq(" + r1.getElement(type) + ",";
} else if (verilog) {
result = r1.getElement(type) + "==";
} else {
result = r1.getElement(type);
}
}
if (!sbmlFlag && !verilog) {
result = result + "=";
}
if (r2 != null) {
if (sbmlFlag) {
result = result + r2.getElement(type) + ")";
} else {
result = result + r2.getElement(type);
}
}
} else if (op.equals("+")) {
if (r1.isit == 'n' && r1.lvalue >= 0 && r2.isit == 'a'
&& r2.op.equals("uniform")) {
ExprTree tempUniform = new ExprTree(r2);
r1.setNodeValues(r1, tempUniform.r1, "+", 'a');
r2.setNodeValues(r1, tempUniform.r2, "+", 'a');
isit = 'a';
op = "uniform";
} else if (r1.isit == 'a' && r1.op.equals("uniform")
&& r2.isit == 'n' && r2.lvalue >= 0) {
ExprTree tempUniform = new ExprTree(r1);
r1.setNodeValues(r2, tempUniform.r1, "+", 'a');
r2.setNodeValues(r2, tempUniform.r2, "+", 'a');
isit = 'a';
op = "uniform";
} else {
try {
String r1String = r1.getElement(type);
String r2String = r2.getElement(type);
result = new Float(Float.parseFloat(r1String)
+ Float.parseFloat(r2String)).toString();
} catch (NumberFormatException e) {
if (r1.isit == 'b'
|| r1.isit == 'i'
|| r1.isit == 'c'
|| r1.isit == 'n'
|| r1.isit == 't'
|| (r1.isit == 'a' && (r1.op.equals("+")
|| r1.op.equals("-")
|| r1.op.equals("*")
|| r1.op.equals("/") || r1.op
.equals("^")))) {
if (r1 != null) {
result = r1.getElement(type);
}
} else {
if (r1 != null) {
result = "(" + r1.getElement(type) + ")";
}
}
result = result + "+";
if (r2.isit == 'b'
|| r2.isit == 'i'
|| r2.isit == 'c'
|| r2.isit == 'n'
|| r2.isit == 't'
|| (r2.isit == 'a' && (r2.op.equals("+")
|| r2.op.equals("-")
|| r2.op.equals("*")
|| r2.op.equals("/") || r2.op
.equals("^")))) {
if (r2 != null) {
result = result + r2.getElement(type);
}
} else {
if (r2 != null) {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
}
}
} else if (op.equals("-")) {
if (r1.isit == 'a' && r1.op.equals("uniform")
&& r2.isit == 'n' && r2.lvalue >= 0) {
ExprTree tempUniform = new ExprTree(r1);
r1.setNodeValues(tempUniform.r1, r2, "-", 'a');
r2.setNodeValues(tempUniform.r2, r2, "-", 'a');
isit = 'a';
op = "uniform";
} else {
try {
String r1String = r1.getElement(type);
String r2String = r2.getElement(type);
result = new Float(Float.parseFloat(r1String)
- Float.parseFloat(r2String)).toString();
} catch (NumberFormatException e) {
if (r1.isit == 'b'
|| r1.isit == 'i'
|| r1.isit == 'c'
|| r1.isit == 'n'
|| r1.isit == 't'
|| (r1.isit == 'a' && (r1.op.equals("+")
|| r1.op.equals("-")
|| r1.op.equals("*")
|| r1.op.equals("/") || r1.op
.equals("^")))) {
if (r1 != null) {
result = r1.getElement(type);
}
} else {
if (r1 != null) {
result = "(" + r1.getElement(type) + ")";
}
}
result = result + "-";
if (r2.isit == 'b'
|| r2.isit == 'i'
|| r2.isit == 'c'
|| r2.isit == 'n'
|| r2.isit == 't'
|| (r2.isit == 'a' && (r2.op.equals("-")
|| r2.op.equals("*")
|| r2.op.equals("/") || r2.op
.equals("^")))) {
if (r2 != null) {
result = result + r2.getElement(type);
}
} else {
if (r2 != null) {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
}
}
} else if (op.equals("*")) {
if (r1.isit == 'n' && r1.lvalue >= 0 && r2.isit == 'a'
&& r2.op.equals("uniform")) {
ExprTree tempUniform = new ExprTree(r2);
r1.setNodeValues(r1, tempUniform.r1, "*", 'a');
r2.setNodeValues(r1, tempUniform.r2, "*", 'a');
isit = 'a';
op = "uniform";
} else if (r1.isit == 'a' && r1.op.equals("uniform")
&& r2.isit == 'n' && r2.lvalue >= 0) {
ExprTree tempUniform = new ExprTree(r1);
r1.setNodeValues(r2, tempUniform.r1, "*", 'a');
r2.setNodeValues(r2, tempUniform.r2, "*", 'a');
isit = 'a';
op = "uniform";
} else {
try {
String r1String = r1.getElement(type);
String r2String = r2.getElement(type);
result = new Float(Float.parseFloat(r1String)
* Float.parseFloat(r2String)).toString();
} catch (NumberFormatException e) {
if (r1.isit == 'b'
|| r1.isit == 'i'
|| r1.isit == 'c'
|| r1.isit == 'n'
|| r1.isit == 't'
|| (r1.isit == 'a' && (r1.op.equals("*")
|| r1.op.equals("/") || r1.op
.equals("^")))) {
if (r1 != null) {
result = r1.getElement(type);
}
} else {
if (r1 != null) {
result = "(" + r1.getElement(type) + ")";
}
}
result = result + "*";
if (r2.isit == 'b'
|| r2.isit == 'i'
|| r2.isit == 'c'
|| r2.isit == 'n'
|| r2.isit == 't'
|| (r2.isit == 'a' && (r2.op.equals("*")
|| r2.op.equals("/") || r2.op
.equals("^")))) {
if (r2 != null) {
result = result + r2.getElement(type);
}
} else {
if (r2 != null) {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
}
}
} else if (op.equals("/")) {
if (r1.isit == 'a' && r1.op.equals("uniform")
&& r2.isit == 'n' && r2.lvalue >= 0) {
ExprTree tempUniform = new ExprTree(r1);
r1.setNodeValues(tempUniform.r1, r2, "/", 'a');
r2.setNodeValues(tempUniform.r2, r2, "/", 'a');
isit = 'a';
op = "uniform";
} else {
try {
String r1String = r1.getElement(type);
String r2String = r2.getElement(type);
result = new Float(Float.parseFloat(r1String)
/ Float.parseFloat(r2String)).toString();
} catch (NumberFormatException e) {
if (r1.isit == 'b'
|| r1.isit == 'i'
|| r1.isit == 'c'
|| r1.isit == 'n'
|| r1.isit == 't'
|| (r1.isit == 'a' && (r1.op.equals("*")
|| r1.op.equals("/") || r1.op
.equals("^")))) {
if (r1 != null) {
result = r1.getElement(type);
}
} else {
if (r1 != null) {
result = "(" + r1.getElement(type) + ")";
}
}
result = result + "/";
if (r2.isit == 'b'
|| r2.isit == 'i'
|| r2.isit == 'c'
|| r2.isit == 'n'
|| r2.isit == 't'
|| (r2.isit == 'a' && (r2.op.equals("/") || r2.op
.equals("^")))) {
if (r2 != null) {
result = result + r2.getElement(type);
}
} else {
if (r2 != null) {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
}
}
} else if (op.equals("^")) {
try {
String r1String = r1.getElement(type);
String r2String = r2.getElement(type);
result = new Integer(Integer.parseInt(r1String)
^ Integer.parseInt(r2String)).toString();
} catch (NumberFormatException e) {
if (r1.isit == 'b'
|| r1.isit == 'i'
|| r1.isit == 'c'
|| r1.isit == 'n'
|| r1.isit == 't'
|| (r1.isit == 'a' && (r1.op.equals("*")
|| r1.op.equals("/") || r1.op
.equals("^")))) {
if (r1 != null) {
result = "(" + r1.getElement(type) + ")";
}
} else {
if (r1 != null) {
result = "(" + r1.getElement(type) + ")";
}
}
if (type.equals("prism")) result = "pow(" + result + ",";
else result = result + "^";
if (r2.isit == 'b'
|| r2.isit == 'i'
|| r2.isit == 'c'
|| r2.isit == 'n'
|| r2.isit == 't'
|| (r2.isit == 'a' && (r2.op.equals("/") || r2.op
.equals("^")))) {
if (r2 != null) {
result = result + "(" + r2.getElement(type)
+ ")";
}
} else {
if (r2 != null) {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
if (type.equals("prism")) result = result + ")";
}
}
// relational ops: geq, leq, gt, lt
// mod
else {
if (!sbmlFlag) {
if (r1 != null) {
if (r1.isit == 'b' || r1.isit == 'i'
|| r1.isit == 'c' || r1.isit == 'n'
|| r1.isit == 't') {
result = r1.getElement(type);
} else {
result = "(" + r1.getElement(type) + ")";
}
}
result = result + op;
if (r2 != null) {
if (r2.isit == 'b' || r2.isit == 'i'
|| r2.isit == 'c' || r2.isit == 'n'
|| r2.isit == 't') {
result = result + r2.getElement(type);
} else {
result = result + "(" + r2.getElement(type)
+ ")";
}
}
}
if (sbmlFlag) {
if (op.equals("<=")) {
if (r1 != null && r2 != null) {
result = "leq(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
if (op.equals(">=")) {
if (r1 != null && r2 != null) {
result = "geq(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
if (op.equals(">")) {
if (r1 != null && r2 != null) {
result = "gt(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
if (op.equals("<")) {
if (r1 != null && r2 != null) {
result = "lt(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
if (op.equals("%")) {
if (r1 != null && r2 != null) {
result = "mod(" + r1.getElement(type) + ","
+ r2.getElement(type) + ")";
}
}
}
}
}
return result;
}
public ExprTree minimizeUniforms() {
if (r1 != null) {
r1.minimizeUniforms();
}
if (r2 != null) {
r2.minimizeUniforms();
}
if (isit == 'a' && op.equals("m")) {
if (r1.isit == 'n' && r2.isit == 'n') {
isit = 'n';
if (r1.lvalue < r2.lvalue) {
lvalue = r1.lvalue;
} else {
lvalue = r2.lvalue;
}
r1 = null;
r2 = null;
} else if (r1.isit == 'a' && r1.op.equals("uniform")
&& r2.isit == 'a' && r2.op.equals("uniform")) {
ExprTree l1 = r1.r1;
ExprTree l2 = r2.r1;
ExprTree u1 = r1.r2;
ExprTree u2 = r2.r2;
op = "uniform";
r1.op = "m";
r2.op = "m";
r1.r1 = l1;
r1.r2 = l2;
r2.r1 = u1;
r2.r2 = u2;
}
}
if (isit == 'a' && op.equals("M")) {
if (r1.isit == 'n' && r2.isit == 'n') {
isit = 'n';
if (r1.lvalue < r2.lvalue) {
lvalue = r2.lvalue;
} else {
lvalue = r1.lvalue;
}
r1 = null;
r2 = null;
} else if (r1.isit == 'a' && r1.op.equals("uniform")
&& r2.isit == 'a' && r2.op.equals("uniform")) {
ExprTree l1 = r1.r1;
ExprTree l2 = r2.r1;
ExprTree u1 = r1.r2;
ExprTree u2 = r2.r2;
op = "uniform";
r1.op = "M";
r2.op = "M";
r1.r1 = l1;
r1.r2 = l2;
r2.r1 = u1;
r2.r2 = u2;
}
}
if (isit == 'a' && op.equals("+")) {
if (r1.isit == 'a' && r1.op.equals("uniform") && r2.isit == 'a'
&& r2.op.equals("uniform")) {
ExprTree l1 = r1.r1;
ExprTree l2 = r2.r1;
ExprTree u1 = r1.r2;
ExprTree u2 = r2.r2;
op = "uniform";
r1.op = "+";
r2.op = "+";
r1.r1 = l1;
r1.r2 = l2;
r2.r1 = u1;
r2.r2 = u2;
}
}
if (isit == 'a' && op.equals("-")) {
if (r1.isit == 'a' && r1.op.equals("uniform") && r2.isit == 'a'
&& r2.op.equals("uniform")) {
ExprTree l1 = r1.r1;
ExprTree l2 = r2.r1;
ExprTree u1 = r1.r2;
ExprTree u2 = r2.r2;
op = "uniform";
r1.op = "+";
r2.op = "+";
r1.r1 = l1;
r1.r2 = u2;
r2.r1 = u1;
r2.r2 = l2;
}
}
if (isit == 'a' && op.equals("c")) {
if (r1.isit == 'a' && r1.op.equals("uniform")) {
ExprTree l1 = r1.r1;
ExprTree u1 = r1.r2;
op = "uniform";
r1 = new ExprTree(l1, null, "c", 'a');
r2 = new ExprTree(u1, null, "c", 'a');
}
}
if (isit == 'a' && op.equals("f")) {
if (r1.isit == 'a' && r1.op.equals("uniform")) {
ExprTree l1 = r1.r1;
ExprTree u1 = r1.r2;
op = "uniform";
r1 = new ExprTree(l1, null, "f", 'a');
r2 = new ExprTree(u1, null, "f", 'a');
}
}
if (isit == 'a' && op.equals("uniform")) {
if (r1.isit == 'a' && r1.op.equals("uniform")) {
r1 = r1.r1;
}
if (r2.isit == 'a' && r2.op.equals("uniform")) {
r2 = r2.r2;
}
}
return this;
}
public boolean isEqual(ExprTree expr) {
if (isit == expr.isit) {
boolean same = false;
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
if (variable.equals(expr.variable)) {
same = true;
}
break;
case 'n': // Number
case 't': // Truth value
if (uvalue == expr.uvalue && lvalue == expr.lvalue) {
same = true;
}
break;
case 'w': // bitWise
case 'a': // Arithmetic
case 'r': // Relational
case 'l': // Logical
if (op.equals(expr.op)) {
same = true;
}
}
if (same) {
boolean r1Same = false, r2Same = false;
if (r1 == null) {
if (expr.r1 == null) {
r1Same = true;
}
} else if (r1.isEqual(expr.r1)) {
r1Same = true;
}
if (r2 == null) {
if (expr.r2 == null) {
r2Same = true;
}
} else if (r2.isEqual(expr.r2)) {
r2Same = true;
}
if (r1Same && r2Same) {
return true;
}
}
}
return false;
}
private boolean isEqual(ExprTree expr, HashMap<String, String> variables) {
if (isit == expr.isit) {
boolean same = false;
switch (isit) {
case 'b': // Boolean
case 'i': // Integer
case 'c': // Continuous
if (variables.containsKey(variable)) {
if (variables.containsKey(expr.variable)) {
if (variables.get(variable).equals(
variables.get(expr.variable)))
same = true;
}
} else if (variable.equals(expr.variable)) {
same = true;
}
break;
case 'n': // Number
case 't': // Truth value
if (uvalue == expr.uvalue && lvalue == expr.lvalue) {
same = true;
} else if (variables.containsKey(expr.variable)) {
if (uvalue == lvalue) {
if (uvalue == 1.0
&& variables.get(expr.variable).toLowerCase()
.equals("true"))
same = true;
else if (uvalue == 0.0
&& variables.get(expr.variable).toLowerCase()
.equals("false"))
same = true;
}
}
break;
case 'w': // bitWise
case 'a': // Arithmetic
case 'r': // Relational
case 'l': // Logical
if (op.equals(expr.op)) {
same = true;
}
}
if (same) {
boolean r1Same = false, r2Same = false;
if (r1 == null) {
if (expr.r1 == null) {
r1Same = true;
}
} else if (r1.isEqual(expr.r1)) {
r1Same = true;
}
if (r2 == null) {
if (expr.r2 == null) {
r2Same = true;
}
} else if (r2.isEqual(expr.r2)) {
r2Same = true;
}
if (r1Same && r2Same) {
return true;
}
}
}
return false;
}
private void setVarValues(char willbe, double lNV, double uNV, String var) {
op = "";
r1 = null;
r2 = null;
isit = willbe;
if ((isit == 'b') || (isit == 't'))
logical = true;
else
logical = false;
uvalue = uNV;
lvalue = lNV;
variable = var;
real = 0;
}
public void setNodeValues(ExprTree nr1, ExprTree nr2, String nop,
char willbe) {
ExprTree r1temp = null, r2temp = null;
if (nr1 != null) {
r1temp = new ExprTree(nr1);
}
if (nr2 != null) {
r2temp = new ExprTree(nr2);
}
r1 = r1temp;
r2 = r2temp;
op = nop;
isit = willbe;
if ((isit == 'r') || (isit == 'l')) {
logical = true;
uvalue = 1;
lvalue = 0;
} else {
logical = false;
uvalue = INFIN;
lvalue = -INFIN;
}
variable = null;
// simplify if operands are static
if (isit == 'a' || isit == 'r' || isit == 'l' || isit == 'w') {
if (op.equals("&&")) {
if ((r1.isit == 'n') || (r1.isit == 't')) {
if (r1.lvalue == 0) {
setVarValues('t', 0.0, 0.0, null);
} else {
if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w'
|| r2.isit == 'r') {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
} else {
setVarValues(r2.isit, r2.lvalue, r2.uvalue,
r2.variable);
}
}
} else if (((r2).isit == 'n') || ((r2).isit == 't')) {
if (r2.lvalue == 0) {
setVarValues('t', 0.0, 0.0, null);
} else {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue,
r1.variable);
}
}
} else if (r1.equals(r2)) {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable);
}
} else {
ExprTree notE = new ExprTree(this);
notE.setNodeValues((this), null, "!", 'l');
if (r1.equals(notE) || notE.equals(r1)) {
setVarValues('t', 0.0, 0.0, null);
}
}
} else if (op.equals("||")) {
if ((r1.isit == 'n') || (r1.isit == 't')) {
if (r1.lvalue != 0) {
setVarValues('t', 1.0, 1.0, null);
} else {
if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w'
|| r2.isit == 'r') {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
} else {
setVarValues(r2.isit, r2.lvalue, r2.uvalue,
r2.variable);
}
}
} else if (((r2).isit == 'n') || ((r2).isit == 't')) {
if (r2.lvalue != 0) {
setVarValues('t', 1.0, 1.0, null);
} else {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue,
r1.variable);
}
}
} else if (r1.equals(r2)) {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable);
}
} else {
ExprTree notE = new ExprTree(this);
notE.setNodeValues((this), null, "!", 'l');
if (r1.equals(notE) || notE.equals(r1)) {
setVarValues('t', 1.0, 1.0, null);
}
}
} else if (op.equals("->")) {
if (r1.isit == 'n' || r1.isit == 't') {
if (r1.lvalue != 0) {
if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w'
|| r2.isit == 'r') {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
} else {
setVarValues(r2.isit, r2.lvalue, r2.uvalue,
r2.variable);
}
} else if (r1.uvalue == 0) {
setVarValues('t', 1.0, 1.0, null);
}
} else if (r2.isit == 't' || r2.isit == 'n') {
if (r2.lvalue != 0) {
setVarValues('t', 1.0, 1.0, null);
} else if (r2.uvalue == 0) {
ExprTree notE = new ExprTree(r2);
notE.setNodeValues((this), null, "!", 'l');
setNodeValues(notE.r1, notE.r2, notE.op, notE.isit);
}
}
} else if (op.equals("!")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 't';
if (r1.lvalue == 1) {
this.lvalue = 0;
} else {
this.lvalue = 1;
}
(this).uvalue = (this).lvalue;
}
} else if (op.equals("==")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if (r1.lvalue == r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
}
} else if (op.equals(">=")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue >= r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
}
} else if (op.equals(">")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue > r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
}
} else if (op.equals("<=")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue <= r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
}
} else if (op.equals("<")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
if ((r1).lvalue < r2.lvalue) {
this.lvalue = 1;
} else {
this.lvalue = 0;
}
(this).uvalue = (this).lvalue;
}
} else if (op.equals("&")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = ((int) (r1).lvalue) & ((int) r2.lvalue);
(this).uvalue = (this).lvalue;
}
} else if (op.equals("|")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (int) (r1).lvalue | (int) r2.lvalue;
(this).uvalue = (this).lvalue;
}
} else if (isit == 'w' && op.equals("X")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (int) (r1).lvalue ^ (int) r2.lvalue;
(this).uvalue = (this).lvalue;
}
} else if (op.equals("m")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = Math.min((r1).lvalue, r2.lvalue);
(this).uvalue = (this).lvalue;
}
} else if (op.equals("M")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = Math.max((r1).lvalue, r2.lvalue);
(this).uvalue = (this).lvalue;
}
} else if (op.equals("i")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = Math.floor((r1).lvalue / r2.lvalue);
(this).uvalue = (this).lvalue;
}
} else if (op.equals("f")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = Math.floor((r1).lvalue);
(this).uvalue = (this).lvalue;
}
} else if (op.equals("c")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = Math.ceil((r1).lvalue);
(this).uvalue = (this).lvalue;
}
} else if (op.equals("~")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = ~(int) (r1).lvalue;
(this).uvalue = (this).lvalue;
}
} else if (op.equals("[]")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 't';
(this).lvalue = (((int) (r1).lvalue) >> ((int) r2.lvalue)) & 1;
(this).uvalue = (this).lvalue;
}
} else if (op.equals("U-")) {
if (((r1).isit == 'n') || ((r1).isit == 't')) {
(this).isit = 'n';
(this).lvalue = -((r1).lvalue);
(this).uvalue = (this).lvalue;
}
} else if (op.equals("*")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue * r2.lvalue;
(this).uvalue = (this).lvalue;
} else if (r1.isit == 'n' || r1.isit == 't') {
if (r1.lvalue == 0 && r1.uvalue == 0) {
setVarValues('t', 0.0, 0.0, null);
} else if (r1.lvalue == 1 && r1.uvalue == 1) {
if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w'
|| r2.isit == 'r') {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
} else {
setVarValues(r2.isit, r2.lvalue, r2.uvalue,
r2.variable);
}
}
} else if (r2.isit == 'n' || r2.isit == 't') {
if (r2.lvalue == 0 && r2.uvalue == 0) {
setVarValues('t', 0.0, 0.0, null);
} else if (r2.lvalue == 1 && r2.uvalue == 1) {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue,
r1.variable);
}
}
}
} else if (op.equals("/")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue / r2.lvalue;
(this).uvalue = (this).lvalue;
} else if ((r1.isit == 'n' || r1.isit == 't') && r1.uvalue == 0
&& r1.lvalue == 0) {
setVarValues('n', 0.0, 0.0, null);
} else if ((r2.isit == 'n' || r2.isit == 't') && r2.lvalue == 1
&& r2.uvalue == 1) {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable);
}
}
} else if (op.equals("%")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue % r2.lvalue;
(this).uvalue = (this).lvalue;
} else if ((r2.isit == 'n' || r2.isit == 't')
&& r2.lvalue == 1.0 && r2.uvalue == 1.0) {
setVarValues('n', 0.0, 0.0, null);
} else if ((r1.isit == 'n' || r1.isit == 't')
&& r1.lvalue == 1.0 && r1.uvalue == 1.0) {
setVarValues('n', 1.0, 1.0, null);
}
} else if (op.equals("+")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue + r2.lvalue;
(this).uvalue = (this).lvalue;
} else if ((r1.isit == 'n' || r1.isit == 't') && r1.lvalue == 0
&& r1.uvalue == 0) {
if (r2.isit == 'l' || r2.isit == 'a' || r2.isit == 'w'
|| r2.isit == 'r') {
setNodeValues(r2.r1, r2.r2, r2.op, r2.isit);
} else {
setVarValues(r2.isit, r2.lvalue, r2.uvalue, r2.variable);
}
} else if ((r2.isit == 'n' || r2.isit == 't') && r2.lvalue == 0
&& r2.uvalue == 0) {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable);
}
}
} else if (op.equals("-")) {
if (((r1.isit == 'n') || (r1.isit == 't'))
&& (((r2).isit == 'n') || ((r2).isit == 't'))) {
(this).isit = 'n';
(this).lvalue = (r1).lvalue - r2.lvalue;
(this).uvalue = (this).lvalue;
} else if ((r1.isit == 'n' || r1.isit == 't') && r1.lvalue == 0
&& r1.uvalue == 0) {
setNodeValues(r2, null, "U-", 'a');
} else if ((r2.isit == 'n' || r2.isit == 't') && r2.lvalue == 0
&& r2.uvalue == 0) {
if (r1.isit == 'l' || r1.isit == 'a' || r1.isit == 'w'
|| r1.isit == 'r') {
setNodeValues(r1.r1, r1.r2, r1.op, r1.isit);
} else {
setVarValues(r1.isit, r1.lvalue, r1.uvalue, r1.variable);
}
}
}
}
}
public double evaluateExpr(HashMap<String, String> variables) {
double left;
double right;
switch (isit) {
case 'b': // Boolean
if (variables != null) {
if (!variables.containsKey(variable)
|| variables.get(variable).toLowerCase().equals(
"unknown"))
return Double.NaN;
if (variables.get(variable).toLowerCase().equals("true") ||
variables.get(variable).equals("1")) {
return 1.0;
}
return 0.0;
}
return Double.NaN;
case 'c': // Continuous
return Double.NaN;
case 'i': // Integer
if (variables != null) {
try {
return Double.parseDouble(variables.get(variable));
} catch (Exception e) {
return Double.NaN;
}
}
return Double.NaN;
case 'n': // Number
if (uvalue == lvalue) {
return uvalue;
}
return ((uvalue - lvalue) * new java.util.Random().nextDouble())
+ lvalue;
case 't': // Truth value
if (uvalue == 1 && lvalue == 1) {
return 1.0;
} else if (uvalue == 0 && lvalue == 0) {
return 0.0;
} else {
return Double.NaN;
}
case 'w': // bitWise
if (r1 != null) {
left = r1.evaluateExpr(variables);
} else {
left = Double.NaN;
}
if (r2 != null) {
right = r2.evaluateExpr(variables);
} else {
right = Double.NaN;
}
if (op.equals("&")) {
return ((int) left) & ((int) right);
} else if (op.equals("|")) {
return ((int) left) | ((int) right);
} else if (op.equals("!")) {
return ~((int) left);
} else if (op.equals("X")) {
return ((int) left) ^ ((int) right);
}
break;
case 'a': // Arithmetic
case 'r': // Relational
case 'l': // Logical
if (op.equals("!")) {
if (r1 != null) {
if (r1.evaluateExpr(variables) == 1.0) {
return 0.0;
} else if (r1.evaluateExpr(variables) == 0.0) {
return 1.0;
} else {
return Double.NaN;
}
} else if (r2 != null) {
if (r2.evaluateExpr(variables) == 1.0) {
return 0.0;
} else if (r2.evaluateExpr(variables) == 0.0) {
return 1.0;
} else {
return Double.NaN;
}
} else {
return Double.NaN;
}
}
if (r1 != null) {
left = r1.evaluateExpr(variables);
} else {
left = Double.NaN;
}
if (r2 != null) {
right = r2.evaluateExpr(variables);
} else {
right = Double.NaN;
}
if (op.equals("&&")) {
if (left == 1.0 && right == 1.0) {
return 1.0;
} else if (left == 0.0 || right == 0.0) {
return 0.0;
} else
return Double.NaN;
} else if (op.equals("||")) {
if (left == 1.0 || right == 1.0) {
return 1.0;
} else if (left == 0.0 && right == 0.0) {
return 0.0;
} else
return Double.NaN;
} else if (op.equals("==")) {
if (left == Double.NaN || right == Double.NaN) {
return Double.NaN;
} else if (left == right) {
return 1.0;
} else if (left != right) {
return 0.0;
} else {
return Double.NaN;
}
} else if (op.equals("->")) {
if (left == 0.0 && (right == 1.0 || right == 0.0)) {
return 1.0;
} else if (left == 1.0 && right == 1.0) {
return 1.0;
} else if (left == 1.0 && right == 0.0) {
return 0.0;
} else {
return Double.NaN;
}
} else if (op.equals("+")) {
return left + right;
} else if (op.equals("-")) {
return left - right;
} else if (op.equals("*")) {
return left * right;
} else if (op.equals("/")) {
return left / right;
} else if (op.equals("%")) {
return left % right;
} else if (op.equals("^")) {
return Math.pow(left, right);
} else if (op.equals("[]")) {
return (((int) left) >> ((int) right)) & 1;
} else if (op.equals("f")) {
return Math.floor(left);
} else if (op.equals("c")) {
return Math.ceil(left);
} else if (op.equals("m")) {
return Math.min(left, right);
} else if (op.equals("M")) {
return Math.max(left, right);
} else if (op.equals("i")) {
return ((int) left) / ((int) right);
} else if (op.equals("uniform")) {
return Double.NaN;
} else if (op.equals("normal")) {
return Double.NaN;
} else if (op.equals("gamma")) {
return Double.NaN;
} else if (op.equals("lognormal")) {
return Double.NaN;
} else if (op.equals("binomial")) {
return Double.NaN;
} else if (op.equals("exponential")) {
return Double.NaN;
} else if (op.equals("chisq")) {
return Double.NaN;
} else if (op.equals("laplace")) {
return Double.NaN;
} else if (op.equals("cauchy")) {
return Double.NaN;
} else if (op.equals("rayleigh")) {
return Double.NaN;
} else if (op.equals("poisson")) {
return Double.NaN;
} else if (op.equals("bernoulli")) {
return Double.NaN;
} else if (op.equals("rate")) {
return Double.parseDouble(variables.get(r1.variable+"_" + GlobalConstants.RATE));
} else if (op.equals("INT")) {
return ((int) left);
} else if (op.equals("<")) {
if (left < right) {
return 1.0;
} else if (left >= right) {
return 0.0;
} else {
return Double.NaN;
}
} else if (op.equals(">")) {
if (left > right) {
return 1.0;
} else if (left <= right) {
return 0.0;
} else {
return Double.NaN;
}
} else if (op.equals("<=")) {
if (left <= right) {
return 1.0;
} else if (left > right) {
return 0.0;
} else {
return Double.NaN;
}
} else if (op.equals(">=")) {
if (left >= right) {
return 1.0;
} else if (left < right) {
return 0.0;
} else {
return Double.NaN;
}
} else {
return Double.NaN;
}
}
return Double.NaN;
}
private static final int WORD = 1;
private static final int IMPLIES = 7;
private static final int END_OF_STRING = 2;
private static final int INFIN = 2147483647;
public String getOp()
{
return op;
}
public ExprTree getLeftChild()
{
return r1;
}
public ExprTree getRightChild()
{
return r2;
}
@Override
public ExprTree clone(){
ExprTree ET = new ExprTree(); // ET phone home.
ET.op = op;
ET.isit = isit;
ET.lvalue = lvalue;
ET.uvalue = uvalue;
ET.variable = variable;
ET.real = real;
ET.logical = logical;
ET.r1 = r1 != null ? r1.clone() : null;
ET.r2 = r2 != null ? r2.clone() : null;
ET.tokvalue = tokvalue;
ET.position = position;
ET.token = token;
ET.newresult = newresult != null ? newresult.clone() : null;
//private ArrayList<String> booleanSignals, integerSignals, continuousSignals;
ET.booleanSignals = (ArrayList<String>) booleanSignals.clone();
ET.integerSignals = (ArrayList<String>) integerSignals.clone();
ET.continuousSignals = continuousSignals;
ET.lhpn = lhpn;
ET.expression = expression;
return ET;
}
/*
* Performs the same operation as this.clone except it does not copy the parsing information.
*/
public ExprTree shallowclone(){
ExprTree ET = new ExprTree(); // ET phone home.
ET.op = op;
ET.isit = isit;
ET.lvalue = lvalue;
ET.uvalue = uvalue;
ET.variable = variable;
ET.real = real;
ET.logical = logical;
ET.r1 = r1 != null ? r1.shallowclone() : null;
ET.r2 = r2 != null ? r2.shallowclone() : null;
//private ArrayList<String> booleanSignals, integerSignals, continuousSignals;
ET.booleanSignals = (ArrayList<String>) booleanSignals.clone();
ET.integerSignals = (ArrayList<String>) integerSignals.clone();
ET.continuousSignals = continuousSignals;
ET.lhpn = lhpn;
ET.expression = expression;
return ET;
}
public ExprTree getExprTree() {
token = this.intexpr_gettok(expression);
this.intexpr_L(expression);
return this;
}
public void setIntegerSignals(Set<String> signalSet) {
for (String s : signalSet) {
integerSignals.add(s);
}
}
/**
* Evaluates an expression tree involving ranges.
* Note: if no continuous variables are present, both z and continuousValues can be null.
* If continuous variables are present, then at least one must be non-null. Finally, if
* z is non-null, then the values will be taken from z and continuousValues will not be consulted.
* @param variables
* The values of the variables.
* @param z
* The zone containing the continuous variables.
* @param continuousValues
* The continuous variables along with their values.
* @return
* The range of values for the expression tree.
*/
public IntervalPair evaluateExprBound(HashMap<String, String> variables, Equivalence z,
// HashMap<LPNContinuousPair, IntervalPair> continuousValues){
HashMap<LPNContAndRate, IntervalPair> continuousValues){
/*
* The code for this method was modified from atacs/src/lhpnrsg.c.
*/
// void exprsn::eval(lhpnStateADT cur_state,int nevents){
// char log_val;
// int tl1,tl2,tu1,tu2,i,j,k;
// int preciser = 1;
//
int lBound, uBound;
// If lBound and uBound are never set, then return "don't know".
lBound = -INFIN;
uBound = INFIN;
IntervalPair r1Range,r2Range = null;
if(!op.equals("")){
// if (op!=""){
// //printf("%s, eval left child\n",op.c_str());
// r1->eval(cur_state,nevents);
// if ((r1->lvalue == -INFIN)||(r1->uvalue == INFIN)){
// lvalue = -INFIN;
// uvalue = INFIN;
// return;
// }
r1Range = r1.evaluateExprBound(variables, z, continuousValues);
if ((r1Range.get_LowerBound() == -INFIN) || (r1Range.get_UpperBound() == INFIN)){
return new IntervalPair(-INFIN, INFIN);
}
// if (r2){
// //printf("eval right child\n");
// r2->eval(cur_state,nevents);
// if ((r2->lvalue == -INFIN)||(r2->uvalue == INFIN)){
// lvalue = -INFIN;
// uvalue = INFIN;
// return;
// }
// }
if(r2 != null){
r2Range = r2.evaluateExprBound(variables, z, continuousValues);
if ((r2Range.get_LowerBound() == - INFIN) || (r1Range.get_UpperBound() == INFIN)){
return new IntervalPair(-INFIN, INFIN);
}
} else {
r2Range = new IntervalPair(-INFIN, INFIN);
}
// if (op=="||"){
// // logical OR
// if (r1->logical){
// tl1 = r1->lvalue;
// tu1 = r1->uvalue;
// }
if( op.equals("||")){
Boolean tl1, tu1, tl2, tu2;
// logical OR
if(r1.logical){
tl1 = r1Range.get_LowerBound() != 0; // false if value is zero and true otherwise
tu1 = r1Range.get_UpperBound() != 0; // false if value is zero and true otherwise
}
else{ // convert numeric r1 to boolean
// else{//convert numeric r1 to boolean
// if ((r1->lvalue == 0)&&(r1->uvalue == 0)){//false
// tl1 = tu1 = 0;
// }
if((r1Range.get_LowerBound() == 0) && (r1Range.get_UpperBound() == 0)){ // false
tl1 = tu1 = false;
}
// else if ((r1->lvalue < 0)&&(r1->uvalue < 0)||
// (r1->lvalue > 0)&&(r1->uvalue > 0)){//true
// tl1 = tu1 = 1;
// }
else if (((r1Range.get_LowerBound() < 0) && (r1Range.get_UpperBound() < 0)) ||
((r1Range.get_LowerBound() > 0) && (r1Range.get_UpperBound() > 0))){ // true
tl1 = tu1 = true;
}
// else{
// tl1 = 0;
// tu1 = 1;
// }
// }
else{
tl1 = false;
tu1 = true;
}
}
// if (r2->logical){
// tl2 = r2->lvalue;
// tu2 = r2->uvalue;
// }
if(r2.logical){ // Note : r2Range can only be set if r2 was non-null.
tl2 = r2Range.get_LowerBound() != 0; // False if value is zero and true otherwise.
tu2 = r2Range.get_UpperBound() != 0; // False if value is zero and true otherwise.
}
else{// convert numeric r2 to boolean
// else{//convert numeric r2 to boolean
// if ((r2->lvalue == 0)&&(r2->uvalue == 0)){//false
// tl2 = tu2 = 0;
// }
if((r2Range.get_LowerBound() == 0) && (r2Range.get_UpperBound() == 0)){// false
tl2 = tu2 = false;
}
// else if ((r2->lvalue < 0)&&(r2->uvalue < 0)||
// (r2->lvalue > 0)&&(r2->uvalue > 0)){//true
// tl2 = tu2 = 1;
// }
else if (((r2Range.get_LowerBound() < 0) && (r2Range.get_UpperBound() < 0)) ||
((r2Range.get_LowerBound() > 0) && (r2Range.get_UpperBound() > 0))){ // true
tl2 = tu2 = true;
}
// else{
// tl2 = 0;
// tu2 = 1;
// }
// }
else{
tl2 = false;
tu2 = true;
}
}
// lvalue = tl1 || tl2;
// uvalue = tu1 || tu2;
// lBound = tl1 || lt2;
// uBound = tu1 || tu2;
lBound = (tl1 || tl2) ? 1 : 0; // Poor man casting from boolean to int.
uBound = (tu1 || tu2) ? 1 : 0;
}
// }else if(op=="&&"){
// // logical AND
else if (op.equals("&&")){ // logical AND
Boolean tl1, tu1, tl2, tu2;
// if (r1->logical){
// tl1 = r1->lvalue;
// tu1 = r1->uvalue;
// }
if(r1.logical){
tl1 = r1Range.get_LowerBound() != 0; // false if value is zero and true otherwise
tu1 = r1Range.get_UpperBound() != 0; // false if value is zero and true otherwise
}
// else{//convert numeric r1 to boolean
// if ((r1->lvalue == 0)&&(r1->uvalue == 0)){//false
// tl1 = tu1 = 0;
// }
else{ // convert number r1 to boolean
if((r1Range.get_LowerBound() == 0) && (r1Range.get_UpperBound() == 0)){ // false
tl1 = tu1 = false;
}
// else if ((r1->lvalue < 0)&&(r1->uvalue < 0)||
// (r1->lvalue > 0)&&(r1->uvalue > 0)){//true
// tl1 = tu1 = 1;
// }
else if (((r1Range.get_LowerBound() < 0) && (r1Range.get_UpperBound() < 0)) ||
((r1Range.get_LowerBound() > 0) && (r1Range.get_UpperBound() > 0))){ // true
tl1 = tu1 = true;
}
// else{
// tl1 = 0;
// tu1 = 1;
// }
// }
else{
tl1 = false;
tu1 = true;
}
}
// if (r2->logical){
// tl2 = r2->lvalue;
// tu2 = r2->uvalue;
// }
// else{//convert numeric r2 to boolean
if(r2.logical){ // Note : r2Range can only be set if r2 was non-null.
tl2 = r2Range.get_LowerBound() != 0; // False if value is zero and true otherwise.
tu2 = r2Range.get_UpperBound() != 0; // False if value is zero and true otherwise.
}
else{// convert numeric r2 to boolean
// if ((r2->lvalue == 0)&&(r2->uvalue == 0)){//false
// tl2 = tu2 = 0;
// }
if((r2Range.get_LowerBound() == 0) && (r2Range.get_UpperBound() == 0)){// false
tl2 = tu2 = false;
}
// else if ((r2->lvalue < 0)&&(r2->uvalue < 0)||
// (r2->lvalue > 0)&&(r2->uvalue > 0)){//true
// tl2 = tu2 = 1;
// }
else if (((r2Range.get_LowerBound() < 0) && (r2Range.get_UpperBound() < 0)) ||
((r2Range.get_LowerBound() > 0) && (r2Range.get_UpperBound() > 0))){ // true
tl2 = tu2 = true;
}
// else{
// tl2 = 0;
// tu2 = 1;
// }
// }
else{
tl2 = false;
tu2 = true;
}
}
// lvalue = tl1 && tl2;
// uvalue = tu1 && tu2;
lBound = (tl1 && tl2) ? 1 : 0; // Poor man casting from boolean to int.
uBound = (tu1 && tu2) ? 1 : 0; // Or clever way; depends on how you look at it.
// #ifdef __LHPN_EVAL__
// printf("and: [%d,%d](%c)&[%d,%d](%c) = [%d,%d]\n",r1->lvalue,
// r1->uvalue,r1->isit,r2->lvalue,r2->uvalue,r2->isit,lvalue,uvalue);
// #endif
}
// }else if(op=="->"){
// // implication operator
else if(op.equals("->")){ // Implication operator.
Boolean tl1, tu1, tl2, tu2;
// if (r1->logical){
// tl1 = r1->lvalue;
// tu1 = r1->uvalue;
// }
// else{//convert numeric r1 to boolean
// if ((r1->lvalue == 0)&&(r1->uvalue == 0)){//false
// tl1 = tu1 = 0;
// }
// else if ((r1->lvalue < 0)&&(r1->uvalue < 0)||
// (r1->lvalue > 0)&&(r1->uvalue > 0)){//true
// tl1 = tu1 = 1;
// }
// else{
// tl1 = 0;
// tu1 = 1;
// }
// }
BooleanPair lowerBounds = logicalConversion(r1, r1Range);
tl1 = lowerBounds.get_lower();
tu1 = lowerBounds.get_upper();
// if (r2->logical){
// tl2 = r2->lvalue;
// tu2 = r2->uvalue;
// }
// else{//convert numeric r2 to boolean
// if ((r2->lvalue == 0)&&(r2->uvalue == 0)){//false
// tl2 = tu2 = 0;
// }
// else if ((r2->lvalue < 0)&&(r2->uvalue < 0)||
// (r2->lvalue > 0)&&(r2->uvalue > 0)){//true
// tl2 = tu2 = 1;
// }
// else{
// tl2 = 0;
// tu2 = 1;
// }
// }
// lvalue = tl1 || !tl2;
// uvalue = tu1 || !tu2;
BooleanPair upperBounds = logicalConversion(r2, r2Range);
tl2 = upperBounds.get_lower();
tu2 = upperBounds.get_upper();
lBound = (tl1 || !tl2) ? 1 : 0; // Poor man casting from boolean to int.
uBound = (tu1 || !tu2) ? 1 : 0; // Or clever way; depends on how you look at it.
}
// }else if(op=="!"){
// // logical NOT
else if(op.equals("!")){
Boolean tl1, tu1;
BooleanPair bounds = logicalConversion(r1, r1Range);
tl1 = bounds.get_lower();
tu1 = bounds.get_upper();
// if (r1->logical){
// tl1 = r1->lvalue;
// tu1 = r1->uvalue;
// }
// else{//convert numeric r1 to boolean
// if ((r1->lvalue == 0)&&(r1->uvalue == 0)){//false
// tl1 = tu1 = 0;
// }
// else if ((r1->lvalue < 0)&&(r1->uvalue < 0)||
// (r1->lvalue > 0)&&(r1->uvalue > 0)){//true
// tl1 = tu1 = 1;
// }
// else{
// tl1 = 0;
// tu1 = 1;
// }
// }
// if (tl1 == tu1){
// lvalue = 1- tl1;
// uvalue = 1- tl1;
// }
if(tl1 == tu1){
lBound = !tl1 ? 1 : 0;
uBound = !tl1 ? 1 : 0;
}
// #ifdef __LHPN_EVAL__
// printf("not: [%d,%d](%c) = [%d,%d]\n",r1->lvalue,
// r1->uvalue,r1->isit,lvalue,uvalue);
// #endif
// //printf("negation: ~[%d,%d] = [%d,%d]\n",r1->lvalue,r1->uvalue,
// // lvalue,uvalue);
}
// }else if(op=="=="){
// // "equality" operator
else if (op.equals("==")){ //"equality" operator.
// // true if same point value
// if ((r1->lvalue == r1->uvalue) && (r2->lvalue == r2->uvalue) &&
// (r1->lvalue == r2->uvalue))
// lvalue = uvalue = 1;
// true if same point value.
if((r1Range.get_LowerBound() == r1Range.get_UpperBound()) &&
(r2Range.get_LowerBound() == r2Range.get_UpperBound()) &&
(r1Range.get_LowerBound() == r2Range.get_UpperBound())){
lBound = uBound = 1;
}
// // false if no overlap
// else if ((r1->lvalue > r2->uvalue)||(r2->lvalue > r1->uvalue))
// lvalue = uvalue = 0;
// false if no overlap
else if ((r1Range.get_LowerBound() > r2Range.get_UpperBound()) ||
(r2Range.get_LowerBound() > r1Range.get_UpperBound())){
lBound = uBound = 0;
}
// // maybe if overlap
// else{
// lvalue = 0;
// uvalue = 1;
// }
// maybe if overlap
else{
lBound = 0;
uBound = 1;
}
// #ifdef __LHPN_EVAL__
// printf("[%d,%d]==[%d,%d]=[%d,%d]\n",r1->lvalue,r1->uvalue ,r2->lvalue,r2->uvalue,lvalue,uvalue);
// #endif
}
else if(op.equals(">")){// "greater than" operator
// }else if(op==">"){
// // "greater than" operator
// //true if lower1 > upper2
// if (r1->lvalue > r2->uvalue)
// lvalue = uvalue = 1;
// true if lower1 > upper2
if( r1Range.get_LowerBound() > r2Range.get_UpperBound()){
lBound = uBound = 1;
}
// //false if lower2 >= upper1
// else if (r2->lvalue >= r1->uvalue)
// lvalue = uvalue = 0;
// false if lower 2 >= upper1
else if (r2Range.get_LowerBound() >= r1Range.get_UpperBound()){
lBound = uBound = 0;
}
// // maybe if overlap
// else{
// lvalue = 0;
// uvalue = 1;
// }
// maybe, if overlap
else {
lBound = 0;
uBound = 1;
}
}
// }else if(op==">="){
// // "greater than or equal" operator
else if (op.equals(">=")){
// //true if lower1 >= upper2
// if (r1->lvalue >= r2->uvalue)
// lvalue = uvalue = 1;
// true if lower1 >= upper2
if(r1Range.get_LowerBound() >= r2Range.get_UpperBound()){
lBound = uBound = 1;
}
// //false if lower2 > upper1
// else if (r2->lvalue > r1->uvalue)
// lvalue = uvalue = 0;
// false if lower2 > upper1
else if (r2Range.get_LowerBound() > r1Range.get_UpperBound()){
lBound = uBound = 0;
}
// // maybe if overlap
// else{
// lvalue = 0;
// uvalue = 1;
// }
// maybe if overlap
else {
lBound = 0;
uBound = 1;
}
}
// }else if(op=="<"){
// // "less than" operator
else if (op.equals("<")){// "less than" operator.
// //true if lower2 > upper1
// if (r2->lvalue > r1->uvalue)
// lvalue = uvalue = 1;
// true if lower2 > upper1
if(r2Range.get_LowerBound() > r1Range.get_UpperBound()){
lBound = uBound = 1;
}
// //false if lower1 >= upper2
// else if (r1->lvalue >= r2->uvalue)
// lvalue = uvalue = 0;
// false if lower1 >= upper2
else if (r1Range.get_LowerBound() >= r2Range.get_UpperBound()){
lBound = uBound = 0;
}
// // maybe if overlap
// else{
// lvalue = 0;
// uvalue = 1;
// }
// maybe if overlap
else{
lBound = 0;
uBound = 1;
}
}
// }else if(op=="<="){
// // "less than or equal" operator
else if (op.equals("<=")){// "less than or equal" operator
// //true if lower2 >= upper1
// if (r2->lvalue >= r1->uvalue)
// lvalue = uvalue = 1;
// true if lower2 >= upper1
if(r2Range.get_LowerBound() >= r1Range.get_UpperBound()){
lBound = uBound = 1;
}
// //false if lower1 > upper2
// else if (r1->lvalue > r2->uvalue)
// lvalue = uvalue = 0;
// false if lower1 > upper2
else if (r1Range.get_LowerBound() > r2Range.get_UpperBound()){
lBound = uBound =0;
}
// // maybe if overlap
// else{
// lvalue = 0;
// uvalue = 1;
// }
// maybe if overlap
else {
lBound = 0;
uBound = 1;
}
// #ifdef __LHPN_EVAL__
// printf("[%d,%d]<=[%d,%d]=[%d,%d]\n",r1->lvalue,r1->uvalue ,r2->lvalue,r2->uvalue,lvalue,uvalue);
// #endif
}
// }else if(op=="[]"){//NEEDS WORK
// // bit extraction operator
else if (op.equals("[]")){ // Apparently needs work.
// // Only extract if both are point values.
// if ((r1->lvalue == r1->uvalue)&&(r2->lvalue == r2->uvalue)){
// lvalue = uvalue = (r1->lvalue >> r2->uvalue) & 1;
// }
if( (r1Range.get_LowerBound() == r1Range.get_UpperBound()) &&
(r2Range.get_LowerBound() == r2Range.get_UpperBound())){
lBound = uBound =
(r1Range.get_LowerBound() >> r2Range.get_UpperBound()) & 1;
}
// else {
// if (!preciser)
// {
// lvalue = 0;
// uvalue = 1;
// }
// else {
// uvalue = 0;
// lvalue = 1;
// for (i = r1->lvalue;i<=r1->uvalue;i++)
// for (j = r2->lvalue;j<=r2->uvalue;j++){
// k = (i >> j) & 1;
// lvalue &= k;
// uvalue |= k;
// if (lvalue < uvalue)
// return;
// }
// }
// }
else{
// Not doing the !preciser part.
uBound = 0;
lBound = 1;
for (int i = r1Range.get_LowerBound(); i<r1Range.get_UpperBound();
i++){
for (int j = r2Range.get_LowerBound();
j<r2Range.get_UpperBound(); j++){
int k = (i >> j) & 1;
lBound &= k;
uBound |= k;
if(lBound < uBound){
return new IntervalPair(lBound, uBound);
}
}
}
}
}
// }else if(op=="+"){
// lvalue = r1->lvalue + r2->lvalue;
// uvalue = r1->uvalue + r2->uvalue;
else if (op.equals("+")){
lBound = r1Range.get_LowerBound() + r2Range.get_LowerBound();
uBound = r1Range.get_UpperBound() + r2Range.get_UpperBound();
}
// }else if(op=="-"){
// lvalue = r1->lvalue - r2->uvalue;
// uvalue = r1->uvalue - r2->lvalue;
else if (op.equals("-")){
lBound = r1Range.get_LowerBound() - r2Range.get_LowerBound();
uBound = r1Range.get_UpperBound() - r2Range.get_UpperBound();
}
// }else if(op=="*"){
// tl1 = r1->lvalue * r2->lvalue;
// tl2 = r1->uvalue * r2->uvalue;
// tu1 = r1->lvalue * r2->uvalue;
// tu2 = r1->uvalue * r2->lvalue;
// lvalue = min(min(min(tl1,tl2),tu1),tu2);
// uvalue = max(max(max(tl1,tl2),tu1),tu2);
else if (op.equals("*")){
int tl1, tl2, tu1, tu2;
tl1 = r1Range.get_LowerBound() * r2Range.get_LowerBound();
tl2 = r1Range.get_UpperBound() * r2Range.get_UpperBound();
tu1 = r1Range.get_LowerBound() * r2Range.get_UpperBound();
tu2 = r1Range.get_UpperBound() * r2Range.get_LowerBound();
lBound = Math.min(Math.min(Math.min(tl1, tl2), tu1), tu2);
uBound = Math.max(Math.max(Math.max(tl1, tl2), tu1), tu2);
}
// }else if(op=="^"){
// tl1 = pow((double)r1->lvalue,(double)r2->lvalue);
// tl2 = pow((double)r1->uvalue,(double)r2->uvalue);
// tu1 = pow((double)r1->lvalue,(double)r2->uvalue);
// tu2 = pow((double)r1->uvalue,(double)r2->lvalue);
// lvalue = min(min(min(tl1,tl2),tu1),tu2);
// uvalue = max(max(max(tl1,tl2),tu1),tu2);
else if (op.equals("^")){
double tl1, tl2, tu1, tu2;
tl1 = Math.pow(r1Range.get_LowerBound(), r2Range.get_LowerBound());
tl2 = Math.pow(r1Range.get_UpperBound(), r2Range.get_UpperBound());
tu1 = Math.pow(r1Range.get_LowerBound(), r2Range.get_UpperBound());
tu2 = Math.pow(r1Range.get_UpperBound(), r2Range.get_LowerBound());
lBound = (int) Math.min(Math.min(Math.min(tl1, tl2), tu1), tu2);
uBound = (int) Math.max(Math.max(Math.max(tl1, tl2), tu1), tu2);
}
// }else if(op=="u"){
// lvalue = r1->lvalue;
// uvalue = r2->uvalue;
else if (op.equals("uniform")){
lBound = r1Range.get_LowerBound();
uBound = r2Range.get_UpperBound();
}
else if (op.equals("rate")){
LPNContinuousPair lcPair = new LPNContinuousPair(r1.lhpn.getLpnIndex(),
lhpn.getContVarIndex(r1.variable));
lBound = z.getCurrentRate(lcPair);
uBound = z.getCurrentRate(lcPair);
}
// }else if(op=="/"){
// //ropughly integer division.
// //DON"T KNOW WHAT FLOATING POINT PART IS!!!!!
// tl1 = floor(r1->lvalue / r2->lvalue);
// tl2 = floor(r1->uvalue / r2->uvalue);
// tu1 = floor(r1->lvalue / r2->uvalue);
// tu2 = floor(r1->uvalue / r2->lvalue);
// lvalue = min(min(min(tl1,tl2),tu1),tu2);
// tl1 = ceil(r1->lvalue / r2->lvalue);
// tl2 = ceil(r1->uvalue / r2->uvalue);
// tu1 = ceil(r1->lvalue / r2->uvalue);
// tu2 = ceil(r1->uvalue / r2->lvalue);
// uvalue = max(max(max(tl1,tl2),tu1),tu2);
else if (op.equals("/")){ // roughly integer division.
// STILL DON'T KNOW WHAT FLOATING POINT PART IS !!!! :) !!!!
double tl1, tl2, tu1, tu2;
tl1 = Math.floor(((double)r1Range.get_LowerBound()) / r2Range.get_LowerBound());
tl2 = Math.floor(((double)r1Range.get_UpperBound()) / r2Range.get_UpperBound());
tu1 = Math.floor(((double)r1Range.get_LowerBound()) / r2Range.get_UpperBound());
tu2 = Math.floor(((double)r1Range.get_UpperBound()) / r2Range.get_LowerBound());
lBound = (int) Math.min(Math.min(Math.min(tl1, tl2), tu1), tu2);
tl1 = Math.ceil(((double)r1Range.get_LowerBound()) / r2Range.get_LowerBound());
tl2 = Math.ceil(((double)r1Range.get_UpperBound()) / r2Range.get_UpperBound());
tu1 = Math.ceil(((double)r1Range.get_LowerBound()) / r2Range.get_UpperBound());
tu2 = Math.ceil(((double)r1Range.get_UpperBound()) / r2Range.get_LowerBound());
uBound = (int) Math.max(Math.max(Math.max(tl1, tl2), tu1), tu2);
}
// }else if(op=="%"){//NEEDS WORK
else if (op.equals("%")){// STILL NEEDS WORK.
// if (!preciser){
// // Only calculate if both are point values.
// if ((r1->lvalue == r1->uvalue)&&(r2->lvalue == r2->uvalue)){
// lvalue = uvalue = r1->lvalue % r2->uvalue;
// }
// else{
// lvalue = min(0,max(-(max(abs(r2->lvalue),abs(r2->lvalue))-1),r1->lvalue));
// uvalue = max(0,min(max(abs(r2->lvalue),abs(r2->uvalue))-1,r1->uvalue));
// }
// }
// else{
// uvalue = -INFIN;
// lvalue = INFIN;
// for (i = r1->lvalue;i<=r1->uvalue;i++)
// for (j = r2->lvalue;j<=r2->uvalue;j++){
// k = i%j;
// if (k < lvalue)
// lvalue = k;
// if (k > uvalue)
// uvalue = k;
// }
// }
// Not doing the !precier part.
lBound = -INFIN;
uBound = INFIN;
for (int i = r1Range.get_LowerBound(); i <= r1Range.get_UpperBound(); i++){
for ( int j = r2Range.get_LowerBound(); j <= r2Range.get_UpperBound(); j++){
int k = i%j;
if(k < lBound){
lBound = k;
}
if( k > uBound){
uBound = k;
}
}
}
}
// }else if(op=="U-"){
// lvalue = -(r1->uvalue);
// uvalue = -(r1->lvalue);
else if (op.equals("U-")){
lBound = -1 * r1Range.get_UpperBound();
uBound = -1 * (r1Range.get_LowerBound());
}
// }else if(op=="INT"){
// lvalue = r1->lvalue;
// uvalue = r1->uvalue;
else if (op.equals("INT")){
lBound = r1Range.get_LowerBound();
uBound = r1Range.get_UpperBound();
}
// }else if(op=="BOOL"){
// if ((r1->lvalue == 0)&& (r1->uvalue == 0))
// lvalue = uvalue = 0;
// else if (((r1->lvalue > 0) && (r1->uvalue > 0))||
// ((r1->lvalue < 0) && (r1->uvalue < 0)))
// lvalue = uvalue = 1;
// else {
// lvalue = 0;
// uvalue = 1;
// }
else if(op.equals("BOOL")){
if( (r1Range.get_LowerBound() == 0) && (r1Range.get_UpperBound() == 0)){
lBound = uBound =0;
}
else if ((r1Range.get_LowerBound() > 0) && (r1Range.get_UpperBound() > 0) ||
(r1Range.get_LowerBound() < 0) && (r1Range.get_UpperBound() < 0)){
lBound = uBound =1 ;
}
else{
lBound = 0;
uBound = 1;
}
}
// }else if(op=="&"){
else if(op.equals("&")){
// if ((r1->lvalue!=r1->uvalue)||(r2->lvalue!=r2->uvalue)) {
if((r1Range.get_LowerBound() != r1Range.get_UpperBound()) ||
(r2Range.get_LowerBound() != r2Range.get_UpperBound())){
// if (!preciser){
// lvalue = min(r1->lvalue+r2->lvalue,0);
// uvalue = max((r1->uvalue),(r2->uvalue));
// }
// else{
// uvalue = -INFIN;
// lvalue = INFIN;
// for (i = r1->lvalue;i<=r1->uvalue;i++)
// for (j = r2->lvalue;j<=r2->uvalue;j++){
// k = i&j;
// if (k < lvalue)
// lvalue = k;
// if (k > uvalue)
// uvalue = k;
// }
// }
// }
// Not doing the !preciser part.
uBound = -INFIN;
lBound = INFIN;
for( int i=r1Range.get_LowerBound(); i<=r1Range.get_UpperBound(); i++){
for(int j=r2Range.get_LowerBound(); j<=r2Range.get_UpperBound(); j++){
int k = i&j;
if (k < lBound){
lBound =k;
}
if( k > uBound){
uBound = k;
}
}
}
}
// else {
// lvalue = (r1->lvalue & r2->lvalue);
// uvalue = (r1->lvalue & r2->lvalue);
// }
else {
lBound = (r1Range.get_LowerBound() & r2Range.get_LowerBound());
uBound = (r1Range.get_LowerBound() & r2Range.get_LowerBound());
}
// #ifdef __LHPN_EVAL__
// printf("BITWISE AND: [%d,%d](%c)&[%d,%d](%c) = [%d,%d]\n",r1->lvalue,
// r1->uvalue,r1->isit,r2->lvalue,r2->uvalue,r2->isit,lvalue,uvalue);
// #endif
}
// }else if(op=="|"){
else if (op.equals("|")){
// if ((r1->lvalue!=r1->uvalue)||(r2->lvalue!=r2->uvalue)) {
// lvalue = min(r1->lvalue,r2->lvalue);
// uvalue = max(r1->uvalue + r2->uvalue,-1);
// } else {
// lvalue = (r1->lvalue | r2->lvalue);
// uvalue = (r1->lvalue | r2->lvalue);
// }
if((r1Range.get_LowerBound() != r1Range.get_UpperBound()) ||
(r2Range.get_LowerBound() != r2Range.get_UpperBound())){
lBound = Math.min(r1Range.get_LowerBound(), r2Range.get_LowerBound());
uBound = Math.max(r1Range.get_UpperBound() + r2Range.get_UpperBound(), -1);
}
else {
lBound = (r1Range.get_LowerBound() | r2Range.get_LowerBound());
uBound = (r1Range.get_LowerBound() | r2Range.get_LowerBound());
}
}
// }else if(op=="m"){
// lvalue = min(r1->lvalue,r2->lvalue);
// uvalue = min(r1->uvalue,r2->uvalue);
else if(op.equals("m")){
lBound = Math.min(r1Range.get_LowerBound(), r2Range.get_LowerBound());
uBound = Math.min(r1Range.get_UpperBound(), r2Range.get_UpperBound());
}
// }else if(op=="M"){
// lvalue = max(r1->lvalue,r2->lvalue);
// uvalue = max(r1->uvalue,r2->uvalue);
else if (op.equals("M")){
lBound = Math.max(r1Range.get_LowerBound(), r2Range.get_LowerBound());
uBound = Math.max(r1Range.get_UpperBound(), r2Range.get_UpperBound());
}
// }else if(op=="i"){
// tl1 = r1->lvalue / r2->lvalue;
// tl2 = r1->uvalue / r2->uvalue;
// tu1 = r1->lvalue / r2->uvalue;
// tu2 = r1->uvalue / r2->lvalue;
// lvalue = min(min(min(tl1,tl2),tu1),tu2);
// uvalue = max(max(max(tl1,tl2),tu1),tu2);
else if (op.equals("i")){
int tl1, tl2, tu1, tu2;
tl1 = r1Range.get_LowerBound() / r2Range.get_LowerBound();
tl2 = r1Range.get_UpperBound() / r2Range.get_UpperBound();
tu1 = r1Range.get_LowerBound() / r2Range.get_UpperBound();
tu2 = r1Range.get_UpperBound() / r2Range.get_LowerBound();
lBound = Math.min(Math.min(Math.min(tl1, tl2), tu1), tu2);
uBound = Math.max(Math.max(Math.max(tl1, tl2), tu1), tu2);
}
// }else if(op=="X"){
// lvalue = min(min(r1->lvalue-r2->uvalue,r2->lvalue-r1->uvalue),0);
// uvalue = max(max(r1->uvalue + r2->uvalue,-(r1->lvalue + r2->lvalue)),-1);
else if(op.equals("X")){
lBound = Math.min(Math.min(r1Range.get_LowerBound()-r2Range.get_UpperBound(),
r2Range.get_LowerBound()-r1Range.get_UpperBound()), 0);
uBound = Math.max(Math.max(r1Range.get_UpperBound()+r2Range.get_UpperBound(),
r2Range.get_LowerBound()+r1Range.get_LowerBound()), -1);
}
//// }else if(op=="floor"){
//// lvalue = floor(r1->lvalue);
//// uvalue = floor(r1->uvalue);
//// }else if(op=="round"){
//// lvalue = round(r1->lvalue);
//// uvalue = round(r1->uvalue);
//// }else if(op=="ceil"){
//// lvalue = ceil(r1->lvalue);
//// uvalue = ceil(r1->uvalue);
// }else if(op=="~"){
// //bitwise negation operator (1's complement)
// lvalue = -((r1->uvalue)+1);
// uvalue = -((r1->lvalue)+1);
// }
else if (op.equals("~")){
// bitwise negation operator (1's complement)
lBound = -1*(r1Range.get_LowerBound());
uBound = -1*(r1Range.get_UpperBound());
}
// }else if(isit == 'd'){
// for (i = 1;i<cur_state->z->size;i++){
// if (cur_state->z->curClocks[i].enabled == index){
// lvalue = cur_state->r->bound[cur_state->z->curClocks[i].enabled-nevents].lower;
// uvalue = cur_state->r->bound[cur_state->z->curClocks[i].enabled-nevents].upper;
// #ifdef __LHPN_EVAL__
// printf("lv=%d,uv=%d,index=%d,i=%d\n",lvalue, uvalue,index,i);
// #endif
// break;
// }
// }
// Not present in the current implementation. These are 'i'.
// else if (isit == 'd'){
// //Check what this is before doing it.
// }
// }else{
}
else{
// if ((isit == 'i')||(isit == 'c')){
if(isit == 'i'){
// for (i = 1;i<cur_state->z->size;i++){
// if (cur_state->z->curClocks[i].enabled == index){
// if (i>=cur_state->z->dbmEnd){
// lvalue = -1*(cur_state->z->matrix[0][i]);
// uvalue = cur_state->z->matrix[i][0];
// }
// Get the value of the variable from the passed HashMap and convert it as appropriate.
String sV = variables.get(variable); // sV for "string value"
if(sV != null){
int tmp = Integer.parseInt(sV);
// Currently the platu.state does not support integer ranges.
lBound = uBound = tmp;
}
else{
lBound = -INFIN;
uBound = INFIN;
}
// else{// uses lower rate bound for both????
// lvalue = -1*(cur_state->z->matrix[0][i])*
// cur_state->r->bound[cur_state->z->curClocks[i].enabled-nevents].current;
// uvalue = cur_state->z->matrix[i][0]*
// cur_state->r->bound[cur_state->z->curClocks[i].enabled-nevents].current;
// }
// #ifdef __LHPN_EVAL__
// printf("lv=%d,uv=%d,index=%d,i=%d\n",lvalue, uvalue,index,i);
// #endif
// break;
// }
// }
}
else if(isit == 'c'){
// if(z != null){
// return z.getContinuousBounds(variable, lhpn);
// }
// else{
// return continuousValues.get(new LPNContinuousPair(lhpn.getLpnIndex(),
// lhpn.getContVarIndex(variable)));
// }
LPNContinuousPair lcPair = new LPNContinuousPair(lhpn.getLpnIndex(),
lhpn.getContVarIndex(variable));
IntervalPair result = null;
if(continuousValues != null){
result = continuousValues.get(new LPNContAndRate(lcPair));
}
if(result != null){
return result;
}
return z.getContinuousBounds(variable, lhpn);
}
else if (isit == 'b'){
// }else if (isit == 'b'){
// log_val = cur_state->m->state[index];
// if (log_val == '1'){
// lvalue = 1;
// uvalue = 1;
// } else if (log_val == 'X'){
// lvalue = 0;
// uvalue = 1;
// } else if (log_val == '0'){
// lvalue = 0;
// uvalue = 0;
// }
// #ifdef __LHPN_EVAL__
// printf("successful lookup of boolean %d,%c[%d,%d]\n",index,
// cur_state->m->state[index],lvalue,uvalue);
// #endif
// Get the value of the variable from the passed HashMap and convert it as appropriate.
String sV = variables.get(variable); // sV for "string value"
if(sV != null){
int tmp = (sV.toLowerCase().equals("true") || sV.equals("1")) ? 1 : 0;
// Currently the platu.state does not support boolean ranges.
lBound = uBound = tmp;
}
else{
lBound = 0;
uBound = 1;
}
}
else if(isit == 'n'){
// }else if ((isit == 'n')||(isit == 't')){
// // values already stored, no need to evaluate!
// }
// }
lBound = uBound = (int) lvalue;
// if (uvalue == lvalue) {
// return uvalue;
// } else {
// return ((uvalue - lvalue) * new java.util.Random().nextDouble())
// + lvalue;
// }
}
else if ((isit == 't')){
// Should be fine to use the lvalue and uvalue.
lBound = (int) lvalue;
uBound = (int) uvalue;
// // Get the value of the variable from the passed HashMap and convert it as appropriate.
// String sV = variables.get(variable); // sV for "string value"
//
// if(sV != null){
// lBound = uBound = 1;
// }
// else{
// lBound = 0;
// uBound = 1;
// }
}
// };
}
// TODO : need to return an appropriate value when the operation is "".
return new IntervalPair(lBound, uBound);
}
/**
* Converts an integer range for an expression tree representing a logical into
* a boolean pair.
* @param expr
* An expression tree.
* @param range
* The integer range.
* @return
* The range converted to a boolean pair if expr.logical is true and range is non-null.
*/
private BooleanPair logicalConversion(ExprTree expr, IntervalPair range){
Boolean lower, upper;
if( range != null && expr.logical){ // Note : range can only be set if range is non-null.
lower = range.get_LowerBound() != 0; // False if value is zero and true otherwise.
upper = range.get_UpperBound() != 0; // False if value is zero and true otherwise.
}
else{
if (range!=null) {
if((range.get_LowerBound() == 0) && (range.get_UpperBound() == 0)){// false
lower = upper = false;
}
else if (((range.get_LowerBound() < 0) && (range.get_UpperBound() < 0)) ||
((range.get_LowerBound() > 0) && (range.get_UpperBound() > 0))){ // true
lower = upper = true;
}
else{
lower = false;
upper = true;
}
} else {
lower = false;
upper = true;
}
}
return new BooleanPair(lower, upper);
}
//------------------------------- Inner Class -------------------------------------
private class BooleanPair {
private Boolean _lower;
private Boolean _upper;
public BooleanPair(Boolean lower, Boolean upper) {
super();
this._lower = lower;
this._upper = upper;
}
public Boolean get_lower() {
return _lower;
}
// public void set_lower(Boolean lower) {
// this._lower = lower;
// }
public Boolean get_upper() {
return _upper;
}
// public void set_upper(Boolean upper) {
// this._upper = upper;
// }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((_lower == null) ? 0 : _lower.hashCode());
result = prime * result + ((_upper == null) ? 0 : _upper.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof BooleanPair))
return false;
BooleanPair other = (BooleanPair) obj;
if (_lower == null) {
if (other._lower != null)
return false;
} else if (!_lower.equals(other._lower))
return false;
if (_upper == null) {
if (other._upper != null)
return false;
} else if (!_upper.equals(other._upper))
return false;
return true;
}
@Override
public String toString() {
return "BooleanPair [lower=" + _lower + ", upper=" + _upper + "]";
}
}
} | Fix ^ precedence in ExprTree parsing | verification/src/main/java/edu/utah/ece/async/lema/verification/lpn/ExprTree.java | Fix ^ precedence in ExprTree parsing |
|
Java | apache-2.0 | e02844d24b180cbaee64061aa8ffa33b61a1b2cf | 0 | drankye/directory-server,apache/directory-server,drankye/directory-server,apache/directory-server | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.server.kerberos.shared.replay;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import javax.security.auth.kerberos.KerberosPrincipal;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import org.apache.directory.junit.tools.MultiThreadedMultiInvoker;
import org.apache.directory.shared.kerberos.KerberosTime;
import org.apache.directory.shared.kerberos.codec.types.PrincipalNameType;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.mycila.junit.concurrent.Concurrency;
import com.mycila.junit.concurrent.ConcurrentJunitRunner;
/**
* Test the InMemory replay cache
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
@RunWith(ConcurrentJunitRunner.class)
@Concurrency()
public class ReplayCacheImplTest
{
@Rule
public MultiThreadedMultiInvoker i = new MultiThreadedMultiInvoker( MultiThreadedMultiInvoker.THREADSAFE );
/**
* Test that the cache is working well. We will create a new entry
* every 500 ms, with 4 different serverPrincipals.
*
* After this period of time, we should only have 2 entries in the cache
*/
@Test
public void testCacheSetting() throws Exception
{
CacheManager cacheManager = null;
try
{
long clockSkew = 1000; // 1 sec
cacheManager = new CacheManager();
cacheManager.addCache( "kdcReplayCache" );
Cache ehCache = cacheManager.getCache( "kdcReplayCache" );
ehCache.getCacheConfiguration().setMaxElementsInMemory( 4 );
ehCache.getCacheConfiguration().setTimeToLiveSeconds( 1 );
ehCache.getCacheConfiguration().setTimeToIdleSeconds( 1 );
ehCache.getCacheConfiguration().setDiskExpiryThreadIntervalSeconds( 1 );
ReplayCacheImpl cache = new ReplayCacheImpl( ehCache, clockSkew );
int i = 0;
// Inject 4 entries
while ( i < 4 )
{
KerberosPrincipal serverPrincipal = new KerberosPrincipal( "server" + i + "@APACHE.ORG",
PrincipalNameType.KRB_NT_PRINCIPAL.getValue() );
KerberosPrincipal clientPrincipal = new KerberosPrincipal( "client" + i + "@APACHE.ORG",
PrincipalNameType.KRB_NT_PRINCIPAL.getValue() );
cache.save( serverPrincipal, clientPrincipal, new KerberosTime( System.currentTimeMillis() ), 0 );
i++;
}
List<?> keys = ehCache.getKeys();
// We should have 4 entries
assertTrue( keys.size() != 0 );
// Wait till the timetolive time exceeds
Thread.sleep( 1200 );
// then access the cache so that the objects present in the cache will be expired
for ( Object k : keys )
{
assertNull( ehCache.get( k ) );
}
assertEquals( 0, ehCache.getKeys().size() );
}
finally
{
if ( cacheManager != null )
{
cacheManager.shutdown();
}
}
}
}
| kerberos-codec/src/test/java/org/apache/directory/server/kerberos/shared/replay/ReplayCacheImplTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.server.kerberos.shared.replay;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import javax.security.auth.kerberos.KerberosPrincipal;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import org.apache.directory.junit.tools.MultiThreadedMultiInvoker;
import org.apache.directory.shared.kerberos.KerberosTime;
import org.apache.directory.shared.kerberos.codec.types.PrincipalNameType;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.mycila.junit.concurrent.Concurrency;
import com.mycila.junit.concurrent.ConcurrentJunitRunner;
/**
* Test the InMemory replay cache
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
@RunWith(ConcurrentJunitRunner.class)
@Concurrency()
public class ReplayCacheImplTest
{
@Rule
public MultiThreadedMultiInvoker i = new MultiThreadedMultiInvoker( MultiThreadedMultiInvoker.THREADSAFE );
/**
* Test that the cache is working well. We will create a new entry
* every 500 ms, with 4 different serverPrincipals.
*
* After this period of time, we should only have 2 entries in the cache
*/
@Test
public void testCacheSetting() throws Exception
{
CacheManager cacheManager = null;
try
{
long clockSkew = 1000; // 1 sec
cacheManager = new CacheManager();
cacheManager.addCache( "kdcReplayCache" );
Cache ehCache = cacheManager.getCache( "kdcReplayCache" );
ehCache.getCacheConfiguration().setMaxElementsInMemory( 2 );
ehCache.getCacheConfiguration().setTimeToLiveSeconds( 1 );
ehCache.getCacheConfiguration().setTimeToIdleSeconds( 1 );
ehCache.getCacheConfiguration().setDiskExpiryThreadIntervalSeconds( 1 );
ReplayCacheImpl cache = new ReplayCacheImpl( ehCache, clockSkew );
int i = 0;
// Inject 4 entries
while ( i < 4 )
{
KerberosPrincipal serverPrincipal = new KerberosPrincipal( "server" + i + "@APACHE.ORG",
PrincipalNameType.KRB_NT_PRINCIPAL.getValue() );
KerberosPrincipal clientPrincipal = new KerberosPrincipal( "client" + i + "@APACHE.ORG",
PrincipalNameType.KRB_NT_PRINCIPAL.getValue() );
cache.save( serverPrincipal, clientPrincipal, new KerberosTime( System.currentTimeMillis() ), 0 );
i++;
}
List<?> keys = ehCache.getKeys();
// We should have 4 entries
assertTrue( keys.size() != 0 );
// Wait till the timetolive time exceeds
Thread.sleep( 1200 );
// then access the cache so that the objects present in the cache will be expired
for ( Object k : keys )
{
assertNull( ehCache.get( k ) );
}
assertEquals( 0, ehCache.getKeys().size() );
}
finally
{
if ( cacheManager != null )
{
cacheManager.shutdown();
}
}
}
}
| Applied patch for DIRSERVER-2035
git-svn-id: 90776817adfbd895fc5cfa90f675377e0a62e745@1644601 13f79535-47bb-0310-9956-ffa450edef68
| kerberos-codec/src/test/java/org/apache/directory/server/kerberos/shared/replay/ReplayCacheImplTest.java | Applied patch for DIRSERVER-2035 |
|
Java | apache-2.0 | d96c3d85f54d8cad4722c96722b2f5380edd7e01 | 0 | brightchen/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,siyuanh/apex-malhar,vrozov/apex-malhar,patilvikram/apex-malhar,sandeep-n/incubator-apex-malhar,ilganeli/incubator-apex-malhar,davidyan74/apex-malhar,tweise/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,vrozov/apex-malhar,yogidevendra/apex-malhar,PramodSSImmaneni/apex-malhar,yogidevendra/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,trusli/apex-malhar,davidyan74/apex-malhar,siyuanh/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,skekre98/apex-mlhr,patilvikram/apex-malhar,prasannapramod/apex-malhar,trusli/apex-malhar,siyuanh/apex-malhar,tweise/incubator-apex-malhar,skekre98/apex-mlhr,tweise/apex-malhar,patilvikram/apex-malhar,patilvikram/apex-malhar,ilganeli/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,skekre98/apex-mlhr,tweise/apex-malhar,ananthc/apex-malhar,yogidevendra/apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,PramodSSImmaneni/apex-malhar,vrozov/incubator-apex-malhar,vrozov/apex-malhar,sandeep-n/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,tweise/apex-malhar,vrozov/apex-malhar,apache/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,chandnisingh/apex-malhar,ilganeli/incubator-apex-malhar,vrozov/apex-malhar,patilvikram/apex-malhar,sandeep-n/incubator-apex-malhar,davidyan74/apex-malhar,chinmaykolhatkar/apex-malhar,skekre98/apex-mlhr,ananthc/apex-malhar,siyuanh/apex-malhar,vrozov/incubator-apex-malhar,vrozov/incubator-apex-malhar,siyuanh/incubator-apex-malhar,brightchen/apex-malhar,trusli/apex-malhar,sandeep-n/incubator-apex-malhar,tweise/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,ananthc/apex-malhar,vrozov/incubator-apex-malhar,siyuanh/apex-malhar,vrozov/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,tweise/apex-malhar,ananthc/apex-malhar,brightchen/apex-malhar,chandnisingh/apex-malhar,yogidevendra/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,chinmaykolhatkar/apex-malhar,tweise/incubator-apex-malhar,ananthc/apex-malhar,DataTorrent/incubator-apex-malhar,prasannapramod/apex-malhar,trusli/apex-malhar,apache/incubator-apex-malhar,siyuanh/apex-malhar,DataTorrent/incubator-apex-malhar,ilganeli/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,brightchen/apex-malhar,yogidevendra/apex-malhar,patilvikram/apex-malhar,prasannapramod/apex-malhar,tweise/apex-malhar,chandnisingh/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,ananthc/apex-malhar,yogidevendra/apex-malhar,tweise/incubator-apex-malhar,apache/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,skekre98/apex-mlhr,prasannapramod/apex-malhar,davidyan74/apex-malhar,yogidevendra/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,siyuanh/apex-malhar,apache/incubator-apex-malhar,skekre98/apex-mlhr,prasannapramod/apex-malhar,trusli/apex-malhar,prasannapramod/apex-malhar,tushargosavi/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,apache/incubator-apex-malhar,chandnisingh/apex-malhar,DataTorrent/incubator-apex-malhar,siyuanh/apex-malhar,vrozov/incubator-apex-malhar,ilganeli/incubator-apex-malhar,ilganeli/incubator-apex-malhar,brightchen/apex-malhar,siyuanh/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,siyuanh/incubator-apex-malhar,brightchen/apex-malhar,tushargosavi/incubator-apex-malhar,trusli/apex-malhar,siyuanh/incubator-apex-malhar,chandnisingh/apex-malhar,ilganeli/incubator-apex-malhar,siyuanh/incubator-apex-malhar,patilvikram/apex-malhar,yogidevendra/apex-malhar,davidyan74/apex-malhar,brightchen/apex-malhar,apache/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,PramodSSImmaneni/apex-malhar,vrozov/incubator-apex-malhar,chandnisingh/apex-malhar,yogidevendra/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,apache/incubator-apex-malhar,tweise/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,vrozov/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,trusli/apex-malhar,davidyan74/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,siyuanh/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,tweise/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,chandnisingh/apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,tweise/apex-malhar | /**
* Copyright (C) 2015 DataTorrent, Inc.
*
* 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.datatorrent.lib.db.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.lib.db.AbstractStoreInputOperator;
/**
* This is a base implementation of a JDBC input operator.
* This operator reads data from a database through the JAVA DataBase Connectivity (JDBC) API
* and emits the data as tuples.
* Subclasses should implement the methods required to read the data from the database.
* <p>
* This is an abstract class. Sub-classes need to implement {@link #queryToRetrieveData()} and {@link #getTuple(ResultSet)}.
* </p>
* @displayName Abstract JDBC Input
* @category Input
* @tags database, sql
*
* @param <T> The tuple type
* @since 0.9.4
*/
public abstract class AbstractJdbcInputOperator<T> extends AbstractStoreInputOperator<T, JdbcStore>
{
private static final Logger logger = LoggerFactory.getLogger(AbstractJdbcInputOperator.class);
protected transient Statement queryStatement;
private transient int waitForDataTimeout;
/**
* Any concrete class has to override this method to convert a Database row into Tuple.
*
* @param result a single row that has been read from database.
* @return Tuple a tuples created from row which can be any Java object.
*/
public abstract T getTuple(ResultSet result);
/**
* Any concrete class has to override this method to return the query string which will be used to
* retrieve data from database.
*
* @return Query string
*/
public abstract String queryToRetrieveData();
/**
* This executes the query to retrieve result from database.
* It then converts each row into tuple and emit that into output port.
*/
@Override
public void emitTuples()
{
String query = queryToRetrieveData();
logger.debug(String.format("select statement: %s", query));
try {
ResultSet result = queryStatement.executeQuery(query);
if (result.next()) {
do {
T tuple = getTuple(result);
outputPort.emit(tuple);
}
while (result.next());
}
else {
// No rows available wait for some time before retrying so as to not continuously slam the database
Thread.sleep(waitForDataTimeout);
}
}
catch (SQLException ex) {
store.disconnect();
throw new RuntimeException(String.format("Error while running query: %s", query), ex);
}
catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
@Override
public void setup(OperatorContext context)
{
waitForDataTimeout = context.getValue(OperatorContext.SPIN_MILLIS);
super.setup(context);
try {
queryStatement = store.getConnection().createStatement();
}
catch (SQLException e) {
throw new RuntimeException("creating query", e);
}
}
}
| library/src/main/java/com/datatorrent/lib/db/jdbc/AbstractJdbcInputOperator.java | /**
* Copyright (C) 2015 DataTorrent, Inc.
*
* 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.datatorrent.lib.db.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.lib.db.AbstractStoreInputOperator;
/**
* This is a base implementation of a JDBC input operator.
* This operator reads data from a database through the JAVA DataBase Connectivity (JDBC) API
* and emits the data as tuples.
* Subclasses should implement the methods required to read the data from the database.
* <p>
* This is an abstract class. Sub-classes need to implement {@link #queryToRetrieveData()} and {@link #getTuple(ResultSet)}.
* </p>
* @displayName Abstract JDBC Input
* @category Input
* @tags database, sql
*
* @param <T> The tuple type
* @since 0.9.4
*/
public abstract class AbstractJdbcInputOperator<T> extends AbstractStoreInputOperator<T, JdbcStore>
{
private static final Logger logger = LoggerFactory.getLogger(AbstractJdbcInputOperator.class);
Statement queryStatement = null;
private transient int waitForDataTimeout;
/**
* Any concrete class has to override this method to convert a Database row into Tuple.
*
* @param result a single row that has been read from database.
* @return Tuple a tuples created from row which can be any Java object.
*/
public abstract T getTuple(ResultSet result);
/**
* Any concrete class has to override this method to return the query string which will be used to
* retrieve data from database.
*
* @return Query string
*/
public abstract String queryToRetrieveData();
/**
* This executes the query to retrieve result from database.
* It then converts each row into tuple and emit that into output port.
*/
@Override
public void emitTuples()
{
String query = queryToRetrieveData();
logger.debug(String.format("select statement: %s", query));
try {
ResultSet result = queryStatement.executeQuery(query);
if (result.next()) {
do {
T tuple = getTuple(result);
outputPort.emit(tuple);
}
while (result.next());
}
else {
// No rows available wait for some time before retrying so as to not continuously slam the database
Thread.sleep(waitForDataTimeout);
}
}
catch (SQLException ex) {
store.disconnect();
throw new RuntimeException(String.format("Error while running query: %s", query), ex);
}
catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
@Override
public void setup(OperatorContext context)
{
waitForDataTimeout = context.getValue(OperatorContext.SPIN_MILLIS);
super.setup(context);
try {
queryStatement = store.getConnection().createStatement();
}
catch (SQLException e) {
throw new RuntimeException("creating query", e);
}
}
}
| statement should be transient
| library/src/main/java/com/datatorrent/lib/db/jdbc/AbstractJdbcInputOperator.java | statement should be transient |
|
Java | bsd-3-clause | 6410b502f6cde3354148e2b9cc6303010515e13e | 0 | oci-pronghorn/PronghornIoT-Examples,oci-pronghorn/PronghornIoT,oci-pronghorn/PronghornIoT,oci-pronghorn/FogLight,oci-pronghorn/FogLight,oci-pronghorn/FogLight,oci-pronghorn/PronghornIoT-Examples | package com.ociweb.iot.nightlight;
import static com.ociweb.iot.grove.GroveTwig.AngleSensor;
import static com.ociweb.iot.grove.GroveTwig.LightSensor;
import com.ociweb.iot.grove.Grove_LCD_RGB;
import com.ociweb.iot.hardware.Hardware;
import com.ociweb.iot.maker.CommandChannel;
import com.ociweb.iot.maker.DeviceRuntime;
import com.ociweb.iot.maker.IoTSetup;
/**
* As it gets dark the back light of the LCD comes on.
* Angle sensor is used for brightness adjustment
*/
public class IoTApp implements IoTSetup
{
public static final int LIGHT_SENSOR_CONNECTION = 2;
public static final int ANGLE_SENSOR_CONNECTION = 1;
int brightness = 255;
public static void main( String[] args ) {
DeviceRuntime.run(new IoTApp());
}
@Override
public void declareConnections(Hardware c) {
c.useConnectA(LightSensor, LIGHT_SENSOR_CONNECTION);
c.useConnectA(AngleSensor, ANGLE_SENSOR_CONNECTION);
c.useI2C();
}
@Override
public void declareBehavior(DeviceRuntime runtime) {
final CommandChannel lcdScreenChannel = runtime.newCommandChannel();
runtime.addAnalogListener((connection, time, average, value)->{
switch(connection) {
case LIGHT_SENSOR_CONNECTION:
int leadingZeros = Integer.numberOfLeadingZeros(value) - (32-10); //value is only 10 bits max
int level = Math.min(255, (brightness * Math.min(leadingZeros,8))/8);
Grove_LCD_RGB.commandForColor(lcdScreenChannel, level, level, level);
break;
case ANGLE_SENSOR_CONNECTION:
brightness = (400 * value)/1024;
break;
}
});
}
}
| nightLight/src/main/java/com/ociweb/iot/nightlight/IoTApp.java | package com.ociweb.iot.nightlight;
import static com.ociweb.iot.grove.GroveTwig.AngleSensor;
import static com.ociweb.iot.grove.GroveTwig.LightSensor;
import com.ociweb.iot.grove.Grove_LCD_RGB;
import com.ociweb.iot.hardware.Hardware;
import com.ociweb.iot.maker.CommandChannel;
import com.ociweb.iot.maker.DeviceRuntime;
import com.ociweb.iot.maker.IoTSetup;
/**
* As it gets dark the back light of the LCD comes on.
* Angle sensor is used for brightness adjustment
*/
public class IoTApp implements IoTSetup
{
public static final int LIGHT_SENSOR_CONNECTION = 2;
public static final int ANGLE_SENSOR_CONNECTION = 1;
int brightness = 255;
public static void main( String[] args ) {
DeviceRuntime.run(new IoTApp());
}
@Override
public void declareConnections(Hardware c) {
c.useConnectA(LightSensor, LIGHT_SENSOR_CONNECTION);
c.useConnectA(AngleSensor, ANGLE_SENSOR_CONNECTION);
c.useI2C();
}
@Override
public void declareBehavior(DeviceRuntime runtime) {
final CommandChannel lcdScreenChannel = runtime.newCommandChannel();
runtime.addAnalogListener((connection, time, average, value)->{
switch(connection) {
case LIGHT_SENSOR_CONNECTION:
int leadingZeros = Integer.numberOfLeadingZeros(value) - (32-10); //value is only 10 bits max
int level = Math.min(255, (brightness * Math.min(leadingZeros,8))/8);
Grove_LCD_RGB.commandForColor(lcdScreenChannel, level, level, level);
break;
case ANGLE_SENSOR_CONNECTION:
brightness = (400 * value)/1024;
break;
}
});
}
}
| clean up values | nightLight/src/main/java/com/ociweb/iot/nightlight/IoTApp.java | clean up values |
|
Java | bsd-3-clause | 63cf17e5a40f9e6ce8a5503b9075266b5196e404 | 0 | musiKk/classreader | /*
* Copyright (c) 2013, Werner Hahn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ONANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.github.musikk.classreader.attributes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import com.github.musikk.classreader.ClassReader;
import com.github.musikk.classreader.ClassReaderContext;
import com.google.common.collect.Iterators;
public class ExceptionTable implements Iterable<ExceptionTableEntry> {
private final List<ExceptionTableEntry> exceptionTableEntries;
private ExceptionTable(List<ExceptionTableEntry> exceptionTableEntries) {
this.exceptionTableEntries = exceptionTableEntries;
}
public List<ExceptionTableEntry> getExceptionTableEntries() {
return Collections.unmodifiableList(exceptionTableEntries);
}
@Override
public Iterator<ExceptionTableEntry> iterator() {
return Iterators.unmodifiableIterator(exceptionTableEntries.iterator());
}
protected static ExceptionTable getExceptionTable(ClassReaderContext ctxt) {
ClassReader reader = ctxt.getClassReader();
int exceptionTableLength = reader.readUnsignedShort();
List<ExceptionTableEntry> exceptionTableEntries = new ArrayList<>(exceptionTableLength);
for (int i = 0; i < exceptionTableLength; i++) {
exceptionTableEntries.add(ExceptionTableEntry.getExceptionTableEntry(ctxt));
}
return new ExceptionTable(exceptionTableEntries);
}
}
| src/main/java/com/github/musikk/classreader/attributes/ExceptionTable.java | /*
* Copyright (c) 2013, Werner Hahn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ONANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.github.musikk.classreader.attributes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.github.musikk.classreader.ClassReader;
import com.github.musikk.classreader.ClassReaderContext;
public class ExceptionTable {
private final List<ExceptionTableEntry> exceptionTableEntries;
private ExceptionTable(List<ExceptionTableEntry> exceptionTableEntries) {
this.exceptionTableEntries = exceptionTableEntries;
}
public List<ExceptionTableEntry> getExceptionTableEntries() {
return Collections.unmodifiableList(exceptionTableEntries);
}
protected static ExceptionTable getExceptionTable(ClassReaderContext ctxt) {
ClassReader reader = ctxt.getClassReader();
int exceptionTableLength = reader.readUnsignedShort();
List<ExceptionTableEntry> exceptionTableEntries = new ArrayList<>(exceptionTableLength);
for (int i = 0; i < exceptionTableLength; i++) {
exceptionTableEntries.add(ExceptionTableEntry.getExceptionTableEntry(ctxt));
}
return new ExceptionTable(exceptionTableEntries);
}
}
| make exception table iterable
| src/main/java/com/github/musikk/classreader/attributes/ExceptionTable.java | make exception table iterable |
|
Java | bsd-3-clause | 626d71409995c76b78f68291f737d52fa44b5a44 | 0 | mogol/flutter_secure_storage,mogol/flutter_secure_storage,mogol/flutter_secure_storage,mogol/flutter_secure_storage,mogol/flutter_secure_storage,mogol/flutter_secure_storage,mogol/flutter_secure_storage | package com.it_nomads.fluttersecurestorage.ciphers;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import java.math.BigInteger;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Calendar;
import javax.crypto.Cipher;
import javax.security.auth.x500.X500Principal;
public class StorageCipher18Implementation implements StorageCipher {
private static final String KEY_ALIAS;
private static final String KEYSTORE_PROVIDER_ANDROID = "AndroidKeyStore";
private static final String TYPE_RSA = "RSA";
public StorageCipher18Implementation(Context context) throws Exception {
KEY_ALIAS = context.getPackageName() + ".FlutterSecureStoragePluginKey";
createKeysIfNeeded(context);
}
@Override
public byte[] encrypt(byte[] input) throws Exception {
PublicKey publicKey = getEntry().getCertificate().getPublicKey();
Cipher cipher = getCipher();
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(input);
}
@Override
public byte[] decrypt(byte[] input) throws Exception {
PrivateKey privateKey = getEntry().getPrivateKey();
Cipher cipher = getCipher();
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(input);
}
private KeyStore.PrivateKeyEntry getEntry() throws Exception {
KeyStore ks = KeyStore.getInstance(KEYSTORE_PROVIDER_ANDROID);
ks.load(null);
KeyStore.Entry entry = ks.getEntry(KEY_ALIAS, null);
if (entry == null) {
throw new Exception("No key found under alias: " + KEY_ALIAS);
}
if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
throw new Exception("Not an instance of a PrivateKeyEntry");
}
return (KeyStore.PrivateKeyEntry) entry;
}
private Cipher getCipher() throws Exception {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL"); // error in android 6: InvalidKeyException: Need RSA private or public key
} else {
return Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidKeyStoreBCWorkaround"); // error in android 5: NoSuchProviderException: Provider not available: AndroidKeyStoreBCWorkaround
}
}
private void createKeysIfNeeded(Context context) throws Exception {
KeyStore ks = KeyStore.getInstance(KEYSTORE_PROVIDER_ANDROID);
ks.load(null);
KeyStore.Entry entry = ks.getEntry(KEY_ALIAS, null);
if (entry == null) {
createKeys(context);
}
}
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private void createKeys(Context context) throws Exception {
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.add(Calendar.YEAR, 25);
KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(TYPE_RSA, KEYSTORE_PROVIDER_ANDROID);
AlgorithmParameterSpec spec;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
//noinspection deprecation
spec = new android.security.KeyPairGeneratorSpec.Builder(context)
.setAlias(KEY_ALIAS)
.setSubject(new X500Principal("CN=" + KEY_ALIAS))
.setSerialNumber(BigInteger.valueOf(1))
.setStartDate(start.getTime())
.setEndDate(end.getTime())
.build();
} else {
spec = new KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT)
.setCertificateSubject(new X500Principal("CN=" + KEY_ALIAS))
.setDigests(KeyProperties.DIGEST_SHA256)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.setCertificateSerialNumber(BigInteger.valueOf(1))
.setCertificateNotBefore(start.getTime())
.setCertificateNotAfter(end.getTime())
.build();
}
kpGenerator.initialize(spec);
kpGenerator.generateKeyPair();
}
static public boolean isAvailable() {
return Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2;
}
}
| android/src/main/java/com/it_nomads/fluttersecurestorage/ciphers/StorageCipher18Implementation.java | package com.it_nomads.fluttersecurestorage.ciphers;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import java.math.BigInteger;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Calendar;
import javax.crypto.Cipher;
import javax.security.auth.x500.X500Principal;
public class StorageCipher18Implementation implements StorageCipher {
private static final String KEY_ALIAS = "FlutterSecureStoragePluginKey";
private static final String KEYSTORE_PROVIDER_ANDROID = "AndroidKeyStore";
private static final String TYPE_RSA = "RSA";
public StorageCipher18Implementation(Context context) throws Exception {
createKeysIfNeeded(context);
}
@Override
public byte[] encrypt(byte[] input) throws Exception {
PublicKey publicKey = getEntry().getCertificate().getPublicKey();
Cipher cipher = getCipher();
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(input);
}
@Override
public byte[] decrypt(byte[] input) throws Exception {
PrivateKey privateKey = getEntry().getPrivateKey();
Cipher cipher = getCipher();
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(input);
}
private KeyStore.PrivateKeyEntry getEntry() throws Exception {
KeyStore ks = KeyStore.getInstance(KEYSTORE_PROVIDER_ANDROID);
ks.load(null);
KeyStore.Entry entry = ks.getEntry(KEY_ALIAS, null);
if (entry == null) {
throw new Exception("No key found under alias: " + KEY_ALIAS);
}
if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
throw new Exception("Not an instance of a PrivateKeyEntry");
}
return (KeyStore.PrivateKeyEntry) entry;
}
private Cipher getCipher() throws Exception {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL"); // error in android 6: InvalidKeyException: Need RSA private or public key
} else {
return Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidKeyStoreBCWorkaround"); // error in android 5: NoSuchProviderException: Provider not available: AndroidKeyStoreBCWorkaround
}
}
private void createKeysIfNeeded(Context context) throws Exception {
KeyStore ks = KeyStore.getInstance(KEYSTORE_PROVIDER_ANDROID);
ks.load(null);
KeyStore.Entry entry = ks.getEntry(KEY_ALIAS, null);
if (entry == null) {
createKeys(context);
}
}
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private void createKeys(Context context) throws Exception {
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.add(Calendar.YEAR, 25);
KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(TYPE_RSA, KEYSTORE_PROVIDER_ANDROID);
AlgorithmParameterSpec spec;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
//noinspection deprecation
spec = new android.security.KeyPairGeneratorSpec.Builder(context)
.setAlias(KEY_ALIAS)
.setSubject(new X500Principal("CN=" + KEY_ALIAS))
.setSerialNumber(BigInteger.valueOf(1))
.setStartDate(start.getTime())
.setEndDate(end.getTime())
.build();
} else {
spec = new KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT)
.setCertificateSubject(new X500Principal("CN=" + KEY_ALIAS))
.setDigests(KeyProperties.DIGEST_SHA256)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.setCertificateSerialNumber(BigInteger.valueOf(1))
.setCertificateNotBefore(start.getTime())
.setCertificateNotAfter(end.getTime())
.build();
}
kpGenerator.initialize(spec);
kpGenerator.generateKeyPair();
}
static public boolean isAvailable() {
return Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2;
}
}
| Fixed KEY_ALIAS for Android 4.4.2.
| android/src/main/java/com/it_nomads/fluttersecurestorage/ciphers/StorageCipher18Implementation.java | Fixed KEY_ALIAS for Android 4.4.2. |
|
Java | mit | 4508f30f84e78bdbbe7d3a88a6773d26cf8ccb52 | 0 | dtm/ProvToolbox,dtm/ProvToolbox,joansmith/ProvToolbox,joansmith/ProvToolbox,joansmith/ProvToolbox,dtm/ProvToolbox,joansmith/ProvToolbox | package org.openprovenance.prov.xml;
import java.io.File;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.net.URI;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
import junit.framework.TestCase;
/**
* Unit test for PROV roundtrip conversion between Java and XML
*/
public class RoundTripFromJavaTest extends TestCase {
public static final String EX_NS = "http://example.org/";
public static final String EX2_NS = "http://example2.org/";
public static final String EX_PREFIX = "ex";
public static final String EX2_PREFIX = "ex2";
public static final String EX3_NS = "http://example3.org/";
static final ProvUtilities util=new ProvUtilities();
static final Hashtable<String, String> namespaces;
public static ProvFactory pFactory;
public static ValueConverter vconv;
static Hashtable<String, String> updateNamespaces (Hashtable<String, String> nss) {
nss.put(EX_PREFIX, EX_NS);
nss.put(EX2_PREFIX, EX2_NS);
nss.put("_", EX3_NS);
return nss;
}
static void setNamespaces() {
pFactory.resetNamespaces();
pFactory.getNss().putAll(updateNamespaces(new Hashtable<String, String>()));
}
static {
namespaces = updateNamespaces(new Hashtable<String, String>());
pFactory = new ProvFactory(namespaces);
vconv=new ValueConverter(pFactory);
}
private DocumentEquality documentEquality;
/**
* Create the test case
*
* @param testName
* name of the test case
*/
public RoundTripFromJavaTest(String testName) {
super(testName);
this.documentEquality = new DocumentEquality(mergeDuplicateProperties());
}
public boolean urlFlag = true;
/**
* @return the suite of tests being tested
*/
public void updateNamespaces(Document doc) {
Hashtable<String, String> nss = new Hashtable<String, String>();
updateNamespaces(nss);
doc.setNss(nss);
}
public String extension() {
return ".xml";
}
public void makeDocAndTest(Statement stment, String file) {
makeDocAndTest(stment, file, null, true);
}
public void makeDocAndTest(Statement stment, String file, boolean check) {
makeDocAndTest(stment, file, null, check);
}
public void makeDocAndTest(Statement stment, Statement[] opt, String file) {
makeDocAndTest(stment, file, opt, true);
}
public void makeDocAndTest(Statement [] stment, Statement[] opt, String file) {
makeDocAndTest(stment, file, opt, true);
}
public void makeDocAndTest(Statement stment, String file, Statement[] opt, boolean check) {
makeDocAndTest(new Statement[] {stment}, file, opt, check);
}
public void makeDocAndTest(Statement []stment, String file, Statement[] opt, boolean check) {
makeDocAndTest(stment, null, file, opt, check);
}
public void makeDocAndTest(Statement []stment, NamedBundle[] bundles, String file, Statement[] opt, boolean check) {
Document doc = pFactory.newDocument();
for (int i=0; i< stment.length; i++) {
doc.getEntityAndActivityAndWasGeneratedBy().add(stment[i]);
}
if (bundles!=null) {
for (int j=0; j<bundles.length; j++) {
doc.getEntityAndActivityAndWasGeneratedBy().add(bundles[j]);
}
}
updateNamespaces(doc);
String file1=(opt==null) ? file : file+"-S";
compareDocAndFile(doc, file1, check);
if (opt!=null) {
String file2=file+"-M";
doc.getEntityAndActivityAndWasGeneratedBy().addAll(Arrays.asList(opt));
compareDocAndFile(doc, file2, check);
}
}
public void compareDocAndFile(Document doc, String file, boolean check) {
file=file+extension();
writeDocument(doc, file);
Document doc3=readDocument(file);
compareDocuments(doc, doc3, check && checkTest(file));
}
public Document readDocument(String file1) {
try {
return readXMLDocument(file1);
} catch (JAXBException e) {
throw new UncheckedTestException(e);
}
}
public void writeDocument(Document doc, String file2) {
try {
writeXMLDocument(doc, file2);
} catch (JAXBException e) {
throw new UncheckedTestException(e);
}
}
public void compareDocuments(Document doc, Document doc2, boolean check) {
assertTrue("self doc equality", doc.equals(doc));
assertTrue("self doc2 equality", doc2.equals(doc2));
if (check) {
boolean result=this.documentEquality.check(doc, doc2);
if (!result) {
System.out.println("Pre-write graph: "+doc);
System.out.println("Read graph: "+doc2);
}
assertTrue("doc equals doc2", result);
} else {
assertFalse("doc distinct from doc2", doc.equals(doc2));
}
}
public boolean checkTest(String name) {
// all tests successful in this file
return true;
}
public boolean mergeDuplicateProperties() {
return false;
}
public Document readXMLDocument(String file) throws javax.xml.bind.JAXBException {
ProvDeserialiser deserial = ProvDeserialiser
.getThreadProvDeserialiser();
Document c = deserial.deserialiseDocument(new File(file));
return c;
}
public void writeXMLDocument(Document doc, String file) throws JAXBException {
ProvSerialiser serial = ProvSerialiser.getThreadProvSerialiser();
serial.serialiseDocument(new File(file), doc, true);
StringWriter sw = new StringWriter();
serial.serialiseDocument(sw, doc, true);
//System.out.println(sw.toString());
}
///////////////////////////////////////////////////////////////////////
public void addLabel(HasLabel hl) {
hl.getLabel().add(pFactory.newInternationalizedString("hello"));
}
public void addLabels(HasLabel hl) {
hl.getLabel().add(pFactory.newInternationalizedString("hello"));
hl.getLabel().add(pFactory.newInternationalizedString("bye","EN"));
hl.getLabel().add(pFactory.newInternationalizedString("bonjour","FR"));
}
public void addTypes(HasType ht) {
ht.getType().add("a");
ht.getType().add(1);
ht.getType().add(1.0);
ht.getType().add(true);
ht.getType().add(new QName(EX_NS, "abc", EX_PREFIX));
ht.getType().add(pFactory.newTimeNow());
URIWrapper w=new URIWrapper();
w.setValue(URI.create(EX_NS+"hello"));
ht.getType().add(w);
}
public void addLocations(HasLocation hl) {
hl.getLocation().add("London");
hl.getLocation().add(1);
hl.getLocation().add(1.0);
hl.getLocation().add(true);
hl.getLocation().add(new QName(EX_NS, "london", EX_PREFIX));
hl.getLocation().add(pFactory.newTimeNow());
URIWrapper w=new URIWrapper();
w.setValue(URI.create(EX_NS+"london"));
hl.getLocation().add(w);
hl.getLocation().add(pFactory.newGYear("2002"));
}
public void addValue(HasValue hl) {
hl.setValue(new QName(EX_NS, "avalue", EX_PREFIX));
}
public void addFurtherAttributes(HasExtensibility he) {
he.getAny().add(pFactory.newAttribute(EX_NS,"tag1",EX_PREFIX,"hello", vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "bye", vconv));
//he.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, pFactory.newInternationalizedString("bonjour","fr"), "xsd:string"));
he.getAny().add(pFactory.newAttribute(EX2_NS,"tag3",EX2_PREFIX, "hi", vconv));
}
public void addFurtherAttributes0(HasExtensibility he) {
he.getAny().add(pFactory.newAttribute(EX_NS,"tag1",EX_PREFIX,"hello", vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "bye", vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, pFactory.newInternationalizedString("bonjour","fr"), ValueConverter.QNAME_XSD_STRING));
he.getAny().add(pFactory.newAttribute(EX2_NS,"tag3",EX2_PREFIX, "hi", vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new Integer(1), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new Long(1), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new Short((short) 1), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new Double(1.0), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new Float(1.0), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new java.math.BigDecimal(1.0), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new Boolean(true), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new Byte((byte) 123), vconv));
addFurtherAttributesWithQNames(he);
URIWrapper w=new URIWrapper();
w.setValue(URI.create(EX_NS+"london"));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, w, vconv));
}
///////////////////////////////////////////////////////////////////////
public void addFurtherAttributesWithQNames(HasExtensibility he) {
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new QName(EX2_NS,"newyork", EX2_PREFIX), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new QName(EX_NS, "london", EX_PREFIX), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new QName(EX3_NS, "london"), vconv));
}
public void testEntity0() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e0");
a.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, pFactory.newInternationalizedString("bonjour","fr"), ValueConverter.QNAME_XSD_STRING));
makeDocAndTest(a,"target/entity0");
}
public void testEntity1() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e1");
makeDocAndTest(a,"target/entity1");
}
public void testEntity2() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e2", "entity2");
makeDocAndTest(a,"target/entity2");
}
public void testEntity3() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e3", "entity3");
addValue(a);
makeDocAndTest(a,"target/entity3");
}
public void testEntity4() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e4", "entity4");
addLabels(a);
makeDocAndTest(a,"target/entity4");
}
public void testEntity5() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e5", "entity5");
addTypes(a);
makeDocAndTest(a,"target/entity5");
}
public void testEntity6() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e6", "entity6");
addLocations(a);
makeDocAndTest(a,"target/entity6");
}
public void testEntity7() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e7", "entity7");
addTypes(a);
addLocations(a);
addLabels(a);
makeDocAndTest(a,"target/entity7");
}
public void testEntity8() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e8", "entity8");
addTypes(a);
addTypes(a);
addLocations(a);
addLocations(a);
addLabels(a);
addLabels(a);
makeDocAndTest(a,"target/entity8");
}
public void testEntity9() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e9", "entity9");
addTypes(a);
addLocations(a);
addLabels(a);
addFurtherAttributes(a);
makeDocAndTest(a,"target/entity9");
}
public void testEntity10() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e10", "entity10");
addTypes(a);
addLocations(a);
addLabels(a);
addFurtherAttributes(a);
makeDocAndTest(a,"target/entity10");
}
///////////////////////////////////////////////////////////////////////
public void testActivity1() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a1");
makeDocAndTest(a,"target/activity1");
}
public void testActivity2() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a2", "activity2");
makeDocAndTest(a,"target/activity2");
}
public void testActivity3() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a1");
a.setStartTime(pFactory.newTimeNow());
a.setEndTime(pFactory.newTimeNow());
makeDocAndTest(a,"target/activity3");
}
public void testActivity4() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a2", "activity2");
addLabels(a);
makeDocAndTest(a,"target/activity4");
}
public void testActivity5() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a2", "activity2");
addTypes(a);
makeDocAndTest(a,"target/activity5");
}
public void testActivity6() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a6", "activity6");
addLocations(a);
makeDocAndTest(a,"target/activity6");
}
public void testActivity7() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a7", "activity7");
addTypes(a);
addLocations(a);
addLabels(a);
makeDocAndTest(a,"target/activity7");
}
public void testActivity8() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a8", "activity8");
a.setStartTime(pFactory.newTimeNow());
a.setEndTime(pFactory.newTimeNow());
addTypes(a);
addTypes(a);
addLocations(a);
addLocations(a);
addLabels(a);
addLabels(a);
makeDocAndTest(a,"target/activity8");
}
public void testActivity9() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a9", "activity9");
addTypes(a);
addLocations(a);
addLabels(a);
addFurtherAttributes(a);
makeDocAndTest(a,"target/activity9");
}
///////////////////////////////////////////////////////////////////////
public void testAgent1() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag1");
makeDocAndTest(a,"target/agent1");
}
public void testAgent2() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag2", "agent2");
makeDocAndTest(a,"target/agent2");
}
public void testAgent3() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag2", "agent2");
a.getLabel().add(pFactory.newInternationalizedString("hello"));
makeDocAndTest(a,"target/agent3");
}
public void testAgent4() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag2", "agent2");
a.getLabel().add(pFactory.newInternationalizedString("hello"));
a.getLabel().add(pFactory.newInternationalizedString("bye","EN"));
makeDocAndTest(a,"target/agent4");
}
public void testAgent5() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag2", "agent2");
a.getLabel().add(pFactory.newInternationalizedString("hello"));
a.getLabel().add(pFactory.newInternationalizedString("bye","EN"));
a.getLabel().add(pFactory.newInternationalizedString("bonjour","FR"));
makeDocAndTest(a,"target/agent5");
}
public void testAgent6() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag6", "agent6");
a.getType().add("a");
a.getType().add(1);
a.getType().add(1.0);
a.getType().add(true);
a.getType().add(new QName(EX_NS, "abc", EX_PREFIX));
a.getType().add(pFactory.newTimeNow());
URIWrapper w=new URIWrapper();
w.setValue(URI.create(EX_NS+"hello"));
a.getType().add(w);
makeDocAndTest(a,"target/agent6");
}
public void testAgent7() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag7", "agent7");
pFactory.addType(a,"a");
pFactory.addType(a,1);
pFactory.addType(a,1.0);
pFactory.addType(a,true);
pFactory.addType(a,new QName(EX_NS, "abc", EX_PREFIX));
pFactory.addType(a,pFactory.newTimeNow());
pFactory.addType(a,URI.create(EX_NS+"hello"));
a.getLabel().add(pFactory.newInternationalizedString("hello"));
a.getLabel().add(pFactory.newInternationalizedString("bye","EN"));
a.getLabel().add(pFactory.newInternationalizedString("bonjour","FR"));
a.getLocation().add("London");
a.getLocation().add(1);
a.getLocation().add(1.0);
a.getLocation().add(true);
a.getLocation().add(new QName(EX_NS, "london", EX_PREFIX));
a.getLocation().add(pFactory.newTimeNow());
URIWrapper w=new URIWrapper();
w.setValue(URI.create(EX_NS+"london"));
a.getLocation().add(w);
makeDocAndTest(a,"target/agent7");
}
public void testAgent8() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag8", "agent8");
a.getType().add("a");
a.getType().add("a");
a.getType().add(1);
a.getType().add(1);
a.getType().add(1.0);
a.getType().add(1.0);
a.getType().add(true);
a.getType().add(true);
a.getType().add(new QName(EX_NS, "abc", EX_PREFIX));
a.getType().add(new QName(EX_NS, "abc", EX_PREFIX));
a.getType().add(pFactory.newTimeNow());
a.getType().add(pFactory.newTimeNow());
URIWrapper w=new URIWrapper();
w.setValue(URI.create(EX_NS+"hello"));
a.getType().add(w);
a.getType().add(w);
a.getLabel().add(pFactory.newInternationalizedString("hello"));
a.getLabel().add(pFactory.newInternationalizedString("hello"));
a.getLabel().add(pFactory.newInternationalizedString("bye","EN"));
a.getLabel().add(pFactory.newInternationalizedString("bye","EN"));
a.getLabel().add(pFactory.newInternationalizedString("bonjour","FR"));
a.getLabel().add(pFactory.newInternationalizedString("bonjour","FR"));
a.getLocation().add("London");
a.getLocation().add("London");
a.getLocation().add(1);
a.getLocation().add(1);
a.getLocation().add(1.0);
a.getLocation().add(1.0);
a.getLocation().add(true);
a.getLocation().add(true);
a.getLocation().add(new QName(EX_NS, "london", EX_PREFIX));
a.getLocation().add(new QName(EX_NS, "london", EX_PREFIX));
a.getLocation().add(pFactory.newTimeNow());
a.getLocation().add(pFactory.newTimeNow());
URIWrapper w2=new URIWrapper();
w2.setValue(URI.create(EX_NS+"london"));
a.getLocation().add(w2);
a.getLocation().add(w2);
makeDocAndTest(a,"target/agent8");
}
///////////////////////////////////////////////////////////////////////
public QName q(String n) {
return new QName(EX_NS, n, EX_PREFIX);
}
public void testGeneration1() throws JAXBException {
setNamespaces();
WasGeneratedBy gen = pFactory.newWasGeneratedBy(q("gen1"),
pFactory.newEntityRef(q("e1")),
null,
null);
makeDocAndTest(gen, "target/generation1");
}
public void testGeneration2() throws JAXBException {
setNamespaces();
WasGeneratedBy gen = pFactory.newWasGeneratedBy(q("gen2"),
pFactory.newEntityRef(q("e1")),
null,
pFactory.newActivityRef(q("a1")));
makeDocAndTest(gen, "target/generation2");
}
public void testGeneration3() throws JAXBException {
setNamespaces();
WasGeneratedBy gen = pFactory.newWasGeneratedBy(q("gen3"),
pFactory.newEntityRef(q("e1")),
"somerole",
pFactory.newActivityRef(q("a1")));
gen.getRole().add("otherRole");
makeDocAndTest(gen,"target/generation3");
}
public void testGeneration4() throws JAXBException {
setNamespaces();
WasGeneratedBy gen = pFactory.newWasGeneratedBy(q("gen4"),
pFactory.newEntityRef(q("e1")),
"somerole",
pFactory.newActivityRef(q("a1")));
gen.setTime(pFactory.newTimeNow());
makeDocAndTest(gen,"target/generation4");
}
public void testGeneration5() throws JAXBException {
setNamespaces();
WasGeneratedBy gen = pFactory.newWasGeneratedBy(q("gen4"),
pFactory.newEntityRef(q("e1")),
"somerole",
pFactory.newActivityRef(q("a1")));
gen.setTime(pFactory.newTimeNow());
addTypes(gen);
addLocations(gen);
addLabels(gen);
addFurtherAttributes(gen);
makeDocAndTest(gen,"target/generation5");
}
public void testGeneration6() throws JAXBException {
setNamespaces();
WasGeneratedBy gen = pFactory.newWasGeneratedBy((QName)null,
pFactory.newEntityRef(q("e1")),
null,
pFactory.newActivityRef(q("a1")));
makeDocAndTest(gen,"target/generation6");
}
public void testGeneration7() throws JAXBException {
setNamespaces();
WasGeneratedBy gen = pFactory.newWasGeneratedBy((QName)null,
pFactory.newEntityRef(q("e1")),
"somerole",
pFactory.newActivityRef(q("a1")));
gen.setTime(pFactory.newTimeNow());
addTypes(gen);
addLocations(gen);
addLabels(gen);
addFurtherAttributes(gen);
makeDocAndTest(gen,"target/generation7");
}
//////////////////////////////////
public void testUsage1() throws JAXBException {
setNamespaces();
Used use = pFactory.newUsed(q("use1"),
null,
null,
pFactory.newEntityRef(q("e1")));
makeDocAndTest(use,"target/usage1");
}
public void testUsage2() throws JAXBException {
setNamespaces();
Used use = pFactory.newUsed(q("use2"),
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
makeDocAndTest(use,"target/usage2");
}
public void testUsage3() throws JAXBException {
setNamespaces();
Used use = pFactory.newUsed(q("use3"),
pFactory.newActivityRef(q("a1")),
"somerole",
pFactory.newEntityRef(q("e1")));
use.getRole().add("otherRole");
makeDocAndTest(use,"target/usage3");
}
public void testUsage4() throws JAXBException {
setNamespaces();
Used use = pFactory.newUsed(q("use4"),
pFactory.newActivityRef(q("a1")),
"somerole",
pFactory.newEntityRef(q("e1")));
use.setTime(pFactory.newTimeNow());
makeDocAndTest(use,"target/usage4");
}
public void testUsage5() throws JAXBException {
setNamespaces();
Used use = pFactory.newUsed(q("use4"),
pFactory.newActivityRef(q("a1")),
"somerole",
pFactory.newEntityRef(q("e1")));
use.setTime(pFactory.newTimeNow());
addTypes(use);
addLocations(use);
addLabels(use);
addFurtherAttributes(use);
makeDocAndTest(use,"target/usage5");
}
public void testUsage6() throws JAXBException {
setNamespaces();
Used use = pFactory.newUsed((QName)null,
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
makeDocAndTest(use,"target/usage6");
}
public void testUsage7() throws JAXBException {
setNamespaces();
Used use = pFactory.newUsed((QName)null,
pFactory.newActivityRef(q("a1")),
"somerole",
pFactory.newEntityRef(q("e1")));
use.setTime(pFactory.newTimeNow());
addTypes(use);
addLocations(use);
addLabels(use);
addFurtherAttributes(use);
makeDocAndTest(use,"target/usage7");
}
// //////////////////////////////////////////////
public void testInvalidation1() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv = pFactory.newWasInvalidatedBy(q("inv1"),
pFactory.newEntityRef(q("e1")),
null);
makeDocAndTest(inv, "target/invalidation1");
}
public void testInvalidation2() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv = pFactory.newWasInvalidatedBy(q("inv2"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
makeDocAndTest(inv, "target/invalidation2");
}
public void testInvalidation3() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv = pFactory.newWasInvalidatedBy(q("inv3"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv.getRole().add("someRole");
inv.getRole().add("otherRole");
makeDocAndTest(inv, "target/invalidation3");
}
public void testInvalidation4() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv = pFactory.newWasInvalidatedBy(q("inv4"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv.getRole().add("someRole");
inv.setTime(pFactory.newTimeNow());
makeDocAndTest(inv, "target/invalidation4");
}
public void testInvalidation5() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv = pFactory.newWasInvalidatedBy(q("inv4"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv.getRole().add("someRole");
inv.setTime(pFactory.newTimeNow());
addTypes(inv);
addLocations(inv);
addLabels(inv);
addFurtherAttributes(inv);
makeDocAndTest(inv, "target/invalidation5");
}
public void testInvalidation6() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv = pFactory.newWasInvalidatedBy((QName) null,
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
makeDocAndTest(inv, "target/invalidation6");
}
public void testInvalidation7() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv = pFactory.newWasInvalidatedBy((QName) null,
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv.getRole().add("someRole");
inv.setTime(pFactory.newTimeNow());
addTypes(inv);
addLocations(inv);
addLabels(inv);
addFurtherAttributes(inv);
makeDocAndTest(inv, "target/invalidation7");
}
//////////////////////////////////
public void testStart1() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start1"),
null,
pFactory.newEntityRef(q("e1")));
makeDocAndTest(start, "target/start1");
}
public void testStart2() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start2"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(start, "target/start2");
}
public void testStart3() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start3"),
pFactory.newActivityRef(q("a1")),
null);
makeDocAndTest(start, "target/start3");
}
public void testStart4() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start4"),
null,
pFactory.newEntityRef(q("e1")));
start.setStarter(pFactory.newActivityRef(q("a2")));
makeDocAndTest(start, "target/start4");
}
public void testStart5() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start5"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start.setStarter(pFactory.newActivityRef(q("a2")));
makeDocAndTest(start, "target/start5");
}
public void testStart6() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start6"),
pFactory.newActivityRef(q("a1")),
null);
start.setStarter(pFactory.newActivityRef(q("a2")));
makeDocAndTest(start, "target/start6");
}
public void testStart7() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start7"),
pFactory.newActivityRef(q("a1")),
null);
start.setStarter(pFactory.newActivityRef(q("a2")));
start.setTime(pFactory.newTimeNow());
makeDocAndTest(start, "target/start7");
}
public void testStart8() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start8"),
pFactory.newActivityRef(q("a1")),
null);
start.setStarter(pFactory.newActivityRef(q("a2")));
start.setTime(pFactory.newTimeNow());
start.getRole().add("someRole");
start.getRole().add("otherRole");
addTypes(start);
addLocations(start);
addLabels(start);
addFurtherAttributes(start);
makeDocAndTest(start, "target/start8");
}
public void testStart9() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy((QName)null,
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(start, "target/start9");
}
public void testStart10() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy((QName)null,
pFactory.newActivityRef(q("a1")),
null);
start.setStarter(pFactory.newActivityRef(q("a2")));
start.setTime(pFactory.newTimeNow());
start.getRole().add("someRole");
start.getRole().add("otherRole");
addTypes(start);
addLocations(start);
addLabels(start);
addFurtherAttributes(start);
makeDocAndTest(start, "target/start10");
}
// ////////////////////////////////
public void testEnd1() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end1"), null,
pFactory.newEntityRef(q("e1")));
makeDocAndTest(end, "target/end1");
}
public void testEnd2() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end2"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(end, "target/end2");
}
public void testEnd3() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end3"),
pFactory.newActivityRef(q("a1")),
null);
makeDocAndTest(end, "target/end3");
}
public void testEnd4() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end4"), null,
pFactory.newEntityRef(q("e1")));
end.setEnder(pFactory.newActivityRef(q("a2")));
makeDocAndTest(end, "target/end4");
}
public void testEnd5() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end5"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end.setEnder(pFactory.newActivityRef(q("a2")));
makeDocAndTest(end, "target/end5");
}
public void testEnd6() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end6"),
pFactory.newActivityRef(q("a1")),
null);
end.setEnder(pFactory.newActivityRef(q("a2")));
makeDocAndTest(end, "target/end6");
}
public void testEnd7() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end7"),
pFactory.newActivityRef(q("a1")),
null);
end.setEnder(pFactory.newActivityRef(q("a2")));
end.setTime(pFactory.newTimeNow());
makeDocAndTest(end, "target/end7");
}
public void testEnd8() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end8"),
pFactory.newActivityRef(q("a1")),
null);
end.setEnder(pFactory.newActivityRef(q("a2")));
end.setTime(pFactory.newTimeNow());
end.getRole().add("someRole");
end.getRole().add("otherRole");
addTypes(end);
addLocations(end);
addLabels(end);
addFurtherAttributes(end);
makeDocAndTest(end, "target/end8");
}
public void testEnd9() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy((QName) null,
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(end, "target/end9");
}
public void testEnd10() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy((QName) null,
pFactory.newActivityRef(q("a1")),
null);
end.setEnder(pFactory.newActivityRef(q("a2")));
end.setTime(pFactory.newTimeNow());
end.getRole().add("someRole");
end.getRole().add("otherRole");
addTypes(end);
addLocations(end);
addLabels(end);
addFurtherAttributes(end);
makeDocAndTest(end, "target/end10");
}
// ////////////////////////////////
public void testDerivation1() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der1"),
null,
pFactory.newEntityRef(q("e1")));
makeDocAndTest(der, "target/derivation1");
}
public void testDerivation2() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der2"),
pFactory.newEntityRef(q("e2")),
null);
makeDocAndTest(der, "target/derivation2");
}
public void testDerivation3() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der3"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(der, "target/derivation3");
}
public void testDerivation4() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der4"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
addLabel(der);
makeDocAndTest(der, "target/derivation4");
}
public void testDerivation5() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der5"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
der.setActivity(pFactory.newActivityRef(q("a")));
makeDocAndTest(der, "target/derivation5");
}
public void testDerivation6() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der6"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
der.setActivity(pFactory.newActivityRef(q("a")));
der.setUsage(pFactory.newUsageRef(q("u")));
makeDocAndTest(der, "target/derivation6");
}
public void testDerivation7() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der7"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
der.setActivity(pFactory.newActivityRef(q("a")));
der.setUsage(pFactory.newUsageRef(q("u")));
der.setGeneration(pFactory.newGenerationRef(q("g")));
makeDocAndTest(der, "target/derivation7");
}
public void testDerivation8() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der8"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
addLabel(der);
addTypes(der);
addFurtherAttributes(der);
makeDocAndTest(der, "target/derivation8");
}
public void testDerivation9() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom((QName)null,
pFactory.newEntityRef(q("e2")),
null);
addTypes(der);
makeDocAndTest(der, "target/derivation9");
}
public void testDerivation10() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom((QName)null,
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
der.setActivity(pFactory.newActivityRef(q("a")));
der.setUsage(pFactory.newUsageRef(q("u")));
der.setGeneration(pFactory.newGenerationRef(q("g")));
makeDocAndTest(der, "target/derivation10");
}
public void testDerivation11() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("rev1"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
der.setActivity(pFactory.newActivityRef(q("a")));
der.setUsage(pFactory.newUsageRef(q("u")));
der.setGeneration(pFactory.newGenerationRef(q("g")));
pFactory.addRevisionType(der);
makeDocAndTest(der, "target/derivation11");
}
public void testDerivation12() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("quo1"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
der.setActivity(pFactory.newActivityRef(q("a")));
der.setUsage(pFactory.newUsageRef(q("u")));
der.setGeneration(pFactory.newGenerationRef(q("g")));
pFactory.addQuotationType(der);
makeDocAndTest(der, "target/derivation12");
}
public void testDerivation13() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("prim1"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
der.setActivity(pFactory.newActivityRef(q("a")));
der.setUsage(pFactory.newUsageRef(q("u")));
der.setGeneration(pFactory.newGenerationRef(q("g")));
pFactory.addPrimarySourceType(der);
makeDocAndTest(der, "target/derivation13");
}
// ////////////////////////////////
public void testAssociation1() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc1"),
pFactory.newActivityRef(q("a1")),
null);
makeDocAndTest(assoc, "target/association1");
}
public void testAssociation2() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc2"),
null,
pFactory.newAgentRef(q("ag1")));
makeDocAndTest(assoc, "target/association2");
}
public void testAssociation3() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc3"),
pFactory.newActivityRef(q("a1")),
pFactory.newAgentRef(q("ag1")));
makeDocAndTest(assoc, "target/association3");
}
public void testAssociation4() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc4"),
pFactory.newActivityRef(q("a1")),
pFactory.newAgentRef(q("ag1")));
assoc.setPlan(pFactory.newEntityRef(q("plan1")));
makeDocAndTest(assoc, "target/association4");
}
public void testAssociation5() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith((QName)null,
pFactory.newActivityRef(q("a1")),
pFactory.newAgentRef(q("ag1")));
makeDocAndTest(assoc, "target/association5");
}
public void testAssociation6() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc6"),
pFactory.newActivityRef(q("a1")),
pFactory.newAgentRef(q("ag1")));
assoc.setPlan(pFactory.newEntityRef(q("plan1")));
addLabels(assoc);
makeDocAndTest(assoc, "target/association6");
}
public void testAssociation7() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc7"),
pFactory.newActivityRef(q("a1")),
pFactory.newAgentRef(q("ag1")));
assoc.setPlan(pFactory.newEntityRef(q("plan1")));
addLabels(assoc);
addTypes(assoc);
makeDocAndTest(assoc, "target/association7");
}
public void testAssociation8() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc8"),
pFactory.newActivityRef(q("a1")),
pFactory.newAgentRef(q("ag1")));
assoc.setPlan(pFactory.newEntityRef(q("plan1")));
assoc.getRole().add("someRole");
assoc.getRole().add("someOtherRole");
makeDocAndTest(assoc, "target/association8");
}
public void testAssociation9() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc9"),
pFactory.newActivityRef(q("a1")),
pFactory.newAgentRef(q("ag1")));
assoc.setPlan(pFactory.newEntityRef(q("plan1")));
addLabels(assoc);
addTypes(assoc);
addFurtherAttributes(assoc);
makeDocAndTest(assoc, "target/association9");
}
// ////////////////////////////////
public void testAttribution1() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo(q("attr1"),
pFactory.newEntityRef(q("e1")),
null);
makeDocAndTest(attr, "target/attribution1");
}
public void testAttribution2() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo(q("attr2"),
null,
pFactory.newAgentRef(q("ag1")));
makeDocAndTest(attr, "target/attribution2");
}
public void testAttribution3() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo(q("attr3"),
pFactory.newEntityRef(q("e1")),
pFactory.newAgentRef(q("ag1")));
makeDocAndTest(attr, "target/attribution3");
}
public void testAttribution4() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo(q("attr4"),
pFactory.newEntityRef(q("e1")),
pFactory.newAgentRef(q("ag1")));
makeDocAndTest(attr, "target/attribution4");
}
public void testAttribution5() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo((QName)null,
pFactory.newEntityRef(q("e1")),
pFactory.newAgentRef(q("ag1")));
makeDocAndTest(attr, "target/attribution5");
}
public void testAttribution6() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo(q("attr6"),
pFactory.newEntityRef(q("e1")),
pFactory.newAgentRef(q("ag1")));
addLabels(attr);
makeDocAndTest(attr, "target/attribution6");
}
public void testAttribution7() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo(q("attr7"),
pFactory.newEntityRef(q("e1")),
pFactory.newAgentRef(q("ag1")));
addLabels(attr);
addTypes(attr);
makeDocAndTest(attr, "target/attribution7");
}
public void testAttribution8() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo(q("attr8"),
pFactory.newEntityRef(q("e1")),
pFactory.newAgentRef(q("ag1")));
addLabels(attr);
addTypes(attr);
addFurtherAttributes(attr);
makeDocAndTest(attr, "target/attribution8");
}
// ////////////////////////////////
public void testDelegation1() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf(q("del1"),
pFactory.newAgentRef(q("e1")),
null,
null);
makeDocAndTest(del, "target/delegation1");
}
public void testDelegation2() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf(q("del2"),
null,
pFactory.newAgentRef(q("ag1")),
null);
makeDocAndTest(del, "target/delegation2");
}
public void testDelegation3() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf(q("del3"),
pFactory.newAgentRef(q("e1")),
pFactory.newAgentRef(q("ag1")),
null);
makeDocAndTest(del, "target/delegation3");
}
public void testDelegation4() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf(q("del4"),
pFactory.newAgentRef(q("e1")),
pFactory.newAgentRef(q("ag1")),
pFactory.newActivityRef(q("a")));
makeDocAndTest(del, "target/delegation4");
}
public void testDelegation5() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf((QName)null,
pFactory.newAgentRef(q("e1")),
pFactory.newAgentRef(q("ag1")),
null);
makeDocAndTest(del, "target/delegation5");
}
public void testDelegation6() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf(q("del6"),
pFactory.newAgentRef(q("e1")),
pFactory.newAgentRef(q("ag1")),
pFactory.newActivityRef(q("a")));
addLabels(del);
makeDocAndTest(del, "target/delegation6");
}
public void testDelegation7() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf(q("del7"),
pFactory.newAgentRef(q("e1")),
pFactory.newAgentRef(q("ag1")),
pFactory.newActivityRef(q("a")));
addLabels(del);
addTypes(del);
makeDocAndTest(del, "target/delegation7");
}
public void testDelegation8() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf(q("del8"),
pFactory.newAgentRef(q("e1")),
pFactory.newAgentRef(q("ag1")),
pFactory.newActivityRef(q("a")));
addLabels(del);
addTypes(del);
addFurtherAttributes(del);
makeDocAndTest(del, "target/delegation8");
}
// ////////////////////////////////
public void testCommunication1() throws JAXBException {
setNamespaces();
WasInformedBy inf = pFactory.newWasInformedBy(q("inf1"),
pFactory.newActivityRef(q("a2")),
null);
makeDocAndTest(inf, "target/communication1");
}
public void testCommunication2() throws JAXBException {
setNamespaces();
WasInformedBy inf = pFactory.newWasInformedBy(q("inf2"),
null,
pFactory.newActivityRef(q("a1")));
makeDocAndTest(inf, "target/communication2");
}
public void testCommunication3() throws JAXBException {
setNamespaces();
WasInformedBy inf = pFactory.newWasInformedBy(q("inf3"),
pFactory.newActivityRef(q("a2")),
pFactory.newActivityRef(q("a1")));
makeDocAndTest(inf, "target/communication3");
}
public void testCommunication4() throws JAXBException {
setNamespaces();
WasInformedBy inf = pFactory.newWasInformedBy((QName)null,
pFactory.newActivityRef(q("a2")),
pFactory.newActivityRef(q("a1")));
makeDocAndTest(inf, "target/communication4");
}
public void testCommunication5() throws JAXBException {
setNamespaces();
WasInformedBy inf = pFactory.newWasInformedBy(q("inf5"),
pFactory.newActivityRef(q("a2")),
pFactory.newActivityRef(q("a1")));
addLabels(inf);
makeDocAndTest(inf, "target/communication5");
}
public void testCommunication6() throws JAXBException {
setNamespaces();
WasInformedBy inf = pFactory.newWasInformedBy(q("inf6"),
pFactory.newActivityRef(q("a2")),
pFactory.newActivityRef(q("a1")));
addLabels(inf);
addTypes(inf);
makeDocAndTest(inf, "target/communication6");
}
public void testCommunication7() throws JAXBException {
setNamespaces();
WasInformedBy inf = pFactory.newWasInformedBy(q("inf7"),
pFactory.newActivityRef(q("a2")),
pFactory.newActivityRef(q("a1")));
addLabels(inf);
addTypes(inf);
addFurtherAttributes(inf);
makeDocAndTest(inf, "target/communication7");
}
// ////////////////////////////////
public void testInfluence1() throws JAXBException {
setNamespaces();
WasInfluencedBy inf = pFactory.newWasInfluencedBy(q("inf1"),
pFactory.newAnyRef(q("a2")),
null);
makeDocAndTest(inf, "target/influence1");
}
public void testInfluence2() throws JAXBException {
setNamespaces();
WasInfluencedBy inf = pFactory.newWasInfluencedBy(q("inf2"),
null,
pFactory.newAnyRef(q("a1")));
makeDocAndTest(inf, "target/influence2");
}
public void testInfluence3() throws JAXBException {
setNamespaces();
WasInfluencedBy inf = pFactory.newWasInfluencedBy(q("inf3"),
pFactory.newAnyRef(q("a2")),
pFactory.newAnyRef(q("a1")));
makeDocAndTest(inf, "target/influence3");
}
public void testInfluence4() throws JAXBException {
setNamespaces();
WasInfluencedBy inf = pFactory.newWasInfluencedBy((QName)null,
pFactory.newAnyRef(q("a2")),
pFactory.newAnyRef(q("a1")));
makeDocAndTest(inf, "target/influence4");
}
public void testInfluence5() throws JAXBException {
setNamespaces();
WasInfluencedBy inf = pFactory.newWasInfluencedBy(q("inf5"),
pFactory.newAnyRef(q("a2")),
pFactory.newAnyRef(q("a1")));
addLabels(inf);
makeDocAndTest(inf, "target/influence5");
}
public void testInfluence6() throws JAXBException {
setNamespaces();
WasInfluencedBy inf = pFactory.newWasInfluencedBy(q("inf6"),
pFactory.newAnyRef(q("a2")),
pFactory.newAnyRef(q("a1")));
addLabels(inf);
addTypes(inf);
makeDocAndTest(inf, "target/influence6");
}
public void testInfluence7() throws JAXBException {
setNamespaces();
WasInfluencedBy inf = pFactory.newWasInfluencedBy(q("inf7"),
pFactory.newAnyRef(q("a2")),
pFactory.newAnyRef(q("a1")));
addLabels(inf);
addTypes(inf);
addFurtherAttributes(inf);
makeDocAndTest(inf, "target/influence7");
}
// ////////////////////////////////
public void testAlternate1() throws JAXBException {
setNamespaces();
AlternateOf alt = pFactory.newAlternateOf(pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(alt, "target/alternate1");
}
public void testSpecialization1() throws JAXBException {
setNamespaces();
SpecializationOf spe = pFactory.newSpecializationOf(pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(spe, "target/specialization1");
}
public void testMention1() throws JAXBException {
setNamespaces();
MentionOf men = pFactory.newMentionOf(pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")),
null);
makeDocAndTest(men, "target/mention1");
}
public void testMention2() throws JAXBException {
setNamespaces();
MentionOf men = pFactory.newMentionOf(pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")),
pFactory.newEntityRef(q("b")));
makeDocAndTest(men, "target/mention2");
}
public void testMembership1() throws JAXBException {
setNamespaces();
HadMember mem = pFactory.newHadMember(pFactory.newEntityRef(q("c")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(mem, "target/member1");
}
public void testMembership2() throws JAXBException {
setNamespaces();
HadMember mem = pFactory.newHadMember(pFactory.newEntityRef(q("c")),
pFactory.newEntityRef(q("e1")),
pFactory.newEntityRef(q("e2")));
//TODO: multiple arguments not supported by toolbox
makeDocAndTest(mem, "target/member2");
}
public void testMembership3() throws JAXBException {
setNamespaces();
HadMember mem = pFactory.newHadMember(pFactory.newEntityRef(q("c")),
pFactory.newEntityRef(q("e1")),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e3")));
//TODO: multiple arguments not supported by toolbox
makeDocAndTest(mem, "target/member3");
}
public void testScruffyGeneration1() throws JAXBException {
setNamespaces();
WasGeneratedBy gen1 = pFactory.newWasGeneratedBy(q("gen1"),
pFactory.newEntityRef(q("e1")),
null,
pFactory.newActivityRef(q("a1")));
gen1.setTime(pFactory.newTimeNow());
WasGeneratedBy gen2 = pFactory.newWasGeneratedBy(q("gen1"),
pFactory.newEntityRef(q("e1")),
null,
pFactory.newActivityRef(q("a1")));
gen2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { gen1, gen2 };
makeDocAndTest(statements, opt , "target/scruffy-generation1");
}
public void testScruffyGeneration2() throws JAXBException {
setNamespaces();
WasGeneratedBy gen1 = pFactory.newWasGeneratedBy(q("gen1"),
pFactory.newEntityRef(q("e1")),
null,
pFactory.newActivityRef(q("a1")));
gen1.setTime(pFactory.newTimeNow());
gen1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
WasGeneratedBy gen2 = pFactory.newWasGeneratedBy(q("gen1"),
pFactory.newEntityRef(q("e1")),
null,
pFactory.newActivityRef(q("a1")));
gen2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
gen2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { gen1, gen2 };
makeDocAndTest(statements, opt , "target/scruffy-generation2");
}
public void testScruffyInvalidation1() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv1 = pFactory.newWasInvalidatedBy(q("inv1"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv1.setTime(pFactory.newTimeNow());
WasInvalidatedBy inv2 = pFactory.newWasInvalidatedBy(q("inv1"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { inv1, inv2 };
makeDocAndTest(statements, opt , "target/scruffy-invalidation1");
}
public void testScruffyInvalidation2() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv1 = pFactory.newWasInvalidatedBy(q("inv1"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv1.setTime(pFactory.newTimeNow());
inv1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
WasInvalidatedBy inv2 = pFactory.newWasInvalidatedBy(q("inv1"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
inv2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { inv1, inv2 };
makeDocAndTest(statements, opt , "target/scruffy-invalidation2");
}
public void testScruffyUsage1() throws JAXBException {
setNamespaces();
Used use1 = pFactory.newUsed(q("use1"),
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
use1.setTime(pFactory.newTimeNow());
Used use2 = pFactory.newUsed(q("use1"),
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
use2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { use1, use2 };
makeDocAndTest(statements, opt , "target/scruffy-usage1");
}
public void testScruffyUsage2() throws JAXBException {
setNamespaces();
Used use1 = pFactory.newUsed(q("use1"),
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
use1.setTime(pFactory.newTimeNow());
use1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
Used use2 = pFactory.newUsed(q("use1"),
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
use2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
use2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { use1, use2 };
makeDocAndTest(statements, opt , "target/scruffy-usage2");
}
public void testScruffyStart1() throws JAXBException {
setNamespaces();
WasStartedBy start1 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start1.setTime(pFactory.newTimeNow());
WasStartedBy start2 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { start1, start2 };
makeDocAndTest(statements, opt , "target/scruffy-start1");
}
public void testScruffyStart2() throws JAXBException {
setNamespaces();
WasStartedBy start1 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start1.setTime(pFactory.newTimeNow());
start1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
WasStartedBy start2 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
start2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { start1, start2 };
makeDocAndTest(statements, opt , "target/scruffy-start2");
}
public void testScruffyStart3() throws JAXBException {
setNamespaces();
WasStartedBy start1 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start1.setTime(pFactory.newTimeNow());
start1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
start1.setStarter(pFactory.newActivityRef(q("a1s")));
WasStartedBy start2 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
start2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
start2.setStarter(pFactory.newActivityRef(q("a2s")));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Activity a2=pFactory.newActivity(q("a2"));
Activity a2s=pFactory.newActivity(q("a2s"));
Statement [] opt=new Statement[] { e1, a1, a2, a2s };
Statement [] statements=new Statement[] { start1, start2 };
makeDocAndTest(statements, opt , "target/scruffy-start3");
}
public void testScruffyStart4() throws JAXBException {
setNamespaces();
WasStartedBy start1 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start1.setTime(pFactory.newTimeNow());
start1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
start1.setStarter(pFactory.newActivityRef(q("a1s")));
WasStartedBy start2 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a2")),
pFactory.newEntityRef(q("e2")));
start2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
start2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
start2.setStarter(pFactory.newActivityRef(q("a2s")));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Activity a1s=pFactory.newActivity(q("a1s"));
Entity e2=pFactory.newEntity(q("e2"));
Activity a2=pFactory.newActivity(q("a2"));
Activity a2s=pFactory.newActivity(q("a2s"));
Statement [] opt=new Statement[] { e1, a1, a1s, e2, a2, a2s };
Statement [] statements=new Statement[] { start1, start2 };
makeDocAndTest(statements, opt , "target/scruffy-start4");
}
public void testScruffyEnd1() throws JAXBException {
setNamespaces();
WasEndedBy end1 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end1.setTime(pFactory.newTimeNow());
WasEndedBy end2 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { end1, end2 };
makeDocAndTest(statements, opt , "target/scruffy-end1");
}
public void testScruffyEnd2() throws JAXBException {
setNamespaces();
WasEndedBy end1 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end1.setTime(pFactory.newTimeNow());
end1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
WasEndedBy end2 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
end2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { end1, end2 };
makeDocAndTest(statements, opt , "target/scruffy-end2");
}
public void testScruffyEnd3() throws JAXBException {
setNamespaces();
WasEndedBy end1 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end1.setTime(pFactory.newTimeNow());
end1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
end1.setEnder(pFactory.newActivityRef(q("a1s")));
WasEndedBy end2 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
end2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
end2.setEnder(pFactory.newActivityRef(q("a2s")));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Activity a2=pFactory.newActivity(q("a2"));
Activity a2s=pFactory.newActivity(q("a2s"));
Statement [] opt=new Statement[] { e1, a1, a2, a2s };
Statement [] statements=new Statement[] { end1, end2 };
makeDocAndTest(statements, opt , "target/scruffy-end3");
}
public void testScruffyEnd4() throws JAXBException {
setNamespaces();
WasEndedBy end1 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end1.setTime(pFactory.newTimeNow());
end1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
end1.setEnder(pFactory.newActivityRef(q("a1s")));
WasEndedBy end2 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a2")),
pFactory.newEntityRef(q("e2")));
end2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
end2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
end2.setEnder(pFactory.newActivityRef(q("a2s")));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Activity a1s=pFactory.newActivity(q("a1s"));
Entity e2=pFactory.newEntity(q("e2"));
Activity a2=pFactory.newActivity(q("a2"));
Activity a2s=pFactory.newActivity(q("a2s"));
Statement [] opt=new Statement[] { e1, a1, a1s, e2, a2, a2s };
Statement [] statements=new Statement[] { end1, end2 };
makeDocAndTest(statements, opt , "target/scruffy-end4");
}
public void testBundle1 () throws JAXBException {
setNamespaces();
Used use1 = pFactory.newUsed(q("use1"),
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
List<Statement> st1=new LinkedList<Statement>();
st1.add(a1);
st1.add(e1);
st1.add(use1);
NamedBundle b1=pFactory.newNamedBundle(q("bundle1"), st1);
Used use2 = pFactory.newUsed(q("use2"),
pFactory.newActivityRef(q("aa1")),
null,
pFactory.newEntityRef(q("ee1")));
Entity ee1=pFactory.newEntity(q("ee1"));
Activity aa1=pFactory.newActivity(q("aa1"));
List<Statement> st2=new LinkedList<Statement>();
st2.add(aa1);
st2.add(ee1);
st2.add(use2);
NamedBundle b2=pFactory.newNamedBundle(q("bundle2"), st2);
Entity eb1=pFactory.newEntity(q("bundle1"));
pFactory.addType(eb1, pFactory.newQName("prov:Bundle"));
Entity eb2=pFactory.newEntity(q("bundle2"));
pFactory.addType(eb2, pFactory.newQName("prov:Bundle"));
Statement [] statements=new Statement[] { eb1, eb2,};
NamedBundle [] bundles=new NamedBundle[] { b1, b2 };
makeDocAndTest(statements, bundles, "target/bundle1", null, true);
}
public void testBundle2 () throws JAXBException {
setNamespaces();
Used use1 = pFactory.newUsed(q("use1"),
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
List<Statement> st1=new LinkedList<Statement>();
st1.add(a1);
st1.add(e1);
st1.add(use1);
NamedBundle b1=pFactory.newNamedBundle(q("bundle1"), st1);
Used use2 = pFactory.newUsed(q("use2"),
pFactory.newActivityRef(q("e1")),
null,
pFactory.newEntityRef(q("a1")));
Entity ee1=pFactory.newEntity(q("a1"));
Activity aa1=pFactory.newActivity(q("e1"));
List<Statement> st2=new LinkedList<Statement>();
st2.add(aa1);
st2.add(ee1);
st2.add(use2);
NamedBundle b2=pFactory.newNamedBundle(q("bundle2"), st2);
Entity eb1=pFactory.newEntity(q("bundle1"));
pFactory.addType(eb1, pFactory.newQName("prov:Bundle"));
Entity eb2=pFactory.newEntity(q("bundle2"));
pFactory.addType(eb2, pFactory.newQName("prov:Bundle"));
Statement [] statements=new Statement[] { eb1, eb2,};
NamedBundle [] bundles=new NamedBundle[] { b1, b2 };
makeDocAndTest(statements, bundles, "target/bundle2", null, true);
}
public void NOtestDictionary1 () throws JAXBException {
DerivedByInsertionFrom d1=pFactory.newDerivedByInsertionFrom(null, q("d2"), q("d1"), null, null);
Statement [] statements=new Statement[] { d1 };
Statement [] opt=new Statement[] { };
makeDocAndTest(statements, opt , "target/dictionary1");
}
public void NOtestDictionary2 () throws JAXBException {
DerivedByInsertionFrom d2=pFactory.newDerivedByInsertionFrom(q("deriv"), q("d2"), q("d1"), null, null);
Statement [] statements=new Statement[] { d2 };
Statement [] opt=new Statement[] { };
makeDocAndTest(statements, opt , "target/dictionary2");
}
}
| prov-xml/src/test/java/org/openprovenance/prov/xml/RoundTripFromJavaTest.java | package org.openprovenance.prov.xml;
import java.io.File;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.net.URI;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
import junit.framework.TestCase;
/**
* Unit test for PROV roundtrip conversion between Java and XML
*/
public class RoundTripFromJavaTest extends TestCase {
public static final String EX_NS = "http://example.org/";
public static final String EX2_NS = "http://example2.org/";
public static final String EX_PREFIX = "ex";
public static final String EX2_PREFIX = "ex2";
public static final String EX3_NS = "http://example3.org/";
static final ProvUtilities util=new ProvUtilities();
static final Hashtable<String, String> namespaces;
public static ProvFactory pFactory;
public static ValueConverter vconv;
static Hashtable<String, String> updateNamespaces (Hashtable<String, String> nss) {
nss.put(EX_PREFIX, EX_NS);
nss.put(EX2_PREFIX, EX2_NS);
nss.put("_", EX3_NS);
return nss;
}
static void setNamespaces() {
pFactory.resetNamespaces();
pFactory.getNss().putAll(updateNamespaces(new Hashtable<String, String>()));
}
static {
namespaces = updateNamespaces(new Hashtable<String, String>());
pFactory = new ProvFactory(namespaces);
vconv=new ValueConverter(pFactory);
}
private DocumentEquality documentEquality;
/**
* Create the test case
*
* @param testName
* name of the test case
*/
public RoundTripFromJavaTest(String testName) {
super(testName);
this.documentEquality = new DocumentEquality(mergeDuplicateProperties());
}
public boolean urlFlag = true;
/**
* @return the suite of tests being tested
*/
public void updateNamespaces(Document doc) {
Hashtable<String, String> nss = new Hashtable<String, String>();
updateNamespaces(nss);
doc.setNss(nss);
}
public String extension() {
return ".xml";
}
public void makeDocAndTest(Statement stment, String file) {
makeDocAndTest(stment, file, null, true);
}
public void makeDocAndTest(Statement stment, String file, boolean check) {
makeDocAndTest(stment, file, null, check);
}
public void makeDocAndTest(Statement stment, Statement[] opt, String file) {
makeDocAndTest(stment, file, opt, true);
}
public void makeDocAndTest(Statement [] stment, Statement[] opt, String file) {
makeDocAndTest(stment, file, opt, true);
}
public void makeDocAndTest(Statement stment, String file, Statement[] opt, boolean check) {
makeDocAndTest(new Statement[] {stment}, file, opt, check);
}
public void makeDocAndTest(Statement []stment, String file, Statement[] opt, boolean check) {
makeDocAndTest(stment, null, file, opt, check);
}
public void makeDocAndTest(Statement []stment, NamedBundle[] bundles, String file, Statement[] opt, boolean check) {
Document doc = pFactory.newDocument();
for (int i=0; i< stment.length; i++) {
doc.getEntityAndActivityAndWasGeneratedBy().add(stment[i]);
}
if (bundles!=null) {
for (int j=0; j<bundles.length; j++) {
doc.getEntityAndActivityAndWasGeneratedBy().add(bundles[j]);
}
}
updateNamespaces(doc);
String file1=(opt==null) ? file : file+"-S";
compareDocAndFile(doc, file1, check);
if (opt!=null) {
String file2=file+"-M";
doc.getEntityAndActivityAndWasGeneratedBy().addAll(Arrays.asList(opt));
compareDocAndFile(doc, file2, check);
}
}
public void compareDocAndFile(Document doc, String file, boolean check) {
file=file+extension();
writeDocument(doc, file);
Document doc3=readDocument(file);
compareDocuments(doc, doc3, check && checkTest(file));
}
public Document readDocument(String file1) {
try {
return readXMLDocument(file1);
} catch (JAXBException e) {
throw new UncheckedTestException(e);
}
}
public void writeDocument(Document doc, String file2) {
try {
writeXMLDocument(doc, file2);
} catch (JAXBException e) {
throw new UncheckedTestException(e);
}
}
public void compareDocuments(Document doc, Document doc2, boolean check) {
assertTrue("self doc equality", doc.equals(doc));
assertTrue("self doc2 equality", doc2.equals(doc2));
if (check) {
boolean result=this.documentEquality.check(doc, doc2);
if (!result) {
System.out.println("Pre-write graph: "+doc);
System.out.println("Read graph: "+doc2);
}
assertTrue("doc equals doc2", result);
} else {
assertFalse("doc distinct from doc2", doc.equals(doc2));
}
}
public boolean checkTest(String name) {
// all tests successful in this file
return true;
}
public boolean mergeDuplicateProperties() {
return false;
}
public Document readXMLDocument(String file) throws javax.xml.bind.JAXBException {
ProvDeserialiser deserial = ProvDeserialiser
.getThreadProvDeserialiser();
Document c = deserial.deserialiseDocument(new File(file));
return c;
}
public void writeXMLDocument(Document doc, String file) throws JAXBException {
ProvSerialiser serial = ProvSerialiser.getThreadProvSerialiser();
serial.serialiseDocument(new File(file), doc, true);
StringWriter sw = new StringWriter();
serial.serialiseDocument(sw, doc, true);
//System.out.println(sw.toString());
}
///////////////////////////////////////////////////////////////////////
public void addLabel(HasLabel hl) {
hl.getLabel().add(pFactory.newInternationalizedString("hello"));
}
public void addLabels(HasLabel hl) {
hl.getLabel().add(pFactory.newInternationalizedString("hello"));
hl.getLabel().add(pFactory.newInternationalizedString("bye","EN"));
hl.getLabel().add(pFactory.newInternationalizedString("bonjour","FR"));
}
public void addTypes(HasType ht) {
ht.getType().add("a");
ht.getType().add(1);
ht.getType().add(1.0);
ht.getType().add(true);
ht.getType().add(new QName(EX_NS, "abc", EX_PREFIX));
ht.getType().add(pFactory.newTimeNow());
URIWrapper w=new URIWrapper();
w.setValue(URI.create(EX_NS+"hello"));
ht.getType().add(w);
}
public void addLocations(HasLocation hl) {
hl.getLocation().add("London");
hl.getLocation().add(1);
hl.getLocation().add(1.0);
hl.getLocation().add(true);
hl.getLocation().add(new QName(EX_NS, "london", EX_PREFIX));
hl.getLocation().add(pFactory.newTimeNow());
URIWrapper w=new URIWrapper();
w.setValue(URI.create(EX_NS+"london"));
hl.getLocation().add(w);
hl.getLocation().add(pFactory.newGYear("2002"));
}
public void addValue(HasValue hl) {
hl.setValue(new QName(EX_NS, "avalue", EX_PREFIX));
}
public void addFurtherAttributes(HasExtensibility he) {
he.getAny().add(pFactory.newAttribute(EX_NS,"tag1",EX_PREFIX,"hello", vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "bye", vconv));
//he.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, pFactory.newInternationalizedString("bonjour","fr"), "xsd:string"));
he.getAny().add(pFactory.newAttribute(EX2_NS,"tag3",EX2_PREFIX, "hi", vconv));
}
public void addFurtherAttributes0(HasExtensibility he) {
he.getAny().add(pFactory.newAttribute(EX_NS,"tag1",EX_PREFIX,"hello", vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "bye", vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, pFactory.newInternationalizedString("bonjour","fr"), ValueConverter.QNAME_XSD_STRING));
he.getAny().add(pFactory.newAttribute(EX2_NS,"tag3",EX2_PREFIX, "hi", vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new Integer(1), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new Long(1), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new Short((short) 1), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new Double(1.0), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new Float(1.0), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new java.math.BigDecimal(1.0), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new Boolean(true), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new Byte((byte) 123), vconv));
addFurtherAttributesWithQNames(he);
URIWrapper w=new URIWrapper();
w.setValue(URI.create(EX_NS+"london"));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, w, vconv));
}
///////////////////////////////////////////////////////////////////////
public void addFurtherAttributesWithQNames(HasExtensibility he) {
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new QName(EX2_NS,"newyork", EX2_PREFIX), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new QName(EX_NS, "london", EX_PREFIX), vconv));
he.getAny().add(pFactory.newAttribute(EX_NS,"tag",EX_PREFIX, new QName(EX3_NS, "london"), vconv));
}
public void testEntity0() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e0");
a.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, pFactory.newInternationalizedString("bonjour","fr"), ValueConverter.QNAME_XSD_STRING));
makeDocAndTest(a,"target/entity0");
}
public void testEntity1() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e1");
makeDocAndTest(a,"target/entity1");
}
public void testEntity2() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e2", "entity2");
makeDocAndTest(a,"target/entity2");
}
public void testEntity3() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e3", "entity3");
addValue(a);
makeDocAndTest(a,"target/entity3");
}
public void testEntity4() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e4", "entity4");
addLabels(a);
makeDocAndTest(a,"target/entity4");
}
public void testEntity5() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e5", "entity5");
addTypes(a);
makeDocAndTest(a,"target/entity5");
}
public void testEntity6() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e6", "entity6");
addLocations(a);
makeDocAndTest(a,"target/entity6");
}
public void testEntity7() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e7", "entity7");
addTypes(a);
addLocations(a);
addLabels(a);
makeDocAndTest(a,"target/entity7");
}
public void testEntity8() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e8", "entity8");
addTypes(a);
addTypes(a);
addLocations(a);
addLocations(a);
addLabels(a);
addLabels(a);
makeDocAndTest(a,"target/entity8");
}
public void testEntity9() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e9", "entity9");
addTypes(a);
addLocations(a);
addLabels(a);
addFurtherAttributes(a);
makeDocAndTest(a,"target/entity9");
}
public void testEntity10() throws JAXBException {
setNamespaces();
Entity a = pFactory.newEntity("ex:e10", "entity10");
addTypes(a);
addLocations(a);
addLabels(a);
addFurtherAttributes(a);
makeDocAndTest(a,"target/entity10");
}
///////////////////////////////////////////////////////////////////////
public void testActivity1() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a1");
makeDocAndTest(a,"target/activity1");
}
public void testActivity2() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a2", "activity2");
makeDocAndTest(a,"target/activity2");
}
public void testActivity3() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a1");
a.setStartTime(pFactory.newTimeNow());
a.setEndTime(pFactory.newTimeNow());
makeDocAndTest(a,"target/activity3");
}
public void testActivity4() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a2", "activity2");
addLabels(a);
makeDocAndTest(a,"target/activity4");
}
public void testActivity5() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a2", "activity2");
addTypes(a);
makeDocAndTest(a,"target/activity5");
}
public void testActivity6() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a6", "activity6");
addLocations(a);
makeDocAndTest(a,"target/activity6");
}
public void testActivity7() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a7", "activity7");
addTypes(a);
addLocations(a);
addLabels(a);
makeDocAndTest(a,"target/activity7");
}
public void testActivity8() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a8", "activity8");
a.setStartTime(pFactory.newTimeNow());
a.setEndTime(pFactory.newTimeNow());
addTypes(a);
addTypes(a);
addLocations(a);
addLocations(a);
addLabels(a);
addLabels(a);
makeDocAndTest(a,"target/activity8");
}
public void testActivity9() throws JAXBException {
setNamespaces();
Activity a = pFactory.newActivity("ex:a9", "activity9");
addTypes(a);
addLocations(a);
addLabels(a);
addFurtherAttributes(a);
makeDocAndTest(a,"target/activity9");
}
///////////////////////////////////////////////////////////////////////
public void testAgent1() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag1");
makeDocAndTest(a,"target/agent1");
}
public void testAgent2() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag2", "agent2");
makeDocAndTest(a,"target/agent2");
}
public void testAgent3() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag2", "agent2");
a.getLabel().add(pFactory.newInternationalizedString("hello"));
makeDocAndTest(a,"target/agent3");
}
public void testAgent4() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag2", "agent2");
a.getLabel().add(pFactory.newInternationalizedString("hello"));
a.getLabel().add(pFactory.newInternationalizedString("bye","EN"));
makeDocAndTest(a,"target/agent4");
}
public void testAgent5() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag2", "agent2");
a.getLabel().add(pFactory.newInternationalizedString("hello"));
a.getLabel().add(pFactory.newInternationalizedString("bye","EN"));
a.getLabel().add(pFactory.newInternationalizedString("bonjour","FR"));
makeDocAndTest(a,"target/agent5");
}
public void testAgent6() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag6", "agent6");
a.getType().add("a");
a.getType().add(1);
a.getType().add(1.0);
a.getType().add(true);
a.getType().add(new QName(EX_NS, "abc", EX_PREFIX));
a.getType().add(pFactory.newTimeNow());
URIWrapper w=new URIWrapper();
w.setValue(URI.create(EX_NS+"hello"));
a.getType().add(w);
makeDocAndTest(a,"target/agent6");
}
public void testAgent7() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag7", "agent7");
pFactory.addType(a,"a");
pFactory.addType(a,1);
pFactory.addType(a,1.0);
pFactory.addType(a,true);
pFactory.addType(a,new QName(EX_NS, "abc", EX_PREFIX));
pFactory.addType(a,pFactory.newTimeNow());
pFactory.addType(a,URI.create(EX_NS+"hello"));
a.getLabel().add(pFactory.newInternationalizedString("hello"));
a.getLabel().add(pFactory.newInternationalizedString("bye","EN"));
a.getLabel().add(pFactory.newInternationalizedString("bonjour","FR"));
a.getLocation().add("London");
a.getLocation().add(1);
a.getLocation().add(1.0);
a.getLocation().add(true);
a.getLocation().add(new QName(EX_NS, "london", EX_PREFIX));
a.getLocation().add(pFactory.newTimeNow());
URIWrapper w=new URIWrapper();
w.setValue(URI.create(EX_NS+"london"));
a.getLocation().add(w);
makeDocAndTest(a,"target/agent7");
}
public void testAgent8() throws JAXBException {
setNamespaces();
Agent a = pFactory.newAgent("ex:ag8", "agent8");
a.getType().add("a");
a.getType().add("a");
a.getType().add(1);
a.getType().add(1);
a.getType().add(1.0);
a.getType().add(1.0);
a.getType().add(true);
a.getType().add(true);
a.getType().add(new QName(EX_NS, "abc", EX_PREFIX));
a.getType().add(new QName(EX_NS, "abc", EX_PREFIX));
a.getType().add(pFactory.newTimeNow());
a.getType().add(pFactory.newTimeNow());
URIWrapper w=new URIWrapper();
w.setValue(URI.create(EX_NS+"hello"));
a.getType().add(w);
a.getType().add(w);
a.getLabel().add(pFactory.newInternationalizedString("hello"));
a.getLabel().add(pFactory.newInternationalizedString("hello"));
a.getLabel().add(pFactory.newInternationalizedString("bye","EN"));
a.getLabel().add(pFactory.newInternationalizedString("bye","EN"));
a.getLabel().add(pFactory.newInternationalizedString("bonjour","FR"));
a.getLabel().add(pFactory.newInternationalizedString("bonjour","FR"));
a.getLocation().add("London");
a.getLocation().add("London");
a.getLocation().add(1);
a.getLocation().add(1);
a.getLocation().add(1.0);
a.getLocation().add(1.0);
a.getLocation().add(true);
a.getLocation().add(true);
a.getLocation().add(new QName(EX_NS, "london", EX_PREFIX));
a.getLocation().add(new QName(EX_NS, "london", EX_PREFIX));
a.getLocation().add(pFactory.newTimeNow());
a.getLocation().add(pFactory.newTimeNow());
URIWrapper w2=new URIWrapper();
w2.setValue(URI.create(EX_NS+"london"));
a.getLocation().add(w2);
a.getLocation().add(w2);
makeDocAndTest(a,"target/agent8");
}
///////////////////////////////////////////////////////////////////////
public QName q(String n) {
return new QName(EX_NS, n, EX_PREFIX);
}
public void testGeneration1() throws JAXBException {
setNamespaces();
WasGeneratedBy gen = pFactory.newWasGeneratedBy(q("gen1"),
pFactory.newEntityRef(q("e1")),
null,
null);
makeDocAndTest(gen, "target/generation1");
}
public void testGeneration2() throws JAXBException {
setNamespaces();
WasGeneratedBy gen = pFactory.newWasGeneratedBy(q("gen2"),
pFactory.newEntityRef(q("e1")),
null,
pFactory.newActivityRef(q("a1")));
makeDocAndTest(gen, "target/generation2");
}
public void testGeneration3() throws JAXBException {
setNamespaces();
WasGeneratedBy gen = pFactory.newWasGeneratedBy(q("gen3"),
pFactory.newEntityRef(q("e1")),
"somerole",
pFactory.newActivityRef(q("a1")));
gen.getRole().add("otherRole");
makeDocAndTest(gen,"target/generation3");
}
public void testGeneration4() throws JAXBException {
setNamespaces();
WasGeneratedBy gen = pFactory.newWasGeneratedBy(q("gen4"),
pFactory.newEntityRef(q("e1")),
"somerole",
pFactory.newActivityRef(q("a1")));
gen.setTime(pFactory.newTimeNow());
makeDocAndTest(gen,"target/generation4");
}
public void testGeneration5() throws JAXBException {
setNamespaces();
WasGeneratedBy gen = pFactory.newWasGeneratedBy(q("gen4"),
pFactory.newEntityRef(q("e1")),
"somerole",
pFactory.newActivityRef(q("a1")));
gen.setTime(pFactory.newTimeNow());
addTypes(gen);
addLocations(gen);
addLabels(gen);
addFurtherAttributes(gen);
makeDocAndTest(gen,"target/generation5");
}
public void testGeneration6() throws JAXBException {
setNamespaces();
WasGeneratedBy gen = pFactory.newWasGeneratedBy((QName)null,
pFactory.newEntityRef(q("e1")),
null,
pFactory.newActivityRef(q("a1")));
makeDocAndTest(gen,"target/generation6");
}
public void testGeneration7() throws JAXBException {
setNamespaces();
WasGeneratedBy gen = pFactory.newWasGeneratedBy((QName)null,
pFactory.newEntityRef(q("e1")),
"somerole",
pFactory.newActivityRef(q("a1")));
gen.setTime(pFactory.newTimeNow());
addTypes(gen);
addLocations(gen);
addLabels(gen);
addFurtherAttributes(gen);
makeDocAndTest(gen,"target/generation7");
}
//////////////////////////////////
public void testUsage1() throws JAXBException {
setNamespaces();
Used use = pFactory.newUsed(q("use1"),
null,
null,
pFactory.newEntityRef(q("e1")));
makeDocAndTest(use,"target/usage1");
}
public void testUsage2() throws JAXBException {
setNamespaces();
Used use = pFactory.newUsed(q("use2"),
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
makeDocAndTest(use,"target/usage2");
}
public void testUsage3() throws JAXBException {
setNamespaces();
Used use = pFactory.newUsed(q("use3"),
pFactory.newActivityRef(q("a1")),
"somerole",
pFactory.newEntityRef(q("e1")));
use.getRole().add("otherRole");
makeDocAndTest(use,"target/usage3");
}
public void testUsage4() throws JAXBException {
setNamespaces();
Used use = pFactory.newUsed(q("use4"),
pFactory.newActivityRef(q("a1")),
"somerole",
pFactory.newEntityRef(q("e1")));
use.setTime(pFactory.newTimeNow());
makeDocAndTest(use,"target/usage4");
}
public void testUsage5() throws JAXBException {
setNamespaces();
Used use = pFactory.newUsed(q("use4"),
pFactory.newActivityRef(q("a1")),
"somerole",
pFactory.newEntityRef(q("e1")));
use.setTime(pFactory.newTimeNow());
addTypes(use);
addLocations(use);
addLabels(use);
addFurtherAttributes(use);
makeDocAndTest(use,"target/usage5");
}
public void testUsage6() throws JAXBException {
setNamespaces();
Used use = pFactory.newUsed((QName)null,
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
makeDocAndTest(use,"target/usage6");
}
public void testUsage7() throws JAXBException {
setNamespaces();
Used use = pFactory.newUsed((QName)null,
pFactory.newActivityRef(q("a1")),
"somerole",
pFactory.newEntityRef(q("e1")));
use.setTime(pFactory.newTimeNow());
addTypes(use);
addLocations(use);
addLabels(use);
addFurtherAttributes(use);
makeDocAndTest(use,"target/usage7");
}
// //////////////////////////////////////////////
public void testInvalidation1() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv = pFactory.newWasInvalidatedBy(q("inv1"),
pFactory.newEntityRef(q("e1")),
null);
makeDocAndTest(inv, "target/invalidation1");
}
public void testInvalidation2() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv = pFactory.newWasInvalidatedBy(q("inv2"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
makeDocAndTest(inv, "target/invalidation2");
}
public void testInvalidation3() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv = pFactory.newWasInvalidatedBy(q("inv3"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv.getRole().add("someRole");
inv.getRole().add("otherRole");
makeDocAndTest(inv, "target/invalidation3");
}
public void testInvalidation4() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv = pFactory.newWasInvalidatedBy(q("inv4"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv.getRole().add("someRole");
inv.setTime(pFactory.newTimeNow());
makeDocAndTest(inv, "target/invalidation4");
}
public void testInvalidation5() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv = pFactory.newWasInvalidatedBy(q("inv4"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv.getRole().add("someRole");
inv.setTime(pFactory.newTimeNow());
addTypes(inv);
addLocations(inv);
addLabels(inv);
addFurtherAttributes(inv);
makeDocAndTest(inv, "target/invalidation5");
}
public void testInvalidation6() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv = pFactory.newWasInvalidatedBy((QName) null,
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
makeDocAndTest(inv, "target/invalidation6");
}
public void testInvalidation7() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv = pFactory.newWasInvalidatedBy((QName) null,
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv.getRole().add("someRole");
inv.setTime(pFactory.newTimeNow());
addTypes(inv);
addLocations(inv);
addLabels(inv);
addFurtherAttributes(inv);
makeDocAndTest(inv, "target/invalidation7");
}
//////////////////////////////////
public void testStart1() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start1"),
null,
pFactory.newEntityRef(q("e1")));
makeDocAndTest(start, "target/start1");
}
public void testStart2() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start2"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(start, "target/start2");
}
public void testStart3() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start3"),
pFactory.newActivityRef(q("a1")),
null);
makeDocAndTest(start, "target/start3");
}
public void testStart4() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start4"),
null,
pFactory.newEntityRef(q("e1")));
start.setStarter(pFactory.newActivityRef(q("a2")));
makeDocAndTest(start, "target/start4");
}
public void testStart5() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start5"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start.setStarter(pFactory.newActivityRef(q("a2")));
makeDocAndTest(start, "target/start5");
}
public void testStart6() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start6"),
pFactory.newActivityRef(q("a1")),
null);
start.setStarter(pFactory.newActivityRef(q("a2")));
makeDocAndTest(start, "target/start6");
}
public void testStart7() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start7"),
pFactory.newActivityRef(q("a1")),
null);
start.setStarter(pFactory.newActivityRef(q("a2")));
start.setTime(pFactory.newTimeNow());
makeDocAndTest(start, "target/start7");
}
public void testStart8() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy(q("start8"),
pFactory.newActivityRef(q("a1")),
null);
start.setStarter(pFactory.newActivityRef(q("a2")));
start.setTime(pFactory.newTimeNow());
start.getRole().add("someRole");
start.getRole().add("otherRole");
addTypes(start);
addLocations(start);
addLabels(start);
addFurtherAttributes(start);
makeDocAndTest(start, "target/start8");
}
public void testStart9() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy((QName)null,
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(start, "target/start9");
}
public void testStart10() throws JAXBException {
setNamespaces();
WasStartedBy start = pFactory.newWasStartedBy((QName)null,
pFactory.newActivityRef(q("a1")),
null);
start.setStarter(pFactory.newActivityRef(q("a2")));
start.setTime(pFactory.newTimeNow());
start.getRole().add("someRole");
start.getRole().add("otherRole");
addTypes(start);
addLocations(start);
addLabels(start);
addFurtherAttributes(start);
makeDocAndTest(start, "target/start10");
}
// ////////////////////////////////
public void testEnd1() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end1"), null,
pFactory.newEntityRef(q("e1")));
makeDocAndTest(end, "target/end1");
}
public void testEnd2() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end2"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(end, "target/end2");
}
public void testEnd3() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end3"),
pFactory.newActivityRef(q("a1")),
null);
makeDocAndTest(end, "target/end3");
}
public void testEnd4() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end4"), null,
pFactory.newEntityRef(q("e1")));
end.setEnder(pFactory.newActivityRef(q("a2")));
makeDocAndTest(end, "target/end4");
}
public void testEnd5() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end5"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end.setEnder(pFactory.newActivityRef(q("a2")));
makeDocAndTest(end, "target/end5");
}
public void testEnd6() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end6"),
pFactory.newActivityRef(q("a1")),
null);
end.setEnder(pFactory.newActivityRef(q("a2")));
makeDocAndTest(end, "target/end6");
}
public void testEnd7() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end7"),
pFactory.newActivityRef(q("a1")),
null);
end.setEnder(pFactory.newActivityRef(q("a2")));
end.setTime(pFactory.newTimeNow());
makeDocAndTest(end, "target/end7");
}
public void testEnd8() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy(q("end8"),
pFactory.newActivityRef(q("a1")),
null);
end.setEnder(pFactory.newActivityRef(q("a2")));
end.setTime(pFactory.newTimeNow());
end.getRole().add("someRole");
end.getRole().add("otherRole");
addTypes(end);
addLocations(end);
addLabels(end);
addFurtherAttributes(end);
makeDocAndTest(end, "target/end8");
}
public void testEnd9() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy((QName) null,
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(end, "target/end9");
}
public void testEnd10() throws JAXBException {
setNamespaces();
WasEndedBy end = pFactory.newWasEndedBy((QName) null,
pFactory.newActivityRef(q("a1")),
null);
end.setEnder(pFactory.newActivityRef(q("a2")));
end.setTime(pFactory.newTimeNow());
end.getRole().add("someRole");
end.getRole().add("otherRole");
addTypes(end);
addLocations(end);
addLabels(end);
addFurtherAttributes(end);
makeDocAndTest(end, "target/end10");
}
// ////////////////////////////////
public void testDerivation1() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der1"),
null,
pFactory.newEntityRef(q("e1")));
makeDocAndTest(der, "target/derivation1");
}
public void testDerivation2() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der2"),
pFactory.newEntityRef(q("e2")),
null);
makeDocAndTest(der, "target/derivation2");
}
public void testDerivation3() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der3"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(der, "target/derivation3");
}
public void testDerivation4() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der4"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
addLabel(der);
makeDocAndTest(der, "target/derivation4");
}
public void testDerivation5() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der5"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
der.setActivity(pFactory.newActivityRef(q("a")));
makeDocAndTest(der, "target/derivation5");
}
public void testDerivation6() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der6"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
der.setActivity(pFactory.newActivityRef(q("a")));
der.setUsage(pFactory.newUsageRef(q("u")));
makeDocAndTest(der, "target/derivation6");
}
public void testDerivation7() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der7"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
der.setActivity(pFactory.newActivityRef(q("a")));
der.setUsage(pFactory.newUsageRef(q("u")));
der.setGeneration(pFactory.newGenerationRef(q("g")));
makeDocAndTest(der, "target/derivation7");
}
public void testDerivation8() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("der8"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
addLabel(der);
addTypes(der);
addFurtherAttributes(der);
makeDocAndTest(der, "target/derivation8");
}
public void testDerivation9() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom((QName)null,
pFactory.newEntityRef(q("e2")),
null);
addTypes(der);
makeDocAndTest(der, "target/derivation9");
}
public void testDerivation10() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom((QName)null,
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
der.setActivity(pFactory.newActivityRef(q("a")));
der.setUsage(pFactory.newUsageRef(q("u")));
der.setGeneration(pFactory.newGenerationRef(q("g")));
makeDocAndTest(der, "target/derivation10");
}
public void testDerivation11() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("rev1"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
der.setActivity(pFactory.newActivityRef(q("a")));
der.setUsage(pFactory.newUsageRef(q("u")));
der.setGeneration(pFactory.newGenerationRef(q("g")));
pFactory.addRevisionType(der);
makeDocAndTest(der, "target/derivation11");
}
public void testDerivation12() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("quo1"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
der.setActivity(pFactory.newActivityRef(q("a")));
der.setUsage(pFactory.newUsageRef(q("u")));
der.setGeneration(pFactory.newGenerationRef(q("g")));
pFactory.addQuotationType(der);
makeDocAndTest(der, "target/derivation12");
}
public void testDerivation13() throws JAXBException {
setNamespaces();
WasDerivedFrom der = pFactory.newWasDerivedFrom(q("prim1"),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
der.setActivity(pFactory.newActivityRef(q("a")));
der.setUsage(pFactory.newUsageRef(q("u")));
der.setGeneration(pFactory.newGenerationRef(q("g")));
pFactory.addPrimarySourceType(der);
makeDocAndTest(der, "target/derivation13");
}
// ////////////////////////////////
public void testAssociation1() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc1"),
pFactory.newActivityRef(q("a1")),
null);
makeDocAndTest(assoc, "target/association1");
}
public void testAssociation2() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc2"),
null,
pFactory.newAgentRef(q("ag1")));
makeDocAndTest(assoc, "target/association2");
}
public void testAssociation3() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc3"),
pFactory.newActivityRef(q("a1")),
pFactory.newAgentRef(q("ag1")));
makeDocAndTest(assoc, "target/association3");
}
public void testAssociation4() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc4"),
pFactory.newActivityRef(q("a1")),
pFactory.newAgentRef(q("ag1")));
assoc.setPlan(pFactory.newEntityRef(q("plan1")));
makeDocAndTest(assoc, "target/association4");
}
public void testAssociation5() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith((QName)null,
pFactory.newActivityRef(q("a1")),
pFactory.newAgentRef(q("ag1")));
makeDocAndTest(assoc, "target/association5");
}
public void testAssociation6() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc6"),
pFactory.newActivityRef(q("a1")),
pFactory.newAgentRef(q("ag1")));
assoc.setPlan(pFactory.newEntityRef(q("plan1")));
addLabels(assoc);
makeDocAndTest(assoc, "target/association6");
}
public void testAssociation7() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc7"),
pFactory.newActivityRef(q("a1")),
pFactory.newAgentRef(q("ag1")));
assoc.setPlan(pFactory.newEntityRef(q("plan1")));
addLabels(assoc);
addTypes(assoc);
makeDocAndTest(assoc, "target/association7");
}
public void testAssociation8() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc8"),
pFactory.newActivityRef(q("a1")),
pFactory.newAgentRef(q("ag1")));
assoc.setPlan(pFactory.newEntityRef(q("plan1")));
assoc.getRole().add("someRole");
assoc.getRole().add("someOtherRole");
makeDocAndTest(assoc, "target/association8");
}
public void testAssociation9() throws JAXBException {
setNamespaces();
WasAssociatedWith assoc = pFactory.newWasAssociatedWith(q("assoc9"),
pFactory.newActivityRef(q("a1")),
pFactory.newAgentRef(q("ag1")));
assoc.setPlan(pFactory.newEntityRef(q("plan1")));
addLabels(assoc);
addTypes(assoc);
addFurtherAttributes(assoc);
makeDocAndTest(assoc, "target/association9");
}
// ////////////////////////////////
public void testAttribution1() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo(q("attr1"),
pFactory.newEntityRef(q("e1")),
null);
makeDocAndTest(attr, "target/attribution1");
}
public void testAttribution2() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo(q("attr2"),
null,
pFactory.newAgentRef(q("ag1")));
makeDocAndTest(attr, "target/attribution2");
}
public void testAttribution3() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo(q("attr3"),
pFactory.newEntityRef(q("e1")),
pFactory.newAgentRef(q("ag1")));
makeDocAndTest(attr, "target/attribution3");
}
public void testAttribution4() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo(q("attr4"),
pFactory.newEntityRef(q("e1")),
pFactory.newAgentRef(q("ag1")));
makeDocAndTest(attr, "target/attribution4");
}
public void testAttribution5() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo((QName)null,
pFactory.newEntityRef(q("e1")),
pFactory.newAgentRef(q("ag1")));
makeDocAndTest(attr, "target/attribution5");
}
public void testAttribution6() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo(q("attr6"),
pFactory.newEntityRef(q("e1")),
pFactory.newAgentRef(q("ag1")));
addLabels(attr);
makeDocAndTest(attr, "target/attribution6");
}
public void testAttribution7() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo(q("attr7"),
pFactory.newEntityRef(q("e1")),
pFactory.newAgentRef(q("ag1")));
addLabels(attr);
addTypes(attr);
makeDocAndTest(attr, "target/attribution7");
}
public void testAttribution8() throws JAXBException {
setNamespaces();
WasAttributedTo attr = pFactory.newWasAttributedTo(q("attr8"),
pFactory.newEntityRef(q("e1")),
pFactory.newAgentRef(q("ag1")));
addLabels(attr);
addTypes(attr);
addFurtherAttributes(attr);
makeDocAndTest(attr, "target/attribution8");
}
// ////////////////////////////////
public void testDelegation1() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf(q("del1"),
pFactory.newAgentRef(q("e1")),
null,
null);
makeDocAndTest(del, "target/delegation1");
}
public void testDelegation2() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf(q("del2"),
null,
pFactory.newAgentRef(q("ag1")),
null);
makeDocAndTest(del, "target/delegation2");
}
public void testDelegation3() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf(q("del3"),
pFactory.newAgentRef(q("e1")),
pFactory.newAgentRef(q("ag1")),
null);
makeDocAndTest(del, "target/delegation3");
}
public void testDelegation4() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf(q("del4"),
pFactory.newAgentRef(q("e1")),
pFactory.newAgentRef(q("ag1")),
pFactory.newActivityRef(q("a")));
makeDocAndTest(del, "target/delegation4");
}
public void testDelegation5() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf((QName)null,
pFactory.newAgentRef(q("e1")),
pFactory.newAgentRef(q("ag1")),
null);
makeDocAndTest(del, "target/delegation5");
}
public void testDelegation6() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf(q("del6"),
pFactory.newAgentRef(q("e1")),
pFactory.newAgentRef(q("ag1")),
pFactory.newActivityRef(q("a")));
addLabels(del);
makeDocAndTest(del, "target/delegation6");
}
public void testDelegation7() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf(q("del7"),
pFactory.newAgentRef(q("e1")),
pFactory.newAgentRef(q("ag1")),
pFactory.newActivityRef(q("a")));
addLabels(del);
addTypes(del);
makeDocAndTest(del, "target/delegation7");
}
public void testDelegation8() throws JAXBException {
setNamespaces();
ActedOnBehalfOf del = pFactory.newActedOnBehalfOf(q("del8"),
pFactory.newAgentRef(q("e1")),
pFactory.newAgentRef(q("ag1")),
pFactory.newActivityRef(q("a")));
addLabels(del);
addTypes(del);
addFurtherAttributes(del);
makeDocAndTest(del, "target/delegation8");
}
// ////////////////////////////////
public void testCommunication1() throws JAXBException {
setNamespaces();
WasInformedBy inf = pFactory.newWasInformedBy(q("inf1"),
pFactory.newActivityRef(q("a2")),
null);
makeDocAndTest(inf, "target/communication1");
}
public void testCommunication2() throws JAXBException {
setNamespaces();
WasInformedBy inf = pFactory.newWasInformedBy(q("inf2"),
null,
pFactory.newActivityRef(q("a1")));
makeDocAndTest(inf, "target/communication2");
}
public void testCommunication3() throws JAXBException {
setNamespaces();
WasInformedBy inf = pFactory.newWasInformedBy(q("inf3"),
pFactory.newActivityRef(q("a2")),
pFactory.newActivityRef(q("a1")));
makeDocAndTest(inf, "target/communication3");
}
public void testCommunication4() throws JAXBException {
setNamespaces();
WasInformedBy inf = pFactory.newWasInformedBy((QName)null,
pFactory.newActivityRef(q("a2")),
pFactory.newActivityRef(q("a1")));
makeDocAndTest(inf, "target/communication4");
}
public void testCommunication5() throws JAXBException {
setNamespaces();
WasInformedBy inf = pFactory.newWasInformedBy(q("inf5"),
pFactory.newActivityRef(q("a2")),
pFactory.newActivityRef(q("a1")));
addLabels(inf);
makeDocAndTest(inf, "target/communication5");
}
public void testCommunication6() throws JAXBException {
setNamespaces();
WasInformedBy inf = pFactory.newWasInformedBy(q("inf6"),
pFactory.newActivityRef(q("a2")),
pFactory.newActivityRef(q("a1")));
addLabels(inf);
addTypes(inf);
makeDocAndTest(inf, "target/communication6");
}
public void testCommunication7() throws JAXBException {
setNamespaces();
WasInformedBy inf = pFactory.newWasInformedBy(q("inf7"),
pFactory.newActivityRef(q("a2")),
pFactory.newActivityRef(q("a1")));
addLabels(inf);
addTypes(inf);
addFurtherAttributes(inf);
makeDocAndTest(inf, "target/communication7");
}
// ////////////////////////////////
public void testInfluence1() throws JAXBException {
setNamespaces();
WasInfluencedBy inf = pFactory.newWasInfluencedBy(q("inf1"),
pFactory.newAnyRef(q("a2")),
null);
makeDocAndTest(inf, "target/influence1");
}
public void testInfluence2() throws JAXBException {
setNamespaces();
WasInfluencedBy inf = pFactory.newWasInfluencedBy(q("inf2"),
null,
pFactory.newAnyRef(q("a1")));
makeDocAndTest(inf, "target/influence2");
}
public void testInfluence3() throws JAXBException {
setNamespaces();
WasInfluencedBy inf = pFactory.newWasInfluencedBy(q("inf3"),
pFactory.newAnyRef(q("a2")),
pFactory.newAnyRef(q("a1")));
makeDocAndTest(inf, "target/influence3");
}
public void testInfluence4() throws JAXBException {
setNamespaces();
WasInfluencedBy inf = pFactory.newWasInfluencedBy((QName)null,
pFactory.newAnyRef(q("a2")),
pFactory.newAnyRef(q("a1")));
makeDocAndTest(inf, "target/influence4");
}
public void testInfluence5() throws JAXBException {
setNamespaces();
WasInfluencedBy inf = pFactory.newWasInfluencedBy(q("inf5"),
pFactory.newAnyRef(q("a2")),
pFactory.newAnyRef(q("a1")));
addLabels(inf);
makeDocAndTest(inf, "target/influence5");
}
public void testInfluence6() throws JAXBException {
setNamespaces();
WasInfluencedBy inf = pFactory.newWasInfluencedBy(q("inf6"),
pFactory.newAnyRef(q("a2")),
pFactory.newAnyRef(q("a1")));
addLabels(inf);
addTypes(inf);
makeDocAndTest(inf, "target/influence6");
}
public void testInfluence7() throws JAXBException {
setNamespaces();
WasInfluencedBy inf = pFactory.newWasInfluencedBy(q("inf7"),
pFactory.newAnyRef(q("a2")),
pFactory.newAnyRef(q("a1")));
addLabels(inf);
addTypes(inf);
addFurtherAttributes(inf);
makeDocAndTest(inf, "target/influence7");
}
// ////////////////////////////////
public void testAlternate1() throws JAXBException {
setNamespaces();
AlternateOf alt = pFactory.newAlternateOf(pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(alt, "target/alternate1");
}
public void testSpecialization1() throws JAXBException {
setNamespaces();
SpecializationOf spe = pFactory.newSpecializationOf(pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(spe, "target/specialization1");
}
public void testMention1() throws JAXBException {
setNamespaces();
MentionOf men = pFactory.newMentionOf(pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")),
null);
makeDocAndTest(men, "target/mention1");
}
public void testMention2() throws JAXBException {
setNamespaces();
MentionOf men = pFactory.newMentionOf(pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e1")),
pFactory.newEntityRef(q("b")));
makeDocAndTest(men, "target/mention2");
}
public void testMembership1() throws JAXBException {
setNamespaces();
HadMember mem = pFactory.newHadMember(pFactory.newEntityRef(q("c")),
pFactory.newEntityRef(q("e1")));
makeDocAndTest(mem, "target/member1");
}
public void testMembership2() throws JAXBException {
setNamespaces();
HadMember mem = pFactory.newHadMember(pFactory.newEntityRef(q("c")),
pFactory.newEntityRef(q("e1")),
pFactory.newEntityRef(q("e2")));
//TODO: multiple arguments not supported by toolbox
makeDocAndTest(mem, "target/member2");
}
public void testMembership3() throws JAXBException {
setNamespaces();
HadMember mem = pFactory.newHadMember(pFactory.newEntityRef(q("c")),
pFactory.newEntityRef(q("e1")),
pFactory.newEntityRef(q("e2")),
pFactory.newEntityRef(q("e3")));
//TODO: multiple arguments not supported by toolbox
makeDocAndTest(mem, "target/member3");
}
public void testScruffyGeneration1() throws JAXBException {
setNamespaces();
WasGeneratedBy gen1 = pFactory.newWasGeneratedBy(q("gen1"),
pFactory.newEntityRef(q("e1")),
null,
pFactory.newActivityRef(q("a1")));
gen1.setTime(pFactory.newTimeNow());
WasGeneratedBy gen2 = pFactory.newWasGeneratedBy(q("gen1"),
pFactory.newEntityRef(q("e1")),
null,
pFactory.newActivityRef(q("a1")));
gen2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { gen1, gen2 };
makeDocAndTest(statements, opt , "target/scruffy-generation1");
}
public void testScruffyGeneration2() throws JAXBException {
setNamespaces();
WasGeneratedBy gen1 = pFactory.newWasGeneratedBy(q("gen1"),
pFactory.newEntityRef(q("e1")),
null,
pFactory.newActivityRef(q("a1")));
gen1.setTime(pFactory.newTimeNow());
gen1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
WasGeneratedBy gen2 = pFactory.newWasGeneratedBy(q("gen1"),
pFactory.newEntityRef(q("e1")),
null,
pFactory.newActivityRef(q("a1")));
gen2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
gen2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { gen1, gen2 };
makeDocAndTest(statements, opt , "target/scruffy-generation2");
}
public void testScruffyInvalidation1() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv1 = pFactory.newWasInvalidatedBy(q("inv1"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv1.setTime(pFactory.newTimeNow());
WasInvalidatedBy inv2 = pFactory.newWasInvalidatedBy(q("inv1"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { inv1, inv2 };
makeDocAndTest(statements, opt , "target/scruffy-invalidation1");
}
public void testScruffyInvalidation2() throws JAXBException {
setNamespaces();
WasInvalidatedBy inv1 = pFactory.newWasInvalidatedBy(q("inv1"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv1.setTime(pFactory.newTimeNow());
inv1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
WasInvalidatedBy inv2 = pFactory.newWasInvalidatedBy(q("inv1"),
pFactory.newEntityRef(q("e1")),
pFactory.newActivityRef(q("a1")));
inv2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
inv2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { inv1, inv2 };
makeDocAndTest(statements, opt , "target/scruffy-invalidation2");
}
public void testScruffyUsage1() throws JAXBException {
setNamespaces();
Used use1 = pFactory.newUsed(q("use1"),
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
use1.setTime(pFactory.newTimeNow());
Used use2 = pFactory.newUsed(q("use1"),
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
use2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { use1, use2 };
makeDocAndTest(statements, opt , "target/scruffy-usage1");
}
public void testScruffyUsage2() throws JAXBException {
setNamespaces();
Used use1 = pFactory.newUsed(q("use1"),
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
use1.setTime(pFactory.newTimeNow());
use1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
Used use2 = pFactory.newUsed(q("use1"),
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
use2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
use2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { use1, use2 };
makeDocAndTest(statements, opt , "target/scruffy-usage2");
}
public void testScruffyStart1() throws JAXBException {
setNamespaces();
WasStartedBy start1 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start1.setTime(pFactory.newTimeNow());
WasStartedBy start2 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { start1, start2 };
makeDocAndTest(statements, opt , "target/scruffy-start1");
}
public void testScruffyStart2() throws JAXBException {
setNamespaces();
WasStartedBy start1 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start1.setTime(pFactory.newTimeNow());
start1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
WasStartedBy start2 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
start2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { start1, start2 };
makeDocAndTest(statements, opt , "target/scruffy-start2");
}
public void testScruffyStart3() throws JAXBException {
setNamespaces();
WasStartedBy start1 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start1.setTime(pFactory.newTimeNow());
start1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
start1.setStarter(pFactory.newActivityRef(q("a1s")));
WasStartedBy start2 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
start2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
start2.setStarter(pFactory.newActivityRef(q("a2s")));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Activity a2=pFactory.newActivity(q("a2"));
Activity a2s=pFactory.newActivity(q("a2s"));
Statement [] opt=new Statement[] { e1, a1, a2, a2s };
Statement [] statements=new Statement[] { start1, start2 };
makeDocAndTest(statements, opt , "target/scruffy-start3");
}
public void testScruffyStart4() throws JAXBException {
setNamespaces();
WasStartedBy start1 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
start1.setTime(pFactory.newTimeNow());
start1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
start1.setStarter(pFactory.newActivityRef(q("a1s")));
WasStartedBy start2 = pFactory.newWasStartedBy(q("start1"),
pFactory.newActivityRef(q("a2")),
pFactory.newEntityRef(q("e2")));
start2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
start2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
start2.setStarter(pFactory.newActivityRef(q("a2s")));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Activity a1s=pFactory.newActivity(q("a1s"));
Entity e2=pFactory.newEntity(q("e2"));
Activity a2=pFactory.newActivity(q("a2"));
Activity a2s=pFactory.newActivity(q("a2s"));
Statement [] opt=new Statement[] { e1, a1, a1s, e2, a2, a2s };
Statement [] statements=new Statement[] { start1, start2 };
makeDocAndTest(statements, opt , "target/scruffy-start4");
}
public void testScruffyEnd1() throws JAXBException {
setNamespaces();
WasEndedBy end1 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end1.setTime(pFactory.newTimeNow());
WasEndedBy end2 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { end1, end2 };
makeDocAndTest(statements, opt , "target/scruffy-end1");
}
public void testScruffyEnd2() throws JAXBException {
setNamespaces();
WasEndedBy end1 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end1.setTime(pFactory.newTimeNow());
end1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
WasEndedBy end2 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
end2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Statement [] opt=new Statement[] { e1, a1 };
Statement [] statements=new Statement[] { end1, end2 };
makeDocAndTest(statements, opt , "target/scruffy-end2");
}
public void testScruffyEnd3() throws JAXBException {
setNamespaces();
WasEndedBy end1 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end1.setTime(pFactory.newTimeNow());
end1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
end1.setEnder(pFactory.newActivityRef(q("a1s")));
WasEndedBy end2 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
end2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
end2.setEnder(pFactory.newActivityRef(q("a2s")));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Activity a2=pFactory.newActivity(q("a2"));
Activity a2s=pFactory.newActivity(q("a2s"));
Statement [] opt=new Statement[] { e1, a1, a2, a2s };
Statement [] statements=new Statement[] { end1, end2 };
makeDocAndTest(statements, opt , "target/scruffy-end3");
}
public void testScruffyEnd4() throws JAXBException {
setNamespaces();
WasEndedBy end1 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a1")),
pFactory.newEntityRef(q("e1")));
end1.setTime(pFactory.newTimeNow());
end1.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hello", ValueConverter.QNAME_XSD_STRING));
end1.setEnder(pFactory.newActivityRef(q("a1s")));
WasEndedBy end2 = pFactory.newWasEndedBy(q("end1"),
pFactory.newActivityRef(q("a2")),
pFactory.newEntityRef(q("e2")));
end2.setTime(pFactory.newISOTime("2012-12-03T21:08:16.686Z"));
end2.getAny().add(pFactory.newAttribute(EX_NS,"tag2",EX_PREFIX, "hi", ValueConverter.QNAME_XSD_STRING));
end2.setEnder(pFactory.newActivityRef(q("a2s")));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
Activity a1s=pFactory.newActivity(q("a1s"));
Entity e2=pFactory.newEntity(q("e2"));
Activity a2=pFactory.newActivity(q("a2"));
Activity a2s=pFactory.newActivity(q("a2s"));
Statement [] opt=new Statement[] { e1, a1, a1s, e2, a2, a2s };
Statement [] statements=new Statement[] { end1, end2 };
makeDocAndTest(statements, opt , "target/scruffy-end4");
}
public void testBundle1 () throws JAXBException {
setNamespaces();
Used use1 = pFactory.newUsed(q("use1"),
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
List<Statement> st1=new LinkedList<Statement>();
st1.add(a1);
st1.add(e1);
st1.add(use1);
NamedBundle b1=pFactory.newNamedBundle(q("bundle1"), st1);
Used use2 = pFactory.newUsed(q("use2"),
pFactory.newActivityRef(q("aa1")),
null,
pFactory.newEntityRef(q("ee1")));
Entity ee1=pFactory.newEntity(q("ee1"));
Activity aa1=pFactory.newActivity(q("aa1"));
List<Statement> st2=new LinkedList<Statement>();
st2.add(aa1);
st2.add(ee1);
st2.add(use2);
NamedBundle b2=pFactory.newNamedBundle(q("bundle2"), st2);
Entity eb1=pFactory.newEntity(q("bundle1"));
pFactory.addType(eb1, pFactory.newQName("prov:Bundle"));
Entity eb2=pFactory.newEntity(q("bundle2"));
pFactory.addType(eb2, pFactory.newQName("prov:Bundle"));
Statement [] statements=new Statement[] { eb1, eb2,};
NamedBundle [] bundles=new NamedBundle[] { b1, b2 };
makeDocAndTest(statements, bundles, "target/bundle1", null, true);
}
public void testBundle2 () throws JAXBException {
setNamespaces();
Used use1 = pFactory.newUsed(q("use1"),
pFactory.newActivityRef(q("a1")),
null,
pFactory.newEntityRef(q("e1")));
Entity e1=pFactory.newEntity(q("e1"));
Activity a1=pFactory.newActivity(q("a1"));
List<Statement> st1=new LinkedList<Statement>();
st1.add(a1);
st1.add(e1);
st1.add(use1);
NamedBundle b1=pFactory.newNamedBundle(q("bundle1"), st1);
Used use2 = pFactory.newUsed(q("use2"),
pFactory.newActivityRef(q("e1")),
null,
pFactory.newEntityRef(q("a1")));
Entity ee1=pFactory.newEntity(q("a1"));
Activity aa1=pFactory.newActivity(q("e1"));
List<Statement> st2=new LinkedList<Statement>();
st2.add(aa1);
st2.add(ee1);
st2.add(use2);
NamedBundle b2=pFactory.newNamedBundle(q("bundle2"), st2);
Entity eb1=pFactory.newEntity(q("bundle1"));
pFactory.addType(eb1, pFactory.newQName("prov:Bundle"));
Entity eb2=pFactory.newEntity(q("bundle2"));
pFactory.addType(eb2, pFactory.newQName("prov:Bundle"));
Statement [] statements=new Statement[] { eb1, eb2,};
NamedBundle [] bundles=new NamedBundle[] { b1, b2 };
makeDocAndTest(statements, bundles, "target/bundle2", null, true);
}
public void testDictionary1 () throws JAXBException {
DerivedByInsertionFrom d1=pFactory.newDerivedByInsertionFrom(null, q("d2"), q("d1"), null, null);
Statement [] statements=new Statement[] { d1 };
Statement [] opt=new Statement[] { };
makeDocAndTest(statements, opt , "target/dictionary1");
}
public void testDictionary2 () throws JAXBException {
DerivedByInsertionFrom d2=pFactory.newDerivedByInsertionFrom(q("deriv"), q("d2"), q("d1"), null, null);
Statement [] statements=new Statement[] { d2 };
Statement [] opt=new Statement[] { };
makeDocAndTest(statements, opt , "target/dictionary2");
}
}
| round trips with dicos
| prov-xml/src/test/java/org/openprovenance/prov/xml/RoundTripFromJavaTest.java | round trips with dicos |
|
Java | mit | e34c29cedbe724b0c56cadbf8dd08e5b87bfb8aa | 0 | WesleyyC/ImageEditor,WesleyyC/Image-Editor,WesleyyC/ImageEditor,WesleyyC/Image-Editor | // This is a program that edits a picture.
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
public class TheImage {
public BufferedImage im = null;
public int[] packedData = null;
public int[][][] pixelData = null; // Unit be modified.
public int height = 0;
public int width = 0;
public int startX = 0;
public int startY = 0;
// Constructor.
public TheImage (BufferedImage image) {
im = image;
height = im.getHeight();
width = im.getWidth();
System.out.println(width);
System.out.println(height);
packedData = im.getRGB(0, 0, width, height, null, 0, width);
unpackPixels();
}
// Flip the picture horizontally.
public void flipHorizontal()
{
for (int i = 0; i < pixelData.length; i++)
{
for (int j = 0; j <= (pixelData[i].length - 1)/2; j++) // only need to go through half-way point.
{
int k = pixelData[i].length - 1 - j;
int[] temp = pixelData[i][j];
pixelData[i][j] = pixelData[i][k];
pixelData[i][k] = temp;
}
}
System.out.println("Flipped Horizontally.");
}
// Flip the picture vertically.
public void flipVertical()
{
for (int i = 0; i <= (pixelData.length - 1)/2; i++) // only need to go through half-way point.
{
for (int j = 0; j < pixelData[i].length; j++)
{
int k = pixelData.length - 1 - i;
int[] temp = pixelData[i][j];
pixelData[i][j] = pixelData[k][j];
pixelData[k][j] = temp;
}
}
System.out.println("Flipped Vertically.");
}
// Invert the color of the picture.
public void invert()
{
for (int i = 0; i < pixelData.length; i++)
{
for (int j = 0; j < pixelData[i].length; j++)
{
pixelData[i][j][0] = Math.abs (pixelData[i][j][0] - 255);
pixelData[i][j][1] = Math.abs (pixelData[i][j][1] - 255);
pixelData[i][j][2] = Math.abs (pixelData[i][j][2] - 255);
}
}
System.out.println("Inverted.");
}
public void brighten()
{
RescaleOp rescaleOp = new RescaleOp(1.2f, 15, null);
rescaleOp.filter(im, im);
System.out.println("Brighten.");
updatePixel();
}
private void updatePixel(){
packedData = im.getRGB(0, 0, width, height, null, 0, width);
pixelData = null; // Release memory first
unpackPixels();
}
// Replace the color in a certain range.
public void replaceColor(int[] oldColor, int[] newColor, int range)
{
for (int i = 0; i < pixelData.length; i++)
{
for (int j = 0; j < pixelData[i].length; j++)
{
// Every channel needs to be in the range.
if (oldColor[0] - range < pixelData[i][j][0] && pixelData[i][j][0] < oldColor[0] + range && oldColor[1] - range < pixelData[i][j][1] && pixelData[i][j][1] < oldColor[1] + range && oldColor[2] - range < pixelData[i][j][2] && pixelData[i][j][2] < oldColor[2] + range)
{
pixelData[i][j] = newColor;
}
}
}
System.out.println("Replaced color");
}
//Writes the current data in pixelData to a .png image by first packing
//the data into a 1D array of ints, then calling the write() method of
//the ImageIO class.
public boolean writeImage(File file) {
//put pixelData into packedData
packPixels();
//Write new packed array back into BufferedImage
//bi.setRGB(startX, startY, w, h, rgbArray, offset, scansize)
im.setRGB(0, 0, width, height, packedData, 0, width);
try{
ImageIO.write(im, "jpg", file);
} catch (IOException e) {
System.out.println("Writing image failed.");
return false;
}
return true;
}
//Uses bitwise operations to convert one integer into four channels,
//each with a range from 0 to 255.
public void unpackPixels() {
System.out.println("Getting pixel values from packed data...");
//This is a rows x columns array. That is, it is an array of rows.
pixelData = new int[height][width][3];
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col ++) {
pixelData[row][col][0] = (packedData[(row * width) + col] >> 16) & 0xff;
pixelData[row][col][1] = (packedData[(row * width) + col] >> 8) & 0xff;
pixelData[row][col][2] = (packedData[(row * width) + col]) & 0xff;
}
}
}
// Crop the image as a squre in the center.
public void crop(){
if(width<height){
startY=(height-width)/2;
height = width;
}else{
startX=(width-height)/2;
width = height;
}
im = im.getSubimage(startX,startY, width, height);
System.out.println("Cropped.");
}
//Uses bitwise operations to convert four integer (ranging from 0 to 255)
//into a single integer for use with the BufferedImage class.
public void packPixels() {
System.out.println("putting pixel values in packed format...");
// Pack the data from the startX and startY coordinate
for (int row = startY; row < height+startY; row ++) {
for (int col = startX; col < width+startX; col ++) {
packedData[((row-startY) * width) + (col-startX)] = ((255 & 0xFF) << 24) | //alpha
((pixelData[row][col][0] & 0xFF) << 16) | //red
((pixelData[row][col][1] & 0xFF) << 8) | //green
((pixelData[row][col][2] & 0xFF) << 0); //blue
}
}
}
}
| TheImage.java | // This is a program that edits a picture.
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
public class TheImage {
public BufferedImage im = null;
public int[] packedData = null;
public int[][][] pixelData = null; // Unit be modified.
public int height = 0;
public int width = 0;
public int startX = 0;
public int startY = 0;
// Constructor.
public TheImage (BufferedImage image) {
im = image;
height = im.getHeight();
width = im.getWidth();
System.out.println(width);
System.out.println(height);
packedData = im.getRGB(0, 0, width, height, null, 0, width);
unpackPixels();
}
// Flip the picture horizontally.
public void flipHorizontal()
{
for (int i = 0; i < pixelData.length; i++)
{
for (int j = 0; j <= (pixelData[i].length - 1)/2; j++) // only need to go through half-way point.
{
int k = pixelData[i].length - 1 - j;
int[] temp = pixelData[i][j];
pixelData[i][j] = pixelData[i][k];
pixelData[i][k] = temp;
}
}
System.out.println("Flipped Horizontally.");
}
// Flip the picture vertically.
public void flipVertical()
{
for (int i = 0; i <= (pixelData.length - 1)/2; i++) // only need to go through half-way point.
{
for (int j = 0; j < pixelData[i].length; j++)
{
int k = pixelData.length - 1 - i;
int[] temp = pixelData[i][j];
pixelData[i][j] = pixelData[k][j];
pixelData[k][j] = temp;
}
}
System.out.println("Flipped Vertically.");
}
// Invert the color of the picture.
public void invert()
{
for (int i = 0; i < pixelData.length; i++)
{
for (int j = 0; j < pixelData[i].length; j++)
{
pixelData[i][j][0] = Math.abs (pixelData[i][j][0] - 255);
pixelData[i][j][1] = Math.abs (pixelData[i][j][1] - 255);
pixelData[i][j][2] = Math.abs (pixelData[i][j][2] - 255);
}
}
System.out.println("Inverted.");
}
public void brighten()
{
for (int i = 0; i < pixelData.length; i++)
{
for (int j = 0; j < pixelData[i].length; j++)
{
pixelData[i][j][0] = (int) (pixelData[i][j][0] * 1.1);
pixelData[i][j][1] = (int) (pixelData[i][j][1] * 1.1);
pixelData[i][j][2] = (int) (pixelData[i][j][2] * 1.1);
}
}
System.out.println("Brighten 50%.");
}
// Replace the color in a certain range.
public void replaceColor(int[] oldColor, int[] newColor, int range)
{
for (int i = 0; i < pixelData.length; i++)
{
for (int j = 0; j < pixelData[i].length; j++)
{
// Every channel needs to be in the range.
if (oldColor[0] - range < pixelData[i][j][0] && pixelData[i][j][0] < oldColor[0] + range && oldColor[1] - range < pixelData[i][j][1] && pixelData[i][j][1] < oldColor[1] + range && oldColor[2] - range < pixelData[i][j][2] && pixelData[i][j][2] < oldColor[2] + range)
{
pixelData[i][j] = newColor;
}
}
}
System.out.println("Replaced color");
}
//Writes the current data in pixelData to a .png image by first packing
//the data into a 1D array of ints, then calling the write() method of
//the ImageIO class.
public boolean writeImage(File file) {
//put pixelData into packedData
packPixels();
//Write new packed array back into BufferedImage
//bi.setRGB(startX, startY, w, h, rgbArray, offset, scansize)
im.setRGB(0, 0, width, height, packedData, 0, width);
try{
ImageIO.write(im, "jpg", file);
} catch (IOException e) {
System.out.println("Writing image failed.");
return false;
}
return true;
}
//Uses bitwise operations to convert one integer into four channels,
//each with a range from 0 to 255.
public void unpackPixels() {
System.out.println("Getting pixel values from packed data...");
//This is a rows x columns array. That is, it is an array of rows.
pixelData = new int[height][width][3];
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col ++) {
pixelData[row][col][0] = (packedData[(row * width) + col] >> 16) & 0xff;
pixelData[row][col][1] = (packedData[(row * width) + col] >> 8) & 0xff;
pixelData[row][col][2] = (packedData[(row * width) + col]) & 0xff;
}
}
}
// Crop the image as a squre in the center.
public void crop(){
if(width<height){
startY=(height-width)/2;
height = width;
}else{
startX=(width-height)/2;
width = height;
}
im = im.getSubimage(startX,startY, width, height);
System.out.println("Cropped.");
}
//Uses bitwise operations to convert four integer (ranging from 0 to 255)
//into a single integer for use with the BufferedImage class.
public void packPixels() {
System.out.println("putting pixel values in packed format...");
// Pack the data from the startX and startY coordinate
for (int row = startY; row < height+startY; row ++) {
for (int col = startX; col < width+startX; col ++) {
packedData[((row-startY) * width) + (col-startX)] = ((255 & 0xFF) << 24) | //alpha
((pixelData[row][col][0] & 0xFF) << 16) | //red
((pixelData[row][col][1] & 0xFF) << 8) | //green
((pixelData[row][col][2] & 0xFF) << 0); //blue
}
}
}
}
| birhten function
| TheImage.java | birhten function |
|
Java | mit | e32736739171e023a55d28fb997ec32fed4346d9 | 0 | Ordinastie/MalisisCore | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Ordinastie
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.malisis.core.client.gui.component.interaction;
import java.util.Collections;
import java.util.Iterator;
import net.malisis.core.client.gui.ClipArea;
import net.malisis.core.client.gui.GuiRenderer;
import net.malisis.core.client.gui.MalisisGui;
import net.malisis.core.client.gui.component.IClipable;
import net.malisis.core.client.gui.component.UIComponent;
import net.malisis.core.client.gui.component.interaction.UISelect.Option;
import net.malisis.core.client.gui.element.GuiShape;
import net.malisis.core.client.gui.element.SimpleGuiShape;
import net.malisis.core.client.gui.element.XResizableGuiShape;
import net.malisis.core.client.gui.element.XYResizableGuiShape;
import net.malisis.core.client.gui.event.ComponentEvent.ValueChange;
import net.malisis.core.client.gui.icon.GuiIcon;
import net.minecraft.util.EnumChatFormatting;
import org.apache.commons.lang3.StringUtils;
import org.lwjgl.input.Keyboard;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterables;
/**
* The Class UISelect.
*
* @author Ordinastie
*/
public class UISelect<T> extends UIComponent<UISelect<T>> implements Iterable<Option<T>>, IClipable
{
/** The {@link Option options} of this {@link UISelect}. */
protected FluentIterable<Option<T>> options;
/** Currently selected option index. */
protected Option<T> selectedOption = null;
/** Max width of the option container. */
protected int maxExpandedWidth = -1;
/** Max number displayed options. */
protected int maxDisplayedOptions = -1;
/** Whether this {@link UISelect} is expanded. */
protected boolean expanded = false;
/** Width of displayed {@link Option} box */
protected int optionsWidth = 0;
/** Height of displayed {@link Option} box */
protected int optionsHeight = 0;
/** Pattern to use for options labels. */
protected String labelPattern;
/** Function for option creation **/
protected Function<T, ? extends Option<T>> optionFunction;
/** Function for options label */
protected Function<T, String> labelFunction = (Function<T, String>) Functions.toStringFunction();
/** Predicate for option disability */
protected Predicate<T> disablePredicate = Predicates.alwaysFalse();
private Function<T, Option<T>> toOption = new Function<T, Option<T>>()
{
@Override
public Option<T> apply(T input)
{
Option<T> option = optionFunction != null ? optionFunction.apply(input) : new Option(input);
option.setLabel(labelFunction.apply(input));
option.setDisabled(disablePredicate.apply(input));
return option;
}
};
/** Text color. */
protected int textColor = 0xFFFFFF;
/** Background color */
protected int bgColor = 0xFFFFFF;
/** Hovered text color */
protected int hoverTextColor = 0xDED89F;
/** Hovered background color */
protected int hoverBgColor = 0x5E789F;
/** Selected text color */
protected int selectTextColor = 0x9EA8DF;
/* Disabled text color */
protected int disabledTextColor = 0x444444;
/** Text shadow */
protected boolean textShadow = true;
/** Shape used to draw the arrow. */
protected GuiShape arrowShape;
/** Shape used to draw the {@link Option options} box */
protected GuiShape optionsShape;
/** Shape used to draw the hovered {@link Option} background **/
protected GuiShape optionBackground;
/** Icon used to draw this {@link UISelect}. */
protected GuiIcon iconsSelect;
/** Icon used to draw this {@link UISelect} when disabled. */
protected GuiIcon iconsSelectDisabled;
/** Icon used to draw the option container. */
protected GuiIcon iconsExpanded;
/** Icon used to draw the arrow. */
protected GuiIcon arrowIcon;
/**
* Instantiates a new {@link UISelect}
*
* @param gui the gui
* @param width the width
* @param options the options
*/
public UISelect(MalisisGui gui, int width, Iterable<T> values)
{
super(gui);
setSize(width, 12);
setOptions(values);
shape = new XResizableGuiShape(3);
arrowShape = new SimpleGuiShape();
arrowShape.setSize(7, 4);
arrowShape.storeState();
optionsShape = new XYResizableGuiShape(1);
optionBackground = new SimpleGuiShape();
iconsSelect = gui.getGuiTexture().getXResizableIcon(200, 30, 9, 12, 3);
iconsSelectDisabled = gui.getGuiTexture().getXResizableIcon(200, 42, 9, 12, 3);
iconsExpanded = gui.getGuiTexture().getXYResizableIcon(200, 30, 9, 12, 1);
arrowIcon = gui.getGuiTexture().getIcon(209, 48, 7, 4);
}
/**
* Instantiates a new {@link UISelect}.
*
* @param gui the gui
* @param width the width
*/
public UISelect(MalisisGui gui, int width)
{
this(gui, width, null);
}
//#region Getters/Setters
public int getTextColor()
{
return textColor;
}
public UISelect<T> setTextColor(int textColor)
{
this.textColor = textColor;
return this;
}
public int getBgColor()
{
return bgColor;
}
public UISelect<T> setBgColor(int bgColor)
{
this.bgColor = bgColor;
return this;
}
public int getHoverTextColor()
{
return hoverTextColor;
}
public UISelect<T> setHoverTextColor(int hoverTextColor)
{
this.hoverTextColor = hoverTextColor;
return this;
}
public int getHoverBgColor()
{
return hoverBgColor;
}
public UISelect<T> setHoverBgColor(int hoverBgColor)
{
this.hoverBgColor = hoverBgColor;
return this;
}
public int getSelectTextColor()
{
return selectTextColor;
}
public UISelect<T> setSelectTextColor(int selectTextColor)
{
this.selectTextColor = selectTextColor;
return this;
}
public int getDisabledTextColor()
{
return disabledTextColor;
}
public UISelect<T> setDisabledTextColor(int disabledTextColor)
{
this.disabledTextColor = disabledTextColor;
return this;
}
public boolean isTextShadow()
{
return textShadow;
}
public UISelect<T> setTextShadow(boolean textShadow)
{
this.textShadow = textShadow;
return this;
}
public UISelect<T> setColors(int textColor, int bgColor, int hoverTextColor, int hoverBgColor, int selectTextColor, int disabledTextColor, boolean textShadow)
{
this.textColor = textColor;
this.bgColor = bgColor;
this.hoverTextColor = hoverTextColor;
this.hoverBgColor = hoverBgColor;
this.selectTextColor = selectTextColor;
this.disabledTextColor = disabledTextColor;
this.textShadow = textShadow;
return this;
}
public UISelect<T> setOptionFunction(Function<T, ? extends Option<T>> func)
{
this.optionFunction = func;
return this;
}
public UISelect<T> setLabelFunction(Function<T, String> func)
{
if (func == null)
func = (Function<T, String>) Functions.toStringFunction();
this.labelFunction = func;
calcOptionsSize();
return this;
}
public UISelect<T> setDisablePredicate(Predicate<T> predicate)
{
if (predicate == null)
predicate = Predicates.alwaysFalse();
this.disablePredicate = predicate;
return this;
}
//#end Getters/Setters
@Override
public void setFocused(boolean focused)
{
super.setFocused(focused);
if (!focused && expanded)
expanded = false;
}
/**
* Sets a pattern that will be used to format the option label.
*
* @param labelPattern the label pattern
* @return this {@link UISelect}
*/
public UISelect<T> setLabelPattern(String labelPattern)
{
this.labelPattern = labelPattern;
calcOptionsSize();
return this;
}
/**
* Sets the max width of the option container.
*
* @param width the width
* @return this {@link UISelect}
*/
public UISelect<T> setMaxExpandedWidth(int width)
{
maxExpandedWidth = width;
calcOptionsSize();
return this;
}
/**
* Calculates the size of this container base on the options. TODO : handle maximum display options
*/
private void calcOptionsSize()
{
optionsWidth = getWidth() - 4;
for (Option<?> option : this)
optionsWidth = Math.max(optionsWidth, GuiRenderer.getStringWidth(option.getLabel(labelPattern)));
optionsWidth += 4;
if (maxExpandedWidth > 0)
optionsWidth = Math.min(maxExpandedWidth, optionsWidth);
}
/**
* Sets the maximum number of options displayed when expanded.
*
* @param amount the amount
* @return this {@link UISelect}
*/
public UISelect<T> maxDisplayedOptions(int amount)
{
maxDisplayedOptions = amount;
calcOptionsSize();
return this;
}
/**
* Set the {@link Option options} to use for this {@link UISelect}
*
* @param options the options
* @return this {@link UISelect}
*/
public UISelect<T> setOptions(Iterable<T> values)
{
if (values == null)
values = Collections.EMPTY_LIST;
options = FluentIterable.from(values).transform(toOption);
calcOptionsSize();
return this;
}
/**
* Gets the {@link Option} corresponding to the object.
*
* @param obj the key of the Option
* @return the option
*/
public Option getOption(T obj)
{
for (Option<T> opt : this)
if (obj == opt.getKey())
return opt;
return null;
}
public Option getOption(int y)
{
//TODO
return null;
}
/**
* Sets the selected {@link Option} from its containing key.
*
* @param obj the new selected option
*/
public void setSelectedOption(T obj)
{
setSelectedOption(getOption(obj));
}
/**
* Sets the selected {@link Option}.
*
* @param option the new selected option
*/
public void setSelectedOption(Option<T> option)
{
selectedOption = option;
}
/**
* Gets the currently selected {@link Option}.
*
* @return the selected option
*/
public Option getSelectedOption()
{
return selectedOption;
}
/**
* Gets the value of the {@link #selectedOption}.
*
* @return the selected value
*/
public T getSelectedValue()
{
Option<T> opt = getSelectedOption();
if (opt == null)
return null;
return opt.getKey();
}
/**
* Select the {@link Option} using the index.
*
* @param index the index
* @return the option
*/
public T select(Option<T> option)
{
if (option == null || option.isDisabled())
return getSelectedValue();
T value = option != null ? option.getKey() : null;
if (option.equals(selectedOption))
return value;
if (fireEvent(new SelectEvent<T>(this, value)))
setSelectedOption(option);
return getSelectedValue();
}
public T select(T obj)
{
return select(getOption(obj));
}
public T selectFirst()
{
return select(Iterables.getFirst(options, null));
}
public T selectLast()
{
return select(Iterables.getLast(options, null));
}
public T selectPrevious()
{
if (selectedOption == null)
return selectFirst();
Option<T> option = null;
for (Option<T> opt : this)
{
if (opt.isDisabled())
continue;
if (opt.equals(selectedOption))
return select(option);
option = opt;
}
//should not happen
return null;
}
public T selectNext()
{
if (selectedOption == null)
return selectFirst();
Option<T> option = null;
for (Option<T> opt : this)
{
if (opt.isDisabled())
continue;
if (selectedOption.equals(option))
return select(opt);
option = opt;
}
//should not happen
return null;
}
protected Option getHoveredOption(int mouseX, int mouseY)
{
if (!isInsideBounds(mouseX, mouseY))
return null;
int y = relativeY(mouseY - 13);
if (y < 0)
return null;
int cy = 0;
for (Option<T> option : this)
{
if (cy + option.getHeight() > y)
return option;
cy += option.getHeight();
}
return null;
}
@Override
public boolean isInsideBounds(int x, int y)
{
if (super.isInsideBounds(x, y))
return true;
if (!expanded || !isVisible())
return false;
return x >= screenX() && x <= screenX() + optionsWidth && y >= screenY() + 12 && y <= screenY() + 12 + optionsHeight;
}
@Override
public int getZIndex()
{
return super.getZIndex() + (expanded ? 300 : 0);
}
public boolean isOptionHovered(Option option)
{
return false;
}
@Override
public ClipArea getClipArea()
{
return new ClipArea(this, screenX(), screenY(), screenX() + optionsWidth, screenY() + optionsHeight + 12, false);
}
@Override
public void setClipContent(boolean clip)
{}
@Override
public boolean shouldClipContent()
{
return expanded;
}
@Override
public void drawBackground(GuiRenderer renderer, int mouseX, int mouseY, float partialTick)
{
shape.resetState();
shape.setSize(super.getWidth(), super.getHeight());
rp.icon.set(isDisabled() ? iconsSelectDisabled : iconsSelect);
rp.colorMultiplier.set(bgColor);
renderer.drawShape(shape, rp);
}
@Override
public void drawForeground(GuiRenderer renderer, int mouseX, int mouseY, float partialTick)
{
optionsHeight = 10 * (maxDisplayedOptions == -1 ? options.size() : maxDisplayedOptions) + 2;
if (optionsHeight < 10)
optionsHeight = 10;
if (selectedOption != null)
select(selectedOption.getKey());
//draw regular select
arrowShape.resetState();
arrowShape.setPosition(width - 9, 4);
if (isHovered() || expanded)
rp.colorMultiplier.set(0xBEC8FF);
else
rp.colorMultiplier.reset();
rp.icon.set(arrowIcon);
renderer.drawShape(arrowShape, rp);
//draw selected value
if (selectedOption != null)
{
selectedOption.draw(this, renderer, 2, 2, 2, partialTick, false, true);
}
if (!expanded)
return;
renderer.next();
ClipArea area = getClipArea();
renderer.startClipping(area);
optionsShape.resetState();
optionsShape.setSize(optionsWidth, optionsHeight);
optionsShape.translate(0, 12, 1);
rp.icon.set(iconsExpanded);
rp.colorMultiplier.set(bgColor);
renderer.drawShape(optionsShape, rp);
renderer.next();
int y = 14;
Option hover = getHoveredOption(mouseX, mouseY);
for (Option option : this)
{
option.draw(this, renderer, 0, y, 0, partialTick, option.equals(hover), false);
y += option.getHeight();
}
renderer.endClipping(area);
}
@Override
public boolean onClick(int x, int y)
{
if (!expanded)
{
expanded = true;
return true;
}
Option opt = getHoveredOption(x, y);
if (opt != null)
{
if (opt.isDisabled())
{
setFocused(true);
return true;
}
select(opt);
}
expanded = false;
setFocused(true);
return true;
}
@Override
public boolean onScrollWheel(int x, int y, int delta)
{
if (!isFocused())
return super.onScrollWheel(x, y, delta);
if (delta < 0)
selectNext();
else
selectPrevious();
return true;
}
@Override
public boolean onKeyTyped(char keyChar, int keyCode)
{
if (!isFocused())
return super.onKeyTyped(keyChar, keyCode);
switch (keyCode)
{
case Keyboard.KEY_UP:
selectPrevious();
break;
case Keyboard.KEY_DOWN:
selectNext();
break;
case Keyboard.KEY_HOME:
selectFirst();
break;
case Keyboard.KEY_END:
selectLast();
break;
default:
return super.onKeyTyped(keyChar, keyCode);
}
return true;
}
@Override
public Iterator<Option<T>> iterator()
{
return options.iterator();
}
/**
* The Class Option.
*
* @param <T> the generic type
*/
public static class Option<T>
{
/** The key. */
private T key;
/** The label. */
private String label;
/** Whether this option is disabled */
private boolean disabled;
/**
* Instantiates a new {@link Option}.
*
* @param index the index
* @param key the key
* @param value the value
*/
public Option(T key)
{
this.key = key;
}
public Option(T key, String label)
{
this.key = key;
this.label = label;
}
/**
* Gets the key of this {@link Option}.
*
* @return the key
*/
public T getKey()
{
return key;
}
/**
* Gets the label of this {@link Option} using a pattern.
*
* @param pattern the pattern
* @return the label
*/
public String getLabel(String pattern)
{
if (pattern == null)
return label;
return String.format(pattern, label);
}
/**
* Gets the base label of this {@link Option}.
*
* @return the label
*/
public String getLabel()
{
return label;
}
/**
* Sets the label for this {@link Option}.
*
* @param label the new label
*/
public void setLabel(String label)
{
this.label = label;
}
/**
* Checks if this {@link Option} is disabled.
*
* @return true, if is disabled
*/
public boolean isDisabled()
{
return disabled;
}
/**
* Sets the disabled state of this {@link Option}.
*
* @param disabled the new disabled
*/
public void setDisabled(boolean disabled)
{
this.disabled = disabled;
}
public int getHeight()
{
return GuiRenderer.getStringHeight() + 1;
}
public void draw(UISelect select, GuiRenderer renderer, int x, int y, int z, float partialTick, boolean hovered, boolean isTop)
{
String text = getLabel(select.labelPattern);
if (StringUtils.isEmpty(text))
return;
if (hovered && !disabled)
{
renderer.drawRectangle(x + 1, y - 1, z + 2, select.optionsWidth - 2, getHeight(), select.getHoverBgColor(), 255);
}
if (isTop)
text = GuiRenderer.clipString(text, select.getWidth() - 15);
int color = equals(select.getSelectedOption()) && !isTop ? select.getSelectTextColor() : select.getTextColor();
boolean shadow = select.isTextShadow();
if (hovered)
color = select.getHoverTextColor();
if (disabled)
{
text = EnumChatFormatting.ITALIC + text;
color = select.getDisabledTextColor();
shadow = false;
}
renderer.drawText(text, x + 2, y, z + 2, color, shadow, true);
}
@Override
public boolean equals(Object obj)
{
return obj != null && obj instanceof Option && key.equals(((Option) obj).key);
}
}
/**
* Event fired when a {@link UISelect} changes its selected {@link Option}.<br>
* When catching the event, the state is not applied to the {@code UISelect} yet.<br>
* Cancelling the event will prevent the {@code Option} to be set for the {@code UISelect} .
*/
public static class SelectEvent<T> extends ValueChange<UISelect, T>
{
public SelectEvent(UISelect<T> component, T newValue)
{
super(component, component.getSelectedValue(), newValue);
}
}
}
| src/main/java/net/malisis/core/client/gui/component/interaction/UISelect.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Ordinastie
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.malisis.core.client.gui.component.interaction;
import java.util.Collections;
import java.util.Iterator;
import net.malisis.core.client.gui.ClipArea;
import net.malisis.core.client.gui.GuiRenderer;
import net.malisis.core.client.gui.MalisisGui;
import net.malisis.core.client.gui.component.IClipable;
import net.malisis.core.client.gui.component.UIComponent;
import net.malisis.core.client.gui.component.interaction.UISelect.Option;
import net.malisis.core.client.gui.element.GuiShape;
import net.malisis.core.client.gui.element.SimpleGuiShape;
import net.malisis.core.client.gui.element.XResizableGuiShape;
import net.malisis.core.client.gui.element.XYResizableGuiShape;
import net.malisis.core.client.gui.event.ComponentEvent.ValueChange;
import net.malisis.core.client.gui.icon.GuiIcon;
import net.minecraft.util.EnumChatFormatting;
import org.apache.commons.lang3.StringUtils;
import org.lwjgl.input.Keyboard;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterables;
/**
* The Class UISelect.
*
* @author Ordinastie
*/
public class UISelect<T> extends UIComponent<UISelect<T>> implements Iterable<Option<T>>, IClipable
{
/** The {@link Option options} of this {@link UISelect}. */
protected FluentIterable<Option<T>> options;
/** Currently selected option index. */
protected Option<T> selectedOption = null;
/** Max width of the option container. */
protected int maxExpandedWidth = -1;
/** Max number displayed options. */
protected int maxDisplayedOptions = -1;
/** Whether this {@link UISelect} is expanded. */
protected boolean expanded = false;
/** Width of displayed {@link Option} box */
protected int optionsWidth = 0;
/** Height of displayed {@link Option} box */
protected int optionsHeight = 0;
/** Pattern to use for options labels. */
protected String labelPattern;
/** Function for option creation **/
protected Function<T, ? extends Option<T>> optionFunction;
/** Function for options label */
protected Function<T, String> labelFunction = (Function<T, String>) Functions.toStringFunction();
/** Predicate for option disability */
protected Predicate<T> disablePredicate = Predicates.alwaysFalse();
private Function<T, Option<T>> toOption = new Function<T, Option<T>>()
{
@Override
public Option<T> apply(T input)
{
Option<T> option = optionFunction != null ? optionFunction.apply(input) : new Option(input);
option.setLabel(labelFunction.apply(input));
option.setDisabled(disablePredicate.apply(input));
return option;
}
};
/** Text color. */
protected int textColor = 0xFFFFFF;
/** Background color */
protected int bgColor = 0xFFFFFF;
/** Hovered text color */
protected int hoverTextColor = 0xDED89F;
/** Hovered background color */
protected int hoverBgColor = 0x5E789F;
/** Selected text color */
protected int selectTextColor = 0x9EA8DF;
/* Disabled text color */
protected int disabledTextColor = 0x444444;
/** Text shadow */
protected boolean textShadow = true;
/** Shape used to draw the arrow. */
protected GuiShape arrowShape;
/** Shape used to draw the {@link Option options} box */
protected GuiShape optionsShape;
/** Shape used to draw the hovered {@link Option} background **/
protected GuiShape optionBackground;
/** Icon used to draw this {@link UISelect}. */
protected GuiIcon iconsSelect;
/** Icon used to draw this {@link UISelect} when disabled. */
protected GuiIcon iconsSelectDisabled;
/** Icon used to draw the option container. */
protected GuiIcon iconsExpanded;
/** Icon used to draw the arrow. */
protected GuiIcon arrowIcon;
/**
* Instantiates a new {@link UISelect}
*
* @param gui the gui
* @param width the width
* @param options the options
*/
public UISelect(MalisisGui gui, int width, Iterable<T> values)
{
super(gui);
setSize(width, 12);
setOptions(values);
shape = new XResizableGuiShape(3);
arrowShape = new SimpleGuiShape();
arrowShape.setSize(7, 4);
arrowShape.storeState();
optionsShape = new XYResizableGuiShape(1);
optionBackground = new SimpleGuiShape();
iconsSelect = gui.getGuiTexture().getXResizableIcon(200, 30, 9, 12, 3);
iconsSelectDisabled = gui.getGuiTexture().getXResizableIcon(200, 42, 9, 12, 3);
iconsExpanded = gui.getGuiTexture().getXYResizableIcon(200, 30, 9, 12, 1);
arrowIcon = gui.getGuiTexture().getIcon(209, 48, 7, 4);
}
/**
* Instantiates a new {@link UISelect}.
*
* @param gui the gui
* @param width the width
*/
public UISelect(MalisisGui gui, int width)
{
this(gui, width, null);
}
//#region Getters/Setters
public int getTextColor()
{
return textColor;
}
public UISelect<T> setTextColor(int textColor)
{
this.textColor = textColor;
return this;
}
public int getBgColor()
{
return bgColor;
}
public UISelect<T> setBgColor(int bgColor)
{
this.bgColor = bgColor;
return this;
}
public int getHoverTextColor()
{
return hoverTextColor;
}
public UISelect<T> setHoverTextColor(int hoverTextColor)
{
this.hoverTextColor = hoverTextColor;
return this;
}
public int getHoverBgColor()
{
return hoverBgColor;
}
public UISelect<T> setHoverBgColor(int hoverBgColor)
{
this.hoverBgColor = hoverBgColor;
return this;
}
public int getSelectTextColor()
{
return selectTextColor;
}
public UISelect<T> setSelectTextColor(int selectTextColor)
{
this.selectTextColor = selectTextColor;
return this;
}
public int getDisabledTextColor()
{
return disabledTextColor;
}
public UISelect<T> setDisabledTextColor(int disabledTextColor)
{
this.disabledTextColor = disabledTextColor;
return this;
}
public boolean isTextShadow()
{
return textShadow;
}
public UISelect<T> setTextShadow(boolean textShadow)
{
this.textShadow = textShadow;
return this;
}
public UISelect<T> setColors(int textColor, int bgColor, int hoverTextColor, int hoverBgColor, int selectTextColor, int disabledTextColor, boolean textShadow)
{
this.textColor = textColor;
this.bgColor = bgColor;
this.hoverTextColor = hoverTextColor;
this.hoverBgColor = hoverBgColor;
this.selectTextColor = selectTextColor;
this.disabledTextColor = disabledTextColor;
this.textShadow = textShadow;
return this;
}
public UISelect<T> setOptionFunction(Function<T, ? extends Option<T>> func)
{
this.optionFunction = func;
return this;
}
public UISelect<T> setLabelFunction(Function<T, String> func)
{
if (func == null)
func = (Function<T, String>) Functions.toStringFunction();
this.labelFunction = func;
return this;
}
public UISelect<T> setDisablePredicate(Predicate<T> predicate)
{
if (predicate == null)
predicate = Predicates.alwaysFalse();
this.disablePredicate = predicate;
return this;
}
//#end Getters/Setters
@Override
public void setFocused(boolean focused)
{
super.setFocused(focused);
if (!focused && expanded)
expanded = false;
}
/**
* Sets a pattern that will be used to format the option label.
*
* @param labelPattern the label pattern
* @return this {@link UISelect}
*/
public UISelect<T> setLabelPattern(String labelPattern)
{
this.labelPattern = labelPattern;
calcOptionsSize();
return this;
}
/**
* Sets the max width of the option container.
*
* @param width the width
* @return this {@link UISelect}
*/
public UISelect<T> setMaxExpandedWidth(int width)
{
maxExpandedWidth = width;
calcOptionsSize();
return this;
}
/**
* Calculates the size of this container base on the options. TODO : handle maximum display options
*/
private void calcOptionsSize()
{
optionsWidth = getWidth();
for (Option<?> option : this)
optionsWidth = Math.max(optionsWidth, GuiRenderer.getStringWidth(option.getLabel(labelPattern)));
optionsWidth += 4;
if (maxExpandedWidth > 0)
optionsWidth = Math.min(maxExpandedWidth, optionsWidth);
}
/**
* Sets the maximum number of options displayed when expanded.
*
* @param amount the amount
* @return this {@link UISelect}
*/
public UISelect<T> maxDisplayedOptions(int amount)
{
maxDisplayedOptions = amount;
calcOptionsSize();
return this;
}
/**
* Set the {@link Option options} to use for this {@link UISelect}
*
* @param options the options
* @return this {@link UISelect}
*/
public UISelect<T> setOptions(Iterable<T> values)
{
if (values == null)
values = Collections.EMPTY_LIST;
options = FluentIterable.from(values).transform(toOption);
calcOptionsSize();
return this;
}
/**
* Gets the {@link Option} corresponding to the object.
*
* @param obj the key of the Option
* @return the option
*/
public Option getOption(T obj)
{
for (Option<T> opt : this)
if (obj == opt.getKey())
return opt;
return null;
}
public Option getOption(int y)
{
//TODO
return null;
}
/**
* Sets the selected {@link Option} from its containing key.
*
* @param obj the new selected option
*/
public void setSelectedOption(T obj)
{
setSelectedOption(getOption(obj));
}
/**
* Sets the selected {@link Option}.
*
* @param option the new selected option
*/
public void setSelectedOption(Option<T> option)
{
selectedOption = option;
}
/**
* Gets the currently selected {@link Option}.
*
* @return the selected option
*/
public Option getSelectedOption()
{
return selectedOption;
}
/**
* Gets the value of the {@link #selectedOption}.
*
* @return the selected value
*/
public T getSelectedValue()
{
Option<T> opt = getSelectedOption();
if (opt == null)
return null;
return opt.getKey();
}
/**
* Select the {@link Option} using the index.
*
* @param index the index
* @return the option
*/
public T select(Option<T> option)
{
if (option.isDisabled())
option = null;
T value = option != null ? option.getKey() : null;
if (option == selectedOption)
return value;
if (fireEvent(new SelectEvent<T>(this, value)))
setSelectedOption(option);
return getSelectedValue();
}
public T select(T obj)
{
return select(getOption(obj));
}
public T selectFirst()
{
return select(Iterables.getFirst(options, null));
}
public T selectLast()
{
return select(Iterables.getLast(options, null));
}
public T selectPrevious()
{
if (selectedOption == null)
return selectFirst();
Option<T> option = selectedOption;
for (Option<T> opt : this)
{
if (opt.isDisabled())
continue;
if (opt == selectedOption)
return select(option);
option = opt;
}
//should not happen
return null;
}
public T selectNext()
{
if (selectedOption == null)
return selectFirst();
Option<T> option = selectedOption;
for (Option<T> opt : this)
{
if (option == selectedOption)
return select(opt);
option = opt;
}
//should not happen
return null;
}
protected Option getHoveredOption(int mouseX, int mouseY)
{
if (!isInsideBounds(mouseX, mouseY))
return null;
int y = relativeY(mouseY - 13);
if (y < 0)
return null;
int cy = 0;
for (Option<T> option : this)
{
if (cy + option.getHeight() > y)
return option;
cy += option.getHeight();
}
return null;
}
@Override
public boolean isInsideBounds(int x, int y)
{
if (super.isInsideBounds(x, y))
return true;
if (!expanded || !isVisible())
return false;
return x >= screenX() && x <= screenX() + optionsWidth && y >= screenY() + 12 && y <= screenY() + 12 + optionsHeight;
}
@Override
public int getZIndex()
{
return super.getZIndex() + (expanded ? 300 : 0);
}
public boolean isOptionHovered(Option option)
{
return false;
}
@Override
public ClipArea getClipArea()
{
return new ClipArea(this, screenX(), screenY(), screenX() + optionsWidth, screenY() + optionsHeight + 12, false);
}
@Override
public void setClipContent(boolean clip)
{}
@Override
public boolean shouldClipContent()
{
return expanded;
}
@Override
public void drawBackground(GuiRenderer renderer, int mouseX, int mouseY, float partialTick)
{
shape.resetState();
shape.setSize(super.getWidth(), super.getHeight());
rp.icon.set(isDisabled() ? iconsSelectDisabled : iconsSelect);
rp.colorMultiplier.set(bgColor);
renderer.drawShape(shape, rp);
}
@Override
public void drawForeground(GuiRenderer renderer, int mouseX, int mouseY, float partialTick)
{
optionsHeight = 10 * (maxDisplayedOptions == -1 ? options.size() : maxDisplayedOptions) + 2;
if (optionsHeight < 10)
optionsHeight = 10;
if (selectedOption != null)
select(selectedOption.getKey());
//draw regular select
arrowShape.resetState();
arrowShape.setPosition(width - 9, 4);
if (isHovered() || expanded)
rp.colorMultiplier.set(0xBEC8FF);
else
rp.colorMultiplier.reset();
rp.icon.set(arrowIcon);
renderer.drawShape(arrowShape, rp);
//draw selected value
if (selectedOption != null)
{
selectedOption.draw(this, renderer, 2, 2, 2, partialTick, false, true);
}
if (!expanded)
return;
renderer.next();
ClipArea area = getClipArea();
renderer.startClipping(area);
optionsShape.resetState();
optionsShape.setSize(optionsWidth, optionsHeight);
optionsShape.translate(0, 12, 1);
rp.icon.set(iconsExpanded);
rp.colorMultiplier.set(bgColor);
renderer.drawShape(optionsShape, rp);
renderer.next();
int y = 14;
Option hover = getHoveredOption(mouseX, mouseY);
for (Option option : this)
{
option.draw(this, renderer, 0, y, 0, partialTick, option.equals(hover), false);
y += option.getHeight();
}
renderer.endClipping(area);
}
@Override
public boolean onClick(int x, int y)
{
if (!expanded)
{
expanded = true;
return true;
}
Option opt = getHoveredOption(x, y);
if (opt != null)
{
if (opt.isDisabled())
{
setFocused(true);
return true;
}
select(opt);
}
expanded = false;
setFocused(true);
return true;
}
@Override
public boolean onScrollWheel(int x, int y, int delta)
{
if (!isFocused())
return super.onScrollWheel(x, y, delta);
if (delta > 0)
selectNext();
else
selectPrevious();
return true;
}
@Override
public boolean onKeyTyped(char keyChar, int keyCode)
{
if (!isFocused())
return super.onKeyTyped(keyChar, keyCode);
switch (keyCode)
{
case Keyboard.KEY_UP:
selectPrevious();
break;
case Keyboard.KEY_DOWN:
selectNext();
break;
case Keyboard.KEY_HOME:
selectFirst();
break;
case Keyboard.KEY_END:
selectLast();
break;
default:
return super.onKeyTyped(keyChar, keyCode);
}
return true;
}
@Override
public Iterator<Option<T>> iterator()
{
return options.iterator();
}
/**
* The Class Option.
*
* @param <T> the generic type
*/
public static class Option<T>
{
/** The key. */
private T key;
/** The label. */
private String label;
/** Whether this option is disabled */
private boolean disabled;
/**
* Instantiates a new {@link Option}.
*
* @param index the index
* @param key the key
* @param value the value
*/
public Option(T key)
{
this.key = key;
}
public Option(T key, String label)
{
this.key = key;
this.label = label;
}
/**
* Gets the key of this {@link Option}.
*
* @return the key
*/
public T getKey()
{
return key;
}
/**
* Gets the label of this {@link Option} using a pattern.
*
* @param pattern the pattern
* @return the label
*/
public String getLabel(String pattern)
{
if (pattern == null)
return label;
return String.format(pattern, label);
}
/**
* Gets the base label of this {@link Option}.
*
* @return the label
*/
public String getLabel()
{
return label;
}
/**
* Sets the label for this {@link Option}.
*
* @param label the new label
*/
public void setLabel(String label)
{
this.label = label;
}
/**
* Checks if this {@link Option} is disabled.
*
* @return true, if is disabled
*/
public boolean isDisabled()
{
return disabled;
}
/**
* Sets the disabled state of this {@link Option}.
*
* @param disabled the new disabled
*/
public void setDisabled(boolean disabled)
{
this.disabled = disabled;
}
public int getHeight()
{
return GuiRenderer.getStringHeight() + 1;
}
public void draw(UISelect select, GuiRenderer renderer, int x, int y, int z, float partialTick, boolean hovered, boolean isTop)
{
String text = getLabel(select.labelPattern);
if (StringUtils.isEmpty(text))
return;
if (hovered && !disabled)
{
renderer.drawRectangle(x + 1, y - 1, z + 2, select.optionsWidth - 2, getHeight(), select.getHoverBgColor(), 255);
}
if (isTop)
text = GuiRenderer.clipString(text, select.getWidth() - 15);
int color = equals(select.getSelectedOption()) && !isTop ? select.getSelectTextColor() : select.getTextColor();
boolean shadow = select.isTextShadow();
if (hovered)
color = select.getHoverTextColor();
if (disabled)
{
text = EnumChatFormatting.ITALIC + text;
color = select.getDisabledTextColor();
shadow = false;
}
renderer.drawText(text, x + 2, y, z + 2, color, shadow, true);
}
@Override
public boolean equals(Object obj)
{
return obj != null && obj instanceof Option && key.equals(((Option) obj).key);
}
}
/**
* Event fired when a {@link UISelect} changes its selected {@link Option}.<br>
* When catching the event, the state is not applied to the {@code UISelect} yet.<br>
* Cancelling the event will prevent the {@code Option} to be set for the {@code UISelect} .
*/
public static class SelectEvent<T> extends ValueChange<UISelect, T>
{
public SelectEvent(UISelect<T> component, T newValue)
{
super(component, component.getSelectedValue(), newValue);
}
}
}
| Fixed select() | src/main/java/net/malisis/core/client/gui/component/interaction/UISelect.java | Fixed select() |
|
Java | mit | 5cd8f0485a4cf6ac343e21a782fee814b0421e29 | 0 | fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode | package leetcode;
/**
* https://leetcode.com/problems/base-7/
*/
public class Problem504 {
public String convertToBase7(int num) {
if (num == 0) {
return "0";
}
StringBuilder result = new StringBuilder();
boolean negative = false;
if (num < 0) {
num *= -1;
negative = true;
}
while (num > 0) {
result.append(num % 7);
num /= 7;
}
if (negative) {
result.append("-");
return result.reverse().toString();
}
return result.reverse().toString();
}
}
| src/main/java/leetcode/Problem504.java | package leetcode;
/**
* https://leetcode.com/problems/base-7/
*/
public class Problem504 {
public String convertToBase7(int num) {
// TODO
return null;
}
public static void main(String[] args) {
Problem504 prob = new Problem504();
System.out.println(prob.convertToBase7(100)); // 202
System.out.println(prob.convertToBase7(-7)); // -10
}
}
| Solve problem 504
| src/main/java/leetcode/Problem504.java | Solve problem 504 |
|
Java | mit | 4274675234fc46a34f41f3e19c52cb0b23011ddc | 0 | jaquadro/StorageDrawers,jaquadro/StorageDrawers,codewarrior0/StorageDrawers,bloodmc/StorageDrawers | package com.jaquadro.minecraft.storagedrawers.block.tile;
import com.jaquadro.minecraft.storagedrawers.StorageDrawers;
import com.jaquadro.minecraft.storagedrawers.api.inventory.IDrawerInventory;
import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawer;
import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawerGroup;
import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawerGroupInteractive;
import com.jaquadro.minecraft.storagedrawers.network.ControllerUpdateMessage;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
import java.util.*;
public class TileEntityController extends TileEntity implements IDrawerGroup, ISidedInventory
{
private static final int DEPTH_LIMIT = 12;
private static final int[] emptySlots = new int[0];
private static class BlockCoord {
private int x;
private int y;
private int z;
public BlockCoord (int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public boolean equals (Object obj) {
if (obj == null || obj.getClass() != getClass())
return false;
BlockCoord that = (BlockCoord)obj;
return x == that.x && y == that.y && z == that.z;
}
@Override
public int hashCode () {
int hash = 23;
hash = hash * 31 + x;
hash = hash * 31 + y;
hash = hash * 31 + z;
return hash;
}
}
private static class StorageRecord
{
public IDrawerGroup storage;
public boolean mark;
public int invStorageSize;
public int drawerStorageSize;
public int distance = Integer.MAX_VALUE;
public void clear () {
storage = null;
mark = false;
invStorageSize = 0;
drawerStorageSize = 0;
distance = Integer.MAX_VALUE;
}
}
private Map<BlockCoord, StorageRecord> storage = new HashMap<BlockCoord, StorageRecord>();
private List<BlockCoord> invBlockList = new ArrayList<BlockCoord>();
private List<Integer> invSlotList = new ArrayList<Integer>();
private List<BlockCoord> drawerBlockList = new ArrayList<BlockCoord>();
private List<Integer> drawerSlotList = new ArrayList<Integer>();
private int[] inventorySlots = new int[0];
private int[] autoSides = new int[] { 0, 1 };
private int direction;
private int drawerSize = 0;
private long lastClickTime;
private UUID lastClickUUID;
public TileEntityController () {
invBlockList.add(null);
invSlotList.add(0);
inventorySlots = new int[] { 0 };
}
public int getDirection () {
return direction;
}
public void setDirection (int direction) {
this.direction = direction % 6;
autoSides = new int[] { 0, 1, ForgeDirection.OPPOSITES[direction], 2, 3 };
if (direction == 2 || direction == 3) {
autoSides[3] = 4;
autoSides[4] = 5;
}
}
public int interactPutItemsIntoInventory (EntityPlayer player) {
if (inventorySlots.length == 0)
updateCache();
boolean dumpInventory = worldObj.getTotalWorldTime() - lastClickTime < 10 && player.getPersistentID().equals(lastClickUUID);
int count = 0;
for (int i = 0, n = drawerSlotList.size(); i < n; i++) {
IDrawerGroup group = getDrawerBlockForGroup(i);
if (group == null || !(group instanceof IDrawerGroupInteractive))
continue;
IDrawerGroupInteractive intGroup = (IDrawerGroupInteractive)group;
int slot = getDrawerSlotForGroup(i);
if (!group.isDrawerEnabled(slot))
continue;
IDrawer drawer = group.getDrawer(slot);
if (drawer == null || drawer.isEmpty())
continue;
if (dumpInventory)
count += intGroup.interactPutCurrentInventoryIntoSlot(slot, player);
else
count += intGroup.interactPutCurrentItemIntoSlot(slot, player);
}
lastClickTime = worldObj.getTotalWorldTime();
lastClickUUID = player.getPersistentID();
return count;
}
private void resetCache () {
storage.clear();
invBlockList.clear();
invSlotList.clear();
drawerBlockList.clear();
drawerSlotList.clear();
drawerSize = 0;
}
private void rebuildCache () {
resetCache();
updateCache();
}
public void updateCache () {
int preCount = inventorySlots.length;
for (StorageRecord record : storage.values())
record.mark = false;
populateNode(xCoord, yCoord, zCoord, 0);
for (BlockCoord coord : storage.keySet()) {
StorageRecord record = storage.get(coord);
if (!record.mark) {
record.clear();
for (int i = 0, n = invBlockList.size(); i < n; i++) {
if (coord.equals(invBlockList.get(i)))
invBlockList.set(i, null);
}
for (int i = 0, n = drawerBlockList.size(); i < n; i++) {
if (coord.equals(drawerBlockList.get(i)))
drawerBlockList.set(i, null);
}
}
}
/*int validSlotCount = 0;
for (int i = 0, n = invBlockList.size(); i < n; i++) {
if (invBlockList.get(i) != null)
validSlotCount++;
}*/
inventorySlots = new int[invBlockList.size()];
for (int i = 0, j = 0, n = invBlockList.size(); i < n; i++) {
//if (invBlockList.get(i) != null)
inventorySlots[j++] = i;
}
if (!worldObj.isRemote)
syncClient();
if (preCount != inventorySlots.length && (preCount == 0 || inventorySlots.length == 0)) {
if (!worldObj.isRemote)
markDirty();
}
}
private void populateNode (int x, int y, int z, int depth) {
TileEntity te = worldObj.getTileEntity(x, y, z);
if (te == null || !(te instanceof IDrawerGroup))
return;
//if (te instanceof TileEntityController && depth < DEPTH_LIMIT) {
// populateNeighborNodes(x, y, z, depth + 1);
// return;
//}
BlockCoord coord = new BlockCoord(x, y, z);
StorageRecord record = storage.get(coord);
if (record != null) {
if (record.storage != null) {
if (!record.mark || record.distance > depth) {
record.mark = true;
record.distance = depth;
populateNeighborNodes(x, y, z, depth + 1);
}
return;
}
}
else {
record = new StorageRecord();
storage.put(coord, record);
}
record.mark = true;
if (te instanceof TileEntityController) {
record.storage = null;
record.invStorageSize = 1;
invBlockList.add(null);
invSlotList.add(0);
}
else {
IDrawerGroup group = (IDrawerGroup)te;
IDrawerInventory inventory = group.getDrawerInventory();
if (inventory == null)
return;
record.storage = group;
record.invStorageSize = inventory.getSizeInventory();
record.drawerStorageSize = group.getDrawerCount();
for (int i = 0, n = record.invStorageSize; i < n; i++) {
invBlockList.add(coord);
invSlotList.add(i);
}
for (int i = 0, n = record.drawerStorageSize; i < n; i++) {
drawerBlockList.add(coord);
drawerSlotList.add(i);
}
drawerSize += record.drawerStorageSize;
}
if (depth == DEPTH_LIMIT)
return;
populateNeighborNodes(x, y, z, depth + 1);
}
private void populateNeighborNodes (int x, int y, int z, int depth) {
populateNode(x - 1, y, z, depth);
populateNode(x + 1, y, z, depth);
populateNode(x, y - 1, z, depth);
populateNode(x, y + 1, z, depth);
populateNode(x, y, z - 1, depth);
populateNode(x, y, z + 1, depth);
}
private IDrawerGroup getDrawerBlockForInv (int slot) {
if (slot >= invBlockList.size())
return null;
BlockCoord coord = invBlockList.get(slot);
if (coord == null)
return null;
if (!storage.containsKey(coord))
return null;
TileEntity te = worldObj.getTileEntity(coord.x, coord.y, coord.z);
if (!(te instanceof IDrawerGroup)) {
storage.remove(coord);
return null;
}
return storage.get(coord).storage;
}
private IDrawerGroup getDrawerBlockForGroup (int slot) {
if (slot >= drawerBlockList.size())
return null;
BlockCoord coord = drawerBlockList.get(slot);
if (coord == null)
return null;
if (!storage.containsKey(coord))
return null;
TileEntity te = worldObj.getTileEntity(coord.x, coord.y, coord.z);
if (!(te instanceof IDrawerGroup)) {
storage.remove(coord);
return null;
}
return storage.get(coord).storage;
}
private int getDrawerSlotForInv (int slot) {
if (slot >= invSlotList.size())
return 0;
return invSlotList.get(slot);
}
private int getDrawerSlotForGroup (int slot) {
if (slot >= drawerSlotList.size())
return 0;
return drawerSlotList.get(slot);
}
private IDrawerInventory getDrawerInventory (int slot) {
IDrawerGroup group = getDrawerBlockForInv(slot);
if (group == null)
return null;
return group.getDrawerInventory();
}
@Override
public void readFromNBT (NBTTagCompound tag) {
super.readFromNBT(tag);
setDirection(tag.getByte("Dir"));
if (worldObj != null && !worldObj.isRemote)
rebuildCache();
}
@Override
public void writeToNBT (NBTTagCompound tag) {
super.writeToNBT(tag);
tag.setByte("Dir", (byte)direction);
}
@Override
public Packet getDescriptionPacket () {
NBTTagCompound tag = new NBTTagCompound();
writeToNBT(tag);
return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 5, tag);
}
@Override
public void onDataPacket (NetworkManager net, S35PacketUpdateTileEntity pkt) {
readFromNBT(pkt.func_148857_g());
getWorldObj().func_147479_m(xCoord, yCoord, zCoord); // markBlockForRenderUpdate
}
private void syncClient () {
IMessage message = new ControllerUpdateMessage(xCoord, yCoord, zCoord, inventorySlots);
NetworkRegistry.TargetPoint targetPoint = new NetworkRegistry.TargetPoint(worldObj.provider.dimensionId, xCoord, yCoord, zCoord, 500);
StorageDrawers.network.sendToAllAround(message, targetPoint);
worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, worldObj.getBlock(xCoord, yCoord, zCoord));
}
public void clientUpdate (int[] inventorySlots) {
this.inventorySlots = inventorySlots;
}
@Override
public IDrawerInventory getDrawerInventory () {
return null;
}
@Override
public int getDrawerCount () {
return drawerSlotList.size();
}
@Override
public IDrawer getDrawer (int slot) {
IDrawerGroup group = getDrawerBlockForGroup(slot);
if (group == null)
return null;
return group.getDrawer(getDrawerSlotForGroup(slot));
}
@Override
public boolean isDrawerEnabled (int slot) {
IDrawerGroup group = getDrawerBlockForGroup(slot);
if (group == null)
return false;
return group.isDrawerEnabled(getDrawerSlotForGroup(slot));
}
@Override
public void markDirty () {
for (StorageRecord record : storage.values()) {
IDrawerGroup group = record.storage;
if (group != null && group.getDrawerInventory() != null)
group.markDirtyIfNeeded();
}
super.markDirty();
}
@Override
public boolean markDirtyIfNeeded () {
boolean synced = false;
for (StorageRecord record : storage.values()) {
IDrawerGroup group = record.storage;
if (group != null && group.getDrawerInventory() != null)
synced |= group.markDirtyIfNeeded();
}
if (synced)
super.markDirty();
return synced;
}
@Override
public int[] getAccessibleSlotsFromSide (int side) {
for (int aside : autoSides) {
if (side == aside)
return inventorySlots;
}
return emptySlots;
}
@Override
public boolean canInsertItem (int slot, ItemStack stack, int side) {
IDrawerInventory inventory = getDrawerInventory(slot);
if (inventory == null)
return false;
return inventory.canInsertItem(getDrawerSlotForInv(slot), stack);
}
@Override
public boolean canExtractItem (int slot, ItemStack stack, int side) {
IDrawerInventory inventory = getDrawerInventory(slot);
if (inventory == null)
return false;
return inventory.canExtractItem(getDrawerSlotForInv(slot), stack);
}
@Override
public int getSizeInventory () {
return inventorySlots.length;
}
@Override
public ItemStack getStackInSlot (int slot) {
IDrawerInventory inventory = getDrawerInventory(slot);
if (inventory == null)
return null;
return inventory.getStackInSlot(getDrawerSlotForInv(slot));
}
@Override
public ItemStack decrStackSize (int slot, int count) {
IDrawerInventory inventory = getDrawerInventory(slot);
if (inventory == null)
return null;
return inventory.decrStackSize(getDrawerSlotForInv(slot), count);
}
@Override
public ItemStack getStackInSlotOnClosing (int slot) {
IDrawerInventory inventory = getDrawerInventory(slot);
if (inventory == null)
return null;
return inventory.getStackInSlotOnClosing(getDrawerSlotForInv(slot));
}
@Override
public void setInventorySlotContents (int slot, ItemStack stack) {
IDrawerInventory inventory = getDrawerInventory(slot);
if (inventory == null)
return;
inventory.setInventorySlotContents(getDrawerSlotForInv(slot), stack);
inventory.markDirty();
}
@Override
public String getInventoryName () {
// TODO
return null;
}
@Override
public boolean hasCustomInventoryName () {
// TODO
return false;
}
@Override
public int getInventoryStackLimit () {
return 64;
}
@Override
public boolean isUseableByPlayer (EntityPlayer player) {
return false;
}
@Override
public void openInventory () { }
@Override
public void closeInventory () { }
@Override
public boolean isItemValidForSlot (int slot, ItemStack stack) {
IDrawerInventory inventory = getDrawerInventory(slot);
if (inventory == null)
return false;
return inventory.isItemValidForSlot(getDrawerSlotForInv(slot), stack);
}
}
| src/com/jaquadro/minecraft/storagedrawers/block/tile/TileEntityController.java | package com.jaquadro.minecraft.storagedrawers.block.tile;
import com.jaquadro.minecraft.storagedrawers.StorageDrawers;
import com.jaquadro.minecraft.storagedrawers.api.inventory.IDrawerInventory;
import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawer;
import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawerGroup;
import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawerGroupInteractive;
import com.jaquadro.minecraft.storagedrawers.network.ControllerUpdateMessage;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
import java.util.*;
public class TileEntityController extends TileEntity implements IDrawerGroup, ISidedInventory
{
private static final int DEPTH_LIMIT = 12;
private static final int[] emptySlots = new int[0];
private static class BlockCoord {
private int x;
private int y;
private int z;
public BlockCoord (int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public boolean equals (Object obj) {
if (obj == null || obj.getClass() != getClass())
return false;
BlockCoord that = (BlockCoord)obj;
return x == that.x && y == that.y && z == that.z;
}
@Override
public int hashCode () {
int hash = 23;
hash = hash * 31 + x;
hash = hash * 31 + y;
hash = hash * 31 + z;
return hash;
}
}
private Map<BlockCoord, IDrawerGroup> storage = new HashMap<BlockCoord, IDrawerGroup>();
private Map<BlockCoord, Boolean> mark = new HashMap<BlockCoord, Boolean>();
private Map<BlockCoord, Integer> invStorageSize = new HashMap<BlockCoord, Integer>();
private Map<BlockCoord, Integer> drawerStorageSize = new HashMap<BlockCoord, Integer>();
private List<BlockCoord> invBlockList = new ArrayList<BlockCoord>();
private List<Integer> invSlotList = new ArrayList<Integer>();
private List<BlockCoord> drawerBlockList = new ArrayList<BlockCoord>();
private List<Integer> drawerSlotList = new ArrayList<Integer>();
private int[] inventorySlots = new int[0];
private int[] autoSides = new int[] { 0, 1 };
private int direction;
private int drawerSize = 0;
private long lastClickTime;
private UUID lastClickUUID;
public TileEntityController () {
invBlockList.add(null);
invSlotList.add(0);
inventorySlots = new int[] { 0 };
}
public int getDirection () {
return direction;
}
public void setDirection (int direction) {
this.direction = direction % 6;
autoSides = new int[] { 0, 1, ForgeDirection.OPPOSITES[direction], 2, 3 };
if (direction == 2 || direction == 3) {
autoSides[3] = 4;
autoSides[4] = 5;
}
}
public int interactPutItemsIntoInventory (EntityPlayer player) {
if (inventorySlots.length == 0)
updateCache();
boolean dumpInventory = worldObj.getTotalWorldTime() - lastClickTime < 10 && player.getPersistentID().equals(lastClickUUID);
int count = 0;
for (int i = 0, n = drawerSlotList.size(); i < n; i++) {
IDrawerGroup group = getDrawerBlockForGroup(i);
if (group == null || !(group instanceof IDrawerGroupInteractive))
continue;
IDrawerGroupInteractive intGroup = (IDrawerGroupInteractive)group;
int slot = getDrawerSlotForGroup(i);
if (!group.isDrawerEnabled(slot))
continue;
IDrawer drawer = group.getDrawer(slot);
if (drawer == null || drawer.isEmpty())
continue;
if (dumpInventory)
count += intGroup.interactPutCurrentInventoryIntoSlot(slot, player);
else
count += intGroup.interactPutCurrentItemIntoSlot(slot, player);
}
lastClickTime = worldObj.getTotalWorldTime();
lastClickUUID = player.getPersistentID();
return count;
}
private void resetCache () {
storage.clear();
invStorageSize.clear();
drawerStorageSize.clear();
invBlockList.clear();
invSlotList.clear();
drawerBlockList.clear();
drawerSlotList.clear();
drawerSize = 0;
}
private void rebuildCache () {
resetCache();
updateCache();
}
public void updateCache () {
int preCount = inventorySlots.length;
mark.clear();
populateNode(xCoord, yCoord, zCoord, 0);
for (BlockCoord coord : storage.keySet()) {
if (!mark.containsKey(coord)) {
storage.put(coord, null);
for (int i = 0, n = invBlockList.size(); i < n; i++) {
if (coord.equals(invBlockList.get(i)))
invBlockList.set(i, null);
}
for (int i = 0, n = drawerBlockList.size(); i < n; i++) {
if (coord.equals(drawerBlockList.get(i)))
drawerBlockList.set(i, null);
}
}
}
/*int validSlotCount = 0;
for (int i = 0, n = invBlockList.size(); i < n; i++) {
if (invBlockList.get(i) != null)
validSlotCount++;
}*/
inventorySlots = new int[invBlockList.size()];
for (int i = 0, j = 0, n = invBlockList.size(); i < n; i++) {
//if (invBlockList.get(i) != null)
inventorySlots[j++] = i;
}
if (!worldObj.isRemote)
syncClient();
if (preCount != inventorySlots.length && (preCount == 0 || inventorySlots.length == 0)) {
if (!worldObj.isRemote)
markDirty();
}
}
private void populateNode (int x, int y, int z, int depth) {
TileEntity te = worldObj.getTileEntity(x, y, z);
if (te == null || !(te instanceof IDrawerGroup))
return;
//if (te instanceof TileEntityController && depth < DEPTH_LIMIT) {
// populateNeighborNodes(x, y, z, depth + 1);
// return;
//}
BlockCoord coord = new BlockCoord(x, y, z);
if (storage.containsKey(coord)) {
if (storage.get(coord) != null) {
if (!mark.containsKey(coord)) {
mark.put(coord, true);
populateNeighborNodes(x, y, z, depth + 1);
}
return;
}
}
mark.put(coord, true);
if (te instanceof TileEntityController) {
storage.put(coord, null);
invStorageSize.put(coord, 1);
invBlockList.add(null);
invSlotList.add(0);
}
else {
IDrawerGroup group = (IDrawerGroup)te;
IDrawerInventory inventory = group.getDrawerInventory();
if (inventory == null)
return;
storage.put(coord, group);
invStorageSize.put(coord, inventory.getSizeInventory());
drawerStorageSize.put(coord, group.getDrawerCount());
for (int i = 0, n = invStorageSize.get(coord); i < n; i++) {
invBlockList.add(coord);
invSlotList.add(i);
}
for (int i = 0, n = drawerStorageSize.get(coord); i < n; i++) {
drawerBlockList.add(coord);
drawerSlotList.add(i);
}
drawerSize += drawerStorageSize.get(coord);
}
if (depth == DEPTH_LIMIT)
return;
populateNeighborNodes(x, y, z, depth + 1);
}
private void populateNeighborNodes (int x, int y, int z, int depth) {
populateNode(x - 1, y, z, depth);
populateNode(x + 1, y, z, depth);
populateNode(x, y - 1, z, depth);
populateNode(x, y + 1, z, depth);
populateNode(x, y, z - 1, depth);
populateNode(x, y, z + 1, depth);
}
private IDrawerGroup getDrawerBlockForInv (int slot) {
if (slot >= invBlockList.size())
return null;
BlockCoord coord = invBlockList.get(slot);
if (coord == null)
return null;
if (!storage.containsKey(coord))
return null;
TileEntity te = worldObj.getTileEntity(coord.x, coord.y, coord.z);
if (!(te instanceof IDrawerGroup)) {
storage.remove(coord);
return null;
}
return storage.get(coord);
}
private IDrawerGroup getDrawerBlockForGroup (int slot) {
if (slot >= drawerBlockList.size())
return null;
BlockCoord coord = drawerBlockList.get(slot);
if (coord == null)
return null;
if (!storage.containsKey(coord))
return null;
TileEntity te = worldObj.getTileEntity(coord.x, coord.y, coord.z);
if (!(te instanceof IDrawerGroup)) {
storage.remove(coord);
return null;
}
return storage.get(coord);
}
private int getDrawerSlotForInv (int slot) {
if (slot >= invSlotList.size())
return 0;
return invSlotList.get(slot);
}
private int getDrawerSlotForGroup (int slot) {
if (slot >= drawerSlotList.size())
return 0;
return drawerSlotList.get(slot);
}
private IDrawerInventory getDrawerInventory (int slot) {
IDrawerGroup group = getDrawerBlockForInv(slot);
if (group == null)
return null;
return group.getDrawerInventory();
}
@Override
public void readFromNBT (NBTTagCompound tag) {
super.readFromNBT(tag);
setDirection(tag.getByte("Dir"));
if (worldObj != null && !worldObj.isRemote)
rebuildCache();
}
@Override
public void writeToNBT (NBTTagCompound tag) {
super.writeToNBT(tag);
tag.setByte("Dir", (byte)direction);
}
@Override
public Packet getDescriptionPacket () {
NBTTagCompound tag = new NBTTagCompound();
writeToNBT(tag);
return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 5, tag);
}
@Override
public void onDataPacket (NetworkManager net, S35PacketUpdateTileEntity pkt) {
readFromNBT(pkt.func_148857_g());
getWorldObj().func_147479_m(xCoord, yCoord, zCoord); // markBlockForRenderUpdate
}
private void syncClient () {
IMessage message = new ControllerUpdateMessage(xCoord, yCoord, zCoord, inventorySlots);
NetworkRegistry.TargetPoint targetPoint = new NetworkRegistry.TargetPoint(worldObj.provider.dimensionId, xCoord, yCoord, zCoord, 500);
StorageDrawers.network.sendToAllAround(message, targetPoint);
worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, worldObj.getBlock(xCoord, yCoord, zCoord));
}
public void clientUpdate (int[] inventorySlots) {
this.inventorySlots = inventorySlots;
}
@Override
public IDrawerInventory getDrawerInventory () {
return null;
}
@Override
public int getDrawerCount () {
return drawerSlotList.size();
}
@Override
public IDrawer getDrawer (int slot) {
IDrawerGroup group = getDrawerBlockForGroup(slot);
if (group == null)
return null;
return group.getDrawer(getDrawerSlotForGroup(slot));
}
@Override
public boolean isDrawerEnabled (int slot) {
IDrawerGroup group = getDrawerBlockForGroup(slot);
if (group == null)
return false;
return group.isDrawerEnabled(getDrawerSlotForGroup(slot));
}
@Override
public void markDirty () {
for (IDrawerGroup group : storage.values()) {
if (group != null && group.getDrawerInventory() != null)
group.markDirtyIfNeeded();
}
super.markDirty();
}
@Override
public boolean markDirtyIfNeeded () {
boolean synced = false;
for (IDrawerGroup group : storage.values()) {
if (group != null && group.getDrawerInventory() != null)
synced |= group.markDirtyIfNeeded();
}
if (synced)
super.markDirty();
return synced;
}
@Override
public int[] getAccessibleSlotsFromSide (int side) {
for (int aside : autoSides) {
if (side == aside)
return inventorySlots;
}
return emptySlots;
}
@Override
public boolean canInsertItem (int slot, ItemStack stack, int side) {
IDrawerInventory inventory = getDrawerInventory(slot);
if (inventory == null)
return false;
return inventory.canInsertItem(getDrawerSlotForInv(slot), stack);
}
@Override
public boolean canExtractItem (int slot, ItemStack stack, int side) {
IDrawerInventory inventory = getDrawerInventory(slot);
if (inventory == null)
return false;
return inventory.canExtractItem(getDrawerSlotForInv(slot), stack);
}
@Override
public int getSizeInventory () {
return inventorySlots.length;
}
@Override
public ItemStack getStackInSlot (int slot) {
IDrawerInventory inventory = getDrawerInventory(slot);
if (inventory == null)
return null;
return inventory.getStackInSlot(getDrawerSlotForInv(slot));
}
@Override
public ItemStack decrStackSize (int slot, int count) {
IDrawerInventory inventory = getDrawerInventory(slot);
if (inventory == null)
return null;
return inventory.decrStackSize(getDrawerSlotForInv(slot), count);
}
@Override
public ItemStack getStackInSlotOnClosing (int slot) {
IDrawerInventory inventory = getDrawerInventory(slot);
if (inventory == null)
return null;
return inventory.getStackInSlotOnClosing(getDrawerSlotForInv(slot));
}
@Override
public void setInventorySlotContents (int slot, ItemStack stack) {
IDrawerInventory inventory = getDrawerInventory(slot);
if (inventory == null)
return;
inventory.setInventorySlotContents(getDrawerSlotForInv(slot), stack);
inventory.markDirty();
}
@Override
public String getInventoryName () {
// TODO
return null;
}
@Override
public boolean hasCustomInventoryName () {
// TODO
return false;
}
@Override
public int getInventoryStackLimit () {
return 64;
}
@Override
public boolean isUseableByPlayer (EntityPlayer player) {
return false;
}
@Override
public void openInventory () { }
@Override
public void closeInventory () { }
@Override
public boolean isItemValidForSlot (int slot, ItemStack stack) {
IDrawerInventory inventory = getDrawerInventory(slot);
if (inventory == null)
return false;
return inventory.isItemValidForSlot(getDrawerSlotForInv(slot), stack);
}
}
| Fix controller not always finding all drawers within 12 block distance.
| src/com/jaquadro/minecraft/storagedrawers/block/tile/TileEntityController.java | Fix controller not always finding all drawers within 12 block distance. |
|
Java | epl-1.0 | 5a9a8a5598c822c424d1d508fee86d36624ce490 | 0 | opendaylight/opflex,opendaylight/opflex,mhrobinson/opflex,mhrobinson/opflex,mhrobinson/opflex,opendaylight/opflex,opendaylight/opflex,mhrobinson/opflex | package org.opendaylight.opflex.genie.content.format.proxy.structure.cpp;
import org.opendaylight.opflex.genie.content.format.agent.meta.cpp.FMetaDef;
import org.opendaylight.opflex.genie.content.model.mclass.MClass;
import org.opendaylight.opflex.genie.content.model.mnaming.MNameComponent;
import org.opendaylight.opflex.genie.content.model.mnaming.MNameRule;
import org.opendaylight.opflex.genie.content.model.module.Module;
import org.opendaylight.opflex.genie.content.model.mprop.MProp;
import org.opendaylight.opflex.genie.content.model.mtype.Language;
import org.opendaylight.opflex.genie.content.model.mtype.MLanguageBinding;
import org.opendaylight.opflex.genie.content.model.mtype.MType;
import org.opendaylight.opflex.genie.content.model.mtype.PassBy;
import org.opendaylight.opflex.genie.engine.file.WriteStats;
import org.opendaylight.opflex.genie.engine.format.*;
import org.opendaylight.opflex.genie.engine.model.Ident;
import org.opendaylight.opflex.genie.engine.model.Item;
import org.opendaylight.opflex.genie.engine.model.Pair;
import org.opendaylight.opflex.genie.engine.proc.Config;
import org.opendaylight.opflex.modlan.report.Severity;
import org.opendaylight.opflex.modlan.utils.Strings;
import java.util.*;
/**
* Created by midvorki on 11/20/14.
*/
public class FClassDef extends ItemFormatterTask
{
public FClassDef(
FormatterCtx aInFormatterCtx,
FileNameRule aInFileNameRule,
Indenter aInIndenter,
BlockFormatDirective aInHeaderFormatDirective,
BlockFormatDirective aInCommentFormatDirective,
boolean aInIsUserFile,
WriteStats aInStats,
Item aInItem)
{
super(
aInFormatterCtx,
aInFileNameRule,
aInIndenter,
aInHeaderFormatDirective,
aInCommentFormatDirective,
aInIsUserFile,
aInStats,
aInItem);
}
/**
* Optional API required by framework to regulate triggering of tasks.
* This method identifies whether this task should be triggered for the item passed in.
* @param aIn item for which task is considered to be trriggered
* @return true if task shouold be triggered, false if task should be skipped for this item.
*/
public static boolean shouldTriggerTask(Item aIn)
{
return ((MClass)aIn).isConcrete();
}
/**
* Optional API required by framework to identify namespace/module-space for the corresponding generated file.
* @param aIn item for which task is being triggered
* @return name of the module/namespace that corresponds to the item
*/
public static String getTargetModule(Item aIn)
{
return ((MClass) aIn).getModule().getLID().getName();
}
/**
* Optional API required by the framework for transformation of file naming rule for the corresponding
* generated file. This method can customize the location for the generated file.
* @param aInFnr file name rule template
* @param aInItem item for which file is generated
* @return transformed file name rule
*/
public static FileNameRule transformFileNameRule(FileNameRule aInFnr,Item aInItem)
{
String lTargetModue = getTargetModule(aInItem);
String lOldRelativePath = aInFnr.getRelativePath();
String lNewRelativePath = lOldRelativePath + "/include/" + Config.getProjName() + "/" + lTargetModue;
FileNameRule lFnr = new FileNameRule(
lNewRelativePath,
null,
aInFnr.getFilePrefix(),
aInFnr.getFileSuffix(),
aInFnr.getFileExtension(),
getClassName((MClass)aInItem, false));
return lFnr;
}
public void generate()
{
MClass lClass = (MClass) getItem();
generate(0, lClass);
}
public static String getClassName(MClass aInClass, boolean aInFullyQualified)
{
return aInFullyQualified ? (getNamespace(aInClass,true) + "::" + aInClass.getLID().getName()) : aInClass.getLID().getName();
}
public static String getInclTag(MClass aInClass)
{
return "GI_" + aInClass.getModule().getLID().getName().toUpperCase() + '_' + aInClass.getLID().getName().toUpperCase() + "_HPP";
}
public static String getNamespace(String aInModuleName, boolean aInFullyQualified)
{
return aInFullyQualified ? (Config.getProjName() + "::" + aInModuleName) : (aInModuleName);
}
public static String getNamespace(MClass aInClass, boolean aInFullyQualified)
{
return getNamespace(aInClass.getModule().getLID().getName(), aInFullyQualified);
}
public static String getInclude(String aInPath, boolean aInIsBuiltIn)
{
return "#include " + (aInIsBuiltIn ? '<' : '\"') + aInPath + (aInIsBuiltIn ? '>' : '\"');
}
public static String getIncludePath(MClass aIn)
{
return Config.getProjName() + "/" + getNamespace(aIn,false) + "/" + aIn.getLID().getName();
}
public static String getInclude(MClass aIn)
{
return getInclude(getIncludePath(aIn) + ".hpp", false);
}
private void generate(int aInIndent, MClass aInClass)
{
String lInclTag = getInclTag(aInClass);
out.println(aInIndent,"#pragma once");
out.println(aInIndent,"#ifndef " + lInclTag);
out.println(aInIndent,"#define " + lInclTag);
// doesn't seem to be needed for now. Revisit?
//genForwardDecls(aInIndent, aInClass);
genIncludes(aInIndent, aInClass);
genBody(aInIndent, aInClass);
out.println(aInIndent,"#endif // " + lInclTag);
}
private void genForwardDecls(int aInIndent, MClass aInClass)
{
out.println();
out.println(aInIndent, "namespace " + Config.getProjName() + " {");
out.println();
out.printIncodeComment(aInIndent, "FORWARD DECLARATIONS FOR INHERITANCE ");
for (MClass lThis = aInClass; null != lThis; lThis = lThis.getSuperclass())
{
genForwardDecl(aInIndent, lThis);
}
TreeMap<Ident, MClass> lConts = new TreeMap<Ident, MClass>();
aInClass.getContainsClasses(lConts, true, true);
out.printIncodeComment(aInIndent, "FORWARD DECLARATIONS FOR CONTAINED ");
for (MClass lThis : lConts.values())
{
genForwardDecl(aInIndent, lThis);
}
TreeMap<Ident, MClass> lContr = new TreeMap<Ident, MClass>();
aInClass.getContainedByClasses(lContr, true, true);
out.printIncodeComment(aInIndent, "FORWARD DECLARATIONS FOR CONTAINERS ");
for (MClass lThis : lContr.values())
{
genForwardDecl(aInIndent,lThis);
}
out.println();
out.println(aInIndent, "} // namespace " + Config.getProjName());
out.println();
}
private void genForwardDecl(int aInIndent, MClass aInClass)
{
String lNs = getNamespace(aInClass, false);
out.println(aInIndent, "namespace " + lNs + " {");
out.println();
out.printHeaderComment(aInIndent, "forward declaration for " + aInClass);
out.println(aInIndent, "class " + aInClass.getLID().getName() + ";");
out.println();
out.println(aInIndent, "} // namespace " + lNs);
out.println();
}
private void genIncludes(int aInIndent, MClass aInClass)
{
out.println();
out.println(aInIndent,getInclude("boost/optional.hpp", true));
out.println(aInIndent,getInclude("opflex/modb/URIBuilder.h", false));
out.println(aInIndent,getInclude("opflex/modb/MO.h", false));
/**
if (aInClass.hasSuperclass())
{
MClass lSuper = aInClass.getSuperclass();
out.printIncodeComment(aInIndent, "superclass: " + lSuper);
out.println(aInIndent,getInclude(lSuper), false);
}
*/
TreeMap<Ident, MClass> lConts = new TreeMap<Ident, MClass>();
aInClass.getContainsClasses(lConts, true, true);
for (MClass lThis : lConts.values())
{
out.printIncodeComment(aInIndent, "contains: " + lThis);
out.println(aInIndent, getInclude(lThis), false);
}
}
private void genBody(int aInIndent, MClass aInClass)
{
out.println();
String lNs = getNamespace(aInClass, false);
out.println(aInIndent, "namespace " + Config.getProjName() + " {");
out.println(aInIndent, "namespace " + lNs + " {");
out.println();
genClass(aInIndent, aInClass);
out.println();
out.println(aInIndent, "} // namespace " + lNs);
out.println(aInIndent, "} // namespace " + Config.getProjName());
}
private void genClass(int aInIndent, MClass aInClass)
{
out.println(aInIndent, "class " + aInClass.getLID().getName());
/**
if (aInClass.hasSuperclass())
{
MClass lSuperclass = aInClass.getSuperclass();
out.println(aInIndent + 1, ": public " + getClassName(lSuperclass,true));
}
else**/
{
out.println(aInIndent + 1, ": public opflex::modb::MO");
}
out.println(aInIndent, "{");
genPublic(aInIndent + 1, aInClass);
out.println(aInIndent, "}; // class " + aInClass.getLID().getName());
}
private void genPublic(int aInIndent, MClass aInClass)
{
out.println(aInIndent - 1, "public:");
out.println();
genClassId(aInIndent, aInClass);
genProps(aInIndent, aInClass);
genConstructor(aInIndent, aInClass);
}
private void genClassId(int aInIndent, MClass aInClass)
{
String lClassName = getClassName(aInClass, false);
out.printHeaderComment(aInIndent, Arrays.asList("The unique class ID for " + lClassName));
out.println(aInIndent, "static const opflex::modb::class_id_t CLASS_ID = " + aInClass.getGID().getId() + ";");
out.println();
}
private void genProps(int aInIndent, MClass aInClass)
{
TreeMap<String, MProp> lProps = new TreeMap<String, MProp>();
aInClass.findProp(lProps, true); // false
for (MProp lProp : lProps.values())
{
// ONLY IF THIS PROPERTY IS DEFINED LOCALLY
//if (lProp.getBase().getMClass() == aInClass)
{
genProp(aInIndent, aInClass, lProp, lProp.getPropId(aInClass));
}
}
}
public static String getTypeAccessor(String aInPType)
{
if (aInPType.startsWith("Enum") ||
aInPType.startsWith("Bitmask") ||
aInPType.startsWith("UInt"))
{
aInPType = "UInt64";
}
else if (aInPType.equals("URI") ||
aInPType.equals("IP") ||
aInPType.equals("UUID"))
{
aInPType = "String";
}
return aInPType;
}
public static String getCast(String aInPType, String aInSyntax)
{
if (aInPType.startsWith("Enum") ||
aInPType.startsWith("Bitmask") ||
(aInPType.startsWith("UInt") &&
!aInPType.equals("UInt64")))
{
return "(" + aInSyntax + ")";
}
return "";
}
private String toUnsignedStr(int aInInt)
{
return Long.toString(aInInt & 0xFFFFFFFFL) + "ul";
}
private void genProp(int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx)
{
MProp lBaseProp = aInProp.getBase();
MType lType = lBaseProp.getType(false);
MType lBaseType = lType.getBuiltInType();
LinkedList<String> lComments = new LinkedList<String>();
aInProp.getComments(lComments);
{
genPropCheck(aInIndent,aInClass,aInProp,aInPropIdx,lType,lBaseType,lComments);
genPropAccessor(aInIndent, aInClass, aInProp, aInPropIdx, lType, lBaseType, lComments);
genPropMutator(aInIndent, aInClass, aInProp, aInPropIdx, lType, lBaseType, lComments);
}
}
private void genPropCheck(
int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx, MType aInType, MType aInBaseType,
Collection<String> aInComments, String aInCheckName, String aInPType)
{
//
// COMMENT
//
int lCommentSize = 2 + aInComments.size();
String lComment[] = new String[lCommentSize];
int lCommentIdx = 0;
lComment[lCommentIdx++] = "Check whether " + aInCheckName + " has been set";
for (String lCommLine : aInComments)
{
lComment[lCommentIdx++] = lCommLine;
}
lComment[lCommentIdx++] = "@return true if " + aInCheckName + " has been set";
out.printHeaderComment(aInIndent,lComment);
//
// METHOD DEFINITION
//
out.println(aInIndent,"bool is" + Strings.upFirstLetter(aInCheckName) + "Set()");
//
// METHOD BODY
//
out.println(aInIndent,"{");
out.println(aInIndent + 1, "return isPropertySet(" + toUnsignedStr(aInPropIdx) + ");");
out.println(aInIndent,"}");
out.println();
}
private void genPropCheck(
int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx, MType aInType, MType aInBaseType,
Collection<String> aInComments)
{
String lPType = FMetaDef.getTypeName(aInBaseType);
genPropCheck(aInIndent, aInClass, aInProp, aInPropIdx, aInType, aInBaseType,
aInComments, aInProp.getLID().getName(),
lPType);
}
private void genPropAccessor(
int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx, MType aInType, MType aInBaseType,
Collection<String> aInComments)
{
String lName = aInProp.getLID().getName();
String lPType = Strings.upFirstLetter(aInBaseType.getLID().getName());
String lEffSyntax = getPropEffSyntax(aInBaseType);
String lCast = getCast(lPType, lEffSyntax);
lPType = getTypeAccessor(lPType);
genPropAccessor(aInIndent, aInClass, aInProp, aInPropIdx, aInType, aInBaseType, aInComments,
lName, lName, lEffSyntax, lPType, lCast, "");
}
private void genPropAccessor(
int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx, MType aInType, MType aInBaseType,
Collection<String> aInComments, String aInCheckName, String aInName, String aInEffSyntax, String aInPType,
String aInCast, String aInAccessor)
{
//
// COMMENT
//
int lCommentSize = 2 + aInComments.size();
String lComment[] = new String[lCommentSize];
int lCommentIdx = 0;
lComment[lCommentIdx++] = "Get the value of " + aInName + " if it has been set.";
for (String lCommLine : aInComments)
{
lComment[lCommentIdx++] = lCommLine;
}
lComment[lCommentIdx++] = "@return the value of " + aInName + " or boost::none if not set";
out.printHeaderComment(aInIndent,lComment);
out.println(aInIndent,"boost::optional<" + aInEffSyntax + "> get" + Strings.upFirstLetter(aInName) + "()");
out.println(aInIndent,"{");
out.println(aInIndent + 1,"if (is" + Strings.upFirstLetter(aInCheckName) + "Set())");
out.println(aInIndent + 2,"return boost::get<" + aInEffSyntax + ">(getProperty(" + toUnsignedStr(aInPropIdx) + "));");
out.println(aInIndent + 1,"return boost::none;");
out.println(aInIndent,"}");
out.println();
}
private void genPropDefaultedAccessor(
int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx, MType aInType, MType aInBaseType,
Collection<String> aInComments, String aInName, String aInEffSyntax)
{
//
// COMMENT
//
int lCommentSize = 3 + aInComments.size();
String lComment[] = new String[lCommentSize];
int lCommentIdx = 0;
lComment[lCommentIdx++] = "Get the value of " + aInName + " if set, otherwise the value of default passed in.";
for (String lCommLine : aInComments)
{
lComment[lCommentIdx++] = lCommLine;
}
//
// DEF
//
lComment[lCommentIdx++] = "@param defaultValue default value returned if the property is not set";
lComment[lCommentIdx++] = "@return the value of " + aInName + " if set, otherwise the value of default passed in";
out.printHeaderComment(aInIndent,lComment);
out.println(aInIndent, aInEffSyntax + " get" + Strings.upFirstLetter(aInName) + "(" + aInEffSyntax + " defaultValue)");
//
// BODY
//
out.println(aInIndent,"{");
out.println(aInIndent + 1, "return get" + Strings.upFirstLetter(aInName) + "().get_value_or(defaultValue);");
out.println(aInIndent,"}");
out.println();
}
private void genPropMutator(int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx, MType aInType, MType aInBaseType,
Collection<String> aInBaseComments, Collection<String> aInComments, String aInName, String aInPType, String aInEffSyntax, String aInParamName, String aInParamHelp,
String aInSetterPrefix)
{
//
// COMMENT
//
ArrayList<String> lComment = new ArrayList<>(aInBaseComments);
if (aInComments.size() > 0) lComment.add("");
lComment.addAll(aInComments);
// Arrays.asList(
//
lComment.add("");
lComment.add("@param " + aInParamName + " " + aInParamHelp);
lComment.add("@return a reference to the current object");
lComment.add("@throws std::logic_error if no mutator is active");
lComment.add("@see opflex::modb::Mutator");
out.printHeaderComment(aInIndent,lComment);
//
// DEF
//
out.println(aInIndent, getClassName(aInClass, true) + "& set" + Strings.upFirstLetter(aInName) + "(" + aInEffSyntax + " " + aInParamName + ")");
//
// BODY
//
out.println(aInIndent,"{");
out.println(aInIndent + 1, "setProperty(" + toUnsignedStr(aInPropIdx)+ ", " + aInParamName + ");");
out.println(aInIndent + 1, "return *this;");
out.println(aInIndent,"}");
out.println();
}
private void genPropMutator(int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx, MType aInType, MType aInBaseType,
Collection<String> aInComments)
{
String lName = aInProp.getLID().getName();
String lPType = Strings.upFirstLetter(aInBaseType.getLID().getName());
lPType = getTypeAccessor(lPType);
List<String> lComments = Arrays.asList(
"Set " + lName + " to the specified value in the currently-active mutator.");
genPropMutator(aInIndent, aInClass, aInProp, aInPropIdx, aInType, aInBaseType,
lComments, aInComments, lName, lPType,
getPropEffSyntax(aInBaseType), "newValue", "the new value to set.",
"");
}
private static String getMethName(List<Pair<String, MNameRule>> aInNamingPath,
boolean aInIsUniqueNaming,
String prefix)
{
if (aInIsUniqueNaming)
{
return prefix;
}
else
{
StringBuilder lSb = new StringBuilder();
lSb.append(prefix + "Under");
int lSize = aInNamingPath.size();
int lIdx = lSize;
for (Pair<String, MNameRule> lPathNode : aInNamingPath)
{
if (0 < --lIdx)
{
MClass lClass = MClass.get(lPathNode.getFirst());
Module lMod = lClass.getModule();
lPathNode.getSecond();
lSb.append(Strings.upFirstLetter(lMod.getLID().getName()));
lSb.append(Strings.upFirstLetter(lClass.getLID().getName()));
}
}
return lSb.toString();
}
}
private static String getResolverMethName(List<Pair<String, MNameRule>> aInNamingPath,
boolean aInIsUniqueNaming)
{
return getMethName(aInNamingPath, aInIsUniqueNaming, "resolve");
}
private static String getRemoverMethName(List<Pair<String, MNameRule>> aInNamingPath,
boolean aInIsUniqueNaming)
{
return getMethName(aInNamingPath, aInIsUniqueNaming, "remove");
}
public static int countNamingProps(List<Pair<String, MNameRule>> aInNamingPath)
{
int lRet = 0;
for (Pair<String, MNameRule> lNode : aInNamingPath)
{
Collection<MNameComponent> lNcs = lNode.getSecond().getComponents();
if (!(null == lNcs || lNcs.isEmpty()))
{
for (MNameComponent lNc : lNcs)
{
if (lNc.hasPropName())
{
lRet++;
}
}
}
}
return lRet;
}
public static void getPropParamName(MClass aInClass, String aInPropName, StringBuilder aOutSb)
{
aOutSb.append(aInClass.getModule().getLID().getName());
aOutSb.append(Strings.upFirstLetter(aInClass.getLID().getName()));
aOutSb.append(Strings.upFirstLetter(aInPropName));
}
public static String getPropParamName(MClass aInClass, String aInPropName)
{
StringBuilder lSb = new StringBuilder();
getPropParamName(aInClass,aInPropName,lSb);
return lSb.toString();
}
public static String getPropEffSyntax(MType aInBaseType)
{
StringBuilder lRet = new StringBuilder();
MLanguageBinding lLang = aInBaseType.getLanguageBinding(Language.CPP);
boolean lPassAsConst = lLang.getPassConst();
PassBy lPassBy = lLang.getPassBy();
String lSyntax = aInBaseType.getLanguageBinding(Language.CPP).getSyntax();
if (lPassAsConst)
{
lRet.append("const ");
}
lRet.append(lSyntax);
switch (lPassBy)
{
case REFERENCE:
case POINTER:
lRet.append('&');
break;
case VALUE:
default:
break;
}
return lRet.toString();
}
public static String getPropParamDef(MClass aInClass, String aInPropName)
{
MProp lProp = aInClass.findProp(aInPropName, false);
if (null == lProp)
{
Severity.DEATH.report(aInClass.toString(),
"preparing param defs for prop: " + aInPropName,
"no such property: " + aInPropName, "");
}
MProp lBaseProp = lProp.getBase();
MType lType = lBaseProp.getType(false);
MType lBaseType = lType.getBuiltInType();
StringBuilder lRet = new StringBuilder();
lRet.append(getPropEffSyntax(lBaseType));
lRet.append(" ");
getPropParamName(aInClass, aInPropName, lRet);
return lRet.toString();
}
private void genConstructor(int aInIdent, MClass aInClass)
{
String lclassName = getClassName(aInClass, false);
String[] lComment =
{"Construct an instance of " + lclassName + ".",
"This should not typically be called from user code."};
out.printHeaderComment(aInIdent,lComment);
if (aInClass.isConcrete())
{
out.println(aInIdent, aInClass.getLID().getName() + "(");
out.println(aInIdent + 1, "const opflex::modb::URI& uri)");
out.println(aInIdent + 1, ": MO(CLASS_ID, uri) { }");
}
}
}
| genie/src/main/java/org/opendaylight/opflex/genie/content/format/proxy/structure/cpp/FClassDef.java | package org.opendaylight.opflex.genie.content.format.proxy.structure.cpp;
import org.opendaylight.opflex.genie.content.format.agent.meta.cpp.FMetaDef;
import org.opendaylight.opflex.genie.content.model.mclass.MClass;
import org.opendaylight.opflex.genie.content.model.mnaming.MNameComponent;
import org.opendaylight.opflex.genie.content.model.mnaming.MNameRule;
import org.opendaylight.opflex.genie.content.model.module.Module;
import org.opendaylight.opflex.genie.content.model.mprop.MProp;
import org.opendaylight.opflex.genie.content.model.mtype.Language;
import org.opendaylight.opflex.genie.content.model.mtype.MLanguageBinding;
import org.opendaylight.opflex.genie.content.model.mtype.MType;
import org.opendaylight.opflex.genie.content.model.mtype.PassBy;
import org.opendaylight.opflex.genie.engine.file.WriteStats;
import org.opendaylight.opflex.genie.engine.format.*;
import org.opendaylight.opflex.genie.engine.model.Ident;
import org.opendaylight.opflex.genie.engine.model.Item;
import org.opendaylight.opflex.genie.engine.model.Pair;
import org.opendaylight.opflex.genie.engine.proc.Config;
import org.opendaylight.opflex.modlan.report.Severity;
import org.opendaylight.opflex.modlan.utils.Strings;
import java.util.*;
/**
* Created by midvorki on 11/20/14.
*/
public class FClassDef extends ItemFormatterTask
{
public FClassDef(
FormatterCtx aInFormatterCtx,
FileNameRule aInFileNameRule,
Indenter aInIndenter,
BlockFormatDirective aInHeaderFormatDirective,
BlockFormatDirective aInCommentFormatDirective,
boolean aInIsUserFile,
WriteStats aInStats,
Item aInItem)
{
super(
aInFormatterCtx,
aInFileNameRule,
aInIndenter,
aInHeaderFormatDirective,
aInCommentFormatDirective,
aInIsUserFile,
aInStats,
aInItem);
}
/**
* Optional API required by framework to regulate triggering of tasks.
* This method identifies whether this task should be triggered for the item passed in.
* @param aIn item for which task is considered to be trriggered
* @return true if task shouold be triggered, false if task should be skipped for this item.
*/
public static boolean shouldTriggerTask(Item aIn)
{
return ((MClass)aIn).isConcrete();
}
/**
* Optional API required by framework to identify namespace/module-space for the corresponding generated file.
* @param aIn item for which task is being triggered
* @return name of the module/namespace that corresponds to the item
*/
public static String getTargetModule(Item aIn)
{
return ((MClass) aIn).getModule().getLID().getName();
}
/**
* Optional API required by the framework for transformation of file naming rule for the corresponding
* generated file. This method can customize the location for the generated file.
* @param aInFnr file name rule template
* @param aInItem item for which file is generated
* @return transformed file name rule
*/
public static FileNameRule transformFileNameRule(FileNameRule aInFnr,Item aInItem)
{
String lTargetModue = getTargetModule(aInItem);
String lOldRelativePath = aInFnr.getRelativePath();
String lNewRelativePath = lOldRelativePath + "/include/" + Config.getProjName() + "/" + lTargetModue;
FileNameRule lFnr = new FileNameRule(
lNewRelativePath,
null,
aInFnr.getFilePrefix(),
aInFnr.getFileSuffix(),
aInFnr.getFileExtension(),
getClassName((MClass)aInItem, false));
return lFnr;
}
public void generate()
{
MClass lClass = (MClass) getItem();
generate(0, lClass);
}
public static String getClassName(MClass aInClass, boolean aInFullyQualified)
{
return aInFullyQualified ? (getNamespace(aInClass,true) + "::" + aInClass.getLID().getName()) : aInClass.getLID().getName();
}
public static String getInclTag(MClass aInClass)
{
return "GI_" + aInClass.getModule().getLID().getName().toUpperCase() + '_' + aInClass.getLID().getName().toUpperCase() + "_HPP";
}
public static String getNamespace(String aInModuleName, boolean aInFullyQualified)
{
return aInFullyQualified ? (Config.getProjName() + "::" + aInModuleName) : (aInModuleName);
}
public static String getNamespace(MClass aInClass, boolean aInFullyQualified)
{
return getNamespace(aInClass.getModule().getLID().getName(), aInFullyQualified);
}
public static String getInclude(String aInPath, boolean aInIsBuiltIn)
{
return "#include " + (aInIsBuiltIn ? '<' : '\"') + aInPath + (aInIsBuiltIn ? '>' : '\"');
}
public static String getIncludePath(MClass aIn)
{
return Config.getProjName() + "/" + getNamespace(aIn,false) + "/" + aIn.getLID().getName();
}
public static String getInclude(MClass aIn)
{
return getInclude(getIncludePath(aIn) + ".hpp", false);
}
private void generate(int aInIndent, MClass aInClass)
{
String lInclTag = getInclTag(aInClass);
out.println(aInIndent,"#pragma once");
out.println(aInIndent,"#ifndef " + lInclTag);
out.println(aInIndent,"#define " + lInclTag);
// doesn't seem to be needed for now. Revisit?
//genForwardDecls(aInIndent, aInClass);
genIncludes(aInIndent, aInClass);
genBody(aInIndent, aInClass);
out.println(aInIndent,"#endif // " + lInclTag);
}
private void genForwardDecls(int aInIndent, MClass aInClass)
{
out.println();
out.println(aInIndent, "namespace " + Config.getProjName() + " {");
out.println();
out.printIncodeComment(aInIndent, "FORWARD DECLARATIONS FOR INHERITANCE ");
for (MClass lThis = aInClass; null != lThis; lThis = lThis.getSuperclass())
{
genForwardDecl(aInIndent, lThis);
}
TreeMap<Ident, MClass> lConts = new TreeMap<Ident, MClass>();
aInClass.getContainsClasses(lConts, true, true);
out.printIncodeComment(aInIndent, "FORWARD DECLARATIONS FOR CONTAINED ");
for (MClass lThis : lConts.values())
{
genForwardDecl(aInIndent, lThis);
}
TreeMap<Ident, MClass> lContr = new TreeMap<Ident, MClass>();
aInClass.getContainedByClasses(lContr, true, true);
out.printIncodeComment(aInIndent, "FORWARD DECLARATIONS FOR CONTAINERS ");
for (MClass lThis : lContr.values())
{
genForwardDecl(aInIndent,lThis);
}
out.println();
out.println(aInIndent, "} // namespace " + Config.getProjName());
out.println();
}
private void genForwardDecl(int aInIndent, MClass aInClass)
{
String lNs = getNamespace(aInClass, false);
out.println(aInIndent, "namespace " + lNs + " {");
out.println();
out.printHeaderComment(aInIndent, "forward declaration for " + aInClass);
out.println(aInIndent, "class " + aInClass.getLID().getName() + ";");
out.println();
out.println(aInIndent, "} // namespace " + lNs);
out.println();
}
private void genIncludes(int aInIndent, MClass aInClass)
{
out.println();
out.println(aInIndent,getInclude("boost/optional.hpp", true));
out.println(aInIndent,getInclude("opflex/modb/URIBuilder.h", false));
out.println(aInIndent,getInclude("opflex/modb/mo-internal/MO.h", false));
/**
if (aInClass.hasSuperclass())
{
MClass lSuper = aInClass.getSuperclass();
out.printIncodeComment(aInIndent, "superclass: " + lSuper);
out.println(aInIndent,getInclude(lSuper), false);
}
*/
TreeMap<Ident, MClass> lConts = new TreeMap<Ident, MClass>();
aInClass.getContainsClasses(lConts, true, true);
for (MClass lThis : lConts.values())
{
out.printIncodeComment(aInIndent, "contains: " + lThis);
out.println(aInIndent, getInclude(lThis), false);
}
}
private void genBody(int aInIndent, MClass aInClass)
{
out.println();
String lNs = getNamespace(aInClass, false);
out.println(aInIndent, "namespace " + Config.getProjName() + " {");
out.println(aInIndent, "namespace " + lNs + " {");
out.println();
genClass(aInIndent, aInClass);
out.println();
out.println(aInIndent, "} // namespace " + lNs);
out.println(aInIndent, "} // namespace " + Config.getProjName());
}
private void genClass(int aInIndent, MClass aInClass)
{
out.println(aInIndent, "class " + aInClass.getLID().getName());
/**
if (aInClass.hasSuperclass())
{
MClass lSuperclass = aInClass.getSuperclass();
out.println(aInIndent + 1, ": public " + getClassName(lSuperclass,true));
}
else**/
{
out.println(aInIndent + 1, ": public opflex::modb::mointernal::MO");
}
out.println(aInIndent, "{");
genPublic(aInIndent + 1, aInClass);
out.println(aInIndent, "}; // class " + aInClass.getLID().getName());
}
private void genPublic(int aInIndent, MClass aInClass)
{
out.println(aInIndent - 1, "public:");
out.println();
genClassId(aInIndent, aInClass);
genProps(aInIndent, aInClass);
genConstructor(aInIndent, aInClass);
}
private void genClassId(int aInIndent, MClass aInClass)
{
String lClassName = getClassName(aInClass, false);
out.printHeaderComment(aInIndent, Arrays.asList("The unique class ID for " + lClassName));
out.println(aInIndent, "static const opflex::modb::class_id_t CLASS_ID = " + aInClass.getGID().getId() + ";");
out.println();
}
private void genProps(int aInIndent, MClass aInClass)
{
TreeMap<String, MProp> lProps = new TreeMap<String, MProp>();
aInClass.findProp(lProps, true); // false
for (MProp lProp : lProps.values())
{
// ONLY IF THIS PROPERTY IS DEFINED LOCALLY
//if (lProp.getBase().getMClass() == aInClass)
{
genProp(aInIndent, aInClass, lProp, lProp.getPropId(aInClass));
}
}
}
public static String getTypeAccessor(String aInPType)
{
if (aInPType.startsWith("Enum") ||
aInPType.startsWith("Bitmask") ||
aInPType.startsWith("UInt"))
{
aInPType = "UInt64";
}
else if (aInPType.equals("URI") ||
aInPType.equals("IP") ||
aInPType.equals("UUID"))
{
aInPType = "String";
}
return aInPType;
}
public static String getCast(String aInPType, String aInSyntax)
{
if (aInPType.startsWith("Enum") ||
aInPType.startsWith("Bitmask") ||
(aInPType.startsWith("UInt") &&
!aInPType.equals("UInt64")))
{
return "(" + aInSyntax + ")";
}
return "";
}
private String toUnsignedStr(int aInInt)
{
return Long.toString(aInInt & 0xFFFFFFFFL) + "ul";
}
private void genProp(int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx)
{
MProp lBaseProp = aInProp.getBase();
MType lType = lBaseProp.getType(false);
MType lBaseType = lType.getBuiltInType();
LinkedList<String> lComments = new LinkedList<String>();
aInProp.getComments(lComments);
{
genPropCheck(aInIndent,aInClass,aInProp,aInPropIdx,lType,lBaseType,lComments);
genPropAccessor(aInIndent, aInClass, aInProp, aInPropIdx, lType, lBaseType, lComments);
genPropMutator(aInIndent, aInClass, aInProp, aInPropIdx, lType, lBaseType, lComments);
}
}
private void genPropCheck(
int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx, MType aInType, MType aInBaseType,
Collection<String> aInComments, String aInCheckName, String aInPType)
{
//
// COMMENT
//
int lCommentSize = 2 + aInComments.size();
String lComment[] = new String[lCommentSize];
int lCommentIdx = 0;
lComment[lCommentIdx++] = "Check whether " + aInCheckName + " has been set";
for (String lCommLine : aInComments)
{
lComment[lCommentIdx++] = lCommLine;
}
lComment[lCommentIdx++] = "@return true if " + aInCheckName + " has been set";
out.printHeaderComment(aInIndent,lComment);
//
// METHOD DEFINITION
//
out.println(aInIndent,"bool is" + Strings.upFirstLetter(aInCheckName) + "Set()");
//
// METHOD BODY
//
out.println(aInIndent,"{");
out.println(aInIndent + 1, "return isPropertySet(" + toUnsignedStr(aInPropIdx) + ";");
out.println(aInIndent,"}");
out.println();
}
private void genPropCheck(
int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx, MType aInType, MType aInBaseType,
Collection<String> aInComments)
{
String lPType = FMetaDef.getTypeName(aInBaseType);
genPropCheck(aInIndent, aInClass, aInProp, aInPropIdx, aInType, aInBaseType,
aInComments, aInProp.getLID().getName(),
lPType);
}
private void genPropAccessor(
int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx, MType aInType, MType aInBaseType,
Collection<String> aInComments)
{
String lName = aInProp.getLID().getName();
String lPType = Strings.upFirstLetter(aInBaseType.getLID().getName());
String lEffSyntax = getPropEffSyntax(aInBaseType);
String lCast = getCast(lPType, lEffSyntax);
lPType = getTypeAccessor(lPType);
genPropAccessor(aInIndent, aInClass, aInProp, aInPropIdx, aInType, aInBaseType, aInComments,
lName, lName, lEffSyntax, lPType, lCast, "");
}
private void genPropAccessor(
int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx, MType aInType, MType aInBaseType,
Collection<String> aInComments, String aInCheckName, String aInName, String aInEffSyntax, String aInPType,
String aInCast, String aInAccessor)
{
//
// COMMENT
//
int lCommentSize = 2 + aInComments.size();
String lComment[] = new String[lCommentSize];
int lCommentIdx = 0;
lComment[lCommentIdx++] = "Get the value of " + aInName + " if it has been set.";
for (String lCommLine : aInComments)
{
lComment[lCommentIdx++] = lCommLine;
}
lComment[lCommentIdx++] = "@return the value of " + aInName + " or boost::none if not set";
out.printHeaderComment(aInIndent,lComment);
out.println(aInIndent,"boost::optional<" + aInEffSyntax + "> get" + Strings.upFirstLetter(aInName) + "()");
out.println(aInIndent,"{");
out.println(aInIndent + 1,"if (is" + Strings.upFirstLetter(aInCheckName) + "Set())");
out.println(aInIndent + 2,"return " + aInCast + "getProperty(" + toUnsignedStr(aInPropIdx) + ");");
out.println(aInIndent + 1,"return boost::none;");
out.println(aInIndent,"}");
out.println();
}
private void genPropDefaultedAccessor(
int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx, MType aInType, MType aInBaseType,
Collection<String> aInComments, String aInName, String aInEffSyntax)
{
//
// COMMENT
//
int lCommentSize = 3 + aInComments.size();
String lComment[] = new String[lCommentSize];
int lCommentIdx = 0;
lComment[lCommentIdx++] = "Get the value of " + aInName + " if set, otherwise the value of default passed in.";
for (String lCommLine : aInComments)
{
lComment[lCommentIdx++] = lCommLine;
}
//
// DEF
//
lComment[lCommentIdx++] = "@param defaultValue default value returned if the property is not set";
lComment[lCommentIdx++] = "@return the value of " + aInName + " if set, otherwise the value of default passed in";
out.printHeaderComment(aInIndent,lComment);
out.println(aInIndent, aInEffSyntax + " get" + Strings.upFirstLetter(aInName) + "(" + aInEffSyntax + " defaultValue)");
//
// BODY
//
out.println(aInIndent,"{");
out.println(aInIndent + 1, "return get" + Strings.upFirstLetter(aInName) + "().get_value_or(defaultValue);");
out.println(aInIndent,"}");
out.println();
}
private void genPropMutator(int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx, MType aInType, MType aInBaseType,
Collection<String> aInBaseComments, Collection<String> aInComments, String aInName, String aInPType, String aInEffSyntax, String aInParamName, String aInParamHelp,
String aInSetterPrefix)
{
//
// COMMENT
//
ArrayList<String> lComment = new ArrayList<>(aInBaseComments);
if (aInComments.size() > 0) lComment.add("");
lComment.addAll(aInComments);
// Arrays.asList(
//
lComment.add("");
lComment.add("@param " + aInParamName + " " + aInParamHelp);
lComment.add("@return a reference to the current object");
lComment.add("@throws std::logic_error if no mutator is active");
lComment.add("@see opflex::modb::Mutator");
out.printHeaderComment(aInIndent,lComment);
//
// DEF
//
out.println(aInIndent, getClassName(aInClass, true) + "& set" + Strings.upFirstLetter(aInName) + "(" + aInEffSyntax + " " + aInParamName + ")");
//
// BODY
//
out.println(aInIndent,"{");
out.println(aInIndent + 1, "setProperty(" + toUnsignedStr(aInPropIdx)+ ", " + aInParamName + ");");
out.println(aInIndent + 1, "return *this;");
out.println(aInIndent,"}");
out.println();
}
private void genPropMutator(int aInIndent, MClass aInClass, MProp aInProp, int aInPropIdx, MType aInType, MType aInBaseType,
Collection<String> aInComments)
{
String lName = aInProp.getLID().getName();
String lPType = Strings.upFirstLetter(aInBaseType.getLID().getName());
lPType = getTypeAccessor(lPType);
List<String> lComments = Arrays.asList(
"Set " + lName + " to the specified value in the currently-active mutator.");
genPropMutator(aInIndent, aInClass, aInProp, aInPropIdx, aInType, aInBaseType,
lComments, aInComments, lName, lPType,
getPropEffSyntax(aInBaseType), "newValue", "the new value to set.",
"");
}
private static String getMethName(List<Pair<String, MNameRule>> aInNamingPath,
boolean aInIsUniqueNaming,
String prefix)
{
if (aInIsUniqueNaming)
{
return prefix;
}
else
{
StringBuilder lSb = new StringBuilder();
lSb.append(prefix + "Under");
int lSize = aInNamingPath.size();
int lIdx = lSize;
for (Pair<String, MNameRule> lPathNode : aInNamingPath)
{
if (0 < --lIdx)
{
MClass lClass = MClass.get(lPathNode.getFirst());
Module lMod = lClass.getModule();
lPathNode.getSecond();
lSb.append(Strings.upFirstLetter(lMod.getLID().getName()));
lSb.append(Strings.upFirstLetter(lClass.getLID().getName()));
}
}
return lSb.toString();
}
}
private static String getResolverMethName(List<Pair<String, MNameRule>> aInNamingPath,
boolean aInIsUniqueNaming)
{
return getMethName(aInNamingPath, aInIsUniqueNaming, "resolve");
}
private static String getRemoverMethName(List<Pair<String, MNameRule>> aInNamingPath,
boolean aInIsUniqueNaming)
{
return getMethName(aInNamingPath, aInIsUniqueNaming, "remove");
}
public static int countNamingProps(List<Pair<String, MNameRule>> aInNamingPath)
{
int lRet = 0;
for (Pair<String, MNameRule> lNode : aInNamingPath)
{
Collection<MNameComponent> lNcs = lNode.getSecond().getComponents();
if (!(null == lNcs || lNcs.isEmpty()))
{
for (MNameComponent lNc : lNcs)
{
if (lNc.hasPropName())
{
lRet++;
}
}
}
}
return lRet;
}
public static void getPropParamName(MClass aInClass, String aInPropName, StringBuilder aOutSb)
{
aOutSb.append(aInClass.getModule().getLID().getName());
aOutSb.append(Strings.upFirstLetter(aInClass.getLID().getName()));
aOutSb.append(Strings.upFirstLetter(aInPropName));
}
public static String getPropParamName(MClass aInClass, String aInPropName)
{
StringBuilder lSb = new StringBuilder();
getPropParamName(aInClass,aInPropName,lSb);
return lSb.toString();
}
public static String getPropEffSyntax(MType aInBaseType)
{
StringBuilder lRet = new StringBuilder();
MLanguageBinding lLang = aInBaseType.getLanguageBinding(Language.CPP);
boolean lPassAsConst = lLang.getPassConst();
PassBy lPassBy = lLang.getPassBy();
String lSyntax = aInBaseType.getLanguageBinding(Language.CPP).getSyntax();
if (lPassAsConst)
{
lRet.append("const ");
}
lRet.append(lSyntax);
switch (lPassBy)
{
case REFERENCE:
case POINTER:
lRet.append('&');
break;
case VALUE:
default:
break;
}
return lRet.toString();
}
public static String getPropParamDef(MClass aInClass, String aInPropName)
{
MProp lProp = aInClass.findProp(aInPropName, false);
if (null == lProp)
{
Severity.DEATH.report(aInClass.toString(),
"preparing param defs for prop: " + aInPropName,
"no such property: " + aInPropName, "");
}
MProp lBaseProp = lProp.getBase();
MType lType = lBaseProp.getType(false);
MType lBaseType = lType.getBuiltInType();
StringBuilder lRet = new StringBuilder();
lRet.append(getPropEffSyntax(lBaseType));
lRet.append(" ");
getPropParamName(aInClass, aInPropName, lRet);
return lRet.toString();
}
private void genConstructor(int aInIdent, MClass aInClass)
{
String lclassName = getClassName(aInClass, false);
String[] lComment =
{"Construct an instance of " + lclassName + ".",
"This should not typically be called from user code."};
out.printHeaderComment(aInIdent,lComment);
if (aInClass.isConcrete())
{
out.println(aInIdent, aInClass.getLID().getName() + "(");
out.println(aInIdent + 1, "const opflex::modb::URI& uri)");
out.println(aInIdent + 1, ": MO(CLASS_ID, uri) { }");
}
}
}
| Fix compilation problems with genie generated code for proxy
Change-Id: Ie7d423d1a7e145774d98d13717639e7a8712874f
Signed-off-by: Tom Flynn <[email protected]>
| genie/src/main/java/org/opendaylight/opflex/genie/content/format/proxy/structure/cpp/FClassDef.java | Fix compilation problems with genie generated code for proxy |
|
Java | epl-1.0 | 86c19773f9de786f23f194156cc122d2b5a4b02b | 0 | gnodet/wikitext | /*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.mylyn.tasks.ui;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiImages;
import org.eclipse.mylyn.monitor.core.DateUtil;
import org.eclipse.mylyn.monitor.core.StatusHandler;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryQuery;
import org.eclipse.mylyn.tasks.core.AbstractTask;
import org.eclipse.mylyn.tasks.core.QueryHitCollector;
import org.eclipse.mylyn.tasks.core.TaskList;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.AbstractTask.RepositoryTaskSyncState;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressConstants;
/**
* Not API.
*
* @author Mik Kersten
* @author Rob Elves
* @author Steffen Pingel
*/
class SynchronizeQueryJob extends Job {
private final AbstractRepositoryConnector connector;
private final TaskRepository repository;
private final Set<AbstractRepositoryQuery> queries;
private final TaskList taskList;
private boolean synchronizeChangedTasks;
private boolean forced = false;
private HashSet<AbstractTask> tasksToBeSynchronized = new HashSet<AbstractTask>();
private boolean fullSynchronization;
public SynchronizeQueryJob(AbstractRepositoryConnector connector, TaskRepository repository,
Set<AbstractRepositoryQuery> queries, TaskList taskList) {
super("Synchronizing queries for " + repository.getRepositoryLabel());
this.connector = connector;
this.repository = repository;
this.queries = queries;
this.taskList = taskList;
}
public void setSynchronizeChangedTasks(boolean synchronizeChangedTasks) {
this.synchronizeChangedTasks = synchronizeChangedTasks;
}
/**
* @since 2.2
*/
public boolean isFullSynchronization() {
return fullSynchronization;
}
/**
* @since 2.2
*/
public void setFullSynchronization(boolean fullSynchronization) {
this.fullSynchronization = fullSynchronization;
}
/**
* Returns true, if synchronization was triggered manually and not by an automatic background job.
*/
public boolean isForced() {
return forced;
}
/**
* Indicates a manual synchronization (User initiated). If set to true, a dialog will be displayed in case of
* errors. Any tasks with missing data will be retrieved.
*/
public void setForced(boolean forced) {
this.forced = forced;
}
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
monitor.beginTask("Synchronizing " + queries.size() + " queries", 20 + queries.size() * 10 + 40);
Set<AbstractTask> allTasks = Collections.unmodifiableSet(taskList.getRepositoryTasks(repository.getUrl()));
for (AbstractTask task : allTasks) {
task.setStale(false);
}
// check if the repository has changed at all and have the connector mark tasks that need synchronization
if (isFullSynchronization()) {
try {
monitor.subTask("Checking for changed tasks");
boolean hasChangedOrNew = connector.markStaleTasks(repository, allTasks, new SubProgressMonitor(
monitor, 20));
if (!hasChangedOrNew && !forced) {
updateQueryStatus(null);
return Status.OK_STATUS;
}
} catch (CoreException e) {
// synchronization is unlikely to succeed, inform user and exit
updateQueryStatus(e.getStatus());
return Status.OK_STATUS;
}
}
// synchronize queries, tasks changed within query are added to set of tasks to be synchronized
int n = 0;
for (AbstractRepositoryQuery repositoryQuery : queries) {
repositoryQuery.setSynchronizationStatus(null);
monitor.setTaskName("Synchronizing " + ++n + "/" + queries.size() + ": " + repositoryQuery.getSummary());
synchronizeQuery(repositoryQuery, new SubProgressMonitor(monitor, 10));
repositoryQuery.setSynchronizing(false);
taskList.notifyContainersUpdated(Collections.singleton(repositoryQuery));
}
// for background synchronizations all changed tasks are synchronized including the ones that are not part of a query
if (!forced) {
for (AbstractTask task : allTasks) {
if (task.isStale()) {
tasksToBeSynchronized.add(task);
task.setSynchronizing(true);
}
}
}
// synchronize tasks that were marked by the connector
if (!tasksToBeSynchronized.isEmpty()) {
monitor.setTaskName("Synchronizing " + tasksToBeSynchronized.size() + " changed tasks");
SynchronizeTaskJob job = new SynchronizeTaskJob(connector, tasksToBeSynchronized);
job.setForced(forced);
job.run(new SubProgressMonitor(monitor, 40));
if (Platform.isRunning() && !(TasksUiPlugin.getRepositoryManager() == null) && isFullSynchronization()) {
TasksUiPlugin.getRepositoryManager().setSynchronizationTime(repository,
connector.getSynchronizationTimestamp(repository, tasksToBeSynchronized),
TasksUiPlugin.getDefault().getRepositoriesFilePath());
}
}
taskList.notifyContainersUpdated(null);
return Status.OK_STATUS;
} finally {
monitor.done();
}
}
private void updateQueryStatus(final IStatus status) {
for (AbstractRepositoryQuery repositoryQuery : queries) {
repositoryQuery.setSynchronizationStatus(status);
repositoryQuery.setSynchronizing(false);
}
taskList.notifyContainersUpdated(queries);
if (status != null && isForced()) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
StatusHandler.displayStatus("Query Synchronization Failed", status);
}
});
}
}
private void synchronizeQuery(AbstractRepositoryQuery repositoryQuery, IProgressMonitor monitor) {
setProperty(IProgressConstants.ICON_PROPERTY, TasksUiImages.REPOSITORY_SYNCHRONIZE);
QueryHitCollector collector = new QueryHitCollector(new TaskFactory(repository, true, false));
final IStatus resultingStatus = connector.performQuery(repositoryQuery, repository, monitor, collector);
if (resultingStatus.getSeverity() == IStatus.CANCEL) {
// do nothing
} else if (resultingStatus.isOK()) {
if (collector.getTasks().size() >= QueryHitCollector.MAX_HITS) {
StatusHandler.log(QueryHitCollector.MAX_HITS_REACHED + "\n" + repositoryQuery.getSummary(), this);
}
// bug#195485 - tasks dissappear form tasklist
for (AbstractTask removedTask : repositoryQuery.getChildren()) {
taskList.removeFromQuery(repositoryQuery, removedTask);
}
for (AbstractTask hit : collector.getTasks()) {
AbstractTask task = taskList.getTask(hit.getHandleIdentifier());
if (task != null) {
// update the existing task from the query hit
boolean changed = connector.updateTaskFromQueryHit(repository, task, hit);
if (changed && !task.isStale()
&& task.getSynchronizationState() == RepositoryTaskSyncState.SYNCHRONIZED) {
// set incoming marker for web tasks
task.setSynchronizationState(RepositoryTaskSyncState.INCOMING);
}
task.setSynchronizationStatus(null);
task.setSynchronizing(false);
} else {
// new tasks are marked stale by default
task = hit;
task.setStale(true);
task.setSynchronizationState(RepositoryTaskSyncState.INCOMING);
}
taskList.addTask(task, repositoryQuery);
if (synchronizeChangedTasks && task.isStale()) {
tasksToBeSynchronized.add(task);
task.setSynchronizing(true);
}
}
repositoryQuery.setLastSynchronizedStamp(DateUtil.getFormattedDate(new Date(), "MMM d, H:mm:ss"));
} else {
repositoryQuery.setSynchronizationStatus(resultingStatus);
if (isForced()) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
StatusHandler.displayStatus("Query Synchronization Failed", resultingStatus);
}
});
}
}
}
}
| org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/SynchronizeQueryJob.java | /*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.mylyn.tasks.ui;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiImages;
import org.eclipse.mylyn.monitor.core.DateUtil;
import org.eclipse.mylyn.monitor.core.StatusHandler;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryQuery;
import org.eclipse.mylyn.tasks.core.AbstractTask;
import org.eclipse.mylyn.tasks.core.QueryHitCollector;
import org.eclipse.mylyn.tasks.core.TaskList;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.AbstractTask.RepositoryTaskSyncState;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressConstants;
/**
* Not API.
*
* @author Mik Kersten
* @author Rob Elves
* @author Steffen Pingel
*/
class SynchronizeQueryJob extends Job {
private final AbstractRepositoryConnector connector;
private final TaskRepository repository;
private final Set<AbstractRepositoryQuery> queries;
private final TaskList taskList;
private boolean synchronizeChangedTasks;
private boolean forced = false;
private HashSet<AbstractTask> tasksToBeSynchronized = new HashSet<AbstractTask>();
private boolean fullSynchronization;
public SynchronizeQueryJob(AbstractRepositoryConnector connector, TaskRepository repository,
Set<AbstractRepositoryQuery> queries, TaskList taskList) {
super("Synchronizing queries for " + repository.getRepositoryLabel());
this.connector = connector;
this.repository = repository;
this.queries = queries;
this.taskList = taskList;
}
public void setSynchronizeChangedTasks(boolean synchronizeChangedTasks) {
this.synchronizeChangedTasks = synchronizeChangedTasks;
}
/**
* @since 2.2
*/
public boolean isFullSynchronization() {
return fullSynchronization;
}
/**
* @since 2.2
*/
public void setFullSynchronization(boolean fullSynchronization) {
this.fullSynchronization = fullSynchronization;
}
/**
* Returns true, if synchronization was triggered manually and not by an automatic background job.
*/
public boolean isForced() {
return forced;
}
/**
* Indicates a manual synchronization (User initiated). If set to true, a dialog will be displayed in case of
* errors. Any tasks with missing data will be retrieved.
*/
public void setForced(boolean forced) {
this.forced = forced;
}
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
monitor.beginTask("Synchronizing " + queries.size() + " queries", 20 + queries.size() * 10 + 40);
Set<AbstractTask> allTasks = Collections.unmodifiableSet(taskList.getRepositoryTasks(repository.getUrl()));
for (AbstractTask task : allTasks) {
task.setStale(false);
}
// check if the repository has changed at all and have the connector mark tasks that need synchronization
if (isFullSynchronization()) {
try {
monitor.subTask("Checking for changed tasks");
boolean hasChangedOrNew = connector.markStaleTasks(repository, allTasks, new SubProgressMonitor(
monitor, 20));
if (!hasChangedOrNew && !forced) {
updateQueryStatus(null);
return Status.OK_STATUS;
}
} catch (CoreException e) {
// synchronization is unlikely to succeed, inform user and exit
updateQueryStatus(e.getStatus());
return Status.OK_STATUS;
}
}
// synchronize queries, tasks changed within query are added to set of tasks to be synchronized
int n = 0;
for (AbstractRepositoryQuery repositoryQuery : queries) {
repositoryQuery.setSynchronizationStatus(null);
monitor.setTaskName("Synchronizing " + ++n + "/" + queries.size() + ": " + repositoryQuery.getSummary());
synchronizeQuery(repositoryQuery, new SubProgressMonitor(monitor, 10));
repositoryQuery.setSynchronizing(false);
taskList.notifyContainersUpdated(Collections.singleton(repositoryQuery));
}
// for background synchronizations all changed tasks are synchronized including the ones that are not part of a query
if (!forced) {
for (AbstractTask task : allTasks) {
if (task.isStale()) {
tasksToBeSynchronized.add(task);
task.setSynchronizing(true);
}
}
}
// synchronize tasks that were marked by the connector
if (!tasksToBeSynchronized.isEmpty()) {
monitor.setTaskName("Synchronizing " + tasksToBeSynchronized.size() + " changed tasks");
SynchronizeTaskJob job = new SynchronizeTaskJob(connector, tasksToBeSynchronized);
job.setForced(forced);
job.run(new SubProgressMonitor(monitor, 40));
if (Platform.isRunning() && !(TasksUiPlugin.getRepositoryManager() == null)) {
TasksUiPlugin.getRepositoryManager().setSynchronizationTime(repository,
connector.getSynchronizationTimestamp(repository, tasksToBeSynchronized),
TasksUiPlugin.getDefault().getRepositoriesFilePath());
}
}
taskList.notifyContainersUpdated(null);
return Status.OK_STATUS;
} finally {
monitor.done();
}
}
private void updateQueryStatus(final IStatus status) {
for (AbstractRepositoryQuery repositoryQuery : queries) {
repositoryQuery.setSynchronizationStatus(status);
repositoryQuery.setSynchronizing(false);
}
taskList.notifyContainersUpdated(queries);
if (status != null && isForced()) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
StatusHandler.displayStatus("Query Synchronization Failed", status);
}
});
}
}
private void synchronizeQuery(AbstractRepositoryQuery repositoryQuery, IProgressMonitor monitor) {
setProperty(IProgressConstants.ICON_PROPERTY, TasksUiImages.REPOSITORY_SYNCHRONIZE);
QueryHitCollector collector = new QueryHitCollector(new TaskFactory(repository, true, false));
final IStatus resultingStatus = connector.performQuery(repositoryQuery, repository, monitor, collector);
if (resultingStatus.getSeverity() == IStatus.CANCEL) {
// do nothing
} else if (resultingStatus.isOK()) {
if (collector.getTasks().size() >= QueryHitCollector.MAX_HITS) {
StatusHandler.log(QueryHitCollector.MAX_HITS_REACHED + "\n" + repositoryQuery.getSummary(), this);
}
// bug#195485 - tasks dissappear form tasklist
for (AbstractTask removedTask : repositoryQuery.getChildren()) {
taskList.removeFromQuery(repositoryQuery, removedTask);
}
for (AbstractTask hit : collector.getTasks()) {
AbstractTask task = taskList.getTask(hit.getHandleIdentifier());
if (task != null) {
// update the existing task from the query hit
boolean changed = connector.updateTaskFromQueryHit(repository, task, hit);
if (changed && !task.isStale()
&& task.getSynchronizationState() == RepositoryTaskSyncState.SYNCHRONIZED) {
// set incoming marker for web tasks
task.setSynchronizationState(RepositoryTaskSyncState.INCOMING);
}
task.setSynchronizationStatus(null);
task.setSynchronizing(false);
} else {
// new tasks are marked stale by default
task = hit;
task.setStale(true);
task.setSynchronizationState(RepositoryTaskSyncState.INCOMING);
}
taskList.addTask(task, repositoryQuery);
if (synchronizeChangedTasks && task.isStale()) {
tasksToBeSynchronized.add(task);
task.setSynchronizing(true);
}
}
repositoryQuery.setLastSynchronizedStamp(DateUtil.getFormattedDate(new Date(), "MMM d, H:mm:ss"));
} else {
repositoryQuery.setSynchronizationStatus(resultingStatus);
if (isForced()) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
StatusHandler.displayStatus("Query Synchronization Failed", resultingStatus);
}
});
}
}
}
}
| RESOLVED - bug 208488: [performance] streamline synch after task submit
https://bugs.eclipse.org/bugs/show_bug.cgi?id=208488
| org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/SynchronizeQueryJob.java | RESOLVED - bug 208488: [performance] streamline synch after task submit https://bugs.eclipse.org/bugs/show_bug.cgi?id=208488 |
|
Java | mpl-2.0 | 224b2c19e1b8d7e98b5cac9cf20c9d70bcba01c4 | 0 | JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core |
import drafts.com.sun.star.accessibility.XAccessibleContext;
import drafts.com.sun.star.accessibility.XAccessibleText;
import drafts.com.sun.star.accessibility.XAccessibleEditableText;
import drafts.com.sun.star.accessibility.AccessibleTextType;
import com.sun.star.awt.Rectangle;
import com.sun.star.awt.Point;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.lang.IndexOutOfBoundsException;
import com.sun.star.beans.PropertyValue;
import java.util.Vector;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JDialog;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.Icon;
import javax.swing.JTextArea;
import javax.swing.JOptionPane;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.BoxLayout;
import javax.swing.text.JTextComponent;
class AccessibleTextHandler extends NodeHandler
{
public NodeHandler createHandler (XAccessibleContext xContext)
{
XAccessibleText xText = (XAccessibleText) UnoRuntime.queryInterface (
XAccessibleText.class, xContext);
if (xText != null)
return new AccessibleTextHandler (xText);
else
return null;
}
public AccessibleTextHandler ()
{
}
public AccessibleTextHandler (XAccessibleText xText)
{
if (xText != null)
maChildList.setSize (8);
}
public AccessibleTreeNode createChild (AccessibleTreeNode aParent, int nIndex)
{
AccessibleTreeNode aChild = null;
XAccessibleText xText = null;
if (aParent instanceof AccTreeNode)
xText = ((AccTreeNode)aParent).getText();
try
{
if( xText != null )
{
switch( nIndex )
{
case 0:
aChild = new StringNode (xText.getText(), aParent);
break;
case 1:
aChild = new StringNode ("# chars: " + xText.getCharacterCount(), aParent);
break;
case 2:
aChild = new StringNode (characters( xText ), aParent);
break;
case 3:
aChild = new StringNode ("selection: "
+ "[" + xText.getSelectionStart()
+ "," + xText.getSelectionEnd()
+ "] \"" + xText.getSelectedText() + "\"",
aParent);
break;
case 4:
aChild = new StringNode ("getCaretPosition: " + xText.getCaretPosition(), aParent);
break;
case 5:
{
VectorNode aVec = new VectorNode("portions", aParent);
aChild = aVec;
aVec.addChild(
textAtIndexNode( xText, "Character",
AccessibleTextType.CHARACTER,
aParent ) );
aVec.addChild(
textAtIndexNode( xText, "Word",
AccessibleTextType.WORD,
aParent ) );
aVec.addChild(
textAtIndexNode( xText, "Sentence",
AccessibleTextType.SENTENCE,
aParent ) );
aVec.addChild(
textAtIndexNode( xText, "Paragraph",
AccessibleTextType.PARAGRAPH,
aParent ) );
aVec.addChild(
textAtIndexNode( xText, "Line",
AccessibleTextType.LINE,
aParent ) );
aVec.addChild(
textAtIndexNode( xText, "Attribute",
AccessibleTextType.ATTRIBUTE_RUN,
aParent ) );
aVec.addChild(
textAtIndexNode( xText, "Glyph",
AccessibleTextType.GLYPH,
aParent ) );
}
break;
case 6:
aChild = new StringNode (bounds( xText ), aParent);
break;
case 7:
aChild = getAttributes( xText, aParent );
break;
default:
aChild = new StringNode ("unknown child index " + nIndex, aParent);
}
}
}
catch (Exception e)
{
// Return empty child.
}
return aChild;
}
private String textAtIndexNodeString(
int nStart, int nEnd,
String sWord, String sBefore, String sBehind)
{
return "[" + nStart + "," + nEnd + "] "
+ "\"" + sWord + "\" \t"
+ "(" + sBefore + ","
+ "" + sBehind + ")";
}
/** Create a text node that lists all strings of a particular text type
*/
private AccessibleTreeNode textAtIndexNode(
XAccessibleText xText,
String sName,
short nTextType,
AccessibleTreeNode aParent)
{
VectorNode aNode = new VectorNode (sName, aParent);
// get word at all positions;
// for nicer display, compare current word to previous one and
// make a new node for every interval, not for every word
int nLength = xText.getCharacterCount();
if( nLength > 0 )
{
try
{
// sWord + nStart mark the current word
// make a node as soon as a new one is found; close the last
// one at the end
String sWord = xText.getTextAtIndex(0, nTextType);
String sBefore = xText.getTextBeforeIndex(0, nTextType);
String sBehind = xText.getTextBehindIndex(0, nTextType);
int nStart = 0;
for(int i = 1; i < nLength; i++)
{
String sTmp = xText.getTextAtIndex(i, nTextType);
String sTBef = xText.getTextBeforeIndex(i, nTextType);
String sTBeh = xText.getTextBehindIndex(i, nTextType);
if( ! ( sTmp.equals( sWord ) && sTBef.equals( sBefore ) &&
sTBeh.equals( sBehind ) ) )
{
aNode.addChild (new StringNode (textAtIndexNodeString(
nStart, i, sWord, sBefore, sBehind), aNode));
sWord = sTmp;
sBefore = sTBef;
sBehind = sTBeh;
nStart = i;
}
// don't generate more than 50 children.
if (aNode.getChildCount() > 50)
{
sWord = "...";
break;
}
}
aNode.addChild (new StringNode (textAtIndexNodeString(
nStart, nLength, sWord, sBefore, sBehind), aNode));
}
catch( IndexOutOfBoundsException e )
{
aNode.addChild (new StringNode (e.toString(), aNode));
}
}
return aNode;
}
/** getCharacter (display as array string) */
private String characters(XAccessibleText xText)
{
// get count (max. 30)
int nChars = xText.getCharacterCount();
if( nChars > 30 )
nChars = 30;
// build up string
StringBuffer aChars = new StringBuffer();
try
{
aChars.append( "[" );
for( int i = 0; i < nChars; i++)
{
aChars.append( xText.getCharacter(i) );
aChars.append( "," );
}
if( nChars > 0)
{
if( nChars == xText.getCharacterCount() )
aChars.deleteCharAt( aChars.length() - 1 );
else
aChars.append( "..." );
}
aChars.append( "]" );
}
catch( IndexOutOfBoundsException e )
{
aChars.append( " ERROR " );
}
// return result
return "getCharacters: " + aChars;
}
/** iterate over characters, and translate their positions
* back and forth */
private String bounds( XAccessibleText xText )
{
StringBuffer aBuffer = new StringBuffer( "bounds: " );
try
{
// iterate over characters
int nCount = xText.getCharacterCount();
for(int i = 0; i < nCount; i++ )
{
// get bounds for this character
Rectangle aRect = xText.getCharacterBounds( i );
// get the character by 'clicking' into the middle of
// the bounds
Point aMiddle = new Point();
aMiddle.X = aRect.X + (aRect.Width / 2) - 1;
aMiddle.Y = aRect.Y + (aRect.Height / 2 ) - 1;
int nIndex = xText.getIndexAtPoint( aMiddle );
// get the character, or a '#' for an illegal index
if( (nIndex >= 0) && (nIndex < xText.getCharacter(i)) )
aBuffer.append( xText.getCharacter(nIndex) );
else
aBuffer.append( '#' );
}
}
catch( IndexOutOfBoundsException e )
{ ; } // ignore errors
return aBuffer.toString();
}
private AccessibleTreeNode getAttributes( XAccessibleText xText,
AccessibleTreeNode aParent)
{
AccessibleTreeNode aRet;
try
{
VectorNode aPortions = new VectorNode ("getAttributes", aParent);
int nIndex = 0;
int nLength = xText.getCharacterCount();
while( nIndex < nLength )
{
// get attribute run
String aPortion = xText.getTextAtIndex(
nIndex, (short)6/*AccessibleTextType.ATTRIBUTE*/ );
// get attributes and make node with attribute children
PropertyValue[] aValues = xText.getCharacterAttributes(nIndex);
VectorNode aAttrs = new VectorNode (aPortion, aPortions);
for( int i = 0; i < aValues.length; i++ )
{
new StringNode( aValues[i].Name + ": " + aValues[i].Value,
aAttrs );
}
// get next portion, but advance at least one
nIndex += (aPortion.length() > 0) ? aPortion.length() : 1;
}
aRet = aPortions;
}
catch( IndexOutOfBoundsException e )
{
aRet = new StringNode( "Exception caught:" + e, aParent );
}
return aRet;
}
static String[] aTextActions =
new String[] { "select...", "copy..." };
static String[] aEditableTextActions =
new String[] { "select...", "copy...",
"cut...", "paste...", "edit...", "format..." };
public String[] getActions (AccessibleTreeNode aNode)
{
XAccessibleEditableText xEText = null;
if (aNode instanceof AccTreeNode)
xEText = ((AccTreeNode)aNode).getEditText ();
return (xEText == null) ? aTextActions : aEditableTextActions;
}
public void performAction (AccessibleTreeNode aNode, int nIndex)
{
if ( ! (aNode instanceof AccTreeNode))
return;
AccTreeNode aATNode = (AccTreeNode)aNode;
TextActionDialog aDialog = null;
// create proper dialog
switch( nIndex )
{
case 0:
aDialog = new TextActionDialog( aATNode,
"Select range:",
"select" )
{
boolean action(
JTextComponent aText, AccTreeNode aNode )
throws IndexOutOfBoundsException
{
return aNode.getText().setSelection(
getSelectionStart(),
getSelectionEnd() );
}
};
break;
case 1:
aDialog = new TextActionDialog( aATNode,
"Select range and copy:",
"copy" )
{
boolean action(
JTextComponent aText, AccTreeNode aNode )
throws IndexOutOfBoundsException
{
return aNode.getText().copyText(
getSelectionStart(),
getSelectionEnd() );
}
};
break;
case 2:
aDialog = new TextActionDialog( aATNode,
"Select range and cut:",
"cut" )
{
boolean action(
JTextComponent aText, AccTreeNode aNode )
throws IndexOutOfBoundsException
{
return aNode.getEditText().cutText(
getSelectionStart(),
getSelectionEnd() );
}
};
break;
case 3:
aDialog = new TextActionDialog( aATNode,
"Place Caret and paste:",
"paste" )
{
boolean action(
JTextComponent aText, AccTreeNode aNode )
throws IndexOutOfBoundsException
{
return aNode.getEditText().pasteText(
aText.getCaretPosition() );
}
};
break;
case 4:
aDialog = new TextEditDialog( aATNode, "Edit text:",
"edit" );
break;
case 5:
aDialog = new TextAttributeDialog( aATNode );
break;
}
if( aDialog != null )
aDialog.show();
}
}
/**
* Display a dialog with a text field and a pair of cancel/do-it buttons
*/
class TextActionDialog extends JDialog
implements ActionListener
{
AccTreeNode aNode;
JTextArea aText;
String sName;
JCheckBox aIndexToggle;
public TextActionDialog( AccTreeNode aNd,
String sExplanation,
String sButtonText )
{
super( AccessibilityWorkBench.get() );
aNode = aNd;
sName = sButtonText;
init( sExplanation, aNode.getText().getText(), sButtonText );
// setSize( getPreferredSize() );
setSize( 350, 225 );
}
/** build dialog */
protected void init( String sExplanation,
String sText,
String sButtonText )
{
setTitle( sName );
// vertical stacking of the elements
Container aContent = getContentPane();
// aContent.setLayout( new BorderLayout() );
// label with explanation
if( sExplanation.length() > 0 )
aContent.add( new JLabel( sExplanation ), BorderLayout.NORTH );
// the text field
aText = new JTextArea();
aText.setText( sText );
aText.setColumns( Math.min( Math.max( 40, sText.length() ), 20 ) );
aText.setRows( sText.length() / 40 + 1 );
aText.setLineWrap( true );
aText.setEditable( false );
aContent.add( aText, BorderLayout.CENTER );
JPanel aButtons = new JPanel();
aButtons.setLayout( new FlowLayout() );
aIndexToggle = new JCheckBox( "reverse selection" );
aButtons.add( aIndexToggle );
JButton aActionButton = new JButton( sButtonText );
aActionButton.setActionCommand( "Action" );
aActionButton.addActionListener( this );
aButtons.add( aActionButton );
JButton aCancelButton = new JButton( "cancel" );
aCancelButton.setActionCommand( "Cancel" );
aCancelButton.addActionListener( this );
aButtons.add( aCancelButton );
// add Panel with buttons
aContent.add( aButtons, BorderLayout.SOUTH );
}
void cancel()
{
hide();
dispose();
}
void action()
{
String sError = null;
try
{
boolean bSuccess = action( aText, aNode );
if( !bSuccess )
sError = "Can't execute";
}
catch( IndexOutOfBoundsException e )
{
sError = "Index out of bounds";
}
if( sError != null )
JOptionPane.showMessageDialog( AccessibilityWorkBench.get(),
sError, sName,
JOptionPane.ERROR_MESSAGE);
cancel();
}
public void actionPerformed(ActionEvent e)
{
String sCommand = e.getActionCommand();
if( "Cancel".equals( sCommand ) )
cancel();
else if( "Action".equals( sCommand ) )
action();
}
int getSelectionStart() { return getSelection(true); }
int getSelectionEnd() { return getSelection(false); }
int getSelection(boolean bStart)
{
return ( bStart ^ aIndexToggle.isSelected() )
? aText.getSelectionStart() : aText.getSelectionEnd();
}
/** override this for dialog-specific action */
boolean action( JTextComponent aText, AccTreeNode aNode )
throws IndexOutOfBoundsException
{
return false;
}
}
class TextEditDialog extends TextActionDialog
{
public TextEditDialog( AccTreeNode aNode,
String sExplanation,
String sButtonText )
{
super( aNode, sExplanation, sButtonText );
}
protected void init( String sExplanation,
String sText,
String sButtonText )
{
super.init( sExplanation, sText, sButtonText );
aText.setEditable( true );
}
/** edit the text */
boolean action( JTextComponent aText, AccTreeNode aNode )
{
// is this text editable? if not, fudge you and return
XAccessibleEditableText xEdit = aNode.getEditText();
return ( xEdit == null ) ? false :
updateText( xEdit, aText.getText() );
}
/** update the text */
boolean updateText( XAccessibleEditableText xEdit, String sNew )
{
String sOld = xEdit.getText();
// false alarm? Early out if no change was done!
if( sOld.equals( sNew ) )
return false;
// get the minimum length of both strings
int nMinLength = sOld.length();
if( sNew.length() < nMinLength )
nMinLength = sNew.length();
// count equal characters from front and end
int nFront = 0;
while( (nFront < nMinLength) &&
(sNew.charAt(nFront) == sOld.charAt(nFront)) )
nFront++;
int nBack = 0;
while( (nBack < nMinLength) &&
( sNew.charAt(sNew.length()-nBack-1) ==
sOld.charAt(sOld.length()-nBack-1) ) )
nBack++;
if( nFront + nBack > nMinLength )
nBack = nMinLength - nFront;
// so... the first nFront and the last nBack characters
// are the same. Change the others!
String sDel = sOld.substring( nFront, sOld.length() - nBack );
String sIns = sNew.substring( nFront, sNew.length() - nBack );
System.out.println("edit text: " +
sOld.substring(0, nFront) +
" [ " + sDel + " -> " + sIns + " ] " +
sOld.substring(sOld.length() - nBack) );
boolean bRet = false;
try
{
// edit the text, and use
// (set|insert|delete|replace)Text as needed
if( nFront+nBack == 0 )
bRet = xEdit.setText( sIns );
else if( sDel.length() == 0 )
bRet = xEdit.insertText( sIns, nFront );
else if( sIns.length() == 0 )
bRet = xEdit.deleteText( nFront, sOld.length()-nBack );
else
bRet = xEdit.replaceText(nFront, sOld.length()-nBack,sIns);
}
catch( IndexOutOfBoundsException e )
{
bRet = false;
}
return bRet;
}
}
class TextAttributeDialog extends TextActionDialog
{
public TextAttributeDialog(
AccTreeNode aNode )
{
super( aNode, "Choose attributes, select text, and press 'Set':",
"set" );
}
private JCheckBox aBold, aUnderline, aItalics;
private Color aForeground, aBackground;
protected void init( String sExplanation,
String sText,
String sButtonText )
{
super.init( sExplanation, sText, sButtonText );
aForeground = Color.black;
aBackground = Color.white;
JPanel aAttr = new JPanel();
aAttr.setLayout( new BoxLayout( aAttr, BoxLayout.Y_AXIS ) );
aBold = new JCheckBox( "bold" );
aUnderline = new JCheckBox( "underline" );
aItalics = new JCheckBox( "italics" );
JButton aForeButton = new JButton("Foreground", new ColorIcon(true));
aForeButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e)
{
aForeground = JColorChooser.showDialog(
TextAttributeDialog.this,
"Select Foreground Color",
aForeground);
}
} );
JButton aBackButton = new JButton("Background", new ColorIcon(false));
aBackButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e)
{
aBackground = JColorChooser.showDialog(
TextAttributeDialog.this,
"Select Background Color",
aBackground);
}
} );
aAttr.add( aBold );
aAttr.add( aUnderline );
aAttr.add( aItalics );
aAttr.add( aForeButton );
aAttr.add( aBackButton );
getContentPane().add( aAttr, BorderLayout.WEST );
}
class ColorIcon implements Icon
{
boolean bForeground;
static final int nHeight = 16;
static final int nWidth = 16;
public ColorIcon(boolean bWhich) { bForeground = bWhich; }
public int getIconHeight() { return nHeight; }
public int getIconWidth() { return nWidth; }
public void paintIcon(Component c, Graphics g, int x, int y)
{
g.setColor( getColor() );
g.fillRect( x, y, nHeight, nWidth );
g.setColor( c.getForeground() );
g.drawRect( x, y, nHeight, nWidth );
}
Color getColor()
{
return bForeground ? aForeground : aBackground;
}
}
/** edit the text */
boolean action( JTextComponent aText, AccTreeNode aNode )
throws IndexOutOfBoundsException
{
// is this text editable? if not, fudge you and return
XAccessibleEditableText xEdit = aNode.getEditText();
boolean bSuccess = false;
if( xEdit != null )
{
PropertyValue[] aSequence = new PropertyValue[6];
aSequence[0] = new PropertyValue();
aSequence[0].Name = "CharWeight";
aSequence[0].Value = new Integer( aBold.isSelected() ? 150 : 100 );
aSequence[1] = new PropertyValue();
aSequence[1].Name = "CharUnderline";
aSequence[1].Value = new Integer( aUnderline.isSelected() ? 1 : 0 );
aSequence[2] = new PropertyValue();
aSequence[2].Name = "CharBackColor";
aSequence[2].Value = new Integer( aBackground.getRGB() );
aSequence[3] = new PropertyValue();
aSequence[3].Name = "CharColor";
aSequence[3].Value = new Integer( aForeground.getRGB() );
aSequence[4] = new PropertyValue();
aSequence[4].Name = "CharPosture";
aSequence[4].Value = new Integer( aItalics.isSelected() ? 1 : 0 );
aSequence[5] = new PropertyValue();
aSequence[5].Name = "CharBackTransparent";
aSequence[5].Value = new Boolean( false );
bSuccess = xEdit.setAttributes( getSelectionStart(),
getSelectionEnd(),
aSequence );
}
return bSuccess;
}
}
| toolkit/test/accessibility/AccessibleTextHandler.java |
import drafts.com.sun.star.accessibility.XAccessibleContext;
import drafts.com.sun.star.accessibility.XAccessibleText;
import drafts.com.sun.star.accessibility.XAccessibleEditableText;
import drafts.com.sun.star.accessibility.AccessibleTextType;
import com.sun.star.awt.Rectangle;
import com.sun.star.awt.Point;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.lang.IndexOutOfBoundsException;
import com.sun.star.beans.PropertyValue;
import java.util.Vector;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JDialog;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.Icon;
import javax.swing.JTextArea;
import javax.swing.JOptionPane;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.BoxLayout;
import javax.swing.text.JTextComponent;
class AccessibleTextHandler extends NodeHandler
{
public NodeHandler createHandler (XAccessibleContext xContext)
{
XAccessibleText xText = (XAccessibleText) UnoRuntime.queryInterface (
XAccessibleText.class, xContext);
if (xText != null)
return new AccessibleTextHandler (xText);
else
return null;
}
public AccessibleTextHandler ()
{
}
public AccessibleTextHandler (XAccessibleText xText)
{
if (xText != null)
maChildList.setSize (13);
}
public AccessibleTreeNode createChild (AccessibleTreeNode aParent, int nIndex)
{
AccessibleTreeNode aChild = null;
XAccessibleText xText = null;
if (aParent instanceof AccTreeNode)
xText = ((AccTreeNode)aParent).getText();
try
{
if( xText != null )
{
switch( nIndex )
{
case 0:
aChild = new StringNode (xText.getText(), aParent);
break;
case 1:
aChild = new StringNode ("# chars: " + xText.getCharacterCount(), aParent);
break;
case 2:
aChild = new StringNode (characters( xText ), aParent);
break;
case 3:
aChild = new StringNode ("selection: "
+ "[" + xText.getSelectionStart()
+ "," + xText.getSelectionEnd()
+ "] \"" + xText.getSelectedText() + "\"",
aParent);
break;
case 4:
aChild = new StringNode ("getCaretPosition: " + xText.getCaretPosition(), aParent);
break;
case 5:
aChild = textAtIndexNode( xText, "Character",
AccessibleTextType.CHARACTER,
aParent);
break;
case 6:
aChild = textAtIndexNode( xText, "Word",
AccessibleTextType.WORD,
aParent);
break;
case 7:
aChild = textAtIndexNode( xText, "Sentence",
AccessibleTextType.SENTENCE,
aParent);
break;
case 8:
aChild = textAtIndexNode( xText, "Paragraph",
AccessibleTextType.PARAGRAPH,
aParent);
break;
case 9:
aChild = textAtIndexNode( xText, "Line",
AccessibleTextType.LINE,
aParent);
break;
case 10:
aChild = textAtIndexNode( xText, "Attribute",
(short)6/*AccessibleTextType.ATTRIBUTE*/,
aParent);
break;
case 11:
aChild = new StringNode (bounds( xText ), aParent);
break;
case 12:
aChild = getAttributes( xText, aParent );
break;
default:
aChild = new StringNode ("unknown child index " + nIndex, aParent);
}
}
}
catch (Exception e)
{
// Return empty child.
}
return aChild;
}
private String textAtIndexNodeString(
int nStart, int nEnd,
String sWord, String sBefore, String sBehind)
{
return "[" + nStart + "," + nEnd + "] "
+ "\"" + sWord + "\" \t"
+ "(" + sBefore + ","
+ "" + sBehind + ")";
}
/** Create a text node that lists all strings of a particular text type
*/
private AccessibleTreeNode textAtIndexNode(
XAccessibleText xText,
String sName,
short nTextType,
AccessibleTreeNode aParent)
{
VectorNode aNode = new VectorNode (sName, aParent);
// get word at all positions;
// for nicer display, compare current word to previous one and
// make a new node for every interval, not for every word
int nLength = xText.getCharacterCount();
if( nLength > 0 )
{
try
{
// sWord + nStart mark the current word
// make a node as soon as a new one is found; close the last
// one at the end
String sWord = xText.getTextAtIndex(0, nTextType);
String sBefore = xText.getTextBeforeIndex(0, nTextType);
String sBehind = xText.getTextBehindIndex(0, nTextType);
int nStart = 0;
for(int i = 1; i < nLength; i++)
{
String sTmp = xText.getTextAtIndex(i, nTextType);
String sTBef = xText.getTextBeforeIndex(i, nTextType);
String sTBeh = xText.getTextBehindIndex(i, nTextType);
if( ! ( sTmp.equals( sWord ) && sTBef.equals( sBefore ) &&
sTBeh.equals( sBehind ) ) )
{
aNode.addChild (new StringNode (textAtIndexNodeString(
nStart, i, sWord, sBefore, sBehind), aNode));
sWord = sTmp;
sBefore = sTBef;
sBehind = sTBeh;
nStart = i;
}
// don't generate more than 50 children.
if (aNode.getChildCount() > 50)
{
sWord = "...";
break;
}
}
aNode.addChild (new StringNode (textAtIndexNodeString(
nStart, nLength, sWord, sBefore, sBehind), aNode));
}
catch( IndexOutOfBoundsException e )
{
aNode.addChild (new StringNode (e.toString(), aNode));
}
}
return aNode;
}
/** getCharacter (display as array string) */
private String characters(XAccessibleText xText)
{
// get count (max. 30)
int nChars = xText.getCharacterCount();
if( nChars > 30 )
nChars = 30;
// build up string
StringBuffer aChars = new StringBuffer();
try
{
aChars.append( "[" );
for( int i = 0; i < nChars; i++)
{
aChars.append( xText.getCharacter(i) );
aChars.append( "," );
}
if( nChars > 0)
{
if( nChars == xText.getCharacterCount() )
aChars.deleteCharAt( aChars.length() - 1 );
else
aChars.append( "..." );
}
aChars.append( "]" );
}
catch( IndexOutOfBoundsException e )
{
aChars.append( " ERROR " );
}
// return result
return "getCharacters: " + aChars;
}
/** iterate over characters, and translate their positions
* back and forth */
private String bounds( XAccessibleText xText )
{
StringBuffer aBuffer = new StringBuffer( "bounds: " );
try
{
// iterate over characters
int nCount = xText.getCharacterCount();
for(int i = 0; i < nCount; i++ )
{
// get bounds for this character
Rectangle aRect = xText.getCharacterBounds( i );
// get the character by 'clicking' into the middle of
// the bounds
Point aMiddle = new Point();
aMiddle.X = aRect.X + (aRect.Width / 2) - 1;
aMiddle.Y = aRect.Y + (aRect.Height / 2 ) - 1;
int nIndex = xText.getIndexAtPoint( aMiddle );
// get the character, or a '#' for an illegal index
if( (nIndex >= 0) && (nIndex < xText.getCharacter(i)) )
aBuffer.append( xText.getCharacter(nIndex) );
else
aBuffer.append( '#' );
}
}
catch( IndexOutOfBoundsException e )
{ ; } // ignore errors
return aBuffer.toString();
}
private AccessibleTreeNode getAttributes( XAccessibleText xText,
AccessibleTreeNode aParent)
{
AccessibleTreeNode aRet;
try
{
VectorNode aPortions = new VectorNode ("getAttributes", aParent);
int nIndex = 0;
int nLength = xText.getCharacterCount();
while( nIndex < nLength )
{
// get attribute run
String aPortion = xText.getTextAtIndex(
nIndex, (short)6/*AccessibleTextType.ATTRIBUTE*/ );
// get attributes and make node with attribute children
PropertyValue[] aValues = xText.getCharacterAttributes(nIndex);
VectorNode aAttrs = new VectorNode (aPortion, aPortions);
for( int i = 0; i < aValues.length; i++ )
{
new StringNode( aValues[i].Name + ": " + aValues[i].Value,
aAttrs );
}
// get next portion, but advance at least one
nIndex += (aPortion.length() > 0) ? aPortion.length() : 1;
}
aRet = aPortions;
}
catch( IndexOutOfBoundsException e )
{
aRet = new StringNode( "Exception caught:" + e, aParent );
}
return aRet;
}
static String[] aTextActions =
new String[] { "select...", "copy..." };
static String[] aEditableTextActions =
new String[] { "select...", "copy...",
"cut...", "paste...", "edit...", "format..." };
public String[] getActions (AccessibleTreeNode aNode)
{
XAccessibleEditableText xEText = null;
if (aNode instanceof AccTreeNode)
xEText = ((AccTreeNode)aNode).getEditText ();
return (xEText == null) ? aTextActions : aEditableTextActions;
}
public void performAction (AccessibleTreeNode aNode, int nIndex)
{
if ( ! (aNode instanceof AccTreeNode))
return;
AccTreeNode aATNode = (AccTreeNode)aNode;
TextActionDialog aDialog = null;
// create proper dialog
switch( nIndex )
{
case 0:
aDialog = new TextActionDialog( aATNode,
"Select range:",
"select" )
{
boolean action(
JTextComponent aText, AccTreeNode aNode )
throws IndexOutOfBoundsException
{
return aNode.getText().setSelection(
getSelectionStart(),
getSelectionEnd() );
}
};
break;
case 1:
aDialog = new TextActionDialog( aATNode,
"Select range and copy:",
"copy" )
{
boolean action(
JTextComponent aText, AccTreeNode aNode )
throws IndexOutOfBoundsException
{
return aNode.getText().copyText(
getSelectionStart(),
getSelectionEnd() );
}
};
break;
case 2:
aDialog = new TextActionDialog( aATNode,
"Select range and cut:",
"cut" )
{
boolean action(
JTextComponent aText, AccTreeNode aNode )
throws IndexOutOfBoundsException
{
return aNode.getEditText().cutText(
getSelectionStart(),
getSelectionEnd() );
}
};
break;
case 3:
aDialog = new TextActionDialog( aATNode,
"Place Caret and paste:",
"paste" )
{
boolean action(
JTextComponent aText, AccTreeNode aNode )
throws IndexOutOfBoundsException
{
return aNode.getEditText().pasteText(
aText.getCaretPosition() );
}
};
break;
case 4:
aDialog = new TextEditDialog( aATNode, "Edit text:",
"edit" );
break;
case 5:
aDialog = new TextAttributeDialog( aATNode );
break;
}
if( aDialog != null )
aDialog.show();
}
}
/**
* Display a dialog with a text field and a pair of cancel/do-it buttons
*/
class TextActionDialog extends JDialog
implements ActionListener
{
AccTreeNode aNode;
JTextArea aText;
String sName;
JCheckBox aIndexToggle;
public TextActionDialog( AccTreeNode aNd,
String sExplanation,
String sButtonText )
{
super( AccessibilityWorkBench.get() );
aNode = aNd;
sName = sButtonText;
init( sExplanation, aNode.getText().getText(), sButtonText );
// setSize( getPreferredSize() );
setSize( 350, 225 );
}
/** build dialog */
protected void init( String sExplanation,
String sText,
String sButtonText )
{
setTitle( sName );
// vertical stacking of the elements
Container aContent = getContentPane();
// aContent.setLayout( new BorderLayout() );
// label with explanation
if( sExplanation.length() > 0 )
aContent.add( new JLabel( sExplanation ), BorderLayout.NORTH );
// the text field
aText = new JTextArea();
aText.setText( sText );
aText.setColumns( Math.min( Math.max( 40, sText.length() ), 20 ) );
aText.setRows( sText.length() / 40 + 1 );
aText.setLineWrap( true );
aText.setEditable( false );
aContent.add( aText, BorderLayout.CENTER );
JPanel aButtons = new JPanel();
aButtons.setLayout( new FlowLayout() );
aIndexToggle = new JCheckBox( "reverse selection" );
aButtons.add( aIndexToggle );
JButton aActionButton = new JButton( sButtonText );
aActionButton.setActionCommand( "Action" );
aActionButton.addActionListener( this );
aButtons.add( aActionButton );
JButton aCancelButton = new JButton( "cancel" );
aCancelButton.setActionCommand( "Cancel" );
aCancelButton.addActionListener( this );
aButtons.add( aCancelButton );
// add Panel with buttons
aContent.add( aButtons, BorderLayout.SOUTH );
}
void cancel()
{
hide();
dispose();
}
void action()
{
String sError = null;
try
{
boolean bSuccess = action( aText, aNode );
if( !bSuccess )
sError = "Can't execute";
}
catch( IndexOutOfBoundsException e )
{
sError = "Index out of bounds";
}
if( sError != null )
JOptionPane.showMessageDialog( AccessibilityWorkBench.get(),
sError, sName,
JOptionPane.ERROR_MESSAGE);
cancel();
}
public void actionPerformed(ActionEvent e)
{
String sCommand = e.getActionCommand();
if( "Cancel".equals( sCommand ) )
cancel();
else if( "Action".equals( sCommand ) )
action();
}
int getSelectionStart() { return getSelection(true); }
int getSelectionEnd() { return getSelection(false); }
int getSelection(boolean bStart)
{
return ( bStart ^ aIndexToggle.isSelected() )
? aText.getSelectionStart() : aText.getSelectionEnd();
}
/** override this for dialog-specific action */
boolean action( JTextComponent aText, AccTreeNode aNode )
throws IndexOutOfBoundsException
{
return false;
}
}
class TextEditDialog extends TextActionDialog
{
public TextEditDialog( AccTreeNode aNode,
String sExplanation,
String sButtonText )
{
super( aNode, sExplanation, sButtonText );
}
protected void init( String sExplanation,
String sText,
String sButtonText )
{
super.init( sExplanation, sText, sButtonText );
aText.setEditable( true );
}
/** edit the text */
boolean action( JTextComponent aText, AccTreeNode aNode )
{
// is this text editable? if not, fudge you and return
XAccessibleEditableText xEdit = aNode.getEditText();
return ( xEdit == null ) ? false :
updateText( xEdit, aText.getText() );
}
/** update the text */
boolean updateText( XAccessibleEditableText xEdit, String sNew )
{
String sOld = xEdit.getText();
// false alarm? Early out if no change was done!
if( sOld.equals( sNew ) )
return false;
// get the minimum length of both strings
int nMinLength = sOld.length();
if( sNew.length() < nMinLength )
nMinLength = sNew.length();
// count equal characters from front and end
int nFront = 0;
while( (nFront < nMinLength) &&
(sNew.charAt(nFront) == sOld.charAt(nFront)) )
nFront++;
int nBack = 0;
while( (nBack < nMinLength) &&
( sNew.charAt(sNew.length()-nBack-1) ==
sOld.charAt(sOld.length()-nBack-1) ) )
nBack++;
if( nFront + nBack > nMinLength )
nBack = nMinLength - nFront;
// so... the first nFront and the last nBack characters
// are the same. Change the others!
String sDel = sOld.substring( nFront, sOld.length() - nBack );
String sIns = sNew.substring( nFront, sNew.length() - nBack );
System.out.println("edit text: " +
sOld.substring(0, nFront) +
" [ " + sDel + " -> " + sIns + " ] " +
sOld.substring(sOld.length() - nBack) );
boolean bRet = false;
try
{
// edit the text, and use
// (set|insert|delete|replace)Text as needed
if( nFront+nBack == 0 )
bRet = xEdit.setText( sIns );
else if( sDel.length() == 0 )
bRet = xEdit.insertText( sIns, nFront );
else if( sIns.length() == 0 )
bRet = xEdit.deleteText( nFront, sOld.length()-nBack );
else
bRet = xEdit.replaceText(nFront, sOld.length()-nBack,sIns);
}
catch( IndexOutOfBoundsException e )
{
bRet = false;
}
return bRet;
}
}
class TextAttributeDialog extends TextActionDialog
{
public TextAttributeDialog(
AccTreeNode aNode )
{
super( aNode, "Choose attributes, select text, and press 'Set':",
"set" );
}
private JCheckBox aBold, aUnderline, aItalics;
private Color aForeground, aBackground;
protected void init( String sExplanation,
String sText,
String sButtonText )
{
super.init( sExplanation, sText, sButtonText );
aForeground = Color.black;
aBackground = Color.white;
JPanel aAttr = new JPanel();
aAttr.setLayout( new BoxLayout( aAttr, BoxLayout.Y_AXIS ) );
aBold = new JCheckBox( "bold" );
aUnderline = new JCheckBox( "underline" );
aItalics = new JCheckBox( "italics" );
JButton aForeButton = new JButton("Foreground", new ColorIcon(true));
aForeButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e)
{
aForeground = JColorChooser.showDialog(
TextAttributeDialog.this,
"Select Foreground Color",
aForeground);
}
} );
JButton aBackButton = new JButton("Background", new ColorIcon(false));
aBackButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e)
{
aBackground = JColorChooser.showDialog(
TextAttributeDialog.this,
"Select Background Color",
aBackground);
}
} );
aAttr.add( aBold );
aAttr.add( aUnderline );
aAttr.add( aItalics );
aAttr.add( aForeButton );
aAttr.add( aBackButton );
getContentPane().add( aAttr, BorderLayout.WEST );
}
class ColorIcon implements Icon
{
boolean bForeground;
static final int nHeight = 16;
static final int nWidth = 16;
public ColorIcon(boolean bWhich) { bForeground = bWhich; }
public int getIconHeight() { return nHeight; }
public int getIconWidth() { return nWidth; }
public void paintIcon(Component c, Graphics g, int x, int y)
{
g.setColor( getColor() );
g.fillRect( x, y, nHeight, nWidth );
g.setColor( c.getForeground() );
g.drawRect( x, y, nHeight, nWidth );
}
Color getColor()
{
return bForeground ? aForeground : aBackground;
}
}
/** edit the text */
boolean action( JTextComponent aText, AccTreeNode aNode )
throws IndexOutOfBoundsException
{
// is this text editable? if not, fudge you and return
XAccessibleEditableText xEdit = aNode.getEditText();
boolean bSuccess = false;
if( xEdit != null )
{
PropertyValue[] aSequence = new PropertyValue[6];
aSequence[0] = new PropertyValue();
aSequence[0].Name = "CharWeight";
aSequence[0].Value = new Integer( aBold.isSelected() ? 150 : 100 );
aSequence[1] = new PropertyValue();
aSequence[1].Name = "CharUnderline";
aSequence[1].Value = new Integer( aUnderline.isSelected() ? 1 : 0 );
aSequence[2] = new PropertyValue();
aSequence[2].Name = "CharBackColor";
aSequence[2].Value = new Integer( aBackground.getRGB() );
aSequence[3] = new PropertyValue();
aSequence[3].Name = "CharColor";
aSequence[3].Value = new Integer( aForeground.getRGB() );
aSequence[4] = new PropertyValue();
aSequence[4].Name = "CharPosture";
aSequence[4].Value = new Integer( aItalics.isSelected() ? 1 : 0 );
aSequence[5] = new PropertyValue();
aSequence[5].Name = "CharBackTransparent";
aSequence[5].Value = new Boolean( false );
bSuccess = xEdit.setAttributes( getSelectionStart(),
getSelectionEnd(),
aSequence );
}
return bSuccess;
}
}
| added support for AccessibleTextType::GLYPH and ATTRIBUTE_RUN
| toolkit/test/accessibility/AccessibleTextHandler.java | added support for AccessibleTextType::GLYPH and ATTRIBUTE_RUN |
|
Java | agpl-3.0 | 6b01cb80da4541563c2c845c9f266f2fc6d76e79 | 0 | edbaskerville/mc3kit,edbaskerville/mc3kit | /***
This file is part of mc3kit.
Copyright (C) 2013 Edward B. Baskerville
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
package mc3kit.distributions;
import static java.lang.Math.log;
import cern.jet.random.Exponential;
import mc3kit.*;
import mc3kit.proposal.*;
@SuppressWarnings("serial")
public class ExponentialDistribution extends DoubleDistribution {
double rate;
ModelEdge rateEdge;
ModelEdge scaleEdge;
protected ExponentialDistribution() { }
public ExponentialDistribution(Model model) {
this(model, null);
}
public ExponentialDistribution(Model model, String name) {
this(model, name, 1.0);
}
public ExponentialDistribution(Model model, double rate) {
this(model, null, rate);
}
public ExponentialDistribution(Model model, String name, double rate) {
super(model, name);
this.rate = rate;
}
@Override
public VariableProposer makeVariableProposer(String varName) {
return new MHMultiplierProposer(varName);
}
public <T extends ModelNode & DoubleValued> void setRate(T rateNode) throws MC3KitException {
scaleEdge = updateEdge(scaleEdge, null);
rateEdge = updateEdge(rateEdge, rateNode);
}
public <T extends ModelNode & DoubleValued> void setScale(T scaleNode) throws MC3KitException {
rateEdge = updateEdge(rateEdge, null);
scaleEdge = updateEdge(scaleEdge, scaleNode);
}
@Override
public double getLogP(Variable v) {
double x = ((DoubleVariable)v).getValue();
if(scaleEdge != null) {
assert rateEdge == null;
return getLogPScale(x, getDoubleValue(scaleEdge));
}
else {
assert scaleEdge == null;
return getLogPRate(x, rateEdge == null ? rate : getDoubleValue(rateEdge));
}
}
public static double getLogPRate(double x, double rate) {
assert x > 0;
assert rate > 0;
return log(rate) - rate * x;
}
public static double getLogPScale(double x, double scale) {
assert x > 0;
assert scale > 0;
return -log(scale) - x / scale;
}
@Override
public boolean valueIsValid(double val) {
if(Double.isInfinite(val) || Double.isNaN(val) || val <= 0.0) {
return false;
}
return true;
}
@Override
public void sample(Variable var) {
double rate;
if(rateEdge != null) {
rate = getDoubleValue(rateEdge);
}
else if(scaleEdge != null) {
rate = 1.0 / getDoubleValue(scaleEdge);
}
else {
rate = this.rate;
}
double newVal = new Exponential(rate, getRng()).nextDouble();
assert !Double.isNaN(newVal);
assert !Double.isInfinite(newVal);
assert newVal > 0.0;
((DoubleVariable)var).setValue(newVal);
}
}
| src/mc3kit/distributions/ExponentialDistribution.java | /***
This file is part of mc3kit.
Copyright (C) 2013 Edward B. Baskerville
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***/
package mc3kit.distributions;
import static java.lang.Math.log;
import cern.jet.random.Exponential;
import mc3kit.*;
import mc3kit.proposal.*;
@SuppressWarnings("serial")
public class ExponentialDistribution extends DoubleDistribution {
double rate;
ModelEdge rateEdge;
ModelEdge scaleEdge;
protected ExponentialDistribution() { }
public ExponentialDistribution(Model model) {
this(model, null);
}
public ExponentialDistribution(Model model, String name) {
this(model, name, 1.0);
}
public ExponentialDistribution(Model model, double rate) {
this(model, null, rate);
}
public ExponentialDistribution(Model model, String name, double rate) {
super(model, name);
this.rate = rate;
}
@Override
public VariableProposer makeVariableProposer(String varName) {
return new MHMultiplierProposer(varName);
}
public <T extends ModelNode & DoubleValued> void setRate(T rateNode) throws MC3KitException {
scaleEdge = updateEdge(scaleEdge, null);
rateEdge = updateEdge(rateEdge, rateNode);
}
public <T extends ModelNode & DoubleValued> void setScale(T scaleNode) throws MC3KitException {
rateEdge = updateEdge(rateEdge, null);
scaleEdge = updateEdge(scaleEdge, scaleNode);
}
@Override
public double getLogP(Variable v) {
double x = ((DoubleVariable)v).getValue();
if(scaleEdge != null) {
assert rateEdge == null;
return getLogPScale(x, getDoubleValue(scaleEdge));
}
else {
assert scaleEdge == null;
return getLogPRate(x, rateEdge == null ? rate : getDoubleValue(rateEdge));
}
}
public static double getLogPRate(double x, double rate) {
assert x > 0;
assert rate > 0;
return log(rate) - rate * x;
}
public static double getLogPScale(double x, double scale) {
assert x > 0;
assert scale > 0;
return -log(scale) - x / scale;
}
@Override
public boolean valueIsValid(double val) {
if(Double.isInfinite(val) || Double.isNaN(val) || val <= 0.0) {
return false;
}
return true;
}
@Override
public void sample(Variable var) {
double rate;
if(rateEdge != null) {
rate = getDoubleValue(rateEdge);
}
else if(scaleEdge != null) {
rate = 1.0 / getDoubleValue(scaleEdge);
}
else {
rate = 1.0;
}
double newVal = new Exponential(rate, getRng()).nextDouble();
assert !Double.isNaN(newVal);
assert !Double.isInfinite(newVal);
assert newVal > 0.0;
((DoubleVariable)var).setValue(newVal);
}
}
| Exponential was using 1.0 instead of user-set fixed rate; fixed. | src/mc3kit/distributions/ExponentialDistribution.java | Exponential was using 1.0 instead of user-set fixed rate; fixed. |
|
Java | agpl-3.0 | 1c379e47941bf1cd1e0d50c4c387017261d365f7 | 0 | bio4j/bio4j | /*
# ENZYME
This graph includes all Enzyme terms that are included in the ExPASy ENZYME database but **not** those that have been either _transferred_ or _deleted_.
You can get more information about the Enzyme database from its [website](http://enzyme.expasy.org/), in particular
- **[Enzyme description and sample entry](http://enzyme.expasy.org/enzyme_details.html)**
- the **[User manual](http://enzyme.expasy.org/enzuser.txt)**, which contains a more precise description of the data model
The main entity here are `Enzyme`s, which are categorized into a hierarchy of classes. There are other graphs which add edges between `Enzyme`s and other entitities such as proteins.
*/
package com.bio4j.model;
import com.bio4j.angulillos.*;
import com.bio4j.angulillos.Arity.*;
public final class ENZYMEGraph<V,E> extends TypedGraph<ENZYMEGraph<V,E>,V,E> {
public ENZYMEGraph(UntypedGraph<V,E> graph) { super(graph); }
@Override
public final ENZYMEGraph<V,E> self() { return this; }
/*
## Enzymes
*/
public final class Enzyme extends Vertex<Enzyme> {
private Enzyme(V raw) { super(raw, enzyme); }
@Override public final Enzyme self() { return this; }
}
public final EnzymeType enzyme = new EnzymeType();
public final class EnzymeType extends VertexType<Enzyme> {
public final Enzyme fromRaw(V raw) { return new Enzyme(raw); }
/*
### ID
The ENZYME ID of this enzyme, as a `String`. This property is indexed for unique matches.
*/
public final ID id = new ID();
public final class ID extends Property<String> implements FromAtMostOne, ToOne {
private ID() { super(String.class); }
public final Index index = new Index();
public final class Index extends UniqueIndex<ID,String> {
private Index() { super(id); }
}
}
/*
### Cofactors
The cofactors for this enzyme, stored in an array of `String`s.
*/
public final Cofactors cofactors = new Cofactors();
public final class Cofactors extends Property<String[]> implements FromAny {
private Cofactors() { super(String[].class); }
}
/*
### Comments
Enzymes have sometimes text comments; this property will have them as value, stored in a `String` array.
*/
public final Comments comments = new Comments();
public final class Comments extends Property<String[]> implements FromAny {
private Comments() { super(String[].class); }
}
/*
### Name
The (official) name of this enzyme.
*/
public final Name name = new Name();
public final class Name extends Property<String> implements FromAny, ToOne {
private Name() { super(String.class); }
}
/*
### Alternate names
Sometimes enzymes have alternate names; they are available here as an array of `String`s.
*/
public final AlternateNames alternateNames = new AlternateNames();
public final class AlternateNames extends Property<String[]> implements FromAny {
private AlternateNames() { super(String[].class); }
}
/*
### Catalytic activity
Reactions in which this enzyme takes part, described textually.
*/
public final CatalyticActivity catalyticActivity = new CatalyticActivity();
public final class CatalyticActivity extends Property<String[]> implements FromAny {
private CatalyticActivity() { super(String[].class); }
}
}
/*
## Enzyme classes, sub-classes, subsub-classes
Classes are a set of sub-classes, who are a set of subsub-classes, who are a set of enzymes.
They are defined in [enzclass.txt](ftp://ftp.expasy.org/databases/enzyme/enzclass.txt) from the ENZYME ftp.
*/
public final class EnzymeClass extends Vertex<EnzymeClass> {
private EnzymeClass(V raw) { super(raw, enzymeClass); }
@Override public final EnzymeClass self() { return this; }
}
public final EnzymeClassType enzymeClass = new EnzymeClassType();
public final class EnzymeClassType extends VertexType<EnzymeClass> {
public final EnzymeClass fromRaw(V raw) { return new EnzymeClass(raw); }
public final ID id = new ID();
public final class ID extends Property<String> implements FromAtMostOne, ToOne {
private ID() { super(String.class); }
public final Index index = new Index();
public final class Index extends UniqueIndex<ID,String> {
private Index() { super(id); }
}
}
}
public final class EnzymeSubClass extends Vertex<EnzymeSubClass> {
private EnzymeSubClass(V raw) { super(raw, enzymeSubClass); }
@Override public final EnzymeSubClass self() { return this; }
}
public final EnzymeSubClassType enzymeSubClass = new EnzymeSubClassType();
public final class EnzymeSubClassType extends VertexType<EnzymeSubClass> {
public final EnzymeSubClass fromRaw(V raw) { return new EnzymeSubClass(raw); }
public final ID id = new ID();
public final class ID extends Property<String> implements FromAtMostOne, ToOne {
private ID() { super(String.class); }
public final Index index = new Index();
public final class Index extends UniqueIndex<ID,String> {
private Index() { super(id); }
}
}
}
public final class EnzymeSubSubClass extends Vertex<EnzymeSubSubClass> {
private EnzymeSubSubClass(V raw) { super(raw, enzymeSubSubClass); }
@Override public final EnzymeSubSubClass self() { return this; }
}
public final EnzymeSubSubClassType enzymeSubSubClass = new EnzymeSubSubClassType();
public final class EnzymeSubSubClassType extends VertexType<EnzymeSubSubClass> {
public final EnzymeSubSubClass fromRaw(V raw) { return new EnzymeSubSubClass(raw); }
public final ID id = new ID();
public final class ID extends Property<String> implements FromAtMostOne, ToOne {
private ID() { super(String.class); }
public final Index index = new Index();
public final class Index extends UniqueIndex<ID,String> {
private Index() { super(id); }
}
}
}
/*
### Sub-class, subsub-class edges
These edges go from an element to its members. The Enzyme ID structure `w.x.y.z` mirrors this structure, where each prefix ending in a dot determines one of these categories. Going up in this hierarchy corresponds to a less specific function. Note that annotations coming from other databases such as UniProt frequently point to enzyme classes, not enzymes themselves.
*/
public final class SubClasses extends Edge<EnzymeClass, SubClasses, EnzymeSubClass> {
private SubClasses(E edge) { super(edge, subClasses); }
@Override
public final SubClasses self() { return this; }
}
public final SubClassesType subClasses = new SubClassesType();
public final class SubClassesType extends EdgeType<EnzymeClass, SubClasses, EnzymeSubClass> implements FromOne, ToAtLeastOne {
private SubClassesType() { super(enzymeClass, enzymeSubClass); }
@Override
public final SubClasses fromRaw(E edge) { return new SubClasses(edge); }
}
public final class SubSubClasses extends Edge<EnzymeSubClass, SubSubClasses, EnzymeSubSubClass> {
private SubSubClasses(E edge) { super(edge, subSubClasses); }
@Override
public final SubSubClasses self() { return this; }
}
public final SubSubClassesType subSubClasses = new SubSubClassesType();
public final class SubSubClassesType extends EdgeType<EnzymeSubClass, SubSubClasses, EnzymeSubSubClass> implements FromOne, ToAtLeastOne {
private SubSubClassesType() { super(enzymeSubClass, enzymeSubSubClass); }
@Override
public final SubSubClasses fromRaw(E edge) { return new SubSubClasses(edge); }
}
public final class Enzymes extends Edge<EnzymeSubSubClass, Enzymes, Enzyme> {
private Enzymes(E edge) { super(edge, enzymes); }
@Override
public final Enzymes self() { return this; }
}
public final EnzymesType enzymes = new EnzymesType();
public final class EnzymesType extends EdgeType<EnzymeSubSubClass, Enzymes, Enzyme> implements FromOne, ToAtLeastOne {
private EnzymesType() { super(enzymeSubSubClass, enzyme); }
@Override
public final Enzymes fromRaw(E edge) { return new Enzymes(edge); }
}
}
| src/main/java/com/bio4j/model/ENZYMEGraph.java | /*
# ENZYME
This graph includes all Enzyme terms that are included in the ExPASy ENZYME database but **not** those that have been either _transferred_ or _deleted_.
You can get more information about the Enzyme database from its [website](http://enzyme.expasy.org/), in particular
- **[Enzyme description and sample entry](http://enzyme.expasy.org/enzyme_details.html)**
- the **[User manual](http://enzyme.expasy.org/enzuser.txt)**, which contains a more precise description of the data model
The main entity here are `Enzyme`s, which are categorized into a hierarchy of classes. There are other graphs which add edges between `Enzyme`s and other entitities such as proteins.
*/
package com.bio4j.model;
import com.bio4j.angulillos.*;
import com.bio4j.angulillos.Arity.*;
public final class ENZYMEGraph<V,E> extends TypedGraph<ENZYMEGraph<V,E>,V,E> {
public ENZYMEGraph(UntypedGraph<V,E> graph) { super(graph); }
@Override
public final ENZYMEGraph<V,E> self() { return this; }
/*
## Enzymes
*/
public final class Enzyme extends Vertex<Enzyme> {
private Enzyme(V raw) { super(raw, enzyme); }
@Override public final Enzyme self() { return this; }
}
public final EnzymeType enzyme = new EnzymeType();
public final class EnzymeType extends VertexType<Enzyme> {
public final Enzyme fromRaw(V raw) { return new Enzyme(raw); }
/*
### ID
The ENZYME ID of this enzyme, as a `String`. This property is indexed for unique matches.
*/
public final ID id = new ID();
public final class ID extends Property<String> implements FromAtMostOne, ToOne {
private ID() { super(String.class); }
public final Index index = new Index();
public final class Index extends UniqueIndex<ID,String> {
private Index() { super(id); }
}
}
/*
### Cofactors
The cofactors for this enzyme, stored in an array of `String`s.
*/
public final Cofactors cofactors = new Cofactors();
public final class Cofactors extends Property<String[]> implements FromAny {
private Cofactors() { super(String[].class); }
}
/*
### Comments
Enzymes have sometimes text comments; this property will have them as value, stored in a `String` array.
*/
public final Comments comments = new Comments();
public final class Comments extends Property<String[]> implements FromAny {
private Comments() { super(String[].class); }
}
/*
### Name
The (official) name of this enzyme.
*/
public final Name name = new Name();
public final class Name extends Property<String> implements FromAny, ToOne {
private Name() { super(String.class); }
}
/*
### Alternate names
Sometimes enzymes have alternate names; they are available here as an array of `String`s.
*/
public final AlternateNames alternateNames = new AlternateNames();
public final class AlternateNames extends Property<String[]> implements FromAny {
private AlternateNames() { super(String[].class); }
}
/*
### Catalytic activity
Reactions in which this enzyme takes part, described textually.
*/
public final CatalyticActivity catalyticActivity = new CatalyticActivity();
public final class CatalyticActivity extends Property<String[]> implements FromAny {
private CatalyticActivity() { super(String[].class); }
}
}
/*
## Enzyme classes, sub-classes, subsub-classes
Classes are a set of sub-classes, who are a set of subsub-classes, who are a set of enzymes.
They are defined in [enzclass.txt](ftp://ftp.expasy.org/databases/enzyme/enzclass.txt) from the ENZYME ftp.
*/
public final class EnzymeClass extends Vertex<EnzymeClass> {
private EnzymeClass(V raw) { super(raw, enzymeClass); }
@Override public final EnzymeClass self() { return this; }
}
public final EnzymeClassType enzymeClass = new EnzymeClassType();
public final class EnzymeClassType extends VertexType<EnzymeClass> {
public final EnzymeClass fromRaw(V raw) { return new EnzymeClass(raw); }
public final ID id = new ID();
public final class ID extends Property<String> implements FromAtMostOne, ToOne {
private ID() { super(String.class); }
public final Index index = new Index();
public final class Index extends UniqueIndex<ID,String> {
private Index() { super(id); }
}
}
}
public final class EnzymeSubClass extends Vertex<EnzymeSubClass> {
private EnzymeSubClass(V raw) { super(raw, enzymeSubClass); }
@Override public final EnzymeSubClass self() { return this; }
}
public final EnzymeSubClassType enzymeSubClass = new EnzymeSubClassType();
public final class EnzymeSubClassType extends VertexType<EnzymeSubClass> {
public final EnzymeSubClass fromRaw(V raw) { return new EnzymeSubClass(raw); }
public final ID id = new ID();
public final class ID extends Property<String> implements FromAtMostOne, ToOne {
private ID() { super(String.class); }
public final Index index = new Index();
public final class Index extends UniqueIndex<ID,String> {
private Index() { super(id); }
}
}
}
public final class EnzymeSubSubClass extends Vertex<EnzymeSubSubClass> {
private EnzymeSubSubClass(V raw) { super(raw, enzymeSubSubClass); }
@Override public final EnzymeSubSubClass self() { return this; }
}
public final EnzymeSubSubClassType enzymeSubSubClass = new EnzymeSubSubClassType();
public final class EnzymeSubSubClassType extends VertexType<EnzymeSubSubClass> {
public final EnzymeSubSubClass fromRaw(V raw) { return new EnzymeSubSubClass(raw); }
public final ID id = new ID();
public final class ID extends Property<String> implements FromAtMostOne, ToOne {
private ID() { super(String.class); }
public final Index index = new Index();
public final class Index extends UniqueIndex<ID,String> {
private Index() { super(id); }
}
}
}
/*
### Sub-class, subsub-class edges
These edges go from an element to its members. The Enzyme ID structure `w.x.y.z` mirrors this structure, where each prefix ending in a dot determines one of these categories. Going up in this hierarchy corresponds to a less specific function. Note that annotations coming from other databases such as UniProt frequently point to enzyme classes, not enzymes themselves.
*/
public final class SubClass extends Edge<EnzymeClass, SubClass, EnzymeSubClass> {
private SubClass(E edge) { super(edge, subClass); }
@Override
public final SubClass self() { return this; }
}
public final SubClassType subClass = new SubClassType();
public final class SubClassType extends EdgeType<EnzymeClass, SubClass, EnzymeSubClass> implements FromOne, ToAtLeastOne {
private SubClassType() { super(enzymeClass, enzymeSubClass); }
@Override
public final SubClass fromRaw(E edge) { return new SubClass(edge); }
}
public final class SubSubClass extends Edge<EnzymeSubClass, SubSubClass, EnzymeSubSubClass> {
private SubSubClass(E edge) { super(edge, subSubClass); }
@Override
public final SubSubClass self() { return this; }
}
public final SubSubClassType subSubClass = new SubSubClassType();
public final class SubSubClassType extends EdgeType<EnzymeSubClass, SubSubClass, EnzymeSubSubClass> implements FromOne, ToAtLeastOne {
private SubSubClassType() { super(enzymeSubClass, enzymeSubSubClass); }
@Override
public final SubSubClass fromRaw(E edge) { return new SubSubClass(edge); }
}
public final class Enzymes extends Edge<EnzymeSubSubClass, Enzymes, Enzyme> {
private Enzymes(E edge) { super(edge, enzymes); }
@Override
public final Enzymes self() { return this; }
}
public final EnzymesType enzymes = new EnzymesType();
public final class EnzymesType extends EdgeType<EnzymeSubSubClass, Enzymes, Enzyme> implements FromOne, ToAtLeastOne {
private EnzymesType() { super(enzymeSubSubClass, enzyme); }
@Override
public final Enzymes fromRaw(E edge) { return new Enzymes(edge); }
}
}
| make edges for Enzyme subclasses have plural name
| src/main/java/com/bio4j/model/ENZYMEGraph.java | make edges for Enzyme subclasses have plural name |
|
Java | agpl-3.0 | de4efa7767643fc37dbaeb818c5fa48f9005c1ba | 0 | quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials | /*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2016 The Kuali Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.sys.datatools.exportdata;
import org.kuali.kfs.sys.datatools.util.PropertyLoadingFactoryBean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.sql.DataSource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Exports a database schema in a format suitable for phase 2 of demo database creation.
*
* Usage: java -cp path_to_kfs/WEB-INF/lib/*:path_to_jdbc_connector.jar -Dadditional.kfs.config.locations=path_to_config.properties org.kuali.kfs.sys.datatools.exportdata.ExportData
*
* On Windows, the classpath separator is a semicolon, rather than a colon.
*
*/
public class ExportData {
private String rootDirectory;
private String schema;
private List<String> skipTableExpressions;
private Map<Integer, String> typeNames;
private ClassPathXmlApplicationContext applicationContext;
private SimpleDateFormat dateFormat;
public static final String DATE_FORMAT = "YYYYMMddHHmmssSSSS";
public static final String DELIMITER = "~&~\t~&~";
public static final String QUOTE = "'";
public static final String HEADER_BEGIN = "HEADER[";
public static final String HEADER_END = "]HEADER";
public static final String RECORD_BEGIN = "RECORD[";
public static final String RECORD_END = "]RECORD";
public static final String COLUMN_SEPARATOR = "::";
private static final String LIQUIBASE_BEGIN= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<!--\n"
+ " - The Kuali Financial System, a comprehensive financial management system for higher education.\n"
+ " - \n"
+ " - Copyright 2005-2016 The Kuali Foundation\n"
+ " - \n"
+ " - This program is free software: you can redistribute it and/or modify\n"
+ " - it under the terms of the GNU Affero General Public License as\n"
+ " - published by the Free Software Foundation, either version 3 of the\n"
+ " - License, or (at your option) any later version.\n"
+ " - \n"
+ " - This program is distributed in the hope that it will be useful,\n"
+ " - but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
+ " - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
+ " - GNU Affero General Public License for more details.\n"
+ " - \n"
+ " - You should have received a copy of the GNU Affero General Public License\n"
+ " - along with this program. If not, see <http://www.gnu.org/licenses/>.\n"
+ " -->\n"
+ "<databaseChangeLog xmlns=\"http://www.liquibase.org/xml/ns/dbchangelog\" xmlns:ext=\"http://www.liquibase.org/xml/ns/dbchangelog-ext\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd\">\n";
private static final String LIQUIBASE_END = "</databaseChangeLog>\n";
public static final void main(String[] args) throws IOException {
ExportData c = new ExportData();
long startTime = System.nanoTime();
c.go();
long estimatedTime = System.nanoTime() - startTime;
System.out.printf("\nTime run: %d seconds\n", estimatedTime / 1000 / 1000 / 1000);
}
public void go() throws IOException {
dateFormat = new SimpleDateFormat(DATE_FORMAT);
initialize();
DataSource kfsDataSource = applicationContext.getBean("dataSource", DataSource.class);
try (Connection con = kfsDataSource.getConnection()) {
List<String> tableNames = getTableNames(con);
for (String table : tableNames) {
extractTable(con, table, rootDirectory);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
/**
* Creates a single data file, corresponding to a single database table.
*
* @param con
* @param table
* @param root
* @throws Exception
*/
private void extractTable(Connection con,String table,String root) throws Exception {
System.out.println(table);
try (PreparedStatement ps = con.prepareStatement("select * from " + table)) {
try (ResultSet rs = ps.executeQuery()) {
if (!rs.isBeforeFirst()) {
// Empty rowset; don't create files
return;
}
// Create Liquibase file
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(root + table + ".xml")))) {
out.print(LIQUIBASE_BEGIN);
out.print(" <changeSet id=\"IMPORT_" + table + "\" author=\"kfs\" context=\"demo,unit\">\n");
out.print(" <customChange class=\"org.kuali.kfs.sys.datatools.util.TableDataLoader\">\n");
out.print(" <param name=\"table\" value=\"" + table + "\"/>\n");
out.print(" <param name=\"file\" value=\"org/kuali/kfs/core/db/phase2/" + table + ".dat\" />\n");
out.print(" </customChange>\n");
out.print(" </changeSet>\n");
out.print(LIQUIBASE_END);
}
// Create data file
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(root + table + ".dat")))) {
// Print column list for header
ResultSetMetaData rsmd = rs.getMetaData();
out.print(HEADER_BEGIN + DELIMITER);
for ( int i = 1; i <= rsmd.getColumnCount(); i++ ) {
String typeName = typeNames.get(rsmd.getColumnType(i));
if (typeName == null) {
throw new RuntimeException("Unknown JDBC type: " + i);
}
out.print(rsmd.getColumnName(i) + COLUMN_SEPARATOR + typeName + DELIMITER);
}
out.print(HEADER_END + "\n");
// Loop through records
while (rs.next()) {
out.print(RECORD_BEGIN + DELIMITER);
for ( int i = 1; i <= rsmd.getColumnCount(); i++ ) {
out.print(columnData(rsmd,rs,i) + DELIMITER);
}
out.print(RECORD_END + "\n");
}
}
}
}
}
/**
* Formats a column's value.
*
* @param rsmd
* @param rs
* @param i
* @return
* @throws SQLException
*/
private String columnData(ResultSetMetaData rsmd,ResultSet rs,int i) throws SQLException {
String value = rs.getString(i);
int columnType = rsmd.getColumnType(i);
if (value != null) {
switch (columnType) {
case Types.BLOB:
Blob blob = rs.getBlob(i);
if (blob != null) {
byte[] bytes = blob.getBytes(1, (int) blob.length());
value = Base64.getEncoder().encodeToString(bytes);
}
break;
case Types.DATE:
value = dateFormat.format(rs.getDate(i));
break;
case Types.TIMESTAMP:
value = dateFormat.format(rs.getTimestamp(i));
break;
}
return QUOTE + value + QUOTE;
} else {
return "NULL";
}
}
/**
* Gets the list of tables to export.
*
* @param con
* @return
* @throws SQLException
*/
private List<String> getTableNames(Connection con) throws SQLException {
List<String> tableNames = new ArrayList<>();
try (ResultSet rs = con.getMetaData().getTables(null, schema, "%", new String[]{ "TABLE" })) {
while (rs.next()) {
String table = rs.getString(3);
if ( ! skipTable(table) ) {
tableNames.add(table);
} else {
System.out.println("Skipping " + table);
}
}
}
return tableNames;
}
/**
* Determines whether a table is in the exclusion list.
*
* @param table
* @return
*/
private boolean skipTable(String table) {
for (String expression : skipTableExpressions) {
if ( table.matches(expression) ) {
return true;
}
}
return false;
}
private void initialize() {
applicationContext = new ClassPathXmlApplicationContext("org/kuali/kfs/sys/datatools/liquirelational/kfs-liqui-relational-bootstrap.xml");
applicationContext.start();
readProperties();
loadTypeNames();
}
private void readProperties() {
rootDirectory = PropertyLoadingFactoryBean.getBaseProperty("export.rootDirectory");
if (!rootDirectory.endsWith(File.separator)) {
rootDirectory += File.separator;
}
schema = PropertyLoadingFactoryBean.getBaseProperty("export.schema");
String skipTables = PropertyLoadingFactoryBean.getBaseProperty("export.skip");
if (skipTables != null) {
skipTableExpressions = Arrays.asList(skipTables.split(";"));
} else {
skipTableExpressions = new ArrayList<String>();
}
}
/**
* For convenience, loads a map to turn JDBC column type values into their names.
*/
private void loadTypeNames() {
typeNames = new HashMap<Integer, String>();
for (Field field : Types.class.getFields()) {
try {
typeNames.put((Integer)field.get(null), field.getName());
} catch (IllegalArgumentException | IllegalAccessException e) { }
}
}
}
| kfs-datatools/src/main/java/org/kuali/kfs/sys/datatools/exportdata/ExportData.java | /*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2016 The Kuali Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.sys.datatools.exportdata;
import org.kuali.kfs.sys.datatools.util.PropertyLoadingFactoryBean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.sql.DataSource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Exports a database schema in a format suitable for phase 2 of demo database creation.
*
* Usage: java -cp path_to_kfs/WEB-INF/lib/*:path_to_jdbc_connector.jar -Dadditional.kfs.config.locations=path_to_config.properties org.kuali.kfs.sys.datatools.exportdata.ExportData
*
* On Windows, the classpath separator is a semicolon, rather than a colon.
*
*/
public class ExportData {
private String rootDirectory;
private String schema;
private List<String> skipTableExpressions;
private Map<Integer, String> typeNames;
private ClassPathXmlApplicationContext applicationContext;
public static final String DELIMITER = "~&~\t~&~";
public static final String QUOTE = "'";
public static final String HEADER_BEGIN = "HEADER[";
public static final String HEADER_END = "]HEADER";
public static final String RECORD_BEGIN = "RECORD[";
public static final String RECORD_END = "]RECORD";
public static final String COLUMN_SEPARATOR = "::";
private static final String LIQUIBASE_BEGIN= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<!--\n"
+ " - The Kuali Financial System, a comprehensive financial management system for higher education.\n"
+ " - \n"
+ " - Copyright 2005-2016 The Kuali Foundation\n"
+ " - \n"
+ " - This program is free software: you can redistribute it and/or modify\n"
+ " - it under the terms of the GNU Affero General Public License as\n"
+ " - published by the Free Software Foundation, either version 3 of the\n"
+ " - License, or (at your option) any later version.\n"
+ " - \n"
+ " - This program is distributed in the hope that it will be useful,\n"
+ " - but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
+ " - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
+ " - GNU Affero General Public License for more details.\n"
+ " - \n"
+ " - You should have received a copy of the GNU Affero General Public License\n"
+ " - along with this program. If not, see <http://www.gnu.org/licenses/>.\n"
+ " -->\n"
+ "<databaseChangeLog xmlns=\"http://www.liquibase.org/xml/ns/dbchangelog\" xmlns:ext=\"http://www.liquibase.org/xml/ns/dbchangelog-ext\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd\">\n";
private static final String LIQUIBASE_END = "</databaseChangeLog>\n";
public static final void main(String[] args) throws IOException {
ExportData c = new ExportData();
long startTime = System.nanoTime();
c.go();
long estimatedTime = System.nanoTime() - startTime;
System.out.printf("\nTime run: %d seconds\n", estimatedTime / 1000 / 1000 / 1000);
}
public void go() throws IOException {
initialize();
DataSource kfsDataSource = applicationContext.getBean("dataSource", DataSource.class);
try (Connection con = kfsDataSource.getConnection()) {
List<String> tableNames = getTableNames(con);
for (String table : tableNames) {
extractTable(con, table, rootDirectory);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
/**
* Creates a single data file, corresponding to a single database table.
*
* @param con
* @param table
* @param root
* @throws Exception
*/
private void extractTable(Connection con,String table,String root) throws Exception {
System.out.println(table);
try (PreparedStatement ps = con.prepareStatement("select * from " + table)) {
try (ResultSet rs = ps.executeQuery()) {
if (!rs.isBeforeFirst()) {
// Empty rowset; don't create files
return;
}
// Create Liquibase file
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(root + table + ".xml")))) {
out.print(LIQUIBASE_BEGIN);
out.print(" <changeSet id=\"IMPORT_" + table + "\" author=\"kfs\" context=\"demo,unit\">\n");
out.print(" <customChange class=\"org.kuali.kfs.sys.datatools.util.TableDataLoader\">\n");
out.print(" <param name=\"table\" value=\"" + table + "\"/>\n");
out.print(" <param name=\"file\" value=\"org/kuali/kfs/core/db/phase2/" + table + ".dat\" />\n");
out.print(" </customChange>\n");
out.print(" </changeSet>\n");
out.print(LIQUIBASE_END);
}
// Create data file
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(root + table + ".dat")))) {
// Print column list for header
ResultSetMetaData rsmd = rs.getMetaData();
out.print(HEADER_BEGIN + DELIMITER);
for ( int i = 1; i <= rsmd.getColumnCount(); i++ ) {
String typeName = typeNames.get(rsmd.getColumnType(i));
if (typeName == null) {
throw new RuntimeException("Unknown JDBC type: " + i);
}
out.print(rsmd.getColumnName(i) + COLUMN_SEPARATOR + typeName + DELIMITER);
}
out.print(HEADER_END + "\n");
// Loop through records
while (rs.next()) {
out.print(RECORD_BEGIN + DELIMITER);
for ( int i = 1; i <= rsmd.getColumnCount(); i++ ) {
out.print(columnData(rsmd,rs,i) + DELIMITER);
}
out.print(RECORD_END + "\n");
}
}
}
}
}
/**
* Formats a column's value.
*
* @param rsmd
* @param rs
* @param i
* @return
* @throws SQLException
*/
private String columnData(ResultSetMetaData rsmd,ResultSet rs,int i) throws SQLException {
String value = rs.getString(i);
int columnType = rsmd.getColumnType(i);
if (value != null) {
switch (columnType) {
case Types.BLOB:
Blob blob = rs.getBlob(i);
if (blob != null) {
byte[] bytes = blob.getBytes(1, (int) blob.length());
value = Base64.getEncoder().encodeToString(bytes);
}
break;
case Types.DATE:
value = Long.toString(rs.getDate(i).getTime());
break;
case Types.TIMESTAMP:
value = Long.toString(rs.getTimestamp(i).getTime());
break;
case Types.TIME:
value = Long.toString(rs.getTime(i).getTime());
}
return QUOTE + value + QUOTE;
} else {
return "NULL";
}
}
/**
* Gets the list of tables to export.
*
* @param con
* @return
* @throws SQLException
*/
private List<String> getTableNames(Connection con) throws SQLException {
List<String> tableNames = new ArrayList<>();
try (ResultSet rs = con.getMetaData().getTables(null, schema, "%", new String[]{ "TABLE" })) {
while (rs.next()) {
String table = rs.getString(3);
if ( ! skipTable(table) ) {
tableNames.add(table);
} else {
System.out.println("Skipping " + table);
}
}
}
return tableNames;
}
/**
* Determines whether a table is in the exclusion list.
*
* @param table
* @return
*/
private boolean skipTable(String table) {
for (String expression : skipTableExpressions) {
if ( table.matches(expression) ) {
return true;
}
}
return false;
}
private void initialize() {
applicationContext = new ClassPathXmlApplicationContext("org/kuali/kfs/sys/datatools/liquirelational/kfs-liqui-relational-bootstrap.xml");
applicationContext.start();
readProperties();
loadTypeNames();
}
private void readProperties() {
rootDirectory = PropertyLoadingFactoryBean.getBaseProperty("export.rootDirectory");
if (!rootDirectory.endsWith(File.separator)) {
rootDirectory += File.separator;
}
schema = PropertyLoadingFactoryBean.getBaseProperty("export.schema");
String skipTables = PropertyLoadingFactoryBean.getBaseProperty("export.skip");
if (skipTables != null) {
skipTableExpressions = Arrays.asList(skipTables.split(";"));
} else {
skipTableExpressions = new ArrayList<String>();
}
}
/**
* For convenience, loads a map to turn JDBC column type values into their names.
*/
private void loadTypeNames() {
typeNames = new HashMap<Integer, String>();
for (Field field : Types.class.getFields()) {
try {
typeNames.put((Integer)field.get(null), field.getName());
} catch (IllegalArgumentException | IllegalAccessException e) { }
}
}
}
| FINI-1464 Change date format in data files
| kfs-datatools/src/main/java/org/kuali/kfs/sys/datatools/exportdata/ExportData.java | FINI-1464 Change date format in data files |
|
Java | lgpl-2.1 | 54f47fe87456980ab5d3d70f3c7822219f383a1e | 0 | aaronc/jfreechart,aaronc/jfreechart,aaronc/jfreechart | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -----------------
* XYSeriesTest.java
* -----------------
* (C) Copyright 2003-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 23-Dec-2003 : Version 1 (DG);
* 15-Jan-2007 : Added tests for new toArray() method (DG);
* 30-Jan-2007 : Fixed some code that won't compile with Java 1.4 (DG);
* 31-Oct-2007 : New hashCode() test (DG);
* 01-May-2008 : Added testAddOrUpdate3() (DG);
* 24-Nov-2008 : Added testBug1955483() (DG);
* 06-Mar-2009 : Added tests for cached bounds values (DG);
*
*/
package org.jfree.data.xy;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
import org.jfree.chart.TestUtilities;
import org.jfree.data.general.SeriesException;
import org.junit.Test;
/**
* Tests for the {@link XYSeries} class.
*/
public class XYSeriesTest {
/**
* Confirm that the equals method can distinguish all the required fields.
*/
@Test
public void testEquals() {
XYSeries s1 = new XYSeries("Series");
s1.add(1.0, 1.1);
XYSeries s2 = new XYSeries("Series");
s2.add(1.0, 1.1);
assertTrue(s1.equals(s2));
assertTrue(s2.equals(s1));
s1.setKey("Series X");
assertFalse(s1.equals(s2));
s2.setKey("Series X");
assertTrue(s1.equals(s2));
s1.add(2.0, 2.2);
assertFalse(s1.equals(s2));
s2.add(2.0, 2.2);
assertTrue(s1.equals(s2));
}
/**
* Some simple checks for the hashCode() method.
*/
@Test
public void testHashCode() {
XYSeries s1 = new XYSeries("Test");
XYSeries s2 = new XYSeries("Test");
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add(1.0, 500.0);
s2.add(1.0, 500.0);
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add(2.0, null);
s2.add(2.0, null);
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add(5.0, 111.0);
s2.add(5.0, 111.0);
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add(9.0, 1.0);
s2.add(9.0, 1.0);
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
}
/**
* Confirm that cloning works.
*/
@Test
public void testCloning() throws CloneNotSupportedException {
XYSeries s1 = new XYSeries("Series");
s1.add(1.0, 1.1);
XYSeries s2 = (XYSeries) s1.clone();
assertTrue(s1 != s2);
assertTrue(s1.getClass() == s2.getClass());
assertTrue(s1.equals(s2));
}
/**
* Another test of the clone() method.
*/
@Test
public void testCloning2() throws CloneNotSupportedException {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 100.0);
s1.add(2.0, null);
s1.add(3.0, 200.0);
XYSeries s2 = (XYSeries) s1.clone();
assertTrue(s1.equals(s2));
// check independence
s2.add(4.0, 300.0);
assertFalse(s1.equals(s2));
s1.add(4.0, 300.0);
assertTrue(s1.equals(s2));
}
/**
* Another test of the clone() method.
*/
@Test
public void testCloning3() throws CloneNotSupportedException {
XYSeries s1 = new XYSeries("S1");
XYSeries s2 = (XYSeries) s1.clone();
assertTrue(s1.equals(s2));
// check independence
s2.add(4.0, 300.0);
assertFalse(s1.equals(s2));
s1.add(4.0, 300.0);
assertTrue(s1.equals(s2));
}
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() {
XYSeries s1 = new XYSeries("Series");
s1.add(1.0, 1.1);
XYSeries s2 = (XYSeries) TestUtilities.serialised(s1);
assertEquals(s1, s2);
}
/**
* Simple test for the indexOf() method.
*/
@Test
public void testIndexOf() {
XYSeries s1 = new XYSeries("Series 1");
s1.add(1.0, 1.0);
s1.add(2.0, 2.0);
s1.add(3.0, 3.0);
assertEquals(0, s1.indexOf(new Double(1.0)));
assertEquals(1, s1.indexOf(new Double(2.0)));
assertEquals(2, s1.indexOf(new Double(3.0)));
assertEquals(-4, s1.indexOf(new Double(99.9)));
}
/**
* A check for the indexOf() method for an unsorted series.
*/
@Test
public void testIndexOf2() {
XYSeries s1 = new XYSeries("Series 1", false, true);
s1.add(1.0, 1.0);
s1.add(3.0, 3.0);
s1.add(2.0, 2.0);
assertEquals(0, s1.indexOf(new Double(1.0)));
assertEquals(1, s1.indexOf(new Double(3.0)));
assertEquals(2, s1.indexOf(new Double(2.0)));
}
/**
* A check for the indexOf(Number) method when the series has duplicate
* x-values.
*/
@Test
public void testIndexOf3() {
XYSeries s1 = new XYSeries("Series 1");
s1.add(1.0, 1.0);
s1.add(2.0, 2.0);
s1.add(2.0, 3.0);
assertEquals(0, s1.indexOf(new Double(1.0)));
assertEquals(1, s1.indexOf(new Double(2.0)));
}
/**
* Simple test for the remove() method.
*/
@Test
public void testRemove() {
XYSeries s1 = new XYSeries("Series 1");
s1.add(1.0, 1.0);
s1.add(2.0, 2.0);
s1.add(3.0, 3.0);
assertEquals(3, s1.getItemCount());
s1.remove(new Double(2.0));
assertEquals(new Double(3.0), s1.getX(1));
s1.remove(0);
assertEquals(new Double(3.0), s1.getX(0));
}
/**
* Some checks for the remove(int) method.
*/
@Test
public void testRemove2() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
s1.add(4.0, 4.4);
s1.add(5.0, 5.5);
s1.add(6.0, 6.6);
assertEquals(6, s1.getItemCount());
assertEquals(1.0, s1.getMinX(), EPSILON);
assertEquals(6.0, s1.getMaxX(), EPSILON);
assertEquals(1.1, s1.getMinY(), EPSILON);
assertEquals(6.6, s1.getMaxY(), EPSILON);
s1.remove(5);
assertEquals(5, s1.getItemCount());
assertEquals(1.0, s1.getMinX(), EPSILON);
assertEquals(5.0, s1.getMaxX(), EPSILON);
assertEquals(1.1, s1.getMinY(), EPSILON);
assertEquals(5.5, s1.getMaxY(), EPSILON);
}
private static final double EPSILON = 0.0000000001;
/**
* When items are added with duplicate x-values, we expect them to remain
* in the order they were added.
*/
@Test
public void testAdditionOfDuplicateXValues() {
XYSeries s1 = new XYSeries("Series 1");
s1.add(1.0, 1.0);
s1.add(2.0, 2.0);
s1.add(2.0, 3.0);
s1.add(2.0, 4.0);
s1.add(3.0, 5.0);
assertEquals(1.0, s1.getY(0).doubleValue(), EPSILON);
assertEquals(2.0, s1.getY(1).doubleValue(), EPSILON);
assertEquals(3.0, s1.getY(2).doubleValue(), EPSILON);
assertEquals(4.0, s1.getY(3).doubleValue(), EPSILON);
assertEquals(5.0, s1.getY(4).doubleValue(), EPSILON);
}
/**
* Some checks for the update(Number, Number) method.
*/
@Test
public void testUpdate() {
XYSeries series = new XYSeries("S1");
series.add(new Integer(1), new Integer(2));
assertEquals(new Integer(2), series.getY(0));
series.update(new Integer(1), new Integer(3));
assertEquals(new Integer(3), series.getY(0));
try {
series.update(new Integer(2), new Integer(99));
assertTrue(false);
}
catch (SeriesException e) {
// got the required exception
}
}
/**
* Some checks for the update() method for an unsorted series.
*/
@Test
public void testUpdate2() {
XYSeries series = new XYSeries("Series", false, true);
series.add(5.0, 55.0);
series.add(4.0, 44.0);
series.add(6.0, 66.0);
series.update(new Double(4.0), new Double(99.0));
assertEquals(new Double(99.0), series.getY(1));
}
/**
* Some checks for the addOrUpdate() method.
*/
@Test
public void testAddOrUpdate() {
XYSeries series = new XYSeries("S1", true, false);
XYDataItem old = series.addOrUpdate(new Long(1), new Long(2));
assertTrue(old == null);
assertEquals(1, series.getItemCount());
assertEquals(new Long(2), series.getY(0));
old = series.addOrUpdate(new Long(2), new Long(3));
assertTrue(old == null);
assertEquals(2, series.getItemCount());
assertEquals(new Long(3), series.getY(1));
old = series.addOrUpdate(new Long(1), new Long(99));
assertEquals(new XYDataItem(new Long(1), new Long(2)), old);
assertEquals(2, series.getItemCount());
assertEquals(new Long(99), series.getY(0));
assertEquals(new Long(3), series.getY(1));
}
/**
* Some checks for the addOrUpdate() method for an UNSORTED series.
*/
@Test
public void testAddOrUpdate2() {
XYSeries series = new XYSeries("Series", false, false);
series.add(5.0, 5.5);
series.add(6.0, 6.6);
series.add(3.0, 3.3);
series.add(4.0, 4.4);
series.add(2.0, 2.2);
series.add(1.0, 1.1);
series.addOrUpdate(new Double(3.0), new Double(33.3));
series.addOrUpdate(new Double(2.0), new Double(22.2));
assertEquals(33.3, series.getY(2).doubleValue(), EPSILON);
assertEquals(22.2, series.getY(4).doubleValue(), EPSILON);
}
/**
* Another test for the addOrUpdate() method.
*/
@Test
public void testAddOrUpdate3() {
XYSeries series = new XYSeries("Series", false, true);
series.addOrUpdate(1.0, 1.0);
series.addOrUpdate(1.0, 2.0);
series.addOrUpdate(1.0, 3.0);
assertEquals(new Double(1.0), series.getY(0));
assertEquals(new Double(2.0), series.getY(1));
assertEquals(new Double(3.0), series.getY(2));
assertEquals(3, series.getItemCount());
}
/**
* Some checks for the add() method for an UNSORTED series.
*/
@Test
public void testAdd() {
XYSeries series = new XYSeries("Series", false, true);
series.add(5.0, 5.50);
series.add(5.1, 5.51);
series.add(6.0, 6.6);
series.add(3.0, 3.3);
series.add(4.0, 4.4);
series.add(2.0, 2.2);
series.add(1.0, 1.1);
assertEquals(5.5, series.getY(0).doubleValue(), EPSILON);
assertEquals(5.51, series.getY(1).doubleValue(), EPSILON);
assertEquals(6.6, series.getY(2).doubleValue(), EPSILON);
assertEquals(3.3, series.getY(3).doubleValue(), EPSILON);
assertEquals(4.4, series.getY(4).doubleValue(), EPSILON);
assertEquals(2.2, series.getY(5).doubleValue(), EPSILON);
assertEquals(1.1, series.getY(6).doubleValue(), EPSILON);
}
/**
* A simple check that the maximumItemCount attribute is working.
*/
@Test
public void testSetMaximumItemCount() {
XYSeries s1 = new XYSeries("S1");
assertEquals(Integer.MAX_VALUE, s1.getMaximumItemCount());
s1.setMaximumItemCount(2);
assertEquals(2, s1.getMaximumItemCount());
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
assertEquals(2.0, s1.getX(0).doubleValue(), EPSILON);
assertEquals(3.0, s1.getX(1).doubleValue(), EPSILON);
}
/**
* Check that the maximum item count can be applied retrospectively.
*/
@Test
public void testSetMaximumItemCount2() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
s1.setMaximumItemCount(2);
assertEquals(2.0, s1.getX(0).doubleValue(), EPSILON);
assertEquals(3.0, s1.getX(1).doubleValue(), EPSILON);
}
/**
* Check that the item bounds are determined correctly when there is a
* maximum item count.
*/
@Test
public void testSetMaximumItemCount3() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
s1.add(4.0, 4.4);
s1.add(5.0, 5.5);
s1.add(6.0, 6.6);
s1.setMaximumItemCount(2);
assertEquals(5.0, s1.getX(0).doubleValue(), EPSILON);
assertEquals(6.0, s1.getX(1).doubleValue(), EPSILON);
assertEquals(5.0, s1.getMinX(), EPSILON);
assertEquals(6.0, s1.getMaxX(), EPSILON);
assertEquals(5.5, s1.getMinY(), EPSILON);
assertEquals(6.6, s1.getMaxY(), EPSILON);
}
/**
* Check that the item bounds are determined correctly when there is a
* maximum item count.
*/
@Test
public void testSetMaximumItemCount4() {
XYSeries s1 = new XYSeries("S1");
s1.setMaximumItemCount(2);
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
assertEquals(2.0, s1.getX(0).doubleValue(), EPSILON);
assertEquals(3.0, s1.getX(1).doubleValue(), EPSILON);
assertEquals(2.0, s1.getMinX(), EPSILON);
assertEquals(3.0, s1.getMaxX(), EPSILON);
assertEquals(2.2, s1.getMinY(), EPSILON);
assertEquals(3.3, s1.getMaxY(), EPSILON);
}
/**
* Some checks for the toArray() method.
*/
@Test
public void testToArray() {
XYSeries s = new XYSeries("S1");
double[][] array = s.toArray();
assertEquals(2, array.length);
assertEquals(0, array[0].length);
assertEquals(0, array[1].length);
s.add(1.0, 2.0);
array = s.toArray();
assertEquals(1, array[0].length);
assertEquals(1, array[1].length);
assertEquals(2, array.length);
assertEquals(1.0, array[0][0], EPSILON);
assertEquals(2.0, array[1][0], EPSILON);
s.add(2.0, null);
array = s.toArray();
assertEquals(2, array.length);
assertEquals(2, array[0].length);
assertEquals(2, array[1].length);
assertEquals(2.0, array[0][1], EPSILON);
assertTrue(Double.isNaN(array[1][1]));
}
/**
* Some checks for an example using the toArray() method.
*/
@Test
public void testToArrayExample() {
XYSeries s = new XYSeries("S");
s.add(1.0, 11.0);
s.add(2.0, 22.0);
s.add(3.5, 35.0);
s.add(5.0, null);
DefaultXYDataset dataset = new DefaultXYDataset();
dataset.addSeries("S", s.toArray());
assertEquals(1, dataset.getSeriesCount());
assertEquals(4, dataset.getItemCount(0));
assertEquals("S", dataset.getSeriesKey(0));
assertEquals(1.0, dataset.getXValue(0, 0), EPSILON);
assertEquals(2.0, dataset.getXValue(0, 1), EPSILON);
assertEquals(3.5, dataset.getXValue(0, 2), EPSILON);
assertEquals(5.0, dataset.getXValue(0, 3), EPSILON);
assertEquals(11.0, dataset.getYValue(0, 0), EPSILON);
assertEquals(22.0, dataset.getYValue(0, 1), EPSILON);
assertEquals(35.0, dataset.getYValue(0, 2), EPSILON);
assertTrue(Double.isNaN(dataset.getYValue(0, 3)));
}
/**
* Another test for the addOrUpdate() method.
*/
@Test
public void testBug1955483() {
XYSeries series = new XYSeries("Series", true, true);
series.addOrUpdate(1.0, 1.0);
series.addOrUpdate(1.0, 2.0);
assertEquals(new Double(1.0), series.getY(0));
assertEquals(new Double(2.0), series.getY(1));
assertEquals(2, series.getItemCount());
}
/**
* Some checks for the delete(int, int) method.
*/
@Test
public void testDelete() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
s1.add(4.0, 4.4);
s1.add(5.0, 5.5);
s1.add(6.0, 6.6);
s1.delete(2, 5);
assertEquals(2, s1.getItemCount());
assertEquals(1.0, s1.getX(0).doubleValue(), EPSILON);
assertEquals(2.0, s1.getX(1).doubleValue(), EPSILON);
assertEquals(1.0, s1.getMinX(), EPSILON);
assertEquals(2.0, s1.getMaxX(), EPSILON);
assertEquals(1.1, s1.getMinY(), EPSILON);
assertEquals(2.2, s1.getMaxY(), EPSILON);
}
/**
* Some checks for the getMinX() method.
*/
@Test
public void testGetMinX() {
XYSeries s1 = new XYSeries("S1");
assertTrue(Double.isNaN(s1.getMinX()));
s1.add(1.0, 1.1);
assertEquals(1.0, s1.getMinX(), EPSILON);
s1.add(2.0, 2.2);
assertEquals(1.0, s1.getMinX(), EPSILON);
s1.add(Double.NaN, 99.9);
assertEquals(1.0, s1.getMinX(), EPSILON);
s1.add(-1.0, -1.1);
assertEquals(-1.0, s1.getMinX(), EPSILON);
s1.add(0.0, null);
assertEquals(-1.0, s1.getMinX(), EPSILON);
}
/**
* Some checks for the getMaxX() method.
*/
@Test
public void testGetMaxX() {
XYSeries s1 = new XYSeries("S1");
assertTrue(Double.isNaN(s1.getMaxX()));
s1.add(1.0, 1.1);
assertEquals(1.0, s1.getMaxX(), EPSILON);
s1.add(2.0, 2.2);
assertEquals(2.0, s1.getMaxX(), EPSILON);
s1.add(Double.NaN, 99.9);
assertEquals(2.0, s1.getMaxX(), EPSILON);
s1.add(-1.0, -1.1);
assertEquals(2.0, s1.getMaxX(), EPSILON);
s1.add(0.0, null);
assertEquals(2.0, s1.getMaxX(), EPSILON);
}
/**
* Some checks for the getMinY() method.
*/
@Test
public void testGetMinY() {
XYSeries s1 = new XYSeries("S1");
assertTrue(Double.isNaN(s1.getMinY()));
s1.add(1.0, 1.1);
assertEquals(1.1, s1.getMinY(), EPSILON);
s1.add(2.0, 2.2);
assertEquals(1.1, s1.getMinY(), EPSILON);
s1.add(Double.NaN, 99.9);
assertEquals(1.1, s1.getMinY(), EPSILON);
s1.add(-1.0, -1.1);
assertEquals(-1.1, s1.getMinY(), EPSILON);
s1.add(0.0, null);
assertEquals(-1.1, s1.getMinY(), EPSILON);
}
/**
* Some checks for the getMaxY() method.
*/
@Test
public void testGetMaxY() {
XYSeries s1 = new XYSeries("S1");
assertTrue(Double.isNaN(s1.getMaxY()));
s1.add(1.0, 1.1);
assertEquals(1.1, s1.getMaxY(), EPSILON);
s1.add(2.0, 2.2);
assertEquals(2.2, s1.getMaxY(), EPSILON);
s1.add(Double.NaN, 99.9);
assertEquals(99.9, s1.getMaxY(), EPSILON);
s1.add(-1.0, -1.1);
assertEquals(99.9, s1.getMaxY(), EPSILON);
s1.add(0.0, null);
assertEquals(99.9, s1.getMaxY(), EPSILON);
}
/**
* A test for a bug reported in the forum:
*
* http://www.jfree.org/forum/viewtopic.php?f=3&t=116601
*/
@Test
public void testGetMaxY2() {
XYSeries series = new XYSeries(1, true, false);
series.addOrUpdate(1, 20);
series.addOrUpdate(2, 30);
series.addOrUpdate(3, 40);
assertEquals(40.0, series.getMaxY(), EPSILON);
series.addOrUpdate(2, 22);
assertEquals(40.0, series.getMaxY(), EPSILON);
}
/**
* A test for the clear method.
*/
@Test
public void testClear() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
assertEquals(3, s1.getItemCount());
s1.clear();
assertEquals(0, s1.getItemCount());
assertTrue(Double.isNaN(s1.getMinX()));
assertTrue(Double.isNaN(s1.getMaxX()));
assertTrue(Double.isNaN(s1.getMinY()));
assertTrue(Double.isNaN(s1.getMaxY()));
}
/**
* Some checks for the updateByIndex() method.
*/
@Test
public void testUpdateByIndex() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
assertEquals(1.1, s1.getMinY(), EPSILON);
assertEquals(3.3, s1.getMaxY(), EPSILON);
s1.updateByIndex(0, new Double(-5.0));
assertEquals(-5.0, s1.getMinY(), EPSILON);
assertEquals(3.3, s1.getMaxY(), EPSILON);
s1.updateByIndex(0, null);
assertEquals(2.2, s1.getMinY(), EPSILON);
assertEquals(3.3, s1.getMaxY(), EPSILON);
s1.updateByIndex(2, null);
assertEquals(2.2, s1.getMinY(), EPSILON);
assertEquals(2.2, s1.getMaxY(), EPSILON);
s1.updateByIndex(1, null);
assertTrue(Double.isNaN(s1.getMinY()));
assertTrue(Double.isNaN(s1.getMaxY()));
}
/**
* Some checks for the updateByIndex() method.
*/
@Test
public void testUpdateByIndex2() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, Double.NaN);
assertTrue(Double.isNaN(s1.getMinY()));
assertTrue(Double.isNaN(s1.getMaxY()));
s1.updateByIndex(0, new Double(1.0));
assertEquals(1.0, s1.getMinY(), EPSILON);
assertEquals(1.0, s1.getMaxY(), EPSILON);
s1.updateByIndex(0, new Double(2.0));
assertEquals(2.0, s1.getMinY(), EPSILON);
assertEquals(2.0, s1.getMaxY(), EPSILON);
s1.add(-1.0, -1.0);
s1.updateByIndex(0, new Double(0.0));
assertEquals(0.0, s1.getMinY(), EPSILON);
assertEquals(2.0, s1.getMaxY(), EPSILON);
}
/**
* Some checks for the updateByIndex() method.
*/
@Test
public void testUpdateByIndex3() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
s1.updateByIndex(1, new Double(2.05));
assertEquals(1.1, s1.getMinY(), EPSILON);
assertEquals(3.3, s1.getMaxY(), EPSILON);
}
/**
* Some checks for the update(Number, Number) method.
*/
@Test
public void testUpdateXY() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, Double.NaN);
assertTrue(Double.isNaN(s1.getMinY()));
assertTrue(Double.isNaN(s1.getMaxY()));
s1.update(new Double(1.0), new Double(1.0));
assertEquals(1.0, s1.getMinY(), EPSILON);
assertEquals(1.0, s1.getMaxY(), EPSILON);
s1.update(new Double(1.0), new Double(2.0));
assertEquals(2.0, s1.getMinY(), EPSILON);
assertEquals(2.0, s1.getMaxY(), EPSILON);
}
}
| tests/org/jfree/data/xy/XYSeriesTest.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -----------------
* XYSeriesTest.java
* -----------------
* (C) Copyright 2003-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 23-Dec-2003 : Version 1 (DG);
* 15-Jan-2007 : Added tests for new toArray() method (DG);
* 30-Jan-2007 : Fixed some code that won't compile with Java 1.4 (DG);
* 31-Oct-2007 : New hashCode() test (DG);
* 01-May-2008 : Added testAddOrUpdate3() (DG);
* 24-Nov-2008 : Added testBug1955483() (DG);
* 06-Mar-2009 : Added tests for cached bounds values (DG);
*
*/
package org.jfree.data.xy;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
import org.jfree.chart.TestUtilities;
import org.jfree.data.general.SeriesException;
import org.junit.Test;
/**
* Tests for the {@link XYSeries} class.
*/
public class XYSeriesTest {
/**
* Confirm that the equals method can distinguish all the required fields.
*/
@Test
public void testEquals() {
XYSeries s1 = new XYSeries("Series");
s1.add(1.0, 1.1);
XYSeries s2 = new XYSeries("Series");
s2.add(1.0, 1.1);
assertTrue(s1.equals(s2));
assertTrue(s2.equals(s1));
s1.setKey("Series X");
assertFalse(s1.equals(s2));
s2.setKey("Series X");
assertTrue(s1.equals(s2));
s1.add(2.0, 2.2);
assertFalse(s1.equals(s2));
s2.add(2.0, 2.2);
assertTrue(s1.equals(s2));
}
/**
* Some simple checks for the hashCode() method.
*/
@Test
public void testHashCode() {
XYSeries s1 = new XYSeries("Test");
XYSeries s2 = new XYSeries("Test");
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add(1.0, 500.0);
s2.add(1.0, 500.0);
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add(2.0, null);
s2.add(2.0, null);
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add(5.0, 111.0);
s2.add(5.0, 111.0);
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add(9.0, 1.0);
s2.add(9.0, 1.0);
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
}
/**
* Confirm that cloning works.
*/
@Test
public void testCloning() throws CloneNotSupportedException {
XYSeries s1 = new XYSeries("Series");
s1.add(1.0, 1.1);
XYSeries s2 = (XYSeries) s1.clone();
assertTrue(s1 != s2);
assertTrue(s1.getClass() == s2.getClass());
assertTrue(s1.equals(s2));
}
/**
* Another test of the clone() method.
*/
@Test
public void testCloning2() throws CloneNotSupportedException {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 100.0);
s1.add(2.0, null);
s1.add(3.0, 200.0);
XYSeries s2 = (XYSeries) s1.clone();
assertTrue(s1.equals(s2));
// check independence
s2.add(4.0, 300.0);
assertFalse(s1.equals(s2));
s1.add(4.0, 300.0);
assertTrue(s1.equals(s2));
}
/**
* Another test of the clone() method.
*/
@Test
public void testCloning3() throws CloneNotSupportedException {
XYSeries s1 = new XYSeries("S1");
XYSeries s2 = (XYSeries) s1.clone();
assertTrue(s1.equals(s2));
// check independence
s2.add(4.0, 300.0);
assertFalse(s1.equals(s2));
s1.add(4.0, 300.0);
assertTrue(s1.equals(s2));
}
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() {
XYSeries s1 = new XYSeries("Series");
s1.add(1.0, 1.1);
XYSeries s2 = (XYSeries) TestUtilities.serialised(s1);
assertEquals(s1, s2);
}
/**
* Simple test for the indexOf() method.
*/
@Test
public void testIndexOf() {
XYSeries s1 = new XYSeries("Series 1");
s1.add(1.0, 1.0);
s1.add(2.0, 2.0);
s1.add(3.0, 3.0);
assertEquals(0, s1.indexOf(new Double(1.0)));
assertEquals(1, s1.indexOf(new Double(2.0)));
assertEquals(2, s1.indexOf(new Double(3.0)));
assertEquals(-4, s1.indexOf(new Double(99.9)));
}
/**
* A check for the indexOf() method for an unsorted series.
*/
@Test
public void testIndexOf2() {
XYSeries s1 = new XYSeries("Series 1", false, true);
s1.add(1.0, 1.0);
s1.add(3.0, 3.0);
s1.add(2.0, 2.0);
assertEquals(0, s1.indexOf(new Double(1.0)));
assertEquals(1, s1.indexOf(new Double(3.0)));
assertEquals(2, s1.indexOf(new Double(2.0)));
}
/**
* A check for the indexOf(Number) method when the series has duplicate
* x-values.
*/
@Test
public void testIndexOf3() {
XYSeries s1 = new XYSeries("Series 1");
s1.add(1.0, 1.0);
s1.add(2.0, 2.0);
s1.add(2.0, 3.0);
assertEquals(0, s1.indexOf(new Double(1.0)));
assertEquals(1, s1.indexOf(new Double(2.0)));
}
/**
* Simple test for the remove() method.
*/
@Test
public void testRemove() {
XYSeries s1 = new XYSeries("Series 1");
s1.add(1.0, 1.0);
s1.add(2.0, 2.0);
s1.add(3.0, 3.0);
assertEquals(3, s1.getItemCount());
s1.remove(new Double(2.0));
assertEquals(new Double(3.0), s1.getX(1));
s1.remove(0);
assertEquals(new Double(3.0), s1.getX(0));
}
/**
* Some checks for the remove(int) method.
*/
@Test
public void testRemove2() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
s1.add(4.0, 4.4);
s1.add(5.0, 5.5);
s1.add(6.0, 6.6);
assertEquals(6, s1.getItemCount());
assertEquals(1.0, s1.getMinX(), EPSILON);
assertEquals(6.0, s1.getMaxX(), EPSILON);
assertEquals(1.1, s1.getMinY(), EPSILON);
assertEquals(6.6, s1.getMaxY(), EPSILON);
s1.remove(5);
assertEquals(5, s1.getItemCount());
assertEquals(1.0, s1.getMinX(), EPSILON);
assertEquals(5.0, s1.getMaxX(), EPSILON);
assertEquals(1.1, s1.getMinY(), EPSILON);
assertEquals(5.5, s1.getMaxY(), EPSILON);
}
private static final double EPSILON = 0.0000000001;
/**
* When items are added with duplicate x-values, we expect them to remain
* in the order they were added.
*/
@Test
public void testAdditionOfDuplicateXValues() {
XYSeries s1 = new XYSeries("Series 1");
s1.add(1.0, 1.0);
s1.add(2.0, 2.0);
s1.add(2.0, 3.0);
s1.add(2.0, 4.0);
s1.add(3.0, 5.0);
assertEquals(1.0, s1.getY(0).doubleValue(), EPSILON);
assertEquals(2.0, s1.getY(1).doubleValue(), EPSILON);
assertEquals(3.0, s1.getY(2).doubleValue(), EPSILON);
assertEquals(4.0, s1.getY(3).doubleValue(), EPSILON);
assertEquals(5.0, s1.getY(4).doubleValue(), EPSILON);
}
/**
* Some checks for the update(Number, Number) method.
*/
@Test
public void testUpdate() {
XYSeries series = new XYSeries("S1");
series.add(new Integer(1), new Integer(2));
assertEquals(new Integer(2), series.getY(0));
series.update(new Integer(1), new Integer(3));
assertEquals(new Integer(3), series.getY(0));
try {
series.update(new Integer(2), new Integer(99));
assertTrue(false);
}
catch (SeriesException e) {
// got the required exception
}
}
/**
* Some checks for the update() method for an unsorted series.
*/
@Test
public void testUpdate2() {
XYSeries series = new XYSeries("Series", false, true);
series.add(5.0, 55.0);
series.add(4.0, 44.0);
series.add(6.0, 66.0);
series.update(new Double(4.0), new Double(99.0));
assertEquals(new Double(99.0), series.getY(1));
}
/**
* Some checks for the addOrUpdate() method.
*/
@Test
public void testAddOrUpdate() {
XYSeries series = new XYSeries("S1", true, false);
XYDataItem old = series.addOrUpdate(new Long(1), new Long(2));
assertTrue(old == null);
assertEquals(1, series.getItemCount());
assertEquals(new Long(2), series.getY(0));
old = series.addOrUpdate(new Long(2), new Long(3));
assertTrue(old == null);
assertEquals(2, series.getItemCount());
assertEquals(new Long(3), series.getY(1));
old = series.addOrUpdate(new Long(1), new Long(99));
assertEquals(new XYDataItem(new Long(1), new Long(2)), old);
assertEquals(2, series.getItemCount());
assertEquals(new Long(99), series.getY(0));
assertEquals(new Long(3), series.getY(1));
}
/**
* Some checks for the addOrUpdate() method for an UNSORTED series.
*/
@Test
public void testAddOrUpdate2() {
XYSeries series = new XYSeries("Series", false, false);
series.add(5.0, 5.5);
series.add(6.0, 6.6);
series.add(3.0, 3.3);
series.add(4.0, 4.4);
series.add(2.0, 2.2);
series.add(1.0, 1.1);
series.addOrUpdate(new Double(3.0), new Double(33.3));
series.addOrUpdate(new Double(2.0), new Double(22.2));
assertEquals(33.3, series.getY(2).doubleValue(), EPSILON);
assertEquals(22.2, series.getY(4).doubleValue(), EPSILON);
}
/**
* Another test for the addOrUpdate() method.
*/
@Test
public void testAddOrUpdate3() {
XYSeries series = new XYSeries("Series", false, true);
series.addOrUpdate(1.0, 1.0);
series.addOrUpdate(1.0, 2.0);
series.addOrUpdate(1.0, 3.0);
assertEquals(new Double(1.0), series.getY(0));
assertEquals(new Double(2.0), series.getY(1));
assertEquals(new Double(3.0), series.getY(2));
assertEquals(3, series.getItemCount());
}
/**
* Some checks for the add() method for an UNSORTED series.
*/
@Test
public void testAdd() {
XYSeries series = new XYSeries("Series", false, true);
series.add(5.0, 5.50);
series.add(5.1, 5.51);
series.add(6.0, 6.6);
series.add(3.0, 3.3);
series.add(4.0, 4.4);
series.add(2.0, 2.2);
series.add(1.0, 1.1);
assertEquals(5.5, series.getY(0).doubleValue(), EPSILON);
assertEquals(5.51, series.getY(1).doubleValue(), EPSILON);
assertEquals(6.6, series.getY(2).doubleValue(), EPSILON);
assertEquals(3.3, series.getY(3).doubleValue(), EPSILON);
assertEquals(4.4, series.getY(4).doubleValue(), EPSILON);
assertEquals(2.2, series.getY(5).doubleValue(), EPSILON);
assertEquals(1.1, series.getY(6).doubleValue(), EPSILON);
}
/**
* A simple check that the maximumItemCount attribute is working.
*/
@Test
public void testSetMaximumItemCount() {
XYSeries s1 = new XYSeries("S1");
assertEquals(Integer.MAX_VALUE, s1.getMaximumItemCount());
s1.setMaximumItemCount(2);
assertEquals(2, s1.getMaximumItemCount());
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
assertEquals(2.0, s1.getX(0).doubleValue(), EPSILON);
assertEquals(3.0, s1.getX(1).doubleValue(), EPSILON);
}
/**
* Check that the maximum item count can be applied retrospectively.
*/
@Test
public void testSetMaximumItemCount2() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
s1.setMaximumItemCount(2);
assertEquals(2.0, s1.getX(0).doubleValue(), EPSILON);
assertEquals(3.0, s1.getX(1).doubleValue(), EPSILON);
}
/**
* Check that the item bounds are determined correctly when there is a
* maximum item count.
*/
@Test
public void testSetMaximumItemCount3() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
s1.add(4.0, 4.4);
s1.add(5.0, 5.5);
s1.add(6.0, 6.6);
s1.setMaximumItemCount(2);
assertEquals(5.0, s1.getX(0).doubleValue(), EPSILON);
assertEquals(6.0, s1.getX(1).doubleValue(), EPSILON);
assertEquals(5.0, s1.getMinX(), EPSILON);
assertEquals(6.0, s1.getMaxX(), EPSILON);
assertEquals(5.5, s1.getMinY(), EPSILON);
assertEquals(6.6, s1.getMaxY(), EPSILON);
}
/**
* Check that the item bounds are determined correctly when there is a
* maximum item count.
*/
@Test
public void testSetMaximumItemCount4() {
XYSeries s1 = new XYSeries("S1");
s1.setMaximumItemCount(2);
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
assertEquals(2.0, s1.getX(0).doubleValue(), EPSILON);
assertEquals(3.0, s1.getX(1).doubleValue(), EPSILON);
assertEquals(2.0, s1.getMinX(), EPSILON);
assertEquals(3.0, s1.getMaxX(), EPSILON);
assertEquals(2.2, s1.getMinY(), EPSILON);
assertEquals(3.3, s1.getMaxY(), EPSILON);
}
/**
* Some checks for the toArray() method.
*/
@Test
public void testToArray() {
XYSeries s = new XYSeries("S1");
double[][] array = s.toArray();
assertEquals(2, array.length);
assertEquals(0, array[0].length);
assertEquals(0, array[1].length);
s.add(1.0, 2.0);
array = s.toArray();
assertEquals(1, array[0].length);
assertEquals(1, array[1].length);
assertEquals(2, array.length);
assertEquals(1.0, array[0][0], EPSILON);
assertEquals(2.0, array[1][0], EPSILON);
s.add(2.0, null);
array = s.toArray();
assertEquals(2, array.length);
assertEquals(2, array[0].length);
assertEquals(2, array[1].length);
assertEquals(2.0, array[0][1], EPSILON);
assertTrue(Double.isNaN(array[1][1]));
}
/**
* Some checks for an example using the toArray() method.
*/
@Test
public void testToArrayExample() {
XYSeries s = new XYSeries("S");
s.add(1.0, 11.0);
s.add(2.0, 22.0);
s.add(3.5, 35.0);
s.add(5.0, null);
DefaultXYDataset dataset = new DefaultXYDataset();
dataset.addSeries("S", s.toArray());
assertEquals(1, dataset.getSeriesCount());
assertEquals(4, dataset.getItemCount(0));
assertEquals("S", dataset.getSeriesKey(0));
assertEquals(1.0, dataset.getXValue(0, 0), EPSILON);
assertEquals(2.0, dataset.getXValue(0, 1), EPSILON);
assertEquals(3.5, dataset.getXValue(0, 2), EPSILON);
assertEquals(5.0, dataset.getXValue(0, 3), EPSILON);
assertEquals(11.0, dataset.getYValue(0, 0), EPSILON);
assertEquals(22.0, dataset.getYValue(0, 1), EPSILON);
assertEquals(35.0, dataset.getYValue(0, 2), EPSILON);
assertTrue(Double.isNaN(dataset.getYValue(0, 3)));
}
/**
* Another test for the addOrUpdate() method.
*/
@Test
public void testBug1955483() {
XYSeries series = new XYSeries("Series", true, true);
series.addOrUpdate(1.0, 1.0);
series.addOrUpdate(1.0, 2.0);
assertEquals(new Double(1.0), series.getY(0));
assertEquals(new Double(2.0), series.getY(1));
assertEquals(2, series.getItemCount());
}
/**
* Some checks for the delete(int, int) method.
*/
@Test
public void testDelete() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
s1.add(4.0, 4.4);
s1.add(5.0, 5.5);
s1.add(6.0, 6.6);
s1.delete(2, 5);
assertEquals(2, s1.getItemCount());
assertEquals(1.0, s1.getX(0).doubleValue(), EPSILON);
assertEquals(2.0, s1.getX(1).doubleValue(), EPSILON);
assertEquals(1.0, s1.getMinX(), EPSILON);
assertEquals(2.0, s1.getMaxX(), EPSILON);
assertEquals(1.1, s1.getMinY(), EPSILON);
assertEquals(2.2, s1.getMaxY(), EPSILON);
}
/**
* Some checks for the getMinX() method.
*/
@Test
public void testGetMinX() {
XYSeries s1 = new XYSeries("S1");
assertTrue(Double.isNaN(s1.getMinX()));
s1.add(1.0, 1.1);
assertEquals(1.0, s1.getMinX(), EPSILON);
s1.add(2.0, 2.2);
assertEquals(1.0, s1.getMinX(), EPSILON);
s1.add(Double.NaN, 99.9);
assertEquals(1.0, s1.getMinX(), EPSILON);
s1.add(-1.0, -1.1);
assertEquals(-1.0, s1.getMinX(), EPSILON);
s1.add(0.0, null);
assertEquals(-1.0, s1.getMinX(), EPSILON);
}
/**
* Some checks for the getMaxX() method.
*/
@Test
public void testGetMaxX() {
XYSeries s1 = new XYSeries("S1");
assertTrue(Double.isNaN(s1.getMaxX()));
s1.add(1.0, 1.1);
assertEquals(1.0, s1.getMaxX(), EPSILON);
s1.add(2.0, 2.2);
assertEquals(2.0, s1.getMaxX(), EPSILON);
s1.add(Double.NaN, 99.9);
assertEquals(2.0, s1.getMaxX(), EPSILON);
s1.add(-1.0, -1.1);
assertEquals(2.0, s1.getMaxX(), EPSILON);
s1.add(0.0, null);
assertEquals(2.0, s1.getMaxX(), EPSILON);
}
/**
* Some checks for the getMinY() method.
*/
@Test
public void testGetMinY() {
XYSeries s1 = new XYSeries("S1");
assertTrue(Double.isNaN(s1.getMinY()));
s1.add(1.0, 1.1);
assertEquals(1.1, s1.getMinY(), EPSILON);
s1.add(2.0, 2.2);
assertEquals(1.1, s1.getMinY(), EPSILON);
s1.add(Double.NaN, 99.9);
assertEquals(1.1, s1.getMinY(), EPSILON);
s1.add(-1.0, -1.1);
assertEquals(-1.1, s1.getMinY(), EPSILON);
s1.add(0.0, null);
assertEquals(-1.1, s1.getMinY(), EPSILON);
}
/**
* Some checks for the getMaxY() method.
*/
@Test
public void testGetMaxY() {
XYSeries s1 = new XYSeries("S1");
assertTrue(Double.isNaN(s1.getMaxY()));
s1.add(1.0, 1.1);
assertEquals(1.1, s1.getMaxY(), EPSILON);
s1.add(2.0, 2.2);
assertEquals(2.2, s1.getMaxY(), EPSILON);
s1.add(Double.NaN, 99.9);
assertEquals(99.9, s1.getMaxY(), EPSILON);
s1.add(-1.0, -1.1);
assertEquals(99.9, s1.getMaxY(), EPSILON);
s1.add(0.0, null);
assertEquals(99.9, s1.getMaxY(), EPSILON);
}
/**
* A test for the clear method.
*/
@Test
public void testClear() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
assertEquals(3, s1.getItemCount());
s1.clear();
assertEquals(0, s1.getItemCount());
assertTrue(Double.isNaN(s1.getMinX()));
assertTrue(Double.isNaN(s1.getMaxX()));
assertTrue(Double.isNaN(s1.getMinY()));
assertTrue(Double.isNaN(s1.getMaxY()));
}
/**
* Some checks for the updateByIndex() method.
*/
@Test
public void testUpdateByIndex() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
assertEquals(1.1, s1.getMinY(), EPSILON);
assertEquals(3.3, s1.getMaxY(), EPSILON);
s1.updateByIndex(0, new Double(-5.0));
assertEquals(-5.0, s1.getMinY(), EPSILON);
assertEquals(3.3, s1.getMaxY(), EPSILON);
s1.updateByIndex(0, null);
assertEquals(2.2, s1.getMinY(), EPSILON);
assertEquals(3.3, s1.getMaxY(), EPSILON);
s1.updateByIndex(2, null);
assertEquals(2.2, s1.getMinY(), EPSILON);
assertEquals(2.2, s1.getMaxY(), EPSILON);
s1.updateByIndex(1, null);
assertTrue(Double.isNaN(s1.getMinY()));
assertTrue(Double.isNaN(s1.getMaxY()));
}
/**
* Some checks for the updateByIndex() method.
*/
@Test
public void testUpdateByIndex2() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, Double.NaN);
assertTrue(Double.isNaN(s1.getMinY()));
assertTrue(Double.isNaN(s1.getMaxY()));
s1.updateByIndex(0, new Double(1.0));
assertEquals(1.0, s1.getMinY(), EPSILON);
assertEquals(1.0, s1.getMaxY(), EPSILON);
s1.updateByIndex(0, new Double(2.0));
assertEquals(2.0, s1.getMinY(), EPSILON);
assertEquals(2.0, s1.getMaxY(), EPSILON);
s1.add(-1.0, -1.0);
s1.updateByIndex(0, new Double(0.0));
assertEquals(0.0, s1.getMinY(), EPSILON);
assertEquals(2.0, s1.getMaxY(), EPSILON);
}
/**
* Some checks for the updateByIndex() method.
*/
@Test
public void testUpdateByIndex3() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, 1.1);
s1.add(2.0, 2.2);
s1.add(3.0, 3.3);
s1.updateByIndex(1, new Double(2.05));
assertEquals(1.1, s1.getMinY(), EPSILON);
assertEquals(3.3, s1.getMaxY(), EPSILON);
}
/**
* Some checks for the update(Number, Number) method.
*/
@Test
public void testUpdateXY() {
XYSeries s1 = new XYSeries("S1");
s1.add(1.0, Double.NaN);
assertTrue(Double.isNaN(s1.getMinY()));
assertTrue(Double.isNaN(s1.getMaxY()));
s1.update(new Double(1.0), new Double(1.0));
assertEquals(1.0, s1.getMinY(), EPSILON);
assertEquals(1.0, s1.getMaxY(), EPSILON);
s1.update(new Double(1.0), new Double(2.0));
assertEquals(2.0, s1.getMinY(), EPSILON);
assertEquals(2.0, s1.getMaxY(), EPSILON);
}
}
| Fix maxY for series that doesn't allow duplicates (JUnit test added as well).
git-svn-id: ca96c60061366ac92493e2142a352bb838ea8caa@2889 4df5dd95-b682-48b0-b31b-748e37b65e73
| tests/org/jfree/data/xy/XYSeriesTest.java | Fix maxY for series that doesn't allow duplicates (JUnit test added as well). |
|
Java | apache-2.0 | aa58e1e5db4af2a6f97520756831e87aa1d3e3fb | 0 | apache/beam,lukecwik/incubator-beam,chamikaramj/beam,apache/beam,lukecwik/incubator-beam,apache/beam,lukecwik/incubator-beam,apache/beam,robertwb/incubator-beam,robertwb/incubator-beam,chamikaramj/beam,robertwb/incubator-beam,chamikaramj/beam,apache/beam,lukecwik/incubator-beam,lukecwik/incubator-beam,lukecwik/incubator-beam,apache/beam,chamikaramj/beam,chamikaramj/beam,apache/beam,lukecwik/incubator-beam,robertwb/incubator-beam,apache/beam,chamikaramj/beam,robertwb/incubator-beam,lukecwik/incubator-beam,apache/beam,robertwb/incubator-beam,robertwb/incubator-beam,robertwb/incubator-beam,lukecwik/incubator-beam,apache/beam,robertwb/incubator-beam,chamikaramj/beam,apache/beam,chamikaramj/beam,chamikaramj/beam,lukecwik/incubator-beam,robertwb/incubator-beam,chamikaramj/beam | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.io.gcp.healthcare;
import static org.apache.beam.sdk.io.gcp.healthcare.FhirIOTestUtil.DEFAULT_TEMP_BUCKET;
import static org.apache.beam.sdk.io.gcp.healthcare.HL7v2IOTestUtil.HEALTHCARE_DATASET_TEMPLATE;
import com.google.api.services.healthcare.v1beta1.model.DeidentifyConfig;
import java.io.IOException;
import java.security.SecureRandom;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.values.PCollection;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class FhirIOLROIT {
@Rule public final transient TestPipeline pipeline = TestPipeline.create();
private transient HealthcareApiClient client;
private final String project;
private String healthcareDataset;
private final String fhirStoreId;
private final String deidFhirStoreId;
private String version;
public FhirIOLROIT() {
long testTime = System.currentTimeMillis();
this.fhirStoreId = "FHIR_store_" + testTime + "_" + (new SecureRandom().nextInt(32));
this.deidFhirStoreId = fhirStoreId + "_deid";
this.version = "STU3";
this.project =
TestPipeline.testingPipelineOptions()
.as(HealthcareStoreTestPipelineOptions.class)
.getStoreProjectId();
}
@Before
public void setup() throws Exception {
healthcareDataset = String.format(HEALTHCARE_DATASET_TEMPLATE, project);
if (client == null) {
this.client = new HttpHealthcareApiClient();
}
client.createFhirStore(healthcareDataset, fhirStoreId, version, null);
client.createFhirStore(healthcareDataset, deidFhirStoreId, version, null);
// Execute bundles to populate some data.
FhirIOTestUtil.executeFhirBundles(
client,
healthcareDataset + "/fhirStores/" + fhirStoreId,
FhirIOTestUtil.BUNDLES.get(version));
}
@After
public void deleteAllFhirStores() throws IOException {
try {
HealthcareApiClient client = new HttpHealthcareApiClient();
client.deleteFhirStore(healthcareDataset + "/fhirStores/" + fhirStoreId);
client.deleteFhirStore(healthcareDataset + "/fhirStores/" + deidFhirStoreId);
} catch (IOException e) {
// Do nothing.
}
}
@AfterClass
public static void teardownBucket() throws IOException {
FhirIOTestUtil.tearDownTempBucket();
}
@Test
public void test_FhirIO_exportFhirResourcesGcs() {
String fhirStoreName = healthcareDataset + "/fhirStores/" + fhirStoreId;
String exportGcsUriPrefix =
"gs://" + DEFAULT_TEMP_BUCKET + "/export/" + (new SecureRandom().nextInt(32));
PCollection<String> resources =
pipeline.apply(FhirIO.exportResourcesToGcs(fhirStoreName, exportGcsUriPrefix));
pipeline.run();
}
@Test
public void test_FhirIO_deidentify() throws IOException {
String fhirStoreName = healthcareDataset + "/fhirStores/" + fhirStoreId;
String destinationFhirStoreName = healthcareDataset + "/fhirStores/" + deidFhirStoreId;
DeidentifyConfig deidConfig = new DeidentifyConfig(); // use default DeidentifyConfig
pipeline.apply(FhirIO.deidentify(fhirStoreName, destinationFhirStoreName, deidConfig));
pipeline.run();
}
}
| sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/healthcare/FhirIOLROIT.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.io.gcp.healthcare;
import static org.apache.beam.sdk.io.gcp.healthcare.FhirIOTestUtil.DEFAULT_TEMP_BUCKET;
import static org.apache.beam.sdk.io.gcp.healthcare.HL7v2IOTestUtil.HEALTHCARE_DATASET_TEMPLATE;
import com.google.api.services.healthcare.v1beta1.model.DeidentifyConfig;
import java.io.IOException;
import java.security.SecureRandom;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.values.PCollection;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class FhirIOLROIT {
@Rule public final transient TestPipeline pipeline = TestPipeline.create();
private transient HealthcareApiClient client;
private final String project;
private String healthcareDataset;
private final String fhirStoreId;
private final String deidFhirStoreId;
private String version;
public FhirIOLROIT() {
long testTime = System.currentTimeMillis();
this.fhirStoreId = "FHIR_store_" + testTime + "_" + (new SecureRandom().nextInt(32));
this.deidFhirStoreId = "FHIR_store_" + testTime + "_" + (new SecureRandom().nextInt(32));
this.version = "STU3";
this.project =
TestPipeline.testingPipelineOptions()
.as(HealthcareStoreTestPipelineOptions.class)
.getStoreProjectId();
}
@Before
public void setup() throws Exception {
healthcareDataset = String.format(HEALTHCARE_DATASET_TEMPLATE, project);
if (client == null) {
this.client = new HttpHealthcareApiClient();
}
client.createFhirStore(healthcareDataset, fhirStoreId, version, null);
client.createFhirStore(healthcareDataset, deidFhirStoreId, version, null);
// Execute bundles to populate some data.
FhirIOTestUtil.executeFhirBundles(
client,
healthcareDataset + "/fhirStores/" + fhirStoreId,
FhirIOTestUtil.BUNDLES.get(version));
}
@After
public void deleteAllFhirStores() throws IOException {
try {
HealthcareApiClient client = new HttpHealthcareApiClient();
client.deleteFhirStore(healthcareDataset + "/fhirStores/" + fhirStoreId);
client.deleteFhirStore(healthcareDataset + "/fhirStores/" + deidFhirStoreId);
} catch (IOException e) {
// Do nothing.
}
}
@AfterClass
public static void teardownBucket() throws IOException {
FhirIOTestUtil.tearDownTempBucket();
}
@Test
public void test_FhirIO_exportFhirResourcesGcs() {
String fhirStoreName = healthcareDataset + "/fhirStores/" + fhirStoreId;
String exportGcsUriPrefix =
"gs://" + DEFAULT_TEMP_BUCKET + "/export/" + (new SecureRandom().nextInt(32));
PCollection<String> resources =
pipeline.apply(FhirIO.exportResourcesToGcs(fhirStoreName, exportGcsUriPrefix));
pipeline.run();
}
@Test
public void test_FhirIO_deidentify() throws IOException {
String fhirStoreName = healthcareDataset + "/fhirStores/" + fhirStoreId;
String destinationFhirStoreName = healthcareDataset + "/fhirStores/" + deidFhirStoreId;
DeidentifyConfig deidConfig = new DeidentifyConfig(); // use default DeidentifyConfig
pipeline.apply(FhirIO.deidentify(fhirStoreName, destinationFhirStoreName, deidConfig));
pipeline.run();
}
}
| [BEAM-10871] Fix FhirLROIT tests (again) (#12908)
* Add export FHIR resources to GCS method for HealthcareApiClient.
* Add export FHIR resources to GCS method for HealthcareApiClient.
* Add export FHIR resources to GCS method for HealthcareApiClient.
* Add export FHIR resources to GCS IO connector.
* Add export FHIR resources to GCS IO connector.
* Add export FHIR resources to GCS IO connector.
* Add export FHIR resources to GCS IO connector.
* Add export FHIR resources to GCS IO connector.
* Add export FHIR resources to GCS IO connector.
* Add export FHIR resources to GCS IO connector.
* Add export FHIR resources to GCS IO connector.
* Add export FHIR resources to GCS IO connector.
* Add deidentify FHIR resources IO connector.
* Add deidentify FHIR resources IO connector.
* Add deidentify FHIR resources IO connector.
* Add deidentify FHIR resources IO connector.
* Add deidentify FHIR resources IO connector.
* Add deidentify FHIR resources IO connector.
* Add deidentify FHIR resources IO connector.
* Add deidentify FHIR resources IO connector.
* Add deidentify FHIR resources IO connector.
* Add deidentify FHIR resources IO connector.
* Add deidentify FHIR resources IO connector.
* Add deidentify FHIR resources IO connector.
* Only delete FHIR stores that were being used in FhirIOLROIT tests. This is to follow-up [BEAM-10871] Add deidentify for FhirIO connector #12721
R: da39a3ee5e6b4b0d3255bfef95601890afd80709@pabloem
* Fix FhirLROIT tests
* Fix FhirLROIT tests | sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/healthcare/FhirIOLROIT.java | [BEAM-10871] Fix FhirLROIT tests (again) (#12908) |
|
Java | apache-2.0 | af4d03cf0455c45c67d8412f56db254b343eb286 | 0 | wanggc/mongo-java-driver,gianpaj/mongo-java-driver,rozza/mongo-java-driver,davydotcom/mongo-java-driver,PSCGroup/mongo-java-driver,wanggc/mongo-java-driver,rozza/mongo-java-driver,jyemin/mongo-java-driver,jsonking/mongo-java-driver,jyemin/mongo-java-driver,kay-kim/mongo-java-driver,davydotcom/mongo-java-driver,jsonking/mongo-java-driver | /**
* Copyright (C) 2008 10gen Inc.
*
* 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.mongodb.gridfs;
import java.io.*;
import java.util.List;
import org.testng.annotations.*;
import com.mongodb.*;
import com.mongodb.util.*;
public class GridFSTest extends TestCase {
public GridFSTest()
throws IOException , MongoException {
super();
try {
cleanupMongo = new Mongo( "127.0.0.1" );
cleanupDB = "com_mongodb_unittest_GridFSTest";
_db = cleanupMongo.getDB( cleanupDB );
_fs = new GridFS( _db );
}
catch ( MongoException e ){
e.printStackTrace();
throw e;
}
catch ( IOException io ){
io.printStackTrace();
throw io;
}
catch ( RuntimeException re ){
re.printStackTrace();
throw re;
}
catch ( Throwable t ){
t.printStackTrace();
throw new RuntimeException( t );
}
}
int[] _get(){
int[] i = new int[2];
i[0] = _fs._filesCollection.find().count();
i[1] = _fs._chunkCollection.find().count();
return i;
}
void testInOut( String s )
throws Exception {
int[] start = _get();
GridFSInputFile in = _fs.createFile( s.getBytes() );
in.save();
GridFSDBFile out = _fs.findOne( new BasicDBObject( "_id" , in.getId() ) );
assert( out.getId().equals( in.getId() ) );
assert( out.getChunkSize() == (long)GridFS.DEFAULT_CHUNKSIZE );
ByteArrayOutputStream bout = new ByteArrayOutputStream();
out.writeTo( bout );
String outString = new String( bout.toByteArray() );
assert( outString.equals( s ) );
out.remove();
int[] end = _get();
assertEquals( start[0] , end[0] );
assertEquals( start[1] , end[1] );
}
@Test(groups = {"basic"})
public void testSmall()
throws Exception {
testInOut( "this is a simple test" );
}
@Test(groups = {"basic"})
public void testBig()
throws Exception {
int target = GridFS.DEFAULT_CHUNKSIZE * 3;
StringBuilder buf = new StringBuilder( target );
while ( buf.length() < target )
buf.append( "asdasdkjasldkjasldjlasjdlajsdljasldjlasjdlkasjdlaskjdlaskjdlsakjdlaskjdasldjsad" );
String s = buf.toString();
testInOut( s );
}
void testOutStream( String s ) throws Exception {
int[] start = _get();
GridFSInputFile in = _fs.createFile();
OutputStream writeStream = in.getOutputStream();
writeStream.write( s.getBytes(), 0, s.length() );
writeStream.close();
GridFSDBFile out = _fs.findOne( new BasicDBObject( "_id" , in.getId() ) );
assert ( out.getId().equals( in.getId() ) );
assert ( out.getChunkSize() == (long) GridFS.DEFAULT_CHUNKSIZE );
ByteArrayOutputStream bout = new ByteArrayOutputStream();
out.writeTo( bout );
String outString = new String( bout.toByteArray() );
assert (outString.equals( s ));
out.remove();
int[] end = _get();
assertEquals( start[0], end[0] );
assertEquals( start[1], end[1] );
}
@Test(groups = { "basic" })
public void testOutStreamSmall() throws Exception {
testOutStream( "this is a simple test" );
}
@Test(groups = { "basic" })
public void testOutStreamBig() throws Exception {
int target = (int) (GridFS.DEFAULT_CHUNKSIZE * 3.5);
StringBuilder buf = new StringBuilder( target );
while ( buf.length() < target ) {
buf.append( "asdasdkjasldkjasldjlasjdlajsdljasldjlasjdlkasjdlaskjdlaskjdlsakjdlaskjdasldjsad" );
}
String s = buf.toString();
testOutStream( s );
}
@Test(groups = { "basic" })
public void testOutStreamBigAligned() throws Exception {
int target = (GridFS.DEFAULT_CHUNKSIZE * 4);
StringBuilder buf = new StringBuilder( target );
while ( buf.length() < target ) {
buf.append( "a" );
}
String s = buf.toString();
testOutStream( s );
}
@Test(groups = {"basic"})
public void testMetadata()
throws Exception {
GridFSInputFile in = _fs.createFile( "foo".getBytes() );
in.put("meta", 5);
in.save();
GridFSDBFile out = _fs.findOne( new BasicDBObject( "_id" , in.getId() ) );
assert( out.get("meta").equals( 5 ) );
}
@Test(groups = {"basic"})
public void testBadChunkSize() throws Exception {
int fileSize = (int)(2 * GridFS.MAX_CHUNKSIZE);
if (fileSize > 1024 * 1024 * 1024)
//If this is the case, GridFS is probably obsolete...
fileSize = 10 * 1024 * 1024;
byte[] randomBytes = new byte[fileSize];
for (int idx = 0; idx < fileSize; ++idx)
randomBytes[idx] = (byte)(256 * Math.random());
GridFSInputFile inputFile = _fs.createFile(randomBytes);
inputFile.setFilename("bad_chunk_size.bin");
try{
inputFile.save(0);
fail("should have received an exception about a chunk size being zero");
}catch(MongoException mongoExc) {
//We expect this exception to complain about the chunksize
assertTrue(mongoExc.toString().contains("chunkSize must be greater than zero"));
}
try{
inputFile.save(GridFS.MAX_CHUNKSIZE + 10);
fail("should have received an exception about a chunk size being too big");
}catch(MongoException mongoExc) {
//also expecting it to complain about the chunkSize
assertTrue(mongoExc.toString().contains("and less than or equal to GridFS.MAX_CHUNKSIZE"));
}
//For good measure let's save and restore the bytes
inputFile.save(GridFS.MAX_CHUNKSIZE / 2);
GridFSDBFile savedFile = _fs.findOne(new BasicDBObject("_id", inputFile.getId()));
ByteArrayOutputStream savedFileByteStream = new ByteArrayOutputStream();
savedFile.writeTo(savedFileByteStream);
byte[] savedFileBytes = savedFileByteStream.toByteArray();
assertArrayEquals(randomBytes, savedFileBytes);
}
@Test(groups = {"basic"})
public void getBigChunkSize() throws Exception {
GridFSInputFile file = _fs.createFile("512kb_bucket");
file.setChunkSize(file.getChunkSize() * 2);
OutputStream os = file.getOutputStream();
for (int i = 0; i < 1024; i++) {
os.write(new byte[GridFS.DEFAULT_CHUNKSIZE / 1024 + 1]);
}
os.close();
}
@Test(groups = {"basic"})
public void testInputStreamSkipping() throws Exception {
//int chunkSize = 5;
int chunkSize = GridFS.DEFAULT_CHUNKSIZE;
int fileSize = (int)(7.25 * chunkSize);
byte[] fileBytes = new byte[fileSize];
for (int idx = 0; idx < fileSize; ++idx)
fileBytes[idx] = (byte)(idx % 251);
//Don't want chunks to be aligned at byte position 0
GridFSInputFile inputFile = _fs.createFile(fileBytes);
inputFile.setFilename("input_stream_skipping.bin");
inputFile.save(chunkSize);
GridFSDBFile savedFile = _fs.findOne(new BasicDBObject("_id", inputFile.getId()));
GridFSDBFile.MyInputStream inputStream = (GridFSDBFile.MyInputStream)savedFile.getInputStream();
//Quick run-through, make sure the file is as expected
for (int idx = 0; idx < fileSize; ++idx)
assertEquals((byte)(idx % 251), (byte)inputStream.read());
inputStream = (GridFSDBFile.MyInputStream)savedFile.getInputStream();
long skipped = inputStream.skip(1);
assertEquals(1, skipped);
int position = 1;
assertEquals((byte)(position++ % 251), (byte)inputStream.read());
skipped = inputStream.skip(chunkSize);
assertEquals(chunkSize, skipped);
position += chunkSize;
assertEquals((byte)(position++ % 251), (byte)inputStream.read());
skipped = inputStream.skip(-1);
assertEquals(0, skipped);
skipped = inputStream.skip(0);
assertEquals(0, skipped);
skipped = inputStream.skip(3 * chunkSize);
assertEquals(3 * chunkSize, skipped);
position += 3 * chunkSize;
assertEquals((byte)(position++ % 251), (byte)inputStream.read());
//Make sure skipping works when we skip to an exact chunk boundary
long toSkip = inputStream.available();
skipped = inputStream.skip(toSkip);
assertEquals(toSkip, skipped);
position += toSkip;
assertEquals((byte)(position++ % 251), (byte)inputStream.read());
skipped = inputStream.skip(2 * fileSize);
assertEquals(fileSize - position, skipped);
assertEquals(-1, inputStream.read());
}
@Test(groups = {"basic"})
public void testCustomFileID() throws IOException {
int chunkSize = 10;
int fileSize = (int)(3.25 * chunkSize);
byte[] fileBytes = new byte[fileSize];
for (int idx = 0; idx < fileSize; ++idx)
fileBytes[idx] = (byte)(idx % 251);
GridFSInputFile inputFile = _fs.createFile(fileBytes);
int id = 1;
inputFile.setId(id);
inputFile.setFilename("custom_file_id.bin");
inputFile.save(chunkSize);
assertEquals(id, inputFile.getId());
GridFSDBFile savedFile = _fs.findOne(new BasicDBObject("_id", id));
InputStream inputStream = savedFile.getInputStream();
for (int idx = 0; idx < fileSize; ++idx)
assertEquals((byte)(idx % 251), (byte)inputStream.read());
}
@Test(groups = {"basic"})
public void testGetFileListWithSorting() throws Exception {
_fs.remove(new BasicDBObject());
int chunkSize = 10;
int fileSize = (int)(3.25 * chunkSize);
byte[] fileBytes = new byte[fileSize];
for (int idx = 0; idx < fileSize; ++idx)
fileBytes[idx] = (byte)(idx % 251);
GridFSInputFile inputFile;
for (int i = 1; i < 5; i++){
inputFile = _fs.createFile(fileBytes);
inputFile.setId(i);
inputFile.setFilename("custom_file_id" + i + ".bin");
inputFile.put("orderTest", i + "");
inputFile.save(chunkSize);
}
DBCursor cursor = _fs.getFileList(null,new BasicDBObject("orderTest", 1));
assertEquals(cursor.size(),4);
assertEquals(cursor.next().get("_id"),1);
assertEquals(cursor.next().get("_id"),2);
assertEquals(cursor.next().get("_id"),3);
assertEquals(cursor.next().get("_id"),4);
cursor = _fs.getFileList(null,new BasicDBObject("filename", -1));
assertEquals(cursor.size(),4);
assertEquals(cursor.next().get("_id"),4);
assertEquals(cursor.next().get("_id"),3);
assertEquals(cursor.next().get("_id"),2);
assertEquals(cursor.next().get("_id"),1);
}
@Test(groups = {"basic"})
public void testFindWithSorting() throws Exception {
_fs.remove(new BasicDBObject());
int chunkSize = 10;
int fileSize = (int)(3.25 * chunkSize);
byte[] fileBytes = new byte[fileSize];
for (int idx = 0; idx < fileSize; ++idx)
fileBytes[idx] = (byte)(idx % 251);
GridFSInputFile inputFile;
for (int i = 1; i < 5; i++){
inputFile = _fs.createFile(fileBytes);
inputFile.setId(i);
inputFile.setFilename("custom_file_id"+i+".bin");
inputFile.put("orderTest", i+"");
inputFile.save(chunkSize);
}
List<GridFSDBFile> result = _fs.find(new BasicDBObject(), new BasicDBObject("orderTest", 1));
assertEquals(result.size(),4);
assertEquals(result.get(0).getId(),1);
assertEquals(result.get(1).getId(),2);
assertEquals(result.get(2).getId(),3);
assertEquals(result.get(3).getId(),4);
result = _fs.find(new BasicDBObject(), new BasicDBObject("filename", -1));
assertEquals(result.size(),4);
assertEquals(result.get(0).getId(),4);
assertEquals(result.get(1).getId(),3);
assertEquals(result.get(2).getId(),2);
assertEquals(result.get(3).getId(),1);
}
final DB _db;
final GridFS _fs;
public static void main( String args[] )
throws Exception {
(new GridFSTest()).runConsole();
}
}
| src/test/com/mongodb/gridfs/GridFSTest.java | /**
* Copyright (C) 2008 10gen Inc.
*
* 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.mongodb.gridfs;
import java.io.*;
import org.testng.annotations.*;
import com.mongodb.*;
import com.mongodb.util.*;
public class GridFSTest extends TestCase {
public GridFSTest()
throws IOException , MongoException {
super();
try {
cleanupMongo = new Mongo( "127.0.0.1" );
cleanupDB = "com_mongodb_unittest_GridFSTest";
_db = cleanupMongo.getDB( cleanupDB );
_fs = new GridFS( _db );
}
catch ( MongoException e ){
e.printStackTrace();
throw e;
}
catch ( IOException io ){
io.printStackTrace();
throw io;
}
catch ( RuntimeException re ){
re.printStackTrace();
throw re;
}
catch ( Throwable t ){
t.printStackTrace();
throw new RuntimeException( t );
}
}
int[] _get(){
int[] i = new int[2];
i[0] = _fs._filesCollection.find().count();
i[1] = _fs._chunkCollection.find().count();
return i;
}
void testInOut( String s )
throws Exception {
int[] start = _get();
GridFSInputFile in = _fs.createFile( s.getBytes() );
in.save();
GridFSDBFile out = _fs.findOne( new BasicDBObject( "_id" , in.getId() ) );
assert( out.getId().equals( in.getId() ) );
assert( out.getChunkSize() == (long)GridFS.DEFAULT_CHUNKSIZE );
ByteArrayOutputStream bout = new ByteArrayOutputStream();
out.writeTo( bout );
String outString = new String( bout.toByteArray() );
assert( outString.equals( s ) );
out.remove();
int[] end = _get();
assertEquals( start[0] , end[0] );
assertEquals( start[1] , end[1] );
}
@Test(groups = {"basic"})
public void testSmall()
throws Exception {
testInOut( "this is a simple test" );
}
@Test(groups = {"basic"})
public void testBig()
throws Exception {
int target = GridFS.DEFAULT_CHUNKSIZE * 3;
StringBuilder buf = new StringBuilder( target );
while ( buf.length() < target )
buf.append( "asdasdkjasldkjasldjlasjdlajsdljasldjlasjdlkasjdlaskjdlaskjdlsakjdlaskjdasldjsad" );
String s = buf.toString();
testInOut( s );
}
void testOutStream( String s ) throws Exception {
int[] start = _get();
GridFSInputFile in = _fs.createFile();
OutputStream writeStream = in.getOutputStream();
writeStream.write( s.getBytes(), 0, s.length() );
writeStream.close();
GridFSDBFile out = _fs.findOne( new BasicDBObject( "_id" , in.getId() ) );
assert ( out.getId().equals( in.getId() ) );
assert ( out.getChunkSize() == (long) GridFS.DEFAULT_CHUNKSIZE );
ByteArrayOutputStream bout = new ByteArrayOutputStream();
out.writeTo( bout );
String outString = new String( bout.toByteArray() );
assert (outString.equals( s ));
out.remove();
int[] end = _get();
assertEquals( start[0], end[0] );
assertEquals( start[1], end[1] );
}
@Test(groups = { "basic" })
public void testOutStreamSmall() throws Exception {
testOutStream( "this is a simple test" );
}
@Test(groups = { "basic" })
public void testOutStreamBig() throws Exception {
int target = (int) (GridFS.DEFAULT_CHUNKSIZE * 3.5);
StringBuilder buf = new StringBuilder( target );
while ( buf.length() < target ) {
buf.append( "asdasdkjasldkjasldjlasjdlajsdljasldjlasjdlkasjdlaskjdlaskjdlsakjdlaskjdasldjsad" );
}
String s = buf.toString();
testOutStream( s );
}
@Test(groups = { "basic" })
public void testOutStreamBigAligned() throws Exception {
int target = (GridFS.DEFAULT_CHUNKSIZE * 4);
StringBuilder buf = new StringBuilder( target );
while ( buf.length() < target ) {
buf.append( "a" );
}
String s = buf.toString();
testOutStream( s );
}
@Test(groups = {"basic"})
public void testMetadata()
throws Exception {
GridFSInputFile in = _fs.createFile( "foo".getBytes() );
in.put("meta", 5);
in.save();
GridFSDBFile out = _fs.findOne( new BasicDBObject( "_id" , in.getId() ) );
assert( out.get("meta").equals( 5 ) );
}
@Test(groups = {"basic"})
public void testBadChunkSize() throws Exception {
int fileSize = (int)(2 * GridFS.MAX_CHUNKSIZE);
if (fileSize > 1024 * 1024 * 1024)
//If this is the case, GridFS is probably obsolete...
fileSize = 10 * 1024 * 1024;
byte[] randomBytes = new byte[fileSize];
for (int idx = 0; idx < fileSize; ++idx)
randomBytes[idx] = (byte)(256 * Math.random());
GridFSInputFile inputFile = _fs.createFile(randomBytes);
inputFile.setFilename("bad_chunk_size.bin");
try{
inputFile.save(0);
fail("should have received an exception about a chunk size being zero");
}catch(MongoException mongoExc) {
//We expect this exception to complain about the chunksize
assertTrue(mongoExc.toString().contains("chunkSize must be greater than zero"));
}
try{
inputFile.save(GridFS.MAX_CHUNKSIZE + 10);
fail("should have received an exception about a chunk size being too big");
}catch(MongoException mongoExc) {
//also expecting it to complain about the chunkSize
assertTrue(mongoExc.toString().contains("and less than or equal to GridFS.MAX_CHUNKSIZE"));
}
//For good measure let's save and restore the bytes
inputFile.save(GridFS.MAX_CHUNKSIZE / 2);
GridFSDBFile savedFile = _fs.findOne(new BasicDBObject("_id", inputFile.getId()));
ByteArrayOutputStream savedFileByteStream = new ByteArrayOutputStream();
savedFile.writeTo(savedFileByteStream);
byte[] savedFileBytes = savedFileByteStream.toByteArray();
assertArrayEquals(randomBytes, savedFileBytes);
}
@Test(groups = {"basic"})
public void getBigChunkSize() throws Exception {
GridFSInputFile file = _fs.createFile("512kb_bucket");
file.setChunkSize(file.getChunkSize() * 2);
OutputStream os = file.getOutputStream();
for (int i = 0; i < 1024; i++) {
os.write(new byte[GridFS.DEFAULT_CHUNKSIZE / 1024 + 1]);
}
os.close();
}
@Test(groups = {"basic"})
public void testInputStreamSkipping() throws Exception {
//int chunkSize = 5;
int chunkSize = GridFS.DEFAULT_CHUNKSIZE;
int fileSize = (int)(7.25 * chunkSize);
byte[] fileBytes = new byte[fileSize];
for (int idx = 0; idx < fileSize; ++idx)
fileBytes[idx] = (byte)(idx % 251);
//Don't want chunks to be aligned at byte position 0
GridFSInputFile inputFile = _fs.createFile(fileBytes);
inputFile.setFilename("input_stream_skipping.bin");
inputFile.save(chunkSize);
GridFSDBFile savedFile = _fs.findOne(new BasicDBObject("_id", inputFile.getId()));
GridFSDBFile.MyInputStream inputStream = (GridFSDBFile.MyInputStream)savedFile.getInputStream();
//Quick run-through, make sure the file is as expected
for (int idx = 0; idx < fileSize; ++idx)
assertEquals((byte)(idx % 251), (byte)inputStream.read());
inputStream = (GridFSDBFile.MyInputStream)savedFile.getInputStream();
long skipped = inputStream.skip(1);
assertEquals(1, skipped);
int position = 1;
assertEquals((byte)(position++ % 251), (byte)inputStream.read());
skipped = inputStream.skip(chunkSize);
assertEquals(chunkSize, skipped);
position += chunkSize;
assertEquals((byte)(position++ % 251), (byte)inputStream.read());
skipped = inputStream.skip(-1);
assertEquals(0, skipped);
skipped = inputStream.skip(0);
assertEquals(0, skipped);
skipped = inputStream.skip(3 * chunkSize);
assertEquals(3 * chunkSize, skipped);
position += 3 * chunkSize;
assertEquals((byte)(position++ % 251), (byte)inputStream.read());
//Make sure skipping works when we skip to an exact chunk boundary
long toSkip = inputStream.available();
skipped = inputStream.skip(toSkip);
assertEquals(toSkip, skipped);
position += toSkip;
assertEquals((byte)(position++ % 251), (byte)inputStream.read());
skipped = inputStream.skip(2 * fileSize);
assertEquals(fileSize - position, skipped);
assertEquals(-1, inputStream.read());
}
@Test(groups = {"basic"})
public void testCustomFileID() throws IOException {
int chunkSize = 10;
int fileSize = (int)(3.25 * chunkSize);
byte[] fileBytes = new byte[fileSize];
for (int idx = 0; idx < fileSize; ++idx)
fileBytes[idx] = (byte)(idx % 251);
GridFSInputFile inputFile = _fs.createFile(fileBytes);
int id = 1;
inputFile.setId(id);
inputFile.setFilename("custom_file_id.bin");
inputFile.save(chunkSize);
assertEquals(id, inputFile.getId());
GridFSDBFile savedFile = _fs.findOne(new BasicDBObject("_id", id));
InputStream inputStream = savedFile.getInputStream();
for (int idx = 0; idx < fileSize; ++idx)
assertEquals((byte)(idx % 251), (byte)inputStream.read());
}
final DB _db;
final GridFS _fs;
public static void main( String args[] )
throws Exception {
(new GridFSTest()).runConsole();
}
}
| JAVA-431 the find() method of GridFS should can be sorted
- added test for both methods for sorting
| src/test/com/mongodb/gridfs/GridFSTest.java | JAVA-431 the find() method of GridFS should can be sorted - added test for both methods for sorting |
|
Java | apache-2.0 | 31ffbf22bed82a0808ec4d800123c8b22175d4bb | 0 | SRCB-CloudPart/ngrinder,bwahn/ngrinder,GwonGisoo/ngrinder,bwahn/ngrinder,songeunwoo/ngrinder,songeunwoo/ngrinder,GwonGisoo/ngrinder,naver/ngrinder,nanpa83/ngrinder,SRCB-CloudPart/ngrinder,SRCB-CloudPart/ngrinder,ropik/ngrinder,chengaomin/ngrinder,ropik/ngrinder,naver/ngrinder,naver/ngrinder,nanpa83/ngrinder,chengaomin/ngrinder,nanpa83/ngrinder,bwahn/ngrinder,GwonGisoo/ngrinder,naver/ngrinder,songeunwoo/ngrinder,GwonGisoo/ngrinder,songeunwoo/ngrinder,nanpa83/ngrinder,SRCB-CloudPart/ngrinder,chengaomin/ngrinder,ropik/ngrinder,naver/ngrinder,GwonGisoo/ngrinder,chengaomin/ngrinder,chengaomin/ngrinder,songeunwoo/ngrinder,bwahn/ngrinder,bwahn/ngrinder,SRCB-CloudPart/ngrinder,ropik/ngrinder,nanpa83/ngrinder | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ngrinder.infra.init;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import liquibase.database.Database;
import liquibase.database.DatabaseFactory;
import liquibase.database.core.H2ExTypeConverter;
import liquibase.database.jvm.JdbcConnection;
import liquibase.database.typeconversion.TypeConverterFactory;
import liquibase.exception.LiquibaseException;
import liquibase.resource.ClassLoaderResourceAccessor;
import liquibase.sqlgenerator.SqlGeneratorFactory;
import liquibase.sqlgenerator.core.NGrinderRenameColumnGenerator;
import liquibase.sqlgenerator.core.RenameColumnGenerator;
import org.ngrinder.common.exception.NGrinderRuntimeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
/**
* DB Data Updater. This class is used to update DB automatically when System restarted through log
* file db.changelog.xml
*
* @author Matt
* @author JunHo Yoon
* @since 3.0
*/
@Service
@DependsOn("dataSource")
public class DatabaseUpdater implements ResourceLoaderAware {
@Autowired
private DataSource dataSource;
private String changeLog = "ngrinder_datachange_logfile/db.changelog.xml";
private String contexts;
private ResourceLoader resourceLoader;
private Database getDatabase() {
try {
Database databaseImplementation = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(
new JdbcConnection(dataSource.getConnection()));
return databaseImplementation;
} catch (Exception e) {
throw new NGrinderRuntimeException("Error getting database", e);
}
}
public String getChangeLog() {
return changeLog;
}
public void setChangeLog(String changeLog) {
this.changeLog = changeLog;
}
/**
* Automated updates DB after nGrinder has load with all bean properties.
*
* @throws Exception
* occurs when db update is failed.
*/
@PostConstruct
public void init() throws Exception {
SqlGeneratorFactory.getInstance().register(new LockExDatabaseChangeLogGenerator());
TypeConverterFactory.getInstance().register(H2ExTypeConverter.class);
LiquibaseEx liquibase = new LiquibaseEx(getChangeLog(), new ClassLoaderResourceAccessor(getResourceLoader()
.getClassLoader()), getDatabase());
SqlGeneratorFactory.getInstance().unregister(new RenameColumnGenerator());
SqlGeneratorFactory.getInstance().register(new NGrinderRenameColumnGenerator());
try {
liquibase.update(contexts);
} catch (LiquibaseException e) {
throw new NGrinderRuntimeException("Exception occurs while Liquibase update DB", e);
}
}
public ResourceLoader getResourceLoader() {
return resourceLoader;
}
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
}
| ngrinder-controller/src/main/java/org/ngrinder/infra/init/DatabaseUpdater.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ngrinder.infra.init;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import liquibase.database.Database;
import liquibase.database.DatabaseFactory;
import liquibase.database.core.H2ExTypeConverter;
import liquibase.database.jvm.JdbcConnection;
import liquibase.database.typeconversion.TypeConverterFactory;
import liquibase.exception.LiquibaseException;
import liquibase.resource.ClassLoaderResourceAccessor;
import liquibase.sqlgenerator.SqlGeneratorFactory;
import liquibase.sqlgenerator.core.NGrinderRenameColumnGenerator;
import liquibase.sqlgenerator.core.RenameColumnGenerator;
import org.ngrinder.common.exception.NGrinderRuntimeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
/**
* DB Data Updater. This class is used to update DB automatically when System restarted through log
* file db.changelog.xml
*
* @author Matt
* @author JunHo Yoon
* @since 3.0
*/
@Service
@DependsOn("dataSource")
public class DatabaseUpdater implements ResourceLoaderAware {
@Autowired
private DataSource dataSource;
private String changeLog = "ngrinder_datachange_logfile/db.changelog.xml";
private String contexts;
private ResourceLoader resourceLoader;
private Database getDatabase() {
try {
Database databaseImplementation = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(
new JdbcConnection(dataSource.getConnection()));
return databaseImplementation;
} catch (Exception e) {
throw new NGrinderRuntimeException("Error getting database", e);
}
}
public String getChangeLog() {
return changeLog;
}
public void setChangeLog(String changeLog) {
this.changeLog = changeLog;
}
/**
* Automated updates DB after nGrinder has load with all bean properties.
*
* @throws Exception
* occurs when db update is failed.
*/
@PostConstruct
public void init() throws Exception {
SqlGeneratorFactory.getInstance().register(new LockExDatabaseChangeLogGenerator());
SqlGeneratorFactory.getInstance().unregister(new RenameColumnGenerator());
SqlGeneratorFactory.getInstance().register(new NGrinderRenameColumnGenerator());
TypeConverterFactory.getInstance().register(H2ExTypeConverter.class);
LiquibaseEx liquibase = new LiquibaseEx(getChangeLog(), new ClassLoaderResourceAccessor(getResourceLoader()
.getClassLoader()), getDatabase());
try {
liquibase.update(contexts);
} catch (LiquibaseException e) {
throw new NGrinderRuntimeException("Exception occurs while Liquibase update DB", e);
}
}
public ResourceLoader getResourceLoader() {
return resourceLoader;
}
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
}
| [NOBTS]create NGrinderRenameColumnGenerator to replace
RenameColumnGenerator | ngrinder-controller/src/main/java/org/ngrinder/infra/init/DatabaseUpdater.java | [NOBTS]create NGrinderRenameColumnGenerator to replace RenameColumnGenerator |
|
Java | apache-2.0 | adf1007cca44e1f4dbd8b3a0d4cfaa9665898439 | 0 | merlimat/pulsar,merlimat/pulsar,merlimat/pulsar,yahoo/pulsar,yahoo/pulsar,massakam/pulsar,yahoo/pulsar,massakam/pulsar,merlimat/pulsar,merlimat/pulsar,yahoo/pulsar,massakam/pulsar,massakam/pulsar,massakam/pulsar,merlimat/pulsar,yahoo/pulsar,yahoo/pulsar,massakam/pulsar | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.metadata;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import lombok.Cleanup;
import org.apache.pulsar.metadata.api.MetadataStoreConfig;
import org.apache.pulsar.metadata.api.coordination.CoordinationService;
import org.apache.pulsar.metadata.api.coordination.LeaderElection;
import org.apache.pulsar.metadata.api.coordination.LeaderElectionState;
import org.apache.pulsar.metadata.api.coordination.LockManager;
import org.apache.pulsar.metadata.api.coordination.ResourceLock;
import org.apache.pulsar.metadata.api.extended.MetadataStoreExtended;
import org.apache.pulsar.metadata.api.extended.SessionEvent;
import org.apache.pulsar.metadata.coordination.impl.CoordinationServiceImpl;
import org.apache.pulsar.metadata.impl.ZKMetadataStore;
import org.awaitility.Awaitility;
import org.testng.annotations.Test;
public class ZKSessionTest extends BaseMetadataStoreTest {
@Test
public void testDisconnection() throws Exception {
@Cleanup
MetadataStoreExtended store = MetadataStoreExtended.create(zks.getConnectionString(),
MetadataStoreConfig.builder()
.sessionTimeoutMillis(30_000)
.build());
BlockingQueue<SessionEvent> sessionEvents = new LinkedBlockingQueue<>();
store.registerSessionListener(sessionEvents::add);
zks.stop();
SessionEvent e = sessionEvents.poll(5, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.ConnectionLost);
zks.start();
e = sessionEvents.poll(20, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.Reconnected);
e = sessionEvents.poll(5, TimeUnit.SECONDS);
assertNull(e);
}
@Test
public void testSessionLost() throws Exception {
@Cleanup
MetadataStoreExtended store = MetadataStoreExtended.create(zks.getConnectionString(),
MetadataStoreConfig.builder()
.sessionTimeoutMillis(10_000)
.build());
BlockingQueue<SessionEvent> sessionEvents = new LinkedBlockingQueue<>();
store.registerSessionListener(sessionEvents::add);
zks.stop();
SessionEvent e = sessionEvents.poll(5, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.ConnectionLost);
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.SessionLost);
zks.start();
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.Reconnected);
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.SessionReestablished);
e = sessionEvents.poll(1, TimeUnit.SECONDS);
assertNull(e);
}
@Test
public void testReacquireLocksAfterSessionLost() throws Exception {
@Cleanup
MetadataStoreExtended store = MetadataStoreExtended.create(zks.getConnectionString(),
MetadataStoreConfig.builder()
.sessionTimeoutMillis(2_000)
.build());
BlockingQueue<SessionEvent> sessionEvents = new LinkedBlockingQueue<>();
store.registerSessionListener(sessionEvents::add);
@Cleanup
CoordinationService coordinationService = new CoordinationServiceImpl(store);
@Cleanup
LockManager<String> lm1 = coordinationService.getLockManager(String.class);
String path = newKey();
ResourceLock<String> lock = lm1.acquireLock(path, "value-1").join();
zks.expireSession(((ZKMetadataStore) store).getZkSessionId());
SessionEvent e = sessionEvents.poll(5, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.ConnectionLost);
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.SessionLost);
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.Reconnected);
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.SessionReestablished);
Awaitility.waitAtMost(30, TimeUnit.SECONDS).untilAsserted(() -> {
assertFalse(lock.getLockExpiredFuture().isDone());
});
assertTrue(store.get(path).join().isPresent());
}
@Test
public void testReacquireLeadershipAfterSessionLost() throws Exception {
// --- init
@Cleanup
MetadataStoreExtended store = MetadataStoreExtended.create(zks.getConnectionString(),
MetadataStoreConfig.builder()
.sessionTimeoutMillis(2_000)
.build());
BlockingQueue<SessionEvent> sessionEvents = new LinkedBlockingQueue<>();
store.registerSessionListener(sessionEvents::add);
BlockingQueue<LeaderElectionState> leaderElectionEvents = new LinkedBlockingQueue<>();
String path = newKey();
@Cleanup
CoordinationService coordinationService = new CoordinationServiceImpl(store);
@Cleanup
LeaderElection<String> le1 = coordinationService.getLeaderElection(String.class, path,
leaderElectionEvents::add);
// --- test manual elect
le1.elect("value-1").join();
assertEquals(le1.getState(), LeaderElectionState.Leading);
LeaderElectionState les = leaderElectionEvents.poll(5, TimeUnit.SECONDS);
assertEquals(les, LeaderElectionState.Leading);
// --- expire session
zks.expireSession(((ZKMetadataStore) store).getZkSessionId());
SessionEvent e = sessionEvents.poll(5, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.ConnectionLost);
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.SessionLost);
// --- test le1 can be leader
Awaitility.await()
.untilAsserted(()-> assertEquals(le1.getState(),LeaderElectionState.Leading)); // reacquire leadership
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.Reconnected);
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.SessionReestablished);
Awaitility.await()
.untilAsserted(()-> assertEquals(le1.getState(),LeaderElectionState.Leading));
assertTrue(store.get(path).join().isPresent());
}
}
| pulsar-metadata/src/test/java/org/apache/pulsar/metadata/ZKSessionTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.metadata;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import lombok.Cleanup;
import org.apache.pulsar.metadata.api.MetadataStoreConfig;
import org.apache.pulsar.metadata.api.coordination.CoordinationService;
import org.apache.pulsar.metadata.api.coordination.LeaderElection;
import org.apache.pulsar.metadata.api.coordination.LeaderElectionState;
import org.apache.pulsar.metadata.api.coordination.LockManager;
import org.apache.pulsar.metadata.api.coordination.ResourceLock;
import org.apache.pulsar.metadata.api.extended.MetadataStoreExtended;
import org.apache.pulsar.metadata.api.extended.SessionEvent;
import org.apache.pulsar.metadata.coordination.impl.CoordinationServiceImpl;
import org.apache.pulsar.metadata.impl.ZKMetadataStore;
import org.awaitility.Awaitility;
import org.testng.annotations.Test;
public class ZKSessionTest extends BaseMetadataStoreTest {
@Test
public void testDisconnection() throws Exception {
@Cleanup
MetadataStoreExtended store = MetadataStoreExtended.create(zks.getConnectionString(),
MetadataStoreConfig.builder()
.sessionTimeoutMillis(30_000)
.build());
BlockingQueue<SessionEvent> sessionEvents = new LinkedBlockingQueue<>();
store.registerSessionListener(sessionEvents::add);
zks.stop();
SessionEvent e = sessionEvents.poll(5, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.ConnectionLost);
zks.start();
e = sessionEvents.poll(20, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.Reconnected);
e = sessionEvents.poll(5, TimeUnit.SECONDS);
assertNull(e);
}
@Test
public void testSessionLost() throws Exception {
@Cleanup
MetadataStoreExtended store = MetadataStoreExtended.create(zks.getConnectionString(),
MetadataStoreConfig.builder()
.sessionTimeoutMillis(10_000)
.build());
BlockingQueue<SessionEvent> sessionEvents = new LinkedBlockingQueue<>();
store.registerSessionListener(sessionEvents::add);
zks.stop();
SessionEvent e = sessionEvents.poll(5, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.ConnectionLost);
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.SessionLost);
zks.start();
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.Reconnected);
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.SessionReestablished);
e = sessionEvents.poll(1, TimeUnit.SECONDS);
assertNull(e);
}
@Test
public void testReacquireLocksAfterSessionLost() throws Exception {
@Cleanup
MetadataStoreExtended store = MetadataStoreExtended.create(zks.getConnectionString(),
MetadataStoreConfig.builder()
.sessionTimeoutMillis(2_000)
.build());
BlockingQueue<SessionEvent> sessionEvents = new LinkedBlockingQueue<>();
store.registerSessionListener(sessionEvents::add);
@Cleanup
CoordinationService coordinationService = new CoordinationServiceImpl(store);
@Cleanup
LockManager<String> lm1 = coordinationService.getLockManager(String.class);
String path = newKey();
ResourceLock<String> lock = lm1.acquireLock(path, "value-1").join();
zks.expireSession(((ZKMetadataStore) store).getZkSessionId());
SessionEvent e = sessionEvents.poll(5, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.ConnectionLost);
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.SessionLost);
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.Reconnected);
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.SessionReestablished);
Awaitility.await().untilAsserted(() -> {
assertFalse(lock.getLockExpiredFuture().isDone());
});
assertTrue(store.get(path).join().isPresent());
}
@Test
public void testReacquireLeadershipAfterSessionLost() throws Exception {
// --- init
@Cleanup
MetadataStoreExtended store = MetadataStoreExtended.create(zks.getConnectionString(),
MetadataStoreConfig.builder()
.sessionTimeoutMillis(2_000)
.build());
BlockingQueue<SessionEvent> sessionEvents = new LinkedBlockingQueue<>();
store.registerSessionListener(sessionEvents::add);
BlockingQueue<LeaderElectionState> leaderElectionEvents = new LinkedBlockingQueue<>();
String path = newKey();
@Cleanup
CoordinationService coordinationService = new CoordinationServiceImpl(store);
@Cleanup
LeaderElection<String> le1 = coordinationService.getLeaderElection(String.class, path,
leaderElectionEvents::add);
// --- test manual elect
le1.elect("value-1").join();
assertEquals(le1.getState(), LeaderElectionState.Leading);
LeaderElectionState les = leaderElectionEvents.poll(5, TimeUnit.SECONDS);
assertEquals(les, LeaderElectionState.Leading);
// --- expire session
zks.expireSession(((ZKMetadataStore) store).getZkSessionId());
SessionEvent e = sessionEvents.poll(5, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.ConnectionLost);
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.SessionLost);
// --- test le1 can be leader
Awaitility.await()
.untilAsserted(()-> assertEquals(le1.getState(),LeaderElectionState.Leading)); // reacquire leadership
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.Reconnected);
e = sessionEvents.poll(10, TimeUnit.SECONDS);
assertEquals(e, SessionEvent.SessionReestablished);
Awaitility.await()
.untilAsserted(()-> assertEquals(le1.getState(),LeaderElectionState.Leading));
assertTrue(store.get(path).join().isPresent());
}
}
| fix flaky test testReacquireLocksAfterSessionLost (#11815)
### Motivation
Then run ZKSessionTest#testReacquireLocksAfterSessionLost, it will fail occasionally.
Error: testReacquireLocksAfterSessionLost(org.apache.pulsar.metadata.ZKSessionTest) Time elapsed: 12.974 s <<< FAILURE!
org.awaitility.core.ConditionTimeoutException: Assertion condition defined as a lambda expression in org.apache.pulsar.metadata.ZKSessionTest that uses org.apache.pulsar.metadata.api.coordination.ResourceLock expected [false] but found [true] within 10 seconds.
at org.awaitility.core.ConditionAwaiter.await(ConditionAwaiter.java:165)
at org.awaitility.core.AssertionCondition.await(AssertionCondition.java:119)
at org.awaitility.core.AssertionCondition.await(AssertionCondition.java:31)
at org.awaitility.core.ConditionFactory.until(ConditionFactory.java:895)
at org.awaitility.core.ConditionFactory.untilAsserted(ConditionFactory.java:679)
at org.apache.pulsar.metadata.ZKSessionTest.testReacquireLocksAfterSessionLost(ZKSessionTest.java:130)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:132)
at org.testng.internal.InvokeMethodRunnable.runOne(InvokeMethodRunnable.java:45)
at org.testng.internal.InvokeMethodRunnable.call(InvokeMethodRunnable.java:73)
at org.testng.internal.InvokeMethodRunnable.call(InvokeMethodRunnable.java:11)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.lang.AssertionError: expected [false] but found [true]
at org.testng.Assert.fail(Assert.java:99)
at org.testng.Assert.failNotEquals(Assert.java:1037)
at org.testng.Assert.assertFalse(Assert.java:67)
at org.testng.Assert.assertFalse(Assert.java:77)
at org.apache.pulsar.metadata.ZKSessionTest.lambda$testReacquireLocksAfterSessionLost$0(ZKSessionTest.java:131)
at org.awaitility.core.AssertionCondition.lambda$new$0(AssertionCondition.java:53)
at org.awaitility.core.ConditionAwaiter$ConditionPoller.call(ConditionAwaiter.java:222)
at org.awaitility.core.ConditionAwaiter$ConditionPoller.call(ConditionAwaiter.java:209)
... 4 more
### Modification
Change the waiting time from default 10s to 30s. | pulsar-metadata/src/test/java/org/apache/pulsar/metadata/ZKSessionTest.java | fix flaky test testReacquireLocksAfterSessionLost (#11815) |
|
Java | apache-2.0 | 0bf6088d02d3c13e654bdcf6b48732805ccc9658 | 0 | lichtemo/strategoxt,metaborg/strategoxt,Apanatshka/strategoxt,Apanatshka/strategoxt,Apanatshka/strategoxt,lichtemo/strategoxt,Apanatshka/strategoxt,metaborg/strategoxt,Apanatshka/strategoxt,metaborg/strategoxt,lichtemo/strategoxt,lichtemo/strategoxt,metaborg/strategoxt,metaborg/strategoxt,lichtemo/strategoxt | strategoxt-java-backend/src/java/org/strategoxt/NotImplementedException.java | /*
* Created on 17. sep.. 2006
*
* Copyright (c) 2005, Karl Trygve Kalleberg <[email protected]>
*
* Licensed under the GNU General Public License, v2
*/
package org.strategoxt;
public class NotImplementedException extends RuntimeException {
private final String message;
public NotImplementedException() {
message = "Not Implemented";
}
public NotImplementedException(String message) {
this.message = message;
}
private static final long serialVersionUID = -1028814795329444374L;
@Override
public String toString() {
return message;
}
}
| Removed unused file.
svn path=/strc-java/trunk/; revision=19211
| strategoxt-java-backend/src/java/org/strategoxt/NotImplementedException.java | Removed unused file. |
||
Java | apache-2.0 | d2af87d191fb71f57be59c70e05a8c9bf8c656c9 | 0 | littlezhou/SSM-1,huafengw/SSM,littlezhou/SSM-1,huafengw/SSM,Intel-bigdata/SSM,Intel-bigdata/SSM,duzhen1996/SSM,drankye/SSM,drankye/SSM,Intel-bigdata/SSM,drankye/SSM,Intel-bigdata/SSM,duzhen1996/SSM,huafengw/SSM,Intel-bigdata/SSM,littlezhou/SSM-1,littlezhou/SSM-1,duzhen1996/SSM,drankye/SSM,drankye/SSM,littlezhou/SSM-1,huafengw/SSM,littlezhou/SSM-1,duzhen1996/SSM,drankye/SSM,huafengw/SSM,Intel-bigdata/SSM,huafengw/SSM,duzhen1996/SSM,duzhen1996/SSM,drankye/SSM,huafengw/SSM,Intel-bigdata/SSM,duzhen1996/SSM | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartdata.metastore.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartdata.conf.SmartConf;
import org.smartdata.conf.SmartConfKeys;
import org.smartdata.metastore.DruidPool;
import org.smartdata.metastore.MetaStore;
import org.smartdata.metastore.MetaStoreException;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* Utilities for table operations.
*/
public class MetaStoreUtils {
public static final String SQLITE_URL_PREFIX = "jdbc:sqlite:";
public static final String MYSQL_URL_PREFIX = "jdbc:mysql:";
static final Logger LOG = LoggerFactory.getLogger(MetaStoreUtils.class);
public static Connection createConnection(String url,
String userName, String password)
throws ClassNotFoundException, SQLException {
if (url.startsWith(SQLITE_URL_PREFIX)) {
Class.forName("org.sqlite.JDBC");
} else if (url.startsWith(MYSQL_URL_PREFIX)) {
Class.forName("com.mysql.jdbc.Driver");
}
Connection conn = DriverManager.getConnection(url, userName, password);
return conn;
}
public static Connection createConnection(String driver, String url,
String userName,
String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, userName, password);
return conn;
}
public static Connection createSqliteConnection(String dbFilePath)
throws MetaStoreException {
try {
return createConnection("org.sqlite.JDBC", SQLITE_URL_PREFIX + dbFilePath,
null, null);
} catch (Exception e) {
throw new MetaStoreException(e);
}
}
public static void initializeDataBase(
Connection conn) throws MetaStoreException {
String createEmptyTables[] = new String[]{
"DROP TABLE IF EXISTS access_count_tables;",
"DROP TABLE IF EXISTS cached_files;",
"DROP TABLE IF EXISTS ecpolicys;",
"DROP TABLE IF EXISTS files;",
"DROP TABLE IF EXISTS groups;",
"DROP TABLE IF EXISTS owners;",
"DROP TABLE IF EXISTS storages;",
"DROP TABLE IF EXISTS storage_policy;",
"DROP TABLE IF EXISTS xattr;",
"DROP TABLE IF EXISTS datanode_info;",
"DROP TABLE IF EXISTS datanode_storage_info;",
"DROP TABLE IF EXISTS rules;",
"DROP TABLE IF EXISTS cmdlets;",
"DROP TABLE IF EXISTS actions;",
"DROP TABLE IF EXISTS blank_access_count_info;", // for special cases
"DROP TABLE IF EXISTS file_diff;", // incremental diff for disaster recovery
"DROP TABLE IF EXISTS global_config",
"DROP TABLE IF EXISTS cluster_config",
"CREATE TABLE access_count_tables (\n" +
" table_name varchar(255) NOT NULL,\n" +
" start_time bigint(20) NOT NULL,\n" +
" end_time bigint(20) NOT NULL\n" +
") ;",
"CREATE TABLE blank_access_count_info (\n" +
" fid bigint(20) NOT NULL,\n" +
" count bigint(20) NOT NULL\n" +
") ;",
"CREATE TABLE cached_files (\n" +
" fid bigint(20) NOT NULL,\n" +
" path varchar(4096) NOT NULL,\n" +
" from_time bigint(20) NOT NULL,\n" +
" last_access_time bigint(20) NOT NULL,\n" +
" num_accessed int(11) NOT NULL\n" +
") ;",
"CREATE TABLE ecpolicys (\n" +
" id INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" name varchar(255) DEFAULT NULL,\n" +
" cellsize int(11) DEFAULT NULL,\n" +
" numDataUnits int(11) DEFAULT NULL,\n" +
" numParityUnits int(11) DEFAULT NULL,\n" +
" codecName varchar(64) DEFAULT NULL\n" +
") ;",
"CREATE TABLE files (\n" +
" path varchar(4096) NOT NULL,\n" +
" fid bigint(20) NOT NULL,\n" +
" length bigint(20) DEFAULT NULL,\n" +
" block_replication smallint(6) DEFAULT NULL,\n" +
" block_size bigint(20) DEFAULT NULL,\n" +
" modification_time bigint(20) DEFAULT NULL,\n" +
" access_time bigint(20) DEFAULT NULL,\n" +
" is_dir tinyint(1) DEFAULT NULL,\n" +
" sid tinyint(4) DEFAULT NULL,\n" +
" oid smallint(6) DEFAULT NULL,\n" +
" gid smallint(6) DEFAULT NULL,\n" +
" permission smallint(6) DEFAULT NULL,\n" +
" ec_policy_id smallint(6) DEFAULT NULL\n" +
") ;",
"CREATE TABLE groups (\n" +
" gid INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" group_name varchar(255) DEFAULT NULL\n" +
") ;",
"CREATE TABLE owners (\n" +
" oid INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" owner_name varchar(255) DEFAULT NULL\n" +
") ;",
"CREATE TABLE storages (\n" +
" type varchar(255) NOT NULL,\n" +
" capacity bigint(20) NOT NULL,\n" +
" free bigint(20) NOT NULL\n" +
") ;",
"CREATE TABLE storage_policy (\n" +
" sid tinyint(4) NOT NULL,\n" +
" policy_name varchar(64) DEFAULT NULL\n" +
") ;",
"INSERT INTO storage_policy VALUES ('0', 'HOT');",
"INSERT INTO storage_policy VALUES ('2', 'COLD');",
"INSERT INTO storage_policy VALUES ('5', 'WARM');",
"INSERT INTO storage_policy VALUES ('7', 'HOT');",
"INSERT INTO storage_policy VALUES ('10', 'ONE_SSD');",
"INSERT INTO storage_policy VALUES ('12', 'ALL_SSD');",
"INSERT INTO storage_policy VALUES ('15', 'LAZY_PERSIST');",
"CREATE TABLE xattr (\n" +
" fid bigint(20) NOT NULL,\n" +
" namespace varchar(255) NOT NULL,\n" +
" name varchar(255) NOT NULL,\n" +
" value blob NOT NULL\n" +
") ;",
"CREATE TABLE datanode_info (\n" +
" uuid varchar(64) NOT NULL,\n" +
" hostname varchar(255) NOT NULL,\n" + // DatanodeInfo
" ip varchar(16) DEFAULT NULL,\n" +
" port tinyint(4) DEFAULT NULL,\n" +
" cache_capacity bigint(20) DEFAULT NULL,\n" +
" cache_used bigint(20) DEFAULT NULL,\n" +
" location varchar(255) DEFAULT NULL\n" +
") ;",
"CREATE TABLE datanode_storage_info (\n" +
" uuid varchar(64) NOT NULL,\n" +
" sid tinyint(4) NOT NULL,\n" + // storage type
" state tinyint(4) NOT NULL,\n" + // DatanodeStorage.state
" storageid varchar(64) NOT NULL,\n" + // StorageReport ...
" failed tinyint(1) DEFAULT NULL,\n" +
" capacity bigint(20) DEFAULT NULL,\n" +
" dfs_used bigint(20) DEFAULT NULL,\n" +
" remaining bigint(20) DEFAULT NULL,\n" +
" block_pool_used bigint(20) DEFAULT NULL\n" +
") ;",
"CREATE TABLE rules (\n" +
" id INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
// TODO: may required later
// " name varchar(255) DEFAULT NULL,\n" +
" state tinyint(4) NOT NULL,\n" +
" rule_text varchar(4096) NOT NULL,\n" +
" submit_time bigint(20) NOT NULL,\n" +
" last_check_time bigint(20) DEFAULT NULL,\n" +
" checked_count int(11) NOT NULL,\n" +
" cmdlets_generated int(11) NOT NULL\n" +
") ;",
"CREATE TABLE cmdlets (\n" +
" cid INTEGER PRIMARY KEY,\n" +
" rid INTEGER NOT NULL,\n" +
" aids varchar(4096) NOT NULL,\n" +
" state tinyint(4) NOT NULL,\n" +
" parameters varchar(4096) NOT NULL,\n" +
" generate_time bigint(20) NOT NULL,\n" +
" state_changed_time bigint(20) NOT NULL\n" +
") ;",
"CREATE TABLE actions (\n" +
" aid INTEGER PRIMARY KEY,\n" +
" cid INTEGER NOT NULL,\n" +
" action_name varchar(4096) NOT NULL,\n" +
" args varchar(4096) NOT NULL,\n" +
" result text NOT NULL,\n" +
" log text NOT NULL,\n" +
" successful tinyint(4) NOT NULL,\n" +
" create_time bigint(20) NOT NULL,\n" +
" finished tinyint(4) NOT NULL,\n" +
" finish_time bigint(20) NOT NULL,\n" +
" progress INTEGER NOT NULL\n" +
") ;",
"CREATE TABLE file_diff (\n" +
" did INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" diff_type varchar(4096) NOT NULL,\n" +
" src varchar(4096) NOT NULL,\n" +
" parameters varchar(4096) NOT NULL,\n" +
" applied tinyint(4) NOT NULL,\n" +
" create_time bigint(20) NOT NULL\n" +
") ;",
"CREATE TABLE global_config (\n" +
" cid INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" property_name varchar(3072) NOT NULL UNIQUE,\n" +
" property_value varchar(3072) NOT NULL\n" +
") ;",
"CREATE TABLE cluster_config (\n" +
" cid INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" node_name varchar(3072) NOT NULL UNIQUE,\n" +
" config_path varchar(3072) NOT NULL\n" +
") ;"
};
try {
for (String s : createEmptyTables) {
String url = conn.getMetaData().getURL();
if (url.startsWith(MetaStoreUtils.MYSQL_URL_PREFIX)) {
s = s.replace("AUTOINCREMENT", "AUTO_INCREMENT");
}
LOG.info(s);
executeSql(conn, s);
}
} catch (Exception e) {
throw new MetaStoreException(e);
}
}
public static void executeSql(Connection conn, String sql)
throws MetaStoreException {
try {
Statement s = conn.createStatement();
s.execute(sql);
} catch (Exception e) {
throw new MetaStoreException(e);
}
}
public static boolean supportsBatchUpdates(Connection conn) {
try {
return conn.getMetaData().supportsBatchUpdates();
} catch (Exception e) {
return false;
}
}
public static void formatDatabase(SmartConf conf) throws MetaStoreException {
getDBAdapter(conf).formatDataBase();
}
public static MetaStore getDBAdapter(
SmartConf conf) throws MetaStoreException {
URL pathUrl = ClassLoader.getSystemResource("");
String path = pathUrl.getPath();
String fileName = "druid.xml";
String expectedCpPath = path + fileName;
LOG.info("Expected DB connection pool configuration path = "
+ expectedCpPath);
File cpConfigFile = new File(expectedCpPath);
if (cpConfigFile.exists()) {
LOG.info("Using pool configure file: " + expectedCpPath);
Properties p = new Properties();
try {
p.loadFromXML(new FileInputStream(cpConfigFile));
String url = conf.get(SmartConfKeys.SMART_METASTORE_DB_URL_KEY);
if (url != null) {
p.setProperty("url", url);
}
String purl = p.getProperty("url");
if (purl == null || purl.length() == 0) {
purl = getDefaultSqliteDB(); // For testing
p.setProperty("url", purl);
LOG.warn("Database URL not specified, using " + purl);
}
for (String key : p.stringPropertyNames()) {
LOG.info("\t" + key + " = " + p.getProperty(key));
}
return new MetaStore(new DruidPool(p));
} catch (Exception e) {
throw new MetaStoreException(e);
}
} else {
LOG.info("DB connection pool config file " + expectedCpPath
+ " NOT found.");
}
// Get Default configure from druid-template.xml
fileName = "druid-template.xml";
expectedCpPath = path + fileName;
LOG.info("Expected DB connection pool configuration path = "
+ expectedCpPath);
cpConfigFile = new File(expectedCpPath);
LOG.info("Using pool configure file: " + expectedCpPath);
Properties p = new Properties();
try {
p.loadFromXML(new FileInputStream(cpConfigFile));
} catch (Exception e) {
throw new MetaStoreException(e);
}
String url = conf.get(SmartConfKeys.SMART_METASTORE_DB_URL_KEY);
if (url != null) {
p.setProperty("url", url);
}
for (String key : p.stringPropertyNames()) {
LOG.info("\t" + key + " = " + p.getProperty(key));
}
return new MetaStore(new DruidPool(p));
}
public static Integer getKey(Map<Integer, String> map, String value) {
for (Integer key : map.keySet()) {
if (map.get(key).equals(value)) {
return key;
}
}
return null;
}
/**
* This default behavior provided here is mainly for convenience.
*
* @return
*/
private static String getDefaultSqliteDB() throws MetaStoreException {
String absFilePath = System.getProperty("user.home")
+ "/smart-test-default.db";
File file = new File(absFilePath);
if (file.exists()) {
return MetaStoreUtils.SQLITE_URL_PREFIX + absFilePath;
}
try {
Connection conn = MetaStoreUtils.createSqliteConnection(absFilePath);
MetaStoreUtils.initializeDataBase(conn);
conn.close();
} catch (Exception e) {
throw new MetaStoreException(e);
}
return MetaStoreUtils.SQLITE_URL_PREFIX + absFilePath;
}
public static void dropAllTablesSqlite(
Connection conn) throws MetaStoreException {
try {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT tbl_name FROM sqlite_master;");
List<String> list = new ArrayList<>();
while (rs.next()) {
list.add(rs.getString(1));
}
for (String tb : list) {
if (!"sqlite_sequence".equals(tb)) {
s.execute("DROP TABLE IF EXISTS '" + tb + "';");
}
}
} catch (Exception e) {
throw new MetaStoreException(e);
}
}
public static void dropAllTablesMysql(Connection conn,
String url) throws MetaStoreException {
try {
Statement stat = conn.createStatement();
String dbName;
if (url.contains("?")) {
dbName = url.substring(url.indexOf("/", 13) + 1, url.indexOf("?"));
} else {
dbName = url.substring(url.lastIndexOf("/") + 1, url.length());
}
LOG.info("Drop All tables of Current DBname: " + dbName);
ResultSet rs = stat.executeQuery("SELECT TABLE_NAME FROM "
+ "INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '" + dbName + "';");
List<String> tbList = new ArrayList<>();
while (rs.next()) {
tbList.add(rs.getString(1));
}
for (String tb : tbList) {
LOG.info(tb);
stat.execute("DROP TABLE IF EXISTS " + tb + ";");
}
} catch (Exception e) {
throw new MetaStoreException(e);
}
}
}
| smart-metastore/src/main/java/org/smartdata/metastore/utils/MetaStoreUtils.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartdata.metastore.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartdata.conf.SmartConf;
import org.smartdata.conf.SmartConfKeys;
import org.smartdata.metastore.DruidPool;
import org.smartdata.metastore.MetaStore;
import org.smartdata.metastore.MetaStoreException;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* Utilities for table operations.
*/
public class MetaStoreUtils {
public static final String SQLITE_URL_PREFIX = "jdbc:sqlite:";
public static final String MYSQL_URL_PREFIX = "jdbc:mysql:";
static final Logger LOG = LoggerFactory.getLogger(MetaStoreUtils.class);
public static Connection createConnection(String url,
String userName, String password)
throws ClassNotFoundException, SQLException {
if (url.startsWith(SQLITE_URL_PREFIX)) {
Class.forName("org.sqlite.JDBC");
} else if (url.startsWith(MYSQL_URL_PREFIX)) {
Class.forName("com.mysql.jdbc.Driver");
}
Connection conn = DriverManager.getConnection(url, userName, password);
return conn;
}
public static Connection createConnection(String driver, String url,
String userName,
String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, userName, password);
return conn;
}
public static Connection createSqliteConnection(String dbFilePath)
throws MetaStoreException {
try {
return createConnection("org.sqlite.JDBC", SQLITE_URL_PREFIX + dbFilePath,
null, null);
} catch (Exception e) {
throw new MetaStoreException(e);
}
}
public static void initializeDataBase(
Connection conn) throws MetaStoreException {
String createEmptyTables[] = new String[]{
"DROP TABLE IF EXISTS access_count_tables;",
"DROP TABLE IF EXISTS cached_files;",
"DROP TABLE IF EXISTS ecpolicys;",
"DROP TABLE IF EXISTS files;",
"DROP TABLE IF EXISTS groups;",
"DROP TABLE IF EXISTS owners;",
"DROP TABLE IF EXISTS storages;",
"DROP TABLE IF EXISTS storage_policy;",
"DROP TABLE IF EXISTS xattr;",
"DROP TABLE IF EXISTS datanode_info;",
"DROP TABLE IF EXISTS datanode_storage_info;",
"DROP TABLE IF EXISTS rules;",
"DROP TABLE IF EXISTS cmdlets;",
"DROP TABLE IF EXISTS actions;",
"DROP TABLE IF EXISTS blank_access_count_info;", // for special cases
"DROP TABLE IF EXISTS file_diff;", // incremental diff for disaster recovery
"DROP TABLE IF EXISTS global_config",
"DROP TABLE IF EXISTS cluster_config",
"CREATE TABLE access_count_tables (\n" +
" table_name varchar(255) NOT NULL,\n" +
" start_time bigint(20) NOT NULL,\n" +
" end_time bigint(20) NOT NULL\n" +
") ;",
"CREATE TABLE blank_access_count_info (\n" +
" fid bigint(20) NOT NULL,\n" +
" count bigint(20) NOT NULL\n" +
") ;",
"CREATE TABLE cached_files (\n" +
" fid bigint(20) NOT NULL,\n" +
" path varchar(4096) NOT NULL,\n" +
" from_time bigint(20) NOT NULL,\n" +
" last_access_time bigint(20) NOT NULL,\n" +
" num_accessed int(11) NOT NULL\n" +
") ;",
"CREATE TABLE ecpolicys (\n" +
" id INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" name varchar(255) DEFAULT NULL,\n" +
" cellsize int(11) DEFAULT NULL,\n" +
" numDataUnits int(11) DEFAULT NULL,\n" +
" numParityUnits int(11) DEFAULT NULL,\n" +
" codecName varchar(64) DEFAULT NULL\n" +
") ;",
"CREATE TABLE files (\n" +
" path varchar(4096) NOT NULL,\n" +
" fid bigint(20) NOT NULL,\n" +
" length bigint(20) DEFAULT NULL,\n" +
" block_replication smallint(6) DEFAULT NULL,\n" +
" block_size bigint(20) DEFAULT NULL,\n" +
" modification_time bigint(20) DEFAULT NULL,\n" +
" access_time bigint(20) DEFAULT NULL,\n" +
" is_dir tinyint(1) DEFAULT NULL,\n" +
" sid tinyint(4) DEFAULT NULL,\n" +
" oid smallint(6) DEFAULT NULL,\n" +
" gid smallint(6) DEFAULT NULL,\n" +
" permission smallint(6) DEFAULT NULL,\n" +
" ec_policy_id smallint(6) DEFAULT NULL\n" +
") ;",
"CREATE TABLE groups (\n" +
" gid INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" group_name varchar(255) DEFAULT NULL\n" +
") ;",
"CREATE TABLE owners (\n" +
" oid INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" owner_name varchar(255) DEFAULT NULL\n" +
") ;",
"CREATE TABLE storages (\n" +
" type varchar(255) NOT NULL,\n" +
" capacity bigint(20) NOT NULL,\n" +
" free bigint(20) NOT NULL\n" +
") ;",
"CREATE TABLE storage_policy (\n" +
" sid tinyint(4) NOT NULL,\n" +
" policy_name varchar(64) DEFAULT NULL\n" +
") ;",
"INSERT INTO storage_policy VALUES ('0', 'HOT');",
"INSERT INTO storage_policy VALUES ('2', 'COLD');",
"INSERT INTO storage_policy VALUES ('5', 'WARM');",
"INSERT INTO storage_policy VALUES ('7', 'HOT');",
"INSERT INTO storage_policy VALUES ('10', 'ONE_SSD');",
"INSERT INTO storage_policy VALUES ('12', 'ALL_SSD');",
"INSERT INTO storage_policy VALUES ('15', 'LAZY_PERSIST');",
"CREATE TABLE xattr (\n" +
" fid bigint(20) NOT NULL,\n" +
" namespace varchar(255) NOT NULL,\n" +
" name varchar(255) NOT NULL,\n" +
" value blob NOT NULL\n" +
") ;",
"CREATE TABLE datanode_info (\n" +
" uuid varchar(64) NOT NULL,\n" +
" hostname varchar(255) NOT NULL,\n" + // DatanodeInfo
" ip varchar(16) DEFAULT NULL,\n" +
" port tinyint(4) DEFAULT NULL,\n" +
" cache_capacity bigint(20) DEFAULT NULL,\n" +
" cache_used bigint(20) DEFAULT NULL,\n" +
" location varchar(255) DEFAULT NULL\n" +
") ;",
"CREATE TABLE datanode_storage_info (\n" +
" uuid varchar(64) NOT NULL,\n" +
" sid tinyint(4) NOT NULL,\n" + // storage type
" state tinyint(4) NOT NULL,\n" + // DatanodeStorage.state
" storageid varchar(64) NOT NULL,\n" + // StorageReport ...
" failed tinyint(1) DEFAULT NULL,\n" +
" capacity bigint(20) DEFAULT NULL,\n" +
" dfs_used bigint(20) DEFAULT NULL,\n" +
" remaining bigint(20) DEFAULT NULL,\n" +
" block_pool_used bigint(20) DEFAULT NULL\n" +
") ;",
"CREATE TABLE rules (\n" +
" id INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
// TODO: may required later
// " name varchar(255) DEFAULT NULL,\n" +
" state tinyint(4) NOT NULL,\n" +
" rule_text varchar(4096) NOT NULL,\n" +
" submit_time bigint(20) NOT NULL,\n" +
" last_check_time bigint(20) DEFAULT NULL,\n" +
" checked_count int(11) NOT NULL,\n" +
" cmdlets_generated int(11) NOT NULL\n" +
") ;",
"CREATE TABLE cmdlets (\n" +
" cid INTEGER PRIMARY KEY,\n" +
" rid INTEGER NOT NULL,\n" +
" aids varchar(4096) NOT NULL,\n" +
" state tinyint(4) NOT NULL,\n" +
" parameters varchar(4096) NOT NULL,\n" +
" generate_time bigint(20) NOT NULL,\n" +
" state_changed_time bigint(20) NOT NULL\n" +
") ;",
"CREATE TABLE actions (\n" +
" aid INTEGER PRIMARY KEY,\n" +
" cid INTEGER NOT NULL,\n" +
" action_name varchar(4096) NOT NULL,\n" +
" args varchar(4096) NOT NULL,\n" +
" result text NOT NULL,\n" +
" log text NOT NULL,\n" +
" successful tinyint(4) NOT NULL,\n" +
" create_time bigint(20) NOT NULL,\n" +
" finished tinyint(4) NOT NULL,\n" +
" finish_time bigint(20) NOT NULL,\n" +
" progress INTEGER NOT NULL\n" +
") ;",
"CREATE TABLE file_diff (\n" +
" did INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" diff_type varchar(4096) NOT NULL,\n" +
" src varchar(4096) NOT NULL,\n" +
" parameters varchar(4096) NOT NULL,\n" +
" applied tinyint(4) NOT NULL,\n" +
" create_time bigint(20) NOT NULL\n" +
") ;",
"CREATE TABLE global_config (\n" +
" cid INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" property_name varchar(4096) NOT NULL UNIQUE,\n" +
" property_value varchar(4096 ) NOT NULL\n" +
") ;",
"CREATE TABLE cluster_config (\n" +
" cid INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" node_name varchar(4096) NOT NULL UNIQUE,\n" +
" config_path varchar(4096) NOT NULL\n" +
") ;"
};
try {
for (String s : createEmptyTables) {
String url = conn.getMetaData().getURL();
if (url.startsWith(MetaStoreUtils.MYSQL_URL_PREFIX)) {
s = s.replace("AUTOINCREMENT", "AUTO_INCREMENT");
}
executeSql(conn, s);
}
} catch (Exception e) {
throw new MetaStoreException(e);
}
}
public static void executeSql(Connection conn, String sql)
throws MetaStoreException {
try {
Statement s = conn.createStatement();
s.execute(sql);
} catch (Exception e) {
throw new MetaStoreException(e);
}
}
public static boolean supportsBatchUpdates(Connection conn) {
try {
return conn.getMetaData().supportsBatchUpdates();
} catch (Exception e) {
return false;
}
}
public static void formatDatabase(SmartConf conf) throws MetaStoreException {
getDBAdapter(conf).formatDataBase();
}
public static MetaStore getDBAdapter(
SmartConf conf) throws MetaStoreException {
URL pathUrl = ClassLoader.getSystemResource("");
String path = pathUrl.getPath();
String fileName = "druid.xml";
String expectedCpPath = path + fileName;
LOG.info("Expected DB connection pool configuration path = "
+ expectedCpPath);
File cpConfigFile = new File(expectedCpPath);
if (cpConfigFile.exists()) {
LOG.info("Using pool configure file: " + expectedCpPath);
Properties p = new Properties();
try {
p.loadFromXML(new FileInputStream(cpConfigFile));
String url = conf.get(SmartConfKeys.SMART_METASTORE_DB_URL_KEY);
if (url != null) {
p.setProperty("url", url);
}
String purl = p.getProperty("url");
if (purl == null || purl.length() == 0) {
purl = getDefaultSqliteDB(); // For testing
p.setProperty("url", purl);
LOG.warn("Database URL not specified, using " + purl);
}
for (String key : p.stringPropertyNames()) {
LOG.info("\t" + key + " = " + p.getProperty(key));
}
return new MetaStore(new DruidPool(p));
} catch (Exception e) {
throw new MetaStoreException(e);
}
} else {
LOG.info("DB connection pool config file " + expectedCpPath
+ " NOT found.");
}
// Get Default configure from druid-template.xml
fileName = "druid-template.xml";
expectedCpPath = path + fileName;
LOG.info("Expected DB connection pool configuration path = "
+ expectedCpPath);
cpConfigFile = new File(expectedCpPath);
LOG.info("Using pool configure file: " + expectedCpPath);
Properties p = new Properties();
try {
p.loadFromXML(new FileInputStream(cpConfigFile));
} catch (Exception e) {
throw new MetaStoreException(e);
}
String url = conf.get(SmartConfKeys.SMART_METASTORE_DB_URL_KEY);
if (url != null) {
p.setProperty("url", url);
}
for (String key : p.stringPropertyNames()) {
LOG.info("\t" + key + " = " + p.getProperty(key));
}
return new MetaStore(new DruidPool(p));
}
public static Integer getKey(Map<Integer, String> map, String value) {
for (Integer key : map.keySet()) {
if (map.get(key).equals(value)) {
return key;
}
}
return null;
}
/**
* This default behavior provided here is mainly for convenience.
*
* @return
*/
private static String getDefaultSqliteDB() throws MetaStoreException {
String absFilePath = System.getProperty("user.home")
+ "/smart-test-default.db";
File file = new File(absFilePath);
if (file.exists()) {
return MetaStoreUtils.SQLITE_URL_PREFIX + absFilePath;
}
try {
Connection conn = MetaStoreUtils.createSqliteConnection(absFilePath);
MetaStoreUtils.initializeDataBase(conn);
conn.close();
} catch (Exception e) {
throw new MetaStoreException(e);
}
return MetaStoreUtils.SQLITE_URL_PREFIX + absFilePath;
}
public static void dropAllTablesSqlite(
Connection conn) throws MetaStoreException {
try {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT tbl_name FROM sqlite_master;");
List<String> list = new ArrayList<>();
while (rs.next()) {
list.add(rs.getString(1));
}
for (String tb : list) {
if (!"sqlite_sequence".equals(tb)) {
s.execute("DROP TABLE IF EXISTS '" + tb + "';");
}
}
} catch (Exception e) {
throw new MetaStoreException(e);
}
}
public static void dropAllTablesMysql(Connection conn,
String url) throws MetaStoreException {
try {
Statement stat = conn.createStatement();
String dbName;
if (url.contains("?")) {
dbName = url.substring(url.indexOf("/", 13) + 1, url.indexOf("?"));
} else {
dbName = url.substring(url.lastIndexOf("/") + 1, url.length());
}
LOG.info("Drop All tables of Current DBname: " + dbName);
ResultSet rs = stat.executeQuery("SELECT TABLE_NAME FROM "
+ "INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '" + dbName + "';");
List<String> tbList = new ArrayList<>();
while (rs.next()) {
tbList.add(rs.getString(1));
}
for (String tb : tbList) {
LOG.info(tb);
stat.execute("DROP TABLE IF EXISTS " + tb + ";");
}
} catch (Exception e) {
throw new MetaStoreException(e);
}
}
}
| Fix table key length error
| smart-metastore/src/main/java/org/smartdata/metastore/utils/MetaStoreUtils.java | Fix table key length error |
|
Java | apache-2.0 | 172be153955ef683e7264c282436cedc89e3bc69 | 0 | flexiblepower/fpai-core,flexiblepower/fpai-core,flexiblepower/fpai-core,flexiblepower/fpai-core | package org.flexiblepower.ral.ext;
import java.util.List;
import org.flexiblepower.messaging.Connection;
import org.flexiblepower.messaging.MessageHandler;
import org.flexiblepower.ral.ControllerManager;
import org.flexiblepower.ral.ResourceControlParameters;
import org.flexiblepower.ral.ResourceDriver;
import org.flexiblepower.ral.ResourceManager;
import org.flexiblepower.ral.ResourceState;
import org.flexiblepower.ral.messages.Allocation;
import org.flexiblepower.ral.messages.AllocationStatusUpdate;
import org.flexiblepower.ral.messages.ResourceMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Gives a basic implementation for a {@link ResourceManager} which does simple translation, possible while keeping
* state information.
*
* @param <RS>
* The type of the {@link ResourceState}
* @param <RCP>
* The type of the {@link ResourceControlParameters}
*/
public abstract class AbstractResourceManager<RS extends ResourceState, RCP extends ResourceControlParameters> implements
ResourceManager {
/**
* The logger that should be used by any subclass.
*/
protected final Logger logger;
/**
* Creates a new instance for the specific driver class type and the control space class.
*/
protected AbstractResourceManager() {
logger = LoggerFactory.getLogger(getClass());
}
private volatile boolean hasRegistered = false;
/**
* This method is called when a state update from the driver has been received, but this manager is not connected.
*
* The default implementation logs a info message to remind that it is not connected.
*
* @param state
* The state of the driver
*/
protected void unconnectedStateUpdate(RS state) {
logger.info("Message Received by Resource Manager but no controler connected");
}
/**
* This method is called when the first state has been received from the driver and a registration is needed. This
* method should return a list of {@link ResourceMessage}s that should at least contain a registration message.
*
* @param state
* The state of the driver
* @return A list of {@link ResourceMessage}s that will be sent to the controller.
*/
protected abstract List<? extends ResourceMessage> startRegistration(RS state);
/**
* This method is called when the state is updated and the {@link #startRegistration(ResourceState)} has already
* been called previously.
*
* @param state
* The state of the driver
* @return A list of {@link ResourceMessage}s that will be sent to the controller.
*/
protected abstract List<? extends ResourceMessage> updatedState(RS state);
/**
* This method is called when a message has been received from the controller. This will generally be an
* {@link Allocation} object, but could also be of another type, depending on the used message type.
*
* @param message
* The received message
* @return The {@link ResourceControlParameters} that should be sent to the driver.
*/
protected abstract RCP receivedAllocation(ResourceMessage message);
private volatile Connection driverConnection, controllerConnection;
@Override
public MessageHandler onConnect(Connection connection) {
if (driverConnection == null && "driver".equals(connection.getPort().name())) {
driverConnection = connection;
return new MessageHandler() {
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Object message) {
try {
if (controllerConnection != null) {
List<? extends ResourceMessage> messages = null;
if (!hasRegistered) {
messages = startRegistration((RS) message);
hasRegistered = true;
} else {
messages = updatedState((RS) message);
}
if (messages != null) {
for (ResourceMessage msg : messages) {
if (msg == null) {
logger.warn("Trying to send a null message, this is not allowed");
} else {
controllerConnection.sendMessage(msg);
}
}
}
} else {
unconnectedStateUpdate((RS) message);
}
} catch (ClassCastException ex) {
logger.warn("Received unknown message type {}", message.getClass().getName());
}
}
@Override
public void disconnected() {
hasRegistered = false;
driverConnection = null;
}
};
} else if (controllerConnection == null && "controller".equals(connection.getPort().name())) {
controllerConnection = connection;
return new MessageHandler() {
@Override
public void handleMessage(Object message) {
try {
if (driverConnection != null) {
RCP control = receivedAllocation((ResourceMessage) message);
if (control != null) {
driverConnection.sendMessage(control);
}
} else {
logger.warn("Message Received by Resource Manager but no driver connected");
}
} catch (ClassCastException ex) {
logger.warn("Received unknown message type {}", message.getClass().getName());
}
}
@Override
public void disconnected() {
hasRegistered = false;
controllerConnection = null;
}
};
}
return null;
}
/**
* Indicate if this {@link ResourceManager} is currently connected to a {@link ControllerManager}.
*
* @return boolean indicating if this {@link ResourceManager} is currently connected to a {@link ControllerManager}
*/
protected boolean isConnectedWithResourceController() {
return controllerConnection != null;
}
/**
* Indicate if this {@link ResourceManager} is currently connected to a {@link ResourceDriver}.
*
* @return boolean indicating if this {@link ResourceManager} is currently connected to a {@link ResourceDriver}
*/
protected boolean isConnectedWithResourceDriver() {
return driverConnection != null;
}
/**
* Send status update to attached controller.
*
* @param allocationStatusUpdate
* The {@link AllocationStatusUpdate} that is to be sent to the controller.
*/
protected void allocationStatusUpdate(AllocationStatusUpdate allocationStatusUpdate) {
if (controllerConnection != null) {
controllerConnection.sendMessage(allocationStatusUpdate);
} else {
logger.warn("Allocation Status update from Resource Manager but no controller connected");
}
}
/**
* Send control parameters to attached driver.
*
* @param controlParameters
* The parameters that have to be sent to the driver
*/
protected void sendControlParameters(ResourceControlParameters controlParameters) {
if (driverConnection != null) {
driverConnection.sendMessage(controlParameters);
} else {
logger.warn("Control Parameters update from Resource Manager but no controller connected");
}
}
}
| flexiblepower.ral.ext/src/org/flexiblepower/ral/ext/AbstractResourceManager.java | package org.flexiblepower.ral.ext;
import java.util.List;
import org.flexiblepower.messaging.Connection;
import org.flexiblepower.messaging.MessageHandler;
import org.flexiblepower.ral.ControllerManager;
import org.flexiblepower.ral.ResourceControlParameters;
import org.flexiblepower.ral.ResourceDriver;
import org.flexiblepower.ral.ResourceManager;
import org.flexiblepower.ral.ResourceState;
import org.flexiblepower.ral.messages.AllocationStatusUpdate;
import org.flexiblepower.ral.messages.ResourceMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Gives a basic implementation for a {@link ResourceManager} which does simple translation, possible while keeping
* state information.
*/
public abstract class AbstractResourceManager<RS extends ResourceState, RCP extends ResourceControlParameters> implements
ResourceManager {
/**
* The logger that should be used by any subclass.
*/
protected final Logger logger;
/**
* Creates a new instance for the specific driver class type and the control space class.
*/
protected AbstractResourceManager() {
logger = LoggerFactory.getLogger(getClass());
}
private volatile boolean hasRegistered = false;
protected abstract List<? extends ResourceMessage> startRegistration(RS state);
protected abstract List<? extends ResourceMessage> updatedState(RS state);
protected abstract RCP receivedAllocation(ResourceMessage message);
private volatile Connection driverConnection, controllerConnection;
@Override
public MessageHandler onConnect(Connection connection) {
if (driverConnection == null && "driver".equals(connection.getPort().name())) {
driverConnection = connection;
return new MessageHandler() {
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Object message) {
try {
if (controllerConnection != null) {
List<? extends ResourceMessage> messages = null;
if (!hasRegistered) {
messages = startRegistration((RS) message);
hasRegistered = true;
} else {
messages = updatedState((RS) message);
}
if (messages != null) {
for (ResourceMessage msg : messages) {
if (msg == null) {
logger.warn("Trying to send a null message, this is not allowed");
} else {
controllerConnection.sendMessage(msg);
}
}
}
}
else {
logger.warn("Message Received by Resource Manager but no controler connected");
}
} catch (ClassCastException ex) {
logger.warn("Received unknown message type {}", message.getClass().getName());
}
}
@Override
public void disconnected() {
hasRegistered = false;
driverConnection = null;
}
};
} else if (controllerConnection == null && "controller".equals(connection.getPort().name())) {
controllerConnection = connection;
return new MessageHandler() {
@Override
public void handleMessage(Object message) {
try {
if (driverConnection != null) {
RCP control = receivedAllocation((ResourceMessage) message);
if (control != null) {
driverConnection.sendMessage(control);
}
}
else {
logger.warn("Message Received by Resource Manager but no driver connected");
}
} catch (ClassCastException ex) {
logger.warn("Received unknown message type {}", message.getClass().getName());
}
}
@Override
public void disconnected() {
hasRegistered = false;
controllerConnection = null;
}
};
}
return null;
}
/**
* Indicate if this {@link ResourceManager} is currently connected to a {@link ControllerManager}
*
* @return boolean indicating if this {@link ResourceManager} is currently connected to a {@link ControllerManager}
*/
protected boolean isConnectedWithResourceController() {
return controllerConnection != null;
}
/**
* Indicate if this {@link ResourceManager} is currently connected to a {@link ResourceDriver}
*
* @return boolean indicating if this {@link ResourceManager} is currently connected to a {@link ResourceDriver}
*/
protected boolean isConnectedWithResourceDriver() {
return driverConnection != null;
}
/**
* Send status update to attached controller
*
* @param allocationStatusUpdate
*/
protected void allocationStatusUpdate(AllocationStatusUpdate allocationStatusUpdate) {
if (controllerConnection != null) {
controllerConnection.sendMessage(allocationStatusUpdate);
}
else {
logger.warn("Allocation Status update from Resource Manager but no controller connected");
}
}
/**
* Send control parameters to attached driver
*
* @param controlParameters
* The parameters that have to be sent to the driver
*/
protected void sendControlParameters(ResourceControlParameters controlParameters) {
if (driverConnection != null) {
driverConnection.sendMessage(controlParameters);
}
else {
logger.warn("Control Parameters update from Resource Manager but no controller connected");
}
}
}
| Fixes #26, by adding a unconnectedStateUpdate method
Also reduces the logging level, because this should not be a warning
| flexiblepower.ral.ext/src/org/flexiblepower/ral/ext/AbstractResourceManager.java | Fixes #26, by adding a unconnectedStateUpdate method |
|
Java | apache-2.0 | 76fd0cf88afbeff8b883e988fbb4f71f81f8506d | 0 | CenturyLinkCloud/clc-java-sdk,CenturyLinkCloud/clc-java-sdk,CenturyLinkCloud/clc-java-sdk | /*
* (c) 2015 CenturyLink. All Rights Reserved.
*
* 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.centurylink.cloud.sdk.common.management.client;
import com.centurylink.cloud.sdk.common.management.client.domain.datacenters.DataCenterMetadata;
import com.centurylink.cloud.sdk.common.management.client.domain.datacenters.GetDataCenterListResponse;
import com.centurylink.cloud.sdk.common.management.client.domain.datacenters.deployment.capabilities.DatacenterDeploymentCapabilitiesMetadata;
import com.centurylink.cloud.sdk.core.auth.services.BearerAuthentication;
import com.centurylink.cloud.sdk.core.client.AuthenticatedSdkHttpClient;
import com.centurylink.cloud.sdk.core.client.ClcClientException;
import com.centurylink.cloud.sdk.core.config.SdkConfiguration;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.inject.Inject;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* @author ilya.drabenia
*/
public class DataCentersClient extends AuthenticatedSdkHttpClient {
private LoadingCache<String, DataCenterMetadata> cache = CacheBuilder.newBuilder()
.maximumSize(20)
.expireAfterWrite(1, TimeUnit.HOURS)
.build(new CacheLoader<String, DataCenterMetadata>() {
@Override
public DataCenterMetadata load(String id) throws Exception {
return loadDataCenter(id);
}
}
);
@Inject
public DataCentersClient(BearerAuthentication authFilter, SdkConfiguration config) {
super(authFilter, config);
GetDataCenterListResponse dataCenters = loadAllDataCenters();
dataCenters.forEach(dc -> cache.put(dc.getId(), dc));
}
public DatacenterDeploymentCapabilitiesMetadata getDeploymentCapabilities(String dataCenterId) {
return
client("/datacenters/{accountAlias}/{dataCenterId}/deploymentCapabilities")
.resolveTemplate("dataCenterId", dataCenterId)
.request().get(DatacenterDeploymentCapabilitiesMetadata.class);
}
public DataCenterMetadata getDataCenter(String dataCenterId) {
try {
return cache.get(dataCenterId);
} catch (ExecutionException e) {
throw new ClcClientException(e.getMessage());
}
}
private DataCenterMetadata loadDataCenter(String dataCenterId) {
return
client("/datacenters/{accountAlias}/{dataCenterId}")
.queryParam("groupLinks", true)
.resolveTemplate("dataCenterId", dataCenterId)
.request().get(DataCenterMetadata.class);
}
public GetDataCenterListResponse findAllDataCenters() {
return new GetDataCenterListResponse(cache.asMap().values());
}
private GetDataCenterListResponse loadAllDataCenters() {
return
client("/datacenters/{accountAlias}?groupLinks=true")
.request()
.get(GetDataCenterListResponse.class);
}
}
| clc-java-sdk/sdk/src/main/java/com/centurylink/cloud/sdk/common/management/client/DataCentersClient.java | /*
* (c) 2015 CenturyLink. All Rights Reserved.
*
* 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.centurylink.cloud.sdk.common.management.client;
import com.centurylink.cloud.sdk.common.management.client.domain.datacenters.DataCenterMetadata;
import com.centurylink.cloud.sdk.common.management.client.domain.datacenters.GetDataCenterListResponse;
import com.centurylink.cloud.sdk.common.management.client.domain.datacenters.deployment.capabilities.DatacenterDeploymentCapabilitiesMetadata;
import com.centurylink.cloud.sdk.core.auth.services.BearerAuthentication;
import com.centurylink.cloud.sdk.core.client.AuthenticatedSdkHttpClient;
import com.centurylink.cloud.sdk.core.client.ClcClientException;
import com.centurylink.cloud.sdk.core.config.SdkConfiguration;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.inject.Inject;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* @author ilya.drabenia
*/
public class DataCentersClient extends AuthenticatedSdkHttpClient {
private LoadingCache<String, DataCenterMetadata> cache = CacheBuilder.newBuilder()
.maximumSize(20)
.expireAfterWrite(1, TimeUnit.DAYS)
.build(new CacheLoader<String, DataCenterMetadata>() {
@Override
public DataCenterMetadata load(String id) throws Exception {
return loadDataCenter(id);
}
}
);
@Inject
public DataCentersClient(BearerAuthentication authFilter, SdkConfiguration config) {
super(authFilter, config);
GetDataCenterListResponse dataCenters = findAllDataCenters();
dataCenters.forEach(dc -> cache.put(dc.getId(), dc));
}
public DatacenterDeploymentCapabilitiesMetadata getDeploymentCapabilities(String dataCenterId) {
return
client("/datacenters/{accountAlias}/{dataCenterId}/deploymentCapabilities")
.resolveTemplate("dataCenterId", dataCenterId)
.request().get(DatacenterDeploymentCapabilitiesMetadata.class);
}
public DataCenterMetadata getDataCenter(String dataCenterId) {
try {
return cache.get(dataCenterId);
} catch (ExecutionException e) {
throw new ClcClientException(e.getMessage());
}
}
private DataCenterMetadata loadDataCenter(String dataCenterId) {
return
client("/datacenters/{accountAlias}/{dataCenterId}")
.queryParam("groupLinks", true)
.resolveTemplate("dataCenterId", dataCenterId)
.request().get(DataCenterMetadata.class);
}
// TODO: need to implement memoization of this method with acceptable expiration time
public GetDataCenterListResponse findAllDataCenters() {
return
client("/datacenters/{accountAlias}?groupLinks=true")
.request()
.get(GetDataCenterListResponse.class);
}
}
| issue #51 Implement caching for result of get datacenters remote call. changes according comments
| clc-java-sdk/sdk/src/main/java/com/centurylink/cloud/sdk/common/management/client/DataCentersClient.java | issue #51 Implement caching for result of get datacenters remote call. changes according comments |
|
Java | apache-2.0 | 46399472519cd049213621f644656a9480190c6e | 0 | OpenXIP/xip-host,OpenXIP/xip-host | /**
* Copyright (c) 2011 Washington University in St. Louis. All Rights Reserved.
*/
package edu.wustl.xipHost.avt2ext;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.dcm4che2.io.DicomOutputStream;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.nema.dicom.wg23.ObjectDescriptor;
import org.nema.dicom.wg23.ObjectLocator;
import org.nema.dicom.wg23.Uuid;
import com.siemens.scr.avt.ad.annotation.ImageAnnotation;
import com.siemens.scr.avt.ad.api.ADFacade;
import edu.wustl.xipHost.dataAccess.DataSource;
import edu.wustl.xipHost.dataAccess.Retrieve;
import edu.wustl.xipHost.dataAccess.RetrieveEvent;
import edu.wustl.xipHost.dataAccess.RetrieveListener;
import edu.wustl.xipHost.dataAccess.RetrieveTarget;
import edu.wustl.xipHost.dicom.DicomUtil;
/**
* @author Jaroslaw Krych
*
*/
public class AVTRetrieve implements Retrieve {
final static Logger logger = Logger.getLogger(AVTRetrieve.class);
ADFacade adService = AVTFactory.getADServiceInstance();
Map<Integer, Object> dicomCriteria;
Map<String, Object> aimCriteria;
List<ObjectDescriptor> objectDescriptors;
File importDir;
RetrieveTarget retrieveTarget;
DataSource dataSource;
public AVTRetrieve(){}
/**
*
*/
public AVTRetrieve(Map<Integer, Object> dicomCriteria, Map<String, Object> aimCriteria, File importDir, RetrieveTarget retrieveTarget, DataSource dataSource) {
this.dicomCriteria = dicomCriteria;
this.aimCriteria = aimCriteria;
this.importDir = importDir;
this.retrieveTarget = retrieveTarget;
this.dataSource = dataSource;
}
@Override
public void setCriteria(Map<Integer, Object> dicomCriteria, Map<String, Object> aimCriteria) {
this.dicomCriteria = dicomCriteria;
this.aimCriteria = aimCriteria;
}
@Override
public void setCriteria(Object criteria) {
}
List<ObjectDescriptor> objDescsDICOM;
List<ObjectDescriptor> objDescsAIM;
@Override
public void setObjectDescriptors(List<ObjectDescriptor> objectDescriptors) {
this.objectDescriptors = objectDescriptors;
objDescsDICOM = new ArrayList<ObjectDescriptor>();
objDescsAIM = new ArrayList<ObjectDescriptor>();
for(ObjectDescriptor objDesc : objectDescriptors){
if(objDesc.getMimeType().equalsIgnoreCase("application/dicom")){
objDescsDICOM.add(objDesc);
} else if (objDesc.getMimeType().equalsIgnoreCase("text/xml")){
objDescsAIM.add(objDesc);
}
}
}
@Override
public void setImportDir(File importDir) {
this.importDir = importDir;
}
@Override
public void setRetrieveTarget(RetrieveTarget retrieveTarget) {
this.retrieveTarget = retrieveTarget;
}
@Override
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void run() {
try {
logger.info("Executing AVT retrieve.");
Map<String, ObjectLocator> objectLocs = retrieve(dicomCriteria, aimCriteria, importDir, retrieveTarget);
fireResultsAvailable(objectLocs);
} catch (IOException e) {
logger.error(e, e);
return;
}
}
SAXBuilder builder = new SAXBuilder();
Document document;
XMLOutputter outToXMLFile = new XMLOutputter();
Map<String, ObjectLocator> retrieve(Map<Integer, Object> dicomCriteria, Map<String, Object> aimCriteria, File importDir, RetrieveTarget retrieveTarget) throws IOException {
Map<String, ObjectLocator> objectLocators = new HashMap<String, ObjectLocator>();
if(retrieveTarget == RetrieveTarget.DICOM_AIM_SEG){
objectLocators = retrieveDICOM();
Map<String, ObjectLocator> objectLocatorsAIMandSEG = retrieveAIMandDICOMSeg();
Iterator<String> keySet = objectLocatorsAIMandSEG.keySet().iterator();
while(keySet.hasNext()){
String key = keySet.next();
ObjectLocator objLoc = objectLocatorsAIMandSEG.get(key);
objectLocators.put(key, objLoc);
}
} else if (retrieveTarget == RetrieveTarget.DICOM) {
objectLocators = retrieveDICOM();
} else if (retrieveTarget == RetrieveTarget.AIM_SEG) {
objectLocators = retrieveAIMandDICOMSeg();
}
return objectLocators;
}
Map<String, ObjectLocator> retrieveDICOM(){
//Retrieve DICOM
logger.debug("DICOM retrieve criteria: ");
Iterator<Integer> keySet = dicomCriteria.keySet().iterator();
while(keySet.hasNext()){
Integer key = keySet.next();
Object value = dicomCriteria.get(key);
logger.debug("Tag: " + DicomUtil.toDicomHex(key) + " Value: " + value.toString());
}
Map<String, ObjectLocator> objectLocators = new HashMap<String, ObjectLocator>();
List<DicomObject> retrievedDICOM = adService.retrieveDicomObjs(dicomCriteria, aimCriteria);
int i;
for(i = 0; i < retrievedDICOM.size(); i++){
DicomObject dicom = retrievedDICOM.get(i);
String filePrefix = dicom.getString(Tag.SOPInstanceUID);
try {
File file = new File(importDir.getAbsolutePath() + File.separatorChar + filePrefix);
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DicomOutputStream dout = new DicomOutputStream(bos);
dout.writeDicomFile(dicom);
dout.close();
ObjectLocator objLoc = new ObjectLocator();
//ObjectDescriptor objDesc = objectDescriptors.get(i);
ObjectDescriptor objDesc = objDescsDICOM.get(i);
Uuid itemUUID = objDesc.getUuid();
objLoc.setUuid(itemUUID);
objLoc.setUri(file.getAbsolutePath());
objectLocators.put(itemUUID.getUuid(), objLoc);
} catch (IOException e) {
logger.error(e, e);
return null;
}
}
return objectLocators;
}
Map<String, ObjectLocator> retrieveAIMandDICOMSeg() throws IOException {
//Retrieve AIM and DICOM SEG objects
logger.debug("AVT AD RetrieveTarget = " + retrieveTarget.toString());
Map<String, ObjectLocator> objectLocators = new HashMap<String, ObjectLocator>();
File dirPath = importDir.getAbsoluteFile();
List<String> annotationUIDs = adService.findAnnotations(dicomCriteria, aimCriteria);
Set<String> uniqueAnnotUIDs = new HashSet<String>(annotationUIDs);
Iterator<String> iter = uniqueAnnotUIDs.iterator();
Iterator<ObjectDescriptor> iterObjDescsAIM = objDescsAIM.iterator();
while(iter.hasNext()){
String uid = iter.next();
ImageAnnotation loadedAnnot = adService.getAnnotation(uid);
String strXML = loadedAnnot.getAIM();
byte[] source = strXML.getBytes();
InputStream is = new ByteArrayInputStream(source);
try {
document = builder.build(is);
} catch (JDOMException e) {
logger.error(e, e);
return null;
}
File outFile = new File(dirPath + File.separator + uid);
FileOutputStream outStream = new FileOutputStream(outFile);
outToXMLFile.output(document, outStream);
outStream.flush();
outStream.close();
ObjectLocator objLoc = new ObjectLocator();
ObjectDescriptor objDesc = iterObjDescsAIM.next();
Uuid itemUUID = objDesc.getUuid();
objLoc.setUuid(itemUUID);
objLoc.setUri(outFile.getAbsolutePath());
objectLocators.put(itemUUID.getUuid(), objLoc);
//Retrieve DICOM SEG objects
Set<String> dicomSegSOPInstanceUIDs = new HashSet<String>();
List<DicomObject> segObjects = adService.retrieveSegmentationObjects(uid);
for(int j = 0; j < segObjects.size(); j++){
DicomObject dicom = segObjects.get(j);
String sopInstanceUID = dicom.getString(Tag.SOPInstanceUID);
//Check if DICOM SEG was not serialized in reference to another AIM
if(!dicomSegSOPInstanceUIDs.contains(sopInstanceUID)){
dicomSegSOPInstanceUIDs.add(sopInstanceUID);
DicomObject dicomSeg = adService.getDicomObject(sopInstanceUID);
String message = "DICOM SEG " + sopInstanceUID + " cannot be loaded from file system!";
if(dicomSeg == null){
throw new FileNotFoundException(message);
} else {
//TODO DICOM SEG tmp file not found e.g. DICOM SEG belongs to not specified Study for which TargetIteratorRunner was not requested
File outDicomSegFile = new File(dirPath + File.separator + sopInstanceUID);
FileOutputStream fos = new FileOutputStream(outDicomSegFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DicomOutputStream dout = new DicomOutputStream(bos);
dout.writeDicomFile(dicomSeg);
dout.close();
ObjectLocator dicomSegObjLoc = new ObjectLocator();
Uuid dicomSegItemUUID = new Uuid();
dicomSegItemUUID.setUuid(UUID.randomUUID().toString());
ObjectDescriptor objDescDicomSeg = new ObjectDescriptor();
objDescDicomSeg.setUuid(dicomSegItemUUID);
//TODO set MIME type, sopClass UID etc.
objectDescriptors.add(objDescDicomSeg);
dicomSegObjLoc.setUuid(dicomSegItemUUID);
dicomSegObjLoc.setUri(outDicomSegFile.getAbsolutePath());
objectLocators.put(dicomSegItemUUID.getUuid(), dicomSegObjLoc);
}
}
}
}
return objectLocators;
}
void fireResultsAvailable(Map<String, ObjectLocator> objectLocators){
RetrieveEvent event = new RetrieveEvent(objectLocators);
listener.retrieveResultsAvailable(event);
}
RetrieveListener listener;
@Override
public void addRetrieveListener(RetrieveListener l) {
listener = l;
}
}
| src/edu/wustl/xipHost/avt2ext/AVTRetrieve.java | /**
* Copyright (c) 2011 Washington University in St. Louis. All Rights Reserved.
*/
package edu.wustl.xipHost.avt2ext;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.dcm4che2.io.DicomOutputStream;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.nema.dicom.wg23.ObjectDescriptor;
import org.nema.dicom.wg23.ObjectLocator;
import org.nema.dicom.wg23.Uuid;
import com.siemens.scr.avt.ad.annotation.ImageAnnotation;
import com.siemens.scr.avt.ad.api.ADFacade;
import edu.wustl.xipHost.dataAccess.DataSource;
import edu.wustl.xipHost.dataAccess.Retrieve;
import edu.wustl.xipHost.dataAccess.RetrieveEvent;
import edu.wustl.xipHost.dataAccess.RetrieveListener;
import edu.wustl.xipHost.dataAccess.RetrieveTarget;
import edu.wustl.xipHost.dicom.DicomUtil;
/**
* @author Jaroslaw Krych
*
*/
public class AVTRetrieve implements Retrieve {
final static Logger logger = Logger.getLogger(AVTRetrieve.class);
ADFacade adService = AVTFactory.getADServiceInstance();
Map<Integer, Object> dicomCriteria;
Map<String, Object> aimCriteria;
List<ObjectDescriptor> objectDescriptors;
File importDir;
RetrieveTarget retrieveTarget;
DataSource dataSource;
public AVTRetrieve(){}
/**
*
*/
public AVTRetrieve(Map<Integer, Object> dicomCriteria, Map<String, Object> aimCriteria, File importDir, RetrieveTarget retrieveTarget, DataSource dataSource) {
this.dicomCriteria = dicomCriteria;
this.aimCriteria = aimCriteria;
this.importDir = importDir;
this.retrieveTarget = retrieveTarget;
this.dataSource = dataSource;
}
@Override
public void setCriteria(Map<Integer, Object> dicomCriteria, Map<String, Object> aimCriteria) {
this.dicomCriteria = dicomCriteria;
this.aimCriteria = aimCriteria;
}
@Override
public void setCriteria(Object criteria) {
}
List<ObjectDescriptor> objDescsDICOM;
List<ObjectDescriptor> objDescsAIM;
@Override
public void setObjectDescriptors(List<ObjectDescriptor> objectDescriptors) {
this.objectDescriptors = objectDescriptors;
objDescsDICOM = new ArrayList<ObjectDescriptor>();
objDescsAIM = new ArrayList<ObjectDescriptor>();
for(ObjectDescriptor objDesc : objectDescriptors){
if(objDesc.getMimeType().equalsIgnoreCase("application/dicom")){
objDescsDICOM.add(objDesc);
} else if (objDesc.getMimeType().equalsIgnoreCase("text/xml")){
objDescsAIM.add(objDesc);
}
}
}
@Override
public void setImportDir(File importDir) {
this.importDir = importDir;
}
@Override
public void setRetrieveTarget(RetrieveTarget retrieveTarget) {
this.retrieveTarget = retrieveTarget;
}
@Override
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void run() {
try {
logger.info("Executing AVT retrieve.");
Map<String, ObjectLocator> objectLocs = retrieve(dicomCriteria, aimCriteria, importDir, retrieveTarget);
fireResultsAvailable(objectLocs);
} catch (IOException e) {
logger.error(e, e);
return;
}
}
SAXBuilder builder = new SAXBuilder();
Document document;
XMLOutputter outToXMLFile = new XMLOutputter();
Map<String, ObjectLocator> retrieve(Map<Integer, Object> dicomCriteria, Map<String, Object> aimCriteria, File importDir, RetrieveTarget retrieveTarget) throws IOException {
Map<String, ObjectLocator> objectLocators = new HashMap<String, ObjectLocator>();
if(retrieveTarget == RetrieveTarget.DICOM_AND_AIM){
objectLocators = retrieveDICOM();
Map<String, ObjectLocator> objectLocatorsAIMandSEG = retrieveAIMandDICOMSeg();
Iterator<String> keySet = objectLocatorsAIMandSEG.keySet().iterator();
while(keySet.hasNext()){
String key = keySet.next();
ObjectLocator objLoc = objectLocatorsAIMandSEG.get(key);
objectLocators.put(key, objLoc);
}
} else if (retrieveTarget == RetrieveTarget.DICOM) {
objectLocators = retrieveDICOM();
} else if (retrieveTarget == RetrieveTarget.AIM_SEG) {
objectLocators = retrieveAIMandDICOMSeg();
}
return objectLocators;
}
Map<String, ObjectLocator> retrieveDICOM(){
//Retrieve DICOM
//If oneSeries contains subset of items, narrow dicomCriteria to individual SOPInstanceUIDs
//Then retrieve data item by item
logger.debug("DICOM retrieve criteria: ");
Iterator<Integer> keySet = dicomCriteria.keySet().iterator();
while(keySet.hasNext()){
Integer key = keySet.next();
Object value = dicomCriteria.get(key);
logger.debug("Tag: " + DicomUtil.toDicomHex(key) + " Value: " + value.toString());
}
Map<String, ObjectLocator> objectLocators = new HashMap<String, ObjectLocator>();
List<DicomObject> retrievedDICOM = adService.retrieveDicomObjs(dicomCriteria, aimCriteria);
int i;
for(i = 0; i < retrievedDICOM.size(); i++){
DicomObject dicom = retrievedDICOM.get(i);
String filePrefix = dicom.getString(Tag.SOPInstanceUID);
try {
File file = new File(importDir.getAbsolutePath() + File.separatorChar + filePrefix);
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DicomOutputStream dout = new DicomOutputStream(bos);
dout.writeDicomFile(dicom);
dout.close();
ObjectLocator objLoc = new ObjectLocator();
//ObjectDescriptor objDesc = objectDescriptors.get(i);
ObjectDescriptor objDesc = objDescsDICOM.get(i);
Uuid itemUUID = objDesc.getUuid();
objLoc.setUuid(itemUUID);
objLoc.setUri(file.getAbsolutePath());
objectLocators.put(itemUUID.getUuid(), objLoc);
} catch (IOException e) {
logger.error(e, e);
return null;
}
}
return objectLocators;
}
Map<String, ObjectLocator> retrieveAIMandDICOMSeg() throws IOException {
//Retrieve AIM and DICOM SEG objects
logger.debug("AVT AD RetrieveTarget = " + retrieveTarget.toString());
Map<String, ObjectLocator> objectLocators = new HashMap<String, ObjectLocator>();
File dirPath = importDir.getAbsoluteFile();
List<String> annotationUIDs = adService.findAnnotations(dicomCriteria, aimCriteria);
Set<String> uniqueAnnotUIDs = new HashSet<String>(annotationUIDs);
Iterator<String> iter = uniqueAnnotUIDs.iterator();
Iterator<ObjectDescriptor> iterObjDescsAIM = objDescsAIM.iterator();
while(iter.hasNext()){
String uid = iter.next();
ImageAnnotation loadedAnnot = adService.getAnnotation(uid);
String strXML = loadedAnnot.getAIM();
byte[] source = strXML.getBytes();
InputStream is = new ByteArrayInputStream(source);
try {
document = builder.build(is);
} catch (JDOMException e) {
logger.error(e, e);
return null;
}
File outFile = new File(dirPath + File.separator + uid);
FileOutputStream outStream = new FileOutputStream(outFile);
outToXMLFile.output(document, outStream);
outStream.flush();
outStream.close();
//retrievedFiles.add(outFile);
ObjectLocator objLoc = new ObjectLocator();
//ObjectDescriptor objDesc = objectDescriptors.get(i);
ObjectDescriptor objDesc = iterObjDescsAIM.next();
Uuid itemUUID = objDesc.getUuid();
objLoc.setUuid(itemUUID);
objLoc.setUri(outFile.getAbsolutePath());
objectLocators.put(itemUUID.getUuid(), objLoc);
//Retrieve DICOM SEG objects
Set<String> dicomSegSOPInstanceUIDs = new HashSet<String>();
List<DicomObject> segObjects = adService.retrieveSegmentationObjects(uid);
for(int j = 0; j < segObjects.size(); j++){
DicomObject dicom = segObjects.get(j);
String sopInstanceUID = dicom.getString(Tag.SOPInstanceUID);
//Check if DICOM SEG was not serialized in reference to another AIM
if(!dicomSegSOPInstanceUIDs.contains(sopInstanceUID)){
dicomSegSOPInstanceUIDs.add(sopInstanceUID);
DicomObject dicomSeg = adService.getDicomObject(sopInstanceUID);
String message = "DICOM SEG " + sopInstanceUID + " cannot be loaded from file system!";
if(dicomSeg == null){
throw new FileNotFoundException(message);
} else {
//TODO DICOM SEG tmp file not found e.g. DICOM SEG belongs to not specified Study for which TargetIteratorRunner was not requested
File outDicomSegFile = new File(dirPath + File.separator + sopInstanceUID);
FileOutputStream fos = new FileOutputStream(outDicomSegFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DicomOutputStream dout = new DicomOutputStream(bos);
dout.writeDicomFile(dicomSeg);
dout.close();
ObjectLocator dicomSegObjLoc = new ObjectLocator();
Uuid dicomSegItemUUID = new Uuid();
dicomSegItemUUID.setUuid(UUID.randomUUID().toString());
ObjectDescriptor objDescDicomSeg = new ObjectDescriptor();
objDescDicomSeg.setUuid(dicomSegItemUUID);
//TODO set MIME type, sopClass UID etc.
objectDescriptors.add(objDescDicomSeg);
dicomSegObjLoc.setUuid(dicomSegItemUUID);
dicomSegObjLoc.setUri(outDicomSegFile.getAbsolutePath());
objectLocators.put(dicomSegItemUUID.getUuid(), dicomSegObjLoc);
}
}
}
}
return objectLocators;
}
void fireResultsAvailable(Map<String, ObjectLocator> objectLocators){
RetrieveEvent event = new RetrieveEvent(objectLocators);
listener.retrieveResultsAvailable(event);
}
RetrieveListener listener;
@Override
public void addRetrieveListener(RetrieveListener l) {
listener = l;
}
}
| Modified retrieve() method in AVTRetrieve. Changed retrieve target from DICOM_AND_AIM to DICOM_AIM_SEG.
SVN-Revision: 1082
| src/edu/wustl/xipHost/avt2ext/AVTRetrieve.java | Modified retrieve() method in AVTRetrieve. Changed retrieve target from DICOM_AND_AIM to DICOM_AIM_SEG. |
|
Java | apache-2.0 | 8859f43319cc449e987f738ae010165e651e9034 | 0 | wildfly-security/wildfly-elytron,wildfly-security/wildfly-elytron | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.security.credential.store.impl;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.Provider;
import java.security.Security;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.wildfly.security.auth.server.IdentityCredentials;
import org.wildfly.security.credential.Credential;
import org.wildfly.security.credential.PasswordCredential;
import org.wildfly.security.credential.SecretKeyCredential;
import org.wildfly.security.credential.source.CredentialSource;
import org.wildfly.security.credential.store.CredentialStore;
import org.wildfly.security.credential.store.CredentialStore.CredentialSourceProtectionParameter;
import org.wildfly.security.encryption.SecretKeyUtil;
import org.wildfly.security.password.Password;
import org.wildfly.security.password.PasswordFactory;
import org.wildfly.security.password.WildFlyElytronPasswordProvider;
import org.wildfly.security.password.interfaces.ClearPassword;
import org.wildfly.security.password.spec.ClearPasswordSpec;
@RunWith(Parameterized.class)
public class KeyStoreCredentialStoreTest {
@Parameter
public String keyStoreFormat;
@Rule
public TemporaryFolder tmp = new TemporaryFolder();
private final char[] keyStorePassword = "The quick brown fox jumped over the lazy dog".toCharArray();
private PasswordFactory passwordFactory;
private String providerName;
private char[] secretPassword;
private PasswordCredential storedPasswordCredential;
private SecretKeyCredential storedSecretKeyCredential;
private CredentialSourceProtectionParameter storeProtection;
@Parameters(name = "format={0}")
public static Iterable<Object[]> keystoreFormats() {
final String vendor = System.getProperty("java.vendor");
if (vendor.contains("IBM") || vendor.toLowerCase().contains("hewlett")) {
// IBM PKCS12 does not allow storing PasswordCredential (and requires singed JAR)
// HP requires signed JAR
return Collections.singletonList(new Object[] { "JCEKS" });
} else {
return Arrays.asList(new Object[] { "JCEKS" }, new Object[] { "PKCS12" });
}
}
@Before
public void installWildFlyElytronProvider() throws Exception {
final Provider provider = WildFlyElytronPasswordProvider.getInstance();
providerName = provider.getName();
Security.addProvider(provider);
passwordFactory = PasswordFactory.getInstance(ClearPassword.ALGORITHM_CLEAR);
final Password password = passwordFactory.generatePassword(new ClearPasswordSpec(keyStorePassword));
final Credential credential = new PasswordCredential(password);
final CredentialSource credentialSource = IdentityCredentials.NONE.withCredential(credential);
storeProtection = new CredentialStore.CredentialSourceProtectionParameter(credentialSource);
secretPassword = "this is a password".toCharArray();
final Password secret = passwordFactory.generatePassword(new ClearPasswordSpec(secretPassword));
storedPasswordCredential = new PasswordCredential(secret);
storedSecretKeyCredential = new SecretKeyCredential(SecretKeyUtil.generateSecretKey(256));
}
@After
public void removeWildFlyElytronProvider() {
Security.removeProvider(providerName);
}
@Test
public void shouldSupportKeyStoreFormat() throws Exception {
final KeyStoreCredentialStore originalStore = new KeyStoreCredentialStore();
final File keyStoreFile = new File(tmp.getRoot(), "keystore");
final Map<String, String> attributes = new HashMap<>();
attributes.put("location", keyStoreFile.getAbsolutePath());
attributes.put("create", Boolean.TRUE.toString());
attributes.put("keyStoreType", keyStoreFormat);
originalStore.initialize(attributes, storeProtection, null);
originalStore.store("key", storedPasswordCredential, null);
originalStore.flush();
assertTrue(keyStoreFile.exists());
final KeyStoreCredentialStore retrievalStore = new KeyStoreCredentialStore();
attributes.put("modifiable", "false");
retrievalStore.initialize(attributes, storeProtection, null);
final PasswordCredential retrievedCredential = retrievalStore.retrieve("key", PasswordCredential.class, null,
null, null);
final ClearPasswordSpec retrievedPassword = passwordFactory.getKeySpec(retrievedCredential.getPassword(),
ClearPasswordSpec.class);
assertArrayEquals(secretPassword, retrievedPassword.getEncodedPassword());
}
@Test
public void multipleCredentialTypes() throws Exception {
final KeyStoreCredentialStore originalStore = new KeyStoreCredentialStore();
final File keyStoreFile = new File(tmp.getRoot(), "keystore");
final Map<String, String> attributes = new HashMap<>();
attributes.put("location", keyStoreFile.getAbsolutePath());
attributes.put("create", Boolean.TRUE.toString());
attributes.put("keyStoreType", keyStoreFormat);
originalStore.initialize(attributes, storeProtection, null);
originalStore.store("key", storedPasswordCredential, null);
originalStore.store("key", storedSecretKeyCredential, null);
originalStore.flush();
assertTrue(keyStoreFile.exists());
final KeyStoreCredentialStore retrievalStore = new KeyStoreCredentialStore();
retrievalStore.initialize(attributes, storeProtection, null);
Set<String> aliases = retrievalStore.getAliases();
assertEquals("Expected alias count", 1, aliases.size());
assertTrue("Expected alias 'key'", aliases.contains("key"));
final PasswordCredential retrievedPasswordCredential = retrievalStore.retrieve("key", PasswordCredential.class, null,
null, null);
final ClearPasswordSpec retrievedPassword = passwordFactory.getKeySpec(retrievedPasswordCredential.getPassword(),
ClearPasswordSpec.class);
assertArrayEquals(secretPassword, retrievedPassword.getEncodedPassword());
SecretKeyCredential retrievedSecretKeyCredential = retrievalStore.retrieve("key", SecretKeyCredential.class, null, null, null);
assertEquals("Expect SecretKeys to match", storedSecretKeyCredential.getSecretKey(), retrievedSecretKeyCredential.getSecretKey());
retrievalStore.remove("key", PasswordCredential.class, null, null);
aliases = retrievalStore.getAliases();
assertEquals("Expected alias count", 1, aliases.size());
assertTrue("Expected alias 'key'", aliases.contains("key"));
retrievalStore.remove("key", SecretKeyCredential.class, null, null);
aliases = retrievalStore.getAliases();
assertEquals("Expected alias count", 0, aliases.size());
}
@Test
public void symbolicLinkLocation() throws Exception {
final KeyStoreCredentialStore originalStore = new KeyStoreCredentialStore();
final File keyStoreFile = new File(tmp.getRoot(), "keystore");
final Map<String, String> attributes = new HashMap<>();
attributes.put("location", keyStoreFile.getAbsolutePath());
attributes.put("create", Boolean.TRUE.toString());
attributes.put("keyStoreType", "JCEKS");
originalStore.initialize(attributes, storeProtection, null);
originalStore.store("key", storedPasswordCredential, null);
originalStore.flush();
assertTrue(keyStoreFile.exists());
final KeyStoreCredentialStore retrievalStore = new KeyStoreCredentialStore();
final File symbolicLinkFile = new File(tmp.getRoot(), "link");
Assume.assumeTrue("Running on Windows without administrator privileges, test skipped.",
createSymbolicLink(symbolicLinkFile, keyStoreFile));
final Map<String, String> attributesRetrieval = new HashMap<>();
attributesRetrieval.put("location", symbolicLinkFile.getAbsolutePath());
attributesRetrieval.put("keyStoreType", "JCEKS");
retrievalStore.initialize(attributesRetrieval, storeProtection, null);
retrievalStore.store("key2", storedPasswordCredential, null);
retrievalStore.flush();
assertTrue(Files.isSymbolicLink(Paths.get(symbolicLinkFile.getAbsolutePath())));
}
private boolean createSymbolicLink(File symbolicLinkFile, File targetFile) {
try {
Files.createSymbolicLink(Paths.get(symbolicLinkFile.getAbsolutePath()), Paths.get(targetFile.getAbsolutePath()));
return true;
} catch (Exception e) {
return false;
}
}
}
| credential/store/src/test/java/org/wildfly/security/credential/store/impl/KeyStoreCredentialStoreTest.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.security.credential.store.impl;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.Provider;
import java.security.Security;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.wildfly.security.auth.server.IdentityCredentials;
import org.wildfly.security.credential.Credential;
import org.wildfly.security.credential.PasswordCredential;
import org.wildfly.security.credential.SecretKeyCredential;
import org.wildfly.security.credential.source.CredentialSource;
import org.wildfly.security.credential.store.CredentialStore;
import org.wildfly.security.credential.store.CredentialStore.CredentialSourceProtectionParameter;
import org.wildfly.security.encryption.SecretKeyUtil;
import org.wildfly.security.password.Password;
import org.wildfly.security.password.PasswordFactory;
import org.wildfly.security.password.WildFlyElytronPasswordProvider;
import org.wildfly.security.password.interfaces.ClearPassword;
import org.wildfly.security.password.spec.ClearPasswordSpec;
@RunWith(Parameterized.class)
public class KeyStoreCredentialStoreTest {
@Parameter
public String keyStoreFormat;
@Rule
public TemporaryFolder tmp = new TemporaryFolder();
private final char[] keyStorePassword = "The quick brown fox jumped over the lazy dog".toCharArray();
private PasswordFactory passwordFactory;
private String providerName;
private char[] secretPassword;
private PasswordCredential storedPasswordCredential;
private SecretKeyCredential storedSecretKeyCredential;
private CredentialSourceProtectionParameter storeProtection;
@Parameters(name = "format={0}")
public static Iterable<Object[]> keystoreFormats() {
final String vendor = System.getProperty("java.vendor");
if (vendor.contains("IBM") || vendor.toLowerCase().contains("hewlett")) {
// IBM PKCS12 does not allow storing PasswordCredential (and requires singed JAR)
// HP requires signed JAR
return Collections.singletonList(new Object[] { "JCEKS" });
} else {
return Arrays.asList(new Object[] { "JCEKS" }, new Object[] { "PKCS12" });
}
}
@Before
public void installWildFlyElytronProvider() throws Exception {
final Provider provider = WildFlyElytronPasswordProvider.getInstance();
providerName = provider.getName();
Security.addProvider(provider);
passwordFactory = PasswordFactory.getInstance(ClearPassword.ALGORITHM_CLEAR);
final Password password = passwordFactory.generatePassword(new ClearPasswordSpec(keyStorePassword));
final Credential credential = new PasswordCredential(password);
final CredentialSource credentialSource = IdentityCredentials.NONE.withCredential(credential);
storeProtection = new CredentialStore.CredentialSourceProtectionParameter(credentialSource);
secretPassword = "this is a password".toCharArray();
final Password secret = passwordFactory.generatePassword(new ClearPasswordSpec(secretPassword));
storedPasswordCredential = new PasswordCredential(secret);
storedSecretKeyCredential = new SecretKeyCredential(SecretKeyUtil.generateSecretKey(256));
}
@After
public void removeWildFlyElytronProvider() {
Security.removeProvider(providerName);
}
@Test
public void shouldSupportKeyStoreFormat() throws Exception {
final KeyStoreCredentialStore originalStore = new KeyStoreCredentialStore();
final File keyStoreFile = new File(tmp.getRoot(), "keystore");
final Map<String, String> attributes = new HashMap<>();
attributes.put("location", keyStoreFile.getAbsolutePath());
attributes.put("create", Boolean.TRUE.toString());
attributes.put("keyStoreType", keyStoreFormat);
originalStore.initialize(attributes, storeProtection, null);
originalStore.store("key", storedPasswordCredential, null);
originalStore.flush();
assertTrue(keyStoreFile.exists());
final KeyStoreCredentialStore retrievalStore = new KeyStoreCredentialStore();
attributes.put("modifiable", "false");
retrievalStore.initialize(attributes, storeProtection, null);
final PasswordCredential retrievedCredential = retrievalStore.retrieve("key", PasswordCredential.class, null,
null, null);
final ClearPasswordSpec retrievedPassword = passwordFactory.getKeySpec(retrievedCredential.getPassword(),
ClearPasswordSpec.class);
assertArrayEquals(secretPassword, retrievedPassword.getEncodedPassword());
}
@Test
public void multipleCredentialTypes() throws Exception {
final KeyStoreCredentialStore originalStore = new KeyStoreCredentialStore();
final File keyStoreFile = new File(tmp.getRoot(), "keystore");
final Map<String, String> attributes = new HashMap<>();
attributes.put("location", keyStoreFile.getAbsolutePath());
attributes.put("create", Boolean.TRUE.toString());
attributes.put("keyStoreType", keyStoreFormat);
originalStore.initialize(attributes, storeProtection, null);
originalStore.store("key", storedPasswordCredential, null);
originalStore.store("key", storedSecretKeyCredential, null);
originalStore.flush();
assertTrue(keyStoreFile.exists());
final KeyStoreCredentialStore retrievalStore = new KeyStoreCredentialStore();
retrievalStore.initialize(attributes, storeProtection, null);
Set<String> aliases = retrievalStore.getAliases();
assertEquals("Expected alias count", 1, aliases.size());
assertTrue("Expected alias 'key'", aliases.contains("key"));
final PasswordCredential retrievedPasswordCredential = retrievalStore.retrieve("key", PasswordCredential.class, null,
null, null);
final ClearPasswordSpec retrievedPassword = passwordFactory.getKeySpec(retrievedPasswordCredential.getPassword(),
ClearPasswordSpec.class);
assertArrayEquals(secretPassword, retrievedPassword.getEncodedPassword());
SecretKeyCredential retrievedSecretKeyCredential = retrievalStore.retrieve("key", SecretKeyCredential.class, null, null, null);
assertEquals("Expect SecretKeys to match", storedSecretKeyCredential.getSecretKey(), retrievedSecretKeyCredential.getSecretKey());
retrievalStore.remove("key", PasswordCredential.class, null, null);
aliases = retrievalStore.getAliases();
assertEquals("Expected alias count", 1, aliases.size());
assertTrue("Expected alias 'key'", aliases.contains("key"));
retrievalStore.remove("key", SecretKeyCredential.class, null, null);
aliases = retrievalStore.getAliases();
assertEquals("Expected alias count", 0, aliases.size());
}
@Test
public void symbolicLinkLocation() throws Exception {
final KeyStoreCredentialStore originalStore = new KeyStoreCredentialStore();
final File keyStoreFile = new File(tmp.getRoot(), "keystore");
final Map<String, String> attributes = new HashMap<>();
attributes.put("location", keyStoreFile.getAbsolutePath());
attributes.put("create", Boolean.TRUE.toString());
attributes.put("keyStoreType", "JCEKS");
originalStore.initialize(attributes, storeProtection, null);
originalStore.store("key", storedPasswordCredential, null);
originalStore.flush();
assertTrue(keyStoreFile.exists());
final KeyStoreCredentialStore retrievalStore = new KeyStoreCredentialStore();
final File symbolicLinkFile = new File(tmp.getRoot(), "link");
Files.createSymbolicLink(Paths.get(symbolicLinkFile.getAbsolutePath()), Paths.get(keyStoreFile.getAbsolutePath()));
final Map<String, String> attributesRetrieval = new HashMap<>();
attributesRetrieval.put("location", symbolicLinkFile.getAbsolutePath());
attributesRetrieval.put("keyStoreType", "JCEKS");
retrievalStore.initialize(attributesRetrieval, storeProtection, null);
retrievalStore.store("key2", storedPasswordCredential, null);
retrievalStore.flush();
assertTrue(Files.isSymbolicLink(Paths.get(symbolicLinkFile.getAbsolutePath())));
}
}
| [ELY-2383] KeyStoreCredentialStoreTest fails in Windows without administrator privileges
| credential/store/src/test/java/org/wildfly/security/credential/store/impl/KeyStoreCredentialStoreTest.java | [ELY-2383] KeyStoreCredentialStoreTest fails in Windows without administrator privileges |
|
Java | apache-2.0 | 99bb69f450b7d904942a7d643820f040b52b86df | 0 | alien11689/incubator-groovy,adjohnson916/groovy-core,nkhuyu/incubator-groovy,taoguan/incubator-groovy,guangying945/incubator-groovy,shils/incubator-groovy,russel/groovy,dpolivaev/groovy,ebourg/incubator-groovy,russel/groovy,EPadronU/incubator-groovy,aaronzirbes/incubator-groovy,antoaravinth/incubator-groovy,dpolivaev/groovy,i55ac/incubator-groovy,aaronzirbes/incubator-groovy,alien11689/incubator-groovy,EPadronU/incubator-groovy,yukangguo/incubator-groovy,apache/groovy,fpavageau/groovy,apache/incubator-groovy,samanalysis/incubator-groovy,nkhuyu/incubator-groovy,jwagenleitner/groovy,shils/incubator-groovy,adjohnson916/groovy-core,ChanJLee/incubator-groovy,nobeans/incubator-groovy,groovy/groovy-core,rlovtangen/groovy-core,sagarsane/incubator-groovy,mariogarcia/groovy-core,mariogarcia/groovy-core,jwagenleitner/incubator-groovy,russel/incubator-groovy,graemerocher/incubator-groovy,pledbrook/incubator-groovy,alien11689/groovy-core,paplorinc/incubator-groovy,sagarsane/incubator-groovy,yukangguo/incubator-groovy,traneHead/groovy-core,mariogarcia/groovy-core,ChanJLee/incubator-groovy,pickypg/incubator-groovy,samanalysis/incubator-groovy,sagarsane/groovy-core,shils/groovy,kidaa/incubator-groovy,eginez/incubator-groovy,i55ac/incubator-groovy,alien11689/groovy-core,gillius/incubator-groovy,christoph-frick/groovy-core,paplorinc/incubator-groovy,russel/incubator-groovy,antoaravinth/incubator-groovy,rabbitcount/incubator-groovy,sagarsane/incubator-groovy,bsideup/groovy-core,paulk-asert/groovy,antoaravinth/incubator-groovy,pickypg/incubator-groovy,eginez/incubator-groovy,EPadronU/incubator-groovy,fpavageau/groovy,adjohnson916/groovy-core,apache/groovy,pickypg/incubator-groovy,upadhyayap/incubator-groovy,christoph-frick/groovy-core,groovy/groovy-core,nobeans/incubator-groovy,paulk-asert/groovy,upadhyayap/incubator-groovy,groovy/groovy-core,taoguan/incubator-groovy,nkhuyu/incubator-groovy,taoguan/incubator-groovy,shils/incubator-groovy,dpolivaev/groovy,pledbrook/incubator-groovy,shils/groovy,guangying945/incubator-groovy,guangying945/incubator-groovy,kidaa/incubator-groovy,armsargis/groovy,kenzanmedia/incubator-groovy,bsideup/groovy-core,jwagenleitner/incubator-groovy,pickypg/incubator-groovy,eginez/incubator-groovy,christoph-frick/groovy-core,sagarsane/groovy-core,ebourg/groovy-core,rabbitcount/incubator-groovy,shils/groovy,bsideup/groovy-core,gillius/incubator-groovy,bsideup/incubator-groovy,upadhyayap/incubator-groovy,ebourg/groovy-core,rlovtangen/groovy-core,samanalysis/incubator-groovy,alien11689/groovy-core,genqiang/incubator-groovy,gillius/incubator-groovy,aaronzirbes/incubator-groovy,taoguan/incubator-groovy,shils/incubator-groovy,avafanasiev/groovy,eginez/incubator-groovy,ebourg/groovy-core,kidaa/incubator-groovy,apache/groovy,genqiang/incubator-groovy,fpavageau/groovy,avafanasiev/groovy,aim-for-better/incubator-groovy,jwagenleitner/incubator-groovy,i55ac/incubator-groovy,PascalSchumacher/incubator-groovy,avafanasiev/groovy,aim-for-better/incubator-groovy,jwagenleitner/groovy,yukangguo/incubator-groovy,russel/incubator-groovy,adjohnson916/groovy-core,mariogarcia/groovy-core,PascalSchumacher/incubator-groovy,adjohnson916/incubator-groovy,christoph-frick/groovy-core,gillius/incubator-groovy,russel/incubator-groovy,kenzanmedia/incubator-groovy,nobeans/incubator-groovy,paulk-asert/incubator-groovy,genqiang/incubator-groovy,ChanJLee/incubator-groovy,paplorinc/incubator-groovy,traneHead/groovy-core,PascalSchumacher/incubator-groovy,ebourg/incubator-groovy,apache/groovy,guangying945/incubator-groovy,armsargis/groovy,antoaravinth/incubator-groovy,sagarsane/incubator-groovy,tkruse/incubator-groovy,armsargis/groovy,sagarsane/groovy-core,pledbrook/incubator-groovy,graemerocher/incubator-groovy,genqiang/incubator-groovy,graemerocher/incubator-groovy,bsideup/incubator-groovy,traneHead/groovy-core,fpavageau/groovy,paulk-asert/groovy,kenzanmedia/incubator-groovy,PascalSchumacher/incubator-groovy,samanalysis/incubator-groovy,paulk-asert/incubator-groovy,ebourg/groovy-core,tkruse/incubator-groovy,apache/incubator-groovy,rlovtangen/groovy-core,nkhuyu/incubator-groovy,paulk-asert/incubator-groovy,bsideup/incubator-groovy,aim-for-better/incubator-groovy,paulk-asert/groovy,shils/groovy,apache/incubator-groovy,groovy/groovy-core,paulk-asert/incubator-groovy,adjohnson916/groovy-core,pledbrook/incubator-groovy,jwagenleitner/groovy,i55ac/incubator-groovy,christoph-frick/groovy-core,russel/groovy,kidaa/incubator-groovy,graemerocher/incubator-groovy,dpolivaev/groovy,yukangguo/incubator-groovy,paplorinc/incubator-groovy,nobeans/incubator-groovy,russel/groovy,tkruse/incubator-groovy,traneHead/groovy-core,alien11689/incubator-groovy,mariogarcia/groovy-core,alien11689/groovy-core,ebourg/incubator-groovy,rlovtangen/groovy-core,rabbitcount/incubator-groovy,paulk-asert/incubator-groovy,rlovtangen/groovy-core,sagarsane/groovy-core,jwagenleitner/groovy,adjohnson916/incubator-groovy,ChanJLee/incubator-groovy,PascalSchumacher/incubator-groovy,avafanasiev/groovy,alien11689/incubator-groovy,groovy/groovy-core,aim-for-better/incubator-groovy,ebourg/groovy-core,aaronzirbes/incubator-groovy,adjohnson916/incubator-groovy,sagarsane/groovy-core,apache/incubator-groovy,upadhyayap/incubator-groovy,armsargis/groovy,EPadronU/incubator-groovy,alien11689/groovy-core,bsideup/groovy-core,ebourg/incubator-groovy,adjohnson916/incubator-groovy,jwagenleitner/incubator-groovy,tkruse/incubator-groovy,rabbitcount/incubator-groovy,bsideup/incubator-groovy,kenzanmedia/incubator-groovy | /*
$Id$
Copyright 2003 (C) James Strachan and Bob Mcwhirter. All Rights Reserved.
Redistribution and use of this software and associated documentation
("Software"), with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions of source code must retain copyright
statements and notices. Redistributions must also contain a
copy of this document.
2. Redistributions in binary form must reproduce the
above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
3. The name "groovy" must not be used to endorse or promote
products derived from this Software without prior written
permission of The Codehaus. For written permission,
please contact [email protected].
4. Products derived from this Software may not be called "groovy"
nor may "groovy" appear in their names without prior written
permission of The Codehaus. "groovy" is a registered
trademark of The Codehaus.
5. Due credit should be given to The Codehaus -
http://groovy.codehaus.org/
THIS SOFTWARE IS PROVIDED BY THE CODEHAUS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE CODEHAUS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package groovy.lang;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.syntax.SyntaxException;
/**
* Represents a groovy shell capable of running arbitrary groovy scripts
*
* @author <a href="mailto:[email protected]">James Strachan</a>
* @version $Revision$
*/
public class GroovyShell extends GroovyObjectSupport {
public static final String[] EMPTY_ARGS = {
};
private GroovyClassLoader loader;
private ScriptContext context;
public static void main(String args[]) {
int length = args.length;
if (length <= 0) {
System.out.println("Usage: Groovy groovyScript [arguments]");
return;
}
String script = args[0];
String[] newArgs = new String[length - 1];
if (length > 1) {
System.arraycopy(args, 1, newArgs, 0, length - 1);
}
try {
GroovyShell groovy = new GroovyShell();
groovy.run(script, newArgs);
}
catch (Exception e) {
System.out.println("Caught: " + e);
e.printStackTrace();
}
}
public GroovyShell() {
this(GroovyShell.class.getClassLoader(), new ScriptContext());
}
public GroovyShell(ClassLoader parent, ScriptContext binding) {
this.loader = new GroovyClassLoader(parent);
this.context = binding;
}
public ScriptContext getContext() {
return context;
}
public Object getProperty(String property) {
Object answer = getVariable(property);
if (answer == null) {
answer = super.getProperty(property);
}
return answer;
}
public void setProperty(String property, Object newValue) {
setVariable(property, newValue);
super.setProperty(property, newValue);
}
/**
* A helper method which runs the given script file with the given command line arguments
*
* @param scriptFile the file of the script to run
* @param args the command line arguments to pass in
*/
public void run(File scriptFile, List list) throws ClassNotFoundException, SyntaxException, IOException {
String[] args = new String[list.size()];
list.toArray(args);
run(scriptFile.toString(), args);
}
/**
* Runs the given script file name with the given command line arguments
*
* @param scriptFile the file name of the script to run
* @param args the command line arguments to pass in
*/
public void run(String scriptFile, String[] args) throws ClassNotFoundException, SyntaxException, IOException {
// Get the current context classloader and save it on the stack
Thread thread = Thread.currentThread();
ClassLoader currentClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader(loader);
// Parse the script, generate the class, and invoke the main method. This is a little looser than
// if you are compiling the script because the JVM isn't executing the main method.
Class scriptClass = loader.parseClass(scriptFile);
InvokerHelper.invokeMethod(scriptClass, "main", new Object[] { args });
// Set the context classloader back to what it was.
thread.setContextClassLoader(currentClassLoader);
}
/**
* Runs the given script text with command line arguments
*
* @param scriptText is the text content of the script
* @param fileName is the logical file name of the script (which is used to create the class name of the script)
* @param args the command line arguments to pass in
*/
public void run(String scriptText, String fileName, String[] args) throws ClassNotFoundException, SyntaxException, IOException {
run(new ByteArrayInputStream(scriptText.getBytes()), fileName, args);
}
/**
* Runs the given script with command line arguments
*
* @param in the stream reading the script
* @param fileName is the logical file name of the script (which is used to create the class name of the script)
* @param args the command line arguments to pass in
*/
public Object run(InputStream in, String fileName, String[] args) throws ClassNotFoundException, SyntaxException, IOException {
Class scriptClass = loader.parseClass(in, fileName);
return InvokerHelper.invokeMethod(scriptClass, "main", new Object[] { args });
}
public Object getVariable(String name) {
return context.getVariable(name);
}
public void setVariable(String name, Object value) {
context.setVariable(name, value);
}
/**
* Evaluates some script against the current ScriptContext and returns the result
*
* @param in the stream reading the script
* @param fileName is the logical file name of the script (which is used to create the class name of the script)
*/
public Object evaluate(String scriptText, String fileName) throws SyntaxException, ClassNotFoundException, IOException {
return evaluate(new ByteArrayInputStream(scriptText.getBytes()), fileName);
}
/**
* Evaluates some script against the current ScriptContext and returns the result
*
* @param fileName is the logical file name of the script (which is used to create the class name of the script)
*/
public Object evaluate(String fileName) throws SyntaxException, ClassNotFoundException, IOException {
return evaluate(new FileInputStream(fileName), fileName);
}
/**
* Evaluates some script against the current ScriptContext and returns the result
*
* @param in the stream reading the script
* @param fileName is the logical file name of the script (which is used to create the class name of the script)
*/
public Object evaluate(InputStream in, String fileName) throws SyntaxException, ClassNotFoundException, IOException {
Class scriptClass = loader.parseClass(in, fileName);
Script script = InvokerHelper.createScript(scriptClass, context);
return script.run();
}
}
| src/main/groovy/lang/GroovyShell.java | /*
$Id$
Copyright 2003 (C) James Strachan and Bob Mcwhirter. All Rights Reserved.
Redistribution and use of this software and associated documentation
("Software"), with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions of source code must retain copyright
statements and notices. Redistributions must also contain a
copy of this document.
2. Redistributions in binary form must reproduce the
above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
3. The name "groovy" must not be used to endorse or promote
products derived from this Software without prior written
permission of The Codehaus. For written permission,
please contact [email protected].
4. Products derived from this Software may not be called "groovy"
nor may "groovy" appear in their names without prior written
permission of The Codehaus. "groovy" is a registered
trademark of The Codehaus.
5. Due credit should be given to The Codehaus -
http://groovy.codehaus.org/
THIS SOFTWARE IS PROVIDED BY THE CODEHAUS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE CODEHAUS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package groovy.lang;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.syntax.SyntaxException;
/**
* Represents a groovy shell capable of running arbitrary groovy scripts
*
* @author <a href="mailto:[email protected]">James Strachan</a>
* @version $Revision$
*/
public class GroovyShell extends GroovyObjectSupport {
public static final String[] EMPTY_ARGS = {
};
private GroovyClassLoader loader;
private ScriptContext context;
public static void main(String args[]) {
int length = args.length;
if (length <= 0) {
System.out.println("Usage: Groovy groovyScript [arguments]");
return;
}
String script = args[0];
String[] newArgs = new String[length - 1];
if (length > 1) {
System.arraycopy(args, 1, newArgs, 0, length - 1);
}
try {
GroovyShell groovy = new GroovyShell();
groovy.run(script, newArgs);
}
catch (Exception e) {
System.out.println("Caught: " + e);
e.printStackTrace();
}
}
public GroovyShell() {
this(GroovyShell.class.getClassLoader(), new ScriptContext());
}
public GroovyShell(ClassLoader parent, ScriptContext binding) {
this.loader = new GroovyClassLoader(parent);
this.context = binding;
}
public ScriptContext getContext() {
return context;
}
public Object getProperty(String property) {
Object answer = getVariable(property);
if (answer == null) {
answer = super.getProperty(property);
}
return answer;
}
public void setProperty(String property, Object newValue) {
setVariable(property, newValue);
super.setProperty(property, newValue);
}
/**
* A helper method which runs the given script file with the given command line arguments
*
* @param scriptFile the file of the script to run
* @param args the command line arguments to pass in
*/
public void run(File scriptFile, List list) throws ClassNotFoundException, SyntaxException, IOException {
String[] args = new String[list.size()];
list.toArray(args);
run(scriptFile.toString(), args);
}
/**
* Runs the given script file name with the given command line arguments
*
* @param scriptFile the file name of the script to run
* @param args the command line arguments to pass in
*/
public void run(String scriptFile, String[] args) throws ClassNotFoundException, SyntaxException, IOException {
Thread thread = Thread.currentThread();
ClassLoader currentClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader(loader);
Class scriptClass = loader.parseClass(scriptFile);
InvokerHelper.invokeMethod(scriptClass, "main", new Object[] { args });
}
/**
* Runs the given script text with command line arguments
*
* @param scriptText is the text content of the script
* @param fileName is the logical file name of the script (which is used to create the class name of the script)
* @param args the command line arguments to pass in
*/
public void run(String scriptText, String fileName, String[] args) throws ClassNotFoundException, SyntaxException, IOException {
run(new ByteArrayInputStream(scriptText.getBytes()), fileName, args);
}
/**
* Runs the given script with command line arguments
*
* @param in the stream reading the script
* @param fileName is the logical file name of the script (which is used to create the class name of the script)
* @param args the command line arguments to pass in
*/
public Object run(InputStream in, String fileName, String[] args) throws ClassNotFoundException, SyntaxException, IOException {
Class scriptClass = loader.parseClass(in, fileName);
return InvokerHelper.invokeMethod(scriptClass, "main", new Object[] { args });
}
public Object getVariable(String name) {
return context.getVariable(name);
}
public void setVariable(String name, Object value) {
context.setVariable(name, value);
}
/**
* Evaluates some script against the current ScriptContext and returns the result
*
* @param in the stream reading the script
* @param fileName is the logical file name of the script (which is used to create the class name of the script)
*/
public Object evaluate(String scriptText, String fileName) throws SyntaxException, ClassNotFoundException, IOException {
return evaluate(new ByteArrayInputStream(scriptText.getBytes()), fileName);
}
/**
* Evaluates some script against the current ScriptContext and returns the result
*
* @param fileName is the logical file name of the script (which is used to create the class name of the script)
*/
public Object evaluate(String fileName) throws SyntaxException, ClassNotFoundException, IOException {
return evaluate(new FileInputStream(fileName), fileName);
}
/**
* Evaluates some script against the current ScriptContext and returns the result
*
* @param in the stream reading the script
* @param fileName is the logical file name of the script (which is used to create the class name of the script)
*/
public Object evaluate(InputStream in, String fileName) throws SyntaxException, ClassNotFoundException, IOException {
Class scriptClass = loader.parseClass(in, fileName);
Script script = InvokerHelper.createScript(scriptClass, context);
return script.run();
}
}
| Reset the context classloader to the classloader that we saved on the stack to play nicely with application servers.
git-svn-id: aa43ce4553b005588bb3cc6c16966320b011facb@312 a5544e8c-8a19-0410-ba12-f9af4593a198
| src/main/groovy/lang/GroovyShell.java | Reset the context classloader to the classloader that we saved on the stack to play nicely with application servers. |
|
Java | apache-2.0 | 4bafb45ff28e476fa9795a7b7147100e9c7e3490 | 0 | toast2e/spring-cloud-consul,toast2e/spring-cloud-consul,toast2e/spring-cloud-consul | /*
* Copyright 2013-2015 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 org.springframework.cloud.consul.config.watch;
import static org.springframework.util.Base64Utils.decodeFromString;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.cloud.bootstrap.config.PropertySourceBootstrapConfiguration;
import org.springframework.cloud.consul.config.ConsulConfigProperties;
import org.springframework.cloud.consul.config.ConsulPropertySource;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.ConcurrentReferenceHashMap;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.kv.model.GetValue;
import lombok.extern.slf4j.Slf4j;
/**
* A kv store watch that publishes an EnvironmentChangeEvent whenever a value under one of the property sources is changed
*
* @author Andrew DePompa
*/
@Slf4j
public class ConsulConfigWatch implements ApplicationEventPublisherAware, EnvironmentAware {
private ApplicationEventPublisher publisher;
private ConfigurableEnvironment environment;
private Set<ConsulPropertySource> consulPropertySources = null;
private ConsulConfigProperties properties;
private Map<String, BigInteger> kvIndexes = new ConcurrentReferenceHashMap<String, BigInteger>();
// used to keep track of existing props in case one is deleted
private Set<String> existingProps;
public ConsulConfigWatch(ConsulConfigProperties properties) {
this.properties = properties;
}
@SuppressWarnings("boxing")
@Scheduled(fixedDelayString = "${spring.cloud.consul.config.kvWatchDelay:10}")
public void kvWatch() {
findConsulPropertySources();
Map<String, String> changedProps = new HashMap<>();
for (ConsulPropertySource source : consulPropertySources) {
long index = -1;
if(kvIndexes.get(source.getName()) != null) {
index = kvIndexes.get(source.getName()).longValue();
}
Response<List<GetValue>> response = source.getSource().getKVValues(source.getContext(),
new QueryParams(properties.getKvWatchTimeout(), index));
Long consulIndex = response.getConsulIndex();
if (consulIndex != null) {
Set<String> deletedProps = new HashSet<String>(existingProps);
kvIndexes.put(source.getName(), BigInteger.valueOf(consulIndex));
if (index != consulIndex) {
if (response.getValue() != null) {
for (GetValue getValue : response.getValue()) {
if (getValue.getModifyIndex() > index) {
changedProps.put(getValue.getKey(), getValue.getValue() == null ? "" : new String(decodeFromString(getValue.getValue())));
existingProps.add(getValue.getKey().replace(source.getContext(), "").replace("/", "."));
}
deletedProps.remove(getValue.getKey().replace(source.getContext(), "").replace("/", "."));
}
for(String key : deletedProps){
changedProps.put(key, null);
existingProps.remove(key.replace(source.getContext(), "").replace("/", "."));
}
}
}
}
}
if (changedProps.size() > 0) {
log.trace("Received kv update from consul: {}", changedProps.toString());
publisher.publishEvent(new ConsulKeyValueChangeEvent(changedProps));
}
}
private void findConsulPropertySources() {
if (consulPropertySources == null) {
if(existingProps == null) {
existingProps = new HashSet<String>();
}
consulPropertySources = new HashSet<ConsulPropertySource>();
if (environment.getPropertySources()
.get(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME) instanceof CompositePropertySource) {
CompositePropertySource bootstrapPropertySource = ((CompositePropertySource) environment.getPropertySources()
.get(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME));
if (bootstrapPropertySource != null) {
Collection<PropertySource<?>> sources = bootstrapPropertySource.getPropertySources();
for (PropertySource<?> source : sources) {
if (source.getName().equals("consul")) {
CompositePropertySource consulPropertySource = (CompositePropertySource) source;
for (PropertySource<?> consulSource : consulPropertySource.getPropertySources()) {
consulPropertySources.add((ConsulPropertySource) consulSource);
existingProps.addAll(Arrays.asList(((ConsulPropertySource) consulSource).getPropertyNames()));
}
break;
}
}
}
}
}
}
@Override
public void setEnvironment(Environment environment) {
if (environment instanceof ConfigurableEnvironment) {
this.environment = (ConfigurableEnvironment) environment;
}
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
}
| spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/watch/ConsulConfigWatch.java | /*
* Copyright 2013-2015 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 org.springframework.cloud.consul.config.watch;
import static org.springframework.util.Base64Utils.decodeFromString;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.cloud.bootstrap.BootstrapApplicationListener;
import org.springframework.cloud.consul.config.ConsulConfigProperties;
import org.springframework.cloud.consul.config.ConsulPropertySource;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.ConcurrentReferenceHashMap;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.kv.model.GetValue;
import lombok.extern.slf4j.Slf4j;
/**
* A kv store watch that publishes an EnvironmentChangeEvent whenever a value under one of the property sources is changed
*
* @author Andrew DePompa
*/
@Slf4j
public class ConsulConfigWatch implements ApplicationEventPublisherAware, EnvironmentAware {
private ApplicationEventPublisher publisher;
private ConfigurableEnvironment environment;
private Set<ConsulPropertySource> consulPropertySources = null;
private ConsulConfigProperties properties;
private Map<String, BigInteger> kvIndexes = new ConcurrentReferenceHashMap<String, BigInteger>();
// used to keep track of existing props in case one is deleted
private Set<String> existingProps;
public ConsulConfigWatch(ConsulConfigProperties properties) {
this.properties = properties;
}
@SuppressWarnings("boxing")
@Scheduled(fixedDelayString = "${spring.cloud.consul.config.kvWatchDelay:10}")
public void kvWatch() {
findConsulPropertySources();
Map<String, String> changedProps = new HashMap<>();
for (ConsulPropertySource source : consulPropertySources) {
source.init();
long index = -1;
if(kvIndexes.get(source.getName()) != null) {
index = kvIndexes.get(source.getName()).longValue();
}
Response<List<GetValue>> response = source.getSource().getKVValues(source.getContext(),
new QueryParams(properties.getKvWatchTimeout(), index));
Long consulIndex = response.getConsulIndex();
if (consulIndex != null) {
Set<String> deletedProps = new HashSet<String>(existingProps);
kvIndexes.put(source.getName(), BigInteger.valueOf(consulIndex));
if (index != consulIndex) {
if (response.getValue() != null) {
for (GetValue getValue : response.getValue()) {
if (getValue.getModifyIndex() > index) {
changedProps.put(getValue.getKey(), getValue.getValue() == null ? "" : new String(decodeFromString(getValue.getValue())));
existingProps.add(getValue.getKey().replace(source.getContext(), "").replace("/", "."));
}
deletedProps.remove(getValue.getKey().replace(source.getContext(), "").replace("/", "."));
}
for(String key : deletedProps){
changedProps.put(key, null);
existingProps.remove(key.replace(source.getContext(), "").replace("/", "."));
}
}
}
}
}
if (changedProps.size() > 0) {
log.trace("Received kv update from consul: {}", changedProps.toString());
publisher.publishEvent(new ConsulKeyValueChangeEvent(changedProps));
}
}
private void findConsulPropertySources() {
if (consulPropertySources == null) {
if(existingProps == null) {
existingProps = new HashSet<String>();
}
consulPropertySources = new HashSet<ConsulPropertySource>();
if (environment.getPropertySources()
.get(BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME) instanceof CompositePropertySource) {
CompositePropertySource bootstrapPropertySource = ((CompositePropertySource) environment.getPropertySources()
.get(BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME));
if (bootstrapPropertySource != null) {
Collection<PropertySource<?>> sources = bootstrapPropertySource.getPropertySources();
for (PropertySource<?> source : sources) {
if (source.getName().equals("consul")) {
CompositePropertySource consulPropertySource = (CompositePropertySource) source;
for (PropertySource<?> consulSource : consulPropertySource.getPropertySources()) {
consulPropertySources.add((ConsulPropertySource) consulSource);
existingProps.addAll(Arrays.asList(((ConsulPropertySource) consulSource).getPropertyNames()));
}
break;
}
}
}
}
}
}
@Override
public void setEnvironment(Environment environment) {
if (environment instanceof ConfigurableEnvironment) {
this.environment = (ConfigurableEnvironment) environment;
}
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
}
| Changes incorrect bootstrap property source name and removes unnecessary property source reinit
| spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/watch/ConsulConfigWatch.java | Changes incorrect bootstrap property source name and removes unnecessary property source reinit |
|
Java | apache-2.0 | e69e37a0ce7104e6a1cadf5bf66085ba634e6d18 | 0 | eFaps/eFaps-Kernel,ov3rflow/eFaps-Kernel | /*
* Copyright 2006 The eFaps Team
*
* 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.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.admin.datamodel.attributetype;
import java.util.Locale;
/**
*
*/
public class LinkWithRanges extends AbstractLinkType {
/////////////////////////////////////////////////////////////////////////////
/**
* @param _locale locale object
*/
public String getViewableString(Locale _locale) {
return ""+getValue();
}
} | kernel/src/main/java/org/efaps/admin/datamodel/attributetype/LinkWithRanges.java | /*
* Copyright 2005 The eFaps Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.efaps.admin.datamodel.attributetype;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import org.efaps.admin.user.Person;
import org.efaps.admin.user.Role;
import org.efaps.db.Context;
import org.efaps.db.SearchQuery;
import org.efaps.admin.ui.Field;
import org.efaps.admin.datamodel.Attribute;
/**
*
*/
public class LinkWithRanges extends AbstractLinkType {
/////////////////////////////////////////////////////////////////////////////
/**
* @param _locale locale object
*/
public String getViewableString(Locale _locale) {
return ""+getValue();
}
} | - added svn properties
- header updated to new version
- removed unneeded imports
git-svn-id: 4b3b87045ec33e1a2f7ddff44705baa56df11711@113 fee104cc-1dfa-8c0f-632d-d3b7e6b59fb0
| kernel/src/main/java/org/efaps/admin/datamodel/attributetype/LinkWithRanges.java | - added svn properties - header updated to new version - removed unneeded imports |
|
Java | apache-2.0 | f6d198a1aac2a9387e74ccb97876096db0adeb5c | 0 | danc86/jena-core,danc86/jena-core | /*
(c) Copyright 2003, Hewlett-Packard Development Company, LP
[See end of file]
*/
package com.hp.hpl.jena.db.impl;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.CRC32;
import com.hp.hpl.jena.datatypes.RDFDatatype;
import com.hp.hpl.jena.datatypes.TypeMapper;
import com.hp.hpl.jena.db.GraphRDB;
import com.hp.hpl.jena.db.IDBConnection;
import com.hp.hpl.jena.db.RDFRDBException;
import com.hp.hpl.jena.db.impl.DBIDInt;
import com.hp.hpl.jena.graph.Graph;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Node_Literal;
import com.hp.hpl.jena.graph.Node_URI;
import com.hp.hpl.jena.graph.Node_Variable;
import com.hp.hpl.jena.graph.impl.LiteralLabel;
import com.hp.hpl.jena.rdf.model.AnonId;
import com.hp.hpl.jena.shared.*;
import com.hp.hpl.jena.vocabulary.RDF;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xerces.util.XMLChar;
//=======================================================================
/**
* Base database driver for implementing SpecializedGraphs.
* Different drivers are needed for different databases and different
* layout schemes.
* <p>
* This driver is a base implemention from which database-specific
* drivers can inherit. It is not generic in the sense that it will work
* on any minimal SQL store and so should be treated as if it were
* an abstract class.
* <p>The SQL statements which implement each of the functions are
* loaded in a separate file etc/[layout]_[database].sql from the classpath.
*
* @author hkuno modification of Jena1 code by Dave Reynolds (der)
* @version $Revision: 1.43 $ on $Date: 2004-07-25 16:19:10 $
*/
public abstract class DriverRDB implements IRDBDriver {
//=======================================================================
// Cutomization variables
// =======================================================================
/**
* This Graph's db properties
*/
protected DBPropDatabase m_dbProps;
/**
* Name of this class's PSet_TripleStore_XXX class
*/
protected String m_psetClassName;
/**
* Name of this class's PSet_TripleStore_XXX class
*/
protected String m_psetReifierClassName;
/**
* Cached name of this class's SpecializedGraph_XXX class
*/
protected String m_lsetClassName;
/**
* Cached name of this class's SpecializedGraphReifer_XXX class
*/
protected String m_lsetReifierClassName;
/** The class name of the database driver (e.g. jdbc.sql.class)*/
protected String DRIVER_NAME;
// Dummy - needs replacing when instantiated?
/** The name of the database type this driver supports */
protected String DATABASE_TYPE;
/** The maximum size of index key (or a component of a key) */
protected int INDEX_KEY_LENGTH;
/** The maximum possible value for INDEX_KEY_LENGTH (db-dependent) */
protected int INDEX_KEY_LENGTH_MAX;
/** true if graphs using this database instance supports transactions.
* this is a user settable parameter. the underlying db engine may support
* transactions but an application may prefer to run without transactions
* for better performance. this can only be set before the db is formatted.
*/
protected boolean IS_XACT_DB;
protected boolean STRINGS_TRIMMED;
/** true if the database engine will trim trailing spaces in strings. to
* prevent this, append EOS to strings that should not be trimmed.
*/
protected String EOS = "";
protected char EOS_CHAR = ':';
protected int EOS_LEN = 0;
/** EOS is appended to most RDB strings to deal with string trimming. if
* STRINGS_TRIMMED is false, EOS is null. otherwise, EOS is EOS_CHAR.
* EOS_LEN is the length of EOS (0 or 1).
*/
protected char QUOTE_CHAR = '\"';
/** the quote character used to delimit characters and strings.
*/
/**
* Indicates whether search pattern used to select system objects by name should be upper-case.
*/
protected boolean DB_NAMES_TO_UPPER = false;
/** true if URI's are to be compressed by storing prefixes (an approximation
* of a namespace) in the JENA_PREFIX table. note that "short" prefixes are
* not stored, i.e., the prefix length not more than URI_COMPRESS_LENGTH.
*/
protected boolean URI_COMPRESS;
protected int URI_COMPRESS_LENGTH = 100;
/** if URI_COMPRESS is true, compress prefixes that are longer than this.
/** The maximum size of an object that can be stored in a Statement table */
protected int LONG_OBJECT_LENGTH;
/** The maximum possible value for LONG_OBJECT_LENGTH (db-dependent) */
protected int LONG_OBJECT_LENGTH_MAX;
/** The SQL type to use for storing ids (compatible with wrapDBID) */
protected String ID_SQL_TYPE;
/** Set to true if the insert operations already check for duplications */
protected boolean SKIP_DUPLICATE_CHECK;
/** Set to true if IDs are allocated prior to insert */
protected boolean PRE_ALLOCATE_ID;
/** The name of the sql definition file for this database/layout combo */
protected String SQL_FILE;
/** The name of the sql definition file for this database/layout combo */
protected String DEFAULT_SQL_FILE = "etc/generic_generic.sql";
// =======================================================================
// Common variables
// =======================================================================
/**
* Holds prefix for names of Jena database tables.
*/
protected String TABLE_NAME_PREFIX = "jena_";
/**
* Holds maximum length of table and index names in database.
*/
protected int TABLE_NAME_LENGTH_MAX;
/**
* Holds the length of the longest jena table or index name.
* This is really a hack and should be better architected.
* The currently known longest possible name is:
* <prefix>GnTm_StmtXSP where prefix is the table
* name prefix (which isn't counted here), n is the
* graph identifier, m is the table number within that
* graph and XSP refers to the subject-predicate index.
* If we assume n and m might be two digits, we get 14.
*/
protected int JENA_LONGEST_TABLE_NAME_LENGTH = 14;
/** Set to true to enable cache of pre-prepared statements */
protected boolean CACHE_PREPARED_STATEMENTS = true;
/** The name of the layout type this driver supports */
protected String LAYOUT_TYPE = "TripleStore";
/** Default name of the table that holds system property graph asserted statements **/
protected String SYSTEM_STMT_TABLE;
/** Name of the long literal table **/
protected String LONG_LIT_TABLE;
/** Name of the long URI table **/
protected String LONG_URI_TABLE;
/** Name of the prefix table **/
protected String PREFIX_TABLE;
/** Name of the graph table **/
protected String GRAPH_TABLE;
/** If not null, newly-created graphs share tables with the identified graph **/
protected String STORE_WITH_MODEL = null;
/** Name of the graph holding default properties (the one's that a newly-created
* graph will have by default **/
protected final String DEFAULT_PROPS = "JENA_DEFAULT_GRAPH_PROPERTIES";
/** Unique numeric identifier of the graph holding default properties **/
protected final int DEFAULT_ID = 0;
/** Driver version number */
protected final String VERSION = "2.0alpha";
/** Database layout version */
protected String LAYOUT_VERSION = "2.0";
protected static Log logger = LogFactory.getLog( PSet_ReifStore_RDB.class );
// =======================================================================
// Instance variables
// =======================================================================
/**
* Instance of SQLCache used by Driver for hard-coded db commands
*/
protected SQLCache m_sql = null;
/** Cache a reference to the system property graph (java) **/
protected SpecializedGraph m_sysProperties = null;
protected IDBConnection m_dbcon = null;
protected LRUCache prefixCache = null;
public static final int PREFIX_CACHE_SIZE = 50;
//===================================
// for transaction support
//===================================
// caches whether or not underlying connection supports transactions
private Boolean m_transactionsSupported;
/** flag to indicate that there is a transaction active on the associated connection */
protected boolean inTransaction = false;
// =======================================================================
// Constructor
// =======================================================================
/**
* Create a bare instance of the driver. It is not functional until a
* database connection has been supplied via setConnection.
*/
public DriverRDB() {
}
// =======================================================================
// Methods
// =======================================================================
/**
* Return the connection
*/
public IDBConnection getConnection() {
return m_dbcon;
}
/**
* Return the specialized graph used to store system properties.
* (Constuct a new one if necessary).
*/
public SpecializedGraph getSystemSpecializedGraph() {
if (m_sysProperties != null) {
return m_sysProperties;
}
setTableNames(TABLE_NAME_PREFIX);
try {
if( !isDBFormatOK() ) {
// Format the DB
cleanDB();
prefixCache = new LRUCache(PREFIX_CACHE_SIZE);
return formatAndConstructSystemSpecializedGraph();
}
} catch (Exception e) {
// We see an error during format testing, might be a dead
// connection rather than an unformated database so abort
throw new JenaException("The database appears to be unformatted or corrupted.\n" +
"If possible, call IDBConnection.cleanDB(). \n" +
"Warning: cleanDB will remove all Jena models from the databases.");
}
prefixCache = new LRUCache(PREFIX_CACHE_SIZE);
getDbInitTablesParams(); //this call is a hack. it's needed because
// it has the side effect of initializing some vars (e.g., EOS).
IPSet pSet = createIPSetInstanceFromName(m_psetClassName, SYSTEM_STMT_TABLE);
m_sysProperties = createLSetInstanceFromName(m_lsetClassName, pSet, DEFAULT_ID);
m_dbProps = new DBPropDatabase(m_sysProperties);
// now reset the configuration parameters
checkEngine(m_dbProps);
checkDriverVersion(m_dbProps);
checkLayoutVersion(m_dbProps);
String val = m_dbProps.getLongObjectLength();
if ( val == null ) throwBadFormat("long object length");
else LONG_OBJECT_LENGTH = Integer.parseInt(val);
val = m_dbProps.getIndexKeyLength();
if ( val == null ) throwBadFormat("index key length");
else INDEX_KEY_LENGTH = Integer.parseInt(val);
val = m_dbProps.getIsTransactionDb();
if ( val == null ) throwBadFormat("database supports transactions");
else IS_XACT_DB = Boolean.valueOf(val).booleanValue();
val = m_dbProps.getDoCompressURI();
if ( val == null ) throwBadFormat("compress URIs");
else URI_COMPRESS = Boolean.valueOf(val).booleanValue();
val = m_dbProps.getCompressURILength();
if ( val == null ) throwBadFormat("URI compress length");
else URI_COMPRESS_LENGTH = Integer.parseInt(val);
val = m_dbProps.getTableNamePrefix();
if ( val == null ) throwBadFormat("table name prefix");
else TABLE_NAME_PREFIX = val;
return m_sysProperties;
}
private void checkEngine ( DBProp dbProps ) {
String dbtype = m_dbProps.getEngineType();
if ( dbtype == null ) throwBadFormat("database type");
if ( !dbtype.equals(DATABASE_TYPE) ) {
throw new JenaException(
"Database created with incompatible database type for this version of Jena: "
+ dbtype);
}
}
private void checkDriverVersion ( DBProp dbProps ) {
String vers = m_dbProps.getDriverVersion();
if ( vers == null ) throwBadFormat("database version");
if ( !vers.equals(VERSION) ) {
throw new JenaException(
"Models in the database were created with an incompatible version of Jena: "
+ vers);
}
}
private void checkLayoutVersion ( DBProp dbProps ) {
String layout = m_dbProps.getLayoutVersion();
if ( layout == null ) throwBadFormat("database layout");
if ( !layout.equals(LAYOUT_VERSION) ) {
throw new JenaException(
"The database layout cannot be processed by this version of Jena: "
+ layout);
}
}
private void throwBadFormat ( String prop ) {
throw new JenaException(
"The database appears to be unformatted or corrupted - could not find value\n" +
" for \"" + prop + "\" in Jena system properties table.\n" +
"If possible, call IDBConnection.cleanDB(). \n" +
"Warning: cleanDB will remove all Jena models from the databases.");
}
/**
* Format the database and construct a brand new system specialized graph.
*/
protected SpecializedGraph formatAndConstructSystemSpecializedGraph() {
try {
String [] params = getDbInitTablesParams();
m_sql.runSQLGroup("initDBtables", params);
m_sql.runSQLGroup("initDBgenerators");// m_sql.runSQLGroup("initDBprocedures");
} catch (SQLException e) {
logger.warn("Problem formatting database", e);
throw new RDFRDBException("Failed to format database", e);
}
// Construct the system properties
IPSet pSet = createIPSetInstanceFromName(m_psetClassName, SYSTEM_STMT_TABLE);
m_sysProperties = createLSetInstanceFromName(m_lsetClassName, pSet, DEFAULT_ID);
// The following call constructs a new set of database properties and
// adds them to the m_sysProperties specialized graph.
m_dbProps = new DBPropDatabase( m_sysProperties, m_dbcon.getDatabaseType(),
VERSION, LAYOUT_VERSION,String.valueOf(LONG_OBJECT_LENGTH),
String.valueOf(INDEX_KEY_LENGTH), String.valueOf(IS_XACT_DB),
String.valueOf(URI_COMPRESS), String.valueOf(URI_COMPRESS_LENGTH),
TABLE_NAME_PREFIX);
// Now we also need to construct the parameters that will be the
// default settings for any graph added to this database
DBPropGraph def_prop = new DBPropGraph( m_sysProperties, DEFAULT_PROPS, "generic");
def_prop.addGraphId(DEFAULT_ID);
return m_sysProperties;
}
abstract String[] getDbInitTablesParams();
abstract String[] getCreateTableParams( int graphId, boolean isReif );
abstract public int graphIdAlloc ( String graphName );
/**
* Construct and return a new specialized graph.
* @param graphProperties A set of customization properties for the specialized graph.
*/
public List createSpecializedGraphs(DBPropGraph graphProperties) {
String graphName = graphProperties.getName();
String stmtTbl = null;
String reifTbl = null;
String dbSchema = STORE_WITH_MODEL;
int graphId = graphIdAlloc(graphName);
graphProperties.addGraphId(graphId);
boolean useDefault = false;
// dbSchema = graphProperties.getDBSchema();
// use the default schema if:
// 1) no schema is specified and we are creating the default (unnamed) graph
// 2) a schema is specified and it is the default (unnamed) graph
if ( ((dbSchema == null) && graphName.equals(GraphRDB.DEFAULT)) ) {
useDefault = true;
dbSchema = DEFAULT_PROPS; // default graph should use default tables
}
// else if ( ((dbSchema != null) && dbSchema.equals(GraphRDB.DEFAULT)) ) {
// useDefault = true;
// dbSchema = DEFAULT_PROPS; // default graph should use default tables
// }
if ( dbSchema != null ) {
DBPropGraph schProp = DBPropGraph.findPropGraphByName(getSystemSpecializedGraph(),
dbSchema );
if ( schProp != null ) {
reifTbl = schProp.getReifTable();
stmtTbl = schProp.getStmtTable();
}
if ( ((reifTbl == null) || (stmtTbl == null)) && (useDefault == false) )
// schema not found. this is ok ONLY IF it's the DEFAULT schema
throw new RDFRDBException("Creating graph " + graphName +
": referenced schema not found: " + dbSchema);
}
if ( (reifTbl == null) || (stmtTbl == null) ) {
reifTbl = createTable(graphId, true);
stmtTbl = createTable(graphId, false);
if ( (reifTbl == null) || (stmtTbl == null) )
throw new RDFRDBException("Creating graph " + graphName +
": cannot create tables");
}
graphProperties.addStmtTable(stmtTbl);
graphProperties.addReifTable(reifTbl);
// Add the reifier first
DBPropPSet pSetReifier = new DBPropPSet(m_sysProperties, m_psetReifierClassName, reifTbl);
DBPropLSet lSetReifier = new DBPropLSet(m_sysProperties, "LSET_"+graphProperties.getName()+"_REIFIER", m_lsetReifierClassName);
lSetReifier.setPSet(pSetReifier);
graphProperties.addLSet(lSetReifier);
// Now add support for all non-reified triples
DBPropPSet pSet = new DBPropPSet(m_sysProperties, m_psetClassName, stmtTbl);
DBPropLSet lSet = new DBPropLSet(m_sysProperties, "LSET_"+graphProperties.getName(), m_lsetClassName);
lSet.setPSet(pSet);
graphProperties.addLSet(lSet);
return recreateSpecializedGraphs( graphProperties );
}
/**
* Construct and return a list of specialized graphs to match those in the store.
* @param graphProperties A set of customization properties for the graph.
*/
public List recreateSpecializedGraphs(DBPropGraph graphProperties) {
List result = new ArrayList();
int dbGraphId = graphProperties.getGraphId();
// to ensure that reifier graphs occur before stmt graphs, make two passes
String[] lsetTypes = {m_lsetClassName, m_lsetReifierClassName};
int i;
for(i=0;i<2;i++) {
Iterator it = graphProperties.getAllLSets();
while(it.hasNext() ) {
DBPropLSet lSetProps = (DBPropLSet)it.next();
if ( lSetProps.getType().equals(lsetTypes[i]) ) continue;
DBPropPSet pSetProps = lSetProps.getPset();
IPSet pSet = createIPSetInstanceFromName(pSetProps.getType(), pSetProps.getTable());
result.add( createLSetInstanceFromName( lSetProps.getType(), pSet, dbGraphId));
}
}
return result;
}
/**
* Create a new IPSet instance of the named implementation class and set the db connection.
*
* @param pName name of a class that implements IPSet.
* @return an instance of the named class with the db connection set.
*/
private IPSet createIPSetInstanceFromName(String className, String tblName) {
IPSet pSet = null;
try {
// get PSet
pSet = (IPSet) Class.forName(className).newInstance();
pSet.setDriver(this);
pSet.setSQLType(ID_SQL_TYPE);
pSet.setSkipDuplicateCheck(SKIP_DUPLICATE_CHECK);
pSet.setSQLCache(m_sql);
pSet.setCachePreparedStatements(CACHE_PREPARED_STATEMENTS);
pSet.setTblName(tblName);
} catch (Exception e) {
logger.warn("Unable to create IPSet instance ", e);
}
return pSet;
}
private SpecializedGraph createLSetInstanceFromName(String lSetName, IPSet pset, int dbGraphID) {
SpecializedGraph sg = null;
try {
Class cls = Class.forName(lSetName);
Class[] params = {IPSet.class, Integer.class};
java.lang.reflect.Constructor con = cls.getConstructor(params);
Object[] args = {pset, new Integer(dbGraphID)};
sg = (SpecializedGraph) con.newInstance(args);
} catch (Exception e) {
logger.error("Unable to create instance of SpecializedGraph ", e);
}
return sg;
}
/**
* Remove the specialized graph, erasing all trace of a Graph.
* @param graphId The identity of the Graph which these specialized graphs should hold
* @param graphProperties The properties for the graph to be removed.
*/
public void removeSpecializedGraphs( DBPropGraph graphProperties,
List specializedGraphs) {
int graphId = graphProperties.getGraphId();
Iterator it = specializedGraphs.iterator();
while (it.hasNext()){
SpecializedGraph sg = (SpecializedGraph) it.next();
removeSpecializedGraph(sg);
}
String stmtTbl = graphProperties.getStmtTable();
String reifTbl = graphProperties.getReifTable();
// remove from system properties table
// It is sufficient just to remove the lSet properties (it will
// take care of deleting any pset properties automatically).
m_dbProps.removeGraph(graphProperties);
// drop the tables if they are no longer referenced
if ( graphId != DEFAULT_ID ) {
boolean stInUse = false;
boolean rtInUse = false;
it = m_dbProps.getAllGraphs();
while ( it.hasNext() ) {
DBPropGraph gp = (DBPropGraph) it.next();
if ( gp.getStmtTable().equals(stmtTbl) ) stInUse = true;
if ( gp.getReifTable().equals(reifTbl) ) rtInUse = true;
}
if ( stInUse == false ) deleteTable(stmtTbl);
if ( rtInUse == false ) deleteTable(reifTbl);
graphIdDealloc(graphId);
}
}
/**
* Remove specialized graph from the datastore.
* @param graph is the graph to be removed.
*/
private void removeSpecializedGraph(SpecializedGraph graph) {
graph.clear();
}
/**
* Method setDatabaseProperties.
*
* Sets the current properties for the database.
*
* @param databaseProperties is a Graph containing a full set of database properties
*/
public void setDatabaseProperties(Graph databaseProperties) {
SpecializedGraph toGraph = getSystemSpecializedGraph();
// really need to start a transaction here
// Here add code to check if the database has been used - if so,
// it's too late to change the properties, so throw an exception
toGraph.clear();
SpecializedGraph.CompletionFlag complete = new SpecializedGraph.CompletionFlag();
toGraph.add(databaseProperties, complete);
// Now test the properties to see if it's a valid set - if not,
// throw an exception - it's okay to check some things later (there's
// no guarantee that every error will be caught here).
// end transaction here.
}
/**
* Method getDefaultModelProperties
*
* Return the default properties for a new model stored in this database.
* If none are stored, then load default properties into the database.
* @return Graph containg the default properties for a new model
*/
public DBPropGraph getDefaultModelProperties() {
SpecializedGraph sg = getSystemSpecializedGraph();
DBPropGraph result = DBPropGraph.findPropGraphByName(sg, DEFAULT_PROPS);
if (result == null) {
logger.error("No default Model Properties found");
// Construct the parameters that will be the
// default settings for any graph added to this database
//new DBPropGraph( m_sysProperties, "default", "generic");
//result = DBPropGraph.findPropGraph(sg, "default");
}
return result;
}
/**
* Test if the database has previously been formatted.
*
* @return boolean true if database is correctly formatted, false on any error.
*/
public boolean isDBFormatOK() {
boolean result = false;
try {
ResultSet alltables = getAllTables();
int i = 0;
while ( alltables.next() ) i++;
alltables.close();
result = i >= 5;
} catch (Exception e1) {
// An exception might be a totally unformatted db (why??)
// or a real connection problem.
return false;
// throw new JenaException("DB connection problem while testing formating", e1);
}
return result;
}
/**
* Converts string to form accepted by database.
*/
public String stringToDBname(String aName) {
String result = (DB_NAMES_TO_UPPER) ? aName.toUpperCase() : aName;
return(result);
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.graphRDB.IRDBDriver#cleanDB()
*/
public void cleanDB() {
try {
ResultSet alltables = getAllTables();
List tablesPresent = new ArrayList(10);
while (alltables.next()) {
tablesPresent.add(alltables.getString("TABLE_NAME"));
}
alltables.close();
Iterator it = tablesPresent.iterator();
while (it.hasNext()) {
m_sql.runSQLGroup("dropTable", (String) it.next());
}
if (PRE_ALLOCATE_ID) {
clearSequences();
}
} catch (SQLException e1) {
throw new RDFRDBException("Internal SQL error in driver", e1);
}
m_sysProperties = null;
if ( prefixCache != null ) prefixCache.clear();
prefixCache = null;
}
private ResultSet getAllTables() {
try {
DatabaseMetaData dbmd = m_dbcon.getConnection().getMetaData();
String[] tableTypes = { "TABLE" };
String prefixMatch = stringToDBname(TABLE_NAME_PREFIX + "%");
return dbmd.getTables(null, null, prefixMatch, tableTypes);
} catch (SQLException e1) {
throw new RDFRDBException("Internal SQL error in driver", e1);
}
}
/**
* Drop all Jena-related sequences from database, if necessary.
* Override in subclass if sequences must be explicitly deleted.
*/
public void clearSequences() {
}
/**
* Removes named sequence from the database, if it exists.
* @param seqName
*/
public void removeSequence(String seqName) {
if (sequenceExists(seqName)) {
try {
m_sql.runSQLGroup("DropSequence",seqName);
} catch (Exception e) {
logger.warn("Unable to drop sequence " + seqName, e);
}
}
}
/**
* Check database and see if named sequence exists.
* @param seqName
*/
public boolean sequenceExists(String seqName) {
Object[] args = {seqName};
ResultSet rs = null;
boolean result = false;
try {
String op = "SelectSequenceName";
PreparedStatement ps = m_sql.getPreparedSQLStatement(op);
ps.setString(1,seqName);
rs = ps.executeQuery();
result = rs.next();
m_sql.returnPreparedSQLStatement(ps);
} catch (Exception e) {
logger.error("Unable to select sequence " + seqName, e);
}
return result;
}
/**
* Check database and see if named sequence exists.
* @param seqName
*/
public List getSequences() {
List results = new ArrayList(10);
Object[] args = {};
ResultSetIterator it = null;
try {
String opname = "SelectJenaSequences";
PreparedStatement ps = m_sql.getPreparedSQLStatement(opname, TABLE_NAME_PREFIX);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
results.add(rs.getString(1));
}
//rs.close();
m_sql.returnPreparedSQLStatement(ps);
} catch (Exception e) {
logger.error("Unable to select Jena sequences: ", e);
}
return results;
}
/**
* Initialise a database ready to store RDF tables.
* @throws RDFDBException if the is a problem opening the connection or an internal SQL error.
* @deprecated Since Jena 2.0 this call is no longer needed - formatting
* happens automatically as a side effect of creating Models - there should
* be no need for an application to interact directly with the driver.
*/
public void formatDB() throws RDFRDBException {
}
/**
* Create a table for storing asserted or reified statements.
*
* @param graphId the graph which the table is created.
* @param isReif true if table stores reified statements.
* @return the name of the new table
*
*/
public String createTable( int graphId, boolean isReif) {
String opname = isReif ? "createReifStatementTable" : "createStatementTable";
int i = 0;
String params[];
while ( true ) {
params = getCreateTableParams(graphId, isReif);
try {
m_sql.runSQLGroup(opname, params);
break;
} catch (SQLException e) {
i++;
if ( i > 5 ) {
logger.warn("Problem creating table", e);
throw new RDFRDBException("Failed to create table: " + params[0], e);
}
}
}
return params[0];
}
/**
* Delete a table.
*
* @param tableName the name of the table to delete. *
*/
public void deleteTable( String tableName ) {
String opname = "dropTable";
try {
PreparedStatement ps = m_sql.getPreparedSQLStatement(opname, tableName);
ps.executeUpdate();
return;
} catch (Exception e1) {
throw new RDFRDBException("Failed to delete table ", e1);
}
}
/**
* Throws an UnsupportedOperation exception.
*
* @param opName name of the operation that's not supported.
*/
private void notSupported(String opName)
{ throw new UnsupportedOperationException(opName); }
/**
* If underlying database connection supports transactions, call abort()
* on the connection, then turn autocommit on.
*/
public synchronized void abort() throws RDFRDBException {
if (transactionsSupported()) {
try {
if (inTransaction) {
Connection c = m_sql.getConnection();
c.rollback();
c.commit();
c.setAutoCommit(true);
inTransaction = false;
}
} catch (SQLException e) {
throw new JenaException("Transaction support failed: ", e);
}
} else {
}
}
/**
* If the underlying database connection supports transactions,
* turn autocommit off, then begin a new transaction.
* Note that transactions are associated with connections, not with
* Models. This
*/
public synchronized void begin() throws RDFRDBException {
if (transactionsSupported()) {
try {
if (!inTransaction) {
// Starting a transaction could require us to lose any cached prepared statements
// for some jdbc drivers, currently I think all the drivers we use are safe and
// is a major performance hit so commented out for now.
//m_sql.flushPreparedStatementCache();
Connection c = m_sql.getConnection();
c.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
c.setAutoCommit(false);
inTransaction = true;
}
} catch (SQLException e) {
throw new RDFRDBException("Transaction support failed: ", e);
}
} else
{ notSupported("begin transaction"); }
}
/**
* If the underlying database connection supports transactions,
* call commit(), then turn autocommit on.
*/
public void commit() throws RDFRDBException{
if (transactionsSupported()) {
try {
if (inTransaction) {
Connection c = m_sql.getConnection();
c.commit();
c.setAutoCommit(true);
// not sure why read_uncommitted is set, below. commented out by kw.
// c.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
inTransaction = false;
}
} catch (SQLException e) {
throw new RDFRDBException("Transaction support failed: ", e);
}
} else {
notSupported("commit transaction");
}
}
/**
* Return a string identifying underlying database type.
*
*/
public String getDatabaseType() {
return(DATABASE_TYPE);
}
/**
* Returns true if the underlying database supports transactions.
*/
public boolean transactionsSupported() {
if (m_transactionsSupported != null) {
return(m_transactionsSupported.booleanValue());
}
if (m_dbcon != null) {
try {
Connection c = m_sql.getConnection();
if ( c != null) {
m_transactionsSupported = new Boolean(c.getMetaData().supportsMultipleTransactions());
return(m_transactionsSupported.booleanValue());
}
} catch (SQLException e) {
logger.error("SQL Exception caught ", e);
}
}
return (false);
}
//--------------------------------------------------jena 1 backward compatability
/**
* Close the driver
*
* Nothing to do for now.
*
* @throws RDFDBException if there is an access problem
* @deprecated Since Jena 2.0 this call is no longer required - just
* close the DBConnection - there should be no need for an application
* to interact directly with the driver.
*
*/
public void close() throws RDFRDBException {
}
/**
* Returns true if the database layout supports multiple RDF models
* in the same database.
* @deprecated Since Jena 2.0 all databases support multiple models.
*/
public boolean supportsMultipleModels() {
return true;
}
/**
* Returns true if the database layout supports implicit reification
* of statements (i.e. statements can be treated as resources).
* @deprecated Since Jena 2.0 the reification API has changed. The
* new API is supported in all models, but the old Jena 1 API is no
* longer supported. This call will return false to indicate
* to old code that the old style of jena reification is not supported.
*/
public boolean supportsJenaReification() {
return false;
}
/*
* The following routines are responsible for encoding nodes
* as database structures. For each node type stored (currently,
* literals, URI, blank), there are two possible encodings
* depending on the node size. Small nodes may be stored
* within a statement table. If the node is long (will not
* fit within the statement table), it is be stored in a
* separate table for that node type.
*
* In addition, for resources (URI, blank nodes), the URI
* may be optionally compressed. Below, the possibilites
* are enumerated.
*
* Literal Encoding in Statement Tables
* Short Literal: Lv:[langLen]:[datatypeLen]:[langString][datatypeString]value[:]
* Long Literal: Lr:dbid
* Literal Encoding in Long Literal Table
* Literal: Lv:[langLen]:[datatypeLen]:[langString][datatypeString]head[:] hash tail
*
* Comments:
* L indicates a literal
* v indicates a value
* r indicates a reference to another table
* : is used as a delimiter. note that MySQL trims trailing white space for
* certain VARCHAR columns so an extra delimiter is appended when necessary
* for those columns. it is not required for dbid, however.
* dbid references the long literal table
* langLen is the length of the language identifier for the literal
* langString is the language identifier
* datatypeLen is the length of the datatype for the literal
* datatypeString is the datatype for the literal
* value is the lexical form of the string
* head is a prefix of value that can be indexed
* hash is the CRC32 hash value for the tail
* tail is the remainder of the value that cannot be indexed
*
*
*
* URI Encoding in Statement Tables
* Short URI: Uv:[pfx_dbid]:URI[:]
* Long URI: Ur:[pfx_dbid]:dbid
* URI Encoding in Long URI Table
* URI: Uv:head[:] hash tail
*
* Comments:
* U indicates a URI
* pfx_dbid references the prefix table. if the prefix is too
* short (i.e., the length of the prefix is less than
* URI_COMPRESS_LENGTH), the URI is not compressed and
* pfx_dbid is null.
* URI is the complete URI
* other notation same as for literal encoding
*
* Blank Node Encoding in Statement Tables
* Short URI: Bv:[pfx_dbid]:bnid[:]
* Long URI: Br:[pfx_dbid]:dbid
* Blank Encoding in Long URI Table
* URI: Bv:head[:] hash tail
*
* Comments:
* B indicates a blank node
* bnid is the blank node identifier
* other notation same as above
* Note: currently, blank nodes are always stored uncompressed (pfix_dbid is null).
*
* Variable Node Encoding in Statement Tables
* Variable Node: Vv:name
*
* Comments:
* V indicates a variable node
* v indicates a value
* name is the variable name
* Note: the length must be less than LONG_OBJECT_LENGTH
*
* ANY Node Encoding in Statement Tables
* Variable Node: Av:
*
* Prefix Encoding in Prefix Table
* Prefix: Pv:val[:] [hash] [tail]
*
* Comments:
* P indicates a prefix
* other notation same as above
* hash and tail are only required for long prefixes.
*
*/
protected static String RDBCodeURI = "U";
protected static String RDBCodeBlank = "B";
protected static String RDBCodeLiteral = "L";
protected static String RDBCodeVariable = "V";
protected static String RDBCodeANY = "A";
protected static String RDBCodePrefix = "P";
protected static String RDBCodeValue = "v";
protected static String RDBCodeRef = "r";
protected static String RDBCodeDelim = ":";
protected static char RDBCodeDelimChar = ':';
protected static String RDBCodeInvalid = "X";
/**
* Convert a node to a string to be stored in a statement table.
* @param Node The node to convert to a string. Must be a concrete node.
* @param addIfLong If the node is a long object and is not in the database, add it.
* @return the string or null if failure.
*/
public String nodeToRDBString ( Node node, boolean addIfLong ) throws RDFRDBException {
String res = null;
if ( node.isURI() ) {
String uri = new String(((Node_URI) node).getURI());
if ( uri.startsWith(RDBCodeURI) ) {
throw new RDFRDBException ("URI Node looks like a blank node: " + uri );
}
// TODO: need to write special version of splitNamespace for rdb.
// or else, need a guarantee that splitNamespace never changes.
// the problem is that if the splitNamespace algorithm changes,
// then URI's may be encoded differently. so, URI's in existing
// databases may become inaccessible.
int pos = 0;
boolean noCompress;
String pfx;
String qname;
if ( URI_COMPRESS == true ) {
pos = dbSplitNamespace(uri);
noCompress = (pos == uri.length()) || (pos <= URI_COMPRESS_LENGTH);
} else
noCompress = true;
if ( noCompress ) {
pfx = RDBCodeDelim + RDBCodeDelim;
qname = uri;
} else {
// see if it's cached
DBIDInt pfxid = URItoPrefix(uri, pos, addIfLong);
if ( pfxid == null ) return res;
pfx = RDBCodeDelim + ((DBIDInt)pfxid).getIntID() + RDBCodeDelim;
qname = uri.substring(pos);
}
int encodeLen = RDBCodeURI.length() + 1 + pfx.length() + EOS_LEN;
boolean URIisLong = objectIsLong(encodeLen,qname);
if ( URIisLong ) {
int dbid;
// belongs in URI table
DBIDInt URIid = getURIID(qname,addIfLong);
if ( URIid == null ) return res;
dbid = URIid.getIntID();
res = new String(RDBCodeURI + RDBCodeRef + pfx + dbid);
} else {
res = RDBCodeURI + RDBCodeValue + pfx + qname + EOS;
}
} else if ( node.isLiteral() ){
// TODO: may need to encode literal value when datatype is not a string.
Node_Literal litNode = (Node_Literal) node;
LiteralLabel ll = litNode.getLiteral();
String lval = ll.getLexicalForm();
String lang = ll.language();
String dtype = ll.getDatatypeURI();
String ld = litLangTypeToRDBString(lang,dtype);
int encodeLen = RDBCodeLiteral.length() + 2 + ld.length() + EOS_LEN;
boolean litIsLong = objectIsLong(encodeLen,lval);
if ( litIsLong ) {
int dbid;
// belongs in literal table
DBIDInt lid = getLiteralID(litNode,addIfLong);
if ( lid == null ) return res;
dbid = lid.getIntID();
res = new String(RDBCodeLiteral + RDBCodeRef + RDBCodeDelim + dbid);
} else {
res = new String(RDBCodeLiteral + RDBCodeValue + RDBCodeDelim + ld + lval + EOS);
}
} else if ( node.isBlank() ) {
String bnid = node.getBlankNodeId().toString();
String delims = "::";
int encodeLen = RDBCodeBlank.length() + 1 + delims.length() + EOS_LEN;
boolean BisLong = objectIsLong(encodeLen,bnid);
if ( BisLong ) {
int dbid;
// belongs in URI table
DBIDInt URIid = getBlankID(bnid,addIfLong);
if ( URIid == null ) return res;
dbid = URIid.getIntID();
res = new String(RDBCodeBlank + RDBCodeRef + delims + dbid);
} else {
res = new String(RDBCodeBlank + RDBCodeValue + delims + bnid + EOS);
}
} else if ( node.isVariable() ){
String name = ((Node_Variable)node).getName();
int len = name.length();
if ( (len + 3 + EOS_LEN) > LONG_OBJECT_LENGTH )
throw new JenaException ("Variable name too long: " + name );
res = RDBCodeVariable + RDBCodeValue + RDBCodeDelim + name + EOS;
} else if ( node.equals(Node.ANY) ) {
res = RDBCodeANY + RDBCodeValue + RDBCodeDelim;
} else {
throw new RDFRDBException ("Expected Concrete Node, got " + node.toString() );
}
return res;
}
/**
* Convert an RDB string to the node that it encodes. Return null if failure.
* @param RDBstring The string to convert to a node.
* @return The node or null if failure.
*/
public Node RDBStringToNode ( String RDBString ) throws RDFRDBException {
Node res = null;
int len = RDBString.length();
if ( len < 3 )
throw new RDFRDBException("Bad RDBString Header: " + RDBString);
String nodeType = RDBString.substring(0,1);
String valType = RDBString.substring(1,2);
if ( (!(valType.equals(RDBCodeRef) || valType.equals(RDBCodeValue))) ||
(RDBString.charAt(2) != RDBCodeDelimChar) )
throw new RDFRDBException("Bad RDBString Header: " + RDBString);
int pos = 3;
int npos;
if ( nodeType.equals(RDBCodeURI) ) {
ParseInt pi = new ParseInt(pos);
String prefix = "";
RDBStringParseInt(RDBString, pi, false);
if ( pi.val != null ) {
if ( URI_COMPRESS == false )
throw new RDFRDBException("Bad URI: Prefix Compression Disabled: " + RDBString);
prefix = IDtoPrefix(pi.val.intValue());
if ( prefix == null )
throw new RDFRDBException("Bad URI Prefix: " + RDBString);
}
pos = pi.pos + 1;
String qname;
if ( valType.equals(RDBCodeRef) ) {
qname = IDtoURI(RDBString.substring(pos));
if ( qname == null )
throw new RDFRDBException("Bad URI: " + RDBString);
} else
qname = RDBString.substring(pos,len - EOS_LEN);
res = Node.createURI(prefix + qname);
} else if ( nodeType.equals(RDBCodeLiteral) ) {
ParseInt pi = new ParseInt(pos);
String litString = null;
if ( valType.equals(RDBCodeRef) ) {
RDBStringParseInt(RDBString,pi,true);
if ( pi.val != null )
litString = IDtoLiteral(pi.val.intValue());
if ( litString == null )
throw new RDFRDBException("Bad Literal Reference: " + RDBString);
} else
litString = RDBString.substring(pos,len-EOS_LEN);
len = litString.length();
String lang;
String dtype;
int langLen = 0;
int dtypeLen = 0;
LiteralLabel llabel;
pi.pos = 0;
RDBStringParseInt(litString, pi, false);
if ( pi.val == null ) langLen = 0;
else langLen = pi.val.intValue();
pi.pos = pi.pos + 1;
RDBStringParseInt(litString, pi, false);
if ( pi.val == null ) dtypeLen = 0;
else dtypeLen = pi.val.intValue();
pos = pi.pos + 1;
if ( (pos + langLen + dtypeLen) > len )
throw new RDFRDBException("Malformed Literal: " + litString);
lang = litString.substring(pos,pos+langLen);
pos = pos + langLen;
dtype = litString.substring(pos,pos+dtypeLen);
pos = pos + dtypeLen;
String val = litString.substring(pos);
if ( (dtype == null) || (dtype.equals("")) ) {
llabel = new LiteralLabel(val, lang == null ? "" : lang);
} else {
RDFDatatype dt = TypeMapper.getInstance().getSafeTypeByName(dtype);
llabel = new LiteralLabel(val, lang == null ? "" : lang, dt);
}
res = Node.createLiteral(llabel);
} else if ( nodeType.equals(RDBCodeBlank) ) {
String bstr = null;
if ( valType.equals(RDBCodeValue) ) {
bstr = RDBString.substring(4,len-EOS_LEN);
} else {
bstr = IDtoBlank(RDBString.substring(4));
if ( bstr == null )
throw new RDFRDBException("Bad URI: " + RDBString);
}
res = Node.createAnon( new AnonId (bstr) );
} else if ( nodeType.equals(RDBCodeVariable) ) {
String vname = RDBString.substring(3,len-EOS_LEN);
res = Node.createVariable(vname);
} else if ( nodeType.equals(RDBCodeANY) ) {
res = Node.ANY;
} else
throw new RDFRDBException ("Invalid RDBString Prefix, " + RDBString );
return res;
}
/** This is cuurently a copy of Util.splitNamespace. It was
* copied rather than used directly for two reasons. 1) in the
* future it may be desirable to use a different split algorithm
* for persistence. 2) the util version could change at any time,
* which would render existing databases inaccessible. having a
* copy allows the db version to evolve in a controlled way.
*
* Given an absolute URI, determine the split point between the namespace part
* and the localname part.
* If there is no valid localname part then the length of the
* string is returned.
* The algorithm tries to find the longest NCName at the end
* of the uri, not immediately preceeded by the first colon
* in the string.
* @param uri
* @return the index of the first character of the localname
*/
public static int dbSplitNamespace(String uri) {
char ch;
int lg = uri.length();
if (lg == 0)
return 0;
int j;
int i;
for (i = lg - 1; i >= 1; i--) {
ch = uri.charAt(i);
if (!XMLChar.isNCName(ch))
break;
}
for (j = i + 1; j < lg; j++) {
ch = uri.charAt(j);
if (XMLChar.isNCNameStart(ch)) {
if (uri.charAt(j - 1) == ':'
&& uri.lastIndexOf(':', j - 2) == -1)
continue; // split "mailto:me" as "mailto:m" and "e" !
else
break;
}
}
return j;
}
class ParseInt {
int pos;
Integer val;
ParseInt(int p) {pos = p;}
}
protected void RDBStringParseInt ( String RDBString, ParseInt pi, boolean toEnd ) {
int npos = toEnd ? RDBString.length() : RDBString.indexOf(RDBCodeDelimChar,pi.pos);
if ( npos < 0 ) {
throw new RDFRDBException("Bad RDB String: " + RDBString);
}
String intStr = RDBString.substring(pi.pos,npos);
pi.pos = npos;
if ( intStr.equals("") )
pi.val = null;
else try {
pi.val = new Integer(intStr);
} catch (NumberFormatException e1) {
throw new RDFRDBException("Bad RDB String: " + RDBString);
}
return;
}
DBIDInt URItoPrefix ( String uri, int pos, boolean add ) {
DBIDInt res;
Object key = prefixCache.getByValue(uri.substring(0,pos));
if ( key == null ) {
RDBLongObject lobj = PrefixToLongObject(uri,pos);
res = getLongObjectID(lobj, PREFIX_TABLE, add);
if ( res != null )
prefixCache.put(res,uri.substring(0,pos));
} else
res = (DBIDInt) key;
return res;
}
protected RDBLongObject PrefixToLongObject ( String prefix, int split ) {
RDBLongObject res = new RDBLongObject();
int headLen;
int avail;
res.head = RDBCodePrefix + RDBCodeValue + RDBCodeDelim;
headLen = res.head.length();
avail = INDEX_KEY_LENGTH - (headLen + EOS_LEN);
if ( split > avail ) {
res.head = res.head + prefix.substring(0,avail);
res.tail = prefix.substring(avail,split);
res.hash = stringToHash(res.tail);
} else {
res.head = res.head + prefix.substring(0,split);
res.tail = "";
}
res.head = res.head + EOS;
return res;
}
/**
* Encode a literal node's lang and datatype as a string of the
* form ":[langLen]:[datatypeLen]:[langString][dataTypeString]"
* @return the string.
*/
public String litLangTypeToRDBString ( String lang, String dtype ) throws RDFRDBException {
String res = RDBCodeDelim;
res = ((lang == null) ? "" : Integer.toString(lang.length())) + RDBCodeDelim;
res = res + ((dtype == null) ? "" : Integer.toString(dtype.length())) + RDBCodeDelim;
res = res + (lang == null ? "" : lang) + (dtype == null ? "" : dtype);
return res;
}
/**
* Check if an object is long, i.e., it exceeds the length
* limit for storing in a statement table.
* @return true if literal is long, else false.
*/
protected boolean objectIsLong ( int encodingLen, String objAsString ) {
return ( (encodingLen + objAsString.length()) > LONG_OBJECT_LENGTH);
}
class RDBLongObject {
String head; /* prefix of long object that can be indexed */
long hash; /* hash encoding of tail */
String tail; /* remainder of long object */
}
protected RDBLongObject literalToLongObject ( Node_Literal node ) {
RDBLongObject res = new RDBLongObject();
int headLen;
int avail;
LiteralLabel l = node.getLiteral();
String lang = l.language();
String dtype = l.getDatatypeURI();
String val = l.getLexicalForm();
String langType = litLangTypeToRDBString(lang,dtype);
res.head = RDBCodeLiteral + RDBCodeValue + RDBCodeDelim + langType;
headLen = res.head.length();
avail = INDEX_KEY_LENGTH - (headLen + EOS_LEN);
if ( val.length() > avail ) {
res.head = res.head + val.substring(0,avail);
res.tail = val.substring(avail);
res.hash = stringToHash(res.tail);
} else {
res.head = res.head + val;
res.tail = "";
}
res.head = res.head + EOS;
return res;
}
protected long stringToHash ( String str ) {
CRC32 checksum = new CRC32();
checksum.update(str.getBytes());
return checksum.getValue();
}
/**
* Return the database ID for the URI, if it exists
*/
public DBIDInt getBlankID(String bstr, boolean add) throws RDFRDBException {
RDBLongObject lobj = URIToLongObject (bstr,RDBCodeBlank);
return getLongObjectID(lobj, LONG_URI_TABLE, add);
}
/**
* Return the database ID for the URI, if it exists
*/
public DBIDInt getURIID(String qname, boolean add) throws RDFRDBException {
RDBLongObject lobj = URIToLongObject (qname,RDBCodeURI);
return getLongObjectID(lobj, LONG_URI_TABLE, add);
}
protected RDBLongObject URIToLongObject ( String qname, String code ) {
RDBLongObject res = new RDBLongObject();
int headLen;
int avail;
res.head = code + RDBCodeValue + RDBCodeDelim;
headLen = res.head.length();
avail = INDEX_KEY_LENGTH - (headLen + EOS_LEN);
if ( qname.length() > avail ) {
res.head = res.head + qname.substring(0,avail);
res.tail = qname.substring(avail);
res.hash = stringToHash(res.tail);
} else {
res.head = res.head + qname;
res.tail = "";
}
res.head = res.head + EOS;
return res;
}
/**
* Return the database ID for the literal, if it exists
*/
public DBIDInt getLiteralID(Node_Literal lnode, boolean add) throws RDFRDBException {
RDBLongObject lobj = literalToLongObject (lnode);
return getLongObjectID(lobj, LONG_LIT_TABLE, add);
}
public DBIDInt getLongObjectID(RDBLongObject lobj, String table, boolean add) throws RDFRDBException {
try {
String opName = "getLongObjectID";
if ( lobj.tail.length() > 0 )
opName += "withChkSum";
PreparedStatement ps = m_sql.getPreparedSQLStatement(opName, table);
ps.setString(1,lobj.head);
if ( lobj.tail.length() > 0 )
ps.setLong(2, lobj.hash);
ResultSet rs = ps.executeQuery();
DBIDInt result = null;
if (rs.next()) {
result = wrapDBID(rs.getObject(1));
} else {
if ( add )
result = addRDBLongObject(lobj, table);
}
m_sql.returnPreparedSQLStatement(ps);
return result;
} catch (SQLException e1) {
// /* DEBUG */ System.out.println("Literal truncation (" + l.toString().length() + ") " + l.toString().substring(0, 150));
throw new RDFRDBException("Failed to find literal", e1);
}
}
/**
* Insert a long object into the database.
* This assumes the object is not already in the database.
* @return the db index of the added literal
*/
public DBIDInt addRDBLongObject(RDBLongObject lobj, String table) throws RDFRDBException {
try {
int argi = 1;
String opname = "insertLongObject";
PreparedStatement ps = m_sql.getPreparedSQLStatement(opname, table);
int dbid = 0; // init only needed to satisy java compiler
if ( PRE_ALLOCATE_ID ) {
dbid = getInsertID(table);
ps.setInt(argi++,dbid);
}
ps.setString(argi++, lobj.head);
if ( lobj.tail.length() > 0 ) {
ps.setLong(argi++, lobj.hash);
ps.setString(argi++, lobj.tail);
} else {
ps.setNull(argi++,java.sql.Types.BIGINT);
ps.setNull(argi++,java.sql.Types.VARCHAR);
}
/* if (isBlob || (len == 0) ) {
// First convert the literal to a UTF-16 encoded byte array
// (this wouldn't be needed for jdbc 2.0 drivers but not all db's have them)
byte[] temp = lit.getBytes("UTF-8");
int lenb = temp.length;
//System.out.println("utf-16 len = " + lenb);
byte[] litData = new byte[lenb + 4];
litData[0] = (byte)(lenb & 0xff);
litData[1] = (byte)((lenb >> 8) & 0xff);
litData[2] = (byte)((lenb >> 16) & 0xff);
litData[3] = (byte)((lenb >> 24) & 0xff);
System.arraycopy(temp, 0, litData, 4, lenb);
// Oracle has its own way to insert Blobs
if (isBlob && m_driver.getDatabaseType().equalsIgnoreCase("Oracle")) {
//TODO fix to use Blob
// For now, we do not support Blobs under Oracle
throw new RDFRDBException("Oracle driver does not currently support large literals.");
} else {
ps.setBinaryStream(argi++, new ByteArrayInputStream(litData), litData.length);
}
}
*/
ps.executeUpdate();
//m_sql.returnPreparedSQLStatement(ps,opname);
if ( !PRE_ALLOCATE_ID ) dbid = getInsertID(table);
return wrapDBID(new Integer(dbid));
} catch (Exception e1) {
/* DEBUG */ System.out.println("Problem on long object (l=" + lobj.head + ") " + e1 );
// System.out.println("ID is: " + id);
throw new RDFRDBException("Failed to add long object ", e1);
}
}
/**
* Return the prefix string that has the given prefix id.
* @param prefixID - the dbid of the prefix.
* @return the prefix string or null if it does not exist.
*/
protected String IDtoPrefix ( int prefixID ) {
// check cache
DBIDInt dbid = new DBIDInt(prefixID);
Object res = prefixCache.get(dbid);
if ( res != null)
return (String) res;
else
return IDtoString ( prefixID, PREFIX_TABLE, RDBCodePrefix);
}
/**
* Return the Blank node string that has the given database id.
* @param bnID - the dbid of the blank node, as a string.
* @return the Blank node string or null if it does not exist.
*/
protected String IDtoBlank(String bnID) {
return IDtoString(bnID, LONG_URI_TABLE, RDBCodeBlank);
}
/**
* Return the URI string that has the given database id.
* @param uriID - the dbid of the uri, as a string.
* @return the uri string or null if it does not exist.
*/
protected String IDtoURI(String uriID) {
return IDtoString(uriID, LONG_URI_TABLE, RDBCodeURI);
}
/**
* Return the long literal string that has the given database id.
* @param litID - the dbid of the literal..
* @return the long literal string or null if it does not exist.
*/
protected String IDtoLiteral ( int litID ) {
return IDtoString ( litID, LONG_LIT_TABLE, RDBCodeLiteral);
}
protected String IDtoString ( String dbidAsString, String table, String RDBcode ) {
int dbID;
String res = null;
try {
dbID = Integer.parseInt(dbidAsString);
} catch (NumberFormatException e1) {
throw new RDFRDBException("Invalid Object ID: " + dbidAsString);
}
return IDtoString (dbID, table, RDBcode);
}
protected String IDtoString ( int dbID, String table, String RDBcode ) {
String res = null;
RDBLongObject lobj = IDtoLongObject(dbID, table);
if ( lobj == null )
throw new RDFRDBException("Invalid Object ID: " + dbID);
// debug check
if ( !lobj.head.substring(0,3).equals(RDBcode + RDBCodeValue + RDBCodeDelim) )
throw new RDFRDBException("Malformed URI in Database: " + lobj.head);
res = lobj.head.substring(3,lobj.head.length() - EOS_LEN);
if ( lobj.tail != null )
res = res + lobj.tail;
return res;
}
protected RDBLongObject IDtoLongObject ( int dbid, String table ) {
RDBLongObject res = null;
try {
String opName = "getLongObject";
PreparedStatement ps = m_sql.getPreparedSQLStatement(opName, table);
ps.setInt(1,dbid);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
res = new RDBLongObject();
res.head = rs.getString(1);
res.tail = rs.getString(2);
}
m_sql.returnPreparedSQLStatement(ps);
} catch (SQLException e1) {
// /* DEBUG */ System.out.println("Literal truncation (" + l.toString().length() + ") " + l.toString().substring(0, 150));
throw new RDFRDBException("Failed to find literal", e1);
}
return res;
}
protected RDBLongObject IDtoLongObject ( String idAsString, String table ) {
RDBLongObject res = null;
int dbid;
try {
dbid = Integer.parseInt(idAsString);
} catch (NumberFormatException e1) {
throw new RDFRDBException("Invalid Object ID: " + idAsString);
}
return IDtoLongObject(dbid,table);
}
/**
* Convert the raw SQL object used to store a database identifier into a java object
* which meets the DBIDInt interface.
*/
public DBIDInt wrapDBID(Object id) throws RDFRDBException {
if (id instanceof Number) {
return new DBIDInt(((Number)id).intValue());
} else if (id == null) {
return null;
} else {
throw new RDFRDBException("Unexpected DB identifier type: " + id);
//return null;
}
}
public String genSQLReifQualStmt () {
return "stmt = ?";
}
public String genSQLReifQualAnyObj( boolean objIsStmt) {
return "( subj = ? OR prop = ? OR obj = ?" + (objIsStmt ? " OR hasType = " +
QUOTE_CHAR + "T" + QUOTE_CHAR + " )" : " )");
}
public String genSQLReifQualObj ( char reifProp, boolean hasObj ) {
String qual = "";
if ( reifProp == 'T' ) {
qual = "hasType = " + QUOTE_CHAR + "T" + QUOTE_CHAR;
} else {
String cmp = (hasObj ? " = ?" : " is not null");
String col = null;
if ( reifProp == 'S' ) col = "subj";
else if ( reifProp == 'P' ) col = "prop";
else if ( reifProp == 'O' ) col = "obj";
else throw new JenaException("Undefined reification property");
qual = col + cmp;
}
return qual;
}
protected String colidToColname ( char colid ) {
if ( colid == 'G' ) return "GraphID";
if ( colid == 'P' ) return "Prop";
if ( colid == 'S' ) return "Subj";
if ( colid == 'O' ) return "Obj";
if ( colid == 'N' ) return "Stmt";
if ( colid == 'T' ) return "HasType";
throw new JenaException("Invalid column identifer: '" + colid + "\'");
}
protected String aliasToString ( int alias ) {
return "A" + alias;
}
protected String colAliasToString ( int alias, char colid ) {
return aliasToString(alias) + "." + colidToColname(colid);
}
/*
* there's a bug in the code below in that the literal is converted to
* a string BEFORE the query is run. consequently, there's a race
* condition. if the (long) literal is not in the database
* when the query is compiled but is added prior to running the
* query, then the query will (incorrectly) return no results.
* for now, we'll ignore this case and document it as a bug.
*/
public String genSQLQualConst ( int alias, char pred, Node lit ) {
String val = nodeToRDBString(lit, false);
if ( val == "" )
// constant not in database.
// should really optimize this and not
// even run the query but ok for now.
val = RDBCodeInvalid;
return colAliasToString(alias,pred) + "=" + QUOTE_CHAR + val + QUOTE_CHAR;
}
public String genSQLReifQualConst ( int alias, char pred, Node lit ) {
String val = "";
if ( (pred == 'T') && (lit.equals(RDF.Nodes.Statement)) )
val = "T";
else
val = nodeToRDBString(lit, false);
return colAliasToString(alias,pred) + "=" + QUOTE_CHAR + val + QUOTE_CHAR;
}
public String genSQLQualParam( int alias, char pred ) {
return colAliasToString(alias,pred) + "=?";
}
public String genSQLQualGraphId( int alias, int graphId ) {
return colAliasToString(alias,'G') + "=" + graphId;
}
public String genSQLJoin( int lhsAlias, char lhsCol,
int rhsAlias, char rhsCol ) {
return colAliasToString(lhsAlias,lhsCol) + "=" +
colAliasToString(rhsAlias,rhsCol);
}
public String genSQLResList( int resIndex[], VarDesc[] binding ) {
String resList = "";
int i,j;
for(i=0,j=0;i<binding.length;i++) {
VarDesc b = binding[i];
if ( !b.isArgVar() ) {
// next result variable
resList += (j>0?", ":"") + colAliasToString(b.alias,b.column);
if ( j >= resIndex.length )
throw new JenaException("Too many result columns");
resIndex[j++] = b.mapIx;
}
}
return resList;
}
public String genSQLFromList( int aliasCnt, String table ) {
int i;
String resList = "";
for(i=0;i<aliasCnt;i++) {
resList += (i>0?", ":"") + table + " " + aliasToString(i);
}
return resList;
}
public String genSQLSelectKW() {
return "Select ";
}
public String genSQLFromKW() {
return "From ";
}
public String genSQLWhereKW() {
return "Where ";
}
public String genSQLSelectStmt( String res, String from, String qual ) {
return genSQLSelectKW() + res + " " +
genSQLFromKW() + from + " " +
(qual.length() == 0 ? qual :genSQLWhereKW()) + qual;
}
protected int getTableCount(int graphId) {
try {
DatabaseMetaData dbmd = m_dbcon.getConnection().getMetaData();
String[] tableTypes = { "TABLE" };
int res = 0;
String tblPattern =
TABLE_NAME_PREFIX + "g" + Integer.toString(graphId) + "%";
tblPattern = stringToDBname(tblPattern);
ResultSet alltables =
dbmd.getTables(null, null, tblPattern, tableTypes);
while (alltables.next()) {
res += 1;
}
alltables.close();
return res;
} catch (SQLException e1) {
throw new RDFRDBException("Internal SQL error in driver", e1);
}
}
/*
* getters and setters for database options
*/
public int getLongObjectLength () {
return LONG_OBJECT_LENGTH;
}
public void setLongObjectLength ( int len ) {
checkDbUninitialized();
if ( len > LONG_OBJECT_LENGTH_MAX )
throw new JenaException("IndexKeyLength exceeds maximum value for database");
LONG_OBJECT_LENGTH = len;
}
public int getIndexKeyLength () {
return INDEX_KEY_LENGTH;
}
public void setIndexKeyLength ( int len ) {
checkDbUninitialized();
if ( len > INDEX_KEY_LENGTH_MAX )
throw new JenaException("IndexKeyLength exceeds maximum value for database");
INDEX_KEY_LENGTH = len;
}
public boolean getIsTransactionDb () {
return IS_XACT_DB;
}
public void setIsTransactionDb ( boolean bool ) {
checkDbUninitialized();
if ( bool == false )
throw new JenaException("setIsTransactionDb unsupported for this database engine");
}
public boolean getDoCompressURI () {
return URI_COMPRESS;
}
public void setDoCompressURI ( boolean bool ) {
checkDbUninitialized();
URI_COMPRESS = bool;
}
public int getCompressURILength() {
return URI_COMPRESS_LENGTH;
}
public void setCompressURILength ( int len ) {
checkDbUninitialized();
URI_COMPRESS_LENGTH = len;
}
public boolean getDoDuplicateCheck() {
return !SKIP_DUPLICATE_CHECK;
}
public void setDoDuplicateCheck(boolean bool) {
SKIP_DUPLICATE_CHECK = !bool;
}
protected boolean dbIsOpen() {
return (m_sysProperties != null);
}
protected void checkDbIsOpen() {
if ( !dbIsOpen() )
throw new JenaException("Database not open");
}
protected void checkDbUninitialized() {
if ( dbIsOpen() || (isDBFormatOK() == true))
throw new JenaException("Database configuration option cannot be set after database is formatted");
}
public String getTableNamePrefix() {
return TABLE_NAME_PREFIX;
}
public void setTableNamePrefix ( String prefix ) {
if ( (prefix.length() + JENA_LONGEST_TABLE_NAME_LENGTH) >
TABLE_NAME_LENGTH_MAX )
throw new JenaException("TableNamePrefix exceeds maximum length for database: " + TABLE_NAME_LENGTH_MAX);
if ( dbIsOpen() )
throw new JenaException("Table name prefix must be set before opening or connecting to a model.");
setTableNames(prefix);
}
private void setTableNames ( String prefix ) {
TABLE_NAME_PREFIX = stringToDBname(prefix);
SYSTEM_STMT_TABLE = TABLE_NAME_PREFIX + "sys_stmt";
LONG_LIT_TABLE = TABLE_NAME_PREFIX + "long_lit";
LONG_URI_TABLE = TABLE_NAME_PREFIX + "long_uri";
PREFIX_TABLE = TABLE_NAME_PREFIX + "prefix";
GRAPH_TABLE = TABLE_NAME_PREFIX + "graph";
}
public String getStoreWithModel() {
return STORE_WITH_MODEL;
}
public void setStoreWithModel(String modelName) {
String name = null;
if ((modelName != null) && !modelName.equals(""))
name = modelName;
STORE_WITH_MODEL = name;
}
public int getCompressCacheSize() {
checkDbIsOpen();
return prefixCache.getLimit();
}
public void setCompressCacheSize(int count) {
checkDbIsOpen();
prefixCache.setLimit(count);
}
}
/*
* (c) Copyright 2000, 2001 Hewlett-Packard Development Company, LP
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
| src/com/hp/hpl/jena/db/impl/DriverRDB.java | /*
(c) Copyright 2003, Hewlett-Packard Development Company, LP
[See end of file]
*/
package com.hp.hpl.jena.db.impl;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.CRC32;
import com.hp.hpl.jena.datatypes.RDFDatatype;
import com.hp.hpl.jena.datatypes.TypeMapper;
import com.hp.hpl.jena.db.GraphRDB;
import com.hp.hpl.jena.db.IDBConnection;
import com.hp.hpl.jena.db.RDFRDBException;
import com.hp.hpl.jena.db.impl.DBIDInt;
import com.hp.hpl.jena.graph.Graph;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Node_Literal;
import com.hp.hpl.jena.graph.Node_URI;
import com.hp.hpl.jena.graph.Node_Variable;
import com.hp.hpl.jena.graph.impl.LiteralLabel;
import com.hp.hpl.jena.rdf.model.AnonId;
import com.hp.hpl.jena.shared.*;
import com.hp.hpl.jena.vocabulary.RDF;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xerces.util.XMLChar;
//=======================================================================
/**
* Base database driver for implementing SpecializedGraphs.
* Different drivers are needed for different databases and different
* layout schemes.
* <p>
* This driver is a base implemention from which database-specific
* drivers can inherit. It is not generic in the sense that it will work
* on any minimal SQL store and so should be treated as if it were
* an abstract class.
* <p>The SQL statements which implement each of the functions are
* loaded in a separate file etc/[layout]_[database].sql from the classpath.
*
* @author hkuno modification of Jena1 code by Dave Reynolds (der)
* @version $Revision: 1.42 $ on $Date: 2004-07-25 14:39:43 $
*/
public abstract class DriverRDB implements IRDBDriver {
//=======================================================================
// Cutomization variables
// =======================================================================
/**
* This Graph's db properties
*/
protected DBPropDatabase m_dbProps;
/**
* Name of this class's PSet_TripleStore_XXX class
*/
protected String m_psetClassName;
/**
* Name of this class's PSet_TripleStore_XXX class
*/
protected String m_psetReifierClassName;
/**
* Cached name of this class's SpecializedGraph_XXX class
*/
protected String m_lsetClassName;
/**
* Cached name of this class's SpecializedGraphReifer_XXX class
*/
protected String m_lsetReifierClassName;
/** The class name of the database driver (e.g. jdbc.sql.class)*/
protected String DRIVER_NAME;
// Dummy - needs replacing when instantiated?
/** The name of the database type this driver supports */
protected String DATABASE_TYPE;
/** The maximum size of index key (or a component of a key) */
protected int INDEX_KEY_LENGTH;
/** The maximum possible value for INDEX_KEY_LENGTH (db-dependent) */
protected int INDEX_KEY_LENGTH_MAX;
/** true if graphs using this database instance supports transactions.
* this is a user settable parameter. the underlying db engine may support
* transactions but an application may prefer to run without transactions
* for better performance. this can only be set before the db is formatted.
*/
protected boolean IS_XACT_DB;
protected boolean STRINGS_TRIMMED;
/** true if the database engine will trim trailing spaces in strings. to
* prevent this, append EOS to strings that should not be trimmed.
*/
protected String EOS = "";
protected char EOS_CHAR = ':';
protected int EOS_LEN = 0;
/** EOS is appended to most RDB strings to deal with string trimming. if
* STRINGS_TRIMMED is false, EOS is null. otherwise, EOS is EOS_CHAR.
* EOS_LEN is the length of EOS (0 or 1).
*/
protected char QUOTE_CHAR = '\"';
/** the quote character used to delimit characters and strings.
*/
/**
* Indicates whether search pattern used to select system objects by name should be upper-case.
*/
protected boolean DB_NAMES_TO_UPPER = false;
/** true if URI's are to be compressed by storing prefixes (an approximation
* of a namespace) in the JENA_PREFIX table. note that "short" prefixes are
* not stored, i.e., the prefix length not more than URI_COMPRESS_LENGTH.
*/
protected boolean URI_COMPRESS;
protected int URI_COMPRESS_LENGTH = 100;
/** if URI_COMPRESS is true, compress prefixes that are longer than this.
/** The maximum size of an object that can be stored in a Statement table */
protected int LONG_OBJECT_LENGTH;
/** The maximum possible value for LONG_OBJECT_LENGTH (db-dependent) */
protected int LONG_OBJECT_LENGTH_MAX;
/** The SQL type to use for storing ids (compatible with wrapDBID) */
protected String ID_SQL_TYPE;
/** Set to true if the insert operations already check for duplications */
protected boolean SKIP_DUPLICATE_CHECK;
/** Set to true if IDs are allocated prior to insert */
protected boolean PRE_ALLOCATE_ID;
/** The name of the sql definition file for this database/layout combo */
protected String SQL_FILE;
/** The name of the sql definition file for this database/layout combo */
protected String DEFAULT_SQL_FILE = "etc/generic_generic.sql";
// =======================================================================
// Common variables
// =======================================================================
/**
* Holds prefix for names of Jena database tables.
*/
protected String TABLE_NAME_PREFIX = "jena_";
/**
* Holds maximum length of table and index names in database.
*/
protected int TABLE_NAME_LENGTH_MAX;
/**
* Holds the length of the longest jena table or index name.
* This is really a hack and should be better architected.
* The currently known longest possible name is:
* <prefix>GnTm_StmtXSP where prefix is the table
* name prefix (which isn't counted here), n is the
* graph identifier, m is the table number within that
* graph and XSP refers to the subject-predicate index.
* If we assume n and m might be two digits, we get 14.
*/
protected int JENA_LONGEST_TABLE_NAME_LENGTH = 14;
/** Set to true to enable cache of pre-prepared statements */
protected boolean CACHE_PREPARED_STATEMENTS = true;
/** The name of the layout type this driver supports */
protected String LAYOUT_TYPE = "TripleStore";
/** Default name of the table that holds system property graph asserted statements **/
protected String SYSTEM_STMT_TABLE;
/** Name of the long literal table **/
protected String LONG_LIT_TABLE;
/** Name of the long URI table **/
protected String LONG_URI_TABLE;
/** Name of the prefix table **/
protected String PREFIX_TABLE;
/** Name of the graph table **/
protected String GRAPH_TABLE;
/** If not null, newly-created graphs share tables with the identified graph **/
protected String STORE_WITH_MODEL = null;
/** Name of the graph holding default properties (the one's that a newly-created
* graph will have by default **/
protected final String DEFAULT_PROPS = "JENA_DEFAULT_GRAPH_PROPERTIES";
/** Unique numeric identifier of the graph holding default properties **/
protected final int DEFAULT_ID = 0;
/** Driver version number */
protected final String VERSION = "2.0alpha";
/** Database layout version */
protected String LAYOUT_VERSION = "2.0";
protected static Log logger = LogFactory.getLog( PSet_ReifStore_RDB.class );
// =======================================================================
// Instance variables
// =======================================================================
/**
* Instance of SQLCache used by Driver for hard-coded db commands
*/
protected SQLCache m_sql = null;
/** Cache a reference to the system property graph (java) **/
protected SpecializedGraph m_sysProperties = null;
protected IDBConnection m_dbcon = null;
protected LRUCache prefixCache = null;
public static final int PREFIX_CACHE_SIZE = 50;
//===================================
// for transaction support
//===================================
// caches whether or not underlying connection supports transactions
private Boolean m_transactionsSupported;
/** flag to indicate that there is a transaction active on the associated connection */
protected boolean inTransaction = false;
// =======================================================================
// Constructor
// =======================================================================
/**
* Create a bare instance of the driver. It is not functional until a
* database connection has been supplied via setConnection.
*/
public DriverRDB() {
}
// =======================================================================
// Methods
// =======================================================================
/**
* Return the connection
*/
public IDBConnection getConnection() {
return m_dbcon;
}
/**
* Return the specialized graph used to store system properties.
* (Constuct a new one if necessary).
*/
public SpecializedGraph getSystemSpecializedGraph() {
if (m_sysProperties != null) {
return m_sysProperties;
}
setTableNames(TABLE_NAME_PREFIX);
try {
if( !isDBFormatOK() ) {
// Format the DB
cleanDB();
prefixCache = new LRUCache(PREFIX_CACHE_SIZE);
return formatAndConstructSystemSpecializedGraph();
}
} catch (Exception e) {
// We see an error during format testing, might be a dead
// connection rather than an unformated database so abort
throw new JenaException("The database appears to be unformatted or corrupted.\n" +
"If possible, call IDBConnection.cleanDB(). \n" +
"Warning: cleanDB will remove all Jena models from the databases.");
}
prefixCache = new LRUCache(PREFIX_CACHE_SIZE);
getDbInitTablesParams(); //this call is a hack. it's needed because
// it has the side effect of initializing some vars (e.g., EOS).
IPSet pSet = createIPSetInstanceFromName(m_psetClassName, SYSTEM_STMT_TABLE);
m_sysProperties = createLSetInstanceFromName(m_lsetClassName, pSet, DEFAULT_ID);
m_dbProps = new DBPropDatabase(m_sysProperties);
// now reset the configuration parameters
checkEngine(m_dbProps);
checkDriverVersion(m_dbProps);
checkLayoutVersion(m_dbProps);
String val = m_dbProps.getLongObjectLength();
if ( val == null ) throwBadFormat("long object length");
else LONG_OBJECT_LENGTH = Integer.parseInt(val);
val = m_dbProps.getIndexKeyLength();
if ( val == null ) throwBadFormat("index key length");
else INDEX_KEY_LENGTH = Integer.parseInt(val);
val = m_dbProps.getIsTransactionDb();
if ( val == null ) throwBadFormat("database supports transactions");
else IS_XACT_DB = Boolean.valueOf(val).booleanValue();
val = m_dbProps.getDoCompressURI();
if ( val == null ) throwBadFormat("compress URIs");
else URI_COMPRESS = Boolean.valueOf(val).booleanValue();
val = m_dbProps.getCompressURILength();
if ( val == null ) throwBadFormat("URI compress length");
else URI_COMPRESS_LENGTH = Integer.parseInt(val);
val = m_dbProps.getTableNamePrefix();
if ( val == null ) throwBadFormat("table name prefix");
else TABLE_NAME_PREFIX = val;
return m_sysProperties;
}
private void checkEngine ( DBProp dbProps ) {
String dbtype = m_dbProps.getEngineType();
if ( dbtype == null ) throwBadFormat("database type");
if ( !dbtype.equals(DATABASE_TYPE) ) {
throw new JenaException(
"Database created with incompatible database type for this version of Jena: "
+ dbtype);
}
}
private void checkDriverVersion ( DBProp dbProps ) {
String vers = m_dbProps.getDriverVersion();
if ( vers == null ) throwBadFormat("database version");
if ( !vers.equals(VERSION) ) {
throw new JenaException(
"Models in the database were created with an incompatible version of Jena: "
+ vers);
}
}
private void checkLayoutVersion ( DBProp dbProps ) {
String layout = m_dbProps.getLayoutVersion();
if ( layout == null ) throwBadFormat("database layout");
if ( !layout.equals(LAYOUT_VERSION) ) {
throw new JenaException(
"The database layout cannot be processed by this version of Jena: "
+ layout);
}
}
private void throwBadFormat ( String prop ) {
throw new JenaException(
"The database appears to be unformatted or corrupted - could not find value\n" +
" for \"" + prop + "\" in Jena system properties table.\n" +
"If possible, call IDBConnection.cleanDB(). \n" +
"Warning: cleanDB will remove all Jena models from the databases.");
}
/**
* Format the database and construct a brand new system specialized graph.
*/
protected SpecializedGraph formatAndConstructSystemSpecializedGraph() {
try {
String [] params = getDbInitTablesParams();
m_sql.runSQLGroup("initDBtables", params);
m_sql.runSQLGroup("initDBgenerators");// m_sql.runSQLGroup("initDBprocedures");
} catch (SQLException e) {
logger.warn("Problem formatting database", e);
throw new RDFRDBException("Failed to format database", e);
}
// Construct the system properties
IPSet pSet = createIPSetInstanceFromName(m_psetClassName, SYSTEM_STMT_TABLE);
m_sysProperties = createLSetInstanceFromName(m_lsetClassName, pSet, DEFAULT_ID);
// The following call constructs a new set of database properties and
// adds them to the m_sysProperties specialized graph.
m_dbProps = new DBPropDatabase( m_sysProperties, m_dbcon.getDatabaseType(),
VERSION, LAYOUT_VERSION,String.valueOf(LONG_OBJECT_LENGTH),
String.valueOf(INDEX_KEY_LENGTH), String.valueOf(IS_XACT_DB),
String.valueOf(URI_COMPRESS), String.valueOf(URI_COMPRESS_LENGTH),
TABLE_NAME_PREFIX);
// Now we also need to construct the parameters that will be the
// default settings for any graph added to this database
DBPropGraph def_prop = new DBPropGraph( m_sysProperties, DEFAULT_PROPS, "generic");
def_prop.addGraphId(DEFAULT_ID);
return m_sysProperties;
}
abstract String[] getDbInitTablesParams();
abstract String[] getCreateTableParams( int graphId, boolean isReif );
abstract public int graphIdAlloc ( String graphName );
/**
* Construct and return a new specialized graph.
* @param graphProperties A set of customization properties for the specialized graph.
*/
public List createSpecializedGraphs(DBPropGraph graphProperties) {
String graphName = graphProperties.getName();
String stmtTbl = null;
String reifTbl = null;
String dbSchema = STORE_WITH_MODEL;
int graphId = graphIdAlloc(graphName);
graphProperties.addGraphId(graphId);
boolean useDefault = false;
// dbSchema = graphProperties.getDBSchema();
// use the default schema if:
// 1) no schema is specified and we are creating the default (unnamed) graph
// 2) a schema is specified and it is the default (unnamed) graph
if ( ((dbSchema == null) && graphName.equals(GraphRDB.DEFAULT)) ) {
useDefault = true;
dbSchema = DEFAULT_PROPS; // default graph should use default tables
}
// else if ( ((dbSchema != null) && dbSchema.equals(GraphRDB.DEFAULT)) ) {
// useDefault = true;
// dbSchema = DEFAULT_PROPS; // default graph should use default tables
// }
if ( dbSchema != null ) {
DBPropGraph schProp = DBPropGraph.findPropGraphByName(getSystemSpecializedGraph(),
dbSchema );
if ( schProp != null ) {
reifTbl = schProp.getReifTable();
stmtTbl = schProp.getStmtTable();
}
if ( ((reifTbl == null) || (stmtTbl == null)) && (useDefault == false) )
// schema not found. this is ok ONLY IF it's the DEFAULT schema
throw new RDFRDBException("Creating graph " + graphName +
": referenced schema not found: " + dbSchema);
}
if ( (reifTbl == null) || (stmtTbl == null) ) {
reifTbl = createTable(graphId, true);
stmtTbl = createTable(graphId, false);
if ( (reifTbl == null) || (stmtTbl == null) )
throw new RDFRDBException("Creating graph " + graphName +
": cannot create tables");
}
graphProperties.addStmtTable(stmtTbl);
graphProperties.addReifTable(reifTbl);
// Add the reifier first
DBPropPSet pSetReifier = new DBPropPSet(m_sysProperties, m_psetReifierClassName, reifTbl);
DBPropLSet lSetReifier = new DBPropLSet(m_sysProperties, "LSET_"+graphProperties.getName()+"_REIFIER", m_lsetReifierClassName);
lSetReifier.setPSet(pSetReifier);
graphProperties.addLSet(lSetReifier);
// Now add support for all non-reified triples
DBPropPSet pSet = new DBPropPSet(m_sysProperties, m_psetClassName, stmtTbl);
DBPropLSet lSet = new DBPropLSet(m_sysProperties, "LSET_"+graphProperties.getName(), m_lsetClassName);
lSet.setPSet(pSet);
graphProperties.addLSet(lSet);
return recreateSpecializedGraphs( graphProperties );
}
/**
* Construct and return a list of specialized graphs to match those in the store.
* @param graphProperties A set of customization properties for the graph.
*/
public List recreateSpecializedGraphs(DBPropGraph graphProperties) {
List result = new ArrayList();
int dbGraphId = graphProperties.getGraphId();
// to ensure that reifier graphs occur before stmt graphs, make two passes
String[] lsetTypes = {m_lsetClassName, m_lsetReifierClassName};
int i;
for(i=0;i<2;i++) {
Iterator it = graphProperties.getAllLSets();
while(it.hasNext() ) {
DBPropLSet lSetProps = (DBPropLSet)it.next();
if ( lSetProps.getType().equals(lsetTypes[i]) ) continue;
DBPropPSet pSetProps = lSetProps.getPset();
IPSet pSet = createIPSetInstanceFromName(pSetProps.getType(), pSetProps.getTable());
result.add( createLSetInstanceFromName( lSetProps.getType(), pSet, dbGraphId));
}
}
return result;
}
/**
* Create a new IPSet instance of the named implementation class and set the db connection.
*
* @param pName name of a class that implements IPSet.
* @return an instance of the named class with the db connection set.
*/
private IPSet createIPSetInstanceFromName(String className, String tblName) {
IPSet pSet = null;
try {
// get PSet
pSet = (IPSet) Class.forName(className).newInstance();
pSet.setDriver(this);
pSet.setSQLType(ID_SQL_TYPE);
pSet.setSkipDuplicateCheck(SKIP_DUPLICATE_CHECK);
pSet.setSQLCache(m_sql);
pSet.setCachePreparedStatements(CACHE_PREPARED_STATEMENTS);
pSet.setTblName(tblName);
} catch (Exception e) {
logger.warn("Unable to create IPSet instance ", e);
}
return pSet;
}
private SpecializedGraph createLSetInstanceFromName(String lSetName, IPSet pset, int dbGraphID) {
SpecializedGraph sg = null;
try {
Class cls = Class.forName(lSetName);
Class[] params = {IPSet.class, Integer.class};
java.lang.reflect.Constructor con = cls.getConstructor(params);
Object[] args = {pset, new Integer(dbGraphID)};
sg = (SpecializedGraph) con.newInstance(args);
} catch (Exception e) {
logger.error("Unable to create instance of SpecializedGraph ", e);
}
return sg;
}
/**
* Remove the specialized graph, erasing all trace of a Graph.
* @param graphId The identity of the Graph which these specialized graphs should hold
* @param graphProperties The properties for the graph to be removed.
*/
public void removeSpecializedGraphs( DBPropGraph graphProperties,
List specializedGraphs) {
int graphId = graphProperties.getGraphId();
Iterator it = specializedGraphs.iterator();
while (it.hasNext()){
SpecializedGraph sg = (SpecializedGraph) it.next();
removeSpecializedGraph(sg);
}
String stmtTbl = graphProperties.getStmtTable();
String reifTbl = graphProperties.getReifTable();
// remove from system properties table
// It is sufficient just to remove the lSet properties (it will
// take care of deleting any pset properties automatically).
m_dbProps.removeGraph(graphProperties);
// drop the tables if they are no longer referenced
if ( graphId != DEFAULT_ID ) {
boolean stInUse = false;
boolean rtInUse = false;
it = m_dbProps.getAllGraphs();
while ( it.hasNext() ) {
DBPropGraph gp = (DBPropGraph) it.next();
if ( gp.getStmtTable().equals(stmtTbl) ) stInUse = true;
if ( gp.getReifTable().equals(reifTbl) ) rtInUse = true;
}
if ( stInUse == false ) deleteTable(stmtTbl);
if ( rtInUse == false ) deleteTable(reifTbl);
graphIdDealloc(graphId);
}
}
/**
* Remove specialized graph from the datastore.
* @param graph is the graph to be removed.
*/
private void removeSpecializedGraph(SpecializedGraph graph) {
graph.clear();
}
/**
* Method setDatabaseProperties.
*
* Sets the current properties for the database.
*
* @param databaseProperties is a Graph containing a full set of database properties
*/
public void setDatabaseProperties(Graph databaseProperties) {
SpecializedGraph toGraph = getSystemSpecializedGraph();
// really need to start a transaction here
// Here add code to check if the database has been used - if so,
// it's too late to change the properties, so throw an exception
toGraph.clear();
SpecializedGraph.CompletionFlag complete = new SpecializedGraph.CompletionFlag();
toGraph.add(databaseProperties, complete);
// Now test the properties to see if it's a valid set - if not,
// throw an exception - it's okay to check some things later (there's
// no guarantee that every error will be caught here).
// end transaction here.
}
/**
* Method getDefaultModelProperties
*
* Return the default properties for a new model stored in this database.
* If none are stored, then load default properties into the database.
* @return Graph containg the default properties for a new model
*/
public DBPropGraph getDefaultModelProperties() {
SpecializedGraph sg = getSystemSpecializedGraph();
DBPropGraph result = DBPropGraph.findPropGraphByName(sg, DEFAULT_PROPS);
if (result == null) {
logger.error("No default Model Properties found");
// Construct the parameters that will be the
// default settings for any graph added to this database
//new DBPropGraph( m_sysProperties, "default", "generic");
//result = DBPropGraph.findPropGraph(sg, "default");
}
return result;
}
/**
* Test if the database has previously been formatted.
*
* @return boolean true if database is correctly formatted, false on any error.
*/
public boolean isDBFormatOK() {
boolean result = false;
try {
ResultSet alltables = getAllTables();
int i = 0;
while ( alltables.next() ) i++;
alltables.close();
result = i >= 5;
} catch (Exception e1) {
throw new JenaException("DB connection problem while testing formating", e1);
}
return result;
}
/**
* Converts string to form accepted by database.
*/
public String stringToDBname(String aName) {
String result = (DB_NAMES_TO_UPPER) ? aName.toUpperCase() : aName;
return(result);
}
/* (non-Javadoc)
* @see com.hp.hpl.jena.graphRDB.IRDBDriver#cleanDB()
*/
public void cleanDB() {
try {
ResultSet alltables = getAllTables();
List tablesPresent = new ArrayList(10);
while (alltables.next()) {
tablesPresent.add(alltables.getString("TABLE_NAME"));
}
alltables.close();
Iterator it = tablesPresent.iterator();
while (it.hasNext()) {
m_sql.runSQLGroup("dropTable", (String) it.next());
}
if (PRE_ALLOCATE_ID) {
clearSequences();
}
} catch (SQLException e1) {
throw new RDFRDBException("Internal SQL error in driver", e1);
}
m_sysProperties = null;
if ( prefixCache != null ) prefixCache.clear();
prefixCache = null;
}
private ResultSet getAllTables() {
try {
DatabaseMetaData dbmd = m_dbcon.getConnection().getMetaData();
String[] tableTypes = { "TABLE" };
String prefixMatch = stringToDBname(TABLE_NAME_PREFIX + "%");
return dbmd.getTables(null, null, prefixMatch, tableTypes);
} catch (SQLException e1) {
throw new RDFRDBException("Internal SQL error in driver", e1);
}
}
/**
* Drop all Jena-related sequences from database, if necessary.
* Override in subclass if sequences must be explicitly deleted.
*/
public void clearSequences() {
}
/**
* Removes named sequence from the database, if it exists.
* @param seqName
*/
public void removeSequence(String seqName) {
if (sequenceExists(seqName)) {
try {
m_sql.runSQLGroup("DropSequence",seqName);
} catch (Exception e) {
logger.warn("Unable to drop sequence " + seqName, e);
}
}
}
/**
* Check database and see if named sequence exists.
* @param seqName
*/
public boolean sequenceExists(String seqName) {
Object[] args = {seqName};
ResultSet rs = null;
boolean result = false;
try {
String op = "SelectSequenceName";
PreparedStatement ps = m_sql.getPreparedSQLStatement(op);
ps.setString(1,seqName);
rs = ps.executeQuery();
result = rs.next();
m_sql.returnPreparedSQLStatement(ps);
} catch (Exception e) {
logger.error("Unable to select sequence " + seqName, e);
}
return result;
}
/**
* Check database and see if named sequence exists.
* @param seqName
*/
public List getSequences() {
List results = new ArrayList(10);
Object[] args = {};
ResultSetIterator it = null;
try {
String opname = "SelectJenaSequences";
PreparedStatement ps = m_sql.getPreparedSQLStatement(opname, TABLE_NAME_PREFIX);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
results.add(rs.getString(1));
}
//rs.close();
m_sql.returnPreparedSQLStatement(ps);
} catch (Exception e) {
logger.error("Unable to select Jena sequences: ", e);
}
return results;
}
/**
* Initialise a database ready to store RDF tables.
* @throws RDFDBException if the is a problem opening the connection or an internal SQL error.
* @deprecated Since Jena 2.0 this call is no longer needed - formatting
* happens automatically as a side effect of creating Models - there should
* be no need for an application to interact directly with the driver.
*/
public void formatDB() throws RDFRDBException {
}
/**
* Create a table for storing asserted or reified statements.
*
* @param graphId the graph which the table is created.
* @param isReif true if table stores reified statements.
* @return the name of the new table
*
*/
public String createTable( int graphId, boolean isReif) {
String opname = isReif ? "createReifStatementTable" : "createStatementTable";
int i = 0;
String params[];
while ( true ) {
params = getCreateTableParams(graphId, isReif);
try {
m_sql.runSQLGroup(opname, params);
break;
} catch (SQLException e) {
i++;
if ( i > 5 ) {
logger.warn("Problem creating table", e);
throw new RDFRDBException("Failed to create table: " + params[0], e);
}
}
}
return params[0];
}
/**
* Delete a table.
*
* @param tableName the name of the table to delete. *
*/
public void deleteTable( String tableName ) {
String opname = "dropTable";
try {
PreparedStatement ps = m_sql.getPreparedSQLStatement(opname, tableName);
ps.executeUpdate();
return;
} catch (Exception e1) {
throw new RDFRDBException("Failed to delete table ", e1);
}
}
/**
* Throws an UnsupportedOperation exception.
*
* @param opName name of the operation that's not supported.
*/
private void notSupported(String opName)
{ throw new UnsupportedOperationException(opName); }
/**
* If underlying database connection supports transactions, call abort()
* on the connection, then turn autocommit on.
*/
public synchronized void abort() throws RDFRDBException {
if (transactionsSupported()) {
try {
if (inTransaction) {
Connection c = m_sql.getConnection();
c.rollback();
c.commit();
c.setAutoCommit(true);
inTransaction = false;
}
} catch (SQLException e) {
throw new JenaException("Transaction support failed: ", e);
}
} else {
}
}
/**
* If the underlying database connection supports transactions,
* turn autocommit off, then begin a new transaction.
* Note that transactions are associated with connections, not with
* Models. This
*/
public synchronized void begin() throws RDFRDBException {
if (transactionsSupported()) {
try {
if (!inTransaction) {
// Starting a transaction could require us to lose any cached prepared statements
// for some jdbc drivers, currently I think all the drivers we use are safe and
// is a major performance hit so commented out for now.
//m_sql.flushPreparedStatementCache();
Connection c = m_sql.getConnection();
c.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
c.setAutoCommit(false);
inTransaction = true;
}
} catch (SQLException e) {
throw new RDFRDBException("Transaction support failed: ", e);
}
} else
{ notSupported("begin transaction"); }
}
/**
* If the underlying database connection supports transactions,
* call commit(), then turn autocommit on.
*/
public void commit() throws RDFRDBException{
if (transactionsSupported()) {
try {
if (inTransaction) {
Connection c = m_sql.getConnection();
c.commit();
c.setAutoCommit(true);
// not sure why read_uncommitted is set, below. commented out by kw.
// c.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
inTransaction = false;
}
} catch (SQLException e) {
throw new RDFRDBException("Transaction support failed: ", e);
}
} else {
notSupported("commit transaction");
}
}
/**
* Return a string identifying underlying database type.
*
*/
public String getDatabaseType() {
return(DATABASE_TYPE);
}
/**
* Returns true if the underlying database supports transactions.
*/
public boolean transactionsSupported() {
if (m_transactionsSupported != null) {
return(m_transactionsSupported.booleanValue());
}
if (m_dbcon != null) {
try {
Connection c = m_sql.getConnection();
if ( c != null) {
m_transactionsSupported = new Boolean(c.getMetaData().supportsMultipleTransactions());
return(m_transactionsSupported.booleanValue());
}
} catch (SQLException e) {
logger.error("SQL Exception caught ", e);
}
}
return (false);
}
//--------------------------------------------------jena 1 backward compatability
/**
* Close the driver
*
* Nothing to do for now.
*
* @throws RDFDBException if there is an access problem
* @deprecated Since Jena 2.0 this call is no longer required - just
* close the DBConnection - there should be no need for an application
* to interact directly with the driver.
*
*/
public void close() throws RDFRDBException {
}
/**
* Returns true if the database layout supports multiple RDF models
* in the same database.
* @deprecated Since Jena 2.0 all databases support multiple models.
*/
public boolean supportsMultipleModels() {
return true;
}
/**
* Returns true if the database layout supports implicit reification
* of statements (i.e. statements can be treated as resources).
* @deprecated Since Jena 2.0 the reification API has changed. The
* new API is supported in all models, but the old Jena 1 API is no
* longer supported. This call will return false to indicate
* to old code that the old style of jena reification is not supported.
*/
public boolean supportsJenaReification() {
return false;
}
/*
* The following routines are responsible for encoding nodes
* as database structures. For each node type stored (currently,
* literals, URI, blank), there are two possible encodings
* depending on the node size. Small nodes may be stored
* within a statement table. If the node is long (will not
* fit within the statement table), it is be stored in a
* separate table for that node type.
*
* In addition, for resources (URI, blank nodes), the URI
* may be optionally compressed. Below, the possibilites
* are enumerated.
*
* Literal Encoding in Statement Tables
* Short Literal: Lv:[langLen]:[datatypeLen]:[langString][datatypeString]value[:]
* Long Literal: Lr:dbid
* Literal Encoding in Long Literal Table
* Literal: Lv:[langLen]:[datatypeLen]:[langString][datatypeString]head[:] hash tail
*
* Comments:
* L indicates a literal
* v indicates a value
* r indicates a reference to another table
* : is used as a delimiter. note that MySQL trims trailing white space for
* certain VARCHAR columns so an extra delimiter is appended when necessary
* for those columns. it is not required for dbid, however.
* dbid references the long literal table
* langLen is the length of the language identifier for the literal
* langString is the language identifier
* datatypeLen is the length of the datatype for the literal
* datatypeString is the datatype for the literal
* value is the lexical form of the string
* head is a prefix of value that can be indexed
* hash is the CRC32 hash value for the tail
* tail is the remainder of the value that cannot be indexed
*
*
*
* URI Encoding in Statement Tables
* Short URI: Uv:[pfx_dbid]:URI[:]
* Long URI: Ur:[pfx_dbid]:dbid
* URI Encoding in Long URI Table
* URI: Uv:head[:] hash tail
*
* Comments:
* U indicates a URI
* pfx_dbid references the prefix table. if the prefix is too
* short (i.e., the length of the prefix is less than
* URI_COMPRESS_LENGTH), the URI is not compressed and
* pfx_dbid is null.
* URI is the complete URI
* other notation same as for literal encoding
*
* Blank Node Encoding in Statement Tables
* Short URI: Bv:[pfx_dbid]:bnid[:]
* Long URI: Br:[pfx_dbid]:dbid
* Blank Encoding in Long URI Table
* URI: Bv:head[:] hash tail
*
* Comments:
* B indicates a blank node
* bnid is the blank node identifier
* other notation same as above
* Note: currently, blank nodes are always stored uncompressed (pfix_dbid is null).
*
* Variable Node Encoding in Statement Tables
* Variable Node: Vv:name
*
* Comments:
* V indicates a variable node
* v indicates a value
* name is the variable name
* Note: the length must be less than LONG_OBJECT_LENGTH
*
* ANY Node Encoding in Statement Tables
* Variable Node: Av:
*
* Prefix Encoding in Prefix Table
* Prefix: Pv:val[:] [hash] [tail]
*
* Comments:
* P indicates a prefix
* other notation same as above
* hash and tail are only required for long prefixes.
*
*/
protected static String RDBCodeURI = "U";
protected static String RDBCodeBlank = "B";
protected static String RDBCodeLiteral = "L";
protected static String RDBCodeVariable = "V";
protected static String RDBCodeANY = "A";
protected static String RDBCodePrefix = "P";
protected static String RDBCodeValue = "v";
protected static String RDBCodeRef = "r";
protected static String RDBCodeDelim = ":";
protected static char RDBCodeDelimChar = ':';
protected static String RDBCodeInvalid = "X";
/**
* Convert a node to a string to be stored in a statement table.
* @param Node The node to convert to a string. Must be a concrete node.
* @param addIfLong If the node is a long object and is not in the database, add it.
* @return the string or null if failure.
*/
public String nodeToRDBString ( Node node, boolean addIfLong ) throws RDFRDBException {
String res = null;
if ( node.isURI() ) {
String uri = new String(((Node_URI) node).getURI());
if ( uri.startsWith(RDBCodeURI) ) {
throw new RDFRDBException ("URI Node looks like a blank node: " + uri );
}
// TODO: need to write special version of splitNamespace for rdb.
// or else, need a guarantee that splitNamespace never changes.
// the problem is that if the splitNamespace algorithm changes,
// then URI's may be encoded differently. so, URI's in existing
// databases may become inaccessible.
int pos = 0;
boolean noCompress;
String pfx;
String qname;
if ( URI_COMPRESS == true ) {
pos = dbSplitNamespace(uri);
noCompress = (pos == uri.length()) || (pos <= URI_COMPRESS_LENGTH);
} else
noCompress = true;
if ( noCompress ) {
pfx = RDBCodeDelim + RDBCodeDelim;
qname = uri;
} else {
// see if it's cached
DBIDInt pfxid = URItoPrefix(uri, pos, addIfLong);
if ( pfxid == null ) return res;
pfx = RDBCodeDelim + ((DBIDInt)pfxid).getIntID() + RDBCodeDelim;
qname = uri.substring(pos);
}
int encodeLen = RDBCodeURI.length() + 1 + pfx.length() + EOS_LEN;
boolean URIisLong = objectIsLong(encodeLen,qname);
if ( URIisLong ) {
int dbid;
// belongs in URI table
DBIDInt URIid = getURIID(qname,addIfLong);
if ( URIid == null ) return res;
dbid = URIid.getIntID();
res = new String(RDBCodeURI + RDBCodeRef + pfx + dbid);
} else {
res = RDBCodeURI + RDBCodeValue + pfx + qname + EOS;
}
} else if ( node.isLiteral() ){
// TODO: may need to encode literal value when datatype is not a string.
Node_Literal litNode = (Node_Literal) node;
LiteralLabel ll = litNode.getLiteral();
String lval = ll.getLexicalForm();
String lang = ll.language();
String dtype = ll.getDatatypeURI();
String ld = litLangTypeToRDBString(lang,dtype);
int encodeLen = RDBCodeLiteral.length() + 2 + ld.length() + EOS_LEN;
boolean litIsLong = objectIsLong(encodeLen,lval);
if ( litIsLong ) {
int dbid;
// belongs in literal table
DBIDInt lid = getLiteralID(litNode,addIfLong);
if ( lid == null ) return res;
dbid = lid.getIntID();
res = new String(RDBCodeLiteral + RDBCodeRef + RDBCodeDelim + dbid);
} else {
res = new String(RDBCodeLiteral + RDBCodeValue + RDBCodeDelim + ld + lval + EOS);
}
} else if ( node.isBlank() ) {
String bnid = node.getBlankNodeId().toString();
String delims = "::";
int encodeLen = RDBCodeBlank.length() + 1 + delims.length() + EOS_LEN;
boolean BisLong = objectIsLong(encodeLen,bnid);
if ( BisLong ) {
int dbid;
// belongs in URI table
DBIDInt URIid = getBlankID(bnid,addIfLong);
if ( URIid == null ) return res;
dbid = URIid.getIntID();
res = new String(RDBCodeBlank + RDBCodeRef + delims + dbid);
} else {
res = new String(RDBCodeBlank + RDBCodeValue + delims + bnid + EOS);
}
} else if ( node.isVariable() ){
String name = ((Node_Variable)node).getName();
int len = name.length();
if ( (len + 3 + EOS_LEN) > LONG_OBJECT_LENGTH )
throw new JenaException ("Variable name too long: " + name );
res = RDBCodeVariable + RDBCodeValue + RDBCodeDelim + name + EOS;
} else if ( node.equals(Node.ANY) ) {
res = RDBCodeANY + RDBCodeValue + RDBCodeDelim;
} else {
throw new RDFRDBException ("Expected Concrete Node, got " + node.toString() );
}
return res;
}
/**
* Convert an RDB string to the node that it encodes. Return null if failure.
* @param RDBstring The string to convert to a node.
* @return The node or null if failure.
*/
public Node RDBStringToNode ( String RDBString ) throws RDFRDBException {
Node res = null;
int len = RDBString.length();
if ( len < 3 )
throw new RDFRDBException("Bad RDBString Header: " + RDBString);
String nodeType = RDBString.substring(0,1);
String valType = RDBString.substring(1,2);
if ( (!(valType.equals(RDBCodeRef) || valType.equals(RDBCodeValue))) ||
(RDBString.charAt(2) != RDBCodeDelimChar) )
throw new RDFRDBException("Bad RDBString Header: " + RDBString);
int pos = 3;
int npos;
if ( nodeType.equals(RDBCodeURI) ) {
ParseInt pi = new ParseInt(pos);
String prefix = "";
RDBStringParseInt(RDBString, pi, false);
if ( pi.val != null ) {
if ( URI_COMPRESS == false )
throw new RDFRDBException("Bad URI: Prefix Compression Disabled: " + RDBString);
prefix = IDtoPrefix(pi.val.intValue());
if ( prefix == null )
throw new RDFRDBException("Bad URI Prefix: " + RDBString);
}
pos = pi.pos + 1;
String qname;
if ( valType.equals(RDBCodeRef) ) {
qname = IDtoURI(RDBString.substring(pos));
if ( qname == null )
throw new RDFRDBException("Bad URI: " + RDBString);
} else
qname = RDBString.substring(pos,len - EOS_LEN);
res = Node.createURI(prefix + qname);
} else if ( nodeType.equals(RDBCodeLiteral) ) {
ParseInt pi = new ParseInt(pos);
String litString = null;
if ( valType.equals(RDBCodeRef) ) {
RDBStringParseInt(RDBString,pi,true);
if ( pi.val != null )
litString = IDtoLiteral(pi.val.intValue());
if ( litString == null )
throw new RDFRDBException("Bad Literal Reference: " + RDBString);
} else
litString = RDBString.substring(pos,len-EOS_LEN);
len = litString.length();
String lang;
String dtype;
int langLen = 0;
int dtypeLen = 0;
LiteralLabel llabel;
pi.pos = 0;
RDBStringParseInt(litString, pi, false);
if ( pi.val == null ) langLen = 0;
else langLen = pi.val.intValue();
pi.pos = pi.pos + 1;
RDBStringParseInt(litString, pi, false);
if ( pi.val == null ) dtypeLen = 0;
else dtypeLen = pi.val.intValue();
pos = pi.pos + 1;
if ( (pos + langLen + dtypeLen) > len )
throw new RDFRDBException("Malformed Literal: " + litString);
lang = litString.substring(pos,pos+langLen);
pos = pos + langLen;
dtype = litString.substring(pos,pos+dtypeLen);
pos = pos + dtypeLen;
String val = litString.substring(pos);
if ( (dtype == null) || (dtype.equals("")) ) {
llabel = new LiteralLabel(val, lang == null ? "" : lang);
} else {
RDFDatatype dt = TypeMapper.getInstance().getSafeTypeByName(dtype);
llabel = new LiteralLabel(val, lang == null ? "" : lang, dt);
}
res = Node.createLiteral(llabel);
} else if ( nodeType.equals(RDBCodeBlank) ) {
String bstr = null;
if ( valType.equals(RDBCodeValue) ) {
bstr = RDBString.substring(4,len-EOS_LEN);
} else {
bstr = IDtoBlank(RDBString.substring(4));
if ( bstr == null )
throw new RDFRDBException("Bad URI: " + RDBString);
}
res = Node.createAnon( new AnonId (bstr) );
} else if ( nodeType.equals(RDBCodeVariable) ) {
String vname = RDBString.substring(3,len-EOS_LEN);
res = Node.createVariable(vname);
} else if ( nodeType.equals(RDBCodeANY) ) {
res = Node.ANY;
} else
throw new RDFRDBException ("Invalid RDBString Prefix, " + RDBString );
return res;
}
/** This is cuurently a copy of Util.splitNamespace. It was
* copied rather than used directly for two reasons. 1) in the
* future it may be desirable to use a different split algorithm
* for persistence. 2) the util version could change at any time,
* which would render existing databases inaccessible. having a
* copy allows the db version to evolve in a controlled way.
*
* Given an absolute URI, determine the split point between the namespace part
* and the localname part.
* If there is no valid localname part then the length of the
* string is returned.
* The algorithm tries to find the longest NCName at the end
* of the uri, not immediately preceeded by the first colon
* in the string.
* @param uri
* @return the index of the first character of the localname
*/
public static int dbSplitNamespace(String uri) {
char ch;
int lg = uri.length();
if (lg == 0)
return 0;
int j;
int i;
for (i = lg - 1; i >= 1; i--) {
ch = uri.charAt(i);
if (!XMLChar.isNCName(ch))
break;
}
for (j = i + 1; j < lg; j++) {
ch = uri.charAt(j);
if (XMLChar.isNCNameStart(ch)) {
if (uri.charAt(j - 1) == ':'
&& uri.lastIndexOf(':', j - 2) == -1)
continue; // split "mailto:me" as "mailto:m" and "e" !
else
break;
}
}
return j;
}
class ParseInt {
int pos;
Integer val;
ParseInt(int p) {pos = p;}
}
protected void RDBStringParseInt ( String RDBString, ParseInt pi, boolean toEnd ) {
int npos = toEnd ? RDBString.length() : RDBString.indexOf(RDBCodeDelimChar,pi.pos);
if ( npos < 0 ) {
throw new RDFRDBException("Bad RDB String: " + RDBString);
}
String intStr = RDBString.substring(pi.pos,npos);
pi.pos = npos;
if ( intStr.equals("") )
pi.val = null;
else try {
pi.val = new Integer(intStr);
} catch (NumberFormatException e1) {
throw new RDFRDBException("Bad RDB String: " + RDBString);
}
return;
}
DBIDInt URItoPrefix ( String uri, int pos, boolean add ) {
DBIDInt res;
Object key = prefixCache.getByValue(uri.substring(0,pos));
if ( key == null ) {
RDBLongObject lobj = PrefixToLongObject(uri,pos);
res = getLongObjectID(lobj, PREFIX_TABLE, add);
if ( res != null )
prefixCache.put(res,uri.substring(0,pos));
} else
res = (DBIDInt) key;
return res;
}
protected RDBLongObject PrefixToLongObject ( String prefix, int split ) {
RDBLongObject res = new RDBLongObject();
int headLen;
int avail;
res.head = RDBCodePrefix + RDBCodeValue + RDBCodeDelim;
headLen = res.head.length();
avail = INDEX_KEY_LENGTH - (headLen + EOS_LEN);
if ( split > avail ) {
res.head = res.head + prefix.substring(0,avail);
res.tail = prefix.substring(avail,split);
res.hash = stringToHash(res.tail);
} else {
res.head = res.head + prefix.substring(0,split);
res.tail = "";
}
res.head = res.head + EOS;
return res;
}
/**
* Encode a literal node's lang and datatype as a string of the
* form ":[langLen]:[datatypeLen]:[langString][dataTypeString]"
* @return the string.
*/
public String litLangTypeToRDBString ( String lang, String dtype ) throws RDFRDBException {
String res = RDBCodeDelim;
res = ((lang == null) ? "" : Integer.toString(lang.length())) + RDBCodeDelim;
res = res + ((dtype == null) ? "" : Integer.toString(dtype.length())) + RDBCodeDelim;
res = res + (lang == null ? "" : lang) + (dtype == null ? "" : dtype);
return res;
}
/**
* Check if an object is long, i.e., it exceeds the length
* limit for storing in a statement table.
* @return true if literal is long, else false.
*/
protected boolean objectIsLong ( int encodingLen, String objAsString ) {
return ( (encodingLen + objAsString.length()) > LONG_OBJECT_LENGTH);
}
class RDBLongObject {
String head; /* prefix of long object that can be indexed */
long hash; /* hash encoding of tail */
String tail; /* remainder of long object */
}
protected RDBLongObject literalToLongObject ( Node_Literal node ) {
RDBLongObject res = new RDBLongObject();
int headLen;
int avail;
LiteralLabel l = node.getLiteral();
String lang = l.language();
String dtype = l.getDatatypeURI();
String val = l.getLexicalForm();
String langType = litLangTypeToRDBString(lang,dtype);
res.head = RDBCodeLiteral + RDBCodeValue + RDBCodeDelim + langType;
headLen = res.head.length();
avail = INDEX_KEY_LENGTH - (headLen + EOS_LEN);
if ( val.length() > avail ) {
res.head = res.head + val.substring(0,avail);
res.tail = val.substring(avail);
res.hash = stringToHash(res.tail);
} else {
res.head = res.head + val;
res.tail = "";
}
res.head = res.head + EOS;
return res;
}
protected long stringToHash ( String str ) {
CRC32 checksum = new CRC32();
checksum.update(str.getBytes());
return checksum.getValue();
}
/**
* Return the database ID for the URI, if it exists
*/
public DBIDInt getBlankID(String bstr, boolean add) throws RDFRDBException {
RDBLongObject lobj = URIToLongObject (bstr,RDBCodeBlank);
return getLongObjectID(lobj, LONG_URI_TABLE, add);
}
/**
* Return the database ID for the URI, if it exists
*/
public DBIDInt getURIID(String qname, boolean add) throws RDFRDBException {
RDBLongObject lobj = URIToLongObject (qname,RDBCodeURI);
return getLongObjectID(lobj, LONG_URI_TABLE, add);
}
protected RDBLongObject URIToLongObject ( String qname, String code ) {
RDBLongObject res = new RDBLongObject();
int headLen;
int avail;
res.head = code + RDBCodeValue + RDBCodeDelim;
headLen = res.head.length();
avail = INDEX_KEY_LENGTH - (headLen + EOS_LEN);
if ( qname.length() > avail ) {
res.head = res.head + qname.substring(0,avail);
res.tail = qname.substring(avail);
res.hash = stringToHash(res.tail);
} else {
res.head = res.head + qname;
res.tail = "";
}
res.head = res.head + EOS;
return res;
}
/**
* Return the database ID for the literal, if it exists
*/
public DBIDInt getLiteralID(Node_Literal lnode, boolean add) throws RDFRDBException {
RDBLongObject lobj = literalToLongObject (lnode);
return getLongObjectID(lobj, LONG_LIT_TABLE, add);
}
public DBIDInt getLongObjectID(RDBLongObject lobj, String table, boolean add) throws RDFRDBException {
try {
String opName = "getLongObjectID";
if ( lobj.tail.length() > 0 )
opName += "withChkSum";
PreparedStatement ps = m_sql.getPreparedSQLStatement(opName, table);
ps.setString(1,lobj.head);
if ( lobj.tail.length() > 0 )
ps.setLong(2, lobj.hash);
ResultSet rs = ps.executeQuery();
DBIDInt result = null;
if (rs.next()) {
result = wrapDBID(rs.getObject(1));
} else {
if ( add )
result = addRDBLongObject(lobj, table);
}
m_sql.returnPreparedSQLStatement(ps);
return result;
} catch (SQLException e1) {
// /* DEBUG */ System.out.println("Literal truncation (" + l.toString().length() + ") " + l.toString().substring(0, 150));
throw new RDFRDBException("Failed to find literal", e1);
}
}
/**
* Insert a long object into the database.
* This assumes the object is not already in the database.
* @return the db index of the added literal
*/
public DBIDInt addRDBLongObject(RDBLongObject lobj, String table) throws RDFRDBException {
try {
int argi = 1;
String opname = "insertLongObject";
PreparedStatement ps = m_sql.getPreparedSQLStatement(opname, table);
int dbid = 0; // init only needed to satisy java compiler
if ( PRE_ALLOCATE_ID ) {
dbid = getInsertID(table);
ps.setInt(argi++,dbid);
}
ps.setString(argi++, lobj.head);
if ( lobj.tail.length() > 0 ) {
ps.setLong(argi++, lobj.hash);
ps.setString(argi++, lobj.tail);
} else {
ps.setNull(argi++,java.sql.Types.BIGINT);
ps.setNull(argi++,java.sql.Types.VARCHAR);
}
/* if (isBlob || (len == 0) ) {
// First convert the literal to a UTF-16 encoded byte array
// (this wouldn't be needed for jdbc 2.0 drivers but not all db's have them)
byte[] temp = lit.getBytes("UTF-8");
int lenb = temp.length;
//System.out.println("utf-16 len = " + lenb);
byte[] litData = new byte[lenb + 4];
litData[0] = (byte)(lenb & 0xff);
litData[1] = (byte)((lenb >> 8) & 0xff);
litData[2] = (byte)((lenb >> 16) & 0xff);
litData[3] = (byte)((lenb >> 24) & 0xff);
System.arraycopy(temp, 0, litData, 4, lenb);
// Oracle has its own way to insert Blobs
if (isBlob && m_driver.getDatabaseType().equalsIgnoreCase("Oracle")) {
//TODO fix to use Blob
// For now, we do not support Blobs under Oracle
throw new RDFRDBException("Oracle driver does not currently support large literals.");
} else {
ps.setBinaryStream(argi++, new ByteArrayInputStream(litData), litData.length);
}
}
*/
ps.executeUpdate();
//m_sql.returnPreparedSQLStatement(ps,opname);
if ( !PRE_ALLOCATE_ID ) dbid = getInsertID(table);
return wrapDBID(new Integer(dbid));
} catch (Exception e1) {
/* DEBUG */ System.out.println("Problem on long object (l=" + lobj.head + ") " + e1 );
// System.out.println("ID is: " + id);
throw new RDFRDBException("Failed to add long object ", e1);
}
}
/**
* Return the prefix string that has the given prefix id.
* @param prefixID - the dbid of the prefix.
* @return the prefix string or null if it does not exist.
*/
protected String IDtoPrefix ( int prefixID ) {
// check cache
DBIDInt dbid = new DBIDInt(prefixID);
Object res = prefixCache.get(dbid);
if ( res != null)
return (String) res;
else
return IDtoString ( prefixID, PREFIX_TABLE, RDBCodePrefix);
}
/**
* Return the Blank node string that has the given database id.
* @param bnID - the dbid of the blank node, as a string.
* @return the Blank node string or null if it does not exist.
*/
protected String IDtoBlank(String bnID) {
return IDtoString(bnID, LONG_URI_TABLE, RDBCodeBlank);
}
/**
* Return the URI string that has the given database id.
* @param uriID - the dbid of the uri, as a string.
* @return the uri string or null if it does not exist.
*/
protected String IDtoURI(String uriID) {
return IDtoString(uriID, LONG_URI_TABLE, RDBCodeURI);
}
/**
* Return the long literal string that has the given database id.
* @param litID - the dbid of the literal..
* @return the long literal string or null if it does not exist.
*/
protected String IDtoLiteral ( int litID ) {
return IDtoString ( litID, LONG_LIT_TABLE, RDBCodeLiteral);
}
protected String IDtoString ( String dbidAsString, String table, String RDBcode ) {
int dbID;
String res = null;
try {
dbID = Integer.parseInt(dbidAsString);
} catch (NumberFormatException e1) {
throw new RDFRDBException("Invalid Object ID: " + dbidAsString);
}
return IDtoString (dbID, table, RDBcode);
}
protected String IDtoString ( int dbID, String table, String RDBcode ) {
String res = null;
RDBLongObject lobj = IDtoLongObject(dbID, table);
if ( lobj == null )
throw new RDFRDBException("Invalid Object ID: " + dbID);
// debug check
if ( !lobj.head.substring(0,3).equals(RDBcode + RDBCodeValue + RDBCodeDelim) )
throw new RDFRDBException("Malformed URI in Database: " + lobj.head);
res = lobj.head.substring(3,lobj.head.length() - EOS_LEN);
if ( lobj.tail != null )
res = res + lobj.tail;
return res;
}
protected RDBLongObject IDtoLongObject ( int dbid, String table ) {
RDBLongObject res = null;
try {
String opName = "getLongObject";
PreparedStatement ps = m_sql.getPreparedSQLStatement(opName, table);
ps.setInt(1,dbid);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
res = new RDBLongObject();
res.head = rs.getString(1);
res.tail = rs.getString(2);
}
m_sql.returnPreparedSQLStatement(ps);
} catch (SQLException e1) {
// /* DEBUG */ System.out.println("Literal truncation (" + l.toString().length() + ") " + l.toString().substring(0, 150));
throw new RDFRDBException("Failed to find literal", e1);
}
return res;
}
protected RDBLongObject IDtoLongObject ( String idAsString, String table ) {
RDBLongObject res = null;
int dbid;
try {
dbid = Integer.parseInt(idAsString);
} catch (NumberFormatException e1) {
throw new RDFRDBException("Invalid Object ID: " + idAsString);
}
return IDtoLongObject(dbid,table);
}
/**
* Convert the raw SQL object used to store a database identifier into a java object
* which meets the DBIDInt interface.
*/
public DBIDInt wrapDBID(Object id) throws RDFRDBException {
if (id instanceof Number) {
return new DBIDInt(((Number)id).intValue());
} else if (id == null) {
return null;
} else {
throw new RDFRDBException("Unexpected DB identifier type: " + id);
//return null;
}
}
public String genSQLReifQualStmt () {
return "stmt = ?";
}
public String genSQLReifQualAnyObj( boolean objIsStmt) {
return "( subj = ? OR prop = ? OR obj = ?" + (objIsStmt ? " OR hasType = " +
QUOTE_CHAR + "T" + QUOTE_CHAR + " )" : " )");
}
public String genSQLReifQualObj ( char reifProp, boolean hasObj ) {
String qual = "";
if ( reifProp == 'T' ) {
qual = "hasType = " + QUOTE_CHAR + "T" + QUOTE_CHAR;
} else {
String cmp = (hasObj ? " = ?" : " is not null");
String col = null;
if ( reifProp == 'S' ) col = "subj";
else if ( reifProp == 'P' ) col = "prop";
else if ( reifProp == 'O' ) col = "obj";
else throw new JenaException("Undefined reification property");
qual = col + cmp;
}
return qual;
}
protected String colidToColname ( char colid ) {
if ( colid == 'G' ) return "GraphID";
if ( colid == 'P' ) return "Prop";
if ( colid == 'S' ) return "Subj";
if ( colid == 'O' ) return "Obj";
if ( colid == 'N' ) return "Stmt";
if ( colid == 'T' ) return "HasType";
throw new JenaException("Invalid column identifer: '" + colid + "\'");
}
protected String aliasToString ( int alias ) {
return "A" + alias;
}
protected String colAliasToString ( int alias, char colid ) {
return aliasToString(alias) + "." + colidToColname(colid);
}
/*
* there's a bug in the code below in that the literal is converted to
* a string BEFORE the query is run. consequently, there's a race
* condition. if the (long) literal is not in the database
* when the query is compiled but is added prior to running the
* query, then the query will (incorrectly) return no results.
* for now, we'll ignore this case and document it as a bug.
*/
public String genSQLQualConst ( int alias, char pred, Node lit ) {
String val = nodeToRDBString(lit, false);
if ( val == "" )
// constant not in database.
// should really optimize this and not
// even run the query but ok for now.
val = RDBCodeInvalid;
return colAliasToString(alias,pred) + "=" + QUOTE_CHAR + val + QUOTE_CHAR;
}
public String genSQLReifQualConst ( int alias, char pred, Node lit ) {
String val = "";
if ( (pred == 'T') && (lit.equals(RDF.Nodes.Statement)) )
val = "T";
else
val = nodeToRDBString(lit, false);
return colAliasToString(alias,pred) + "=" + QUOTE_CHAR + val + QUOTE_CHAR;
}
public String genSQLQualParam( int alias, char pred ) {
return colAliasToString(alias,pred) + "=?";
}
public String genSQLQualGraphId( int alias, int graphId ) {
return colAliasToString(alias,'G') + "=" + graphId;
}
public String genSQLJoin( int lhsAlias, char lhsCol,
int rhsAlias, char rhsCol ) {
return colAliasToString(lhsAlias,lhsCol) + "=" +
colAliasToString(rhsAlias,rhsCol);
}
public String genSQLResList( int resIndex[], VarDesc[] binding ) {
String resList = "";
int i,j;
for(i=0,j=0;i<binding.length;i++) {
VarDesc b = binding[i];
if ( !b.isArgVar() ) {
// next result variable
resList += (j>0?", ":"") + colAliasToString(b.alias,b.column);
if ( j >= resIndex.length )
throw new JenaException("Too many result columns");
resIndex[j++] = b.mapIx;
}
}
return resList;
}
public String genSQLFromList( int aliasCnt, String table ) {
int i;
String resList = "";
for(i=0;i<aliasCnt;i++) {
resList += (i>0?", ":"") + table + " " + aliasToString(i);
}
return resList;
}
public String genSQLSelectKW() {
return "Select ";
}
public String genSQLFromKW() {
return "From ";
}
public String genSQLWhereKW() {
return "Where ";
}
public String genSQLSelectStmt( String res, String from, String qual ) {
return genSQLSelectKW() + res + " " +
genSQLFromKW() + from + " " +
(qual.length() == 0 ? qual :genSQLWhereKW()) + qual;
}
protected int getTableCount(int graphId) {
try {
DatabaseMetaData dbmd = m_dbcon.getConnection().getMetaData();
String[] tableTypes = { "TABLE" };
int res = 0;
String tblPattern =
TABLE_NAME_PREFIX + "g" + Integer.toString(graphId) + "%";
tblPattern = stringToDBname(tblPattern);
ResultSet alltables =
dbmd.getTables(null, null, tblPattern, tableTypes);
while (alltables.next()) {
res += 1;
}
alltables.close();
return res;
} catch (SQLException e1) {
throw new RDFRDBException("Internal SQL error in driver", e1);
}
}
/*
* getters and setters for database options
*/
public int getLongObjectLength () {
return LONG_OBJECT_LENGTH;
}
public void setLongObjectLength ( int len ) {
checkDbUninitialized();
if ( len > LONG_OBJECT_LENGTH_MAX )
throw new JenaException("IndexKeyLength exceeds maximum value for database");
LONG_OBJECT_LENGTH = len;
}
public int getIndexKeyLength () {
return INDEX_KEY_LENGTH;
}
public void setIndexKeyLength ( int len ) {
checkDbUninitialized();
if ( len > INDEX_KEY_LENGTH_MAX )
throw new JenaException("IndexKeyLength exceeds maximum value for database");
INDEX_KEY_LENGTH = len;
}
public boolean getIsTransactionDb () {
return IS_XACT_DB;
}
public void setIsTransactionDb ( boolean bool ) {
checkDbUninitialized();
if ( bool == false )
throw new JenaException("setIsTransactionDb unsupported for this database engine");
}
public boolean getDoCompressURI () {
return URI_COMPRESS;
}
public void setDoCompressURI ( boolean bool ) {
checkDbUninitialized();
URI_COMPRESS = bool;
}
public int getCompressURILength() {
return URI_COMPRESS_LENGTH;
}
public void setCompressURILength ( int len ) {
checkDbUninitialized();
URI_COMPRESS_LENGTH = len;
}
public boolean getDoDuplicateCheck() {
return !SKIP_DUPLICATE_CHECK;
}
public void setDoDuplicateCheck(boolean bool) {
SKIP_DUPLICATE_CHECK = !bool;
}
protected boolean dbIsOpen() {
return (m_sysProperties != null);
}
protected void checkDbIsOpen() {
if ( !dbIsOpen() )
throw new JenaException("Database not open");
}
protected void checkDbUninitialized() {
if ( dbIsOpen() || (isDBFormatOK() == true))
throw new JenaException("Database configuration option cannot be set after database is formatted");
}
public String getTableNamePrefix() {
return TABLE_NAME_PREFIX;
}
public void setTableNamePrefix ( String prefix ) {
if ( (prefix.length() + JENA_LONGEST_TABLE_NAME_LENGTH) >
TABLE_NAME_LENGTH_MAX )
throw new JenaException("TableNamePrefix exceeds maximum length for database: " + TABLE_NAME_LENGTH_MAX);
if ( dbIsOpen() )
throw new JenaException("Table name prefix must be set before opening or connecting to a model.");
setTableNames(prefix);
}
private void setTableNames ( String prefix ) {
TABLE_NAME_PREFIX = stringToDBname(prefix);
SYSTEM_STMT_TABLE = TABLE_NAME_PREFIX + "sys_stmt";
LONG_LIT_TABLE = TABLE_NAME_PREFIX + "long_lit";
LONG_URI_TABLE = TABLE_NAME_PREFIX + "long_uri";
PREFIX_TABLE = TABLE_NAME_PREFIX + "prefix";
GRAPH_TABLE = TABLE_NAME_PREFIX + "graph";
}
public String getStoreWithModel() {
return STORE_WITH_MODEL;
}
public void setStoreWithModel(String modelName) {
String name = null;
if ((modelName != null) && !modelName.equals(""))
name = modelName;
STORE_WITH_MODEL = name;
}
public int getCompressCacheSize() {
checkDbIsOpen();
return prefixCache.getLimit();
}
public void setCompressCacheSize(int count) {
checkDbIsOpen();
prefixCache.setLimit(count);
}
}
/*
* (c) Copyright 2000, 2001 Hewlett-Packard Development Company, LP
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
| Retracted patch - not clear how to recover from connection errors in isDBFormatOK
git-svn-id: 227c23bb629cf7bef445105b977924772e49ae4f@1111668 13f79535-47bb-0310-9956-ffa450edef68
| src/com/hp/hpl/jena/db/impl/DriverRDB.java | Retracted patch - not clear how to recover from connection errors in isDBFormatOK |
|
Java | apache-2.0 | 309994feee6357b49d10aab14c11c2a3a171c3ac | 0 | MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim | gui/src/biomodel/network/SynthesisNode.java | package biomodel.network;
import java.net.URI;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import org.sbolstandard.core.DnaComponent;
import sbol.SBOLSynthesizer;
public class SynthesisNode {
private LinkedList<URI> sbolURIs;
private LinkedList<DnaComponent> dnaComps = new LinkedList<DnaComponent>();
private String id;
private Set<SynthesisNode> nextNodes = new HashSet<SynthesisNode>();
private SBOLSynthesizer sbolSynth;
private boolean visited;
public SynthesisNode(String id, LinkedList<URI> sbolURIs) {
this.id = id;
this.sbolURIs = sbolURIs;
visited = false;
}
public SynthesisNode(String id, LinkedList<URI> sbolURIs, SBOLSynthesizer sbolSynth) {
this.id = id;
this.sbolURIs = sbolURIs;
this.sbolSynth = sbolSynth;
visited = false;
}
public String getID() {
return id;
}
public void setID(String id) {
this.id = id;
}
public LinkedList<URI> getSbolURIs() {
return sbolURIs;
}
public void addSbolURI(URI uri) {
sbolURIs.add(uri);
}
public void setSbolURIs(LinkedList<URI> sbolURIs) {
this.sbolURIs = sbolURIs;
}
public LinkedList<DnaComponent> getDNAComponents() {
return dnaComps;
}
public void setDNAComponents(LinkedList<DnaComponent> dnaComps) {
this.dnaComps = dnaComps;
}
public SBOLSynthesizer getSynthesizer() {
return sbolSynth;
}
public void setSynthesizer(SBOLSynthesizer sbolSynth) {
this.sbolSynth = sbolSynth;
}
public void addNextNode(SynthesisNode nextNode) {
nextNodes.add(nextNode);
}
public Set<SynthesisNode> getNextNodes() {
return nextNodes;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
}
| Moved SynthesisNode to sbol package and remaned SBOLSynthesisNode.
| gui/src/biomodel/network/SynthesisNode.java | Moved SynthesisNode to sbol package and remaned SBOLSynthesisNode. |
||
Java | apache-2.0 | 18fec780d4516456677b20e5022658036ae0be57 | 0 | baldimir/optaplanner,baldimir/optaplanner,baldimir/optaplanner,baldimir/optaplanner,tkobayas/optaplanner,tkobayas/optaplanner,tkobayas/optaplanner,tkobayas/optaplanner,droolsjbpm/optaplanner,droolsjbpm/optaplanner,droolsjbpm/optaplanner,droolsjbpm/optaplanner | /*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.core.config.heuristic.selector.entity.pillar;
import java.util.Comparator;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import org.apache.commons.lang3.BooleanUtils;
import org.optaplanner.core.config.heuristic.policy.HeuristicConfigPolicy;
import org.optaplanner.core.config.heuristic.selector.SelectorConfig;
import org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType;
import org.optaplanner.core.config.heuristic.selector.common.SelectionOrder;
import org.optaplanner.core.config.heuristic.selector.entity.EntitySelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.generic.SubPillarType;
import org.optaplanner.core.config.util.ConfigUtils;
import org.optaplanner.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import org.optaplanner.core.impl.heuristic.selector.entity.EntitySelector;
import org.optaplanner.core.impl.heuristic.selector.entity.pillar.DefaultPillarSelector;
import org.optaplanner.core.impl.heuristic.selector.entity.pillar.PillarSelector;
import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
@XStreamAlias("pillarSelector")
public class PillarSelectorConfig extends SelectorConfig<PillarSelectorConfig> {
@XStreamAlias("entitySelector")
protected EntitySelectorConfig entitySelectorConfig = null;
protected Boolean subPillarEnabled = null;
protected Integer minimumSubPillarSize = null;
protected Integer maximumSubPillarSize = null;
public EntitySelectorConfig getEntitySelectorConfig() {
return entitySelectorConfig;
}
public void setEntitySelectorConfig(EntitySelectorConfig entitySelectorConfig) {
this.entitySelectorConfig = entitySelectorConfig;
}
/**
* @deprecated in favor of SubPillarType
* @see SubPillarType and its uses in pillar move selectors.
* @return Null when not set.
*/
@Deprecated(/* forRemoval = true */)
public Boolean getSubPillarEnabled() {
return subPillarEnabled;
}
/**
* @param subPillarEnabled true to enable, false to disable, null to leave unset.
* @deprecated in favor of SubPillarType
* @see SubPillarType and its uses in pillar move selectors.
*/
@Deprecated(/* forRemoval = true */)
public void setSubPillarEnabled(Boolean subPillarEnabled) {
this.subPillarEnabled = subPillarEnabled;
}
public Integer getMinimumSubPillarSize() {
return minimumSubPillarSize;
}
public void setMinimumSubPillarSize(Integer minimumSubPillarSize) {
this.minimumSubPillarSize = minimumSubPillarSize;
}
public Integer getMaximumSubPillarSize() {
return maximumSubPillarSize;
}
public void setMaximumSubPillarSize(Integer maximumSubPillarSize) {
this.maximumSubPillarSize = maximumSubPillarSize;
}
// ************************************************************************
// Builder methods
// ************************************************************************
/**
* @param configPolicy never null
* @param subPillarType if null, defaults to {@link SubPillarType#ALL} for backwards compatibility reasons.
* @param subPillarSequenceComparatorClass if not null, will force entites in the pillar to come in this order
* @param minimumCacheType never null, If caching is used (different from {@link SelectionCacheType#JUST_IN_TIME}),
* then it should be at least this {@link SelectionCacheType} because an ancestor already uses such caching
* and less would be pointless.
* @param inheritedSelectionOrder never null
* @param variableNameIncludeList sometimes null
* @return never null
*/
public PillarSelector buildPillarSelector(HeuristicConfigPolicy configPolicy, SubPillarType subPillarType,
Class<? extends Comparator> subPillarSequenceComparatorClass, SelectionCacheType minimumCacheType,
SelectionOrder inheritedSelectionOrder, List<String> variableNameIncludeList) {
if (subPillarEnabled != null && subPillarType != null) {
throw new IllegalArgumentException("Property subPillarEnabled (" + subPillarEnabled +
") on pillarSelectorConfig (" + this + ") must not be present when subPillarType (" +
subPillarType + ") is set on the parent MoveSelectorConfig.");
}
if (subPillarType != SubPillarType.SEQUENCE && subPillarSequenceComparatorClass != null) {
throw new IllegalArgumentException("Subpillar type (" + subPillarType + ") on pillarSelectorConfig (" + this +
") is not " + SubPillarType.SEQUENCE + ", yet subPillarSequenceComparatorClass (" +
subPillarSequenceComparatorClass + ") is provided.");
}
if (minimumCacheType.compareTo(SelectionCacheType.STEP) > 0) {
throw new IllegalArgumentException("The pillarSelectorConfig (" + this
+ ")'s minimumCacheType (" + minimumCacheType
+ ") must not be higher than " + SelectionCacheType.STEP
+ " because the pillars change every step.");
}
boolean subPillarActuallyEnabled = BooleanUtils.isTrue(subPillarEnabled) || subPillarType != SubPillarType.NONE;
// EntitySelector uses SelectionOrder.ORIGINAL because a DefaultPillarSelector STEP caches the values
EntitySelectorConfig entitySelectorConfig_ = entitySelectorConfig == null ? new EntitySelectorConfig()
: entitySelectorConfig;
EntitySelector entitySelector = entitySelectorConfig_.buildEntitySelector(configPolicy,
minimumCacheType, SelectionOrder.ORIGINAL);
List<GenuineVariableDescriptor> variableDescriptors = deduceVariableDescriptorList(
entitySelector.getEntityDescriptor(), variableNameIncludeList);
if (!subPillarActuallyEnabled
&& (minimumSubPillarSize != null || maximumSubPillarSize != null)) {
throw new IllegalArgumentException("The pillarSelectorConfig (" + this
+ ") must not disable subpillars while providing minimumSubPillarSize (" + minimumSubPillarSize
+ ") or maximumSubPillarSize (" + maximumSubPillarSize + ").");
}
SubPillarConfigPolicy subPillarPolicy = subPillarActuallyEnabled ?
configureSubPillars(subPillarType, subPillarSequenceComparatorClass, entitySelector, minimumSubPillarSize,
maximumSubPillarSize) :
SubPillarConfigPolicy.withoutSubpillars();
return new DefaultPillarSelector(entitySelector, variableDescriptors,
inheritedSelectionOrder.toRandomSelectionBoolean(), subPillarPolicy);
}
private SubPillarConfigPolicy configureSubPillars(SubPillarType pillarType,
Class<? extends Comparator> pillarOrderComparatorClass, EntitySelector entitySelector,
Integer minimumSubPillarSize, Integer maximumSubPillarSize) {
int actualMinimumSubPillarSize = defaultIfNull(minimumSubPillarSize, 1);
int actualMaximumSubPillarSize = defaultIfNull(maximumSubPillarSize, Integer.MAX_VALUE);
if (pillarType == null) { // for backwards compatibility reasons
return SubPillarConfigPolicy.withSubpillars(actualMinimumSubPillarSize, actualMaximumSubPillarSize);
}
switch (pillarType) {
case ALL:
return SubPillarConfigPolicy.withSubpillars(actualMinimumSubPillarSize, actualMaximumSubPillarSize);
case SEQUENCE:
if (pillarOrderComparatorClass == null) {
Class<?> entityClass = entitySelector.getEntityDescriptor().getEntityClass();
boolean isComparable = Comparable.class.isAssignableFrom(entityClass);
if (!isComparable) {
throw new IllegalArgumentException("Pillar type (" + pillarType + ") on pillarSelectorConfig (" +
this + ") does not provide pillarOrderComparatorClass while the entity (" +
entityClass.getCanonicalName() + ") does not implement Comparable.");
}
Comparator<Comparable> comparator = Comparable::compareTo;
return SubPillarConfigPolicy.sequential(actualMinimumSubPillarSize, actualMaximumSubPillarSize,
comparator);
} else {
Comparator<Object> comparator = ConfigUtils.newInstance(this, "pillarOrderComparatorClass", pillarOrderComparatorClass);
return SubPillarConfigPolicy.sequential(actualMinimumSubPillarSize, actualMaximumSubPillarSize,
comparator);
}
default:
throw new IllegalStateException("Subpillars can not be enabled and disabled at the same time.");
}
}
@Override
public void inherit(PillarSelectorConfig inheritedConfig) {
super.inherit(inheritedConfig);
entitySelectorConfig = ConfigUtils.inheritConfig(entitySelectorConfig, inheritedConfig.getEntitySelectorConfig());
subPillarEnabled = ConfigUtils.inheritOverwritableProperty(subPillarEnabled,
inheritedConfig.getSubPillarEnabled());
minimumSubPillarSize = ConfigUtils.inheritOverwritableProperty(minimumSubPillarSize,
inheritedConfig.getMinimumSubPillarSize());
maximumSubPillarSize = ConfigUtils.inheritOverwritableProperty(maximumSubPillarSize,
inheritedConfig.getMaximumSubPillarSize());
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + entitySelectorConfig + ")";
}
}
| optaplanner-core/src/main/java/org/optaplanner/core/config/heuristic/selector/entity/pillar/PillarSelectorConfig.java | /*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.core.config.heuristic.selector.entity.pillar;
import java.util.Comparator;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import org.apache.commons.lang3.BooleanUtils;
import org.optaplanner.core.config.heuristic.policy.HeuristicConfigPolicy;
import org.optaplanner.core.config.heuristic.selector.SelectorConfig;
import org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType;
import org.optaplanner.core.config.heuristic.selector.common.SelectionOrder;
import org.optaplanner.core.config.heuristic.selector.entity.EntitySelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.generic.SubPillarType;
import org.optaplanner.core.config.util.ConfigUtils;
import org.optaplanner.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import org.optaplanner.core.impl.heuristic.selector.entity.EntitySelector;
import org.optaplanner.core.impl.heuristic.selector.entity.pillar.DefaultPillarSelector;
import org.optaplanner.core.impl.heuristic.selector.entity.pillar.PillarSelector;
import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
@XStreamAlias("pillarSelector")
public class PillarSelectorConfig extends SelectorConfig<PillarSelectorConfig> {
@XStreamAlias("entitySelector")
protected EntitySelectorConfig entitySelectorConfig = null;
protected Boolean subPillarEnabled = null;
protected Integer minimumSubPillarSize = null;
protected Integer maximumSubPillarSize = null;
public EntitySelectorConfig getEntitySelectorConfig() {
return entitySelectorConfig;
}
public void setEntitySelectorConfig(EntitySelectorConfig entitySelectorConfig) {
this.entitySelectorConfig = entitySelectorConfig;
}
/**
* @deprecated in favor of SubPillarType
* @see SubPillarType and its uses in pillar move selectors.
* @return Null when not set.
*/
@Deprecated(/* forRemoval = true */)
public Boolean getSubPillarEnabled() {
return subPillarEnabled;
}
/**
* @param subPillarEnabled true to enable, false to disable, null to leave unset.
* @deprecated in favor of SubPillarType
* @see SubPillarType and its uses in pillar move selectors.
*/
@Deprecated(/* forRemoval = true */)
public void setSubPillarEnabled(Boolean subPillarEnabled) {
this.subPillarEnabled = subPillarEnabled;
}
public Integer getMinimumSubPillarSize() {
return minimumSubPillarSize;
}
public void setMinimumSubPillarSize(Integer minimumSubPillarSize) {
this.minimumSubPillarSize = minimumSubPillarSize;
}
public Integer getMaximumSubPillarSize() {
return maximumSubPillarSize;
}
public void setMaximumSubPillarSize(Integer maximumSubPillarSize) {
this.maximumSubPillarSize = maximumSubPillarSize;
}
// ************************************************************************
// Builder methods
// ************************************************************************
/**
* @param configPolicy never null
* @param subPillarType if null, defaults to {@link SubPillarType#ALL} for backwards compatibility reasons.
* @param subPillarSequenceComparatorClass if not null, will force entites in the pillar to come in this order
* @param minimumCacheType never null, If caching is used (different from {@link SelectionCacheType#JUST_IN_TIME}),
* then it should be at least this {@link SelectionCacheType} because an ancestor already uses such caching
* and less would be pointless.
* @param inheritedSelectionOrder never null
* @param variableNameIncludeList sometimes null
* @return never null
*/
public PillarSelector buildPillarSelector(HeuristicConfigPolicy configPolicy, SubPillarType subPillarType,
Class<? extends Comparator> subPillarSequenceComparatorClass, SelectionCacheType minimumCacheType,
SelectionOrder inheritedSelectionOrder, List<String> variableNameIncludeList) {
if (subPillarEnabled != null && subPillarType != null) {
throw new IllegalArgumentException("Property subPillarEnabled (" + subPillarEnabled +
") on pillarSelectorConfig (" + this + ") must not be present when subPillarType (" +
subPillarType + ") is set on the parent MoveSelectorConfig.");
}
if (subPillarType != SubPillarType.SEQUENCE && subPillarSequenceComparatorClass != null) {
throw new IllegalArgumentException("Subpillar type (" + subPillarType + ") on pillarSelectorConfig (" + this +
") is not " + SubPillarType.SEQUENCE + ", yet subPillarSequenceComparatorClass (" +
subPillarSequenceComparatorClass + ") is provided.");
}
if (minimumCacheType.compareTo(SelectionCacheType.STEP) > 0) {
throw new IllegalArgumentException("The pillarSelectorConfig (" + this
+ ")'s minimumCacheType (" + minimumCacheType
+ ") must not be higher than " + SelectionCacheType.STEP
+ " because the pillars change every step.");
}
boolean subPillarActuallyEnabled = BooleanUtils.isTrue(subPillarEnabled) || subPillarType != SubPillarType.NONE;
// EntitySelector uses SelectionOrder.ORIGINAL because a DefaultPillarSelector STEP caches the values
EntitySelectorConfig entitySelectorConfig_ = entitySelectorConfig == null ? new EntitySelectorConfig()
: entitySelectorConfig;
EntitySelector entitySelector = entitySelectorConfig_.buildEntitySelector(configPolicy,
minimumCacheType, SelectionOrder.ORIGINAL);
List<GenuineVariableDescriptor> variableDescriptors = deduceVariableDescriptorList(
entitySelector.getEntityDescriptor(), variableNameIncludeList);
if (!subPillarActuallyEnabled
&& (minimumSubPillarSize != null || maximumSubPillarSize != null)) {
throw new IllegalArgumentException("The pillarSelectorConfig (" + this
+ ") must not disable subpillars while providing minimumSubPillarSize (" + minimumSubPillarSize
+ ") or maximumSubPillarSize (" + maximumSubPillarSize + ").");
}
SubPillarConfigPolicy subPillarPolicy = subPillarActuallyEnabled ?
configureSubPillars(subPillarType, subPillarSequenceComparatorClass, entitySelector, minimumSubPillarSize,
maximumSubPillarSize) :
SubPillarConfigPolicy.withoutSubpillars();
return new DefaultPillarSelector(entitySelector, variableDescriptors,
inheritedSelectionOrder.toRandomSelectionBoolean(), subPillarPolicy);
}
private SubPillarConfigPolicy configureSubPillars(SubPillarType pillarType,
Class<? extends Comparator> pillarOrderComparatorClass, EntitySelector entitySelector,
Integer minimumSubPillarSize, Integer maximumSubPillarSize) {
int actualMinimumSubPillarSize = defaultIfNull(minimumSubPillarSize, 1);
int actualMaximumSubPillarSize = defaultIfNull(maximumSubPillarSize, Integer.MAX_VALUE);
if (pillarType == null) { // for backwards compatibility reasons
return SubPillarConfigPolicy.withSubpillars(actualMinimumSubPillarSize, actualMaximumSubPillarSize);
}
switch (pillarType) {
case ALL:
return SubPillarConfigPolicy.withSubpillars(actualMinimumSubPillarSize, actualMaximumSubPillarSize);
case SEQUENCE:
if (pillarOrderComparatorClass == null) {
Class<?> entityClass = entitySelector.getEntityDescriptor().getEntityClass();
boolean isComparable = entityClass.isAssignableFrom(Comparable.class);
if (!isComparable) {
throw new IllegalArgumentException("Pillar type (" + pillarType + ") on pillarSelectorConfig (" +
this + ") does not provide pillarOrderComparatorClass while the entity (" +
entityClass.getCanonicalName() + ") does not implement Comparable.");
}
Comparator<Comparable> comparator = Comparable::compareTo;
return SubPillarConfigPolicy.sequential(actualMinimumSubPillarSize, actualMaximumSubPillarSize,
comparator);
} else {
Comparator<Object> comparator = ConfigUtils.newInstance(this, "pillarOrderComparatorClass", pillarOrderComparatorClass);
return SubPillarConfigPolicy.sequential(actualMinimumSubPillarSize, actualMaximumSubPillarSize,
comparator);
}
default:
throw new IllegalStateException("Subpillars can not be enabled and disabled at the same time.");
}
}
@Override
public void inherit(PillarSelectorConfig inheritedConfig) {
super.inherit(inheritedConfig);
entitySelectorConfig = ConfigUtils.inheritConfig(entitySelectorConfig, inheritedConfig.getEntitySelectorConfig());
subPillarEnabled = ConfigUtils.inheritOverwritableProperty(subPillarEnabled,
inheritedConfig.getSubPillarEnabled());
minimumSubPillarSize = ConfigUtils.inheritOverwritableProperty(minimumSubPillarSize,
inheritedConfig.getMinimumSubPillarSize());
maximumSubPillarSize = ConfigUtils.inheritOverwritableProperty(maximumSubPillarSize,
inheritedConfig.getMaximumSubPillarSize());
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + entitySelectorConfig + ")";
}
}
| Fix processing of Comparable on subpillar sequence comparator XML
| optaplanner-core/src/main/java/org/optaplanner/core/config/heuristic/selector/entity/pillar/PillarSelectorConfig.java | Fix processing of Comparable on subpillar sequence comparator XML |
|
Java | apache-2.0 | 7e1054ac9f0c2db535eeb72ab6a8e3f157056691 | 0 | gaieepo/HubTurbo,gaieepo/HubTurbo | package guitests;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.loadui.testfx.utils.FXTestUtils;
import javafx.application.Platform;
import util.PlatformEx;
public class PlatformExTest extends UITest {
@Override
public void launchApp() {
FXTestUtils.launchApp(TestUI.class);
}
/**
* This method is needed to sequence concurrent tests. Order matters for these
* as they rely on Platform.runLater, so we can't let them run in arbitrary order.
*/
@Test
public void sequenceTests() {
waitOnFxThreadTest();
runLaterAndWaitTest();
}
public void waitOnFxThreadTest() {
AtomicInteger result = new AtomicInteger(0);
Platform.runLater(result::incrementAndGet);
PlatformEx.waitOnFxThread();
assertEquals(1, result.get());
}
public void runLaterAndWaitTest() {
// On another thread, runLaterAndWait blocks until the operation is done
AtomicInteger result = new AtomicInteger(0);
PlatformEx.runLaterAndWait(result::incrementAndGet);
assertEquals(1, result.get());
// On the UI thread, the callback doesn't happen immediately
Platform.runLater(() -> {
assertEquals(1, result.get());
PlatformEx.runLaterAndWait(result::incrementAndGet);
assertEquals(1, result.get());
});
}
@Test
public void runAndWaitTest() {
// On another thread, runAndWait blocks until the operation is done
AtomicInteger result = new AtomicInteger(0);
PlatformEx.runAndWait(result::incrementAndGet);
assertEquals(1, result.get());
// On the UI thread, the callback is invoked immediately
Platform.runLater(() -> {
assertEquals(1, result.get());
PlatformEx.runAndWait(result::incrementAndGet);
assertEquals(2, result.get());
});
}
}
| src/test/java/guitests/PlatformExTest.java | package guitests;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.loadui.testfx.utils.FXTestUtils;
import javafx.application.Platform;
import util.PlatformEx;
public class PlatformExTest extends UITest {
@Override
public void launchApp() {
FXTestUtils.launchApp(TestUI.class);
}
/**
* This method is needed to sequence concurrent tests. Order matters for these
* as they rely on Platform.runLater, so we can't let them run in arbitrary order.
*/
@Test
public void sequenceTests() {
waitOnFxThreadTest();
runLaterAndWaitTest();
}
public void waitOnFxThreadTest() {
AtomicInteger result = new AtomicInteger(0);
Platform.runLater(result::incrementAndGet);
assertEquals(0, result.get());
PlatformEx.waitOnFxThread();
assertEquals(1, result.get());
}
public void runLaterAndWaitTest() {
// On another thread, runLaterAndWait blocks until the operation is done
AtomicInteger result = new AtomicInteger(0);
PlatformEx.runLaterAndWait(result::incrementAndGet);
assertEquals(1, result.get());
// On the UI thread, the callback doesn't happen immediately
Platform.runLater(() -> {
assertEquals(1, result.get());
PlatformEx.runLaterAndWait(result::incrementAndGet);
assertEquals(1, result.get());
});
}
@Test
public void runAndWaitTest() {
// On another thread, runAndWait blocks until the operation is done
AtomicInteger result = new AtomicInteger(0);
PlatformEx.runAndWait(result::incrementAndGet);
assertEquals(1, result.get());
// On the UI thread, the callback is invoked immediately
Platform.runLater(() -> {
assertEquals(1, result.get());
PlatformEx.runAndWait(result::incrementAndGet);
assertEquals(2, result.get());
});
}
}
| Fixed nondeterminism in PlatformExTest
We are not actually guaranteed that the runnable given to
Platform.runLater will execute (on the UI thread) after what immediately
follows it (which executes on an arbitrary thread), though that is what
usually happens.
This gets rid of that assumption. The only thing we can say for sure
about about the result there is that it should be 1 after the
invocation of waitOnFxThread.
| src/test/java/guitests/PlatformExTest.java | Fixed nondeterminism in PlatformExTest |
|
Java | apache-2.0 | 658b28cda48d32f19ca09cc77c1b0ae9e6140fd8 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.xdebugger;
import com.intellij.execution.impl.ConsoleViewImpl;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.UsefulTestCase;
import com.intellij.util.SmartList;
import com.intellij.util.concurrency.FutureResult;
import com.intellij.util.ui.TextTransferable;
import com.intellij.util.ui.UIUtil;
import com.intellij.xdebugger.breakpoints.*;
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator;
import com.intellij.xdebugger.frame.*;
import com.intellij.xdebugger.impl.XDebugSessionImpl;
import com.intellij.xdebugger.impl.XDebuggerUtilImpl;
import com.intellij.xdebugger.impl.XSourcePositionImpl;
import com.intellij.xdebugger.impl.breakpoints.XBreakpointUtil;
import com.intellij.xdebugger.impl.breakpoints.XExpressionImpl;
import com.intellij.xdebugger.impl.breakpoints.XLineBreakpointImpl;
import com.intellij.xdebugger.impl.frame.XStackFrameContainerEx;
import one.util.streamex.StreamEx;
import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.concurrency.Promise;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
public class XDebuggerTestUtil {
private static final int TIMEOUT_MS = 25_000;
private XDebuggerTestUtil() {
}
public static <B extends XBreakpoint<?>> void assertBreakpointValidity(Project project,
VirtualFile file,
int line,
boolean validity,
String errorMessage,
Class<? extends XBreakpointType<B, ?>> breakpointType) {
XLineBreakpointType type = (XLineBreakpointType)XDebuggerUtil.getInstance().findBreakpointType(breakpointType);
XBreakpointManager manager = XDebuggerManager.getInstance(project).getBreakpointManager();
XLineBreakpointImpl breakpoint = ReadAction.compute(() -> (XLineBreakpointImpl)manager.findBreakpointAtLine(type, file, line));
assertNotNull(breakpoint);
assertEquals(validity ? XDebuggerUtilImpl.getVerifiedIcon(breakpoint) : AllIcons.Debugger.Db_invalid_breakpoint, breakpoint.getIcon());
assertEquals(errorMessage, breakpoint.getErrorMessage());
}
@Nullable
public static Promise<List<? extends XLineBreakpointType.XLineBreakpointVariant>>
computeLineBreakpointVariants(Project project, VirtualFile file, int line) {
return ReadAction.compute(() -> {
List<XLineBreakpointType> types = StreamEx.of(XDebuggerUtil.getInstance().getLineBreakpointTypes())
.filter(type -> type.canPutAt(file, line, project))
.collect(Collectors.toCollection(SmartList::new));
return XDebuggerUtilImpl.getLineBreakpointVariants(project, types, XSourcePositionImpl.create(file, line));
});
}
@Nullable
public static XLineBreakpoint toggleBreakpoint(Project project, VirtualFile file, int line) {
final Promise<XLineBreakpoint> breakpointPromise = WriteAction.computeAndWait(() -> ((XDebuggerUtilImpl)XDebuggerUtil.getInstance())
.toggleAndReturnLineBreakpoint(project, file, line, false));
try {
try {
return breakpointPromise.blockingGet(TIMEOUT_MS);
}
catch (TimeoutException e) {
throw new RuntimeException(e);
}
}
catch (ExecutionException e) {
throw new RuntimeException(e.getCause());
}
}
public static <P extends XBreakpointProperties> XBreakpoint<P> insertBreakpoint(final Project project,
final P properties,
final Class<? extends XBreakpointType<XBreakpoint<P>, P>> typeClass) {
return WriteAction.computeAndWait(() -> XDebuggerManager.getInstance(project).getBreakpointManager().addBreakpoint(
XBreakpointType.EXTENSION_POINT_NAME.findExtension(typeClass), properties));
}
public static void removeBreakpoint(@NotNull final Project project,
@NotNull final VirtualFile file,
final int line) {
XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
WriteAction.runAndWait(() -> {
XLineBreakpoint<?> breakpoint = Arrays.stream(XDebuggerUtil.getInstance().getLineBreakpointTypes())
.map(t -> breakpointManager.findBreakpointAtLine(t, file, line)).filter(Objects::nonNull)
.findFirst().orElse(null);
assertNotNull(breakpoint);
breakpointManager.removeBreakpoint(breakpoint);
});
}
public static void assertPosition(XSourcePosition pos, VirtualFile file, int line) throws IOException {
assertNotNull("No current position", pos);
assertEquals(new File(file.getPath()).getCanonicalPath(), new File(pos.getFile().getPath()).getCanonicalPath());
if (line != -1) assertEquals(line, pos.getLine());
}
public static void assertCurrentPosition(XDebugSession session, VirtualFile file, int line) throws IOException {
assertPosition(session.getCurrentPosition(), file, line);
}
public static XExecutionStack getActiveThread(@NotNull XDebugSession session) {
return session.getSuspendContext().getActiveExecutionStack();
}
public static List<XExecutionStack> collectThreads(@NotNull XDebugSession session) {
return collectThreadsWithErrors(session).first;
}
public static Pair<List<XExecutionStack>, String> collectThreadsWithErrors(@NotNull XDebugSession session) {
return collectThreadsWithErrors(session, XDebuggerTestUtil::waitFor);
}
public static Pair<List<XExecutionStack>, String> collectThreadsWithErrors(@NotNull XDebugSession session, @NotNull BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestExecutionStackContainer container = new XTestExecutionStackContainer();
session.getSuspendContext().computeExecutionStacks(container);
return container.waitFor(TIMEOUT_MS, waitFunction);
}
public static List<XStackFrame> collectFrames(@NotNull XDebugSession session) {
return collectFrames(null, session);
}
public static List<XStackFrame> collectFrames(@Nullable XExecutionStack thread, @NotNull XDebugSession session) {
return collectFrames(thread == null ? getActiveThread(session) : thread);
}
public static String getFramePresentation(XStackFrame frame) {
TextTransferable.ColoredStringBuilder builder = new TextTransferable.ColoredStringBuilder();
frame.customizePresentation(builder);
return builder.getBuilder().toString();
}
public static List<XStackFrame> collectFrames(@NotNull XExecutionStack thread) {
return collectFrames(thread, TIMEOUT_MS * 2);
}
public static List<XStackFrame> collectFrames(XExecutionStack thread, long timeout) {
return collectFrames(thread, timeout, XDebuggerTestUtil::waitFor);
}
public static List<XStackFrame> collectFrames(XExecutionStack thread, long timeout, BiFunction<Semaphore, Long, Boolean> waitFunction) {
return collectFramesWithError(thread, timeout, waitFunction).first;
}
public static Pair<List<XStackFrame>, String> collectFramesWithError(XExecutionStack thread, long timeout) {
return collectFramesWithError(thread, timeout, XDebuggerTestUtil::waitFor);
}
public static Pair<List<XStackFrame>, String> collectFramesWithError(XExecutionStack thread, long timeout, BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestStackFrameContainer container = new XTestStackFrameContainer();
thread.computeStackFrames(0, container);
return container.waitFor(timeout, waitFunction);
}
public static Pair<List<XStackFrame>, XStackFrame> collectFramesWithSelected(@NotNull XDebugSession session, long timeout) {
return collectFramesWithSelected(getActiveThread(session), timeout);
}
public static Pair<List<XStackFrame>, XStackFrame> collectFramesWithSelected(XExecutionStack thread, long timeout) {
return collectFramesWithSelected(thread, timeout, XDebuggerTestUtil::waitFor);
}
public static Pair<List<XStackFrame>, XStackFrame> collectFramesWithSelected(XExecutionStack thread, long timeout, BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestStackFrameContainer container = new XTestStackFrameContainer();
thread.computeStackFrames(0, container);
List<XStackFrame> all = container.waitFor(timeout, waitFunction).first;
return Pair.create(all, container.frameToSelect);
}
/**
* @deprecated use {@link XDebuggerTestUtil#collectChildren(XValueContainer)}
*/
@Deprecated
public static List<XValue> collectVariables(XStackFrame frame) {
return collectChildren(frame);
}
public static List<XValue> collectChildren(XValueContainer value) {
return collectChildren(value, XDebuggerTestUtil::waitFor);
}
public static List<XValue> collectChildren(XValueContainer value, BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestCompositeNode container = new XTestCompositeNode();
value.computeChildren(container);
return container.waitFor(TIMEOUT_MS, waitFunction).first;
}
public static Pair<XValue, String> evaluate(XDebugSession session, XExpression expression) {
return evaluate(session, expression, TIMEOUT_MS);
}
public static Pair<XValue, String> evaluate(XDebugSession session, XExpression expression, BiFunction<Semaphore, Long, Boolean> waitFunction) {
return evaluate(session, expression, TIMEOUT_MS, waitFunction);
}
public static Pair<XValue, String> evaluate(XDebugSession session, String expression) {
return evaluate(session, expression, XDebuggerTestUtil::waitFor);
}
public static Pair<XValue, String> evaluate(XDebugSession session, String expression, BiFunction<Semaphore, Long, Boolean> waitFunction) {
return evaluate(session, XExpressionImpl.fromText(expression), TIMEOUT_MS, waitFunction);
}
public static Pair<XValue, String> evaluate(XDebugSession session, String expression, long timeout) {
return evaluate(session, expression, timeout, XDebuggerTestUtil::waitFor);
}
public static Pair<XValue, String> evaluate(XDebugSession session, String expression, long timeout, BiFunction<Semaphore, Long, Boolean> waitFunction) {
return evaluate(session, XExpressionImpl.fromText(expression), timeout, waitFunction);
}
private static Pair<XValue, String> evaluate(XDebugSession session, XExpression expression, long timeout) {
return evaluate(session, expression, timeout, XDebuggerTestUtil::waitFor);
}
private static Pair<XValue, String> evaluate(XDebugSession session, XExpression expression, long timeout, BiFunction<Semaphore, Long, Boolean> waitFunction) {
XStackFrame frame = session.getCurrentStackFrame();
assertNotNull(frame);
XDebuggerEvaluator evaluator = frame.getEvaluator();
assertNotNull(evaluator);
XTestEvaluationCallback callback = new XTestEvaluationCallback();
evaluator.evaluate(expression, callback, session.getCurrentPosition());
return callback.waitFor(timeout, waitFunction);
}
public static void waitForSwing() throws InterruptedException {
final com.intellij.util.concurrency.Semaphore s = new com.intellij.util.concurrency.Semaphore();
s.down();
ApplicationManager.getApplication().invokeLater(() -> s.up());
s.waitForUnsafe();
UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {});
}
@NotNull
public static XValue findVar(Collection<XValue> vars, String name) {
StringBuilder names = new StringBuilder();
for (XValue each : vars) {
if (each instanceof XNamedValue) {
String eachName = ((XNamedValue)each).getName();
if (eachName.equals(name)) return each;
if (names.length() > 0) names.append(", ");
names.append(eachName);
}
}
throw new AssertionError("var '" + name + "' not found among " + names);
}
public static XTestValueNode computePresentation(@NotNull XValue value) {
return computePresentation(value, XDebuggerTestUtil::waitFor);
}
public static XTestValueNode computePresentation(@NotNull XValue value, BiFunction<Semaphore, Long, Boolean> waitFunction) {
return computePresentation(value, TIMEOUT_MS, waitFunction);
}
public static XTestValueNode computePresentation(XValue value, long timeout) {
return computePresentation(value, timeout, XDebuggerTestUtil::waitFor);
}
public static XTestValueNode computePresentation(XValue value, long timeout, BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestValueNode node = new XTestValueNode();
if (value instanceof XNamedValue) {
node.myName = ((XNamedValue)value).getName();
}
value.computePresentation(node, XValuePlace.TREE);
node.waitFor(timeout, waitFunction);
return node;
}
public static void assertVariable(XValue var,
@Nullable String name,
@Nullable String type,
@Nullable String value,
@Nullable Boolean hasChildren) {
assertVariable(var, name, type, value, hasChildren, XDebuggerTestUtil::waitFor);
}
public static void assertVariable(XValue var,
@Nullable String name,
@Nullable String type,
@Nullable String value,
@Nullable Boolean hasChildren,
BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestValueNode node = computePresentation(var, waitFunction);
if (name != null) assertEquals(name, node.myName);
if (type != null) assertEquals(type, node.myType);
if (value != null) assertEquals(value, node.myValue);
if (hasChildren != null) assertEquals(hasChildren, node.myHasChildren);
}
public static void assertVariableValue(XValue var, @Nullable String name, @Nullable String value) {
assertVariable(var, name, null, value, null);
}
public static void assertVariableValue(Collection<XValue> vars, @Nullable String name, @Nullable String value) {
assertVariableValue(findVar(vars, name), name, value);
}
public static void assertVariableValueMatches(@NotNull Collection<XValue> vars,
@Nullable String name,
@Nullable @Language("RegExp") String valuePattern) {
assertVariableValueMatches(findVar(vars, name), name, valuePattern);
}
public static void assertVariableValueMatches(@NotNull Collection<XValue> vars,
@Nullable String name,
@Nullable String type,
@Nullable @Language("RegExp") String valuePattern) {
assertVariableValueMatches(findVar(vars, name), name, type, valuePattern);
}
public static void assertVariableValueMatches(@NotNull Collection<XValue> vars,
@Nullable String name,
@Nullable String type,
@Nullable @Language("RegExp") String valuePattern,
@Nullable Boolean hasChildren) {
assertVariableValueMatches(findVar(vars, name), name, type, valuePattern, hasChildren);
}
public static void assertVariableValueMatches(@NotNull XValue var,
@Nullable String name,
@Nullable @Language("RegExp") String valuePattern) {
assertVariableValueMatches(var, name, null, valuePattern);
}
public static void assertVariableValueMatches(@NotNull XValue var,
@Nullable String name,
@Nullable String type,
@Nullable @Language("RegExp") String valuePattern) {
assertVariableValueMatches(var, name, type, valuePattern, null);
}
public static void assertVariableValueMatches(@NotNull XValue var,
@Nullable String name,
@Nullable String type,
@Nullable @Language("RegExp") String valuePattern,
@Nullable Boolean hasChildren) {
assertVariableValueMatches(var, name, type, valuePattern, hasChildren, XDebuggerTestUtil::waitFor);
}
public static void assertVariableValueMatches(@NotNull XValue var,
@Nullable String name,
@Nullable String type,
@Nullable @Language("RegExp") String valuePattern,
@Nullable Boolean hasChildren,
BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestValueNode node = computePresentation(var, waitFunction);
if (name != null) assertEquals(name, node.myName);
if (type != null) assertEquals(type, node.myType);
if (valuePattern != null) {
assertTrue("Expected value: " + valuePattern + " Actual value: " + node.myValue, node.myValue.matches(valuePattern));
}
if (hasChildren != null) assertEquals(hasChildren, node.myHasChildren);
}
public static void assertVariableTypeMatches(@NotNull Collection<XValue> vars,
@Nullable String name,
@Nullable @Language("RegExp") String typePattern) {
assertVariableTypeMatches(findVar(vars, name), name, typePattern);
}
public static void assertVariableTypeMatches(@NotNull XValue var,
@Nullable String name,
@Nullable @Language("RegExp") String typePattern) {
assertVariableTypeMatches(var, name, typePattern, XDebuggerTestUtil::waitFor);
}
public static void assertVariableTypeMatches(@NotNull XValue var,
@Nullable String name,
@Nullable @Language("RegExp") String typePattern,
@NotNull BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestValueNode node = computePresentation(var, waitFunction);
if (name != null) {
assertEquals(name, node.myName);
}
if (typePattern != null) {
assertTrue("Expected type: " + typePattern + " Actual type: " + node.myType,
node.myType != null && node.myType.matches(typePattern));
}
}
public static void assertVariableFullValue(@NotNull XValue var,
@Nullable String value) throws Exception {
assertVariableFullValue(var, value, XDebuggerTestUtil::waitFor);
}
public static void assertVariableFullValue(@NotNull XValue var,
@Nullable String value,
@NotNull BiFunction<Semaphore, Long, Boolean> waitFunction) throws Exception {
XTestValueNode node = computePresentation(var, waitFunction);
if (value == null) {
assertNull("full value evaluator should be null", node.myFullValueEvaluator);
}
else {
final FutureResult<String> result = new FutureResult<>();
node.myFullValueEvaluator.startEvaluation(new XFullValueEvaluator.XFullValueEvaluationCallback() {
@Override
public void evaluated(@NotNull String fullValue) {
result.set(fullValue);
}
@Override
public void evaluated(@NotNull String fullValue, @Nullable Font font) {
result.set(fullValue);
}
@Override
public void errorOccurred(@NotNull String errorMessage) {
result.set(errorMessage);
}
});
assertEquals(value, result.get(TIMEOUT_MS, TimeUnit.MILLISECONDS));
}
}
public static void assertVariableFullValue(Collection<XValue> vars, @Nullable String name, @Nullable String value)
throws Exception {
assertVariableFullValue(findVar(vars, name), value);
}
public static void assertVariables(List<XValue> vars, String... names) {
List<String> expectedNames = new ArrayList<>(Arrays.asList(names));
List<String> actualNames = new ArrayList<>();
for (XValue each : vars) {
actualNames.add(computePresentation(each).myName);
}
Collections.sort(actualNames);
Collections.sort(expectedNames);
UsefulTestCase.assertOrderedEquals(actualNames, expectedNames);
}
public static void assertVariablesContain(List<XValue> vars, String... names) {
List<String> expectedNames = new ArrayList<>(Arrays.asList(names));
List<String> actualNames = new ArrayList<>();
for (XValue each : vars) {
actualNames.add(computePresentation(each).myName);
}
expectedNames.removeAll(actualNames);
assertTrue("Missing variables:" + StringUtil.join(expectedNames, ", ")
+ "\nAll Variables: " + StringUtil.join(actualNames, ", "),
expectedNames.isEmpty()
);
}
public static void assertSourcePosition(final XValue value, VirtualFile file, int offset) {
final XTestNavigatable n = new XTestNavigatable();
ApplicationManager.getApplication().runReadAction(() -> value.computeSourcePosition(n));
assertNotNull(n.myPosition);
assertEquals(file, n.myPosition.getFile());
assertEquals(offset, n.myPosition.getOffset());
}
public static void assertSourcePosition(final XStackFrame frame, VirtualFile file, int line) {
XSourcePosition position = frame.getSourcePosition();
assertNotNull(position);
assertEquals(file, position.getFile());
assertEquals(line, position.getLine());
}
public static boolean waitFor(Semaphore semaphore, long timeoutInMillis) {
long end = System.currentTimeMillis() + timeoutInMillis;
long remaining = timeoutInMillis;
do {
try {
return semaphore.tryAcquire(remaining, TimeUnit.MILLISECONDS);
}
catch (InterruptedException ignored) {
remaining = end - System.currentTimeMillis();
}
} while (remaining > 0);
return false;
}
public static void assertVariable(Collection<XValue> vars,
@Nullable String name,
@Nullable String type,
@Nullable String value,
@Nullable Boolean hasChildren) {
assertVariable(findVar(vars, name), name, type, value, hasChildren);
}
@NotNull
public static String getConsoleText(final @NotNull ConsoleViewImpl consoleView) {
WriteAction.runAndWait(() -> consoleView.flushDeferredText());
return consoleView.getEditor().getDocument().getText();
}
public static <T extends XBreakpointType> XBreakpoint addBreakpoint(@NotNull final Project project,
@NotNull final Class<T> exceptionType,
@NotNull final XBreakpointProperties properties) {
XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
Ref<XBreakpoint> breakpoint = Ref.create(null);
XBreakpointUtil.breakpointTypes()
.select(exceptionType)
.findFirst()
.ifPresent(type -> WriteAction.runAndWait(() -> breakpoint.set(breakpointManager.addBreakpoint(type, properties))));
return breakpoint.get();
}
public static void removeAllBreakpoints(@NotNull final Project project) {
final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
XBreakpoint<?>[] breakpoints = getBreakpoints(breakpointManager);
for (final XBreakpoint b : breakpoints) {
WriteAction.runAndWait(() -> breakpointManager.removeBreakpoint(b));
}
}
public static XBreakpoint<?>[] getBreakpoints(final XBreakpointManager breakpointManager) {
return ReadAction.compute(breakpointManager::getAllBreakpoints);
}
public static <B extends XBreakpoint<?>>
void setDefaultBreakpointEnabled(@NotNull final Project project, Class<? extends XBreakpointType<B, ?>> bpTypeClass, boolean enabled) {
final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
XBreakpointType<B, ?> bpType = XDebuggerUtil.getInstance().findBreakpointType(bpTypeClass);
XBreakpoint<?> bp = breakpointManager.getDefaultBreakpoint(bpType);
if (bp != null) {
bp.setEnabled(enabled);
}
}
public static void setBreakpointCondition(Project project, int line, final String condition) {
XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
for (XBreakpoint breakpoint : getBreakpoints(breakpointManager)) {
if (breakpoint instanceof XLineBreakpoint) {
final XLineBreakpoint lineBreakpoint = (XLineBreakpoint)breakpoint;
if (lineBreakpoint.getLine() == line) {
WriteAction.runAndWait(() -> lineBreakpoint.setCondition(condition));
}
}
}
}
public static void setBreakpointLogExpression(Project project, int line, final String logExpression) {
XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
for (XBreakpoint breakpoint : getBreakpoints(breakpointManager)) {
if (breakpoint instanceof XLineBreakpoint) {
final XLineBreakpoint lineBreakpoint = (XLineBreakpoint)breakpoint;
if (lineBreakpoint.getLine() == line) {
WriteAction.runAndWait(() -> {
lineBreakpoint.setLogExpression(logExpression);
lineBreakpoint.setLogMessage(true);
});
}
}
}
}
public static void disposeDebugSession(final XDebugSession debugSession) {
WriteAction.runAndWait(() -> {
XDebugSessionImpl session = (XDebugSessionImpl)debugSession;
Disposer.dispose(session.getSessionTab());
Disposer.dispose(session.getConsoleView());
});
}
public static void assertVariable(Pair<XValue, String> varAndErrorMessage,
@Nullable String name,
@Nullable String type,
@Nullable String value,
@Nullable Boolean hasChildren) {
assertNull(varAndErrorMessage.second);
assertVariable(varAndErrorMessage.first, name, type, value, hasChildren);
}
public static String assertVariableExpression(XValue desc, String expectedExpression) {
String expression = desc.getEvaluationExpression();
assertEquals(expectedExpression, expression);
return expression;
}
public static class XTestExecutionStackContainer extends XTestContainer<XExecutionStack> implements XSuspendContext.XExecutionStackContainer {
@Override
public void errorOccurred(@NotNull String errorMessage) {
setErrorMessage(errorMessage);
}
@Override
public void addExecutionStack(@NotNull List<? extends XExecutionStack> executionStacks, boolean last) {
addChildren(executionStacks, last);
}
}
public static class XTestStackFrameContainer extends XTestContainer<XStackFrame> implements XStackFrameContainerEx {
public volatile XStackFrame frameToSelect;
@Override
public void addStackFrames(@NotNull List<? extends XStackFrame> stackFrames, boolean last) {
addChildren(stackFrames, last);
}
@Override
public void addStackFrames(@NotNull List<? extends XStackFrame> stackFrames, @Nullable XStackFrame toSelect, boolean last) {
if (toSelect != null) frameToSelect = toSelect;
addChildren(stackFrames, last);
}
@Override
public void errorOccurred(@NotNull String errorMessage) {
setErrorMessage(errorMessage);
}
}
public static class XTestNavigatable implements XNavigatable {
private XSourcePosition myPosition;
@Override
public void setSourcePosition(@Nullable XSourcePosition sourcePosition) {
myPosition = sourcePosition;
}
public XSourcePosition getPosition() {
return myPosition;
}
}
}
| platform/xdebugger-testFramework/src/com/intellij/xdebugger/XDebuggerTestUtil.java | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.xdebugger;
import com.intellij.execution.impl.ConsoleViewImpl;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.UsefulTestCase;
import com.intellij.util.SmartList;
import com.intellij.util.concurrency.FutureResult;
import com.intellij.util.ui.TextTransferable;
import com.intellij.util.ui.UIUtil;
import com.intellij.xdebugger.breakpoints.*;
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator;
import com.intellij.xdebugger.frame.*;
import com.intellij.xdebugger.impl.XDebugSessionImpl;
import com.intellij.xdebugger.impl.XDebuggerUtilImpl;
import com.intellij.xdebugger.impl.XSourcePositionImpl;
import com.intellij.xdebugger.impl.breakpoints.XBreakpointUtil;
import com.intellij.xdebugger.impl.breakpoints.XExpressionImpl;
import com.intellij.xdebugger.impl.breakpoints.XLineBreakpointImpl;
import com.intellij.xdebugger.impl.frame.XStackFrameContainerEx;
import one.util.streamex.StreamEx;
import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.concurrency.Promise;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
public class XDebuggerTestUtil {
private static final int TIMEOUT_MS = 25_000;
private XDebuggerTestUtil() {
}
public static <B extends XBreakpoint<?>> void assertBreakpointValidity(Project project,
VirtualFile file,
int line,
boolean validity,
String errorMessage,
Class<? extends XBreakpointType<B, ?>> breakpointType) {
XLineBreakpointType type = (XLineBreakpointType)XDebuggerUtil.getInstance().findBreakpointType(breakpointType);
XBreakpointManager manager = XDebuggerManager.getInstance(project).getBreakpointManager();
XLineBreakpointImpl breakpoint = ReadAction.compute(() -> (XLineBreakpointImpl)manager.findBreakpointAtLine(type, file, line));
assertNotNull(breakpoint);
assertEquals(validity ? XDebuggerUtilImpl.getVerifiedIcon(breakpoint) : AllIcons.Debugger.Db_invalid_breakpoint, breakpoint.getIcon());
assertEquals(errorMessage, breakpoint.getErrorMessage());
}
@Nullable
public static Promise<List<? extends XLineBreakpointType.XLineBreakpointVariant>>
computeLineBreakpointVariants(Project project, VirtualFile file, int line) {
return ReadAction.compute(() -> {
List<XLineBreakpointType> types = StreamEx.of(XDebuggerUtil.getInstance().getLineBreakpointTypes())
.filter(type -> type.canPutAt(file, line, project))
.collect(Collectors.toCollection(SmartList::new));
return XDebuggerUtilImpl.getLineBreakpointVariants(project, types, XSourcePositionImpl.create(file, line));
});
}
@Nullable
public static XLineBreakpoint toggleBreakpoint(Project project, VirtualFile file, int line) {
final Promise<XLineBreakpoint> breakpointPromise = WriteAction.computeAndWait(() -> ((XDebuggerUtilImpl)XDebuggerUtil.getInstance())
.toggleAndReturnLineBreakpoint(project, file, line, false));
try {
try {
return breakpointPromise.blockingGet(TIMEOUT_MS);
}
catch (TimeoutException e) {
throw new RuntimeException(e);
}
}
catch (ExecutionException e) {
throw new RuntimeException(e.getCause());
}
}
public static <P extends XBreakpointProperties> XBreakpoint<P> insertBreakpoint(final Project project,
final P properties,
final Class<? extends XBreakpointType<XBreakpoint<P>, P>> typeClass) {
return WriteAction.computeAndWait(() -> XDebuggerManager.getInstance(project).getBreakpointManager().addBreakpoint(
XBreakpointType.EXTENSION_POINT_NAME.findExtension(typeClass), properties));
}
public static void removeBreakpoint(@NotNull final Project project,
@NotNull final VirtualFile file,
final int line) {
XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
WriteAction.runAndWait(() -> {
XLineBreakpoint<?> breakpoint = Arrays.stream(XDebuggerUtil.getInstance().getLineBreakpointTypes())
.map(t -> breakpointManager.findBreakpointAtLine(t, file, line)).filter(Objects::nonNull)
.findFirst().orElse(null);
assertNotNull(breakpoint);
breakpointManager.removeBreakpoint(breakpoint);
});
}
public static void assertPosition(XSourcePosition pos, VirtualFile file, int line) throws IOException {
assertNotNull("No current position", pos);
assertEquals(new File(file.getPath()).getCanonicalPath(), new File(pos.getFile().getPath()).getCanonicalPath());
if (line != -1) assertEquals(line, pos.getLine());
}
public static void assertCurrentPosition(XDebugSession session, VirtualFile file, int line) throws IOException {
assertPosition(session.getCurrentPosition(), file, line);
}
public static XExecutionStack getActiveThread(@NotNull XDebugSession session) {
return session.getSuspendContext().getActiveExecutionStack();
}
public static List<XExecutionStack> collectThreads(@NotNull XDebugSession session) {
return collectThreadsWithErrors(session).first;
}
public static Pair<List<XExecutionStack>, String> collectThreadsWithErrors(@NotNull XDebugSession session) {
return collectThreadsWithErrors(session, XDebuggerTestUtil::waitFor);
}
public static Pair<List<XExecutionStack>, String> collectThreadsWithErrors(@NotNull XDebugSession session, @NotNull BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestExecutionStackContainer container = new XTestExecutionStackContainer();
session.getSuspendContext().computeExecutionStacks(container);
return container.waitFor(TIMEOUT_MS, waitFunction);
}
public static List<XStackFrame> collectFrames(@NotNull XDebugSession session) {
return collectFrames(null, session);
}
public static List<XStackFrame> collectFrames(@Nullable XExecutionStack thread, @NotNull XDebugSession session) {
return collectFrames(thread == null ? getActiveThread(session) : thread);
}
public static String getFramePresentation(XStackFrame frame) {
TextTransferable.ColoredStringBuilder builder = new TextTransferable.ColoredStringBuilder();
frame.customizePresentation(builder);
return builder.getBuilder().toString();
}
public static List<XStackFrame> collectFrames(@NotNull XExecutionStack thread) {
return collectFrames(thread, TIMEOUT_MS * 2);
}
public static List<XStackFrame> collectFrames(XExecutionStack thread, long timeout) {
return collectFrames(thread, timeout, XDebuggerTestUtil::waitFor);
}
public static List<XStackFrame> collectFrames(XExecutionStack thread, long timeout, BiFunction<Semaphore, Long, Boolean> waitFunction) {
return collectFramesWithError(thread, timeout, waitFunction).first;
}
public static Pair<List<XStackFrame>, String> collectFramesWithError(XExecutionStack thread, long timeout) {
return collectFramesWithError(thread, timeout, XDebuggerTestUtil::waitFor);
}
public static Pair<List<XStackFrame>, String> collectFramesWithError(XExecutionStack thread, long timeout, BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestStackFrameContainer container = new XTestStackFrameContainer();
thread.computeStackFrames(0, container);
return container.waitFor(timeout, waitFunction);
}
public static Pair<List<XStackFrame>, XStackFrame> collectFramesWithSelected(@NotNull XDebugSession session, long timeout) {
return collectFramesWithSelected(getActiveThread(session), timeout);
}
public static Pair<List<XStackFrame>, XStackFrame> collectFramesWithSelected(XExecutionStack thread, long timeout) {
return collectFramesWithSelected(thread, timeout, XDebuggerTestUtil::waitFor);
}
public static Pair<List<XStackFrame>, XStackFrame> collectFramesWithSelected(XExecutionStack thread, long timeout, BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestStackFrameContainer container = new XTestStackFrameContainer();
thread.computeStackFrames(0, container);
List<XStackFrame> all = container.waitFor(timeout, waitFunction).first;
return Pair.create(all, container.frameToSelect);
}
/**
* @deprecated use {@link XDebuggerTestUtil#collectChildren(XValueContainer)}
*/
@Deprecated
public static List<XValue> collectVariables(XStackFrame frame) {
return collectChildren(frame);
}
public static List<XValue> collectChildren(XValueContainer value) {
return collectChildren(value, XDebuggerTestUtil::waitFor);
}
public static List<XValue> collectChildren(XValueContainer value, BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestCompositeNode container = new XTestCompositeNode();
value.computeChildren(container);
return container.waitFor(TIMEOUT_MS, waitFunction).first;
}
public static Pair<XValue, String> evaluate(XDebugSession session, XExpression expression) {
return evaluate(session, expression, TIMEOUT_MS);
}
public static Pair<XValue, String> evaluate(XDebugSession session, XExpression expression, BiFunction<Semaphore, Long, Boolean> waitFunction) {
return evaluate(session, expression, TIMEOUT_MS, waitFunction);
}
public static Pair<XValue, String> evaluate(XDebugSession session, String expression) {
return evaluate(session, expression, XDebuggerTestUtil::waitFor);
}
public static Pair<XValue, String> evaluate(XDebugSession session, String expression, BiFunction<Semaphore, Long, Boolean> waitFunction) {
return evaluate(session, XExpressionImpl.fromText(expression), TIMEOUT_MS, waitFunction);
}
public static Pair<XValue, String> evaluate(XDebugSession session, String expression, long timeout) {
return evaluate(session, expression, timeout, XDebuggerTestUtil::waitFor);
}
public static Pair<XValue, String> evaluate(XDebugSession session, String expression, long timeout, BiFunction<Semaphore, Long, Boolean> waitFunction) {
return evaluate(session, XExpressionImpl.fromText(expression), timeout, waitFunction);
}
private static Pair<XValue, String> evaluate(XDebugSession session, XExpression expression, long timeout) {
return evaluate(session, expression, timeout, XDebuggerTestUtil::waitFor);
}
private static Pair<XValue, String> evaluate(XDebugSession session, XExpression expression, long timeout, BiFunction<Semaphore, Long, Boolean> waitFunction) {
XStackFrame frame = session.getCurrentStackFrame();
assertNotNull(frame);
XDebuggerEvaluator evaluator = frame.getEvaluator();
assertNotNull(evaluator);
XTestEvaluationCallback callback = new XTestEvaluationCallback();
evaluator.evaluate(expression, callback, session.getCurrentPosition());
return callback.waitFor(timeout, waitFunction);
}
public static void waitForSwing() throws InterruptedException {
final com.intellij.util.concurrency.Semaphore s = new com.intellij.util.concurrency.Semaphore();
s.down();
ApplicationManager.getApplication().invokeLater(() -> s.up());
s.waitForUnsafe();
UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {});
}
@NotNull
public static XValue findVar(Collection<XValue> vars, String name) {
StringBuilder names = new StringBuilder();
for (XValue each : vars) {
if (each instanceof XNamedValue) {
String eachName = ((XNamedValue)each).getName();
if (eachName.equals(name)) return each;
if (names.length() > 0) names.append(", ");
names.append(eachName);
}
}
throw new AssertionError("var '" + name + "' not found among " + names);
}
public static XTestValueNode computePresentation(@NotNull XValue value) {
return computePresentation(value, XDebuggerTestUtil::waitFor);
}
public static XTestValueNode computePresentation(@NotNull XValue value, BiFunction<Semaphore, Long, Boolean> waitFunction) {
return computePresentation(value, TIMEOUT_MS, waitFunction);
}
public static XTestValueNode computePresentation(XValue value, long timeout) {
return computePresentation(value, timeout, XDebuggerTestUtil::waitFor);
}
public static XTestValueNode computePresentation(XValue value, long timeout, BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestValueNode node = new XTestValueNode();
if (value instanceof XNamedValue) {
node.myName = ((XNamedValue)value).getName();
}
value.computePresentation(node, XValuePlace.TREE);
node.waitFor(timeout, waitFunction);
return node;
}
public static void assertVariable(XValue var,
@Nullable String name,
@Nullable String type,
@Nullable String value,
@Nullable Boolean hasChildren) {
assertVariable(var, name, type, value, hasChildren, XDebuggerTestUtil::waitFor);
}
public static void assertVariable(XValue var,
@Nullable String name,
@Nullable String type,
@Nullable String value,
@Nullable Boolean hasChildren,
BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestValueNode node = computePresentation(var, waitFunction);
if (name != null) assertEquals(name, node.myName);
if (type != null) assertEquals(type, node.myType);
if (value != null) assertEquals(value, node.myValue);
if (hasChildren != null) assertEquals(hasChildren, node.myHasChildren);
}
public static void assertVariableValue(XValue var, @Nullable String name, @Nullable String value) {
assertVariable(var, name, null, value, null);
}
public static void assertVariableValue(Collection<XValue> vars, @Nullable String name, @Nullable String value) {
assertVariableValue(findVar(vars, name), name, value);
}
public static void assertVariableValueMatches(@NotNull Collection<XValue> vars,
@Nullable String name,
@Nullable @Language("RegExp") String valuePattern) {
assertVariableValueMatches(findVar(vars, name), name, valuePattern);
}
public static void assertVariableValueMatches(@NotNull Collection<XValue> vars,
@Nullable String name,
@Nullable String type,
@Nullable @Language("RegExp") String valuePattern) {
assertVariableValueMatches(findVar(vars, name), name, type, valuePattern);
}
public static void assertVariableValueMatches(@NotNull Collection<XValue> vars,
@Nullable String name,
@Nullable String type,
@Nullable @Language("RegExp") String valuePattern,
@Nullable Boolean hasChildren) {
assertVariableValueMatches(findVar(vars, name), name, type, valuePattern, hasChildren);
}
public static void assertVariableValueMatches(@NotNull XValue var,
@Nullable String name,
@Nullable @Language("RegExp") String valuePattern) {
assertVariableValueMatches(var, name, null, valuePattern);
}
public static void assertVariableValueMatches(@NotNull XValue var,
@Nullable String name,
@Nullable String type,
@Nullable @Language("RegExp") String valuePattern) {
assertVariableValueMatches(var, name, type, valuePattern, null);
}
public static void assertVariableValueMatches(@NotNull XValue var,
@Nullable String name,
@Nullable String type,
@Nullable @Language("RegExp") String valuePattern,
@Nullable Boolean hasChildren) {
assertVariableValueMatches(var, name, type, valuePattern, hasChildren, XDebuggerTestUtil::waitFor);
}
public static void assertVariableValueMatches(@NotNull XValue var,
@Nullable String name,
@Nullable String type,
@Nullable @Language("RegExp") String valuePattern,
@Nullable Boolean hasChildren,
BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestValueNode node = computePresentation(var, waitFunction);
if (name != null) assertEquals(name, node.myName);
if (type != null) assertEquals(type, node.myType);
if (valuePattern != null) {
assertTrue("Expected value: " + valuePattern + " Actual value: " + node.myValue, node.myValue.matches(valuePattern));
}
if (hasChildren != null) assertEquals(hasChildren, node.myHasChildren);
}
public static void assertVariableTypeMatches(@NotNull Collection<XValue> vars,
@Nullable String name,
@Nullable @Language("RegExp") String typePattern) {
assertVariableTypeMatches(findVar(vars, name), name, typePattern);
}
public static void assertVariableTypeMatches(@NotNull XValue var,
@Nullable String name,
@Nullable @Language("RegExp") String typePattern) {
assertVariableTypeMatches(var, name, typePattern, XDebuggerTestUtil::waitFor);
}
public static void assertVariableTypeMatches(@NotNull XValue var,
@Nullable String name,
@Nullable @Language("RegExp") String typePattern,
@NotNull BiFunction<Semaphore, Long, Boolean> waitFunction) {
XTestValueNode node = computePresentation(var, waitFunction);
if (name != null) {
assertEquals(name, node.myName);
}
if (typePattern != null) {
assertTrue("Expected type: " + typePattern + " Actual type: " + node.myType, node.myType.matches(typePattern));
}
}
public static void assertVariableFullValue(@NotNull XValue var,
@Nullable String value) throws Exception {
assertVariableFullValue(var, value, XDebuggerTestUtil::waitFor);
}
public static void assertVariableFullValue(@NotNull XValue var,
@Nullable String value,
@NotNull BiFunction<Semaphore, Long, Boolean> waitFunction) throws Exception {
XTestValueNode node = computePresentation(var, waitFunction);
if (value == null) {
assertNull("full value evaluator should be null", node.myFullValueEvaluator);
}
else {
final FutureResult<String> result = new FutureResult<>();
node.myFullValueEvaluator.startEvaluation(new XFullValueEvaluator.XFullValueEvaluationCallback() {
@Override
public void evaluated(@NotNull String fullValue) {
result.set(fullValue);
}
@Override
public void evaluated(@NotNull String fullValue, @Nullable Font font) {
result.set(fullValue);
}
@Override
public void errorOccurred(@NotNull String errorMessage) {
result.set(errorMessage);
}
});
assertEquals(value, result.get(TIMEOUT_MS, TimeUnit.MILLISECONDS));
}
}
public static void assertVariableFullValue(Collection<XValue> vars, @Nullable String name, @Nullable String value)
throws Exception {
assertVariableFullValue(findVar(vars, name), value);
}
public static void assertVariables(List<XValue> vars, String... names) {
List<String> expectedNames = new ArrayList<>(Arrays.asList(names));
List<String> actualNames = new ArrayList<>();
for (XValue each : vars) {
actualNames.add(computePresentation(each).myName);
}
Collections.sort(actualNames);
Collections.sort(expectedNames);
UsefulTestCase.assertOrderedEquals(actualNames, expectedNames);
}
public static void assertVariablesContain(List<XValue> vars, String... names) {
List<String> expectedNames = new ArrayList<>(Arrays.asList(names));
List<String> actualNames = new ArrayList<>();
for (XValue each : vars) {
actualNames.add(computePresentation(each).myName);
}
expectedNames.removeAll(actualNames);
assertTrue("Missing variables:" + StringUtil.join(expectedNames, ", ")
+ "\nAll Variables: " + StringUtil.join(actualNames, ", "),
expectedNames.isEmpty()
);
}
public static void assertSourcePosition(final XValue value, VirtualFile file, int offset) {
final XTestNavigatable n = new XTestNavigatable();
ApplicationManager.getApplication().runReadAction(() -> value.computeSourcePosition(n));
assertNotNull(n.myPosition);
assertEquals(file, n.myPosition.getFile());
assertEquals(offset, n.myPosition.getOffset());
}
public static void assertSourcePosition(final XStackFrame frame, VirtualFile file, int line) {
XSourcePosition position = frame.getSourcePosition();
assertNotNull(position);
assertEquals(file, position.getFile());
assertEquals(line, position.getLine());
}
public static boolean waitFor(Semaphore semaphore, long timeoutInMillis) {
long end = System.currentTimeMillis() + timeoutInMillis;
long remaining = timeoutInMillis;
do {
try {
return semaphore.tryAcquire(remaining, TimeUnit.MILLISECONDS);
}
catch (InterruptedException ignored) {
remaining = end - System.currentTimeMillis();
}
} while (remaining > 0);
return false;
}
public static void assertVariable(Collection<XValue> vars,
@Nullable String name,
@Nullable String type,
@Nullable String value,
@Nullable Boolean hasChildren) {
assertVariable(findVar(vars, name), name, type, value, hasChildren);
}
@NotNull
public static String getConsoleText(final @NotNull ConsoleViewImpl consoleView) {
WriteAction.runAndWait(() -> consoleView.flushDeferredText());
return consoleView.getEditor().getDocument().getText();
}
public static <T extends XBreakpointType> XBreakpoint addBreakpoint(@NotNull final Project project,
@NotNull final Class<T> exceptionType,
@NotNull final XBreakpointProperties properties) {
XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
Ref<XBreakpoint> breakpoint = Ref.create(null);
XBreakpointUtil.breakpointTypes()
.select(exceptionType)
.findFirst()
.ifPresent(type -> WriteAction.runAndWait(() -> breakpoint.set(breakpointManager.addBreakpoint(type, properties))));
return breakpoint.get();
}
public static void removeAllBreakpoints(@NotNull final Project project) {
final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
XBreakpoint<?>[] breakpoints = getBreakpoints(breakpointManager);
for (final XBreakpoint b : breakpoints) {
WriteAction.runAndWait(() -> breakpointManager.removeBreakpoint(b));
}
}
public static XBreakpoint<?>[] getBreakpoints(final XBreakpointManager breakpointManager) {
return ReadAction.compute(breakpointManager::getAllBreakpoints);
}
public static <B extends XBreakpoint<?>>
void setDefaultBreakpointEnabled(@NotNull final Project project, Class<? extends XBreakpointType<B, ?>> bpTypeClass, boolean enabled) {
final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
XBreakpointType<B, ?> bpType = XDebuggerUtil.getInstance().findBreakpointType(bpTypeClass);
XBreakpoint<?> bp = breakpointManager.getDefaultBreakpoint(bpType);
if (bp != null) {
bp.setEnabled(enabled);
}
}
public static void setBreakpointCondition(Project project, int line, final String condition) {
XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
for (XBreakpoint breakpoint : getBreakpoints(breakpointManager)) {
if (breakpoint instanceof XLineBreakpoint) {
final XLineBreakpoint lineBreakpoint = (XLineBreakpoint)breakpoint;
if (lineBreakpoint.getLine() == line) {
WriteAction.runAndWait(() -> lineBreakpoint.setCondition(condition));
}
}
}
}
public static void setBreakpointLogExpression(Project project, int line, final String logExpression) {
XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
for (XBreakpoint breakpoint : getBreakpoints(breakpointManager)) {
if (breakpoint instanceof XLineBreakpoint) {
final XLineBreakpoint lineBreakpoint = (XLineBreakpoint)breakpoint;
if (lineBreakpoint.getLine() == line) {
WriteAction.runAndWait(() -> {
lineBreakpoint.setLogExpression(logExpression);
lineBreakpoint.setLogMessage(true);
});
}
}
}
}
public static void disposeDebugSession(final XDebugSession debugSession) {
WriteAction.runAndWait(() -> {
XDebugSessionImpl session = (XDebugSessionImpl)debugSession;
Disposer.dispose(session.getSessionTab());
Disposer.dispose(session.getConsoleView());
});
}
public static void assertVariable(Pair<XValue, String> varAndErrorMessage,
@Nullable String name,
@Nullable String type,
@Nullable String value,
@Nullable Boolean hasChildren) {
assertNull(varAndErrorMessage.second);
assertVariable(varAndErrorMessage.first, name, type, value, hasChildren);
}
public static String assertVariableExpression(XValue desc, String expectedExpression) {
String expression = desc.getEvaluationExpression();
assertEquals(expectedExpression, expression);
return expression;
}
public static class XTestExecutionStackContainer extends XTestContainer<XExecutionStack> implements XSuspendContext.XExecutionStackContainer {
@Override
public void errorOccurred(@NotNull String errorMessage) {
setErrorMessage(errorMessage);
}
@Override
public void addExecutionStack(@NotNull List<? extends XExecutionStack> executionStacks, boolean last) {
addChildren(executionStacks, last);
}
}
public static class XTestStackFrameContainer extends XTestContainer<XStackFrame> implements XStackFrameContainerEx {
public volatile XStackFrame frameToSelect;
@Override
public void addStackFrames(@NotNull List<? extends XStackFrame> stackFrames, boolean last) {
addChildren(stackFrames, last);
}
@Override
public void addStackFrames(@NotNull List<? extends XStackFrame> stackFrames, @Nullable XStackFrame toSelect, boolean last) {
if (toSelect != null) frameToSelect = toSelect;
addChildren(stackFrames, last);
}
@Override
public void errorOccurred(@NotNull String errorMessage) {
setErrorMessage(errorMessage);
}
}
public static class XTestNavigatable implements XNavigatable {
private XSourcePosition myPosition;
@Override
public void setSourcePosition(@Nullable XSourcePosition sourcePosition) {
myPosition = sourcePosition;
}
public XSourcePosition getPosition() {
return myPosition;
}
}
}
| CIDR: debugger: (testing) Fix NPE in assertVariableTypeMatches()
| platform/xdebugger-testFramework/src/com/intellij/xdebugger/XDebuggerTestUtil.java | CIDR: debugger: (testing) Fix NPE in assertVariableTypeMatches() |
|
Java | apache-2.0 | dc778cacc3fab4da30cb748b1e15b4d42134a1ad | 0 | rwl/requestfactory-addon | package org.springframework.roo.addon.dod;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.roo.addon.beaninfo.BeanInfoMetadata;
import org.springframework.roo.classpath.PhysicalTypeIdentifierNamingUtils;
import org.springframework.roo.classpath.PhysicalTypeMetadata;
import org.springframework.roo.classpath.details.DefaultFieldMetadata;
import org.springframework.roo.classpath.details.DefaultMethodMetadata;
import org.springframework.roo.classpath.details.FieldMetadata;
import org.springframework.roo.classpath.details.MemberFindingUtils;
import org.springframework.roo.classpath.details.MethodMetadata;
import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType;
import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadata;
import org.springframework.roo.classpath.details.annotations.DefaultAnnotationMetadata;
import org.springframework.roo.classpath.details.annotations.EnumAttributeValue;
import org.springframework.roo.classpath.itd.AbstractItdTypeDetailsProvidingMetadataItem;
import org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder;
import org.springframework.roo.metadata.MetadataDependencyRegistry;
import org.springframework.roo.metadata.MetadataIdentificationUtils;
import org.springframework.roo.metadata.MetadataService;
import org.springframework.roo.model.DataType;
import org.springframework.roo.model.EnumDetails;
import org.springframework.roo.model.JavaSymbolName;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.project.Path;
import org.springframework.roo.project.ProjectMetadata;
import org.springframework.roo.support.style.ToStringCreator;
import org.springframework.roo.support.util.Assert;
import org.springframework.roo.support.util.StringUtils;
/**
* Metadata for {@link RooDataOnDemand}.
*
* @author Ben Alex
* @author Stefan Schmidt
* @author Alan Stewart
* @since 1.0
*/
public class DataOnDemandMetadata extends AbstractItdTypeDetailsProvidingMetadataItem {
private static final String PROVIDES_TYPE_STRING = DataOnDemandMetadata.class.getName();
private static final String PROVIDES_TYPE = MetadataIdentificationUtils.create(PROVIDES_TYPE_STRING);
private static final JavaType MAX = new JavaType("javax.validation.constraints.Max");
private static final JavaType MIN = new JavaType("javax.validation.constraints.Min");
private static final JavaType SIZE = new JavaType("javax.validation.constraints.Size");
private static final JavaType COLUMN = new JavaType("javax.persistence.Column");
private static final JavaType NOT_NULL = new JavaType("javax.validation.constraints.NotNull");
private DataOnDemandAnnotationValues annotationValues;
private ProjectMetadata projectMetadata;
private BeanInfoMetadata beanInfoMetadata;
private MethodMetadata identifierAccessorMethod;
private MethodMetadata findMethod;
/** The "findEntityEntries(Integer,Integer):List<Entity>" static method for the entity (required) */
private MethodMetadata findEntriesMethod;
/** The "persist():void" instance method for the entity we are to create (required) */
private MethodMetadata persistMethod;
/** Mandatory methods, in order of discovery (so we can guarantee the ITD is generated in a consistent manner for SCM compatibility) */
private List<MethodMetadata> mandatoryMutators = new ArrayList<MethodMetadata>();
/** key: mandatory setter to invoke; value: the argument to present to the mutator method, expressed as a string */
private Map<MethodMetadata,String> mutatorArguments = new HashMap<MethodMetadata, String>();
/** Other entities requiring a data on demand instance; fields must exist for each of these in the class */
private List<JavaType> requiredDataOnDemandCollaborators = new ArrayList<JavaType>();
// Needed to lookup other DataOnDemand metadata we depend on
private MetadataService metadataService;
private MetadataDependencyRegistry metadataDependencyRegistry;
public DataOnDemandMetadata(String identifier, JavaType aspectName, PhysicalTypeMetadata governorPhysicalTypeMetadata, DataOnDemandAnnotationValues annotationValues, ProjectMetadata projectMetadata, BeanInfoMetadata beanInfoMetadata, MethodMetadata identifierAccessor, MethodMetadata findMethod, MethodMetadata findEntriesMethod, MethodMetadata persistMethod, MetadataService metadataService, MetadataDependencyRegistry metadataDependencyRegistry) {
super(identifier, aspectName, governorPhysicalTypeMetadata);
Assert.isTrue(isValid(identifier), "Metadata identification string '" + identifier + "' does not appear to be a valid");
Assert.notNull(annotationValues, "Annotation values required");
Assert.notNull(projectMetadata, "Project metadata required");
Assert.notNull(beanInfoMetadata, "Bean info metadata required");
Assert.notNull(identifierAccessor, "Identifier accessor method required");
Assert.notNull(findMethod, "Find method required");
Assert.notNull(findEntriesMethod, "Find entries method required");
Assert.notNull(persistMethod, "Persist method required");
Assert.notNull(metadataService, "Metadata service required");
Assert.notNull(metadataDependencyRegistry, "Metadata dependency registry required");
if (!isValid()) {
return;
}
this.annotationValues = annotationValues;
this.projectMetadata = projectMetadata;
this.beanInfoMetadata = beanInfoMetadata;
this.identifierAccessorMethod = identifierAccessor;
this.findMethod = findMethod;
this.findEntriesMethod = findEntriesMethod;
this.persistMethod = persistMethod;
this.metadataService = metadataService;
this.metadataDependencyRegistry = metadataDependencyRegistry;
mutatorDiscovery();
if (isComponentAnnotationIntroduced()) {
builder.addTypeAnnotation(getComponentAnnotation());
}
builder.addField(getRndField());
builder.addField(getDataField());
Set<JavaSymbolName> fieldsAddedToItd = new HashSet<JavaSymbolName>();
for (JavaType entityNeedingCollaborator : requiredDataOnDemandCollaborators) {
JavaType collaboratorType = getCollaboratingType(entityNeedingCollaborator);
String collaboratingFieldName = getCollaboratingFieldName(entityNeedingCollaborator).getSymbolName();
JavaSymbolName fieldSymbolName = new JavaSymbolName(collaboratingFieldName);
FieldMetadata candidate = MemberFindingUtils.getField(governorTypeDetails, fieldSymbolName);
if (candidate != null) {
// We really expect the field to be correct if we're going to rely on it
Assert.isTrue(candidate.getFieldType().equals(collaboratorType), "Field '" + collaboratingFieldName + "' on '" + governorTypeDetails.getName().getFullyQualifiedTypeName() + "' must be of type '" + collaboratorType.getFullyQualifiedTypeName() + "'");
Assert.isTrue(Modifier.isPrivate(candidate.getModifier()), "Field '" + collaboratingFieldName + "' on '" + governorTypeDetails.getName().getFullyQualifiedTypeName() + "' must be private");
Assert.notNull(MemberFindingUtils.getAnnotationOfType(candidate.getAnnotations(), new JavaType("org.springframework.beans.factory.annotation.Autowired")), "Field '" + collaboratingFieldName + "' on '" + governorTypeDetails.getName().getFullyQualifiedTypeName() + "' must be @Autowired");
// It's ok, so we can move onto the new field
continue;
}
// Must make the field
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
annotations.add(new DefaultAnnotationMetadata(new JavaType("org.springframework.beans.factory.annotation.Autowired"), new ArrayList<AnnotationAttributeValue<?>>()));
FieldMetadata field = new DefaultFieldMetadata(getId(), Modifier.PRIVATE, fieldSymbolName, collaboratorType, null, annotations);
// Add it to the ITD, if it hasn't already been
if (!fieldsAddedToItd.contains(field.getFieldName())) {
fieldsAddedToItd.add(field.getFieldName());
builder.addField(field);
fieldsAddedToItd.add(field.getFieldName());
}
}
builder.addMethod(getNewTransientEntityMethod());
builder.addMethod(getSpecificPersistentEntityMethod());
builder.addMethod(getRandomPersistentEntityMethod());
builder.addMethod(getModifyMethod());
builder.addMethod(getInitMethod());
itdTypeDetails = builder.build();
}
/**
* Adds the @org.springframework.stereotype.Component annotation to the type, unless
* it already exists.
*
* @return the annotation is already exists or will be created, or null if it will not be created (required)
*/
public AnnotationMetadata getComponentAnnotation() {
JavaType javaType = new JavaType("org.springframework.stereotype.Component");
if (isComponentAnnotationIntroduced()) {
return new DefaultAnnotationMetadata(javaType, new ArrayList<AnnotationAttributeValue<?>>());
}
return MemberFindingUtils.getDeclaredTypeAnnotation(governorTypeDetails, javaType);
}
/**
* Indicates whether the @org.springframework.stereotype.Component annotation will
* be introduced via this ITD.
*
* @return true if it will be introduced, false otherwise
*/
public boolean isComponentAnnotationIntroduced() {
JavaType javaType = new JavaType("org.springframework.stereotype.Component");
AnnotationMetadata result = MemberFindingUtils.getDeclaredTypeAnnotation(governorTypeDetails, javaType);
return result == null;
}
/**
* @return the "rnd" field to use, which is either provided by the user or produced on demand (never returns null)
*/
public FieldMetadata getRndField() {
int index = -1;
while (true) {
// Compute the required field name
index++;
String fieldName = "";
for (int i = 0; i < index; i++) {
fieldName = fieldName + "_";
}
fieldName = fieldName + "rnd";
JavaSymbolName fieldSymbolName = new JavaSymbolName(fieldName);
FieldMetadata candidate = MemberFindingUtils.getField(governorTypeDetails, fieldSymbolName);
if (candidate != null) {
// Verify if candidate is suitable
if (!Modifier.isPrivate(candidate.getModifier())) {
// Candidate is not private, so we might run into naming clashes if someone subclasses this (therefore go onto the next possible name)
continue;
}
if (!candidate.getFieldType().equals(new JavaType("java.util.Random"))) {
// Candidate isn't a java.util.Random, so it isn't suitable
continue;
}
// If we got this far, we found a valid candidate
// We don't check if there is a corresponding initializer, but we assume the user knows what they're doing and have made one
return candidate;
}
// Candidate not found, so let's create one
return new DefaultFieldMetadata(getId(), Modifier.PRIVATE, fieldSymbolName, new JavaType("java.util.Random"), "new java.security.SecureRandom()", null);
}
}
/**
* @return the "data" field to use, which is either provided by the user or produced on demand (never returns null)
*/
public FieldMetadata getDataField() {
int index = -1;
while (true) {
// Compute the required field name
index++;
String fieldName = "";
for (int i = 0; i < index; i++) {
fieldName = fieldName + "_";
}
fieldName = fieldName + "data";
// The type parameters to be used by the field type
List<JavaType> typeParams = new ArrayList<JavaType>();
typeParams.add(annotationValues.getEntity());
JavaSymbolName fieldSymbolName = new JavaSymbolName(fieldName);
FieldMetadata candidate = MemberFindingUtils.getField(governorTypeDetails, fieldSymbolName);
if (candidate != null) {
// Verify if candidate is suitable
if (!Modifier.isPrivate(candidate.getModifier())) {
// Candidate is not private, so we might run into naming clashes if someone subclasses this (therefore go onto the next possible name)
continue;
}
if (!candidate.getFieldType().equals(new JavaType("java.util.List", 0, DataType.TYPE, null, typeParams))) {
// Candidate isn't a java.util.List<theEntity>, so it isn't suitable
// The equals method also verifies type params are present
continue;
}
// If we got this far, we found a valid candidate
// We don't check if there is a corresponding initializer, but we assume the user knows what they're doing and have made one
return candidate;
}
// Candidate not found, so let's create one
return new DefaultFieldMetadata(getId(), Modifier.PRIVATE, fieldSymbolName, new JavaType("java.util.List", 0, DataType.TYPE, null, typeParams), null, null);
}
}
/**
* @return the "getNewTransientEntity(int index):Entity" method (never returns null)
*/
public MethodMetadata getNewTransientEntityMethod() {
// Method definition to find or build
JavaSymbolName methodName = new JavaSymbolName("getNewTransient" + beanInfoMetadata.getJavaBean().getSimpleTypeName());
List<JavaType> paramTypes = new ArrayList<JavaType>();
paramTypes.add(JavaType.INT_PRIMITIVE);
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("index"));
JavaType returnType = beanInfoMetadata.getJavaBean();
// Locate user-defined method
MethodMetadata userMethod = MemberFindingUtils.getMethod(governorTypeDetails, methodName, paramTypes);
if (userMethod != null) {
Assert.isTrue(userMethod.getReturnType().equals(returnType), "Method '" + methodName + "' on '" + governorTypeDetails.getName() + "' must return '" + returnType.getNameIncludingTypeParameters() + "'");
return userMethod;
}
// Create method
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine(beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + " obj = new " + beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + "();");
for (MethodMetadata mutator : mandatoryMutators) {
String initializer = mutatorArguments.get(mutator);
Assert.hasText(initializer, "Internal error: unable to locate initializer for " + mutator);
JavaSymbolName propertyName = BeanInfoMetadata.getPropertyNameForJavaBeanMethod(mutator);
FieldMetadata field = beanInfoMetadata.getFieldForPropertyName(propertyName);
if (field.getFieldType().equals(new JavaType(String.class.getName())) && MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), NOT_NULL) != null) {
// Check for @Size or @Column with length attribute
AnnotationMetadata sizeAnnotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE);
AnnotationMetadata columnAnnotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), COLUMN);
if (sizeAnnotationMetadata != null && sizeAnnotationMetadata.getAttribute(new JavaSymbolName("max")) != null) {
Integer maxValue = (Integer) sizeAnnotationMetadata.getAttribute(new JavaSymbolName("max")).getValue();
bodyBuilder.appendFormalLine(field.getFieldType().getFullyQualifiedTypeName() + " " + field.getFieldName().getSymbolName() + " = " + initializer + ";");
bodyBuilder.appendFormalLine("if (" + field.getFieldName().getSymbolName() + ".length() > " + maxValue + ") {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine(field.getFieldName().getSymbolName() + " = " + field.getFieldName().getSymbolName() + ".substring(0, " + maxValue + ");");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + field.getFieldName().getSymbolName() + ");");
} else if (sizeAnnotationMetadata == null && columnAnnotationMetadata != null) {
AnnotationAttributeValue<?> lengthAttributeValue = columnAnnotationMetadata.getAttribute(new JavaSymbolName("length"));
if (lengthAttributeValue != null) {
Integer lengthValue = (Integer) columnAnnotationMetadata.getAttribute(new JavaSymbolName("length")).getValue();
bodyBuilder.appendFormalLine(field.getFieldType().getFullyQualifiedTypeName() + " " + field.getFieldName().getSymbolName() + " = " + initializer + ";");
bodyBuilder.appendFormalLine("if (" + field.getFieldName().getSymbolName() + ".length() > " + lengthValue + ") {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine(field.getFieldName().getSymbolName() + " = " + field.getFieldName().getSymbolName() + ".substring(0, " + lengthValue + ");");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + field.getFieldName().getSymbolName() + ");");
} else {
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + initializer + ");");
}
} else {
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + initializer + ");");
}
} else if (isNumericFieldType(field)) {
// Check for @Min and @Max
AnnotationMetadata minAnnotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MIN);
AnnotationMetadata maxAnnotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MAX);
String suffix = "";
if (field.getFieldType().equals(JavaType.LONG_OBJECT) || field.getFieldType().equals(JavaType.LONG_PRIMITIVE)) {
suffix = "L";
} else if (field.getFieldType().equals(JavaType.FLOAT_OBJECT) || field.getFieldType().equals(JavaType.FLOAT_PRIMITIVE)) {
suffix = "F";
} else if (field.getFieldType().equals(JavaType.DOUBLE_OBJECT) || field.getFieldType().equals(JavaType.DOUBLE_PRIMITIVE)) {
suffix = "D";
}
if (minAnnotationMetadata != null && maxAnnotationMetadata == null) {
Long minValue = (Long) minAnnotationMetadata.getAttribute(new JavaSymbolName("value")).getValue();
bodyBuilder.appendFormalLine(field.getFieldType().getFullyQualifiedTypeName() + " " + field.getFieldName().getSymbolName() + " = " + initializer + ";");
bodyBuilder.appendFormalLine("if (" + field.getFieldName().getSymbolName() + " < " + minValue + ") {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine(field.getFieldName().getSymbolName() + " = " + minValue + suffix + ";");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + field.getFieldName().getSymbolName() + ");");
} else if (minAnnotationMetadata == null && maxAnnotationMetadata != null) {
Long maxValue = (Long) maxAnnotationMetadata.getAttribute(new JavaSymbolName("value")).getValue();
bodyBuilder.appendFormalLine(field.getFieldType().getFullyQualifiedTypeName() + " " + field.getFieldName().getSymbolName() + " = " + initializer + ";");
bodyBuilder.appendFormalLine("if (" + field.getFieldName().getSymbolName() + " > " + maxValue + ") {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine(field.getFieldName().getSymbolName() + " = " + maxValue + suffix + ";");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + field.getFieldName().getSymbolName() + ");");
} else if (minAnnotationMetadata != null && maxAnnotationMetadata != null) {
Long minValue = (Long) minAnnotationMetadata.getAttribute(new JavaSymbolName("value")).getValue();
Long maxValue = (Long) maxAnnotationMetadata.getAttribute(new JavaSymbolName("value")).getValue();
Assert.isTrue(maxValue >= minValue, "The value of @Max must be greater or equal to the value of @Min for field " + field.getFieldName().getSymbolName() );
bodyBuilder.appendFormalLine(field.getFieldType().getFullyQualifiedTypeName() + " " + field.getFieldName().getSymbolName() + " = " + initializer + ";");
bodyBuilder.appendFormalLine("if (" + field.getFieldName().getSymbolName() + " < " + minValue + suffix + " || " + field.getFieldName().getSymbolName() + " > " + suffix + maxValue + ") {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine(field.getFieldName().getSymbolName() + " = " + maxValue + suffix + ";");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + field.getFieldName().getSymbolName() + ");");
} else {
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + initializer + ");");
}
} else {
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + initializer + ");");
}
}
bodyBuilder.appendFormalLine("return obj;");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, returnType, AnnotatedJavaType.convertFromJavaTypes(paramTypes), paramNames, new ArrayList<AnnotationMetadata>(), new ArrayList<JavaType>(), bodyBuilder.getOutput());
}
private boolean isNumericFieldType(FieldMetadata field) {
return field.getFieldType().equals(JavaType.INT_OBJECT) || field.getFieldType().equals(JavaType.INT_PRIMITIVE) ||
field.getFieldType().equals(JavaType.DOUBLE_OBJECT) || field.getFieldType().equals(JavaType.DOUBLE_PRIMITIVE) ||
field.getFieldType().equals(JavaType.FLOAT_OBJECT) || field.getFieldType().equals(JavaType.FLOAT_PRIMITIVE) ||
field.getFieldType().equals(JavaType.LONG_OBJECT) || field.getFieldType().equals(JavaType.LONG_PRIMITIVE) ||
field.getFieldType().equals(JavaType.SHORT_OBJECT) || field.getFieldType().equals(JavaType.SHORT_PRIMITIVE);
}
/**
* @return the "modifyEntity(Entity):boolean" method (never returns null)
*/
public MethodMetadata getModifyMethod() {
// Method definition to find or build
JavaSymbolName methodName = new JavaSymbolName("modify" + beanInfoMetadata.getJavaBean().getSimpleTypeName());
List<JavaType> paramTypes = new ArrayList<JavaType>();
paramTypes.add(beanInfoMetadata.getJavaBean());
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("obj"));
JavaType returnType = JavaType.BOOLEAN_PRIMITIVE;
// Locate user-defined method
MethodMetadata userMethod = MemberFindingUtils.getMethod(governorTypeDetails, methodName, paramTypes);
if (userMethod != null) {
Assert.isTrue(userMethod.getReturnType().equals(returnType), "Method '" + methodName + "' on '" + governorTypeDetails.getName() + "' must return '" + returnType.getNameIncludingTypeParameters() + "'");
return userMethod;
}
// Create method
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
// TODO: We should port this more fully from original code base
bodyBuilder.appendFormalLine("return false;");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, returnType, AnnotatedJavaType.convertFromJavaTypes(paramTypes), paramNames, new ArrayList<AnnotationMetadata>(), new ArrayList<JavaType>(), bodyBuilder.getOutput());
}
/**
* @return the "getRandomEntity():Entity" method (never returns null)
*/
public MethodMetadata getRandomPersistentEntityMethod() {
// Method definition to find or build
JavaSymbolName methodName = new JavaSymbolName("getRandom" + beanInfoMetadata.getJavaBean().getSimpleTypeName());
List<JavaType> paramTypes = new ArrayList<JavaType>();
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
JavaType returnType = beanInfoMetadata.getJavaBean();
// Locate user-defined method
MethodMetadata userMethod = MemberFindingUtils.getMethod(governorTypeDetails, methodName, paramTypes);
if (userMethod != null) {
Assert.isTrue(userMethod.getReturnType().equals(returnType), "Method '" + methodName + "' on '" + governorTypeDetails.getName() + "' must return '" + returnType.getNameIncludingTypeParameters() + "'");
return userMethod;
}
// Create method
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("init();");
bodyBuilder.appendFormalLine(beanInfoMetadata.getJavaBean().getSimpleTypeName() + " obj = " + getDataField().getFieldName().getSymbolName() +".get(" + getRndField().getFieldName().getSymbolName() + ".nextInt(" + getDataField().getFieldName().getSymbolName() + ".size()));");
bodyBuilder.appendFormalLine("return " + beanInfoMetadata.getJavaBean().getSimpleTypeName() + "." + findMethod.getMethodName().getSymbolName() + "(obj." + identifierAccessorMethod.getMethodName().getSymbolName() + "());");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, returnType, AnnotatedJavaType.convertFromJavaTypes(paramTypes), paramNames, new ArrayList<AnnotationMetadata>(), new ArrayList<JavaType>(), bodyBuilder.getOutput());
}
/**
* @return the "getSpecificEntity(int):Entity" method (never returns null)
*/
public MethodMetadata getSpecificPersistentEntityMethod() {
// Method definition to find or build
JavaSymbolName methodName = new JavaSymbolName("getSpecific" + beanInfoMetadata.getJavaBean().getSimpleTypeName());
List<JavaType> paramTypes = new ArrayList<JavaType>();
paramTypes.add(JavaType.INT_PRIMITIVE);
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("index"));
JavaType returnType = beanInfoMetadata.getJavaBean();
// Locate user-defined method
MethodMetadata userMethod = MemberFindingUtils.getMethod(governorTypeDetails, methodName, paramTypes);
if (userMethod != null) {
Assert.isTrue(userMethod.getReturnType().equals(returnType), "Method '" + methodName + "' on '" + governorTypeDetails.getName() + "' must return '" + returnType.getNameIncludingTypeParameters() + "'");
return userMethod;
}
// Create method
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("init();");
bodyBuilder.appendFormalLine("if (index < 0) index = 0;");
bodyBuilder.appendFormalLine("if (index > (" + getDataField().getFieldName().getSymbolName() + ".size() - 1)) index = " + getDataField().getFieldName().getSymbolName() + ".size() - 1;");
bodyBuilder.appendFormalLine(beanInfoMetadata.getJavaBean().getSimpleTypeName() + " obj = " + getDataField().getFieldName().getSymbolName() +".get(index);");
bodyBuilder.appendFormalLine("return " + beanInfoMetadata.getJavaBean().getSimpleTypeName() + "." + findMethod.getMethodName().getSymbolName() + "(obj." + identifierAccessorMethod.getMethodName().getSymbolName() + "());");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, returnType, AnnotatedJavaType.convertFromJavaTypes(paramTypes), paramNames, new ArrayList<AnnotationMetadata>(), new ArrayList<JavaType>(), bodyBuilder.getOutput());
}
/**
* @return the "init():void" method (never returns null)
*/
public MethodMetadata getInitMethod() {
// Method definition to find or build
JavaSymbolName methodName = new JavaSymbolName("init");
List<JavaType> paramTypes = new ArrayList<JavaType>();
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
JavaType returnType = JavaType.VOID_PRIMITIVE;
// Locate user-defined method
MethodMetadata userMethod = MemberFindingUtils.getMethod(governorTypeDetails, methodName, paramTypes);
if (userMethod != null) {
Assert.isTrue(userMethod.getReturnType().equals(returnType), "Method '" + methodName + "' on '" + governorTypeDetails.getName() + "' must return '" + returnType.getNameIncludingTypeParameters() + "'");
return userMethod;
}
// Create the method
// Create the annotations
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
if (!projectMetadata.isGaeEnabled()) {
List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new EnumAttributeValue(new JavaSymbolName("propagation"), new EnumDetails(new JavaType("org.springframework.transaction.annotation.Propagation"), new JavaSymbolName("REQUIRES_NEW"))));
annotations.add(new DefaultAnnotationMetadata(new JavaType("org.springframework.transaction.annotation.Transactional"), attributes));
}
// Create the body
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
String dataField = getDataField().getFieldName().getSymbolName();
bodyBuilder.appendFormalLine("if (" + dataField + " != null && !" + dataField + ".isEmpty()) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("return;");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("");
bodyBuilder.appendFormalLine(dataField + " = " + beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + "." + findEntriesMethod.getMethodName().getSymbolName() + "(0, " + annotationValues.getQuantity() + ");");
bodyBuilder.appendFormalLine("if (data == null) throw new IllegalStateException(\"Find entries implementation for '" + beanInfoMetadata.getJavaBean().getSimpleTypeName() + "' illegally returned null\");");
bodyBuilder.appendFormalLine("if (!" + dataField + ".isEmpty()) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("return;");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("");
bodyBuilder.appendFormalLine(dataField + " = new java.util.ArrayList<" + getDataField().getFieldType().getParameters().get(0).getNameIncludingTypeParameters() + ">();");
bodyBuilder.appendFormalLine("for (int i = 0; i < " + annotationValues.getQuantity() + "; i++) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine(beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + " obj = " + getNewTransientEntityMethod().getMethodName() + "(i);");
bodyBuilder.appendFormalLine("obj." + persistMethod.getMethodName().getSymbolName() + "();");
bodyBuilder.appendFormalLine(dataField + ".add(obj);");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, returnType, AnnotatedJavaType.convertFromJavaTypes(paramTypes), paramNames, annotations, new ArrayList<JavaType>(), bodyBuilder.getOutput());
}
private void mutatorDiscovery() {
for (MethodMetadata mutatorMethod : beanInfoMetadata.getPublicMutators()) {
JavaSymbolName propertyName = BeanInfoMetadata.getPropertyNameForJavaBeanMethod(mutatorMethod);
FieldMetadata field = beanInfoMetadata.getFieldForPropertyName(propertyName);
if (field == null) {
// There is no field for this mutator, so chances are it's not mandatory
continue;
}
// Never include id or version fields (they shouldn't normally have a mutator anyway, but the user might have added one)
if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.Id")) != null || MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.Version")) != null) {
continue;
}
// Never include field annotated with @javax.persistence.Transient
if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.Transient")) != null) {
continue;
}
// Never include any sort of collection; user has to make such entities by hand
if (field.getFieldType().isCommonCollectionType() || MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.OneToMany")) != null) {
continue;
}
// Check for @ManyToOne annotation with 'optional = false' attribute (ROO-1075)
boolean hasManyToOne = false;
AnnotationMetadata manyToOneAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.ManyToOne"));
if (manyToOneAnnotation != null) {
AnnotationAttributeValue<?> optionalAttribute = manyToOneAnnotation.getAttribute(new JavaSymbolName("optional"));
hasManyToOne = optionalAttribute != null && !((Boolean) optionalAttribute.getValue());
}
AnnotationMetadata oneToOneAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.OneToOne"));
String initializer = "null";
// Date fields included for DataNucleus (
if (field.getFieldType().equals(new JavaType(Date.class.getName()))) {
if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.Past")) != null) {
initializer = "new java.util.Date(new java.util.Date().getTime() - 10000000L)";
} else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.Future")) != null) {
initializer = "new java.util.Date(new java.util.Date().getTime() + 10000000L)";
} else {
initializer = "new java.util.Date()";
}
} else if (field.getFieldType().equals(JavaType.BOOLEAN_PRIMITIVE) && MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), NOT_NULL) == null ) {
initializer = "true";
} else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), NOT_NULL) != null || MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE) != null || MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MIN) != null || MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MAX) != null || hasManyToOne || field.getAnnotations().size() == 0) {
// Only include the field if it's really required (ie marked with JSR 303 NotNull) or it has no annotations and is therefore probably simple to invoke
if (field.getFieldType().equals(JavaType.STRING_OBJECT)) {
initializer = field.getFieldName().getSymbolName();
// Check for @Size
AnnotationMetadata sizeAnnotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE);
if (sizeAnnotationMetadata != null) {
AnnotationAttributeValue<?> maxValue = sizeAnnotationMetadata.getAttribute(new JavaSymbolName("max"));
if (maxValue != null && (Integer) maxValue.getValue() > 1 && (initializer.length() + 2) > (Integer) maxValue.getValue()) {
initializer = initializer.substring(0, (Integer) maxValue.getValue() - 2);
}
AnnotationAttributeValue<?> minValue = sizeAnnotationMetadata.getAttribute(new JavaSymbolName("min"));
if (minValue != null && (initializer.length() + 2) < (Integer) minValue.getValue()) {
initializer = String.format("%1$-" + ((Integer) minValue.getValue() - 2) + "s", initializer).replace(' ', 'x');
}
}
// Check for @Column
AnnotationMetadata columnAnnotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), COLUMN);
if (columnAnnotationMetadata != null) {
AnnotationAttributeValue<?> lengthValue = columnAnnotationMetadata.getAttribute(new JavaSymbolName("length"));
if (lengthValue != null && (initializer.length() + 2) > (Integer) lengthValue.getValue()) {
initializer = initializer.substring(0, (Integer) lengthValue.getValue() - 2);
}
}
initializer = "\"" + initializer + "_\" + index";
} else if (field.getFieldType().equals(new JavaType(Calendar.class.getName()))) {
if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.Past")) != null) {
initializer = "new java.util.GregorianCalendar(java.util.Calendar.getInstance().get(java.util.Calendar.YEAR), java.util.Calendar.getInstance().get(java.util.Calendar.MONTH), java.util.Calendar.getInstance().get(java.util.Calendar.DAY_OF_MONTH) - 1)";
} else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.Future")) != null) {
initializer = "new java.util.GregorianCalendar(java.util.Calendar.getInstance().get(java.util.Calendar.YEAR), java.util.Calendar.getInstance().get(java.util.Calendar.MONTH), java.util.Calendar.getInstance().get(java.util.Calendar.DAY_OF_MONTH) + 1)";
} else {
initializer = "java.util.Calendar.getInstance()";
}
} else if (field.getFieldType().equals(JavaType.BOOLEAN_OBJECT)) {
initializer = "new Boolean(true)";
} else if (field.getFieldType().equals(JavaType.BOOLEAN_PRIMITIVE)) {
initializer = "true";
} else if (field.getFieldType().equals(JavaType.INT_OBJECT)) {
initializer = "new Integer(index)";
} else if (field.getFieldType().equals(JavaType.INT_PRIMITIVE)) {
initializer = "new Integer(index)"; // Auto-boxed
} else if (field.getFieldType().equals(JavaType.DOUBLE_OBJECT)) {
initializer = "new Integer(index).doubleValue()"; // Auto-boxed
} else if (field.getFieldType().equals(JavaType.DOUBLE_PRIMITIVE)) {
initializer = "new Integer(index).doubleValue()";
} else if (field.getFieldType().equals(JavaType.FLOAT_OBJECT)) {
initializer = "new Integer(index).floatValue()"; // Auto-boxed
} else if (field.getFieldType().equals(JavaType.FLOAT_PRIMITIVE)) {
initializer = "new Integer(index).floatValue()";
} else if (field.getFieldType().equals(JavaType.LONG_OBJECT)) {
initializer = "new Integer(index).longValue()"; // Auto-boxed
} else if (field.getFieldType().equals(JavaType.LONG_PRIMITIVE)) {
initializer = "new Integer(index).longValue()";
} else if (field.getFieldType().equals(JavaType.SHORT_OBJECT)) {
initializer = "new Integer(index).shortValue()"; // Auto-boxed
} else if (field.getFieldType().equals(JavaType.SHORT_PRIMITIVE)) {
initializer = "new Integer(index).shortValue()";
} else if (field.getFieldType().equals(new JavaType("java.math.BigDecimal"))) {
initializer = "new java.math.BigDecimal(index)";
} else if (field.getFieldType().equals(new JavaType("java.math.BigInteger"))) {
initializer = "java.math.BigInteger.valueOf(index)";
} else if (manyToOneAnnotation != null || oneToOneAnnotation != null) {
if (field.getFieldType().equals(this.getAnnotationValues().getEntity())) {
// Avoid circular references (ROO-562)
initializer = "obj";
} else {
requiredDataOnDemandCollaborators.add(field.getFieldType());
String collaboratingFieldName = getCollaboratingFieldName(field.getFieldType()).getSymbolName();
// Look up the metadata we are relying on
String otherProvider = DataOnDemandMetadata.createIdentifier(new JavaType(field.getFieldType() + "DataOnDemand"), Path.SRC_TEST_JAVA);
// Decide if we're dealing with a one-to-one and therefore should _try_ to keep the same id (ROO-568)
boolean oneToOne = oneToOneAnnotation != null;
metadataDependencyRegistry.registerDependency(otherProvider, getId());
DataOnDemandMetadata otherMd = (DataOnDemandMetadata) metadataService.get(otherProvider);
if (otherMd == null || !otherMd.isValid()) {
// There is no metadata around, so we'll just make some basic assumptions
if (oneToOne) {
initializer = collaboratingFieldName + ".getSpecific" + field.getFieldType().getSimpleTypeName() + "(index)";
} else {
initializer = collaboratingFieldName + ".getRandom" + field.getFieldType().getSimpleTypeName() + "()";
}
} else {
// We can use the correct name
if (oneToOne) {
initializer = collaboratingFieldName + "." + otherMd.getSpecificPersistentEntityMethod().getMethodName().getSymbolName() + "(index)";
} else {
initializer = collaboratingFieldName + "." + otherMd.getRandomPersistentEntityMethod().getMethodName().getSymbolName() + "()";
}
}
}
} else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.Enumerated")) != null) {
initializer = field.getFieldType().getFullyQualifiedTypeName() + ".class.getEnumConstants()[0]";
}
}
mandatoryMutators.add(mutatorMethod);
mutatorArguments.put(mutatorMethod, initializer);
}
}
private JavaSymbolName getCollaboratingFieldName(JavaType entity) {
return new JavaSymbolName(StringUtils.uncapitalize(getCollaboratingType(entity).getSimpleTypeName()));
}
private JavaType getCollaboratingType(JavaType entity) {
return new JavaType(entity.getFullyQualifiedTypeName() + "DataOnDemand");
}
/**
* @return the physical type identifier for the {@link BeanInfoMetadata} (never null or empty unless metadata is invalid)
*/
public String getIdentifierForBeanInfoMetadata() {
return beanInfoMetadata.getId();
}
/**
* @return the annotation values specified via {@link RooDataOnDemand} (never null unless the metadata itself is invalid)
*/
public DataOnDemandAnnotationValues getAnnotationValues() {
return annotationValues;
}
public String toString() {
ToStringCreator tsc = new ToStringCreator(this);
tsc.append("identifier", getId());
tsc.append("valid", valid);
tsc.append("aspectName", aspectName);
tsc.append("destinationType", destination);
tsc.append("governor", governorPhysicalTypeMetadata.getId());
tsc.append("itdTypeDetails", itdTypeDetails);
return tsc.toString();
}
public static final String getMetadataIdentiferType() {
return PROVIDES_TYPE;
}
public static final String createIdentifier(JavaType javaType, Path path) {
return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path);
}
public static final JavaType getJavaType(String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING, metadataIdentificationString);
}
public static final Path getPath(String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString);
}
public static boolean isValid(String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING, metadataIdentificationString);
}
}
| addon-dod/src/main/java/org/springframework/roo/addon/dod/DataOnDemandMetadata.java | package org.springframework.roo.addon.dod;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.roo.addon.beaninfo.BeanInfoMetadata;
import org.springframework.roo.classpath.PhysicalTypeIdentifierNamingUtils;
import org.springframework.roo.classpath.PhysicalTypeMetadata;
import org.springframework.roo.classpath.details.DefaultFieldMetadata;
import org.springframework.roo.classpath.details.DefaultMethodMetadata;
import org.springframework.roo.classpath.details.FieldMetadata;
import org.springframework.roo.classpath.details.MemberFindingUtils;
import org.springframework.roo.classpath.details.MethodMetadata;
import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType;
import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadata;
import org.springframework.roo.classpath.details.annotations.DefaultAnnotationMetadata;
import org.springframework.roo.classpath.details.annotations.EnumAttributeValue;
import org.springframework.roo.classpath.itd.AbstractItdTypeDetailsProvidingMetadataItem;
import org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder;
import org.springframework.roo.metadata.MetadataDependencyRegistry;
import org.springframework.roo.metadata.MetadataIdentificationUtils;
import org.springframework.roo.metadata.MetadataService;
import org.springframework.roo.model.DataType;
import org.springframework.roo.model.EnumDetails;
import org.springframework.roo.model.JavaSymbolName;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.project.Path;
import org.springframework.roo.project.ProjectMetadata;
import org.springframework.roo.support.style.ToStringCreator;
import org.springframework.roo.support.util.Assert;
import org.springframework.roo.support.util.StringUtils;
/**
* Metadata for {@link RooDataOnDemand}.
*
* @author Ben Alex
* @author Stefan Schmidt
* @author Alan Stewart
* @since 1.0
*/
public class DataOnDemandMetadata extends AbstractItdTypeDetailsProvidingMetadataItem {
private static final String PROVIDES_TYPE_STRING = DataOnDemandMetadata.class.getName();
private static final String PROVIDES_TYPE = MetadataIdentificationUtils.create(PROVIDES_TYPE_STRING);
private static final JavaType MAX = new JavaType("javax.validation.constraints.Max");
private static final JavaType MIN = new JavaType("javax.validation.constraints.Min");
private static final JavaType SIZE = new JavaType("javax.validation.constraints.Size");
private static final JavaType COLUMN = new JavaType("javax.persistence.Column");
private static final JavaType NOT_NULL = new JavaType("javax.validation.constraints.NotNull");
private DataOnDemandAnnotationValues annotationValues;
private ProjectMetadata projectMetadata;
private BeanInfoMetadata beanInfoMetadata;
private MethodMetadata identifierAccessorMethod;
private MethodMetadata findMethod;
/** The "findEntityEntries(Integer,Integer):List<Entity>" static method for the entity (required) */
private MethodMetadata findEntriesMethod;
/** The "persist():void" instance method for the entity we are to create (required) */
private MethodMetadata persistMethod;
/** Mandatory methods, in order of discovery (so we can guarantee the ITD is generated in a consistent manner for SCM compatibility) */
private List<MethodMetadata> mandatoryMutators = new ArrayList<MethodMetadata>();
/** key: mandatory setter to invoke; value: the argument to present to the mutator method, expressed as a string */
private Map<MethodMetadata,String> mutatorArguments = new HashMap<MethodMetadata, String>();
/** Other entities requiring a data on demand instance; fields must exist for each of these in the class */
private List<JavaType> requiredDataOnDemandCollaborators = new ArrayList<JavaType>();
// Needed to lookup other DataOnDemand metadata we depend on
private MetadataService metadataService;
private MetadataDependencyRegistry metadataDependencyRegistry;
public DataOnDemandMetadata(String identifier, JavaType aspectName, PhysicalTypeMetadata governorPhysicalTypeMetadata, DataOnDemandAnnotationValues annotationValues, ProjectMetadata projectMetadata, BeanInfoMetadata beanInfoMetadata, MethodMetadata identifierAccessor, MethodMetadata findMethod, MethodMetadata findEntriesMethod, MethodMetadata persistMethod, MetadataService metadataService, MetadataDependencyRegistry metadataDependencyRegistry) {
super(identifier, aspectName, governorPhysicalTypeMetadata);
Assert.isTrue(isValid(identifier), "Metadata identification string '" + identifier + "' does not appear to be a valid");
Assert.notNull(annotationValues, "Annotation values required");
Assert.notNull(projectMetadata, "Project metadata required");
Assert.notNull(beanInfoMetadata, "Bean info metadata required");
Assert.notNull(identifierAccessor, "Identifier accessor method required");
Assert.notNull(findMethod, "Find method required");
Assert.notNull(findEntriesMethod, "Find entries method required");
Assert.notNull(persistMethod, "Persist method required");
Assert.notNull(metadataService, "Metadata service required");
Assert.notNull(metadataDependencyRegistry, "Metadata dependency registry required");
if (!isValid()) {
return;
}
this.annotationValues = annotationValues;
this.projectMetadata = projectMetadata;
this.beanInfoMetadata = beanInfoMetadata;
this.identifierAccessorMethod = identifierAccessor;
this.findMethod = findMethod;
this.findEntriesMethod = findEntriesMethod;
this.persistMethod = persistMethod;
this.metadataService = metadataService;
this.metadataDependencyRegistry = metadataDependencyRegistry;
mutatorDiscovery();
if (isComponentAnnotationIntroduced()) {
builder.addTypeAnnotation(getComponentAnnotation());
}
builder.addField(getRndField());
builder.addField(getDataField());
Set<JavaSymbolName> fieldsAddedToItd = new HashSet<JavaSymbolName>();
for (JavaType entityNeedingCollaborator : requiredDataOnDemandCollaborators) {
JavaType collaboratorType = getCollaboratingType(entityNeedingCollaborator);
String collaboratingFieldName = getCollaboratingFieldName(entityNeedingCollaborator).getSymbolName();
JavaSymbolName fieldSymbolName = new JavaSymbolName(collaboratingFieldName);
FieldMetadata candidate = MemberFindingUtils.getField(governorTypeDetails, fieldSymbolName);
if (candidate != null) {
// We really expect the field to be correct if we're going to rely on it
Assert.isTrue(candidate.getFieldType().equals(collaboratorType), "Field '" + collaboratingFieldName + "' on '" + governorTypeDetails.getName().getFullyQualifiedTypeName() + "' must be of type '" + collaboratorType.getFullyQualifiedTypeName() + "'");
Assert.isTrue(Modifier.isPrivate(candidate.getModifier()), "Field '" + collaboratingFieldName + "' on '" + governorTypeDetails.getName().getFullyQualifiedTypeName() + "' must be private");
Assert.notNull(MemberFindingUtils.getAnnotationOfType(candidate.getAnnotations(), new JavaType("org.springframework.beans.factory.annotation.Autowired")), "Field '" + collaboratingFieldName + "' on '" + governorTypeDetails.getName().getFullyQualifiedTypeName() + "' must be @Autowired");
// It's ok, so we can move onto the new field
continue;
}
// Must make the field
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
annotations.add(new DefaultAnnotationMetadata(new JavaType("org.springframework.beans.factory.annotation.Autowired"), new ArrayList<AnnotationAttributeValue<?>>()));
FieldMetadata field = new DefaultFieldMetadata(getId(), Modifier.PRIVATE, fieldSymbolName, collaboratorType, null, annotations);
// Add it to the ITD, if it hasn't already been
if (!fieldsAddedToItd.contains(field.getFieldName())) {
fieldsAddedToItd.add(field.getFieldName());
builder.addField(field);
fieldsAddedToItd.add(field.getFieldName());
}
}
builder.addMethod(getNewTransientEntityMethod());
builder.addMethod(getSpecificPersistentEntityMethod());
builder.addMethod(getRandomPersistentEntityMethod());
builder.addMethod(getModifyMethod());
builder.addMethod(getInitMethod());
itdTypeDetails = builder.build();
}
/**
* Adds the @org.springframework.stereotype.Component annotation to the type, unless
* it already exists.
*
* @return the annotation is already exists or will be created, or null if it will not be created (required)
*/
public AnnotationMetadata getComponentAnnotation() {
JavaType javaType = new JavaType("org.springframework.stereotype.Component");
if (isComponentAnnotationIntroduced()) {
return new DefaultAnnotationMetadata(javaType, new ArrayList<AnnotationAttributeValue<?>>());
}
return MemberFindingUtils.getDeclaredTypeAnnotation(governorTypeDetails, javaType);
}
/**
* Indicates whether the @org.springframework.stereotype.Component annotation will
* be introduced via this ITD.
*
* @return true if it will be introduced, false otherwise
*/
public boolean isComponentAnnotationIntroduced() {
JavaType javaType = new JavaType("org.springframework.stereotype.Component");
AnnotationMetadata result = MemberFindingUtils.getDeclaredTypeAnnotation(governorTypeDetails, javaType);
return result == null;
}
/**
* @return the "rnd" field to use, which is either provided by the user or produced on demand (never returns null)
*/
public FieldMetadata getRndField() {
int index = -1;
while (true) {
// Compute the required field name
index++;
String fieldName = "";
for (int i = 0; i < index; i++) {
fieldName = fieldName + "_";
}
fieldName = fieldName + "rnd";
JavaSymbolName fieldSymbolName = new JavaSymbolName(fieldName);
FieldMetadata candidate = MemberFindingUtils.getField(governorTypeDetails, fieldSymbolName);
if (candidate != null) {
// Verify if candidate is suitable
if (!Modifier.isPrivate(candidate.getModifier())) {
// Candidate is not private, so we might run into naming clashes if someone subclasses this (therefore go onto the next possible name)
continue;
}
if (!candidate.getFieldType().equals(new JavaType("java.util.Random"))) {
// Candidate isn't a java.util.Random, so it isn't suitable
continue;
}
// If we got this far, we found a valid candidate
// We don't check if there is a corresponding initializer, but we assume the user knows what they're doing and have made one
return candidate;
}
// Candidate not found, so let's create one
return new DefaultFieldMetadata(getId(), Modifier.PRIVATE, fieldSymbolName, new JavaType("java.util.Random"), "new java.security.SecureRandom()", null);
}
}
/**
* @return the "data" field to use, which is either provided by the user or produced on demand (never returns null)
*/
public FieldMetadata getDataField() {
int index = -1;
while (true) {
// Compute the required field name
index++;
String fieldName = "";
for (int i = 0; i < index; i++) {
fieldName = fieldName + "_";
}
fieldName = fieldName + "data";
// The type parameters to be used by the field type
List<JavaType> typeParams = new ArrayList<JavaType>();
typeParams.add(annotationValues.getEntity());
JavaSymbolName fieldSymbolName = new JavaSymbolName(fieldName);
FieldMetadata candidate = MemberFindingUtils.getField(governorTypeDetails, fieldSymbolName);
if (candidate != null) {
// Verify if candidate is suitable
if (!Modifier.isPrivate(candidate.getModifier())) {
// Candidate is not private, so we might run into naming clashes if someone subclasses this (therefore go onto the next possible name)
continue;
}
if (!candidate.getFieldType().equals(new JavaType("java.util.List", 0, DataType.TYPE, null, typeParams))) {
// Candidate isn't a java.util.List<theEntity>, so it isn't suitable
// The equals method also verifies type params are present
continue;
}
// If we got this far, we found a valid candidate
// We don't check if there is a corresponding initializer, but we assume the user knows what they're doing and have made one
return candidate;
}
// Candidate not found, so let's create one
return new DefaultFieldMetadata(getId(), Modifier.PRIVATE, fieldSymbolName, new JavaType("java.util.List", 0, DataType.TYPE, null, typeParams), null, null);
}
}
/**
* @return the "getNewTransientEntity(int index):Entity" method (never returns null)
*/
public MethodMetadata getNewTransientEntityMethod() {
// Method definition to find or build
JavaSymbolName methodName = new JavaSymbolName("getNewTransient" + beanInfoMetadata.getJavaBean().getSimpleTypeName());
List<JavaType> paramTypes = new ArrayList<JavaType>();
paramTypes.add(JavaType.INT_PRIMITIVE);
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("index"));
JavaType returnType = beanInfoMetadata.getJavaBean();
// Locate user-defined method
MethodMetadata userMethod = MemberFindingUtils.getMethod(governorTypeDetails, methodName, paramTypes);
if (userMethod != null) {
Assert.isTrue(userMethod.getReturnType().equals(returnType), "Method '" + methodName + "' on '" + governorTypeDetails.getName() + "' must return '" + returnType.getNameIncludingTypeParameters() + "'");
return userMethod;
}
// Create method
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine(beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + " obj = new " + beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + "();");
for (MethodMetadata mutator : mandatoryMutators) {
String initializer = mutatorArguments.get(mutator);
Assert.hasText(initializer, "Internal error: unable to locate initializer for " + mutator);
JavaSymbolName propertyName = BeanInfoMetadata.getPropertyNameForJavaBeanMethod(mutator);
FieldMetadata field = beanInfoMetadata.getFieldForPropertyName(propertyName);
if (field.getFieldType().equals(new JavaType(String.class.getName())) && MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), NOT_NULL) != null) {
// Check for @Size or @Column with length attribute
AnnotationMetadata sizeAnnotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE);
AnnotationMetadata columnAnnotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), COLUMN);
if (sizeAnnotationMetadata != null && sizeAnnotationMetadata.getAttribute(new JavaSymbolName("max")) != null) {
Integer maxValue = (Integer) sizeAnnotationMetadata.getAttribute(new JavaSymbolName("max")).getValue();
bodyBuilder.appendFormalLine(field.getFieldType().getFullyQualifiedTypeName() + " " + field.getFieldName().getSymbolName() + " = " + initializer + ";");
bodyBuilder.appendFormalLine("if (" + field.getFieldName().getSymbolName() + ".length() > " + maxValue + ") {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine(field.getFieldName().getSymbolName() + " = " + field.getFieldName().getSymbolName() + ".substring(0, " + maxValue + ");");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + field.getFieldName().getSymbolName() + ");");
} else if (sizeAnnotationMetadata == null && columnAnnotationMetadata != null) {
AnnotationAttributeValue<?> lengthAttributeValue = columnAnnotationMetadata.getAttribute(new JavaSymbolName("length"));
if (lengthAttributeValue != null) {
Integer lengthValue = (Integer) columnAnnotationMetadata.getAttribute(new JavaSymbolName("length")).getValue();
bodyBuilder.appendFormalLine(field.getFieldType().getFullyQualifiedTypeName() + " " + field.getFieldName().getSymbolName() + " = " + initializer + ";");
bodyBuilder.appendFormalLine("if (" + field.getFieldName().getSymbolName() + ".length() > " + lengthValue + ") {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine(field.getFieldName().getSymbolName() + " = " + field.getFieldName().getSymbolName() + ".substring(0, " + lengthValue + ");");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + field.getFieldName().getSymbolName() + ");");
} else {
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + initializer + ");");
}
} else {
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + initializer + ");");
}
} else if (isNumericFieldType(field)) {
// Check for @Min and @Max
AnnotationMetadata minAnnotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MIN);
AnnotationMetadata maxAnnotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MAX);
String suffix = "";
if (field.getFieldType().equals(JavaType.LONG_OBJECT) || field.getFieldType().equals(JavaType.LONG_PRIMITIVE)) {
suffix = "L";
} else if (field.getFieldType().equals(JavaType.FLOAT_OBJECT) || field.getFieldType().equals(JavaType.FLOAT_PRIMITIVE)) {
suffix = "F";
} else if (field.getFieldType().equals(JavaType.DOUBLE_OBJECT) || field.getFieldType().equals(JavaType.DOUBLE_PRIMITIVE)) {
suffix = "D";
}
if (minAnnotationMetadata != null && maxAnnotationMetadata == null) {
Long minValue = (Long) minAnnotationMetadata.getAttribute(new JavaSymbolName("value")).getValue();
bodyBuilder.appendFormalLine(field.getFieldType().getFullyQualifiedTypeName() + " " + field.getFieldName().getSymbolName() + " = " + initializer + ";");
bodyBuilder.appendFormalLine("if (" + field.getFieldName().getSymbolName() + " < " + minValue + ") {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine(field.getFieldName().getSymbolName() + " = " + minValue + suffix + ";");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + field.getFieldName().getSymbolName() + ");");
} else if (minAnnotationMetadata == null && maxAnnotationMetadata != null) {
Long maxValue = (Long) maxAnnotationMetadata.getAttribute(new JavaSymbolName("value")).getValue();
bodyBuilder.appendFormalLine(field.getFieldType().getFullyQualifiedTypeName() + " " + field.getFieldName().getSymbolName() + " = " + initializer + ";");
bodyBuilder.appendFormalLine("if (" + field.getFieldName().getSymbolName() + " > " + maxValue + ") {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine(field.getFieldName().getSymbolName() + " = " + maxValue + suffix + ";");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + field.getFieldName().getSymbolName() + ");");
} else if (minAnnotationMetadata != null && maxAnnotationMetadata != null) {
Long minValue = (Long) minAnnotationMetadata.getAttribute(new JavaSymbolName("value")).getValue();
Long maxValue = (Long) maxAnnotationMetadata.getAttribute(new JavaSymbolName("value")).getValue();
Assert.isTrue(maxValue >= minValue, "The value of @Max must be greater or equal to the value of @Min for field " + field.getFieldName().getSymbolName() );
bodyBuilder.appendFormalLine(field.getFieldType().getFullyQualifiedTypeName() + " " + field.getFieldName().getSymbolName() + " = " + initializer + ";");
bodyBuilder.appendFormalLine("if (" + field.getFieldName().getSymbolName() + " < " + minValue + suffix + " || " + field.getFieldName().getSymbolName() + " > " + suffix + maxValue + ") {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine(field.getFieldName().getSymbolName() + " = " + maxValue + suffix + ";");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + field.getFieldName().getSymbolName() + ");");
} else {
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + initializer + ");");
}
} else {
bodyBuilder.appendFormalLine("obj." + mutator.getMethodName() + "(" + initializer + ");");
}
}
bodyBuilder.appendFormalLine("return obj;");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, returnType, AnnotatedJavaType.convertFromJavaTypes(paramTypes), paramNames, new ArrayList<AnnotationMetadata>(), new ArrayList<JavaType>(), bodyBuilder.getOutput());
}
private boolean isNumericFieldType(FieldMetadata field) {
return field.getFieldType().equals(JavaType.INT_OBJECT) || field.getFieldType().equals(JavaType.INT_PRIMITIVE) ||
field.getFieldType().equals(JavaType.DOUBLE_OBJECT) || field.getFieldType().equals(JavaType.DOUBLE_PRIMITIVE) ||
field.getFieldType().equals(JavaType.FLOAT_OBJECT) || field.getFieldType().equals(JavaType.FLOAT_PRIMITIVE) ||
field.getFieldType().equals(JavaType.LONG_OBJECT) || field.getFieldType().equals(JavaType.LONG_PRIMITIVE) ||
field.getFieldType().equals(JavaType.SHORT_OBJECT) || field.getFieldType().equals(JavaType.SHORT_PRIMITIVE);
}
/**
* @return the "modifyEntity(Entity):boolean" method (never returns null)
*/
public MethodMetadata getModifyMethod() {
// Method definition to find or build
JavaSymbolName methodName = new JavaSymbolName("modify" + beanInfoMetadata.getJavaBean().getSimpleTypeName());
List<JavaType> paramTypes = new ArrayList<JavaType>();
paramTypes.add(beanInfoMetadata.getJavaBean());
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("obj"));
JavaType returnType = JavaType.BOOLEAN_PRIMITIVE;
// Locate user-defined method
MethodMetadata userMethod = MemberFindingUtils.getMethod(governorTypeDetails, methodName, paramTypes);
if (userMethod != null) {
Assert.isTrue(userMethod.getReturnType().equals(returnType), "Method '" + methodName + "' on '" + governorTypeDetails.getName() + "' must return '" + returnType.getNameIncludingTypeParameters() + "'");
return userMethod;
}
// Create method
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
// TODO: We should port this more fully from original code base
bodyBuilder.appendFormalLine("return false;");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, returnType, AnnotatedJavaType.convertFromJavaTypes(paramTypes), paramNames, new ArrayList<AnnotationMetadata>(), new ArrayList<JavaType>(), bodyBuilder.getOutput());
}
/**
* @return the "getRandomEntity():Entity" method (never returns null)
*/
public MethodMetadata getRandomPersistentEntityMethod() {
// Method definition to find or build
JavaSymbolName methodName = new JavaSymbolName("getRandom" + beanInfoMetadata.getJavaBean().getSimpleTypeName());
List<JavaType> paramTypes = new ArrayList<JavaType>();
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
JavaType returnType = beanInfoMetadata.getJavaBean();
// Locate user-defined method
MethodMetadata userMethod = MemberFindingUtils.getMethod(governorTypeDetails, methodName, paramTypes);
if (userMethod != null) {
Assert.isTrue(userMethod.getReturnType().equals(returnType), "Method '" + methodName + "' on '" + governorTypeDetails.getName() + "' must return '" + returnType.getNameIncludingTypeParameters() + "'");
return userMethod;
}
// Create method
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("init();");
bodyBuilder.appendFormalLine(beanInfoMetadata.getJavaBean().getSimpleTypeName() + " obj = " + getDataField().getFieldName().getSymbolName() +".get(" + getRndField().getFieldName().getSymbolName() + ".nextInt(" + getDataField().getFieldName().getSymbolName() + ".size()));");
bodyBuilder.appendFormalLine("return " + beanInfoMetadata.getJavaBean().getSimpleTypeName() + "." + findMethod.getMethodName().getSymbolName() + "(obj." + identifierAccessorMethod.getMethodName().getSymbolName() + "());");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, returnType, AnnotatedJavaType.convertFromJavaTypes(paramTypes), paramNames, new ArrayList<AnnotationMetadata>(), new ArrayList<JavaType>(), bodyBuilder.getOutput());
}
/**
* @return the "getSpecificEntity(int):Entity" method (never returns null)
*/
public MethodMetadata getSpecificPersistentEntityMethod() {
// Method definition to find or build
JavaSymbolName methodName = new JavaSymbolName("getSpecific" + beanInfoMetadata.getJavaBean().getSimpleTypeName());
List<JavaType> paramTypes = new ArrayList<JavaType>();
paramTypes.add(JavaType.INT_PRIMITIVE);
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("index"));
JavaType returnType = beanInfoMetadata.getJavaBean();
// Locate user-defined method
MethodMetadata userMethod = MemberFindingUtils.getMethod(governorTypeDetails, methodName, paramTypes);
if (userMethod != null) {
Assert.isTrue(userMethod.getReturnType().equals(returnType), "Method '" + methodName + "' on '" + governorTypeDetails.getName() + "' must return '" + returnType.getNameIncludingTypeParameters() + "'");
return userMethod;
}
// Create method
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("init();");
bodyBuilder.appendFormalLine("if (index < 0) index = 0;");
bodyBuilder.appendFormalLine("if (index > (" + getDataField().getFieldName().getSymbolName() + ".size() - 1)) index = " + getDataField().getFieldName().getSymbolName() + ".size() - 1;");
bodyBuilder.appendFormalLine(beanInfoMetadata.getJavaBean().getSimpleTypeName() + " obj = " + getDataField().getFieldName().getSymbolName() +".get(index);");
bodyBuilder.appendFormalLine("return " + beanInfoMetadata.getJavaBean().getSimpleTypeName() + "." + findMethod.getMethodName().getSymbolName() + "(obj." + identifierAccessorMethod.getMethodName().getSymbolName() + "());");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, returnType, AnnotatedJavaType.convertFromJavaTypes(paramTypes), paramNames, new ArrayList<AnnotationMetadata>(), new ArrayList<JavaType>(), bodyBuilder.getOutput());
}
/**
* @return the "init():void" method (never returns null)
*/
public MethodMetadata getInitMethod() {
// Method definition to find or build
JavaSymbolName methodName = new JavaSymbolName("init");
List<JavaType> paramTypes = new ArrayList<JavaType>();
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
JavaType returnType = JavaType.VOID_PRIMITIVE;
// Locate user-defined method
MethodMetadata userMethod = MemberFindingUtils.getMethod(governorTypeDetails, methodName, paramTypes);
if (userMethod != null) {
Assert.isTrue(userMethod.getReturnType().equals(returnType), "Method '" + methodName + "' on '" + governorTypeDetails.getName() + "' must return '" + returnType.getNameIncludingTypeParameters() + "'");
return userMethod;
}
// Create the method
// Create the annotations
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
if (!projectMetadata.isGaeEnabled()) {
List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new EnumAttributeValue(new JavaSymbolName("propagation"), new EnumDetails(new JavaType("org.springframework.transaction.annotation.Propagation"), new JavaSymbolName("REQUIRES_NEW"))));
annotations.add(new DefaultAnnotationMetadata(new JavaType("org.springframework.transaction.annotation.Transactional"), attributes));
}
// Create the body
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
String dataField = getDataField().getFieldName().getSymbolName();
bodyBuilder.appendFormalLine("if (" + dataField + " != null && !" + dataField + ".isEmpty()) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("return;");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("");
bodyBuilder.appendFormalLine(dataField + " = " + beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + "." + findEntriesMethod.getMethodName().getSymbolName() + "(0, " + annotationValues.getQuantity() + ");");
bodyBuilder.appendFormalLine("if (data == null) throw new IllegalStateException(\"Find entries implementation for '" + beanInfoMetadata.getJavaBean().getSimpleTypeName() + "' illegally returned null\");");
bodyBuilder.appendFormalLine("if (!" + dataField + ".isEmpty()) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("return;");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("");
bodyBuilder.appendFormalLine(dataField + " = new java.util.ArrayList<" + getDataField().getFieldType().getParameters().get(0).getNameIncludingTypeParameters() + ">();");
bodyBuilder.appendFormalLine("for (int i = 0; i < " + annotationValues.getQuantity() + "; i++) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine(beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + " obj = " + getNewTransientEntityMethod().getMethodName() + "(i);");
bodyBuilder.appendFormalLine("obj." + persistMethod.getMethodName().getSymbolName() + "();");
bodyBuilder.appendFormalLine(dataField + ".add(obj);");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, returnType, AnnotatedJavaType.convertFromJavaTypes(paramTypes), paramNames, annotations, new ArrayList<JavaType>(), bodyBuilder.getOutput());
}
private void mutatorDiscovery() {
for (MethodMetadata mutatorMethod : beanInfoMetadata.getPublicMutators()) {
JavaSymbolName propertyName = BeanInfoMetadata.getPropertyNameForJavaBeanMethod(mutatorMethod);
FieldMetadata field = beanInfoMetadata.getFieldForPropertyName(propertyName);
if (field == null) {
// There is no field for this mutator, so chances are it's not mandatory
continue;
}
// Never include id or version fields (they shouldn't normally have a mutator anyway, but the user might have added one)
if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.Id")) != null || MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.Version")) != null) {
continue;
}
// Never include field annotated with @javax.persistence.Transient
if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.Transient")) != null) {
continue;
}
// Never include any sort of collection; user has to make such entities by hand
if (field.getFieldType().isCommonCollectionType() || MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.OneToMany")) != null) {
continue;
}
// Check for @ManyToOne annotation with 'optional = false' attribute (ROO-1075)
boolean hasManyToOne = false;
AnnotationMetadata manyToOneAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.ManyToOne"));
if (manyToOneAnnotation != null) {
AnnotationAttributeValue<?> optionalAttribute = manyToOneAnnotation.getAttribute(new JavaSymbolName("optional"));
hasManyToOne = optionalAttribute != null && !((Boolean) optionalAttribute.getValue());
}
AnnotationMetadata oneToOneAnnotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.OneToOne"));
String initializer = "null";
// Date fields included for DataNucleus (
if (field.getFieldType().equals(new JavaType(Date.class.getName()))) {
if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.Past")) != null) {
initializer = "new java.util.Date(new java.util.Date().getTime() - 10000000L)";
} else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.Future")) != null) {
initializer = "new java.util.Date(new java.util.Date().getTime() + 10000000L)";
} else {
initializer = "new java.util.Date()";
}
} else if (field.getFieldType().equals(JavaType.BOOLEAN_PRIMITIVE) && MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), NOT_NULL) == null ) {
initializer = "true";
} else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), NOT_NULL) != null || MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE) != null || MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MIN) != null || MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MAX) != null || hasManyToOne || field.getAnnotations().size() == 0) {
// Only include the field if it's really required (ie marked with JSR 303 NotNull) or it has no annotations and is therefore probably simple to invoke
if (field.getFieldType().equals(JavaType.STRING_OBJECT)) {
initializer = field.getFieldName().getSymbolName();
// Check for @Size
AnnotationMetadata sizeAnnotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), SIZE);
if (sizeAnnotationMetadata != null) {
AnnotationAttributeValue<?> maxValue = sizeAnnotationMetadata.getAttribute(new JavaSymbolName("max"));
if (maxValue != null && (Integer) maxValue.getValue() > 1 && (initializer.length() + 2) > (Integer) maxValue.getValue()) {
initializer = initializer.substring(0, (Integer) maxValue.getValue() - 2);
}
AnnotationAttributeValue<?> minValue = sizeAnnotationMetadata.getAttribute(new JavaSymbolName("min"));
if (minValue != null && (initializer.length() + 2) < (Integer) minValue.getValue()) {
initializer = String.format("%1$-" + ((Integer) minValue.getValue() - 2) + "s", initializer).replace(' ', 'x');
}
}
// Check for @Column
AnnotationMetadata columnAnnotationMetadata = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), COLUMN);
if (columnAnnotationMetadata != null) {
AnnotationAttributeValue<?> lengthValue = columnAnnotationMetadata.getAttribute(new JavaSymbolName("length"));
if (lengthValue != null && (initializer.length() + 2) > (Integer) lengthValue.getValue()) {
initializer = initializer.substring(0, (Integer) lengthValue.getValue() - 2);
}
}
initializer = "\"" + initializer + "_\" + index";
} else if (field.getFieldType().equals(new JavaType(Calendar.class.getName()))) {
if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.Past")) != null) {
initializer = "new java.util.GregorianCalendar(java.util.Calendar.getInstance().get(java.util.Calendar.YEAR), java.util.Calendar.getInstance().get(java.util.Calendar.MONTH), java.util.Calendar.getInstance().get(java.util.Calendar.DAY_OF_MONTH) - 1)";
} else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.Future")) != null) {
initializer = "new java.util.GregorianCalendar(java.util.Calendar.getInstance().get(java.util.Calendar.YEAR), java.util.Calendar.getInstance().get(java.util.Calendar.MONTH), java.util.Calendar.getInstance().get(java.util.Calendar.DAY_OF_MONTH) + 1)";
} else {
initializer = "java.util.Calendar.getInstance()";
}
} else if (field.getFieldType().equals(JavaType.BOOLEAN_OBJECT)) {
initializer = "new Boolean(true)";
} else if (field.getFieldType().equals(JavaType.BOOLEAN_PRIMITIVE)) {
initializer = "true";
} else if (field.getFieldType().equals(JavaType.INT_OBJECT)) {
initializer = "new Integer(index)";
} else if (field.getFieldType().equals(JavaType.INT_PRIMITIVE)) {
initializer = "new Integer(index)"; // Auto-boxed
} else if (field.getFieldType().equals(JavaType.DOUBLE_OBJECT)) {
initializer = "new Integer(index).doubleValue()"; // Auto-boxed
} else if (field.getFieldType().equals(JavaType.DOUBLE_PRIMITIVE)) {
initializer = "new Integer(index).doubleValue()";
} else if (field.getFieldType().equals(JavaType.FLOAT_OBJECT)) {
initializer = "new Integer(index).floatValue()"; // Auto-boxed
} else if (field.getFieldType().equals(JavaType.FLOAT_PRIMITIVE)) {
initializer = "new Integer(index).floatValue()";
} else if (field.getFieldType().equals(JavaType.LONG_OBJECT)) {
initializer = "new Integer(index).longValue()"; // Auto-boxed
} else if (field.getFieldType().equals(JavaType.LONG_PRIMITIVE)) {
initializer = "new Integer(index).longValue()";
} else if (field.getFieldType().equals(JavaType.SHORT_OBJECT)) {
initializer = "new Integer(index).shortValue()"; // Auto-boxed
} else if (field.getFieldType().equals(JavaType.SHORT_PRIMITIVE)) {
initializer = "new Integer(index).shortValue()";
} else if (manyToOneAnnotation != null || oneToOneAnnotation != null) {
if (field.getFieldType().equals(this.getAnnotationValues().getEntity())) {
// Avoid circular references (ROO-562)
initializer = "obj";
} else {
requiredDataOnDemandCollaborators.add(field.getFieldType());
String collaboratingFieldName = getCollaboratingFieldName(field.getFieldType()).getSymbolName();
// Look up the metadata we are relying on
String otherProvider = DataOnDemandMetadata.createIdentifier(new JavaType(field.getFieldType() + "DataOnDemand"), Path.SRC_TEST_JAVA);
// Decide if we're dealing with a one-to-one and therefore should _try_ to keep the same id (ROO-568)
boolean oneToOne = oneToOneAnnotation != null;
metadataDependencyRegistry.registerDependency(otherProvider, getId());
DataOnDemandMetadata otherMd = (DataOnDemandMetadata) metadataService.get(otherProvider);
if (otherMd == null || !otherMd.isValid()) {
// There is no metadata around, so we'll just make some basic assumptions
if (oneToOne) {
initializer = collaboratingFieldName + ".getSpecific" + field.getFieldType().getSimpleTypeName() + "(index)";
} else {
initializer = collaboratingFieldName + ".getRandom" + field.getFieldType().getSimpleTypeName() + "()";
}
} else {
// We can use the correct name
if (oneToOne) {
initializer = collaboratingFieldName + "." + otherMd.getSpecificPersistentEntityMethod().getMethodName().getSymbolName() + "(index)";
} else {
initializer = collaboratingFieldName + "." + otherMd.getRandomPersistentEntityMethod().getMethodName().getSymbolName() + "()";
}
}
}
} else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.Enumerated")) != null) {
initializer = field.getFieldType().getFullyQualifiedTypeName() + ".class.getEnumConstants()[0]";
}
}
mandatoryMutators.add(mutatorMethod);
mutatorArguments.put(mutatorMethod, initializer);
}
}
private JavaSymbolName getCollaboratingFieldName(JavaType entity) {
return new JavaSymbolName(StringUtils.uncapitalize(getCollaboratingType(entity).getSimpleTypeName()));
}
private JavaType getCollaboratingType(JavaType entity) {
return new JavaType(entity.getFullyQualifiedTypeName() + "DataOnDemand");
}
/**
* @return the physical type identifier for the {@link BeanInfoMetadata} (never null or empty unless metadata is invalid)
*/
public String getIdentifierForBeanInfoMetadata() {
return beanInfoMetadata.getId();
}
/**
* @return the annotation values specified via {@link RooDataOnDemand} (never null unless the metadata itself is invalid)
*/
public DataOnDemandAnnotationValues getAnnotationValues() {
return annotationValues;
}
public String toString() {
ToStringCreator tsc = new ToStringCreator(this);
tsc.append("identifier", getId());
tsc.append("valid", valid);
tsc.append("aspectName", aspectName);
tsc.append("destinationType", destination);
tsc.append("governor", governorPhysicalTypeMetadata.getId());
tsc.append("itdTypeDetails", itdTypeDetails);
return tsc.toString();
}
public static final String getMetadataIdentiferType() {
return PROVIDES_TYPE;
}
public static final String createIdentifier(JavaType javaType, Path path) {
return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path);
}
public static final JavaType getJavaType(String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING, metadataIdentificationString);
}
public static final Path getPath(String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString);
}
public static boolean isValid(String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING, metadataIdentificationString);
}
}
| ROO-1113: Generated tests need support for BigDecimal
| addon-dod/src/main/java/org/springframework/roo/addon/dod/DataOnDemandMetadata.java | ROO-1113: Generated tests need support for BigDecimal |
|
Java | apache-2.0 | dd84bb5d868ef3115dcc53f5770d6b8646b02d7f | 0 | Netflix/EVCache,Netflix/EVCache | package com.netflix.evcache.pool;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicStringProperty;
import com.netflix.discovery.DiscoveryClient;
import com.netflix.discovery.DiscoveryManager;
import com.netflix.evcache.connection.DefaultFactoryProvider;
import com.netflix.evcache.connection.IConnectionFactoryProvider;
import com.netflix.evcache.event.EVCacheEventListener;
import com.netflix.evcache.util.EVCacheConfig;
/**
* A manager that holds Pools for each EVCache app. When this class is
* initialized all the EVCache apps defined in the property evcache.appsToInit
* will be initialized and added to the pool. If a service knows all the EVCache
* app it uses, then it can define this property and pass a list of EVCache apps
* that needs to be initialized.
*
* An EVCache app can also be initialized by Injecting
* <code>EVCacheClientPoolManager</code> and calling <code>
* initEVCache(<app name>)
* </code>
*
* This typically should be done in the client libraries that need to initialize
* an EVCache app. For Example VHSViewingHistoryLibrary in its initLibrary
* initializes EVCACHE_VH by calling
*
* <pre>
* {@literal @}Inject
* public VHSViewingHistoryLibrary(EVCacheClientPoolManager instance,...) {
* ....
* instance.initEVCache("EVCACHE_VH");
* ...
* }
* </pre>
*
* @author smadappa
*
*/
@SuppressWarnings("deprecation")
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS", "DM_CONVERT_CASE",
"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" })
@Singleton
public class EVCacheClientPoolManager {
private static final Logger log = LoggerFactory.getLogger(EVCacheClientPoolManager.class);
private static final DynamicIntProperty defaultReadTimeout = EVCacheConfig.getInstance().getDynamicIntProperty("default.read.timeout", 20);
private final DynamicIntProperty defaultRefreshInterval = EVCacheConfig.getInstance().getDynamicIntProperty("EVCacheClientPoolManager.refresh.interval", 60);
private static final DynamicStringProperty logEnabledApps = EVCacheConfig.getInstance().getDynamicStringProperty("EVCacheClientPoolManager.log.apps", "*");
@Deprecated
private volatile static EVCacheClientPoolManager instance;
private final Map<String, EVCacheClientPool> poolMap = new ConcurrentHashMap<String, EVCacheClientPool>();
private final Map<EVCacheClientPool, ScheduledFuture<?>> scheduledTaskMap = new HashMap<EVCacheClientPool, ScheduledFuture<?>>();
private final ScheduledThreadPoolExecutor _scheduler;
private final DiscoveryClient discoveryClient;
private final ApplicationInfoManager applicationInfoManager;
private final List<EVCacheEventListener> evcacheEventListenerList;
private final Provider<IConnectionFactoryProvider> connectionFactoryprovider;
@Inject
public EVCacheClientPoolManager(ApplicationInfoManager applicationInfoManager, DiscoveryClient discoveryClient, Provider<IConnectionFactoryProvider> connectionFactoryprovider) {
instance = this;
try {
ConfigurationManager.loadCascadedPropertiesFromResources("evcache");
} catch (IOException e) {
log.info("Default evcache configuration not loaded", e);
}
this.applicationInfoManager = applicationInfoManager;
this.discoveryClient = discoveryClient;
this.connectionFactoryprovider = connectionFactoryprovider;
this.evcacheEventListenerList = new ArrayList<EVCacheEventListener>();
final int poolSize = EVCacheConfig.getInstance().getDynamicIntProperty("default.refresher.poolsize", 1).get();
//final int poolSize = ConfigurationManager.getConfigInstance().getInt("default.refresher.poolsize", 1);
final ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(
"EVCacheClientPoolManager_refresher-%d").build();
_scheduler = new ScheduledThreadPoolExecutor(poolSize, factory);
defaultRefreshInterval.addCallback(new Runnable() {
public void run() {
refreshScheduler();
}
});
initAtStartup();
}
public IConnectionFactoryProvider getConnectionFactoryProvider() {
return connectionFactoryprovider.get();
}
public void addEVCacheEventListener(EVCacheEventListener listener) {
this.evcacheEventListenerList.add(listener);
}
public void removeEVCacheEventListener(EVCacheEventListener listener) {
this.evcacheEventListenerList.remove(listener);
}
public List<EVCacheEventListener> getEVCacheEventListeners() {
return this.evcacheEventListenerList;
}
private void refreshScheduler() {
for (Iterator<EVCacheClientPool> itr = scheduledTaskMap.keySet().iterator(); itr.hasNext();) {
final EVCacheClientPool pool = itr.next();
final ScheduledFuture<?> task = scheduledTaskMap.get(pool);
itr.remove();
task.cancel(true);
scheduleRefresh(pool);
}
}
/**
* @deprecated. Please use DependencyInjection (@Inject) to obtain
* {@link EVCacheClientPoolManager}. The use of this can result in
* unintended behavior where you will not be able to talk to evcache
* instances.
*/
@Deprecated
public static EVCacheClientPoolManager getInstance() {
if (instance == null) {
new EVCacheClientPoolManager(null, null, new DefaultFactoryProvider());
if (!EVCacheConfig.getInstance().getDynamicBooleanProperty("evcache.use.simple.node.list.provider", false).get()) {
log.warn("Please make sure EVCacheClientPoolManager is injected first. This is not the appropriate way to init EVCacheClientPoolManager."
+ " If you are using simple node list provider please set evcache.use.simple.node.list.provider property to true.", new Exception());
}
}
return instance;
}
public ApplicationInfoManager getApplicationInfoManager() {
return this.applicationInfoManager;
}
public DiscoveryClient getDiscoveryClient() {
DiscoveryClient client = discoveryClient;
if (client == null) client = DiscoveryManager.getInstance().getDiscoveryClient();
return client;
}
/**
* TODO Move to @PostConstruct, so that a non-static EVCacheConfig can be injected by DI, so that Configuration
* subsystem can be properly setup via the DI system.
*/
public void initAtStartup() {
//final String appsToInit = ConfigurationManager.getConfigInstance().getString("evcache.appsToInit");
final String appsToInit = EVCacheConfig.getInstance().getDynamicStringProperty("evcache.appsToInit", "").get();
if (appsToInit != null && appsToInit.length() > 0) {
final StringTokenizer apps = new StringTokenizer(appsToInit, ",");
while (apps.hasMoreTokens()) {
final String app = getAppName(apps.nextToken());
if (log.isDebugEnabled()) log.debug("Initializing EVCache - " + app);
initEVCache(app);
}
}
}
/**
* Will init the given EVCache app call. If one is already initialized for
* the given app method returns without doing anything.
*
* @param app
* - name of the evcache app
*/
public final synchronized void initEVCache(String app) {
if (app == null || (app = app.trim()).length() == 0) throw new IllegalArgumentException(
"param app name null or space");
final String APP = getAppName(app);
if (poolMap.containsKey(APP)) return;
final EVCacheNodeList provider;
if (EVCacheConfig.getInstance().getChainedBooleanProperty(APP + ".use.simple.node.list.provider", "evcache.use.simple.node.list.provider", false).get()) {
provider = new SimpleNodeListProvider(APP + "-NODES");
} else {
provider = new DiscoveryNodeListProvider(applicationInfoManager, discoveryClient, APP);
}
final EVCacheClientPool pool = new EVCacheClientPool(APP, provider, this);
scheduleRefresh(pool);
poolMap.put(APP, pool);
}
private void scheduleRefresh(EVCacheClientPool pool) {
final ScheduledFuture<?> task = _scheduler.scheduleWithFixedDelay(pool, 30, defaultRefreshInterval.get(),
TimeUnit.SECONDS);
scheduledTaskMap.put(pool, task);
}
/**
* Given the appName get the EVCacheClientPool. If the app is already
* created then will return the existing instance. If not one will be
* created and returned.
*
* @param _app
* - name of the evcache app
* @return the Pool for the give app.
* @throws IOException
*/
public EVCacheClientPool getEVCacheClientPool(String _app) {
final String app = getAppName(_app);
final EVCacheClientPool evcacheClientPool = poolMap.get(app);
if (evcacheClientPool != null) return evcacheClientPool;
initEVCache(app);
return poolMap.get(app);
}
public Map<String, EVCacheClientPool> getAllEVCacheClientPool() {
return new HashMap<String, EVCacheClientPool>(poolMap);
}
@PreDestroy
public void shutdown() {
_scheduler.shutdown();
for (EVCacheClientPool pool : poolMap.values()) {
pool.shutdown();
}
}
public boolean shouldLog(String appName) {
if ("*".equals(logEnabledApps.get())) return true;
if (logEnabledApps.get().indexOf(appName) != -1) return true;
return false;
}
public static DynamicIntProperty getDefaultReadTimeout() {
return defaultReadTimeout;
}
private String getAppName(String _app) {
_app = _app.toUpperCase();
final String app = ConfigurationManager.getConfigInstance().getString("EVCacheClientPoolManager." + _app + ".alias", _app).toUpperCase();
if (log.isDebugEnabled()) log.debug("Original App Name : " + _app + "; Alias App Name : " + app);
return app;
}
}
| evcache-client/src/main/java/com/netflix/evcache/pool/EVCacheClientPoolManager.java | package com.netflix.evcache.pool;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicStringProperty;
import com.netflix.discovery.DiscoveryClient;
import com.netflix.discovery.DiscoveryManager;
import com.netflix.evcache.connection.DefaultFactoryProvider;
import com.netflix.evcache.connection.IConnectionFactoryProvider;
import com.netflix.evcache.event.EVCacheEventListener;
import com.netflix.evcache.util.EVCacheConfig;
/**
* A manager that holds Pools for each EVCache app. When this class is
* initialized all the EVCache apps defined in the property evcache.appsToInit
* will be initialized and added to the pool. If a service knows all the EVCache
* app it uses, then it can define this property and pass a list of EVCache apps
* that needs to be initialized.
*
* An EVCache app can also be initialized by Injecting
* <code>EVCacheClientPoolManager</code> and calling <code>
* initEVCache(<app name>)
* </code>
*
* This typically should be done in the client libraries that need to initialize
* an EVCache app. For Example VHSViewingHistoryLibrary in its initLibrary
* initializes EVCACHE_VH by calling
*
* <pre>
* {@literal @}Inject
* public VHSViewingHistoryLibrary(EVCacheClientPoolManager instance,...) {
* ....
* instance.initEVCache("EVCACHE_VH");
* ...
* }
* </pre>
*
* @author smadappa
*
*/
@SuppressWarnings("deprecation")
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS", "DM_CONVERT_CASE",
"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" })
@Singleton
public class EVCacheClientPoolManager {
private static final Logger log = LoggerFactory.getLogger(EVCacheClientPoolManager.class);
private static final DynamicIntProperty defaultReadTimeout = EVCacheConfig.getInstance().getDynamicIntProperty("default.read.timeout", 20);
private final DynamicIntProperty defaultRefreshInterval = EVCacheConfig.getInstance().getDynamicIntProperty("EVCacheClientPoolManager.refresh.interval", 60);
private static final DynamicStringProperty logEnabledApps = EVCacheConfig.getInstance().getDynamicStringProperty("EVCacheClientPoolManager.log.apps", "*");
@Deprecated
private volatile static EVCacheClientPoolManager instance;
private final Map<String, EVCacheClientPool> poolMap = new ConcurrentHashMap<String, EVCacheClientPool>();
private final Map<EVCacheClientPool, ScheduledFuture<?>> scheduledTaskMap = new HashMap<EVCacheClientPool, ScheduledFuture<?>>();
private final ScheduledThreadPoolExecutor _scheduler;
private final DiscoveryClient discoveryClient;
private final ApplicationInfoManager applicationInfoManager;
private final List<EVCacheEventListener> evcacheEventListenerList;
private final Provider<IConnectionFactoryProvider> connectionFactoryprovider;
@Inject
public EVCacheClientPoolManager(ApplicationInfoManager applicationInfoManager, DiscoveryClient discoveryClient, Provider<IConnectionFactoryProvider> connectionFactoryprovider) {
instance = this;
try {
ConfigurationManager.loadCascadedPropertiesFromResources("evcache");
} catch (IOException e) {
log.info("Default evcache configuration not loaded", e);
}
this.applicationInfoManager = applicationInfoManager;
this.discoveryClient = discoveryClient;
this.connectionFactoryprovider = connectionFactoryprovider;
this.evcacheEventListenerList = new ArrayList<EVCacheEventListener>();
final int poolSize = EVCacheConfig.getInstance().getDynamicIntProperty("default.refresher.poolsize", 1).get();
//final int poolSize = ConfigurationManager.getConfigInstance().getInt("default.refresher.poolsize", 1);
final ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(
"EVCacheClientPoolManager_refresher-%d").build();
_scheduler = new ScheduledThreadPoolExecutor(poolSize, factory);
defaultRefreshInterval.addCallback(new Runnable() {
public void run() {
refreshScheduler();
}
});
}
public IConnectionFactoryProvider getConnectionFactoryProvider() {
return connectionFactoryprovider.get();
}
public void addEVCacheEventListener(EVCacheEventListener listener) {
this.evcacheEventListenerList.add(listener);
}
public void removeEVCacheEventListener(EVCacheEventListener listener) {
this.evcacheEventListenerList.remove(listener);
}
public List<EVCacheEventListener> getEVCacheEventListeners() {
return this.evcacheEventListenerList;
}
private void refreshScheduler() {
for (Iterator<EVCacheClientPool> itr = scheduledTaskMap.keySet().iterator(); itr.hasNext();) {
final EVCacheClientPool pool = itr.next();
final ScheduledFuture<?> task = scheduledTaskMap.get(pool);
itr.remove();
task.cancel(true);
scheduleRefresh(pool);
}
}
/**
* @deprecated. Please use DependencyInjection (@Inject) to obtain
* {@link EVCacheClientPoolManager}. The use of this can result in
* unintended behavior where you will not be able to talk to evcache
* instances.
*/
@Deprecated
public static EVCacheClientPoolManager getInstance() {
if (instance == null) {
new EVCacheClientPoolManager(null, null, new DefaultFactoryProvider());
instance.initAtStartup();
if (!EVCacheConfig.getInstance().getDynamicBooleanProperty("evcache.use.simple.node.list.provider", false).get()) {
log.warn("Please make sure EVCacheClientPoolManager is injected first. This is not the appropriate way to init EVCacheClientPoolManager."
+ " If you are using simple node list provider please set evcache.use.simple.node.list.provider property to true.", new Exception());
}
}
return instance;
}
public ApplicationInfoManager getApplicationInfoManager() {
return this.applicationInfoManager;
}
public DiscoveryClient getDiscoveryClient() {
DiscoveryClient client = discoveryClient;
if (client == null) client = DiscoveryManager.getInstance().getDiscoveryClient();
return client;
}
@PostConstruct
public void initAtStartup() {
//final String appsToInit = ConfigurationManager.getConfigInstance().getString("evcache.appsToInit");
final String appsToInit = EVCacheConfig.getInstance().getDynamicStringProperty("evcache.appsToInit", "").get();
if (appsToInit != null && appsToInit.length() > 0) {
final StringTokenizer apps = new StringTokenizer(appsToInit, ",");
while (apps.hasMoreTokens()) {
final String app = getAppName(apps.nextToken());
if (log.isDebugEnabled()) log.debug("Initializing EVCache - " + app);
initEVCache(app);
}
}
}
/**
* Will init the given EVCache app call. If one is already initialized for
* the given app method returns without doing anything.
*
* @param app
* - name of the evcache app
*/
public final synchronized void initEVCache(String app) {
if (app == null || (app = app.trim()).length() == 0) throw new IllegalArgumentException(
"param app name null or space");
final String APP = getAppName(app);
if (poolMap.containsKey(APP)) return;
final EVCacheNodeList provider;
if (EVCacheConfig.getInstance().getChainedBooleanProperty(APP + ".use.simple.node.list.provider", "evcache.use.simple.node.list.provider", false).get()) {
provider = new SimpleNodeListProvider(APP + "-NODES");
} else {
provider = new DiscoveryNodeListProvider(applicationInfoManager, discoveryClient, APP);
}
final EVCacheClientPool pool = new EVCacheClientPool(APP, provider, this);
scheduleRefresh(pool);
poolMap.put(APP, pool);
}
private void scheduleRefresh(EVCacheClientPool pool) {
final ScheduledFuture<?> task = _scheduler.scheduleWithFixedDelay(pool, 30, defaultRefreshInterval.get(),
TimeUnit.SECONDS);
scheduledTaskMap.put(pool, task);
}
/**
* Given the appName get the EVCacheClientPool. If the app is already
* created then will return the existing instance. If not one will be
* created and returned.
*
* @param _app
* - name of the evcache app
* @return the Pool for the give app.
* @throws IOException
*/
public EVCacheClientPool getEVCacheClientPool(String _app) {
final String app = getAppName(_app);
final EVCacheClientPool evcacheClientPool = poolMap.get(app);
if (evcacheClientPool != null) return evcacheClientPool;
initEVCache(app);
return poolMap.get(app);
}
public Map<String, EVCacheClientPool> getAllEVCacheClientPool() {
return new HashMap<String, EVCacheClientPool>(poolMap);
}
@PreDestroy
public void shutdown() {
_scheduler.shutdown();
for (EVCacheClientPool pool : poolMap.values()) {
pool.shutdown();
}
}
public boolean shouldLog(String appName) {
if ("*".equals(logEnabledApps.get())) return true;
if (logEnabledApps.get().indexOf(appName) != -1) return true;
return false;
}
public static DynamicIntProperty getDefaultReadTimeout() {
return defaultReadTimeout;
}
private String getAppName(String _app) {
_app = _app.toUpperCase();
final String app = ConfigurationManager.getConfigInstance().getString("EVCacheClientPoolManager." + _app + ".alias", _app).toUpperCase();
if (log.isDebugEnabled()) log.debug("Original App Name : " + _app + "; Alias App Name : " + app);
return app;
}
}
| Undo initAtStartup to PostConstruct phase.
| evcache-client/src/main/java/com/netflix/evcache/pool/EVCacheClientPoolManager.java | Undo initAtStartup to PostConstruct phase. |
|
Java | apache-2.0 | 5f026ff91a25086f867d395789853afcb06378cb | 0 | fthevenet/binjr,fthevenet/binjr | /*
* Copyright 2016-2018 Frederic Thevenet
*
* 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 eu.binjr.sources.jrds.adapters;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import eu.binjr.common.xml.XmlUtils;
import eu.binjr.core.data.adapters.HttpDataAdapter;
import eu.binjr.core.data.adapters.SerializedDataAdapter;
import eu.binjr.core.data.adapters.TimeSeriesBinding;
import eu.binjr.core.data.codec.csv.CsvDecoder;
import eu.binjr.core.data.exceptions.*;
import eu.binjr.core.data.timeseries.DoubleTimeSeriesProcessor;
import eu.binjr.core.dialogs.Dialogs;
import eu.binjr.sources.jrds.adapters.json.JsonJrdsItem;
import eu.binjr.sources.jrds.adapters.json.JsonJrdsTree;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.fx.ui.controls.tree.FilterableTreeItem;
import javax.xml.bind.JAXB;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* This class provides an implementation of {@link SerializedDataAdapter} for JRDS.
*
* @author Frederic Thevenet
*/
@XmlAccessorType(XmlAccessType.FIELD)
public class JrdsDataAdapter extends HttpDataAdapter {
public static final String JRDS_FILTER = "filter";
public static final String JRDS_TREE = "tree";
protected static final String ENCODING_PARAM_NAME = "encoding";
protected static final String ZONE_ID_PARAM_NAME = "zoneId";
protected static final String TREE_VIEW_TAB_PARAM_NAME = "treeViewTab";
private static final Logger logger = LogManager.getLogger(JrdsDataAdapter.class);
private static final char DELIMITER = ',';
private final static Pattern uriSchemePattern = Pattern.compile("^[a-zA-Z]*://");
private final JrdsSeriesBindingFactory bindingFactory = new JrdsSeriesBindingFactory();
private CsvDecoder decoder;
private String filter;
private ZoneId zoneId;
private String encoding;
private JrdsTreeViewTab treeViewTab;
/**
* Initialises a new instance of the {@link JrdsDataAdapter} class.
*
* @throws DataAdapterException if an error occurs while initializing the adapter.
*/
public JrdsDataAdapter() throws DataAdapterException {
super();
}
/**
* Initializes a new instance of the {@link JrdsDataAdapter} class.
*
* @param baseURL the URL to the JRDS webapp.
* @param zoneId the id of the time zone used to record dates.
* @param encoding the encoding used by the download servlet.
* @param treeViewTab the tab to apply.
* @param filter the filter to apply to the tree view.
* @throws DataAdapterException if an error occurs while initializing the adapter.
*/
public JrdsDataAdapter(URL baseURL, ZoneId zoneId, String encoding, JrdsTreeViewTab treeViewTab, String filter) throws DataAdapterException {
super(baseURL);
this.zoneId = zoneId;
this.encoding = encoding;
this.treeViewTab = treeViewTab;
this.filter = filter;
this.decoder = new CsvDecoder(getEncoding(), DELIMITER,
DoubleTimeSeriesProcessor::new,
s -> {
Double val = Double.parseDouble(s);
return val.isNaN() ? 0 : val;
},
s -> ZonedDateTime.parse(s, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(zoneId)));
}
/**
* Builds a new instance of the {@link JrdsDataAdapter} class from the provided parameters.
*
* @param address the URL to the JRDS webapp.
* @param zoneId the id of the time zone used to record dates.
* @param treeViewTab the tab to apply.
* @param filter the filter to apply to the tree view.
* @return a new instance of the {@link JrdsDataAdapter} class.
* @throws DataAdapterException if an error occurs while initializing the adapter.
*/
public static JrdsDataAdapter fromUrl(String address, ZoneId zoneId, JrdsTreeViewTab treeViewTab, String filter) throws DataAdapterException {
try {
// Detect if URL protocol is present. If not, assume http.
if (!uriSchemePattern.matcher(address).find()) {
address = "http://" + address;
}
URL url = new URL(address.trim());
if (url.getHost().trim().isEmpty()) {
throw new CannotInitializeDataAdapterException("Malformed URL: no host");
}
return new JrdsDataAdapter(url, zoneId, "utf-8", treeViewTab, filter);
} catch (MalformedURLException e) {
throw new CannotInitializeDataAdapterException("Malformed URL: " + e.getMessage(), e);
}
}
//region [DataAdapter Members]
@Override
public FilterableTreeItem<TimeSeriesBinding> getBindingTree() throws DataAdapterException {
Gson gson = new Gson();
try {
JsonJrdsTree t = gson.fromJson(getJsonTree(treeViewTab.getCommand(), treeViewTab.getArgument(), filter), JsonJrdsTree.class);
Map<String, JsonJrdsItem> m = Arrays.stream(t.items).collect(Collectors.toMap(o -> o.id, (o -> o)));
FilterableTreeItem<TimeSeriesBinding> tree = new FilterableTreeItem<>(bindingFactory.of("", getSourceName(), "/", this));
for (JsonJrdsItem branch : Arrays.stream(t.items).filter(jsonJrdsItem -> JRDS_TREE.equals(jsonJrdsItem.type) || JRDS_FILTER.equals(jsonJrdsItem.type)).collect(Collectors.toList())) {
attachNode(tree, branch.id, m);
}
return tree;
} catch (JsonParseException e) {
throw new DataAdapterException("An error occurred while parsing the json response to getBindingTree request", e);
} catch (URISyntaxException e) {
throw new SourceCommunicationException("Error building URI for request", e);
}
}
@Override
protected URI craftFetchUri(String path, Instant begin, Instant end) throws DataAdapterException {
return craftRequestUri("download",
new BasicNameValuePair("id", path),
new BasicNameValuePair("begin", Long.toString(begin.toEpochMilli())),
new BasicNameValuePair("end", Long.toString(end.toEpochMilli()))
);
}
@Override
public String getSourceName() {
return new StringBuilder("[JRDS] ")
.append(getBaseAddress() != null ? getBaseAddress().getHost() : "???")
.append((getBaseAddress() != null && getBaseAddress().getPort() > 0) ? ":" + getBaseAddress().getPort() : "")
.append(" - ")
.append(treeViewTab != null ? treeViewTab : "???")
.append(filter != null ? filter : "")
.append(" (")
.append(zoneId != null ? zoneId : "???")
.append(")").toString();
}
@Override
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<>(super.getParams());
params.put(ZONE_ID_PARAM_NAME, zoneId.toString());
params.put(ENCODING_PARAM_NAME, encoding);
params.put(TREE_VIEW_TAB_PARAM_NAME, treeViewTab.name());
params.put(JRDS_FILTER, this.filter);
return params;
}
@Override
public void loadParams(Map<String, String> params) throws DataAdapterException {
if (params == null) {
throw new InvalidAdapterParameterException("Could not find parameter list for adapter " + getSourceName());
}
super.loadParams(params);
encoding = validateParameterNullity(params, ENCODING_PARAM_NAME);
zoneId = validateParameter(params, ZONE_ID_PARAM_NAME,
s -> {
if (s == null) {
throw new InvalidAdapterParameterException("Parameter " + ZONE_ID_PARAM_NAME + " is missing in adapter " + getSourceName());
}
return ZoneId.of(s);
});
treeViewTab = validateParameter(params, TREE_VIEW_TAB_PARAM_NAME, s -> s == null ? JrdsTreeViewTab.valueOf(params.get(TREE_VIEW_TAB_PARAM_NAME)) : JrdsTreeViewTab.HOSTS_TAB);
this.filter = params.get(JRDS_FILTER);
}
@Override
public String getEncoding() {
return encoding;
}
@Override
public ZoneId getTimeZoneId() {
return zoneId;
}
@Override
public CsvDecoder getDecoder() {
return decoder;
}
@Override
public void close() {
super.close();
}
//endregion
public Collection<String> discoverFilters() throws DataAdapterException, URISyntaxException {
Gson gson = new Gson();
try {
JsonJrdsTree t = gson.fromJson(getJsonTree(treeViewTab.getCommand(), treeViewTab.getArgument()), JsonJrdsTree.class);
return Arrays.stream(t.items).filter(jsonJrdsItem -> JRDS_FILTER.equals(jsonJrdsItem.type)).map(i -> i.filter).collect(Collectors.toList());
} catch (JsonParseException e) {
throw new DataAdapterException("An error occurred while parsing the json response to getBindingTree request", e);
}
}
private void attachNode(FilterableTreeItem<TimeSeriesBinding> tree, String id, Map<String, JsonJrdsItem> nodes) throws DataAdapterException {
JsonJrdsItem n = nodes.get(id);
String currentPath = normalizeId(n.id);
FilterableTreeItem<TimeSeriesBinding> newBranch = new FilterableTreeItem<>(bindingFactory.of(tree.getValue().getTreeHierarchy(), n.name, currentPath, this));
if (JRDS_FILTER.equals(n.type)) {
// add a dummy node so that the branch can be expanded
newBranch.getInternalChildren().add(new FilterableTreeItem<>(null));
// add a listener that will get the treeview filtered according to the selected filter/tag
newBranch.expandedProperty().addListener(new FilteredViewListener(n, newBranch));
} else {
if (n.children != null) {
for (JsonJrdsItem.JsonTreeRef ref : n.children) {
attachNode(newBranch, ref._reference, nodes);
}
} else {
// add a dummy node so that the branch can be expanded
newBranch.getInternalChildren().add(new FilterableTreeItem<>(null));
// add a listener so that bindings for individual datastore are added lazily to avoid
// dozens of individual call to "graphdesc" when the tree is built.
newBranch.expandedProperty().addListener(new GraphDescListener(currentPath, newBranch, tree));
}
}
tree.getInternalChildren().add(newBranch);
}
private String normalizeId(String id) {
if (id == null || id.trim().length() == 0) {
throw new IllegalArgumentException("Argument id cannot be null or blank");
}
String[] data = id.split("\\.");
return data[data.length - 1];
}
private String getJsonTree(String tabName, String argName) throws DataAdapterException, URISyntaxException {
return getJsonTree(tabName, argName, null);
}
private String getJsonTree(String tabName, String argName, String argValue) throws DataAdapterException, URISyntaxException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("tab", tabName));
if (argName != null && argValue != null && argValue.trim().length() > 0) {
params.add(new BasicNameValuePair(argName, argValue));
}
String entityString = doHttpGet(craftRequestUri("jsontree", params), new BasicResponseHandler());
logger.trace(entityString);
return entityString;
}
private Graphdesc getGraphDescriptor(String id) throws DataAdapterException {
URI requestUri = craftRequestUri("graphdesc", new BasicNameValuePair("id", id));
return doHttpGet(requestUri, response -> {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 404) {
// This is probably an older version of JRDS that doesn't provide the graphdesc service,
// so we're falling back to recovering the datastore name from the csv file provided by
// the download service.
logger.warn("Cannot found graphdesc service; falling back to legacy mode.");
try {
return getGraphDescriptorLegacy(id);
} catch (Exception e) {
throw new IOException("", e);
}
}
HttpEntity entity = response.getEntity();
if (statusLine.getStatusCode() >= 300) {
EntityUtils.consume(entity);
throw new HttpResponseException(statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
if (entity != null) {
try {
return JAXB.unmarshal(XmlUtils.toNonValidatingSAXSource(entity.getContent()), Graphdesc.class);
} catch (Exception e) {
throw new IOException("Failed to unmarshall graphdesc response", e);
}
}
return null;
});
}
private Graphdesc getGraphDescriptorLegacy(String id) throws DataAdapterException {
Instant now = ZonedDateTime.now().toInstant();
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
try (InputStream in = fetchRawData(id, now.minusSeconds(300), now, false)) {
List<String> headers = getDecoder().getDataColumnHeaders(in);
Graphdesc desc = new Graphdesc();
desc.seriesDescList = new ArrayList<>();
for (String header : headers) {
Graphdesc.SeriesDesc d = new Graphdesc.SeriesDesc();
d.name = header;
desc.seriesDescList.add(d);
}
return desc;
}
} catch (IOException e) {
throw new FetchingDataFromAdapterException(e);
}
}
private class GraphDescListener implements ChangeListener<Boolean> {
private final String currentPath;
private final FilterableTreeItem<TimeSeriesBinding> newBranch;
private final FilterableTreeItem<TimeSeriesBinding> tree;
public GraphDescListener(String currentPath, FilterableTreeItem<TimeSeriesBinding> newBranch, FilterableTreeItem<TimeSeriesBinding> tree) {
this.currentPath = currentPath;
this.newBranch = newBranch;
this.tree = tree;
}
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (newValue) {
try {
Graphdesc graphdesc = getGraphDescriptor(currentPath);
newBranch.setValue(bindingFactory.of(tree.getValue().getTreeHierarchy(), newBranch.getValue().getLegend(), graphdesc, currentPath, JrdsDataAdapter.this));
for (int i = 0; i < graphdesc.seriesDescList.size(); i++) {
String graphType = graphdesc.seriesDescList.get(i).graphType;
if (!"none".equalsIgnoreCase(graphType) && !"comment".equalsIgnoreCase(graphType)) {
newBranch.getInternalChildren().add(new FilterableTreeItem<>(bindingFactory.of(newBranch.getValue().getTreeHierarchy(), graphdesc, i, currentPath, JrdsDataAdapter.this)));
}
}
//remove dummy node
newBranch.getInternalChildren().remove(0);
// remove the listener so it isn't executed next time node is expanded
newBranch.expandedProperty().removeListener(this);
} catch (Exception e) {
Dialogs.notifyException("Failed to retrieve graph description", e);
}
}
}
}
private class FilteredViewListener implements ChangeListener<Boolean> {
private final JsonJrdsItem n;
private final FilterableTreeItem<TimeSeriesBinding> newBranch;
public FilteredViewListener(JsonJrdsItem n, FilterableTreeItem<TimeSeriesBinding> newBranch) {
this.n = n;
this.newBranch = newBranch;
}
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (newValue) {
try {
JsonJrdsTree t = new Gson().fromJson(getJsonTree(treeViewTab.getCommand(), JRDS_FILTER, n.name), JsonJrdsTree.class);
Map<String, JsonJrdsItem> m = Arrays.stream(t.items).collect(Collectors.toMap(o -> o.id, (o -> o)));
for (JsonJrdsItem branch : Arrays.stream(t.items).filter(jsonJrdsItem -> JRDS_TREE.equals(jsonJrdsItem.type) || JRDS_FILTER.equals(jsonJrdsItem.type)).collect(Collectors.toList())) {
attachNode(newBranch, branch.id, m);
}
//remove dummy node
newBranch.getInternalChildren().remove(0);
// remove the listener so it isn't executed next time node is expanded
newBranch.expandedProperty().removeListener(this);
} catch (Exception e) {
Dialogs.notifyException("Failed to retrieve graph description", e);
}
}
}
}
}
| binjr-adapter-jrds/src/main/java/eu/binjr/sources/jrds/adapters/JrdsDataAdapter.java | /*
* Copyright 2016-2018 Frederic Thevenet
*
* 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 eu.binjr.sources.jrds.adapters;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import eu.binjr.core.data.adapters.HttpDataAdapter;
import eu.binjr.core.data.adapters.SerializedDataAdapter;
import eu.binjr.core.data.adapters.TimeSeriesBinding;
import eu.binjr.core.data.codec.csv.CsvDecoder;
import eu.binjr.core.data.exceptions.*;
import eu.binjr.core.data.timeseries.DoubleTimeSeriesProcessor;
import eu.binjr.core.dialogs.Dialogs;
import eu.binjr.sources.jrds.adapters.json.JsonJrdsItem;
import eu.binjr.sources.jrds.adapters.json.JsonJrdsTree;
import eu.binjr.common.xml.XmlUtils;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.fx.ui.controls.tree.FilterableTreeItem;
import javax.xml.bind.JAXB;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* This class provides an implementation of {@link SerializedDataAdapter} for JRDS.
*
* @author Frederic Thevenet
*/
@XmlAccessorType(XmlAccessType.FIELD)
public class JrdsDataAdapter extends HttpDataAdapter {
private static final Logger logger = LogManager.getLogger(JrdsDataAdapter.class);
private static final char DELIMITER = ',';
public static final String JRDS_FILTER = "filter";
public static final String JRDS_TREE = "tree";
protected static final String ENCODING_PARAM_NAME = "encoding";
protected static final String ZONE_ID_PARAM_NAME = "zoneId";
protected static final String TREE_VIEW_TAB_PARAM_NAME = "treeViewTab";
private final JrdsSeriesBindingFactory bindingFactory = new JrdsSeriesBindingFactory();
private final static Pattern uriSchemePattern = Pattern.compile("^[a-zA-Z]*://");
private String filter;
private ZoneId zoneId;
private String encoding;
private JrdsTreeViewTab treeViewTab;
/**
* Initialises a new instance of the {@link JrdsDataAdapter} class.
*
* @throws DataAdapterException if an error occurs while initializing the adapter.
*/
public JrdsDataAdapter() throws DataAdapterException {
super();
}
/**
* Initializes a new instance of the {@link JrdsDataAdapter} class.
*
* @param baseURL the URL to the JRDS webapp.
* @param zoneId the id of the time zone used to record dates.
* @param encoding the encoding used by the download servlet.
* @param treeViewTab the tab to apply.
* @param filter the filter to apply to the tree view.
* @throws DataAdapterException if an error occurs while initializing the adapter.
*/
public JrdsDataAdapter(URL baseURL, ZoneId zoneId, String encoding, JrdsTreeViewTab treeViewTab, String filter) throws DataAdapterException {
super(baseURL);
this.zoneId = zoneId;
this.encoding = encoding;
this.treeViewTab = treeViewTab;
this.filter = filter;
}
/**
* Builds a new instance of the {@link JrdsDataAdapter} class from the provided parameters.
*
* @param address the URL to the JRDS webapp.
* @param zoneId the id of the time zone used to record dates.
* @param treeViewTab the tab to apply.
* @param filter the filter to apply to the tree view.
* @return a new instance of the {@link JrdsDataAdapter} class.
* @throws DataAdapterException if an error occurs while initializing the adapter.
*/
public static JrdsDataAdapter fromUrl(String address, ZoneId zoneId, JrdsTreeViewTab treeViewTab, String filter) throws DataAdapterException {
try {
// Detect if URL protocol is present. If not, assume http.
if (!uriSchemePattern.matcher(address).find()) {
address = "http://" + address;
}
URL url = new URL(address.trim());
if (url.getHost().trim().isEmpty()) {
throw new CannotInitializeDataAdapterException("Malformed URL: no host");
}
return new JrdsDataAdapter(url, zoneId, "utf-8", treeViewTab, filter);
} catch (MalformedURLException e) {
throw new CannotInitializeDataAdapterException("Malformed URL: " + e.getMessage(), e);
}
}
//region [DataAdapter Members]
@Override
public FilterableTreeItem<TimeSeriesBinding> getBindingTree() throws DataAdapterException {
Gson gson = new Gson();
try {
JsonJrdsTree t = gson.fromJson(getJsonTree(treeViewTab.getCommand(), treeViewTab.getArgument(), filter), JsonJrdsTree.class);
Map<String, JsonJrdsItem> m = Arrays.stream(t.items).collect(Collectors.toMap(o -> o.id, (o -> o)));
FilterableTreeItem<TimeSeriesBinding> tree = new FilterableTreeItem<>(bindingFactory.of("", getSourceName(), "/", this));
for (JsonJrdsItem branch : Arrays.stream(t.items).filter(jsonJrdsItem -> JRDS_TREE.equals(jsonJrdsItem.type) || JRDS_FILTER.equals(jsonJrdsItem.type)).collect(Collectors.toList())) {
attachNode(tree, branch.id, m);
}
return tree;
} catch (JsonParseException e) {
throw new DataAdapterException("An error occurred while parsing the json response to getBindingTree request", e);
} catch (URISyntaxException e) {
throw new SourceCommunicationException("Error building URI for request", e);
}
}
@Override
protected URI craftFetchUri(String path, Instant begin, Instant end) throws DataAdapterException {
return craftRequestUri("download",
new BasicNameValuePair("id", path),
new BasicNameValuePair("begin", Long.toString(begin.toEpochMilli())),
new BasicNameValuePair("end", Long.toString(end.toEpochMilli()))
);
}
@Override
public String getSourceName() {
return new StringBuilder("[JRDS] ")
.append(getBaseAddress() != null ? getBaseAddress().getHost() : "???")
.append((getBaseAddress() != null && getBaseAddress().getPort() > 0) ? ":" + getBaseAddress().getPort() : "")
.append(" - ")
.append(treeViewTab != null ? treeViewTab : "???")
.append(filter != null ? filter : "")
.append(" (")
.append(zoneId != null ? zoneId : "???")
.append(")").toString();
}
@Override
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<>(super.getParams());
params.put(ZONE_ID_PARAM_NAME, zoneId.toString());
params.put(ENCODING_PARAM_NAME, encoding);
params.put(TREE_VIEW_TAB_PARAM_NAME, treeViewTab.name());
params.put(JRDS_FILTER, this.filter);
return params;
}
@Override
public void loadParams(Map<String, String> params) throws DataAdapterException {
if (params == null) {
throw new InvalidAdapterParameterException("Could not find parameter list for adapter " + getSourceName());
}
super.loadParams(params);
encoding = validateParameterNullity(params, ENCODING_PARAM_NAME);
zoneId = validateParameter(params, ZONE_ID_PARAM_NAME,
s -> {
if (s == null) {
throw new InvalidAdapterParameterException("Parameter " + ZONE_ID_PARAM_NAME + " is missing in adapter " + getSourceName());
}
return ZoneId.of(s);
});
treeViewTab = validateParameter(params, TREE_VIEW_TAB_PARAM_NAME, s -> s == null ? JrdsTreeViewTab.valueOf(params.get(TREE_VIEW_TAB_PARAM_NAME)) : JrdsTreeViewTab.HOSTS_TAB);
this.filter = params.get(JRDS_FILTER);
}
@Override
public String getEncoding() {
return encoding;
}
@Override
public ZoneId getTimeZoneId() {
return zoneId;
}
@Override
public CsvDecoder getDecoder() {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(getTimeZoneId());
return new CsvDecoder(getEncoding(), DELIMITER,
DoubleTimeSeriesProcessor::new,
s -> {
Double val = Double.parseDouble(s);
return val.isNaN() ? 0 : val;
},
s -> ZonedDateTime.parse(s, formatter));
}
@Override
public void close() {
super.close();
}
//endregion
public Collection<String> discoverFilters() throws DataAdapterException, URISyntaxException {
Gson gson = new Gson();
try {
JsonJrdsTree t = gson.fromJson(getJsonTree(treeViewTab.getCommand(), treeViewTab.getArgument()), JsonJrdsTree.class);
return Arrays.stream(t.items).filter(jsonJrdsItem -> JRDS_FILTER.equals(jsonJrdsItem.type)).map(i -> i.filter).collect(Collectors.toList());
} catch (JsonParseException e) {
throw new DataAdapterException("An error occurred while parsing the json response to getBindingTree request", e);
}
}
private void attachNode(FilterableTreeItem<TimeSeriesBinding> tree, String id, Map<String, JsonJrdsItem> nodes) throws DataAdapterException {
JsonJrdsItem n = nodes.get(id);
String currentPath = normalizeId(n.id);
FilterableTreeItem<TimeSeriesBinding> newBranch = new FilterableTreeItem<>(bindingFactory.of(tree.getValue().getTreeHierarchy(), n.name, currentPath, this));
if (JRDS_FILTER.equals(n.type)) {
// add a dummy node so that the branch can be expanded
newBranch.getInternalChildren().add(new FilterableTreeItem<>(null));
// add a listener that will get the treeview filtered according to the selected filter/tag
newBranch.expandedProperty().addListener(new FilteredViewListener(n, newBranch));
} else {
if (n.children != null) {
for (JsonJrdsItem.JsonTreeRef ref : n.children) {
attachNode(newBranch, ref._reference, nodes);
}
} else {
// add a dummy node so that the branch can be expanded
newBranch.getInternalChildren().add(new FilterableTreeItem<>(null));
// add a listener so that bindings for individual datastore are added lazily to avoid
// dozens of individual call to "graphdesc" when the tree is built.
newBranch.expandedProperty().addListener(new GraphDescListener(currentPath, newBranch, tree));
}
}
tree.getInternalChildren().add(newBranch);
}
private String normalizeId(String id) {
if (id == null || id.trim().length() == 0) {
throw new IllegalArgumentException("Argument id cannot be null or blank");
}
String[] data = id.split("\\.");
return data[data.length - 1];
}
private String getJsonTree(String tabName, String argName) throws DataAdapterException, URISyntaxException {
return getJsonTree(tabName, argName, null);
}
private String getJsonTree(String tabName, String argName, String argValue) throws DataAdapterException, URISyntaxException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("tab", tabName));
if (argName != null && argValue != null && argValue.trim().length() > 0) {
params.add(new BasicNameValuePair(argName, argValue));
}
String entityString = doHttpGet(craftRequestUri("jsontree", params), new BasicResponseHandler());
logger.trace(entityString);
return entityString;
}
private Graphdesc getGraphDescriptor(String id) throws DataAdapterException {
URI requestUri = craftRequestUri("graphdesc", new BasicNameValuePair("id", id));
return doHttpGet(requestUri, response -> {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 404) {
// This is probably an older version of JRDS that doesn't provide the graphdesc service,
// so we're falling back to recovering the datastore name from the csv file provided by
// the download service.
logger.warn("Cannot found graphdesc service; falling back to legacy mode.");
try {
return getGraphDescriptorLegacy(id);
} catch (Exception e) {
throw new IOException("", e);
}
}
HttpEntity entity = response.getEntity();
if (statusLine.getStatusCode() >= 300) {
EntityUtils.consume(entity);
throw new HttpResponseException(statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
if (entity != null) {
try {
return JAXB.unmarshal(XmlUtils.toNonValidatingSAXSource(entity.getContent()), Graphdesc.class);
} catch (Exception e) {
throw new IOException("Failed to unmarshall graphdesc response", e);
}
}
return null;
});
}
private Graphdesc getGraphDescriptorLegacy(String id) throws DataAdapterException {
Instant now = ZonedDateTime.now().toInstant();
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
try (InputStream in = fetchRawData(id, now.minusSeconds(300), now, false)) {
List<String> headers = getDecoder().getDataColumnHeaders(in);
Graphdesc desc = new Graphdesc();
desc.seriesDescList = new ArrayList<>();
for (String header : headers) {
Graphdesc.SeriesDesc d = new Graphdesc.SeriesDesc();
d.name = header;
desc.seriesDescList.add(d);
}
return desc;
}
} catch (IOException e) {
throw new FetchingDataFromAdapterException(e);
}
}
private class GraphDescListener implements ChangeListener<Boolean> {
private final String currentPath;
private final FilterableTreeItem<TimeSeriesBinding> newBranch;
private final FilterableTreeItem<TimeSeriesBinding> tree;
public GraphDescListener(String currentPath, FilterableTreeItem<TimeSeriesBinding> newBranch, FilterableTreeItem<TimeSeriesBinding> tree) {
this.currentPath = currentPath;
this.newBranch = newBranch;
this.tree = tree;
}
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (newValue) {
try {
Graphdesc graphdesc = getGraphDescriptor(currentPath);
newBranch.setValue(bindingFactory.of(tree.getValue().getTreeHierarchy(), newBranch.getValue().getLegend(), graphdesc, currentPath, JrdsDataAdapter.this));
for (int i = 0; i < graphdesc.seriesDescList.size(); i++) {
String graphType = graphdesc.seriesDescList.get(i).graphType;
if (!"none".equalsIgnoreCase(graphType) && !"comment".equalsIgnoreCase(graphType)) {
newBranch.getInternalChildren().add(new FilterableTreeItem<>(bindingFactory.of(newBranch.getValue().getTreeHierarchy(), graphdesc, i, currentPath, JrdsDataAdapter.this)));
}
}
//remove dummy node
newBranch.getInternalChildren().remove(0);
// remove the listener so it isn't executed next time node is expanded
newBranch.expandedProperty().removeListener(this);
} catch (Exception e) {
Dialogs.notifyException("Failed to retrieve graph description", e);
}
}
}
}
private class FilteredViewListener implements ChangeListener<Boolean> {
private final JsonJrdsItem n;
private final FilterableTreeItem<TimeSeriesBinding> newBranch;
public FilteredViewListener(JsonJrdsItem n, FilterableTreeItem<TimeSeriesBinding> newBranch) {
this.n = n;
this.newBranch = newBranch;
}
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (newValue) {
try {
JsonJrdsTree t = new Gson().fromJson(getJsonTree(treeViewTab.getCommand(), JRDS_FILTER, n.name), JsonJrdsTree.class);
Map<String, JsonJrdsItem> m = Arrays.stream(t.items).collect(Collectors.toMap(o -> o.id, (o -> o)));
for (JsonJrdsItem branch : Arrays.stream(t.items).filter(jsonJrdsItem -> JRDS_TREE.equals(jsonJrdsItem.type) || JRDS_FILTER.equals(jsonJrdsItem.type)).collect(Collectors.toList())) {
attachNode(newBranch, branch.id, m);
}
//remove dummy node
newBranch.getInternalChildren().remove(0);
// remove the listener so it isn't executed next time node is expanded
newBranch.expandedProperty().removeListener(this);
} catch (Exception e) {
Dialogs.notifyException("Failed to retrieve graph description", e);
}
}
}
}
}
| CsvDecoder should not be re-instantiated each time it is called.
| binjr-adapter-jrds/src/main/java/eu/binjr/sources/jrds/adapters/JrdsDataAdapter.java | CsvDecoder should not be re-instantiated each time it is called. |
|
Java | apache-2.0 | a7ef14229dedc9105dc364e9d771cee093e8de6c | 0 | jackminicloud/test,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,Overruler/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,hdost/gerrit,Team-OctOS/host_gerrit,Saulis/gerrit,supriyantomaftuh/gerrit,gerrit-review/gerrit,pkdevbox/gerrit,thesamet/gerrit,hdost/gerrit,jackminicloud/test,dwhipstock/gerrit,supriyantomaftuh/gerrit,GerritCodeReview/gerrit,pkdevbox/gerrit,Saulis/gerrit,gcoders/gerrit,qtproject/qtqa-gerrit,TonyChai24/test,MerritCR/merrit,gcoders/gerrit,MerritCR/merrit,TonyChai24/test,hdost/gerrit,GerritCodeReview/gerrit,Seinlin/gerrit,gerrit-review/gerrit,thesamet/gerrit,supriyantomaftuh/gerrit,anminhsu/gerrit,Overruler/gerrit,renchaorevee/gerrit,gcoders/gerrit,joshuawilson/merrit,gcoders/gerrit,Seinlin/gerrit,jackminicloud/test,Overruler/gerrit,dwhipstock/gerrit,jackminicloud/test,dwhipstock/gerrit,TonyChai24/test,TonyChai24/test,Team-OctOS/host_gerrit,pkdevbox/gerrit,thinkernel/gerrit,MerritCR/merrit,jackminicloud/test,quyixia/gerrit,gcoders/gerrit,Team-OctOS/host_gerrit,thinkernel/gerrit,Overruler/gerrit,GerritCodeReview/gerrit,renchaorevee/gerrit,TonyChai24/test,thinkernel/gerrit,WANdisco/gerrit,Seinlin/gerrit,netroby/gerrit,Saulis/gerrit,MerritCR/merrit,hdost/gerrit,supriyantomaftuh/gerrit,gerrit-review/gerrit,WANdisco/gerrit,jackminicloud/test,Distrotech/gerrit,netroby/gerrit,Seinlin/gerrit,Team-OctOS/host_gerrit,thesamet/gerrit,hdost/gerrit,quyixia/gerrit,hdost/gerrit,Saulis/gerrit,thinkernel/gerrit,Seinlin/gerrit,renchaorevee/gerrit,WANdisco/gerrit,joshuawilson/merrit,TonyChai24/test,Seinlin/gerrit,quyixia/gerrit,netroby/gerrit,Saulis/gerrit,Distrotech/gerrit,qtproject/qtqa-gerrit,MerritCR/merrit,renchaorevee/gerrit,anminhsu/gerrit,dwhipstock/gerrit,MerritCR/merrit,MerritCR/merrit,thinkernel/gerrit,thesamet/gerrit,qtproject/qtqa-gerrit,quyixia/gerrit,Overruler/gerrit,joshuawilson/merrit,Distrotech/gerrit,renchaorevee/gerrit,GerritCodeReview/gerrit,anminhsu/gerrit,Team-OctOS/host_gerrit,anminhsu/gerrit,Distrotech/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,pkdevbox/gerrit,quyixia/gerrit,netroby/gerrit,quyixia/gerrit,jackminicloud/test,joshuawilson/merrit,Distrotech/gerrit,Seinlin/gerrit,gerrit-review/gerrit,thesamet/gerrit,pkdevbox/gerrit,Distrotech/gerrit,WANdisco/gerrit,thinkernel/gerrit,renchaorevee/gerrit,dwhipstock/gerrit,WANdisco/gerrit,netroby/gerrit,renchaorevee/gerrit,gcoders/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,supriyantomaftuh/gerrit,joshuawilson/merrit,pkdevbox/gerrit,TonyChai24/test,netroby/gerrit,thesamet/gerrit,joshuawilson/merrit,WANdisco/gerrit,Distrotech/gerrit,anminhsu/gerrit,thesamet/gerrit,gerrit-review/gerrit,Team-OctOS/host_gerrit,gerrit-review/gerrit,pkdevbox/gerrit,gcoders/gerrit,Team-OctOS/host_gerrit,netroby/gerrit,hdost/gerrit,GerritCodeReview/gerrit,Saulis/gerrit,joshuawilson/merrit,anminhsu/gerrit,dwhipstock/gerrit,GerritCodeReview/gerrit,Overruler/gerrit,thinkernel/gerrit,supriyantomaftuh/gerrit,quyixia/gerrit,MerritCR/merrit,supriyantomaftuh/gerrit,anminhsu/gerrit,joshuawilson/merrit,dwhipstock/gerrit | // Copyright (C) 2013 The Android Open Source Project
//
// 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.google.gerrit.server.change;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.gerrit.extensions.events.GitReferenceUpdatedListener;
import com.google.gerrit.extensions.restapi.ResourceConflictException;
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.change.MergeabilityChecksExecutor.Priority;
import com.google.gerrit.server.change.Mergeable.MergeableInfo;
import com.google.gerrit.server.git.MetaDataUpdate;
import com.google.gerrit.server.git.ProjectConfig;
import com.google.gerrit.server.git.WorkQueue.Executor;
import com.google.gerrit.server.index.ChangeIndexer;
import com.google.gerrit.server.project.ChangeControl;
import com.google.gerrit.server.util.RequestContext;
import com.google.gerrit.server.util.ThreadLocalRequestContext;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.SchemaFactory;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.ProvisionException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
public class MergeabilityChecker implements GitReferenceUpdatedListener {
private static final Logger log = LoggerFactory
.getLogger(MergeabilityChecker.class);
private static final Function<Exception, IOException> MAPPER =
new Function<Exception, IOException>() {
@Override
public IOException apply(Exception in) {
if (in instanceof IOException) {
return (IOException) in;
} else if (in instanceof ExecutionException
&& in.getCause() instanceof IOException) {
return (IOException) in.getCause();
} else {
return new IOException(in);
}
}
};
public class Check {
private List<Change> changes;
private List<Branch.NameKey> branches;
private List<Project.NameKey> projects;
private boolean force;
private boolean reindex;
private boolean interactive;
private Check() {
changes = Lists.newArrayListWithExpectedSize(1);
branches = Lists.newArrayListWithExpectedSize(1);
projects = Lists.newArrayListWithExpectedSize(1);
interactive = true;
}
public Check addChange(Change change) {
changes.add(change);
return this;
}
public Check addBranch(Branch.NameKey branch) {
branches.add(branch);
interactive = false;
return this;
}
public Check addProject(Project.NameKey project) {
projects.add(project);
interactive = false;
return this;
}
/** Force reindexing regardless of whether mergeable flag was modified. */
public Check reindex() {
reindex = true;
return this;
}
/** Force mergeability check even if change is not stale. */
private Check force() {
force = true;
return this;
}
private ListeningExecutorService getExecutor() {
return interactive ? interactiveExecutor : backgroundExecutor;
}
public CheckedFuture<?, IOException> runAsync() {
final ListeningExecutorService executor = getExecutor();
ListenableFuture<List<Change>> getChanges;
if (branches.isEmpty() && projects.isEmpty()) {
getChanges = Futures.immediateFuture(changes);
} else {
getChanges = executor.submit(
new Callable<List<Change>>() {
@Override
public List<Change> call() throws OrmException {
return getChanges();
}
});
}
return Futures.makeChecked(Futures.transform(getChanges,
new AsyncFunction<List<Change>, List<Object>>() {
@Override
public ListenableFuture<List<Object>> apply(List<Change> changes) {
List<ListenableFuture<?>> result =
Lists.newArrayListWithCapacity(changes.size());
for (final Change c : changes) {
ListenableFuture<Boolean> b =
executor.submit(new Task(c, force));
if (reindex) {
result.add(Futures.transform(
b, new AsyncFunction<Boolean, Object>() {
@SuppressWarnings("unchecked")
@Override
public ListenableFuture<Object> apply(
Boolean indexUpdated) throws Exception {
if (!indexUpdated) {
return (ListenableFuture<Object>)
indexer.indexAsync(c.getId());
}
return Futures.immediateFuture(null);
}
}));
} else {
result.add(b);
}
}
return Futures.allAsList(result);
}
}), MAPPER);
}
public void run() throws IOException {
try {
runAsync().checkedGet();
} catch (Exception e) {
Throwables.propagateIfPossible(e, IOException.class);
throw MAPPER.apply(e);
}
}
private List<Change> getChanges() throws OrmException {
ReviewDb db = schemaFactory.open();
try {
List<Change> results = Lists.newArrayList();
results.addAll(changes);
for (Project.NameKey p : projects) {
Iterables.addAll(results, db.changes().byProjectOpenAll(p));
}
for (Branch.NameKey b : branches) {
Iterables.addAll(results, db.changes().byBranchOpenAll(b));
}
return results;
} catch (OrmException e) {
log.error("Failed to fetch changes for mergeability check", e);
throw e;
} finally {
db.close();
}
}
}
private final ThreadLocalRequestContext tl;
private final SchemaFactory<ReviewDb> schemaFactory;
private final IdentifiedUser.GenericFactory identifiedUserFactory;
private final ChangeControl.GenericFactory changeControlFactory;
private final Provider<Mergeable> mergeable;
private final ChangeIndexer indexer;
private final ListeningExecutorService backgroundExecutor;
private final ListeningExecutorService interactiveExecutor;
private final MergeabilityCheckQueue mergeabilityCheckQueue;
private final MetaDataUpdate.Server metaDataUpdateFactory;
@Inject
public MergeabilityChecker(ThreadLocalRequestContext tl,
SchemaFactory<ReviewDb> schemaFactory,
IdentifiedUser.GenericFactory identifiedUserFactory,
ChangeControl.GenericFactory changeControlFactory,
Provider<Mergeable> mergeable, ChangeIndexer indexer,
@MergeabilityChecksExecutor(Priority.BACKGROUND)
Executor backgroundExecutor,
@MergeabilityChecksExecutor(Priority.INTERACTIVE)
Executor interactiveExecutor,
MergeabilityCheckQueue mergeabilityCheckQueue,
MetaDataUpdate.Server metaDataUpdateFactory) {
this.tl = tl;
this.schemaFactory = schemaFactory;
this.identifiedUserFactory = identifiedUserFactory;
this.changeControlFactory = changeControlFactory;
this.mergeable = mergeable;
this.indexer = indexer;
this.backgroundExecutor =
MoreExecutors.listeningDecorator(backgroundExecutor);
this.interactiveExecutor =
MoreExecutors.listeningDecorator(interactiveExecutor);
this.mergeabilityCheckQueue = mergeabilityCheckQueue;
this.metaDataUpdateFactory = metaDataUpdateFactory;
}
public Check newCheck() {
return new Check();
}
@Override
public void onGitReferenceUpdated(GitReferenceUpdatedListener.Event event) {
String ref = event.getRefName();
if (ref.startsWith(Constants.R_HEADS) || ref.equals(RefNames.REFS_CONFIG)) {
Branch.NameKey branch = new Branch.NameKey(
new Project.NameKey(event.getProjectName()), ref);
newCheck().addBranch(branch).runAsync();
}
if (ref.equals(RefNames.REFS_CONFIG)) {
Project.NameKey p = new Project.NameKey(event.getProjectName());
try {
ProjectConfig oldCfg = parseConfig(p, event.getOldObjectId());
ProjectConfig newCfg = parseConfig(p, event.getNewObjectId());
if (recheckMerges(oldCfg, newCfg)) {
newCheck().addProject(p).force().runAsync();
}
} catch (ConfigInvalidException | IOException e) {
String msg = "Failed to update mergeability flags for project " + p.get()
+ " on update of " + RefNames.REFS_CONFIG;
log.error(msg, e);
throw new RuntimeException(msg, e);
}
}
}
private boolean recheckMerges(ProjectConfig oldCfg, ProjectConfig newCfg) {
if (oldCfg == null || newCfg == null) {
return true;
}
return !oldCfg.getProject().getSubmitType().equals(newCfg.getProject().getSubmitType())
|| oldCfg.getProject().getUseContentMerge() != newCfg.getProject().getUseContentMerge()
|| (oldCfg.getRulesId() == null
? newCfg.getRulesId() != null
: !oldCfg.getRulesId().equals(newCfg.getRulesId()));
}
private ProjectConfig parseConfig(Project.NameKey p, String idStr)
throws IOException, ConfigInvalidException, RepositoryNotFoundException {
ObjectId id = ObjectId.fromString(idStr);
if (ObjectId.zeroId().equals(id)) {
return null;
}
return ProjectConfig.read(metaDataUpdateFactory.create(p), id);
}
private class Task implements Callable<Boolean> {
private final Change change;
private final boolean force;
private ReviewDb reviewDb;
Task(Change change, boolean force) {
this.change = change;
this.force = force;
}
@Override
public Boolean call() throws Exception {
mergeabilityCheckQueue.updatingMergeabilityFlag(change, force);
RequestContext context = new RequestContext() {
@Override
public CurrentUser getCurrentUser() {
return identifiedUserFactory.create(change.getOwner());
}
@Override
public Provider<ReviewDb> getReviewDbProvider() {
return new Provider<ReviewDb>() {
@Override
public ReviewDb get() {
if (reviewDb == null) {
try {
reviewDb = schemaFactory.open();
} catch (OrmException e) {
throw new ProvisionException("Cannot open ReviewDb", e);
}
}
return reviewDb;
}
};
}
};
RequestContext old = tl.setContext(context);
ReviewDb db = context.getReviewDbProvider().get();
try {
PatchSet ps = db.patchSets().get(change.currentPatchSetId());
if (ps == null) {
// Cannot compute mergeability if current patch set is missing.
return false;
}
Mergeable m = mergeable.get();
m.setForce(force);
ChangeControl control =
changeControlFactory.controlFor(change.getId(), context.getCurrentUser());
MergeableInfo info = m.apply(
new RevisionResource(new ChangeResource(control), ps));
return change.isMergeable() != info.mergeable;
} catch (ResourceConflictException e) {
// change is closed
return false;
} catch (Exception e) {
String msg = "Failed to update mergeability flags for project "
+ change.getDest().getParentKey() + " on update of "
+ change.getDest().get();
log.error(msg, e);
throw e;
} finally {
tl.setContext(old);
if (reviewDb != null) {
reviewDb.close();
reviewDb = null;
}
}
}
}
}
| gerrit-server/src/main/java/com/google/gerrit/server/change/MergeabilityChecker.java | // Copyright (C) 2013 The Android Open Source Project
//
// 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.google.gerrit.server.change;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.gerrit.extensions.events.GitReferenceUpdatedListener;
import com.google.gerrit.extensions.restapi.ResourceConflictException;
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.change.MergeabilityChecksExecutor.Priority;
import com.google.gerrit.server.change.Mergeable.MergeableInfo;
import com.google.gerrit.server.git.MetaDataUpdate;
import com.google.gerrit.server.git.ProjectConfig;
import com.google.gerrit.server.git.WorkQueue.Executor;
import com.google.gerrit.server.index.ChangeIndexer;
import com.google.gerrit.server.project.ChangeControl;
import com.google.gerrit.server.util.RequestContext;
import com.google.gerrit.server.util.ThreadLocalRequestContext;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.SchemaFactory;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.ProvisionException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
public class MergeabilityChecker implements GitReferenceUpdatedListener {
private static final Logger log = LoggerFactory
.getLogger(MergeabilityChecker.class);
private static final Function<Exception, IOException> MAPPER =
new Function<Exception, IOException>() {
@Override
public IOException apply(Exception in) {
if (in instanceof IOException) {
return (IOException) in;
} else if (in instanceof ExecutionException
&& in.getCause() instanceof IOException) {
return (IOException) in.getCause();
} else {
return new IOException(in);
}
}
};
public class Check {
private List<Change> changes;
private List<Branch.NameKey> branches;
private List<Project.NameKey> projects;
private boolean force;
private boolean reindex;
private boolean interactive;
private Check() {
changes = Lists.newArrayListWithExpectedSize(1);
branches = Lists.newArrayListWithExpectedSize(1);
projects = Lists.newArrayListWithExpectedSize(1);
interactive = true;
}
public Check addChange(Change change) {
changes.add(change);
return this;
}
public Check addBranch(Branch.NameKey branch) {
branches.add(branch);
interactive = false;
return this;
}
public Check addProject(Project.NameKey project) {
projects.add(project);
interactive = false;
return this;
}
/** Force reindexing regardless of whether mergeable flag was modified. */
public Check reindex() {
reindex = true;
return this;
}
/** Force mergeability check even if change is not stale. */
private Check force() {
force = true;
return this;
}
private ListeningExecutorService getExecutor() {
return interactive ? interactiveExecutor : backgroundExecutor;
}
public CheckedFuture<?, IOException> runAsync() {
final ListeningExecutorService executor = getExecutor();
ListenableFuture<List<Change>> getChanges;
if (branches.isEmpty() && projects.isEmpty()) {
getChanges = Futures.immediateFuture(changes);
} else {
getChanges = executor.submit(
new Callable<List<Change>>() {
@Override
public List<Change> call() throws OrmException {
return getChanges();
}
});
}
return Futures.makeChecked(Futures.transform(getChanges,
new AsyncFunction<List<Change>, List<Object>>() {
@Override
public ListenableFuture<List<Object>> apply(List<Change> changes) {
List<ListenableFuture<?>> result =
Lists.newArrayListWithCapacity(changes.size());
for (final Change c : changes) {
ListenableFuture<Boolean> b =
executor.submit(new Task(c, force));
if (reindex) {
result.add(Futures.transform(
b, new AsyncFunction<Boolean, Object>() {
@SuppressWarnings("unchecked")
@Override
public ListenableFuture<Object> apply(
Boolean indexUpdated) throws Exception {
if (!indexUpdated) {
return (ListenableFuture<Object>)
indexer.indexAsync(c.getId());
}
return Futures.immediateFuture(null);
}
}));
} else {
result.add(b);
}
}
return Futures.allAsList(result);
}
}), MAPPER);
}
public void run() throws IOException {
try {
runAsync().checkedGet();
} catch (Exception e) {
Throwables.propagateIfPossible(e, IOException.class);
throw MAPPER.apply(e);
}
}
private List<Change> getChanges() throws OrmException {
ReviewDb db = schemaFactory.open();
try {
List<Change> results = Lists.newArrayList();
results.addAll(changes);
for (Project.NameKey p : projects) {
Iterables.addAll(results, db.changes().byProjectOpenAll(p));
}
for (Branch.NameKey b : branches) {
Iterables.addAll(results, db.changes().byBranchOpenAll(b));
}
return results;
} catch (OrmException e) {
log.error("Failed to fetch changes for mergeability check", e);
throw e;
} finally {
db.close();
}
}
}
private final ThreadLocalRequestContext tl;
private final SchemaFactory<ReviewDb> schemaFactory;
private final IdentifiedUser.GenericFactory identifiedUserFactory;
private final ChangeControl.GenericFactory changeControlFactory;
private final Provider<Mergeable> mergeable;
private final ChangeIndexer indexer;
private final ListeningExecutorService backgroundExecutor;
private final ListeningExecutorService interactiveExecutor;
private final MergeabilityCheckQueue mergeabilityCheckQueue;
private final MetaDataUpdate.Server metaDataUpdateFactory;
@Inject
public MergeabilityChecker(ThreadLocalRequestContext tl,
SchemaFactory<ReviewDb> schemaFactory,
IdentifiedUser.GenericFactory identifiedUserFactory,
ChangeControl.GenericFactory changeControlFactory,
Provider<Mergeable> mergeable, ChangeIndexer indexer,
@MergeabilityChecksExecutor(Priority.BACKGROUND)
Executor backgroundExecutor,
@MergeabilityChecksExecutor(Priority.INTERACTIVE)
Executor interactiveExecutor,
MergeabilityCheckQueue mergeabilityCheckQueue,
MetaDataUpdate.Server metaDataUpdateFactory) {
this.tl = tl;
this.schemaFactory = schemaFactory;
this.identifiedUserFactory = identifiedUserFactory;
this.changeControlFactory = changeControlFactory;
this.mergeable = mergeable;
this.indexer = indexer;
this.backgroundExecutor =
MoreExecutors.listeningDecorator(backgroundExecutor);
this.interactiveExecutor =
MoreExecutors.listeningDecorator(interactiveExecutor);
this.mergeabilityCheckQueue = mergeabilityCheckQueue;
this.metaDataUpdateFactory = metaDataUpdateFactory;
}
public Check newCheck() {
return new Check();
}
@Override
public void onGitReferenceUpdated(GitReferenceUpdatedListener.Event event) {
String ref = event.getRefName();
if (ref.startsWith(Constants.R_HEADS) || ref.equals(RefNames.REFS_CONFIG)) {
Branch.NameKey branch = new Branch.NameKey(
new Project.NameKey(event.getProjectName()), ref);
newCheck().addBranch(branch).runAsync();
}
if (ref.equals(RefNames.REFS_CONFIG)) {
Project.NameKey p = new Project.NameKey(event.getProjectName());
try {
ProjectConfig oldCfg = parseConfig(p, event.getOldObjectId());
ProjectConfig newCfg = parseConfig(p, event.getNewObjectId());
if (recheckMerges(oldCfg, newCfg)) {
newCheck().addProject(p).force().runAsync();
}
} catch (ConfigInvalidException | IOException e) {
String msg = "Failed to update mergeability flags for project " + p.get()
+ " on update of " + RefNames.REFS_CONFIG;
log.error(msg, e);
throw new RuntimeException(msg, e);
}
}
}
private boolean recheckMerges(ProjectConfig oldCfg, ProjectConfig newCfg) {
if (oldCfg == null || newCfg == null) {
return true;
}
return !oldCfg.getProject().getSubmitType().equals(newCfg.getProject().getSubmitType())
|| oldCfg.getProject().getUseContentMerge() != newCfg.getProject().getUseContentMerge()
|| (oldCfg.getRulesId() == null
? newCfg.getRulesId() != null
: !oldCfg.getRulesId().equals(newCfg.getRulesId()));
}
private ProjectConfig parseConfig(Project.NameKey p, String idStr)
throws IOException, ConfigInvalidException, RepositoryNotFoundException {
ObjectId id = ObjectId.fromString(idStr);
if (ObjectId.zeroId().equals(id)) {
return null;
}
return ProjectConfig.read(metaDataUpdateFactory.create(p), id);
}
private class Task implements Callable<Boolean> {
private final Change change;
private final boolean force;
private ReviewDb reviewDb;
Task(Change change, boolean force) {
this.change = change;
this.force = force;
}
@Override
public Boolean call() throws Exception {
mergeabilityCheckQueue.updatingMergeabilityFlag(change, force);
RequestContext context = new RequestContext() {
@Override
public CurrentUser getCurrentUser() {
return identifiedUserFactory.create(change.getOwner());
}
@Override
public Provider<ReviewDb> getReviewDbProvider() {
return new Provider<ReviewDb>() {
@Override
public ReviewDb get() {
if (reviewDb == null) {
try {
reviewDb = schemaFactory.open();
} catch (OrmException e) {
throw new ProvisionException("Cannot open ReviewDb", e);
}
}
return reviewDb;
}
};
}
};
RequestContext old = tl.setContext(context);
ReviewDb db = context.getReviewDbProvider().get();
try {
PatchSet ps = db.patchSets().get(change.currentPatchSetId());
Mergeable m = mergeable.get();
m.setForce(force);
ChangeControl control =
changeControlFactory.controlFor(change.getId(), context.getCurrentUser());
MergeableInfo info = m.apply(
new RevisionResource(new ChangeResource(control), ps));
return change.isMergeable() != info.mergeable;
} catch (ResourceConflictException e) {
// change is closed
return false;
} catch (Exception e) {
String msg = "Failed to update mergeability flags for project "
+ change.getDest().getParentKey() + " on update of "
+ change.getDest().get();
log.error(msg, e);
throw e;
} finally {
tl.setContext(old);
if (reviewDb != null) {
reviewDb.close();
reviewDb = null;
}
}
}
}
}
| Gracefully skip mergeability checking on broken changes
If a change is missing its current patch set the mergeablity check
will NPE. Skip the check and just return false, indicating there
was no update made to the change.
Change-Id: Ic82b2db1d2f7d27105a06c4082b51e7308f02b04
| gerrit-server/src/main/java/com/google/gerrit/server/change/MergeabilityChecker.java | Gracefully skip mergeability checking on broken changes |
|
Java | bsd-3-clause | 1bee8487a1545eb4d87e519d78e0245c99aba66c | 0 | lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon | /*
* $Id: RaiseAlert.java,v 1.13 2006-04-05 22:55:25 tlipkis Exp $
*/
/*
Copyright (c) 2000-2006 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.servlet;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;
import java.net.*;
import java.text.*;
import java.security.*;
import org.mortbay.html.*;
import org.mortbay.util.B64Code;
import org.lockss.app.*;
import org.lockss.util.*;
import org.lockss.alert.*;
import org.lockss.plugin.*;
import org.lockss.poller.*;
import org.lockss.protocol.*;
import org.lockss.daemon.*;
import org.lockss.daemon.status.*;
/** Raise an alert on demand. For testing alerts
*/
public class RaiseAlert extends LockssServlet {
static final String KEY_ACTION = "action";
static final String KEY_NAME_SEL = "name_sel";
static final String KEY_NAME_TYPE = "name_type";
static final String KEY_AUID = "auid";
static final String KEY_TEXT = "text";
static final String ACTION_RAISE = "Raise";
static final String COL2 = "colspan=2";
static final String COL2CENTER = COL2 + " align=center";
static Logger log = Logger.getLogger("RaiseAlert");
private LockssDaemon daemon;
private PluginManager pluginMgr;
private AlertManager alertMgr;
String auid;
String name;
String text;
ArchivalUnit au;
boolean showResult;
protected void resetLocals() {
resetVars();
super.resetLocals();
}
void resetVars() {
auid = null;
errMsg = null;
statusMsg = null;
}
public void init(ServletConfig config) throws ServletException {
super.init(config);
daemon = getLockssDaemon();
alertMgr = daemon.getAlertManager();
pluginMgr = daemon.getPluginManager();
}
public void lockssHandleRequest() throws IOException {
resetVars();
String action = getParameter(KEY_ACTION);
if (ACTION_RAISE.equals(action)) {
doRaise();
}
displayPage();
}
private boolean doRaise() {
auid = getParameter(KEY_AUID);
au = pluginMgr.getAuFromId(auid);
name = getParameter(KEY_NAME_SEL);
if (StringUtil.isNullString(name)) {
name = getParameter(KEY_NAME_TYPE);
}
text = getParameter(KEY_TEXT);
Alert alert;
Alert proto = findProtoAlert(name);
if (proto == null) {
proto = new Alert(name);
}
if (au != null && (proto == null ||
proto.getBool(Alert.ATTR_IS_CONTENT))) {
alert = Alert.auAlert(proto, au);
} else {
alert = Alert.cacheAlert(proto);
}
alert.setAttribute(Alert.ATTR_TEXT, text);
alertMgr.raiseAlert(alert);
return true;
}
private void displayPage() throws IOException {
Page page = newPage();
layoutErrorBlock(page);
ServletUtil.layoutExplanationBlock(page, "Raise an Alert");
page.add(makeForm());
page.add("<br>");
layoutFooter(page);
ServletUtil.writePage(resp, page);
}
void addResultRow(Table tbl, String head, Object value) {
tbl.newRow();
tbl.newCell();
tbl.add(head);
tbl.add(":");
tbl.newCell();
tbl.add(value.toString());
}
private Element makeForm() {
Composite comp = new Composite();
Block centeredBlock = new Block(Block.Center);
Form frm = new Form(srvURL(myServletDescr()));
frm.method("POST");
Table autbl = new Table(0, "cellpadding=0");
autbl.newRow();
autbl.addHeading("Select AU");
Select sel = new Select(KEY_AUID, false);
sel.add("", auid == null, "");
for (Iterator iter = pluginMgr.getAllAus().iterator(); iter.hasNext(); ) {
ArchivalUnit au0 = (ArchivalUnit)iter.next();
String id = au0.getAuId();
sel.add(au0.getName(), id.equals(auid), id);
}
autbl.newRow(); autbl.newCell();
setTabOrder(sel);
autbl.add(sel);
Table alrtbl = new Table(0, "cellpadding=0");
alrtbl.newRow();
alrtbl.addHeading("Select Alert Name");
Select sel2 = new Select(KEY_NAME_SEL, false);
sel2.add("", auid == null, "");
for (int ix = 0; ix < protoAlerts.length; ix++) {
Alert proto = protoAlerts[ix];
String aname = proto.getName();
sel2.add(aname, aname.equals(name), aname);
}
alrtbl.newRow(); alrtbl.newCell();
setTabOrder(sel2);
alrtbl.add(sel2);
Table tbl = new Table(0, "cellpadding=0");
tbl.newRow();
tbl.newCell(COL2CENTER);
tbl.add(autbl);
tbl.newRow();
tbl.newCell(COL2CENTER);
tbl.add(alrtbl);
tbl.newRow();
tbl.newCell();
tbl.add(" ");
addInputRow(tbl, "Name", KEY_NAME_TYPE, 50, name);
addInputRow(tbl, "Text", KEY_TEXT, 50, text);
centeredBlock.add(tbl);
frm.add(centeredBlock);
Input submit = new Input(Input.Submit, KEY_ACTION, ACTION_RAISE);
setTabOrder(submit);
frm.add("<br><center>"+submit+"</center>");
comp.add(frm);
return comp;
}
void addInputRow(Table tbl, String label, String key,
int size, String initVal) {
tbl.newRow();
// tbl.newCell();
tbl.addHeading(label + ":", "align=right");
tbl.newCell();
Input in = new Input(Input.Text, key, initVal);
in.setSize(size);
setTabOrder(in);
tbl.add(in);
}
Alert findProtoAlert(String name) {
if (name == null) return null;
for (int ix = 0; ix < protoAlerts.length; ix++) {
Alert proto = protoAlerts[ix];
if (name.equals(proto.getName())) {
return proto;
}
}
return null;
}
Alert[] protoAlerts = {
Alert.PERMISSION_PAGE_FETCH_ERROR,
Alert.NO_CRAWL_PERMISSION,
Alert.NEW_CONTENT,
Alert.NO_NEW_CONTENT,
Alert.VOLUME_CLOSED,
Alert.PUBLISHER_UNREACHABLE,
Alert.PUBLISHER_CONTENT_CHANGED,
Alert.DAMAGE_DETECTED,
Alert.PERSISTENT_DAMAGE,
Alert.REPAIR_COMPLETE,
Alert.PERSISTENT_NO_QUORUM,
Alert.INCONCLUSIVE_POLL,
Alert.CACHE_DOWN,
Alert.CACHE_UP,
Alert.DISK_SPACE_LOW,
Alert.DISK_SPACE_FULL,
Alert.INTERNAL_ERROR,
};
}
| src/org/lockss/servlet/RaiseAlert.java | /*
* $Id: RaiseAlert.java,v 1.12 2006-03-16 01:41:19 thib_gc Exp $
*/
/*
Copyright (c) 2000-2006 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.servlet;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;
import java.net.*;
import java.text.*;
import java.security.*;
import org.mortbay.html.*;
import org.mortbay.util.B64Code;
import org.lockss.app.*;
import org.lockss.util.*;
import org.lockss.alert.*;
import org.lockss.plugin.*;
import org.lockss.poller.*;
import org.lockss.protocol.*;
import org.lockss.daemon.*;
import org.lockss.daemon.status.*;
/** Raise an alert on demand. For testing alerts
*/
public class RaiseAlert extends LockssServlet {
static final String KEY_ACTION = "action";
static final String KEY_NAME_SEL = "name_sel";
static final String KEY_NAME_TYPE = "name_type";
static final String KEY_AUID = "auid";
static final String KEY_TEXT = "text";
static final String ACTION_RAISE = "Raise";
static final String COL2 = "colspan=2";
static final String COL2CENTER = COL2 + " align=center";
static Logger log = Logger.getLogger("RaiseAlert");
private LockssDaemon daemon;
private PluginManager pluginMgr;
private AlertManager alertMgr;
String auid;
String name;
String text;
ArchivalUnit au;
boolean showResult;
protected void resetLocals() {
resetVars();
super.resetLocals();
}
void resetVars() {
auid = null;
errMsg = null;
statusMsg = null;
}
public void init(ServletConfig config) throws ServletException {
super.init(config);
daemon = getLockssDaemon();
alertMgr = daemon.getAlertManager();
pluginMgr = daemon.getPluginManager();
}
public void lockssHandleRequest() throws IOException {
resetVars();
String action = getParameter(KEY_ACTION);
if (ACTION_RAISE.equals(action)) {
doRaise();
}
displayPage();
}
private boolean doRaise() {
auid = getParameter(KEY_AUID);
au = pluginMgr.getAuFromId(auid);
name = getParameter(KEY_NAME_SEL);
if (StringUtil.isNullString(name)) {
name = getParameter(KEY_NAME_TYPE);
}
text = getParameter(KEY_TEXT);
Alert alert;
Alert proto = findProtoAlert(name);
if (proto == null) {
proto = new Alert(name);
}
if (au != null && (proto == null ||
proto.getBool(Alert.ATTR_IS_CONTENT))) {
alert = Alert.auAlert(proto, au);
} else {
alert = Alert.cacheAlert(proto);
}
alert.setAttribute(Alert.ATTR_TEXT, text);
alertMgr.raiseAlert(alert);
return true;
}
private void displayPage() throws IOException {
Page page = newPage();
layoutErrorBlock(page);
ServletUtil.layoutExplanationBlock(page, "Raise an Alert");
page.add(makeForm());
page.add("<br>");
layoutFooter(page);
ServletUtil.writePage(resp, page);
}
void addResultRow(Table tbl, String head, Object value) {
tbl.newRow();
tbl.newCell();
tbl.add(head);
tbl.add(":");
tbl.newCell();
tbl.add(value.toString());
}
private Element makeForm() {
Composite comp = new Composite();
Block centeredBlock = new Block(Block.Center);
Form frm = new Form(srvURL(myServletDescr()));
frm.method("POST");
Table autbl = new Table(0, "cellpadding=0");
autbl.newRow();
autbl.addHeading("Select AU");
Select sel = new Select(KEY_AUID, false);
sel.add("", auid == null, "");
for (Iterator iter = pluginMgr.getAllAus().iterator(); iter.hasNext(); ) {
ArchivalUnit au0 = (ArchivalUnit)iter.next();
String id = au0.getAuId();
sel.add(au0.getName(), id.equals(auid), id);
}
autbl.newRow(); autbl.newCell();
setTabOrder(sel);
autbl.add(sel);
Table alrtbl = new Table(0, "cellpadding=0");
alrtbl.newRow();
alrtbl.addHeading("Select Alert Name");
Select sel2 = new Select(KEY_NAME_SEL, false);
sel2.add("", auid == null, "");
for (int ix = 0; ix < protoAlerts.length; ix++) {
Alert proto = protoAlerts[ix];
String aname = proto.getName();
sel2.add(aname, aname.equals(name), aname);
}
alrtbl.newRow(); alrtbl.newCell();
setTabOrder(sel2);
alrtbl.add(sel2);
Table tbl = new Table(0, "cellpadding=0");
tbl.newRow();
tbl.newCell(COL2CENTER);
tbl.add(autbl);
tbl.newRow();
tbl.newCell(COL2CENTER);
tbl.add(alrtbl);
tbl.newRow();
tbl.newCell();
tbl.add(" ");
addInputRow(tbl, "Name", KEY_NAME_TYPE, 50, name);
addInputRow(tbl, "Text", KEY_TEXT, 50, text);
centeredBlock.add(tbl);
frm.add(centeredBlock);
Input submit = new Input(Input.Submit, KEY_ACTION, ACTION_RAISE);
setTabOrder(submit);
frm.add("<br><center>"+submit+"</center>");
comp.add(frm);
return comp;
}
void addInputRow(Table tbl, String label, String key,
int size, String initVal) {
tbl.newRow();
// tbl.newCell();
tbl.addHeading(label + ":", "align=right");
tbl.newCell();
Input in = new Input(Input.Text, key, initVal);
in.setSize(size);
setTabOrder(in);
tbl.add(in);
}
Alert findProtoAlert(String name) {
if (name == null) return null;
for (int ix = 0; ix < protoAlerts.length; ix++) {
Alert proto = protoAlerts[ix];
if (name.equals(proto.getName())) {
return proto;
}
}
return null;
}
Alert[] protoAlerts = {
Alert.PERMISSION_PAGE_FETCH_ERROR,
Alert.NO_CRAWL_PERMISSION,
Alert.NEW_CONTENT,
Alert.NO_NEW_CONTENT,
Alert.VOLUME_CLOSED,
Alert.PUBLISHER_UNREACHABLE,
Alert.PUBLISHER_CONTENT_CHANGED,
Alert.DAMAGE_DETECTED,
Alert.PERSISTENT_DAMAGE,
Alert.REPAIR_COMPLETE,
Alert.PERSISTENT_NO_QUORUM,
Alert.INCONCLUSIVE_POLL,
Alert.CACHE_DOWN,
Alert.CACHE_UP,
Alert.DISK_SPACE_LOW,
Alert.DISK_SPACE_FULL,
Alert.INTERNAL_ERROR,
};
}
| Cosmetic
git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@5138 4f837ed2-42f5-46e7-a7a5-fa17313484d4
| src/org/lockss/servlet/RaiseAlert.java | Cosmetic |
|
Java | bsd-3-clause | 91e0fbf951b554433b9d0491b9a86fcc98ac8882 | 0 | ConnCollege/cas,ConnCollege/cas,ConnCollege/cas | /*
* Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license
* distributed with this file and available online at
* http://www.ja-sig.org/products/cas/overview/license/
*/
package org.jasig.cas.adaptors.ldap;
import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.jasig.cas.util.LdapUtils;
import org.inspektr.common.ioc.annotation.IsIn;
import org.springframework.ldap.core.NameClassPairCallbackHandler;
import org.springframework.ldap.core.SearchExecutor;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import java.util.ArrayList;
import java.util.List;
/**
* Handler to do LDAP bind.
*
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 3.0.3
*/
public class BindLdapAuthenticationHandler extends
AbstractLdapUsernamePasswordAuthenticationHandler {
/** The default maximum number of results to return. */
private static final int DEFAULT_MAX_NUMBER_OF_RESULTS = 1000;
/** The default timeout. */
private static final int DEFAULT_TIMEOUT = 1000;
/** The search base to find the user under. */
private String searchBase;
/** The scope. */
@IsIn({SearchControls.OBJECT_SCOPE, SearchControls.ONELEVEL_SCOPE,
SearchControls.SUBTREE_SCOPE})
private int scope = SearchControls.SUBTREE_SCOPE;
/** The maximum number of results to return. */
private int maxNumberResults = DEFAULT_MAX_NUMBER_OF_RESULTS;
/** The amount of time to wait. */
private int timeout = DEFAULT_TIMEOUT;
/** Boolean of whether multiple accounts are allowed. */
private boolean allowMultipleAccounts;
protected final boolean authenticateUsernamePasswordInternal(
final UsernamePasswordCredentials credentials)
throws AuthenticationException {
final List<String> cns = new ArrayList<String>();
final SearchControls searchControls = getSearchControls();
final String base = this.searchBase;
final String filter = LdapUtils.getFilterWithValues(getFilter(), credentials.getUsername());
this.getLdapTemplate().search(
new SearchExecutor() {
public NamingEnumeration executeSearch(final DirContext context) throws NamingException {
return context.search(base, filter, searchControls);
}
},
new NameClassPairCallbackHandler(){
public void handleNameClassPair(final NameClassPair nameClassPair) {
cns.add(nameClassPair.getNameInNamespace());
}
});
if (cns.isEmpty()) {
this.log.info("Search for " + filter + " returned 0 results.");
return false;
}
if (cns.size() > 1 && !this.allowMultipleAccounts) {
this.log.warn("Search for " + filter + " returned multiple results, which is not allowed.");
return false;
}
for (final String dn : cns) {
DirContext test = null;
String finalDn = composeCompleteDnToCheck(dn, credentials);
try {
this.log.debug("Performing LDAP bind with credential: " + dn);
test = this.getContextSource().getContext(
finalDn,
credentials.getPassword());
if (test != null) {
return true;
}
} catch (final Exception e) {
// if we catch an exception, just try the next cn
} finally {
LdapUtils.closeContext(test);
}
}
return false;
}
protected String composeCompleteDnToCheck(final String dn,
final UsernamePasswordCredentials credentials) {
return dn;
}
private final SearchControls getSearchControls() {
final SearchControls constraints = new SearchControls();
constraints.setSearchScope(this.scope);
constraints.setReturningAttributes(new String[0]);
constraints.setTimeLimit(this.timeout);
constraints.setCountLimit(this.maxNumberResults);
return constraints;
}
/**
* Method to return whether multiple accounts are allowed.
* @return true if multiple accounts are allowed, false otherwise.
*/
protected boolean isAllowMultipleAccounts() {
return this.allowMultipleAccounts;
}
/**
* Method to return the max number of results allowed.
* @return the maximum number of results.
*/
protected int getMaxNumberResults() {
return this.maxNumberResults;
}
/**
* Method to return the scope.
* @return the scope
*/
protected int getScope() {
return this.scope;
}
/**
* Method to return the search base.
* @return the search base.
*/
protected String getSearchBase() {
return this.searchBase;
}
/**
* Method to return the timeout.
* @return the timeout.
*/
protected int getTimeout() {
return this.timeout;
}
public final void setScope(final int scope) {
this.scope = scope;
}
/**
* @param allowMultipleAccounts The allowMultipleAccounts to set.
*/
public void setAllowMultipleAccounts(final boolean allowMultipleAccounts) {
this.allowMultipleAccounts = allowMultipleAccounts;
}
/**
* @param maxNumberResults The maxNumberResults to set.
*/
public final void setMaxNumberResults(final int maxNumberResults) {
this.maxNumberResults = maxNumberResults;
}
/**
* @param searchBase The searchBase to set.
*/
public final void setSearchBase(final String searchBase) {
this.searchBase = searchBase;
}
/**
* @param timeout The timeout to set.
*/
public final void setTimeout(final int timeout) {
this.timeout = timeout;
}
} | cas-server-support-ldap/src/main/java/org/jasig/cas/adaptors/ldap/BindLdapAuthenticationHandler.java | /*
* Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license
* distributed with this file and available online at
* http://www.ja-sig.org/products/cas/overview/license/
*/
package org.jasig.cas.adaptors.ldap;
import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.jasig.cas.util.LdapUtils;
import org.inspektr.common.ioc.annotation.IsIn;
import org.springframework.ldap.core.NameClassPairCallbackHandler;
import org.springframework.ldap.core.SearchExecutor;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import java.util.ArrayList;
import java.util.List;
/**
* Handler to do LDAP bind.
*
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 3.0.3
*/
public class BindLdapAuthenticationHandler extends
AbstractLdapUsernamePasswordAuthenticationHandler {
/** The default maximum number of results to return. */
private static final int DEFAULT_MAX_NUMBER_OF_RESULTS = 1000;
/** The default timeout. */
private static final int DEFAULT_TIMEOUT = 1000;
/** The search base to find the user under. */
private String searchBase;
/** The scope. */
@IsIn({SearchControls.OBJECT_SCOPE, SearchControls.ONELEVEL_SCOPE,
SearchControls.SUBTREE_SCOPE})
private int scope = SearchControls.SUBTREE_SCOPE;
/** The maximum number of results to return. */
private int maxNumberResults = DEFAULT_MAX_NUMBER_OF_RESULTS;
/** The amount of time to wait. */
private int timeout = DEFAULT_TIMEOUT;
/** Boolean of whether multiple accounts are allowed. */
private boolean allowMultipleAccounts;
protected final boolean authenticateUsernamePasswordInternal(
final UsernamePasswordCredentials credentials)
throws AuthenticationException {
final List<String> cns = new ArrayList<String>();
final SearchControls searchControls = getSearchControls();
final String base = this.searchBase;
this.getLdapTemplate().search(
new SearchExecutor() {
public NamingEnumeration executeSearch(final DirContext context) throws NamingException {
return context.search(base, LdapUtils.getFilterWithValues(getFilter(), credentials
.getUsername()), searchControls);
}
},
new NameClassPairCallbackHandler(){
public void handleNameClassPair(final NameClassPair nameClassPair) {
cns.add(nameClassPair.getNameInNamespace());
}
});
if (cns.isEmpty()
|| (cns.size() > 1 && !this.allowMultipleAccounts)) {
System.out.println("List was empty.");
return false;
}
for (final String dn : cns) {
DirContext test = null;
String finalDn = composeCompleteDnToCheck(dn, credentials);
try {
test = this.getContextSource().getContext(
finalDn,
credentials.getPassword());
if (test != null) {
return true;
}
} catch (final Exception e) {
// if we catch an exception, just try the next cn
} finally {
LdapUtils.closeContext(test);
}
}
return false;
}
protected String composeCompleteDnToCheck(final String dn,
final UsernamePasswordCredentials credentials) {
return dn;
}
private final SearchControls getSearchControls() {
final SearchControls constraints = new SearchControls();
constraints.setSearchScope(this.scope);
constraints.setReturningAttributes(new String[0]);
constraints.setTimeLimit(this.timeout);
constraints.setCountLimit(this.maxNumberResults);
return constraints;
}
/**
* Method to return whether multiple accounts are allowed.
* @return true if multiple accounts are allowed, false otherwise.
*/
protected boolean isAllowMultipleAccounts() {
return this.allowMultipleAccounts;
}
/**
* Method to return the max number of results allowed.
* @return the maximum number of results.
*/
protected int getMaxNumberResults() {
return this.maxNumberResults;
}
/**
* Method to return the scope.
* @return the scope
*/
protected int getScope() {
return this.scope;
}
/**
* Method to return the search base.
* @return the search base.
*/
protected String getSearchBase() {
return this.searchBase;
}
/**
* Method to return the timeout.
* @return the timeout.
*/
protected int getTimeout() {
return this.timeout;
}
public final void setScope(final int scope) {
this.scope = scope;
}
/**
* @param allowMultipleAccounts The allowMultipleAccounts to set.
*/
public void setAllowMultipleAccounts(final boolean allowMultipleAccounts) {
this.allowMultipleAccounts = allowMultipleAccounts;
}
/**
* @param maxNumberResults The maxNumberResults to set.
*/
public final void setMaxNumberResults(final int maxNumberResults) {
this.maxNumberResults = maxNumberResults;
}
/**
* @param searchBase The searchBase to set.
*/
public final void setSearchBase(final String searchBase) {
this.searchBase = searchBase;
}
/**
* @param timeout The timeout to set.
*/
public final void setTimeout(final int timeout) {
this.timeout = timeout;
}
} | NOJIRA
Provide better logging for BindLdapAuthenticationHandler.
| cas-server-support-ldap/src/main/java/org/jasig/cas/adaptors/ldap/BindLdapAuthenticationHandler.java | NOJIRA Provide better logging for BindLdapAuthenticationHandler. |
|
Java | mit | 687b9e70238eabb26e72503eea245bf6140c39a3 | 0 | BrunerChris/CS242-Group-Project | import java.util.*;
import java.lang.*;
import java.io.*;
public class MapDriver
{
public static void main(String[] args)
{
Scanner input;
String filename = "map.txt";
NodeList map = new NodeList();
try
{
input = new Scanner(new File(filename));
String[] values;
while(input.hasNext())
{
values = input.nextLine().trim().split("\\|");
map.add(new MapPoint(values[0], values[1], Integer.parseInt(values[2])));
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
}
catch(NumberFormatException e)
{
System.out.println("Number format exception.");
}
//Minimum Spanning Tree
NodeList mstMap = map;
MST mst = new MST(mstMap, "Grand Forks");
mst.driveTo(mst.start);
System.out.println(mst.getStats());
//Depth First Search
NodeList dfsMap = map;
DFS dfs = new DFS(dfsMap);
dfs.drive("Grand Forks");
}
}
| MapDriver.java | import java.util.*;
import java.lang.*;
import java.io.*;
public class MapDriver
{
public static void main(String[] args)
{
File file;
Scanner input;
String filename = "map.txt";
NodeList map = new NodeList();
try
{
file = new File(filename);
input = new Scanner(file);
String[] values = new String[3];
while(input.hasNext())
{
String inputFile = input.nextLine().trim();
values = inputFile.split("\\|");
MapPoint newPoint = new MapPoint(values[0], values[1], Integer.parseInt(values[2]));
map.add(newPoint);
}
String output = map.toString();
//System.out.println(output);
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
}
catch(NumberFormatException e)
{
System.out.println("Number format exception.");
}
//Minimum Spanning Tree
MST mst = new MST(map, "Grand Forks");
mst.driveTo(mst.start);
System.out.println(mst.getStats());
//Depth First Search
DFS dfs = new DFS(map);
dfs.drive("Grand Forks");
}
}
| Update MapDriver.java
Cleaned some code up a little bit. Added NodeLists for mst and dfs. Should we do it like this or create a method that will reset only one NodeList after each algorithm runs? | MapDriver.java | Update MapDriver.java |
|
Java | mit | 28dd0700432e75443c1c6d6123a13e44d88c4af8 | 0 | appreciated/quick-start-material,appreciated/quick-start-material,appreciated/quick-start-material | package com.github.appreciated.quickstart.material.theme;
import com.github.appreciated.quickstart.base.authentication.Util;
import com.github.appreciated.quickstart.base.authentication.login.AccessControl;
import com.github.appreciated.quickstart.base.authentication.registration.RegistrationControl;
import com.github.appreciated.quickstart.base.components.DownloadButton;
import com.github.appreciated.quickstart.base.components.UploadButton;
import com.github.appreciated.quickstart.base.navigation.description.WebAppDescription;
import com.github.appreciated.quickstart.base.navigation.theme.NavigationView;
import com.github.appreciated.quickstart.base.notification.QuickNotification;
import com.github.appreciated.quickstart.base.pages.Subpage;
import com.github.appreciated.quickstart.base.pages.actions.*;
import com.github.appreciated.quickstart.base.pages.attributes.HasContextActions;
import com.github.appreciated.quickstart.base.pages.attributes.HasSearch;
import com.github.appreciated.quickstart.base.ui.QuickStartUI;
import com.github.appreciated.quickstart.material.component.desktop.DesktopMenuBarAnimator;
import com.github.appreciated.quickstart.material.components.design.MaterialDesktopActionBar;
import com.github.appreciated.quickstart.material.login.LoginDialog;
import com.github.appreciated.quickstart.material.theme.design.DesktopNavigationDesign;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.ui.*;
import java.util.AbstractMap;
import java.util.List;
import java.util.stream.Stream;
/**
* Created by appreciated on 04.12.2016.
*/
public class MaterialDesktopView extends DesktopNavigationDesign implements NavigationView {
public static final String CONFIGURATION_HIDE_ICON = "hide_icon";
public static final String CONFIGURATION_HIDE_TITLE = "hide_title";
private AccessControl accessControl;
private RegistrationControl registrationControl;
private MaterialDesktopActionBar actionBar = null;
public MaterialDesktopView() {
DesktopMenuBarAnimator animator = new DesktopMenuBarAnimator();
animator.addStyleName("visibility: collapse");
navigationMenuWrapper.addComponent(animator);
}
@Override
public void initWithConfiguration(Stream<AbstractMap.SimpleEntry<String, Boolean>> configurations) {
if (configurations != null) {
configurations.forEach(entry -> {
if (entry.getValue().booleanValue() == true) {
switch (entry.getKey()) {
case CONFIGURATION_HIDE_ICON:
iconContainer.setVisible(false);
break;
case CONFIGURATION_HIDE_TITLE:
title.setVisible(false);
break;
}
}
});
}
}
@Override
public void initNavigationElements(Stream<Subpage> pages) {
navigationMenu.removeItems();
pages.forEach(navigation -> {
MenuBar.MenuItem item = this.navigationMenu.addItem(navigation.getNavigationName(), navigation.getNavigationIcon(), null);
item.setCommand(menuItem -> navigation.navigateTo());
});
}
@Override
public void initWithTitle(String title) {
this.title.setValue(title);
}
@Override
public void initUserFunctionality(WebAppDescription description) {
user.removeItems();
if (description.getLoginNavigable() == null) {
register.addClickListener(clickEvent -> new LoginDialog("Register").initWithAccessControl(accessControl).initRegistrationControl(registrationControl).withLoginVisible(false).initWithLoginListener(() -> showUser()).show());
signIn.addClickListener(clickEvent -> new LoginDialog("Sign-In").initWithAccessControl(accessControl).withLoginVisible(true).initWithLoginListener(() -> showUser()).show());
} else if (QuickStartUI.isUserSignedIn()) {
showUser();
} else {
Util.invalidateSession();
}
}
private void showUser() {
userAuthWrapper.setVisible(false);
MenuBar.MenuItem item = user.addItem(QuickStartUI.getUsername(), VaadinIcons.USER, null);
item.addItem("Edit Profile", menuItem -> QuickNotification.showMessageError("This is currently not implemented"));
item.addItem("Logout", menuItem -> Util.invalidateSession());
}
@Override
public void initCustomMenuElements(List<Component> components) {
menuElements.removeAllComponents();
components.forEach(component -> menuElements.addComponent(component));
}
@Override
public AbstractOrderedLayout getHolder() {
return componentHolder;
}
@Override
public void disableLogout() {
user.setVisible(false);
}
@Override
public void setCurrentContainerLabel(String label) {
actionBar.getContainerLabel().setValue(label);
}
@Override
public void setCurrentActions(HasContextActions contextNavigable) {
if (contextNavigable != null) {
List<Action> actions = contextNavigable.getContextActions();
if (actions != null && actions.size() > 0) {
actionBar.getContextButtons().removeItems();
actions.forEach(action -> {
if (action instanceof CustomAction) {
CustomAction cAction = (CustomAction) action;
actionBar.getCustomActionWrapper().addComponent(cAction.getDesktopComponent());
actionBar.getCustomActionWrapper().setComponentAlignment(cAction.getDesktopComponent(), cAction.getAlignment());
} else if (action instanceof DownloadAction) {
DownloadButton download = new DownloadButton((DownloadAction) action);
download.setHeight(45, Unit.PIXELS);
actionBar.getCustomActionWrapper().addComponent(download);
actionBar.getCustomActionWrapper().setComponentAlignment(download, Alignment.MIDDLE_LEFT);
} else if (action instanceof UploadAction) {
UploadButton upload = new UploadButton((UploadAction) action);
upload.setHeight(45, Unit.PIXELS);
actionBar.getCustomActionWrapper().addComponent(upload);
actionBar.getCustomActionWrapper().setComponentAlignment(upload, Alignment.MIDDLE_LEFT);
} else if (action instanceof ClickAction) {
actionBar.getContextButtons().addItem(action.getName(), action.getResource(), menuItem -> {
((ClickAction) action).getListener().actionPerformed(null);
});
}
});
actionBar.getContextButtons().setVisible(actions.stream().filter(action -> action instanceof ClickAction).count() > 0);
}
}
}
@Override
public void allowPercentagePageHeight(boolean allow) {
if (allow) {
this.pageWrapper.setHeight(100, Unit.PERCENTAGE);
} else {
this.pageWrapper.setHeightUndefined();
}
}
@Override
public void setPageTitleVisibility(boolean visiblity) {
actionBar.getContainerLabel().setVisible(visiblity);
}
@Override
public void setCurrentSearchNavigable(HasSearch navigable) {
if (navigable == null) {
actionBar.getSearchBarWrapper().setVisible(false);
} else {
actionBar.getSearchBar().setValue("");
actionBar.getSearchBarWrapper().setVisible(true);
actionBar.getSearchBar().addValueChangeListener(navigable);
}
}
@Override
public void initWithAccessControl(AccessControl accessControl) {
this.accessControl = accessControl;
}
@Override
public void initRegistrationControl(RegistrationControl registrationControl) {
this.registrationControl = registrationControl;
}
@Override
public Layout getContainerView() {
return getComponentHolder();
}
/*
* To make the view more customizable allow every Property to be accessed
*/
public HorizontalLayout getIconContainer() {
return iconContainer;
}
public Label getTitleLabel() {
return title;
}
public MenuBar getUser() {
return user;
}
public HorizontalLayout getComponentHolder() {
return componentHolder;
}
@Override
public void onNavigate(Subpage subpageComponent) {
initActionBar();
}
@Override
public void onNavigate(Component subpageComponent) {
initActionBar();
}
private void initActionBar() {
this.actionBar = new MaterialDesktopActionBar();
this.actionbarHolder.removeAllComponents();
this.actionbarHolder.addComponent(actionBar);
}
@Override
public void onComponentAdded(Component currentComponent) {
this.componentHolder.setComponentAlignment(currentComponent, Alignment.TOP_CENTER);
}
}
| src/main/java/com/github/appreciated/quickstart/material/theme/MaterialDesktopView.java | package com.github.appreciated.quickstart.material.theme;
import com.github.appreciated.quickstart.base.authentication.Util;
import com.github.appreciated.quickstart.base.authentication.login.AccessControl;
import com.github.appreciated.quickstart.base.authentication.registration.RegistrationControl;
import com.github.appreciated.quickstart.base.components.DownloadButton;
import com.github.appreciated.quickstart.base.components.UploadButton;
import com.github.appreciated.quickstart.base.navigation.description.WebAppDescription;
import com.github.appreciated.quickstart.base.navigation.theme.NavigationView;
import com.github.appreciated.quickstart.base.notification.QuickNotification;
import com.github.appreciated.quickstart.base.pages.Subpage;
import com.github.appreciated.quickstart.base.pages.actions.*;
import com.github.appreciated.quickstart.base.pages.attributes.HasContextActions;
import com.github.appreciated.quickstart.base.pages.attributes.HasSearch;
import com.github.appreciated.quickstart.base.ui.QuickStartUI;
import com.github.appreciated.quickstart.material.component.desktop.DesktopMenuBarAnimator;
import com.github.appreciated.quickstart.material.components.design.MaterialDesktopActionBar;
import com.github.appreciated.quickstart.material.login.LoginDialog;
import com.github.appreciated.quickstart.material.theme.design.DesktopNavigationDesign;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.ui.*;
import java.util.AbstractMap;
import java.util.List;
import java.util.stream.Stream;
/**
* Created by appreciated on 04.12.2016.
*/
public class MaterialDesktopView extends DesktopNavigationDesign implements NavigationView {
public static final String CONFIGURATION_HIDE_ICON = "hide_icon";
public static final String CONFIGURATION_HIDE_TITLE = "hide_title";
private AccessControl accessControl;
private RegistrationControl registrationControl;
private MaterialDesktopActionBar actionBar = null;
public MaterialDesktopView() {
DesktopMenuBarAnimator animator = new DesktopMenuBarAnimator();
animator.addStyleName("visibility: collapse");
navigationMenuWrapper.addComponent(animator);
}
@Override
public void initWithConfiguration(Stream<AbstractMap.SimpleEntry<String, Boolean>> configurations) {
if (configurations != null) {
configurations.forEach(entry -> {
if (entry.getValue().booleanValue() == true) {
switch (entry.getKey()) {
case CONFIGURATION_HIDE_ICON:
iconContainer.setVisible(false);
break;
case CONFIGURATION_HIDE_TITLE:
title.setVisible(false);
break;
}
}
});
}
}
@Override
public void initNavigationElements(Stream<Subpage> pages) {
navigationMenu.removeItems();
pages.forEach(navigation -> {
MenuBar.MenuItem item = this.navigationMenu.addItem(navigation.getNavigationName(), navigation.getNavigationIcon(), null);
item.setCommand(menuItem -> navigation.navigateTo());
});
}
@Override
public void initWithTitle(String title) {
this.title.setValue(title);
}
@Override
public void initUserFunctionality(WebAppDescription description) {
user.removeItems();
if (description.getLoginNavigable() == null) {
register.addClickListener(clickEvent -> new LoginDialog("Register").initWithAccessControl(accessControl).initRegistrationControl(registrationControl).withLoginVisible(false).initWithLoginListener(() -> showUser()).show());
signIn.addClickListener(clickEvent -> new LoginDialog("Sign-In").initWithAccessControl(accessControl).withLoginVisible(true).initWithLoginListener(() -> showUser()).show());
} else if (QuickStartUI.isUserSignedIn()) {
showUser();
} else {
Util.invalidateSession();
}
}
private void showUser() {
userAuthWrapper.setVisible(false);
MenuBar.MenuItem item = user.addItem(QuickStartUI.getUsername(), VaadinIcons.USER, null);
item.addItem("Edit Profile", menuItem -> QuickNotification.showMessageError("This is currently not implemented"));
item.addItem("Logout", menuItem -> Util.invalidateSession());
}
@Override
public void initCustomMenuElements(List<Component> components) {
menuElements.removeAllComponents();
components.forEach(component -> menuElements.addComponent(component));
}
@Override
public AbstractOrderedLayout getHolder() {
return componentHolder;
}
@Override
public void disableLogout() {
user.setVisible(false);
}
@Override
public void setCurrentContainerLabel(String label) {
actionBar.getContainerLabel().setValue(label);
}
@Override
public void setCurrentActions(HasContextActions contextNavigable) {
if (contextNavigable != null) {
List<Action> actions = contextNavigable.getContextActions();
if (actions != null && actions.size() > 0) {
actionBar.getContextButtons().removeItems();
actions.forEach(action -> {
if (action instanceof CustomAction) {
CustomAction cAction = (CustomAction) action;
actionBar.getCustomActionWrapper().addComponent(cAction.getDesktopComponent());
actionBar.getCustomActionWrapper().setComponentAlignment(cAction.getDesktopComponent(), cAction.getAlignment());
} else if (action instanceof DownloadAction) {
DownloadButton download = new DownloadButton((DownloadAction) action);
download.setHeight(45, Unit.PIXELS);
actionBar.getCustomActionWrapper().addComponent(download);
actionBar.getCustomActionWrapper().setComponentAlignment(download, Alignment.MIDDLE_LEFT);
} else if (action instanceof UploadAction) {
UploadButton upload = new UploadButton((UploadAction) action);
upload.setHeight(45, Unit.PIXELS);
actionBar.getCustomActionWrapper().addComponent(upload);
actionBar.getCustomActionWrapper().setComponentAlignment(upload, Alignment.MIDDLE_LEFT);
} else if (action instanceof ClickAction) {
actionBar.getContextButtons().addItem(action.getName(), action.getResource(), menuItem -> {
((ClickAction) action).getListener().actionPerformed(null);
});
}
});
actionBar.getContextButtons().setVisible(actions.stream().filter(action -> action instanceof ClickAction).count() > 0);
}
}
}
@Override
public void allowPercentagePageHeight(boolean allow) {
if (allow) {
this.pageWrapper.setHeight(100, Unit.PERCENTAGE);
} else {
this.pageWrapper.setHeightUndefined();
}
}
@Override
public void setPageTitleVisibility(boolean visiblity) {
actionBar.getContainerLabel().setVisible(visiblity);
}
@Override
public void setCurrentSearchNavigable(HasSearch navigable) {
if (navigable == null) {
actionBar.getSearchBarWrapper().setVisible(false);
} else {
actionBar.getSearchBar().setValue("");
actionBar.getSearchBarWrapper().setVisible(true);
actionBar.getSearchBar().addValueChangeListener(navigable);
}
}
@Override
public void initWithAccessControl(AccessControl accessControl) {
this.accessControl = accessControl;
}
@Override
public void initRegistrationControl(RegistrationControl registrationControl) {
this.registrationControl = registrationControl;
}
@Override
public Layout getContainerView() {
return getComponentHolder();
}
/*
* To make the view more customizable allow every Property to be accessed
*/
public HorizontalLayout getIconContainer() {
return iconContainer;
}
public Label getTitleLabel() {
return title;
}
public MenuBar getUser() {
return user;
}
public HorizontalLayout getComponentHolder() {
return componentHolder;
}
@Override
public void onNavigate(Subpage subpageComponent) {
initActionBar();
}
@Override
public void onNavigate(Component subpageComponent) {
initActionBar();
}
private void initActionBar() {
this.actionBar = new MaterialDesktopActionBar();
this.actionbarHolder.removeAllComponents();
this.actionbarHolder.addComponent(actionBar);
}
}
| - improved DialogBuilder
- fixed unchecked call
- corrected orientation
| src/main/java/com/github/appreciated/quickstart/material/theme/MaterialDesktopView.java | - improved DialogBuilder - fixed unchecked call - corrected orientation |
|
Java | mit | b344738b74e23bb55934a56583c7005114a996fc | 0 | mhogrefe/qbar | package mho.qbar.objects;
import mho.qbar.iterableProviders.QBarExhaustiveProvider;
import mho.qbar.iterableProviders.QBarIterableProvider;
import mho.qbar.iterableProviders.QBarRandomProvider;
import mho.wheels.iterables.ExhaustiveProvider;
import mho.wheels.iterables.IterableUtils;
import mho.wheels.iterables.RandomProvider;
import mho.wheels.ordering.Ordering;
import mho.wheels.structures.Pair;
import java.math.BigInteger;
import java.util.List;
import java.util.Random;
import static mho.qbar.objects.Rational.ZERO;
import static mho.qbar.objects.RationalVector.*;
import static mho.wheels.iterables.IterableUtils.*;
@SuppressWarnings({"ConstantConditions", "UnusedDeclaration"})
public class RationalVectorDemos {
private static final boolean USE_RANDOM = false;
private static final String RATIONAL_VECTOR_CHARS = " ,-/0123456789[]";
private static final int SMALL_LIMIT = 100;
private static int LIMIT;
private static QBarIterableProvider P;
private static void initialize() {
if (USE_RANDOM) {
P = new QBarRandomProvider(new Random(0x6af477d9a7e54fcaL));
LIMIT = 1000;
} else {
P = QBarExhaustiveProvider.INSTANCE;
LIMIT = 10000;
}
}
public static void demoIterator() {
initialize();
for (RationalVector v : take(LIMIT, P.rationalVectors())) {
System.out.println("toList(" + v + ") = " + toList(v));
}
}
public static void demoX() {
initialize();
Iterable<RationalVector> vs = map(
p -> RationalVector.of(toList(cons(p.a, p.b))),
P.pairs(P.rationals(), P.rationalVectors())
);
for (RationalVector v : take(LIMIT, vs)) {
System.out.println("x(" + v + ") = " + v.x());
}
}
public static void demoY() {
initialize();
Iterable<RationalVector> vs = map(
p -> RationalVector.of(toList(concat(p.a, p.b))),
P.pairs(P.rationalVectors(2), P.rationalVectors())
);
for (RationalVector v : take(LIMIT, vs)) {
System.out.println("y(" + v + ") = " + v.y());
}
}
public static void demoZ() {
initialize();
Iterable<RationalVector> vs = map(
p -> RationalVector.of(toList(concat(p.a, p.b))),
P.pairs(P.rationalVectors(3), P.rationalVectors())
);
for (RationalVector v : take(LIMIT, vs)) {
System.out.println("z(" + v + ") = " + v.z());
}
}
public static void demoW() {
initialize();
Iterable<RationalVector> vs = map(
p -> RationalVector.of(toList(concat(p.a, p.b))),
P.pairs(P.rationalVectors(4), P.rationalVectors())
);
for (RationalVector v : take(LIMIT, vs)) {
System.out.println("w(" + v + ") = " + v.w());
}
}
public static void demoX_int() {
initialize();
Iterable<Pair<RationalVector, Integer>> ps = P.dependentPairsLogarithmic(
P.rationalVectors(),
v -> range(0, v.dimension() - 1)
);
for (Pair<RationalVector, Integer> p : take(LIMIT, ps)) {
System.out.println("x(" + p.a + ", " + p.b + ") = " + p.a.x(p.b));
}
}
public static void demoOf_List_Rational() {
initialize();
for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) {
String listString = tail(init(rs.toString()));
System.out.println("of(" + listString + ") = " + of(rs));
}
}
public static void demoOf_Rational() {
initialize();
for (Rational r : take(LIMIT, P.rationals())) {
System.out.println("of(" + r + ") = " + of(r));
}
}
public static void demoDimension() {
initialize();
for (RationalVector v : take(LIMIT, P.rationalVectors())) {
System.out.println("dim(" + v + ") = " + v.dimension());
}
}
public static void demoZero() {
initialize();
Iterable<Integer> is;
if (P instanceof ExhaustiveProvider) {
is = P.naturalIntegers();
} else {
is = ((RandomProvider) P).naturalIntegersGeometric(20);
}
for (int i : take(SMALL_LIMIT, is)) {
System.out.println("zero(" + i + ") = " + zero(i));
}
}
public static void demoIdentity() {
initialize();
Iterable<Integer> is;
if (P instanceof ExhaustiveProvider) {
is = P.naturalIntegers();
} else {
is = ((RandomProvider) P).naturalIntegersGeometric(20);
}
for (Pair<Integer, Integer> p : take(SMALL_LIMIT, filter(q -> q.a > q.b, P.pairs(is)))) {
System.out.println("identity(" + p.a + ", " + p.b + ") = " + identity(p.a, p.b));
}
}
public static void demoIsZero() {
initialize();
for (RationalVector v : take(LIMIT, P.rationalVectors())) {
System.out.println(v + " is " + (v.isZero() ? "" : " not ") + "zero");
}
}
public static void demoNegate() {
initialize();
for (RationalVector v : take(LIMIT, P.rationalVectors())) {
System.out.println("-" + v + " = " + v.negate());
}
}
public static void demoAdd() {
initialize();
Iterable<Pair<RationalVector, RationalVector>> ps;
if (P instanceof ExhaustiveProvider) {
ps = P.dependentPairs(P.rationalVectors(), v -> P.rationalVectors(v.dimension()));
} else {
ps = P.dependentPairs(
((QBarRandomProvider) P).rationalVectorsBySize(8),
v -> ((QBarRandomProvider) P).rationalVectorsBySize(8, v.dimension())
);
}
for (Pair<RationalVector, RationalVector> p : take(LIMIT, ps)) {
System.out.println(p.a + " + " + p.b + " = " + p.a.add(p.b));
}
}
public static void demoSubtract() {
initialize();
Iterable<Pair<RationalVector, RationalVector>> ps;
if (P instanceof ExhaustiveProvider) {
ps = P.dependentPairs(P.rationalVectors(), v -> P.rationalVectors(v.dimension()));
} else {
ps = P.dependentPairs(
((QBarRandomProvider) P).rationalVectorsBySize(8),
v -> ((QBarRandomProvider) P).rationalVectorsBySize(8, v.dimension())
);
}
for (Pair<RationalVector, RationalVector> p : take(LIMIT, ps)) {
System.out.println(p.a + " - " + p.b + " = " + p.a.subtract(p.b));
}
}
public static void demoMultiply_Rational() {
initialize();
for (Pair<RationalVector, Rational> p : take(LIMIT, P.pairs(P.rationalVectors(), P.rationals()))) {
System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b));
}
}
public static void demoMultiply_BigInteger() {
initialize();
for (Pair<RationalVector, BigInteger> p : take(LIMIT, P.pairs(P.rationalVectors(), P.bigIntegers()))) {
System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b));
}
}
public static void demoMultiply_int() {
initialize();
for (Pair<RationalVector, Integer> p : take(LIMIT, P.pairs(P.rationalVectors(), P.integers()))) {
System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b));
}
}
public static void demoDivide_Rational() {
initialize();
Iterable<Pair<RationalVector, Rational>> ps = filter(
p -> p.b != ZERO,
P.pairs(P.rationalVectors(), P.rationals())
);
for (Pair<RationalVector, Rational> p : take(LIMIT, ps)) {
System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b));
}
}
public static void demoDivide_BigInteger() {
initialize();
Iterable<Pair<RationalVector, BigInteger>> ps = P.pairs(
P.rationalVectors(),
filter(bi -> !bi.equals(BigInteger.ZERO), P.bigIntegers())
);
for (Pair<RationalVector, BigInteger> p : take(LIMIT, ps)) {
System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b));
}
}
public static void demoDivide_int() {
initialize();
Iterable<Pair<RationalVector, Integer>> ps = P.pairs(P.rationalVectors(), filter(i -> i != 0, P.integers()));
for (Pair<RationalVector, Integer> p : take(LIMIT, ps)) {
System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b));
}
}
public static void demoSum() {
initialize();
Iterable<Pair<Integer, Integer>> ps;
if (P instanceof ExhaustiveProvider) {
ps = P.pairs(P.positiveIntegers(), P.naturalIntegers());
} else {
ps = P.pairs(
((RandomProvider) P).positiveIntegersGeometric(5),
((RandomProvider) P).naturalIntegersGeometric(5)
);
}
Iterable<List<RationalVector>> vss = map(
q -> q.b,
P.dependentPairsSquare(ps, p -> P.lists(p.a, P.rationalVectors(p.b)))
);
for (List<RationalVector> vs : take(LIMIT, vss)) {
String listString = tail(init(vs.toString()));
System.out.println("sum(" + listString + ") = " + sum(vs));
}
}
public static void demoDelta() {
initialize();
Iterable<Pair<Integer, Integer>> ps;
if (P instanceof ExhaustiveProvider) {
ps = P.pairs(P.positiveIntegers(), P.naturalIntegers());
} else {
ps = P.pairs(
((RandomProvider) P).positiveIntegersGeometric(5),
((RandomProvider) P).naturalIntegersGeometric(5)
);
}
Iterable<List<RationalVector>> vss = map(
q -> q.b,
P.dependentPairsSquare(ps, p -> P.lists(p.a, P.rationalVectors(p.b)))
);
for (List<RationalVector> vs : take(LIMIT, vss)) {
String listString = tail(init(vs.toString()));
System.out.println("delta(" + listString + ") = " + IterableUtils.toString(delta(vs)));
}
}
public static void demoEquals_RationalVector() {
initialize();
for (Pair<RationalVector, RationalVector> p : take(LIMIT, P.pairs(P.rationalVectors()))) {
System.out.println(p.a + (p.a.equals(p.b) ? " = " : " ≠ ") + p.b);
}
}
public static void demoEquals_null() {
initialize();
for (RationalVector v : take(LIMIT, P.rationalVectors())) {
//noinspection ObjectEqualsNull
System.out.println(v + (v.equals(null) ? " = " : " ≠ ") + null);
}
}
public static void demoHashCode() {
initialize();
for (RationalVector v : take(LIMIT, P.rationalVectors())) {
System.out.println("hashCode(" + v + ") = " + v.hashCode());
}
}
public static void demoCompareTo() {
initialize();
for (Pair<RationalVector, RationalVector> p : take(LIMIT, P.pairs(P.rationalVectors()))) {
System.out.println(p.a + " " + Ordering.compare(p.a, p.b).toChar() + " " + p.b);
}
}
public static void demoRead() {
initialize();
for (String s : take(LIMIT, P.strings())) {
System.out.println("read(" + s + ") = " + read(s));
}
}
public static void demoRead_targeted() {
initialize();
Iterable<Character> cs;
if (P instanceof QBarExhaustiveProvider) {
cs = fromString(RATIONAL_VECTOR_CHARS);
} else {
cs = ((QBarRandomProvider) P).uniformSample(RATIONAL_VECTOR_CHARS);
}
for (String s : take(LIMIT, P.strings(cs))) {
System.out.println("read(" + s + ") = " + read(s));
}
}
public static void demoFindIn() {
initialize();
for (String s : take(LIMIT, P.strings())) {
System.out.println("findIn(" + s + ") = " + findIn(s));
}
}
public static void demoFindIn_targeted() {
initialize();
Iterable<Character> cs;
if (P instanceof QBarExhaustiveProvider) {
cs = fromString(RATIONAL_VECTOR_CHARS);
} else {
cs = ((QBarRandomProvider) P).uniformSample(RATIONAL_VECTOR_CHARS);
}
for (String s : take(LIMIT, P.strings(cs))) {
System.out.println("findIn(" + s + ") = " + findIn(s));
}
}
public static void demoToString() {
initialize();
for (RationalVector v : take(LIMIT, P.rationalVectors())) {
System.out.println(v);
}
}
}
| src/test/java/mho/qbar/objects/RationalVectorDemos.java | package mho.qbar.objects;
import mho.qbar.iterableProviders.QBarExhaustiveProvider;
import mho.qbar.iterableProviders.QBarIterableProvider;
import mho.qbar.iterableProviders.QBarRandomProvider;
import mho.wheels.iterables.ExhaustiveProvider;
import mho.wheels.iterables.RandomProvider;
import mho.wheels.ordering.Ordering;
import mho.wheels.structures.Pair;
import java.math.BigInteger;
import java.util.List;
import java.util.Random;
import static mho.qbar.objects.Rational.ZERO;
import static mho.qbar.objects.RationalVector.*;
import static mho.wheels.iterables.IterableUtils.*;
@SuppressWarnings({"ConstantConditions", "UnusedDeclaration"})
public class RationalVectorDemos {
private static final boolean USE_RANDOM = false;
private static final String RATIONAL_VECTOR_CHARS = " ,-/0123456789[]";
private static final int SMALL_LIMIT = 100;
private static int LIMIT;
private static QBarIterableProvider P;
private static void initialize() {
if (USE_RANDOM) {
P = new QBarRandomProvider(new Random(0x6af477d9a7e54fcaL));
LIMIT = 1000;
} else {
P = QBarExhaustiveProvider.INSTANCE;
LIMIT = 10000;
}
}
public static void demoIterator() {
initialize();
for (RationalVector v : take(LIMIT, P.rationalVectors())) {
System.out.println("toList(" + v + ") = " + toList(v));
}
}
public static void demoX() {
initialize();
Iterable<RationalVector> vs = map(
p -> RationalVector.of(toList(cons(p.a, p.b))),
P.pairs(P.rationals(), P.rationalVectors())
);
for (RationalVector v : take(LIMIT, vs)) {
System.out.println("x(" + v + ") = " + v.x());
}
}
public static void demoY() {
initialize();
Iterable<RationalVector> vs = map(
p -> RationalVector.of(toList(concat(p.a, p.b))),
P.pairs(P.rationalVectors(2), P.rationalVectors())
);
for (RationalVector v : take(LIMIT, vs)) {
System.out.println("y(" + v + ") = " + v.y());
}
}
public static void demoZ() {
initialize();
Iterable<RationalVector> vs = map(
p -> RationalVector.of(toList(concat(p.a, p.b))),
P.pairs(P.rationalVectors(3), P.rationalVectors())
);
for (RationalVector v : take(LIMIT, vs)) {
System.out.println("z(" + v + ") = " + v.z());
}
}
public static void demoW() {
initialize();
Iterable<RationalVector> vs = map(
p -> RationalVector.of(toList(concat(p.a, p.b))),
P.pairs(P.rationalVectors(4), P.rationalVectors())
);
for (RationalVector v : take(LIMIT, vs)) {
System.out.println("w(" + v + ") = " + v.w());
}
}
public static void demoX_int() {
initialize();
Iterable<Pair<RationalVector, Integer>> ps = P.dependentPairsLogarithmic(
P.rationalVectors(),
v -> range(0, v.dimension() - 1)
);
for (Pair<RationalVector, Integer> p : take(LIMIT, ps)) {
System.out.println("x(" + p.a + ", " + p.b + ") = " + p.a.x(p.b));
}
}
public static void demoOf_List_Rational() {
initialize();
for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) {
String listString = tail(init(rs.toString()));
System.out.println("of(" + listString + ") = " + of(rs));
}
}
public static void demoOf_Rational() {
initialize();
for (Rational r : take(LIMIT, P.rationals())) {
System.out.println("of(" + r + ") = " + of(r));
}
}
public static void demoDimension() {
initialize();
for (RationalVector v : take(LIMIT, P.rationalVectors())) {
System.out.println("dim(" + v + ") = " + v.dimension());
}
}
public static void demoZero() {
initialize();
Iterable<Integer> is;
if (P instanceof ExhaustiveProvider) {
is = P.naturalIntegers();
} else {
is = ((RandomProvider) P).naturalIntegersGeometric(20);
}
for (int i : take(SMALL_LIMIT, is)) {
System.out.println("zero(" + i + ") = " + zero(i));
}
}
public static void demoIdentity() {
initialize();
Iterable<Integer> is;
if (P instanceof ExhaustiveProvider) {
is = P.naturalIntegers();
} else {
is = ((RandomProvider) P).naturalIntegersGeometric(20);
}
for (Pair<Integer, Integer> p : take(SMALL_LIMIT, filter(q -> q.a > q.b, P.pairs(is)))) {
System.out.println("identity(" + p.a + ", " + p.b + ") = " + identity(p.a, p.b));
}
}
public static void demoIsZero() {
initialize();
for (RationalVector v : take(LIMIT, P.rationalVectors())) {
System.out.println(v + " is " + (v.isZero() ? "" : " not ") + "zero");
}
}
public static void demoNegate() {
initialize();
for (RationalVector v : take(LIMIT, P.rationalVectors())) {
System.out.println("-" + v + " = " + v.negate());
}
}
public static void demoAdd() {
initialize();
Iterable<Pair<RationalVector, RationalVector>> ps;
if (P instanceof ExhaustiveProvider) {
ps = P.dependentPairs(P.rationalVectors(), v -> P.rationalVectors(v.dimension()));
} else {
ps = P.dependentPairs(
((QBarRandomProvider) P).rationalVectorsBySize(8),
v -> ((QBarRandomProvider) P).rationalVectorsBySize(8, v.dimension())
);
}
for (Pair<RationalVector, RationalVector> p : take(LIMIT, ps)) {
System.out.println(p.a + " + " + p.b + " = " + p.a.add(p.b));
}
}
public static void demoSubtract() {
initialize();
Iterable<Pair<RationalVector, RationalVector>> ps;
if (P instanceof ExhaustiveProvider) {
ps = P.dependentPairs(P.rationalVectors(), v -> P.rationalVectors(v.dimension()));
} else {
ps = P.dependentPairs(
((QBarRandomProvider) P).rationalVectorsBySize(8),
v -> ((QBarRandomProvider) P).rationalVectorsBySize(8, v.dimension())
);
}
for (Pair<RationalVector, RationalVector> p : take(LIMIT, ps)) {
System.out.println(p.a + " - " + p.b + " = " + p.a.subtract(p.b));
}
}
public static void demoMultiply_Rational() {
initialize();
for (Pair<RationalVector, Rational> p : take(LIMIT, P.pairs(P.rationalVectors(), P.rationals()))) {
System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b));
}
}
public static void demoMultiply_BigInteger() {
initialize();
for (Pair<RationalVector, BigInteger> p : take(LIMIT, P.pairs(P.rationalVectors(), P.bigIntegers()))) {
System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b));
}
}
public static void demoMultiply_int() {
initialize();
for (Pair<RationalVector, Integer> p : take(LIMIT, P.pairs(P.rationalVectors(), P.integers()))) {
System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b));
}
}
public static void demoDivide_Rational() {
initialize();
Iterable<Pair<RationalVector, Rational>> ps = filter(
p -> p.b != ZERO,
P.pairs(P.rationalVectors(), P.rationals())
);
for (Pair<RationalVector, Rational> p : take(LIMIT, ps)) {
System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b));
}
}
public static void demoDivide_BigInteger() {
initialize();
Iterable<Pair<RationalVector, BigInteger>> ps = P.pairs(
P.rationalVectors(),
filter(bi -> !bi.equals(BigInteger.ZERO), P.bigIntegers())
);
for (Pair<RationalVector, BigInteger> p : take(LIMIT, ps)) {
System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b));
}
}
public static void demoDivide_int() {
initialize();
Iterable<Pair<RationalVector, Integer>> ps = P.pairs(P.rationalVectors(), filter(i -> i != 0, P.integers()));
for (Pair<RationalVector, Integer> p : take(LIMIT, ps)) {
System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b));
}
}
public static void demoEquals_RationalVector() {
initialize();
for (Pair<RationalVector, RationalVector> p : take(LIMIT, P.pairs(P.rationalVectors()))) {
System.out.println(p.a + (p.a.equals(p.b) ? " = " : " ≠ ") + p.b);
}
}
public static void demoEquals_null() {
initialize();
for (RationalVector v : take(LIMIT, P.rationalVectors())) {
//noinspection ObjectEqualsNull
System.out.println(v + (v.equals(null) ? " = " : " ≠ ") + null);
}
}
public static void demoHashCode() {
initialize();
for (RationalVector v : take(LIMIT, P.rationalVectors())) {
System.out.println("hashCode(" + v + ") = " + v.hashCode());
}
}
public static void demoCompareTo() {
initialize();
for (Pair<RationalVector, RationalVector> p : take(LIMIT, P.pairs(P.rationalVectors()))) {
System.out.println(p.a + " " + Ordering.compare(p.a, p.b).toChar() + " " + p.b);
}
}
public static void demoRead() {
initialize();
for (String s : take(LIMIT, P.strings())) {
System.out.println("read(" + s + ") = " + read(s));
}
}
public static void demoRead_targeted() {
initialize();
Iterable<Character> cs;
if (P instanceof QBarExhaustiveProvider) {
cs = fromString(RATIONAL_VECTOR_CHARS);
} else {
cs = ((QBarRandomProvider) P).uniformSample(RATIONAL_VECTOR_CHARS);
}
for (String s : take(LIMIT, P.strings(cs))) {
System.out.println("read(" + s + ") = " + read(s));
}
}
public static void demoFindIn() {
initialize();
for (String s : take(LIMIT, P.strings())) {
System.out.println("findIn(" + s + ") = " + findIn(s));
}
}
public static void demoFindIn_targeted() {
initialize();
Iterable<Character> cs;
if (P instanceof QBarExhaustiveProvider) {
cs = fromString(RATIONAL_VECTOR_CHARS);
} else {
cs = ((QBarRandomProvider) P).uniformSample(RATIONAL_VECTOR_CHARS);
}
for (String s : take(LIMIT, P.strings(cs))) {
System.out.println("findIn(" + s + ") = " + findIn(s));
}
}
public static void demoToString() {
initialize();
for (RationalVector v : take(LIMIT, P.rationalVectors())) {
System.out.println(v);
}
}
}
| added sum and delta demos
| src/test/java/mho/qbar/objects/RationalVectorDemos.java | added sum and delta demos |
|
Java | mit | be2a2d71f12ddbf75ae3e0ca35100aabaaf04b38 | 0 | gurkenlabs/litiengine,gurkenlabs/litiengine | package de.gurkenlabs.litiengine;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.lang.annotation.AnnotationFormatError;
import java.util.logging.LogManager;
import de.gurkenlabs.core.IInitializable;
import de.gurkenlabs.core.ILaunchable;
import de.gurkenlabs.litiengine.annotation.GameInfo;
import de.gurkenlabs.litiengine.configuration.GameConfiguration;
import de.gurkenlabs.litiengine.graphics.IRenderEngine;
import de.gurkenlabs.litiengine.graphics.RenderEngine;
import de.gurkenlabs.litiengine.gui.screens.IScreenManager;
import de.gurkenlabs.litiengine.gui.screens.ScreenManager;
import de.gurkenlabs.litiengine.input.Input;
import de.gurkenlabs.litiengine.physics.IPhysicsEngine;
import de.gurkenlabs.litiengine.physics.PhysicsEngine;
public abstract class Game implements IInitializable, ILaunchable {
private static GameInfo info;
private static final GameConfiguration configuration = new GameConfiguration();
private static IScreenManager screenManager;
private static IRenderEngine graphicsEngine;
private static IPhysicsEngine physicsEngine;
private static IGameLoop gameLoop;
private static GameMetrics metrics;
private final RenderLoop renderLoop;
protected Game() {
final GameInfo inf = this.getClass().getAnnotation(GameInfo.class);
if (inf == null) {
throw new AnnotationFormatError("No GameInfo annotation found on game implementation " + this.getClass());
}
info = inf;
String gameTitle = !getInfo().subTitle().isEmpty() ? getInfo().name() + " - " + getInfo().subTitle() + " " + getInfo().version() : getInfo().name() + " - " + getInfo().version();
final ScreenManager scrMgr = new ScreenManager(gameTitle);
// ensures that we terminate the game, when the window is closed
scrMgr.addWindowListener(new WindowHandler());
screenManager = scrMgr;
graphicsEngine = new RenderEngine(getConfiguration().GRAPHICS, getInfo().orientation());
physicsEngine = new PhysicsEngine();
metrics = new GameMetrics();
// init configuration before init method in order to use configured values
// to initialize components
getConfiguration().load();
this.renderLoop = new RenderLoop();
gameLoop = new GameLoop(getConfiguration().CLIENT.getUpdaterate());
getLoop().onUpsTracked(updateCount -> getMetrics().setUpdatesPerSecond(updateCount));
}
public static GameConfiguration getConfiguration() {
return configuration;
}
public static GameInfo getInfo() {
return info;
}
public static GameMetrics getMetrics() {
return metrics;
}
public static IGameLoop getLoop() {
return gameLoop;
}
public static IPhysicsEngine getPhysicsEngine() {
return physicsEngine;
}
public static IRenderEngine getRenderEngine() {
return graphicsEngine;
}
public static IScreenManager getScreenManager() {
return screenManager;
}
@Override
public void init() {
// init logging
if (new File("logging.properties").exists()) {
System.setProperty("java.util.logging.config.file", "logging.properties");
try {
LogManager.getLogManager().readConfiguration();
}
catch (final Exception e) {
e.printStackTrace();
}
}
// init screens
getScreenManager().init(getConfiguration().GRAPHICS.getResolutionWidth(), getConfiguration().GRAPHICS.getResolutionHeight(), getConfiguration().GRAPHICS.isFullscreen());
getScreenManager().onFpsChanged(fps -> {
getMetrics().setFramesPerSecond(fps);
});
// TODO: init sounds
// init inputs
Input.init();
getScreenManager().getRenderComponent().addMouseListener(Input.MOUSE);
getScreenManager().getRenderComponent().addMouseMotionListener(Input.MOUSE);
getScreenManager().getRenderComponent().addMouseWheelListener(Input.MOUSE);
}
@Override
public void start() {
gameLoop.start();
this.renderLoop.start();
}
@Override
public void terminate() {
gameLoop.terminate();
this.renderLoop.terminate();
}
/**
* The Class RenderLoop.
*/
private class RenderLoop extends Thread {
/** The game is running. */
private boolean gameIsRunning = true;
/** The next render tick. */
private long nextRenderTick = System.currentTimeMillis();
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
while (this.gameIsRunning) {
final int SKIP_FRAMES = 1000 / Game.getConfiguration().CLIENT.getMaxFps();
if (System.currentTimeMillis() > this.nextRenderTick) {
Game.getScreenManager().renderCurrentScreen();
this.nextRenderTick += SKIP_FRAMES;
}
}
}
/**
* Terminate.
*/
public void terminate() {
this.gameIsRunning = false;
}
}
/**
* The Class WindowHandler.
*/
private class WindowHandler implements WindowListener {
/*
* (non-Javadoc)
*
* @see
* java.awt.event.WindowListener#windowActivated(java.awt.event.WindowEvent)
*/
@Override
public void windowActivated(final WindowEvent event) {
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.WindowListener#windowClosed(java.awt.event.WindowEvent)
*/
@Override
public void windowClosed(final WindowEvent event) {
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.WindowListener#windowClosing(java.awt.event.WindowEvent)
*/
@Override
public void windowClosing(final WindowEvent event) {
Game.this.terminate();
System.exit(0);
}
/*
* (non-Javadoc)
*
* @see java.awt.event.WindowListener#windowDeactivated(java.awt.event.
* WindowEvent)
*/
@Override
public void windowDeactivated(final WindowEvent event) {
}
/*
* (non-Javadoc)
*
* @see java.awt.event.WindowListener#windowDeiconified(java.awt.event.
* WindowEvent)
*/
@Override
public void windowDeiconified(final WindowEvent event) {
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.WindowListener#windowIconified(java.awt.event.WindowEvent)
*/
@Override
public void windowIconified(final WindowEvent event) {
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.WindowListener#windowOpened(java.awt.event.WindowEvent)
*/
@Override
public void windowOpened(final WindowEvent event) {
}
}
}
| src/de/gurkenlabs/litiengine/Game.java | package de.gurkenlabs.litiengine;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.lang.annotation.AnnotationFormatError;
import java.util.logging.LogManager;
import de.gurkenlabs.core.IInitializable;
import de.gurkenlabs.core.ILaunchable;
import de.gurkenlabs.litiengine.annotation.GameInfo;
import de.gurkenlabs.litiengine.configuration.GameConfiguration;
import de.gurkenlabs.litiengine.graphics.IRenderEngine;
import de.gurkenlabs.litiengine.graphics.RenderEngine;
import de.gurkenlabs.litiengine.gui.screens.IScreenManager;
import de.gurkenlabs.litiengine.gui.screens.ScreenManager;
import de.gurkenlabs.litiengine.input.Input;
import de.gurkenlabs.litiengine.physics.IPhysicsEngine;
import de.gurkenlabs.litiengine.physics.PhysicsEngine;
public abstract class Game implements IInitializable, ILaunchable {
private static GameInfo info;
private static final GameConfiguration configuration = new GameConfiguration();
private static IScreenManager screenManager;
private static IRenderEngine graphicsEngine;
private static IPhysicsEngine physicsEngine;
private static IGameLoop gameLoop;
private static GameMetrics metrics;
private final RenderLoop renderLoop;
protected Game() {
final GameInfo inf = this.getClass().getAnnotation(GameInfo.class);
if (inf == null) {
throw new AnnotationFormatError("No GameInfo annotation found on game implementation " + this.getClass());
}
info = inf;
final ScreenManager scrMgr = new ScreenManager(getInfo().name() + " " + getInfo().version());
// ensures that we terminate the game, when the window is closed
scrMgr.addWindowListener(new WindowHandler());
screenManager = scrMgr;
graphicsEngine = new RenderEngine(getConfiguration().GRAPHICS, getInfo().orientation());
physicsEngine = new PhysicsEngine();
metrics = new GameMetrics();
// init configuration before init method in order to use configured values
// to initialize components
getConfiguration().load();
this.renderLoop = new RenderLoop();
gameLoop = new GameLoop(getConfiguration().CLIENT.getUpdaterate());
getLoop().onUpsTracked(updateCount -> getMetrics().setUpdatesPerSecond(updateCount));
}
public static GameConfiguration getConfiguration() {
return configuration;
}
public static GameInfo getInfo() {
return info;
}
public static GameMetrics getMetrics() {
return metrics;
}
public static IGameLoop getLoop() {
return gameLoop;
}
public static IPhysicsEngine getPhysicsEngine() {
return physicsEngine;
}
public static IRenderEngine getRenderEngine() {
return graphicsEngine;
}
public static IScreenManager getScreenManager() {
return screenManager;
}
@Override
public void init() {
// init logging
if (new File("logging.properties").exists()) {
System.setProperty("java.util.logging.config.file", "logging.properties");
try {
LogManager.getLogManager().readConfiguration();
}
catch (final Exception e) {
e.printStackTrace();
}
}
// init screens
getScreenManager().init(getConfiguration().GRAPHICS.getResolutionWidth(), getConfiguration().GRAPHICS.getResolutionHeight(), getConfiguration().GRAPHICS.isFullscreen());
getScreenManager().onFpsChanged(fps -> {
getMetrics().setFramesPerSecond(fps);
});
// TODO: init sounds
// init inputs
Input.init();
getScreenManager().getRenderComponent().addMouseListener(Input.MOUSE);
getScreenManager().getRenderComponent().addMouseMotionListener(Input.MOUSE);
getScreenManager().getRenderComponent().addMouseWheelListener(Input.MOUSE);
}
@Override
public void start() {
gameLoop.start();
this.renderLoop.start();
}
@Override
public void terminate() {
gameLoop.terminate();
this.renderLoop.terminate();
}
/**
* The Class RenderLoop.
*/
private class RenderLoop extends Thread {
/** The game is running. */
private boolean gameIsRunning = true;
/** The next render tick. */
private long nextRenderTick = System.currentTimeMillis();
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
while (this.gameIsRunning) {
final int SKIP_FRAMES = 1000 / Game.getConfiguration().CLIENT.getMaxFps();
if (System.currentTimeMillis() > this.nextRenderTick) {
Game.getScreenManager().renderCurrentScreen();
this.nextRenderTick += SKIP_FRAMES;
}
}
}
/**
* Terminate.
*/
public void terminate() {
this.gameIsRunning = false;
}
}
/**
* The Class WindowHandler.
*/
private class WindowHandler implements WindowListener {
/*
* (non-Javadoc)
*
* @see
* java.awt.event.WindowListener#windowActivated(java.awt.event.WindowEvent)
*/
@Override
public void windowActivated(final WindowEvent event) {
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.WindowListener#windowClosed(java.awt.event.WindowEvent)
*/
@Override
public void windowClosed(final WindowEvent event) {
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.WindowListener#windowClosing(java.awt.event.WindowEvent)
*/
@Override
public void windowClosing(final WindowEvent event) {
Game.this.terminate();
System.exit(0);
}
/*
* (non-Javadoc)
*
* @see java.awt.event.WindowListener#windowDeactivated(java.awt.event.
* WindowEvent)
*/
@Override
public void windowDeactivated(final WindowEvent event) {
}
/*
* (non-Javadoc)
*
* @see java.awt.event.WindowListener#windowDeiconified(java.awt.event.
* WindowEvent)
*/
@Override
public void windowDeiconified(final WindowEvent event) {
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.WindowListener#windowIconified(java.awt.event.WindowEvent)
*/
@Override
public void windowIconified(final WindowEvent event) {
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.WindowListener#windowOpened(java.awt.event.WindowEvent)
*/
@Override
public void windowOpened(final WindowEvent event) {
}
}
}
|
git-svn-id: https://dev.wibe.media/svn/code/java/trunk/litiengine@1348 16493bb7-3577-b145-b9c3-72a97d279fb6
| src/de/gurkenlabs/litiengine/Game.java | ||
Java | mit | b0cc35ee7443f2d223f8d77e97b51fea0744e540 | 0 | jeffwmair/Drive | package drive.controller;
import com.jwm.j3dfw.controller.Controller;
import com.jwm.j3dfw.production.Camera;
import drive.domain.car.CarMovement.Move;
import drive.geometry.objects.Car;
public class CarController extends Controller {
private Car c;
public CarController(Car c) {
super(c);
this.c = c;
}
public void leftMouseDown() {
c.setMovement(Move.ACCELERATING);
}
public void rightMouseDown() {
c.setMovement(Move.DECELERATING);
}
public void leftMouseUp() {
c.setMovement(Move.COASTING);
}
public void rightMouseUp() {
c.setMovement(Move.COASTING);
}
public void keyPress(int keyCode) {
if (keyCode == 49) {
c.toggleHoodOpenClose();
}
else if ((char)keyCode == 'r') {
c.getCamera().toggleAutoRotate();
}
else if ((char)keyCode == 't') {
c.getCamera().toggleAutoTrack();
}
}
public void setMousePosition(double xPos, double percent) {
c.setFrontWheelAngle(percent);
}
}
| src/main/drive/controller/CarController.java | package drive.controller;
import com.jwm.j3dfw.controller.Controller;
import com.jwm.j3dfw.production.Camera;
import drive.domain.car.CarMovement.Move;
import drive.geometry.objects.Car;
public class CarController extends Controller {
private Car c;
public CarController(Car c) {
super(c);
this.c = c;
}
public void leftMouseDown() {
c.setMovement(Move.ACCELERATING);
}
public void rightMouseDown() {
c.setMovement(Move.DECELERATING);
}
public void leftMouseUp() {
c.setMovement(Move.COASTING);
}
public void rightMouseUp() {
c.setMovement(Move.COASTING);
}
public void keyPress(int keyCode) {
if (keyCode == 49) {
c.toggleHoodOpenClose();
}
else if ((char)keyCode == 'r') {
c.getCamera().toggleAutoRotate();
}
else if ((char)keyCode == 't') {
c.getCamera().toggleAutoTrack();
}
}
public void setMousePosition(double xPos, double percent) {
c.setFrontWheelAngle(percent);
}
public void mouseWheelMoved(int wheelRotation) {
Camera cam = c.getCamera();
cam.setZoom(wheelRotation);
}
public void cmdMouseWheelMoved(int wheelMoved) {
Camera cam = c.getCamera();
double angleChange = wheelMoved;
cam.incrementAngle(angleChange);
}
public void shiftMouseWheelMoved(int wheelMoved) {
Camera cam = c.getCamera();
double angleChange = wheelMoved;
cam.incrementVerticalAngle(angleChange);
}
}
| moved simple camera control to the base Controller
| src/main/drive/controller/CarController.java | moved simple camera control to the base Controller |
|
Java | mit | 327bb4301b385560f10ab304bc6f7897d42335a0 | 0 | JCThePants/NucleusFramework,JCThePants/NucleusFramework | /*
* This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.jcwhatever.nucleus.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Static methods to aid with date manipulation.
*/
public final class DateUtils {
private DateUtils() {}
/**
* Specifies how time results should be rounded.
*/
public enum TimeRound {
ROUND_UP,
ROUND_DOWN
}
/**
* Get the difference between two dates in milliseconds.
*
* @param start The start date
* @param end The end date
*/
public static long getDeltaMilliseconds(Date start, Date end) {
return end.getTime() - start.getTime();
}
/**
* Get the difference between two dates in ticks.
*
* @param start The start date
* @param end The end date
*/
public static long getDeltaTicks(Date start, Date end) {
return (end.getTime() - start.getTime()) / 50;
}
/**
* Get the difference between two dates in seconds.
*
* @param start The start date
* @param end The end date
*/
public static double getDeltaSeconds(Date start, Date end) {
return (double)getDeltaMilliseconds(start, end) / 1000.0D;
}
/**
* Get the difference between two dates in seconds.
*
* @param start The start date
* @param end The end date
* @param rounding Specify how the result should be rounded
*/
public static long getDeltaSeconds(Date start, Date end, TimeRound rounding) {
double seconds = (double)getDeltaMilliseconds(start, end) / 1000.0D;
switch (rounding) {
case ROUND_UP:
return (long)Math.ceil(seconds);
case ROUND_DOWN:
return (long)Math.floor(seconds);
}
return (long)seconds;
}
/**
* Get the difference between two dates in minutes.
*
* @param start The start date
* @param end The end date
*/
public static double getDeltaMinutes(Date start, Date end) {
return getDeltaSeconds(start, end) / 60.0D;
}
/**
* Get the difference between two dates in minutes.
*
* @param start The start date
* @param end The end date
* @param rounding Specify how the result should be rounded
*/
public static long getDeltaMinutes(Date start, Date end, TimeRound rounding) {
double seconds = getDeltaSeconds(start, end, rounding) / 60.0D;
switch (rounding) {
case ROUND_UP:
return (long)Math.ceil(seconds);
case ROUND_DOWN:
return (long)Math.floor(seconds);
}
return (long)seconds;
}
/**
* Get the difference between two dates in hours.
*
* @param start The start date
* @param end The end date
*/
public static double getDeltaHours(Date start, Date end) {
return getDeltaMinutes(start, end) / 60.0D;
}
/**
* Get the difference between two dates in hours.
*
* @param start The start date
* @param end The end date
* @param rounding Specify how the result should be rounded
*/
public static long getDeltaHours(Date start, Date end, TimeRound rounding) {
double minutes = getDeltaMinutes(start, end, rounding) / 60.0D;
switch (rounding) {
case ROUND_UP:
return (long)Math.ceil(minutes);
case ROUND_DOWN:
return (long)Math.floor(minutes);
}
return (long)minutes;
}
/**
* Get the difference between two dates in days.
*
* @param start The start date
* @param end The end date
*/
public static double getDeltaDays(Date start, Date end) {
return getDeltaHours(start, end) / 24.0D;
}
/**
* Get the difference between two dates in days.
*
* @param start The start date
* @param end The end date
* @param rounding Specify how the result should be rounded
*/
public static long getDeltaDays(Date start, Date end, TimeRound rounding) {
double hours = (double)getDeltaHours(start, end, rounding) / 24.0D;
switch (rounding) {
case ROUND_UP:
return (long)Math.ceil(hours);
case ROUND_DOWN:
return (long)Math.floor(hours);
}
return (long)hours;
}
/**
* Format a {@link java.util.Date} object using {@link java.text.SimpleDateFormat}.
*
* @param date The date to format
* @param format The format to use
*/
public static String format(Date date, String format) {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.format(date);
}
/**
* Add milliseconds to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of milliseconds to add.
*/
public static Date addMilliseconds(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.MILLISECOND, amount);
}
/**
* Add ticks to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of ticks to add.
*/
public static Date addTicks(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.MILLISECOND, amount * 50);
}
/**
* Add seconds to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of seconds to add.
*/
public static Date addSeconds(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.SECOND, amount);
}
/**
* Add minutes to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of minutes to add.
*/
public static Date addMinutes(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.MINUTE, amount);
}
/**
* Add hours to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of hours to add.
*/
public static Date addHours(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.HOUR_OF_DAY, amount);
}
/**
* Add days (24 hour increments) to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of days to add.
*/
public static Date addDays(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.HOUR_OF_DAY, amount * 24);
}
/**
* Add weeks to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of weeks to add.
*/
public static Date addWeeks(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.WEEK_OF_YEAR, amount);
}
/**
* Add months to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of months to add.
*/
public static Date addMonths(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.MONTH, amount);
}
/**
* Add years to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of years to add.
*/
public static Date addYears(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.YEAR, amount);
}
private static Date add(Date date, int field, int amount) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(field, amount);
return calendar.getTime();
}
}
| src/com/jcwhatever/nucleus/utils/DateUtils.java | /*
* This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.jcwhatever.nucleus.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Static methods to aid with date manipulation.
*/
public final class DateUtils {
private DateUtils() {}
/**
* Specifies how time results should be rounded.
*/
public enum TimeRound {
ROUND_UP,
ROUND_DOWN
}
/**
* Get the difference between two dates in milliseconds.
*
* @param start The start date
* @param end The end date
*/
public static long getDeltaMilliseconds(Date start, Date end) {
return end.getTime() - start.getTime();
}
/**
* Get the difference between two dates in ticks.
*
* @param start The start date
* @param end The end date
*/
public static long getDeltaTicks(Date start, Date end) {
return (end.getTime() - start.getTime()) / 50;
}
/**
* Get the difference between two dates in seconds.
*
* @param start The start date
* @param end The end date
*/
public static double getDeltaSeconds(Date start, Date end) {
return (double)getDeltaMilliseconds(start, end) / 1000.0D;
}
/**
* Get the difference between two dates in seconds.
*
* @param start The start date
* @param end The end date
* @param rounding Specify how the result should be rounded
*/
public static long getDeltaSeconds(Date start, Date end, TimeRound rounding) {
double seconds = (double)getDeltaMilliseconds(start, end) / 1000.0D;
switch (rounding) {
case ROUND_UP:
return (long)Math.ceil(seconds);
case ROUND_DOWN:
return (long)Math.floor(seconds);
}
return (long)seconds;
}
/**
* Get the difference between two dates in minutes.
*
* @param start The start date
* @param end The end date
*/
public static double getDeltaMinutes(Date start, Date end) {
return getDeltaSeconds(start, end) / 60.0D;
}
/**
* Get the difference between two dates in minutes.
*
* @param start The start date
* @param end The end date
* @param rounding Specify how the result should be rounded
*/
public static long getDeltaMinutes(Date start, Date end, TimeRound rounding) {
double seconds = getDeltaSeconds(start, end, rounding) / 60.0D;
switch (rounding) {
case ROUND_UP:
return (long)Math.ceil(seconds);
case ROUND_DOWN:
return (long)Math.floor(seconds);
}
return (long)seconds;
}
/**
* Get the difference between two dates in hours.
*
* @param start The start date
* @param end The end date
*/
public static double getDeltaHours(Date start, Date end) {
return getDeltaMinutes(start, end) / 60.0D;
}
/**
* Get the difference between two dates in hours.
*
* @param start The start date
* @param end The end date
* @param rounding Specify how the result should be rounded
*/
public static long getDeltaHours(Date start, Date end, TimeRound rounding) {
double minutes = getDeltaMinutes(start, end, rounding) / 60.0D;
switch (rounding) {
case ROUND_UP:
return (long)Math.ceil(minutes);
case ROUND_DOWN:
return (long)Math.floor(minutes);
}
return (long)minutes;
}
/**
* Get the difference between two dates in days.
*
* @param start The start date
* @param end The end date
*/
public static double getDeltaDays(Date start, Date end) {
return getDeltaHours(start, end) / 24.0D;
}
/**
* Get the difference between two dates in days.
*
* @param start The start date
* @param end The end date
* @param rounding Specify how the result should be rounded
*/
public static long getDeltaDays(Date start, Date end, TimeRound rounding) {
double hours = (double)getDeltaHours(start, end, rounding) / 24.0D;
switch (rounding) {
case ROUND_UP:
return (long)Math.ceil(hours);
case ROUND_DOWN:
return (long)Math.floor(hours);
}
return (long)hours;
}
/**
* Format a {@link java.util.Date} object using {@link java.text.SimpleDateFormat}.
*
* @param date The date to format
* @param format The format to use
*/
public static String format(Date date, String format) {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.format(date);
}
/**
* Add milliseconds to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of milliseconds to add.
*/
public static Date addMilliseconds(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.MILLISECOND, amount);
}
/**
* Add ticks to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of ticks to add.
*/
public static Date addTicks(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.MILLISECOND, amount * 50);
}
/**
* Add seconds to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of seconds to add.
*/
public static Date addSeconds(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.SECOND, amount);
}
/**
* Add minutes to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of minutes to add.
*/
public static Date addMinutes(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.MINUTE, amount);
}
/**
* Add hours to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of hours to add.
*/
public static Date addHours(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.HOUR_OF_DAY, amount);
}
/**
* Add days to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of days to add.
*/
public static Date addDays(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.DAY_OF_MONTH, amount);
}
/**
* Add weeks to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of weeks to add.
*/
public static Date addWeeks(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.WEEK_OF_YEAR, amount);
}
/**
* Add months to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of months to add.
*/
public static Date addMonths(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.MONTH, amount);
}
/**
* Add years to the specified date and return a new
* {@link java.util.Date} object.
*
* @param date The date to modify.
* @param amount The number of years to add.
*/
public static Date addYears(Date date, int amount) {
PreCon.notNull(date);
return add(date, Calendar.YEAR, amount);
}
private static Date add(Date date, int field, int amount) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(field, amount);
return calendar.getTime();
}
}
| fix DateUtils#addDays
add 24 hour increments without any special considerations
| src/com/jcwhatever/nucleus/utils/DateUtils.java | fix DateUtils#addDays |
|
Java | epl-1.0 | be62f29afc16b9f1686b995434f3890e04d0bfc3 | 0 | mduft/lcdsl | /*
* Copyright (c) SSI Schaefer IT Solutions
*/
package com.wamas.ide.launching.ui.launchview;
import java.util.Set;
import java.util.TreeSet;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.launchview.LaunchView;
import org.eclipse.debug.ui.launchview.services.AbstractLaunchObjectProvider;
import org.eclipse.debug.ui.launchview.services.LaunchObject;
import org.eclipse.debug.ui.launchview.services.LaunchObjectProvider;
import org.eclipse.e4.core.di.annotations.CanExecute;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.ui.model.application.ui.menu.ItemType;
import org.eclipse.e4.ui.model.application.ui.menu.MDirectMenuItem;
import org.eclipse.e4.ui.model.application.ui.menu.MMenu;
import org.eclipse.e4.ui.model.application.ui.menu.MMenuFactory;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.xtext.EcoreUtil2;
import org.eclipse.xtext.resource.IEObjectDescription;
import org.eclipse.xtext.resource.IResourceDescriptions;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import com.wamas.ide.launching.generator.LcDslGenerator;
import com.wamas.ide.launching.generator.StandaloneLaunchConfigGenerator;
import com.wamas.ide.launching.lcDsl.LaunchConfig;
import com.wamas.ide.launching.lcDsl.LcDslPackage;
import com.wamas.ide.launching.ui.LcDslHelper;
import com.wamas.ide.launching.ui.internal.LaunchingActivator;
import com.wamas.ide.launching.ui.internal.LcDslInternalHelper;
@Component(service = LaunchObjectProvider.class)
public class LcDslProvider extends AbstractLaunchObjectProvider implements LaunchObjectProvider {
private final ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
private final Runnable generatorListener = () -> fireUpdate();
private boolean hideManual = true;
private StandaloneLaunchConfigGenerator generator;
private static final String HIDE_PREF = "lcdsl.hideManual";
@Activate
public void createService() {
LcDslGenerator.addListener(generatorListener);
getPreferenceStore().setDefault(HIDE_PREF, true);
hideManual = getPreferenceStore().getBoolean(HIDE_PREF);
generator = LcDslHelper.getInjector().getInstance(StandaloneLaunchConfigGenerator.class);
}
private IPreferenceStore getPreferenceStore() {
return LaunchingActivator.getInstance().getPreferenceStore();
}
@Deactivate
public void destroyService() {
LcDslGenerator.removeListener(generatorListener);
}
@Override
public Set<LcDslLaunchObject> getLaunchObjects() {
IResourceDescriptions index = LcDslHelper.getInjector().getInstance(IResourceDescriptions.class);
ResourceSet set = LcDslHelper.getInjector().getInstance(ResourceSet.class);
Set<LcDslLaunchObject> result = new TreeSet<>();
Iterable<IEObjectDescription> descs = index.getExportedObjectsByType(LcDslPackage.eINSTANCE.getLaunchConfig());
for (IEObjectDescription obj : descs) {
EObject lc = EcoreUtil2.resolve(obj.getEObjectOrProxy(), set);
if (lc instanceof LaunchConfig) {
LaunchConfig l = (LaunchConfig) lc;
if (l.isAbstract()) {
continue;
}
LcDslLaunchObject o = new LcDslLaunchObject((LaunchConfig) lc);
if (o.getType() == null) { // unsupported type
continue;
}
// only hide manual if there is no other object it would be (properly) hiding
if (hideManual && l.isManual() && findLaunchConfiguration(o.getType(), generator.fullName(l)) == null) {
continue;
}
result.add(o);
}
}
return result;
}
ILaunchConfiguration findLaunchConfiguration(ILaunchConfigurationType type, String name) {
try {
for (ILaunchConfiguration config : manager.getLaunchConfigurations(type)) {
if (config.getName().equals(name)) {
return config;
}
}
return null;
} catch (Exception e) {
throw new RuntimeException("cannot fetch existing launch configurations", e);
}
}
@Override
public int getPriority() {
return 10; // more prio than the debug core version
}
@Override
public void contributeViewMenu(LaunchView view, MMenu menu) {
MDirectMenuItem hide = MMenuFactory.INSTANCE.createDirectMenuItem();
hide.setLabel("Hide 'manual' LcDsl configurations");
hide.setType(ItemType.CHECK);
hide.setSelected(hideManual);
hide.setIconURI("platform:/plugin/" + LcDslInternalHelper.PLUGIN_ID + "/icons/clear.gif");
hide.setObject(new Object() {
@Execute
public void toggleHide() {
hideManual = hide.isSelected();
getPreferenceStore().setValue(HIDE_PREF, hideManual);
fireUpdate();
}
});
MDirectMenuItem cleanup = MMenuFactory.INSTANCE.createDirectMenuItem();
cleanup.setLabel("Remove 'manual' LcDsl artifacts");
cleanup.setTooltip(
"Removes all launch configurations from Eclipse that have been generated from a 'manual' LcDsl launch configuration");
cleanup.setIconURI("platform:/plugin/" + LcDslInternalHelper.PLUGIN_ID + "/icons/clear.gif");
cleanup.setObject(new Object() {
@Execute
public void cleanup() {
for (LcDslLaunchObject lo : getLaunchObjects()) {
if (!lo.getLaunchConfig().isManual()) {
continue;
}
ILaunchConfiguration c = findLaunchConfiguration(lo.getType(), lo.getId());
if (c != null) {
try {
c.delete();
} catch (CoreException e) {
LcDslInternalHelper.log(IStatus.WARNING, "cannot delete generated configuration " + c.getName(), e);
}
}
}
fireUpdate();
}
});
menu.getChildren().add(MMenuFactory.INSTANCE.createMenuSeparator());
menu.getChildren().add(hide);
menu.getChildren().add(cleanup);
}
@Override
public void contributeContextMenu(LaunchView view, MMenu menu) {
// (re-)generate launch configurations
MDirectMenuItem generate = MMenuFactory.INSTANCE.createDirectMenuItem();
generate.setLabel("(Re-)generate Eclipse launch configuration");
generate.setTooltip("Generates the Eclipse launch configuration from this LcDsl launch configuration");
generate.setIconURI("platform:/plugin/" + LcDslInternalHelper.PLUGIN_ID + "/icons/launch_run.gif");
generate.setObject(new Object() {
@Execute
public void generate() {
for (LaunchObject e : view.getSelectedElements()) {
LcDslLaunchObject o = (LcDslLaunchObject) e;
LcDslHelper.getInstance().generate(o.getLaunchConfig());
}
fireUpdate();
}
@CanExecute
public boolean isEnabled() {
return view.getSelectedElements().stream().allMatch(e -> e instanceof LcDslLaunchObject);
}
});
// cleanup existing launch configurations
MDirectMenuItem cleanup = MMenuFactory.INSTANCE.createDirectMenuItem();
cleanup.setLabel("Remove generated launch configuration");
cleanup.setTooltip(
"Removes the launch configuration from Eclipse that has been generated from this LcDsl launch configuration");
cleanup.setIconURI("platform:/plugin/" + LcDslInternalHelper.PLUGIN_ID + "/icons/clear.gif");
cleanup.setObject(new Object() {
@Execute
public void cleanup() throws CoreException {
for (LaunchObject e : view.getSelectedElements()) {
findLaunchConfiguration(e.getType(), e.getId()).delete();
}
fireUpdate();
}
@CanExecute
public boolean isEnabled() {
return view.getSelectedElements().stream()
.allMatch(e -> e instanceof LcDslLaunchObject && findLaunchConfiguration(e.getType(), e.getId()) != null);
}
});
menu.getChildren().add(MMenuFactory.INSTANCE.createMenuSeparator());
menu.getChildren().add(generate);
menu.getChildren().add(cleanup);
}
}
| com.wamas.ide.launching.ui/src/com/wamas/ide/launching/ui/launchview/LcDslProvider.java | /*
* Copyright (c) SSI Schaefer IT Solutions
*/
package com.wamas.ide.launching.ui.launchview;
import java.util.Set;
import java.util.TreeSet;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.launchview.services.AbstractLaunchObjectProvider;
import org.eclipse.debug.ui.launchview.services.LaunchObjectProvider;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.ui.model.application.ui.menu.ItemType;
import org.eclipse.e4.ui.model.application.ui.menu.MDirectMenuItem;
import org.eclipse.e4.ui.model.application.ui.menu.MMenu;
import org.eclipse.e4.ui.model.application.ui.menu.MMenuFactory;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.xtext.EcoreUtil2;
import org.eclipse.xtext.resource.IEObjectDescription;
import org.eclipse.xtext.resource.IResourceDescriptions;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import com.wamas.ide.launching.generator.LcDslGenerator;
import com.wamas.ide.launching.generator.StandaloneLaunchConfigGenerator;
import com.wamas.ide.launching.lcDsl.LaunchConfig;
import com.wamas.ide.launching.lcDsl.LcDslPackage;
import com.wamas.ide.launching.ui.LcDslHelper;
import com.wamas.ide.launching.ui.internal.LaunchingActivator;
import com.wamas.ide.launching.ui.internal.LcDslInternalHelper;
@Component(service = LaunchObjectProvider.class)
public class LcDslProvider extends AbstractLaunchObjectProvider implements LaunchObjectProvider {
private final ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
private final Runnable generatorListener = () -> fireUpdate();
private boolean hideManual = true;
private StandaloneLaunchConfigGenerator generator;
private static final String HIDE_PREF = "lcdsl.hideManual";
@Activate
public void createService() {
LcDslGenerator.addListener(generatorListener);
getPreferenceStore().setDefault(HIDE_PREF, true);
hideManual = getPreferenceStore().getBoolean(HIDE_PREF);
generator = LcDslHelper.getInjector().getInstance(StandaloneLaunchConfigGenerator.class);
}
private IPreferenceStore getPreferenceStore() {
return LaunchingActivator.getInstance().getPreferenceStore();
}
@Deactivate
public void destroyService() {
LcDslGenerator.removeListener(generatorListener);
}
@Override
public Set<LcDslLaunchObject> getLaunchObjects() {
IResourceDescriptions index = LcDslHelper.getInjector().getInstance(IResourceDescriptions.class);
ResourceSet set = LcDslHelper.getInjector().getInstance(ResourceSet.class);
Set<LcDslLaunchObject> result = new TreeSet<>();
Iterable<IEObjectDescription> descs = index.getExportedObjectsByType(LcDslPackage.eINSTANCE.getLaunchConfig());
for (IEObjectDescription obj : descs) {
EObject lc = EcoreUtil2.resolve(obj.getEObjectOrProxy(), set);
if (lc instanceof LaunchConfig) {
LaunchConfig l = (LaunchConfig) lc;
if (l.isAbstract()) {
continue;
}
LcDslLaunchObject o = new LcDslLaunchObject((LaunchConfig) lc);
if (o.getType() == null) { // unsupported type
continue;
}
// only hide manual if there is no other object it would be (properly) hiding
if (hideManual && l.isManual() && findLaunchConfiguration(o.getType(), generator.fullName(l)) == null) {
continue;
}
result.add(o);
}
}
return result;
}
ILaunchConfiguration findLaunchConfiguration(ILaunchConfigurationType type, String name) {
try {
for (ILaunchConfiguration config : manager.getLaunchConfigurations(type)) {
if (config.getName().equals(name)) {
return config;
}
}
return null;
} catch (Exception e) {
throw new RuntimeException("cannot fetch existing launch configurations", e);
}
}
@Override
public int getPriority() {
return 10; // more prio than the debug core version
}
@Override
public void contributeViewMenu(MMenu menu) {
MDirectMenuItem hide = MMenuFactory.INSTANCE.createDirectMenuItem();
hide.setLabel("Hide 'manual' LcDsl configurations");
hide.setType(ItemType.CHECK);
hide.setSelected(hideManual);
hide.setIconURI("platform:/plugin/" + LcDslInternalHelper.PLUGIN_ID + "/icons/clear.gif");
hide.setObject(new Object() {
@Execute
public void toggleHide() {
hideManual = hide.isSelected();
getPreferenceStore().setValue(HIDE_PREF, hideManual);
fireUpdate();
}
});
MDirectMenuItem cleanup = MMenuFactory.INSTANCE.createDirectMenuItem();
cleanup.setLabel("Remove 'manual' LcDsl artifacts");
cleanup.setTooltip(
"Removes all launch configurations from Eclipse that have been generated from a 'manual' LcDsl launch configuration");
cleanup.setIconURI("platform:/plugin/" + LcDslInternalHelper.PLUGIN_ID + "/icons/clear.gif");
cleanup.setObject(new Object() {
@Execute
public void cleanup() {
for (LcDslLaunchObject lo : getLaunchObjects()) {
if (!lo.getLaunchConfig().isManual()) {
continue;
}
ILaunchConfiguration c = findLaunchConfiguration(lo.getType(), lo.getId());
if (c != null) {
try {
c.delete();
} catch (CoreException e) {
LcDslInternalHelper.log(IStatus.WARNING, "cannot delete generated configuration " + c.getName(), e);
}
}
}
fireUpdate();
}
});
menu.getChildren().add(MMenuFactory.INSTANCE.createMenuSeparator());
menu.getChildren().add(hide);
menu.getChildren().add(cleanup);
}
}
| Update to recent View changes. Implement explicit generate/remove | com.wamas.ide.launching.ui/src/com/wamas/ide/launching/ui/launchview/LcDslProvider.java | Update to recent View changes. Implement explicit generate/remove |
|
Java | agpl-3.0 | 178674cbf87b771bcf8a254fa2e13221131af74b | 0 | VoltDB/voltdb,VoltDB/voltdb,VoltDB/voltdb,VoltDB/voltdb,VoltDB/voltdb,VoltDB/voltdb,VoltDB/voltdb | /* This file is part of VoltDB.
* Copyright (C) 2008-2019 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.iv2;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.Mailbox;
import org.voltcore.utils.CoreUtils;
import org.voltcore.utils.Pair;
import org.voltdb.DRConsumerDrIdTracker.DRSiteDrIdTracker;
import org.voltdb.SiteProcedureConnection;
import org.voltdb.SnapshotCompletionInterest.SnapshotCompletionEvent;
import org.voltdb.SnapshotSaveAPI;
import org.voltdb.VoltDB;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.Table;
import org.voltdb.messaging.RejoinMessage;
import org.voltdb.messaging.RejoinMessage.Type;
import org.voltdb.rejoin.StreamSnapshotDataTarget;
import org.voltdb.rejoin.StreamSnapshotSink;
import org.voltdb.rejoin.StreamSnapshotSink.RestoreWork;
import org.voltdb.rejoin.TaskLog;
import org.voltdb.utils.CatalogUtil;
/**
* Manages the lifecycle of snapshot serialization to a site
* for the purposes of rejoin.
*/
public class RejoinProducer extends JoinProducerBase {
private static final VoltLogger REJOINLOG = new VoltLogger("REJOIN");
private final AtomicBoolean m_currentlyRejoining;
private static ScheduledFuture<?> m_timeFuture;
private Mailbox m_streamSnapshotMb = null;
private StreamSnapshotSink m_rejoinSiteProcessor = null;
// Stores the name of the views to pause/resume during a rejoin stream snapshot restore process.
private String m_commaSeparatedNameOfViewsToPause = null;
// True if there are any persistent tables in the schema.
boolean m_hasPersistentTables = true;
// Barrier that prevents the finish task for firing until all sites have finished the stream snapshot
private static AtomicInteger s_streamingSiteCount;
// Get the snapshot nonce from the RejoinCoordinator's INITIATION message.
// Then register the completion interest.
//
// When the completion interest callback fires for the nonce,
// capture the snapshot txnid and tell the replay agent the snapshot is
// complete and unregister the interest.
//
// The txnId informs post-rejoin replay where to start. TxnId
// is stored in a ReplayCompletionAction which also bundles
// the Replay complete logic; When the snapshot transfer is
// complete, the RejoinProducer will hand the ReplayCompletionAction
// to the Site which must take its own action to conclude rejoin and
// then run the ReplayCompleteAction.
//
// The rest of RejoinProducer is driven by the snapshot sink..
//
// When the first data sink block arrives, offer the
// producer to the SiteTaskerQueue.
//
// Blocking and nonblocking work the same now, the only difference
// is that in blocking the snapshot transaction blocks on streaming all data
//
// In both cases, the site is responding with REJOINING to
// all incoming tasks.
//
// Conditions to complete RejoinProducer and
// transition to the Site controlled portion of rejoin:
// 1. Snapshot must be fully transfered (sink EOF reached)
// 2. The snapshot completion monitor callback must have been
// triggered.
//
// The rejoin producer times out the snapshot block arrival.
// If a block does not arrive within 60s, the RejoinProducer
// terminates the current node. The watchdog timer is accessed
// from multiple threads
/**
* ReplayCompletionAction communicates the snapshot txn id to
* the site and offers a run() method that closes the open
* rejoin state with the rejoin coordinator once the site has
* concluded rejoin.
*/
public class ReplayCompletionAction extends JoinCompletionAction
{
@Override
public void run()
{
REJOINLOG.debug(m_whoami + "informing rejoinCoordinator "
+ CoreUtils.hsIdToString(m_coordinatorHsId)
+ " of REPLAY_FINISHED");
RejoinMessage replay_complete = new RejoinMessage(
m_mailbox.getHSId(), RejoinMessage.Type.REPLAY_FINISHED);
m_mailbox.send(m_coordinatorHsId, replay_complete);
m_currentlyRejoining.set(false);
SnapshotSaveAPI.recoveringSiteCount.decrementAndGet();
}
}
public static void initBarrier(int siteCount) {
s_streamingSiteCount = new AtomicInteger(siteCount);
}
// Run if the watchdog isn't cancelled within the timeout period
private static class TimerCallback implements Runnable
{
@Override
public void run()
{
VoltDB.crashLocalVoltDB(String.format(
"Rejoin process timed out due to no data sent from active nodes for %d seconds Terminating rejoin.",
StreamSnapshotDataTarget.DEFAULT_WRITE_TIMEOUT_MS / 1000),
false,
null);
}
}
// Only instantiated if it must be used. This is important because
// m_currentlyRejoining gates promotion to master. If the rejoin producer
// is instantiated, it must complete its execution and set currentlyRejoining
// to false.
public RejoinProducer(int partitionId, SiteTaskerQueue taskQueue)
{
super(partitionId, "Rejoin producer:" + partitionId + " ", taskQueue);
m_currentlyRejoining = new AtomicBoolean(true);
m_completionAction = new ReplayCompletionAction();
if (REJOINLOG.isDebugEnabled()) {
REJOINLOG.debug(m_whoami + "created.");
}
}
@Override
public boolean acceptPromotion()
{
return !m_currentlyRejoining.get();
}
@Override
public void deliver(RejoinMessage message)
{
if (message.getType() == RejoinMessage.Type.INITIATION
|| message.getType() == RejoinMessage.Type.INITIATION_COMMUNITY) {
doInitiation(message);
}
else {
VoltDB.crashLocalVoltDB(
"Unknown rejoin message type: " + message.getType(), false,
null);
}
}
@Override
public TaskLog constructTaskLog(String voltroot)
{
m_taskLog = initializeTaskLog(voltroot, m_partitionId);
return m_taskLog;
}
@Override
protected VoltLogger getLogger() {
return REJOINLOG;
}
// cancel and maybe rearm the node-global snapshot data-segment watchdog.
@Override
protected void kickWatchdog(boolean rearm)
{
synchronized (RejoinProducer.class) {
if (m_timeFuture != null) {
m_timeFuture.cancel(false);
m_timeFuture = null;
}
if (rearm) {
m_timeFuture = VoltDB.instance().scheduleWork(
new TimerCallback(),
StreamSnapshotDataTarget.DEFAULT_WRITE_TIMEOUT_MS,
0,
TimeUnit.MILLISECONDS);
}
}
}
/**
* Runs when the RejoinCoordinator decides this site should start
* rejoin.
*/
void doInitiation(RejoinMessage message)
{
m_coordinatorHsId = message.m_sourceHSId;
m_hasPersistentTables = message.schemaHasPersistentTables();
if (m_hasPersistentTables) {
m_streamSnapshotMb = VoltDB.instance().getHostMessenger().createMailbox();
m_rejoinSiteProcessor = new StreamSnapshotSink(m_streamSnapshotMb);
// Start the watchdog so if we never get data it will notice
kickWatchdog(true);
} else {
m_streamSnapshotMb = null;
m_rejoinSiteProcessor = null;
}
// MUST choose the leader as the source.
long sourceSite = m_mailbox.getMasterHsId(m_partitionId);
// The lowest partition has a single source for all messages whereas all other partitions have a real
// data source and a dummy data source for replicated tables that are used to sync up replicated table changes.
boolean haveTwoSources = VoltDB.instance().getLowestPartitionId() != m_partitionId;
// Provide a valid sink host id unless it is an empty database.
long hsId = (m_rejoinSiteProcessor != null
? m_rejoinSiteProcessor.initialize(haveTwoSources?2:1,
message.getSnapshotDataBufferPool(),
message.getSnapshotCompressedDataBufferPool())
: Long.MIN_VALUE);
REJOINLOG.debug(m_whoami
+ "received INITIATION message. Doing rejoin"
+ ". Source site is: "
+ CoreUtils.hsIdToString(sourceSite)
+ " and destination rejoin processor is: "
+ CoreUtils.hsIdToString(hsId)
+ " and snapshot nonce is: "
+ message.getSnapshotNonce());
registerSnapshotMonitor(message.getSnapshotNonce());
// Tell the RejoinCoordinator everything it will need to know to get us our snapshot stream.
RejoinMessage initResp = new RejoinMessage(m_mailbox.getHSId(), sourceSite, hsId);
m_mailbox.send(m_coordinatorHsId, initResp);
// Start waiting for snapshot data
m_taskQueue.offer(this);
}
/**
* SiteTasker run -- load this site!
*
* run() is invoked when the RejoinProducer (this) submits itself to the
* site tasker. RejoinProducer submits itself to the site tasker queue
* when rejoin data is available. Rejoin data is available after the
* snapshot request is fulfilled. The snapshot request is made by the rejoin
* coordinator on our behalf.
*/
@Override
public void run(SiteProcedureConnection siteConnection)
{
throw new RuntimeException(
"Unexpected execution of run method in rejoin producer.");
}
/**
* An implementation of run() that does not block the site thread.
* The Site has responsibility for transactions that occur between
* schedulings of this task.
*/
@Override
public void runForRejoin(SiteProcedureConnection siteConnection,
TaskLog m_taskLog) throws IOException
{
// After doInitialization(), the rejoin producer is inserted into the task queue,
// and then we come here repeatedly until the stream snapshot restore finishes.
// The first time when this producer method is run (m_commaSeparatedNameOfViewsToPause is null),
// we need to figure out which views to pause so that they are handled properly
// before the snapshot streams arrive.
if (m_commaSeparatedNameOfViewsToPause == null) {
// The very first execution of runForRejoin will lead us here.
StringBuilder commaSeparatedViewNames = new StringBuilder();
Database db = VoltDB.instance().getCatalogContext().database;
for (Table table : VoltDB.instance().getCatalogContext().tables) {
if (CatalogUtil.isSnapshotablePersistentTableView(db, table)) {
// If the table is a snapshotted persistent table view, we will try to
// temporarily disable its maintenance job to boost restore performance.
commaSeparatedViewNames.append(table.getTypeName()).append(",");
}
}
// Get rid of the trailing comma.
if (commaSeparatedViewNames.length() > 0) {
commaSeparatedViewNames.setLength(commaSeparatedViewNames.length() - 1);
}
m_commaSeparatedNameOfViewsToPause = commaSeparatedViewNames.toString();
// Set enabled to false for the views we found.
siteConnection.setViewsEnabled(m_commaSeparatedNameOfViewsToPause, false);
}
if (m_hasPersistentTables) {
boolean sourcesReady = false;
RestoreWork rejoinWork = m_rejoinSiteProcessor.poll(m_snapshotBufferAllocator);
if (rejoinWork != null) {
restoreBlock(rejoinWork, siteConnection);
sourcesReady = true;
}
if (m_rejoinSiteProcessor.isEOF() == false) {
returnToTaskQueue(sourcesReady);
} else {
REJOINLOG.debug(m_whoami + "Rejoin snapshot transfer is finished");
m_rejoinSiteProcessor.close();
boolean allSitesFinishStreaming;
if (m_streamSnapshotMb != null) {
VoltDB.instance().getHostMessenger().removeMailbox(m_streamSnapshotMb.getHSId());
m_streamSnapshotMb = null;
allSitesFinishStreaming = s_streamingSiteCount.decrementAndGet() == 0;
}
else {
int pendingSites = s_streamingSiteCount.get();
assert(pendingSites >= 0);
allSitesFinishStreaming = pendingSites == 0;
}
if (allSitesFinishStreaming) {
doFinishingTask(siteConnection);
}
else {
returnToTaskQueue(sourcesReady);
}
}
}
else {
doFinishingTask(siteConnection);
// Remove the completion monitor for an empty (zero table) rejoin.
m_snapshotCompletionMonitor.set(null);
}
}
private void doFinishingTask(final SiteProcedureConnection siteConnection) {
/*
* Don't notify the rejoin coordinator yet. The stream snapshot may
* have not finished on all nodes, let the snapshot completion
* monitor tell the rejoin coordinator.
*
* This used to block on the completion interest, but this raced
* with fragments from the MPI that needed dummy responses. If the fragments
* came after the EOF then they wouldn't receive dummy responses
* and then the MPI wouldn't invoke SnapshotSaveAPI.logParticipatingHostCount
*/
final SiteTasker finishingTask = new SiteTasker() {
@Override
public void run(SiteProcedureConnection siteConnection) {
throw new RuntimeException(
"Unexpected execution of run method in rejoin producer.");
}
@Override
public void runForRejoin(SiteProcedureConnection siteConnection, TaskLog rejoinTaskLog) throws IOException {
if (!m_snapshotCompletionMonitor.isDone()) {
m_taskQueue.offer(this);
return;
}
assert(m_commaSeparatedNameOfViewsToPause != null);
// Resume the views.
siteConnection.setViewsEnabled(m_commaSeparatedNameOfViewsToPause, true);
SnapshotCompletionEvent event = null;
Map<String, Map<Integer, Pair<Long,Long>>> exportSequenceNumbers = null;
Map<Integer, Long> drSequenceNumbers = null;
Map<Integer, Map<Integer, Map<Integer, DRSiteDrIdTracker>>> allConsumerSiteTrackers = null;
long clusterCreateTime = -1;
try {
event = m_snapshotCompletionMonitor.get();
if (m_hasPersistentTables) {
REJOINLOG.debug(m_whoami + "waiting on snapshot completion monitor.");
exportSequenceNumbers = event.exportSequenceNumbers;
m_completionAction.setSnapshotTxnId(event.multipartTxnId);
drSequenceNumbers = event.drSequenceNumbers;
allConsumerSiteTrackers = event.drMixedClusterSizeConsumerState;
clusterCreateTime = event.clusterCreateTime;
// Tells EE which DR version going to use
siteConnection.setDRProtocolVersion(event.drVersion);
}
REJOINLOG.debug(m_whoami + " monitor completed. Sending SNAPSHOT_FINISHED "
+ "and handing off to site.");
RejoinMessage snap_complete = new RejoinMessage(
m_mailbox.getHSId(), Type.SNAPSHOT_FINISHED);
m_mailbox.send(m_coordinatorHsId, snap_complete);
} catch (InterruptedException crashme) {
VoltDB.crashLocalVoltDB(
"Interrupted awaiting snapshot completion.", true, crashme);
} catch (ExecutionException e) {
VoltDB.crashLocalVoltDB(
"Unexpected exception awaiting snapshot completion.", true,
e);
}
if (exportSequenceNumbers == null) {
// Send empty sequence number map if the schema is empty (no tables).
exportSequenceNumbers = new HashMap<String, Map<Integer, Pair<Long,Long>>>();
}
setJoinComplete(
siteConnection,
exportSequenceNumbers,
drSequenceNumbers,
allConsumerSiteTrackers,
m_hasPersistentTables /* requireExistingSequenceNumbers */,
clusterCreateTime);
}
};
try {
finishingTask.runForRejoin(siteConnection, null);
} catch (IOException e) {
VoltDB.crashLocalVoltDB("Unexpected IOException in rejoin", true, e);
}
}
}
| src/frontend/org/voltdb/iv2/RejoinProducer.java | /* This file is part of VoltDB.
* Copyright (C) 2008-2019 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.iv2;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.Mailbox;
import org.voltcore.utils.CoreUtils;
import org.voltcore.utils.Pair;
import org.voltdb.DRConsumerDrIdTracker.DRSiteDrIdTracker;
import org.voltdb.SiteProcedureConnection;
import org.voltdb.SnapshotCompletionInterest.SnapshotCompletionEvent;
import org.voltdb.SnapshotSaveAPI;
import org.voltdb.VoltDB;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.Table;
import org.voltdb.messaging.RejoinMessage;
import org.voltdb.messaging.RejoinMessage.Type;
import org.voltdb.rejoin.StreamSnapshotDataTarget;
import org.voltdb.rejoin.StreamSnapshotSink;
import org.voltdb.rejoin.StreamSnapshotSink.RestoreWork;
import org.voltdb.rejoin.TaskLog;
import org.voltdb.utils.CatalogUtil;
/**
* Manages the lifecycle of snapshot serialization to a site
* for the purposes of rejoin.
*/
public class RejoinProducer extends JoinProducerBase {
private static final VoltLogger REJOINLOG = new VoltLogger("REJOIN");
private final AtomicBoolean m_currentlyRejoining;
private static ScheduledFuture<?> m_timeFuture;
private Mailbox m_streamSnapshotMb = null;
private StreamSnapshotSink m_rejoinSiteProcessor = null;
// Stores the name of the views to pause/resume during a rejoin stream snapshot restore process.
private String m_commaSeparatedNameOfViewsToPause = null;
// True if there are any persistent tables in the schema.
boolean m_hasPersistentTables = true;
// Barrier that prevents the finish task for firing until all sites have finished the stream snapshot
private static AtomicInteger s_streamingSiteCount;
// Get the snapshot nonce from the RejoinCoordinator's INITIATION message.
// Then register the completion interest.
//
// When the completion interest callback fires for the nonce,
// capture the snapshot txnid and tell the replay agent the snapshot is
// complete and unregister the interest.
//
// The txnId informs post-rejoin replay where to start. TxnId
// is stored in a ReplayCompletionAction which also bundles
// the Replay complete logic; When the snapshot transfer is
// complete, the RejoinProducer will hand the ReplayCompletionAction
// to the Site which must take its own action to conclude rejoin and
// then run the ReplayCompleteAction.
//
// The rest of RejoinProducer is driven by the snapshot sink..
//
// When the first data sink block arrives, offer the
// producer to the SiteTaskerQueue.
//
// Blocking and nonblocking work the same now, the only difference
// is that in blocking the snapshot transaction blocks on streaming all data
//
// In both cases, the site is responding with REJOINING to
// all incoming tasks.
//
// Conditions to complete RejoinProducer and
// transition to the Site controlled portion of rejoin:
// 1. Snapshot must be fully transfered (sink EOF reached)
// 2. The snapshot completion monitor callback must have been
// triggered.
//
// The rejoin producer times out the snapshot block arrival.
// If a block does not arrive within 60s, the RejoinProducer
// terminates the current node. The watchdog timer is accessed
// from multiple threads
/**
* ReplayCompletionAction communicates the snapshot txn id to
* the site and offers a run() method that closes the open
* rejoin state with the rejoin coordinator once the site has
* concluded rejoin.
*/
public class ReplayCompletionAction extends JoinCompletionAction
{
@Override
public void run()
{
REJOINLOG.debug(m_whoami + "informing rejoinCoordinator "
+ CoreUtils.hsIdToString(m_coordinatorHsId)
+ " of REPLAY_FINISHED");
RejoinMessage replay_complete = new RejoinMessage(
m_mailbox.getHSId(), RejoinMessage.Type.REPLAY_FINISHED);
m_mailbox.send(m_coordinatorHsId, replay_complete);
m_currentlyRejoining.set(false);
SnapshotSaveAPI.recoveringSiteCount.decrementAndGet();
}
}
public static void initBarrier(int siteCount) {
s_streamingSiteCount = new AtomicInteger(siteCount);
}
// Run if the watchdog isn't cancelled within the timeout period
private static class TimerCallback implements Runnable
{
@Override
public void run()
{
VoltDB.crashLocalVoltDB(String.format(
"Rejoin process timed out due to no data sent from active nodes for %d seconds Terminating rejoin.",
StreamSnapshotDataTarget.DEFAULT_WRITE_TIMEOUT_MS / 1000),
false,
null);
}
}
// Only instantiated if it must be used. This is important because
// m_currentlyRejoining gates promotion to master. If the rejoin producer
// is instantiated, it must complete its execution and set currentlyRejoining
// to false.
public RejoinProducer(int partitionId, SiteTaskerQueue taskQueue)
{
super(partitionId, "Rejoin producer:" + partitionId + " ", taskQueue);
m_currentlyRejoining = new AtomicBoolean(true);
m_completionAction = new ReplayCompletionAction();
if (REJOINLOG.isDebugEnabled()) {
REJOINLOG.debug(m_whoami + "created.");
}
}
@Override
public boolean acceptPromotion()
{
return !m_currentlyRejoining.get();
}
@Override
public void deliver(RejoinMessage message)
{
if (message.getType() == RejoinMessage.Type.INITIATION
|| message.getType() == RejoinMessage.Type.INITIATION_COMMUNITY) {
doInitiation(message);
}
else {
VoltDB.crashLocalVoltDB(
"Unknown rejoin message type: " + message.getType(), false,
null);
}
}
@Override
public TaskLog constructTaskLog(String voltroot)
{
m_taskLog = initializeTaskLog(voltroot, m_partitionId);
return m_taskLog;
}
@Override
protected VoltLogger getLogger() {
return REJOINLOG;
}
// cancel and maybe rearm the node-global snapshot data-segment watchdog.
@Override
protected void kickWatchdog(boolean rearm)
{
synchronized (RejoinProducer.class) {
if (m_timeFuture != null) {
m_timeFuture.cancel(false);
m_timeFuture = null;
}
if (rearm) {
m_timeFuture = VoltDB.instance().scheduleWork(
new TimerCallback(),
StreamSnapshotDataTarget.DEFAULT_WRITE_TIMEOUT_MS,
0,
TimeUnit.MILLISECONDS);
}
}
}
/**
* Runs when the RejoinCoordinator decides this site should start
* rejoin.
*/
void doInitiation(RejoinMessage message)
{
m_coordinatorHsId = message.m_sourceHSId;
m_hasPersistentTables = message.schemaHasPersistentTables();
if (m_hasPersistentTables) {
m_streamSnapshotMb = VoltDB.instance().getHostMessenger().createMailbox();
m_rejoinSiteProcessor = new StreamSnapshotSink(m_streamSnapshotMb);
} else {
m_streamSnapshotMb = null;
m_rejoinSiteProcessor = null;
}
// MUST choose the leader as the source.
long sourceSite = m_mailbox.getMasterHsId(m_partitionId);
// The lowest partition has a single source for all messages whereas all other partitions have a real
// data source and a dummy data source for replicated tables that are used to sync up replicated table changes.
boolean haveTwoSources = VoltDB.instance().getLowestPartitionId() != m_partitionId;
// Provide a valid sink host id unless it is an empty database.
long hsId = (m_rejoinSiteProcessor != null
? m_rejoinSiteProcessor.initialize(haveTwoSources?2:1,
message.getSnapshotDataBufferPool(),
message.getSnapshotCompressedDataBufferPool())
: Long.MIN_VALUE);
REJOINLOG.debug(m_whoami
+ "received INITIATION message. Doing rejoin"
+ ". Source site is: "
+ CoreUtils.hsIdToString(sourceSite)
+ " and destination rejoin processor is: "
+ CoreUtils.hsIdToString(hsId)
+ " and snapshot nonce is: "
+ message.getSnapshotNonce());
registerSnapshotMonitor(message.getSnapshotNonce());
// Tell the RejoinCoordinator everything it will need to know to get us our snapshot stream.
RejoinMessage initResp = new RejoinMessage(m_mailbox.getHSId(), sourceSite, hsId);
m_mailbox.send(m_coordinatorHsId, initResp);
// Start waiting for snapshot data
m_taskQueue.offer(this);
}
/**
* SiteTasker run -- load this site!
*
* run() is invoked when the RejoinProducer (this) submits itself to the
* site tasker. RejoinProducer submits itself to the site tasker queue
* when rejoin data is available. Rejoin data is available after the
* snapshot request is fulfilled. The snapshot request is made by the rejoin
* coordinator on our behalf.
*/
@Override
public void run(SiteProcedureConnection siteConnection)
{
throw new RuntimeException(
"Unexpected execution of run method in rejoin producer.");
}
/**
* An implementation of run() that does not block the site thread.
* The Site has responsibility for transactions that occur between
* schedulings of this task.
*/
@Override
public void runForRejoin(SiteProcedureConnection siteConnection,
TaskLog m_taskLog) throws IOException
{
// After doInitialization(), the rejoin producer is inserted into the task queue,
// and then we come here repeatedly until the stream snapshot restore finishes.
// The first time when this producer method is run (m_commaSeparatedNameOfViewsToPause is null),
// we need to figure out which views to pause so that they are handled properly
// before the snapshot streams arrive.
if (m_commaSeparatedNameOfViewsToPause == null) {
// The very first execution of runForRejoin will lead us here.
StringBuilder commaSeparatedViewNames = new StringBuilder();
Database db = VoltDB.instance().getCatalogContext().database;
for (Table table : VoltDB.instance().getCatalogContext().tables) {
if (CatalogUtil.isSnapshotablePersistentTableView(db, table)) {
// If the table is a snapshotted persistent table view, we will try to
// temporarily disable its maintenance job to boost restore performance.
commaSeparatedViewNames.append(table.getTypeName()).append(",");
}
}
// Get rid of the trailing comma.
if (commaSeparatedViewNames.length() > 0) {
commaSeparatedViewNames.setLength(commaSeparatedViewNames.length() - 1);
}
m_commaSeparatedNameOfViewsToPause = commaSeparatedViewNames.toString();
// Set enabled to false for the views we found.
siteConnection.setViewsEnabled(m_commaSeparatedNameOfViewsToPause, false);
}
if (m_hasPersistentTables) {
boolean sourcesReady = false;
RestoreWork rejoinWork = m_rejoinSiteProcessor.poll(m_snapshotBufferAllocator);
if (rejoinWork != null) {
restoreBlock(rejoinWork, siteConnection);
sourcesReady = true;
}
if (m_rejoinSiteProcessor.isEOF() == false) {
returnToTaskQueue(sourcesReady);
} else {
REJOINLOG.debug(m_whoami + "Rejoin snapshot transfer is finished");
m_rejoinSiteProcessor.close();
boolean allSitesFinishStreaming;
if (m_streamSnapshotMb != null) {
VoltDB.instance().getHostMessenger().removeMailbox(m_streamSnapshotMb.getHSId());
m_streamSnapshotMb = null;
allSitesFinishStreaming = s_streamingSiteCount.decrementAndGet() == 0;
}
else {
int pendingSites = s_streamingSiteCount.get();
assert(pendingSites >= 0);
allSitesFinishStreaming = pendingSites == 0;
}
if (allSitesFinishStreaming) {
doFinishingTask(siteConnection);
}
else {
returnToTaskQueue(sourcesReady);
}
}
}
else {
doFinishingTask(siteConnection);
// Remove the completion monitor for an empty (zero table) rejoin.
m_snapshotCompletionMonitor.set(null);
}
}
private void doFinishingTask(final SiteProcedureConnection siteConnection) {
/*
* Don't notify the rejoin coordinator yet. The stream snapshot may
* have not finished on all nodes, let the snapshot completion
* monitor tell the rejoin coordinator.
*
* This used to block on the completion interest, but this raced
* with fragments from the MPI that needed dummy responses. If the fragments
* came after the EOF then they wouldn't receive dummy responses
* and then the MPI wouldn't invoke SnapshotSaveAPI.logParticipatingHostCount
*/
final SiteTasker finishingTask = new SiteTasker() {
@Override
public void run(SiteProcedureConnection siteConnection) {
throw new RuntimeException(
"Unexpected execution of run method in rejoin producer.");
}
@Override
public void runForRejoin(SiteProcedureConnection siteConnection, TaskLog rejoinTaskLog) throws IOException {
if (!m_snapshotCompletionMonitor.isDone()) {
m_taskQueue.offer(this);
return;
}
assert(m_commaSeparatedNameOfViewsToPause != null);
// Resume the views.
siteConnection.setViewsEnabled(m_commaSeparatedNameOfViewsToPause, true);
SnapshotCompletionEvent event = null;
Map<String, Map<Integer, Pair<Long,Long>>> exportSequenceNumbers = null;
Map<Integer, Long> drSequenceNumbers = null;
Map<Integer, Map<Integer, Map<Integer, DRSiteDrIdTracker>>> allConsumerSiteTrackers = null;
long clusterCreateTime = -1;
try {
event = m_snapshotCompletionMonitor.get();
if (m_hasPersistentTables) {
REJOINLOG.debug(m_whoami + "waiting on snapshot completion monitor.");
exportSequenceNumbers = event.exportSequenceNumbers;
m_completionAction.setSnapshotTxnId(event.multipartTxnId);
drSequenceNumbers = event.drSequenceNumbers;
allConsumerSiteTrackers = event.drMixedClusterSizeConsumerState;
clusterCreateTime = event.clusterCreateTime;
// Tells EE which DR version going to use
siteConnection.setDRProtocolVersion(event.drVersion);
}
REJOINLOG.debug(m_whoami + " monitor completed. Sending SNAPSHOT_FINISHED "
+ "and handing off to site.");
RejoinMessage snap_complete = new RejoinMessage(
m_mailbox.getHSId(), Type.SNAPSHOT_FINISHED);
m_mailbox.send(m_coordinatorHsId, snap_complete);
} catch (InterruptedException crashme) {
VoltDB.crashLocalVoltDB(
"Interrupted awaiting snapshot completion.", true, crashme);
} catch (ExecutionException e) {
VoltDB.crashLocalVoltDB(
"Unexpected exception awaiting snapshot completion.", true,
e);
}
if (exportSequenceNumbers == null) {
// Send empty sequence number map if the schema is empty (no tables).
exportSequenceNumbers = new HashMap<String, Map<Integer, Pair<Long,Long>>>();
}
setJoinComplete(
siteConnection,
exportSequenceNumbers,
drSequenceNumbers,
allConsumerSiteTrackers,
m_hasPersistentTables /* requireExistingSequenceNumbers */,
clusterCreateTime);
}
};
try {
finishingTask.runForRejoin(siteConnection, null);
} catch (IOException e) {
VoltDB.crashLocalVoltDB("Unexpected IOException in rejoin", true, e);
}
}
}
| RejoinProducer: Start the watchdog during initialization
| src/frontend/org/voltdb/iv2/RejoinProducer.java | RejoinProducer: Start the watchdog during initialization |
|
Java | lgpl-2.1 | 862ff8a9eb0a68b02feac8ac8ec4f2082ea8cff1 | 0 | threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya | //
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2005 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.jme;
import java.io.File;
import com.samskivert.util.Queue;
import com.samskivert.util.RunQueue;
import com.samskivert.util.StringUtil;
import com.jme.renderer.Camera;
import com.jme.renderer.ColorRGBA;
import com.jme.renderer.Renderer;
import com.jme.scene.Node;
import com.jme.scene.state.LightState;
import com.jme.scene.state.ZBufferState;
import com.jme.system.DisplaySystem;
import com.jme.system.JmeException;
import com.jme.system.PropertiesIO;
import com.jme.system.lwjgl.LWJGLPropertiesDialog;
import com.jme.bui.event.InputDispatcher;
import com.jme.input.InputHandler;
import com.jme.input.InputSystem;
import com.jme.input.Mouse;
import com.jme.light.PointLight;
import com.jme.math.Vector3f;
import com.jme.util.Timer;
import com.threerings.jme.input.GodViewHandler;
import com.threerings.jme.input.HardwareMouse;
/**
* Defines a basic application framework providing integration with the
* <a href="../presents/package.html">Presents</a> networking system and
* targeting a fixed framerate.
*/
public class JmeApp
implements RunQueue
{
/**
* Configures the target frame rate in frames per second.
*/
public void setTargetFrameRate (long framesPerSecond)
{
if (framesPerSecond <= 0) {
throw new IllegalArgumentException("FPS must be > 0.");
}
_targetFrameTicks = _timer.getResolution() / framesPerSecond;
}
/**
* Returns a context implementation that provides access to all the
* necessary bits.
*/
public JmeContext getContext ()
{
return _ctx;
}
/**
* Does the main initialization of the application. This method should
* be called first, and then the {@link #run} method should be called
* to begin the rendering/event loop. Derived classes can override
* this, being sure to call super before doing their own
* initalization.
*
* @return true if the application initialized successfully, false if
* initialization failed. (See {@link #reportInitFailure}.)
*/
public boolean init ()
{
try {
// load up our renderer configuration
_properties = new PropertiesIO(getConfigPath("jme.cfg"));
readDisplayConfig();
// create an appropriate timer
_timer = Timer.getTimer(_properties.getRenderer());
// default to 60 fps
setTargetFrameRate(60);
// initialize the rendering system
initDisplay();
if (!_display.isCreated()) {
throw new IllegalStateException("Failed to initialize display?");
}
// initialize our main camera controls and user input handling
initInput();
// initialize the root node
initRoot();
// initialize the lighting
initLighting();
// initialize the UI support stuff
initInterface();
// update everything for the zeroth tick
_iface.updateRenderState();
_geom.updateRenderState();
_root.updateGeometricState(0f, true);
_root.updateRenderState();
// create and add our statistics display
if (displayStatistics()) {
_stats = new StatsDisplay(_display.getRenderer());
_stats.updateGeometricState(0f, true);
_stats.updateRenderState();
}
return true;
} catch (Throwable t) {
reportInitFailure(t);
return false;
}
}
/**
* Starts up the main rendering and event processing loop. This method
* will not return until the application is terminated with a call to
* {@link #stop}.
*/
public void run ()
{
synchronized (this) {
_dispatchThread = Thread.currentThread();
}
// enter the main rendering and event processing loop
while (!_finished && !_display.isClosing()) {
try {
processFrame();
_failures = 0;
} catch (Throwable t) {
Log.logStackTrace(t);
// stick a fork in things if we fail too many times in a row
if (++_failures > MAX_SUCCESSIVE_FAILURES) {
stop();
}
}
}
try {
cleanup();
} catch (Throwable t) {
Log.logStackTrace(t);
} finally {
exit();
}
}
/**
* Instructs the application to stop the main loop, cleanup and exit.
*/
public void stop ()
{
_finished = true;
}
// documentation inherited from interface RunQueue
public void postRunnable (Runnable r)
{
_evqueue.append(r);
}
// documentation inherited from interface RunQueue
public boolean isDispatchThread ()
{
return Thread.currentThread() == _dispatchThread;
}
/**
* Reads in the contents of our display properties. Derivations may
* wish to override this and configure the display properties from
* some other source.
*/
protected void readDisplayConfig ()
{
if (!_properties.load()) {
LWJGLPropertiesDialog dialog =
new LWJGLPropertiesDialog(_properties, (String)null);
while (dialog.isVisible()) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
Log.warning("Error waiting for dialog system, " +
"using defaults.");
}
}
}
}
/**
* Initializes the underlying rendering system, creating a display of
* the proper resolution and depth.
*/
protected void initDisplay ()
throws JmeException
{
// create the main display system
_display = DisplaySystem.getDisplaySystem(_properties.getRenderer());
_display.createWindow(
_properties.getWidth(), _properties.getHeight(),
_properties.getDepth(), _properties.getFreq(),
_properties.getFullscreen());
_display.setVSyncEnabled(true);
// create a camera
float width = _display.getWidth(), height = _display.getHeight();
_camera = _display.getRenderer().createCamera((int)width, (int)height);
// start with a black background
_display.getRenderer().setBackgroundColor(ColorRGBA.black);
// set up the camera
_camera.setFrustumPerspective(45.0f, width / height, 1, 10000);
Vector3f loc = new Vector3f(0.0f, 0.0f, 25.0f);
Vector3f left = new Vector3f(-1.0f, 0.0f, 0.0f);
Vector3f up = new Vector3f(0.0f, 1.0f, 0.0f);
Vector3f dir = new Vector3f(0.0f, 0f, -1.0f);
_camera.setFrame(loc, left, up, dir);
_camera.update();
_display.getRenderer().setCamera(_camera);
// tell the renderer to keep track of rendering information (total
// triangles drawn, etc.)
_display.getRenderer().enableStatistics(true);
// // set our display title
// _display.setTitle("TBD");
}
/**
* Sets up a main input controller to handle the camera and deal with
* global user input.
*/
protected void initInput ()
{
_input = createInputHandler(_camera, _properties.getRenderer());
_input.setMouse(createMouse());
}
/**
* Creates the input handler used to control our camera and manage
* non-UI keyboard input.
*/
protected InputHandler createInputHandler (Camera camera, String api)
{
return new GodViewHandler(camera, api);
}
/**
* Creates the type of mouse handler we'll use to manage the mouse
* position.
*/
protected Mouse createMouse ()
{
HardwareMouse mouse = new HardwareMouse("Mouse");
mouse.setMouseInput(InputSystem.getMouseInput());
return mouse;
}
/**
* Creates our root node and sets up the basic rendering system.
*/
protected void initRoot ()
{
_root = new Node("Root");
// set up a node for our geometry
_geom = new Node("Geometry");
// set up a zbuffer
ZBufferState zbuf = _display.getRenderer().createZBufferState();
zbuf.setEnabled(true);
zbuf.setFunction(ZBufferState.CF_LEQUAL);
_geom.setRenderState(zbuf);
_root.attachChild(_geom);
}
/**
* Sets up some default lighting.
*/
protected void initLighting ()
{
PointLight light = new PointLight();
light.setDiffuse(new ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f));
light.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f));
light.setLocation(new Vector3f(100, 100, 100));
light.setEnabled(true);
_lights = _display.getRenderer().createLightState();
_lights.setEnabled(true);
_lights.attach(light);
_geom.setRenderState(_lights);
}
/**
* Initializes our user interface bits.
*/
protected void initInterface ()
{
// set up a node for our interface
_iface = new Node("Interface");
_root.attachChild(_iface);
InputSystem.createInputSystem(_properties.getRenderer());
_dispatcher = new InputDispatcher(_timer, _input, _iface);
// we don't hide the cursor
InputSystem.getMouseInput().setCursorVisible(true);
}
/**
* Called when initialization fails to give the application a chance
* to report the failure to the user.
*/
protected void reportInitFailure (Throwable t)
{
Log.logStackTrace(t);
}
/**
* Processes a single frame.
*/
protected final void processFrame ()
{
// update our simulation and render a frame
long frameStart = _timer.getTime();
update(frameStart);
render(frameStart);
_display.getRenderer().displayBackBuffer();
// now process events or sleep until the next frame (assume zero
// frame duration to start to ensure that we always process at
// least one event per frame)
long frameDuration = 0L;
while (frameDuration < _targetFrameTicks) {
Runnable r = (Runnable)_evqueue.getNonBlocking();
if (r == null) {
try {
Thread.sleep(1);
} catch (InterruptedException ie) {
Log.warning("Ticker interrupted: " + ie);
}
} else {
r.run();
}
frameDuration = _timer.getTime() - frameStart;
}
}
/**
* Called every frame to update whatever sort of real time business we
* have that needs updating.
*/
protected void update (long frameTick)
{
// recalculate the frame rate
_timer.update();
// update the input system
float timePerFrame = _timer.getTimePerFrame();
_dispatcher.update(timePerFrame);
// run all of the controllers attached to nodes
_root.updateGeometricState(timePerFrame, true);
// update our stats display if we have one
if (_stats != null) {
_stats.update(_timer, _display.getRenderer());
}
}
/**
* Called every frame to issue the rendering instructions for this frame.
*/
protected void render (float frameTime)
{
// clear out our previous information
_display.getRenderer().clearStatistics();
_display.getRenderer().clearBuffers();
// draw the root node and all of its children
_display.getRenderer().draw(_root);
// this would render bounding boxes
// _display.getRenderer().drawBounds(_root);
// draw our stats atop everything
if (_stats != null) {
_display.getRenderer().draw(_stats);
}
}
/**
* Called when the application is terminating cleanly after having
* successfully completed initialization and begun the main loop.
*/
protected void cleanup ()
{
_display.reset();
if (InputSystem.getKeyInput() != null) {
InputSystem.getKeyInput().destroy();
}
if (InputSystem.getMouseInput() != null) {
InputSystem.getMouseInput().destroy();
}
}
/**
* Closes the display and exits the JVM process.
*/
protected void exit ()
{
if (_display != null) {
_display.close();
}
System.exit(0);
}
/**
* If true we'll display some renderer statistics at the bottom of the
* screen.
*/
protected boolean displayStatistics ()
{
return true;
}
/**
* Prepends the necessary bits onto the supplied path to properly
* locate it in our configuration directory.
*/
protected String getConfigPath (String file)
{
String cfgdir = ".narya";
String home = System.getProperty("user.home");
if (!StringUtil.blank(home)) {
cfgdir = home + File.separator + cfgdir;
}
// create the configuration directory if it does not already exist
File dir = new File(cfgdir);
if (!dir.exists()) {
dir.mkdir();
}
return cfgdir + File.separator + file;
}
/** Provides access to various needed bits. */
protected JmeContext _ctx = new JmeContext() {
public DisplaySystem getDisplay () {
return _display;
}
public Renderer getRenderer () {
return _display.getRenderer();
}
public Camera getCamera () {
return _camera;
}
public Node getGeometry () {
return _geom;
}
public Node getInterface () {
return _iface;
}
public InputHandler getInputHandler () {
return _input;
}
public InputDispatcher getInputDispatcher () {
return _dispatcher;
}
};
protected Timer _timer;
protected Thread _dispatchThread;
protected Queue _evqueue = new Queue();
protected PropertiesIO _properties;
protected DisplaySystem _display;
protected Camera _camera;
protected InputHandler _input;
protected InputDispatcher _dispatcher;
protected long _targetFrameTicks;
protected boolean _finished;
protected int _failures;
protected Node _root, _geom, _iface;
protected LightState _lights;
protected StatsDisplay _stats;
/** If we fail 100 frames in a row, stick a fork in ourselves. */
protected static final int MAX_SUCCESSIVE_FAILURES = 100;
}
| src/java/com/threerings/jme/JmeApp.java | //
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2005 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.jme;
import java.io.File;
import com.samskivert.util.Queue;
import com.samskivert.util.RunQueue;
import com.samskivert.util.StringUtil;
import com.jme.renderer.Camera;
import com.jme.renderer.ColorRGBA;
import com.jme.renderer.Renderer;
import com.jme.scene.Node;
import com.jme.scene.state.LightState;
import com.jme.scene.state.ZBufferState;
import com.jme.system.DisplaySystem;
import com.jme.system.JmeException;
import com.jme.system.PropertiesIO;
import com.jme.system.lwjgl.LWJGLPropertiesDialog;
import com.jme.bui.event.InputDispatcher;
import com.jme.input.InputHandler;
import com.jme.input.InputSystem;
import com.jme.input.Mouse;
import com.jme.light.PointLight;
import com.jme.math.Vector3f;
import com.jme.util.Timer;
import com.threerings.jme.input.GodViewHandler;
import com.threerings.jme.input.HardwareMouse;
/**
* Defines a basic application framework providing integration with the
* <a href="../presents/package.html">Presents</a> networking system and
* targeting a fixed framerate.
*/
public class JmeApp
implements RunQueue
{
/**
* Configures the target frame rate in frames per second.
*/
public void setTargetFrameRate (long framesPerSecond)
{
if (framesPerSecond <= 0) {
throw new IllegalArgumentException("FPS must be > 0.");
}
_targetFrameTicks = _timer.getResolution() / framesPerSecond;
}
/**
* Returns a context implementation that provides access to all the
* necessary bits.
*/
public JmeContext getContext ()
{
return _ctx;
}
/**
* Does the main initialization of the application. This method should
* be called first, and then the {@link #run} method should be called
* to begin the rendering/event loop. Derived classes can override
* this, being sure to call super before doing their own
* initalization.
*
* @return true if the application initialized successfully, false if
* initialization failed. (See {@link #reportInitFailure}.)
*/
public boolean init ()
{
try {
// load up our renderer configuration
_properties = new PropertiesIO(getConfigPath("jme.cfg"));
readDisplayConfig();
// create an appropriate timer
_timer = Timer.getTimer(_properties.getRenderer());
// default to 60 fps
setTargetFrameRate(60);
// initialize the rendering system
initDisplay();
if (!_display.isCreated()) {
throw new IllegalStateException("Failed to initialize display?");
}
// initialize our main camera controls and user input handling
initInput();
// initialize the root node
initRoot();
// initialize the lighting
initLighting();
// initialize the UI support stuff
initInterface();
// update everything for the zeroth tick
_iface.updateRenderState();
_geom.updateRenderState();
_root.updateGeometricState(0f, true);
_root.updateRenderState();
// create and add our statistics display
if (displayStatistics()) {
_stats = new StatsDisplay(_display.getRenderer());
_stats.updateGeometricState(0f, true);
_stats.updateRenderState();
}
return true;
} catch (Exception e) {
reportInitFailure(e);
return false;
}
}
/**
* Starts up the main rendering and event processing loop. This method
* will not return until the application is terminated with a call to
* {@link #stop}.
*/
public void run ()
{
synchronized (this) {
_dispatchThread = Thread.currentThread();
}
// enter the main rendering and event processing loop
while (!_finished && !_display.isClosing()) {
try {
processFrame();
_failures = 0;
} catch (Throwable t) {
Log.logStackTrace(t);
// stick a fork in things if we fail too many times in a row
if (++_failures > MAX_SUCCESSIVE_FAILURES) {
stop();
}
}
}
try {
cleanup();
} catch (Throwable t) {
Log.logStackTrace(t);
} finally {
exit();
}
}
/**
* Instructs the application to stop the main loop, cleanup and exit.
*/
public void stop ()
{
_finished = true;
}
// documentation inherited from interface RunQueue
public void postRunnable (Runnable r)
{
_evqueue.append(r);
}
// documentation inherited from interface RunQueue
public boolean isDispatchThread ()
{
return Thread.currentThread() == _dispatchThread;
}
/**
* Reads in the contents of our display properties. Derivations may
* wish to override this and configure the display properties from
* some other source.
*/
protected void readDisplayConfig ()
{
if (!_properties.load()) {
LWJGLPropertiesDialog dialog =
new LWJGLPropertiesDialog(_properties, (String)null);
while (dialog.isVisible()) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
Log.warning("Error waiting for dialog system, " +
"using defaults.");
}
}
}
}
/**
* Initializes the underlying rendering system, creating a display of
* the proper resolution and depth.
*/
protected void initDisplay ()
throws JmeException
{
// create the main display system
_display = DisplaySystem.getDisplaySystem(_properties.getRenderer());
_display.createWindow(
_properties.getWidth(), _properties.getHeight(),
_properties.getDepth(), _properties.getFreq(),
_properties.getFullscreen());
_display.setVSyncEnabled(true);
// create a camera
float width = _display.getWidth(), height = _display.getHeight();
_camera = _display.getRenderer().createCamera((int)width, (int)height);
// start with a black background
_display.getRenderer().setBackgroundColor(ColorRGBA.black);
// set up the camera
_camera.setFrustumPerspective(45.0f, width / height, 1, 10000);
Vector3f loc = new Vector3f(0.0f, 0.0f, 25.0f);
Vector3f left = new Vector3f(-1.0f, 0.0f, 0.0f);
Vector3f up = new Vector3f(0.0f, 1.0f, 0.0f);
Vector3f dir = new Vector3f(0.0f, 0f, -1.0f);
_camera.setFrame(loc, left, up, dir);
_camera.update();
_display.getRenderer().setCamera(_camera);
// tell the renderer to keep track of rendering information (total
// triangles drawn, etc.)
_display.getRenderer().enableStatistics(true);
// // set our display title
// _display.setTitle("TBD");
}
/**
* Sets up a main input controller to handle the camera and deal with
* global user input.
*/
protected void initInput ()
{
_input = createInputHandler(_camera, _properties.getRenderer());
_input.setMouse(createMouse());
}
/**
* Creates the input handler used to control our camera and manage
* non-UI keyboard input.
*/
protected InputHandler createInputHandler (Camera camera, String api)
{
return new GodViewHandler(camera, api);
}
/**
* Creates the type of mouse handler we'll use to manage the mouse
* position.
*/
protected Mouse createMouse ()
{
HardwareMouse mouse = new HardwareMouse("Mouse");
mouse.setMouseInput(InputSystem.getMouseInput());
return mouse;
}
/**
* Creates our root node and sets up the basic rendering system.
*/
protected void initRoot ()
{
_root = new Node("Root");
// set up a node for our geometry
_geom = new Node("Geometry");
// set up a zbuffer
ZBufferState zbuf = _display.getRenderer().createZBufferState();
zbuf.setEnabled(true);
zbuf.setFunction(ZBufferState.CF_LEQUAL);
_geom.setRenderState(zbuf);
_root.attachChild(_geom);
}
/**
* Sets up some default lighting.
*/
protected void initLighting ()
{
PointLight light = new PointLight();
light.setDiffuse(new ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f));
light.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f));
light.setLocation(new Vector3f(100, 100, 100));
light.setEnabled(true);
_lights = _display.getRenderer().createLightState();
_lights.setEnabled(true);
_lights.attach(light);
_geom.setRenderState(_lights);
}
/**
* Initializes our user interface bits.
*/
protected void initInterface ()
{
// set up a node for our interface
_iface = new Node("Interface");
_root.attachChild(_iface);
InputSystem.createInputSystem(_properties.getRenderer());
_dispatcher = new InputDispatcher(_timer, _input, _iface);
// we don't hide the cursor
InputSystem.getMouseInput().setCursorVisible(true);
}
/**
* Called when initialization fails to give the application a chance
* to report the failure to the user.
*/
protected void reportInitFailure (Exception e)
{
Log.logStackTrace(e);
}
/**
* Processes a single frame.
*/
protected final void processFrame ()
{
// update our simulation and render a frame
long frameStart = _timer.getTime();
update(frameStart);
render(frameStart);
_display.getRenderer().displayBackBuffer();
// now process events or sleep until the next frame (assume zero
// frame duration to start to ensure that we always process at
// least one event per frame)
long frameDuration = 0L;
while (frameDuration < _targetFrameTicks) {
Runnable r = (Runnable)_evqueue.getNonBlocking();
if (r == null) {
try {
Thread.sleep(1);
} catch (InterruptedException ie) {
Log.warning("Ticker interrupted: " + ie);
}
} else {
r.run();
}
frameDuration = _timer.getTime() - frameStart;
}
}
/**
* Called every frame to update whatever sort of real time business we
* have that needs updating.
*/
protected void update (long frameTick)
{
// recalculate the frame rate
_timer.update();
// update the input system
float timePerFrame = _timer.getTimePerFrame();
_dispatcher.update(timePerFrame);
// run all of the controllers attached to nodes
_root.updateGeometricState(timePerFrame, true);
// update our stats display if we have one
if (_stats != null) {
_stats.update(_timer, _display.getRenderer());
}
}
/**
* Called every frame to issue the rendering instructions for this frame.
*/
protected void render (float frameTime)
{
// clear out our previous information
_display.getRenderer().clearStatistics();
_display.getRenderer().clearBuffers();
// draw the root node and all of its children
_display.getRenderer().draw(_root);
// this would render bounding boxes
// _display.getRenderer().drawBounds(_root);
// draw our stats atop everything
if (_stats != null) {
_display.getRenderer().draw(_stats);
}
}
/**
* Called when the application is terminating cleanly after having
* successfully completed initialization and begun the main loop.
*/
protected void cleanup ()
{
_display.reset();
if (InputSystem.getKeyInput() != null) {
InputSystem.getKeyInput().destroy();
}
if (InputSystem.getMouseInput() != null) {
InputSystem.getMouseInput().destroy();
}
}
/**
* Closes the display and exits the JVM process.
*/
protected void exit ()
{
if (_display != null) {
_display.close();
}
System.exit(0);
}
/**
* If true we'll display some renderer statistics at the bottom of the
* screen.
*/
protected boolean displayStatistics ()
{
return true;
}
/**
* Prepends the necessary bits onto the supplied path to properly
* locate it in our configuration directory.
*/
protected String getConfigPath (String file)
{
String cfgdir = ".narya";
String home = System.getProperty("user.home");
if (!StringUtil.blank(home)) {
cfgdir = home + File.separator + cfgdir;
}
// create the configuration directory if it does not already exist
File dir = new File(cfgdir);
if (!dir.exists()) {
dir.mkdir();
}
return cfgdir + File.separator + file;
}
/** Provides access to various needed bits. */
protected JmeContext _ctx = new JmeContext() {
public DisplaySystem getDisplay () {
return _display;
}
public Renderer getRenderer () {
return _display.getRenderer();
}
public Camera getCamera () {
return _camera;
}
public Node getGeometry () {
return _geom;
}
public Node getInterface () {
return _iface;
}
public InputHandler getInputHandler () {
return _input;
}
public InputDispatcher getInputDispatcher () {
return _dispatcher;
}
};
protected Timer _timer;
protected Thread _dispatchThread;
protected Queue _evqueue = new Queue();
protected PropertiesIO _properties;
protected DisplaySystem _display;
protected Camera _camera;
protected InputHandler _input;
protected InputDispatcher _dispatcher;
protected long _targetFrameTicks;
protected boolean _finished;
protected int _failures;
protected Node _root, _geom, _iface;
protected LightState _lights;
protected StatsDisplay _stats;
/** If we fail 100 frames in a row, stick a fork in ourselves. */
protected static final int MAX_SUCCESSIVE_FAILURES = 100;
}
| Catch Throwable because LWJGL kindly throws errors during initialization
in addition to exceptions. Yay!
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@3574 542714f4-19e9-0310-aa3c-eee0fc999fb1
| src/java/com/threerings/jme/JmeApp.java | Catch Throwable because LWJGL kindly throws errors during initialization in addition to exceptions. Yay! |
|
Java | apache-2.0 | 4de2a36698d17b201504ba2e5ffa74b830047e1b | 0 | jesse-gallagher/frostillic.us-Blog,jesse-gallagher/frostillic.us-Blog,jesse-gallagher/frostillic.us-Blog,jesse-gallagher/frostillic.us-Blog | /**
* Copyright © 2016-2018 Jesse Gallagher
*
* 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 controller;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.TreeSet;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import javax.mvc.Models;
import javax.mvc.Controller;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.darwino.commons.json.JsonException;
import com.darwino.commons.json.JsonObject;
import com.darwino.commons.util.StringUtil;
import com.darwino.jsonstore.Database;
import com.darwino.jsonstore.Store;
import com.darwino.platform.DarwinoContext;
import bean.MarkdownBean;
import frostillicus.blog.app.AppDatabaseDef;
import model.CommentRepository;
import model.Post;
import model.PostRepository;
@Path("/posts")
@Controller
public class PostController {
@Inject
Models models;
@Inject
PostRepository posts;
@Inject
CommentRepository comments;
@Inject
MarkdownBean markdown;
@Inject
Database database;
@GET
public String list() throws JsonException {
Collection<String> months = new TreeSet<String>();
// Fetch the months - use Darwino directly for this for now
Store store = database.getStore(AppDatabaseDef.STORE_POSTS);
store.openCursor()
.query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$
.findDocuments(doc -> {
String posted = doc.getString("posted"); //$NON-NLS-1$
if(posted != null && posted.length() >= 7) {
months.add(posted.substring(0, 7));
}
return true;
});
models.put("months", months); //$NON-NLS-1$
return "posts.jsp"; //$NON-NLS-1$
}
@GET
@Path("tag/{tag}")
public String byTag(@PathParam("tag") String tag) {
models.put("tag", tag); //$NON-NLS-1$
models.put("posts", posts.findByTag(tag)); //$NON-NLS-1$
return "posts-bytag.jsp"; //$NON-NLS-1$
}
@GET
@Path("new")
public String compose() {
models.put("post", new Post()); //$NON-NLS-1$
return "post-new.jsp"; //$NON-NLS-1$
}
// TODO figure out if this can be done automatically without adding @FormParam to the model class
@POST
@Consumes({ MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_FORM_URLENCODED })
@RolesAllowed("admin")
public String create(@FormParam("title") String title, @FormParam("bodyMarkdown") String bodyMarkdown, @FormParam("tags") String tags) throws JsonException {
Post post = new Post();
post.setPosted(new Date());
post.setPostedBy(DarwinoContext.get().getSession().getUser().getDn());
post.setTitle(title);
post.setBodyMarkdown(bodyMarkdown);
post.setBodyHtml(markdown.toHtml(bodyMarkdown));
post.setTags(
tags == null ? Collections.emptyList() :
Arrays.stream(tags.split(",")) //$NON-NLS-1$
.map(String::trim)
.filter(StringUtil::isNotEmpty)
.collect(Collectors.toList())
);
post.setPostId(UUID.randomUUID().toString());
posts.save(post);
return "redirect:posts/" + post.getPostId(); //$NON-NLS-1$
}
@GET
@Path("{postId}")
public String show(@PathParam("postId") String postId) {
// IDs are often stored as lowercased UNIDs
Post post = posts.findByPostId(postId)
.orElseGet(() -> posts.findByPostId(StringUtil.toString(postId).toLowerCase())
.orElseGet(() -> posts.findById(postId)
.orElseThrow(() -> new IllegalArgumentException("Unable to find post matching ID " + postId)) //$NON-NLS-1$
));
models.put("post", post); //$NON-NLS-1$
models.put("comments", comments.findByPostId(post.getPostId())); //$NON-NLS-1$
return "post.jsp"; //$NON-NLS-1$
}
@GET
@Path("{year}/{month}/{day}/{postId}")
public String showByDate(@PathParam("postId") String postId) {
return show(postId);
}
@GET
@Path("{year}/{month}/{day}/{postId}/edit")
@RolesAllowed("admin")
public String edit(@PathParam("postId") String postId) {
Post post = posts.findByPostId(postId).orElseThrow(() -> new IllegalArgumentException("Unable to find post matching ID " + postId)); //$NON-NLS-1$
models.put("post", post); //$NON-NLS-1$
return "post-edit.jsp"; //$NON-NLS-1$
}
@DELETE
@Path("{year}/{month}/{day}/{postId}")
@RolesAllowed("admin")
public String deleteByDate(@PathParam("postId") String postId) {
return delete(postId);
}
@DELETE
@Path("{postId}")
@RolesAllowed("admin")
public String delete(@PathParam("postId") String postId) {
Post post = posts.findByPostId(postId).orElseThrow(() -> new IllegalArgumentException("Unable to find post matching ID " + postId)); //$NON-NLS-1$
posts.deleteById(post.getId());
return "redirect:posts"; //$NON-NLS-1$
}
// *******************************************************************************
// * Searching
// *******************************************************************************
@GET
@Path("search")
public String search(@QueryParam("q") String query) {
models.put("posts", posts.search(query)); //$NON-NLS-1$
return "search.jsp"; //$NON-NLS-1$
}
}
| frostillicus-blog/frostillicus-blog-j2ee/src/main/java/controller/PostController.java | /**
* Copyright © 2016-2018 Jesse Gallagher
*
* 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 controller;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.TreeSet;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import javax.mvc.Models;
import javax.mvc.Controller;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.darwino.commons.json.JsonException;
import com.darwino.commons.json.JsonObject;
import com.darwino.commons.util.StringUtil;
import com.darwino.jsonstore.Database;
import com.darwino.jsonstore.Store;
import com.darwino.platform.DarwinoContext;
import bean.MarkdownBean;
import frostillicus.blog.app.AppDatabaseDef;
import model.CommentRepository;
import model.Post;
import model.PostRepository;
@Path("/posts")
@Controller
public class PostController {
@Inject
Models models;
@Inject
PostRepository posts;
@Inject
CommentRepository comments;
@Inject
MarkdownBean markdown;
@Inject
Database database;
@GET
public String list() throws JsonException {
Collection<String> months = new TreeSet<String>();
// Fetch the months - use Darwino directly for this for now
Store store = database.getStore(AppDatabaseDef.STORE_POSTS);
store.openCursor()
.query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$
.findDocuments(doc -> {
String posted = doc.getString("posted"); //$NON-NLS-1$
if(posted != null && posted.length() >= 7) {
months.add(posted.substring(0, 7));
}
return true;
});
models.put("months", months); //$NON-NLS-1$
return "posts.jsp"; //$NON-NLS-1$
}
@GET
@Path("tag/{tag}")
public String byTag(@PathParam("tag") String tag) {
models.put("tag", tag); //$NON-NLS-1$
models.put("posts", posts.findByTag(tag)); //$NON-NLS-1$
return "posts-bytag.jsp"; //$NON-NLS-1$
}
@GET
@Path("new")
public String compose() {
models.put("post", new Post()); //$NON-NLS-1$
return "post-new.jsp"; //$NON-NLS-1$
}
// TODO figure out if this can be done automatically without adding @FormParam to the model class
@POST
@Consumes({ MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_FORM_URLENCODED })
@RolesAllowed("admin")
public String create(@FormParam("title") String title, @FormParam("bodyMarkdown") String bodyMarkdown, @FormParam("tags") String tags) throws JsonException {
Post post = new Post();
post.setPosted(new Date());
post.setPostedBy(DarwinoContext.get().getSession().getUser().getDn());
post.setTitle(title);
post.setBodyMarkdown(bodyMarkdown);
post.setBodyHtml(markdown.toHtml(bodyMarkdown));
post.setTags(
tags == null ? Collections.emptyList() :
Arrays.stream(tags.split(",")) //$NON-NLS-1$
.map(String::trim)
.filter(StringUtil::isNotEmpty)
.collect(Collectors.toList())
);
post.setPostId(UUID.randomUUID().toString());
posts.save(post);
return "redirect:posts/" + post.getPostId(); //$NON-NLS-1$
}
@GET
@Path("{postId}")
public String show(@PathParam("postId") String postId) {
Post post = posts.findByPostId(postId).orElseThrow(() -> new IllegalArgumentException("Unable to find post matching ID " + postId)); //$NON-NLS-1$
models.put("post", post); //$NON-NLS-1$
models.put("comments", comments.findByPostId(post.getPostId())); //$NON-NLS-1$
return "post.jsp"; //$NON-NLS-1$
}
@GET
@Path("{year}/{month}/{day}/{postId}")
public String showByDate(@PathParam("postId") String postId) {
return show(postId);
}
@GET
@Path("{year}/{month}/{day}/{postId}/edit")
@RolesAllowed("admin")
public String edit(@PathParam("postId") String postId) {
Post post = posts.findByPostId(postId).orElseThrow(() -> new IllegalArgumentException("Unable to find post matching ID " + postId)); //$NON-NLS-1$
models.put("post", post); //$NON-NLS-1$
return "post-edit.jsp"; //$NON-NLS-1$
}
@DELETE
@Path("{year}/{month}/{day}/{postId}")
@RolesAllowed("admin")
public String deleteByDate(@PathParam("postId") String postId) {
return delete(postId);
}
@DELETE
@Path("{postId}")
@RolesAllowed("admin")
public String delete(@PathParam("postId") String postId) {
Post post = posts.findByPostId(postId).orElseThrow(() -> new IllegalArgumentException("Unable to find post matching ID " + postId)); //$NON-NLS-1$
posts.deleteById(post.getId());
return "redirect:posts"; //$NON-NLS-1$
}
// *******************************************************************************
// * Searching
// *******************************************************************************
@GET
@Path("search")
public String search(@QueryParam("q") String query) {
models.put("posts", posts.search(query)); //$NON-NLS-1$
return "search.jsp"; //$NON-NLS-1$
}
}
| Add fallbacks for post ID variants
| frostillicus-blog/frostillicus-blog-j2ee/src/main/java/controller/PostController.java | Add fallbacks for post ID variants |
|
Java | apache-2.0 | 42216a8276e23c81ce17d54b7f753ff96f0557e9 | 0 | ricepanda/rice,ricepanda/rice,ricepanda/rice,ricepanda/rice | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.kew.doctype;
import mocks.MockPostProcessor;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.kuali.rice.core.api.config.property.ConfigContext;
import org.kuali.rice.core.api.util.xml.XmlJotter;
import org.kuali.rice.edl.framework.workflow.EDocLitePostProcessor;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.api.KewApiServiceLocator;
import org.kuali.rice.kew.api.WorkflowDocument;
import org.kuali.rice.kew.api.WorkflowDocumentFactory;
import org.kuali.rice.kew.doctype.bo.DocumentType;
import org.kuali.rice.kew.doctype.service.DocumentTypeService;
import org.kuali.rice.kew.engine.node.NodeType;
import org.kuali.rice.kew.engine.node.ProcessDefinitionBo;
import org.kuali.rice.kew.engine.node.RouteNode;
import org.kuali.rice.kew.export.KewExportDataSet;
import org.kuali.rice.kew.framework.postprocessor.PostProcessor;
import org.kuali.rice.kew.postprocessor.DefaultPostProcessor;
import org.kuali.rice.kew.service.KEWServiceLocator;
import org.kuali.rice.kew.test.KEWTestCase;
import org.kuali.rice.kew.test.TestUtilities;
import org.kuali.rice.kew.xml.export.DocumentTypeXmlExporter;
import org.kuali.rice.kim.api.KimConstants;
import org.kuali.rice.kim.api.group.Group;
import org.kuali.rice.krad.util.KRADUtils;
import org.kuali.rice.test.BaselineTestCase;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
@BaselineTestCase.BaselineMode(BaselineTestCase.Mode.NONE)
public class DocumentTypeTest extends KEWTestCase {
private static final Logger LOG = Logger.getLogger(DocumentTypeTest.class);
protected void loadTestData() throws Exception {
ConfigContext.getCurrentContextConfig().putProperty("test.doctype.workgroup", "TestWorkgroup");
loadXmlFile("DoctypeConfig.xml");
}
@Test public void testDuplicateNodeName() throws Exception {
try {
loadXmlFile("DocTypeConfig_loadDupliateNodes.xml");
fail("loadXmlFile should have thrown routing exception");
} catch (Exception e) {
}
}
@Test public void testDuplicateNodeNameInRoutePath() throws Exception {
loadXmlFile("DocTypeConfig_duplicateNodes.xml");
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "TestDoubleNodeDocumentType");
document.setTitle("");
document.route("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), document.getDocumentId());
assertTrue("user2 should have an approve request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), document.getDocumentId());
assertTrue("user3 should have an approve request", document.isApprovalRequested());
document.approve("");
}
@Test public void testDocumentTypeParentChildLinking() throws Exception {
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
verifyDocumentTypeLinking();
// scenario 1, update the parent document type and verify that all linking is correct
super.loadXmlFile("ParentWithChildrenDocTypeConfigurationUpdate1.xml");
verifyDocumentTypeLinking();
// scenario 2, update a child document type and verify that all linking is correct
super.loadXmlFile("ParentWithChildrenDocTypeConfigurationUpdate2.xml");
verifyDocumentTypeLinking();
// let's reimport from the beginning as well
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
verifyDocumentTypeLinking();
// scenario 3, try an xml file with child doctype listed first
super.loadXmlFile("ParentWithChildrenDocTypeConfigurationUpdate3.xml");
verifyDocumentTypeLinking();
// try loading each of these in parallel threads to verify caching can
// handle concurrency situations
String[] fileNames = {
"ParentWithChildrenDocTypeConfiguration.xml",
"DocTypeIngestTestConfig1.xml",
"DocumentTypeAttributeFetchTest.xml",
"ChildDocType1.xml",
"ChildDocType2.xml",
"ChildDocType3.xml",
"ChildDocType4.xml",
};
List<Callback> callbacks = new ArrayList<Callback>();
CyclicBarrier barrier = new CyclicBarrier(fileNames.length);
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < fileNames.length; i++) {
Callback callback = new Callback();
callbacks.add(callback);
threads.add(new Thread(new LoadXml(fileNames[i], callback, barrier)));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join(2*60*1000);
}
// What should have happened here was an optimistic lock being thrown from the
// document type XML import. Currently, that code is catching and just logging
// those errors (not rethrowing), so there's no way for us to check that the
// optimistic lock was thrown. However, the verifyDocumentTypeLinking should pass
// because the update was never made, and we can check to make sure that
// at least one of the above documents failed to be ingested.
boolean atLeastOneFailure = false;
for (Callback callback : callbacks) {
if (!callback.isXmlLoaded()) {
atLeastOneFailure = true;
}
}
assertTrue("At least one of the XML files should have failed the ingestion process", atLeastOneFailure);
verifyDocumentTypeLinking();
// reload again for good measure
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
verifyDocumentTypeLinking();
}
@Test public void testNestedDuplicateNodeNameInRoutePath() throws Exception {
int waitMilliSeconds = 10000;
loadXmlFile("DocTypeConfig_nestedNodes.xml");
// Path 1
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "TestDoubleNodeDocumentType");
document.setTitle("");
document.route("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request; the first request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), document.getDocumentId());
assertTrue("user2 should have an approve request", document.isApprovalRequested());
document.approve("");
Thread.sleep(waitMilliSeconds);
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), document.getDocumentId());
assertTrue("user3 should have an approve request; the first request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user4"), document.getDocumentId());
assertTrue("user4 should have an approve request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request; the second request", document.isApprovalRequested());
document.approve("");
Thread.sleep(waitMilliSeconds);
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), document.getDocumentId());
assertTrue("user3 should have an approve request; the second request", document.isApprovalRequested());
document.approve("");
}
/**
* Verify that enroute documents are not affected if you edit their document type.
* @throws Exception
*/
@Test public void testChangingDocumentTypeOnEnrouteDocument() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "DocumentType");
document.setTitle("");
document.route("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request", document.isApprovalRequested());
org.kuali.rice.kew.api.doctype.DocumentTypeService docTypeService = KewApiServiceLocator.getDocumentTypeService();
Integer version1 = docTypeService.getDocumentTypeByName(document.getDocumentTypeName()).getDocumentTypeVersion();
//update the document type
loadXmlFile("DoctypeSecondVersion.xml");
//verify that we have a new documenttypeid and its a newer version
Integer version2 = docTypeService.getDocumentTypeByName(document.getDocumentTypeName()).getDocumentTypeVersion();
assertTrue("Version2 should be larger than verison1", version2.intValue() > version1.intValue());
//the new version would take the document final
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), document.getDocumentId());
Integer versionDocument = docTypeService.getDocumentTypeById(document.getDocument().getDocumentTypeId()).getDocumentTypeVersion();
assertTrue("user2 should have an approve request", document.isApprovalRequested());
//make sure our document still represents the accurate version
assertEquals("Document has the wrong document type version", version1, versionDocument);
}
/**
* this test will verify that finalapprover node policies work
*
* @throws Exception
*/
@Test public void testFinalApproverRouting() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "FinalApproverDocumentType");
document.setTitle("");
document.route("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
try {
document.approve("");
fail("document should have thrown routing exception");
} catch (Exception e) {
//deal with single transaction issue in test.
TestUtilities.getExceptionThreader().join();
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("Document should be in exception routing", document.isException());
}
}
/**
* this test will verify that a document type with an empty route path will go directly
* to "final" status
*
* @throws Exception
*/
@Test public void testEmptyRoutePath() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "EmptyRoutePathDocumentType");
document.setTitle("");
document.route("");
assertTrue("Document should be in final state", document.isFinal());
}
/**
* Tests that route nodes mark as mandatory send out approve requests
* @throws Exception
*/
@Test public void testMandatoryRoute() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "MandatoryRouteDocumentType");
document.setTitle("");
try {
document.route("");
} catch (Exception e) {
//deal with single transaction issue in test.
TestUtilities.getExceptionThreader().join();
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user1"), document.getDocumentId());
assertTrue("Document should be in exception routing", document.isException());
}
}
/**
* Makes sure the DocumentTypeXmlParser is working. Compare the parsed 'DocumentType' doctype to it's expected values.
* This test does not include multiple processes.
*
* @throws Exception
*/
@Test public void testDocumentTypeXmlParser() throws Exception {
ConfigContext.getCurrentContextConfig().putProperty("test.base.url", "http://someurl/path");
DocumentType parsedDocument = KEWServiceLocator.getDocumentTypeService().findByName("DocumentType");
assertEquals("Wrong name", "DocumentType", parsedDocument.getName());
assertEquals("Wrong description", "TestDocumentType", parsedDocument.getDescription());
assertEquals("Wrong label", "TestDocumentType", parsedDocument.getLabel());
assertEquals("Wrong postprocessor", "org.kuali.rice.kew.postprocessor.DefaultPostProcessor", parsedDocument.getPostProcessorName());
assertEquals("Wrong su workgroup", "TestWorkgroup", parsedDocument.getSuperUserWorkgroup().getName());
// roundabout way of testing to see if the exception workgroup has been processed properly
DocumentTypeXmlExporter exporter = new DocumentTypeXmlExporter();
KewExportDataSet dataSet = new KewExportDataSet();
dataSet.getDocumentTypes().add(parsedDocument);
String regex = "(?s).*<defaultExceptionGroupName namespace=\"" + KimConstants.KIM_GROUP_WORKFLOW_NAMESPACE_CODE + "\">TestWorkgroup</defaultExceptionGroupName>.*";
LOG.warn("Using regex: " + regex);
assertTrue(XmlJotter.jotNode(exporter.export(dataSet.createExportDataSet())).matches(regex));
//assertNotNull(parsedDocument.getDefaultExceptionWorkgroup());
//assertEquals("Wrong default exception workgroup", "TestWorkgroup", parsedDocument.getDefaultExceptionWorkgroup().getDisplayName());
assertEquals("Wrong doc handler url", "http://someurl/path/_blank", parsedDocument.getResolvedDocumentHandlerUrl());
assertEquals("Wrong unresolved doc handler url", "${test.base.url}/_blank", parsedDocument.getUnresolvedDocHandlerUrl());
assertEquals("Wrong help def url", "/_help", parsedDocument.getHelpDefinitionUrl());
assertEquals("Wrong unresolved help def url", "/_help", parsedDocument.getUnresolvedHelpDefinitionUrl());
assertEquals("Wrong blanketApprover workgroup", "TestWorkgroup", parsedDocument.getBlanketApproveWorkgroup().getName());
assertEquals("Wrong blanketApprove policy", null, parsedDocument.getBlanketApprovePolicy());
assertEquals("Wrong DEFAULT_APPROVE policy value", Boolean.FALSE, parsedDocument.getDefaultApprovePolicy().getPolicyValue());
assertEquals("Wrong LOOK_FUTURE", Boolean.TRUE, parsedDocument.getLookIntoFuturePolicy().getPolicyValue());
List processes = parsedDocument.getProcesses();
assertEquals("Should only be 1 process", 1, processes.size());
//this is going against the intended structure and is very brittle
ProcessDefinitionBo process = (ProcessDefinitionBo)processes.get(0);
List flattenedNodeList = KEWServiceLocator.getRouteNodeService().getFlattenedNodes(process);
assertEquals("Should be 6 total route nodes", 6, flattenedNodeList.size());
RouteNode adHocNode = process.getInitialRouteNode();
assertEquals("Wrong node name should be 'AdHoc'", "AdHoc",adHocNode.getRouteNodeName());
assertTrue("Wrong node type", NodeType.START.isAssignableFrom(Class.forName(adHocNode.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", adHocNode.getExceptionWorkgroup().getName());
RouteNode split = (RouteNode)adHocNode.getNextNodes().get(0);
assertEquals("Wrong node name", "Split", split.getRouteNodeName());
assertTrue("Wrong node type", NodeType.SPLIT.isAssignableFrom(Class.forName(split.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", split.getExceptionWorkgroup().getName());
assertTrue(split.getNextNodes().size() == 2);
boolean ruleTemplate1Found = false;
boolean ruleTemplate2Found = false;
for (RouteNode routeNode : split.getNextNodes()) {
if (routeNode.getRouteNodeName().equals("RuleTemplate1")) {
assertTrue("Wrong node type", NodeType.REQUESTS.isAssignableFrom(Class.forName(routeNode.getNodeType())));
assertEquals("Wrong branch name", "B1", routeNode.getBranch().getName());
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", routeNode.getExceptionWorkgroup().getName());
ruleTemplate1Found = true;
}
if (routeNode.getRouteNodeName().equals("RuleTemplate2")) {
assertTrue("Wrong node type", NodeType.REQUESTS.isAssignableFrom(Class.forName(routeNode.getNodeType())));
assertEquals("Wrong branch name", "B2", routeNode.getBranch().getName());
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", routeNode.getExceptionWorkgroup().getName());
ruleTemplate2Found = true;
RouteNode join = (RouteNode)routeNode.getNextNodes().get(0);
assertEquals("Wrong node name", "Join", join.getRouteNodeName());
assertTrue("Wrong node type", NodeType.JOIN.isAssignableFrom(Class.forName(join.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", join.getExceptionWorkgroup().getName());
RouteNode ruleTemplate3 = (RouteNode)join.getNextNodes().get(0);
assertEquals("Wrong node name", "RuleTemplate3", ruleTemplate3.getRouteNodeName());
assertTrue("Wrong node type", NodeType.REQUESTS.isAssignableFrom(Class.forName(ruleTemplate3.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", ruleTemplate3.getExceptionWorkgroup().getName());
}
}
assertTrue(ruleTemplate1Found);
assertTrue(ruleTemplate2Found);
}
//verifies the documenttype hierarchy is intact after multiple uploads
@Test public void testHierarchyUpload() throws Exception {
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
DocumentType parent = KEWServiceLocator.getDocumentTypeService().findByName("UGSDocumentType");
boolean foundRemonstrance = false;
boolean foundNewCourse = false;
boolean foundDelete = false;
for (Iterator iter = parent.getChildrenDocTypes().iterator(); iter.hasNext();) {
DocumentType childDocType = (DocumentType) iter.next();
assertTrue("child documenttype should be current", childDocType.getCurrentInd().booleanValue());
if(childDocType.getName().equals("CourseRemonstranceProcess")) {
foundRemonstrance = true;
} else if (childDocType.getName().equals("NewCourseRequest")) {
foundNewCourse = true;
} else if (childDocType.getName().equals("DeleteCourseRequest")) {
foundDelete = true;
}
}
assertTrue("Didn't find CourseRemonstraneProcess", foundRemonstrance);
assertTrue("Didn't find NewCourseRequest", foundNewCourse);
assertTrue("Didn't find DeleteCourseRequest", foundDelete);
//reload and verify that the structure looks the same - the below is missing one of the children document types
//to verify that a partial upload of the hierarchy doesn't kill the entire hierarchy
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration2.xml");
parent = KEWServiceLocator.getDocumentTypeService().findByName("UGSDocumentType");
foundRemonstrance = false;
foundNewCourse = false;
foundDelete = false;
int i = 0;
for (Iterator iter = parent.getChildrenDocTypes().iterator(); iter.hasNext(); i++) {
DocumentType childDocType = (DocumentType) iter.next();
assertTrue("child documenttype should be current", childDocType.getCurrentInd().booleanValue());
if(childDocType.getName().equals("CourseRemonstranceProcess")) {
foundRemonstrance = true;
} else if (childDocType.getName().equals("NewCourseRequest")) {
foundNewCourse = true;
} else if (childDocType.getName().equals("DeleteCourseRequest")) {
foundDelete = true;
}
}
assertTrue("Didn't find CourseRemonstranceProcess", foundRemonstrance);
assertTrue("Didn't find NewCourseRequest", foundNewCourse);
assertTrue("Didn't find DeleteCourseRequest", foundDelete);
}
//verifies documenttype hierarchy is intact after uploading a series of documenttypes and then
//uploading a parent onto those document types
@Test public void testHierarchyUpload2() throws Exception {
super.loadXmlFile("DocTypesWithoutParent.xml");
//Verify that the document types are there
DocumentType courseRemonstrance1 = KEWServiceLocator.getDocumentTypeService().findByName("CourseRemonstranceProcess");
DocumentType newCourseRequest1 = KEWServiceLocator.getDocumentTypeService().findByName("NewCourseRequest");
DocumentType deleteCourse1 = KEWServiceLocator.getDocumentTypeService().findByName("DeleteCourseRequest");
//upload the new config with the parent and verify we are getting new document types with new versions
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
DocumentType courseRemonstrance2 = null;
DocumentType newCourseRequest2 = null;
DocumentType deleteCourse2 = null;
DocumentType ugsDocumentType = KEWServiceLocator.getDocumentTypeService().findByName("UGSDocumentType");
for (Iterator iter = ugsDocumentType.getChildrenDocTypes().iterator(); iter.hasNext();) {
DocumentType childDocType = (DocumentType) iter.next();
if(childDocType.getName().equals("CourseRemonstranceProcess")) {
courseRemonstrance2 = childDocType;
} else if (childDocType.getName().equals("NewCourseRequest")) {
newCourseRequest2 = childDocType;
} else if (childDocType.getName().equals("DeleteCourseRequest")) {
deleteCourse2 = childDocType;
}
}
assertNotNull(courseRemonstrance2);
assertNotNull(newCourseRequest2);
assertNotNull(deleteCourse2);
assertTrue("Version didn't get incremented", courseRemonstrance1.getVersion().intValue() < courseRemonstrance2.getVersion().intValue());
assertTrue("Version didn't increment", newCourseRequest1.getVersion().intValue() < newCourseRequest2.getVersion().intValue());
assertTrue("Version didn't increment", deleteCourse1.getVersion().intValue() < deleteCourse2.getVersion().intValue());
}
/**
* Tests that the document type ingestion will not create a brand new
* document when only label or description field changes. Relates to
* JIRA's EN-318 and KULOWF-147.
*
* @throws Exception
*/
@Test public void testDocumentTypeIngestion() throws Exception {
// first ingestion
super.loadXmlFile("DocTypeIngestTestConfig1.xml"); // original document
super.loadXmlFile("DocTypeIngestTestConfig2.xml"); // document with changed label and description fields
DocumentType secondIngestDoc = KEWServiceLocator.getDocumentTypeService().findByName("IngestTestDocumentType");
assertNotNull("Second ingested document has empty Previous Version ID after first ingest", secondIngestDoc.getPreviousVersionId());
DocumentType firstIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(secondIngestDoc.getPreviousVersionId());
// the second ingested document should now be set to Current with the first ingested document should no longer be set to Current
assertEquals("First ingested document is still set to Current after first ingest", Boolean.FALSE, firstIngestDoc.getCurrentInd());
assertEquals("Second ingested document is not set to Current after first ingest", Boolean.TRUE, secondIngestDoc.getCurrentInd());
// second ingestion
super.loadXmlFile("DocTypeIngestTestConfig3.xml"); // document setting active to false
firstIngestDoc = null;
secondIngestDoc = null;
DocumentType thirdIngestDoc = KEWServiceLocator.getDocumentTypeService().findByName("IngestTestDocumentType");
assertNotNull("Third ingested document has empty Previous Version ID after second ingest", thirdIngestDoc.getPreviousVersionId());
secondIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(thirdIngestDoc.getPreviousVersionId());
assertNotNull("Second ingested document has empty Previous Version ID after second ingest", secondIngestDoc.getPreviousVersionId());
firstIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(secondIngestDoc.getPreviousVersionId());
// the third ingested document should now be set to Current and Inactive... all others should not be set to Current
assertEquals("First ingested document is set to Current after second ingest", Boolean.FALSE, firstIngestDoc.getCurrentInd());
assertEquals("Second ingested document is set to Current after second ingest", Boolean.FALSE, secondIngestDoc.getCurrentInd());
assertEquals("Third ingested document is not set to Inactive after second ingest", Boolean.FALSE, thirdIngestDoc.getActive());
assertEquals("Third ingested document is not set to Current after second ingest", Boolean.TRUE, thirdIngestDoc.getCurrentInd());
// third ingestion
super.loadXmlFile("DocTypeIngestTestConfig4.xml"); // document setting active to true
firstIngestDoc = null;
secondIngestDoc = null;
thirdIngestDoc = null;
DocumentType fourthIngestDoc = KEWServiceLocator.getDocumentTypeService().findByName("IngestTestDocumentType");
assertNotNull("Fourth ingested document has empty Previous Version ID after third ingest", fourthIngestDoc.getPreviousVersionId());
thirdIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(fourthIngestDoc.getPreviousVersionId());
assertNotNull("Third ingested document has empty Previous Version ID after third ingest", thirdIngestDoc.getPreviousVersionId());
secondIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(thirdIngestDoc.getPreviousVersionId());
assertNotNull("Second ingested document has empty Previous Version ID after third ingest", secondIngestDoc.getPreviousVersionId());
firstIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(secondIngestDoc.getPreviousVersionId());
// the fourth ingested document should now be set to Current and Active... all others should not be set to Current
assertEquals("First ingested document is set to Current after third ingest", Boolean.FALSE, firstIngestDoc.getCurrentInd());
assertEquals("Second ingested document is set to Current after third ingest", Boolean.FALSE, secondIngestDoc.getCurrentInd());
assertEquals("Third ingested document is set to Current after third ingest", Boolean.FALSE, thirdIngestDoc.getCurrentInd());
assertEquals("Fourth ingested document is not set to Active after third ingest", Boolean.TRUE, fourthIngestDoc.getActive());
assertEquals("Fourth ingested document is not set to Current after third ingest", Boolean.TRUE, fourthIngestDoc.getCurrentInd());
}
@Test public void testSameFileChildParentIngestion() throws Exception {
loadXmlFile("ChildParentTestConfig1.xml");
verifyDocumentTypeLinking();
loadXmlFile("ChildParentTestConfig2.xml");
verifyDocumentTypeLinking();
}
@Test
public void testPostProcessor() throws Exception {
loadXmlFile("DoctypePostProcessorConfig.xml");
DocumentType ppTestParent1 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestParent1");
DocumentType ppTestParent2 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestParent2");
DocumentType ppTestChild1 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestChild1");
DocumentType ppTestChild2 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestChild2");
DocumentType ppTestChild3 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestChild3");
assertEquals("Incorrect PostProcessor", MockPostProcessor.class, ppTestParent1.getPostProcessor().getClass());
assertEquals("Incorrect PostProcessor", DefaultPostProcessor.class, ppTestParent2.getPostProcessor().getClass());
assertEquals("Incorrect PostProcessor", MockPostProcessor.class, ppTestChild1.getPostProcessor().getClass());
PostProcessor testChild2PP = ppTestChild2.getPostProcessor();
assertEquals("Incorrect PostProcessorRemote", EDocLitePostProcessor.class, testChild2PP.getClass());
assertEquals("Incorrect PostProcessor", DefaultPostProcessor.class, ppTestChild3.getPostProcessor().getClass());
}
/**
* Tests to ensure that a given document type has its fields updated when the a second XML doc type with the same name is ingested.
*
* NOTE: This unit test is still incomplete.
*
* @throws Exception
*/
@Test public void testUpdateOfDocTypeFields() throws Exception {
//Collection<DocumentTypePolicy> docPolicies = docType.getPolicies();
//List<DocumentTypeAttribute> docAttributes = docType.getDocumentTypeAttributes();
//List firstRouteNode = KEWServiceLocator.getRouteNodeService().getInitialNodeInstances(docType.getDocumentTypeId());
// The expected field values from the test XML files.
String[][] expectedValues = { {"TestWithMostParams1", "TestParent01", "A test of doc type parameters.", "TestWithMostParams1",
"mocks.MockPostProcessor", "KR-WKFLW:TestWorkgroup", null, "any", "KR-WKFLW:TestWorkgroup",
"KR-WKFLW:TestWorkgroup", "_blank", "_blank", "_blank", "_blank", "_blank", "TestCl1", "false", "a.doc.type.authorizer"},
{"TestWithMostParams1", "AnotherParent", "Another test of most parameters.",
"AntoherTestWithMostParams", "org.kuali.rice.kew.postprocessor.DefaultPostProcessor", "KR-WKFLW:WorkflowAdmin",
"KR-WKFLW:WorkflowAdmin", null, "KR-WKFLW:WorkflowAdmin", "KR-WKFLW:WorkflowAdmin", "_nothing", "_nothing",
"_nothing", "_nothing", "_nothing", "KEW", "true", "a.parent.authorizer"}
};
// Ingest each document type, and test the properties of each one.
for (int i = 0; i < expectedValues.length; i++) {
// Load the document type and store its data.
String fileToLoad = "DocTypeWithMostParams" + (i+1) + ".xml";
loadXmlFile(fileToLoad);
DocumentType docType = KEWServiceLocator.getDocumentTypeService().findByName("TestWithMostParams1");
Group baWorkgroup = docType.getBlanketApproveWorkgroup();
Group rpWorkgroup = docType.getReportingWorkgroup();
Group deWorkgroup = getValidDefaultExceptionWorkgroup(docType);
String[] actualValues = {docType.getName(), docType.getParentDocType().getName(), docType.getDescription(),
docType.getLabel(), docType.getPostProcessorName(), constructGroupNameWithNamespace(docType.getSuperUserWorkgroupNoInheritence()),
constructGroupNameWithNamespace(baWorkgroup), docType.getBlanketApprovePolicy(),
constructGroupNameWithNamespace(rpWorkgroup), constructGroupNameWithNamespace(deWorkgroup),
docType.getUnresolvedDocHandlerUrl(), docType.getUnresolvedHelpDefinitionUrl(),
docType.getUnresolvedDocSearchHelpUrl(),
docType.getNotificationFromAddress(), docType.getCustomEmailStylesheet(),
docType.getApplicationId(), docType.getActive().toString(),
docType.getAuthorizer()
};
// Compare the expected field values with the actual ones.
for (int j = 0; j < expectedValues[i].length; j++) {
assertEquals("The document does not have the expected parameter value. (i=" + i + ",j=" + j + ")", expectedValues[i][j], actualValues[j]);
}
}
}
private Group getValidDefaultExceptionWorkgroup(DocumentType documentType) {
List flattenedNodes = KEWServiceLocator.getRouteNodeService().getFlattenedNodes(documentType, false);
assertTrue("Document Type '" + documentType.getName() + "' should have a default exception workgroup.", hasDefaultExceptionWorkgroup(flattenedNodes));
return ((RouteNode)flattenedNodes.get(0)).getExceptionWorkgroup();
}
// this method is duplicated in the DocumentTypeXmlExporter class
private boolean hasDefaultExceptionWorkgroup(List flattenedNodes) {
boolean hasDefaultExceptionWorkgroup = true;
String exceptionWorkgroupName = null;
for (Iterator iterator = flattenedNodes.iterator(); iterator.hasNext();) {
RouteNode node = (RouteNode) iterator.next();
if (exceptionWorkgroupName == null) {
exceptionWorkgroupName = node.getExceptionWorkgroupName();
}
if (exceptionWorkgroupName == null || !exceptionWorkgroupName.equals(node.getExceptionWorkgroupName())) {
hasDefaultExceptionWorkgroup = false;
break;
}
}
return hasDefaultExceptionWorkgroup;
}
private String constructGroupNameWithNamespace(Group group) {
if (group == null) {
return null;
}
return group.getNamespaceCode() + KewApiConstants.KIM_GROUP_NAMESPACE_NAME_DELIMITER_CHARACTER + group.getName();
}
protected void verifyDocumentTypeLinking() throws Exception {
DocumentTypeService service = KEWServiceLocator.getDocumentTypeService();
List rootDocs = service.findAllCurrentRootDocuments();
int numRoots = rootDocs.size();
List documentTypes = service.findAllCurrent();
List<DocumentType> leafs = new ArrayList<DocumentType>();
for (Iterator iterator = documentTypes.iterator(); iterator.hasNext();) {
DocumentType documentType = (DocumentType) iterator.next();
// check that all document types with parents are current
if (KRADUtils.isNotNull(documentType.getParentDocType())) {
assertEquals("Parent of document type '" + documentType.getName() + "' should be Current", Boolean.TRUE, documentType.getParentDocType().getCurrentInd());
}
List children = service.getChildDocumentTypes(documentType.getDocumentTypeId());
if (children.isEmpty()) {
leafs.add(documentType);
} else {
// check that all child document types are current
for (Iterator iterator2 = children.iterator(); iterator2.hasNext();) {
DocumentType childDocType = (DocumentType) iterator2.next();
assertEquals("Any child document type should be Current", Boolean.TRUE, childDocType.getCurrentInd());
}
}
}
Set<String> rootDocIds = new HashSet<String>();
// verify the hierarchy
for (DocumentType leaf : leafs) {
verifyHierarchy(leaf, rootDocIds);
}
// we should have the same number of roots as we did from the original roots query
assertEquals("Should have the same number of roots", numRoots, rootDocIds.size());
}
protected void verifyHierarchy(DocumentType docType, Set<String> rootDocIds) {
assertTrue("DocumentType " + docType.getName() + " should be current.", docType.getCurrentInd().booleanValue());
if (docType.getParentDocType() == null) {
rootDocIds.add(docType.getDocumentTypeId());
} else {
verifyHierarchy(docType.getParentDocType(), rootDocIds);
}
}
private class LoadXml implements Runnable {
private final String xmlFile;
private final Callback callback;
private final CyclicBarrier barrier;
LoadXml(String xmlFile, Callback callback, CyclicBarrier barrier) {
this.xmlFile = xmlFile;
this.callback = callback;
this.barrier = barrier;
}
public void run() {
getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
try {
barrier.await(120, TimeUnit.SECONDS);
} catch (Exception e) {
}
try {
loadXmlFile(xmlFile);
} catch (Throwable t) {
callback.record(xmlFile, t);
}
// try {
// barrier.await(120, TimeUnit.SECONDS);
// } catch (Exception e) {
// }
}
});
}
}
private class Callback {
private String xmlFile;
private Throwable t;
public void record(String xmlFile, Throwable t) {
this.xmlFile = xmlFile;
this.t = t;
}
public boolean isXmlLoaded() {
if (t != null) {
t.printStackTrace();
//fail("Failed to load xml file " + xmlFile);
LOG.info("The XML file " + xmlFile + " failed to load, but this was expected.");
return false;
}
return true;
}
}
}
| rice-middleware/it/kew/src/test/java/org/kuali/rice/kew/doctype/DocumentTypeTest.java | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.kew.doctype;
import mocks.MockPostProcessor;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.kuali.rice.core.api.config.property.ConfigContext;
import org.kuali.rice.core.api.util.xml.XmlJotter;
import org.kuali.rice.edl.framework.workflow.EDocLitePostProcessor;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.api.KewApiServiceLocator;
import org.kuali.rice.kew.api.WorkflowDocument;
import org.kuali.rice.kew.api.WorkflowDocumentFactory;
import org.kuali.rice.kew.doctype.bo.DocumentType;
import org.kuali.rice.kew.doctype.service.DocumentTypeService;
import org.kuali.rice.kew.engine.node.NodeType;
import org.kuali.rice.kew.engine.node.ProcessDefinitionBo;
import org.kuali.rice.kew.engine.node.RouteNode;
import org.kuali.rice.kew.export.KewExportDataSet;
import org.kuali.rice.kew.framework.postprocessor.PostProcessor;
import org.kuali.rice.kew.postprocessor.DefaultPostProcessor;
import org.kuali.rice.kew.service.KEWServiceLocator;
import org.kuali.rice.kew.test.KEWTestCase;
import org.kuali.rice.kew.test.TestUtilities;
import org.kuali.rice.kew.xml.export.DocumentTypeXmlExporter;
import org.kuali.rice.kim.api.KimConstants;
import org.kuali.rice.kim.api.group.Group;
import org.kuali.rice.krad.util.KRADUtils;
import org.kuali.rice.test.BaselineTestCase;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
@BaselineTestCase.BaselineMode(BaselineTestCase.Mode.NONE)
public class DocumentTypeTest extends KEWTestCase {
private static final Logger LOG = Logger.getLogger(DocumentTypeTest.class);
protected void loadTestData() throws Exception {
ConfigContext.getCurrentContextConfig().putProperty("test.doctype.workgroup", "TestWorkgroup");
loadXmlFile("DoctypeConfig.xml");
}
@Test public void testDuplicateNodeName() throws Exception {
try {
loadXmlFile("DocTypeConfig_loadDupliateNodes.xml");
fail("loadXmlFile should have thrown routing exception");
} catch (Exception e) {
}
}
@Test public void testDuplicateNodeNameInRoutePath() throws Exception {
loadXmlFile("DocTypeConfig_duplicateNodes.xml");
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "TestDoubleNodeDocumentType");
document.setTitle("");
document.route("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), document.getDocumentId());
assertTrue("user2 should have an approve request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), document.getDocumentId());
assertTrue("user3 should have an approve request", document.isApprovalRequested());
document.approve("");
}
@Test public void testNestedDuplicateNodeNameInRoutePath() throws Exception {
int waitMilliSeconds = 10000;
loadXmlFile("DocTypeConfig_nestedNodes.xml");
// Path 1
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "TestDoubleNodeDocumentType");
document.setTitle("");
document.route("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request; the first request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), document.getDocumentId());
assertTrue("user2 should have an approve request", document.isApprovalRequested());
document.approve("");
Thread.sleep(waitMilliSeconds);
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), document.getDocumentId());
assertTrue("user3 should have an approve request; the first request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user4"), document.getDocumentId());
assertTrue("user4 should have an approve request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request; the second request", document.isApprovalRequested());
document.approve("");
Thread.sleep(waitMilliSeconds);
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), document.getDocumentId());
assertTrue("user3 should have an approve request; the second request", document.isApprovalRequested());
document.approve("");
}
/**
* Verify that enroute documents are not affected if you edit their document type.
* @throws Exception
*/
@Test public void testChangingDocumentTypeOnEnrouteDocument() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "DocumentType");
document.setTitle("");
document.route("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request", document.isApprovalRequested());
org.kuali.rice.kew.api.doctype.DocumentTypeService docTypeService = KewApiServiceLocator.getDocumentTypeService();
Integer version1 = docTypeService.getDocumentTypeByName(document.getDocumentTypeName()).getDocumentTypeVersion();
//update the document type
loadXmlFile("DoctypeSecondVersion.xml");
//verify that we have a new documenttypeid and its a newer version
Integer version2 = docTypeService.getDocumentTypeByName(document.getDocumentTypeName()).getDocumentTypeVersion();
assertTrue("Version2 should be larger than verison1", version2.intValue() > version1.intValue());
//the new version would take the document final
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("rkirkend should have an approve request", document.isApprovalRequested());
document.approve("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), document.getDocumentId());
Integer versionDocument = docTypeService.getDocumentTypeById(document.getDocument().getDocumentTypeId()).getDocumentTypeVersion();
assertTrue("user2 should have an approve request", document.isApprovalRequested());
//make sure our document still represents the accurate version
assertEquals("Document has the wrong document type version", version1, versionDocument);
}
/**
* this test will verify that finalapprover node policies work
*
* @throws Exception
*/
@Test public void testFinalApproverRouting() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "FinalApproverDocumentType");
document.setTitle("");
document.route("");
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
try {
document.approve("");
fail("document should have thrown routing exception");
} catch (Exception e) {
//deal with single transaction issue in test.
TestUtilities.getExceptionThreader().join();
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("rkirkend"), document.getDocumentId());
assertTrue("Document should be in exception routing", document.isException());
}
}
/**
* this test will verify that a document type with an empty route path will go directly
* to "final" status
*
* @throws Exception
*/
@Test public void testEmptyRoutePath() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "EmptyRoutePathDocumentType");
document.setTitle("");
document.route("");
assertTrue("Document should be in final state", document.isFinal());
}
/**
* Tests that route nodes mark as mandatory send out approve requests
* @throws Exception
*/
@Test public void testMandatoryRoute() throws Exception {
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("user1"), "MandatoryRouteDocumentType");
document.setTitle("");
try {
document.route("");
} catch (Exception e) {
//deal with single transaction issue in test.
TestUtilities.getExceptionThreader().join();
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user1"), document.getDocumentId());
assertTrue("Document should be in exception routing", document.isException());
}
}
/**
* Makes sure the DocumentTypeXmlParser is working. Compare the parsed 'DocumentType' doctype to it's expected values.
* This test does not include multiple processes.
*
* @throws Exception
*/
@Test public void testDocumentTypeXmlParser() throws Exception {
ConfigContext.getCurrentContextConfig().putProperty("test.base.url", "http://someurl/path");
DocumentType parsedDocument = KEWServiceLocator.getDocumentTypeService().findByName("DocumentType");
assertEquals("Wrong name", "DocumentType", parsedDocument.getName());
assertEquals("Wrong description", "TestDocumentType", parsedDocument.getDescription());
assertEquals("Wrong label", "TestDocumentType", parsedDocument.getLabel());
assertEquals("Wrong postprocessor", "org.kuali.rice.kew.postprocessor.DefaultPostProcessor", parsedDocument.getPostProcessorName());
assertEquals("Wrong su workgroup", "TestWorkgroup", parsedDocument.getSuperUserWorkgroup().getName());
// roundabout way of testing to see if the exception workgroup has been processed properly
DocumentTypeXmlExporter exporter = new DocumentTypeXmlExporter();
KewExportDataSet dataSet = new KewExportDataSet();
dataSet.getDocumentTypes().add(parsedDocument);
String regex = "(?s).*<defaultExceptionGroupName namespace=\"" + KimConstants.KIM_GROUP_WORKFLOW_NAMESPACE_CODE + "\">TestWorkgroup</defaultExceptionGroupName>.*";
LOG.warn("Using regex: " + regex);
assertTrue(XmlJotter.jotNode(exporter.export(dataSet.createExportDataSet())).matches(regex));
//assertNotNull(parsedDocument.getDefaultExceptionWorkgroup());
//assertEquals("Wrong default exception workgroup", "TestWorkgroup", parsedDocument.getDefaultExceptionWorkgroup().getDisplayName());
assertEquals("Wrong doc handler url", "http://someurl/path/_blank", parsedDocument.getResolvedDocumentHandlerUrl());
assertEquals("Wrong unresolved doc handler url", "${test.base.url}/_blank", parsedDocument.getUnresolvedDocHandlerUrl());
assertEquals("Wrong help def url", "/_help", parsedDocument.getHelpDefinitionUrl());
assertEquals("Wrong unresolved help def url", "/_help", parsedDocument.getUnresolvedHelpDefinitionUrl());
assertEquals("Wrong blanketApprover workgroup", "TestWorkgroup", parsedDocument.getBlanketApproveWorkgroup().getName());
assertEquals("Wrong blanketApprove policy", null, parsedDocument.getBlanketApprovePolicy());
assertEquals("Wrong DEFAULT_APPROVE policy value", Boolean.FALSE, parsedDocument.getDefaultApprovePolicy().getPolicyValue());
assertEquals("Wrong LOOK_FUTURE", Boolean.TRUE, parsedDocument.getLookIntoFuturePolicy().getPolicyValue());
List processes = parsedDocument.getProcesses();
assertEquals("Should only be 1 process", 1, processes.size());
//this is going against the intended structure and is very brittle
ProcessDefinitionBo process = (ProcessDefinitionBo)processes.get(0);
List flattenedNodeList = KEWServiceLocator.getRouteNodeService().getFlattenedNodes(process);
assertEquals("Should be 6 total route nodes", 6, flattenedNodeList.size());
RouteNode adHocNode = process.getInitialRouteNode();
assertEquals("Wrong node name should be 'AdHoc'", "AdHoc",adHocNode.getRouteNodeName());
assertTrue("Wrong node type", NodeType.START.isAssignableFrom(Class.forName(adHocNode.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", adHocNode.getExceptionWorkgroup().getName());
RouteNode split = (RouteNode)adHocNode.getNextNodes().get(0);
assertEquals("Wrong node name", "Split", split.getRouteNodeName());
assertTrue("Wrong node type", NodeType.SPLIT.isAssignableFrom(Class.forName(split.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", split.getExceptionWorkgroup().getName());
assertTrue(split.getNextNodes().size() == 2);
boolean ruleTemplate1Found = false;
boolean ruleTemplate2Found = false;
for (RouteNode routeNode : split.getNextNodes()) {
if (routeNode.getRouteNodeName().equals("RuleTemplate1")) {
assertTrue("Wrong node type", NodeType.REQUESTS.isAssignableFrom(Class.forName(routeNode.getNodeType())));
assertEquals("Wrong branch name", "B1", routeNode.getBranch().getName());
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", routeNode.getExceptionWorkgroup().getName());
ruleTemplate1Found = true;
}
if (routeNode.getRouteNodeName().equals("RuleTemplate2")) {
assertTrue("Wrong node type", NodeType.REQUESTS.isAssignableFrom(Class.forName(routeNode.getNodeType())));
assertEquals("Wrong branch name", "B2", routeNode.getBranch().getName());
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", routeNode.getExceptionWorkgroup().getName());
ruleTemplate2Found = true;
RouteNode join = (RouteNode)routeNode.getNextNodes().get(0);
assertEquals("Wrong node name", "Join", join.getRouteNodeName());
assertTrue("Wrong node type", NodeType.JOIN.isAssignableFrom(Class.forName(join.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", join.getExceptionWorkgroup().getName());
RouteNode ruleTemplate3 = (RouteNode)join.getNextNodes().get(0);
assertEquals("Wrong node name", "RuleTemplate3", ruleTemplate3.getRouteNodeName());
assertTrue("Wrong node type", NodeType.REQUESTS.isAssignableFrom(Class.forName(ruleTemplate3.getNodeType())));
assertEquals("Default Exception workgroup not propagated", "TestWorkgroup", ruleTemplate3.getExceptionWorkgroup().getName());
}
}
assertTrue(ruleTemplate1Found);
assertTrue(ruleTemplate2Found);
}
//verifies the documenttype hierarchy is intact after multiple uploads
@Test public void testHierarchyUpload() throws Exception {
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
DocumentType parent = KEWServiceLocator.getDocumentTypeService().findByName("UGSDocumentType");
boolean foundRemonstrance = false;
boolean foundNewCourse = false;
boolean foundDelete = false;
for (Iterator iter = parent.getChildrenDocTypes().iterator(); iter.hasNext();) {
DocumentType childDocType = (DocumentType) iter.next();
assertTrue("child documenttype should be current", childDocType.getCurrentInd().booleanValue());
if(childDocType.getName().equals("CourseRemonstranceProcess")) {
foundRemonstrance = true;
} else if (childDocType.getName().equals("NewCourseRequest")) {
foundNewCourse = true;
} else if (childDocType.getName().equals("DeleteCourseRequest")) {
foundDelete = true;
}
}
assertTrue("Didn't find CourseRemonstraneProcess", foundRemonstrance);
assertTrue("Didn't find NewCourseRequest", foundNewCourse);
assertTrue("Didn't find DeleteCourseRequest", foundDelete);
//reload and verify that the structure looks the same - the below is missing one of the children document types
//to verify that a partial upload of the hierarchy doesn't kill the entire hierarchy
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration2.xml");
parent = KEWServiceLocator.getDocumentTypeService().findByName("UGSDocumentType");
foundRemonstrance = false;
foundNewCourse = false;
foundDelete = false;
int i = 0;
for (Iterator iter = parent.getChildrenDocTypes().iterator(); iter.hasNext(); i++) {
DocumentType childDocType = (DocumentType) iter.next();
assertTrue("child documenttype should be current", childDocType.getCurrentInd().booleanValue());
if(childDocType.getName().equals("CourseRemonstranceProcess")) {
foundRemonstrance = true;
} else if (childDocType.getName().equals("NewCourseRequest")) {
foundNewCourse = true;
} else if (childDocType.getName().equals("DeleteCourseRequest")) {
foundDelete = true;
}
}
assertTrue("Didn't find CourseRemonstranceProcess", foundRemonstrance);
assertTrue("Didn't find NewCourseRequest", foundNewCourse);
assertTrue("Didn't find DeleteCourseRequest", foundDelete);
}
//verifies documenttype hierarchy is intact after uploading a series of documenttypes and then
//uploading a parent onto those document types
@Test public void testHierarchyUpload2() throws Exception {
super.loadXmlFile("DocTypesWithoutParent.xml");
//Verify that the document types are there
DocumentType courseRemonstrance1 = KEWServiceLocator.getDocumentTypeService().findByName("CourseRemonstranceProcess");
DocumentType newCourseRequest1 = KEWServiceLocator.getDocumentTypeService().findByName("NewCourseRequest");
DocumentType deleteCourse1 = KEWServiceLocator.getDocumentTypeService().findByName("DeleteCourseRequest");
//upload the new config with the parent and verify we are getting new document types with new versions
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
DocumentType courseRemonstrance2 = null;
DocumentType newCourseRequest2 = null;
DocumentType deleteCourse2 = null;
DocumentType ugsDocumentType = KEWServiceLocator.getDocumentTypeService().findByName("UGSDocumentType");
for (Iterator iter = ugsDocumentType.getChildrenDocTypes().iterator(); iter.hasNext();) {
DocumentType childDocType = (DocumentType) iter.next();
if(childDocType.getName().equals("CourseRemonstranceProcess")) {
courseRemonstrance2 = childDocType;
} else if (childDocType.getName().equals("NewCourseRequest")) {
newCourseRequest2 = childDocType;
} else if (childDocType.getName().equals("DeleteCourseRequest")) {
deleteCourse2 = childDocType;
}
}
assertNotNull(courseRemonstrance2);
assertNotNull(newCourseRequest2);
assertNotNull(deleteCourse2);
assertTrue("Version didn't get incremented", courseRemonstrance1.getVersion().intValue() < courseRemonstrance2.getVersion().intValue());
assertTrue("Version didn't increment", newCourseRequest1.getVersion().intValue() < newCourseRequest2.getVersion().intValue());
assertTrue("Version didn't increment", deleteCourse1.getVersion().intValue() < deleteCourse2.getVersion().intValue());
}
/**
* Tests that the document type ingestion will not create a brand new
* document when only label or description field changes. Relates to
* JIRA's EN-318 and KULOWF-147.
*
* @throws Exception
*/
@Test public void testDocumentTypeIngestion() throws Exception {
// first ingestion
super.loadXmlFile("DocTypeIngestTestConfig1.xml"); // original document
super.loadXmlFile("DocTypeIngestTestConfig2.xml"); // document with changed label and description fields
DocumentType secondIngestDoc = KEWServiceLocator.getDocumentTypeService().findByName("IngestTestDocumentType");
assertNotNull("Second ingested document has empty Previous Version ID after first ingest", secondIngestDoc.getPreviousVersionId());
DocumentType firstIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(secondIngestDoc.getPreviousVersionId());
// the second ingested document should now be set to Current with the first ingested document should no longer be set to Current
assertEquals("First ingested document is still set to Current after first ingest", Boolean.FALSE, firstIngestDoc.getCurrentInd());
assertEquals("Second ingested document is not set to Current after first ingest", Boolean.TRUE, secondIngestDoc.getCurrentInd());
// second ingestion
super.loadXmlFile("DocTypeIngestTestConfig3.xml"); // document setting active to false
firstIngestDoc = null;
secondIngestDoc = null;
DocumentType thirdIngestDoc = KEWServiceLocator.getDocumentTypeService().findByName("IngestTestDocumentType");
assertNotNull("Third ingested document has empty Previous Version ID after second ingest", thirdIngestDoc.getPreviousVersionId());
secondIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(thirdIngestDoc.getPreviousVersionId());
assertNotNull("Second ingested document has empty Previous Version ID after second ingest", secondIngestDoc.getPreviousVersionId());
firstIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(secondIngestDoc.getPreviousVersionId());
// the third ingested document should now be set to Current and Inactive... all others should not be set to Current
assertEquals("First ingested document is set to Current after second ingest", Boolean.FALSE, firstIngestDoc.getCurrentInd());
assertEquals("Second ingested document is set to Current after second ingest", Boolean.FALSE, secondIngestDoc.getCurrentInd());
assertEquals("Third ingested document is not set to Inactive after second ingest", Boolean.FALSE, thirdIngestDoc.getActive());
assertEquals("Third ingested document is not set to Current after second ingest", Boolean.TRUE, thirdIngestDoc.getCurrentInd());
// third ingestion
super.loadXmlFile("DocTypeIngestTestConfig4.xml"); // document setting active to true
firstIngestDoc = null;
secondIngestDoc = null;
thirdIngestDoc = null;
DocumentType fourthIngestDoc = KEWServiceLocator.getDocumentTypeService().findByName("IngestTestDocumentType");
assertNotNull("Fourth ingested document has empty Previous Version ID after third ingest", fourthIngestDoc.getPreviousVersionId());
thirdIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(fourthIngestDoc.getPreviousVersionId());
assertNotNull("Third ingested document has empty Previous Version ID after third ingest", thirdIngestDoc.getPreviousVersionId());
secondIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(thirdIngestDoc.getPreviousVersionId());
assertNotNull("Second ingested document has empty Previous Version ID after third ingest", secondIngestDoc.getPreviousVersionId());
firstIngestDoc = KEWServiceLocator.getDocumentTypeService().findById(secondIngestDoc.getPreviousVersionId());
// the fourth ingested document should now be set to Current and Active... all others should not be set to Current
assertEquals("First ingested document is set to Current after third ingest", Boolean.FALSE, firstIngestDoc.getCurrentInd());
assertEquals("Second ingested document is set to Current after third ingest", Boolean.FALSE, secondIngestDoc.getCurrentInd());
assertEquals("Third ingested document is set to Current after third ingest", Boolean.FALSE, thirdIngestDoc.getCurrentInd());
assertEquals("Fourth ingested document is not set to Active after third ingest", Boolean.TRUE, fourthIngestDoc.getActive());
assertEquals("Fourth ingested document is not set to Current after third ingest", Boolean.TRUE, fourthIngestDoc.getCurrentInd());
}
@Test public void testDocumentTypeParentChildLinking() throws Exception {
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
verifyDocumentTypeLinking();
// scenario 1, update the parent document type and verify that all linking is correct
super.loadXmlFile("ParentWithChildrenDocTypeConfigurationUpdate1.xml");
verifyDocumentTypeLinking();
// scenario 2, update a child document type and verify that all linking is correct
super.loadXmlFile("ParentWithChildrenDocTypeConfigurationUpdate2.xml");
verifyDocumentTypeLinking();
// let's reimport from the beginning as well
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
verifyDocumentTypeLinking();
// scenario 3, try an xml file with child doctype listed first
super.loadXmlFile("ParentWithChildrenDocTypeConfigurationUpdate3.xml");
verifyDocumentTypeLinking();
// try loading each of these in parallel threads to verify caching can
// handle concurrency situations
String[] fileNames = {
"ParentWithChildrenDocTypeConfiguration.xml",
"DocTypeIngestTestConfig1.xml",
"DocumentTypeAttributeFetchTest.xml",
"ChildDocType1.xml",
"ChildDocType2.xml",
"ChildDocType3.xml",
"ChildDocType4.xml",
};
List<Callback> callbacks = new ArrayList<Callback>();
CyclicBarrier barrier = new CyclicBarrier(fileNames.length);
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < fileNames.length; i++) {
Callback callback = new Callback();
callbacks.add(callback);
threads.add(new Thread(new LoadXml(fileNames[i], callback, barrier)));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join(2*60*1000);
}
// What should have happened here was an optimistic lock being thrown from the
// document type XML import. Currently, that code is catching and just logging
// those errors (not rethrowing), so there's no way for us to check that the
// optimistic lock was thrown. However, the verifyDocumentTypeLinking should pass
// because the update was never made, and we can check to make sure that
// at least one of the above documents failed to be ingested.
boolean atLeastOneFailure = false;
for (Callback callback : callbacks) {
if (!callback.isXmlLoaded()) {
atLeastOneFailure = true;
}
}
assertTrue("At least one of the XML files should have failed the ingestion process", atLeastOneFailure);
verifyDocumentTypeLinking();
// reload again for good measure
super.loadXmlFile("ParentWithChildrenDocTypeConfiguration.xml");
verifyDocumentTypeLinking();
}
@Test public void testSameFileChildParentIngestion() throws Exception {
loadXmlFile("ChildParentTestConfig1.xml");
verifyDocumentTypeLinking();
loadXmlFile("ChildParentTestConfig2.xml");
verifyDocumentTypeLinking();
}
@Test
public void testPostProcessor() throws Exception {
loadXmlFile("DoctypePostProcessorConfig.xml");
DocumentType ppTestParent1 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestParent1");
DocumentType ppTestParent2 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestParent2");
DocumentType ppTestChild1 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestChild1");
DocumentType ppTestChild2 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestChild2");
DocumentType ppTestChild3 = KEWServiceLocator.getDocumentTypeService().findByName("PPTestChild3");
assertEquals("Incorrect PostProcessor", MockPostProcessor.class, ppTestParent1.getPostProcessor().getClass());
assertEquals("Incorrect PostProcessor", DefaultPostProcessor.class, ppTestParent2.getPostProcessor().getClass());
assertEquals("Incorrect PostProcessor", MockPostProcessor.class, ppTestChild1.getPostProcessor().getClass());
PostProcessor testChild2PP = ppTestChild2.getPostProcessor();
assertEquals("Incorrect PostProcessorRemote", EDocLitePostProcessor.class, testChild2PP.getClass());
assertEquals("Incorrect PostProcessor", DefaultPostProcessor.class, ppTestChild3.getPostProcessor().getClass());
}
/**
* Tests to ensure that a given document type has its fields updated when the a second XML doc type with the same name is ingested.
*
* NOTE: This unit test is still incomplete.
*
* @throws Exception
*/
@Test public void testUpdateOfDocTypeFields() throws Exception {
//Collection<DocumentTypePolicy> docPolicies = docType.getPolicies();
//List<DocumentTypeAttribute> docAttributes = docType.getDocumentTypeAttributes();
//List firstRouteNode = KEWServiceLocator.getRouteNodeService().getInitialNodeInstances(docType.getDocumentTypeId());
// The expected field values from the test XML files.
String[][] expectedValues = { {"TestWithMostParams1", "TestParent01", "A test of doc type parameters.", "TestWithMostParams1",
"mocks.MockPostProcessor", "KR-WKFLW:TestWorkgroup", null, "any", "KR-WKFLW:TestWorkgroup",
"KR-WKFLW:TestWorkgroup", "_blank", "_blank", "_blank", "_blank", "_blank", "TestCl1", "false", "a.doc.type.authorizer"},
{"TestWithMostParams1", "AnotherParent", "Another test of most parameters.",
"AntoherTestWithMostParams", "org.kuali.rice.kew.postprocessor.DefaultPostProcessor", "KR-WKFLW:WorkflowAdmin",
"KR-WKFLW:WorkflowAdmin", null, "KR-WKFLW:WorkflowAdmin", "KR-WKFLW:WorkflowAdmin", "_nothing", "_nothing",
"_nothing", "_nothing", "_nothing", "KEW", "true", "a.parent.authorizer"}
};
// Ingest each document type, and test the properties of each one.
for (int i = 0; i < expectedValues.length; i++) {
// Load the document type and store its data.
String fileToLoad = "DocTypeWithMostParams" + (i+1) + ".xml";
loadXmlFile(fileToLoad);
DocumentType docType = KEWServiceLocator.getDocumentTypeService().findByName("TestWithMostParams1");
Group baWorkgroup = docType.getBlanketApproveWorkgroup();
Group rpWorkgroup = docType.getReportingWorkgroup();
Group deWorkgroup = getValidDefaultExceptionWorkgroup(docType);
String[] actualValues = {docType.getName(), docType.getParentDocType().getName(), docType.getDescription(),
docType.getLabel(), docType.getPostProcessorName(), constructGroupNameWithNamespace(docType.getSuperUserWorkgroupNoInheritence()),
constructGroupNameWithNamespace(baWorkgroup), docType.getBlanketApprovePolicy(),
constructGroupNameWithNamespace(rpWorkgroup), constructGroupNameWithNamespace(deWorkgroup),
docType.getUnresolvedDocHandlerUrl(), docType.getUnresolvedHelpDefinitionUrl(),
docType.getUnresolvedDocSearchHelpUrl(),
docType.getNotificationFromAddress(), docType.getCustomEmailStylesheet(),
docType.getApplicationId(), docType.getActive().toString(),
docType.getAuthorizer()
};
// Compare the expected field values with the actual ones.
for (int j = 0; j < expectedValues[i].length; j++) {
assertEquals("The document does not have the expected parameter value. (i=" + i + ",j=" + j + ")", expectedValues[i][j], actualValues[j]);
}
}
}
private Group getValidDefaultExceptionWorkgroup(DocumentType documentType) {
List flattenedNodes = KEWServiceLocator.getRouteNodeService().getFlattenedNodes(documentType, false);
assertTrue("Document Type '" + documentType.getName() + "' should have a default exception workgroup.", hasDefaultExceptionWorkgroup(flattenedNodes));
return ((RouteNode)flattenedNodes.get(0)).getExceptionWorkgroup();
}
// this method is duplicated in the DocumentTypeXmlExporter class
private boolean hasDefaultExceptionWorkgroup(List flattenedNodes) {
boolean hasDefaultExceptionWorkgroup = true;
String exceptionWorkgroupName = null;
for (Iterator iterator = flattenedNodes.iterator(); iterator.hasNext();) {
RouteNode node = (RouteNode) iterator.next();
if (exceptionWorkgroupName == null) {
exceptionWorkgroupName = node.getExceptionWorkgroupName();
}
if (exceptionWorkgroupName == null || !exceptionWorkgroupName.equals(node.getExceptionWorkgroupName())) {
hasDefaultExceptionWorkgroup = false;
break;
}
}
return hasDefaultExceptionWorkgroup;
}
private String constructGroupNameWithNamespace(Group group) {
if (group == null) {
return null;
}
return group.getNamespaceCode() + KewApiConstants.KIM_GROUP_NAMESPACE_NAME_DELIMITER_CHARACTER + group.getName();
}
protected void verifyDocumentTypeLinking() throws Exception {
DocumentTypeService service = KEWServiceLocator.getDocumentTypeService();
List rootDocs = service.findAllCurrentRootDocuments();
int numRoots = rootDocs.size();
List documentTypes = service.findAllCurrent();
List<DocumentType> leafs = new ArrayList<DocumentType>();
for (Iterator iterator = documentTypes.iterator(); iterator.hasNext();) {
DocumentType documentType = (DocumentType) iterator.next();
// check that all document types with parents are current
if (KRADUtils.isNotNull(documentType.getParentDocType())) {
assertEquals("Parent of document type '" + documentType.getName() + "' should be Current", Boolean.TRUE, documentType.getParentDocType().getCurrentInd());
}
List children = service.getChildDocumentTypes(documentType.getDocumentTypeId());
if (children.isEmpty()) {
leafs.add(documentType);
} else {
// check that all child document types are current
for (Iterator iterator2 = children.iterator(); iterator2.hasNext();) {
DocumentType childDocType = (DocumentType) iterator2.next();
assertEquals("Any child document type should be Current", Boolean.TRUE, childDocType.getCurrentInd());
}
}
}
Set<String> rootDocIds = new HashSet<String>();
// verify the hierarchy
for (DocumentType leaf : leafs) {
verifyHierarchy(leaf, rootDocIds);
}
// we should have the same number of roots as we did from the original roots query
assertEquals("Should have the same number of roots", numRoots, rootDocIds.size());
}
protected void verifyHierarchy(DocumentType docType, Set<String> rootDocIds) {
assertTrue("DocumentType " + docType.getName() + " should be current.", docType.getCurrentInd().booleanValue());
if (docType.getParentDocType() == null) {
rootDocIds.add(docType.getDocumentTypeId());
} else {
verifyHierarchy(docType.getParentDocType(), rootDocIds);
}
}
private class LoadXml implements Runnable {
private final String xmlFile;
private final Callback callback;
private final CyclicBarrier barrier;
LoadXml(String xmlFile, Callback callback, CyclicBarrier barrier) {
this.xmlFile = xmlFile;
this.callback = callback;
this.barrier = barrier;
}
public void run() {
getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
try {
barrier.await(120, TimeUnit.SECONDS);
} catch (Exception e) {
}
try {
loadXmlFile(xmlFile);
} catch (Throwable t) {
callback.record(xmlFile, t);
}
// try {
// barrier.await(120, TimeUnit.SECONDS);
// } catch (Exception e) {
// }
}
});
}
}
private class Callback {
private String xmlFile;
private Throwable t;
public void record(String xmlFile, Throwable t) {
this.xmlFile = xmlFile;
this.t = t;
}
public boolean isXmlLoaded() {
if (t != null) {
t.printStackTrace();
//fail("Failed to load xml file " + xmlFile);
LOG.info("The XML file " + xmlFile + " failed to load, but this was expected.");
return false;
}
return true;
}
}
}
| KULRICE-12853 - IT Failure DocumentTypeTest testNestedDuplicateNodeNameInRoutePath user3 should have an approve request
git-svn-id: 2a5d2b5a02908a0c4ba7967b726d8c4198d1b9ed@47588 7a7aa7f6-c479-11dc-97e2-85a2497f191d
| rice-middleware/it/kew/src/test/java/org/kuali/rice/kew/doctype/DocumentTypeTest.java | KULRICE-12853 - IT Failure DocumentTypeTest testNestedDuplicateNodeNameInRoutePath user3 should have an approve request |
|
Java | apache-2.0 | 7288819e420f83d69d6e1c28e71e2fe71ce7828f | 0 | indeedeng/proctor,indeedeng/proctor | package com.indeed.proctor.consumer;
import com.indeed.proctor.common.model.Payload;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.reflect.Array;
import java.util.List;
import java.util.function.Function;
public abstract class AbstractGroupsPayload {
/**
* Used because ObjectMapper does not always read in longs as longs (can be integer)
*/
private static final Function<Object, Long> LONG_CONVERTER = o -> ((Number) o).longValue();
/**
* Used because ObjectMapper does not always read in doubles as doubles (can be integer)
*/
private static final Function<Object, Double> DOUBLE_CONVERTER = o -> ((Number) o).doubleValue();
@Nullable
protected String convertToStringValue(final Payload payload, final String payloadMapKey) throws IllegalArgumentException {
checkPayloadExist(payload, payloadMapKey);
// historically, null was allowed for String, reasons unknown
return (String) payload.getMap().get(payloadMapKey);
}
protected Long convertToLongValue(final Payload payload, final String payloadMapKey) throws IllegalArgumentException {
checkPayloadExist(payload, payloadMapKey);
return extractNonNullValueFromMapPayload(payload, payloadMapKey, LONG_CONVERTER);
}
protected Double convertToDoubleValue(final Payload payload, final String payloadMapKey) throws IllegalArgumentException {
checkPayloadExist(payload, payloadMapKey);
return extractNonNullValueFromMapPayload(payload, payloadMapKey, DOUBLE_CONVERTER);
}
@SuppressWarnings("unchecked")
protected String[] convertToStringArray(final Payload payload, final String payloadMapKey) throws IllegalArgumentException {
checkPayloadExist(payload, payloadMapKey);
final List<Object> list = extractNonNullValueFromMapPayload(payload, payloadMapKey, o -> (List) o);
return convertToTypedArray(list, o -> (String) o, String.class);
}
@SuppressWarnings("unchecked")
protected Long[] convertToLongArray(final Payload payload, final String payloadMapKey) throws IllegalArgumentException {
checkPayloadExist(payload, payloadMapKey);
final List<Object> list = extractNonNullValueFromMapPayload(payload, payloadMapKey, o -> (List) o);
return convertToTypedArray(list, LONG_CONVERTER, Long.class);
}
@SuppressWarnings("unchecked")
protected Double[] convertToDoubleArray(final Payload payload, final String payloadMapKey) throws IllegalArgumentException {
checkPayloadExist(payload, payloadMapKey);
final List<Object> list = extractNonNullValueFromMapPayload(payload, payloadMapKey, o -> (List) o);
return convertToTypedArray(list, DOUBLE_CONVERTER, Double.class);
}
private static void checkPayloadExist(final Payload payload, final String payloadMapKey) {
if (payload != null && payload.getMap() != null && payload.getMap().containsKey(payloadMapKey)) {
return;
}
throw new IllegalArgumentException(
"Missing payload for constructor for key '" + payloadMapKey + '\'' + " in Payload: " + payload);
}
/**
* @throws NullPointerException else if map value is null
* @return extracted payload Value cast to given class if not null
*/
@Nonnull
@SuppressWarnings("unchecked")
private static <T> T extractNonNullValueFromMapPayload(
final Payload payload,
final String payloadMapKey,
final Function<Object, T> converter
) {
// assumes (from checkPayloadExist) that payload != null, payload.getMap() != null, ...
final T result = converter.apply(payload.getMap().get(payloadMapKey));
if (result != null) {
return result;
}
throw new NullPointerException(
"Null payload value for constructor for key '" + payloadMapKey + '\'' + " in Payload: " + payload);
}
@SuppressWarnings("unchecked")
private static <T> T[] convertToTypedArray(final List<Object> list, final Function<Object, T> converter, final Class<T> clazz) {
final T[] toReturn = (T[]) Array.newInstance(clazz, list.size());
for (int i = 0; i < list.size(); i++) {
toReturn[i] = converter.apply(list.get(i));
}
return toReturn;
}
}
| proctor-consumer/src/main/java/com/indeed/proctor/consumer/AbstractGroupsPayload.java | package com.indeed.proctor.consumer;
import com.indeed.proctor.common.model.Payload;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.reflect.Array;
import java.util.List;
import java.util.function.Function;
public abstract class AbstractGroupsPayload {
@Nullable
protected String convertToStringValue(final Payload payload, final String payloadMapKey) throws IllegalArgumentException {
checkPayloadExist(payload, payloadMapKey);
// historically, null was allowed for String, reasons unknown
return (String) payload.getMap().get(payloadMapKey);
}
protected Long convertToLongValue(final Payload payload, final String payloadMapKey) throws IllegalArgumentException {
checkPayloadExist(payload, payloadMapKey);
return extractNonNullValueFromMapPayload(payload, payloadMapKey, Number.class).longValue();
}
protected Double convertToDoubleValue(final Payload payload, final String payloadMapKey) throws IllegalArgumentException {
checkPayloadExist(payload, payloadMapKey);
return extractNonNullValueFromMapPayload(payload, payloadMapKey, Number.class).doubleValue();
}
@SuppressWarnings("unchecked")
protected String[] convertToStringArray(final Payload payload, final String payloadMapKey) throws IllegalArgumentException {
checkPayloadExist(payload, payloadMapKey);
final List<Object> list = extractNonNullValueFromMapPayload(payload, payloadMapKey, List.class);
return convertToTypedArray(list, o -> (String) o, String.class);
}
@SuppressWarnings("unchecked")
protected Long[] convertToLongArray(final Payload payload, final String payloadMapKey) throws IllegalArgumentException {
checkPayloadExist(payload, payloadMapKey);
final List<Object> list = extractNonNullValueFromMapPayload(payload, payloadMapKey, List.class);
return convertToTypedArray(list, i -> ((Number) i).longValue(), Long.class);
}
@SuppressWarnings("unchecked")
protected Double[] convertToDoubleArray(final Payload payload, final String payloadMapKey) throws IllegalArgumentException {
checkPayloadExist(payload, payloadMapKey);
final List<Object> list = extractNonNullValueFromMapPayload(payload, payloadMapKey, List.class);
return convertToTypedArray(list, i -> ((Number) i).doubleValue(), Double.class);
}
private static void checkPayloadExist(final Payload payload, final String payloadMapKey) {
if (payload != null && payload.getMap() != null && payload.getMap().containsKey(payloadMapKey)) {
return;
}
throw new IllegalArgumentException(
"Missing payload for constructor for key '" + payloadMapKey + '\'' + " in Payload: " + payload);
}
/**
* @throws NullPointerException else if map value is null
* @return extracted payload Value cast to given class if not null
*/
@Nonnull
@SuppressWarnings("unchecked")
private static <T> T extractNonNullValueFromMapPayload(
final Payload payload,
final String payloadMapKey,
final Class<T> clazz
) {
// assumes (from checkPayloadExist) that payload != null, payload.getMap() != null, ...
final T result = (T) payload.getMap().get(payloadMapKey);
if (result != null) {
return result;
}
throw new NullPointerException(
"Null payload value for constructor for key '" + payloadMapKey + '\'' + " in Payload: " + payload);
}
@SuppressWarnings("unchecked")
private static <T> T[] convertToTypedArray(final List<Object> list, final Function<Object, T> converter, final Class<T> clazz) {
final T[] toReturn = (T[]) Array.newInstance(clazz, list.size());
for (int i = 0; i < list.size(); i++) {
toReturn[i] = converter.apply(list.get(i));
}
return toReturn;
}
}
| NOBUG: Refactor: extract common converters
| proctor-consumer/src/main/java/com/indeed/proctor/consumer/AbstractGroupsPayload.java | NOBUG: Refactor: extract common converters |
|
Java | apache-2.0 | 607ded6bde649b982ed8653bfd913ca37df525c9 | 0 | alexzaitzev/ignite,irudyak/ignite,SharplEr/ignite,zzcclp/ignite,gargvish/ignite,kromulan/ignite,tkpanther/ignite,vsisko/incubator-ignite,dlnufox/ignite,kidaa/incubator-ignite,NSAmelchev/ignite,kidaa/incubator-ignite,abhishek-ch/incubator-ignite,ptupitsyn/ignite,gridgain/apache-ignite,rfqu/ignite,sk0x50/ignite,StalkXT/ignite,apache/ignite,rfqu/ignite,shurun19851206/ignite,vldpyatkov/ignite,irudyak/ignite,psadusumilli/ignite,wmz7year/ignite,agoncharuk/ignite,ascherbakoff/ignite,BiryukovVA/ignite,tkpanther/ignite,shurun19851206/ignite,xtern/ignite,andrey-kuznetsov/ignite,amirakhmedov/ignite,amirakhmedov/ignite,psadusumilli/ignite,pperalta/ignite,mcherkasov/ignite,akuznetsov-gridgain/ignite,vldpyatkov/ignite,a1vanov/ignite,pperalta/ignite,andrey-kuznetsov/ignite,kromulan/ignite,ashutakGG/incubator-ignite,vadopolski/ignite,ryanzz/ignite,kidaa/incubator-ignite,daradurvs/ignite,sk0x50/ignite,agoncharuk/ignite,afinka77/ignite,gridgain/apache-ignite,nizhikov/ignite,nivanov/ignite,SomeFire/ignite,voipp/ignite,shroman/ignite,xtern/ignite,shurun19851206/ignite,thuTom/ignite,VladimirErshov/ignite,murador/ignite,kromulan/ignite,ptupitsyn/ignite,a1vanov/ignite,SharplEr/ignite,andrey-kuznetsov/ignite,gargvish/ignite,sk0x50/ignite,arijitt/incubator-ignite,endian675/ignite,vldpyatkov/ignite,irudyak/ignite,ptupitsyn/ignite,ptupitsyn/ignite,irudyak/ignite,wmz7year/ignite,vsuslov/incubator-ignite,avinogradovgg/ignite,leveyj/ignite,StalkXT/ignite,amirakhmedov/ignite,voipp/ignite,irudyak/ignite,apache/ignite,iveselovskiy/ignite,alexzaitzev/ignite,ntikhonov/ignite,dlnufox/ignite,ryanzz/ignite,avinogradovgg/ignite,leveyj/ignite,samaitra/ignite,kromulan/ignite,leveyj/ignite,andrey-kuznetsov/ignite,daradurvs/ignite,akuznetsov-gridgain/ignite,rfqu/ignite,StalkXT/ignite,sk0x50/ignite,zzcclp/ignite,dlnufox/ignite,voipp/ignite,murador/ignite,agura/incubator-ignite,DoudTechData/ignite,alexzaitzev/ignite,svladykin/ignite,sylentprayer/ignite,voipp/ignite,sylentprayer/ignite,alexzaitzev/ignite,BiryukovVA/ignite,vsisko/incubator-ignite,endian675/ignite,wmz7year/ignite,svladykin/ignite,endian675/ignite,f7753/ignite,gargvish/ignite,kidaa/incubator-ignite,apache/ignite,psadusumilli/ignite,vsisko/incubator-ignite,NSAmelchev/ignite,vldpyatkov/ignite,apacheignite/ignite,psadusumilli/ignite,tkpanther/ignite,WilliamDo/ignite,irudyak/ignite,mcherkasov/ignite,WilliamDo/ignite,NSAmelchev/ignite,arijitt/incubator-ignite,murador/ignite,dmagda/incubator-ignite,apache/ignite,psadusumilli/ignite,agura/incubator-ignite,DoudTechData/ignite,vldpyatkov/ignite,tkpanther/ignite,voipp/ignite,zzcclp/ignite,NSAmelchev/ignite,abhishek-ch/incubator-ignite,xtern/ignite,andrey-kuznetsov/ignite,gargvish/ignite,NSAmelchev/ignite,daradurvs/ignite,vsuslov/incubator-ignite,DoudTechData/ignite,daradurvs/ignite,ascherbakoff/ignite,agura/incubator-ignite,louishust/incubator-ignite,agura/incubator-ignite,BiryukovVA/ignite,ptupitsyn/ignite,louishust/incubator-ignite,thuTom/ignite,vldpyatkov/ignite,mcherkasov/ignite,andrey-kuznetsov/ignite,voipp/ignite,vldpyatkov/ignite,abhishek-ch/incubator-ignite,dream-x/ignite,DoudTechData/ignite,vsisko/incubator-ignite,sylentprayer/ignite,ashutakGG/incubator-ignite,NSAmelchev/ignite,WilliamDo/ignite,chandresh-pancholi/ignite,akuznetsov-gridgain/ignite,adeelmahmood/ignite,apacheignite/ignite,vladisav/ignite,dmagda/incubator-ignite,nizhikov/ignite,alexzaitzev/ignite,SharplEr/ignite,a1vanov/ignite,amirakhmedov/ignite,DoudTechData/ignite,rfqu/ignite,f7753/ignite,ntikhonov/ignite,ascherbakoff/ignite,dlnufox/ignite,afinka77/ignite,shroman/ignite,svladykin/ignite,a1vanov/ignite,VladimirErshov/ignite,DoudTechData/ignite,SharplEr/ignite,voipp/ignite,adeelmahmood/ignite,pperalta/ignite,SomeFire/ignite,pperalta/ignite,vadopolski/ignite,wmz7year/ignite,gargvish/ignite,apache/ignite,xtern/ignite,zzcclp/ignite,ascherbakoff/ignite,chandresh-pancholi/ignite,vadopolski/ignite,shroman/ignite,wmz7year/ignite,andrey-kuznetsov/ignite,VladimirErshov/ignite,vadopolski/ignite,afinka77/ignite,f7753/ignite,f7753/ignite,abhishek-ch/incubator-ignite,SomeFire/ignite,sk0x50/ignite,daradurvs/ignite,iveselovskiy/ignite,dmagda/incubator-ignite,chandresh-pancholi/ignite,tkpanther/ignite,rfqu/ignite,andrey-kuznetsov/ignite,shurun19851206/ignite,leveyj/ignite,amirakhmedov/ignite,adeelmahmood/ignite,louishust/incubator-ignite,dmagda/incubator-ignite,ilantukh/ignite,tkpanther/ignite,SomeFire/ignite,apache/ignite,tkpanther/ignite,ilantukh/ignite,BiryukovVA/ignite,SharplEr/ignite,shurun19851206/ignite,samaitra/ignite,nizhikov/ignite,gridgain/apache-ignite,SomeFire/ignite,nizhikov/ignite,wmz7year/ignite,afinka77/ignite,SomeFire/ignite,NSAmelchev/ignite,BiryukovVA/ignite,vsisko/incubator-ignite,pperalta/ignite,xtern/ignite,f7753/ignite,shurun19851206/ignite,dream-x/ignite,alexzaitzev/ignite,nizhikov/ignite,agoncharuk/ignite,shroman/ignite,agura/incubator-ignite,adeelmahmood/ignite,ilantukh/ignite,mcherkasov/ignite,psadusumilli/ignite,endian675/ignite,nizhikov/ignite,agoncharuk/ignite,sk0x50/ignite,sylentprayer/ignite,psadusumilli/ignite,sk0x50/ignite,daradurvs/ignite,dlnufox/ignite,avinogradovgg/ignite,kromulan/ignite,nizhikov/ignite,DoudTechData/ignite,andrey-kuznetsov/ignite,ptupitsyn/ignite,thuTom/ignite,nivanov/ignite,samaitra/ignite,VladimirErshov/ignite,daradurvs/ignite,svladykin/ignite,chandresh-pancholi/ignite,arijitt/incubator-ignite,shroman/ignite,ascherbakoff/ignite,pperalta/ignite,WilliamDo/ignite,vsisko/incubator-ignite,iveselovskiy/ignite,gridgain/apache-ignite,pperalta/ignite,endian675/ignite,kromulan/ignite,apache/ignite,leveyj/ignite,WilliamDo/ignite,louishust/incubator-ignite,chandresh-pancholi/ignite,arijitt/incubator-ignite,StalkXT/ignite,nivanov/ignite,VladimirErshov/ignite,nizhikov/ignite,a1vanov/ignite,SharplEr/ignite,thuTom/ignite,thuTom/ignite,BiryukovVA/ignite,chandresh-pancholi/ignite,a1vanov/ignite,agoncharuk/ignite,VladimirErshov/ignite,ashutakGG/incubator-ignite,irudyak/ignite,murador/ignite,amirakhmedov/ignite,apache/ignite,thuTom/ignite,dream-x/ignite,ptupitsyn/ignite,dream-x/ignite,shroman/ignite,ilantukh/ignite,ptupitsyn/ignite,vadopolski/ignite,rfqu/ignite,a1vanov/ignite,xtern/ignite,apacheignite/ignite,leveyj/ignite,nivanov/ignite,vsuslov/incubator-ignite,samaitra/ignite,vsisko/incubator-ignite,DoudTechData/ignite,iveselovskiy/ignite,ilantukh/ignite,vladisav/ignite,a1vanov/ignite,svladykin/ignite,nizhikov/ignite,ryanzz/ignite,vladisav/ignite,svladykin/ignite,StalkXT/ignite,VladimirErshov/ignite,afinka77/ignite,ryanzz/ignite,kromulan/ignite,murador/ignite,sk0x50/ignite,ashutakGG/incubator-ignite,dream-x/ignite,afinka77/ignite,alexzaitzev/ignite,mcherkasov/ignite,vadopolski/ignite,sk0x50/ignite,shroman/ignite,apache/ignite,dream-x/ignite,SomeFire/ignite,BiryukovVA/ignite,vsuslov/incubator-ignite,avinogradovgg/ignite,agura/incubator-ignite,ntikhonov/ignite,murador/ignite,vladisav/ignite,leveyj/ignite,dmagda/incubator-ignite,daradurvs/ignite,sylentprayer/ignite,ascherbakoff/ignite,ryanzz/ignite,zzcclp/ignite,NSAmelchev/ignite,gridgain/apache-ignite,shurun19851206/ignite,NSAmelchev/ignite,amirakhmedov/ignite,daradurvs/ignite,mcherkasov/ignite,vadopolski/ignite,dlnufox/ignite,afinka77/ignite,ptupitsyn/ignite,sylentprayer/ignite,arijitt/incubator-ignite,irudyak/ignite,avinogradovgg/ignite,vsuslov/incubator-ignite,dmagda/incubator-ignite,voipp/ignite,nivanov/ignite,agoncharuk/ignite,ntikhonov/ignite,vladisav/ignite,WilliamDo/ignite,SomeFire/ignite,samaitra/ignite,shroman/ignite,wmz7year/ignite,akuznetsov-gridgain/ignite,agoncharuk/ignite,irudyak/ignite,samaitra/ignite,ntikhonov/ignite,ilantukh/ignite,pperalta/ignite,SomeFire/ignite,dmagda/incubator-ignite,murador/ignite,thuTom/ignite,apacheignite/ignite,amirakhmedov/ignite,vldpyatkov/ignite,sylentprayer/ignite,vladisav/ignite,adeelmahmood/ignite,vsisko/incubator-ignite,ashutakGG/incubator-ignite,gridgain/apache-ignite,apacheignite/ignite,ryanzz/ignite,kromulan/ignite,SharplEr/ignite,akuznetsov-gridgain/ignite,afinka77/ignite,agura/incubator-ignite,gargvish/ignite,WilliamDo/ignite,adeelmahmood/ignite,zzcclp/ignite,zzcclp/ignite,svladykin/ignite,f7753/ignite,abhishek-ch/incubator-ignite,f7753/ignite,sylentprayer/ignite,StalkXT/ignite,wmz7year/ignite,arijitt/incubator-ignite,ilantukh/ignite,f7753/ignite,vladisav/ignite,ascherbakoff/ignite,adeelmahmood/ignite,amirakhmedov/ignite,agoncharuk/ignite,nivanov/ignite,dlnufox/ignite,dream-x/ignite,apacheignite/ignite,SharplEr/ignite,StalkXT/ignite,zzcclp/ignite,SomeFire/ignite,thuTom/ignite,vladisav/ignite,endian675/ignite,ashutakGG/incubator-ignite,gargvish/ignite,apacheignite/ignite,xtern/ignite,chandresh-pancholi/ignite,ntikhonov/ignite,vadopolski/ignite,vsuslov/incubator-ignite,VladimirErshov/ignite,ilantukh/ignite,xtern/ignite,alexzaitzev/ignite,samaitra/ignite,ntikhonov/ignite,endian675/ignite,ilantukh/ignite,avinogradovgg/ignite,nivanov/ignite,mcherkasov/ignite,StalkXT/ignite,iveselovskiy/ignite,gridgain/apache-ignite,rfqu/ignite,ryanzz/ignite,louishust/incubator-ignite,shurun19851206/ignite,andrey-kuznetsov/ignite,chandresh-pancholi/ignite,samaitra/ignite,avinogradovgg/ignite,xtern/ignite,SharplEr/ignite,samaitra/ignite,dlnufox/ignite,ptupitsyn/ignite,ascherbakoff/ignite,daradurvs/ignite,rfqu/ignite,BiryukovVA/ignite,louishust/incubator-ignite,apacheignite/ignite,kidaa/incubator-ignite,endian675/ignite,tkpanther/ignite,nivanov/ignite,agura/incubator-ignite,kidaa/incubator-ignite,ntikhonov/ignite,chandresh-pancholi/ignite,psadusumilli/ignite,alexzaitzev/ignite,BiryukovVA/ignite,BiryukovVA/ignite,samaitra/ignite,dmagda/incubator-ignite,abhishek-ch/incubator-ignite,WilliamDo/ignite,ryanzz/ignite,StalkXT/ignite,ilantukh/ignite,dream-x/ignite,murador/ignite,iveselovskiy/ignite,voipp/ignite,ascherbakoff/ignite,akuznetsov-gridgain/ignite,gargvish/ignite,adeelmahmood/ignite,leveyj/ignite,mcherkasov/ignite,shroman/ignite,shroman/ignite | /* @java.file.header */
/* _________ _____ __________________ _____
* __ ____/___________(_)______ /__ ____/______ ____(_)_______
* _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \
* / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /
* \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/
*/
package org.gridgain.grid.util.portable;
import org.gridgain.grid.kernal.*;
import org.gridgain.grid.kernal.processors.rest.client.message.*;
import org.gridgain.grid.util.typedef.internal.*;
import org.gridgain.portable.*;
import org.jdk8.backport.*;
import org.jetbrains.annotations.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import static org.gridgain.grid.util.portable.GridPortableMarshaller.*;
/**
* Portable configurer.
*/
public class GridPortableContextImpl implements GridPortableContext, Externalizable {
/** */
private final ConcurrentMap<Class<?>, GridPortableClassDescriptor> descByCls = new ConcurrentHashMap8<>();
/** */
private final Map<DescriptorKey, GridPortableClassDescriptor> descById = new HashMap<>();
/** */
private final Map<Class<? extends Collection>, Byte> colTypes = new HashMap<>();
/** */
private final Map<Class<? extends Map>, Byte> mapTypes = new HashMap<>();
/** */
private final Map<Integer, GridPortableIdMapper> mappers = new HashMap<>();
/** */
private String gridName;
/**
* For {@link Externalizable}.
*/
public GridPortableContextImpl() {
// No-op.
}
/**
* @param gridName Grid name.
*/
public GridPortableContextImpl(@Nullable String gridName) {
this.gridName = gridName;
}
/**
* @param portableCfg Portable configuration.
* @return Portable context.
* @throws GridPortableException In case of error.
*/
public void configure(@Nullable GridPortableConfiguration portableCfg)
throws GridPortableException {
addDescriptor(Byte.class, BYTE);
addDescriptor(Short.class, SHORT);
addDescriptor(Integer.class, INT);
addDescriptor(Long.class, LONG);
addDescriptor(Float.class, FLOAT);
addDescriptor(Double.class, DOUBLE);
addDescriptor(Character.class, CHAR);
addDescriptor(Boolean.class, BOOLEAN);
addDescriptor(String.class, STRING);
addDescriptor(UUID.class, UUID);
addDescriptor(Date.class, DATE);
addDescriptor(byte[].class, BYTE_ARR);
addDescriptor(short[].class, SHORT_ARR);
addDescriptor(int[].class, INT_ARR);
addDescriptor(long[].class, LONG_ARR);
addDescriptor(float[].class, FLOAT_ARR);
addDescriptor(double[].class, DOUBLE_ARR);
addDescriptor(char[].class, CHAR_ARR);
addDescriptor(boolean[].class, BOOLEAN_ARR);
addDescriptor(String[].class, STRING_ARR);
addDescriptor(UUID[].class, UUID_ARR);
addDescriptor(Date[].class, DATE_ARR);
addDescriptor(Object[].class, OBJ_ARR);
addDescriptor(ArrayList.class, COL);
addDescriptor(LinkedList.class, COL);
addDescriptor(HashSet.class, COL);
addDescriptor(LinkedHashSet.class, COL);
addDescriptor(TreeSet.class, COL);
addDescriptor(ConcurrentSkipListSet.class, COL);
addDescriptor(HashMap.class, MAP);
addDescriptor(LinkedHashMap.class, MAP);
addDescriptor(TreeMap.class, MAP);
addDescriptor(ConcurrentHashMap.class, MAP);
addDescriptor(GridPortableObjectImpl.class, PORTABLE);
colTypes.put(ArrayList.class, ARR_LIST);
colTypes.put(LinkedList.class, LINKED_LIST);
colTypes.put(HashSet.class, HASH_SET);
colTypes.put(LinkedHashSet.class, LINKED_HASH_SET);
colTypes.put(TreeSet.class, TREE_SET);
colTypes.put(ConcurrentSkipListSet.class, CONC_SKIP_LIST_SET);
mapTypes.put(HashMap.class, HASH_MAP);
mapTypes.put(LinkedHashMap.class, LINKED_HASH_MAP);
mapTypes.put(TreeMap.class, TREE_MAP);
mapTypes.put(ConcurrentHashMap.class, CONC_HASH_MAP);
// TODO: Configure from server and client?
addDescriptor(GridClientAuthenticationRequest.class, 51);
addDescriptor(GridClientTopologyRequest.class, 52);
addDescriptor(GridClientTaskRequest.class, 53);
addDescriptor(GridClientCacheRequest.class, 54);
addDescriptor(GridClientLogRequest.class, 55);
addDescriptor(GridClientResponse.class, 56);
addDescriptor(GridClientNodeBean.class, 57);
addDescriptor(GridClientNodeMetricsBean.class, 58);
addDescriptor(GridClientTaskResultBean.class, 59);
if (portableCfg != null) {
GridPortableIdMapper globalIdMapper = portableCfg.getIdMapper();
GridPortableSerializer globalSerializer = portableCfg.getSerializer();
for (GridPortableTypeConfiguration typeCfg : portableCfg.getTypeConfigurations()) {
String clsName = typeCfg.getClassName();
if (clsName == null)
throw new GridPortableException("Class name is required for portable type configuration.");
Class<?> cls;
try {
cls = Class.forName(clsName);
}
catch (ClassNotFoundException e) {
throw new GridPortableException("Portable class doesn't exist: " + clsName, e);
}
GridPortableIdMapper idMapper = globalIdMapper;
GridPortableSerializer serializer = globalSerializer;
if (typeCfg.getIdMapper() != null)
idMapper = typeCfg.getIdMapper();
if (typeCfg.getSerializer() != null)
serializer = typeCfg.getSerializer();
addUserTypeDescriptor(cls, idMapper, serializer);
}
}
}
/** {@inheritDoc} */
@Nullable @Override public GridPortableClassDescriptor descriptorForClass(Class<?> cls)
throws GridPortableException {
assert cls != null;
GridPortableClassDescriptor desc = descByCls.get(cls);
if (desc == null) {
if (Collection.class.isAssignableFrom(cls))
desc = addCollectionDescriptor(cls);
else if (Map.class.isAssignableFrom(cls))
desc = addMapDescriptor(cls);
}
return desc;
}
/** {@inheritDoc} */
@Nullable @Override public GridPortableClassDescriptor descriptorForTypeId(boolean userType, int typeId) {
return descById.get(new DescriptorKey(userType, typeId));
}
/** {@inheritDoc} */
@Override public byte collectionType(Class<? extends Collection> cls) {
assert cls != null;
Byte type = colTypes.get(cls);
return type != null ? type : USER_COL;
}
/** {@inheritDoc} */
@Override public byte mapType(Class<? extends Map> cls) {
assert cls != null;
Byte type = mapTypes.get(cls);
return type != null ? type : USER_COL;
}
/** {@inheritDoc} */
@Override public int fieldId(int typeId, String fieldName) {
GridPortableIdMapper idMapper = mappers.get(typeId);
return idMapper != null ? idMapper.fieldId(typeId, fieldName) : fieldName.hashCode();
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
U.writeString(out, gridName);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
gridName = U.readString(in);
}
/**
* @return Portable context.
* @throws ObjectStreamException In case of error.
*/
protected Object readResolve() throws ObjectStreamException {
try {
GridKernal g = GridGainEx.gridx(gridName);
return g.context().portable().portableContext();
}
catch (IllegalStateException e) {
throw U.withCause(new InvalidObjectException(e.getMessage()), e);
}
}
/**
* @param cls Class.
* @throws GridPortableException In case of error.
*/
private void addDescriptor(Class<?> cls, int typeId) throws GridPortableException {
GridPortableClassDescriptor desc = new GridPortableClassDescriptor(cls, false, typeId, null, null);
descByCls.put(cls, desc);
descById.put(new DescriptorKey(false, typeId), desc);
}
/**
* @param cls Collection class.
* @return Descriptor.
* @throws GridPortableException In case of error.
*/
private GridPortableClassDescriptor addCollectionDescriptor(Class<?> cls) throws GridPortableException {
assert cls != null;
assert Collection.class.isAssignableFrom(cls);
GridPortableClassDescriptor desc = new GridPortableClassDescriptor(cls, false, COL, null, null);
descByCls.put(cls, desc);
return desc;
}
/**
* @param cls Map class.
* @return Descriptor.
* @throws GridPortableException In case of error.
*/
private GridPortableClassDescriptor addMapDescriptor(Class<?> cls) throws GridPortableException {
assert cls != null;
assert Map.class.isAssignableFrom(cls);
GridPortableClassDescriptor desc = new GridPortableClassDescriptor(cls, false, MAP, null, null);
descByCls.put(cls, desc);
return desc;
}
/**
* @param cls Class.
* @param idMapper ID mapper.
* @param serializer Serializer.
* @throws GridPortableException In case of error.
*/
public void addUserTypeDescriptor(Class<?> cls, @Nullable GridPortableIdMapper idMapper,
@Nullable GridPortableSerializer serializer) throws GridPortableException {
assert cls != null;
Integer id = null;
GridPortableId idAnn = cls.getAnnotation(GridPortableId.class);
if (idAnn != null)
id = idAnn.id();
else if (idMapper != null)
id = idMapper.typeId(cls.getName());
if (id == null)
id = cls.getSimpleName().hashCode();
GridPortableClassDescriptor desc = new GridPortableClassDescriptor(cls, true, id, idMapper, serializer);
descByCls.put(cls, desc);
descById.put(new DescriptorKey(true, id), desc);
mappers.put(id, idMapper);
}
/** */
private static class DescriptorKey {
/** */
private final boolean userType;
/** */
private final int typeId;
/**
* @param userType User type flag.
* @param typeId Type ID.
*/
private DescriptorKey(boolean userType, int typeId) {
this.userType = userType;
this.typeId = typeId;
}
@Override public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
DescriptorKey key = (DescriptorKey)other;
return userType == key.userType && typeId == key.typeId;
}
/** {@inheritDoc} */
@Override public int hashCode() {
int res = userType ? 1 : 0;
res = 31 * res + typeId;
return res;
}
}
}
| modules/core/src/main/java/org/gridgain/grid/util/portable/GridPortableContextImpl.java | /* @java.file.header */
/* _________ _____ __________________ _____
* __ ____/___________(_)______ /__ ____/______ ____(_)_______
* _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \
* / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /
* \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/
*/
package org.gridgain.grid.util.portable;
import org.gridgain.grid.kernal.*;
import org.gridgain.grid.kernal.processors.rest.client.message.*;
import org.gridgain.grid.util.typedef.internal.*;
import org.gridgain.portable.*;
import org.jdk8.backport.*;
import org.jetbrains.annotations.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import static org.gridgain.grid.util.portable.GridPortableMarshaller.*;
/**
* Portable configurer.
*/
public class GridPortableContextImpl implements GridPortableContext, Externalizable {
/** */
private final ConcurrentMap<Class<?>, GridPortableClassDescriptor> descByCls = new ConcurrentHashMap8<>();
/** */
private final Map<DescriptorKey, GridPortableClassDescriptor> descById = new HashMap<>();
/** */
private final Map<Class<? extends Collection>, Byte> colTypes = new HashMap<>();
/** */
private final Map<Class<? extends Map>, Byte> mapTypes = new HashMap<>();
/** */
private final Map<Integer, GridPortableIdMapper> mappers = new HashMap<>();
/** */
private String gridName;
/**
* For {@link Externalizable}.
*/
public GridPortableContextImpl() {
// No-op.
}
/**
* @param gridName Grid name.
*/
public GridPortableContextImpl(@Nullable String gridName) {
this.gridName = gridName;
}
/**
* @param portableCfg Portable configuration.
* @return Portable context.
* @throws GridPortableException In case of error.
*/
public void configure(@Nullable GridPortableConfiguration portableCfg)
throws GridPortableException {
addDescriptor(Byte.class, BYTE);
addDescriptor(Short.class, SHORT);
addDescriptor(Integer.class, INT);
addDescriptor(Long.class, LONG);
addDescriptor(Float.class, FLOAT);
addDescriptor(Double.class, DOUBLE);
addDescriptor(Character.class, CHAR);
addDescriptor(Boolean.class, BOOLEAN);
addDescriptor(String.class, STRING);
addDescriptor(UUID.class, UUID);
addDescriptor(Date.class, DATE);
addDescriptor(byte[].class, BYTE_ARR);
addDescriptor(short[].class, SHORT_ARR);
addDescriptor(int[].class, INT_ARR);
addDescriptor(long[].class, LONG_ARR);
addDescriptor(float[].class, FLOAT_ARR);
addDescriptor(double[].class, DOUBLE_ARR);
addDescriptor(char[].class, CHAR_ARR);
addDescriptor(boolean[].class, BOOLEAN_ARR);
addDescriptor(String[].class, STRING_ARR);
addDescriptor(UUID[].class, UUID_ARR);
addDescriptor(Date[].class, DATE_ARR);
addDescriptor(Object[].class, OBJ_ARR);
addDescriptor(ArrayList.class, COL);
addDescriptor(LinkedList.class, COL);
addDescriptor(HashSet.class, COL);
addDescriptor(LinkedHashSet.class, COL);
addDescriptor(TreeSet.class, COL);
addDescriptor(ConcurrentSkipListSet.class, COL);
addDescriptor(HashMap.class, MAP);
addDescriptor(LinkedHashMap.class, MAP);
addDescriptor(TreeMap.class, MAP);
addDescriptor(ConcurrentHashMap.class, MAP);
addDescriptor(GridPortableObjectImpl.class, PORTABLE);
colTypes.put(ArrayList.class, ARR_LIST);
colTypes.put(LinkedList.class, LINKED_LIST);
colTypes.put(HashSet.class, HASH_SET);
colTypes.put(LinkedHashSet.class, LINKED_HASH_SET);
colTypes.put(TreeSet.class, TREE_SET);
colTypes.put(ConcurrentSkipListSet.class, CONC_SKIP_LIST_SET);
mapTypes.put(HashMap.class, HASH_MAP);
mapTypes.put(LinkedHashMap.class, LINKED_HASH_MAP);
mapTypes.put(TreeMap.class, TREE_MAP);
mapTypes.put(ConcurrentHashMap.class, CONC_HASH_MAP);
// TODO: Configure from server and client?
addDescriptor(GridClientAuthenticationRequest.class, 51);
addDescriptor(GridClientTopologyRequest.class, 52);
addDescriptor(GridClientTaskRequest.class, 53);
addDescriptor(GridClientCacheRequest.class, 54);
addDescriptor(GridClientLogRequest.class, 55);
addDescriptor(GridClientResponse.class, 56);
addDescriptor(GridClientNodeBean.class, 57);
addDescriptor(GridClientNodeMetricsBean.class, 58);
addDescriptor(GridClientTaskResultBean.class, 59);
if (portableCfg != null) {
GridPortableIdMapper globalIdMapper = portableCfg.getIdMapper();
GridPortableSerializer globalSerializer = portableCfg.getSerializer();
for (GridPortableTypeConfiguration typeCfg : portableCfg.getTypeConfigurations()) {
String clsName = typeCfg.getClassName();
if (clsName == null)
throw new GridPortableException("Class name is required for portable type configuration.");
Class<?> cls;
try {
cls = Class.forName(clsName);
}
catch (ClassNotFoundException e) {
throw new GridPortableException("Portable class doesn't exist: " + clsName, e);
}
GridPortableIdMapper idMapper = globalIdMapper;
GridPortableSerializer serializer = globalSerializer;
if (typeCfg.getIdMapper() != null)
idMapper = typeCfg.getIdMapper();
if (typeCfg.getSerializer() != null)
serializer = typeCfg.getSerializer();
addUserTypeDescriptor(cls, idMapper, serializer);
}
}
}
/** {@inheritDoc} */
@Nullable @Override public GridPortableClassDescriptor descriptorForClass(Class<?> cls)
throws GridPortableException {
assert cls != null;
GridPortableClassDescriptor desc = descByCls.get(cls);
if (desc == null) {
if (Collection.class.isAssignableFrom(cls))
desc = addCollectionDescriptor(cls);
else if (Map.class.isAssignableFrom(cls))
desc = addMapDescriptor(cls);
}
return desc;
}
/** {@inheritDoc} */
@Nullable @Override public GridPortableClassDescriptor descriptorForTypeId(boolean userType, int typeId) {
return descById.get(new DescriptorKey(userType, typeId));
}
/** {@inheritDoc} */
@Override public byte collectionType(Class<? extends Collection> cls) {
assert cls != null;
Byte type = colTypes.get(cls);
return type != null ? type : USER_COL;
}
/** {@inheritDoc} */
@Override public byte mapType(Class<? extends Map> cls) {
assert cls != null;
Byte type = mapTypes.get(cls);
return type != null ? type : USER_COL;
}
/** {@inheritDoc} */
@Override public int fieldId(int typeId, String fieldName) {
GridPortableIdMapper idMapper = mappers.get(typeId);
return idMapper != null ? idMapper.fieldId(typeId, fieldName) : fieldName.hashCode();
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
U.writeString(out, gridName);
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
gridName = U.readString(in);
}
/**
* @return Portable context.
* @throws ObjectStreamException In case of error.
*/
protected Object readResolve() throws ObjectStreamException {
try {
GridKernal g = GridGainEx.gridx(gridName);
return g.context().portable().portableContext();
}
catch (IllegalStateException e) {
throw U.withCause(new InvalidObjectException(e.getMessage()), e);
}
}
/**
* @param cls Class.
* @throws GridPortableException In case of error.
*/
private void addDescriptor(Class<?> cls, int typeId) throws GridPortableException {
GridPortableClassDescriptor desc = new GridPortableClassDescriptor(cls, false, typeId, null, null);
descByCls.put(cls, desc);
descById.put(new DescriptorKey(false, typeId), desc);
}
/**
* @param cls Collection class.
* @return Descriptor.
* @throws GridPortableException In case of error.
*/
private GridPortableClassDescriptor addCollectionDescriptor(Class<?> cls) throws GridPortableException {
assert cls != null;
assert Collection.class.isAssignableFrom(cls);
GridPortableClassDescriptor desc = new GridPortableClassDescriptor(cls, false, COL, null, null);
descByCls.put(cls, desc);
return desc;
}
/**
* @param cls Map class.
* @return Descriptor.
* @throws GridPortableException In case of error.
*/
private GridPortableClassDescriptor addMapDescriptor(Class<?> cls) throws GridPortableException {
assert cls != null;
assert Map.class.isAssignableFrom(cls);
GridPortableClassDescriptor desc = new GridPortableClassDescriptor(cls, false, MAP, null, null);
descByCls.put(cls, desc);
return desc;
}
/**
* @param cls Class.
* @param idMapper ID mapper.
* @param serializer Serializer.
* @throws GridPortableException In case of error.
*/
private void addUserTypeDescriptor(Class<?> cls, @Nullable GridPortableIdMapper idMapper,
@Nullable GridPortableSerializer serializer) throws GridPortableException {
assert cls != null;
Integer id = null;
GridPortableId idAnn = cls.getAnnotation(GridPortableId.class);
if (idAnn != null)
id = idAnn.id();
else if (idMapper != null)
id = idMapper.typeId(cls.getName());
if (id == null)
id = cls.getSimpleName().hashCode();
GridPortableClassDescriptor desc = new GridPortableClassDescriptor(cls, true, id, idMapper, serializer);
descByCls.put(cls, desc);
descById.put(new DescriptorKey(true, id), desc);
mappers.put(id, idMapper);
}
/** */
private static class DescriptorKey {
/** */
private final boolean userType;
/** */
private final int typeId;
/**
* @param userType User type flag.
* @param typeId Type ID.
*/
private DescriptorKey(boolean userType, int typeId) {
this.userType = userType;
this.typeId = typeId;
}
@Override public boolean equals(Object other) {
if (this == other)
return true;
if (other == null || getClass() != other.getClass())
return false;
DescriptorKey key = (DescriptorKey)other;
return userType == key.userType && typeId == key.typeId;
}
/** {@inheritDoc} */
@Override public int hashCode() {
int res = userType ? 1 : 0;
res = 31 * res + typeId;
return res;
}
}
}
| # GG-8491 - Fixed compilation
| modules/core/src/main/java/org/gridgain/grid/util/portable/GridPortableContextImpl.java | # GG-8491 - Fixed compilation |
|
Java | apache-2.0 | d766b20d3ae28afc30d7034cd4690776d8ca2b63 | 0 | jaxzin/daytrader,jaxzin/daytrader | package org.apache.geronimo.samples.daytrader.ejb3.prims;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
@MessageDriven(name = "TradeBrokerQueue", activationConfig = {
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "TradeBrokerQueue")
})
public class TestMDB implements MessageListener {
/** Creates a new instance of TradeTestMDB */
public TestMDB() {
}
public void onMessage(Message message) {
System.out.println("TestMDB.onMessage: " + message.toString());
}
}
| modules/ejb/src/main/java/org/apache/geronimo/samples/daytrader/ejb3/prims/TestMDB.java | package org.apache.geronimo.samples.daytrader.ejb3.prims;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
@MessageDriven(name = "TradeBrokerQueue", activationConfig = {
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class TestMDB implements MessageListener {
/** Creates a new instance of TradeTestMDB */
public TestMDB() {
}
public void onMessage(Message message) {
System.out.println("TestMDB.onMessage: " + message.toString());
}
}
| Updated TestMDB to include destination of TradeBrokerQueue
git-svn-id: 52591b3751b2475bb1ae80497c335c234b34aa33@530927 13f79535-47bb-0310-9956-ffa450edef68
| modules/ejb/src/main/java/org/apache/geronimo/samples/daytrader/ejb3/prims/TestMDB.java | Updated TestMDB to include destination of TradeBrokerQueue |
|
Java | apache-2.0 | 6a9fdb9983e138ac791a2b280bb50ac49cef3c2f | 0 | tcat-tamu/db | /*******************************************************************************
* Copyright © 2007-14, All Rights Reserved.
* Texas Center for Applied Technology
* Texas A&M Engineering Experiment Station
* The Texas A&M University System
* College Station, Texas, USA 77843
*
* Use is granted only to authorized licensee.
* Proprietary information, not for redistribution.
******************************************************************************/
package edu.tamu.tcat.db.core;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverConnectionFactory;
/**
* A base class for a factory providing {@link DataSource} instances. Subclasses accept configurations as
* {@link Properties} and configure appropriate data sources.
*
* @see edu.tamu.tcat.db.provider.DataSourceProvider
*/
public abstract class AbstractDataSourceFactory
{
public final static String MAX_ACTIVE_CONNECTIONS = "Max Active Connections";
public final static String MAX_IDLE_CONNECTIONS = "Max Idle Connections";
//FIXME: a Properties is an unsafe map key because it is mutable.
protected Map<Properties, BasicDataSource> dataSources = new HashMap<>();
/**
* Get the driver for the concrete database type
* */
protected abstract Driver getDriver() throws DataSourceException;
/**
* Get the connection properties for opening the connection<br>
* This should include user, and password. It should not include database or host name
* */
protected abstract Properties getConnectionProperties(Properties parameters);
/**
* Get the connection url specifying the database driver, host/file, and database name
* */
protected abstract String getConnectionUrl(Properties parameters) throws DataSourceException;
/**
* Create a new {@link BasicDataSource} from the specified {@link DSProperties}
*/
protected synchronized BasicDataSource createDataSource(final Properties parameters) throws DataSourceException
{
BasicDataSource dataSource;
final Driver driver = getDriver();
final String connectionUrl = getConnectionUrl(parameters);
final Properties connectionProps = getConnectionProperties(parameters);
dataSource = new BasicDataSource()
{
@Override
protected ConnectionFactory createConnectionFactory() throws SQLException
{
//The loading of the driver via class-loader does not work properly in OSGI.
if (driver.acceptsURL(getUrl()))
{
if (getValidationQuery() == null)
{
setTestOnBorrow(false);
setTestOnReturn(false);
setTestWhileIdle(false);
}
ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, connectionUrl, connectionProps);
return driverConnectionFactory;
}
return super.createConnectionFactory();
}
};
// dataSource.setDriverClassLoader(Driver.class.getClassLoader());
// should be included in the connection properties and not needed
// dataSource.setUsername(key.getUsername());
// dataSource.setPassword(key.getPassword());
dataSource.setDriverClassName(driver.getClass().getName());
dataSource.setUrl(connectionUrl);
dataSource.setMaxActive(getMaxActiveConnections(parameters));
dataSource.setMaxIdle(getMaxIdleConnections(parameters));
dataSource.setMinIdle(0);
dataSource.setMinEvictableIdleTimeMillis(10000);
dataSource.setTimeBetweenEvictionRunsMillis(1000);
dataSource.setLogAbandoned(true);
dataSource.setRemoveAbandoned(true);//seconds
dataSource.setRemoveAbandonedTimeout(60);
return dataSource;
}
// expose as javax.sql.DataSource - if exposed as org.apache.commons.dbcp.BasicDataSource, clients
// of this class must import that package to link to any factory subclass
public DataSource getDataSource(Properties parameters) throws DataSourceException
{
BasicDataSource dataSource = dataSources.get(parameters);
if (dataSource == null)
{
Properties nonMutating = new Properties();
nonMutating.putAll(parameters);
dataSource = createDataSource(nonMutating);
dataSources.put(nonMutating, dataSource);
}
return dataSource;
}
/**
* Close all datasources<br>
* If the provider is a service, this should be invoked on service deregistration
* */
public void shutdown() throws DataSourceException
{
DataSourceException exception = new DataSourceException("Error closing " + getClass().getName() + "datasources");
for (BasicDataSource ds : dataSources.values())
{
try
{
ds.close();
}
catch (Exception e)
{
exception.addSuppressed(exception);
}
}
if (exception.getSuppressed().length != 0)
throw exception;
}
protected int getMaxActiveConnections(Properties parameters)
{
if(parameters.containsKey(MAX_ACTIVE_CONNECTIONS))
return Integer.parseInt(parameters.getProperty(MAX_ACTIVE_CONNECTIONS));
return 5;
}
protected int getMaxIdleConnections(Properties parameters)
{
if(parameters.containsKey(MAX_IDLE_CONNECTIONS))
return Integer.parseInt(parameters.getProperty(MAX_IDLE_CONNECTIONS));
return 5;
}
public int getNumActive(DataSource ds) throws DataSourceException
{
if(ds instanceof BasicDataSource)
return ((BasicDataSource )ds).getNumActive();
throw new DataSourceException("getNumActive not supported");
}
}
| bundles/edu.tamu.tcat.db.core/src/edu/tamu/tcat/db/core/AbstractDataSourceFactory.java | /*******************************************************************************
* Copyright © 2007-14, All Rights Reserved.
* Texas Center for Applied Technology
* Texas A&M Engineering Experiment Station
* The Texas A&M University System
* College Station, Texas, USA 77843
*
* Use is granted only to authorized licensee.
* Proprietary information, not for redistribution.
******************************************************************************/
package edu.tamu.tcat.db.core;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverConnectionFactory;
/**
* A base class for a factory providing {@link DataSource} instances. Subclasses accept configurations as
* {@link Properties} and configure appropriate data sources.
*
* @see edu.tamu.tcat.db.provider.DataSourceProvider
*/
public abstract class AbstractDataSourceFactory
{
public final static String MAX_ACTIVE_CONNECTIONS = "Max Active Connections";
public final static String MAX_IDLE_CONNECTIONS = "Max Idle Connections";
//FIXME: a Properties is an unsafe map key because it is mutable.
protected Map<Properties, BasicDataSource> dataSources = new HashMap<>();
/**
* Get the driver for the concrete database type
* */
protected abstract Driver getDriver() throws DataSourceException;
/**
* Get the connection properties for opening the connection<br>
* This should include user, and password. It should not include database or host name
* */
protected abstract Properties getConnectionProperties(Properties parameters);
/**
* Get the connection url specifying the database driver, host/file, and database name
* */
protected abstract String getConnectionUrl(Properties parameters) throws DataSourceException;
/**
* Create a new {@link BasicDataSource} from the specified {@link DSProperties}
* */
protected synchronized BasicDataSource createDataSource(final Properties parameters) throws DataSourceException
{
BasicDataSource dataSource;
final Driver driver = getDriver();
final String connectionUrl = getConnectionUrl(parameters);
final Properties connectionProps = getConnectionProperties(parameters);
dataSource = new BasicDataSource()
{
@Override
protected ConnectionFactory createConnectionFactory() throws SQLException
{
//The loading of the driver via class-loader is completely utterly broken in the super.
if (driver.acceptsURL(getUrl()))
{
if (getValidationQuery() == null)
{
setTestOnBorrow(false);
setTestOnReturn(false);
setTestWhileIdle(false);
}
ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, connectionUrl, connectionProps);
return driverConnectionFactory;
}
return super.createConnectionFactory();
}
};
// dataSource.setDriverClassLoader(Driver.class.getClassLoader());
// should be included in the connection properties and not needed
// dataSource.setUsername(key.getUsername());
// dataSource.setPassword(key.getPassword());
dataSource.setDriverClassName(driver.getClass().getName());
dataSource.setUrl(connectionUrl);
dataSource.setMaxActive(getMaxActiveConnections(parameters));
dataSource.setMaxIdle(getMaxIdleConnections(parameters));
dataSource.setMinIdle(0);
dataSource.setMinEvictableIdleTimeMillis(10000);
dataSource.setTimeBetweenEvictionRunsMillis(1000);
dataSource.setLogAbandoned(true);
dataSource.setRemoveAbandoned(true);//seconds
dataSource.setRemoveAbandonedTimeout(60);
return dataSource;
}
// expose as javax.sql.DataSource - if exposed as org.apache.commons.dbcp.BasicDataSource, clients
// of this class must import that package to link to any factory subclass
public DataSource getDataSource(Properties parameters) throws DataSourceException
{
BasicDataSource dataSource = dataSources.get(parameters);
if (dataSource == null)
{
Properties nonMutating = new Properties();
nonMutating.putAll(parameters);
dataSource = createDataSource(nonMutating);
dataSources.put(nonMutating, dataSource);
}
return dataSource;
}
/**
* Close all datasources<br>
* If the provider is a service, this should be invoked on service deregistration
* */
public void shutdown() throws DataSourceException
{
DataSourceException exception = new DataSourceException("Error closing " + getClass().getName() + "datasources");
for (BasicDataSource ds : dataSources.values())
{
try
{
ds.close();
}
catch (Exception e)
{
exception.addSuppressed(exception);
}
}
if (exception.getSuppressed().length != 0)
throw exception;
}
protected int getMaxActiveConnections(Properties parameters)
{
if(parameters.containsKey(MAX_ACTIVE_CONNECTIONS))
return Integer.parseInt(parameters.getProperty(MAX_ACTIVE_CONNECTIONS));
return 5;
}
protected int getMaxIdleConnections(Properties parameters)
{
if(parameters.containsKey(MAX_IDLE_CONNECTIONS))
return Integer.parseInt(parameters.getProperty(MAX_IDLE_CONNECTIONS));
return 5;
}
public int getNumActive(DataSource ds) throws DataSourceException
{
if(ds instanceof BasicDataSource)
return ((BasicDataSource )ds).getNumActive();
throw new DataSourceException("getNumActive not supported");
}
}
| Update comments | bundles/edu.tamu.tcat.db.core/src/edu/tamu/tcat/db/core/AbstractDataSourceFactory.java | Update comments |
|
Java | apache-2.0 | 6eebc9d5e3dd26670d56ccb5f226c14e9739b70f | 0 | ota4j-team/opentest4j | /*
* Copyright 2015-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 org.opentest4j;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* {@link MultipleFailuresError} is an {@link AssertionError} that aggregates
* multiple failures thrown in a given context (i.e., typically within the
* invocation of a single test).
*
* @author Johannes Link
* @author Sam Brannen
* @author Marc Philipp
* @since 1.0
*/
public class MultipleFailuresError extends AssertionError {
private static final long serialVersionUID = 1L;
private static final String EOL = System.getProperty("line.separator");
private final String heading;
private final List<Throwable> failures;
/**
* Constructs an {@code MultipleFailuresError} with the supplied heading and
* failures.
*
* @param heading the message heading; a default value will be used if
* {@code null} or blank
* @param failures the list of failures; must not be {@code null} or contain
* {@code null} elements
*/
public MultipleFailuresError(String heading, List<? extends Throwable> failures) {
if (failures == null) {
throw new NullPointerException("failures must not be null");
}
this.heading = isBlank(heading) ? "Multiple Failures" : heading.trim();
this.failures = new ArrayList<Throwable>();
for (Throwable failure : failures) {
if (failure == null) {
throw new NullPointerException("failures must not contain null elements");
}
this.failures.add(failure);
}
}
@Override
public String getMessage() {
int failureCount = this.failures.size();
if (failureCount == 0) {
return this.heading;
}
// @formatter:off
StringBuilder builder = new StringBuilder(this.heading)
.append(" (")
.append(failureCount).append(" ")
.append(pluralize(failureCount, "failure", "failures"))
.append(")")
.append(EOL);
// @formatter:on
int lastIndex = failureCount - 1;
for (Throwable failure : this.failures.subList(0, lastIndex)) {
builder.append("\t").append(nullSafeMessage(failure)).append(EOL);
}
builder.append('\t').append(nullSafeMessage(this.failures.get(lastIndex)));
return builder.toString();
}
/**
* Returns the list of failures contained in this error.
*/
public List<Throwable> getFailures() {
return Collections.unmodifiableList(this.failures);
}
/**
* Returns whether this error contains any failures.
*/
public boolean hasFailures() {
return !this.failures.isEmpty();
}
private static boolean isBlank(String str) {
return (str == null || str.trim().length() == 0);
}
private static String pluralize(int count, String singular, String plural) {
return count == 1 ? singular : plural;
}
private static String nullSafeMessage(Throwable failure) {
if (isBlank(failure.getMessage())) {
return failure.getClass().getName() + ": <no message>";
}
return failure.getClass().getName() + ": " + failure.getMessage();
}
}
| src/main/java/org/opentest4j/MultipleFailuresError.java | /*
* Copyright 2015-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 org.opentest4j;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* {@link MultipleFailuresError} is an {@link AssertionError} which
* aggregates multiple {@code AssertionErrors} thrown in a given context
* (i.e., typically within the invocation of a single test).
*
* @author Johannes Link
* @author Sam Brannen
* @author Marc Philipp
* @since 1.0
*/
public class MultipleFailuresError extends AssertionError {
private static final long serialVersionUID = 1L;
private static final String EOL = System.getProperty("line.separator");
private final String heading;
private final List<Throwable> failures;
public MultipleFailuresError(String heading, List<? extends Throwable> failures) {
this.heading = isBlank(heading) ? "Multiple Failures" : heading.trim();
this.failures = new ArrayList<Throwable>();
for (Throwable failure : failures) {
if (failure == null) {
throw new NullPointerException("failures must not contain null elements");
}
this.failures.add(failure);
}
}
@Override
public String getMessage() {
int failureCount = this.failures.size();
if (failureCount == 0) {
return this.heading;
}
// @formatter:off
StringBuilder builder = new StringBuilder(this.heading)
.append(" (")
.append(failureCount).append(" ")
.append(pluralize(failureCount, "failure", "failures"))
.append(")")
.append(EOL);
// @formatter:on
int lastIndex = failureCount - 1;
for (Throwable failure : this.failures.subList(0, lastIndex)) {
builder.append("\t").append(nullSafeMessage(failure)).append(EOL);
}
builder.append('\t').append(nullSafeMessage(this.failures.get(lastIndex)));
return builder.toString();
}
public List<Throwable> getFailures() {
return Collections.unmodifiableList(this.failures);
}
public boolean hasFailures() {
return !this.failures.isEmpty();
}
private static boolean isBlank(String str) {
return (str == null || str.trim().length() == 0);
}
private static String pluralize(int count, String singular, String plural) {
return count == 1 ? singular : plural;
}
private static String nullSafeMessage(Throwable failure) {
if (isBlank(failure.getMessage())) {
return failure.getClass().getName() + ": <no message>";
}
return failure.getClass().getName() + ": " + failure.getMessage();
}
}
| Polish Javadoc
| src/main/java/org/opentest4j/MultipleFailuresError.java | Polish Javadoc |
|
Java | apache-2.0 | 63e06bc37060861aabebf93723fc20318152f957 | 0 | tananaev/traccar,tsmgeek/traccar,tananaev/traccar,jssenyange/traccar,tsmgeek/traccar,orcoliver/traccar,ninioe/traccar,orcoliver/traccar,tsmgeek/traccar,jssenyange/traccar,ninioe/traccar,jssenyange/traccar,orcoliver/traccar,ninioe/traccar,tananaev/traccar | package org.traccar.protocol;
import org.junit.Test;
import org.traccar.ProtocolTest;
public class Tlt2hProtocolDecoderTest extends ProtocolTest {
@Test
public void testDecode() throws Exception {
Tlt2hProtocolDecoder decoder = new Tlt2hProtocolDecoder(null);
verifyNull(decoder, text(
"#867962040161955#MT600#0000#0#0#137#41#0#AUTO#1\r\n" +
"#00019023402$GPRMC,084702.00,A,3228.6772,S,11545.9684,E,,159.80,251018,,,A*56\r\n"));
verifyPositions(decoder, text(
"#868323028789359#MT600#0000#AUTOLOW#1\r\n",
"#07d8cd5198$GPRMC,164934.00,A,1814.4854,N,09926.0566,E,0.03,,240417,,,A*4A\r\n"));
verifyNull(decoder, text(
"#861075026000000#\r\n",
"#0000#AUTO#1\r\n",
"#002c4968045$GPRMC,001556.00,A,3542.1569,N,13938.9814,E,7.38,185.71,160417,,,A*55\r\n"));
verifyPositions(decoder, text(
"#863835026938048#MT500#0000#AUTO#1\r\n",
"#67904917c0e$GPRMC,173926.00,A,4247.8476,N,08342.6996,W,0.03,,160417,,,A*59\r\n"));
verifyPositions(decoder, text(
"#357671030108689##0000#AUTO#1\r\n",
"#13AE2F8F$GPRMC,211452.000,A,0017.378794,S,03603.441981,E,0.000,0,060216,,,A*68\r\n"));
verifyPositions(decoder, text(
"#357671030946351#V500#0000#AUTO#1\r\n",
"#$GPRMC,223835.000,A,0615.3545,S,10708.5779,E,14.62,97.41,070313,,,D*70\r\n"),
position("2013-03-07 22:38:35.000", true, -6.25591, 107.14297));
verifyPositions(decoder, text(
"\r\n#357671030946351#V500#0000#AUTO#1\r\n",
"#$GPRMC,223835.000,A,0615.3545,S,10708.5779,E,14.62,97.41,070313,,,D*70\r\n"));
verifyPositions(decoder, text(
"#357671030938911#V500#0000#AUTOSTOP#1\r\n",
"#00b34d3c$GPRMC,140026.000,A,2623.6452,S,02828.8990,E,0.00,65.44,130213,,,A*4B\r\n"));
verifyPositions(decoder, text(
"#123456789000001#V3338#0000#SMS#3\r\n",
"#25ee0dff$GPRMC,083945.180,A,2233.4249,N,11406.0046,E,0.00,315.00,251207,,,A*6E\r\n",
"#25ee0dff$GPRMC,083950.180,A,2233.4249,N,11406.0046,E,0.00,315.00,251207,,,A*6E\r\n",
"#25ee0dff$GPRMC,083955.180,A,2233.4249,N,11406.0046,E,0.00,315.00,251207,,,A*6E"));
verifyPositions(decoder, text(
"#353686009063310#353686009063310#0000#AUTO#2\r\n",
"#239757a9$GPRMC,150252.001,A,2326.6856,S,4631.8154,W,,,260513,,,A*52\r\n",
"#239757a9$GPRMC,150322.001,A,2326.6854,S,4631.8157,W,,,260513,,,A*55"));
verifyPositions(decoder, text(
"#357671031289215#V600#0000#AUTOLOW#1\r\n",
"#00735e1c$GPRMC,115647.000,A,5553.6524,N,02632.3128,E,0.00,0.0,130614,0.0,W,A*28"));
}
}
| test/org/traccar/protocol/Tlt2hProtocolDecoderTest.java | package org.traccar.protocol;
import org.junit.Test;
import org.traccar.ProtocolTest;
public class Tlt2hProtocolDecoderTest extends ProtocolTest {
@Test
public void testDecode() throws Exception {
Tlt2hProtocolDecoder decoder = new Tlt2hProtocolDecoder(null);
verifyPositions(decoder, text(
"#868323028789359#MT600#0000#AUTOLOW#1\r\n",
"#07d8cd5198$GPRMC,164934.00,A,1814.4854,N,09926.0566,E,0.03,,240417,,,A*4A\r\n"));
verifyNull(decoder, text(
"#861075026000000#\r\n",
"#0000#AUTO#1\r\n",
"#002c4968045$GPRMC,001556.00,A,3542.1569,N,13938.9814,E,7.38,185.71,160417,,,A*55\r\n"));
verifyPositions(decoder, text(
"#863835026938048#MT500#0000#AUTO#1\r\n",
"#67904917c0e$GPRMC,173926.00,A,4247.8476,N,08342.6996,W,0.03,,160417,,,A*59\r\n"));
verifyPositions(decoder, text(
"#357671030108689##0000#AUTO#1\r\n",
"#13AE2F8F$GPRMC,211452.000,A,0017.378794,S,03603.441981,E,0.000,0,060216,,,A*68\r\n"));
verifyPositions(decoder, text(
"#357671030946351#V500#0000#AUTO#1\r\n",
"#$GPRMC,223835.000,A,0615.3545,S,10708.5779,E,14.62,97.41,070313,,,D*70\r\n"),
position("2013-03-07 22:38:35.000", true, -6.25591, 107.14297));
verifyPositions(decoder, text(
"\r\n#357671030946351#V500#0000#AUTO#1\r\n",
"#$GPRMC,223835.000,A,0615.3545,S,10708.5779,E,14.62,97.41,070313,,,D*70\r\n"));
verifyPositions(decoder, text(
"#357671030938911#V500#0000#AUTOSTOP#1\r\n",
"#00b34d3c$GPRMC,140026.000,A,2623.6452,S,02828.8990,E,0.00,65.44,130213,,,A*4B\r\n"));
verifyPositions(decoder, text(
"#123456789000001#V3338#0000#SMS#3\r\n",
"#25ee0dff$GPRMC,083945.180,A,2233.4249,N,11406.0046,E,0.00,315.00,251207,,,A*6E\r\n",
"#25ee0dff$GPRMC,083950.180,A,2233.4249,N,11406.0046,E,0.00,315.00,251207,,,A*6E\r\n",
"#25ee0dff$GPRMC,083955.180,A,2233.4249,N,11406.0046,E,0.00,315.00,251207,,,A*6E"));
verifyPositions(decoder, text(
"#353686009063310#353686009063310#0000#AUTO#2\r\n",
"#239757a9$GPRMC,150252.001,A,2326.6856,S,4631.8154,W,,,260513,,,A*52\r\n",
"#239757a9$GPRMC,150322.001,A,2326.6854,S,4631.8157,W,,,260513,,,A*55"));
verifyPositions(decoder, text(
"#357671031289215#V600#0000#AUTOLOW#1\r\n",
"#00735e1c$GPRMC,115647.000,A,5553.6524,N,02632.3128,E,0.00,0.0,130614,0.0,W,A*28"));
}
}
| Add TLT2H test case
| test/org/traccar/protocol/Tlt2hProtocolDecoderTest.java | Add TLT2H test case |
|
Java | apache-2.0 | 1849b33fd7bad3f6520a92349e36cb30d51af096 | 0 | danielpetisme/generator-jhipster,hdurix/generator-jhipster,Tcharl/generator-jhipster,wmarques/generator-jhipster,danielpetisme/generator-jhipster,gmarziou/generator-jhipster,ctamisier/generator-jhipster,rkohel/generator-jhipster,atomfrede/generator-jhipster,mosoft521/generator-jhipster,ruddell/generator-jhipster,mosoft521/generator-jhipster,nkolosnjaji/generator-jhipster,jkutner/generator-jhipster,PierreBesson/generator-jhipster,atomfrede/generator-jhipster,nkolosnjaji/generator-jhipster,gzsombor/generator-jhipster,cbornet/generator-jhipster,rifatdover/generator-jhipster,jkutner/generator-jhipster,duderoot/generator-jhipster,jkutner/generator-jhipster,wmarques/generator-jhipster,ziogiugno/generator-jhipster,sohibegit/generator-jhipster,sendilkumarn/generator-jhipster,hdurix/generator-jhipster,erikkemperman/generator-jhipster,dynamicguy/generator-jhipster,gzsombor/generator-jhipster,pascalgrimaud/generator-jhipster,deepu105/generator-jhipster,gmarziou/generator-jhipster,jhipster/generator-jhipster,jhipster/generator-jhipster,cbornet/generator-jhipster,ziogiugno/generator-jhipster,sendilkumarn/generator-jhipster,ramzimaalej/generator-jhipster,vivekmore/generator-jhipster,sohibegit/generator-jhipster,dynamicguy/generator-jhipster,ramzimaalej/generator-jhipster,dynamicguy/generator-jhipster,robertmilowski/generator-jhipster,pascalgrimaud/generator-jhipster,duderoot/generator-jhipster,wmarques/generator-jhipster,liseri/generator-jhipster,mosoft521/generator-jhipster,robertmilowski/generator-jhipster,erikkemperman/generator-jhipster,gzsombor/generator-jhipster,ruddell/generator-jhipster,eosimosu/generator-jhipster,gzsombor/generator-jhipster,gzsombor/generator-jhipster,danielpetisme/generator-jhipster,jkutner/generator-jhipster,cbornet/generator-jhipster,atomfrede/generator-jhipster,deepu105/generator-jhipster,sohibegit/generator-jhipster,ziogiugno/generator-jhipster,ctamisier/generator-jhipster,wmarques/generator-jhipster,dimeros/generator-jhipster,deepu105/generator-jhipster,ruddell/generator-jhipster,ziogiugno/generator-jhipster,eosimosu/generator-jhipster,rkohel/generator-jhipster,rkohel/generator-jhipster,liseri/generator-jhipster,rifatdover/generator-jhipster,mraible/generator-jhipster,dimeros/generator-jhipster,hdurix/generator-jhipster,vivekmore/generator-jhipster,jkutner/generator-jhipster,erikkemperman/generator-jhipster,hdurix/generator-jhipster,vivekmore/generator-jhipster,liseri/generator-jhipster,Tcharl/generator-jhipster,Tcharl/generator-jhipster,duderoot/generator-jhipster,pascalgrimaud/generator-jhipster,sohibegit/generator-jhipster,Tcharl/generator-jhipster,atomfrede/generator-jhipster,ctamisier/generator-jhipster,ruddell/generator-jhipster,dimeros/generator-jhipster,robertmilowski/generator-jhipster,ziogiugno/generator-jhipster,atomfrede/generator-jhipster,rkohel/generator-jhipster,pascalgrimaud/generator-jhipster,PierreBesson/generator-jhipster,eosimosu/generator-jhipster,duderoot/generator-jhipster,mosoft521/generator-jhipster,danielpetisme/generator-jhipster,liseri/generator-jhipster,PierreBesson/generator-jhipster,danielpetisme/generator-jhipster,wmarques/generator-jhipster,eosimosu/generator-jhipster,vivekmore/generator-jhipster,PierreBesson/generator-jhipster,cbornet/generator-jhipster,duderoot/generator-jhipster,mraible/generator-jhipster,mosoft521/generator-jhipster,sohibegit/generator-jhipster,ctamisier/generator-jhipster,cbornet/generator-jhipster,robertmilowski/generator-jhipster,dimeros/generator-jhipster,gmarziou/generator-jhipster,erikkemperman/generator-jhipster,mraible/generator-jhipster,eosimosu/generator-jhipster,erikkemperman/generator-jhipster,vivekmore/generator-jhipster,ramzimaalej/generator-jhipster,jhipster/generator-jhipster,robertmilowski/generator-jhipster,rifatdover/generator-jhipster,mraible/generator-jhipster,ruddell/generator-jhipster,dimeros/generator-jhipster,sendilkumarn/generator-jhipster,ctamisier/generator-jhipster,mraible/generator-jhipster,rkohel/generator-jhipster,PierreBesson/generator-jhipster,gmarziou/generator-jhipster,deepu105/generator-jhipster,nkolosnjaji/generator-jhipster,nkolosnjaji/generator-jhipster,jhipster/generator-jhipster,liseri/generator-jhipster,pascalgrimaud/generator-jhipster,dynamicguy/generator-jhipster,jhipster/generator-jhipster,gmarziou/generator-jhipster,sendilkumarn/generator-jhipster,Tcharl/generator-jhipster,hdurix/generator-jhipster,sendilkumarn/generator-jhipster,nkolosnjaji/generator-jhipster,deepu105/generator-jhipster | <%#
Copyright 2013-2017 the original author or authors from the JHipster project.
This file is part of the JHipster project, see http://www.jhipster.tech/
for more information.
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 <%=packageName%>.web.rest;
<%_ if (databaseType === 'cassandra') { _%>
import <%=packageName%>.AbstractCassandraTest;
<%_ } _%>
import <%=packageName%>.<%= mainClass %>;
import <%=packageName%>.domain.User;
import <%=packageName%>.repository.UserRepository;
import <%=packageName%>.security.jwt.TokenProvider;
import <%=packageName%>.web.rest.vm.LoginVM;
import <%=packageName%>.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
<%_ if (databaseType === 'sql') { _%>
import org.springframework.transaction.annotation.Transactional;
<%_ } _%>
<%_ if (databaseType === 'cassandra') { _%>
import java.util.UUID;
<%_ } _%>
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.Matchers.not;
/**
* Test class for the UserJWTController REST controller.
*
* @see UserJWTController
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = <%= mainClass %>.class)
public class UserJWTControllerIntTest <% if (databaseType === 'cassandra') { %>extends AbstractCassandraTest <% } %>{
@Autowired
private TokenProvider tokenProvider;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private ExceptionTranslator exceptionTranslator;
private MockMvc mockMvc;
@Before
public void setup() {
UserJWTController userJWTController = new UserJWTController(tokenProvider, authenticationManager);
this.mockMvc = MockMvcBuilders.standaloneSetup(userJWTController)
.setControllerAdvice(exceptionTranslator)
.build();
}
@Test
<%_ if (databaseType === 'sql') { _%>
@Transactional
<%_ } _%>
public void testAuthorize() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setLogin("user-jwt-controller");
user.setEmail("[email protected]");
user.setActivated(true);
user.setPassword(passwordEncoder.encode("test"));
<%_ if (databaseType === 'sql') { _%>
userRepository.saveAndFlush(user);
<%_ } else if (databaseType === 'mongodb' || databaseType === 'cassandra') { _%>
userRepository.save(user);
<%_ } _%>
LoginVM login = new LoginVM();
login.setUsername("user-jwt-controller");
login.setPassword("test");
mockMvc.perform(post("/api/authenticate")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(login)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id_token").isString())
.andExpect(jsonPath("$.id_token").isNotEmpty())
.andExpect(header().string("Authorization", not(nullValue())))
.andExpect(header().string("Authorization", not(isEmptyString())));
}
@Test
<%_ if (databaseType === 'sql') { _%>
@Transactional
<%_ } _%>
public void testAuthorizeWithRememberMe() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setLogin("user-jwt-controller-remember-me");
user.setEmail("[email protected]");
user.setActivated(true);
user.setPassword(passwordEncoder.encode("test"));
<%_ if (databaseType === 'sql') { _%>
userRepository.saveAndFlush(user);
<%_ } else if (databaseType === 'mongodb' || databaseType === 'cassandra') { _%>
userRepository.save(user);
<%_ } _%>
LoginVM login = new LoginVM();
login.setUsername("user-jwt-controller-remember-me");
login.setPassword("test");
login.setRememberMe(true);
mockMvc.perform(post("/api/authenticate")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(login)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id_token").isString())
.andExpect(jsonPath("$.id_token").isNotEmpty())
.andExpect(header().string("Authorization", not(nullValue())))
.andExpect(header().string("Authorization", not(isEmptyString())));
}
@Test
<%_ if (databaseType === 'sql') { _%>
@Transactional
<%_ } _%>
public void testAuthorizeFails() throws Exception {
LoginVM login = new LoginVM();
login.setUsername("wrong-user");
login.setPassword("wrong password");
mockMvc.perform(post("/api/authenticate")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(login)))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.id_token").doesNotExist())
.andExpect(header().doesNotExist("Authorization"));
}
}
| generators/server/templates/src/test/java/package/web/rest/_UserJWTControllerIntTest.java | <%#
Copyright 2013-2017 the original author or authors from the JHipster project.
This file is part of the JHipster project, see http://www.jhipster.tech/
for more information.
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 <%=packageName%>.web.rest;
<%_ if (databaseType === 'cassandra') { _%>
import <%=packageName%>.AbstractCassandraTest;
<%_ } _%>
import <%=packageName%>.<%= mainClass %>;
import <%=packageName%>.domain.User;
import <%=packageName%>.repository.UserRepository;
import <%=packageName%>.security.jwt.TokenProvider;
import <%=packageName%>.web.rest.vm.LoginVM;
import <%=packageName%>.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
<%_ if (databaseType === 'sql') { _%>
import org.springframework.transaction.annotation.Transactional;
<%_ } _%>
<%_ if (databaseType === 'cassandra') { _%>
import java.util.UUID;
<%_ } _%>
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Test class for the UserJWTController REST controller.
*
* @see UserJWTController
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = <%= mainClass %>.class)
public class UserJWTControllerIntTest <% if (databaseType === 'cassandra') { %>extends AbstractCassandraTest <% } %>{
@Autowired
private TokenProvider tokenProvider;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private ExceptionTranslator exceptionTranslator;
private MockMvc mockMvc;
@Before
public void setup() {
UserJWTController userJWTController = new UserJWTController(tokenProvider, authenticationManager);
this.mockMvc = MockMvcBuilders.standaloneSetup(userJWTController)
.setControllerAdvice(exceptionTranslator)
.build();
}
@Test
<%_ if (databaseType === 'sql') { _%>
@Transactional
<%_ } _%>
public void testAuthorize() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setLogin("user-jwt-controller");
user.setEmail("[email protected]");
user.setActivated(true);
user.setPassword(passwordEncoder.encode("test"));
<%_ if (databaseType === 'sql') { _%>
userRepository.saveAndFlush(user);
<%_ } else if (databaseType === 'mongodb' || databaseType === 'cassandra') { _%>
userRepository.save(user);
<%_ } _%>
LoginVM login = new LoginVM();
login.setUsername("user-jwt-controller");
login.setPassword("test");
mockMvc.perform(post("/api/authenticate")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(login)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id_token").isString())
.andExpect(jsonPath("$.id_token").isNotEmpty());
}
@Test
<%_ if (databaseType === 'sql') { _%>
@Transactional
<%_ } _%>
public void testAuthorizeWithRememberMe() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setLogin("user-jwt-controller-remember-me");
user.setEmail("[email protected]");
user.setActivated(true);
user.setPassword(passwordEncoder.encode("test"));
<%_ if (databaseType === 'sql') { _%>
userRepository.saveAndFlush(user);
<%_ } else if (databaseType === 'mongodb' || databaseType === 'cassandra') { _%>
userRepository.save(user);
<%_ } _%>
LoginVM login = new LoginVM();
login.setUsername("user-jwt-controller-remember-me");
login.setPassword("test");
login.setRememberMe(true);
mockMvc.perform(post("/api/authenticate")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(login)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id_token").isString())
.andExpect(jsonPath("$.id_token").isNotEmpty());
}
@Test
<%_ if (databaseType === 'sql') { _%>
@Transactional
<%_ } _%>
public void testAuthorizeFails() throws Exception {
LoginVM login = new LoginVM();
login.setUsername("wrong-user");
login.setPassword("wrong password");
mockMvc.perform(post("/api/authenticate")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(login)))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.id_token").doesNotExist());
}
}
| check Authorization header presence in UserJWTControllerIntTest
| generators/server/templates/src/test/java/package/web/rest/_UserJWTControllerIntTest.java | check Authorization header presence in UserJWTControllerIntTest |
|
Java | apache-2.0 | 616d0c044fbc886c8ba3d4ddb5e055b4a5127af6 | 0 | schonfeld/elasticsearch,ESamir/elasticsearch,Siddartha07/elasticsearch,jchampion/elasticsearch,weipinghe/elasticsearch,vingupta3/elasticsearch,F0lha/elasticsearch,pablocastro/elasticsearch,bestwpw/elasticsearch,F0lha/elasticsearch,fooljohnny/elasticsearch,pablocastro/elasticsearch,gfyoung/elasticsearch,iamjakob/elasticsearch,bestwpw/elasticsearch,wimvds/elasticsearch,overcome/elasticsearch,mjhennig/elasticsearch,hechunwen/elasticsearch,JervyShi/elasticsearch,lchennup/elasticsearch,Kakakakakku/elasticsearch,hechunwen/elasticsearch,hanswang/elasticsearch,kalimatas/elasticsearch,caengcjd/elasticsearch,episerver/elasticsearch,knight1128/elasticsearch,Shepard1212/elasticsearch,kubum/elasticsearch,mcku/elasticsearch,andrestc/elasticsearch,himanshuag/elasticsearch,sarwarbhuiyan/elasticsearch,rajanm/elasticsearch,winstonewert/elasticsearch,HonzaKral/elasticsearch,jango2015/elasticsearch,ydsakyclguozi/elasticsearch,springning/elasticsearch,iantruslove/elasticsearch,sposam/elasticsearch,xuzha/elasticsearch,fernandozhu/elasticsearch,sauravmondallive/elasticsearch,GlenRSmith/elasticsearch,hydro2k/elasticsearch,YosuaMichael/elasticsearch,Widen/elasticsearch,cwurm/elasticsearch,mm0/elasticsearch,ricardocerq/elasticsearch,jpountz/elasticsearch,iamjakob/elasticsearch,palecur/elasticsearch,codebunt/elasticsearch,jimczi/elasticsearch,truemped/elasticsearch,geidies/elasticsearch,MisterAndersen/elasticsearch,tebriel/elasticsearch,snikch/elasticsearch,andrestc/elasticsearch,nazarewk/elasticsearch,clintongormley/elasticsearch,kkirsche/elasticsearch,lydonchandra/elasticsearch,himanshuag/elasticsearch,mnylen/elasticsearch,tahaemin/elasticsearch,nilabhsagar/elasticsearch,wittyameta/elasticsearch,ricardocerq/elasticsearch,glefloch/elasticsearch,jango2015/elasticsearch,sauravmondallive/elasticsearch,winstonewert/elasticsearch,geidies/elasticsearch,MisterAndersen/elasticsearch,iantruslove/elasticsearch,mgalushka/elasticsearch,zkidkid/elasticsearch,wenpos/elasticsearch,zhiqinghuang/elasticsearch,coding0011/elasticsearch,PhaedrusTheGreek/elasticsearch,rmuir/elasticsearch,strapdata/elassandra-test,yuy168/elasticsearch,loconsolutions/elasticsearch,knight1128/elasticsearch,ouyangkongtong/elasticsearch,myelin/elasticsearch,elasticdog/elasticsearch,Kakakakakku/elasticsearch,mcku/elasticsearch,StefanGor/elasticsearch,hanswang/elasticsearch,EasonYi/elasticsearch,KimTaehee/elasticsearch,socialrank/elasticsearch,javachengwc/elasticsearch,cwurm/elasticsearch,loconsolutions/elasticsearch,gingerwizard/elasticsearch,jango2015/elasticsearch,snikch/elasticsearch,markwalkom/elasticsearch,karthikjaps/elasticsearch,tebriel/elasticsearch,JackyMai/elasticsearch,gingerwizard/elasticsearch,tkssharma/elasticsearch,mohit/elasticsearch,Widen/elasticsearch,adrianbk/elasticsearch,avikurapati/elasticsearch,kimimj/elasticsearch,jbertouch/elasticsearch,amaliujia/elasticsearch,springning/elasticsearch,brandonkearby/elasticsearch,trangvh/elasticsearch,zkidkid/elasticsearch,yynil/elasticsearch,kunallimaye/elasticsearch,yuy168/elasticsearch,javachengwc/elasticsearch,mmaracic/elasticsearch,wayeast/elasticsearch,LewayneNaidoo/elasticsearch,lchennup/elasticsearch,pritishppai/elasticsearch,kenshin233/elasticsearch,mute/elasticsearch,anti-social/elasticsearch,weipinghe/elasticsearch,LewayneNaidoo/elasticsearch,tahaemin/elasticsearch,andrestc/elasticsearch,javachengwc/elasticsearch,dpursehouse/elasticsearch,i-am-Nathan/elasticsearch,koxa29/elasticsearch,golubev/elasticsearch,Liziyao/elasticsearch,jeteve/elasticsearch,henakamaMSFT/elasticsearch,wittyameta/elasticsearch,overcome/elasticsearch,sdauletau/elasticsearch,polyfractal/elasticsearch,wbowling/elasticsearch,Shepard1212/elasticsearch,achow/elasticsearch,acchen97/elasticsearch,kunallimaye/elasticsearch,himanshuag/elasticsearch,AshishThakur/elasticsearch,rmuir/elasticsearch,jango2015/elasticsearch,shreejay/elasticsearch,strapdata/elassandra,elancom/elasticsearch,AshishThakur/elasticsearch,karthikjaps/elasticsearch,PhaedrusTheGreek/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,masaruh/elasticsearch,loconsolutions/elasticsearch,sdauletau/elasticsearch,ulkas/elasticsearch,strapdata/elassandra-test,LewayneNaidoo/elasticsearch,ivansun1010/elasticsearch,kalimatas/elasticsearch,chirilo/elasticsearch,nazarewk/elasticsearch,jprante/elasticsearch,pranavraman/elasticsearch,gingerwizard/elasticsearch,yynil/elasticsearch,Rygbee/elasticsearch,awislowski/elasticsearch,lchennup/elasticsearch,kunallimaye/elasticsearch,maddin2016/elasticsearch,lks21c/elasticsearch,andrejserafim/elasticsearch,jaynblue/elasticsearch,linglaiyao1314/elasticsearch,kubum/elasticsearch,schonfeld/elasticsearch,onegambler/elasticsearch,ydsakyclguozi/elasticsearch,Uiho/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,weipinghe/elasticsearch,gingerwizard/elasticsearch,alexkuk/elasticsearch,kkirsche/elasticsearch,i-am-Nathan/elasticsearch,zhiqinghuang/elasticsearch,mnylen/elasticsearch,Siddartha07/elasticsearch,ricardocerq/elasticsearch,alexshadow007/elasticsearch,LeoYao/elasticsearch,kalimatas/elasticsearch,gmarz/elasticsearch,alexbrasetvik/elasticsearch,GlenRSmith/elasticsearch,bestwpw/elasticsearch,mm0/elasticsearch,jw0201/elastic,nrkkalyan/elasticsearch,ouyangkongtong/elasticsearch,javachengwc/elasticsearch,wbowling/elasticsearch,Fsero/elasticsearch,girirajsharma/elasticsearch,Clairebi/ElasticsearchClone,humandb/elasticsearch,jprante/elasticsearch,MjAbuz/elasticsearch,kalburgimanjunath/elasticsearch,andrejserafim/elasticsearch,yynil/elasticsearch,jeteve/elasticsearch,milodky/elasticsearch,golubev/elasticsearch,bawse/elasticsearch,rlugojr/elasticsearch,artnowo/elasticsearch,yanjunh/elasticsearch,avikurapati/elasticsearch,rento19962/elasticsearch,YosuaMichael/elasticsearch,awislowski/elasticsearch,kimimj/elasticsearch,vroyer/elassandra,gingerwizard/elasticsearch,Brijeshrpatel9/elasticsearch,trangvh/elasticsearch,Chhunlong/elasticsearch,tahaemin/elasticsearch,knight1128/elasticsearch,IanvsPoplicola/elasticsearch,pritishppai/elasticsearch,AndreKR/elasticsearch,szroland/elasticsearch,s1monw/elasticsearch,iamjakob/elasticsearch,vingupta3/elasticsearch,fekaputra/elasticsearch,strapdata/elassandra,linglaiyao1314/elasticsearch,codebunt/elasticsearch,jw0201/elastic,amaliujia/elasticsearch,acchen97/elasticsearch,lightslife/elasticsearch,amit-shar/elasticsearch,coding0011/elasticsearch,mnylen/elasticsearch,amaliujia/elasticsearch,lks21c/elasticsearch,nellicus/elasticsearch,iacdingping/elasticsearch,HarishAtGitHub/elasticsearch,beiske/elasticsearch,mrorii/elasticsearch,xingguang2013/elasticsearch,ckclark/elasticsearch,uschindler/elasticsearch,lmtwga/elasticsearch,szroland/elasticsearch,LeoYao/elasticsearch,rmuir/elasticsearch,Helen-Zhao/elasticsearch,Flipkart/elasticsearch,fekaputra/elasticsearch,zeroctu/elasticsearch,wittyameta/elasticsearch,linglaiyao1314/elasticsearch,markllama/elasticsearch,rento19962/elasticsearch,maddin2016/elasticsearch,EasonYi/elasticsearch,TonyChai24/ESSource,vvcephei/elasticsearch,springning/elasticsearch,shreejay/elasticsearch,rhoml/elasticsearch,scottsom/elasticsearch,dongjoon-hyun/elasticsearch,sreeramjayan/elasticsearch,tahaemin/elasticsearch,iamjakob/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,jaynblue/elasticsearch,C-Bish/elasticsearch,sauravmondallive/elasticsearch,lightslife/elasticsearch,ESamir/elasticsearch,Siddartha07/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,Brijeshrpatel9/elasticsearch,ThalaivaStars/OrgRepo1,mute/elasticsearch,vrkansagara/elasticsearch,yongminxia/elasticsearch,sjohnr/elasticsearch,sneivandt/elasticsearch,MisterAndersen/elasticsearch,abibell/elasticsearch,yanjunh/elasticsearch,jimhooker2002/elasticsearch,rlugojr/elasticsearch,vroyer/elasticassandra,SergVro/elasticsearch,lmtwga/elasticsearch,jprante/elasticsearch,sposam/elasticsearch,hafkensite/elasticsearch,nazarewk/elasticsearch,rento19962/elasticsearch,zhiqinghuang/elasticsearch,aglne/elasticsearch,henakamaMSFT/elasticsearch,thecocce/elasticsearch,kunallimaye/elasticsearch,mkis-/elasticsearch,F0lha/elasticsearch,s1monw/elasticsearch,adrianbk/elasticsearch,camilojd/elasticsearch,diendt/elasticsearch,yuy168/elasticsearch,kalburgimanjunath/elasticsearch,Flipkart/elasticsearch,mbrukman/elasticsearch,MaineC/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,jimhooker2002/elasticsearch,zhiqinghuang/elasticsearch,umeshdangat/elasticsearch,ouyangkongtong/elasticsearch,SergVro/elasticsearch,rajanm/elasticsearch,JSCooke/elasticsearch,Kakakakakku/elasticsearch,hafkensite/elasticsearch,hanswang/elasticsearch,iacdingping/elasticsearch,NBSW/elasticsearch,hanswang/elasticsearch,rhoml/elasticsearch,Uiho/elasticsearch,hanst/elasticsearch,Shekharrajak/elasticsearch,Clairebi/ElasticsearchClone,MetSystem/elasticsearch,kevinkluge/elasticsearch,a2lin/elasticsearch,hanswang/elasticsearch,liweinan0423/elasticsearch,Rygbee/elasticsearch,drewr/elasticsearch,vroyer/elassandra,drewr/elasticsearch,kaneshin/elasticsearch,kimimj/elasticsearch,jeteve/elasticsearch,wangtuo/elasticsearch,cnfire/elasticsearch-1,snikch/elasticsearch,truemped/elasticsearch,maddin2016/elasticsearch,kenshin233/elasticsearch,ThalaivaStars/OrgRepo1,sjohnr/elasticsearch,xingguang2013/elasticsearch,fforbeck/elasticsearch,milodky/elasticsearch,NBSW/elasticsearch,Clairebi/ElasticsearchClone,pozhidaevak/elasticsearch,aglne/elasticsearch,ThalaivaStars/OrgRepo1,mjhennig/elasticsearch,wenpos/elasticsearch,btiernay/elasticsearch,sc0ttkclark/elasticsearch,camilojd/elasticsearch,cnfire/elasticsearch-1,sc0ttkclark/elasticsearch,wuranbo/elasticsearch,clintongormley/elasticsearch,ImpressTV/elasticsearch,obourgain/elasticsearch,hanst/elasticsearch,wangyuxue/elasticsearch,vingupta3/elasticsearch,pritishppai/elasticsearch,Ansh90/elasticsearch,mbrukman/elasticsearch,javachengwc/elasticsearch,jaynblue/elasticsearch,cwurm/elasticsearch,sposam/elasticsearch,franklanganke/elasticsearch,alexshadow007/elasticsearch,djschny/elasticsearch,tkssharma/elasticsearch,mgalushka/elasticsearch,lchennup/elasticsearch,elancom/elasticsearch,khiraiwa/elasticsearch,yongminxia/elasticsearch,humandb/elasticsearch,pritishppai/elasticsearch,sarwarbhuiyan/elasticsearch,dylan8902/elasticsearch,markharwood/elasticsearch,pozhidaevak/elasticsearch,nilabhsagar/elasticsearch,diendt/elasticsearch,henakamaMSFT/elasticsearch,masterweb121/elasticsearch,thecocce/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,Clairebi/ElasticsearchClone,overcome/elasticsearch,jw0201/elastic,jimhooker2002/elasticsearch,wuranbo/elasticsearch,ulkas/elasticsearch,uschindler/elasticsearch,AndreKR/elasticsearch,artnowo/elasticsearch,truemped/elasticsearch,camilojd/elasticsearch,likaiwalkman/elasticsearch,SergVro/elasticsearch,queirozfcom/elasticsearch,zhiqinghuang/elasticsearch,hafkensite/elasticsearch,Helen-Zhao/elasticsearch,vietlq/elasticsearch,truemped/elasticsearch,JackyMai/elasticsearch,gmarz/elasticsearch,zhiqinghuang/elasticsearch,mm0/elasticsearch,milodky/elasticsearch,ulkas/elasticsearch,fforbeck/elasticsearch,strapdata/elassandra,nazarewk/elasticsearch,jaynblue/elasticsearch,lightslife/elasticsearch,queirozfcom/elasticsearch,HarishAtGitHub/elasticsearch,nknize/elasticsearch,jchampion/elasticsearch,18098924759/elasticsearch,nrkkalyan/elasticsearch,JackyMai/elasticsearch,HarishAtGitHub/elasticsearch,gingerwizard/elasticsearch,feiqitian/elasticsearch,Uiho/elasticsearch,qwerty4030/elasticsearch,jbertouch/elasticsearch,mnylen/elasticsearch,fred84/elasticsearch,umeshdangat/elasticsearch,wayeast/elasticsearch,Flipkart/elasticsearch,dylan8902/elasticsearch,areek/elasticsearch,ulkas/elasticsearch,hanst/elasticsearch,thecocce/elasticsearch,TonyChai24/ESSource,liweinan0423/elasticsearch,hanswang/elasticsearch,lks21c/elasticsearch,weipinghe/elasticsearch,wimvds/elasticsearch,umeshdangat/elasticsearch,polyfractal/elasticsearch,kenshin233/elasticsearch,kaneshin/elasticsearch,cnfire/elasticsearch-1,StefanGor/elasticsearch,kaneshin/elasticsearch,zeroctu/elasticsearch,Liziyao/elasticsearch,dataduke/elasticsearch,bawse/elasticsearch,mcku/elasticsearch,MjAbuz/elasticsearch,jchampion/elasticsearch,springning/elasticsearch,smflorentino/elasticsearch,vietlq/elasticsearch,apepper/elasticsearch,brandonkearby/elasticsearch,abibell/elasticsearch,iamjakob/elasticsearch,Fsero/elasticsearch,clintongormley/elasticsearch,jprante/elasticsearch,kingaj/elasticsearch,Collaborne/elasticsearch,sdauletau/elasticsearch,huanzhong/elasticsearch,MjAbuz/elasticsearch,jeteve/elasticsearch,petabytedata/elasticsearch,apepper/elasticsearch,cnfire/elasticsearch-1,gingerwizard/elasticsearch,zeroctu/elasticsearch,cwurm/elasticsearch,Chhunlong/elasticsearch,xuzha/elasticsearch,markllama/elasticsearch,lydonchandra/elasticsearch,elancom/elasticsearch,smflorentino/elasticsearch,koxa29/elasticsearch,C-Bish/elasticsearch,18098924759/elasticsearch,kevinkluge/elasticsearch,wenpos/elasticsearch,Stacey-Gammon/elasticsearch,njlawton/elasticsearch,glefloch/elasticsearch,slavau/elasticsearch,vrkansagara/elasticsearch,aglne/elasticsearch,StefanGor/elasticsearch,lzo/elasticsearch-1,zeroctu/elasticsearch,robin13/elasticsearch,ivansun1010/elasticsearch,vrkansagara/elasticsearch,glefloch/elasticsearch,Widen/elasticsearch,tsohil/elasticsearch,weipinghe/elasticsearch,njlawton/elasticsearch,sdauletau/elasticsearch,18098924759/elasticsearch,xuzha/elasticsearch,geidies/elasticsearch,KimTaehee/elasticsearch,queirozfcom/elasticsearch,nknize/elasticsearch,dataduke/elasticsearch,anti-social/elasticsearch,IanvsPoplicola/elasticsearch,TonyChai24/ESSource,sposam/elasticsearch,lydonchandra/elasticsearch,jimczi/elasticsearch,vrkansagara/elasticsearch,slavau/elasticsearch,franklanganke/elasticsearch,franklanganke/elasticsearch,scorpionvicky/elasticsearch,18098924759/elasticsearch,TonyChai24/ESSource,lmtwga/elasticsearch,obourgain/elasticsearch,luiseduardohdbackup/elasticsearch,rajanm/elasticsearch,lmtwga/elasticsearch,HonzaKral/elasticsearch,humandb/elasticsearch,hydro2k/elasticsearch,martinstuga/elasticsearch,fooljohnny/elasticsearch,gmarz/elasticsearch,khiraiwa/elasticsearch,vroyer/elasticassandra,nomoa/elasticsearch,amit-shar/elasticsearch,sc0ttkclark/elasticsearch,strapdata/elassandra5-rc,vingupta3/elasticsearch,mikemccand/elasticsearch,elancom/elasticsearch,lks21c/elasticsearch,chirilo/elasticsearch,franklanganke/elasticsearch,Chhunlong/elasticsearch,winstonewert/elasticsearch,MetSystem/elasticsearch,jsgao0/elasticsearch,bestwpw/elasticsearch,sarwarbhuiyan/elasticsearch,mkis-/elasticsearch,ulkas/elasticsearch,koxa29/elasticsearch,loconsolutions/elasticsearch,anti-social/elasticsearch,martinstuga/elasticsearch,Kakakakakku/elasticsearch,himanshuag/elasticsearch,girirajsharma/elasticsearch,kkirsche/elasticsearch,yanjunh/elasticsearch,scottsom/elasticsearch,ThiagoGarciaAlves/elasticsearch,Chhunlong/elasticsearch,jimczi/elasticsearch,scottsom/elasticsearch,milodky/elasticsearch,yynil/elasticsearch,Rygbee/elasticsearch,truemped/elasticsearch,PhaedrusTheGreek/elasticsearch,apepper/elasticsearch,ESamir/elasticsearch,JervyShi/elasticsearch,ckclark/elasticsearch,kcompher/elasticsearch,mjhennig/elasticsearch,trangvh/elasticsearch,iacdingping/elasticsearch,mgalushka/elasticsearch,s1monw/elasticsearch,skearns64/elasticsearch,mmaracic/elasticsearch,dpursehouse/elasticsearch,lmtwga/elasticsearch,wimvds/elasticsearch,zkidkid/elasticsearch,gmarz/elasticsearch,masterweb121/elasticsearch,Widen/elasticsearch,mohit/elasticsearch,JervyShi/elasticsearch,kalburgimanjunath/elasticsearch,Chhunlong/elasticsearch,overcome/elasticsearch,mortonsykes/elasticsearch,humandb/elasticsearch,Shekharrajak/elasticsearch,njlawton/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,feiqitian/elasticsearch,beiske/elasticsearch,overcome/elasticsearch,khiraiwa/elasticsearch,EasonYi/elasticsearch,NBSW/elasticsearch,KimTaehee/elasticsearch,pozhidaevak/elasticsearch,btiernay/elasticsearch,MetSystem/elasticsearch,codebunt/elasticsearch,zhiqinghuang/elasticsearch,slavau/elasticsearch,Shekharrajak/elasticsearch,alexshadow007/elasticsearch,weipinghe/elasticsearch,MetSystem/elasticsearch,glefloch/elasticsearch,KimTaehee/elasticsearch,yuy168/elasticsearch,AndreKR/elasticsearch,girirajsharma/elasticsearch,pablocastro/elasticsearch,LeoYao/elasticsearch,SergVro/elasticsearch,karthikjaps/elasticsearch,sarwarbhuiyan/elasticsearch,spiegela/elasticsearch,mcku/elasticsearch,yongminxia/elasticsearch,gfyoung/elasticsearch,achow/elasticsearch,amaliujia/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,Helen-Zhao/elasticsearch,wangtuo/elasticsearch,sreeramjayan/elasticsearch,avikurapati/elasticsearch,IanvsPoplicola/elasticsearch,likaiwalkman/elasticsearch,martinstuga/elasticsearch,hirdesh2008/elasticsearch,acchen97/elasticsearch,vingupta3/elasticsearch,masaruh/elasticsearch,bawse/elasticsearch,ydsakyclguozi/elasticsearch,tebriel/elasticsearch,queirozfcom/elasticsearch,kubum/elasticsearch,mcku/elasticsearch,lzo/elasticsearch-1,JervyShi/elasticsearch,xingguang2013/elasticsearch,scorpionvicky/elasticsearch,ckclark/elasticsearch,knight1128/elasticsearch,rento19962/elasticsearch,sreeramjayan/elasticsearch,schonfeld/elasticsearch,iacdingping/elasticsearch,Rygbee/elasticsearch,karthikjaps/elasticsearch,diendt/elasticsearch,petabytedata/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,Collaborne/elasticsearch,a2lin/elasticsearch,jpountz/elasticsearch,fred84/elasticsearch,likaiwalkman/elasticsearch,vietlq/elasticsearch,vrkansagara/elasticsearch,spiegela/elasticsearch,hafkensite/elasticsearch,maddin2016/elasticsearch,JackyMai/elasticsearch,ivansun1010/elasticsearch,amit-shar/elasticsearch,xpandan/elasticsearch,mjason3/elasticsearch,Asimov4/elasticsearch,kalburgimanjunath/elasticsearch,StefanGor/elasticsearch,nrkkalyan/elasticsearch,likaiwalkman/elasticsearch,kunallimaye/elasticsearch,andrejserafim/elasticsearch,alexshadow007/elasticsearch,spiegela/elasticsearch,acchen97/elasticsearch,lightslife/elasticsearch,sneivandt/elasticsearch,mkis-/elasticsearch,mkis-/elasticsearch,nknize/elasticsearch,bawse/elasticsearch,fooljohnny/elasticsearch,jango2015/elasticsearch,javachengwc/elasticsearch,rlugojr/elasticsearch,geidies/elasticsearch,djschny/elasticsearch,sjohnr/elasticsearch,jbertouch/elasticsearch,AndreKR/elasticsearch,mjason3/elasticsearch,uschindler/elasticsearch,amit-shar/elasticsearch,Widen/elasticsearch,lightslife/elasticsearch,girirajsharma/elasticsearch,nazarewk/elasticsearch,amit-shar/elasticsearch,yongminxia/elasticsearch,strapdata/elassandra5-rc,rhoml/elasticsearch,hirdesh2008/elasticsearch,polyfractal/elasticsearch,TonyChai24/ESSource,easonC/elasticsearch,girirajsharma/elasticsearch,naveenhooda2000/elasticsearch,lydonchandra/elasticsearch,ThiagoGarciaAlves/elasticsearch,kevinkluge/elasticsearch,LewayneNaidoo/elasticsearch,JSCooke/elasticsearch,iacdingping/elasticsearch,mm0/elasticsearch,phani546/elasticsearch,schonfeld/elasticsearch,girirajsharma/elasticsearch,i-am-Nathan/elasticsearch,sjohnr/elasticsearch,kimimj/elasticsearch,ckclark/elasticsearch,vroyer/elasticassandra,vietlq/elasticsearch,Rygbee/elasticsearch,kubum/elasticsearch,djschny/elasticsearch,alexkuk/elasticsearch,Asimov4/elasticsearch,Charlesdong/elasticsearch,kenshin233/elasticsearch,elancom/elasticsearch,thecocce/elasticsearch,awislowski/elasticsearch,nrkkalyan/elasticsearch,koxa29/elasticsearch,dylan8902/elasticsearch,LeoYao/elasticsearch,jpountz/elasticsearch,elancom/elasticsearch,andrestc/elasticsearch,sdauletau/elasticsearch,tsohil/elasticsearch,mikemccand/elasticsearch,kaneshin/elasticsearch,fred84/elasticsearch,markharwood/elasticsearch,Clairebi/ElasticsearchClone,jchampion/elasticsearch,ZTE-PaaS/elasticsearch,rhoml/elasticsearch,myelin/elasticsearch,apepper/elasticsearch,iantruslove/elasticsearch,TonyChai24/ESSource,andrestc/elasticsearch,rento19962/elasticsearch,wbowling/elasticsearch,davidvgalbraith/elasticsearch,fekaputra/elasticsearch,AshishThakur/elasticsearch,mjhennig/elasticsearch,mapr/elasticsearch,likaiwalkman/elasticsearch,infusionsoft/elasticsearch,Fsero/elasticsearch,wangyuxue/elasticsearch,wangtuo/elasticsearch,vingupta3/elasticsearch,btiernay/elasticsearch,markwalkom/elasticsearch,spiegela/elasticsearch,MaineC/elasticsearch,Liziyao/elasticsearch,nomoa/elasticsearch,wayeast/elasticsearch,hafkensite/elasticsearch,jsgao0/elasticsearch,jaynblue/elasticsearch,nezirus/elasticsearch,skearns64/elasticsearch,kimimj/elasticsearch,kcompher/elasticsearch,kingaj/elasticsearch,wittyameta/elasticsearch,mm0/elasticsearch,uschindler/elasticsearch,amit-shar/elasticsearch,djschny/elasticsearch,MichaelLiZhou/elasticsearch,jimhooker2002/elasticsearch,vietlq/elasticsearch,strapdata/elassandra5-rc,jeteve/elasticsearch,markllama/elasticsearch,kkirsche/elasticsearch,coding0011/elasticsearch,wittyameta/elasticsearch,wimvds/elasticsearch,linglaiyao1314/elasticsearch,episerver/elasticsearch,huanzhong/elasticsearch,Helen-Zhao/elasticsearch,mohit/elasticsearch,adrianbk/elasticsearch,chirilo/elasticsearch,wbowling/elasticsearch,Brijeshrpatel9/elasticsearch,acchen97/elasticsearch,polyfractal/elasticsearch,petabytedata/elasticsearch,mnylen/elasticsearch,MjAbuz/elasticsearch,mcku/elasticsearch,kevinkluge/elasticsearch,onegambler/elasticsearch,kkirsche/elasticsearch,kcompher/elasticsearch,djschny/elasticsearch,nomoa/elasticsearch,fforbeck/elasticsearch,qwerty4030/elasticsearch,gfyoung/elasticsearch,xingguang2013/elasticsearch,a2lin/elasticsearch,masterweb121/elasticsearch,obourgain/elasticsearch,chirilo/elasticsearch,alexkuk/elasticsearch,Charlesdong/elasticsearch,onegambler/elasticsearch,mikemccand/elasticsearch,Clairebi/ElasticsearchClone,wangtuo/elasticsearch,sneivandt/elasticsearch,kalburgimanjunath/elasticsearch,Collaborne/elasticsearch,onegambler/elasticsearch,mbrukman/elasticsearch,dongjoon-hyun/elasticsearch,caengcjd/elasticsearch,Shepard1212/elasticsearch,yongminxia/elasticsearch,dataduke/elasticsearch,pozhidaevak/elasticsearch,MetSystem/elasticsearch,Helen-Zhao/elasticsearch,ulkas/elasticsearch,kevinkluge/elasticsearch,palecur/elasticsearch,infusionsoft/elasticsearch,MisterAndersen/elasticsearch,wayeast/elasticsearch,nezirus/elasticsearch,martinstuga/elasticsearch,pranavraman/elasticsearch,sposam/elasticsearch,fekaputra/elasticsearch,bestwpw/elasticsearch,Brijeshrpatel9/elasticsearch,myelin/elasticsearch,ImpressTV/elasticsearch,nellicus/elasticsearch,abibell/elasticsearch,iamjakob/elasticsearch,Stacey-Gammon/elasticsearch,tkssharma/elasticsearch,liweinan0423/elasticsearch,truemped/elasticsearch,mute/elasticsearch,knight1128/elasticsearch,amit-shar/elasticsearch,xpandan/elasticsearch,tsohil/elasticsearch,adrianbk/elasticsearch,andrejserafim/elasticsearch,himanshuag/elasticsearch,iantruslove/elasticsearch,NBSW/elasticsearch,vvcephei/elasticsearch,skearns64/elasticsearch,hirdesh2008/elasticsearch,polyfractal/elasticsearch,huypx1292/elasticsearch,yongminxia/elasticsearch,kimimj/elasticsearch,Siddartha07/elasticsearch,PhaedrusTheGreek/elasticsearch,jeteve/elasticsearch,fernandozhu/elasticsearch,luiseduardohdbackup/elasticsearch,zkidkid/elasticsearch,Fsero/elasticsearch,pritishppai/elasticsearch,anti-social/elasticsearch,obourgain/elasticsearch,ThiagoGarciaAlves/elasticsearch,shreejay/elasticsearch,jpountz/elasticsearch,wangyuxue/elasticsearch,strapdata/elassandra,tkssharma/elasticsearch,coding0011/elasticsearch,tebriel/elasticsearch,diendt/elasticsearch,wenpos/elasticsearch,davidvgalbraith/elasticsearch,LeoYao/elasticsearch,Collaborne/elasticsearch,ricardocerq/elasticsearch,lightslife/elasticsearch,rhoml/elasticsearch,xuzha/elasticsearch,avikurapati/elasticsearch,areek/elasticsearch,HonzaKral/elasticsearch,davidvgalbraith/elasticsearch,tsohil/elasticsearch,infusionsoft/elasticsearch,jw0201/elastic,LeoYao/elasticsearch,nellicus/elasticsearch,btiernay/elasticsearch,dataduke/elasticsearch,KimTaehee/elasticsearch,YosuaMichael/elasticsearch,ckclark/elasticsearch,mmaracic/elasticsearch,truemped/elasticsearch,hafkensite/elasticsearch,ydsakyclguozi/elasticsearch,huanzhong/elasticsearch,elasticdog/elasticsearch,ImpressTV/elasticsearch,szroland/elasticsearch,Fsero/elasticsearch,wbowling/elasticsearch,mohit/elasticsearch,smflorentino/elasticsearch,luiseduardohdbackup/elasticsearch,Asimov4/elasticsearch,awislowski/elasticsearch,i-am-Nathan/elasticsearch,pranavraman/elasticsearch,slavau/elasticsearch,episerver/elasticsearch,wimvds/elasticsearch,sauravmondallive/elasticsearch,mm0/elasticsearch,ouyangkongtong/elasticsearch,xpandan/elasticsearch,dylan8902/elasticsearch,Collaborne/elasticsearch,fooljohnny/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,feiqitian/elasticsearch,feiqitian/elasticsearch,pablocastro/elasticsearch,hydro2k/elasticsearch,jchampion/elasticsearch,ThalaivaStars/OrgRepo1,fforbeck/elasticsearch,acchen97/elasticsearch,achow/elasticsearch,huypx1292/elasticsearch,huypx1292/elasticsearch,abibell/elasticsearch,naveenhooda2000/elasticsearch,mjason3/elasticsearch,YosuaMichael/elasticsearch,Asimov4/elasticsearch,mortonsykes/elasticsearch,areek/elasticsearch,MjAbuz/elasticsearch,humandb/elasticsearch,zeroctu/elasticsearch,mmaracic/elasticsearch,sreeramjayan/elasticsearch,clintongormley/elasticsearch,mjason3/elasticsearch,huypx1292/elasticsearch,mbrukman/elasticsearch,artnowo/elasticsearch,kingaj/elasticsearch,trangvh/elasticsearch,NBSW/elasticsearch,hanst/elasticsearch,milodky/elasticsearch,EasonYi/elasticsearch,diendt/elasticsearch,ThalaivaStars/OrgRepo1,Liziyao/elasticsearch,palecur/elasticsearch,Rygbee/elasticsearch,Chhunlong/elasticsearch,mapr/elasticsearch,wuranbo/elasticsearch,markharwood/elasticsearch,mjhennig/elasticsearch,GlenRSmith/elasticsearch,Shekharrajak/elasticsearch,adrianbk/elasticsearch,wittyameta/elasticsearch,tkssharma/elasticsearch,elasticdog/elasticsearch,yanjunh/elasticsearch,wenpos/elasticsearch,Brijeshrpatel9/elasticsearch,iantruslove/elasticsearch,smflorentino/elasticsearch,coding0011/elasticsearch,martinstuga/elasticsearch,fooljohnny/elasticsearch,apepper/elasticsearch,artnowo/elasticsearch,Stacey-Gammon/elasticsearch,lydonchandra/elasticsearch,apepper/elasticsearch,pranavraman/elasticsearch,MisterAndersen/elasticsearch,fernandozhu/elasticsearch,ThiagoGarciaAlves/elasticsearch,AndreKR/elasticsearch,andrestc/elasticsearch,drewr/elasticsearch,Ansh90/elasticsearch,SergVro/elasticsearch,likaiwalkman/elasticsearch,sjohnr/elasticsearch,robin13/elasticsearch,achow/elasticsearch,skearns64/elasticsearch,drewr/elasticsearch,phani546/elasticsearch,sposam/elasticsearch,18098924759/elasticsearch,kkirsche/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,KimTaehee/elasticsearch,abibell/elasticsearch,HarishAtGitHub/elasticsearch,MichaelLiZhou/elasticsearch,nezirus/elasticsearch,artnowo/elasticsearch,strapdata/elassandra,zeroctu/elasticsearch,areek/elasticsearch,tsohil/elasticsearch,hydro2k/elasticsearch,xuzha/elasticsearch,jw0201/elastic,andrejserafim/elasticsearch,karthikjaps/elasticsearch,djschny/elasticsearch,davidvgalbraith/elasticsearch,caengcjd/elasticsearch,kevinkluge/elasticsearch,caengcjd/elasticsearch,nknize/elasticsearch,vvcephei/elasticsearch,Ansh90/elasticsearch,sdauletau/elasticsearch,mbrukman/elasticsearch,AshishThakur/elasticsearch,mjhennig/elasticsearch,thecocce/elasticsearch,beiske/elasticsearch,hanst/elasticsearch,rhoml/elasticsearch,ulkas/elasticsearch,markwalkom/elasticsearch,kubum/elasticsearch,alexbrasetvik/elasticsearch,golubev/elasticsearch,sarwarbhuiyan/elasticsearch,HarishAtGitHub/elasticsearch,brandonkearby/elasticsearch,qwerty4030/elasticsearch,kubum/elasticsearch,TonyChai24/ESSource,karthikjaps/elasticsearch,apepper/elasticsearch,nellicus/elasticsearch,sposam/elasticsearch,kalimatas/elasticsearch,Shekharrajak/elasticsearch,elancom/elasticsearch,likaiwalkman/elasticsearch,franklanganke/elasticsearch,mute/elasticsearch,sneivandt/elasticsearch,kcompher/elasticsearch,mnylen/elasticsearch,hechunwen/elasticsearch,ESamir/elasticsearch,kcompher/elasticsearch,kaneshin/elasticsearch,sreeramjayan/elasticsearch,kenshin233/elasticsearch,ESamir/elasticsearch,wuranbo/elasticsearch,ouyangkongtong/elasticsearch,Stacey-Gammon/elasticsearch,a2lin/elasticsearch,naveenhooda2000/elasticsearch,slavau/elasticsearch,ThiagoGarciaAlves/elasticsearch,knight1128/elasticsearch,ESamir/elasticsearch,aglne/elasticsearch,clintongormley/elasticsearch,bawse/elasticsearch,pozhidaevak/elasticsearch,beiske/elasticsearch,gfyoung/elasticsearch,alexkuk/elasticsearch,Ansh90/elasticsearch,Ansh90/elasticsearch,tahaemin/elasticsearch,Brijeshrpatel9/elasticsearch,szroland/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,HonzaKral/elasticsearch,obourgain/elasticsearch,vvcephei/elasticsearch,jpountz/elasticsearch,strapdata/elassandra5-rc,winstonewert/elasticsearch,khiraiwa/elasticsearch,hydro2k/elasticsearch,codebunt/elasticsearch,humandb/elasticsearch,alexbrasetvik/elasticsearch,hechunwen/elasticsearch,qwerty4030/elasticsearch,scorpionvicky/elasticsearch,wayeast/elasticsearch,PhaedrusTheGreek/elasticsearch,mute/elasticsearch,Liziyao/elasticsearch,thecocce/elasticsearch,MetSystem/elasticsearch,pritishppai/elasticsearch,alexkuk/elasticsearch,scorpionvicky/elasticsearch,henakamaMSFT/elasticsearch,hanst/elasticsearch,sc0ttkclark/elasticsearch,njlawton/elasticsearch,jango2015/elasticsearch,davidvgalbraith/elasticsearch,mjason3/elasticsearch,rento19962/elasticsearch,fekaputra/elasticsearch,ImpressTV/elasticsearch,lmtwga/elasticsearch,socialrank/elasticsearch,naveenhooda2000/elasticsearch,mmaracic/elasticsearch,mortonsykes/elasticsearch,fforbeck/elasticsearch,huanzhong/elasticsearch,tahaemin/elasticsearch,dylan8902/elasticsearch,Flipkart/elasticsearch,sc0ttkclark/elasticsearch,polyfractal/elasticsearch,elasticdog/elasticsearch,drewr/elasticsearch,jbertouch/elasticsearch,JSCooke/elasticsearch,rento19962/elasticsearch,andrejserafim/elasticsearch,masterweb121/elasticsearch,nomoa/elasticsearch,jango2015/elasticsearch,Uiho/elasticsearch,strapdata/elassandra-test,Kakakakakku/elasticsearch,jimczi/elasticsearch,jpountz/elasticsearch,huypx1292/elasticsearch,lydonchandra/elasticsearch,EasonYi/elasticsearch,petabytedata/elasticsearch,ckclark/elasticsearch,palecur/elasticsearch,socialrank/elasticsearch,yuy168/elasticsearch,cnfire/elasticsearch-1,AndreKR/elasticsearch,mortonsykes/elasticsearch,brandonkearby/elasticsearch,xingguang2013/elasticsearch,adrianbk/elasticsearch,easonC/elasticsearch,ivansun1010/elasticsearch,wittyameta/elasticsearch,dataduke/elasticsearch,mrorii/elasticsearch,kingaj/elasticsearch,mgalushka/elasticsearch,F0lha/elasticsearch,linglaiyao1314/elasticsearch,infusionsoft/elasticsearch,hafkensite/elasticsearch,mikemccand/elasticsearch,hechunwen/elasticsearch,GlenRSmith/elasticsearch,MichaelLiZhou/elasticsearch,Siddartha07/elasticsearch,zeroctu/elasticsearch,easonC/elasticsearch,nilabhsagar/elasticsearch,Fsero/elasticsearch,Liziyao/elasticsearch,mapr/elasticsearch,btiernay/elasticsearch,kimimj/elasticsearch,khiraiwa/elasticsearch,Shekharrajak/elasticsearch,alexbrasetvik/elasticsearch,cnfire/elasticsearch-1,mute/elasticsearch,pranavraman/elasticsearch,onegambler/elasticsearch,mgalushka/elasticsearch,easonC/elasticsearch,jsgao0/elasticsearch,dataduke/elasticsearch,easonC/elasticsearch,infusionsoft/elasticsearch,jsgao0/elasticsearch,Liziyao/elasticsearch,iamjakob/elasticsearch,pranavraman/elasticsearch,lks21c/elasticsearch,martinstuga/elasticsearch,geidies/elasticsearch,andrestc/elasticsearch,nrkkalyan/elasticsearch,dongjoon-hyun/elasticsearch,szroland/elasticsearch,tebriel/elasticsearch,NBSW/elasticsearch,jimhooker2002/elasticsearch,MichaelLiZhou/elasticsearch,mortonsykes/elasticsearch,nrkkalyan/elasticsearch,Rygbee/elasticsearch,markharwood/elasticsearch,scottsom/elasticsearch,sauravmondallive/elasticsearch,fred84/elasticsearch,gmarz/elasticsearch,StefanGor/elasticsearch,cwurm/elasticsearch,abibell/elasticsearch,vrkansagara/elasticsearch,robin13/elasticsearch,Charlesdong/elasticsearch,bestwpw/elasticsearch,fernandozhu/elasticsearch,markharwood/elasticsearch,NBSW/elasticsearch,btiernay/elasticsearch,C-Bish/elasticsearch,MaineC/elasticsearch,areek/elasticsearch,wbowling/elasticsearch,Fsero/elasticsearch,s1monw/elasticsearch,amaliujia/elasticsearch,mrorii/elasticsearch,nellicus/elasticsearch,luiseduardohdbackup/elasticsearch,wayeast/elasticsearch,C-Bish/elasticsearch,acchen97/elasticsearch,ZTE-PaaS/elasticsearch,ydsakyclguozi/elasticsearch,slavau/elasticsearch,petabytedata/elasticsearch,Brijeshrpatel9/elasticsearch,sc0ttkclark/elasticsearch,achow/elasticsearch,aglne/elasticsearch,kalburgimanjunath/elasticsearch,ImpressTV/elasticsearch,brandonkearby/elasticsearch,markwalkom/elasticsearch,onegambler/elasticsearch,dylan8902/elasticsearch,onegambler/elasticsearch,pablocastro/elasticsearch,rmuir/elasticsearch,rmuir/elasticsearch,camilojd/elasticsearch,wbowling/elasticsearch,vietlq/elasticsearch,anti-social/elasticsearch,EasonYi/elasticsearch,kingaj/elasticsearch,skearns64/elasticsearch,alexshadow007/elasticsearch,achow/elasticsearch,hechunwen/elasticsearch,masterweb121/elasticsearch,awislowski/elasticsearch,nezirus/elasticsearch,lydonchandra/elasticsearch,feiqitian/elasticsearch,dpursehouse/elasticsearch,Chhunlong/elasticsearch,jbertouch/elasticsearch,hirdesh2008/elasticsearch,Charlesdong/elasticsearch,ImpressTV/elasticsearch,MjAbuz/elasticsearch,scottsom/elasticsearch,Siddartha07/elasticsearch,MichaelLiZhou/elasticsearch,MichaelLiZhou/elasticsearch,rlugojr/elasticsearch,mrorii/elasticsearch,uschindler/elasticsearch,infusionsoft/elasticsearch,schonfeld/elasticsearch,btiernay/elasticsearch,wimvds/elasticsearch,xuzha/elasticsearch,C-Bish/elasticsearch,anti-social/elasticsearch,Asimov4/elasticsearch,szroland/elasticsearch,snikch/elasticsearch,alexbrasetvik/elasticsearch,YosuaMichael/elasticsearch,i-am-Nathan/elasticsearch,jimczi/elasticsearch,masterweb121/elasticsearch,queirozfcom/elasticsearch,nellicus/elasticsearch,franklanganke/elasticsearch,diendt/elasticsearch,davidvgalbraith/elasticsearch,glefloch/elasticsearch,ricardocerq/elasticsearch,yynil/elasticsearch,henakamaMSFT/elasticsearch,fekaputra/elasticsearch,trangvh/elasticsearch,pablocastro/elasticsearch,ivansun1010/elasticsearch,hirdesh2008/elasticsearch,chirilo/elasticsearch,kalimatas/elasticsearch,petabytedata/elasticsearch,tsohil/elasticsearch,scorpionvicky/elasticsearch,camilojd/elasticsearch,Widen/elasticsearch,Charlesdong/elasticsearch,feiqitian/elasticsearch,clintongormley/elasticsearch,sneivandt/elasticsearch,socialrank/elasticsearch,areek/elasticsearch,tkssharma/elasticsearch,mikemccand/elasticsearch,KimTaehee/elasticsearch,s1monw/elasticsearch,yongminxia/elasticsearch,hirdesh2008/elasticsearch,queirozfcom/elasticsearch,jsgao0/elasticsearch,jimhooker2002/elasticsearch,kenshin233/elasticsearch,huypx1292/elasticsearch,smflorentino/elasticsearch,yuy168/elasticsearch,mm0/elasticsearch,iantruslove/elasticsearch,abibell/elasticsearch,lchennup/elasticsearch,episerver/elasticsearch,lmtwga/elasticsearch,tkssharma/elasticsearch,xingguang2013/elasticsearch,mapr/elasticsearch,slavau/elasticsearch,xpandan/elasticsearch,huanzhong/elasticsearch,hydro2k/elasticsearch,rmuir/elasticsearch,wayeast/elasticsearch,kingaj/elasticsearch,sdauletau/elasticsearch,gfyoung/elasticsearch,PhaedrusTheGreek/elasticsearch,JSCooke/elasticsearch,golubev/elasticsearch,mnylen/elasticsearch,myelin/elasticsearch,kalburgimanjunath/elasticsearch,knight1128/elasticsearch,humandb/elasticsearch,iacdingping/elasticsearch,nezirus/elasticsearch,dpursehouse/elasticsearch,loconsolutions/elasticsearch,winstonewert/elasticsearch,camilojd/elasticsearch,GlenRSmith/elasticsearch,amaliujia/elasticsearch,springning/elasticsearch,codebunt/elasticsearch,jprante/elasticsearch,Collaborne/elasticsearch,ouyangkongtong/elasticsearch,achow/elasticsearch,bestwpw/elasticsearch,markllama/elasticsearch,fred84/elasticsearch,beiske/elasticsearch,Flipkart/elasticsearch,robin13/elasticsearch,LewayneNaidoo/elasticsearch,phani546/elasticsearch,caengcjd/elasticsearch,nrkkalyan/elasticsearch,rajanm/elasticsearch,lzo/elasticsearch-1,vingupta3/elasticsearch,franklanganke/elasticsearch,markwalkom/elasticsearch,fekaputra/elasticsearch,jbertouch/elasticsearch,nomoa/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,baishuo/elasticsearch_v2.1.0-baishuo,Shekharrajak/elasticsearch,masterweb121/elasticsearch,JervyShi/elasticsearch,JervyShi/elasticsearch,kcompher/elasticsearch,JackyMai/elasticsearch,Collaborne/elasticsearch,luiseduardohdbackup/elasticsearch,overcome/elasticsearch,sjohnr/elasticsearch,tahaemin/elasticsearch,dongjoon-hyun/elasticsearch,sreeramjayan/elasticsearch,mmaracic/elasticsearch,Asimov4/elasticsearch,socialrank/elasticsearch,xingguang2013/elasticsearch,mgalushka/elasticsearch,vvcephei/elasticsearch,ydsakyclguozi/elasticsearch,elasticdog/elasticsearch,lzo/elasticsearch-1,nknize/elasticsearch,MichaelLiZhou/elasticsearch,petabytedata/elasticsearch,iacdingping/elasticsearch,geidies/elasticsearch,masaruh/elasticsearch,himanshuag/elasticsearch,lzo/elasticsearch-1,Kakakakakku/elasticsearch,kaneshin/elasticsearch,huanzhong/elasticsearch,rlugojr/elasticsearch,robin13/elasticsearch,nilabhsagar/elasticsearch,huanzhong/elasticsearch,mgalushka/elasticsearch,nellicus/elasticsearch,lightslife/elasticsearch,pablocastro/elasticsearch,phani546/elasticsearch,vroyer/elassandra,dongjoon-hyun/elasticsearch,YosuaMichael/elasticsearch,codebunt/elasticsearch,aglne/elasticsearch,kubum/elasticsearch,sarwarbhuiyan/elasticsearch,mrorii/elasticsearch,skearns64/elasticsearch,kunallimaye/elasticsearch,qwerty4030/elasticsearch,18098924759/elasticsearch,pritishppai/elasticsearch,schonfeld/elasticsearch,kingaj/elasticsearch,lzo/elasticsearch-1,palecur/elasticsearch,himanshuag/elasticsearch,cnfire/elasticsearch-1,pranavraman/elasticsearch,a2lin/elasticsearch,yanjunh/elasticsearch,maddin2016/elasticsearch,springning/elasticsearch,MetSystem/elasticsearch,weipinghe/elasticsearch,ZTE-PaaS/elasticsearch,jeteve/elasticsearch,strapdata/elassandra5-rc,iantruslove/elasticsearch,tebriel/elasticsearch,queirozfcom/elasticsearch,beiske/elasticsearch,alexkuk/elasticsearch,phani546/elasticsearch,jsgao0/elasticsearch,dpursehouse/elasticsearch,rajanm/elasticsearch,Uiho/elasticsearch,ckclark/elasticsearch,Shepard1212/elasticsearch,drewr/elasticsearch,zkidkid/elasticsearch,Stacey-Gammon/elasticsearch,18098924759/elasticsearch,jchampion/elasticsearch,SergVro/elasticsearch,socialrank/elasticsearch,wangtuo/elasticsearch,masaruh/elasticsearch,ZTE-PaaS/elasticsearch,mkis-/elasticsearch,shreejay/elasticsearch,markllama/elasticsearch,jw0201/elastic,wimvds/elasticsearch,mapr/elasticsearch,mbrukman/elasticsearch,masaruh/elasticsearch,spiegela/elasticsearch,mkis-/elasticsearch,chirilo/elasticsearch,MjAbuz/elasticsearch,sauravmondallive/elasticsearch,markllama/elasticsearch,ImpressTV/elasticsearch,strapdata/elassandra-test,Siddartha07/elasticsearch,golubev/elasticsearch,areek/elasticsearch,easonC/elasticsearch,HarishAtGitHub/elasticsearch,EasonYi/elasticsearch,Charlesdong/elasticsearch,kevinkluge/elasticsearch,koxa29/elasticsearch,Uiho/elasticsearch,hirdesh2008/elasticsearch,myelin/elasticsearch,strapdata/elassandra-test,golubev/elasticsearch,mute/elasticsearch,IanvsPoplicola/elasticsearch,koxa29/elasticsearch,mcku/elasticsearch,wuranbo/elasticsearch,episerver/elasticsearch,ThalaivaStars/OrgRepo1,liweinan0423/elasticsearch,caengcjd/elasticsearch,markwalkom/elasticsearch,phani546/elasticsearch,hanswang/elasticsearch,AshishThakur/elasticsearch,HarishAtGitHub/elasticsearch,djschny/elasticsearch,mapr/elasticsearch,fooljohnny/elasticsearch,kenshin233/elasticsearch,rajanm/elasticsearch,mbrukman/elasticsearch,infusionsoft/elasticsearch,ZTE-PaaS/elasticsearch,snikch/elasticsearch,fernandozhu/elasticsearch,mohit/elasticsearch,PhaedrusTheGreek/elasticsearch,tsohil/elasticsearch,jaynblue/elasticsearch,liweinan0423/elasticsearch,IanvsPoplicola/elasticsearch,lchennup/elasticsearch,mjhennig/elasticsearch,dataduke/elasticsearch,khiraiwa/elasticsearch,Uiho/elasticsearch,ThiagoGarciaAlves/elasticsearch,beiske/elasticsearch,Ansh90/elasticsearch,lzo/elasticsearch-1,linglaiyao1314/elasticsearch,vietlq/elasticsearch,markllama/elasticsearch,kunallimaye/elasticsearch,MaineC/elasticsearch,umeshdangat/elasticsearch,Widen/elasticsearch,mrorii/elasticsearch,xpandan/elasticsearch,AshishThakur/elasticsearch,kcompher/elasticsearch,markharwood/elasticsearch,schonfeld/elasticsearch,loconsolutions/elasticsearch,naveenhooda2000/elasticsearch,MaineC/elasticsearch,sarwarbhuiyan/elasticsearch,snikch/elasticsearch,YosuaMichael/elasticsearch,Flipkart/elasticsearch,shreejay/elasticsearch,xpandan/elasticsearch,umeshdangat/elasticsearch,njlawton/elasticsearch,socialrank/elasticsearch,vvcephei/elasticsearch,sc0ttkclark/elasticsearch,yuy168/elasticsearch,Shepard1212/elasticsearch,strapdata/elassandra-test,nilabhsagar/elasticsearch,ouyangkongtong/elasticsearch,luiseduardohdbackup/elasticsearch,Charlesdong/elasticsearch,lchennup/elasticsearch,avikurapati/elasticsearch,adrianbk/elasticsearch,springning/elasticsearch,smflorentino/elasticsearch,linglaiyao1314/elasticsearch,yynil/elasticsearch,dylan8902/elasticsearch,JSCooke/elasticsearch,Ansh90/elasticsearch,milodky/elasticsearch,F0lha/elasticsearch,luiseduardohdbackup/elasticsearch,strapdata/elassandra-test,jimhooker2002/elasticsearch,LeoYao/elasticsearch,F0lha/elasticsearch,karthikjaps/elasticsearch,caengcjd/elasticsearch,alexbrasetvik/elasticsearch,ivansun1010/elasticsearch,hydro2k/elasticsearch,drewr/elasticsearch | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.store;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.index.*;
import org.apache.lucene.store.*;
import org.apache.lucene.util.*;
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.lucene.Directories;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.lucene.store.InputStreamIndexInput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.Callback;
import org.elasticsearch.common.util.concurrent.AbstractRefCounted;
import org.elasticsearch.common.util.concurrent.RefCounted;
import org.elasticsearch.env.ShardLock;
import org.elasticsearch.index.settings.IndexSettings;
import org.elasticsearch.index.shard.AbstractIndexShardComponent;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.store.distributor.Distributor;
import java.io.*;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
/**
* A Store provides plain access to files written by an elasticsearch index shard. Each shard
* has a dedicated store that is uses to access Lucene's Directory which represents the lowest level
* of file abstraction in Lucene used to read and write Lucene indices.
* This class also provides access to metadata information like checksums for committed files. A committed
* file is a file that belongs to a segment written by a Lucene commit. Files that have not been committed
* ie. created during a merge or a shard refresh / NRT reopen are not considered in the MetadataSnapshot.
* <p/>
* Note: If you use a store it's reference count should be increased before using it by calling #incRef and a
* corresponding #decRef must be called in a try/finally block to release the store again ie.:
* <pre>
* store.incRef();
* try {
* // use the store...
*
* } finally {
* store.decRef();
* }
* </pre>
*/
public class Store extends AbstractIndexShardComponent implements Closeable, RefCounted {
private static final String CODEC = "store";
private static final int VERSION_STACK_TRACE = 1; // we write the stack trace too since 1.4.0
private static final int VERSION_START = 0;
private static final int VERSION = VERSION_STACK_TRACE;
private static final String CORRUPTED = "corrupted_";
private final AtomicBoolean isClosed = new AtomicBoolean(false);
private final DirectoryService directoryService;
private final StoreDirectory directory;
private final ReentrantReadWriteLock metadataLock = new ReentrantReadWriteLock();
private final ShardLock shardLock;
private final OnClose onClose;
private final AbstractRefCounted refCounter = new AbstractRefCounted("store") {
@Override
protected void closeInternal() {
// close us once we are done
Store.this.closeInternal();
}
};
public Store(ShardId shardId, @IndexSettings Settings indexSettings, DirectoryService directoryService, Distributor distributor, ShardLock shardLock) throws IOException {
this(shardId, indexSettings, directoryService, distributor, shardLock, OnClose.EMPTY);
}
@Inject
public Store(ShardId shardId, @IndexSettings Settings indexSettings, DirectoryService directoryService, Distributor distributor, ShardLock shardLock, OnClose onClose) throws IOException {
super(shardId, indexSettings);
this.directoryService = directoryService;
this.directory = new StoreDirectory(directoryService.newFromDistributor(distributor), Loggers.getLogger("index.store.deletes", indexSettings, shardId));
this.shardLock = shardLock;
this.onClose = onClose;
assert onClose != null;
assert shardLock != null;
assert shardLock.getShardId().equals(shardId);
}
public Directory directory() {
ensureOpen();
return directory;
}
/**
* Returns the last committed segments info for this store
*
* @throws IOException if the index is corrupted or the segments file is not present
*/
public SegmentInfos readLastCommittedSegmentsInfo() throws IOException {
return readSegmentsInfo(null, directory());
}
/**
* Returns the segments info for the given commit or for the latest commit if the given commit is <code>null</code>
*
* @throws IOException if the index is corrupted or the segments file is not present
*/
private static SegmentInfos readSegmentsInfo(IndexCommit commit, Directory directory) throws IOException {
try {
return commit == null ? Lucene.readSegmentInfos(directory) : Lucene.readSegmentInfos(commit, directory);
} catch (EOFException eof) {
// TODO this should be caught by lucene - EOF is almost certainly an index corruption
throw new CorruptIndexException("Read past EOF while reading segment infos", "commit(" + commit + ")", eof);
} catch (IOException exception) {
throw exception; // IOExceptions like too many open files are not necessarily a corruption - just bubble it up
} catch (Exception ex) {
throw new CorruptIndexException("Hit unexpected exception while reading segment infos", "commit(" + commit + ")", ex);
}
}
final void ensureOpen() { // for testing
if (this.refCounter.refCount() <= 0) {
throw new AlreadyClosedException("store is already closed");
}
}
/**
* Returns a new MetadataSnapshot for the latest commit in this store or
* an empty snapshot if no index exists or can not be opened.
*
* @throws CorruptIndexException if the lucene index is corrupted. This can be caused by a checksum mismatch or an
* unexpected exception when opening the index reading the segments file.
*/
public MetadataSnapshot getMetadataOrEmpty() throws IOException {
try {
return getMetadata(null);
} catch (IndexNotFoundException ex) {
// that's fine - happens all the time no need to log
} catch (FileNotFoundException | NoSuchFileException ex) {
logger.info("Failed to open / find files while reading metadata snapshot");
}
return MetadataSnapshot.EMPTY;
}
/**
* Returns a new MetadataSnapshot for the latest commit in this store.
*
* @throws CorruptIndexException if the lucene index is corrupted. This can be caused by a checksum mismatch or an
* unexpected exception when opening the index reading the segments file.
* @throws FileNotFoundException if one or more files referenced by a commit are not present.
* @throws NoSuchFileException if one or more files referenced by a commit are not present.
* @throws IndexNotFoundException if no index / valid commit-point can be found in this store
*/
public MetadataSnapshot getMetadata() throws IOException {
return getMetadata(null);
}
/**
* Returns a new MetadataSnapshot for the given commit. If the given commit is <code>null</code>
* the latest commit point is used.
*
* @throws CorruptIndexException if the lucene index is corrupted. This can be caused by a checksum mismatch or an
* unexpected exception when opening the index reading the segments file.
* @throws FileNotFoundException if one or more files referenced by a commit are not present.
* @throws NoSuchFileException if one or more files referenced by a commit are not present.
* @throws IndexNotFoundException if the commit point can't be found in this store
*/
public MetadataSnapshot getMetadata(IndexCommit commit) throws IOException {
ensureOpen();
failIfCorrupted();
metadataLock.readLock().lock();
try {
return new MetadataSnapshot(commit, directory, logger);
} catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
markStoreCorrupted(ex);
throw ex;
} finally {
metadataLock.readLock().unlock();
}
}
/**
* Renames all the given files form the key of the map to the
* value of the map. All successfully renamed files are removed from the map in-place.
*/
public void renameFilesSafe(Map<String, String> tempFileMap) throws IOException {
// this works just like a lucene commit - we rename all temp files and once we successfully
// renamed all the segments we rename the commit to ensure we don't leave half baked commits behind.
final Map.Entry<String, String>[] entries = tempFileMap.entrySet().toArray(new Map.Entry[tempFileMap.size()]);
ArrayUtil.timSort(entries, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
String left = o1.getValue();
String right = o2.getValue();
if (left.startsWith(IndexFileNames.SEGMENTS) || right.startsWith(IndexFileNames.SEGMENTS)) {
if (left.startsWith(IndexFileNames.SEGMENTS) == false) {
return -1;
} else if (right.startsWith(IndexFileNames.SEGMENTS) == false) {
return 1;
}
}
return left.compareTo(right);
}
});
metadataLock.writeLock().lock();
// we make sure that nobody fetches the metadata while we do this rename operation here to ensure we don't
// get exceptions if files are still open.
try {
for (Map.Entry<String, String> entry : entries) {
String tempFile = entry.getKey();
String origFile = entry.getValue();
// first, go and delete the existing ones
try {
directory.deleteFile(origFile);
} catch (FileNotFoundException | NoSuchFileException e) {
} catch (Throwable ex) {
logger.debug("failed to delete file [{}]", ex, origFile);
}
// now, rename the files... and fail it it won't work
this.renameFile(tempFile, origFile);
final String remove = tempFileMap.remove(tempFile);
assert remove != null;
}
} finally {
metadataLock.writeLock().unlock();
}
}
/**
* Deletes the content of a shard store. Be careful calling this!.
*/
public void deleteContent() throws IOException {
ensureOpen();
final String[] files = directory.listAll();
final List<IOException> exceptions = new ArrayList<>();
for (String file : files) {
try {
directory.deleteFile(file);
} catch (NoSuchFileException | FileNotFoundException e) {
// ignore
} catch (IOException e) {
exceptions.add(e);
}
}
ExceptionsHelper.rethrowAndSuppress(exceptions);
}
public StoreStats stats() throws IOException {
ensureOpen();
return new StoreStats(Directories.estimateSize(directory), directoryService.throttleTimeInNanos());
}
public void renameFile(String from, String to) throws IOException {
ensureOpen();
directory.renameFile(from, to);
}
/**
* Increments the refCount of this Store instance. RefCounts are used to determine when a
* Store can be closed safely, i.e. as soon as there are no more references. Be sure to always call a
* corresponding {@link #decRef}, in a finally clause; otherwise the store may never be closed. Note that
* {@link #close} simply calls decRef(), which means that the Store will not really be closed until {@link
* #decRef} has been called for all outstanding references.
* <p/>
* Note: Close can safely be called multiple times.
*
* @throws AlreadyClosedException iff the reference counter can not be incremented.
* @see #decRef
* @see #tryIncRef()
*/
@Override
public final void incRef() {
refCounter.incRef();
}
/**
* Tries to increment the refCount of this Store instance. This method will return <tt>true</tt> iff the refCount was
* incremented successfully otherwise <tt>false</tt>. RefCounts are used to determine when a
* Store can be closed safely, i.e. as soon as there are no more references. Be sure to always call a
* corresponding {@link #decRef}, in a finally clause; otherwise the store may never be closed. Note that
* {@link #close} simply calls decRef(), which means that the Store will not really be closed until {@link
* #decRef} has been called for all outstanding references.
* <p/>
* Note: Close can safely be called multiple times.
*
* @see #decRef()
* @see #incRef()
*/
@Override
public final boolean tryIncRef() {
return refCounter.tryIncRef();
}
/**
* Decreases the refCount of this Store instance.If the refCount drops to 0, then this
* store is closed.
*
* @see #incRef
*/
@Override
public final void decRef() {
refCounter.decRef();
}
@Override
public void close() {
if (isClosed.compareAndSet(false, true)) {
// only do this once!
decRef();
logger.debug("store reference count on close: " + refCounter.refCount());
}
}
private void closeInternal() {
try {
try {
directory.innerClose(); // this closes the distributorDirectory as well
} finally {
onClose.handle(shardLock);
}
} catch (IOException e) {
logger.debug("failed to close directory", e);
} finally {
IOUtils.closeWhileHandlingException(shardLock);
}
}
/**
* Reads a MetadataSnapshot from the given index locations or returns an empty snapshot if it can't be read.
*
* @throws IOException if the index we try to read is corrupted
*/
public static MetadataSnapshot readMetadataSnapshot(Path[] indexLocations, ESLogger logger) throws IOException {
final Directory[] dirs = new Directory[indexLocations.length];
try {
for (int i = 0; i < indexLocations.length; i++) {
dirs[i] = new SimpleFSDirectory(indexLocations[i]);
}
DistributorDirectory dir = new DistributorDirectory(dirs);
failIfCorrupted(dir, new ShardId("", 1));
return new MetadataSnapshot(null, dir, logger);
} catch (IndexNotFoundException ex) {
// that's fine - happens all the time no need to log
} catch (FileNotFoundException | NoSuchFileException ex) {
logger.info("Failed to open / find files while reading metadata snapshot");
} finally {
IOUtils.close(dirs);
}
return MetadataSnapshot.EMPTY;
}
/**
* The returned IndexOutput might validate the files checksum if the file has been written with a newer lucene version
* and the metadata holds the necessary information to detect that it was been written by Lucene 4.8 or newer. If it has only
* a legacy checksum, returned IndexOutput will not verify the checksum.
* <p/>
* Note: Checksums are calculated nevertheless since lucene does it by default sicne version 4.8.0. This method only adds the
* verification against the checksum in the given metadata and does not add any significant overhead.
*/
public IndexOutput createVerifyingOutput(String fileName, final StoreFileMetaData metadata, final IOContext context) throws IOException {
IndexOutput output = directory().createOutput(fileName, context);
boolean success = false;
try {
if (metadata.hasLegacyChecksum()) {
logger.debug("create legacy adler32 output for {}", fileName);
output = new LegacyVerification.Adler32VerifyingIndexOutput(output, metadata.checksum(), metadata.length());
} else if (metadata.checksum() == null) {
// TODO: when the file is a segments_N, we can still CRC-32 + length for more safety
// its had that checksum forever.
logger.debug("create legacy length-only output for {}", fileName);
output = new LegacyVerification.LengthVerifyingIndexOutput(output, metadata.length());
} else {
assert metadata.writtenBy() != null;
assert metadata.writtenBy().onOrAfter(Version.LUCENE_4_8);
output = new LuceneVerifyingIndexOutput(metadata, output);
}
success = true;
} finally {
if (success == false) {
IOUtils.closeWhileHandlingException(output);
}
}
return output;
}
public static void verify(IndexOutput output) throws IOException {
if (output instanceof VerifyingIndexOutput) {
((VerifyingIndexOutput) output).verify();
}
}
public IndexInput openVerifyingInput(String filename, IOContext context, StoreFileMetaData metadata) throws IOException {
if (metadata.hasLegacyChecksum() || metadata.checksum() == null) {
logger.debug("open legacy input for {}", filename);
return directory().openInput(filename, context);
}
assert metadata.writtenBy() != null;
assert metadata.writtenBy().onOrAfter(Version.LUCENE_4_8_0);
return new VerifyingIndexInput(directory().openInput(filename, context));
}
public static void verify(IndexInput input) throws IOException {
if (input instanceof VerifyingIndexInput) {
((VerifyingIndexInput) input).verify();
}
}
public boolean checkIntegrityNoException(StoreFileMetaData md) {
return checkIntegrityNoException(md, directory());
}
public static boolean checkIntegrityNoException(StoreFileMetaData md, Directory directory) {
try {
checkIntegrity(md, directory);
return true;
} catch (IOException e) {
return false;
}
}
public static void checkIntegrity(final StoreFileMetaData md, final Directory directory) throws IOException {
try (IndexInput input = directory.openInput(md.name(), IOContext.READONCE)) {
if (input.length() != md.length()) { // first check the length no matter how old this file is
throw new CorruptIndexException("expected length=" + md.length() + " != actual length: " + input.length() + " : file truncated?", input);
}
if (md.writtenBy() != null && md.writtenBy().onOrAfter(Version.LUCENE_4_8_0)) {
// throw exception if the file is corrupt
String checksum = Store.digestToString(CodecUtil.checksumEntireFile(input));
// throw exception if metadata is inconsistent
if (!checksum.equals(md.checksum())) {
throw new CorruptIndexException("inconsistent metadata: lucene checksum=" + checksum +
", metadata checksum=" + md.checksum(), input);
}
} else if (md.hasLegacyChecksum()) {
// legacy checksum verification - no footer that we need to omit in the checksum!
final Checksum checksum = new Adler32();
final byte[] buffer = new byte[md.length() > 4096 ? 4096 : (int) md.length()];
final long len = input.length();
long read = 0;
while (len > read) {
final long bytesLeft = len - read;
final int bytesToRead = bytesLeft < buffer.length ? (int) bytesLeft : buffer.length;
input.readBytes(buffer, 0, bytesToRead, false);
checksum.update(buffer, 0, bytesToRead);
read += bytesToRead;
}
String adler32 = Store.digestToString(checksum.getValue());
if (!adler32.equals(md.checksum())) {
throw new CorruptIndexException("checksum failed (hardware problem?) : expected=" + md.checksum() +
" actual=" + adler32, input);
}
}
}
}
public boolean isMarkedCorrupted() throws IOException {
ensureOpen();
/* marking a store as corrupted is basically adding a _corrupted to all
* the files. This prevent
*/
final String[] files = directory().listAll();
for (String file : files) {
if (file.startsWith(CORRUPTED)) {
return true;
}
}
return false;
}
public void failIfCorrupted() throws IOException {
ensureOpen();
failIfCorrupted(directory, shardId);
}
private static final void failIfCorrupted(Directory directory, ShardId shardId) throws IOException {
final String[] files = directory.listAll();
List<CorruptIndexException> ex = new ArrayList<>();
for (String file : files) {
if (file.startsWith(CORRUPTED)) {
try (ChecksumIndexInput input = directory.openChecksumInput(file, IOContext.READONCE)) {
int version = CodecUtil.checkHeader(input, CODEC, VERSION_START, VERSION);
String msg = input.readString();
StringBuilder builder = new StringBuilder(shardId.toString());
builder.append(" Preexisting corrupted index [");
builder.append(file).append("] caused by: ");
builder.append(msg);
if (version == VERSION_STACK_TRACE) {
builder.append(System.lineSeparator());
builder.append(input.readString());
}
ex.add(new CorruptIndexException(builder.toString(), "preexisting_corruption"));
CodecUtil.checkFooter(input);
}
}
}
if (ex.isEmpty() == false) {
ExceptionsHelper.rethrowAndSuppress(ex);
}
}
/**
* This method deletes every file in this store that is not contained in the given source meta data or is a
* legacy checksum file. After the delete it pulls the latest metadata snapshot from the store and compares it
* to the given snapshot. If the snapshots are inconsistent an illegal state exception is thrown
*
* @param reason the reason for this cleanup operation logged for each deleted file
* @param sourceMetaData the metadata used for cleanup. all files in this metadata should be kept around.
* @throws IOException if an IOException occurs
* @throws ElasticsearchIllegalStateException if the latest snapshot in this store differs from the given one after the cleanup.
*/
public void cleanupAndVerify(String reason, MetadataSnapshot sourceMetaData) throws IOException {
failIfCorrupted();
metadataLock.writeLock().lock();
try {
final StoreDirectory dir = directory;
for (String existingFile : dir.listAll()) {
// don't delete snapshot file, or the checksums file (note, this is extra protection since the Store won't delete checksum)
if (!sourceMetaData.contains(existingFile) && !Store.isChecksum(existingFile)) {
try {
dir.deleteFile(reason, existingFile);
} catch (Exception e) {
// ignore, we don't really care, will get deleted later on
}
}
}
final Store.MetadataSnapshot metadataOrEmpty = getMetadata();
verifyAfterCleanup(sourceMetaData, metadataOrEmpty);
} finally {
metadataLock.writeLock().unlock();
}
}
// pkg private for testing
final void verifyAfterCleanup(MetadataSnapshot sourceMetaData, MetadataSnapshot targetMetaData) {
final RecoveryDiff recoveryDiff = targetMetaData.recoveryDiff(sourceMetaData);
if (recoveryDiff.identical.size() != recoveryDiff.size()) {
if (recoveryDiff.missing.isEmpty()) {
for (StoreFileMetaData meta : recoveryDiff.different) {
StoreFileMetaData local = targetMetaData.get(meta.name());
StoreFileMetaData remote = sourceMetaData.get(meta.name());
// if we have different files the they must have no checksums otherwise something went wrong during recovery.
// we have that problem when we have an empty index is only a segments_1 file then we can't tell if it's a Lucene 4.8 file
// and therefore no checksum. That isn't much of a problem since we simply copy it over anyway but those files come out as
// different in the diff. That's why we have to double check here again if the rest of it matches.
// all is fine this file is just part of a commit or a segment that is different
final boolean same = local.isSame(remote);
// this check ensures that the two files are consistent ie. if we don't have checksums only the rest needs to match we are just
// verifying that we are consistent on both ends source and target
final boolean hashAndLengthEqual = (
local.checksum() == null
&& remote.checksum() == null
&& local.hash().equals(remote.hash())
&& local.length() == remote.length());
final boolean consistent = hashAndLengthEqual || same;
if (consistent == false) {
logger.debug("Files are different on the recovery target: {} ", recoveryDiff);
throw new ElasticsearchIllegalStateException("local version: " + local + " is different from remote version after recovery: " + remote, null);
}
}
} else {
logger.debug("Files are missing on the recovery target: {} ", recoveryDiff);
throw new ElasticsearchIllegalStateException("Files are missing on the recovery target: [different="
+ recoveryDiff.different + ", missing=" + recoveryDiff.missing + ']', null);
}
}
}
/**
* Returns the current reference count.
*/
public int refCount() {
return refCounter.refCount();
}
private static final class StoreDirectory extends FilterDirectory {
private final ESLogger deletesLogger;
StoreDirectory(Directory delegateDirectory, ESLogger deletesLogger) throws IOException {
super(delegateDirectory);
this.deletesLogger = deletesLogger;
}
@Override
public void close() throws IOException {
assert false : "Nobody should close this directory except of the Store itself";
}
public void deleteFile(String msg, String name) throws IOException {
deletesLogger.trace("{}: delete file {}", msg, name);
super.deleteFile(name);
}
@Override
public void deleteFile(String name) throws IOException {
deleteFile("StoreDirectory.deleteFile", name);
}
private void innerClose() throws IOException {
super.close();
}
@Override
public String toString() {
return "store(" + in.toString() + ")";
}
}
/** Log that we are about to delete this file, to the index.store.deletes component. */
public void deleteFile(String msg, String storeFile) throws IOException {
directory.deleteFile(msg, storeFile);
}
/**
* Represents a snapshot of the current directory build from the latest Lucene commit.
* Only files that are part of the last commit are considered in this datastrucutre.
* For backwards compatibility the snapshot might include legacy checksums that
* are derived from a dedicated checksum file written by older elasticsearch version pre 1.3
* <p/>
* Note: This class will ignore the <tt>segments.gen</tt> file since it's optional and might
* change concurrently for safety reasons.
*
* @see StoreFileMetaData
*/
public final static class MetadataSnapshot implements Iterable<StoreFileMetaData>, Streamable {
private static final ESLogger logger = Loggers.getLogger(MetadataSnapshot.class);
private static final Version FIRST_LUCENE_CHECKSUM_VERSION = Version.LUCENE_4_8;
private Map<String, StoreFileMetaData> metadata;
public static final MetadataSnapshot EMPTY = new MetadataSnapshot();
public MetadataSnapshot(Map<String, StoreFileMetaData> metadata) {
this.metadata = metadata;
}
MetadataSnapshot() {
this.metadata = Collections.emptyMap();
}
MetadataSnapshot(IndexCommit commit, Directory directory, ESLogger logger) throws IOException {
metadata = buildMetadata(commit, directory, logger);
}
ImmutableMap<String, StoreFileMetaData> buildMetadata(IndexCommit commit, Directory directory, ESLogger logger) throws IOException {
ImmutableMap.Builder<String, StoreFileMetaData> builder = ImmutableMap.builder();
Map<String, String> checksumMap = readLegacyChecksums(directory).v1();
try {
final SegmentInfos segmentCommitInfos = Store.readSegmentsInfo(commit, directory);
Version maxVersion = Version.LUCENE_4_0; // we don't know which version was used to write so we take the max version.
for (SegmentCommitInfo info : segmentCommitInfos) {
final Version version = info.info.getVersion();
if (version == null) {
// version is written since 3.1+: we should have already hit IndexFormatTooOld.
throw new IllegalArgumentException("expected valid version value: " + info.info.toString());
}
if (version.onOrAfter(maxVersion)) {
maxVersion = version;
}
for (String file : info.files()) {
String legacyChecksum = checksumMap.get(file);
if (version.onOrAfter(FIRST_LUCENE_CHECKSUM_VERSION)) {
checksumFromLuceneFile(directory, file, builder, logger, version, SEGMENT_INFO_EXTENSION.equals(IndexFileNames.getExtension(file)));
} else {
builder.put(file, new StoreFileMetaData(file, directory.fileLength(file), legacyChecksum, version));
}
}
}
final String segmentsFile = segmentCommitInfos.getSegmentsFileName();
String legacyChecksum = checksumMap.get(segmentsFile);
if (maxVersion.onOrAfter(FIRST_LUCENE_CHECKSUM_VERSION)) {
checksumFromLuceneFile(directory, segmentsFile, builder, logger, maxVersion, true);
} else {
final BytesRefBuilder fileHash = new BytesRefBuilder();
final long length;
try (final IndexInput in = directory.openInput(segmentsFile, IOContext.READONCE)) {
length = in.length();
hashFile(fileHash, new InputStreamIndexInput(in, length), length);
}
builder.put(segmentsFile, new StoreFileMetaData(segmentsFile, length, legacyChecksum, maxVersion, fileHash.get()));
}
} catch (CorruptIndexException | IndexNotFoundException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
// we either know the index is corrupted or it's just not there
throw ex;
} catch (Throwable ex) {
try {
// Lucene checks the checksum after it tries to lookup the codec etc.
// in that case we might get only IAE or similar exceptions while we are really corrupt...
// TODO we should check the checksum in lucene if we hit an exception
logger.warn("failed to build store metadata. checking segment info integrity (with commit [{}])",
ex, commit == null ? "no" : "yes");
Lucene.checkSegmentInfoIntegrity(directory);
} catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException cex) {
cex.addSuppressed(ex);
throw cex;
} catch (Throwable e) {
// ignore...
}
throw ex;
}
return builder.build();
}
/**
* Reads legacy checksum files found in the directory.
* <p/>
* Files are expected to start with _checksums- prefix
* followed by long file version. Only file with the highest version is read, all other files are ignored.
*
* @param directory the directory to read checksums from
* @return a map of file checksums and the checksum file version
* @throws IOException
*/
static Tuple<Map<String, String>, Long> readLegacyChecksums(Directory directory) throws IOException {
synchronized (directory) {
long lastFound = -1;
for (String name : directory.listAll()) {
if (!isChecksum(name)) {
continue;
}
long current = Long.parseLong(name.substring(CHECKSUMS_PREFIX.length()));
if (current > lastFound) {
lastFound = current;
}
}
if (lastFound > -1) {
try (IndexInput indexInput = directory.openInput(CHECKSUMS_PREFIX + lastFound, IOContext.READONCE)) {
indexInput.readInt(); // version
return new Tuple(indexInput.readStringStringMap(), lastFound);
}
}
return new Tuple(new HashMap<>(), -1l);
}
}
/**
* Deletes all checksum files with version lower than newVersion.
*
* @param directory the directory to clean
* @param newVersion the latest checksum file version
* @throws IOException
*/
static void cleanLegacyChecksums(Directory directory, long newVersion) throws IOException {
synchronized (directory) {
for (String name : directory.listAll()) {
if (isChecksum(name)) {
long current = Long.parseLong(name.substring(CHECKSUMS_PREFIX.length()));
if (current < newVersion) {
try {
directory.deleteFile(name);
} catch (IOException ex) {
logger.debug("can't delete old checksum file [{}]", ex, name);
}
}
}
}
}
}
private static void checksumFromLuceneFile(Directory directory, String file, ImmutableMap.Builder<String, StoreFileMetaData> builder, ESLogger logger, Version version, boolean readFileAsHash) throws IOException {
final String checksum;
final BytesRefBuilder fileHash = new BytesRefBuilder();
try (final IndexInput in = directory.openInput(file, IOContext.READONCE)) {
final long length;
try {
length = in.length();
if (length < CodecUtil.footerLength()) {
// truncated files trigger IAE if we seek negative... these files are really corrupted though
throw new CorruptIndexException("Can't retrieve checksum from file: " + file + " file length must be >= " + CodecUtil.footerLength() + " but was: " + in.length(), in);
}
if (readFileAsHash) {
final VerifyingIndexInput verifyingIndexInput = new VerifyingIndexInput(in); // additional safety we checksum the entire file we read the hash for...
hashFile(fileHash, new InputStreamIndexInput(verifyingIndexInput, length), length);
checksum = digestToString(verifyingIndexInput.verify());
} else {
checksum = digestToString(CodecUtil.retrieveChecksum(in));
}
} catch (Throwable ex) {
logger.debug("Can retrieve checksum from file [{}]", ex, file);
throw ex;
}
builder.put(file, new StoreFileMetaData(file, length, checksum, version, fileHash.get()));
}
}
/**
* Computes a strong hash value for small files. Note that this method should only be used for files < 1MB
*/
public static BytesRef hashFile(Directory directory, String file) throws IOException {
final BytesRefBuilder fileHash = new BytesRefBuilder();
try (final IndexInput in = directory.openInput(file, IOContext.READONCE)) {
hashFile(fileHash, new InputStreamIndexInput(in, in.length()), in.length());
}
return fileHash.get();
}
/**
* Computes a strong hash value for small files. Note that this method should only be used for files < 1MB
*/
public static void hashFile(BytesRefBuilder fileHash, InputStream in, long size) throws IOException {
final int len = (int) Math.min(1024 * 1024, size); // for safety we limit this to 1MB
fileHash.grow(len);
fileHash.setLength(len);
final int readBytes = Streams.readFully(in, fileHash.bytes(), 0, len);
assert readBytes == len : Integer.toString(readBytes) + " != " + Integer.toString(len);
assert fileHash.length() == len : Integer.toString(fileHash.length()) + " != " + Integer.toString(len);
}
@Override
public Iterator<StoreFileMetaData> iterator() {
return metadata.values().iterator();
}
public StoreFileMetaData get(String name) {
return metadata.get(name);
}
public Map<String, StoreFileMetaData> asMap() {
return metadata;
}
private static final String DEL_FILE_EXTENSION = "del"; // legacy delete file
private static final String LIV_FILE_EXTENSION = "liv"; // lucene 5 delete file
private static final String FIELD_INFOS_FILE_EXTENSION = "fnm";
private static final String SEGMENT_INFO_EXTENSION = "si";
/**
* Returns a diff between the two snapshots that can be used for recovery. The given snapshot is treated as the
* recovery target and this snapshot as the source. The returned diff will hold a list of files that are:
* <ul>
* <li>identical: they exist in both snapshots and they can be considered the same ie. they don't need to be recovered</li>
* <li>different: they exist in both snapshots but their they are not identical</li>
* <li>missing: files that exist in the source but not in the target</li>
* </ul>
* This method groups file into per-segment files and per-commit files. A file is treated as
* identical if and on if all files in it's group are identical. On a per-segment level files for a segment are treated
* as identical iff:
* <ul>
* <li>all files in this segment have the same checksum</li>
* <li>all files in this segment have the same length</li>
* <li>the segments <tt>.si</tt> files hashes are byte-identical Note: This is a using a perfect hash function, The metadata transfers the <tt>.si</tt> file content as it's hash</li>
* </ul>
* <p/>
* The <tt>.si</tt> file contains a lot of diagnostics including a timestamp etc. in the future there might be
* unique segment identifiers in there hardening this method further.
* <p/>
* The per-commit files handles very similar. A commit is composed of the <tt>segments_N</tt> files as well as generational files like
* deletes (<tt>_x_y.del</tt>) or field-info (<tt>_x_y.fnm</tt>) files. On a per-commit level files for a commit are treated
* as identical iff:
* <ul>
* <li>all files belonging to this commit have the same checksum</li>
* <li>all files belonging to this commit have the same length</li>
* <li>the segments file <tt>segments_N</tt> files hashes are byte-identical Note: This is a using a perfect hash function, The metadata transfers the <tt>segments_N</tt> file content as it's hash</li>
* </ul>
* <p/>
* NOTE: this diff will not contain the <tt>segments.gen</tt> file. This file is omitted on recovery.
*/
public RecoveryDiff recoveryDiff(MetadataSnapshot recoveryTargetSnapshot) {
final ImmutableList.Builder<StoreFileMetaData> identical = ImmutableList.builder();
final ImmutableList.Builder<StoreFileMetaData> different = ImmutableList.builder();
final ImmutableList.Builder<StoreFileMetaData> missing = ImmutableList.builder();
final Map<String, List<StoreFileMetaData>> perSegment = new HashMap<>();
final List<StoreFileMetaData> perCommitStoreFiles = new ArrayList<>();
for (StoreFileMetaData meta : this) {
if (IndexFileNames.OLD_SEGMENTS_GEN.equals(meta.name())) { // legacy
continue; // we don't need that file at all
}
final String segmentId = IndexFileNames.parseSegmentName(meta.name());
final String extension = IndexFileNames.getExtension(meta.name());
assert FIELD_INFOS_FILE_EXTENSION.equals(extension) == false || IndexFileNames.stripExtension(IndexFileNames.stripSegmentName(meta.name())).isEmpty() : "FieldInfos are generational but updateable DV are not supported in elasticsearch";
if (IndexFileNames.SEGMENTS.equals(segmentId) || DEL_FILE_EXTENSION.equals(extension) || LIV_FILE_EXTENSION.equals(extension)) {
// only treat del files as per-commit files fnm files are generational but only for upgradable DV
perCommitStoreFiles.add(meta);
} else {
List<StoreFileMetaData> perSegStoreFiles = perSegment.get(segmentId);
if (perSegStoreFiles == null) {
perSegStoreFiles = new ArrayList<>();
perSegment.put(segmentId, perSegStoreFiles);
}
perSegStoreFiles.add(meta);
}
}
final ArrayList<StoreFileMetaData> identicalFiles = new ArrayList<>();
for (List<StoreFileMetaData> segmentFiles : Iterables.concat(perSegment.values(), Collections.singleton(perCommitStoreFiles))) {
identicalFiles.clear();
boolean consistent = true;
for (StoreFileMetaData meta : segmentFiles) {
StoreFileMetaData storeFileMetaData = recoveryTargetSnapshot.get(meta.name());
if (storeFileMetaData == null) {
consistent = false;
missing.add(meta);
} else if (storeFileMetaData.isSame(meta) == false) {
consistent = false;
different.add(meta);
} else {
identicalFiles.add(meta);
}
}
if (consistent) {
identical.addAll(identicalFiles);
} else {
// make sure all files are added - this can happen if only the deletes are different
different.addAll(identicalFiles);
}
}
RecoveryDiff recoveryDiff = new RecoveryDiff(identical.build(), different.build(), missing.build());
assert recoveryDiff.size() == this.metadata.size() - (metadata.containsKey(IndexFileNames.OLD_SEGMENTS_GEN) ? 1 : 0)
: "some files are missing recoveryDiff size: [" + recoveryDiff.size() + "] metadata size: [" + this.metadata.size() + "] contains segments.gen: [" + metadata.containsKey(IndexFileNames.OLD_SEGMENTS_GEN) + "]";
return recoveryDiff;
}
/**
* Returns the number of files in this snapshot
*/
public int size() {
return metadata.size();
}
public static MetadataSnapshot read(StreamInput in) throws IOException {
MetadataSnapshot storeFileMetaDatas = new MetadataSnapshot();
storeFileMetaDatas.readFrom(in);
return storeFileMetaDatas;
}
@Override
public void readFrom(StreamInput in) throws IOException {
int size = in.readVInt();
ImmutableMap.Builder<String, StoreFileMetaData> builder = ImmutableMap.builder();
for (int i = 0; i < size; i++) {
StoreFileMetaData meta = StoreFileMetaData.readStoreFileMetaData(in);
builder.put(meta.name(), meta);
}
this.metadata = builder.build();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(this.metadata.size());
for (StoreFileMetaData meta : this) {
meta.writeTo(out);
}
}
/**
* Returns true iff this metadata contains the given file.
*/
public boolean contains(String existingFile) {
return metadata.containsKey(existingFile);
}
}
/**
* A class representing the diff between a recovery source and recovery target
*
* @see MetadataSnapshot#recoveryDiff(org.elasticsearch.index.store.Store.MetadataSnapshot)
*/
public static final class RecoveryDiff {
/**
* Files that exist in both snapshots and they can be considered the same ie. they don't need to be recovered
*/
public final List<StoreFileMetaData> identical;
/**
* Files that exist in both snapshots but their they are not identical
*/
public final List<StoreFileMetaData> different;
/**
* Files that exist in the source but not in the target
*/
public final List<StoreFileMetaData> missing;
RecoveryDiff(List<StoreFileMetaData> identical, List<StoreFileMetaData> different, List<StoreFileMetaData> missing) {
this.identical = identical;
this.different = different;
this.missing = missing;
}
/**
* Returns the sum of the files in this diff.
*/
public int size() {
return identical.size() + different.size() + missing.size();
}
@Override
public String toString() {
return "RecoveryDiff{" +
"identical=" + identical +
", different=" + different +
", missing=" + missing +
'}';
}
}
public final static class LegacyChecksums {
private final Map<String, String> legacyChecksums = new HashMap<>();
public void add(StoreFileMetaData metaData) throws IOException {
if (metaData.hasLegacyChecksum()) {
synchronized (this) {
// we don't add checksums if they were written by LUCENE_48... now we are using the build in mechanism.
legacyChecksums.put(metaData.name(), metaData.checksum());
}
}
}
public synchronized void write(Store store) throws IOException {
synchronized (store.directory) {
Tuple<Map<String, String>, Long> tuple = MetadataSnapshot.readLegacyChecksums(store.directory);
tuple.v1().putAll(legacyChecksums);
if (!tuple.v1().isEmpty()) {
writeChecksums(store.directory, tuple.v1(), tuple.v2());
}
}
}
synchronized void writeChecksums(Directory directory, Map<String, String> checksums, long lastVersion) throws IOException {
long nextVersion = System.currentTimeMillis();
while (nextVersion <= lastVersion) {
nextVersion = System.currentTimeMillis();
}
final String checksumName = CHECKSUMS_PREFIX + nextVersion;
try (IndexOutput output = directory.createOutput(checksumName, IOContext.DEFAULT)) {
output.writeInt(0); // version
output.writeStringStringMap(checksums);
}
directory.sync(Collections.singleton(checksumName));
MetadataSnapshot.cleanLegacyChecksums(directory, nextVersion);
}
public void clear() {
this.legacyChecksums.clear();
}
public void remove(String name) {
legacyChecksums.remove(name);
}
}
public static final String CHECKSUMS_PREFIX = "_checksums-";
public static final boolean isChecksum(String name) {
// TODO can we drowp .cks
return name.startsWith(CHECKSUMS_PREFIX) || name.endsWith(".cks"); // bwcomapt - .cks used to be a previous checksum file
}
/**
* Produces a string representation of the given digest value.
*/
public static String digestToString(long digest) {
return Long.toString(digest, Character.MAX_RADIX);
}
static class LuceneVerifyingIndexOutput extends VerifyingIndexOutput {
private final StoreFileMetaData metadata;
private long writtenBytes;
private final long checksumPosition;
private String actualChecksum;
LuceneVerifyingIndexOutput(StoreFileMetaData metadata, IndexOutput out) {
super(out);
this.metadata = metadata;
checksumPosition = metadata.length() - 8; // the last 8 bytes are the checksum
}
@Override
public void verify() throws IOException {
if (metadata.checksum().equals(actualChecksum) && writtenBytes == metadata.length()) {
return;
}
throw new CorruptIndexException("verification failed (hardware problem?) : expected=" + metadata.checksum() +
" actual=" + actualChecksum + " writtenLength=" + writtenBytes + " expectedLength=" + metadata.length() +
" (resource=" + metadata.toString() + ")", "VerifyingIndexOutput(" + metadata.name() + ")");
}
@Override
public void writeByte(byte b) throws IOException {
if (writtenBytes++ == checksumPosition) {
readAndCompareChecksum();
}
out.writeByte(b);
}
private void readAndCompareChecksum() throws IOException {
actualChecksum = digestToString(getChecksum());
if (!metadata.checksum().equals(actualChecksum)) {
throw new CorruptIndexException("checksum failed (hardware problem?) : expected=" + metadata.checksum() +
" actual=" + actualChecksum +
" (resource=" + metadata.toString() + ")", "VerifyingIndexOutput(" + metadata.name() + ")");
}
}
@Override
public void writeBytes(byte[] b, int offset, int length) throws IOException {
if (writtenBytes + length > checksumPosition && actualChecksum == null) {
assert writtenBytes <= checksumPosition;
final int bytesToWrite = (int) (checksumPosition - writtenBytes);
out.writeBytes(b, offset, bytesToWrite);
readAndCompareChecksum();
offset += bytesToWrite;
length -= bytesToWrite;
writtenBytes += bytesToWrite;
}
out.writeBytes(b, offset, length);
writtenBytes += length;
}
}
/**
* Index input that calculates checksum as data is read from the input.
* <p/>
* This class supports random access (it is possible to seek backward and forward) in order to accommodate retry
* mechanism that is used in some repository plugins (S3 for example). However, the checksum is only calculated on
* the first read. All consecutive reads of the same data are not used to calculate the checksum.
*/
static class VerifyingIndexInput extends ChecksumIndexInput {
private final IndexInput input;
private final Checksum digest;
private final long checksumPosition;
private final byte[] checksum = new byte[8];
private long verifiedPosition = 0;
public VerifyingIndexInput(IndexInput input) {
this(input, new BufferedChecksum(new CRC32()));
}
public VerifyingIndexInput(IndexInput input, Checksum digest) {
super("VerifyingIndexInput(" + input + ")");
this.input = input;
this.digest = digest;
checksumPosition = input.length() - 8;
}
@Override
public byte readByte() throws IOException {
long pos = input.getFilePointer();
final byte b = input.readByte();
pos++;
if (pos > verifiedPosition) {
if (pos <= checksumPosition) {
digest.update(b);
} else {
checksum[(int) (pos - checksumPosition - 1)] = b;
}
verifiedPosition = pos;
}
return b;
}
@Override
public void readBytes(byte[] b, int offset, int len)
throws IOException {
long pos = input.getFilePointer();
input.readBytes(b, offset, len);
if (pos + len > verifiedPosition) {
// Conversion to int is safe here because (verifiedPosition - pos) can be at most len, which is integer
int alreadyVerified = (int) Math.max(0, verifiedPosition - pos);
if (pos < checksumPosition) {
if (pos + len < checksumPosition) {
digest.update(b, offset + alreadyVerified, len - alreadyVerified);
} else {
int checksumOffset = (int) (checksumPosition - pos);
if (checksumOffset - alreadyVerified > 0) {
digest.update(b, offset + alreadyVerified, checksumOffset - alreadyVerified);
}
System.arraycopy(b, offset + checksumOffset, checksum, 0, len - checksumOffset);
}
} else {
// Conversion to int is safe here because checksumPosition is (file length - 8) so
// (pos - checksumPosition) cannot be bigger than 8 unless we are reading after the end of file
assert pos - checksumPosition < 8;
System.arraycopy(b, offset, checksum, (int) (pos - checksumPosition), len);
}
verifiedPosition = pos + len;
}
}
@Override
public long getChecksum() {
return digest.getValue();
}
@Override
public void seek(long pos) throws IOException {
if (pos < verifiedPosition) {
// going within verified region - just seek there
input.seek(pos);
} else {
if (verifiedPosition > getFilePointer()) {
// portion of the skip region is verified and portion is not
// skipping the verified portion
input.seek(verifiedPosition);
// and checking unverified
skipBytes(pos - verifiedPosition);
} else {
skipBytes(pos - getFilePointer());
}
}
}
@Override
public void close() throws IOException {
input.close();
}
@Override
public long getFilePointer() {
return input.getFilePointer();
}
@Override
public long length() {
return input.length();
}
@Override
public IndexInput clone() {
throw new UnsupportedOperationException();
}
@Override
public IndexInput slice(String sliceDescription, long offset, long length) throws IOException {
throw new UnsupportedOperationException();
}
public long getStoredChecksum() {
return new ByteArrayDataInput(checksum).readLong();
}
public long verify() throws CorruptIndexException {
long storedChecksum = getStoredChecksum();
if (getChecksum() == storedChecksum) {
return storedChecksum;
}
throw new CorruptIndexException("verification failed : calculated=" + Store.digestToString(getChecksum()) +
" stored=" + Store.digestToString(storedChecksum), this);
}
}
public void deleteQuiet(String... files) {
for (String file : files) {
try {
directory().deleteFile(file);
} catch (Throwable ex) {
// ignore
}
}
}
/**
* Marks this store as corrupted. This method writes a <tt>corrupted_${uuid}</tt> file containing the given exception
* message. If a store contains a <tt>corrupted_${uuid}</tt> file {@link #isMarkedCorrupted()} will return <code>true</code>.
*/
public void markStoreCorrupted(IOException exception) throws IOException {
ensureOpen();
if (!isMarkedCorrupted()) {
String uuid = CORRUPTED + Strings.randomBase64UUID();
try (IndexOutput output = this.directory().createOutput(uuid, IOContext.DEFAULT)) {
CodecUtil.writeHeader(output, CODEC, VERSION);
output.writeString(ExceptionsHelper.detailedMessage(exception, true, 0)); // handles null exception
output.writeString(ExceptionsHelper.stackTrace(exception));
CodecUtil.writeFooter(output);
} catch (IOException ex) {
logger.warn("Can't mark store as corrupted", ex);
}
directory().sync(Collections.singleton(uuid));
}
}
/**
* A listener that is executed once the store is closed and all references to it are released
*/
public static interface OnClose extends Callback<ShardLock> {
static final OnClose EMPTY = new OnClose() {
/**
* This method is called while the provided {@link org.elasticsearch.env.ShardLock} is held.
* This method is only called once after all resources for a store are released.
*/
@Override
public void handle(ShardLock Lock) {
}
};
}
}
| src/main/java/org/elasticsearch/index/store/Store.java | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.store;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.index.*;
import org.apache.lucene.store.*;
import org.apache.lucene.util.*;
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.lucene.Directories;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.lucene.store.InputStreamIndexInput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.Callback;
import org.elasticsearch.common.util.concurrent.AbstractRefCounted;
import org.elasticsearch.common.util.concurrent.RefCounted;
import org.elasticsearch.env.ShardLock;
import org.elasticsearch.index.settings.IndexSettings;
import org.elasticsearch.index.shard.AbstractIndexShardComponent;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.store.distributor.Distributor;
import java.io.*;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
/**
* A Store provides plain access to files written by an elasticsearch index shard. Each shard
* has a dedicated store that is uses to access Lucene's Directory which represents the lowest level
* of file abstraction in Lucene used to read and write Lucene indices.
* This class also provides access to metadata information like checksums for committed files. A committed
* file is a file that belongs to a segment written by a Lucene commit. Files that have not been committed
* ie. created during a merge or a shard refresh / NRT reopen are not considered in the MetadataSnapshot.
* <p/>
* Note: If you use a store it's reference count should be increased before using it by calling #incRef and a
* corresponding #decRef must be called in a try/finally block to release the store again ie.:
* <pre>
* store.incRef();
* try {
* // use the store...
*
* } finally {
* store.decRef();
* }
* </pre>
*/
public class Store extends AbstractIndexShardComponent implements Closeable, RefCounted {
private static final String CODEC = "store";
private static final int VERSION_STACK_TRACE = 1; // we write the stack trace too since 1.4.0
private static final int VERSION_START = 0;
private static final int VERSION = VERSION_STACK_TRACE;
private static final String CORRUPTED = "corrupted_";
private final AtomicBoolean isClosed = new AtomicBoolean(false);
private final DirectoryService directoryService;
private final StoreDirectory directory;
private final ReentrantReadWriteLock metadataLock = new ReentrantReadWriteLock();
private final ShardLock shardLock;
private final OnClose onClose;
private final AbstractRefCounted refCounter = new AbstractRefCounted("store") {
@Override
protected void closeInternal() {
// close us once we are done
Store.this.closeInternal();
}
};
public Store(ShardId shardId, @IndexSettings Settings indexSettings, DirectoryService directoryService, Distributor distributor, ShardLock shardLock) throws IOException {
this(shardId, indexSettings, directoryService, distributor, shardLock, OnClose.EMPTY);
}
@Inject
public Store(ShardId shardId, @IndexSettings Settings indexSettings, DirectoryService directoryService, Distributor distributor, ShardLock shardLock, OnClose onClose) throws IOException {
super(shardId, indexSettings);
this.directoryService = directoryService;
this.directory = new StoreDirectory(directoryService.newFromDistributor(distributor), Loggers.getLogger("index.store.deletes", indexSettings, shardId));
this.shardLock = shardLock;
this.onClose = onClose;
assert onClose != null;
assert shardLock != null;
assert shardLock.getShardId().equals(shardId);
}
public Directory directory() {
ensureOpen();
return directory;
}
/**
* Returns the last committed segments info for this store
*
* @throws IOException if the index is corrupted or the segments file is not present
*/
public SegmentInfos readLastCommittedSegmentsInfo() throws IOException {
return readSegmentsInfo(null, directory());
}
/**
* Returns the segments info for the given commit or for the latest commit if the given commit is <code>null</code>
*
* @throws IOException if the index is corrupted or the segments file is not present
*/
private static SegmentInfos readSegmentsInfo(IndexCommit commit, Directory directory) throws IOException {
try {
return commit == null ? Lucene.readSegmentInfos(directory) : Lucene.readSegmentInfos(commit, directory);
} catch (EOFException eof) {
// TODO this should be caught by lucene - EOF is almost certainly an index corruption
throw new CorruptIndexException("Read past EOF while reading segment infos", "commit(" + commit + ")", eof);
} catch (IOException exception) {
throw exception; // IOExceptions like too many open files are not necessarily a corruption - just bubble it up
} catch (Exception ex) {
throw new CorruptIndexException("Hit unexpected exception while reading segment infos", "commit(" + commit + ")", ex);
}
}
final void ensureOpen() { // for testing
if (this.refCounter.refCount() <= 0) {
throw new AlreadyClosedException("store is already closed");
}
}
/**
* Returns a new MetadataSnapshot for the latest commit in this store or
* an empty snapshot if no index exists or can not be opened.
*
* @throws CorruptIndexException if the lucene index is corrupted. This can be caused by a checksum mismatch or an
* unexpected exception when opening the index reading the segments file.
*/
public MetadataSnapshot getMetadataOrEmpty() throws IOException {
try {
return getMetadata(null);
} catch (IndexNotFoundException ex) {
// that's fine - happens all the time no need to log
} catch (FileNotFoundException | NoSuchFileException ex) {
logger.info("Failed to open / find files while reading metadata snapshot");
}
return MetadataSnapshot.EMPTY;
}
/**
* Returns a new MetadataSnapshot for the latest commit in this store.
*
* @throws CorruptIndexException if the lucene index is corrupted. This can be caused by a checksum mismatch or an
* unexpected exception when opening the index reading the segments file.
* @throws FileNotFoundException if one or more files referenced by a commit are not present.
* @throws NoSuchFileException if one or more files referenced by a commit are not present.
* @throws IndexNotFoundException if no index / valid commit-point can be found in this store
*/
public MetadataSnapshot getMetadata() throws IOException {
return getMetadata(null);
}
/**
* Returns a new MetadataSnapshot for the given commit. If the given commit is <code>null</code>
* the latest commit point is used.
*
* @throws CorruptIndexException if the lucene index is corrupted. This can be caused by a checksum mismatch or an
* unexpected exception when opening the index reading the segments file.
* @throws FileNotFoundException if one or more files referenced by a commit are not present.
* @throws NoSuchFileException if one or more files referenced by a commit are not present.
* @throws IndexNotFoundException if the commit point can't be found in this store
*/
public MetadataSnapshot getMetadata(IndexCommit commit) throws IOException {
ensureOpen();
failIfCorrupted();
metadataLock.readLock().lock();
try {
return new MetadataSnapshot(commit, directory, logger);
} catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
markStoreCorrupted(ex);
throw ex;
} finally {
metadataLock.readLock().unlock();
}
}
/**
* Renames all the given files form the key of the map to the
* value of the map. All successfully renamed files are removed from the map in-place.
*/
public void renameFilesSafe(Map<String, String> tempFileMap) throws IOException {
// this works just like a lucene commit - we rename all temp files and once we successfully
// renamed all the segments we rename the commit to ensure we don't leave half baked commits behind.
final Map.Entry<String, String>[] entries = tempFileMap.entrySet().toArray(new Map.Entry[tempFileMap.size()]);
ArrayUtil.timSort(entries, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
String left = o1.getValue();
String right = o2.getValue();
if (left.startsWith(IndexFileNames.SEGMENTS) || right.startsWith(IndexFileNames.SEGMENTS)) {
if (left.startsWith(IndexFileNames.SEGMENTS) == false) {
return -1;
} else if (right.startsWith(IndexFileNames.SEGMENTS) == false) {
return 1;
}
}
return left.compareTo(right);
}
});
metadataLock.writeLock().lock();
// we make sure that nobody fetches the metadata while we do this rename operation here to ensure we don't
// get exceptions if files are still open.
try {
for (Map.Entry<String, String> entry : entries) {
String tempFile = entry.getKey();
String origFile = entry.getValue();
// first, go and delete the existing ones
try {
directory.deleteFile(origFile);
} catch (FileNotFoundException | NoSuchFileException e) {
} catch (Throwable ex) {
logger.debug("failed to delete file [{}]", ex, origFile);
}
// now, rename the files... and fail it it won't work
this.renameFile(tempFile, origFile);
final String remove = tempFileMap.remove(tempFile);
assert remove != null;
}
} finally {
metadataLock.writeLock().unlock();
}
}
/**
* Deletes the content of a shard store. Be careful calling this!.
*/
public void deleteContent() throws IOException {
ensureOpen();
final String[] files = directory.listAll();
final List<IOException> exceptions = new ArrayList<>();
for (String file : files) {
try {
directory.deleteFile(file);
} catch (NoSuchFileException | FileNotFoundException e) {
// ignore
} catch (IOException e) {
exceptions.add(e);
}
}
ExceptionsHelper.rethrowAndSuppress(exceptions);
}
public StoreStats stats() throws IOException {
ensureOpen();
return new StoreStats(Directories.estimateSize(directory), directoryService.throttleTimeInNanos());
}
public void renameFile(String from, String to) throws IOException {
ensureOpen();
directory.renameFile(from, to);
}
/**
* Increments the refCount of this Store instance. RefCounts are used to determine when a
* Store can be closed safely, i.e. as soon as there are no more references. Be sure to always call a
* corresponding {@link #decRef}, in a finally clause; otherwise the store may never be closed. Note that
* {@link #close} simply calls decRef(), which means that the Store will not really be closed until {@link
* #decRef} has been called for all outstanding references.
* <p/>
* Note: Close can safely be called multiple times.
*
* @throws AlreadyClosedException iff the reference counter can not be incremented.
* @see #decRef
* @see #tryIncRef()
*/
@Override
public final void incRef() {
refCounter.incRef();
}
/**
* Tries to increment the refCount of this Store instance. This method will return <tt>true</tt> iff the refCount was
* incremented successfully otherwise <tt>false</tt>. RefCounts are used to determine when a
* Store can be closed safely, i.e. as soon as there are no more references. Be sure to always call a
* corresponding {@link #decRef}, in a finally clause; otherwise the store may never be closed. Note that
* {@link #close} simply calls decRef(), which means that the Store will not really be closed until {@link
* #decRef} has been called for all outstanding references.
* <p/>
* Note: Close can safely be called multiple times.
*
* @see #decRef()
* @see #incRef()
*/
@Override
public final boolean tryIncRef() {
return refCounter.tryIncRef();
}
/**
* Decreases the refCount of this Store instance.If the refCount drops to 0, then this
* store is closed.
*
* @see #incRef
*/
@Override
public final void decRef() {
refCounter.decRef();
}
@Override
public void close() {
if (isClosed.compareAndSet(false, true)) {
// only do this once!
decRef();
logger.debug("store reference count on close: " + refCounter.refCount());
}
}
private void closeInternal() {
try {
try {
directory.innerClose(); // this closes the distributorDirectory as well
} finally {
onClose.handle(shardLock);
}
} catch (IOException e) {
logger.debug("failed to close directory", e);
} finally {
IOUtils.closeWhileHandlingException(shardLock);
}
}
/**
* Reads a MetadataSnapshot from the given index locations or returns an empty snapshot if it can't be read.
*
* @throws IOException if the index we try to read is corrupted
*/
public static MetadataSnapshot readMetadataSnapshot(Path[] indexLocations, ESLogger logger) throws IOException {
final Directory[] dirs = new Directory[indexLocations.length];
try {
for (int i = 0; i < indexLocations.length; i++) {
dirs[i] = new SimpleFSDirectory(indexLocations[i]);
}
DistributorDirectory dir = new DistributorDirectory(dirs);
failIfCorrupted(dir, new ShardId("", 1));
return new MetadataSnapshot(null, dir, logger);
} catch (IndexNotFoundException ex) {
// that's fine - happens all the time no need to log
} catch (FileNotFoundException | NoSuchFileException ex) {
logger.info("Failed to open / find files while reading metadata snapshot");
} finally {
IOUtils.close(dirs);
}
return MetadataSnapshot.EMPTY;
}
/**
* The returned IndexOutput might validate the files checksum if the file has been written with a newer lucene version
* and the metadata holds the necessary information to detect that it was been written by Lucene 4.8 or newer. If it has only
* a legacy checksum, returned IndexOutput will not verify the checksum.
* <p/>
* Note: Checksums are calculated nevertheless since lucene does it by default sicne version 4.8.0. This method only adds the
* verification against the checksum in the given metadata and does not add any significant overhead.
*/
public IndexOutput createVerifyingOutput(String fileName, final StoreFileMetaData metadata, final IOContext context) throws IOException {
IndexOutput output = directory().createOutput(fileName, context);
boolean success = false;
try {
if (metadata.hasLegacyChecksum()) {
logger.debug("create legacy adler32 output for {}", fileName);
output = new LegacyVerification.Adler32VerifyingIndexOutput(output, metadata.checksum(), metadata.length());
} else if (metadata.checksum() == null) {
// TODO: when the file is a segments_N, we can still CRC-32 + length for more safety
// its had that checksum forever.
logger.debug("create legacy length-only output for {}", fileName);
output = new LegacyVerification.LengthVerifyingIndexOutput(output, metadata.length());
} else {
assert metadata.writtenBy() != null;
assert metadata.writtenBy().onOrAfter(Version.LUCENE_4_8);
output = new LuceneVerifyingIndexOutput(metadata, output);
}
success = true;
} finally {
if (success == false) {
IOUtils.closeWhileHandlingException(output);
}
}
return output;
}
public static void verify(IndexOutput output) throws IOException {
if (output instanceof VerifyingIndexOutput) {
((VerifyingIndexOutput) output).verify();
}
}
public IndexInput openVerifyingInput(String filename, IOContext context, StoreFileMetaData metadata) throws IOException {
if (metadata.hasLegacyChecksum() || metadata.checksum() == null) {
logger.debug("open legacy input for {}", filename);
return directory().openInput(filename, context);
}
assert metadata.writtenBy() != null;
assert metadata.writtenBy().onOrAfter(Version.LUCENE_4_8_0);
return new VerifyingIndexInput(directory().openInput(filename, context));
}
public static void verify(IndexInput input) throws IOException {
if (input instanceof VerifyingIndexInput) {
((VerifyingIndexInput) input).verify();
}
}
public boolean checkIntegrityNoException(StoreFileMetaData md) {
return checkIntegrityNoException(md, directory());
}
public static boolean checkIntegrityNoException(StoreFileMetaData md, Directory directory) {
try {
checkIntegrity(md, directory);
return true;
} catch (IOException e) {
return false;
}
}
public static void checkIntegrity(final StoreFileMetaData md, final Directory directory) throws IOException {
try (IndexInput input = directory.openInput(md.name(), IOContext.READONCE)) {
if (input.length() != md.length()) { // first check the length no matter how old this file is
throw new CorruptIndexException("expected length=" + md.length() + " != actual length: " + input.length() + " : file truncated?", input);
}
if (md.writtenBy() != null && md.writtenBy().onOrAfter(Version.LUCENE_4_8_0)) {
// throw exception if the file is corrupt
String checksum = Store.digestToString(CodecUtil.checksumEntireFile(input));
// throw exception if metadata is inconsistent
if (!checksum.equals(md.checksum())) {
throw new CorruptIndexException("inconsistent metadata: lucene checksum=" + checksum +
", metadata checksum=" + md.checksum(), input);
}
} else if (md.hasLegacyChecksum()) {
// legacy checksum verification - no footer that we need to omit in the checksum!
final Checksum checksum = new Adler32();
final byte[] buffer = new byte[md.length() > 4096 ? 4096 : (int) md.length()];
final long len = input.length();
long read = 0;
while (len > read) {
final long bytesLeft = len - read;
final int bytesToRead = bytesLeft < buffer.length ? (int) bytesLeft : buffer.length;
input.readBytes(buffer, 0, bytesToRead, false);
checksum.update(buffer, 0, bytesToRead);
read += bytesToRead;
}
String adler32 = Store.digestToString(checksum.getValue());
if (!adler32.equals(md.checksum())) {
throw new CorruptIndexException("checksum failed (hardware problem?) : expected=" + md.checksum() +
" actual=" + adler32, input);
}
}
}
}
public boolean isMarkedCorrupted() throws IOException {
ensureOpen();
/* marking a store as corrupted is basically adding a _corrupted to all
* the files. This prevent
*/
final String[] files = directory().listAll();
for (String file : files) {
if (file.startsWith(CORRUPTED)) {
return true;
}
}
return false;
}
public void failIfCorrupted() throws IOException {
ensureOpen();
failIfCorrupted(directory, shardId);
}
private static final void failIfCorrupted(Directory directory, ShardId shardId) throws IOException {
final String[] files = directory.listAll();
List<CorruptIndexException> ex = new ArrayList<>();
for (String file : files) {
if (file.startsWith(CORRUPTED)) {
try (ChecksumIndexInput input = directory.openChecksumInput(file, IOContext.READONCE)) {
int version = CodecUtil.checkHeader(input, CODEC, VERSION_START, VERSION);
String msg = input.readString();
StringBuilder builder = new StringBuilder(shardId.toString());
builder.append(" Preexisting corrupted index [");
builder.append(file).append("] caused by: ");
builder.append(msg);
if (version == VERSION_STACK_TRACE) {
builder.append(System.lineSeparator());
builder.append(input.readString());
}
ex.add(new CorruptIndexException(builder.toString(), "preexisting_corruption"));
CodecUtil.checkFooter(input);
}
}
}
if (ex.isEmpty() == false) {
ExceptionsHelper.rethrowAndSuppress(ex);
}
}
/**
* This method deletes every file in this store that is not contained in the given source meta data or is a
* legacy checksum file. After the delete it pulls the latest metadata snapshot from the store and compares it
* to the given snapshot. If the snapshots are inconsistent an illegal state exception is thrown
*
* @param reason the reason for this cleanup operation logged for each deleted file
* @param sourceMetaData the metadata used for cleanup. all files in this metadata should be kept around.
* @throws IOException if an IOException occurs
* @throws ElasticsearchIllegalStateException if the latest snapshot in this store differs from the given one after the cleanup.
*/
public void cleanupAndVerify(String reason, MetadataSnapshot sourceMetaData) throws IOException {
failIfCorrupted();
metadataLock.writeLock().lock();
try {
final StoreDirectory dir = directory;
for (String existingFile : dir.listAll()) {
// don't delete snapshot file, or the checksums file (note, this is extra protection since the Store won't delete checksum)
if (!sourceMetaData.contains(existingFile) && !Store.isChecksum(existingFile)) {
try {
dir.deleteFile(reason, existingFile);
} catch (Exception e) {
// ignore, we don't really care, will get deleted later on
}
}
}
final Store.MetadataSnapshot metadataOrEmpty = getMetadata();
verifyAfterCleanup(sourceMetaData, metadataOrEmpty);
} finally {
metadataLock.writeLock().unlock();
}
}
// pkg private for testing
final void verifyAfterCleanup(MetadataSnapshot sourceMetaData, MetadataSnapshot targetMetaData) {
final RecoveryDiff recoveryDiff = targetMetaData.recoveryDiff(sourceMetaData);
if (recoveryDiff.identical.size() != recoveryDiff.size()) {
if (recoveryDiff.missing.isEmpty()) {
for (StoreFileMetaData meta : recoveryDiff.different) {
StoreFileMetaData local = targetMetaData.get(meta.name());
StoreFileMetaData remote = sourceMetaData.get(meta.name());
// if we have different files the they must have no checksums otherwise something went wrong during recovery.
// we have that problem when we have an empty index is only a segments_1 file then we can't tell if it's a Lucene 4.8 file
// and therefore no checksum. That isn't much of a problem since we simply copy it over anyway but those files come out as
// different in the diff. That's why we have to double check here again if the rest of it matches.
// all is fine this file is just part of a commit or a segment that is different
final boolean same = local.isSame(remote);
// this check ensures that the two files are consistent ie. if we don't have checksums only the rest needs to match we are just
// verifying that we are consistent on both ends source and target
final boolean hashAndLengthEqual = (
local.checksum() == null
&& remote.checksum() == null
&& local.hash().equals(remote.hash())
&& local.length() == remote.length());
final boolean consistent = hashAndLengthEqual || same;
if (consistent == false) {
logger.debug("Files are different on the recovery target: {} ", recoveryDiff);
throw new ElasticsearchIllegalStateException("local version: " + local + " is different from remote version after recovery: " + remote, null);
}
}
} else {
logger.debug("Files are missing on the recovery target: {} ", recoveryDiff);
throw new ElasticsearchIllegalStateException("Files are missing on the recovery target: [different="
+ recoveryDiff.different + ", missing=" + recoveryDiff.missing + ']', null);
}
}
}
/**
* Returns the current reference count.
*/
public int refCount() {
return refCounter.refCount();
}
private static final class StoreDirectory extends FilterDirectory {
private final ESLogger deletesLogger;
StoreDirectory(Directory delegateDirectory, ESLogger deletesLogger) throws IOException {
super(delegateDirectory);
this.deletesLogger = deletesLogger;
}
@Override
public void close() throws IOException {
assert false : "Nobody should close this directory except of the Store itself";
}
public void deleteFile(String msg, String name) throws IOException {
deletesLogger.trace("{}: delete file {}", msg, name);
super.deleteFile(name);
}
@Override
public void deleteFile(String name) throws IOException {
deleteFile("StoreDirectory.deleteFile", name);
}
private void innerClose() throws IOException {
super.close();
}
@Override
public String toString() {
return "store(" + in.toString() + ")";
}
}
/** Log that we are about to delete this file, to the index.store.deletes component. */
public void deleteFile(String msg, String storeFile) throws IOException {
directory.deleteFile(msg, storeFile);
}
/**
* Represents a snapshot of the current directory build from the latest Lucene commit.
* Only files that are part of the last commit are considered in this datastrucutre.
* For backwards compatibility the snapshot might include legacy checksums that
* are derived from a dedicated checksum file written by older elasticsearch version pre 1.3
* <p/>
* Note: This class will ignore the <tt>segments.gen</tt> file since it's optional and might
* change concurrently for safety reasons.
*
* @see StoreFileMetaData
*/
public final static class MetadataSnapshot implements Iterable<StoreFileMetaData>, Streamable {
private static final ESLogger logger = Loggers.getLogger(MetadataSnapshot.class);
private static final Version FIRST_LUCENE_CHECKSUM_VERSION = Version.LUCENE_4_8;
// we stopped writing legacy checksums in 1.3.0 so all segments here must use the new CRC32 version
private static final Version FIRST_ES_CRC32_VERSION = org.elasticsearch.Version.V_1_3_0.luceneVersion;
private Map<String, StoreFileMetaData> metadata;
public static final MetadataSnapshot EMPTY = new MetadataSnapshot();
public MetadataSnapshot(Map<String, StoreFileMetaData> metadata) {
this.metadata = metadata;
}
MetadataSnapshot() {
this.metadata = Collections.emptyMap();
}
MetadataSnapshot(IndexCommit commit, Directory directory, ESLogger logger) throws IOException {
metadata = buildMetadata(commit, directory, logger);
}
ImmutableMap<String, StoreFileMetaData> buildMetadata(IndexCommit commit, Directory directory, ESLogger logger) throws IOException {
ImmutableMap.Builder<String, StoreFileMetaData> builder = ImmutableMap.builder();
Map<String, String> checksumMap = readLegacyChecksums(directory).v1();
try {
final SegmentInfos segmentCommitInfos = Store.readSegmentsInfo(commit, directory);
Version maxVersion = Version.LUCENE_4_0; // we don't know which version was used to write so we take the max version.
for (SegmentCommitInfo info : segmentCommitInfos) {
final Version version = info.info.getVersion();
if (version == null) {
// version is written since 3.1+: we should have already hit IndexFormatTooOld.
throw new IllegalArgumentException("expected valid version value: " + info.info.toString());
}
if (version.onOrAfter(maxVersion)) {
maxVersion = version;
}
for (String file : info.files()) {
String legacyChecksum = checksumMap.get(file);
if (version.onOrAfter(FIRST_LUCENE_CHECKSUM_VERSION)) {
checksumFromLuceneFile(directory, file, builder, logger, version, SEGMENT_INFO_EXTENSION.equals(IndexFileNames.getExtension(file)));
} else {
builder.put(file, new StoreFileMetaData(file, directory.fileLength(file), legacyChecksum, version));
}
}
}
final String segmentsFile = segmentCommitInfos.getSegmentsFileName();
String legacyChecksum = checksumMap.get(segmentsFile);
if (maxVersion.onOrAfter(FIRST_LUCENE_CHECKSUM_VERSION)) {
checksumFromLuceneFile(directory, segmentsFile, builder, logger, maxVersion, true);
} else {
final BytesRefBuilder fileHash = new BytesRefBuilder();
final long length;
try (final IndexInput in = directory.openInput(segmentsFile, IOContext.READONCE)) {
length = in.length();
hashFile(fileHash, new InputStreamIndexInput(in, length), length);
}
builder.put(segmentsFile, new StoreFileMetaData(segmentsFile, length, legacyChecksum, maxVersion, fileHash.get()));
}
} catch (CorruptIndexException | IndexNotFoundException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
// we either know the index is corrupted or it's just not there
throw ex;
} catch (Throwable ex) {
try {
// Lucene checks the checksum after it tries to lookup the codec etc.
// in that case we might get only IAE or similar exceptions while we are really corrupt...
// TODO we should check the checksum in lucene if we hit an exception
logger.warn("failed to build store metadata. checking segment info integrity (with commit [{}])",
ex, commit == null ? "no" : "yes");
Lucene.checkSegmentInfoIntegrity(directory);
} catch (CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException cex) {
cex.addSuppressed(ex);
throw cex;
} catch (Throwable e) {
// ignore...
}
throw ex;
}
return builder.build();
}
/**
* Reads legacy checksum files found in the directory.
* <p/>
* Files are expected to start with _checksums- prefix
* followed by long file version. Only file with the highest version is read, all other files are ignored.
*
* @param directory the directory to read checksums from
* @return a map of file checksums and the checksum file version
* @throws IOException
*/
static Tuple<Map<String, String>, Long> readLegacyChecksums(Directory directory) throws IOException {
synchronized (directory) {
long lastFound = -1;
for (String name : directory.listAll()) {
if (!isChecksum(name)) {
continue;
}
long current = Long.parseLong(name.substring(CHECKSUMS_PREFIX.length()));
if (current > lastFound) {
lastFound = current;
}
}
if (lastFound > -1) {
try (IndexInput indexInput = directory.openInput(CHECKSUMS_PREFIX + lastFound, IOContext.READONCE)) {
indexInput.readInt(); // version
return new Tuple(indexInput.readStringStringMap(), lastFound);
}
}
return new Tuple(new HashMap<>(), -1l);
}
}
/**
* Deletes all checksum files with version lower than newVersion.
*
* @param directory the directory to clean
* @param newVersion the latest checksum file version
* @throws IOException
*/
static void cleanLegacyChecksums(Directory directory, long newVersion) throws IOException {
synchronized (directory) {
for (String name : directory.listAll()) {
if (isChecksum(name)) {
long current = Long.parseLong(name.substring(CHECKSUMS_PREFIX.length()));
if (current < newVersion) {
try {
directory.deleteFile(name);
} catch (IOException ex) {
logger.debug("can't delete old checksum file [{}]", ex, name);
}
}
}
}
}
}
private static void checksumFromLuceneFile(Directory directory, String file, ImmutableMap.Builder<String, StoreFileMetaData> builder, ESLogger logger, Version version, boolean readFileAsHash) throws IOException {
final String checksum;
final BytesRefBuilder fileHash = new BytesRefBuilder();
try (final IndexInput in = directory.openInput(file, IOContext.READONCE)) {
final long length;
try {
length = in.length();
if (length < CodecUtil.footerLength()) {
// truncated files trigger IAE if we seek negative... these files are really corrupted though
throw new CorruptIndexException("Can't retrieve checksum from file: " + file + " file length must be >= " + CodecUtil.footerLength() + " but was: " + in.length(), in);
}
if (readFileAsHash) {
final VerifyingIndexInput verifyingIndexInput = new VerifyingIndexInput(in); // additional safety we checksum the entire file we read the hash for...
hashFile(fileHash, new InputStreamIndexInput(verifyingIndexInput, length), length);
checksum = digestToString(verifyingIndexInput.verify());
} else {
checksum = digestToString(CodecUtil.retrieveChecksum(in));
}
} catch (Throwable ex) {
logger.debug("Can retrieve checksum from file [{}]", ex, file);
throw ex;
}
builder.put(file, new StoreFileMetaData(file, length, checksum, version, fileHash.get()));
}
}
/**
* Computes a strong hash value for small files. Note that this method should only be used for files < 1MB
*/
public static BytesRef hashFile(Directory directory, String file) throws IOException {
final BytesRefBuilder fileHash = new BytesRefBuilder();
try (final IndexInput in = directory.openInput(file, IOContext.READONCE)) {
hashFile(fileHash, new InputStreamIndexInput(in, in.length()), in.length());
}
return fileHash.get();
}
/**
* Computes a strong hash value for small files. Note that this method should only be used for files < 1MB
*/
public static void hashFile(BytesRefBuilder fileHash, InputStream in, long size) throws IOException {
final int len = (int) Math.min(1024 * 1024, size); // for safety we limit this to 1MB
fileHash.grow(len);
fileHash.setLength(len);
final int readBytes = Streams.readFully(in, fileHash.bytes(), 0, len);
assert readBytes == len : Integer.toString(readBytes) + " != " + Integer.toString(len);
assert fileHash.length() == len : Integer.toString(fileHash.length()) + " != " + Integer.toString(len);
}
@Override
public Iterator<StoreFileMetaData> iterator() {
return metadata.values().iterator();
}
public StoreFileMetaData get(String name) {
return metadata.get(name);
}
public Map<String, StoreFileMetaData> asMap() {
return metadata;
}
private static final String DEL_FILE_EXTENSION = "del"; // legacy delete file
private static final String LIV_FILE_EXTENSION = "liv"; // lucene 5 delete file
private static final String FIELD_INFOS_FILE_EXTENSION = "fnm";
private static final String SEGMENT_INFO_EXTENSION = "si";
/**
* Returns a diff between the two snapshots that can be used for recovery. The given snapshot is treated as the
* recovery target and this snapshot as the source. The returned diff will hold a list of files that are:
* <ul>
* <li>identical: they exist in both snapshots and they can be considered the same ie. they don't need to be recovered</li>
* <li>different: they exist in both snapshots but their they are not identical</li>
* <li>missing: files that exist in the source but not in the target</li>
* </ul>
* This method groups file into per-segment files and per-commit files. A file is treated as
* identical if and on if all files in it's group are identical. On a per-segment level files for a segment are treated
* as identical iff:
* <ul>
* <li>all files in this segment have the same checksum</li>
* <li>all files in this segment have the same length</li>
* <li>the segments <tt>.si</tt> files hashes are byte-identical Note: This is a using a perfect hash function, The metadata transfers the <tt>.si</tt> file content as it's hash</li>
* </ul>
* <p/>
* The <tt>.si</tt> file contains a lot of diagnostics including a timestamp etc. in the future there might be
* unique segment identifiers in there hardening this method further.
* <p/>
* The per-commit files handles very similar. A commit is composed of the <tt>segments_N</tt> files as well as generational files like
* deletes (<tt>_x_y.del</tt>) or field-info (<tt>_x_y.fnm</tt>) files. On a per-commit level files for a commit are treated
* as identical iff:
* <ul>
* <li>all files belonging to this commit have the same checksum</li>
* <li>all files belonging to this commit have the same length</li>
* <li>the segments file <tt>segments_N</tt> files hashes are byte-identical Note: This is a using a perfect hash function, The metadata transfers the <tt>segments_N</tt> file content as it's hash</li>
* </ul>
* <p/>
* NOTE: this diff will not contain the <tt>segments.gen</tt> file. This file is omitted on recovery.
*/
public RecoveryDiff recoveryDiff(MetadataSnapshot recoveryTargetSnapshot) {
final ImmutableList.Builder<StoreFileMetaData> identical = ImmutableList.builder();
final ImmutableList.Builder<StoreFileMetaData> different = ImmutableList.builder();
final ImmutableList.Builder<StoreFileMetaData> missing = ImmutableList.builder();
final Map<String, List<StoreFileMetaData>> perSegment = new HashMap<>();
final List<StoreFileMetaData> perCommitStoreFiles = new ArrayList<>();
for (StoreFileMetaData meta : this) {
if (IndexFileNames.OLD_SEGMENTS_GEN.equals(meta.name())) { // legacy
continue; // we don't need that file at all
}
final String segmentId = IndexFileNames.parseSegmentName(meta.name());
final String extension = IndexFileNames.getExtension(meta.name());
assert FIELD_INFOS_FILE_EXTENSION.equals(extension) == false || IndexFileNames.stripExtension(IndexFileNames.stripSegmentName(meta.name())).isEmpty() : "FieldInfos are generational but updateable DV are not supported in elasticsearch";
if (IndexFileNames.SEGMENTS.equals(segmentId) || DEL_FILE_EXTENSION.equals(extension) || LIV_FILE_EXTENSION.equals(extension)) {
// only treat del files as per-commit files fnm files are generational but only for upgradable DV
perCommitStoreFiles.add(meta);
} else {
List<StoreFileMetaData> perSegStoreFiles = perSegment.get(segmentId);
if (perSegStoreFiles == null) {
perSegStoreFiles = new ArrayList<>();
perSegment.put(segmentId, perSegStoreFiles);
}
perSegStoreFiles.add(meta);
}
}
final ArrayList<StoreFileMetaData> identicalFiles = new ArrayList<>();
for (List<StoreFileMetaData> segmentFiles : Iterables.concat(perSegment.values(), Collections.singleton(perCommitStoreFiles))) {
identicalFiles.clear();
boolean consistent = true;
for (StoreFileMetaData meta : segmentFiles) {
StoreFileMetaData storeFileMetaData = recoveryTargetSnapshot.get(meta.name());
if (storeFileMetaData == null) {
consistent = false;
missing.add(meta);
} else if (storeFileMetaData.isSame(meta) == false) {
consistent = false;
different.add(meta);
} else {
identicalFiles.add(meta);
}
}
if (consistent) {
identical.addAll(identicalFiles);
} else {
// make sure all files are added - this can happen if only the deletes are different
different.addAll(identicalFiles);
}
}
RecoveryDiff recoveryDiff = new RecoveryDiff(identical.build(), different.build(), missing.build());
assert recoveryDiff.size() == this.metadata.size() - (metadata.containsKey(IndexFileNames.OLD_SEGMENTS_GEN) ? 1 : 0)
: "some files are missing recoveryDiff size: [" + recoveryDiff.size() + "] metadata size: [" + this.metadata.size() + "] contains segments.gen: [" + metadata.containsKey(IndexFileNames.OLD_SEGMENTS_GEN) + "]";
return recoveryDiff;
}
/**
* Returns the number of files in this snapshot
*/
public int size() {
return metadata.size();
}
public static MetadataSnapshot read(StreamInput in) throws IOException {
MetadataSnapshot storeFileMetaDatas = new MetadataSnapshot();
storeFileMetaDatas.readFrom(in);
return storeFileMetaDatas;
}
@Override
public void readFrom(StreamInput in) throws IOException {
int size = in.readVInt();
ImmutableMap.Builder<String, StoreFileMetaData> builder = ImmutableMap.builder();
for (int i = 0; i < size; i++) {
StoreFileMetaData meta = StoreFileMetaData.readStoreFileMetaData(in);
builder.put(meta.name(), meta);
}
this.metadata = builder.build();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(this.metadata.size());
for (StoreFileMetaData meta : this) {
meta.writeTo(out);
}
}
/**
* Returns true iff this metadata contains the given file.
*/
public boolean contains(String existingFile) {
return metadata.containsKey(existingFile);
}
}
/**
* A class representing the diff between a recovery source and recovery target
*
* @see MetadataSnapshot#recoveryDiff(org.elasticsearch.index.store.Store.MetadataSnapshot)
*/
public static final class RecoveryDiff {
/**
* Files that exist in both snapshots and they can be considered the same ie. they don't need to be recovered
*/
public final List<StoreFileMetaData> identical;
/**
* Files that exist in both snapshots but their they are not identical
*/
public final List<StoreFileMetaData> different;
/**
* Files that exist in the source but not in the target
*/
public final List<StoreFileMetaData> missing;
RecoveryDiff(List<StoreFileMetaData> identical, List<StoreFileMetaData> different, List<StoreFileMetaData> missing) {
this.identical = identical;
this.different = different;
this.missing = missing;
}
/**
* Returns the sum of the files in this diff.
*/
public int size() {
return identical.size() + different.size() + missing.size();
}
@Override
public String toString() {
return "RecoveryDiff{" +
"identical=" + identical +
", different=" + different +
", missing=" + missing +
'}';
}
}
public final static class LegacyChecksums {
private final Map<String, String> legacyChecksums = new HashMap<>();
public void add(StoreFileMetaData metaData) throws IOException {
if (metaData.hasLegacyChecksum()) {
synchronized (this) {
// we don't add checksums if they were written by LUCENE_48... now we are using the build in mechanism.
legacyChecksums.put(metaData.name(), metaData.checksum());
}
}
}
public synchronized void write(Store store) throws IOException {
synchronized (store.directory) {
Tuple<Map<String, String>, Long> tuple = MetadataSnapshot.readLegacyChecksums(store.directory);
tuple.v1().putAll(legacyChecksums);
if (!tuple.v1().isEmpty()) {
writeChecksums(store.directory, tuple.v1(), tuple.v2());
}
}
}
synchronized void writeChecksums(Directory directory, Map<String, String> checksums, long lastVersion) throws IOException {
long nextVersion = System.currentTimeMillis();
while (nextVersion <= lastVersion) {
nextVersion = System.currentTimeMillis();
}
final String checksumName = CHECKSUMS_PREFIX + nextVersion;
try (IndexOutput output = directory.createOutput(checksumName, IOContext.DEFAULT)) {
output.writeInt(0); // version
output.writeStringStringMap(checksums);
}
directory.sync(Collections.singleton(checksumName));
MetadataSnapshot.cleanLegacyChecksums(directory, nextVersion);
}
public void clear() {
this.legacyChecksums.clear();
}
public void remove(String name) {
legacyChecksums.remove(name);
}
}
public static final String CHECKSUMS_PREFIX = "_checksums-";
public static final boolean isChecksum(String name) {
// TODO can we drowp .cks
return name.startsWith(CHECKSUMS_PREFIX) || name.endsWith(".cks"); // bwcomapt - .cks used to be a previous checksum file
}
/**
* Produces a string representation of the given digest value.
*/
public static String digestToString(long digest) {
return Long.toString(digest, Character.MAX_RADIX);
}
static class LuceneVerifyingIndexOutput extends VerifyingIndexOutput {
private final StoreFileMetaData metadata;
private long writtenBytes;
private final long checksumPosition;
private String actualChecksum;
LuceneVerifyingIndexOutput(StoreFileMetaData metadata, IndexOutput out) {
super(out);
this.metadata = metadata;
checksumPosition = metadata.length() - 8; // the last 8 bytes are the checksum
}
@Override
public void verify() throws IOException {
if (metadata.checksum().equals(actualChecksum) && writtenBytes == metadata.length()) {
return;
}
throw new CorruptIndexException("verification failed (hardware problem?) : expected=" + metadata.checksum() +
" actual=" + actualChecksum + " writtenLength=" + writtenBytes + " expectedLength=" + metadata.length() +
" (resource=" + metadata.toString() + ")", "VerifyingIndexOutput(" + metadata.name() + ")");
}
@Override
public void writeByte(byte b) throws IOException {
if (writtenBytes++ == checksumPosition) {
readAndCompareChecksum();
}
out.writeByte(b);
}
private void readAndCompareChecksum() throws IOException {
actualChecksum = digestToString(getChecksum());
if (!metadata.checksum().equals(actualChecksum)) {
throw new CorruptIndexException("checksum failed (hardware problem?) : expected=" + metadata.checksum() +
" actual=" + actualChecksum +
" (resource=" + metadata.toString() + ")", "VerifyingIndexOutput(" + metadata.name() + ")");
}
}
@Override
public void writeBytes(byte[] b, int offset, int length) throws IOException {
if (writtenBytes + length > checksumPosition && actualChecksum == null) {
assert writtenBytes <= checksumPosition;
final int bytesToWrite = (int) (checksumPosition - writtenBytes);
out.writeBytes(b, offset, bytesToWrite);
readAndCompareChecksum();
offset += bytesToWrite;
length -= bytesToWrite;
writtenBytes += bytesToWrite;
}
out.writeBytes(b, offset, length);
writtenBytes += length;
}
}
/**
* Index input that calculates checksum as data is read from the input.
* <p/>
* This class supports random access (it is possible to seek backward and forward) in order to accommodate retry
* mechanism that is used in some repository plugins (S3 for example). However, the checksum is only calculated on
* the first read. All consecutive reads of the same data are not used to calculate the checksum.
*/
static class VerifyingIndexInput extends ChecksumIndexInput {
private final IndexInput input;
private final Checksum digest;
private final long checksumPosition;
private final byte[] checksum = new byte[8];
private long verifiedPosition = 0;
public VerifyingIndexInput(IndexInput input) {
this(input, new BufferedChecksum(new CRC32()));
}
public VerifyingIndexInput(IndexInput input, Checksum digest) {
super("VerifyingIndexInput(" + input + ")");
this.input = input;
this.digest = digest;
checksumPosition = input.length() - 8;
}
@Override
public byte readByte() throws IOException {
long pos = input.getFilePointer();
final byte b = input.readByte();
pos++;
if (pos > verifiedPosition) {
if (pos <= checksumPosition) {
digest.update(b);
} else {
checksum[(int) (pos - checksumPosition - 1)] = b;
}
verifiedPosition = pos;
}
return b;
}
@Override
public void readBytes(byte[] b, int offset, int len)
throws IOException {
long pos = input.getFilePointer();
input.readBytes(b, offset, len);
if (pos + len > verifiedPosition) {
// Conversion to int is safe here because (verifiedPosition - pos) can be at most len, which is integer
int alreadyVerified = (int) Math.max(0, verifiedPosition - pos);
if (pos < checksumPosition) {
if (pos + len < checksumPosition) {
digest.update(b, offset + alreadyVerified, len - alreadyVerified);
} else {
int checksumOffset = (int) (checksumPosition - pos);
if (checksumOffset - alreadyVerified > 0) {
digest.update(b, offset + alreadyVerified, checksumOffset - alreadyVerified);
}
System.arraycopy(b, offset + checksumOffset, checksum, 0, len - checksumOffset);
}
} else {
// Conversion to int is safe here because checksumPosition is (file length - 8) so
// (pos - checksumPosition) cannot be bigger than 8 unless we are reading after the end of file
assert pos - checksumPosition < 8;
System.arraycopy(b, offset, checksum, (int) (pos - checksumPosition), len);
}
verifiedPosition = pos + len;
}
}
@Override
public long getChecksum() {
return digest.getValue();
}
@Override
public void seek(long pos) throws IOException {
if (pos < verifiedPosition) {
// going within verified region - just seek there
input.seek(pos);
} else {
if (verifiedPosition > getFilePointer()) {
// portion of the skip region is verified and portion is not
// skipping the verified portion
input.seek(verifiedPosition);
// and checking unverified
skipBytes(pos - verifiedPosition);
} else {
skipBytes(pos - getFilePointer());
}
}
}
@Override
public void close() throws IOException {
input.close();
}
@Override
public long getFilePointer() {
return input.getFilePointer();
}
@Override
public long length() {
return input.length();
}
@Override
public IndexInput clone() {
throw new UnsupportedOperationException();
}
@Override
public IndexInput slice(String sliceDescription, long offset, long length) throws IOException {
throw new UnsupportedOperationException();
}
public long getStoredChecksum() {
return new ByteArrayDataInput(checksum).readLong();
}
public long verify() throws CorruptIndexException {
long storedChecksum = getStoredChecksum();
if (getChecksum() == storedChecksum) {
return storedChecksum;
}
throw new CorruptIndexException("verification failed : calculated=" + Store.digestToString(getChecksum()) +
" stored=" + Store.digestToString(storedChecksum), this);
}
}
public void deleteQuiet(String... files) {
for (String file : files) {
try {
directory().deleteFile(file);
} catch (Throwable ex) {
// ignore
}
}
}
/**
* Marks this store as corrupted. This method writes a <tt>corrupted_${uuid}</tt> file containing the given exception
* message. If a store contains a <tt>corrupted_${uuid}</tt> file {@link #isMarkedCorrupted()} will return <code>true</code>.
*/
public void markStoreCorrupted(IOException exception) throws IOException {
ensureOpen();
if (!isMarkedCorrupted()) {
String uuid = CORRUPTED + Strings.randomBase64UUID();
try (IndexOutput output = this.directory().createOutput(uuid, IOContext.DEFAULT)) {
CodecUtil.writeHeader(output, CODEC, VERSION);
output.writeString(ExceptionsHelper.detailedMessage(exception, true, 0)); // handles null exception
output.writeString(ExceptionsHelper.stackTrace(exception));
CodecUtil.writeFooter(output);
} catch (IOException ex) {
logger.warn("Can't mark store as corrupted", ex);
}
directory().sync(Collections.singleton(uuid));
}
}
/**
* A listener that is executed once the store is closed and all references to it are released
*/
public static interface OnClose extends Callback<ShardLock> {
static final OnClose EMPTY = new OnClose() {
/**
* This method is called while the provided {@link org.elasticsearch.env.ShardLock} is held.
* This method is only called once after all resources for a store are released.
*/
@Override
public void handle(ShardLock Lock) {
}
};
}
}
| remove dead code
| src/main/java/org/elasticsearch/index/store/Store.java | remove dead code |
|
Java | apache-2.0 | a60b4a3a758b629c704242024a9558ea0c823820 | 0 | OpenHFT/Chronicle-Queue,OpenHFT/Chronicle-Queue | /*
* Copyright 2016 higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.queue.impl.single;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.core.annotation.UsedViaReflection;
import net.openhft.chronicle.core.io.IORuntimeException;
import net.openhft.chronicle.core.util.StringUtils;
import net.openhft.chronicle.queue.*;
import net.openhft.chronicle.queue.impl.RollingChronicleQueue;
import net.openhft.chronicle.queue.impl.WireStore;
import net.openhft.chronicle.wire.*;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.StreamCorruptedException;
import java.nio.BufferOverflowException;
import java.util.function.BiConsumer;
public class SingleChronicleQueueExcerpts {
private static final Logger LOG = LoggerFactory.getLogger(SingleChronicleQueueExcerpts.class);
@FunctionalInterface
public interface WireWriter<T> {
void write(
T message,
WireOut wireOut);
}
// *************************************************************************
//
// APPENDERS
//
// *************************************************************************
/**
* StoreAppender
*/
public static class StoreAppender implements ExcerptAppender {
@NotNull
private final SingleChronicleQueue queue;
private final StoreAppenderContext context;
private final int indexSpacingMask;
private int cycle = Integer.MIN_VALUE;
private WireStore store;
private Wire wire;
private Wire bufferWire;
private long position = -1;
private volatile Thread appendingThread = null;
private long lastIndex = Long.MIN_VALUE;
private boolean lazyIndexing = false;
public StoreAppender(@NotNull SingleChronicleQueue queue) {
this.queue = queue;
indexSpacingMask = queue.rollCycle().defaultIndexSpacing() - 1;
context = new StoreAppenderContext();
}
@Override
public ExcerptAppender lazyIndexing(boolean lazyIndexing) {
this.lazyIndexing = lazyIndexing;
resetPosition();
return this;
}
@Override
public boolean lazyIndexing() {
return lazyIndexing;
}
@Override
public boolean recordHistory() {
return sourceId() != 0;
}
private void setCycle(int cycle, boolean createIfAbsent) {
if (cycle != this.cycle)
setCycle2(cycle, createIfAbsent);
}
private void setCycle2(int cycle, boolean createIfAbsent) {
if (cycle < 0)
throw new IllegalArgumentException("You can not have a cycle that starts " +
"before Epoch. cycle=" + cycle);
SingleChronicleQueue queue = this.queue;
if (this.store != null) {
queue.release(this.store);
}
this.store = queue.storeForCycle(cycle, queue.epoch(), createIfAbsent);
if (store == null) {
wire = null;
return;
}
this.cycle = cycle;
wire = queue.wireType().apply(store.bytes());
// only set the cycle after the wire is set.
this.cycle = cycle;
assert wire.startUse();
wire.parent(this);
wire.pauser(queue.pauserSupplier.get());
resetPosition();
}
private void resetPosition() {
try {
if (store == null || wire == null)
return;
final long position = store.writePosition();
wire.bytes().writePosition(position);
if (lazyIndexing)
return;
final long headerNumber = store.indexForPosition(wire, position, queue.timeoutMS);
wire.headerNumber(queue.rollCycle().toIndex(cycle, headerNumber));
} catch (BufferOverflowException e) {
throw new AssertionError(e);
} catch (EOFException e) {
throw new AssertionError(e);
} catch (UnrecoverableTimeoutException e) {
throw new AssertionError(e);
} catch (StreamCorruptedException e) {
throw new AssertionError(e);
}
}
@Override
public DocumentContext writingDocument() throws UnrecoverableTimeoutException {
assert checkAppendingThread();
try {
for (int i = 0; i < 100; i++) {
try {
int cycle = queue.cycle();
if (this.cycle != cycle || wire == null) {
rollCycleTo(cycle);
wire.bytes().writePosition(store.writePosition());
}
assert wire != null;
if (wire.bytes().writePosition() >= wire.bytes().writeLimit()) {
LOG.debug("Reset write position");
wire.bytes().writePosition(store.writePosition());
}
position = store.writeHeader(wire, Wires.UNKNOWN_LENGTH, queue.timeoutMS);
lastIndex = wire.headerNumber();
context.metaData = false;
context.wire = wire;
break;
} catch (EOFException theySeeMeRolling) {
// retry.
}
}
} catch (Exception e) {
assert resetAppendingThread();
throw e;
}
return context;
}
@Override
public DocumentContext writingDocument(long index) {
assert checkAppendingThread();
context.wire = acquireBufferWire();
context.wire.headerNumber(index);
return context;
}
@Override
public int sourceId() {
return queue.sourceId;
}
@Override
public void writeBytes(@NotNull Bytes bytes) throws UnrecoverableTimeoutException {
// still uses append as it has a known length.
append(Maths.toUInt31(bytes.readRemaining()), (m, w) -> w.bytes().write(m), bytes);
}
Wire acquireBufferWire() {
if (bufferWire == null) {
bufferWire = queue.wireType().apply(Bytes.elasticByteBuffer());
} else {
bufferWire.clear();
}
return bufferWire;
}
@Override
public void writeBytes(long index, Bytes<?> bytes) throws StreamCorruptedException {
if (bytes.isEmpty())
throw new UnsupportedOperationException("Cannot append a zero length message");
assert checkAppendingThread();
try {
moveToIndexForWrite(index);
// only get the bytes after moveToIndex
Bytes<?> wireBytes = wire.bytes();
try {
// wire.bytes().writePosition(store.writePosition());
int length = bytes.length();
position = store.writeHeader(wire, length, queue.timeoutMS);
wireBytes.write(bytes);
wire.updateHeader(length, position, false);
} catch (EOFException theySeeMeRolling) {
if (wireBytes.compareAndSwapInt(wireBytes.writePosition(), Wires.END_OF_DATA, Wires.NOT_COMPLETE)) {
wireBytes.write(bytes);
wire.updateHeader(0, position, false);
}
}
lastIndex = index;
} catch (UnrecoverableTimeoutException | StreamCorruptedException | EOFException e) {
throw Jvm.rethrow(e);
} finally {
Bytes<?> wireBytes = wire.bytes();
store.writePosition(wireBytes.writePosition());
assert resetAppendingThread();
}
}
void moveToIndexForWrite(long index) throws EOFException {
if (index != lastIndex + 1) {
int cycle = queue.rollCycle().toCycle(index);
ScanResult scanResult = moveToIndex(cycle, queue.rollCycle().toSequenceNumber(index));
switch (scanResult) {
case FOUND:
throw new IllegalStateException("Unable to move to index " + Long.toHexString(index) + " as the index already exists");
case NOT_REACHED:
throw new IllegalStateException("Unable to move to index " + Long.toHexString(index) + " beyond the end of the queue");
case NOT_FOUND:
break;
}
}
}
ScanResult moveToIndex(int cycle, long sequenceNumber) throws UnrecoverableTimeoutException, EOFException {
if (LOG.isDebugEnabled()) {
LOG.debug("moveToIndex: " + Long.toHexString(cycle) + " " + Long.toHexString(sequenceNumber));
}
if (this.cycle != cycle) {
if (cycle > this.cycle)
rollCycleTo(cycle);
else
setCycle2(cycle, true);
}
ScanResult scanResult = this.store.moveToIndexForRead(wire, sequenceNumber, queue.timeoutMS);
Bytes<?> bytes = wire.bytes();
if (scanResult == ScanResult.NOT_FOUND) {
wire.bytes().writePosition(wire.bytes().readPosition());
return scanResult;
}
bytes.readLimit(bytes.readPosition());
return scanResult;
}
@Override
public long lastIndexAppended() {
if (lastIndex != Long.MIN_VALUE)
return lastIndex;
if (this.position == -1)
throw new IllegalStateException("no messages written");
try {
final long timeoutMS = lazyIndexing ? 0 : queue.timeoutMS;
long sequenceNumber = store.indexForPosition(wire, position, timeoutMS);
lastIndex = queue.rollCycle().toIndex(cycle, sequenceNumber);
return lastIndex;
} catch (EOFException | UnrecoverableTimeoutException | StreamCorruptedException e) {
throw new AssertionError(e);
} finally {
wire.bytes().writePosition(store.writePosition());
}
}
@Override
public int cycle() {
if (cycle == Integer.MIN_VALUE) {
int cycle = this.queue.lastCycle();
if (cycle < 0)
cycle = queue.cycle();
setCycle2(cycle, true);
}
return cycle;
}
public SingleChronicleQueue queue() {
return queue;
}
private <T> void append(int length, WireWriter<T> wireWriter, T writer) throws UnrecoverableTimeoutException {
lastIndex = Long.MIN_VALUE;
assert checkAppendingThread();
try {
int cycle = queue.cycle();
if (this.cycle != cycle || wire == null)
rollCycleTo(cycle);
try {
position = store.writeHeader(wire, length, queue.timeoutMS);
wireWriter.write(writer, wire);
lastIndex = wire.headerNumber();
wire.updateHeader(length, position, false);
writeIndexForPosition(lastIndex, position, queue.timeoutMS);
} catch (EOFException theySeeMeRolling) {
try {
append2(length, wireWriter, writer);
} catch (EOFException e) {
throw new AssertionError(e);
}
}
} catch (StreamCorruptedException e) {
throw new AssertionError(e);
} finally {
store.writePosition(wire.bytes().writePosition());
assert resetAppendingThread();
}
}
private void rollCycleTo(int cycle) throws UnrecoverableTimeoutException {
if (this.cycle == cycle)
throw new AssertionError();
if (wire != null)
store.writeEOF(wire, queue.timeoutMS);
setCycle2(cycle, true);
resetPosition();
}
private <T> void append2(int length, WireWriter<T> wireWriter, T writer) throws UnrecoverableTimeoutException, EOFException, StreamCorruptedException {
setCycle(Math.max(queue.cycle(), cycle + 1), true);
position = store.writeHeader(wire, length, queue.timeoutMS);
wireWriter.write(writer, wire);
wire.updateHeader(length, position, false);
}
private boolean checkAppendingThread() {
Thread appendingThread = this.appendingThread;
Thread currentThread = Thread.currentThread();
if (appendingThread != null) {
if (appendingThread == currentThread)
throw new IllegalStateException("Nested blocks of writingDocument() not supported");
throw new IllegalStateException("Attempting to use Appender in " + currentThread + " while used by " + appendingThread);
}
this.appendingThread = currentThread;
return true;
}
private boolean resetAppendingThread() {
if (this.appendingThread == null)
throw new IllegalStateException("Attempting to release Appender in " + Thread.currentThread() + " but already released");
this.appendingThread = null;
return true;
}
void writeIndexForPosition(long index, long position, long timeoutMS) throws UnrecoverableTimeoutException, StreamCorruptedException {
assert lazyIndexing || checkIndex(index, position, timeoutMS);
if (!lazyIndexing && (index & indexSpacingMask) == 0) {
store.setPositionForIndex(wire,
queue.rollCycle().toSequenceNumber(index),
position, timeoutMS);
}
}
boolean checkIndex(long index, long position, long timeoutMS) {
try {
final long seq1 = queue.rollCycle().toSequenceNumber(index);
final long seq2 = store.indexForPosition(wire, position, timeoutMS);
assert seq1 == seq2;
} catch (EOFException | UnrecoverableTimeoutException | StreamCorruptedException e) {
throw new AssertionError(e);
}
return true;
}
class StoreAppenderContext implements DocumentContext {
private boolean metaData = false;
private Wire wire;
@Override
public int sourceId() {
return StoreAppender.this.sourceId();
}
@Override
public boolean isPresent() {
return false;
}
@Override
public Wire wire() {
return wire;
}
@Override
public boolean isMetaData() {
return metaData;
}
@Override
public void metaData(boolean metaData) {
this.metaData = metaData;
}
@Override
public void close() {
boolean isClosed = false;
try {
if (wire == StoreAppender.this.wire) {
final long timeoutMS = queue.timeoutMS;
wire.updateHeader(position, metaData);
long index = wire.headerNumber() - 1;
long position2 = wire.bytes().writePosition();
store.writePosition(position2);
if (!metaData)
writeIndexForPosition(index, position, timeoutMS);
} else {
isClosed = true;
assert resetAppendingThread();
writeBytes(wire.headerNumber(), wire.bytes());
}
} catch (StreamCorruptedException | UnrecoverableTimeoutException e) {
throw new IllegalStateException(e);
} finally {
assert isClosed || resetAppendingThread();
}
}
@Override
public long index() {
return wire.headerNumber();
}
@Override
public boolean isNotComplete() {
throw new UnsupportedOperationException();
}
}
}
// *************************************************************************
//
// TAILERS
//
// *************************************************************************
/**
* Tailer
*/
public static class StoreTailer implements ExcerptTailer, SourceContext {
@NotNull
private final SingleChronicleQueue queue;
private final StoreTailerContext context = new StoreTailerContext();
private int cycle;
private long index; // index of the next read.
private WireStore store;
private TailerDirection direction = TailerDirection.FORWARD;
private boolean lazyIndexing = false;
private int indexSpacingMask;
public StoreTailer(@NotNull final SingleChronicleQueue queue) {
this.queue = queue;
this.cycle = Integer.MIN_VALUE;
this.index = 0;
indexSpacingMask = queue.rollCycle().defaultIndexSpacing() - 1;
toStart();
}
@Override
public ExcerptTailer lazyIndexing(boolean lazyIndexing) {
this.lazyIndexing = lazyIndexing;
return this;
}
@Override
public boolean lazyIndexing() {
return lazyIndexing;
}
@Override
public int sourceId() {
return queue.sourceId;
}
@Override
public String toString() {
return "StoreTailer{" +
"index sequence=" + queue.rollCycle().toSequenceNumber(index) +
", index cycle=" + queue.rollCycle().toCycle(index) +
", store=" + store + ", queue=" + queue + '}';
}
@Override
public DocumentContext readingDocument(boolean includeMetaData) {
try {
assert context.wire() == null || context.wire().startUse();
if (context.present(next(includeMetaData)))
return context;
} catch (StreamCorruptedException e) {
throw new IllegalStateException(e);
} catch (UnrecoverableTimeoutException notComplete) {
// so treat as empty.
}
return NoDocumentContext.INSTANCE;
}
private boolean next(boolean includeMetaData) throws UnrecoverableTimeoutException, StreamCorruptedException {
if (this.store == null) { // load the first store
final long firstIndex = queue.firstIndex();
if (firstIndex == Long.MAX_VALUE)
return false;
if (!moveToIndex(firstIndex))
return false;
}
Bytes<?> bytes = context.wire().bytes();
bytes.readLimit(bytes.capacity());
for (int i = 0; i < 1000; i++) {
try {
if (direction != TailerDirection.FORWARD)
if (!moveToIndex(index))
return false;
switch (context.wire().readDataHeader(includeMetaData)) {
case NONE:
return false;
case META_DATA:
context.metaData(true);
break;
case DATA:
context.metaData(false);
break;
}
if (!lazyIndexing && direction == TailerDirection.FORWARD && (index & indexSpacingMask) == 0)
store.setPositionForIndex(context.wire(), queue.rollCycle().toSequenceNumber(index), bytes.readPosition(), queue.timeoutMS);
context.closeReadLimit(bytes.capacity());
context.wire().readAndSetLength(bytes.readPosition());
long end = bytes.readLimit();
context.closeReadPosition(end);
return true;
} catch (EOFException eof) {
if (cycle <= queue.lastCycle() && direction != TailerDirection.NONE)
if (moveToIndex(cycle + direction.add(), 0) == ScanResult.FOUND) {
bytes = context.wire().bytes();
continue;
}
return false;
}
}
throw new IllegalStateException("Unable to progress to the next cycle");
}
/**
* @return provides an index that includes the cycle number
*/
@Override
public long index() {
if (this.store == null)
return Long.MIN_VALUE;
return queue.rollCycle().toIndex(this.cycle, this.index);
}
@Override
public int cycle() {
return this.cycle;
}
@Override
public boolean moveToIndex(final long index) {
final ScanResult scanResult = moveToIndexResult(index);
return scanResult == ScanResult.FOUND;
}
ScanResult moveToIndexResult(long index) {
final int cycle = queue.rollCycle().toCycle(index);
final long sequenceNumber = queue.rollCycle().toSequenceNumber(index);
return moveToIndex(cycle, sequenceNumber, index);
}
ScanResult moveToIndex(int cycle, long sequenceNumber) {
return moveToIndex(cycle, sequenceNumber, queue.rollCycle().toIndex(cycle, sequenceNumber));
}
ScanResult moveToIndex(int cycle, long sequenceNumber, long index) {
if (LOG.isDebugEnabled()) {
LOG.debug("moveToIndex: " + Long.toHexString(cycle) + " " + Long.toHexString(sequenceNumber));
}
if (cycle != this.cycle) {
// moves to the expected cycle
cycle(cycle, false);
}
this.index = index;
if (store == null)
return ScanResult.NOT_REACHED;
ScanResult scanResult = this.store.moveToIndexForRead(context.wire(), sequenceNumber, queue.timeoutMS);
Bytes<?> bytes = context.wire().bytes();
if (scanResult == ScanResult.FOUND) {
return scanResult;
}
bytes.readLimit(bytes.readPosition());
return scanResult;
}
@NotNull
@Override
public final ExcerptTailer toStart() {
assert direction != TailerDirection.BACKWARD;
final int firstCycle = queue.firstCycle();
if (firstCycle == Integer.MAX_VALUE) {
return this;
}
if (firstCycle != this.cycle) {
// moves to the expected cycle
cycle(firstCycle, false);
}
index = queue.rollCycle().toIndex(cycle, 0);
if (context.wire() != null)
context.wire().bytes().readPosition(0);
return this;
}
@NotNull
@Override
public ExcerptTailer toEnd() {
long index = queue.nextIndexToWrite();
if (index == Long.MIN_VALUE)
return this;
if (direction != TailerDirection.FORWARD &&
queue.rollCycle().toSequenceNumber(index + 1) != 0) {
index--;
}
if (moveToIndexResult(index) == ScanResult.NOT_REACHED) {
LOG.warn("Failed to moveToIndex(" + Long.toHexString(index) + " for toEnd()");
if (moveToIndexResult(index - 1) == ScanResult.NOT_REACHED)
LOG.error("Failed to moveToIndex(" + Long.toHexString(index - 1) + " for toEnd()");
}
return this;
}
@Override
public TailerDirection direction() {
return direction;
}
@Override
public ExcerptTailer direction(TailerDirection direction) {
this.direction = direction;
return this;
}
public RollingChronicleQueue queue() {
return queue;
}
private <T> boolean __read(@NotNull final T t, @NotNull final BiConsumer<T, Wire> c) {
if (this.store == null) {
toStart();
if (this.store == null) return false;
}
if (read0(t, c)) {
incrementIndex();
return true;
}
return false;
}
private void incrementIndex() {
RollCycle rollCycle = queue.rollCycle();
long seq = rollCycle.toSequenceNumber(this.index);
seq += direction.add();
if (rollCycle.toSequenceNumber(seq) < seq) {
cycle(cycle + 1, false);
seq = 0;
} else if (seq < 0) {
if (seq == -1) {
cycle(cycle - 1, false);
} else {
// TODO FIX so we can roll back to the precious cycle.
throw new IllegalStateException("Winding to the previous day not supported");
}
}
this.index = rollCycle.toIndex(this.cycle, seq);
}
private <T> boolean read0(@NotNull final T t, @NotNull final BiConsumer<T, Wire> c) {
final Wire wire = context.wire();
Bytes<?> bytes = wire.bytes();
bytes.readLimit(bytes.capacity());
for (int i = 0; i < 1000; i++) {
try {
if (direction != TailerDirection.FORWARD)
if (!moveToIndex(index))
return false;
if (wire.readDataHeader()) {
wire.readAndSetLength(bytes.readPosition());
long end = bytes.readLimit();
try {
c.accept(t, wire);
return true;
} finally {
bytes.readLimit(bytes.capacity()).readPosition(end);
}
}
return false;
} catch (EOFException eof) {
if (cycle <= queue.lastCycle() && direction != TailerDirection.NONE)
if (moveToIndex(cycle + direction.add(), 0) == ScanResult.FOUND) {
bytes = wire.bytes();
continue;
}
return false;
}
}
throw new IllegalStateException("Unable to progress to the next cycle");
}
@NotNull
private StoreTailer cycle(final int cycle, boolean createIfAbsent) {
if (this.cycle != cycle) {
if (this.store != null) {
this.queue.release(this.store);
}
this.store = this.queue.storeForCycle(cycle, queue.epoch(), createIfAbsent);
if (store == null) {
context.wire(null);
return this;
}
this.cycle = cycle;
context.wire((AbstractWire) queue.wireType().apply(store.bytes()));
final Wire wire = context.wire();
assert wire.startUse();
try {
wire.parent(this);
wire.pauser(queue.pauserSupplier.get());
// if (LOG.isDebugEnabled())
// LOG.debug("tailer=" + ((MappedBytes) wire.bytes()).mappedFile().file().getAbsolutePath());
} finally {
assert wire.endUse();
}
}
return this;
}
@Override
public ExcerptTailer afterLastWritten(ChronicleQueue queue) {
if (queue == this.queue)
throw new IllegalArgumentException("You must pass the queue written to, not the queue read");
ExcerptTailer tailer = queue.createTailer()
.direction(TailerDirection.BACKWARD)
.toEnd();
StringBuilder sb = new StringBuilder();
VanillaMessageHistory veh = new VanillaMessageHistory();
veh.addSourceDetails(false);
while (true) {
try (DocumentContext context = tailer.readingDocument()) {
if (!context.isData()) {
toStart();
return this;
}
ValueIn valueIn = context.wire().readEventName(sb);
if (!StringUtils.isEqual("history", sb))
continue;
final Wire wire = context.wire();
Object parent = wire.parent();
try {
wire.parent(null);
valueIn.marshallable(veh);
} finally {
wire.parent(parent);
}
int i = veh.sources() - 1;
// skip the one we just added.
if (i < 0)
continue;
long sourceIndex = veh.sourceIndex(i);
if (!moveToIndex(sourceIndex))
throw new IORuntimeException("Unable to wind to index: " + sourceIndex);
try (DocumentContext content = readingDocument()) {
if (!content.isPresent())
throw new IORuntimeException("Unable to wind to index: " + (sourceIndex + 1));
// skip this message and go to the next.
}
return this;
}
}
}
@UsedViaReflection
public void lastAcknowledgedIndexReplicated(long acknowledgeIndex) {
if (store != null)
store.lastAcknowledgedIndexReplicated(acknowledgeIndex);
}
class StoreTailerContext extends ReadDocumentContext {
public StoreTailerContext() {
super(null);
}
@Override
public long index() {
return StoreTailer.this.index();
}
@Override
public int sourceId() {
return StoreTailer.this.sourceId();
}
@Override
public void close() {
if (isPresent())
incrementIndex();
super.close();
}
public boolean present(boolean present) {
return this.present = present;
}
public void wire(AbstractWire wire) {
this.wire = wire;
}
}
}
}
| src/main/java/net/openhft/chronicle/queue/impl/single/SingleChronicleQueueExcerpts.java | /*
* Copyright 2016 higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.queue.impl.single;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.core.annotation.UsedViaReflection;
import net.openhft.chronicle.core.io.IORuntimeException;
import net.openhft.chronicle.core.util.StringUtils;
import net.openhft.chronicle.queue.*;
import net.openhft.chronicle.queue.impl.RollingChronicleQueue;
import net.openhft.chronicle.queue.impl.WireStore;
import net.openhft.chronicle.wire.*;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.StreamCorruptedException;
import java.nio.BufferOverflowException;
import java.util.function.BiConsumer;
public class SingleChronicleQueueExcerpts {
private static final Logger LOG = LoggerFactory.getLogger(SingleChronicleQueueExcerpts.class);
@FunctionalInterface
public interface WireWriter<T> {
void write(
T message,
WireOut wireOut);
}
// *************************************************************************
//
// APPENDERS
//
// *************************************************************************
/**
* StoreAppender
*/
public static class StoreAppender implements ExcerptAppender {
@NotNull
private final SingleChronicleQueue queue;
private final StoreAppenderContext context;
private final int indexSpacingMask;
private int cycle = Integer.MIN_VALUE;
private WireStore store;
private Wire wire;
private Wire bufferWire;
private long position = -1;
private volatile Thread appendingThread = null;
private long lastIndex = Long.MIN_VALUE;
private boolean lazyIndexing = false;
public StoreAppender(@NotNull SingleChronicleQueue queue) {
this.queue = queue;
indexSpacingMask = queue.rollCycle().defaultIndexSpacing() - 1;
context = new StoreAppenderContext();
}
@Override
public ExcerptAppender lazyIndexing(boolean lazyIndexing) {
this.lazyIndexing = lazyIndexing;
resetPosition();
return this;
}
@Override
public boolean lazyIndexing() {
return lazyIndexing;
}
@Override
public boolean recordHistory() {
return sourceId() != 0;
}
private void setCycle(int cycle, boolean createIfAbsent) {
if (cycle != this.cycle)
setCycle2(cycle, createIfAbsent);
}
private void setCycle2(int cycle, boolean createIfAbsent) {
if (cycle < 0)
throw new IllegalArgumentException("You can not have a cycle that starts " +
"before Epoch. cycle=" + cycle);
SingleChronicleQueue queue = this.queue;
if (this.store != null) {
queue.release(this.store);
}
this.store = queue.storeForCycle(cycle, queue.epoch(), createIfAbsent);
if (store == null) {
wire = null;
return;
}
this.cycle = cycle;
wire = queue.wireType().apply(store.bytes());
// only set the cycle after the wire is set.
this.cycle = cycle;
assert wire.startUse();
wire.parent(this);
wire.pauser(queue.pauserSupplier.get());
resetPosition();
}
private void resetPosition() {
try {
if (store == null || wire == null)
return;
final long position = store.writePosition();
wire.bytes().writePosition(position);
if (lazyIndexing)
return;
final long headerNumber = store.indexForPosition(wire, position, queue.timeoutMS);
wire.headerNumber(queue.rollCycle().toIndex(cycle, headerNumber));
} catch (BufferOverflowException e) {
throw new AssertionError(e);
} catch (EOFException e) {
throw new AssertionError(e);
} catch (UnrecoverableTimeoutException e) {
throw new AssertionError(e);
} catch (StreamCorruptedException e) {
throw new AssertionError(e);
}
}
@Override
public DocumentContext writingDocument() throws UnrecoverableTimeoutException {
assert checkAppendingThread();
try {
for (int i = 0; i < 100; i++) {
try {
int cycle = queue.cycle();
if (this.cycle != cycle || wire == null) {
rollCycleTo(cycle);
wire.bytes().writePosition(store.writePosition());
}
assert wire != null;
if (wire.bytes().writePosition() >= wire.bytes().writeLimit()) {
LOG.debug("Reset write position");
wire.bytes().writePosition(store.writePosition());
}
position = store.writeHeader(wire, Wires.UNKNOWN_LENGTH, queue.timeoutMS);
lastIndex = wire.headerNumber();
context.metaData = false;
context.wire = wire;
break;
} catch (EOFException theySeeMeRolling) {
// retry.
}
}
} catch (Exception e) {
assert resetAppendingThread();
throw e;
}
return context;
}
@Override
public DocumentContext writingDocument(long index) {
context.wire = acquireBufferWire();
context.wire.headerNumber(index);
return context;
}
@Override
public int sourceId() {
return queue.sourceId;
}
@Override
public void writeBytes(@NotNull Bytes bytes) throws UnrecoverableTimeoutException {
// still uses append as it has a known length.
append(Maths.toUInt31(bytes.readRemaining()), (m, w) -> w.bytes().write(m), bytes);
}
Wire acquireBufferWire() {
if (bufferWire == null) {
bufferWire = queue.wireType().apply(Bytes.elasticByteBuffer());
} else {
bufferWire.clear();
}
return bufferWire;
}
@Override
public void writeBytes(long index, Bytes<?> bytes) throws StreamCorruptedException {
if (bytes.isEmpty())
throw new UnsupportedOperationException("Cannot append a zero length message");
assert checkAppendingThread();
try {
moveToIndexForWrite(index);
// only get the bytes after moveToIndex
Bytes<?> wireBytes = wire.bytes();
try {
// wire.bytes().writePosition(store.writePosition());
int length = bytes.length();
position = store.writeHeader(wire, length, queue.timeoutMS);
wireBytes.write(bytes);
wire.updateHeader(length, position, false);
} catch (EOFException theySeeMeRolling) {
if (wireBytes.compareAndSwapInt(wireBytes.writePosition(), Wires.END_OF_DATA, Wires.NOT_COMPLETE)) {
wireBytes.write(bytes);
wire.updateHeader(0, position, false);
}
}
lastIndex = index;
} catch (UnrecoverableTimeoutException | StreamCorruptedException | EOFException e) {
throw Jvm.rethrow(e);
} finally {
Bytes<?> wireBytes = wire.bytes();
store.writePosition(wireBytes.writePosition());
assert resetAppendingThread();
}
}
void moveToIndexForWrite(long index) throws EOFException {
if (index != lastIndex + 1) {
int cycle = queue.rollCycle().toCycle(index);
ScanResult scanResult = moveToIndex(cycle, queue.rollCycle().toSequenceNumber(index));
switch (scanResult) {
case FOUND:
throw new IllegalStateException("Unable to move to index " + Long.toHexString(index) + " as the index already exists");
case NOT_REACHED:
throw new IllegalStateException("Unable to move to index " + Long.toHexString(index) + " beyond the end of the queue");
case NOT_FOUND:
break;
}
}
}
ScanResult moveToIndex(int cycle, long sequenceNumber) throws UnrecoverableTimeoutException, EOFException {
if (LOG.isDebugEnabled()) {
LOG.debug("moveToIndex: " + Long.toHexString(cycle) + " " + Long.toHexString(sequenceNumber));
}
if (this.cycle != cycle) {
if (cycle > this.cycle)
rollCycleTo(cycle);
else
setCycle2(cycle, true);
}
ScanResult scanResult = this.store.moveToIndexForRead(wire, sequenceNumber, queue.timeoutMS);
Bytes<?> bytes = wire.bytes();
if (scanResult == ScanResult.NOT_FOUND) {
wire.bytes().writePosition(wire.bytes().readPosition());
return scanResult;
}
bytes.readLimit(bytes.readPosition());
return scanResult;
}
@Override
public long lastIndexAppended() {
if (lastIndex != Long.MIN_VALUE)
return lastIndex;
if (this.position == -1)
throw new IllegalStateException("no messages written");
try {
final long timeoutMS = lazyIndexing ? 0 : queue.timeoutMS;
long sequenceNumber = store.indexForPosition(wire, position, timeoutMS);
lastIndex = queue.rollCycle().toIndex(cycle, sequenceNumber);
return lastIndex;
} catch (EOFException | UnrecoverableTimeoutException | StreamCorruptedException e) {
throw new AssertionError(e);
} finally {
wire.bytes().writePosition(store.writePosition());
}
}
@Override
public int cycle() {
if (cycle == Integer.MIN_VALUE) {
int cycle = this.queue.lastCycle();
if (cycle < 0)
cycle = queue.cycle();
setCycle2(cycle, true);
}
return cycle;
}
public SingleChronicleQueue queue() {
return queue;
}
private <T> void append(int length, WireWriter<T> wireWriter, T writer) throws UnrecoverableTimeoutException {
lastIndex = Long.MIN_VALUE;
assert checkAppendingThread();
try {
int cycle = queue.cycle();
if (this.cycle != cycle || wire == null)
rollCycleTo(cycle);
try {
position = store.writeHeader(wire, length, queue.timeoutMS);
wireWriter.write(writer, wire);
lastIndex = wire.headerNumber();
wire.updateHeader(length, position, false);
writeIndexForPosition(lastIndex, position, queue.timeoutMS);
} catch (EOFException theySeeMeRolling) {
try {
append2(length, wireWriter, writer);
} catch (EOFException e) {
throw new AssertionError(e);
}
}
} catch (StreamCorruptedException e) {
throw new AssertionError(e);
} finally {
store.writePosition(wire.bytes().writePosition());
assert resetAppendingThread();
}
}
private void rollCycleTo(int cycle) throws UnrecoverableTimeoutException {
if (this.cycle == cycle)
throw new AssertionError();
if (wire != null)
store.writeEOF(wire, queue.timeoutMS);
setCycle2(cycle, true);
resetPosition();
}
private <T> void append2(int length, WireWriter<T> wireWriter, T writer) throws UnrecoverableTimeoutException, EOFException, StreamCorruptedException {
setCycle(Math.max(queue.cycle(), cycle + 1), true);
position = store.writeHeader(wire, length, queue.timeoutMS);
wireWriter.write(writer, wire);
wire.updateHeader(length, position, false);
}
private boolean checkAppendingThread() {
Thread appendingThread = this.appendingThread;
Thread currentThread = Thread.currentThread();
if (appendingThread != null) {
if (appendingThread == currentThread)
throw new IllegalStateException("Nested blocks of writingDocument() not supported");
throw new IllegalStateException("Attempting to use Appender in " + currentThread + " while used by " + appendingThread);
}
this.appendingThread = currentThread;
return true;
}
private boolean resetAppendingThread() {
if (this.appendingThread == null)
throw new IllegalStateException("Attempting to release Appender in " + Thread.currentThread() + " but already released");
this.appendingThread = null;
return true;
}
void writeIndexForPosition(long index, long position, long timeoutMS) throws UnrecoverableTimeoutException, StreamCorruptedException {
assert lazyIndexing || checkIndex(index, position, timeoutMS);
if (!lazyIndexing && (index & indexSpacingMask) == 0) {
store.setPositionForIndex(wire,
queue.rollCycle().toSequenceNumber(index),
position, timeoutMS);
}
}
boolean checkIndex(long index, long position, long timeoutMS) {
try {
final long seq1 = queue.rollCycle().toSequenceNumber(index);
final long seq2 = store.indexForPosition(wire, position, timeoutMS);
assert seq1 == seq2;
} catch (EOFException | UnrecoverableTimeoutException | StreamCorruptedException e) {
throw new AssertionError(e);
}
return true;
}
class StoreAppenderContext implements DocumentContext {
private boolean metaData = false;
private Wire wire;
@Override
public int sourceId() {
return StoreAppender.this.sourceId();
}
@Override
public boolean isPresent() {
return false;
}
@Override
public Wire wire() {
return wire;
}
@Override
public boolean isMetaData() {
return metaData;
}
@Override
public void metaData(boolean metaData) {
this.metaData = metaData;
}
@Override
public void close() {
try {
if (wire == StoreAppender.this.wire) {
final long timeoutMS = queue.timeoutMS;
wire.updateHeader(position, metaData);
long index = wire.headerNumber() - 1;
long position2 = wire.bytes().writePosition();
store.writePosition(position2);
if (!metaData)
writeIndexForPosition(index, position, timeoutMS);
} else {
writeBytes(wire.headerNumber(), wire.bytes());
}
} catch (StreamCorruptedException | UnrecoverableTimeoutException e) {
throw new IllegalStateException(e);
} finally {
assert resetAppendingThread();
}
}
@Override
public long index() {
return wire.headerNumber();
}
@Override
public boolean isNotComplete() {
throw new UnsupportedOperationException();
}
}
}
// *************************************************************************
//
// TAILERS
//
// *************************************************************************
/**
* Tailer
*/
public static class StoreTailer implements ExcerptTailer, SourceContext {
@NotNull
private final SingleChronicleQueue queue;
private final StoreTailerContext context = new StoreTailerContext();
private int cycle;
private long index; // index of the next read.
private WireStore store;
private TailerDirection direction = TailerDirection.FORWARD;
private boolean lazyIndexing = false;
private int indexSpacingMask;
public StoreTailer(@NotNull final SingleChronicleQueue queue) {
this.queue = queue;
this.cycle = Integer.MIN_VALUE;
this.index = 0;
indexSpacingMask = queue.rollCycle().defaultIndexSpacing() - 1;
toStart();
}
@Override
public ExcerptTailer lazyIndexing(boolean lazyIndexing) {
this.lazyIndexing = lazyIndexing;
return this;
}
@Override
public boolean lazyIndexing() {
return lazyIndexing;
}
@Override
public int sourceId() {
return queue.sourceId;
}
@Override
public String toString() {
return "StoreTailer{" +
"index sequence=" + queue.rollCycle().toSequenceNumber(index) +
", index cycle=" + queue.rollCycle().toCycle(index) +
", store=" + store + ", queue=" + queue + '}';
}
@Override
public DocumentContext readingDocument(boolean includeMetaData) {
try {
assert context.wire() == null || context.wire().startUse();
if (context.present(next(includeMetaData)))
return context;
} catch (StreamCorruptedException e) {
throw new IllegalStateException(e);
} catch (UnrecoverableTimeoutException notComplete) {
// so treat as empty.
}
return NoDocumentContext.INSTANCE;
}
private boolean next(boolean includeMetaData) throws UnrecoverableTimeoutException, StreamCorruptedException {
if (this.store == null) { // load the first store
final long firstIndex = queue.firstIndex();
if (firstIndex == Long.MAX_VALUE)
return false;
if (!moveToIndex(firstIndex))
return false;
}
Bytes<?> bytes = context.wire().bytes();
bytes.readLimit(bytes.capacity());
for (int i = 0; i < 1000; i++) {
try {
if (direction != TailerDirection.FORWARD)
if (!moveToIndex(index))
return false;
switch (context.wire().readDataHeader(includeMetaData)) {
case NONE:
return false;
case META_DATA:
context.metaData(true);
break;
case DATA:
context.metaData(false);
break;
}
if (!lazyIndexing && direction == TailerDirection.FORWARD && (index & indexSpacingMask) == 0)
store.setPositionForIndex(context.wire(), queue.rollCycle().toSequenceNumber(index), bytes.readPosition(), queue.timeoutMS);
context.closeReadLimit(bytes.capacity());
context.wire().readAndSetLength(bytes.readPosition());
long end = bytes.readLimit();
context.closeReadPosition(end);
return true;
} catch (EOFException eof) {
if (cycle <= queue.lastCycle() && direction != TailerDirection.NONE)
if (moveToIndex(cycle + direction.add(), 0) == ScanResult.FOUND) {
bytes = context.wire().bytes();
continue;
}
return false;
}
}
throw new IllegalStateException("Unable to progress to the next cycle");
}
/**
* @return provides an index that includes the cycle number
*/
@Override
public long index() {
if (this.store == null)
return Long.MIN_VALUE;
return queue.rollCycle().toIndex(this.cycle, this.index);
}
@Override
public int cycle() {
return this.cycle;
}
@Override
public boolean moveToIndex(final long index) {
final ScanResult scanResult = moveToIndexResult(index);
return scanResult == ScanResult.FOUND;
}
ScanResult moveToIndexResult(long index) {
final int cycle = queue.rollCycle().toCycle(index);
final long sequenceNumber = queue.rollCycle().toSequenceNumber(index);
return moveToIndex(cycle, sequenceNumber, index);
}
ScanResult moveToIndex(int cycle, long sequenceNumber) {
return moveToIndex(cycle, sequenceNumber, queue.rollCycle().toIndex(cycle, sequenceNumber));
}
ScanResult moveToIndex(int cycle, long sequenceNumber, long index) {
if (LOG.isDebugEnabled()) {
LOG.debug("moveToIndex: " + Long.toHexString(cycle) + " " + Long.toHexString(sequenceNumber));
}
if (cycle != this.cycle) {
// moves to the expected cycle
cycle(cycle, false);
}
this.index = index;
if (store == null)
return ScanResult.NOT_REACHED;
ScanResult scanResult = this.store.moveToIndexForRead(context.wire(), sequenceNumber, queue.timeoutMS);
Bytes<?> bytes = context.wire().bytes();
if (scanResult == ScanResult.FOUND) {
return scanResult;
}
bytes.readLimit(bytes.readPosition());
return scanResult;
}
@NotNull
@Override
public final ExcerptTailer toStart() {
assert direction != TailerDirection.BACKWARD;
final int firstCycle = queue.firstCycle();
if (firstCycle == Integer.MAX_VALUE) {
return this;
}
if (firstCycle != this.cycle) {
// moves to the expected cycle
cycle(firstCycle, false);
}
index = queue.rollCycle().toIndex(cycle, 0);
if (context.wire() != null)
context.wire().bytes().readPosition(0);
return this;
}
@NotNull
@Override
public ExcerptTailer toEnd() {
long index = queue.nextIndexToWrite();
if (index == Long.MIN_VALUE)
return this;
if (direction != TailerDirection.FORWARD &&
queue.rollCycle().toSequenceNumber(index + 1) != 0) {
index--;
}
if (moveToIndexResult(index) == ScanResult.NOT_REACHED) {
LOG.warn("Failed to moveToIndex(" + Long.toHexString(index) + " for toEnd()");
if (moveToIndexResult(index - 1) == ScanResult.NOT_REACHED)
LOG.error("Failed to moveToIndex(" + Long.toHexString(index - 1) + " for toEnd()");
}
return this;
}
@Override
public TailerDirection direction() {
return direction;
}
@Override
public ExcerptTailer direction(TailerDirection direction) {
this.direction = direction;
return this;
}
public RollingChronicleQueue queue() {
return queue;
}
private <T> boolean __read(@NotNull final T t, @NotNull final BiConsumer<T, Wire> c) {
if (this.store == null) {
toStart();
if (this.store == null) return false;
}
if (read0(t, c)) {
incrementIndex();
return true;
}
return false;
}
private void incrementIndex() {
RollCycle rollCycle = queue.rollCycle();
long seq = rollCycle.toSequenceNumber(this.index);
seq += direction.add();
if (rollCycle.toSequenceNumber(seq) < seq) {
cycle(cycle + 1, false);
seq = 0;
} else if (seq < 0) {
if (seq == -1) {
cycle(cycle - 1, false);
} else {
// TODO FIX so we can roll back to the precious cycle.
throw new IllegalStateException("Winding to the previous day not supported");
}
}
this.index = rollCycle.toIndex(this.cycle, seq);
}
private <T> boolean read0(@NotNull final T t, @NotNull final BiConsumer<T, Wire> c) {
final Wire wire = context.wire();
Bytes<?> bytes = wire.bytes();
bytes.readLimit(bytes.capacity());
for (int i = 0; i < 1000; i++) {
try {
if (direction != TailerDirection.FORWARD)
if (!moveToIndex(index))
return false;
if (wire.readDataHeader()) {
wire.readAndSetLength(bytes.readPosition());
long end = bytes.readLimit();
try {
c.accept(t, wire);
return true;
} finally {
bytes.readLimit(bytes.capacity()).readPosition(end);
}
}
return false;
} catch (EOFException eof) {
if (cycle <= queue.lastCycle() && direction != TailerDirection.NONE)
if (moveToIndex(cycle + direction.add(), 0) == ScanResult.FOUND) {
bytes = wire.bytes();
continue;
}
return false;
}
}
throw new IllegalStateException("Unable to progress to the next cycle");
}
@NotNull
private StoreTailer cycle(final int cycle, boolean createIfAbsent) {
if (this.cycle != cycle) {
if (this.store != null) {
this.queue.release(this.store);
}
this.store = this.queue.storeForCycle(cycle, queue.epoch(), createIfAbsent);
if (store == null) {
context.wire(null);
return this;
}
this.cycle = cycle;
context.wire((AbstractWire) queue.wireType().apply(store.bytes()));
final Wire wire = context.wire();
assert wire.startUse();
try {
wire.parent(this);
wire.pauser(queue.pauserSupplier.get());
// if (LOG.isDebugEnabled())
// LOG.debug("tailer=" + ((MappedBytes) wire.bytes()).mappedFile().file().getAbsolutePath());
} finally {
assert wire.endUse();
}
}
return this;
}
@Override
public ExcerptTailer afterLastWritten(ChronicleQueue queue) {
if (queue == this.queue)
throw new IllegalArgumentException("You must pass the queue written to, not the queue read");
ExcerptTailer tailer = queue.createTailer()
.direction(TailerDirection.BACKWARD)
.toEnd();
StringBuilder sb = new StringBuilder();
VanillaMessageHistory veh = new VanillaMessageHistory();
veh.addSourceDetails(false);
while (true) {
try (DocumentContext context = tailer.readingDocument()) {
if (!context.isData()) {
toStart();
return this;
}
ValueIn valueIn = context.wire().readEventName(sb);
if (!StringUtils.isEqual("history", sb))
continue;
final Wire wire = context.wire();
Object parent = wire.parent();
try {
wire.parent(null);
valueIn.marshallable(veh);
} finally {
wire.parent(parent);
}
int i = veh.sources() - 1;
// skip the one we just added.
if (i < 0)
continue;
long sourceIndex = veh.sourceIndex(i);
if (!moveToIndex(sourceIndex))
throw new IORuntimeException("Unable to wind to index: " + sourceIndex);
try (DocumentContext content = readingDocument()) {
if (!content.isPresent())
throw new IORuntimeException("Unable to wind to index: " + (sourceIndex + 1));
// skip this message and go to the next.
}
return this;
}
}
}
@UsedViaReflection
public void lastAcknowledgedIndexReplicated(long acknowledgeIndex) {
if (store != null)
store.lastAcknowledgedIndexReplicated(acknowledgeIndex);
}
class StoreTailerContext extends ReadDocumentContext {
public StoreTailerContext() {
super(null);
}
@Override
public long index() {
return StoreTailer.this.index();
}
@Override
public int sourceId() {
return StoreTailer.this.sourceId();
}
@Override
public void close() {
if (isPresent())
incrementIndex();
super.close();
}
public boolean present(boolean present) {
return this.present = present;
}
public void wire(AbstractWire wire) {
this.wire = wire;
}
}
}
}
| refactors with peter around, around messge adaptor
| src/main/java/net/openhft/chronicle/queue/impl/single/SingleChronicleQueueExcerpts.java | refactors with peter around, around messge adaptor |
|
Java | apache-2.0 | 5ee47b0e2b7b518474087287f2e5f65e14dd6ab1 | 0 | adedayo/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,ibinti/intellij-community,jexp/idea2,MER-GROUP/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,diorcety/intellij-community,asedunov/intellij-community,supersven/intellij-community,robovm/robovm-studio,robovm/robovm-studio,adedayo/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,jexp/idea2,asedunov/intellij-community,MichaelNedzelsky/intellij-community,jexp/idea2,ivan-fedorov/intellij-community,da1z/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,signed/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,slisson/intellij-community,nicolargo/intellij-community,samthor/intellij-community,petteyg/intellij-community,jagguli/intellij-community,jexp/idea2,izonder/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,ryano144/intellij-community,robovm/robovm-studio,ernestp/consulo,da1z/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,semonte/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,apixandru/intellij-community,supersven/intellij-community,caot/intellij-community,caot/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,amith01994/intellij-community,jagguli/intellij-community,joewalnes/idea-community,amith01994/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,consulo/consulo,semonte/intellij-community,ibinti/intellij-community,adedayo/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,joewalnes/idea-community,adedayo/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,lucafavatella/intellij-community,jagguli/intellij-community,ernestp/consulo,hurricup/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,apixandru/intellij-community,xfournet/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,diorcety/intellij-community,holmes/intellij-community,gnuhub/intellij-community,joewalnes/idea-community,supersven/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,kdwink/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,izonder/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,supersven/intellij-community,xfournet/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,joewalnes/idea-community,xfournet/intellij-community,fitermay/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,diorcety/intellij-community,slisson/intellij-community,vladmm/intellij-community,caot/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,kdwink/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,signed/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,slisson/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,allotria/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,samthor/intellij-community,xfournet/intellij-community,retomerz/intellij-community,joewalnes/idea-community,jagguli/intellij-community,gnuhub/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,samthor/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,da1z/intellij-community,blademainer/intellij-community,asedunov/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,allotria/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,amith01994/intellij-community,hurricup/intellij-community,kdwink/intellij-community,fitermay/intellij-community,asedunov/intellij-community,petteyg/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,holmes/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,jexp/idea2,pwoodworth/intellij-community,robovm/robovm-studio,dslomov/intellij-community,semonte/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,dslomov/intellij-community,retomerz/intellij-community,slisson/intellij-community,vladmm/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,da1z/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,kool79/intellij-community,da1z/intellij-community,supersven/intellij-community,orekyuu/intellij-community,allotria/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,retomerz/intellij-community,fnouama/intellij-community,da1z/intellij-community,dslomov/intellij-community,vladmm/intellij-community,izonder/intellij-community,consulo/consulo,da1z/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,supersven/intellij-community,izonder/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,jexp/idea2,vladmm/intellij-community,izonder/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,diorcety/intellij-community,signed/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,signed/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,clumsy/intellij-community,FHannes/intellij-community,signed/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,FHannes/intellij-community,slisson/intellij-community,jagguli/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,consulo/consulo,vladmm/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,caot/intellij-community,clumsy/intellij-community,signed/intellij-community,kdwink/intellij-community,clumsy/intellij-community,ibinti/intellij-community,ibinti/intellij-community,consulo/consulo,lucafavatella/intellij-community,allotria/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,FHannes/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,idea4bsd/idea4bsd,supersven/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,caot/intellij-community,retomerz/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,jagguli/intellij-community,signed/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,joewalnes/idea-community,ibinti/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,kool79/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,amith01994/intellij-community,ernestp/consulo,kool79/intellij-community,fitermay/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,kool79/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,allotria/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,caot/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,jexp/idea2,tmpgit/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,blademainer/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,holmes/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,mglukhikh/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,vladmm/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,slisson/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,asedunov/intellij-community,petteyg/intellij-community,kool79/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,semonte/intellij-community,supersven/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,ibinti/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,vladmm/intellij-community,blademainer/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,semonte/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,youdonghai/intellij-community,allotria/intellij-community,kool79/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,ibinti/intellij-community,amith01994/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,jexp/idea2,ivan-fedorov/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,petteyg/intellij-community,fnouama/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,holmes/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,xfournet/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,robovm/robovm-studio,semonte/intellij-community,semonte/intellij-community,Lekanich/intellij-community,allotria/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,caot/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,fitermay/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,slisson/intellij-community,supersven/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,kool79/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,signed/intellij-community,izonder/intellij-community,joewalnes/idea-community,FHannes/intellij-community,signed/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,caot/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,slisson/intellij-community,jagguli/intellij-community,allotria/intellij-community,caot/intellij-community,da1z/intellij-community,amith01994/intellij-community,caot/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,signed/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,retomerz/intellij-community,adedayo/intellij-community,adedayo/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ernestp/consulo,ol-loginov/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,fnouama/intellij-community,orekyuu/intellij-community | package com.intellij.ide.todo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.fileTypes.FileTypeEvent;
import com.intellij.openapi.fileTypes.FileTypeListener;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.util.ProgressWindow;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.peer.PeerFactory;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.PsiSearchHelper;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManager;
import com.intellij.ui.content.TabbedPaneContentUI;
import org.jdom.Element;
import javax.swing.*;
import javax.swing.tree.DefaultTreeModel;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Iterator;
/**
* @author Vladimir Kondratyev
*/
public class TodoView implements ProjectComponent,JDOMExternalizable{
private final Project myProject;
private MyPropertyChangeListener myPropertyChangeListener;
private MyFileTypeListener myFileTypeListener;
private ContentManager myContentManager;
private CurrentFileTodosPanel myCurrentFileTodos;
private TodoPanel myAllTodos;
private int mySelectedIndex;
private TodoPanelSettings myCurrentPanelSettings;
private TodoPanelSettings myAllPanelSettings;
/* Invoked by reflection */
TodoView(Project project){
myProject=project;
myCurrentPanelSettings=new TodoPanelSettings();
myAllPanelSettings=new TodoPanelSettings();
}
public void readExternal(Element element) throws InvalidDataException{
mySelectedIndex=0;
try{
mySelectedIndex=Integer.parseInt(element.getAttributeValue("selected-index"));
}catch(NumberFormatException ignored){}
for(Iterator i=element.getChildren().iterator();i.hasNext();){
Element child=(Element)i.next();
if("todo-panel".equals(child.getName())){
String id=child.getAttributeValue("id");
if("selected-file".equals(id)){
myCurrentPanelSettings.readExternal(child);
}else if("all".equals(id)){
myAllPanelSettings.readExternal(child);
}else{
throw new IllegalArgumentException("unknown id: "+id);
}
}
}
}
public void writeExternal(Element element) throws WriteExternalException{
if(myContentManager!=null){ // all panel were constructed
Content content=myContentManager.getSelectedContent();
element.setAttribute("selected-index",Integer.toString(myContentManager.getIndexOfContent(content)));
}
Element selectedFileElement=new Element("todo-panel");
selectedFileElement.setAttribute("id","selected-file");
myCurrentPanelSettings.writeExternal(selectedFileElement);
element.addContent(selectedFileElement);
Element allElement=new Element("todo-panel");
allElement.setAttribute("id","all");
myAllPanelSettings.writeExternal(allElement);
element.addContent(allElement);
}
public void disposeComponent(){}
public String getComponentName(){
return "TodoView";
}
public void initComponent(){}
public void projectClosed(){
TodoConfiguration.getInstance().removePropertyChangeListener(myPropertyChangeListener);
FileTypeManager.getInstance().removeFileTypeListener(myFileTypeListener);
if(myAllTodos!=null){ // Panels can be null if project was closed before starup activities run
myCurrentFileTodos.dispose();
myAllTodos.dispose();
ToolWindowManager toolWindowManager=ToolWindowManager.getInstance(myProject);
toolWindowManager.unregisterToolWindow(ToolWindowId.TODO_VIEW);
}
}
public void projectOpened(){
myPropertyChangeListener=new MyPropertyChangeListener();
TodoConfiguration.getInstance().addPropertyChangeListener(myPropertyChangeListener);
myFileTypeListener=new MyFileTypeListener();
FileTypeManager.getInstance().addFileTypeListener(myFileTypeListener);
StartupManager startupManager=StartupManager.getInstance(myProject);
// it causes building caches for TODOs
startupManager.registerPostStartupActivity(
new Runnable(){
public void run(){
// Create panels
Content allTodosContent=PeerFactory.getInstance().getContentFactory().createContent(null,"Project",false);
myAllTodos=new TodoPanel(myProject,myAllPanelSettings,false,allTodosContent){
protected TodoTreeBuilder createTreeBuilder(JTree tree,DefaultTreeModel treeModel,Project project){
AllTodosTreeBuilder builder=new AllTodosTreeBuilder(tree,treeModel,project);
builder.init();
return builder;
}
};
allTodosContent.setComponent(myAllTodos);
Content currentFileTodosContent=PeerFactory.getInstance().getContentFactory().createContent(null,"Current File",false);
myCurrentFileTodos=new CurrentFileTodosPanel(myProject,myCurrentPanelSettings,currentFileTodosContent){
protected TodoTreeBuilder createTreeBuilder(JTree tree,DefaultTreeModel treeModel,Project project){
CurrentFileTodosTreeBuilder builder=new CurrentFileTodosTreeBuilder(tree,treeModel,project);
builder.init();
return builder;
}
};
currentFileTodosContent.setComponent(myCurrentFileTodos);
// Register tool window
myContentManager=PeerFactory.getInstance().getContentFactory().createContentManager(new TabbedPaneContentUI(),false, myProject);
myContentManager.addContent(allTodosContent);
myContentManager.addContent(currentFileTodosContent);
Content content=myContentManager.getContent(mySelectedIndex);
myContentManager.setSelectedContent(content);
ToolWindowManager toolWindowManager=ToolWindowManager.getInstance(myProject);
ToolWindow toolWindow=toolWindowManager.registerToolWindow(
ToolWindowId.TODO_VIEW,
myContentManager.getComponent(),
ToolWindowAnchor.BOTTOM
);
toolWindow.setIcon(IconLoader.getIcon("/general/toolWindowTodo.png"));
new TodoContentManagerWatcher(toolWindow,myContentManager);
}
}
);
}
private final class MyPropertyChangeListener implements PropertyChangeListener{
/**
* If patterns have been changed the filtes can be touched also. But we have to update
* filters after caches are rebuilded. Therefore if <code>myRebuildInProgress</code>
* is <code>true</code> then it is deferred update of filters.
*/
private boolean myRebuildInProgress;
public void propertyChange(PropertyChangeEvent e){
if (TodoConfiguration.PROP_TODO_PATTERNS.equals(e.getPropertyName())) {
myRebuildInProgress = true;
// this invokeLater guaranties that this code will be invoked after
// PSI gets the same event.
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
// [vova] It's very important to pass null as project. Each TODO view shows own progress
// window. It causes frame switching.
final ProgressWindow progressWindow = new ProgressWindow(false, null);
progressWindow.setTitle("Looking for TODOs...");
progressWindow.setText("Please wait...");
final Runnable process = new Runnable() {
public void run() {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
PsiSearchHelper searchHelper = PsiManager.getInstance(myProject).getSearchHelper();
searchHelper.findFilesWithTodoItems();
}
});
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
updateFilters();
myRebuildInProgress = false;
}
}, ModalityState.NON_MMODAL);
}
};
Thread thread = new Thread(new Runnable() {
public void run() {
ProgressManager.getInstance().runProcess(process, progressWindow);
}
}, "Todo finder");
thread.start();
}
});
}
else if (TodoConfiguration.PROP_TODO_FILTERS.equals(e.getPropertyName())) {
if (!myRebuildInProgress) {
updateFilters();
}
}
}
private void updateFilters(){
myCurrentFileTodos.updateTodoFilter();
myAllTodos.updateTodoFilter();
}
}
private final class MyFileTypeListener implements FileTypeListener{
public void beforeFileTypesChanged(FileTypeEvent event) {
}
public void fileTypesChanged(FileTypeEvent e){
// this invokeLater guaranties that this code will be invoked after
// PSI gets the same event.
ApplicationManager.getApplication().invokeLater(new Runnable(){
public void run(){
// [vova] It's very important to pass null as project. Each TODO view shows own progress
// window. It causes frame switching.
final ProgressWindow progressWindow=new ProgressWindow(false,null);
progressWindow.setTitle("Looking for TODOs...");
progressWindow.setText("Please wait...");
final Runnable process=new Runnable(){
public void run(){
if (myAllTodos == null) return;
ApplicationManager.getApplication().runReadAction(
new Runnable(){
public void run(){
myAllTodos.rebuildCache();
myCurrentFileTodos.rebuildCache();
}
}
);
ApplicationManager.getApplication().invokeLater(new Runnable(){
public void run(){
myAllTodos.updateTree();
myCurrentFileTodos.updateTree();
}
}, ModalityState.NON_MMODAL);
}
};
Thread thread=new Thread(
new Runnable(){
public void run(){
ProgressManager.getInstance().runProcess(process,progressWindow);
}
}, "Todo finder"
);
thread.start();
}
}, ModalityState.NON_MMODAL);
}
}
} | source/com/intellij/ide/todo/TodoView.java | package com.intellij.ide.todo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.fileTypes.FileTypeEvent;
import com.intellij.openapi.fileTypes.FileTypeListener;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.util.ProgressWindow;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.peer.PeerFactory;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.PsiSearchHelper;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManager;
import com.intellij.ui.content.TabbedPaneContentUI;
import org.jdom.Element;
import javax.swing.*;
import javax.swing.tree.DefaultTreeModel;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Iterator;
/**
* @author Vladimir Kondratyev
*/
public class TodoView implements ProjectComponent,JDOMExternalizable{
private final Project myProject;
private MyPropertyChangeListener myPropertyChangeListener;
private MyFileTypeListener myFileTypeListener;
private ContentManager myContentManager;
private CurrentFileTodosPanel myCurrentFileTodos;
private TodoPanel myAllTodos;
private int mySelectedIndex;
private TodoPanelSettings myCurrentPanelSettings;
private TodoPanelSettings myAllPanelSettings;
/* Invoked by reflection */
TodoView(Project project){
myProject=project;
myCurrentPanelSettings=new TodoPanelSettings();
myAllPanelSettings=new TodoPanelSettings();
}
public void readExternal(Element element) throws InvalidDataException{
mySelectedIndex=0;
try{
mySelectedIndex=Integer.parseInt(element.getAttributeValue("selected-index"));
}catch(NumberFormatException ignored){}
for(Iterator i=element.getChildren().iterator();i.hasNext();){
Element child=(Element)i.next();
if("todo-panel".equals(child.getName())){
String id=child.getAttributeValue("id");
if("selected-file".equals(id)){
myCurrentPanelSettings.readExternal(child);
}else if("all".equals(id)){
myAllPanelSettings.readExternal(child);
}else{
throw new IllegalArgumentException("unknown id: "+id);
}
}
}
}
public void writeExternal(Element element) throws WriteExternalException{
if(myContentManager!=null){ // all panel were constructed
Content content=myContentManager.getSelectedContent();
element.setAttribute("selected-index",Integer.toString(myContentManager.getIndexOfContent(content)));
}
Element selectedFileElement=new Element("todo-panel");
selectedFileElement.setAttribute("id","selected-file");
myCurrentPanelSettings.writeExternal(selectedFileElement);
element.addContent(selectedFileElement);
Element allElement=new Element("todo-panel");
allElement.setAttribute("id","all");
myAllPanelSettings.writeExternal(allElement);
element.addContent(allElement);
}
public void disposeComponent(){}
public String getComponentName(){
return "TodoView";
}
public void initComponent(){}
public void projectClosed(){
TodoConfiguration.getInstance().removePropertyChangeListener(myPropertyChangeListener);
FileTypeManager.getInstance().removeFileTypeListener(myFileTypeListener);
if(myAllTodos!=null){ // Panels can be null if project was closed before starup activities run
myCurrentFileTodos.dispose();
myAllTodos.dispose();
ToolWindowManager toolWindowManager=ToolWindowManager.getInstance(myProject);
toolWindowManager.unregisterToolWindow(ToolWindowId.TODO_VIEW);
}
}
public void projectOpened(){
myPropertyChangeListener=new MyPropertyChangeListener();
TodoConfiguration.getInstance().addPropertyChangeListener(myPropertyChangeListener);
myFileTypeListener=new MyFileTypeListener();
FileTypeManager.getInstance().addFileTypeListener(myFileTypeListener);
StartupManager startupManager=StartupManager.getInstance(myProject);
// it causes building caches for TODOs
startupManager.registerPostStartupActivity(
new Runnable(){
public void run(){
// Create panels
Content allTodosContent=PeerFactory.getInstance().getContentFactory().createContent(null,"Project",false);
myAllTodos=new TodoPanel(myProject,myAllPanelSettings,false,allTodosContent){
protected TodoTreeBuilder createTreeBuilder(JTree tree,DefaultTreeModel treeModel,Project project){
AllTodosTreeBuilder builder=new AllTodosTreeBuilder(tree,treeModel,project);
builder.init();
return builder;
}
};
allTodosContent.setComponent(myAllTodos);
Content currentFileTodosContent=PeerFactory.getInstance().getContentFactory().createContent(null,"Current File",false);
myCurrentFileTodos=new CurrentFileTodosPanel(myProject,myCurrentPanelSettings,currentFileTodosContent){
protected TodoTreeBuilder createTreeBuilder(JTree tree,DefaultTreeModel treeModel,Project project){
CurrentFileTodosTreeBuilder builder=new CurrentFileTodosTreeBuilder(tree,treeModel,project);
builder.init();
return builder;
}
};
currentFileTodosContent.setComponent(myCurrentFileTodos);
// Register tool window
myContentManager=PeerFactory.getInstance().getContentFactory().createContentManager(new TabbedPaneContentUI(),false, myProject);
myContentManager.addContent(allTodosContent);
myContentManager.addContent(currentFileTodosContent);
Content content=myContentManager.getContent(mySelectedIndex);
myContentManager.setSelectedContent(content);
ToolWindowManager toolWindowManager=ToolWindowManager.getInstance(myProject);
ToolWindow toolWindow=toolWindowManager.registerToolWindow(
ToolWindowId.TODO_VIEW,
myContentManager.getComponent(),
ToolWindowAnchor.BOTTOM
);
toolWindow.setIcon(IconLoader.getIcon("/general/toolWindowTodo.png"));
new TodoContentManagerWatcher(toolWindow,myContentManager);
}
}
);
}
private final class MyPropertyChangeListener implements PropertyChangeListener{
/**
* If patterns have been changed the filtes can be touched also. But we have to update
* filters after caches are rebuilded. Therefore if <code>myRebuildInProgress</code>
* is <code>true</code> then it is deferred update of filters.
*/
private boolean myRebuildInProgress;
public void propertyChange(PropertyChangeEvent e){
if (TodoConfiguration.PROP_TODO_PATTERNS.equals(e.getPropertyName())) {
myRebuildInProgress = true;
// this invokeLater guaranties that this code will be invoked after
// PSI gets the same event.
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
// [vova] It's very important to pass null as project. Each TODO view shows own progress
// window. It causes frame switching.
final ProgressWindow progressWindow = new ProgressWindow(false, null);
progressWindow.setTitle("Looking for TODOs...");
progressWindow.setText("Please wait...");
final Runnable process = new Runnable() {
public void run() {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
PsiSearchHelper searchHelper = PsiManager.getInstance(myProject).getSearchHelper();
searchHelper.findFilesWithTodoItems();
}
});
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
updateFilters();
myRebuildInProgress = false;
}
}, ModalityState.NON_MMODAL);
}
};
Thread thread = new Thread(new Runnable() {
public void run() {
ProgressManager.getInstance().runProcess(process, progressWindow);
}
}, "Todo finder");
thread.start();
}
});
}
else if (TodoConfiguration.PROP_TODO_FILTERS.equals(e.getPropertyName())) {
if (!myRebuildInProgress) {
updateFilters();
}
}
}
private void updateFilters(){
myCurrentFileTodos.updateTodoFilter();
myAllTodos.updateTodoFilter();
}
}
private final class MyFileTypeListener implements FileTypeListener{
public void beforeFileTypesChanged(FileTypeEvent event) {
}
public void fileTypesChanged(FileTypeEvent e){
// this invokeLater guaranties that this code will be invoked after
// PSI gets the same event.
ApplicationManager.getApplication().invokeLater(new Runnable(){
public void run(){
// [vova] It's very important to pass null as project. Each TODO view shows own progress
// window. It causes frame switching.
final ProgressWindow progressWindow=new ProgressWindow(false,null);
progressWindow.setTitle("Looking for TODOs...");
progressWindow.setText("Please wait...");
final Runnable process=new Runnable(){
public void run(){
if (myAllTodos == null) return;
ApplicationManager.getApplication().runReadAction(
new Runnable(){
public void run(){
myAllTodos.rebuildCache();
myCurrentFileTodos.rebuildCache();
}
}
);
ApplicationManager.getApplication().invokeLater(new Runnable(){
public void run(){
myAllTodos.updateTree();
myCurrentFileTodos.updateTree();
}
}, ModalityState.NON_MMODAL);
}
};
Thread thread=new Thread(
new Runnable(){
public void run(){
ProgressManager.getInstance().runProcess(process,progressWindow);
}
}, "Todo finder"
);
thread.start();
}
});
}
}
} | deadlock fixed
| source/com/intellij/ide/todo/TodoView.java | deadlock fixed |
|
Java | apache-2.0 | 8594dfd3ef43728c6dcccd046654e8dc98ad0c3a | 0 | apache/derby,apache/derby,apache/derby,trejkaz/derby,trejkaz/derby,trejkaz/derby,apache/derby | /*
Derby - Class org.apache.derbyTesting.functionTests.tests.jdbcapi.J2EEDataSourceTest
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derbyTesting.functionTests.tests.jdbcapi;
import java.io.File;
import java.io.Serializable;
import java.security.AccessController;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Savepoint;
import java.util.Hashtable;
import java.util.Iterator;
import javax.sql.ConnectionEvent;
import javax.sql.ConnectionEventListener;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.PooledConnection;
import javax.sql.XAConnection;
import javax.sql.XADataSource;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.derby.jdbc.ClientConnectionPoolDataSource;
import org.apache.derby.jdbc.ClientXADataSource;
import org.apache.derby.jdbc.EmbeddedSimpleDataSource;
import org.apache.derbyTesting.functionTests.util.SecurityCheck;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.CleanDatabaseTestSetup;
import org.apache.derbyTesting.junit.DatabasePropertyTestSetup;
import org.apache.derbyTesting.junit.J2EEDataSource;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.JDBCClient;
import org.apache.derbyTesting.junit.JDBCDataSource;
import org.apache.derbyTesting.junit.TestConfiguration;
/**
* Test the ConnectionPoolDataSource and XADataSource implementations of Derby.
* DataSource functionality common to DataSources including what is
* supported with JSR169 is tested in DataSourceTest.
*
* Performs SecurityCheck analysis on the JDBC objects returned.
* This is because this test returns to the client a number of
* different implementations of Connection, Statement etc.
*
* @see org.apache.derbyTesting.functionTests.util.SecurityCheck
*
*/
public class J2EEDataSourceTest extends BaseJDBCTestCase {
private static final String dbName =
TestConfiguration.getCurrent().getDefaultDatabaseName();
/**
* A hashtable of opened connections. This is used when checking to
* make sure connection strings are unique; we need to make sure all
* the connections are closed when we are done, so they are stored
* in this hashtable
*/
protected static Hashtable conns = new Hashtable();
/** The expected format of a connection string. In English:
* "<classname>@<hashcode> (XID=<xid>), (SESSION = <sessionid>),
* (DATABASE=<dbname>), (DRDAID = <drdaid>)"
*/
private static final String CONNSTRING_FORMAT =
"\\S+@\\-?[0-9]+.* \\(XID = .*\\), \\(SESSIONID = [0-9]+\\), " +
"\\(DATABASE = [A-Za-z]+\\), \\(DRDAID = .*\\) ";
/**
* Hang onto the SecurityCheck class while running the
* tests so that it is not garbage collected during the
* test and lose the information it has collected,
* in case it should get printed out.
*/
private final Object nogc = SecurityCheck.class;
public J2EEDataSourceTest(String name) {
super(name);
}
/**
* Return a suite of tests that are run with a lower lock timeout.
*
* @param postfix suite name postfix
* @return A suite of tests being run with a lower lock timeout.
*/
private static Test getTimeoutSuite(String postfix) {
TestSuite suite = new TestSuite("Lower lock timeout" + postfix);
suite.addTest(new J2EEDataSourceTest("timeoutTestDerby1144PooledDS"));
suite.addTest(new J2EEDataSourceTest("timeoutTestDerby1144XADS"));
// Reduce the timeout threshold to make the tests run faster.
return DatabasePropertyTestSetup.setLockTimeouts(suite, 3, 5);
}
/**
* Return a suite of tests that are run with both client and embedded
*
* @param postfix suite name postfix
* @return A suite of tests to be run with client and/or embedded
*/
private static Test baseSuite(String postfix) {
TestSuite suite = new TestSuite("ClientAndEmbedded" + postfix);
suite.addTest(new J2EEDataSourceTest("testGlobalLocalInterleaf"));
suite.addTest(new J2EEDataSourceTest("testSetIsolationWithStatement"));
suite.addTest(new J2EEDataSourceTest("testJira95xads"));
suite.addTest(new J2EEDataSourceTest("testBadConnectionAttributeSyntax"));
suite.addTest(new J2EEDataSourceTest("testDescriptionProperty"));
suite.addTest(new J2EEDataSourceTest("testConnectionErrorEvent"));
suite.addTest(new J2EEDataSourceTest("testReadOnlyToWritableTran"));
suite.addTest(new J2EEDataSourceTest("testAutoCommitOnXAResourceStart"));
suite.addTest(new J2EEDataSourceTest("testAllDataSources"));
suite.addTest(new J2EEDataSourceTest("testClosedCPDSConnection"));
suite.addTest(new J2EEDataSourceTest("testClosedXADSConnection"));
suite.addTest(new J2EEDataSourceTest("testSetSchemaInXAConnection"));
suite.addTest(new J2EEDataSourceTest("testPooledReuseOnClose"));
return suite;
}
/**
* Return a suite of tests that are run with client only
*
* @return A suite of tests being run with client only
*/
private static Test getClientSuite() {
TestSuite suite = new TestSuite("Client/Server");
suite.addTest(new J2EEDataSourceTest("testClientDSConnectionAttributes"));
suite.addTest(new J2EEDataSourceTest(
"testClientTraceFileDSConnectionAttribute"));
suite.addTest(new J2EEDataSourceTest(
"testClientMessageTextConnectionAttribute"));
return suite;
}
/**
* Return a suite of tests that are run with embedded only
*
* @param postfix suite name postfix
* @return A suite of tests being run with embedded only
*/
private static Test getEmbeddedSuite(String postfix) {
TestSuite suite = new TestSuite("Embedded" + postfix);
suite.addTest(new J2EEDataSourceTest("testDSRequestAuthentication"));
// when DERBY-2498 gets fixed, move this one to baseSuite
suite.addTest(new J2EEDataSourceTest("testJira95pds"));
// Following cannot run with client because of DERBY-2533; it hangs
// when fixed, this can be moved to baseSuite.
suite.addTest(new J2EEDataSourceTest("testReuseAcrossGlobalLocal"));
suite.addTest(new J2EEDataSourceTest("testXAHoldability"));
return suite;
}
public static Test suite() {
if (JDBC.vmSupportsJSR169())
{
// test uses unsupported classes like DriverManager, XADataSource,
// ConnectionPoolDataSource, ConnectionEvenListenere, as well as
// unsupported methods, like Connection.setTypeMap()...
TestSuite suite =
new TestSuite("J2EEDatasourceTest cannot run with JSR169");
return suite;
}
else
{
TestSuite suite = new TestSuite("J2EEDataSourceTest suite");
// Add tests that will run with both embedded
suite.addTest(baseSuite(":embedded"));
// and network server/client
suite.addTest(TestConfiguration.clientServerDecorator(
baseSuite(":client")));
// Add the tests that only run with client
suite.addTest(TestConfiguration.clientServerDecorator(
getClientSuite()));
// Add the tests that only run with embedded
suite.addTest(getEmbeddedSuite("embedded"));
// Add the tests relying on getting timeouts.
suite.addTest(getTimeoutSuite(":embedded"));
suite.addTest(TestConfiguration.clientServerDecorator(
getTimeoutSuite(":client")));
// wrap all in CleanDatabaseTestSetup that creates all database
// objects any fixture might need.
// Note that not all fixtures need (all of) these.
return new CleanDatabaseTestSetup(suite) {
/**
* Create and populate database objects
*
* @see org.apache.derbyTesting.junit.CleanDatabaseTestSetup#decorateSQL(java.sql.Statement)
*/
protected void decorateSQL(Statement s) throws SQLException {
s.executeUpdate("create table autocommitxastart(i int)");
s.executeUpdate("insert into autocommitxastart values 1,2,3,4,5");
s.executeUpdate("create schema SCHEMA_Patricio");
s.executeUpdate("create table " +
"SCHEMA_Patricio.Patricio (id VARCHAR(255), value INTEGER)");
s.executeUpdate("create table intTable(i int)");
s.executeUpdate("create table hold_30 " +
"(id int not null primary key, b char(30))");
s.executeUpdate(
"create procedure checkConn2(in dsname varchar(20)) " +
"parameter style java language java modifies SQL DATA " +
"external name " +
"'org.apache.derbyTesting.functionTests.tests.jdbcapi.J2EEDataSourceTest." +
getNestedMethodName() +
"'");
}
};
}
}
public void tearDown() throws Exception {
// attempt to get rid of any left-over trace files
AccessController.doPrivileged(new java.security.PrivilegedAction() {
public Object run() {
for (int i=0 ; i < 6 ; i++)
{
String traceFileName = "trace" + (i+1) + ".out";
File traceFile = new File(traceFileName);
if (traceFile.exists())
{
// if it exists, attempt to get rid of it
traceFile.delete();
}
}
return null;
}
});
super.tearDown();
}
/* comment out. leaving in, just in case it's ever relevant.
* when uncommented, this will run when network server tests are
* started, and then reflect the results of the embedded checks.
// perform security analysis of the public api for the embedded engine
public void testDataSourceAPI() throws SQLException, ClassNotFoundException
{
SecurityCheck.report();
}
*/
/**
* Test case for DERBY-3172
* When the Derby engine is shutdown or Network Server is brought down, any
* api on JDBC Connection object should generate a Connection error event.
*/
public void testConnectionErrorEvent() throws SQLException, Exception
{
AssertEventCatcher aes12 = new AssertEventCatcher(12);
ConnectionPoolDataSource ds = J2EEDataSource.getConnectionPoolDataSource();
PooledConnection pc = ds.getPooledConnection();
//Add a connection event listener to ConnectionPoolDataSource
pc.addConnectionEventListener(aes12);
Connection conn = pc.getConnection();
dropTable(conn, "TAB1");
//No event should have been generated at this point
assertFalse(aes12.didConnectionClosedEventHappen());
assertFalse(aes12.didConnectionErrorEventHappen());
aes12.resetState();
//Shutdown the Derby engine or Network Server depending on what
//mode we are running in.
if (usingEmbedded())
{
getTestConfiguration().shutdownDatabase();
} else
{
getTestConfiguration().stopNetworkServer();
}
//Now try to use various apis on the JDBC Connection object created
//before shutdown and they all should generate connection error event.
try {
conn.prepareStatement("CREATE TABLE TAB1(COL1 INT NOT NULL)");
} catch (SQLException e) {
//The first call on JDBC Connection object after Network Server
//shutdown will generate a communication error and that's why we
//are checking for SQL State 08006 rather than No current connection
//SQL State 08003. In embedded mode, we will get SQL State 08003
//meaning No current connection
if (usingEmbedded())
assertSQLState("08003", e);
else
assertSQLState("08006", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.prepareStatement("CREATE TABLE TAB1(COL1 INT NOT NULL)", 1);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
int[] columnIndexes = {1};
conn.prepareStatement("CREATE TABLE TAB1(COL1 INT NOT NULL)",
columnIndexes);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
String[] columnNames = {"col1"};
conn.prepareStatement("CREATE TABLE TAB1(COL1 INT NOT NULL)",
columnNames);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.prepareStatement("CREATE TABLE TAB1(COL1 INT NOT NULL)",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.prepareStatement("CREATE TABLE TAB1(COL1 INT NOT NULL)",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.createStatement();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.prepareCall("CREATE TABLE TAB1(COL1 INT NOT NULL)",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.prepareCall("CREATE TABLE TAB1(COL1 INT NOT NULL)");
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.prepareCall("CREATE TABLE TAB1(COL1 INT NOT NULL)",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.nativeSQL("CREATE TABLE TAB1(COL1 INT NOT NULL)");
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.getAutoCommit();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setAutoCommit(false);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.getHoldability();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setHoldability(1);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.commit();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.rollback();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setSavepoint();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setSavepoint("savept1");
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.rollback((Savepoint)null);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.releaseSavepoint((Savepoint)null);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.getTransactionIsolation();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.getWarnings();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.clearWarnings();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.getMetaData();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.isReadOnly();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setReadOnly(true);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setCatalog(null);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.getCatalog();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.getTypeMap();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setTypeMap(null);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
if (usingEmbedded())
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
}else
{
getTestConfiguration().startNetworkServer();
}
// Get a new connection to the database
conn = getConnection();
conn.close();
}
/**
* Test that a PooledConnection can be reused and closed
* (separately) during the close event raised by the
* closing of its logical connection.
* DERBY-2142.
* @throws SQLException
*
*/
public void testPooledReuseOnClose() throws SQLException
{
// PooledConnection from a ConnectionPoolDataSource
ConnectionPoolDataSource cpds =
J2EEDataSource.getConnectionPoolDataSource();
subtestPooledReuseOnClose(cpds.getPooledConnection());
subtestPooledCloseOnClose(cpds.getPooledConnection());
// DERBY-3401 - removing a callback during a close causes problems.
//subtestPooledRemoveListenerOnClose(cpds.getPooledConnection());
// PooledConnection from an XDataSource
XADataSource xads = J2EEDataSource.getXADataSource();
subtestPooledReuseOnClose(xads.getXAConnection());
subtestPooledCloseOnClose(xads.getXAConnection());
// DERBY-3401 - removing a callback during a close causes problems.
//subtestPooledRemoveListenerOnClose(xads.getXAConnection());
}
/**
* Tests that a pooled connection can successfully be reused
* (a new connection obtained from it) during the processing
* of its close event by its listener.
* Sections 11.2 & 12.5 of JDBC 4 specification indicate that the
* connection can be returned to the pool when the
* ConnectionEventListener.connectionClosed() is called.
*/
private void subtestPooledReuseOnClose(final PooledConnection pc) throws SQLException
{
final Connection[] newConn = new Connection[1];
pc.addConnectionEventListener(new ConnectionEventListener() {
/**
* Mimic a pool handler that returns the PooledConnection
* to the pool and then reallocates it to a new logical connection.
*/
public void connectionClosed(ConnectionEvent event) {
PooledConnection pce = (PooledConnection) event.getSource();
assertSame(pc, pce);
try {
// open a new logical connection and pass
// back to the fixture.
newConn[0] = pce.getConnection();
} catch (SQLException e) {
// Need to catch the exception here because
// we cannot throw a checked exception through
// the api method. Wrap it in a RuntimeException.
throw new RuntimeException(e);
}
}
public void connectionErrorOccurred(ConnectionEvent event) {
}
});
// Open a connection then close it to trigger the
// fetching of a new connection in the callback.
Connection c1 = pc.getConnection();
c1.close();
// Fetch the connection created in the close callback
Connection c2 = newConn[0];
assertNotNull(c2);
// Ensure the connection is useable, this hit a NPE before DERBY-2142
// was fixed (for embedded).
c2.createStatement().close();
pc.close();
}
/**
* Tests that a pooled connection can successfully be closed
* during the processing of its close event by its listener.
*/
private void subtestPooledCloseOnClose(final PooledConnection pc) throws SQLException
{
pc.addConnectionEventListener(new ConnectionEventListener() {
/**
* Mimic a pool handler that closes the PooledConnection
* (say it no longer needs it, pool size being reduced)
*/
public void connectionClosed(ConnectionEvent event) {
PooledConnection pce = (PooledConnection) event.getSource();
assertSame(pc, pce);
try {
pce.close();
} catch (SQLException e) {
// Need to catch the exception here because
// we cannot throw a checked exception through
// the api method. Wrap it in a RuntimeException.
throw new RuntimeException(e);
}
}
public void connectionErrorOccurred(ConnectionEvent event) {
}
});
// Open and close a connection to invoke the logic above
// through the callback
pc.getConnection().close();
// The callback closed the actual pooled connection
// so subsequent requests to get a logical connection
// should fail.
try {
pc.getConnection();
fail("PooledConnection should be closed");
} catch (SQLException sqle) {
assertSQLState("08003", sqle);
}
}
/**
* Tests that a listener of a pooled connection can successfully
* remove itself during the processing of its close event by its listener.
*/
private void subtestPooledRemoveListenerOnClose(final PooledConnection pc) throws SQLException
{
final int[] count1 = new int[1];
pc.addConnectionEventListener(new ConnectionEventListener() {
/**
* Mimic a pool handler that removes the listener during
* a logical close.
*/
public void connectionClosed(ConnectionEvent event) {
PooledConnection pce = (PooledConnection) event.getSource();
assertSame(pc, pce);
count1[0]++;
pce.removeConnectionEventListener(this);
}
public void connectionErrorOccurred(ConnectionEvent event) {
}
});
// and have another listener to ensure removing one leaves
// the other working and intact.
final int[] count2 = new int[1];
pc.addConnectionEventListener(new ConnectionEventListener() {
/**
* Mimic a pool handler that closes the PooledConnection
* (say it no longer needs it, pool size being reduced)
*/
public void connectionClosed(ConnectionEvent event) {
PooledConnection pce = (PooledConnection) event.getSource();
assertSame(pc, pce);
count2[0]++;
}
public void connectionErrorOccurred(ConnectionEvent event) {
}
});
// no callback yet
assertEquals(0, count1[0]);
assertEquals(0, count2[0]);
// Open and close a connection to invoke the logic above
// through the callback
pc.getConnection().close();
// one callback for each
assertEquals(1, count1[0]);
assertEquals(1, count2[0]);
// the callback (count1) that was removed is not called on the
// second close but the second callback (count2) is called.
pc.getConnection().close();
assertEquals(1, count1[0]);
assertEquals(2, count2[0]);
pc.close();
}
public void testAllDataSources() throws SQLException, Exception
{
Connection dmc = getConnection();
CallableStatement cs = dmc.prepareCall("call checkConn2(?)");
cs.setString(1,"Nested");
try {
cs.execute();
} catch (SQLException sqle) {
assertSQLState("40XC0", sqle);
}
cs.setString(1,"Nested2");
cs.execute();
String EmptyMapValue=null;
// Note: currently, not supported
String NullMapValue=null;
String MapMapValue=null;
if (usingEmbedded())
{
EmptyMapValue="OK"; NullMapValue="XJ081"; MapMapValue="0A000";
}
else if (usingDerbyNetClient())
{
EmptyMapValue="0A000"; NullMapValue="0A000"; MapMapValue="0A000";
}
Object[] expectedValues = {
new Integer(ResultSet.HOLD_CURSORS_OVER_COMMIT), "XJ010",
new Integer(2), new Boolean(true), new Boolean(false),
EmptyMapValue, NullMapValue, MapMapValue};
assertConnectionOK(expectedValues, "DriverManager ", dmc);
if (usingEmbedded())
assertTenConnectionsUnique();
DataSource dscs = JDBCDataSource.getDataSource();
if (usingEmbedded())
assertToString(dscs);
DataSource ds = dscs;
assertConnectionOK(expectedValues, "DataSource", ds.getConnection());
DataSource dssimple = null;
// simple datasource is only supported with embedded
if (usingEmbedded())
{
EmbeddedSimpleDataSource realdssimple =
new EmbeddedSimpleDataSource();
realdssimple.setDatabaseName(dbName);
ds = realdssimple;
dssimple = (DataSource)realdssimple;
assertConnectionOK(
expectedValues, "SimpleDataSource", ds.getConnection());
}
ConnectionPoolDataSource dsp =
J2EEDataSource.getConnectionPoolDataSource();
if (usingEmbedded())
assertToString(dsp);
PooledConnection pc = dsp.getPooledConnection();
// checks currently only implemented for embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(
pc, "javax.sql.PooledConnection");
}
AssertEventCatcher aes1 = new AssertEventCatcher(1);
pc.addConnectionEventListener(aes1);
// DERBY-2531
// with Network Server / DerbyNetClient, the assertConnectionOK check
// returns a different connection object...
assertConnectionOK(
expectedValues, "ConnectionPoolDataSource", pc.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes1.didConnectionClosedEventHappen());
assertFalse(aes1.didConnectionErrorEventHappen());
aes1.resetState();
assertConnectionOK(
expectedValues, "ConnectionPoolDataSource", pc.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes1.didConnectionClosedEventHappen());
assertFalse(aes1.didConnectionErrorEventHappen());
aes1.resetState();
XADataSource dsx = J2EEDataSource.getXADataSource();
if (usingEmbedded())
assertToString(dsx);
// shutdown db and check all's still ok thereafter
TestConfiguration.getCurrent().shutdownDatabase();
dmc = getConnection();
cs = dmc.prepareCall("call checkConn2(?)");
// checks currently only implemented for embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(
cs, "java.sql.CallableStatement");
}
cs.setString(1,"Nested");
try {
cs.execute();
} catch (SQLException sqle) {
assertSQLState("40XC0", sqle);
}
cs.setString(1, "Nested2");
cs.execute();
XAConnection xac = dsx.getXAConnection();
// checks currently only implemented for embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(xac, "javax.sql.XAConnection");
}
AssertEventCatcher aes3 = new AssertEventCatcher(3);
xac.addConnectionEventListener(aes3);
assertConnectionOK(
expectedValues, "XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes3.didConnectionClosedEventHappen());
assertFalse(aes3.didConnectionErrorEventHappen());
aes3.resetState();
pc = dsp.getPooledConnection();
AssertEventCatcher aes2 = new AssertEventCatcher(2);
pc.addConnectionEventListener(aes2);
assertConnectionOK(
expectedValues, "ConnectionPoolDataSource", pc.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes2.didConnectionClosedEventHappen());
assertFalse(aes2.didConnectionErrorEventHappen());
aes2.resetState();
// test "local" XAConnections
xac = dsx.getXAConnection();
AssertEventCatcher aes4 = new AssertEventCatcher(4);
xac.addConnectionEventListener(aes4);
assertConnectionOK(
expectedValues, "XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes4.didConnectionClosedEventHappen());
assertFalse(aes4.didConnectionErrorEventHappen());
aes4.resetState();
assertConnectionOK(
expectedValues, "XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes4.didConnectionClosedEventHappen());
assertFalse(aes4.didConnectionErrorEventHappen());
aes4.resetState();
xac.close();
// test "global" XAConnections
xac = dsx.getXAConnection();
AssertEventCatcher aes5 = new AssertEventCatcher(5);
xac.addConnectionEventListener(aes5);
XAResource xar = xac.getXAResource();
// checks currently only implemented for embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(
xar, "javax.transaction.xa.XAResource");
}
Xid xid = new cdsXid(1, (byte) 35, (byte) 47);
xar.start(xid, XAResource.TMNOFLAGS);
Connection xacc = xac.getConnection();
xacc.close();
expectedValues[0] = new Integer(ResultSet.CLOSE_CURSORS_AT_COMMIT);
if (usingEmbedded())
expectedValues[1] = "XJ058";
expectedValues[3] = new Boolean(false);
assertConnectionOK(
expectedValues, "Global XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes5.didConnectionClosedEventHappen());
assertFalse(aes5.didConnectionErrorEventHappen());
aes5.resetState();
assertConnectionOK(
expectedValues, "Global XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes5.didConnectionClosedEventHappen());
assertFalse(aes5.didConnectionErrorEventHappen());
aes5.resetState();
xar.end(xid, XAResource.TMSUCCESS);
expectedValues[0] = new Integer(ResultSet.HOLD_CURSORS_OVER_COMMIT);
expectedValues[3] = new Boolean(true);
assertConnectionOK(expectedValues,
"Switch to local XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes5.didConnectionClosedEventHappen());
assertFalse(aes5.didConnectionErrorEventHappen());
aes5.resetState();
assertConnectionOK(expectedValues,
"Switch to local XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes5.didConnectionClosedEventHappen());
assertFalse(aes5.didConnectionErrorEventHappen());
aes5.resetState();
Connection backtoGlobal = xac.getConnection();
xar.start(xid, XAResource.TMJOIN);
expectedValues[0] = new Integer(ResultSet.CLOSE_CURSORS_AT_COMMIT);
expectedValues[3] = new Boolean(false);
assertConnectionOK(expectedValues,
"Switch to global XADataSource", backtoGlobal);
//Check if got connection closed event but not connection error event
assertTrue(aes5.didConnectionClosedEventHappen());
assertFalse(aes5.didConnectionErrorEventHappen());
aes5.resetState();
assertConnectionOK(expectedValues,
"Switch to global XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes5.didConnectionClosedEventHappen());
assertFalse(aes5.didConnectionErrorEventHappen());
aes5.resetState();
xar.end(xid, XAResource.TMSUCCESS);
xar.commit(xid, true);
xac.close();
}
public void testClosedCPDSConnection() throws SQLException, Exception {
// verify that outstanding updates from a closed connection, obtained
// from a ConnectionPoolDataSource, are not committed, but rolled back.
ConnectionPoolDataSource dsp =
J2EEDataSource.getConnectionPoolDataSource();
PooledConnection pc = dsp.getPooledConnection();
Connection c1 = pc.getConnection();
Statement s = c1.createStatement();
// start by deleting all rows from intTable
s.executeUpdate("delete from intTable");
c1.setAutoCommit(false);
// this update should get rolled back later
s.executeUpdate("insert into intTable values(1)");
// this should automatically close the original connection
c1 = pc.getConnection();
ResultSet rs =
c1.createStatement().executeQuery("select count(*) from intTable");
rs.next();
assertEquals(0, rs.getInt(1));
c1.close();
// check connection objects are closed once connection is closed
try {
rs.next();
fail("ResultSet is open for a closed connection obtained from PooledConnection");
} catch (SQLException sqle) {
// 08003 - No current connection; XCL16 - ResultSet not open
if (usingEmbedded())
assertSQLState("08003", sqle);
else if (usingDerbyNetClient())
assertSQLState("XCL16", sqle);
}
try {
s.executeUpdate("update intTable set i = 1");
fail("Statement is open for a closed connection " +
"obtained from PooledConnection");
} catch (SQLException sqle) {
assertSQLState("08003", sqle);
}
pc.close();
pc = null;
PoolReset("ConnectionPoolDataSource", dsp.getPooledConnection());
s.close();
rs.close();
c1.close();
}
public void testClosedXADSConnection() throws SQLException, Exception {
// verify that outstanding updates from a closed connection, obtained
// from an XADataSource, are not committed, but rolled back.
XADataSource dsx = J2EEDataSource.getXADataSource();
XAConnection xac = dsx.getXAConnection();
Connection c1 = xac.getConnection();
Statement s = c1.createStatement();
c1.setAutoCommit(false);
// this update should be rolled back
s.executeUpdate("insert into intTable values(2)");
c1 = xac.getConnection();
ResultSet rs = c1.createStatement().executeQuery(
"select count(*) from intTable");
rs.next();
assertEquals(0, rs.getInt(1));
rs.close();
c1.close();
xac.close();
xac = null;
PoolReset("XADataSource", dsx.getXAConnection());
}
public void testGlobalLocalInterleaf() throws SQLException, XAException {
// now some explicit tests for how connection state behaves
// when switching between global transactions and local
// and setting connection state.
// some of this may be tested elsewhere too.
XADataSource dsx = J2EEDataSource.getXADataSource();
XAConnection xac = dsx.getXAConnection();
AssertEventCatcher aes6 = new AssertEventCatcher(6);
xac.addConnectionEventListener(aes6);
XAResource xar = xac.getXAResource();
Xid xid = new cdsXid(1, (byte) 93, (byte) 103);
// series 1 - Single connection object
Connection cs1 = xac.getConnection();
// initial local
assertConnectionState(
ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
true, false, cs1);
xar.start(xid, XAResource.TMNOFLAGS);
// initial X1
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
false, false, cs1);
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
cs1.setReadOnly(true);
setHoldability(cs1, false); // close cursors
// modified X1
boolean ReadOnly = false;
// see DERBY-911, ReadOnly state different for Embedded/DerbyNetClient
if (usingEmbedded())
ReadOnly = true;
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
false, ReadOnly, cs1);
xar.end(xid, XAResource.TMSUCCESS);
// the underlying local transaction/connection must pick up the
// state of the Connection handle cs1
// modified local:
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
true, ReadOnly, cs1);
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
cs1.setReadOnly(false);
setHoldability(cs1, false); // close cursors
// reset local
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
true, false, cs1);
// now re-join the transaction, should pick up the read-only
// and isolation level from the transaction,
// holdability remains that of this handle.
xar.start(xid, XAResource.TMJOIN);
// re-join X1
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
false, ReadOnly, cs1);
xar.end(xid, XAResource.TMSUCCESS);
// back to local - should be the same as the reset local
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
true, false, cs1);
// test suspend/resume
// now re-join the transaction (X1) for the second time, should pick
// up the read-only and isolation level from the transaction,
// holdability remains that of this handle.
xar.start(xid, XAResource.TMJOIN);
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
false, ReadOnly, cs1);
xar.end(xid, XAResource.TMSUSPEND);
// local after suspend
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
true, false, cs1);
xar.start(xid, XAResource.TMRESUME);
// resume X1
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
false, ReadOnly, cs1);
xar.end(xid, XAResource.TMSUCCESS);
// back to local (second time)
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
true, false, cs1);
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
cs1.setReadOnly(true);
setHoldability(cs1, true); // hold
//Confirm - no connection closed event & connection error event
assertFalse(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
cs1.close();
//Check if got connection closed event but not connection error event
assertTrue(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
cs1 = xac.getConnection();
// new handle - local
assertConnectionState(
ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
true, false, cs1);
cs1.close();
//Check if got connection closed event but not connection error event
assertTrue(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
xar.start(xid, XAResource.TMJOIN);
cs1 = xac.getConnection();
// re-join with new handle X1
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
false, ReadOnly, cs1);
cs1.close();
xar.end(xid, XAResource.TMSUCCESS);
//Check if got connection closed event but not connection error event
assertTrue(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
// now get a connection (attached to a local)
// attach to the global and commit it.
// state should be that of the local after the commit.
cs1 = xac.getConnection();
cs1.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
// pre-X1 commit - local
assertConnectionState(
ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
true, false, cs1);
xar.start(xid, XAResource.TMJOIN);
// pre-X1 commit - X1
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
false, ReadOnly, cs1);
xar.end(xid, XAResource.TMSUCCESS);
// post-X1 end - local
assertConnectionState(
ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
true, false, cs1);
xar.commit(xid, true);
// post-X1 commit - local
assertConnectionState(
ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
true, false, cs1);
//Confirm - no connection closed event & connection error event
assertFalse(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
cs1.close();
//Check if got connection closed event but not connection error event
assertTrue(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
}
// really part of testGlobalLocalInterLeaf:
/**
* @throws SQLException
* @throws XAException
*/
public void testSetIsolationWithStatement()
throws SQLException, XAException {
// DERBY-421 Setting isolation level with SQL was not getting
// handled correctly
// Some more isolation testing using SQL and JDBC api
XADataSource dsx = J2EEDataSource.getXADataSource();
XAConnection xac = dsx.getXAConnection();
AssertEventCatcher aes6 = new AssertEventCatcher(6);
xac.addConnectionEventListener(aes6);
XAResource xar = xac.getXAResource();
Connection conn = xac.getConnection();
Statement s = conn.createStatement();
// initial local
assertConnectionState(
ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
true, false, conn);
// Issue setTransactionIsolation in local transaction
conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
// setTransactionIsolation in local
assertConnectionState(
ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
true, false, conn);
Xid xid;
//Issue SQL to change isolation in local transaction
s.executeUpdate("set current isolation = RR");
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_SERIALIZABLE,
true, false, conn);
xid = new cdsXid(1, (byte) 35, (byte) 47);
xar.start(xid, XAResource.TMNOFLAGS);
// 1st global (new)
assertConnectionState(ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_SERIALIZABLE,
false, false, conn);
xar.end(xid, XAResource.TMSUCCESS);
// local
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_SERIALIZABLE,
true, false, conn);
//Issue SQL to change isolation in local transaction
s.executeUpdate("set current isolation = RS");
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
true, false, conn);
// DERBY-1325 - Isolation level of local connection does not get reset after ending
// a global transaction that was joined/resumed if the isolation level was changed
// using SQL
xar.start(xid, XAResource.TMJOIN);
// 1st global(existing)
assertConnectionState(ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_SERIALIZABLE,
false, false, conn);
xar.end(xid, XAResource.TMSUCCESS);
// local
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
true, false, conn);
// DERBY-1325 end test
Xid xid2 = new cdsXid(1, (byte) 93, (byte) 103);
xar.start(xid2, XAResource.TMNOFLAGS);
// 2nd global (new)
assertConnectionState(ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
false, false, conn);
xar.end(xid2, XAResource.TMSUCCESS);
xar.start(xid, XAResource.TMJOIN);
// 1st global (existing)
assertConnectionState(ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_SERIALIZABLE,
false, false, conn);
xar.end(xid, XAResource.TMSUCCESS);
//local
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
true, false, conn);
xar.start(xid, XAResource.TMJOIN);
// 1st global (existing)
assertConnectionState(ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_SERIALIZABLE,
false, false, conn);
// Issue SQL to change isolation in 1st global transaction
s.executeUpdate("set current isolation = UR");
assertConnectionState(ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
false, false, conn);
xar.end(xid, XAResource.TMSUCCESS);
// local
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
true, false, conn);
xar.start(xid2, XAResource.TMJOIN);
// 2nd global (existing)
assertConnectionState(ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
false, false, conn);
xar.end(xid2, XAResource.TMSUCCESS);
xar.rollback(xid2);
// (After 2nd global rollback ) local
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
true, false, conn);
xar.rollback(xid);
// (After 1st global rollback) local
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
true, false, conn);
//Confirm - no connection closed event & connection error event
assertFalse(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
}
// This test includes some short-hand descriptions of the test cases
// left in for reference to the original non-junit test
public void testReuseAcrossGlobalLocal() throws SQLException, XAException {
// DERBY-2533 -
// network server cannot run this test - it hits a protocol error
// on tearDown. Embedded requires a database shutdown
if (usingDerbyNetClient())
return;
int[] onetwothree = {1,2,3};
int[] three = {3};
int[] pspc = {1, 4}; // expected parameter count for prepared statements
int[] cspc = {2, 12, 12}; // for callable statements
// statics for testReuseAcrossGlobalLocal
int[] StatementExpectedValues = {
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY,
ResultSet.FETCH_REVERSE, 444, 713, 19,
ResultSet.HOLD_CURSORS_OVER_COMMIT};
//ResultSet.CLOSE_CURSORS_AT_COMMIT};
int[] PreparedStatementExpectedValues = {
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY,
ResultSet.FETCH_REVERSE, 888, 317, 91,
ResultSet.HOLD_CURSORS_OVER_COMMIT};
int[] CallableStatementExpectedValues = {
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY,
ResultSet.FETCH_REVERSE, 999, 137, 85,
ResultSet.HOLD_CURSORS_OVER_COMMIT};
XADataSource dsx = J2EEDataSource.getXADataSource();
XAConnection xac = dsx.getXAConnection();
AssertEventCatcher aes6 = new AssertEventCatcher(6);
xac.addConnectionEventListener(aes6);
XAResource xar = xac.getXAResource();
Xid xid = new cdsXid(1, (byte) 103, (byte) 119);
// now check re-use of *Statement objects across local/global
// connections.
Connection cs1 = xac.getConnection();
// ensure read locks stay around until end-of transaction
cs1.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
cs1.setAutoCommit(false);
assertLocks(null, cs1);
Statement sru1 = cs1.createStatement();
sru1.setCursorName("SN1");
sru1.executeUpdate("insert into intTable values 1,2,3");
Statement sruBatch = cs1.createStatement();
sruBatch.setCursorName("sruBatch");
Statement sruState = createFloatStatementForStateChecking(
StatementExpectedValues, cs1);
PreparedStatement psruState = createFloatStatementForStateChecking(
new int[] {1, 4}, PreparedStatementExpectedValues, cs1,
"select i from intTable where i = ?");
CallableStatement csruState = createFloatCallForStateChecking(
new int[] {2, 12, 12}, CallableStatementExpectedValues, cs1,
"CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?,?)");
PreparedStatement psParams =
cs1.prepareStatement("select * from intTable where i > ?");
psParams.setCursorName("params");
psParams.setInt(1, 2);
// Params-local-1
resultSetQuery("params", three, psParams.executeQuery());
sruBatch.addBatch("insert into intTable values 4");
// sru1-local-1
queryOnStatement("SN1", onetwothree, cs1, sru1);
cs1.commit(); // need to commit to switch to an global connection;
// simple case - underlying connection is re-used for global.
xar.start(xid, XAResource.TMNOFLAGS);
// Expecting downgrade because global transaction sru1-global-2 is
// using a statement with holdability true
// sru1-global-2
queryOnStatement("SN1", onetwothree, cs1, sru1);
sruBatch.addBatch("insert into intTable values 5");
Statement sru2 = cs1.createStatement();
sru2.setCursorName("OAK2");
//sru2-global-3
queryOnStatement("OAK2", onetwothree, cs1, sru2);
// Expecting downgrade because global transaction sru1-global-4 is
// using a statement with holdability true
// sru1-global-4
queryOnStatement("SN1", onetwothree, cs1, sru1);
// Global statement
StatementExpectedValues[6] = ResultSet.CLOSE_CURSORS_AT_COMMIT;
PreparedStatementExpectedValues[6] = ResultSet.CLOSE_CURSORS_AT_COMMIT;
CallableStatementExpectedValues[6] = ResultSet.CLOSE_CURSORS_AT_COMMIT;
assertStatementState(null, StatementExpectedValues ,sruState);
// Global PreparedStatement
assertStatementState(pspc, PreparedStatementExpectedValues, psruState);
// Global CallableStatement
assertStatementState(cspc, CallableStatementExpectedValues, csruState);
// Params-global-1
resultSetQuery("params", three, psParams.executeQuery());
xar.end(xid, XAResource.TMSUCCESS);
// now a new underlying connection is created
// sru1-local-5
queryOnStatement("SN1", onetwothree, cs1, sru1);
// sru2-local-6
queryOnStatement("OAK2", onetwothree, cs1, sru2);
sruBatch.addBatch("insert into intTable values 6,7");
Statement sru3 = cs1.createStatement();
sru3.setCursorName("SF3");
// sru3-local-7
queryOnStatement("SF3", onetwothree, cs1, sru3);
// Two transactions should hold locks (global and the current XA);
// LOCAL
StatementExpectedValues[6] = ResultSet.HOLD_CURSORS_OVER_COMMIT;
PreparedStatementExpectedValues[6] = ResultSet.HOLD_CURSORS_OVER_COMMIT;
CallableStatementExpectedValues[6] = ResultSet.HOLD_CURSORS_OVER_COMMIT;
assertStatementState(null, StatementExpectedValues, sruState);
assertStatementState(pspc, PreparedStatementExpectedValues, psruState);
assertStatementState(cspc, CallableStatementExpectedValues, csruState);
// Params-local-2
resultSetQuery("params", three, psParams.executeQuery());
assertLocks(new int[] {14,14}, cs1);
cs1.commit();
//Confirm - no connection closed event & connection error event
assertFalse(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
// attach the XA transaction to another connection and see what happens
XAConnection xac2 = dsx.getXAConnection();
AssertEventCatcher aes5 = new AssertEventCatcher(5);
xac2.addConnectionEventListener(aes5);
XAResource xar2 = xac2.getXAResource();
xar2.start(xid, XAResource.TMJOIN);
Connection cs2 = xac2.getConnection();
// these statements were generated by cs1 and thus are still
// in a local connection.
// sru1-local-8
queryOnStatement("SN1", onetwothree, cs1, sru1);
// sru2-local-9
queryOnStatement("OAK2", onetwothree, cs1, sru2);
// sru3-local-10
queryOnStatement("SF3", onetwothree, cs1, sru3);
sruBatch.addBatch("insert into intTable values 8");
// LOCAL 2
assertStatementState(null, StatementExpectedValues, sruState);
assertStatementState(pspc, PreparedStatementExpectedValues, psruState);
assertStatementState(cspc, CallableStatementExpectedValues, csruState);
assertLocks(new int[] {14, 12}, cs1);
int[] updateCounts = sruBatch.executeBatch();
int[] expectedUpdateCounts = {1, 1, 2, 1};
// sruBatch update counts:
for (int i = 0; i < updateCounts.length; i++) {
assertEquals(expectedUpdateCounts[i], updateCounts[i]);
}
// sruBatch
queryOnStatement(
"sruBatch", new int[] {1,2,3,4,5,6,7,8}, cs1, sruBatch);
xar2.end(xid, XAResource.TMSUCCESS);
//Confirm - no connection closed event & connection error event
assertFalse(aes5.didConnectionClosedEventHappen());
assertFalse(aes5.didConnectionErrorEventHappen());
aes5.resetState();
xac2.close();
// allow close on already closed XAConnection
xac2.close();
xac2.addConnectionEventListener(null);
xac2.removeConnectionEventListener(null);
// test methods against a closed XAConnection and its resource
try {
xac2.getXAResource();
// DERBY-2532
// Network Server does not think this is worth an exception.
if (usingEmbedded())
fail("expected SQLException on " +
"closed XAConnection.getXAResource");
} catch (SQLException sqle) {
assertSQLState("08003", sqle);
}
try {
xac2.getConnection();
fail ("expected SQLException on XAConnection.getConnection");
} catch (SQLException sqle) {
assertSQLState("08003", sqle);
}
try {
xar2.start(xid, XAResource.TMJOIN);
fail ("expected XAException on XAResource.TMJOIN");
} catch (XAException xae) {
assertXAException("XAResource.start", xae);
}
try {
xar2.end(xid, XAResource.TMJOIN);
fail ("expected XAException on XAResource.TMJOIN");
} catch (XAException xae) {
assertXAException("XAResource.end", xae);
}
try {
xar2.commit(xid, true);
fail ("expected XAException on XAResource.commit");
} catch (XAException xae) {
assertXAException("XAResource.commit", xae);
}
try {
xar2.prepare(xid);
fail ("expected XAException on XAResource.prepare");
} catch (XAException xae) {
assertXAException("XAResource.prepare", xae);
}
try {
xar2.recover(0);
fail ("expected XAException on XAResource.recover");
} catch (XAException xae) {
assertXAException("XAResource.recover", xae);
}
try {
xar2.prepare(xid);
fail ("expected XAException on XAResource.prepare");
} catch (XAException xae) {
assertXAException("XAResource.prepare", xae);
}
try {
xar2.isSameRM(xar2);
fail ("expected XAException on XAResource.isSameRM");
} catch (XAException xae) {
assertXAException("XAResource.isSameRM", xae);
}
// close everything
cs1.rollback();
sruState.close();
psruState.close();
csruState.close();
psParams.close();
sruBatch.close();
sru1.close();
sru2.close();
sru3.close();
cs1.close();
cs2.close();
xac.removeConnectionEventListener(null);
xac.close();
xac2.close();
// but, still not enough.
// what with all the switching between global and local transactions
// we still have a lock open on intTable, which will interfere with
// our tearDown efforts. Bounce the database.
TestConfiguration.getCurrent().shutdownDatabase();
}
public void testSetSchemaInXAConnection() throws SQLException {
// tests that set schema works correctly in an XA connection.
XADataSource dsx = J2EEDataSource.getXADataSource();
XAConnection xac3 = dsx.getXAConnection();
Connection conn3 = xac3.getConnection();
Statement st3 = conn3.createStatement();
st3.execute("SET SCHEMA SCHEMA_Patricio");
st3.close();
PreparedStatement ps3 =
conn3.prepareStatement("INSERT INTO Patricio VALUES (?, ?)");
ps3.setString(1, "Patricio");
ps3.setInt(2, 3);
ps3.executeUpdate();
assertEquals(1, ps3.getUpdateCount());
ps3.close();
conn3.close();
xac3.close();
}
// test that an xastart in auto commit mode commits the existing work.
// test fix of a bug ('beetle 5178') wherein XAresource.start() when
// auto-commit is true did not implictly commit any transaction
// Also tests DERBY-1025, same description, but for client.
public void testAutoCommitOnXAResourceStart() throws SQLException, XAException {
XADataSource dsx = J2EEDataSource.getXADataSource();
XAConnection xac4 = dsx.getXAConnection();
Xid xid4a= null;
// We get an XAID_DUP error from networkserver when attempting
// the XAResource.start below if we use the same xid.
// Possibly because we're in the same jvm.
// When the test is run with clientserverSuite, rather than default,
// this wasn't needed, so just create a different id for client
if (usingEmbedded())
xid4a = new cdsXid(4, (byte) 23, (byte) 76);
else if (usingDerbyNetClient())
xid4a = new cdsXid(5, (byte) 23, (byte) 76);
Connection conn4 = xac4.getConnection();
assertTrue(conn4.getAutoCommit());
Statement s4 = conn4.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT);
ResultSet rs4 = s4.executeQuery("select i from autocommitxastart");
rs4.next();
assertEquals(1, rs4.getInt(1));
rs4.next();
assertEquals(2, rs4.getInt(1));
// XAResource().start should commit the transaction
xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS);
xac4.getXAResource().end(xid4a, XAResource.TMSUCCESS);
try {
rs4.next();
fail ("expected an exception indicating resultset is closed.");
} catch (SQLException sqle) {
// Embedded gets 08003. No current connection (DERBY-2620)
if (usingDerbyNetClient())
assertSQLState("XCL16",sqle);
}
conn4.setAutoCommit(false);
assertFalse(conn4.getAutoCommit());
rs4 = s4.executeQuery("select i from autocommitxastart");
rs4.next();
assertEquals(1, rs4.getInt(1));
rs4.next();
assertEquals(2, rs4.getInt(1));
// Get a new xid to begin another transaction.
if (usingEmbedded())
xid4a = new cdsXid(4, (byte) 93, (byte) 103);
else if (usingDerbyNetClient())
xid4a = new cdsXid(5, (byte) 93, (byte) 103);
try {
xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS);
} catch (XAException xae) {
if (usingEmbedded())
assertNull(xae.getMessage());
else if (usingDerbyNetClient())
{
// This should give XAER_OUTSIDE exception because
// the resource manager is busy in the local transaction
assertTrue(xae.getMessage().indexOf("XAER_OUTSIDE") >=0 );
}
assertEquals(-9, xae.errorCode);
}
rs4.next();
assertEquals(3, rs4.getInt(1));
rs4.close();
conn4.rollback();
conn4.close();
xac4.close();
}
public void testReadOnlyToWritableTran() throws SQLException, Exception
{
// This fixture will run twice, once with embedded, once with client,
// and insert 2 rows in addition to the 5 rows inserted during setup.
// The fixture tests a commit, so before running, try to remove row
// 6 and 7 in case this is the second run of the fixture.
Statement s = createStatement();
s.executeUpdate("delete from autocommitxastart where i = 6");
s.executeUpdate("delete from autocommitxastart where i = 7");
// TESTING READ_ONLY TRANSACTION FOLLOWED BY WRITABLE TRANSACTION
// Test following sequence of steps
// 1)start a read-only global transaction
// 2)finish that read-only transaction
// 3)start another global transaction
XADataSource dsx = J2EEDataSource.getXADataSource();
XAConnection xac5 = dsx.getXAConnection();
Xid xid5a = new cdsXid(5, (byte) 119, (byte) 129);
Connection conn5 = xac5.getConnection();
Statement sru5a = conn5.createStatement();
XAResource xar = xac5.getXAResource();
xar.start(xid5a, XAResource.TMNOFLAGS);
conn5.setReadOnly(true);
// Read-Only XA transaction;
// holdability: (hold, or close cursors over commit) ,
// transaction isolation: read-committed,
// auto-commit false, read-only true (with embedded)
if (usingEmbedded())
{
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
false, true, conn5);
}
// Note: the original test had no comments about this difference
// between Embedded and DerbyNetClient, this has apparently
// been accepted behavior.
else if (usingDerbyNetClient())
{
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
false, false, conn5);
}
ResultSet rs5 = sru5a.executeQuery(
"select count(*) from autocommitxastart");
rs5.next();
assertEquals(5, rs5.getInt(1));
rs5.close();
xar.end(xid5a, XAResource.TMSUCCESS);
xar.commit(xid5a, true);
conn5.close();
//now start a new transaction
conn5 = xac5.getConnection();
sru5a = conn5.createStatement();
xar.start(xid5a, XAResource.TMNOFLAGS);
// Writeable XA transaction
// holdability: (hold, or close cursors over commit) ,
// transaction isolation: read-committed,
// auto-commit false, read-only false
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
false, false, conn5);
sru5a.executeUpdate("insert into autocommitxastart values 6,7");
rs5 = sru5a.executeQuery("select count(*) from autocommitxastart");
rs5.next();
assertEquals(7, rs5.getInt(1));
xar.end(xid5a, XAResource.TMSUCCESS);
xar.commit(xid5a, true);
conn5.close();
xac5.close();
sru5a.close();
}
// test jira-derby 95 - a NullPointerException was returned when passing
// an incorrect database name, should now give error XCY00
// with ConnectionPoolDataSource
public void testJira95pds() throws Exception {
try {
ConnectionPoolDataSource pds = J2EEDataSource.getConnectionPoolDataSource();
JDBCDataSource.setBeanProperty(pds, "databaseName", "jdbc:derby:boo");
pds.getPooledConnection();
fail ("expected an SQLException!");
} catch (SQLException sqle) {
// DERBY-2498 - when fixed, remove if
if (usingEmbedded())
assertSQLState("XCY00", sqle);
} catch (Exception e) {
// DERBY-2498 - when fixed, remove if
if (usingEmbedded())
throw e;
}
}
// test jira-derby 95 - a NullPointerException was returned when passing
// an incorrect database name, should now give error XCY00
// with XADataSource
public void testJira95xads() throws SQLException {
try {
XADataSource dxs = J2EEDataSource.getXADataSource();
JDBCDataSource.setBeanProperty(dxs, "databaseName", "jdbc:derby:boo");
dxs.getXAConnection().getConnection();
fail ("expected an SQLException!");
} catch (SQLException sqle) {
assertSQLState("XCY00", sqle);
}
}
// there is a corresponding fixture for datasources in DataSourceTest
public void testBadConnectionAttributeSyntax() throws SQLException {
// ConnectionPoolDataSource - bad connatr syntax
ConnectionPoolDataSource cpds = J2EEDataSource.getConnectionPoolDataSource();
JDBCDataSource.setBeanProperty(cpds, "ConnectionAttributes", "bad");
try {
cpds.getPooledConnection();
fail ("should have seen an error");
} catch (SQLException e) {
assertSQLState("XJ028", e);
}
// XADataSource - bad connattr syntax");
XADataSource xads = J2EEDataSource.getXADataSource();
JDBCDataSource.setBeanProperty(xads, "ConnectionAttributes", "bad");
try {
xads.getXAConnection();
fail ("should have seen an error");
} catch (SQLException e) {
assertSQLState("XJ028", e);
}
} // End testBadConnectionAttributeSyntax
/**
* Check that database name set using setConnectionAttributes is not used
* by ClientDataSource. This method tests DERBY-1130.
*
* @throws SQLException
*/
public void testClientDSConnectionAttributes() throws SQLException {
if (usingEmbedded())
return;
// now with ConnectionPoolDataSource
ClientConnectionPoolDataSource cpds =
new ClientConnectionPoolDataSource();
// ConnectionPoolDataSource - EMPTY
dsConnectionRequests(new String[]
{"08001","08001","08001","08001",
"08001","08001","08001","08001","08001"},
(ConnectionPoolDataSource)cpds);
// ConnectionPoolDataSource
// - connectionAttributes=databaseName=<valid dbname>
cpds.setConnectionAttributes("databaseName=" + dbName);
dsConnectionRequests(new String[]
{"08001","08001","08001","08001",
"08001","08001","08001","08001","08001"},
(ConnectionPoolDataSource)cpds);
cpds.setConnectionAttributes(null);
// Test that database name specified in connection attributes is
// not used
// ConnectionPoolDataSource - databaseName=wombat and
// connectionAttributes=databaseName=kangaroo
cpds.setConnectionAttributes("databaseName=kangaroo");
cpds.setDatabaseName(dbName);
dsConnectionRequests(new String[]
{"OK","08001","OK","OK","08001","08001","OK","OK","OK"},
(ConnectionPoolDataSource)cpds);
cpds.setConnectionAttributes(null);
cpds.setDatabaseName(null);
// now with XADataSource
ClientXADataSource xads = new ClientXADataSource();
// XADataSource - EMPTY
dsConnectionRequests(new String[]
{"08001","08001","08001","08001",
"08001","08001","08001","08001","08001"},
(XADataSource) xads);
// XADataSource - connectionAttributes=databaseName=<valid dbname>
xads.setConnectionAttributes("databaseName=wombat");
dsConnectionRequests(new String[]
{"08001","08001","08001","08001",
"08001","08001","08001","08001","08001"},
(XADataSource) xads);
xads.setConnectionAttributes(null);
// Test that database name specified in connection attributes is not used
// XADataSource - databaseName=wombat and
// connectionAttributes=databaseName=kangaroo
xads.setConnectionAttributes("databaseName=kangaroo");
xads.setDatabaseName("wombat");
dsConnectionRequests(new String[]
{"OK","08001","OK","OK","08001","08001","OK","OK","OK"},
(XADataSource) xads);
xads.setConnectionAttributes(null);
xads.setDatabaseName(null);
} // End testClientDSConnectionAttributes
// Following test is similar to testClientDSConnectionAttributes, but
// for embedded datasources.
// This subtest does not run for network server, it uses
// setAttributesAsPassword, which isn't supported for client datasources.
//
// Note that DataSourceTest has some more basic testing of
// an empty DataSource in a fixture with similar name - however
// that fixture does not test setAttributesAsPassword
public void testDSRequestAuthentication() throws Exception {
// if (usingDerbyNetClient())
// return;
JDBCClient dsclient = getTestConfiguration().getJDBCClient();
String dsName = dsclient.getDataSourceClassName();
DataSource ds = (DataSource) Class.forName(dsName).newInstance();
// DataSource - attributesAsPassword=true");
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.TRUE);
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ028",
"XJ028","XJ004","XJ004","XJ004","XJ004"}, ds);
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.FALSE);
// DataSource - attributesAsPassword=true,
// connectionAttributes=databaseName=kangaroo");
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.TRUE);
JDBCDataSource.setBeanProperty(ds, "connectionAttributes", "databaseName=kangaroo");
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ028",
"XJ028","XJ004","XJ004","XJ004","XJ004"}, ds);
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.FALSE);
JDBCDataSource.clearStringBeanProperty(ds, "connectionAttributes");
// Enable Authentication;
setDatabaseProperty("derby.user.fred", "wilma");
setDatabaseProperty("derby.user.APP", "APP");
setDatabaseProperty("derby.authentication.provider", "BUILTIN");
setDatabaseProperty("derby.connection.requireAuthentication", "true");
JDBCDataSource.setBeanProperty(ds, "shutdownDatabase", "shutdown");
try {
ds.getConnection();
} catch (SQLException sqle) {
assertSQLState("XJ015", sqle);
}
JDBCDataSource.clearStringBeanProperty(ds, "databaseName");
JDBCDataSource.clearStringBeanProperty(ds, "shutdownDatabase");
// "AUTHENTICATION NOW ENABLED");
// DataSource - attributesAsPassword=true
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.TRUE);
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ028",
"XJ028","XJ004","XJ004","XJ004","XJ004"}, ds);
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.FALSE);
// ensure the DS property password is not treated as a set of
// attributes.
// DataSource - attributesAsPassword=true, user=fred,
// password=databaseName=wombat;password=wilma
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.TRUE);
JDBCDataSource.setBeanProperty(ds, "user", "fred");
JDBCDataSource.setBeanProperty(ds, "password", "databaseName=" + dbName + ";password=wilma");
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ028",
"XJ028","XJ004","XJ004","XJ004","XJ004"}, ds);
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.FALSE);
JDBCDataSource.clearStringBeanProperty(ds, "user");
JDBCDataSource.clearStringBeanProperty(ds, "password");
ds = null;
// now with ConnectionPoolDataSource
String cpdsName = dsclient.getConnectionPoolDataSourceClassName();
ConnectionPoolDataSource cpds =
(ConnectionPoolDataSource) Class.forName(cpdsName).newInstance();
// ConnectionPoolDataSource - EMPTY
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ004",
"XJ004","XJ004","XJ004","XJ004","XJ004"},
(ConnectionPoolDataSource)cpds);
// ConnectionPoolDataSource -
// connectionAttributes=databaseName=wombat
JDBCDataSource.setBeanProperty(cpds, "connectionAttributes", "databaseName=" + dbName);
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ004",
"XJ004","XJ004","XJ004","XJ004","XJ004"},
(ConnectionPoolDataSource)cpds);
JDBCDataSource.clearStringBeanProperty(cpds, "connectionAttributes");
// ConnectionPoolDataSource - attributesAsPassword=true
JDBCDataSource.setBeanProperty(cpds, "attributesAsPassword", Boolean.TRUE);
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ028",
"XJ028","XJ004","XJ004","XJ004","XJ004"},
(ConnectionPoolDataSource)cpds);
JDBCDataSource.setBeanProperty(cpds, "attributesAsPassword", Boolean.FALSE);
// ensure the DS property password is not treated as a set of
// attributes.
// ConnectionPoolDataSource - attributesAsPassword=true,
// user=fred, password=databaseName=wombat;password=wilma");
JDBCDataSource.setBeanProperty(cpds, "attributesAsPassword", Boolean.TRUE);
JDBCDataSource.setBeanProperty(cpds, "user", "fred");
JDBCDataSource.setBeanProperty(cpds, "password", "databaseName=" + dbName + ";password=wilma");
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ028",
"XJ028","XJ004","XJ004","XJ004","XJ004"},
(ConnectionPoolDataSource)cpds);
JDBCDataSource.setBeanProperty(cpds, "attributesAsPassword", Boolean.FALSE);
JDBCDataSource.clearStringBeanProperty(cpds, "user");
JDBCDataSource.clearStringBeanProperty(cpds, "password");
cpds = null;
// now with XADataSource
// EmbeddedXADataSource xads = new EmbeddedXADataSource();
String xadsName = dsclient.getXADataSourceClassName();
XADataSource xads =
(XADataSource) Class.forName(xadsName).newInstance();
// XADataSource - EMPTY
dsConnectionRequests(new String[] {
"08006","08006","08006","08006",
"08006","08006","08006","08006","08006"},
(XADataSource) xads);
// XADataSource - databaseName=wombat
JDBCDataSource.setBeanProperty(xads, "databaseName", dbName);
dsConnectionRequests(new String[] {
"08004","08004","08004","OK",
"08004","08004","08004","08004","08004"},
(XADataSource) xads);
JDBCDataSource.clearStringBeanProperty(xads, "databaseName");
// XADataSource - connectionAttributes=databaseName=wombat");
JDBCDataSource.setBeanProperty(xads, "connectionAttributes", "databaseName=" + dbName);
dsConnectionRequests(new String[] {
"08006","08006","08006","08006",
"08006","08006","08006","08006","08006"},
(XADataSource) xads);
JDBCDataSource.clearStringBeanProperty(xads, "connectionAttributes");
// XADataSource - attributesAsPassword=true
JDBCDataSource.setBeanProperty(xads, "attributesAsPassword", Boolean.TRUE);
dsConnectionRequests(new String[] {
"08006","08006","08006","08006",
"08006","08006","08006","08006","08006"},
(XADataSource) xads);
JDBCDataSource.setBeanProperty(xads, "attributesAsPassword", Boolean.FALSE);
// XADataSource - databaseName=wombat, attributesAsPassword=true
JDBCDataSource.setBeanProperty(xads, "databaseName", dbName);
JDBCDataSource.setBeanProperty(xads, "attributesAsPassword", Boolean.TRUE);
dsConnectionRequests(new String[] {
"08004","08004","08004","XJ028",
"XJ028","08004","08004","OK","08004"},
(XADataSource) xads);
JDBCDataSource.setBeanProperty(xads, "attributesAsPassword", Boolean.FALSE);
JDBCDataSource.clearStringBeanProperty(xads, "databaseName");
setDatabaseProperty("derby.connection.requireAuthentication", "false");
TestConfiguration.getCurrent().shutdownDatabase();
}
/**
* Check that traceFile connection attribute functions correctly.
* tracefile was tested in checkDriver, but not for DataSources.
* tracefile= was used in datasourcepermissions_net, but that's
* incorrect syntax. Note that we're not checking the contents of
* the tracefile.
*
* Note also that this test cannot run against a remote server.
*
* @throws SQLException
*/
public void testClientTraceFileDSConnectionAttribute() throws SQLException
{
if (usingEmbedded())
return;
String traceFile;
// with ConnectionPoolDataSource
ConnectionPoolDataSource cpds = J2EEDataSource.getConnectionPoolDataSource();
traceFile = "trace3.out";
JDBCDataSource.setBeanProperty(cpds, "connectionAttributes",
"traceFile="+traceFile);
// DERBY-2468 - trace3.out does not get created
((ClientConnectionPoolDataSource) cpds).getConnection();
JDBCDataSource.clearStringBeanProperty(cpds, "connectionAttributes");
traceFile = "trace4.out";
JDBCDataSource.setBeanProperty(cpds, "traceFile", traceFile);
((ClientConnectionPoolDataSource) cpds).getConnection();
cpds = null;
// now with XADataSource
XADataSource xads = J2EEDataSource.getXADataSource();
traceFile = "trace5.out";
JDBCDataSource.setBeanProperty(xads, "connectionAttributes",
"traceFile="+traceFile);
((ClientXADataSource) xads).getConnection();
// DERBY-2468 - trace5.out does not get created
JDBCDataSource.clearStringBeanProperty(xads, "connectionAttributes");
traceFile = "trace6.out";
JDBCDataSource.setBeanProperty(xads, "traceFile", traceFile);
((ClientXADataSource) xads).getConnection();
assertTraceFilesExist();
}
/* -- Helper Methods for testClientTraceFileDSConnectionAttribute -- */
/**
* Check that trace file exists in <framework> directory
*/
private static void assertTraceFilesExist()
{
AccessController.doPrivileged(new java.security.PrivilegedAction() {
public Object run() {
for (int i=3 ; i < 6 ; i++)
{
String traceFileName = "trace" + (i+1) + ".out";
File traceFile = new File(traceFileName);
if (i == 4)
continue;
else
{
assertTrue(traceFile.exists());
}
}
return null;
}
});
}
/**
* Check that messageText connection attribute functions correctly.
* retrievemessagetext was tested in checkdriver, and derbynet/testij,
* but not tested for datasources, and in datasourcepermissions_net,
* but as it has nothing to do with permissions/authentication,
* this test seems a better place for it.
*
* There is a corresponding fixture for clientDataSource in DataSourceTest
*
* @throws SQLException
*/
public void testClientMessageTextConnectionAttribute() throws SQLException
{
if (usingEmbedded())
return;
String retrieveMessageTextProperty = "retrieveMessageText";
Connection conn;
// with ConnectionPoolDataSource
// ConnectionPoolDataSource - retrieveMessageTextProperty
ClientConnectionPoolDataSource cpds = new ClientConnectionPoolDataSource();
cpds.setDatabaseName(dbName);
cpds.setConnectionAttributes(
retrieveMessageTextProperty + "=false");
conn = cpds.getConnection();
assertMessageText(conn,"false");
conn.close();
cpds.setConnectionAttributes(
retrieveMessageTextProperty + "=true");
conn = cpds.getConnection();
assertMessageText(conn,"true");
cpds.setConnectionAttributes(null);
conn.close();
// now with XADataSource
ClientXADataSource xads = new ClientXADataSource();
//XADataSource - retrieveMessageTextProperty
xads.setDatabaseName(dbName);
xads.setConnectionAttributes(
retrieveMessageTextProperty + "=false");
conn = xads.getConnection();
assertMessageText(conn,"false");
conn.close();
xads.setConnectionAttributes(
retrieveMessageTextProperty + "=true");
conn = xads.getConnection();
assertMessageText(conn,"true");
conn.close();
xads.setConnectionAttributes(null);
}
/* -- Helper Method for testClientMessageTextDSConnectionAttribute -- */
private static void assertMessageText(
Connection conn, String retrieveMessageTextValue)
throws SQLException
{
try {
conn.createStatement().executeQuery("SELECT * FROM APP.NOTTHERE");
}
catch (SQLException e)
{
assertSQLState("42X05", e);
if (retrieveMessageTextValue.equals("true") )
{
assertTrue(e.getMessage().indexOf("does not exist") >= 0);
}
else
{
// retrieveMessageTextValue is false
assertTrue(e.getMessage().indexOf("does not exist") == -1);
}
}
}
/**
* Check that messageText connection attribute functions correctly.
* retrievemessagetext was tested in checkdriver, and derbynet/testij
* (but not tested for datasources), and in datasourcepermissions_net,
* but as it has nothing to do with permissions/authentication,
* this test seems a better place for it.
*
* there is a corresponding method call for datasources in DataSourceTest
*
* @throws SQLException
*/
public void testDescriptionProperty()
throws SQLException, Exception {
// ConnectionPoolDataSource - setDescription
subTestDataSourceDescription(
(DataSource) J2EEDataSource.getConnectionPoolDataSource());
// XADataSource - setDescription
subTestDataSourceDescription(
(DataSource) J2EEDataSource.getXADataSource());
}
/**
* Utility method for testing setting and fetching the description
* property on a data source.
*/
private void subTestDataSourceDescription(DataSource ds) throws Exception
{
String setDescription =
"Everything you ever wanted to know about this datasource";
JDBCDataSource.setBeanProperty(ds, "description", setDescription);
ds.getConnection();
assertEquals(setDescription, JDBCDataSource.getBeanProperty(ds, "description"));
JDBCDataSource.clearStringBeanProperty(ds, "description");
assertNull(JDBCDataSource.getBeanProperty(ds, "description"));
}
/* ------------------ JDBC30 (and up) Fixtures ------------------ */
public void testXAHoldability() throws SQLException, XAException {
// DERBY-2533 -
// This test, when run with Network server / DerbyNetClient
// leaves the database is a bad state which results in a
// network protocol error
if (usingDerbyNetClient())
return;
// START XA HOLDABILITY TEST
XADataSource dscsx = J2EEDataSource.getXADataSource();
XAConnection xac = dscsx.getXAConnection();
XAResource xr = xac.getXAResource();
Xid xid = new cdsXid(25, (byte) 21, (byte) 01);
Connection conn1 = xac.getConnection();
// check that autocommit is true; default for a connection
assertTrue(conn1.getAutoCommit());
// check that holdability is HOLD_CURSORS_OVER_COMMIT in a default
// CONNECTION(not in xa transaction yet)
assertEquals(
ResultSet.HOLD_CURSORS_OVER_COMMIT, conn1.getHoldability());
// start a global transaction and default holdability and
// autocommit will be switched to match Derby XA restrictions
xr.start(xid, XAResource.TMNOFLAGS);
// So, now autocommit should be false for connection because it is
// part of the global transaction
assertFalse(conn1.getAutoCommit());
// Connection's holdability is now CLOSE_CURSORS_AT_COMMIT because
// it is part of the global transaction
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT, conn1.getHoldability());
xr.end(xid, XAResource.TMSUCCESS);
conn1.commit();
conn1.close();
xid = new cdsXid(27, (byte) 21, (byte) 01);
xr.start(xid, XAResource.TMNOFLAGS);
conn1 = xac.getConnection();
// CONNECTION(in xa transaction) HOLDABILITY:
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT, conn1.getHoldability());
// Autocommit on Connection inside global transaction should be false
assertFalse(conn1.getAutoCommit());
xr.end(xid, XAResource.TMSUCCESS);
conn1.rollback();
Connection conn = xac.getConnection();
conn.setAutoCommit(false);
conn.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
// CONNECTION(non-xa transaction) HOLDABILITY:
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT, conn.getHoldability());
Statement s = conn.createStatement();
// STATEMENT HOLDABILITY:
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT, s.getResultSetHoldability());
s.executeUpdate("insert into hold_30 values " +
"(1,'init2'), (2, 'init3'), (3,'init3')");
s.executeUpdate("insert into hold_30 values " +
"(4,'init4'), (5, 'init5'), (6,'init6')");
s.executeUpdate("insert into hold_30 values " +
"(7,'init7'), (8, 'init8'), (9,'init9')");
// STATEMENT HOLDABILITY :
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT, s.getResultSetHoldability());
Statement sh = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT);
PreparedStatement psh = conn.prepareStatement(
"select id from hold_30 for update", ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT);
CallableStatement csh = conn.prepareCall(
"select id from hold_30 for update", ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT);
// STATEMENT HOLDABILITY :
assertEquals(
ResultSet.HOLD_CURSORS_OVER_COMMIT, sh.getResultSetHoldability());
// PREPARED STATEMENT HOLDABILITY :
assertEquals(
ResultSet.HOLD_CURSORS_OVER_COMMIT, psh.getResultSetHoldability());
// CALLABLE STATEMENT HOLDABILITY :
assertEquals(
ResultSet.HOLD_CURSORS_OVER_COMMIT, csh.getResultSetHoldability());
ResultSet rsh = sh.executeQuery("select id from hold_30 for update");
rsh.next();
assertEquals(1, rsh.getInt(1)); // H@1 id
rsh.next();
assertEquals(2, rsh.getInt(1)); // H@2 id
conn.commit();
rsh.next();
assertEquals(3, rsh.getInt(1)); // H@3 id
conn.commit();
xid = new cdsXid(23, (byte) 21, (byte) 01);
xr.start(xid, XAResource.TMNOFLAGS);
Statement stmtInsideGlobalTransaction = conn.createStatement();
PreparedStatement prepstmtInsideGlobalTransaction =
conn.prepareStatement("select id from hold_30");
CallableStatement callablestmtInsideGlobalTransaction =
conn.prepareCall("select id from hold_30");
// CONNECTION(xa) HOLDABILITY:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, conn.getHoldability());
// STATEMENT(this one was created with holdability false, outside the
// global transaction. Check its holdability inside global transaction
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT, s.getResultSetHoldability());
// STATEMENT(this one was created with holdability true,
// outside the global transaction. Check its holdability inside
// global transaction:
// DERBY-2531: network server / DerbyNetClient has a different value
// than embedded.
if (usingEmbedded())
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
sh.getResultSetHoldability());
else if (usingDerbyNetClient())
assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT,
sh.getResultSetHoldability());
// STATEMENT(this one was created with default holdability inside this
// global transaction. Check its holdability:
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
stmtInsideGlobalTransaction.getResultSetHoldability());
// PREPAREDSTATEMENT(this one was created with default holdability
// inside this global transaction. Check its holdability:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
prepstmtInsideGlobalTransaction.getResultSetHoldability());
// CALLABLESTATEMENT(this one was created with default holdability
// inside this global transaction. Check its holdability:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
callablestmtInsideGlobalTransaction.getResultSetHoldability());
ResultSet rsx = s.executeQuery("select id from hold_30 for update");
rsx.next();
assertEquals(1, rsx.getInt(1)); // X@1 id
rsx.next();
assertEquals(2, rsx.getInt(1)); // X@2 id
xr.end(xid, XAResource.TMSUCCESS);
// result set should not be useable, since it is part of a detached
// XAConnection
try {
rsx.next();
fail("rsx's connection not active id ");
} catch (SQLException sqle) {
assertSQLState("08003", sqle);
}
// result set should not be useable, it should have been closed by
// the xa start.
try {
rsh.next();
fail("rsh's connection not active id ");
} catch (SQLException sqle) {
assertSQLState("XCL16", sqle);
}
// resume XA transaction and keep using rs");
xr.start(xid, XAResource.TMJOIN);
Statement stmtAfterGlobalTransactionResume = conn.createStatement();
PreparedStatement prepstmtAfterGlobalTransactionResume =
conn.prepareStatement("select id from hold_30");
CallableStatement callablestmtAfterGlobalTransactionResume =
conn.prepareCall("select id from hold_30");
// Check holdability of various jdbc objects after resuming XA
// transaction
// CONNECTION(xa) HOLDABILITY:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,conn.getHoldability());
// STATEMENT(this one was created with holdability false, outside the
// global transaction. Check its holdability inside global transaction
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT, s.getResultSetHoldability());
// STATEMENT(this one was created with holdability true, outside the
// global transaction. Check its holdability inside global transaction
if (usingEmbedded())
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
sh.getResultSetHoldability());
else if (usingDerbyNetClient())
assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT,
sh.getResultSetHoldability());
// STATEMENT(this one was created with default holdability inside the
// global transaction when it was first started. Check its holdability
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
stmtInsideGlobalTransaction.getResultSetHoldability());
// PREPAREDSTATEMENT(this one was created with default holdability
// inside the global transaction when it was first started. Check its
// holdability)
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
prepstmtInsideGlobalTransaction.getResultSetHoldability());
// CALLABLESTATEMENT(this one was created with default holdability
// inside the global transaction when it was first started. Check its
// holdability) HOLDABILITY
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
callablestmtInsideGlobalTransaction.getResultSetHoldability());
// STATEMENT(this one was created with default holdability after the
// global transaction was resumed. Check its holdability
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
stmtAfterGlobalTransactionResume.getResultSetHoldability());
// PREPAREDSTATEMENT(this one was created with default holdability
// after the global transaction was resumed. Check its holdability
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
prepstmtAfterGlobalTransactionResume.getResultSetHoldability());
// CALLABLESTATEMENT(this one was created with default holdability
// after the global transaction was resumed. Check its holdability
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
callablestmtAfterGlobalTransactionResume.getResultSetHoldability());
// DERBY-1370
if (usingEmbedded())
{
// Network XA BUG gives result set closed
rsx.next();
assertEquals(3, rsx.getInt(1)); // X@3 id
}
xr.end(xid, XAResource.TMSUCCESS);
if (xr.prepare(xid) != XAResource.XA_RDONLY)
xr.commit(xid, false);
// try again once the xa transaction has been committed.
try {
rsx.next();
fail("rsx's connection not active id (B)");
} catch (SQLException sqle) {
assertSQLState("XCL16", sqle);
}
try {
rsh.next();
fail ("rsh's should be closed (B)");
} catch (SQLException sqle) {
assertSQLState("XCL16", sqle);
}
// Set connection to hold
conn.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
// CONNECTION(held) HOLDABILITY:
assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT,
conn.getHoldability());
xid = new cdsXid(24, (byte) 21, (byte) 01);
xr.start(xid, XAResource.TMNOFLAGS);
// CONNECTION(xa) HOLDABILITY:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, conn.getHoldability());
try {
conn.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
fail("allowed to set hold mode in xa transaction");
} catch (SQLException sqle) {
assertSQLState("XJ05C", sqle);
}
// JDBC 4.0 (proposed final draft) section 16.1.3.1 allows Statements
// to be created with a different holdability if the driver cannot
// support it. In this case the driver does not support holdability in
// a global transaction, so a valid statement is returned with close
// cursors on commit.
Statement shxa = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT);
// HOLDABLE Statement in global xact "
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
s.getResultSetHoldability());
assertEquals(10000, conn.getWarnings().getErrorCode());
shxa.close();
shxa = conn.prepareStatement("select id from hold_30",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
// HOLDABLE PreparedStatement in global xact
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
s.getResultSetHoldability());
assertEquals(10000, conn.getWarnings().getErrorCode());
shxa.close();
shxa = conn.prepareCall("CALL SYSCS_UTIL.SYSCS_CHECKPOINT_DATABASE()",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
// HOLDABLE CallableStatement in global xact:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
s.getResultSetHoldability());
assertEquals(10000, conn.getWarnings().getErrorCode());
shxa.close();
// check we can use a holdable statement set up in local mode.
// holdability is downgraded, tested in XATest.java
// DERBY-1370
if(usingEmbedded()) {
// STATEMENT HOLDABILITY:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
sh.getResultSetHoldability());
sh.executeQuery("select id from hold_30").close();
sh.execute("select id from hold_30");
sh.getResultSet().close();
// PREPARED STATEMENT HOLDABILITY:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
psh.getResultSetHoldability());
psh.executeQuery().close();
psh.execute();
psh.getResultSet().close();
// CALLABLE STATEMENT HOLDABILITY:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
csh.getResultSetHoldability());
csh.executeQuery().close();
csh.execute();
csh.getResultSet().close();
}
// but an update works
sh.executeUpdate("insert into hold_30 values(10, 'init10')");
xr.end(xid, XAResource.TMSUCCESS);
// CONNECTION(held) HOLDABILITY:
assertEquals(
ResultSet.HOLD_CURSORS_OVER_COMMIT, conn.getHoldability());
s.close();
sh.close();
csh.close();
psh.close();
rsx.close();
stmtInsideGlobalTransaction.close();
prepstmtInsideGlobalTransaction.close();
callablestmtInsideGlobalTransaction.close();
stmtAfterGlobalTransactionResume.close();
prepstmtAfterGlobalTransactionResume.close();
callablestmtAfterGlobalTransactionResume.close();
conn.close();
xac.close();
TestConfiguration.getCurrent().shutdownDatabase();
// END XA HOLDABILITY TEST");
}
/**
* Tests that DatabaseMetaData.getConnection does not leak references to
* physical connections or other logical connections.
*
* @throws SQLException if something goes wrong
*/
// Disabled because the test fails. It fails in different ways for client
// and embedded. See DERBY-3431 for information.
// To enable, remove 'DISABLED_' from the method name and add the test
// to the appropriate suite (i.e. baseSuite).
public void DISABLED_testConnectionLeakInDatabaseMetaData()
throws SQLException {
ConnectionPoolDataSource cpDs =
J2EEDataSource.getConnectionPoolDataSource();
PooledConnection pc = cpDs.getPooledConnection();
// Get first logical connection and a meta data object.
Connection con1 = pc.getConnection();
DatabaseMetaData dmd1 = con1.getMetaData();
assertSame(con1, dmd1.getConnection());
con1.close();
// Get second logical connection and a meta data object.
Connection con2 = pc.getConnection();
DatabaseMetaData dmd2 = con2.getMetaData();
con2.close();
pc.close();
// The first meta data object should not return a reference to the
// second logical connection.
assertSame(con2, dmd2.getConnection());
assertNotSame(con2, dmd1.getConnection());
}
/**
* Tests for DERBY-1144
*
* This test tests that holdability, autocomit, and transactionIsolation
* are reset on getConnection for PooledConnections obtaind from
* connectionPoolDataSources
*
* DERBY-1134 has been filed for more comprehensive testing of client
* connection state.
*
* @throws SQLException
*/
public void timeoutTestDerby1144PooledDS() throws SQLException {
PooledConnection pc1 = null;
// Test holdability
ConnectionPoolDataSource ds =
J2EEDataSource.getConnectionPoolDataSource();
pc1 = ds.getPooledConnection();
assertPooledConnHoldability("PooledConnection", pc1);
pc1.close();
// Test autocommit
pc1 = ds.getPooledConnection();
assertPooledConnAutoCommit("PooledConnection", pc1);
pc1.close();
// Test pooled connection isolation
pc1 = ds.getPooledConnection();
assertPooledConnIso("PooledConnection" , pc1);
pc1.close();
}
public void timeoutTestDerby1144XADS() throws SQLException {
XADataSource xds = J2EEDataSource.getXADataSource();
// Test xa connection isolation
XAConnection xpc1 = xds.getXAConnection();
assertPooledConnIso("XAConnection", xpc1);
xpc1.close();
}
/* -------------- Helper Methods for testDerby1144 -------------- */
/**
* Make sure autocommit gets reset on PooledConnection.getConnection()
* @param desc description of connection
* @param pc1 pooled connection to test
* @throws SQLException
*/
private static void assertPooledConnAutoCommit(
String desc, PooledConnection pc1) throws SQLException
{
// ** Verify autoCommit state
Connection conn = pc1.getConnection();
conn.setAutoCommit(true);
// reset the connection and see if the autocommit has changed
conn = pc1.getConnection();
boolean autocommit = conn.getAutoCommit();
// autocommit should get reset on getConnection
assertTrue(autocommit);
conn.close();
}
/**
* Checks that Holdability gets reset on PooledConnection.getConnection()
* @param desc
* @param pc1
* @throws SQLException
*/
private static void assertPooledConnHoldability(
String desc, PooledConnection pc1) throws SQLException
{
// **Test holdability state
Connection conn = pc1.getConnection();
conn.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
// reset the connection and see if the holdability gets reset
// to HOLD_CURSORS_OVER_COMMIT
conn = pc1.getConnection();
assertConnHoldability(conn, ResultSet.HOLD_CURSORS_OVER_COMMIT);
conn.close();
}
/**
* Verify connection holdablity is expected holdability
* @param conn
* @param expectedHoldability
* * @throws SQLException
*/
private static void assertConnHoldability(
Connection conn, int expectedHoldability) throws SQLException
{
int holdability = conn.getHoldability();
assertEquals (expectedHoldability, holdability);
}
/**
* Test that isolation is reset on PooledConnection.getConnection()
* @param pooledConnType Descripiton of the type of pooled connection
* @param pc PooledConnection or XAConnection
* @throws SQLException
*/
private void assertPooledConnIso(
String pooledConnType, PooledConnection pc) throws SQLException {
Connection conn = pc.getConnection();
setupDerby1144Table(conn);
// *** Test isolation level reset on conntype.getConnection()
conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
assertIsoLocks(conn, Connection.TRANSACTION_READ_UNCOMMITTED);
conn.close();
//Get a new connection with pooledConnType.getConnection()
// Isolation level should be reset to READ_COMMITTED
Connection newconn = pc.getConnection();
assertIsoLocks(newconn, Connection.TRANSACTION_READ_COMMITTED);
}
/*
* insert two rows into the simple table for DERBY-1144 tests
* @param conn
* @throws SQLException
*/
private static void setupDerby1144Table(Connection conn)
throws SQLException {
Statement stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO intTable VALUES(1)");
stmt.executeUpdate("INSERT INTO intTable VALUES(2)");
conn.commit ();
}
/*
* Checks locks for designated isolation level on the connection.
* Currently only supports TRANSACTION_READ_COMMITTED and
* TRANSACTION_READ_UNCOMMITTED
* @param conn Connection to test
* @param isoLevel expected isolation level
*
*/
private void assertIsoLocks(Connection conn, int expectedIsoLevel)
throws SQLException {
int conniso = conn.getTransactionIsolation();
assertEquals(expectedIsoLevel, conniso);
boolean selectTimedOut = selectTimesoutDuringUpdate(conn);
// expect a lock timeout for READ_COMMITTED
switch (conniso) {
case Connection.TRANSACTION_READ_UNCOMMITTED:
assertFalse(selectTimedOut); break;
case Connection.TRANSACTION_READ_COMMITTED:
assertTrue(selectTimedOut); break;
default:
System.out.println("No test support for isolation level");
}
}
/*
* Determine if a select on this connection during update will timeout.
* Used to establish isolation level. If the connection isolation level
* is <code> Connection.TRANSACTION_READ_UNCOMMITTED </code> it will not
* timeout. Otherwise it should.
*
* @param conn Connection to test.
* @return true if the select got a lock timeout, false otherwise.
*/
private boolean selectTimesoutDuringUpdate(Connection conn)
throws SQLException {
Connection updateConn=null;
conn.setAutoCommit(false);
try {
// create another connection and do an update but don't commit
updateConn = openDefaultConnection();
updateConn.setAutoCommit(false);
// First update the rows on the update connection
Statement upStmt = updateConn.createStatement();
upStmt.executeUpdate("update intTable set i = 3");
// now see if we can select them
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select * from intTable");
while (rs.next()){};
rs.close();
}
catch (SQLException e)
{
if (e.getSQLState().equals("40XL1"))
{
// If we got a lock timeout this is not read uncommitted
return true;
}
}
finally {
try {
conn.rollback();
updateConn.rollback();
}catch (SQLException se) {
se.printStackTrace();
}
}
return false;
}
/* -------------------- Other Helper Methods -------------------- */
private void assertConnectionState(
int expectedHoldability, int expectedIsolation,
boolean expectedCommitSetting, boolean expectedReadOnly,
Connection conn) throws SQLException
{
assertEquals(expectedHoldability, conn.getHoldability());
assertEquals(expectedIsolation, conn.getTransactionIsolation());
assertEquals(expectedCommitSetting, conn.getAutoCommit());
assertEquals(expectedReadOnly, conn.isReadOnly());
}
private static void setDatabaseProperty(String property, String value)
throws SQLException
{
DataSource ds = JDBCDataSource.getDataSource();
Connection cadmin = ds.getConnection();
CallableStatement cs = cadmin.prepareCall(
"CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?, ?)");
cs.setString(1, property);
cs.setString(2, value);
cs.execute();
cs.close();
cadmin.close();
}
private void setHoldability(Connection conn, boolean hold) throws SQLException {
conn.setHoldability(hold ? ResultSet.HOLD_CURSORS_OVER_COMMIT : ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
private static void dsConnectionRequests(
String[] expectedValues, DataSource ds) {
// checks currently only implemented for embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(ds, "javax.sql.DataSource");
}
try {
ds.getConnection();
if (!expectedValues[0].equals("OK"))
fail (" expected connection to fail, but was OK");
} catch (SQLException sqle) {
assertSQLState(expectedValues[0], sqle);
}
dsConnectionRequest(expectedValues[1], ds, null, null);
dsConnectionRequest(expectedValues[2], ds, "fred", null);
dsConnectionRequest(expectedValues[3], ds, "fred", "wilma");
dsConnectionRequest(expectedValues[4], ds, null, "wilma");
dsConnectionRequest(
expectedValues[5], ds, null, "databaseName=wombat");
dsConnectionRequest(
expectedValues[6], ds, "fred", "databaseName=wombat");
dsConnectionRequest(expectedValues[7],
ds, "fred", "databaseName=wombat;password=wilma");
dsConnectionRequest(expectedValues[8],
ds, "fred", "databaseName=wombat;password=betty");
}
private static void dsConnectionRequest(
String expectedValue, DataSource ds, String user, String ConnAttr)
{
try {
ds.getConnection(user, ConnAttr);
if (!expectedValue.equals("OK"))
fail (" expected connection to fail, but was OK");
} catch (SQLException sqle) {
assertSQLState(expectedValue, sqle);
}
}
private static void dsConnectionRequests(
String[] expectedValues, ConnectionPoolDataSource ds) {
try {
ds.getPooledConnection();
if (!expectedValues[0].equals("OK"))
fail (" expected connection to fail, but was OK");
} catch (SQLException sqle) {
assertSQLState(expectedValues[0], sqle);
}
dsConnectionRequest(expectedValues[1], ds, null, null);
dsConnectionRequest(expectedValues[2], ds, "fred", null);
dsConnectionRequest(expectedValues[3], ds, "fred", "wilma");
dsConnectionRequest(expectedValues[4], ds, null, "wilma");
dsConnectionRequest(
expectedValues[5], ds, null, "databaseName=wombat");
dsConnectionRequest(
expectedValues[6], ds, "fred", "databaseName=wombat");
dsConnectionRequest(expectedValues[7],
ds, "fred", "databaseName=wombat;password=wilma");
dsConnectionRequest(expectedValues[8],
ds, "fred", "databaseName=wombat;password=betty");
}
private static void dsConnectionRequest(String expectedValue,
ConnectionPoolDataSource ds, String user, String ConnAttr)
{
try {
ds.getPooledConnection(user, ConnAttr);
if (!expectedValue.equals("OK"))
fail (" expected connection to fail, but was OK");
} catch (SQLException sqle) {
assertSQLState(expectedValue, sqle);
}
}
private static void dsConnectionRequests(
String[] expectedValues, XADataSource ds) {
try {
ds.getXAConnection();
if (!expectedValues[0].equals("OK"))
fail (" expected connection to fail, but was OK");
} catch (SQLException sqle) {
assertSQLState(expectedValues[0], sqle);
}
dsConnectionRequest(expectedValues[1], ds, null, null);
dsConnectionRequest(expectedValues[2], ds, "fred", null);
dsConnectionRequest(expectedValues[3], ds, "fred", "wilma");
dsConnectionRequest(expectedValues[4], ds, null, "wilma");
dsConnectionRequest(
expectedValues[5], ds, null, "databaseName=" + dbName);
dsConnectionRequest(
expectedValues[6], ds, "fred", "databaseName=" + dbName);
dsConnectionRequest(expectedValues[7],
ds, "fred", "databaseName=" + dbName + ";password=wilma");
dsConnectionRequest(expectedValues[8],
ds, "fred", "databaseName=" + dbName + ";password=betty");
}
private static void dsConnectionRequest(String expectedValue,
XADataSource ds, String user, String ConnAttr)
{
try {
ds.getXAConnection(user, ConnAttr);
if (!expectedValue.equals("OK"))
fail (" expected connection to fail, but was OK");
} catch (SQLException sqle) {
assertSQLState(expectedValue, sqle);
}
}
protected void assertXAException(String tag, XAException xae) {
// for all our cases, we expect some kind of closed con error
// but the message is different for embedded vs. network server
if (usingEmbedded())
assertEquals("No current connection.", xae.getMessage());
else if (usingDerbyNetClient())
assertEquals(
"XAER_RMFAIL : No current connection.", xae.getMessage());
Throwable t = xae.getCause();
if (t instanceof SQLException)
assertSQLState("08003", (SQLException)t);
}
private static void queryOnStatement(String expectedCursorName,
int[] expectedValues, Connection conn, Statement s)
throws SQLException {
// DERBY-2531
// network server gives mismatched connections. See also
// comment in testAllDataSources()
if (usingEmbedded()) {
assertEquals(conn, s.getConnection());
}
resultSetQuery(expectedCursorName, expectedValues,
s.executeQuery("select * from intTable"));
}
private static void resultSetQuery(String expectedCursorName,
int[] expectedValues, ResultSet rs) throws SQLException
{
// checks currently only implemented for embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(rs, "java.sql.ResultSet");
}
assertEquals(expectedCursorName, rs.getCursorName());
int index=0;
while (rs.next()) {
assertEquals(expectedValues[index], rs.getInt(1));
index++;
}
assertEquals(expectedValues.length, index++);
rs.close();
}
private static void assertLocks(int[] expectedValues, Connection conn)
throws SQLException {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery(
"SELECT XID, sum(cast (LOCKCOUNT AS INT)) " +
"FROM SYSCS_DIAG.LOCK_TABLE AS L GROUP BY XID");
// Don't output actual XID's as they tend for every catalog change
// to the system.
int xact_index = 0;
while (rs.next()) {
if (expectedValues != null)
assertEquals(expectedValues[xact_index], rs.getInt(2));
else
fail("expected no locks");
xact_index++;
}
if (expectedValues != null)
assertEquals(expectedValues.length, xact_index);
rs.close();
s.close();
}
private void assertStatementState(int[] parameterExpectedValues,
int[] expectedValues, Statement s)
throws SQLException {
assertEquals(expectedValues[0], s.getResultSetType());
assertEquals(
expectedValues[1], s.getResultSetConcurrency());
assertEquals(
expectedValues[2], s.getFetchDirection());
assertEquals(expectedValues[3], s.getFetchSize());
assertEquals(expectedValues[4], s.getMaxFieldSize());
assertEquals(expectedValues[5], s.getMaxRows());
assertEquals(expectedValues[6], s.getResultSetHoldability());
if (s instanceof PreparedStatement) {
PreparedStatement ps = (PreparedStatement) s;
ParameterMetaData psmd = ps.getParameterMetaData();
// Parameter count:
assertEquals(parameterExpectedValues[0], psmd.getParameterCount());
for (int i = 1; i <= psmd.getParameterCount(); i++) {
assertEquals(parameterExpectedValues[i], psmd.getParameterType(i));
}
}
}
/**
Create a statement with modified State.
*/
private Statement createFloatStatementForStateChecking(
int[] StatementExpectedValues, Connection conn)
throws SQLException {
Statement s = internalCreateFloatStatementForStateChecking(conn);
s.setCursorName("StokeNewington");
s.setFetchDirection(ResultSet.FETCH_REVERSE);
s.setFetchSize(444);
s.setMaxFieldSize(713);
s.setMaxRows(19);
// Create
assertStatementState(null, StatementExpectedValues, s);
return s;
}
private Statement internalCreateFloatStatementForStateChecking(
Connection conn) throws SQLException {
return conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
}
private PreparedStatement createFloatStatementForStateChecking(
int[] parameterExpectedValues, int[] PreparedStatementExpectedValues,
Connection conn, String sql)
throws SQLException {
PreparedStatement s =
internalCreateFloatStatementForStateChecking(conn, sql);
s.setCursorName("StokeNewington");
s.setFetchDirection(ResultSet.FETCH_REVERSE);
s.setFetchSize(888);
s.setMaxFieldSize(317);
s.setMaxRows(91);
// PreparedStatement Create
assertStatementState(
parameterExpectedValues, PreparedStatementExpectedValues, s);
return s;
}
private PreparedStatement internalCreateFloatStatementForStateChecking(
Connection conn, String sql) throws SQLException {
return conn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
}
private CallableStatement createFloatCallForStateChecking(
int[] parameterExpectedValues, int[] CallableStatementExpectedValues,
Connection conn, String sql)
throws SQLException
{
CallableStatement s =
internalCreateFloatCallForStateChecking(conn, sql);
s.setCursorName("StokeNewington");
s.setFetchDirection(ResultSet.FETCH_REVERSE);
s.setFetchSize(999);
s.setMaxFieldSize(137);
s.setMaxRows(85);
// Callable Statement Create
assertStatementState(
parameterExpectedValues, CallableStatementExpectedValues, s);
return s;
}
private CallableStatement internalCreateFloatCallForStateChecking(
Connection conn, String sql) throws SQLException {
return conn.prepareCall(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
}
private void assertConnectionOK(
Object[] expectedValues, String dsName, Connection conn)
throws SQLException {
assertEquals(
((Integer)expectedValues[0]).intValue(), conn.getHoldability());
// check it's a 3.0 connection object by checking if
// set & release Savepoint is ok.
try {
conn.releaseSavepoint(conn.setSavepoint());
if (conn.getAutoCommit())
fail("expected a SQLExpection (savepoint with autocommit on");
if (!((String)expectedValues[1]).equals("OK"))
fail("expected a SQLExpection (savepoint with autocommit on");
} catch (SQLException sqle) {
// we expect savepoints exceptions because either
// it's a global transaction, or it's in auto commit mode.
if (conn.getAutoCommit())
assertSQLState("XJ010", sqle);
else if (((String)expectedValues[1]).equals("OK"))
throw sqle;
else
assertSQLState((String)expectedValues[1], sqle);
}
// Running connection checks
// connection checks currently only implemented for Embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(conn, "java.sql.Connection");
SecurityCheck.assertSourceSecurity(
conn.getMetaData(), "java.sql.DatabaseMetaData");
}
assertEquals(((Integer)expectedValues[2]).intValue(),
conn.getTransactionIsolation());
assertEquals(((Boolean)expectedValues[3]).booleanValue(),
conn.getAutoCommit());
assertEquals(((Boolean)expectedValues[4]).booleanValue(),
conn.isReadOnly());
if (dsName.endsWith("DataSource"))
assertNull(conn.getWarnings());
Statement s1 = conn.createStatement();
assertStatementOK(dsName, conn, s1);
assertStatementOK(dsName, conn, conn.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY));
Connection c1 = conn.getMetaData().getConnection();
// c1 and conn should be the same connection object.
if (!usingDerbyNetClient() && dsName.indexOf("DataSource")>=0)
assertEquals(c1, conn);
// Derby-33 - setTypeMap on connection
try {
conn.setTypeMap(java.util.Collections.EMPTY_MAP);
if (!((String)expectedValues[5]).equals("OK"))
fail (" expected an sqlexception on setTypeMap(EMPTY_MAP)");
} catch (SQLException sqle) {
if (((String)expectedValues[5]).equals("OK"))
throw sqle;
else
assertSQLState((String)expectedValues[5], sqle);
}
try {
// expect 0A000 - not implemented for client,
// XJ081 - invalid null value passed as map for embedded
conn.setTypeMap(null);
fail ("setTypeMap(null) should throw exception");
} catch (SQLException sqle) {
assertSQLState((String)expectedValues[6], sqle);
}
try {
// a populated map, not implemented
java.util.Map map = new java.util.HashMap();
map.put("name", "class");
conn.setTypeMap(map);
if (!((String)expectedValues[7]).equals("OK"))
fail (" expected an sqlexception on setTypeMap(map)");
} catch (SQLException sqle) {
if (((String)expectedValues[7]).equals("OK"))
throw sqle;
else
assertSQLState((String)expectedValues[7], sqle);
}
assertConnectionPreClose(dsName, conn);
conn.close();
// method calls on a closed connection
conn.close(); // expect no error
try {
conn.createStatement();
fail (dsName + " <closedconn>.createStatement(), " +
"expected 08003 - No current connection");
} catch (SQLException sqle) {
assertSQLState("08003", sqle);
}
try {
s1.execute("values 1");
fail(dsName + " <closedstmt>.execute(), " +
"expected 08003 - No current connection");
} catch (SQLException sqle) {
assertSQLState("08003", sqle);
}
}
private void assertConnectionPreClose(String dsName, Connection conn)
throws SQLException {
// before closing the connection, attempt to change holdability
// and readOnly
conn.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
if (!dsName.equals("Nested2"))
{
try {
conn.setReadOnly(true);
} catch (SQLException sqle) {
// cannot set read-only in an active transaction, & sometimes
// connections are active at this point.
assertSQLState("25501", sqle);
}
}
}
private void assertStatementOK(String dsName, Connection conn, Statement s)
throws SQLException {
// checks currently only implemented for embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(s, "java.sql.Statement");
}
Connection c1 = s.getConnection();
if (c1 != conn)
{
// with DerbyNetClient and any kind of DataSource, this goes wrong
if (!usingDerbyNetClient() && (dsName.indexOf("DataSource") >= 0))
fail ("incorrect connection object returned for Statement.getConnection()");
}
s.addBatch("insert into intTable values 1");
s.addBatch("insert into intTable values 2,3");
int[] states = s.executeBatch();
if (states[0] != 1)
fail ("invalid update count for first batch statement");
if (states[1] != 2)
fail ("invalid update count for second batch statement");
ResultSet rs = s.executeQuery("VALUES 1");
if (rs.getStatement() != s)
fail ("incorrect Statement object returned for ResultSet.getStatement for " + dsName);
rs.close();
s.close();
}
/**
When a connection is being pooled, the underlying JDBC embedded
connection object is re-used. As each application gets a new
Connection object, that is really a wrapper around the old connection
it should reset any connection spoecific state on the embedded connection
object.
*/
private static void PoolReset(String type, PooledConnection pc) throws SQLException
{
PoolResetWork("1", "C", pc.getConnection());
PoolResetWork("2", "", pc.getConnection());
PoolResetWork("3", "D", pc.getConnection());
pc.close();
}
private static void PoolResetWork(
String expectedID, String tableAction, Connection conn)
throws SQLException
{
Statement s = conn.createStatement();
if (tableAction.equals("C"))
{
s.execute("CREATE TABLE PoolResetWork (id int generated always as identity, name varchar(25))");
}
ResultSet rs = s.executeQuery("VALUES IDENTITY_VAL_LOCAL()");
rs.next();
String val = rs.getString(1);
if (!rs.wasNull() || (val != null))
fail ("initial call to IDENTITY_VAL_LOCAL is not NULL!" + val);
rs.close();
s.executeUpdate("INSERT INTO PoolResetWork(name) values ('derby-222')");
rs = s.executeQuery("VALUES IDENTITY_VAL_LOCAL()");
rs.next();
val = rs.getString(1);
assertEquals(expectedID, val);
rs.close();
if (tableAction.equals("D"))
{
s.execute("DROP TABLE PoolResetWork");
}
s.close();
conn.close();
}
/**
* Make sure this connection's string is unique (DERBY-243)
*/
private static void assertToString(Connection conn) throws Exception
{
assertStringFormat(conn);
String str = conn.toString();
if ( conns.containsKey(str))
{
throw new Exception("ERROR: Connection toString() is not unique: "
+ str);
}
conns.put(str, conn);
}
/**
* Check the format of a pooled connection
**/
private static void assertStringFormat(PooledConnection pc) throws Exception
{
String prefix = assertStringPrefix(pc);
String connstr = pc.toString();
String format = prefix + " \\(ID = [0-9]+\\), Physical Connection = " +
"<none>|" + CONNSTRING_FORMAT;
assertTrue(connstr.matches(format));
}
/**
* Check the format of the connection string. This is the default test
* to run if this is not a BrokeredConnection class
*/
private static void assertStringFormat(Connection conn) //throws Exception
{
assertStringPrefix(conn);
String str = conn.toString();
assertTrue("\nexpected format:\n " + CONNSTRING_FORMAT + "\nactual value:\n " + str,
str.matches(CONNSTRING_FORMAT));
}
/**
* Make sure the connection string starts with the right prefix, which
* is the classname@hashcode.
*
* @return the expected prefix string, this is used in further string
* format checking
*/
private static String assertStringPrefix(Object conn) //throws Exception
{
String connstr = conn.toString();
String prefix = conn.getClass().getName() + "@" + conn.hashCode();
// Connection class and has code for connection string should
// match prefix
assertTrue(connstr.startsWith(prefix));
return prefix;
}
/**
* Check uniqueness of connection strings coming from a
* DataSouce
*/
private static void assertToString(DataSource ds) throws Exception
{
clearConnections();
int numConnections = 10;
for ( int i = 0 ; i < numConnections ; i++ )
{
Connection conn = ds.getConnection();
assertToString(conn);
}
clearConnections();
}
/**
* Clear out and close connections in the connections
* hashtable.
*/
private static void clearConnections() throws SQLException
{
java.util.Iterator it = conns.values().iterator();
while ( it.hasNext() )
{
Connection conn = (Connection)it.next();
conn.close();
}
conns.clear();
}
/**
* Get connections using getConnection() and make sure
* they're unique
*/
private void assertTenConnectionsUnique() throws Exception
{
clearConnections();
// Open ten connections rather than just two to
// try and catch any odd uniqueness bugs. Still
// no guarantee but is better than just two.
int numConnections = 10;
for ( int i = 0 ; i < numConnections ; i++ )
{
Connection conn = openDefaultConnection();
assertToString(conn);
}
// Now close the connections
clearConnections();
}
/**
* Check uniqueness of strings for an XA data source
*/
private static void assertToString(XADataSource xds) throws Exception
{
int numConnections = 10;
// First get a bunch of pooled connections
// and make sure they're all unique
Hashtable xaConns = new Hashtable();
for ( int i = 0 ; i < numConnections ; i++ )
{
XAConnection xc = xds.getXAConnection();
assertStringFormat(xc);
String str = xc.toString();
// XA connection toString should be unique
assertNull(xaConns.get(str));
xaConns.put(str, xc);
}
// Now check that connections from each of these
// pooled connections have different string values
Iterator it = xaConns.values().iterator();
clearConnections();
while ( it.hasNext() )
{
XAConnection xc = (XAConnection)it.next();
Connection conn = xc.getConnection();
assertToString(conn);
}
clearConnections();
// Now clear out the pooled connections
it = xaConns.values().iterator();
while ( it.hasNext() )
{
XAConnection xc = (XAConnection)it.next();
xc.close();
}
xaConns.clear();
}
/**
* Check uniqueness of strings with a pooled data source.
* We want to check the PooledConnection as well as the
* underlying physical connection.
*/
private static void assertToString(ConnectionPoolDataSource pds)
throws Exception
{
int numConnections = 10;
// First get a bunch of pooled connections
// and make sure they're all unique
Hashtable pooledConns = new Hashtable();
for ( int i = 0 ; i < numConnections ; i++ )
{
PooledConnection pc = pds.getPooledConnection();
assertStringFormat(pc);
String str = pc.toString();
// Pooled connection toString should be unique
assertNull( pooledConns.get(str));
pooledConns.put(str, pc);
}
// Now check that connections from each of these
// pooled connections have different string values
Iterator it = pooledConns.values().iterator();
clearConnections();
while ( it.hasNext() )
{
PooledConnection pc = (PooledConnection)it.next();
Connection conn = pc.getConnection();
assertToString(conn);
}
clearConnections();
// Now clear out the pooled connections
it = pooledConns.values().iterator();
while ( it.hasNext() )
{
PooledConnection pc = (PooledConnection)it.next();
pc.close();
}
pooledConns.clear();
}
/**
* Return the Java class and method for the procedure
* for the nested connection test.
*/
private static String getNestedMethodName()
{
return "checkNesConn";
}
// calling checkConnection
// - for use in a procedure to get a nested connection.
public static void checkNesConn (String dsName) throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:default:connection");
String EmptyMapValue=null;
// Note: currently, not supported
String NullMapValue=null;
String MapMapValue=null;
if (usingEmbedded())
{
EmptyMapValue="OK"; NullMapValue="XJ081"; MapMapValue="0A000";
}
else if (usingDerbyNetClient())
{
EmptyMapValue="0A000"; NullMapValue="0A000"; MapMapValue="0A000";
}
Object[] expectedValues = {
new Integer(ResultSet.HOLD_CURSORS_OVER_COMMIT), "OK",
new Integer(2), new Boolean(false), new Boolean(false),
EmptyMapValue, NullMapValue, MapMapValue};
new J2EEDataSourceTest("J2EEDataSourceTest").assertConnectionOK(
expectedValues, dsName, conn);
}
}
class cdsXid implements Xid, Serializable
{
private static final long serialVersionUID = 64467338100036L;
private final int format_id;
private byte[] global_id;
private byte[] branch_id;
cdsXid(int xid, byte b1, byte b2)
{
format_id = xid;
global_id = new byte[Xid.MAXGTRIDSIZE];
branch_id = new byte[Xid.MAXBQUALSIZE];
for (int i = 0; i < global_id.length; i++) {
global_id[i] = b1;
}
for (int i = 0; i < branch_id.length; i++) {
branch_id[i] = b2;
}
}
/**
* Obtain the format id part of the Xid.
* <p>
*
* @return Format identifier. O means the OSI CCR format.
**/
public int getFormatId()
{
return(format_id);
}
/**
* Obtain the global transaction identifier part of XID as an array of
* bytes.
* <p>
*
* @return A byte array containing the global transaction identifier.
**/
public byte[] getGlobalTransactionId()
{
return(global_id);
}
/**
* Obtain the transaction branch qualifier part of the Xid in a byte array.
* <p>
*
* @return A byte array containing the branch qualifier of the transaction.
**/
public byte[] getBranchQualifier()
{
return(branch_id);
}
}
| java/testing/org/apache/derbyTesting/functionTests/tests/jdbcapi/J2EEDataSourceTest.java | /*
Derby - Class org.apache.derbyTesting.functionTests.tests.jdbcapi.J2EEDataSourceTest
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derbyTesting.functionTests.tests.jdbcapi;
import java.io.File;
import java.io.Serializable;
import java.security.AccessController;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Savepoint;
import java.util.Hashtable;
import java.util.Iterator;
import javax.sql.ConnectionEvent;
import javax.sql.ConnectionEventListener;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.PooledConnection;
import javax.sql.XAConnection;
import javax.sql.XADataSource;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.derby.jdbc.ClientConnectionPoolDataSource;
import org.apache.derby.jdbc.ClientXADataSource;
import org.apache.derby.jdbc.EmbeddedSimpleDataSource;
import org.apache.derbyTesting.functionTests.util.SecurityCheck;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.CleanDatabaseTestSetup;
import org.apache.derbyTesting.junit.DatabasePropertyTestSetup;
import org.apache.derbyTesting.junit.J2EEDataSource;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.JDBCClient;
import org.apache.derbyTesting.junit.JDBCDataSource;
import org.apache.derbyTesting.junit.TestConfiguration;
/**
* Test the ConnectionPoolDataSource and XADataSource implementations of Derby.
* DataSource functionality common to DataSources including what is
* supported with JSR169 is tested in DataSourceTest.
*
* Performs SecurityCheck analysis on the JDBC objects returned.
* This is because this test returns to the client a number of
* different implementations of Connection, Statement etc.
*
* @see org.apache.derbyTesting.functionTests.util.SecurityCheck
*
*/
public class J2EEDataSourceTest extends BaseJDBCTestCase {
private static final String dbName =
TestConfiguration.getCurrent().getDefaultDatabaseName();
/**
* A hashtable of opened connections. This is used when checking to
* make sure connection strings are unique; we need to make sure all
* the connections are closed when we are done, so they are stored
* in this hashtable
*/
protected static Hashtable conns = new Hashtable();
/** The expected format of a connection string. In English:
* "<classname>@<hashcode> (XID=<xid>), (SESSION = <sessionid>),
* (DATABASE=<dbname>), (DRDAID = <drdaid>)"
*/
private static final String CONNSTRING_FORMAT =
"\\S+@\\-?[0-9]+.* \\(XID = .*\\), \\(SESSIONID = [0-9]+\\), " +
"\\(DATABASE = [A-Za-z]+\\), \\(DRDAID = .*\\) ";
/**
* Hang onto the SecurityCheck class while running the
* tests so that it is not garbage collected during the
* test and lose the information it has collected,
* in case it should get printed out.
*/
private final Object nogc = SecurityCheck.class;
public J2EEDataSourceTest(String name) {
super(name);
}
/**
* Return a suite of tests that are run with a lower lock timeout.
*
* @param postfix suite name postfix
* @return A suite of tests being run with a lower lock timeout.
*/
private static Test getTimeoutSuite(String postfix) {
TestSuite suite = new TestSuite("Lower lock timeout" + postfix);
suite.addTest(new J2EEDataSourceTest("timeoutTestDerby1144PooledDS"));
suite.addTest(new J2EEDataSourceTest("timeoutTestDerby1144XADS"));
// Reduce the timeout threshold to make the tests run faster.
return DatabasePropertyTestSetup.setLockTimeouts(suite, 3, 5);
}
/**
* Return a suite of tests that are run with both client and embedded
*
* @param postfix suite name postfix
* @return A suite of tests to be run with client and/or embedded
*/
private static Test baseSuite(String postfix) {
TestSuite suite = new TestSuite("ClientAndEmbedded" + postfix);
suite.addTest(new J2EEDataSourceTest("testGlobalLocalInterleaf"));
suite.addTest(new J2EEDataSourceTest("testSetIsolationWithStatement"));
suite.addTest(new J2EEDataSourceTest("testJira95xads"));
suite.addTest(new J2EEDataSourceTest("testBadConnectionAttributeSyntax"));
suite.addTest(new J2EEDataSourceTest("testDescriptionProperty"));
suite.addTest(new J2EEDataSourceTest("testConnectionErrorEvent"));
suite.addTest(new J2EEDataSourceTest("testReadOnlyToWritableTran"));
suite.addTest(new J2EEDataSourceTest("testAutoCommitOnXAResourceStart"));
suite.addTest(new J2EEDataSourceTest("testAllDataSources"));
suite.addTest(new J2EEDataSourceTest("testClosedCPDSConnection"));
suite.addTest(new J2EEDataSourceTest("testClosedXADSConnection"));
suite.addTest(new J2EEDataSourceTest("testSetSchemaInXAConnection"));
suite.addTest(new J2EEDataSourceTest("testPooledReuseOnClose"));
return suite;
}
/**
* Return a suite of tests that are run with client only
*
* @return A suite of tests being run with client only
*/
private static Test getClientSuite() {
TestSuite suite = new TestSuite("Client/Server");
suite.addTest(new J2EEDataSourceTest("testClientDSConnectionAttributes"));
suite.addTest(new J2EEDataSourceTest(
"testClientTraceFileDSConnectionAttribute"));
suite.addTest(new J2EEDataSourceTest(
"testClientMessageTextConnectionAttribute"));
return suite;
}
/**
* Return a suite of tests that are run with embedded only
*
* @param postfix suite name postfix
* @return A suite of tests being run with embedded only
*/
private static Test getEmbeddedSuite(String postfix) {
TestSuite suite = new TestSuite("Embedded" + postfix);
suite.addTest(new J2EEDataSourceTest("testDSRequestAuthentication"));
// when DERBY-2498 gets fixed, move this one to baseSuite
suite.addTest(new J2EEDataSourceTest("testJira95pds"));
// Following cannot run with client because of DERBY-2533; it hangs
// when fixed, this can be moved to baseSuite.
suite.addTest(new J2EEDataSourceTest("testReuseAcrossGlobalLocal"));
suite.addTest(new J2EEDataSourceTest("testXAHoldability"));
return suite;
}
public static Test suite() {
if (JDBC.vmSupportsJSR169())
{
// test uses unsupported classes like DriverManager, XADataSource,
// ConnectionPoolDataSource, ConnectionEvenListenere, as well as
// unsupported methods, like Connection.setTypeMap()...
TestSuite suite =
new TestSuite("J2EEDatasourceTest cannot run with JSR169");
return suite;
}
else
{
TestSuite suite = new TestSuite("J2EEDataSourceTest suite");
// Add tests that will run with both embedded
suite.addTest(baseSuite(":embedded"));
// and network server/client
suite.addTest(TestConfiguration.clientServerDecorator(
baseSuite(":client")));
// Add the tests that only run with client
suite.addTest(TestConfiguration.clientServerDecorator(
getClientSuite()));
// Add the tests that only run with embedded
suite.addTest(getEmbeddedSuite("embedded"));
// Add the tests relying on getting timeouts.
suite.addTest(getTimeoutSuite(":embedded"));
suite.addTest(TestConfiguration.clientServerDecorator(
getTimeoutSuite(":client")));
// wrap all in CleanDatabaseTestSetup that creates all database
// objects any fixture might need.
// Note that not all fixtures need (all of) these.
return new CleanDatabaseTestSetup(suite) {
/**
* Create and populate database objects
*
* @see org.apache.derbyTesting.junit.CleanDatabaseTestSetup#decorateSQL(java.sql.Statement)
*/
protected void decorateSQL(Statement s) throws SQLException {
s.executeUpdate("create table autocommitxastart(i int)");
s.executeUpdate("insert into autocommitxastart values 1,2,3,4,5");
s.executeUpdate("create schema SCHEMA_Patricio");
s.executeUpdate("create table " +
"SCHEMA_Patricio.Patricio (id VARCHAR(255), value INTEGER)");
s.executeUpdate("create table intTable(i int)");
s.executeUpdate("create table hold_30 " +
"(id int not null primary key, b char(30))");
s.executeUpdate(
"create procedure checkConn2(in dsname varchar(20)) " +
"parameter style java language java modifies SQL DATA " +
"external name " +
"'org.apache.derbyTesting.functionTests.tests.jdbcapi.J2EEDataSourceTest." +
getNestedMethodName() +
"'");
}
};
}
}
public void tearDown() throws Exception {
// attempt to get rid of any left-over trace files
AccessController.doPrivileged(new java.security.PrivilegedAction() {
public Object run() {
for (int i=0 ; i < 6 ; i++)
{
String traceFileName = "trace" + (i+1) + ".out";
File traceFile = new File(traceFileName);
if (traceFile.exists())
{
// if it exists, attempt to get rid of it
traceFile.delete();
}
}
return null;
}
});
super.tearDown();
}
/* comment out. leaving in, just in case it's ever relevant.
* when uncommented, this will run when network server tests are
* started, and then reflect the results of the embedded checks.
// perform security analysis of the public api for the embedded engine
public void testDataSourceAPI() throws SQLException, ClassNotFoundException
{
SecurityCheck.report();
}
*/
/**
* Test case for DERBY-3172
* When the Derby engine is shutdown or Network Server is brought down, any
* api on JDBC Connection object should generate a Connection error event.
*/
public void testConnectionErrorEvent() throws SQLException, Exception
{
AssertEventCatcher aes12 = new AssertEventCatcher(12);
ConnectionPoolDataSource ds = J2EEDataSource.getConnectionPoolDataSource();
PooledConnection pc = ds.getPooledConnection();
//Add a connection event listener to ConnectionPoolDataSource
pc.addConnectionEventListener(aes12);
Connection conn = pc.getConnection();
dropTable(conn, "TAB1");
//No event should have been generated at this point
assertFalse(aes12.didConnectionClosedEventHappen());
assertFalse(aes12.didConnectionErrorEventHappen());
aes12.resetState();
//Shutdown the Derby engine or Network Server depending on what
//mode we are running in.
if (usingEmbedded())
{
getTestConfiguration().shutdownDatabase();
} else
{
getTestConfiguration().stopNetworkServer();
}
//Now try to use various apis on the JDBC Connection object created
//before shutdown and they all should generate connection error event.
try {
conn.prepareStatement("CREATE TABLE TAB1(COL1 INT NOT NULL)");
} catch (SQLException e) {
//The first call on JDBC Connection object after Network Server
//shutdown will generate a communication error and that's why we
//are checking for SQL State 08006 rather than No current connection
//SQL State 08003. In embedded mode, we will get SQL State 08003
//meaning No current connection
if (usingEmbedded())
assertSQLState("08003", e);
else
assertSQLState("08006", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.prepareStatement("CREATE TABLE TAB1(COL1 INT NOT NULL)", 1);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
int[] columnIndexes = {1};
conn.prepareStatement("CREATE TABLE TAB1(COL1 INT NOT NULL)",
columnIndexes);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
String[] columnNames = {"col1"};
conn.prepareStatement("CREATE TABLE TAB1(COL1 INT NOT NULL)",
columnNames);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.prepareStatement("CREATE TABLE TAB1(COL1 INT NOT NULL)",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.prepareStatement("CREATE TABLE TAB1(COL1 INT NOT NULL)",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.createStatement();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.prepareCall("CREATE TABLE TAB1(COL1 INT NOT NULL)",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.prepareCall("CREATE TABLE TAB1(COL1 INT NOT NULL)");
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.prepareCall("CREATE TABLE TAB1(COL1 INT NOT NULL)",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.nativeSQL("CREATE TABLE TAB1(COL1 INT NOT NULL)");
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.getAutoCommit();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setAutoCommit(false);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.getHoldability();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setHoldability(1);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.commit();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.rollback();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setSavepoint();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setSavepoint("savept1");
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.rollback((Savepoint)null);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.releaseSavepoint((Savepoint)null);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.getTransactionIsolation();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.getWarnings();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.clearWarnings();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.getMetaData();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.isReadOnly();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setReadOnly(true);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setCatalog(null);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.getCatalog();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.getTypeMap();
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
try {
conn.setTypeMap(null);
} catch (SQLException e) {
assertSQLState("08003", e);
}
assertFalse(aes12.didConnectionClosedEventHappen());
assertTrue(aes12.didConnectionErrorEventHappen());
aes12.resetState();
if (usingEmbedded())
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
}else
{
getTestConfiguration().startNetworkServer();
}
// Get a new connection to the database
conn = getConnection();
conn.close();
}
/**
* Test that a PooledConnection can be reused and closed
* (separately) during the close event raised by the
* closing of its logical connection.
* DERBY-2142.
* @throws SQLException
*
*/
public void testPooledReuseOnClose() throws SQLException
{
// PooledConnection from a ConnectionPoolDataSource
ConnectionPoolDataSource cpds =
J2EEDataSource.getConnectionPoolDataSource();
subtestPooledReuseOnClose(cpds.getPooledConnection());
subtestPooledCloseOnClose(cpds.getPooledConnection());
// DERBY-3401 - removing a callback during a close causes problems.
//subtestPooledRemoveListenerOnClose(cpds.getPooledConnection());
// PooledConnection from an XDataSource
XADataSource xads = J2EEDataSource.getXADataSource();
subtestPooledReuseOnClose(xads.getXAConnection());
subtestPooledCloseOnClose(xads.getXAConnection());
// DERBY-3401 - removing a callback during a close causes problems.
//subtestPooledRemoveListenerOnClose(xads.getXAConnection());
}
/**
* Tests that a pooled connection can successfully be reused
* (a new connection obtained from it) during the processing
* of its close event by its listener.
* Sections 11.2 & 12.5 of JDBC 4 specification indicate that the
* connection can be returned to the pool when the
* ConnectionEventListener.connectionClosed() is called.
*/
private void subtestPooledReuseOnClose(final PooledConnection pc) throws SQLException
{
final Connection[] newConn = new Connection[1];
pc.addConnectionEventListener(new ConnectionEventListener() {
/**
* Mimic a pool handler that returns the PooledConnection
* to the pool and then reallocates it to a new logical connection.
*/
public void connectionClosed(ConnectionEvent event) {
PooledConnection pce = (PooledConnection) event.getSource();
assertSame(pc, pce);
try {
// open a new logical connection and pass
// back to the fixture.
newConn[0] = pce.getConnection();
} catch (SQLException e) {
// Need to catch the exception here because
// we cannot throw a checked exception through
// the api method. Wrap it in a RuntimeException.
throw new RuntimeException(e);
}
}
public void connectionErrorOccurred(ConnectionEvent event) {
}
});
// Open a connection then close it to trigger the
// fetching of a new connection in the callback.
Connection c1 = pc.getConnection();
c1.close();
// Fetch the connection created in the close callback
Connection c2 = newConn[0];
assertNotNull(c2);
// Ensure the connection is useable, this hit a NPE before DERBY-2142
// was fixed (for embedded).
c2.createStatement().close();
pc.close();
}
/**
* Tests that a pooled connection can successfully be closed
* during the processing of its close event by its listener.
*/
private void subtestPooledCloseOnClose(final PooledConnection pc) throws SQLException
{
pc.addConnectionEventListener(new ConnectionEventListener() {
/**
* Mimic a pool handler that closes the PooledConnection
* (say it no longer needs it, pool size being reduced)
*/
public void connectionClosed(ConnectionEvent event) {
PooledConnection pce = (PooledConnection) event.getSource();
assertSame(pc, pce);
try {
pce.close();
} catch (SQLException e) {
// Need to catch the exception here because
// we cannot throw a checked exception through
// the api method. Wrap it in a RuntimeException.
throw new RuntimeException(e);
}
}
public void connectionErrorOccurred(ConnectionEvent event) {
}
});
// Open and close a connection to invoke the logic above
// through the callback
pc.getConnection().close();
// The callback closed the actual pooled connection
// so subsequent requests to get a logical connection
// should fail.
try {
pc.getConnection();
fail("PooledConnection should be closed");
} catch (SQLException sqle) {
assertSQLState("08003", sqle);
}
}
/**
* Tests that a listener of a pooled connection can successfully
* remove itself during the processing of its close event by its listener.
*/
private void subtestPooledRemoveListenerOnClose(final PooledConnection pc) throws SQLException
{
final int[] count1 = new int[1];
pc.addConnectionEventListener(new ConnectionEventListener() {
/**
* Mimic a pool handler that removes the listener during
* a logical close.
*/
public void connectionClosed(ConnectionEvent event) {
PooledConnection pce = (PooledConnection) event.getSource();
assertSame(pc, pce);
count1[0]++;
pce.removeConnectionEventListener(this);
}
public void connectionErrorOccurred(ConnectionEvent event) {
}
});
// and have another listener to ensure removing one leaves
// the other working and intact.
final int[] count2 = new int[1];
pc.addConnectionEventListener(new ConnectionEventListener() {
/**
* Mimic a pool handler that closes the PooledConnection
* (say it no longer needs it, pool size being reduced)
*/
public void connectionClosed(ConnectionEvent event) {
PooledConnection pce = (PooledConnection) event.getSource();
assertSame(pc, pce);
count2[0]++;
}
public void connectionErrorOccurred(ConnectionEvent event) {
}
});
// no callback yet
assertEquals(0, count1[0]);
assertEquals(0, count2[0]);
// Open and close a connection to invoke the logic above
// through the callback
pc.getConnection().close();
// one callback for each
assertEquals(1, count1[0]);
assertEquals(1, count2[0]);
// the callback (count1) that was removed is not called on the
// second close but the second callback (count2) is called.
pc.getConnection().close();
assertEquals(1, count1[0]);
assertEquals(2, count2[0]);
pc.close();
}
public void testAllDataSources() throws SQLException, Exception
{
Connection dmc = getConnection();
CallableStatement cs = dmc.prepareCall("call checkConn2(?)");
cs.setString(1,"Nested");
try {
cs.execute();
} catch (SQLException sqle) {
assertSQLState("40XC0", sqle);
}
cs.setString(1,"Nested2");
cs.execute();
String EmptyMapValue=null;
// Note: currently, not supported
String NullMapValue=null;
String MapMapValue=null;
if (usingEmbedded())
{
EmptyMapValue="OK"; NullMapValue="XJ081"; MapMapValue="0A000";
}
else if (usingDerbyNetClient())
{
EmptyMapValue="0A000"; NullMapValue="0A000"; MapMapValue="0A000";
}
Object[] expectedValues = {
new Integer(ResultSet.HOLD_CURSORS_OVER_COMMIT), "XJ010",
new Integer(2), new Boolean(true), new Boolean(false),
EmptyMapValue, NullMapValue, MapMapValue};
assertConnectionOK(expectedValues, "DriverManager ", dmc);
if (usingEmbedded())
assertTenConnectionsUnique();
DataSource dscs = JDBCDataSource.getDataSource();
if (usingEmbedded())
assertToString(dscs);
DataSource ds = dscs;
assertConnectionOK(expectedValues, "DataSource", ds.getConnection());
DataSource dssimple = null;
// simple datasource is only supported with embedded
if (usingEmbedded())
{
EmbeddedSimpleDataSource realdssimple =
new EmbeddedSimpleDataSource();
realdssimple.setDatabaseName(dbName);
ds = realdssimple;
dssimple = (DataSource)realdssimple;
assertConnectionOK(
expectedValues, "SimpleDataSource", ds.getConnection());
}
ConnectionPoolDataSource dsp =
J2EEDataSource.getConnectionPoolDataSource();
if (usingEmbedded())
assertToString(dsp);
PooledConnection pc = dsp.getPooledConnection();
// checks currently only implemented for embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(
pc, "javax.sql.PooledConnection");
}
AssertEventCatcher aes1 = new AssertEventCatcher(1);
pc.addConnectionEventListener(aes1);
// DERBY-2531
// with Network Server / DerbyNetClient, the assertConnectionOK check
// returns a different connection object...
assertConnectionOK(
expectedValues, "ConnectionPoolDataSource", pc.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes1.didConnectionClosedEventHappen());
assertFalse(aes1.didConnectionErrorEventHappen());
aes1.resetState();
assertConnectionOK(
expectedValues, "ConnectionPoolDataSource", pc.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes1.didConnectionClosedEventHappen());
assertFalse(aes1.didConnectionErrorEventHappen());
aes1.resetState();
XADataSource dsx = J2EEDataSource.getXADataSource();
if (usingEmbedded())
assertToString(dsx);
// shutdown db and check all's still ok thereafter
TestConfiguration.getCurrent().shutdownDatabase();
dmc = getConnection();
cs = dmc.prepareCall("call checkConn2(?)");
// checks currently only implemented for embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(
cs, "java.sql.CallableStatement");
}
cs.setString(1,"Nested");
try {
cs.execute();
} catch (SQLException sqle) {
assertSQLState("40XC0", sqle);
}
cs.setString(1, "Nested2");
cs.execute();
XAConnection xac = dsx.getXAConnection();
// checks currently only implemented for embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(xac, "javax.sql.XAConnection");
}
AssertEventCatcher aes3 = new AssertEventCatcher(3);
xac.addConnectionEventListener(aes3);
assertConnectionOK(
expectedValues, "XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes3.didConnectionClosedEventHappen());
assertFalse(aes3.didConnectionErrorEventHappen());
aes3.resetState();
pc = dsp.getPooledConnection();
AssertEventCatcher aes2 = new AssertEventCatcher(2);
pc.addConnectionEventListener(aes2);
assertConnectionOK(
expectedValues, "ConnectionPoolDataSource", pc.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes2.didConnectionClosedEventHappen());
assertFalse(aes2.didConnectionErrorEventHappen());
aes2.resetState();
// test "local" XAConnections
xac = dsx.getXAConnection();
AssertEventCatcher aes4 = new AssertEventCatcher(4);
xac.addConnectionEventListener(aes4);
assertConnectionOK(
expectedValues, "XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes4.didConnectionClosedEventHappen());
assertFalse(aes4.didConnectionErrorEventHappen());
aes4.resetState();
assertConnectionOK(
expectedValues, "XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes4.didConnectionClosedEventHappen());
assertFalse(aes4.didConnectionErrorEventHappen());
aes4.resetState();
xac.close();
// test "global" XAConnections
xac = dsx.getXAConnection();
AssertEventCatcher aes5 = new AssertEventCatcher(5);
xac.addConnectionEventListener(aes5);
XAResource xar = xac.getXAResource();
// checks currently only implemented for embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(
xar, "javax.transaction.xa.XAResource");
}
Xid xid = new cdsXid(1, (byte) 35, (byte) 47);
xar.start(xid, XAResource.TMNOFLAGS);
Connection xacc = xac.getConnection();
xacc.close();
expectedValues[0] = new Integer(ResultSet.CLOSE_CURSORS_AT_COMMIT);
if (usingEmbedded())
expectedValues[1] = "XJ058";
expectedValues[3] = new Boolean(false);
assertConnectionOK(
expectedValues, "Global XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes5.didConnectionClosedEventHappen());
assertFalse(aes5.didConnectionErrorEventHappen());
aes5.resetState();
assertConnectionOK(
expectedValues, "Global XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes5.didConnectionClosedEventHappen());
assertFalse(aes5.didConnectionErrorEventHappen());
aes5.resetState();
xar.end(xid, XAResource.TMSUCCESS);
expectedValues[0] = new Integer(ResultSet.HOLD_CURSORS_OVER_COMMIT);
expectedValues[3] = new Boolean(true);
assertConnectionOK(expectedValues,
"Switch to local XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes5.didConnectionClosedEventHappen());
assertFalse(aes5.didConnectionErrorEventHappen());
aes5.resetState();
assertConnectionOK(expectedValues,
"Switch to local XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes5.didConnectionClosedEventHappen());
assertFalse(aes5.didConnectionErrorEventHappen());
aes5.resetState();
Connection backtoGlobal = xac.getConnection();
xar.start(xid, XAResource.TMJOIN);
expectedValues[0] = new Integer(ResultSet.CLOSE_CURSORS_AT_COMMIT);
expectedValues[3] = new Boolean(false);
assertConnectionOK(expectedValues,
"Switch to global XADataSource", backtoGlobal);
//Check if got connection closed event but not connection error event
assertTrue(aes5.didConnectionClosedEventHappen());
assertFalse(aes5.didConnectionErrorEventHappen());
aes5.resetState();
assertConnectionOK(expectedValues,
"Switch to global XADataSource", xac.getConnection());
//Check if got connection closed event but not connection error event
assertTrue(aes5.didConnectionClosedEventHappen());
assertFalse(aes5.didConnectionErrorEventHappen());
aes5.resetState();
xar.end(xid, XAResource.TMSUCCESS);
xar.commit(xid, true);
xac.close();
}
public void testClosedCPDSConnection() throws SQLException, Exception {
// verify that outstanding updates from a closed connection, obtained
// from a ConnectionPoolDataSource, are not committed, but rolled back.
ConnectionPoolDataSource dsp =
J2EEDataSource.getConnectionPoolDataSource();
PooledConnection pc = dsp.getPooledConnection();
Connection c1 = pc.getConnection();
Statement s = c1.createStatement();
// start by deleting all rows from intTable
s.executeUpdate("delete from intTable");
c1.setAutoCommit(false);
// this update should get rolled back later
s.executeUpdate("insert into intTable values(1)");
// this should automatically close the original connection
c1 = pc.getConnection();
ResultSet rs =
c1.createStatement().executeQuery("select count(*) from intTable");
rs.next();
assertEquals(0, rs.getInt(1));
c1.close();
// check connection objects are closed once connection is closed
try {
rs.next();
fail("ResultSet is open for a closed connection obtained from PooledConnection");
} catch (SQLException sqle) {
// 08003 - No current connection; XCL16 - ResultSet not open
if (usingEmbedded())
assertSQLState("08003", sqle);
else if (usingDerbyNetClient())
assertSQLState("XCL16", sqle);
}
try {
s.executeUpdate("update intTable set i = 1");
fail("Statement is open for a closed connection " +
"obtained from PooledConnection");
} catch (SQLException sqle) {
assertSQLState("08003", sqle);
}
pc.close();
pc = null;
PoolReset("ConnectionPoolDataSource", dsp.getPooledConnection());
s.close();
rs.close();
c1.close();
}
public void testClosedXADSConnection() throws SQLException, Exception {
// verify that outstanding updates from a closed connection, obtained
// from an XADataSource, are not committed, but rolled back.
XADataSource dsx = J2EEDataSource.getXADataSource();
XAConnection xac = dsx.getXAConnection();
Connection c1 = xac.getConnection();
Statement s = c1.createStatement();
c1.setAutoCommit(false);
// this update should be rolled back
s.executeUpdate("insert into intTable values(2)");
c1 = xac.getConnection();
ResultSet rs = c1.createStatement().executeQuery(
"select count(*) from intTable");
rs.next();
assertEquals(0, rs.getInt(1));
rs.close();
c1.close();
xac.close();
xac = null;
PoolReset("XADataSource", dsx.getXAConnection());
}
public void testGlobalLocalInterleaf() throws SQLException, XAException {
// now some explicit tests for how connection state behaves
// when switching between global transactions and local
// and setting connection state.
// some of this may be tested elsewhere too.
XADataSource dsx = J2EEDataSource.getXADataSource();
XAConnection xac = dsx.getXAConnection();
AssertEventCatcher aes6 = new AssertEventCatcher(6);
xac.addConnectionEventListener(aes6);
XAResource xar = xac.getXAResource();
Xid xid = new cdsXid(1, (byte) 93, (byte) 103);
// series 1 - Single connection object
Connection cs1 = xac.getConnection();
// initial local
assertConnectionState(
ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
true, false, cs1);
xar.start(xid, XAResource.TMNOFLAGS);
// initial X1
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
false, false, cs1);
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
cs1.setReadOnly(true);
setHoldability(cs1, false); // close cursors
// modified X1
boolean ReadOnly = false;
// see DERBY-911, ReadOnly state different for Embedded/DerbyNetClient
if (usingEmbedded())
ReadOnly = true;
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
false, ReadOnly, cs1);
xar.end(xid, XAResource.TMSUCCESS);
// the underlying local transaction/connection must pick up the
// state of the Connection handle cs1
// modified local:
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
true, ReadOnly, cs1);
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
cs1.setReadOnly(false);
setHoldability(cs1, false); // close cursors
// reset local
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
true, false, cs1);
// now re-join the transaction, should pick up the read-only
// and isolation level from the transaction,
// holdability remains that of this handle.
xar.start(xid, XAResource.TMJOIN);
// re-join X1
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
false, ReadOnly, cs1);
xar.end(xid, XAResource.TMSUCCESS);
// back to local - should be the same as the reset local
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
true, false, cs1);
// test suspend/resume
// now re-join the transaction (X1) for the second time, should pick
// up the read-only and isolation level from the transaction,
// holdability remains that of this handle.
xar.start(xid, XAResource.TMJOIN);
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
false, ReadOnly, cs1);
xar.end(xid, XAResource.TMSUSPEND);
// local after suspend
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
true, false, cs1);
xar.start(xid, XAResource.TMRESUME);
// resume X1
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
false, ReadOnly, cs1);
xar.end(xid, XAResource.TMSUCCESS);
// back to local (second time)
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
true, false, cs1);
cs1.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
cs1.setReadOnly(true);
setHoldability(cs1, true); // hold
//Confirm - no connection closed event & connection error event
assertFalse(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
cs1.close();
//Check if got connection closed event but not connection error event
assertTrue(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
cs1 = xac.getConnection();
// new handle - local
assertConnectionState(
ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
true, false, cs1);
cs1.close();
//Check if got connection closed event but not connection error event
assertTrue(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
xar.start(xid, XAResource.TMJOIN);
cs1 = xac.getConnection();
// re-join with new handle X1
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
false, ReadOnly, cs1);
cs1.close();
xar.end(xid, XAResource.TMSUCCESS);
//Check if got connection closed event but not connection error event
assertTrue(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
// now get a connection (attached to a local)
// attach to the global and commit it.
// state should be that of the local after the commit.
cs1 = xac.getConnection();
cs1.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
// pre-X1 commit - local
assertConnectionState(
ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
true, false, cs1);
xar.start(xid, XAResource.TMJOIN);
// pre-X1 commit - X1
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
false, ReadOnly, cs1);
xar.end(xid, XAResource.TMSUCCESS);
// post-X1 end - local
assertConnectionState(
ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
true, false, cs1);
xar.commit(xid, true);
// post-X1 commit - local
assertConnectionState(
ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
true, false, cs1);
//Confirm - no connection closed event & connection error event
assertFalse(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
cs1.close();
//Check if got connection closed event but not connection error event
assertTrue(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
}
// really part of testGlobalLocalInterLeaf:
/**
* @throws SQLException
* @throws XAException
*/
public void testSetIsolationWithStatement()
throws SQLException, XAException {
// DERBY-421 Setting isolation level with SQL was not getting
// handled correctly
// Some more isolation testing using SQL and JDBC api
XADataSource dsx = J2EEDataSource.getXADataSource();
XAConnection xac = dsx.getXAConnection();
AssertEventCatcher aes6 = new AssertEventCatcher(6);
xac.addConnectionEventListener(aes6);
XAResource xar = xac.getXAResource();
Connection conn = xac.getConnection();
Statement s = conn.createStatement();
// initial local
assertConnectionState(
ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
true, false, conn);
// Issue setTransactionIsolation in local transaction
conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
// setTransactionIsolation in local
assertConnectionState(
ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
true, false, conn);
Xid xid;
//Issue SQL to change isolation in local transaction
s.executeUpdate("set current isolation = RR");
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_SERIALIZABLE,
true, false, conn);
xid = new cdsXid(1, (byte) 35, (byte) 47);
xar.start(xid, XAResource.TMNOFLAGS);
// 1st global (new)
assertConnectionState(ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_SERIALIZABLE,
false, false, conn);
xar.end(xid, XAResource.TMSUCCESS);
// local
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_SERIALIZABLE,
true, false, conn);
//Issue SQL to change isolation in local transaction
s.executeUpdate("set current isolation = RS");
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
true, false, conn);
// DERBY-1325 - Isolation level of local connection does not get reset after ending
// a global transaction that was joined/resumed if the isolation level was changed
// using SQL
xar.start(xid, XAResource.TMJOIN);
// 1st global(existing)
assertConnectionState(ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_SERIALIZABLE,
false, false, conn);
xar.end(xid, XAResource.TMSUCCESS);
// local
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
true, false, conn);
// DERBY-1325 end test
Xid xid2 = new cdsXid(1, (byte) 93, (byte) 103);
xar.start(xid2, XAResource.TMNOFLAGS);
// 2nd global (new)
assertConnectionState(ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
false, false, conn);
xar.end(xid2, XAResource.TMSUCCESS);
xar.start(xid, XAResource.TMJOIN);
// 1st global (existing)
assertConnectionState(ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_SERIALIZABLE,
false, false, conn);
xar.end(xid, XAResource.TMSUCCESS);
//local
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
true, false, conn);
xar.start(xid, XAResource.TMJOIN);
// 1st global (existing)
assertConnectionState(ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_SERIALIZABLE,
false, false, conn);
// Issue SQL to change isolation in 1st global transaction
s.executeUpdate("set current isolation = UR");
assertConnectionState(ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
false, false, conn);
xar.end(xid, XAResource.TMSUCCESS);
// local
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
true, false, conn);
xar.start(xid2, XAResource.TMJOIN);
// 2nd global (existing)
assertConnectionState(ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_REPEATABLE_READ,
false, false, conn);
xar.end(xid2, XAResource.TMSUCCESS);
xar.rollback(xid2);
// (After 2nd global rollback ) local
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
true, false, conn);
xar.rollback(xid);
// (After 1st global rollback) local
assertConnectionState(ResultSet.HOLD_CURSORS_OVER_COMMIT,
Connection.TRANSACTION_READ_UNCOMMITTED,
true, false, conn);
//Confirm - no connection closed event & connection error event
assertFalse(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
}
// This test includes some short-hand descriptions of the test cases
// left in for reference to the original non-junit test
public void testReuseAcrossGlobalLocal() throws SQLException, XAException {
// DERBY-2533 -
// network server cannot run this test - it hits a protocol error
// on tearDown. Embedded requires a database shutdown
if (usingDerbyNetClient())
return;
int[] onetwothree = {1,2,3};
int[] three = {3};
int[] pspc = {1, 4}; // expected parameter count for prepared statements
int[] cspc = {2, 12, 12}; // for callable statements
// statics for testReuseAcrossGlobalLocal
int[] StatementExpectedValues = {
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY,
ResultSet.FETCH_REVERSE, 444, 713, 19,
ResultSet.HOLD_CURSORS_OVER_COMMIT};
//ResultSet.CLOSE_CURSORS_AT_COMMIT};
int[] PreparedStatementExpectedValues = {
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY,
ResultSet.FETCH_REVERSE, 888, 317, 91,
ResultSet.HOLD_CURSORS_OVER_COMMIT};
int[] CallableStatementExpectedValues = {
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY,
ResultSet.FETCH_REVERSE, 999, 137, 85,
ResultSet.HOLD_CURSORS_OVER_COMMIT};
XADataSource dsx = J2EEDataSource.getXADataSource();
XAConnection xac = dsx.getXAConnection();
AssertEventCatcher aes6 = new AssertEventCatcher(6);
xac.addConnectionEventListener(aes6);
XAResource xar = xac.getXAResource();
Xid xid = new cdsXid(1, (byte) 103, (byte) 119);
// now check re-use of *Statement objects across local/global
// connections.
Connection cs1 = xac.getConnection();
// ensure read locks stay around until end-of transaction
cs1.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
cs1.setAutoCommit(false);
assertLocks(null, cs1);
Statement sru1 = cs1.createStatement();
sru1.setCursorName("SN1");
sru1.executeUpdate("insert into intTable values 1,2,3");
Statement sruBatch = cs1.createStatement();
sruBatch.setCursorName("sruBatch");
Statement sruState = createFloatStatementForStateChecking(
StatementExpectedValues, cs1);
PreparedStatement psruState = createFloatStatementForStateChecking(
new int[] {1, 4}, PreparedStatementExpectedValues, cs1,
"select i from intTable where i = ?");
CallableStatement csruState = createFloatCallForStateChecking(
new int[] {2, 12, 12}, CallableStatementExpectedValues, cs1,
"CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?,?)");
PreparedStatement psParams =
cs1.prepareStatement("select * from intTable where i > ?");
psParams.setCursorName("params");
psParams.setInt(1, 2);
// Params-local-1
resultSetQuery("params", three, psParams.executeQuery());
sruBatch.addBatch("insert into intTable values 4");
// sru1-local-1
queryOnStatement("SN1", onetwothree, cs1, sru1);
cs1.commit(); // need to commit to switch to an global connection;
// simple case - underlying connection is re-used for global.
xar.start(xid, XAResource.TMNOFLAGS);
// Expecting downgrade because global transaction sru1-global-2 is
// using a statement with holdability true
// sru1-global-2
queryOnStatement("SN1", onetwothree, cs1, sru1);
sruBatch.addBatch("insert into intTable values 5");
Statement sru2 = cs1.createStatement();
sru2.setCursorName("OAK2");
//sru2-global-3
queryOnStatement("OAK2", onetwothree, cs1, sru2);
// Expecting downgrade because global transaction sru1-global-4 is
// using a statement with holdability true
// sru1-global-4
queryOnStatement("SN1", onetwothree, cs1, sru1);
// Global statement
StatementExpectedValues[6] = ResultSet.CLOSE_CURSORS_AT_COMMIT;
PreparedStatementExpectedValues[6] = ResultSet.CLOSE_CURSORS_AT_COMMIT;
CallableStatementExpectedValues[6] = ResultSet.CLOSE_CURSORS_AT_COMMIT;
assertStatementState(null, StatementExpectedValues ,sruState);
// Global PreparedStatement
assertStatementState(pspc, PreparedStatementExpectedValues, psruState);
// Global CallableStatement
assertStatementState(cspc, CallableStatementExpectedValues, csruState);
// Params-global-1
resultSetQuery("params", three, psParams.executeQuery());
xar.end(xid, XAResource.TMSUCCESS);
// now a new underlying connection is created
// sru1-local-5
queryOnStatement("SN1", onetwothree, cs1, sru1);
// sru2-local-6
queryOnStatement("OAK2", onetwothree, cs1, sru2);
sruBatch.addBatch("insert into intTable values 6,7");
Statement sru3 = cs1.createStatement();
sru3.setCursorName("SF3");
// sru3-local-7
queryOnStatement("SF3", onetwothree, cs1, sru3);
// Two transactions should hold locks (global and the current XA);
// LOCAL
StatementExpectedValues[6] = ResultSet.HOLD_CURSORS_OVER_COMMIT;
PreparedStatementExpectedValues[6] = ResultSet.HOLD_CURSORS_OVER_COMMIT;
CallableStatementExpectedValues[6] = ResultSet.HOLD_CURSORS_OVER_COMMIT;
assertStatementState(null, StatementExpectedValues, sruState);
assertStatementState(pspc, PreparedStatementExpectedValues, psruState);
assertStatementState(cspc, CallableStatementExpectedValues, csruState);
// Params-local-2
resultSetQuery("params", three, psParams.executeQuery());
assertLocks(new int[] {14,14}, cs1);
cs1.commit();
//Confirm - no connection closed event & connection error event
assertFalse(aes6.didConnectionClosedEventHappen());
assertFalse(aes6.didConnectionErrorEventHappen());
aes6.resetState();
// attach the XA transaction to another connection and see what happens
XAConnection xac2 = dsx.getXAConnection();
AssertEventCatcher aes5 = new AssertEventCatcher(5);
xac2.addConnectionEventListener(aes5);
XAResource xar2 = xac2.getXAResource();
xar2.start(xid, XAResource.TMJOIN);
Connection cs2 = xac2.getConnection();
// these statements were generated by cs1 and thus are still
// in a local connection.
// sru1-local-8
queryOnStatement("SN1", onetwothree, cs1, sru1);
// sru2-local-9
queryOnStatement("OAK2", onetwothree, cs1, sru2);
// sru3-local-10
queryOnStatement("SF3", onetwothree, cs1, sru3);
sruBatch.addBatch("insert into intTable values 8");
// LOCAL 2
assertStatementState(null, StatementExpectedValues, sruState);
assertStatementState(pspc, PreparedStatementExpectedValues, psruState);
assertStatementState(cspc, CallableStatementExpectedValues, csruState);
assertLocks(new int[] {14, 12}, cs1);
int[] updateCounts = sruBatch.executeBatch();
int[] expectedUpdateCounts = {1, 1, 2, 1};
// sruBatch update counts:
for (int i = 0; i < updateCounts.length; i++) {
assertEquals(expectedUpdateCounts[i], updateCounts[i]);
}
// sruBatch
queryOnStatement(
"sruBatch", new int[] {1,2,3,4,5,6,7,8}, cs1, sruBatch);
xar2.end(xid, XAResource.TMSUCCESS);
//Confirm - no connection closed event & connection error event
assertFalse(aes5.didConnectionClosedEventHappen());
assertFalse(aes5.didConnectionErrorEventHappen());
aes5.resetState();
xac2.close();
// allow close on already closed XAConnection
xac2.close();
xac2.addConnectionEventListener(null);
xac2.removeConnectionEventListener(null);
// test methods against a closed XAConnection and its resource
try {
xac2.getXAResource();
// DERBY-2532
// Network Server does not think this is worth an exception.
if (usingEmbedded())
fail("expected SQLException on " +
"closed XAConnection.getXAResource");
} catch (SQLException sqle) {
assertSQLState("08003", sqle);
}
try {
xac2.getConnection();
fail ("expected SQLException on XAConnection.getConnection");
} catch (SQLException sqle) {
assertSQLState("08003", sqle);
}
try {
xar2.start(xid, XAResource.TMJOIN);
fail ("expected XAException on XAResource.TMJOIN");
} catch (XAException xae) {
assertXAException("XAResource.start", xae);
}
try {
xar2.end(xid, XAResource.TMJOIN);
fail ("expected XAException on XAResource.TMJOIN");
} catch (XAException xae) {
assertXAException("XAResource.end", xae);
}
try {
xar2.commit(xid, true);
fail ("expected XAException on XAResource.commit");
} catch (XAException xae) {
assertXAException("XAResource.commit", xae);
}
try {
xar2.prepare(xid);
fail ("expected XAException on XAResource.prepare");
} catch (XAException xae) {
assertXAException("XAResource.prepare", xae);
}
try {
xar2.recover(0);
fail ("expected XAException on XAResource.recover");
} catch (XAException xae) {
assertXAException("XAResource.recover", xae);
}
try {
xar2.prepare(xid);
fail ("expected XAException on XAResource.prepare");
} catch (XAException xae) {
assertXAException("XAResource.prepare", xae);
}
try {
xar2.isSameRM(xar2);
fail ("expected XAException on XAResource.isSameRM");
} catch (XAException xae) {
assertXAException("XAResource.isSameRM", xae);
}
// close everything
cs1.rollback();
sruState.close();
psruState.close();
csruState.close();
psParams.close();
sruBatch.close();
sru1.close();
sru2.close();
sru3.close();
cs1.close();
cs2.close();
xac.removeConnectionEventListener(null);
xac.close();
xac2.close();
// but, still not enough.
// what with all the switching between global and local transactions
// we still have a lock open on intTable, which will interfere with
// our tearDown efforts. Bounce the database.
TestConfiguration.getCurrent().shutdownDatabase();
}
public void testSetSchemaInXAConnection() throws SQLException {
// tests that set schema works correctly in an XA connection.
XADataSource dsx = J2EEDataSource.getXADataSource();
XAConnection xac3 = dsx.getXAConnection();
Connection conn3 = xac3.getConnection();
Statement st3 = conn3.createStatement();
st3.execute("SET SCHEMA SCHEMA_Patricio");
st3.close();
PreparedStatement ps3 =
conn3.prepareStatement("INSERT INTO Patricio VALUES (?, ?)");
ps3.setString(1, "Patricio");
ps3.setInt(2, 3);
ps3.executeUpdate();
assertEquals(1, ps3.getUpdateCount());
ps3.close();
conn3.close();
xac3.close();
}
// test that an xastart in auto commit mode commits the existing work.
// test fix of a bug ('beetle 5178') wherein XAresource.start() when
// auto-commit is true did not implictly commit any transaction
// Also tests DERBY-1025, same description, but for client.
public void testAutoCommitOnXAResourceStart() throws SQLException, XAException {
XADataSource dsx = J2EEDataSource.getXADataSource();
XAConnection xac4 = dsx.getXAConnection();
Xid xid4a= null;
// We get an XAID_DUP error from networkserver when attempting
// the XAResource.start below if we use the same xid.
// Possibly because we're in the same jvm.
// When the test is run with clientserverSuite, rather than default,
// this wasn't needed, so just create a different id for client
if (usingEmbedded())
xid4a = new cdsXid(4, (byte) 23, (byte) 76);
else if (usingDerbyNetClient())
xid4a = new cdsXid(5, (byte) 23, (byte) 76);
Connection conn4 = xac4.getConnection();
assertTrue(conn4.getAutoCommit());
Statement s4 = conn4.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT);
ResultSet rs4 = s4.executeQuery("select i from autocommitxastart");
rs4.next();
assertEquals(1, rs4.getInt(1));
rs4.next();
assertEquals(2, rs4.getInt(1));
// XAResource().start should commit the transaction
xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS);
xac4.getXAResource().end(xid4a, XAResource.TMSUCCESS);
try {
rs4.next();
fail ("expected an exception indicating resultset is closed.");
} catch (SQLException sqle) {
// Embedded gets 08003. No current connection (DERBY-2620)
if (usingDerbyNetClient())
assertSQLState("XCL16",sqle);
}
conn4.setAutoCommit(false);
assertFalse(conn4.getAutoCommit());
rs4 = s4.executeQuery("select i from autocommitxastart");
rs4.next();
assertEquals(1, rs4.getInt(1));
rs4.next();
assertEquals(2, rs4.getInt(1));
// Get a new xid to begin another transaction.
if (usingEmbedded())
xid4a = new cdsXid(4, (byte) 93, (byte) 103);
else if (usingDerbyNetClient())
xid4a = new cdsXid(5, (byte) 93, (byte) 103);
try {
xac4.getXAResource().start(xid4a, XAResource.TMNOFLAGS);
} catch (XAException xae) {
if (usingEmbedded())
assertNull(xae.getMessage());
else if (usingDerbyNetClient())
{
// This should give XAER_OUTSIDE exception because
// the resource manager is busy in the local transaction
assertTrue(xae.getMessage().indexOf("XAER_OUTSIDE") >=0 );
}
assertEquals(-9, xae.errorCode);
}
rs4.next();
assertEquals(3, rs4.getInt(1));
rs4.close();
conn4.rollback();
conn4.close();
xac4.close();
}
public void testReadOnlyToWritableTran() throws SQLException, Exception
{
// This fixture will run twice, once with embedded, once with client,
// and insert 2 rows in addition to the 5 rows inserted during setup.
// The fixture tests a commit, so before running, try to remove row
// 6 and 7 in case this is the second run of the fixture.
Statement s = createStatement();
s.executeUpdate("delete from autocommitxastart where i = 6");
s.executeUpdate("delete from autocommitxastart where i = 7");
// TESTING READ_ONLY TRANSACTION FOLLOWED BY WRITABLE TRANSACTION
// Test following sequence of steps
// 1)start a read-only global transaction
// 2)finish that read-only transaction
// 3)start another global transaction
XADataSource dsx = J2EEDataSource.getXADataSource();
XAConnection xac5 = dsx.getXAConnection();
Xid xid5a = new cdsXid(5, (byte) 119, (byte) 129);
Connection conn5 = xac5.getConnection();
Statement sru5a = conn5.createStatement();
XAResource xar = xac5.getXAResource();
xar.start(xid5a, XAResource.TMNOFLAGS);
conn5.setReadOnly(true);
// Read-Only XA transaction;
// holdability: (hold, or close cursors over commit) ,
// transaction isolation: read-committed,
// auto-commit false, read-only true (with embedded)
if (usingEmbedded())
{
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
false, true, conn5);
}
// Note: the original test had no comments about this difference
// between Embedded and DerbyNetClient, this has apparently
// been accepted behavior.
else if (usingDerbyNetClient())
{
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
false, false, conn5);
}
ResultSet rs5 = sru5a.executeQuery(
"select count(*) from autocommitxastart");
rs5.next();
assertEquals(5, rs5.getInt(1));
rs5.close();
xar.end(xid5a, XAResource.TMSUCCESS);
xar.commit(xid5a, true);
conn5.close();
//now start a new transaction
conn5 = xac5.getConnection();
sru5a = conn5.createStatement();
xar.start(xid5a, XAResource.TMNOFLAGS);
// Writeable XA transaction
// holdability: (hold, or close cursors over commit) ,
// transaction isolation: read-committed,
// auto-commit false, read-only false
assertConnectionState(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
Connection.TRANSACTION_READ_COMMITTED,
false, false, conn5);
sru5a.executeUpdate("insert into autocommitxastart values 6,7");
rs5 = sru5a.executeQuery("select count(*) from autocommitxastart");
rs5.next();
assertEquals(7, rs5.getInt(1));
xar.end(xid5a, XAResource.TMSUCCESS);
xar.commit(xid5a, true);
conn5.close();
xac5.close();
sru5a.close();
}
// test jira-derby 95 - a NullPointerException was returned when passing
// an incorrect database name, should now give error XCY00
// with ConnectionPoolDataSource
public void testJira95pds() throws Exception {
try {
ConnectionPoolDataSource pds = J2EEDataSource.getConnectionPoolDataSource();
JDBCDataSource.setBeanProperty(pds, "databaseName", "jdbc:derby:boo");
pds.getPooledConnection();
fail ("expected an SQLException!");
} catch (SQLException sqle) {
// DERBY-2498 - when fixed, remove if
if (usingEmbedded())
assertSQLState("XCY00", sqle);
} catch (Exception e) {
// DERBY-2498 - when fixed, remove if
if (usingEmbedded())
throw e;
}
}
// test jira-derby 95 - a NullPointerException was returned when passing
// an incorrect database name, should now give error XCY00
// with XADataSource
public void testJira95xads() throws SQLException {
try {
XADataSource dxs = J2EEDataSource.getXADataSource();
JDBCDataSource.setBeanProperty(dxs, "databaseName", "jdbc:derby:boo");
dxs.getXAConnection().getConnection();
fail ("expected an SQLException!");
} catch (SQLException sqle) {
assertSQLState("XCY00", sqle);
}
}
// there is a corresponding fixture for datasources in DataSourceTest
public void testBadConnectionAttributeSyntax() throws SQLException {
// ConnectionPoolDataSource - bad connatr syntax
ConnectionPoolDataSource cpds = J2EEDataSource.getConnectionPoolDataSource();
JDBCDataSource.setBeanProperty(cpds, "ConnectionAttributes", "bad");
try {
cpds.getPooledConnection();
fail ("should have seen an error");
} catch (SQLException e) {
assertSQLState("XJ028", e);
}
// XADataSource - bad connattr syntax");
XADataSource xads = J2EEDataSource.getXADataSource();
JDBCDataSource.setBeanProperty(xads, "ConnectionAttributes", "bad");
try {
xads.getXAConnection();
fail ("should have seen an error");
} catch (SQLException e) {
assertSQLState("XJ028", e);
}
} // End testBadConnectionAttributeSyntax
/**
* Check that database name set using setConnectionAttributes is not used
* by ClientDataSource. This method tests DERBY-1130.
*
* @throws SQLException
*/
public void testClientDSConnectionAttributes() throws SQLException {
if (usingEmbedded())
return;
// now with ConnectionPoolDataSource
ClientConnectionPoolDataSource cpds =
new ClientConnectionPoolDataSource();
// ConnectionPoolDataSource - EMPTY
dsConnectionRequests(new String[]
{"08001","08001","08001","08001",
"08001","08001","08001","08001","08001"},
(ConnectionPoolDataSource)cpds);
// ConnectionPoolDataSource
// - connectionAttributes=databaseName=<valid dbname>
cpds.setConnectionAttributes("databaseName=" + dbName);
dsConnectionRequests(new String[]
{"08001","08001","08001","08001",
"08001","08001","08001","08001","08001"},
(ConnectionPoolDataSource)cpds);
cpds.setConnectionAttributes(null);
// Test that database name specified in connection attributes is
// not used
// ConnectionPoolDataSource - databaseName=wombat and
// connectionAttributes=databaseName=kangaroo
cpds.setConnectionAttributes("databaseName=kangaroo");
cpds.setDatabaseName(dbName);
dsConnectionRequests(new String[]
{"OK","08001","OK","OK","08001","08001","OK","OK","OK"},
(ConnectionPoolDataSource)cpds);
cpds.setConnectionAttributes(null);
cpds.setDatabaseName(null);
// now with XADataSource
ClientXADataSource xads = new ClientXADataSource();
// XADataSource - EMPTY
dsConnectionRequests(new String[]
{"08001","08001","08001","08001",
"08001","08001","08001","08001","08001"},
(XADataSource) xads);
// XADataSource - connectionAttributes=databaseName=<valid dbname>
xads.setConnectionAttributes("databaseName=wombat");
dsConnectionRequests(new String[]
{"08001","08001","08001","08001",
"08001","08001","08001","08001","08001"},
(XADataSource) xads);
xads.setConnectionAttributes(null);
// Test that database name specified in connection attributes is not used
// XADataSource - databaseName=wombat and
// connectionAttributes=databaseName=kangaroo
xads.setConnectionAttributes("databaseName=kangaroo");
xads.setDatabaseName("wombat");
dsConnectionRequests(new String[]
{"OK","08001","OK","OK","08001","08001","OK","OK","OK"},
(XADataSource) xads);
xads.setConnectionAttributes(null);
xads.setDatabaseName(null);
} // End testClientDSConnectionAttributes
// Following test is similar to testClientDSConnectionAttributes, but
// for embedded datasources.
// This subtest does not run for network server, it uses
// setAttributesAsPassword, which isn't supported for client datasources.
//
// Note that DataSourceTest has some more basic testing of
// an empty DataSource in a fixture with similar name - however
// that fixture does not test setAttributesAsPassword
public void testDSRequestAuthentication() throws Exception {
// if (usingDerbyNetClient())
// return;
JDBCClient dsclient = getTestConfiguration().getJDBCClient();
String dsName = dsclient.getDataSourceClassName();
DataSource ds = (DataSource) Class.forName(dsName).newInstance();
// DataSource - attributesAsPassword=true");
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.TRUE);
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ028",
"XJ028","XJ004","XJ004","XJ004","XJ004"}, ds);
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.FALSE);
// DataSource - attributesAsPassword=true,
// connectionAttributes=databaseName=kangaroo");
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.TRUE);
JDBCDataSource.setBeanProperty(ds, "connectionAttributes", "databaseName=kangaroo");
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ028",
"XJ028","XJ004","XJ004","XJ004","XJ004"}, ds);
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.FALSE);
JDBCDataSource.clearStringBeanProperty(ds, "connectionAttributes");
// Enable Authentication;
setDatabaseProperty("derby.user.fred", "wilma");
setDatabaseProperty("derby.user.APP", "APP");
setDatabaseProperty("derby.authentication.provider", "BUILTIN");
setDatabaseProperty("derby.connection.requireAuthentication", "true");
JDBCDataSource.setBeanProperty(ds, "shutdownDatabase", "shutdown");
try {
ds.getConnection();
} catch (SQLException sqle) {
assertSQLState("XJ015", sqle);
}
JDBCDataSource.clearStringBeanProperty(ds, "databaseName");
JDBCDataSource.clearStringBeanProperty(ds, "shutdownDatabase");
// "AUTHENTICATION NOW ENABLED");
// DataSource - attributesAsPassword=true
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.TRUE);
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ028",
"XJ028","XJ004","XJ004","XJ004","XJ004"}, ds);
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.FALSE);
// ensure the DS property password is not treated as a set of
// attributes.
// DataSource - attributesAsPassword=true, user=fred,
// password=databaseName=wombat;password=wilma
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.TRUE);
JDBCDataSource.setBeanProperty(ds, "user", "fred");
JDBCDataSource.setBeanProperty(ds, "password", "databaseName=" + dbName + ";password=wilma");
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ028",
"XJ028","XJ004","XJ004","XJ004","XJ004"}, ds);
JDBCDataSource.setBeanProperty(ds, "attributesAsPassword", Boolean.FALSE);
JDBCDataSource.clearStringBeanProperty(ds, "user");
JDBCDataSource.clearStringBeanProperty(ds, "password");
ds = null;
// now with ConnectionPoolDataSource
String cpdsName = dsclient.getConnectionPoolDataSourceClassName();
ConnectionPoolDataSource cpds =
(ConnectionPoolDataSource) Class.forName(cpdsName).newInstance();
// ConnectionPoolDataSource - EMPTY
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ004",
"XJ004","XJ004","XJ004","XJ004","XJ004"},
(ConnectionPoolDataSource)cpds);
// ConnectionPoolDataSource -
// connectionAttributes=databaseName=wombat
JDBCDataSource.setBeanProperty(cpds, "connectionAttributes", "databaseName=" + dbName);
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ004",
"XJ004","XJ004","XJ004","XJ004","XJ004"},
(ConnectionPoolDataSource)cpds);
JDBCDataSource.clearStringBeanProperty(cpds, "connectionAttributes");
// ConnectionPoolDataSource - attributesAsPassword=true
JDBCDataSource.setBeanProperty(cpds, "attributesAsPassword", Boolean.TRUE);
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ028",
"XJ028","XJ004","XJ004","XJ004","XJ004"},
(ConnectionPoolDataSource)cpds);
JDBCDataSource.setBeanProperty(cpds, "attributesAsPassword", Boolean.FALSE);
// ensure the DS property password is not treated as a set of
// attributes.
// ConnectionPoolDataSource - attributesAsPassword=true,
// user=fred, password=databaseName=wombat;password=wilma");
JDBCDataSource.setBeanProperty(cpds, "attributesAsPassword", Boolean.TRUE);
JDBCDataSource.setBeanProperty(cpds, "user", "fred");
JDBCDataSource.setBeanProperty(cpds, "password", "databaseName=" + dbName + ";password=wilma");
dsConnectionRequests(new String[] {
"XJ004","XJ004","XJ004","XJ028",
"XJ028","XJ004","XJ004","XJ004","XJ004"},
(ConnectionPoolDataSource)cpds);
JDBCDataSource.setBeanProperty(cpds, "attributesAsPassword", Boolean.FALSE);
JDBCDataSource.clearStringBeanProperty(cpds, "user");
JDBCDataSource.clearStringBeanProperty(cpds, "password");
cpds = null;
// now with XADataSource
// EmbeddedXADataSource xads = new EmbeddedXADataSource();
String xadsName = dsclient.getXADataSourceClassName();
XADataSource xads =
(XADataSource) Class.forName(xadsName).newInstance();
// XADataSource - EMPTY
dsConnectionRequests(new String[] {
"08006","08006","08006","08006",
"08006","08006","08006","08006","08006"},
(XADataSource) xads);
// XADataSource - databaseName=wombat
JDBCDataSource.setBeanProperty(xads, "databaseName", dbName);
dsConnectionRequests(new String[] {
"08004","08004","08004","OK",
"08004","08004","08004","08004","08004"},
(XADataSource) xads);
JDBCDataSource.clearStringBeanProperty(xads, "databaseName");
// XADataSource - connectionAttributes=databaseName=wombat");
JDBCDataSource.setBeanProperty(xads, "connectionAttributes", "databaseName=" + dbName);
dsConnectionRequests(new String[] {
"08006","08006","08006","08006",
"08006","08006","08006","08006","08006"},
(XADataSource) xads);
JDBCDataSource.clearStringBeanProperty(xads, "connectionAttributes");
// XADataSource - attributesAsPassword=true
JDBCDataSource.setBeanProperty(xads, "attributesAsPassword", Boolean.TRUE);
dsConnectionRequests(new String[] {
"08006","08006","08006","08006",
"08006","08006","08006","08006","08006"},
(XADataSource) xads);
JDBCDataSource.setBeanProperty(xads, "attributesAsPassword", Boolean.FALSE);
// XADataSource - databaseName=wombat, attributesAsPassword=true
JDBCDataSource.setBeanProperty(xads, "databaseName", dbName);
JDBCDataSource.setBeanProperty(xads, "attributesAsPassword", Boolean.TRUE);
dsConnectionRequests(new String[] {
"08004","08004","08004","XJ028",
"XJ028","08004","08004","OK","08004"},
(XADataSource) xads);
JDBCDataSource.setBeanProperty(xads, "attributesAsPassword", Boolean.FALSE);
JDBCDataSource.clearStringBeanProperty(xads, "databaseName");
setDatabaseProperty("derby.connection.requireAuthentication", "false");
TestConfiguration.getCurrent().shutdownDatabase();
}
/**
* Check that traceFile connection attribute functions correctly.
* tracefile was tested in checkDriver, but not for DataSources.
* tracefile= was used in datasourcepermissions_net, but that's
* incorrect syntax. Note that we're not checking the contents of
* the tracefile.
*
* Note also that this test cannot run against a remote server.
*
* @throws SQLException
*/
public void testClientTraceFileDSConnectionAttribute() throws SQLException
{
if (usingEmbedded())
return;
String traceFile;
// with ConnectionPoolDataSource
ConnectionPoolDataSource cpds = J2EEDataSource.getConnectionPoolDataSource();
traceFile = "trace3.out";
JDBCDataSource.setBeanProperty(cpds, "connectionAttributes",
"traceFile="+traceFile);
// DERBY-2468 - trace3.out does not get created
((ClientConnectionPoolDataSource) cpds).getConnection();
JDBCDataSource.clearStringBeanProperty(cpds, "connectionAttributes");
traceFile = "trace4.out";
JDBCDataSource.setBeanProperty(cpds, "traceFile", traceFile);
((ClientConnectionPoolDataSource) cpds).getConnection();
cpds = null;
// now with XADataSource
XADataSource xads = J2EEDataSource.getXADataSource();
traceFile = "trace5.out";
JDBCDataSource.setBeanProperty(xads, "connectionAttributes",
"traceFile="+traceFile);
((ClientXADataSource) xads).getConnection();
// DERBY-2468 - trace5.out does not get created
JDBCDataSource.clearStringBeanProperty(xads, "connectionAttributes");
traceFile = "trace6.out";
JDBCDataSource.setBeanProperty(xads, "traceFile", traceFile);
((ClientXADataSource) xads).getConnection();
assertTraceFilesExist();
}
/* -- Helper Methods for testClientTraceFileDSConnectionAttribute -- */
/**
* Check that trace file exists in <framework> directory
*/
private static void assertTraceFilesExist()
{
AccessController.doPrivileged(new java.security.PrivilegedAction() {
public Object run() {
for (int i=3 ; i < 6 ; i++)
{
String traceFileName = "trace" + (i+1) + ".out";
File traceFile = new File(traceFileName);
if (i == 4)
continue;
else
{
assertTrue(traceFile.exists());
}
}
return null;
}
});
}
/**
* Check that messageText connection attribute functions correctly.
* retrievemessagetext was tested in checkdriver, and derbynet/testij,
* but not tested for datasources, and in datasourcepermissions_net,
* but as it has nothing to do with permissions/authentication,
* this test seems a better place for it.
*
* There is a corresponding fixture for clientDataSource in DataSourceTest
*
* @throws SQLException
*/
public void testClientMessageTextConnectionAttribute() throws SQLException
{
if (usingEmbedded())
return;
String retrieveMessageTextProperty = "retrieveMessageText";
Connection conn;
// with ConnectionPoolDataSource
// ConnectionPoolDataSource - retrieveMessageTextProperty
ClientConnectionPoolDataSource cpds = new ClientConnectionPoolDataSource();
cpds.setDatabaseName(dbName);
cpds.setConnectionAttributes(
retrieveMessageTextProperty + "=false");
conn = cpds.getConnection();
assertMessageText(conn,"false");
conn.close();
cpds.setConnectionAttributes(
retrieveMessageTextProperty + "=true");
conn = cpds.getConnection();
assertMessageText(conn,"true");
cpds.setConnectionAttributes(null);
conn.close();
// now with XADataSource
ClientXADataSource xads = new ClientXADataSource();
//XADataSource - retrieveMessageTextProperty
xads.setDatabaseName(dbName);
xads.setConnectionAttributes(
retrieveMessageTextProperty + "=false");
conn = xads.getConnection();
assertMessageText(conn,"false");
conn.close();
xads.setConnectionAttributes(
retrieveMessageTextProperty + "=true");
conn = xads.getConnection();
assertMessageText(conn,"true");
conn.close();
xads.setConnectionAttributes(null);
}
/* -- Helper Method for testClientMessageTextDSConnectionAttribute -- */
private static void assertMessageText(
Connection conn, String retrieveMessageTextValue)
throws SQLException
{
try {
conn.createStatement().executeQuery("SELECT * FROM APP.NOTTHERE");
}
catch (SQLException e)
{
assertSQLState("42X05", e);
if (retrieveMessageTextValue.equals("true") )
{
assertTrue(e.getMessage().indexOf("does not exist") >= 0);
}
else
{
// retrieveMessageTextValue is false
assertTrue(e.getMessage().indexOf("does not exist") == -1);
}
}
}
/**
* Check that messageText connection attribute functions correctly.
* retrievemessagetext was tested in checkdriver, and derbynet/testij
* (but not tested for datasources), and in datasourcepermissions_net,
* but as it has nothing to do with permissions/authentication,
* this test seems a better place for it.
*
* there is a corresponding method call for datasources in DataSourceTest
*
* @throws SQLException
*/
public void testDescriptionProperty()
throws SQLException, Exception {
// ConnectionPoolDataSource - setDescription
subTestDataSourceDescription(
(DataSource) J2EEDataSource.getConnectionPoolDataSource());
// XADataSource - setDescription
subTestDataSourceDescription(
(DataSource) J2EEDataSource.getXADataSource());
}
/**
* Utility method for testing setting and fetching the description
* property on a data source.
*/
private void subTestDataSourceDescription(DataSource ds) throws Exception
{
String setDescription =
"Everything you ever wanted to know about this datasource";
JDBCDataSource.setBeanProperty(ds, "description", setDescription);
ds.getConnection();
assertEquals(setDescription, JDBCDataSource.getBeanProperty(ds, "description"));
JDBCDataSource.clearStringBeanProperty(ds, "description");
assertNull(JDBCDataSource.getBeanProperty(ds, "description"));
}
/* ------------------ JDBC30 (and up) Fixtures ------------------ */
public void testXAHoldability() throws SQLException, XAException {
// DERBY-2533 -
// This test, when run with Network server / DerbyNetClient
// leaves the database is a bad state which results in a
// network protocol error
if (usingDerbyNetClient())
return;
// START XA HOLDABILITY TEST
XADataSource dscsx = J2EEDataSource.getXADataSource();
XAConnection xac = dscsx.getXAConnection();
XAResource xr = xac.getXAResource();
Xid xid = new cdsXid(25, (byte) 21, (byte) 01);
Connection conn1 = xac.getConnection();
// check that autocommit is true; default for a connection
assertTrue(conn1.getAutoCommit());
// check that holdability is HOLD_CURSORS_OVER_COMMIT in a default
// CONNECTION(not in xa transaction yet)
assertEquals(
ResultSet.HOLD_CURSORS_OVER_COMMIT, conn1.getHoldability());
// start a global transaction and default holdability and
// autocommit will be switched to match Derby XA restrictions
xr.start(xid, XAResource.TMNOFLAGS);
// So, now autocommit should be false for connection because it is
// part of the global transaction
assertFalse(conn1.getAutoCommit());
// Connection's holdability is now CLOSE_CURSORS_AT_COMMIT because
// it is part of the global transaction
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT, conn1.getHoldability());
xr.end(xid, XAResource.TMSUCCESS);
conn1.commit();
conn1.close();
xid = new cdsXid(27, (byte) 21, (byte) 01);
xr.start(xid, XAResource.TMNOFLAGS);
conn1 = xac.getConnection();
// CONNECTION(in xa transaction) HOLDABILITY:
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT, conn1.getHoldability());
// Autocommit on Connection inside global transaction should be false
assertFalse(conn1.getAutoCommit());
xr.end(xid, XAResource.TMSUCCESS);
conn1.rollback();
Connection conn = xac.getConnection();
conn.setAutoCommit(false);
conn.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
// CONNECTION(non-xa transaction) HOLDABILITY:
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT, conn.getHoldability());
Statement s = conn.createStatement();
// STATEMENT HOLDABILITY:
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT, s.getResultSetHoldability());
s.executeUpdate("insert into hold_30 values " +
"(1,'init2'), (2, 'init3'), (3,'init3')");
s.executeUpdate("insert into hold_30 values " +
"(4,'init4'), (5, 'init5'), (6,'init6')");
s.executeUpdate("insert into hold_30 values " +
"(7,'init7'), (8, 'init8'), (9,'init9')");
// STATEMENT HOLDABILITY :
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT, s.getResultSetHoldability());
Statement sh = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT);
PreparedStatement psh = conn.prepareStatement(
"select id from hold_30 for update", ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT);
CallableStatement csh = conn.prepareCall(
"select id from hold_30 for update", ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT);
// STATEMENT HOLDABILITY :
assertEquals(
ResultSet.HOLD_CURSORS_OVER_COMMIT, sh.getResultSetHoldability());
// PREPARED STATEMENT HOLDABILITY :
assertEquals(
ResultSet.HOLD_CURSORS_OVER_COMMIT, psh.getResultSetHoldability());
// CALLABLE STATEMENT HOLDABILITY :
assertEquals(
ResultSet.HOLD_CURSORS_OVER_COMMIT, csh.getResultSetHoldability());
ResultSet rsh = sh.executeQuery("select id from hold_30 for update");
rsh.next();
assertEquals(1, rsh.getInt(1)); // H@1 id
rsh.next();
assertEquals(2, rsh.getInt(1)); // H@2 id
conn.commit();
rsh.next();
assertEquals(3, rsh.getInt(1)); // H@3 id
conn.commit();
xid = new cdsXid(23, (byte) 21, (byte) 01);
xr.start(xid, XAResource.TMNOFLAGS);
Statement stmtInsideGlobalTransaction = conn.createStatement();
PreparedStatement prepstmtInsideGlobalTransaction =
conn.prepareStatement("select id from hold_30");
CallableStatement callablestmtInsideGlobalTransaction =
conn.prepareCall("select id from hold_30");
// CONNECTION(xa) HOLDABILITY:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, conn.getHoldability());
// STATEMENT(this one was created with holdability false, outside the
// global transaction. Check its holdability inside global transaction
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT, s.getResultSetHoldability());
// STATEMENT(this one was created with holdability true,
// outside the global transaction. Check its holdability inside
// global transaction:
// DERBY-2531: network server / DerbyNetClient has a different value
// than embedded.
if (usingEmbedded())
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
sh.getResultSetHoldability());
else if (usingDerbyNetClient())
assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT,
sh.getResultSetHoldability());
// STATEMENT(this one was created with default holdability inside this
// global transaction. Check its holdability:
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT,
stmtInsideGlobalTransaction.getResultSetHoldability());
// PREPAREDSTATEMENT(this one was created with default holdability
// inside this global transaction. Check its holdability:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
prepstmtInsideGlobalTransaction.getResultSetHoldability());
// CALLABLESTATEMENT(this one was created with default holdability
// inside this global transaction. Check its holdability:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
callablestmtInsideGlobalTransaction.getResultSetHoldability());
ResultSet rsx = s.executeQuery("select id from hold_30 for update");
rsx.next();
assertEquals(1, rsx.getInt(1)); // X@1 id
rsx.next();
assertEquals(2, rsx.getInt(1)); // X@2 id
xr.end(xid, XAResource.TMSUCCESS);
// result set should not be useable, since it is part of a detached
// XAConnection
try {
rsx.next();
fail("rsx's connection not active id ");
} catch (SQLException sqle) {
assertSQLState("08003", sqle);
}
// result set should not be useable, it should have been closed by
// the xa start.
try {
rsh.next();
fail("rsh's connection not active id ");
} catch (SQLException sqle) {
assertSQLState("XCL16", sqle);
}
// resume XA transaction and keep using rs");
xr.start(xid, XAResource.TMJOIN);
Statement stmtAfterGlobalTransactionResume = conn.createStatement();
PreparedStatement prepstmtAfterGlobalTransactionResume =
conn.prepareStatement("select id from hold_30");
CallableStatement callablestmtAfterGlobalTransactionResume =
conn.prepareCall("select id from hold_30");
// Check holdability of various jdbc objects after resuming XA
// transaction
// CONNECTION(xa) HOLDABILITY:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,conn.getHoldability());
// STATEMENT(this one was created with holdability false, outside the
// global transaction. Check its holdability inside global transaction
assertEquals(
ResultSet.CLOSE_CURSORS_AT_COMMIT, s.getResultSetHoldability());
// STATEMENT(this one was created with holdability true, outside the
// global transaction. Check its holdability inside global transaction
if (usingEmbedded())
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
sh.getResultSetHoldability());
else if (usingDerbyNetClient())
assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT,
sh.getResultSetHoldability());
// STATEMENT(this one was created with default holdability inside the
// global transaction when it was first started. Check its holdability
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
stmtInsideGlobalTransaction.getResultSetHoldability());
// PREPAREDSTATEMENT(this one was created with default holdability
// inside the global transaction when it was first started. Check its
// holdability)
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
prepstmtInsideGlobalTransaction.getResultSetHoldability());
// CALLABLESTATEMENT(this one was created with default holdability
// inside the global transaction when it was first started. Check its
// holdability) HOLDABILITY
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
callablestmtInsideGlobalTransaction.getResultSetHoldability());
// STATEMENT(this one was created with default holdability after the
// global transaction was resumed. Check its holdability
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
stmtAfterGlobalTransactionResume.getResultSetHoldability());
// PREPAREDSTATEMENT(this one was created with default holdability
// after the global transaction was resumed. Check its holdability
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
prepstmtAfterGlobalTransactionResume.getResultSetHoldability());
// CALLABLESTATEMENT(this one was created with default holdability
// after the global transaction was resumed. Check its holdability
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
callablestmtAfterGlobalTransactionResume.getResultSetHoldability());
// DERBY-1370
if (usingEmbedded())
{
// Network XA BUG gives result set closed
rsx.next();
assertEquals(3, rsx.getInt(1)); // X@3 id
}
xr.end(xid, XAResource.TMSUCCESS);
if (xr.prepare(xid) != XAResource.XA_RDONLY)
xr.commit(xid, false);
// try again once the xa transaction has been committed.
try {
rsx.next();
fail("rsx's connection not active id (B)");
} catch (SQLException sqle) {
assertSQLState("XCL16", sqle);
}
try {
rsh.next();
fail ("rsh's should be closed (B)");
} catch (SQLException sqle) {
assertSQLState("XCL16", sqle);
}
// Set connection to hold
conn.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
// CONNECTION(held) HOLDABILITY:
assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT,
conn.getHoldability());
xid = new cdsXid(24, (byte) 21, (byte) 01);
xr.start(xid, XAResource.TMNOFLAGS);
// CONNECTION(xa) HOLDABILITY:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, conn.getHoldability());
try {
conn.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
fail("allowed to set hold mode in xa transaction");
} catch (SQLException sqle) {
assertSQLState("XJ05C", sqle);
}
// JDBC 4.0 (proposed final draft) section 16.1.3.1 allows Statements
// to be created with a different holdability if the driver cannot
// support it. In this case the driver does not support holdability in
// a global transaction, so a valid statement is returned with close
// cursors on commit.
Statement shxa = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT);
// HOLDABLE Statement in global xact "
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
s.getResultSetHoldability());
assertEquals(10000, conn.getWarnings().getErrorCode());
shxa.close();
shxa = conn.prepareStatement("select id from hold_30",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
// HOLDABLE PreparedStatement in global xact
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
s.getResultSetHoldability());
assertEquals(10000, conn.getWarnings().getErrorCode());
shxa.close();
shxa = conn.prepareCall("CALL SYSCS_UTIL.SYSCS_CHECKPOINT_DATABASE()",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
// HOLDABLE CallableStatement in global xact:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
s.getResultSetHoldability());
assertEquals(10000, conn.getWarnings().getErrorCode());
shxa.close();
// check we can use a holdable statement set up in local mode.
// holdability is downgraded, tested in XATest.java
// DERBY-1370
if(usingEmbedded()) {
// STATEMENT HOLDABILITY:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
sh.getResultSetHoldability());
sh.executeQuery("select id from hold_30").close();
sh.execute("select id from hold_30");
sh.getResultSet().close();
// PREPARED STATEMENT HOLDABILITY:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
psh.getResultSetHoldability());
psh.executeQuery().close();
psh.execute();
psh.getResultSet().close();
// CALLABLE STATEMENT HOLDABILITY:
assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT,
csh.getResultSetHoldability());
csh.executeQuery().close();
csh.execute();
csh.getResultSet().close();
}
// but an update works
sh.executeUpdate("insert into hold_30 values(10, 'init10')");
xr.end(xid, XAResource.TMSUCCESS);
// CONNECTION(held) HOLDABILITY:
assertEquals(
ResultSet.HOLD_CURSORS_OVER_COMMIT, conn.getHoldability());
s.close();
sh.close();
csh.close();
psh.close();
rsx.close();
stmtInsideGlobalTransaction.close();
prepstmtInsideGlobalTransaction.close();
callablestmtInsideGlobalTransaction.close();
stmtAfterGlobalTransactionResume.close();
prepstmtAfterGlobalTransactionResume.close();
callablestmtAfterGlobalTransactionResume.close();
conn.close();
xac.close();
TestConfiguration.getCurrent().shutdownDatabase();
// END XA HOLDABILITY TEST");
}
/**
* Tests for DERBY-1144
*
* This test tests that holdability, autocomit, and transactionIsolation
* are reset on getConnection for PooledConnections obtaind from
* connectionPoolDataSources
*
* DERBY-1134 has been filed for more comprehensive testing of client
* connection state.
*
* @throws SQLException
*/
public void timeoutTestDerby1144PooledDS() throws SQLException {
PooledConnection pc1 = null;
// Test holdability
ConnectionPoolDataSource ds =
J2EEDataSource.getConnectionPoolDataSource();
pc1 = ds.getPooledConnection();
assertPooledConnHoldability("PooledConnection", pc1);
pc1.close();
// Test autocommit
pc1 = ds.getPooledConnection();
assertPooledConnAutoCommit("PooledConnection", pc1);
pc1.close();
// Test pooled connection isolation
pc1 = ds.getPooledConnection();
assertPooledConnIso("PooledConnection" , pc1);
pc1.close();
}
public void timeoutTestDerby1144XADS() throws SQLException {
XADataSource xds = J2EEDataSource.getXADataSource();
// Test xa connection isolation
XAConnection xpc1 = xds.getXAConnection();
assertPooledConnIso("XAConnection", xpc1);
xpc1.close();
}
/* -------------- Helper Methods for testDerby1144 -------------- */
/**
* Make sure autocommit gets reset on PooledConnection.getConnection()
* @param desc description of connection
* @param pc1 pooled connection to test
* @throws SQLException
*/
private static void assertPooledConnAutoCommit(
String desc, PooledConnection pc1) throws SQLException
{
// ** Verify autoCommit state
Connection conn = pc1.getConnection();
conn.setAutoCommit(true);
// reset the connection and see if the autocommit has changed
conn = pc1.getConnection();
boolean autocommit = conn.getAutoCommit();
// autocommit should get reset on getConnection
assertTrue(autocommit);
conn.close();
}
/**
* Checks that Holdability gets reset on PooledConnection.getConnection()
* @param desc
* @param pc1
* @throws SQLException
*/
private static void assertPooledConnHoldability(
String desc, PooledConnection pc1) throws SQLException
{
// **Test holdability state
Connection conn = pc1.getConnection();
conn.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
// reset the connection and see if the holdability gets reset
// to HOLD_CURSORS_OVER_COMMIT
conn = pc1.getConnection();
assertConnHoldability(conn, ResultSet.HOLD_CURSORS_OVER_COMMIT);
conn.close();
}
/**
* Verify connection holdablity is expected holdability
* @param conn
* @param expectedHoldability
* * @throws SQLException
*/
private static void assertConnHoldability(
Connection conn, int expectedHoldability) throws SQLException
{
int holdability = conn.getHoldability();
assertEquals (expectedHoldability, holdability);
}
/**
* Test that isolation is reset on PooledConnection.getConnection()
* @param pooledConnType Descripiton of the type of pooled connection
* @param pc PooledConnection or XAConnection
* @throws SQLException
*/
private void assertPooledConnIso(
String pooledConnType, PooledConnection pc) throws SQLException {
Connection conn = pc.getConnection();
setupDerby1144Table(conn);
// *** Test isolation level reset on conntype.getConnection()
conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
assertIsoLocks(conn, Connection.TRANSACTION_READ_UNCOMMITTED);
conn.close();
//Get a new connection with pooledConnType.getConnection()
// Isolation level should be reset to READ_COMMITTED
Connection newconn = pc.getConnection();
assertIsoLocks(newconn, Connection.TRANSACTION_READ_COMMITTED);
}
/*
* insert two rows into the simple table for DERBY-1144 tests
* @param conn
* @throws SQLException
*/
private static void setupDerby1144Table(Connection conn)
throws SQLException {
Statement stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO intTable VALUES(1)");
stmt.executeUpdate("INSERT INTO intTable VALUES(2)");
conn.commit ();
}
/*
* Checks locks for designated isolation level on the connection.
* Currently only supports TRANSACTION_READ_COMMITTED and
* TRANSACTION_READ_UNCOMMITTED
* @param conn Connection to test
* @param isoLevel expected isolation level
*
*/
private void assertIsoLocks(Connection conn, int expectedIsoLevel)
throws SQLException {
int conniso = conn.getTransactionIsolation();
assertEquals(expectedIsoLevel, conniso);
boolean selectTimedOut = selectTimesoutDuringUpdate(conn);
// expect a lock timeout for READ_COMMITTED
switch (conniso) {
case Connection.TRANSACTION_READ_UNCOMMITTED:
assertFalse(selectTimedOut); break;
case Connection.TRANSACTION_READ_COMMITTED:
assertTrue(selectTimedOut); break;
default:
System.out.println("No test support for isolation level");
}
}
/*
* Determine if a select on this connection during update will timeout.
* Used to establish isolation level. If the connection isolation level
* is <code> Connection.TRANSACTION_READ_UNCOMMITTED </code> it will not
* timeout. Otherwise it should.
*
* @param conn Connection to test.
* @return true if the select got a lock timeout, false otherwise.
*/
private boolean selectTimesoutDuringUpdate(Connection conn)
throws SQLException {
Connection updateConn=null;
conn.setAutoCommit(false);
try {
// create another connection and do an update but don't commit
updateConn = openDefaultConnection();
updateConn.setAutoCommit(false);
// First update the rows on the update connection
Statement upStmt = updateConn.createStatement();
upStmt.executeUpdate("update intTable set i = 3");
// now see if we can select them
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select * from intTable");
while (rs.next()){};
rs.close();
}
catch (SQLException e)
{
if (e.getSQLState().equals("40XL1"))
{
// If we got a lock timeout this is not read uncommitted
return true;
}
}
finally {
try {
conn.rollback();
updateConn.rollback();
}catch (SQLException se) {
se.printStackTrace();
}
}
return false;
}
/* -------------------- Other Helper Methods -------------------- */
private void assertConnectionState(
int expectedHoldability, int expectedIsolation,
boolean expectedCommitSetting, boolean expectedReadOnly,
Connection conn) throws SQLException
{
assertEquals(expectedHoldability, conn.getHoldability());
assertEquals(expectedIsolation, conn.getTransactionIsolation());
assertEquals(expectedCommitSetting, conn.getAutoCommit());
assertEquals(expectedReadOnly, conn.isReadOnly());
}
private static void setDatabaseProperty(String property, String value)
throws SQLException
{
DataSource ds = JDBCDataSource.getDataSource();
Connection cadmin = ds.getConnection();
CallableStatement cs = cadmin.prepareCall(
"CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?, ?)");
cs.setString(1, property);
cs.setString(2, value);
cs.execute();
cs.close();
cadmin.close();
}
private void setHoldability(Connection conn, boolean hold) throws SQLException {
conn.setHoldability(hold ? ResultSet.HOLD_CURSORS_OVER_COMMIT : ResultSet.CLOSE_CURSORS_AT_COMMIT);
}
private static void dsConnectionRequests(
String[] expectedValues, DataSource ds) {
// checks currently only implemented for embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(ds, "javax.sql.DataSource");
}
try {
ds.getConnection();
if (!expectedValues[0].equals("OK"))
fail (" expected connection to fail, but was OK");
} catch (SQLException sqle) {
assertSQLState(expectedValues[0], sqle);
}
dsConnectionRequest(expectedValues[1], ds, null, null);
dsConnectionRequest(expectedValues[2], ds, "fred", null);
dsConnectionRequest(expectedValues[3], ds, "fred", "wilma");
dsConnectionRequest(expectedValues[4], ds, null, "wilma");
dsConnectionRequest(
expectedValues[5], ds, null, "databaseName=wombat");
dsConnectionRequest(
expectedValues[6], ds, "fred", "databaseName=wombat");
dsConnectionRequest(expectedValues[7],
ds, "fred", "databaseName=wombat;password=wilma");
dsConnectionRequest(expectedValues[8],
ds, "fred", "databaseName=wombat;password=betty");
}
private static void dsConnectionRequest(
String expectedValue, DataSource ds, String user, String ConnAttr)
{
try {
ds.getConnection(user, ConnAttr);
if (!expectedValue.equals("OK"))
fail (" expected connection to fail, but was OK");
} catch (SQLException sqle) {
assertSQLState(expectedValue, sqle);
}
}
private static void dsConnectionRequests(
String[] expectedValues, ConnectionPoolDataSource ds) {
try {
ds.getPooledConnection();
if (!expectedValues[0].equals("OK"))
fail (" expected connection to fail, but was OK");
} catch (SQLException sqle) {
assertSQLState(expectedValues[0], sqle);
}
dsConnectionRequest(expectedValues[1], ds, null, null);
dsConnectionRequest(expectedValues[2], ds, "fred", null);
dsConnectionRequest(expectedValues[3], ds, "fred", "wilma");
dsConnectionRequest(expectedValues[4], ds, null, "wilma");
dsConnectionRequest(
expectedValues[5], ds, null, "databaseName=wombat");
dsConnectionRequest(
expectedValues[6], ds, "fred", "databaseName=wombat");
dsConnectionRequest(expectedValues[7],
ds, "fred", "databaseName=wombat;password=wilma");
dsConnectionRequest(expectedValues[8],
ds, "fred", "databaseName=wombat;password=betty");
}
private static void dsConnectionRequest(String expectedValue,
ConnectionPoolDataSource ds, String user, String ConnAttr)
{
try {
ds.getPooledConnection(user, ConnAttr);
if (!expectedValue.equals("OK"))
fail (" expected connection to fail, but was OK");
} catch (SQLException sqle) {
assertSQLState(expectedValue, sqle);
}
}
private static void dsConnectionRequests(
String[] expectedValues, XADataSource ds) {
try {
ds.getXAConnection();
if (!expectedValues[0].equals("OK"))
fail (" expected connection to fail, but was OK");
} catch (SQLException sqle) {
assertSQLState(expectedValues[0], sqle);
}
dsConnectionRequest(expectedValues[1], ds, null, null);
dsConnectionRequest(expectedValues[2], ds, "fred", null);
dsConnectionRequest(expectedValues[3], ds, "fred", "wilma");
dsConnectionRequest(expectedValues[4], ds, null, "wilma");
dsConnectionRequest(
expectedValues[5], ds, null, "databaseName=" + dbName);
dsConnectionRequest(
expectedValues[6], ds, "fred", "databaseName=" + dbName);
dsConnectionRequest(expectedValues[7],
ds, "fred", "databaseName=" + dbName + ";password=wilma");
dsConnectionRequest(expectedValues[8],
ds, "fred", "databaseName=" + dbName + ";password=betty");
}
private static void dsConnectionRequest(String expectedValue,
XADataSource ds, String user, String ConnAttr)
{
try {
ds.getXAConnection(user, ConnAttr);
if (!expectedValue.equals("OK"))
fail (" expected connection to fail, but was OK");
} catch (SQLException sqle) {
assertSQLState(expectedValue, sqle);
}
}
protected void assertXAException(String tag, XAException xae) {
// for all our cases, we expect some kind of closed con error
// but the message is different for embedded vs. network server
if (usingEmbedded())
assertEquals("No current connection.", xae.getMessage());
else if (usingDerbyNetClient())
assertEquals(
"XAER_RMFAIL : No current connection.", xae.getMessage());
Throwable t = xae.getCause();
if (t instanceof SQLException)
assertSQLState("08003", (SQLException)t);
}
private static void queryOnStatement(String expectedCursorName,
int[] expectedValues, Connection conn, Statement s)
throws SQLException {
// DERBY-2531
// network server gives mismatched connections. See also
// comment in testAllDataSources()
if (usingEmbedded()) {
assertEquals(conn, s.getConnection());
}
resultSetQuery(expectedCursorName, expectedValues,
s.executeQuery("select * from intTable"));
}
private static void resultSetQuery(String expectedCursorName,
int[] expectedValues, ResultSet rs) throws SQLException
{
// checks currently only implemented for embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(rs, "java.sql.ResultSet");
}
assertEquals(expectedCursorName, rs.getCursorName());
int index=0;
while (rs.next()) {
assertEquals(expectedValues[index], rs.getInt(1));
index++;
}
assertEquals(expectedValues.length, index++);
rs.close();
}
private static void assertLocks(int[] expectedValues, Connection conn)
throws SQLException {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery(
"SELECT XID, sum(cast (LOCKCOUNT AS INT)) " +
"FROM SYSCS_DIAG.LOCK_TABLE AS L GROUP BY XID");
// Don't output actual XID's as they tend for every catalog change
// to the system.
int xact_index = 0;
while (rs.next()) {
if (expectedValues != null)
assertEquals(expectedValues[xact_index], rs.getInt(2));
else
fail("expected no locks");
xact_index++;
}
if (expectedValues != null)
assertEquals(expectedValues.length, xact_index);
rs.close();
s.close();
}
private void assertStatementState(int[] parameterExpectedValues,
int[] expectedValues, Statement s)
throws SQLException {
assertEquals(expectedValues[0], s.getResultSetType());
assertEquals(
expectedValues[1], s.getResultSetConcurrency());
assertEquals(
expectedValues[2], s.getFetchDirection());
assertEquals(expectedValues[3], s.getFetchSize());
assertEquals(expectedValues[4], s.getMaxFieldSize());
assertEquals(expectedValues[5], s.getMaxRows());
assertEquals(expectedValues[6], s.getResultSetHoldability());
if (s instanceof PreparedStatement) {
PreparedStatement ps = (PreparedStatement) s;
ParameterMetaData psmd = ps.getParameterMetaData();
// Parameter count:
assertEquals(parameterExpectedValues[0], psmd.getParameterCount());
for (int i = 1; i <= psmd.getParameterCount(); i++) {
assertEquals(parameterExpectedValues[i], psmd.getParameterType(i));
}
}
}
/**
Create a statement with modified State.
*/
private Statement createFloatStatementForStateChecking(
int[] StatementExpectedValues, Connection conn)
throws SQLException {
Statement s = internalCreateFloatStatementForStateChecking(conn);
s.setCursorName("StokeNewington");
s.setFetchDirection(ResultSet.FETCH_REVERSE);
s.setFetchSize(444);
s.setMaxFieldSize(713);
s.setMaxRows(19);
// Create
assertStatementState(null, StatementExpectedValues, s);
return s;
}
private Statement internalCreateFloatStatementForStateChecking(
Connection conn) throws SQLException {
return conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
}
private PreparedStatement createFloatStatementForStateChecking(
int[] parameterExpectedValues, int[] PreparedStatementExpectedValues,
Connection conn, String sql)
throws SQLException {
PreparedStatement s =
internalCreateFloatStatementForStateChecking(conn, sql);
s.setCursorName("StokeNewington");
s.setFetchDirection(ResultSet.FETCH_REVERSE);
s.setFetchSize(888);
s.setMaxFieldSize(317);
s.setMaxRows(91);
// PreparedStatement Create
assertStatementState(
parameterExpectedValues, PreparedStatementExpectedValues, s);
return s;
}
private PreparedStatement internalCreateFloatStatementForStateChecking(
Connection conn, String sql) throws SQLException {
return conn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
}
private CallableStatement createFloatCallForStateChecking(
int[] parameterExpectedValues, int[] CallableStatementExpectedValues,
Connection conn, String sql)
throws SQLException
{
CallableStatement s =
internalCreateFloatCallForStateChecking(conn, sql);
s.setCursorName("StokeNewington");
s.setFetchDirection(ResultSet.FETCH_REVERSE);
s.setFetchSize(999);
s.setMaxFieldSize(137);
s.setMaxRows(85);
// Callable Statement Create
assertStatementState(
parameterExpectedValues, CallableStatementExpectedValues, s);
return s;
}
private CallableStatement internalCreateFloatCallForStateChecking(
Connection conn, String sql) throws SQLException {
return conn.prepareCall(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
}
private void assertConnectionOK(
Object[] expectedValues, String dsName, Connection conn)
throws SQLException {
assertEquals(
((Integer)expectedValues[0]).intValue(), conn.getHoldability());
// check it's a 3.0 connection object by checking if
// set & release Savepoint is ok.
try {
conn.releaseSavepoint(conn.setSavepoint());
if (conn.getAutoCommit())
fail("expected a SQLExpection (savepoint with autocommit on");
if (!((String)expectedValues[1]).equals("OK"))
fail("expected a SQLExpection (savepoint with autocommit on");
} catch (SQLException sqle) {
// we expect savepoints exceptions because either
// it's a global transaction, or it's in auto commit mode.
if (conn.getAutoCommit())
assertSQLState("XJ010", sqle);
else if (((String)expectedValues[1]).equals("OK"))
throw sqle;
else
assertSQLState((String)expectedValues[1], sqle);
}
// Running connection checks
// connection checks currently only implemented for Embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(conn, "java.sql.Connection");
SecurityCheck.assertSourceSecurity(
conn.getMetaData(), "java.sql.DatabaseMetaData");
}
assertEquals(((Integer)expectedValues[2]).intValue(),
conn.getTransactionIsolation());
assertEquals(((Boolean)expectedValues[3]).booleanValue(),
conn.getAutoCommit());
assertEquals(((Boolean)expectedValues[4]).booleanValue(),
conn.isReadOnly());
if (dsName.endsWith("DataSource"))
assertNull(conn.getWarnings());
Statement s1 = conn.createStatement();
assertStatementOK(dsName, conn, s1);
assertStatementOK(dsName, conn, conn.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY));
Connection c1 = conn.getMetaData().getConnection();
// c1 and conn should be the same connection object.
if (!usingDerbyNetClient() && dsName.indexOf("DataSource")>=0)
assertEquals(c1, conn);
// Derby-33 - setTypeMap on connection
try {
conn.setTypeMap(java.util.Collections.EMPTY_MAP);
if (!((String)expectedValues[5]).equals("OK"))
fail (" expected an sqlexception on setTypeMap(EMPTY_MAP)");
} catch (SQLException sqle) {
if (((String)expectedValues[5]).equals("OK"))
throw sqle;
else
assertSQLState((String)expectedValues[5], sqle);
}
try {
// expect 0A000 - not implemented for client,
// XJ081 - invalid null value passed as map for embedded
conn.setTypeMap(null);
fail ("setTypeMap(null) should throw exception");
} catch (SQLException sqle) {
assertSQLState((String)expectedValues[6], sqle);
}
try {
// a populated map, not implemented
java.util.Map map = new java.util.HashMap();
map.put("name", "class");
conn.setTypeMap(map);
if (!((String)expectedValues[7]).equals("OK"))
fail (" expected an sqlexception on setTypeMap(map)");
} catch (SQLException sqle) {
if (((String)expectedValues[7]).equals("OK"))
throw sqle;
else
assertSQLState((String)expectedValues[7], sqle);
}
assertConnectionPreClose(dsName, conn);
conn.close();
// method calls on a closed connection
conn.close(); // expect no error
try {
conn.createStatement();
fail (dsName + " <closedconn>.createStatement(), " +
"expected 08003 - No current connection");
} catch (SQLException sqle) {
assertSQLState("08003", sqle);
}
try {
s1.execute("values 1");
fail(dsName + " <closedstmt>.execute(), " +
"expected 08003 - No current connection");
} catch (SQLException sqle) {
assertSQLState("08003", sqle);
}
}
private void assertConnectionPreClose(String dsName, Connection conn)
throws SQLException {
// before closing the connection, attempt to change holdability
// and readOnly
conn.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
if (!dsName.equals("Nested2"))
{
try {
conn.setReadOnly(true);
} catch (SQLException sqle) {
// cannot set read-only in an active transaction, & sometimes
// connections are active at this point.
assertSQLState("25501", sqle);
}
}
}
private void assertStatementOK(String dsName, Connection conn, Statement s)
throws SQLException {
// checks currently only implemented for embedded
if (usingEmbedded())
{
SecurityCheck.assertSourceSecurity(s, "java.sql.Statement");
}
Connection c1 = s.getConnection();
if (c1 != conn)
{
// with DerbyNetClient and any kind of DataSource, this goes wrong
if (!usingDerbyNetClient() && (dsName.indexOf("DataSource") >= 0))
fail ("incorrect connection object returned for Statement.getConnection()");
}
s.addBatch("insert into intTable values 1");
s.addBatch("insert into intTable values 2,3");
int[] states = s.executeBatch();
if (states[0] != 1)
fail ("invalid update count for first batch statement");
if (states[1] != 2)
fail ("invalid update count for second batch statement");
ResultSet rs = s.executeQuery("VALUES 1");
if (rs.getStatement() != s)
fail ("incorrect Statement object returned for ResultSet.getStatement for " + dsName);
rs.close();
s.close();
}
/**
When a connection is being pooled, the underlying JDBC embedded
connection object is re-used. As each application gets a new
Connection object, that is really a wrapper around the old connection
it should reset any connection spoecific state on the embedded connection
object.
*/
private static void PoolReset(String type, PooledConnection pc) throws SQLException
{
PoolResetWork("1", "C", pc.getConnection());
PoolResetWork("2", "", pc.getConnection());
PoolResetWork("3", "D", pc.getConnection());
pc.close();
}
private static void PoolResetWork(
String expectedID, String tableAction, Connection conn)
throws SQLException
{
Statement s = conn.createStatement();
if (tableAction.equals("C"))
{
s.execute("CREATE TABLE PoolResetWork (id int generated always as identity, name varchar(25))");
}
ResultSet rs = s.executeQuery("VALUES IDENTITY_VAL_LOCAL()");
rs.next();
String val = rs.getString(1);
if (!rs.wasNull() || (val != null))
fail ("initial call to IDENTITY_VAL_LOCAL is not NULL!" + val);
rs.close();
s.executeUpdate("INSERT INTO PoolResetWork(name) values ('derby-222')");
rs = s.executeQuery("VALUES IDENTITY_VAL_LOCAL()");
rs.next();
val = rs.getString(1);
assertEquals(expectedID, val);
rs.close();
if (tableAction.equals("D"))
{
s.execute("DROP TABLE PoolResetWork");
}
s.close();
conn.close();
}
/**
* Make sure this connection's string is unique (DERBY-243)
*/
private static void assertToString(Connection conn) throws Exception
{
assertStringFormat(conn);
String str = conn.toString();
if ( conns.containsKey(str))
{
throw new Exception("ERROR: Connection toString() is not unique: "
+ str);
}
conns.put(str, conn);
}
/**
* Check the format of a pooled connection
**/
private static void assertStringFormat(PooledConnection pc) throws Exception
{
String prefix = assertStringPrefix(pc);
String connstr = pc.toString();
String format = prefix + " \\(ID = [0-9]+\\), Physical Connection = " +
"<none>|" + CONNSTRING_FORMAT;
assertTrue(connstr.matches(format));
}
/**
* Check the format of the connection string. This is the default test
* to run if this is not a BrokeredConnection class
*/
private static void assertStringFormat(Connection conn) //throws Exception
{
assertStringPrefix(conn);
String str = conn.toString();
assertTrue("\nexpected format:\n " + CONNSTRING_FORMAT + "\nactual value:\n " + str,
str.matches(CONNSTRING_FORMAT));
}
/**
* Make sure the connection string starts with the right prefix, which
* is the classname@hashcode.
*
* @return the expected prefix string, this is used in further string
* format checking
*/
private static String assertStringPrefix(Object conn) //throws Exception
{
String connstr = conn.toString();
String prefix = conn.getClass().getName() + "@" + conn.hashCode();
// Connection class and has code for connection string should
// match prefix
assertTrue(connstr.startsWith(prefix));
return prefix;
}
/**
* Check uniqueness of connection strings coming from a
* DataSouce
*/
private static void assertToString(DataSource ds) throws Exception
{
clearConnections();
int numConnections = 10;
for ( int i = 0 ; i < numConnections ; i++ )
{
Connection conn = ds.getConnection();
assertToString(conn);
}
clearConnections();
}
/**
* Clear out and close connections in the connections
* hashtable.
*/
private static void clearConnections() throws SQLException
{
java.util.Iterator it = conns.values().iterator();
while ( it.hasNext() )
{
Connection conn = (Connection)it.next();
conn.close();
}
conns.clear();
}
/**
* Get connections using getConnection() and make sure
* they're unique
*/
private void assertTenConnectionsUnique() throws Exception
{
clearConnections();
// Open ten connections rather than just two to
// try and catch any odd uniqueness bugs. Still
// no guarantee but is better than just two.
int numConnections = 10;
for ( int i = 0 ; i < numConnections ; i++ )
{
Connection conn = openDefaultConnection();
assertToString(conn);
}
// Now close the connections
clearConnections();
}
/**
* Check uniqueness of strings for an XA data source
*/
private static void assertToString(XADataSource xds) throws Exception
{
int numConnections = 10;
// First get a bunch of pooled connections
// and make sure they're all unique
Hashtable xaConns = new Hashtable();
for ( int i = 0 ; i < numConnections ; i++ )
{
XAConnection xc = xds.getXAConnection();
assertStringFormat(xc);
String str = xc.toString();
// XA connection toString should be unique
assertNull(xaConns.get(str));
xaConns.put(str, xc);
}
// Now check that connections from each of these
// pooled connections have different string values
Iterator it = xaConns.values().iterator();
clearConnections();
while ( it.hasNext() )
{
XAConnection xc = (XAConnection)it.next();
Connection conn = xc.getConnection();
assertToString(conn);
}
clearConnections();
// Now clear out the pooled connections
it = xaConns.values().iterator();
while ( it.hasNext() )
{
XAConnection xc = (XAConnection)it.next();
xc.close();
}
xaConns.clear();
}
/**
* Check uniqueness of strings with a pooled data source.
* We want to check the PooledConnection as well as the
* underlying physical connection.
*/
private static void assertToString(ConnectionPoolDataSource pds)
throws Exception
{
int numConnections = 10;
// First get a bunch of pooled connections
// and make sure they're all unique
Hashtable pooledConns = new Hashtable();
for ( int i = 0 ; i < numConnections ; i++ )
{
PooledConnection pc = pds.getPooledConnection();
assertStringFormat(pc);
String str = pc.toString();
// Pooled connection toString should be unique
assertNull( pooledConns.get(str));
pooledConns.put(str, pc);
}
// Now check that connections from each of these
// pooled connections have different string values
Iterator it = pooledConns.values().iterator();
clearConnections();
while ( it.hasNext() )
{
PooledConnection pc = (PooledConnection)it.next();
Connection conn = pc.getConnection();
assertToString(conn);
}
clearConnections();
// Now clear out the pooled connections
it = pooledConns.values().iterator();
while ( it.hasNext() )
{
PooledConnection pc = (PooledConnection)it.next();
pc.close();
}
pooledConns.clear();
}
/**
* Return the Java class and method for the procedure
* for the nested connection test.
*/
private static String getNestedMethodName()
{
return "checkNesConn";
}
// calling checkConnection
// - for use in a procedure to get a nested connection.
public static void checkNesConn (String dsName) throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:default:connection");
String EmptyMapValue=null;
// Note: currently, not supported
String NullMapValue=null;
String MapMapValue=null;
if (usingEmbedded())
{
EmptyMapValue="OK"; NullMapValue="XJ081"; MapMapValue="0A000";
}
else if (usingDerbyNetClient())
{
EmptyMapValue="0A000"; NullMapValue="0A000"; MapMapValue="0A000";
}
Object[] expectedValues = {
new Integer(ResultSet.HOLD_CURSORS_OVER_COMMIT), "OK",
new Integer(2), new Boolean(false), new Boolean(false),
EmptyMapValue, NullMapValue, MapMapValue};
new J2EEDataSourceTest("J2EEDataSourceTest").assertConnectionOK(
expectedValues, dsName, conn);
}
}
class cdsXid implements Xid, Serializable
{
private static final long serialVersionUID = 64467338100036L;
private final int format_id;
private byte[] global_id;
private byte[] branch_id;
cdsXid(int xid, byte b1, byte b2)
{
format_id = xid;
global_id = new byte[Xid.MAXGTRIDSIZE];
branch_id = new byte[Xid.MAXBQUALSIZE];
for (int i = 0; i < global_id.length; i++) {
global_id[i] = b1;
}
for (int i = 0; i < branch_id.length; i++) {
branch_id[i] = b2;
}
}
/**
* Obtain the format id part of the Xid.
* <p>
*
* @return Format identifier. O means the OSI CCR format.
**/
public int getFormatId()
{
return(format_id);
}
/**
* Obtain the global transaction identifier part of XID as an array of
* bytes.
* <p>
*
* @return A byte array containing the global transaction identifier.
**/
public byte[] getGlobalTransactionId()
{
return(global_id);
}
/**
* Obtain the transaction branch qualifier part of the Xid in a byte array.
* <p>
*
* @return A byte array containing the branch qualifier of the transaction.
**/
public byte[] getBranchQualifier()
{
return(branch_id);
}
}
| DERBY-3431: DatabaseMetaData.getConnection returns the wrong connection when using connection pooling.
Added a test case exposing the bug where DatabaseMetaData.getConnection returns a reference to a connection it should not publish.
Note that the test is disabled, because the bug is still at large.
Patch file: derby-3431-2a-test.diff
git-svn-id: 2c06e9c5008124d912b69f0b82df29d4867c0ce2@650814 13f79535-47bb-0310-9956-ffa450edef68
| java/testing/org/apache/derbyTesting/functionTests/tests/jdbcapi/J2EEDataSourceTest.java | DERBY-3431: DatabaseMetaData.getConnection returns the wrong connection when using connection pooling. Added a test case exposing the bug where DatabaseMetaData.getConnection returns a reference to a connection it should not publish. Note that the test is disabled, because the bug is still at large. Patch file: derby-3431-2a-test.diff |
|
Java | apache-2.0 | 23a1ee388242539944e5608ef39343f01f6bb987 | 0 | mduerig/jackrabbit-oak,afilimonov/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,catholicon/jackrabbit-oak,francescomari/jackrabbit-oak,meggermo/jackrabbit-oak,davidegiannella/jackrabbit-oak,kwin/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,yesil/jackrabbit-oak,stillalex/jackrabbit-oak,ieb/jackrabbit-oak,mduerig/jackrabbit-oak,leftouterjoin/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,code-distillery/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,catholicon/jackrabbit-oak,meggermo/jackrabbit-oak,leftouterjoin/jackrabbit-oak,leftouterjoin/jackrabbit-oak,meggermo/jackrabbit-oak,ieb/jackrabbit-oak,afilimonov/jackrabbit-oak,tripodsan/jackrabbit-oak,chetanmeh/jackrabbit-oak,alexparvulescu/jackrabbit-oak,anchela/jackrabbit-oak,alexkli/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,alexkli/jackrabbit-oak,tripodsan/jackrabbit-oak,kwin/jackrabbit-oak,bdelacretaz/jackrabbit-oak,francescomari/jackrabbit-oak,joansmith/jackrabbit-oak,anchela/jackrabbit-oak,alexkli/jackrabbit-oak,code-distillery/jackrabbit-oak,catholicon/jackrabbit-oak,yesil/jackrabbit-oak,anchela/jackrabbit-oak,stillalex/jackrabbit-oak,chetanmeh/jackrabbit-oak,yesil/jackrabbit-oak,alexparvulescu/jackrabbit-oak,alexkli/jackrabbit-oak,joansmith/jackrabbit-oak,bdelacretaz/jackrabbit-oak,joansmith/jackrabbit-oak,meggermo/jackrabbit-oak,alexparvulescu/jackrabbit-oak,anchela/jackrabbit-oak,afilimonov/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,catholicon/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,bdelacretaz/jackrabbit-oak,chetanmeh/jackrabbit-oak,kwin/jackrabbit-oak,stillalex/jackrabbit-oak,stillalex/jackrabbit-oak,afilimonov/jackrabbit-oak,francescomari/jackrabbit-oak,mduerig/jackrabbit-oak,rombert/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,yesil/jackrabbit-oak,catholicon/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,anchela/jackrabbit-oak,code-distillery/jackrabbit-oak,chetanmeh/jackrabbit-oak,davidegiannella/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,rombert/jackrabbit-oak,alexparvulescu/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,alexparvulescu/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,francescomari/jackrabbit-oak,code-distillery/jackrabbit-oak,meggermo/jackrabbit-oak,stillalex/jackrabbit-oak,mduerig/jackrabbit-oak,leftouterjoin/jackrabbit-oak,alexkli/jackrabbit-oak,bdelacretaz/jackrabbit-oak,ieb/jackrabbit-oak,mduerig/jackrabbit-oak,rombert/jackrabbit-oak,francescomari/jackrabbit-oak,rombert/jackrabbit-oak,davidegiannella/jackrabbit-oak,kwin/jackrabbit-oak,davidegiannella/jackrabbit-oak,davidegiannella/jackrabbit-oak,code-distillery/jackrabbit-oak,joansmith/jackrabbit-oak,ieb/jackrabbit-oak,tripodsan/jackrabbit-oak,chetanmeh/jackrabbit-oak,joansmith/jackrabbit-oak,tripodsan/jackrabbit-oak,kwin/jackrabbit-oak | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.segment.file;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newTreeSet;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Map;
import org.apache.jackrabbit.oak.plugins.segment.SegmentNodeBuilder;
import org.apache.jackrabbit.oak.plugins.segment.SegmentNodeState;
import org.junit.Before;
import org.junit.Test;
public class FileStoreTest {
private File directory;
@Before
public void setUp() throws IOException {
directory = File.createTempFile(
"FileStoreTest", "dir", new File("target"));
directory.delete();
directory.mkdir();
}
@Test
public void testRecovery() throws IOException {
FileStore store = new FileStore(directory, 1, false);
store.flush(); // first 1kB
SegmentNodeState base = store.getHead();
SegmentNodeBuilder builder = base.builder();
builder.setProperty("step", "a");
store.setHead(base, builder.getNodeState());
store.flush(); // second 1kB
base = store.getHead();
builder = base.builder();
builder.setProperty("step", "b");
store.setHead(base, builder.getNodeState());
store.close(); // third 1kB
store = new FileStore(directory, 1, false);
assertEquals("b", store.getHead().getString("step"));
store.close();
RandomAccessFile file = new RandomAccessFile(
new File(directory, "data00000a.tar"), "rw");
file.setLength(2048);
file.close();
store = new FileStore(directory, 1, false);
assertEquals("a", store.getHead().getString("step"));
store.close();
file = new RandomAccessFile(
new File(directory, "data00000a.tar"), "rw");
file.setLength(1024);
file.close();
store = new FileStore(directory, 1, false);
assertFalse(store.getHead().hasProperty("step"));
store.close();
}
@Test
public void testRearrangeOldData() throws IOException {
new FileOutputStream(new File(directory, "data00000.tar")).close();
new FileOutputStream(new File(directory, "data00010a.tar")).close();
new FileOutputStream(new File(directory, "data00030.tar")).close();
new FileOutputStream(new File(directory, "bulk00002.tar")).close();
new FileOutputStream(new File(directory, "bulk00005a.tar")).close();
Map<Integer, ?> files = FileStore.collectFiles(directory);
assertEquals(
newArrayList(0, 1, 31, 32, 33),
newArrayList(newTreeSet(files.keySet())));
assertTrue(new File(directory, "data00000a.tar").isFile());
assertTrue(new File(directory, "data00001a.tar").isFile());
assertTrue(new File(directory, "data00031a.tar").isFile());
assertTrue(new File(directory, "data00032a.tar").isFile());
assertTrue(new File(directory, "data00033a.tar").isFile());
files = FileStore.collectFiles(directory);
assertEquals(
newArrayList(0, 1, 31, 32, 33),
newArrayList(newTreeSet(files.keySet())));
}
}
| oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/segment/file/FileStoreTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.segment.file;
import static com.google.common.collect.Lists.newArrayList;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Map;
import org.apache.jackrabbit.oak.plugins.segment.SegmentNodeBuilder;
import org.apache.jackrabbit.oak.plugins.segment.SegmentNodeState;
import org.junit.Before;
import org.junit.Test;
public class FileStoreTest {
private File directory;
@Before
public void setUp() throws IOException {
directory = File.createTempFile(
"FileStoreTest", "dir", new File("target"));
directory.delete();
directory.mkdir();
}
@Test
public void testRecovery() throws IOException {
FileStore store = new FileStore(directory, 1, false);
store.flush(); // first 1kB
SegmentNodeState base = store.getHead();
SegmentNodeBuilder builder = base.builder();
builder.setProperty("step", "a");
store.setHead(base, builder.getNodeState());
store.flush(); // second 1kB
base = store.getHead();
builder = base.builder();
builder.setProperty("step", "b");
store.setHead(base, builder.getNodeState());
store.close(); // third 1kB
store = new FileStore(directory, 1, false);
assertEquals("b", store.getHead().getString("step"));
store.close();
RandomAccessFile file = new RandomAccessFile(
new File(directory, "data00000a.tar"), "rw");
file.setLength(2048);
file.close();
store = new FileStore(directory, 1, false);
assertEquals("a", store.getHead().getString("step"));
store.close();
file = new RandomAccessFile(
new File(directory, "data00000a.tar"), "rw");
file.setLength(1024);
file.close();
store = new FileStore(directory, 1, false);
assertFalse(store.getHead().hasProperty("step"));
store.close();
}
@Test
public void testRearrangeOldData() throws IOException {
new FileOutputStream(new File(directory, "data00000.tar")).close();
new FileOutputStream(new File(directory, "data00010a.tar")).close();
new FileOutputStream(new File(directory, "data00030.tar")).close();
new FileOutputStream(new File(directory, "bulk00002.tar")).close();
new FileOutputStream(new File(directory, "bulk00005a.tar")).close();
Map<Integer, ?> files = FileStore.collectFiles(directory);
assertEquals(newArrayList(0, 1, 31, 32, 33), newArrayList(files.keySet()));
assertTrue(new File(directory, "data00000a.tar").isFile());
assertTrue(new File(directory, "data00001a.tar").isFile());
assertTrue(new File(directory, "data00031a.tar").isFile());
assertTrue(new File(directory, "data00032a.tar").isFile());
assertTrue(new File(directory, "data00033a.tar").isFile());
files = FileStore.collectFiles(directory);
assertEquals(newArrayList(0, 1, 31, 32, 33), newArrayList(files.keySet()));
}
}
| OAK-631: SegmentMK: Implement garbage collection
The return value of collectFiles is no longer a SortedMap,
use TreeSet to explicitly order the returned list of index numbers
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1584381 13f79535-47bb-0310-9956-ffa450edef68
| oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/segment/file/FileStoreTest.java | OAK-631: SegmentMK: Implement garbage collection |
|
Java | apache-2.0 | fcebdffed6070167be3fec33a452c1cbf4ac85ce | 0 | finmath/finmath-experiments | /*
* (c) Copyright Christian P. Fries, Germany. All rights reserved. Contact: [email protected].
*
* Created on 10.03.2013
*/
package net.finmath.tests.convexityadjustment;
import static org.junit.Assert.assertTrue;
import java.text.DecimalFormat;
import net.finmath.exception.CalculationException;
import net.finmath.functions.AnalyticFormulas;
import net.finmath.marketdata.model.curves.ForwardCurve;
import net.finmath.marketdata.model.curves.ForwardCurveInterface;
import net.finmath.marketdata.products.Swap;
import net.finmath.marketdata.products.SwapAnnuity;
import net.finmath.montecarlo.BrownianMotion;
import net.finmath.montecarlo.interestrate.LIBORMarketModel;
import net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulation;
import net.finmath.montecarlo.interestrate.modelplugins.LIBORCorrelationModelExponentialDecay;
import net.finmath.montecarlo.interestrate.modelplugins.LIBORCovarianceModelFromVolatilityAndCorrelation;
import net.finmath.montecarlo.interestrate.modelplugins.LIBORVolatilityModelTwoParameterExponentialForm;
import net.finmath.montecarlo.interestrate.products.CMSOption;
import net.finmath.montecarlo.interestrate.products.Caplet;
import net.finmath.montecarlo.interestrate.products.Swaption;
import net.finmath.montecarlo.interestrate.products.SwaptionAnalyticApproximation;
import net.finmath.montecarlo.process.ProcessEulerScheme;
import net.finmath.time.TimeDiscretization;
import net.finmath.time.TimeDiscretizationInterface;
import org.junit.Test;
public class CMSOptionTest {
// Model properties
private double initialValue = 0.10;
private double volatility = 0.10;
private int numberOfFactors = 5;
private double correlationDecay = 0.1;
// Process discretization properties
private int numberOfPaths = 10000;
private int numberOfTimeSteps = 15;
private double deltaT = 0.5;
// LIBOR tenor discretization
private int numberOfPeriods = 30;
private double periodLength = 0.5;
// Random number generator seed
private int seed = 3141;
// Java DecimalFormat for our output format
static final DecimalFormat formatterPercent = new DecimalFormat("0.0000%");
/**
* @param args
*/
public static void main(String[] args) {
long startMillis = System.currentTimeMillis();
CMSOptionTest pricingTest = new CMSOptionTest();
try {
pricingTest.runTestCMSOption();
} catch (CalculationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long endMillis = System.currentTimeMillis();
System.out.println("Calculation time: " + (endMillis - startMillis)/1000.0 + " sec");
}
public LIBORModelMonteCarloSimulation getLIBORModelMonteCarloSimulation(ForwardCurveInterface forwardCurve) {
// Create the time discretization
TimeDiscretizationInterface timeDiscretization = new TimeDiscretization(0.0, numberOfTimeSteps, deltaT);
// Create the tenor discretization
TimeDiscretizationInterface tenorDiscretization = new TimeDiscretization(0.0, numberOfPeriods, periodLength);
/*
* Create LIBOR Market Model
*/
LIBORMarketModel liborMarketModel = new LIBORMarketModel(
tenorDiscretization,
forwardCurve,
new LIBORCovarianceModelFromVolatilityAndCorrelation(
timeDiscretization, tenorDiscretization,
new LIBORVolatilityModelTwoParameterExponentialForm(timeDiscretization, tenorDiscretization, volatility, 0.0),
new LIBORCorrelationModelExponentialDecay(timeDiscretization, tenorDiscretization, numberOfFactors, correlationDecay, false))
);
liborMarketModel.setMeasure(LIBORMarketModel.Measure.SPOT);
BrownianMotion brownianMotion = new BrownianMotion(timeDiscretization, numberOfFactors, numberOfPaths, seed);
ProcessEulerScheme process = new ProcessEulerScheme(brownianMotion);
// process.setScheme(ProcessEulerScheme.Scheme.PREDICTOR_CORRECTOR);
LIBORModelMonteCarloSimulation liborMarketModelMonteCarloSimulation = new LIBORModelMonteCarloSimulation(liborMarketModel, process);
return liborMarketModelMonteCarloSimulation;
}
@Test
public void runTestCMSOption() throws CalculationException {
// Create a flaw forward rate curve
ForwardCurveInterface forwardCurve = ForwardCurve.createForwardCurveFromForwards("forwardCurve",
new double[] { 0.0, numberOfPeriods*periodLength },
new double[] { initialValue, initialValue },
periodLength);
// Create a LIBOR market model Monte-Carlo simulation
LIBORModelMonteCarloSimulation liborMarketModelMonteCarloSimulation = this.getLIBORModelMonteCarloSimulation(forwardCurve);
double exerciseDate = 5.0;
double[] fixingDates = {5.0, 5.5, 6.0, 6.5, 7.0, 7.5};
double[] paymentDates = {5.5, 6.0, 6.5, 7.0, 7.5, 8.0};
double[] swapTenor = {5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0};
double[] periodLengths = {0.5, 0.5, 0.5, 0.5, 0.5, 0.5};
double strike = 0.100;
double[] swaprates = new double[periodLengths.length];
java.util.Arrays.fill(swaprates, strike);
/*
* Value the CMS Option
*/
// Calculate approximate swaprate volatility from LIBOR market model (analytic).
SwaptionAnalyticApproximation swaptionAnalytic = new SwaptionAnalyticApproximation(strike, swapTenor, SwaptionAnalyticApproximation.ValueUnit.INTEGRATEDVARIANCE);
double swaprateIntegratedVariance = swaptionAnalytic.getValue(liborMarketModelMonteCarloSimulation);
double swaprateVolatility = Math.sqrt(swaprateIntegratedVariance/exerciseDate);
// Create CMS Option
CMSOption cmsOption = new CMSOption(exerciseDate, fixingDates, paymentDates, periodLengths, strike);
// Value using LMM
double valueCMSOptionLMM = cmsOption.getValue(liborMarketModelMonteCarloSimulation);
System.out.println("CMS Option with LIBOR Market Model..........................:\t" + formatterPercent.format(valueCMSOptionLMM));
// Value using analytics model
double valueCMSOptionHK = cmsOption.getValue(forwardCurve, swaprateVolatility);
System.out.println("CMS Option with Hunt-Kennedy/Black-Scholes..................:\t" + formatterPercent.format(valueCMSOptionHK));
// Value using convexity adjusted forward rate in a Black-Scholes formula
TimeDiscretizationInterface fixTenor = new TimeDiscretization(swapTenor);
TimeDiscretizationInterface floatTenor = new TimeDiscretization(swapTenor);
double rate = Swap.getForwardSwapRate(fixTenor, floatTenor, forwardCurve);
double swapAnnuity = SwapAnnuity.getSwapAnnuity(fixTenor, forwardCurve);
double payoffUnit = SwapAnnuity.getSwapAnnuity(new TimeDiscretization( new double[] { swapTenor[0], swapTenor[1] } ), forwardCurve) / (swapTenor[1]-swapTenor[0]);
double adjustedCMSRate = AnalyticFormulas.huntKennedyCMSAdjustedRate(rate, swaprateVolatility, swapAnnuity, exerciseDate, swapTenor[swapTenor.length-1]-swapTenor[0], payoffUnit);
double valueCMSOptionHKAdjRate = AnalyticFormulas.blackModelSwaptionValue(adjustedCMSRate, swaprateVolatility, exerciseDate, strike, payoffUnit) * (swapTenor[1]-swapTenor[0]);
System.out.println("CMS Option with Black-Scholes using Adjusted Forward Swapate:\t" + formatterPercent.format(valueCMSOptionHKAdjRate));
System.out.println("\nInfo:");
System.out.println("Forward Swaprate............................................:\t" + formatterPercent.format(rate));
System.out.println("Convexity Adjusted Forward Swaprate (Hunt-Kennedy)..........:\t" + formatterPercent.format(adjustedCMSRate));
// Test condition
assertTrue(Math.abs(valueCMSOptionLMM - valueCMSOptionHK) < 1E-3);
/*
* Value a caplet with same fixing date
*/
Caplet caplet = new Caplet(fixingDates[0], periodLengths[0], strike);
double valueCaplet = caplet.getValue(liborMarketModelMonteCarloSimulation);
System.out.println("Caplet with LIBOR Market Model..............................:\t" + formatterPercent.format(valueCaplet));
/*
* Value a swaption with same swap tenor and exercise date
*/
Swaption swaption = new Swaption(exerciseDate, fixingDates, paymentDates, periodLengths, swaprates);
double swaptionNotional = payoffUnit / swapAnnuity * (swapTenor[1]-swapTenor[0]);
double valueSwp = swaption.getValue(liborMarketModelMonteCarloSimulation);
System.out.println("Swaption with LIBOR Market Model............................:\t" + formatterPercent.format(valueSwp * swaptionNotional));
double valueSwaptionAnalytic = swaption.getValue(forwardCurve, swaprateVolatility);
System.out.println("Swaption with Black-Scholes.................................:\t" + formatterPercent.format(valueSwaptionAnalytic * swaptionNotional));
}
}
| src/net/finmath/tests/convexityadjustment/CMSOptionTest.java | /*
* (c) Copyright Christian P. Fries, Germany. All rights reserved. Contact: [email protected].
*
* Created on 10.03.2013
*/
package net.finmath.tests.convexityadjustment;
import static org.junit.Assert.*;
import java.text.DecimalFormat;
import org.junit.Test;
import net.finmath.exception.CalculationException;
import net.finmath.functions.AnalyticFormulas;
import net.finmath.marketdata.model.curves.ForwardCurve;
import net.finmath.marketdata.model.curves.ForwardCurveInterface;
import net.finmath.marketdata.products.Swap;
import net.finmath.marketdata.products.SwapAnnuity;
import net.finmath.montecarlo.BrownianMotion;
import net.finmath.montecarlo.interestrate.LIBORMarketModel;
import net.finmath.montecarlo.interestrate.LIBORMarketModelInterface;
import net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulation;
import net.finmath.montecarlo.interestrate.modelplugins.LIBORCorrelationModelExponentialDecay;
import net.finmath.montecarlo.interestrate.modelplugins.LIBORCovarianceModelFromVolatilityAndCorrelation;
import net.finmath.montecarlo.interestrate.modelplugins.LIBORVolatilityModelTwoParameterExponentialForm;
import net.finmath.montecarlo.interestrate.products.CMSOption;
import net.finmath.montecarlo.interestrate.products.Caplet;
import net.finmath.montecarlo.interestrate.products.Swaption;
import net.finmath.montecarlo.interestrate.products.SwaptionAnalyticApproximation;
import net.finmath.montecarlo.process.ProcessEulerScheme;
import net.finmath.time.TimeDiscretization;
import net.finmath.time.TimeDiscretizationInterface;
public class CMSOptionTest {
// Model properties
private double initialValue = 0.10;
private double volatility = 0.10;
private int numberOfFactors = 5;
private double correlationDecay = 0.1;
// Process discretization properties
private int numberOfPaths = 10000;
private int numberOfTimeSteps = 15;
private double deltaT = 0.5;
// LIBOR tenor discretization
private int numberOfPeriods = 30;
private double periodLength = 0.5;
// Random number generator seed
private int seed = 3141;
// Java DecimalFormat for our output format
static final DecimalFormat formatterPercent = new DecimalFormat("0.0000%");
/**
* @param args
*/
public static void main(String[] args) {
long startMillis = System.currentTimeMillis();
CMSOptionTest pricingTest = new CMSOptionTest();
try {
pricingTest.runTestCMSOption();
} catch (CalculationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long endMillis = System.currentTimeMillis();
System.out.println("Calculation time: " + (endMillis - startMillis)/1000.0 + " sec");
}
public LIBORModelMonteCarloSimulation getLIBORModelMonteCarloSimulation(ForwardCurveInterface forwardCurve) {
// Create the time discretization
TimeDiscretizationInterface timeDiscretization = new TimeDiscretization(0.0, numberOfTimeSteps, deltaT);
// Create the tenor discretization
TimeDiscretizationInterface tenorDiscretization = new TimeDiscretization(0.0, numberOfPeriods, periodLength);
/*
* Create LIBOR Market Model
*/
LIBORMarketModel liborMarketModel = new LIBORMarketModel(
tenorDiscretization,
forwardCurve,
new LIBORCovarianceModelFromVolatilityAndCorrelation(
timeDiscretization, tenorDiscretization,
new LIBORVolatilityModelTwoParameterExponentialForm(timeDiscretization, tenorDiscretization, volatility, 0.0),
new LIBORCorrelationModelExponentialDecay(timeDiscretization, tenorDiscretization, numberOfFactors, correlationDecay, false))
);
liborMarketModel.setMeasure(LIBORMarketModel.Measure.SPOT);
BrownianMotion brownianMotion = new BrownianMotion(timeDiscretization, numberOfFactors, numberOfPaths, seed);
ProcessEulerScheme process = new ProcessEulerScheme(brownianMotion);
// process.setScheme(ProcessEulerScheme.Scheme.PREDICTOR_CORRECTOR);
LIBORModelMonteCarloSimulation liborMarketModelMonteCarloSimulation = new LIBORModelMonteCarloSimulation(liborMarketModel, process);
return liborMarketModelMonteCarloSimulation;
}
@Test
public void runTestCMSOption() throws CalculationException {
// Create a flaw forward rate curve
ForwardCurveInterface forwardCurve = ForwardCurve.createForwardCurveFromForwards("forwardCurve",
new double[] { 0.0, numberOfPeriods*periodLength },
new double[] { initialValue, initialValue },
periodLength);
// Create a LIBOR market model Monte-Carlo simulation
LIBORModelMonteCarloSimulation liborMarketModelMonteCarloSimulation = this.getLIBORModelMonteCarloSimulation(forwardCurve);
double exerciseDate = 5.0;
double[] fixingDates = {5.0, 5.5, 6.0, 6.5, 7.0, 7.5};
double[] paymentDates = {5.5, 6.0, 6.5, 7.0, 7.5, 8.0};
double[] swapTenor = {5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0};
double[] periodLengths = {0.5, 0.5, 0.5, 0.5, 0.5, 0.5};
double strike = 0.100;
double[] swaprates = new double[periodLengths.length];
java.util.Arrays.fill(swaprates, strike);
/*
* Value the CMS Option
*/
// Calculate approximate swaprate volatility from LIBOR market model (analytic).
SwaptionAnalyticApproximation swaptionAnalytic = new SwaptionAnalyticApproximation(strike, swapTenor, SwaptionAnalyticApproximation.ValueUnit.INTEGRATEDVARIANCE);
double swaprateIntegratedVariance = swaptionAnalytic.getValue(liborMarketModelMonteCarloSimulation);
double swaprateVolatility = Math.sqrt(swaprateIntegratedVariance/exerciseDate);
// Create CMS Option
CMSOption cmsOption = new CMSOption(exerciseDate, fixingDates, paymentDates, periodLengths, strike);
// Value using LMM
double valueCMSOptionLMM = cmsOption.getValue(liborMarketModelMonteCarloSimulation);
System.out.println("CMS Option with LIBOR Market Model..........................:\t" + formatterPercent.format(valueCMSOptionLMM));
// Value using analytics model
double valueCMSOptionHK = cmsOption.getValue(forwardCurve, swaprateVolatility);
System.out.println("CMS Option with Hunt-Kennedy/Black-Scholes..................:\t" + formatterPercent.format(valueCMSOptionHK));
// Value using convexity adjusted forward rate in a Black-Scholes formula
TimeDiscretizationInterface fixTenor = new TimeDiscretization(swapTenor);
TimeDiscretizationInterface floatTenor = new TimeDiscretization(swapTenor);
double rate = Swap.getForwardSwapRate(fixTenor, floatTenor, forwardCurve);
double swapAnnuity = SwapAnnuity.getSwapAnnuity(fixTenor, forwardCurve);
double payoffUnit = SwapAnnuity.getSwapAnnuity(new TimeDiscretization( new double[] { swapTenor[0], swapTenor[1] } ), forwardCurve) / (swapTenor[1]-swapTenor[0]);
double adjustedCMSRate = AnalyticFormulas.huntKennedyCMSAdjustedRate(rate, swaprateVolatility, swapAnnuity, exerciseDate, swapTenor[swapTenor.length-1]-swapTenor[0], payoffUnit);
double valueCMSOptionHKAdjRate = AnalyticFormulas.blackModelSwaptionValue(adjustedCMSRate, swaprateVolatility, exerciseDate, strike, payoffUnit) * (swapTenor[1]-swapTenor[0]);
System.out.println("CMS Option with Black-Scholes using Adjusted Forward Swapate:\t" + formatterPercent.format(valueCMSOptionHKAdjRate));
System.out.println("\nInfo:");
System.out.println("Forward Swaprate............................................:\t" + formatterPercent.format(rate));
System.out.println("Convexity Adjusted Forward Swaprate (Hunt-Kennedy)..........:\t" + formatterPercent.format(adjustedCMSRate));
// Test condition
assertTrue(Math.abs(valueCMSOptionLMM - valueCMSOptionHK) < 1E-3);
/*
* Value a caplet with same fixing date
*/
Caplet caplet = new Caplet(fixingDates[0], periodLengths[0], strike);
double valueCaplet = caplet.getValue(liborMarketModelMonteCarloSimulation);
System.out.println("Caplet with LIBOR Market Model..............................:\t" + formatterPercent.format(valueCaplet));
/*
* Value a swaption with same swap tenor and exercise date
*/
Swaption swaption = new Swaption(exerciseDate, fixingDates, paymentDates, periodLengths, swaprates);
double swaptionNotional = payoffUnit / swapAnnuity * (swapTenor[1]-swapTenor[0]);
double valueSwp = swaption.getValue(liborMarketModelMonteCarloSimulation);
System.out.println("Swaption with LIBOR Market Model............................:\t" + formatterPercent.format(valueSwp * swaptionNotional));
double valueSwaptionAnalytic = swaption.getValue(forwardCurve, swaprateVolatility);
System.out.println("Swaption with Black-Scholes.................................:\t" + formatterPercent.format(valueSwaptionAnalytic * swaptionNotional));
}
}
| Code cleanup.
git-svn-id: a9d4857bbcd0eec574f75730dc3d02feb83aff94@342 48fcbb9e-5639-0410-8b25-842128a4905d
| src/net/finmath/tests/convexityadjustment/CMSOptionTest.java | Code cleanup. |
|
Java | apache-2.0 | 090947e6ad8e6ec03ec2c2a45df42858cc3b2dfa | 0 | nguyentruongtho/buck,romanoid/buck,nguyentruongtho/buck,facebook/buck,brettwooldridge/buck,rmaz/buck,brettwooldridge/buck,romanoid/buck,clonetwin26/buck,Addepar/buck,rmaz/buck,JoelMarcey/buck,ilya-klyuchnikov/buck,Addepar/buck,zpao/buck,SeleniumHQ/buck,LegNeato/buck,zpao/buck,rmaz/buck,brettwooldridge/buck,kageiit/buck,brettwooldridge/buck,rmaz/buck,LegNeato/buck,clonetwin26/buck,ilya-klyuchnikov/buck,shs96c/buck,clonetwin26/buck,romanoid/buck,brettwooldridge/buck,rmaz/buck,ilya-klyuchnikov/buck,rmaz/buck,SeleniumHQ/buck,clonetwin26/buck,SeleniumHQ/buck,zpao/buck,romanoid/buck,romanoid/buck,facebook/buck,SeleniumHQ/buck,JoelMarcey/buck,ilya-klyuchnikov/buck,JoelMarcey/buck,clonetwin26/buck,shs96c/buck,nguyentruongtho/buck,LegNeato/buck,brettwooldridge/buck,kageiit/buck,ilya-klyuchnikov/buck,Addepar/buck,clonetwin26/buck,ilya-klyuchnikov/buck,kageiit/buck,ilya-klyuchnikov/buck,kageiit/buck,clonetwin26/buck,facebook/buck,nguyentruongtho/buck,ilya-klyuchnikov/buck,JoelMarcey/buck,SeleniumHQ/buck,SeleniumHQ/buck,clonetwin26/buck,nguyentruongtho/buck,shs96c/buck,kageiit/buck,clonetwin26/buck,JoelMarcey/buck,romanoid/buck,shs96c/buck,shs96c/buck,SeleniumHQ/buck,brettwooldridge/buck,rmaz/buck,zpao/buck,romanoid/buck,nguyentruongtho/buck,ilya-klyuchnikov/buck,JoelMarcey/buck,shs96c/buck,shs96c/buck,brettwooldridge/buck,kageiit/buck,brettwooldridge/buck,shs96c/buck,JoelMarcey/buck,shs96c/buck,LegNeato/buck,clonetwin26/buck,LegNeato/buck,Addepar/buck,brettwooldridge/buck,LegNeato/buck,LegNeato/buck,facebook/buck,ilya-klyuchnikov/buck,rmaz/buck,SeleniumHQ/buck,ilya-klyuchnikov/buck,clonetwin26/buck,Addepar/buck,ilya-klyuchnikov/buck,brettwooldridge/buck,SeleniumHQ/buck,brettwooldridge/buck,Addepar/buck,zpao/buck,facebook/buck,JoelMarcey/buck,kageiit/buck,shs96c/buck,romanoid/buck,rmaz/buck,clonetwin26/buck,SeleniumHQ/buck,LegNeato/buck,romanoid/buck,romanoid/buck,shs96c/buck,JoelMarcey/buck,zpao/buck,facebook/buck,LegNeato/buck,clonetwin26/buck,Addepar/buck,LegNeato/buck,rmaz/buck,romanoid/buck,JoelMarcey/buck,shs96c/buck,facebook/buck,Addepar/buck,JoelMarcey/buck,LegNeato/buck,JoelMarcey/buck,romanoid/buck,nguyentruongtho/buck,Addepar/buck,JoelMarcey/buck,Addepar/buck,romanoid/buck,Addepar/buck,rmaz/buck,LegNeato/buck,SeleniumHQ/buck,Addepar/buck,SeleniumHQ/buck,brettwooldridge/buck,rmaz/buck,rmaz/buck,ilya-klyuchnikov/buck,shs96c/buck,LegNeato/buck,Addepar/buck,zpao/buck,SeleniumHQ/buck | /*
* Copyright 2012-present Facebook, Inc.
*
* 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.facebook.buck.cli;
import static com.facebook.buck.distributed.ClientStatsTracker.DistBuildClientStat.LOCAL_FILE_HASH_COMPUTATION;
import static com.facebook.buck.distributed.ClientStatsTracker.DistBuildClientStat.LOCAL_GRAPH_CONSTRUCTION;
import static com.facebook.buck.distributed.ClientStatsTracker.DistBuildClientStat.LOCAL_PREPARATION;
import static com.facebook.buck.distributed.ClientStatsTracker.DistBuildClientStat.PERFORM_LOCAL_BUILD;
import static com.facebook.buck.distributed.ClientStatsTracker.DistBuildClientStat.POST_BUILD_ANALYSIS;
import static com.facebook.buck.distributed.ClientStatsTracker.DistBuildClientStat.POST_DISTRIBUTED_BUILD_LOCAL_STEPS;
import static com.facebook.buck.util.concurrent.MostExecutors.newMultiThreadExecutor;
import com.facebook.buck.artifact_cache.config.ArtifactCacheBuckConfig;
import com.facebook.buck.cli.output.Mode;
import com.facebook.buck.command.Build;
import com.facebook.buck.command.LocalBuildExecutor;
import com.facebook.buck.command.LocalBuildExecutorInvoker;
import com.facebook.buck.config.BuckConfig;
import com.facebook.buck.distributed.AnalysisResults;
import com.facebook.buck.distributed.BuckVersionUtil;
import com.facebook.buck.distributed.BuildJobStateSerializer;
import com.facebook.buck.distributed.ClientStatsTracker;
import com.facebook.buck.distributed.DistBuildCellIndexer;
import com.facebook.buck.distributed.DistBuildClientStatsEvent;
import com.facebook.buck.distributed.DistBuildConfig;
import com.facebook.buck.distributed.DistBuildFileHashes;
import com.facebook.buck.distributed.DistBuildPostBuildAnalysis;
import com.facebook.buck.distributed.DistBuildService;
import com.facebook.buck.distributed.DistBuildState;
import com.facebook.buck.distributed.DistBuildTargetGraphCodec;
import com.facebook.buck.distributed.RuleKeyNameAndType;
import com.facebook.buck.distributed.build_client.DistBuildControllerArgs;
import com.facebook.buck.distributed.build_client.DistBuildControllerInvocationArgs;
import com.facebook.buck.distributed.build_client.LogStateTracker;
import com.facebook.buck.distributed.build_client.StampedeBuildClient;
import com.facebook.buck.distributed.thrift.BuckVersion;
import com.facebook.buck.distributed.thrift.BuildJobState;
import com.facebook.buck.distributed.thrift.BuildJobStateFileHashEntry;
import com.facebook.buck.distributed.thrift.BuildJobStateFileHashes;
import com.facebook.buck.distributed.thrift.BuildMode;
import com.facebook.buck.distributed.thrift.RuleKeyLogEntry;
import com.facebook.buck.distributed.thrift.StampedeId;
import com.facebook.buck.event.BuckEventListener;
import com.facebook.buck.event.ConsoleEvent;
import com.facebook.buck.event.listener.DistBuildClientEventListener;
import com.facebook.buck.io.file.MoreFiles;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.log.CommandThreadFactory;
import com.facebook.buck.log.Logger;
import com.facebook.buck.log.thrift.ThriftRuleKeyLogger;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.parser.BuildTargetParser;
import com.facebook.buck.parser.BuildTargetPatternParser;
import com.facebook.buck.parser.DefaultParserTargetNodeFactory;
import com.facebook.buck.parser.ParserConfig;
import com.facebook.buck.parser.ParserTargetNodeFactory;
import com.facebook.buck.parser.exceptions.BuildFileParseException;
import com.facebook.buck.parser.exceptions.BuildTargetException;
import com.facebook.buck.rules.ActionAndTargetGraphs;
import com.facebook.buck.rules.ActionGraphAndResolver;
import com.facebook.buck.rules.BuildEvent;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.CachingBuildEngine;
import com.facebook.buck.rules.DefaultSourcePathResolver;
import com.facebook.buck.rules.LocalCachingBuildEngineDelegate;
import com.facebook.buck.rules.NoOpRemoteBuildRuleCompletionWaiter;
import com.facebook.buck.rules.ParallelRuleKeyCalculator;
import com.facebook.buck.rules.RemoteBuildRuleCompletionWaiter;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.TargetGraphAndBuildTargets;
import com.facebook.buck.rules.TargetNode;
import com.facebook.buck.rules.TargetNodeFactory;
import com.facebook.buck.rules.coercer.ConstructorArgMarshaller;
import com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory;
import com.facebook.buck.rules.coercer.PathTypeCoercer;
import com.facebook.buck.rules.coercer.TypeCoercerFactory;
import com.facebook.buck.rules.keys.DefaultRuleKeyFactory;
import com.facebook.buck.rules.keys.RuleKeyCacheRecycler;
import com.facebook.buck.rules.keys.RuleKeyCacheScope;
import com.facebook.buck.rules.keys.RuleKeyFieldLoader;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.ExecutorPool;
import com.facebook.buck.util.CloseableMemoizedSupplier;
import com.facebook.buck.util.CommandLineException;
import com.facebook.buck.util.ExitCode;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.ListeningProcessExecutor;
import com.facebook.buck.util.MoreExceptions;
import com.facebook.buck.util.ObjectMappers;
import com.facebook.buck.util.cache.FileHashCache;
import com.facebook.buck.util.concurrent.MostExecutors;
import com.facebook.buck.util.concurrent.WeightedListeningExecutorService;
import com.facebook.buck.versions.VersionException;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
public class BuildCommand extends AbstractCommand {
private static final Logger LOG = Logger.get(BuildCommand.class);
private static final String KEEP_GOING_LONG_ARG = "--keep-going";
private static final String BUILD_REPORT_LONG_ARG = "--build-report";
private static final String JUST_BUILD_LONG_ARG = "--just-build";
private static final String DEEP_LONG_ARG = "--deep";
private static final String OUT_LONG_ARG = "--out";
private static final String POPULATE_CACHE_LONG_ARG = "--populate-cache";
private static final String SHALLOW_LONG_ARG = "--shallow";
private static final String REPORT_ABSOLUTE_PATHS = "--report-absolute-paths";
private static final String SHOW_OUTPUT_LONG_ARG = "--show-output";
private static final String SHOW_FULL_OUTPUT_LONG_ARG = "--show-full-output";
private static final String SHOW_JSON_OUTPUT_LONG_ARG = "--show-json-output";
private static final String SHOW_FULL_JSON_OUTPUT_LONG_ARG = "--show-full-json-output";
private static final String SHOW_RULEKEY_LONG_ARG = "--show-rulekey";
private static final String DISTRIBUTED_LONG_ARG = "--distributed";
private static final String BUCK_BINARY_STRING_ARG = "--buck-binary";
private static final String RULEKEY_LOG_PATH_LONG_ARG = "--rulekeys-log-path";
private static final String BUCK_GIT_COMMIT_KEY = "buck.git_commit";
private static final int STAMPEDE_EXECUTOR_SHUTDOWN_TIMEOUT_MILLIS = 100;
@Option(name = KEEP_GOING_LONG_ARG, usage = "Keep going when some targets can't be made.")
private boolean keepGoing = false;
@Option(name = BUILD_REPORT_LONG_ARG, usage = "File where build report will be written.")
@Nullable
private Path buildReport = null;
@Nullable
@Option(
name = JUST_BUILD_LONG_ARG,
usage = "For debugging, limits the build to a specific target in the action graph.",
hidden = true
)
private String justBuildTarget = null;
@Option(
name = DEEP_LONG_ARG,
usage =
"Perform a \"deep\" build, which makes the output of all transitive dependencies"
+ " available.",
forbids = SHALLOW_LONG_ARG
)
private boolean deepBuild = false;
@Option(
name = POPULATE_CACHE_LONG_ARG,
usage =
"Performs a cache population, which makes the output of all unchanged "
+ "transitive dependencies available (if these outputs are available "
+ "in the remote cache). Does not build changed or unavailable dependencies locally.",
forbids = {SHALLOW_LONG_ARG, DEEP_LONG_ARG}
)
private boolean populateCacheOnly = false;
@Option(
name = SHALLOW_LONG_ARG,
usage =
"Perform a \"shallow\" build, which only makes the output of all explicitly listed"
+ " targets available.",
forbids = DEEP_LONG_ARG
)
private boolean shallowBuild = false;
@Option(
name = REPORT_ABSOLUTE_PATHS,
usage = "Reports errors using absolute paths to the source files instead of relative paths."
)
private boolean shouldReportAbsolutePaths = false;
@Option(
name = SHOW_OUTPUT_LONG_ARG,
usage = "Print the path to the output for each of the built rules relative to the cell."
)
private boolean showOutput;
@Option(name = OUT_LONG_ARG, usage = "Copies the output of the lone build target to this path.")
@Nullable
private Path outputPathForSingleBuildTarget;
@Option(
name = SHOW_FULL_OUTPUT_LONG_ARG,
usage = "Print the absolute path to the output for each of the built rules."
)
private boolean showFullOutput;
@Option(name = SHOW_JSON_OUTPUT_LONG_ARG, usage = "Show output in JSON format.")
private boolean showJsonOutput;
@Option(name = SHOW_FULL_JSON_OUTPUT_LONG_ARG, usage = "Show full output in JSON format.")
private boolean showFullJsonOutput;
@Option(name = SHOW_RULEKEY_LONG_ARG, usage = "Print the rulekey for each of the built rules.")
private boolean showRuleKey;
@Option(
name = DISTRIBUTED_LONG_ARG,
usage = "Whether to run in distributed build mode. (experimental)",
hidden = true
)
private boolean useDistributedBuild = false;
@Nullable
@Option(
name = DistBuildRunCommand.BUILD_STATE_FILE_ARG_NAME,
usage = DistBuildRunCommand.BUILD_STATE_FILE_ARG_USAGE,
hidden = true
)
private String distributedBuildStateFile = null;
@Nullable
@Option(
name = BUCK_BINARY_STRING_ARG,
usage = "Buck binary to use on a distributed build instead of the current git version.",
hidden = true
)
private String buckBinary = null;
@Nullable
@Option(
name = RULEKEY_LOG_PATH_LONG_ARG,
usage = "If set, log a binary representation of rulekeys to this file."
)
private String ruleKeyLogPath = null;
@Argument private List<String> arguments = new ArrayList<>();
private boolean buildTargetsHaveBeenCalculated;
@Nullable private DistBuildClientEventListener distBuildClientEventListener;
public List<String> getArguments() {
return arguments;
}
public boolean isCodeCoverageEnabled() {
return false;
}
public boolean isDebugEnabled() {
return false;
}
protected Mode getOutputMode() {
if (this.showFullOutput) {
return Mode.FULL;
} else if (this.showOutput) {
return Mode.SIMPLE;
} else {
return Mode.NONE;
}
}
public BuildCommand() {
this(ImmutableList.of());
}
public BuildCommand(List<String> arguments) {
this.arguments.addAll(arguments);
}
public Optional<CachingBuildEngine.BuildMode> getBuildEngineMode() {
Optional<CachingBuildEngine.BuildMode> mode = Optional.empty();
if (deepBuild) {
mode = Optional.of(CachingBuildEngine.BuildMode.DEEP);
}
if (populateCacheOnly) {
mode = Optional.of(CachingBuildEngine.BuildMode.POPULATE_FROM_REMOTE_CACHE);
}
if (shallowBuild) {
mode = Optional.of(CachingBuildEngine.BuildMode.SHALLOW);
}
return mode;
}
public boolean isKeepGoing() {
return keepGoing;
}
protected boolean shouldReportAbsolutePaths() {
return shouldReportAbsolutePaths;
}
public void setKeepGoing(boolean keepGoing) {
this.keepGoing = keepGoing;
}
public boolean isUseDistributedBuild() {
return useDistributedBuild;
}
public void setUseDistributedBuild(boolean useDistributedBuild) {
this.useDistributedBuild = useDistributedBuild;
}
/** @return an absolute path or {@link Optional#empty()}. */
public Optional<Path> getPathToBuildReport(BuckConfig buckConfig) {
return Optional.ofNullable(
buckConfig.resolvePathThatMayBeOutsideTheProjectFilesystem(buildReport));
}
private final AtomicReference<Build> lastBuild = new AtomicReference<>(null);
private final SettableFuture<ParallelRuleKeyCalculator<RuleKey>> localRuleKeyCalculator =
SettableFuture.create();
private ImmutableSet<BuildTarget> buildTargets = ImmutableSet.of();
/**
* Create the serializable {@link BuildJobState} for distributed builds.
*
* @param buildTargets - Top level targets.
* @param params - Client side parameters.
* @param executor - Executor for async ops.
* @param poolSupplier - the supplier of an executor for parallel action graph construction
* @return - New instance of serializable {@link BuildJobState}.
* @throws InterruptedException
* @throws IOException
*/
public static ListenableFuture<BuildJobState> getAsyncDistBuildState(
List<String> buildTargets,
CommandRunnerParams params,
WeightedListeningExecutorService executor,
CloseableMemoizedSupplier<ForkJoinPool, RuntimeException> poolSupplier)
throws InterruptedException, IOException {
BuildCommand buildCommand = new BuildCommand(buildTargets);
buildCommand.assertArguments(params);
ActionAndTargetGraphs graphs = null;
try {
graphs = buildCommand.createGraphs(params, executor, Optional.empty(), poolSupplier);
} catch (ActionGraphCreationException e) {
throw BuildFileParseException.createForUnknownParseError(e.getMessage());
}
return buildCommand.computeDistBuildState(params, graphs, executor, Optional.empty())
.asyncJobState;
}
@Override
public ExitCode runWithoutHelp(CommandRunnerParams params)
throws IOException, InterruptedException {
assertArguments(params);
ListeningProcessExecutor processExecutor = new ListeningProcessExecutor();
try (CommandThreadManager pool =
new CommandThreadManager("Build", getConcurrencyLimit(params.getBuckConfig()));
BuildPrehook prehook =
new BuildPrehook(
processExecutor,
params.getCell(),
params.getBuckEventBus(),
params.getBuckConfig(),
params.getEnvironment()); ) {
prehook.startPrehookScript();
return run(params, pool, ImmutableSet.of());
}
}
/** @throw CommandLineException if arguments provided are incorrect */
protected void assertArguments(CommandRunnerParams params) {
if (!getArguments().isEmpty()) {
return;
}
String message = "Must specify at least one build target.";
ImmutableSet<String> aliases = params.getBuckConfig().getAliases().keySet();
if (!aliases.isEmpty()) {
// If there are aliases defined in .buckconfig, suggest that the user
// build one of them. We show the user only the first 10 aliases.
message +=
String.format(
"%nTry building one of the following targets:%n%s",
Joiner.on(' ').join(Iterators.limit(aliases.iterator(), 10)));
}
throw new CommandLineException(message);
}
protected ExitCode run(
CommandRunnerParams params,
CommandThreadManager commandThreadManager,
ImmutableSet<String> additionalTargets)
throws IOException, InterruptedException {
if (!additionalTargets.isEmpty()) {
this.arguments.addAll(additionalTargets);
}
BuildEvent.Started started = postBuildStartedEvent(params);
ExitCode exitCode = ExitCode.SUCCESS;
try (CloseableMemoizedSupplier<ForkJoinPool, RuntimeException> poolSupplier =
getForkJoinPoolSupplier(params.getBuckConfig())) {
exitCode = executeBuildAndProcessResult(params, commandThreadManager, poolSupplier);
} catch (ActionGraphCreationException e) {
params.getConsole().printBuildFailure(e.getMessage());
exitCode = ExitCode.PARSE_ERROR;
} finally {
params.getBuckEventBus().post(BuildEvent.finished(started, exitCode));
}
return exitCode;
}
private BuildEvent.Started postBuildStartedEvent(CommandRunnerParams params) {
// Post the build started event, setting it to the Parser recorded start time if appropriate.
BuildEvent.Started started = BuildEvent.started(getArguments());
if (params.getParser().getParseStartTime().isPresent()) {
params.getBuckEventBus().post(started, params.getParser().getParseStartTime().get());
} else {
params.getBuckEventBus().post(started);
}
return started;
}
private ActionAndTargetGraphs createGraphs(
CommandRunnerParams params,
ListeningExecutorService executorService,
Optional<ThriftRuleKeyLogger> ruleKeyLogger,
CloseableMemoizedSupplier<ForkJoinPool, RuntimeException> poolSupplier)
throws ActionGraphCreationException, IOException, InterruptedException {
TargetGraphAndBuildTargets unversionedTargetGraph =
createUnversionedTargetGraph(params, executorService);
Optional<TargetGraphAndBuildTargets> versionedTargetGraph = Optional.empty();
try {
if (params.getBuckConfig().getBuildVersions()) {
versionedTargetGraph = Optional.of(toVersionedTargetGraph(params, unversionedTargetGraph));
}
} catch (VersionException e) {
throw new ActionGraphCreationException(MoreExceptions.getHumanReadableOrLocalizedMessage(e));
}
TargetGraphAndBuildTargets targetGraphForLocalBuild =
ActionAndTargetGraphs.getTargetGraphForLocalBuild(
unversionedTargetGraph, versionedTargetGraph);
checkSingleBuildTargetSpecifiedForOutBuildMode(targetGraphForLocalBuild);
ActionGraphAndResolver actionGraph =
createActionGraphAndResolver(params, targetGraphForLocalBuild, ruleKeyLogger, poolSupplier);
return ActionAndTargetGraphs.builder()
.setUnversionedTargetGraph(unversionedTargetGraph)
.setVersionedTargetGraph(versionedTargetGraph)
.setActionGraphAndResolver(actionGraph)
.build();
}
private void checkSingleBuildTargetSpecifiedForOutBuildMode(
TargetGraphAndBuildTargets targetGraphAndBuildTargets) throws ActionGraphCreationException {
// Ideally, we would error out of this before we build the entire graph, but it is possible
// that `getArguments().size()` is 1 but `targetGraphAndBuildTargets.getBuildTargets().size()`
// is greater than 1 if the lone argument is a wildcard build target that ends in "...".
// As such, we have to get the result of createTargetGraph() before we can do this check.
if (outputPathForSingleBuildTarget != null
&& targetGraphAndBuildTargets.getBuildTargets().size() != 1) {
throw new CommandLineException(
String.format(
"When using %s you must specify exactly one build target, but you specified %s",
OUT_LONG_ARG, targetGraphAndBuildTargets.getBuildTargets()));
}
}
private ExitCode executeBuildAndProcessResult(
CommandRunnerParams params,
CommandThreadManager commandThreadManager,
CloseableMemoizedSupplier<ForkJoinPool, RuntimeException> poolSupplier)
throws IOException, InterruptedException, ActionGraphCreationException {
ExitCode exitCode = ExitCode.SUCCESS;
final ActionAndTargetGraphs graphs;
if (useDistributedBuild) {
DistBuildConfig distBuildConfig = new DistBuildConfig(params.getBuckConfig());
ClientStatsTracker distBuildClientStatsTracker =
new ClientStatsTracker(distBuildConfig.getBuildLabel());
distBuildClientStatsTracker.startTimer(LOCAL_PREPARATION);
distBuildClientStatsTracker.startTimer(LOCAL_GRAPH_CONSTRUCTION);
graphs =
createGraphs(
params,
commandThreadManager.getListeningExecutorService(),
Optional.empty(),
poolSupplier);
distBuildClientStatsTracker.stopTimer(LOCAL_GRAPH_CONSTRUCTION);
try (RuleKeyCacheScope<RuleKey> ruleKeyCacheScope =
getDefaultRuleKeyCacheScope(params, graphs.getActionGraphAndResolver())) {
try {
exitCode =
executeDistBuild(
params,
distBuildConfig,
graphs,
commandThreadManager.getWeightedListeningExecutorService(),
params.getCell().getFilesystem(),
params.getFileHashCache(),
distBuildClientStatsTracker,
ruleKeyCacheScope);
} catch (Throwable ex) {
String stackTrace = Throwables.getStackTraceAsString(ex);
distBuildClientStatsTracker.setBuckClientErrorMessage(ex.toString() + "\n" + stackTrace);
distBuildClientStatsTracker.setBuckClientError(true);
throw ex;
} finally {
if (distBuildClientStatsTracker.hasStampedeId()) {
params
.getBuckEventBus()
.post(new DistBuildClientStatsEvent(distBuildClientStatsTracker.generateStats()));
} else {
LOG.error(
"Failed to published DistBuildClientStatsEvent as no Stampede ID was received");
}
}
if (exitCode == ExitCode.SUCCESS) {
exitCode = processSuccessfulBuild(params, graphs, ruleKeyCacheScope);
}
}
} else {
try (ThriftRuleKeyLogger ruleKeyLogger = createRuleKeyLogger().orElse(null)) {
Optional<ThriftRuleKeyLogger> optionalRuleKeyLogger = Optional.ofNullable(ruleKeyLogger);
graphs =
createGraphs(
params,
commandThreadManager.getListeningExecutorService(),
optionalRuleKeyLogger,
poolSupplier);
try (RuleKeyCacheScope<RuleKey> ruleKeyCacheScope =
getDefaultRuleKeyCacheScope(params, graphs.getActionGraphAndResolver())) {
exitCode =
executeLocalBuild(
params,
graphs.getActionGraphAndResolver(),
commandThreadManager.getWeightedListeningExecutorService(),
optionalRuleKeyLogger,
new NoOpRemoteBuildRuleCompletionWaiter(),
false,
Optional.empty(),
ruleKeyCacheScope,
lastBuild);
if (exitCode == ExitCode.SUCCESS) {
exitCode = processSuccessfulBuild(params, graphs, ruleKeyCacheScope);
}
}
}
}
return exitCode;
}
/**
* Create a {@link ThriftRuleKeyLogger} depending on whether {@link BuildCommand#ruleKeyLogPath}
* is set or not
*/
private Optional<ThriftRuleKeyLogger> createRuleKeyLogger() throws IOException {
if (ruleKeyLogPath == null) {
return Optional.empty();
} else {
return Optional.of(ThriftRuleKeyLogger.create(Paths.get(ruleKeyLogPath)));
}
}
private ExitCode processSuccessfulBuild(
CommandRunnerParams params,
ActionAndTargetGraphs graphs,
RuleKeyCacheScope<RuleKey> ruleKeyCacheScope)
throws IOException {
if (params.getBuckConfig().createBuildOutputSymLinksEnabled()) {
symLinkBuildResults(params, graphs.getActionGraphAndResolver());
}
if (showOutput || showFullOutput || showJsonOutput || showFullJsonOutput || showRuleKey) {
showOutputs(params, graphs.getActionGraphAndResolver(), ruleKeyCacheScope);
}
if (outputPathForSingleBuildTarget != null) {
BuildTarget loneTarget =
Iterables.getOnlyElement(graphs.getTargetGraphForLocalBuild().getBuildTargets());
BuildRule rule = graphs.getActionGraphAndResolver().getResolver().getRule(loneTarget);
if (!rule.outputFileCanBeCopied()) {
params
.getConsole()
.printErrorText(
String.format(
"%s does not have an output that is compatible with `buck build --out`",
loneTarget));
return ExitCode.BUILD_ERROR;
} else {
SourcePath output =
Preconditions.checkNotNull(
rule.getSourcePathToOutput(),
"%s specified a build target that does not have an output file: %s",
OUT_LONG_ARG,
loneTarget);
ProjectFilesystem projectFilesystem = rule.getProjectFilesystem();
SourcePathResolver pathResolver =
DefaultSourcePathResolver.from(
new SourcePathRuleFinder(graphs.getActionGraphAndResolver().getResolver()));
projectFilesystem.copyFile(
pathResolver.getAbsolutePath(output), outputPathForSingleBuildTarget);
}
}
return ExitCode.SUCCESS;
}
private void symLinkBuildResults(
CommandRunnerParams params, ActionGraphAndResolver actionGraphAndResolver)
throws IOException {
// Clean up last buck-out/last.
Path lastOutputDirPath =
params.getCell().getFilesystem().getBuckPaths().getLastOutputDir().toAbsolutePath();
MoreFiles.deleteRecursivelyIfExists(lastOutputDirPath);
Files.createDirectories(lastOutputDirPath);
SourcePathRuleFinder ruleFinder =
new SourcePathRuleFinder(actionGraphAndResolver.getResolver());
SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
for (BuildTarget buildTarget : buildTargets) {
BuildRule rule = actionGraphAndResolver.getResolver().requireRule(buildTarget);
Optional<Path> outputPath =
TargetsCommand.getUserFacingOutputPath(
pathResolver, rule, params.getBuckConfig().getBuckOutCompatLink());
if (outputPath.isPresent()) {
Path absolutePath = outputPath.get();
Path destPath = lastOutputDirPath.relativize(absolutePath);
Path linkPath = lastOutputDirPath.resolve(absolutePath.getFileName());
// Don't overwrite existing symlink in case there are duplicate names.
if (!Files.exists(linkPath)) {
Files.createSymbolicLink(linkPath, destPath);
}
}
}
}
private AsyncJobStateAndCells computeDistBuildState(
final CommandRunnerParams params,
ActionAndTargetGraphs graphs,
final ListeningExecutorService executorService,
Optional<ClientStatsTracker> clientStatsTracker)
throws IOException, InterruptedException {
DistBuildCellIndexer cellIndexer = new DistBuildCellIndexer(params.getCell());
// Compute the file hashes.
ActionGraphAndResolver actionGraphAndResolver = graphs.getActionGraphAndResolver();
SourcePathRuleFinder ruleFinder =
new SourcePathRuleFinder(actionGraphAndResolver.getResolver());
SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
clientStatsTracker.ifPresent(tracker -> tracker.startTimer(LOCAL_FILE_HASH_COMPUTATION));
DistBuildFileHashes distributedBuildFileHashes =
new DistBuildFileHashes(
actionGraphAndResolver.getActionGraph(),
pathResolver,
ruleFinder,
params.getFileHashCache(),
cellIndexer,
executorService,
params.getRuleKeyConfiguration(),
params.getCell());
distributedBuildFileHashes
.getFileHashesComputationFuture()
.addListener(
() ->
clientStatsTracker.ifPresent(
tracker -> tracker.stopTimer(LOCAL_FILE_HASH_COMPUTATION)),
executorService);
// Distributed builds serialize and send the unversioned target graph,
// and then deserialize and version remotely.
TargetGraphAndBuildTargets targetGraphAndBuildTargets =
graphs.getTargetGraphForDistributedBuild();
TypeCoercerFactory typeCoercerFactory =
new DefaultTypeCoercerFactory(PathTypeCoercer.PathExistenceVerificationMode.DO_NOT_VERIFY);
ParserTargetNodeFactory<TargetNode<?, ?>> parserTargetNodeFactory =
DefaultParserTargetNodeFactory.createForDistributedBuild(
new ConstructorArgMarshaller(typeCoercerFactory),
new TargetNodeFactory(typeCoercerFactory),
params.getRuleKeyConfiguration());
DistBuildTargetGraphCodec targetGraphCodec =
new DistBuildTargetGraphCodec(
parserTargetNodeFactory,
input -> {
return params
.getParser()
.getRawTargetNode(
params.getBuckEventBus(),
params.getCell().getCell(input.getBuildTarget()),
false /* enableProfiling */,
executorService,
input);
},
targetGraphAndBuildTargets
.getBuildTargets()
.stream()
.map(t -> t.getFullyQualifiedName())
.collect(Collectors.toSet()));
return new AsyncJobStateAndCells(
distributedBuildFileHashes,
executorService.submit(
() -> {
try {
BuildJobState state =
DistBuildState.dump(
cellIndexer,
distributedBuildFileHashes,
targetGraphCodec,
targetGraphAndBuildTargets.getTargetGraph(),
buildTargets,
clientStatsTracker);
LOG.info("Finished computing serializable distributed build state.");
return state;
} catch (InterruptedException ex) {
LOG.warn(
ex,
"Failed computing serializable distributed build state as interrupted. Local build probably finished first.");
Thread.currentThread().interrupt();
throw ex;
}
}),
cellIndexer);
}
private ListeningExecutorService createStampedeControllerExecutorService(int maxThreads) {
CommandThreadFactory stampedeCommandThreadFactory =
new CommandThreadFactory("StampedeController");
return MoreExecutors.listeningDecorator(
newMultiThreadExecutor(stampedeCommandThreadFactory, maxThreads));
}
private ListeningExecutorService createStampedeLocalBuildExecutorService() {
CommandThreadFactory stampedeCommandThreadFactory =
new CommandThreadFactory("StampedeLocalBuild");
return MoreExecutors.listeningDecorator(
MostExecutors.newSingleThreadExecutor(stampedeCommandThreadFactory));
}
private ExitCode executeDistBuild(
CommandRunnerParams params,
DistBuildConfig distBuildConfig,
ActionAndTargetGraphs graphs,
WeightedListeningExecutorService executorService,
ProjectFilesystem filesystem,
FileHashCache fileHashCache,
ClientStatsTracker distBuildClientStats,
RuleKeyCacheScope<RuleKey> ruleKeyCacheScope)
throws IOException, InterruptedException {
Preconditions.checkNotNull(distBuildClientEventListener);
Preconditions.checkArgument(
(distBuildConfig.getPerformRuleKeyConsistencyCheck()
&& distBuildConfig.getLogMaterializationEnabled())
|| !distBuildConfig.getPerformRuleKeyConsistencyCheck(),
"Log materialization must be enabled to perform rule key consistency check.");
if (distributedBuildStateFile == null
&& distBuildConfig.getBuildMode().equals(BuildMode.DISTRIBUTED_BUILD_WITH_LOCAL_COORDINATOR)
&& !distBuildConfig.getMinionQueue().isPresent()) {
throw new HumanReadableException(
"Stampede Minion Queue name must be specified to use Local Coordinator Mode.");
}
BuildEvent.DistBuildStarted started = BuildEvent.distBuildStarted();
params.getBuckEventBus().post(started);
LOG.info("Starting async file hash computation and job state serialization.");
AsyncJobStateAndCells stateAndCells =
computeDistBuildState(params, graphs, executorService, Optional.of(distBuildClientStats));
ListenableFuture<BuildJobState> asyncJobState = stateAndCells.asyncJobState;
DistBuildCellIndexer distBuildCellIndexer = stateAndCells.distBuildCellIndexer;
if (distributedBuildStateFile != null) {
BuildJobState jobState;
try {
jobState = asyncJobState.get();
} catch (ExecutionException e) {
throw new RuntimeException("Failed to compute DistBuildState.", e);
}
// Read all files inline if we're dumping state to a file.
for (BuildJobStateFileHashes cell : jobState.getFileHashes()) {
ProjectFilesystem cellFilesystem =
Preconditions.checkNotNull(
distBuildCellIndexer.getLocalFilesystemsByCellIndex().get(cell.getCellIndex()));
for (BuildJobStateFileHashEntry entry : cell.getEntries()) {
cellFilesystem
.readFileIfItExists(cellFilesystem.resolve(entry.getPath().getPath()))
.ifPresent(contents -> entry.setContents(contents.getBytes()));
}
}
Path stateDumpPath = Paths.get(distributedBuildStateFile);
BuildJobStateSerializer.serialize(jobState, filesystem.newFileOutputStream(stateDumpPath));
return ExitCode.SUCCESS;
}
BuckVersion buckVersion = getBuckVersion();
Preconditions.checkArgument(params.getInvocationInfo().isPresent());
distBuildClientStats.setIsLocalFallbackBuildEnabled(
distBuildConfig.isSlowLocalBuildFallbackModeEnabled());
try (DistBuildService distBuildService = DistBuildFactory.newDistBuildService(params)) {
ListeningExecutorService stampedeControllerExecutor =
createStampedeControllerExecutorService(distBuildConfig.getControllerMaxThreadCount());
ListeningExecutorService stampedeLocalBuildExecutor =
createStampedeLocalBuildExecutorService();
LogStateTracker distBuildLogStateTracker =
DistBuildFactory.newDistBuildLogStateTracker(
params.getInvocationInfo().get().getLogDirectoryPath(), filesystem, distBuildService);
DistBuildControllerArgs.Builder distBuildControllerArgsBuilder =
DistBuildControllerArgs.builder()
.setBuilderExecutorArgs(params.createBuilderArgs())
.setBuckEventBus(params.getBuckEventBus())
.setTopLevelTargets(buildTargets)
.setBuildGraphs(graphs)
.setCachingBuildEngineDelegate(
Optional.of(new LocalCachingBuildEngineDelegate(params.getFileHashCache())))
.setAsyncJobState(asyncJobState)
.setDistBuildCellIndexer(distBuildCellIndexer)
.setDistBuildService(distBuildService)
.setDistBuildLogStateTracker(distBuildLogStateTracker)
.setBuckVersion(buckVersion)
.setDistBuildClientStats(distBuildClientStats)
.setScheduler(params.getScheduledExecutor())
.setMaxTimeoutWaitingForLogsMillis(
distBuildConfig.getMaxWaitForRemoteLogsToBeAvailableMillis())
.setLogMaterializationEnabled(distBuildConfig.getLogMaterializationEnabled())
.setBuildLabel(distBuildConfig.getBuildLabel());
LocalBuildExecutorInvoker localBuildExecutorInvoker =
new LocalBuildExecutorInvoker() {
@Override
public int executeLocalBuild(
boolean isDownloadHeavyBuild,
RemoteBuildRuleCompletionWaiter remoteBuildRuleCompletionWaiter,
CountDownLatch initializeBuildLatch,
AtomicReference<Build> buildReference)
throws IOException, InterruptedException {
return BuildCommand.this
.executeLocalBuild(
params,
graphs.getActionGraphAndResolver(),
executorService,
Optional.empty(),
remoteBuildRuleCompletionWaiter,
isDownloadHeavyBuild,
Optional.of(initializeBuildLatch),
ruleKeyCacheScope,
buildReference)
.getCode();
}
};
DistBuildControllerInvocationArgs distBuildControllerInvocationArgs =
DistBuildControllerInvocationArgs.builder()
.setExecutorService(stampedeControllerExecutor)
.setProjectFilesystem(filesystem)
.setFileHashCache(fileHashCache)
.setInvocationInfo(params.getInvocationInfo().get())
.setBuildMode(distBuildConfig.getBuildMode())
.setNumberOfMinions(distBuildConfig.getNumberOfMinions())
.setRepository(distBuildConfig.getRepository())
.setTenantId(distBuildConfig.getTenantId())
.setRuleKeyCalculatorFuture(localRuleKeyCalculator)
.build();
// TODO(alisdair): ensure minion build status recorded even if local build finishes first.
boolean waitForDistBuildThreadToFinishGracefully =
distBuildConfig.getLogMaterializationEnabled();
StampedeBuildClient stampedeBuildClient =
new StampedeBuildClient(
params.getBuckEventBus(),
stampedeLocalBuildExecutor,
stampedeControllerExecutor,
distBuildService,
started,
localBuildExecutorInvoker,
distBuildControllerArgsBuilder,
distBuildControllerInvocationArgs,
waitForDistBuildThreadToFinishGracefully);
distBuildClientStats.startTimer(PERFORM_LOCAL_BUILD);
// Perform either a single phase build that waits for all remote artifacts before proceeding,
// or a two stage build where local build first races against remote, and depending on
// progress either completes first or falls back to build that waits for remote artifacts.
boolean skipRacingBuild =
distBuildConfig.shouldAlwaysWaitForRemoteBuildBeforeProceedingLocally();
int localExitCode =
stampedeBuildClient.build(
skipRacingBuild, distBuildConfig.isSlowLocalBuildFallbackModeEnabled());
// All local/distributed build steps are now finished.
StampedeId stampedeId = stampedeBuildClient.getStampedeId();
int distributedBuildExitCode = stampedeBuildClient.getDistBuildExitCode();
distBuildClientStats.setStampedeId(stampedeId.getId());
distBuildClientStats.setDistributedBuildExitCode(distributedBuildExitCode);
// Set local build stats
distBuildClientStats.setPerformedLocalBuild(true);
distBuildClientStats.stopTimer(PERFORM_LOCAL_BUILD);
distBuildClientStats.setLocalBuildExitCode(localExitCode);
// If local build finished before hashing was complete, it's important to cancel
// related Futures to avoid this operation blocking forever.
stateAndCells.cancel();
// stampedeControllerExecutor is now redundant. Kill it as soon as possible.
killExecutor(
stampedeControllerExecutor,
("Stampede controller executor service still running after build finished"
+ " and timeout elapsed. Terminating.."));
killExecutor(
stampedeLocalBuildExecutor,
("Stampede local build executor service still running after build finished"
+ " and timeout elapsed. Terminating.."));
// Publish details about all default rule keys that were cache misses.
// A non-zero value suggests a problem that needs investigating.
try {
Set<String> cacheMissRequestKeys =
distBuildClientEventListener.getDefaultCacheMissRequestKeys();
ArtifactCacheBuckConfig artifactCacheBuckConfig =
ArtifactCacheBuckConfig.of(distBuildConfig.getBuckConfig());
LOG.info(
String.format(
"Fetching rule key logs for [%d] cache misses", cacheMissRequestKeys.size()));
if (cacheMissRequestKeys.size() > 0) {
List<RuleKeyLogEntry> ruleKeyLogs =
distBuildService.fetchRuleKeyLogs(
cacheMissRequestKeys,
artifactCacheBuckConfig.getRepository(),
artifactCacheBuckConfig.getScheduleType(),
true /* distributedBuildModeEnabled */);
params
.getBuckEventBus()
.post(
distBuildClientEventListener.createDistBuildClientCacheResultsEvent(ruleKeyLogs));
}
LOG.info(
String.format(
"Fetched rule key logs for [%d] cache misses", cacheMissRequestKeys.size()));
} catch (Exception ex) {
LOG.error("Failed to publish distributed build client cache request event", ex);
}
boolean ruleKeyConsistencyChecksPassedOrSkipped =
performStampedePostBuildAnalysisAndRuleKeyConsistencyChecks(
params,
distBuildConfig,
filesystem,
distBuildClientStats,
stampedeId,
distributedBuildExitCode,
localExitCode,
distBuildLogStateTracker);
int finalExitCode = localExitCode;
if (!ruleKeyConsistencyChecksPassedOrSkipped) {
finalExitCode =
com.facebook.buck.distributed.ExitCode.RULE_KEY_CONSISTENCY_CHECK_FAILED.getCode();
}
// Post distributed build phase starts POST_DISTRIBUTED_BUILD_LOCAL_STEPS counter internally.
if (distributedBuildExitCode == 0) {
distBuildClientStats.stopTimer(POST_DISTRIBUTED_BUILD_LOCAL_STEPS);
}
if (distBuildClientStats.hasStampedeId()) {
params
.getBuckEventBus()
.post(new DistBuildClientStatsEvent(distBuildClientStats.generateStats()));
}
return ExitCode.map(finalExitCode);
}
}
private void killExecutor(
ListeningExecutorService stampedeControllerExecutor, String failureWarning)
throws InterruptedException {
stampedeControllerExecutor.shutdown();
if (!stampedeControllerExecutor.awaitTermination(
STAMPEDE_EXECUTOR_SHUTDOWN_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
LOG.warn(failureWarning);
stampedeControllerExecutor.shutdownNow();
}
}
private boolean performStampedePostBuildAnalysisAndRuleKeyConsistencyChecks(
CommandRunnerParams params,
DistBuildConfig distBuildConfig,
ProjectFilesystem filesystem,
ClientStatsTracker distBuildClientStats,
StampedeId stampedeId,
int distributedBuildExitCode,
int localBuildExitCode,
LogStateTracker distBuildLogStateTracker)
throws IOException {
// If we are pulling down remote logs, and the distributed build finished successfully,
// then perform analysis
if (distBuildConfig.getLogMaterializationEnabled()
&& distributedBuildExitCode == 0
&& localBuildExitCode == 0) {
distBuildClientStats.startTimer(POST_BUILD_ANALYSIS);
DistBuildPostBuildAnalysis postBuildAnalysis =
new DistBuildPostBuildAnalysis(
params.getInvocationInfo().get().getBuildId(),
stampedeId,
filesystem.resolve(params.getInvocationInfo().get().getLogDirectoryPath()),
distBuildLogStateTracker.getBuildSlaveLogsMaterializer().getMaterializedRunIds(),
DistBuildCommand.class.getSimpleName().toLowerCase());
LOG.info("Created DistBuildPostBuildAnalysis");
AnalysisResults results = postBuildAnalysis.runAnalysis();
Path analysisSummaryFile = postBuildAnalysis.dumpResultsToLogFile(results);
distBuildClientStats.stopTimer(POST_BUILD_ANALYSIS);
LOG.info(String.format("Dumped DistBuildPostBuildAnalysis to [%s]", analysisSummaryFile));
Path relativePathToSummaryFile = filesystem.getRootPath().relativize(analysisSummaryFile);
params
.getBuckEventBus()
.post(
ConsoleEvent.warning(
"Details of distributed build analysis: %s",
relativePathToSummaryFile.toString()));
LOG.info(
"Number of mismatching default rule keys: " + results.numMismatchingDefaultRuleKeys());
if (distBuildConfig.getPerformRuleKeyConsistencyCheck()
&& results.numMismatchingDefaultRuleKeys() > 0) {
params
.getBuckEventBus()
.post(
ConsoleEvent.severe(
"*** [%d] default rule keys mismatched between client and server. *** \nMismatching rule keys:",
results.numMismatchingDefaultRuleKeys()));
for (RuleKeyNameAndType ruleKeyNameAndType :
postBuildAnalysis.getMismatchingDefaultRuleKeys(results)) {
params
.getBuckEventBus()
.post(
ConsoleEvent.severe(
"MISMATCHING RULE: %s [%s]",
ruleKeyNameAndType.getRuleName(), ruleKeyNameAndType.getRuleType()));
}
return false; // Rule keys were not consistent
}
}
return true; // Rule keys were consistent, or test was skipped.
}
private BuckVersion getBuckVersion() throws IOException {
if (buckBinary == null) {
String gitHash = System.getProperty(BUCK_GIT_COMMIT_KEY, null);
if (gitHash == null) {
throw new CommandLineException(
String.format(
"Property [%s] is not set and the command line flag [%s] was not passed.",
BUCK_GIT_COMMIT_KEY, BUCK_BINARY_STRING_ARG));
}
return BuckVersionUtil.createFromGitHash(gitHash);
}
Path binaryPath = Paths.get(buckBinary);
if (!Files.isRegularFile(binaryPath)) {
throw new CommandLineException(
String.format(
"Buck binary [%s] passed under flag [%s] does not exist.",
binaryPath, BUCK_BINARY_STRING_ARG));
}
return BuckVersionUtil.createFromLocalBinary(binaryPath);
}
private void showOutputs(
CommandRunnerParams params,
ActionGraphAndResolver actionGraphAndResolver,
RuleKeyCacheScope<RuleKey> ruleKeyCacheScope)
throws IOException {
TreeMap<String, String> sortedJsonOutputs = new TreeMap<String, String>();
Optional<DefaultRuleKeyFactory> ruleKeyFactory = Optional.empty();
SourcePathRuleFinder ruleFinder =
new SourcePathRuleFinder(actionGraphAndResolver.getResolver());
SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
if (showRuleKey) {
RuleKeyFieldLoader fieldLoader = new RuleKeyFieldLoader(params.getRuleKeyConfiguration());
ruleKeyFactory =
Optional.of(
new DefaultRuleKeyFactory(
fieldLoader,
params.getFileHashCache(),
pathResolver,
ruleFinder,
ruleKeyCacheScope.getCache(),
Optional.empty()));
}
for (BuildTarget buildTarget : buildTargets) {
BuildRule rule = actionGraphAndResolver.getResolver().requireRule(buildTarget);
Optional<Path> outputPath =
TargetsCommand.getUserFacingOutputPath(
pathResolver, rule, params.getBuckConfig().getBuckOutCompatLink())
.map(
path ->
showFullOutput || showFullJsonOutput
? path
: params.getCell().getFilesystem().relativize(path));
params.getConsole().getStdOut().flush();
if (showJsonOutput || showFullJsonOutput) {
sortedJsonOutputs.put(
rule.getFullyQualifiedName(), outputPath.map(Object::toString).orElse(""));
} else {
params
.getConsole()
.getStdOut()
.printf(
"%s%s%s\n",
rule.getFullyQualifiedName(),
showRuleKey ? " " + ruleKeyFactory.get().build(rule).toString() : "",
showOutput || showFullOutput
? " " + outputPath.map(Object::toString).orElse("")
: "");
}
}
if (showJsonOutput || showFullJsonOutput) {
// Print the build rule information as JSON.
StringWriter stringWriter = new StringWriter();
ObjectMappers.WRITER.withDefaultPrettyPrinter().writeValue(stringWriter, sortedJsonOutputs);
String output = stringWriter.getBuffer().toString();
params.getConsole().getStdOut().println(output);
}
}
private TargetGraphAndBuildTargets createUnversionedTargetGraph(
CommandRunnerParams params, ListeningExecutorService executor)
throws IOException, InterruptedException, ActionGraphCreationException {
// Parse the build files to create a ActionGraph.
ParserConfig parserConfig = params.getBuckConfig().getView(ParserConfig.class);
try {
return params
.getParser()
.buildTargetGraphForTargetNodeSpecs(
params.getBuckEventBus(),
params.getCell(),
getEnableParserProfiling(),
executor,
parseArgumentsAsTargetNodeSpecs(params.getBuckConfig(), getArguments()),
parserConfig.getDefaultFlavorsMode());
} catch (BuildTargetException e) {
throw new ActionGraphCreationException(MoreExceptions.getHumanReadableOrLocalizedMessage(e));
}
}
private ActionGraphAndResolver createActionGraphAndResolver(
CommandRunnerParams params,
TargetGraphAndBuildTargets targetGraphAndBuildTargets,
Optional<ThriftRuleKeyLogger> ruleKeyLogger,
CloseableMemoizedSupplier<ForkJoinPool, RuntimeException> poolSupplier)
throws ActionGraphCreationException {
buildTargets = targetGraphAndBuildTargets.getBuildTargets();
buildTargetsHaveBeenCalculated = true;
ActionGraphAndResolver actionGraphAndResolver =
params
.getActionGraphCache()
.getActionGraph(
params.getBuckEventBus(),
targetGraphAndBuildTargets.getTargetGraph(),
params.getBuckConfig(),
params.getRuleKeyConfiguration(),
ruleKeyLogger,
poolSupplier);
// If the user specified an explicit build target, use that.
if (justBuildTarget != null) {
BuildTarget explicitTarget =
BuildTargetParser.INSTANCE.parse(
justBuildTarget,
BuildTargetPatternParser.fullyQualified(),
params.getCell().getCellPathResolver());
Iterable<BuildRule> actionGraphRules =
Preconditions.checkNotNull(actionGraphAndResolver.getActionGraph().getNodes());
ImmutableSet<BuildTarget> actionGraphTargets =
ImmutableSet.copyOf(Iterables.transform(actionGraphRules, BuildRule::getBuildTarget));
if (!actionGraphTargets.contains(explicitTarget)) {
throw new ActionGraphCreationException(
"Targets specified via `--just-build` must be a subset of action graph.");
}
buildTargets = ImmutableSet.of(explicitTarget);
}
return actionGraphAndResolver;
}
protected ExitCode executeLocalBuild(
CommandRunnerParams params,
ActionGraphAndResolver actionGraphAndResolver,
WeightedListeningExecutorService executor,
Optional<ThriftRuleKeyLogger> ruleKeyLogger,
RemoteBuildRuleCompletionWaiter remoteBuildRuleCompletionWaiter,
boolean isDownloadHeavyBuild,
Optional<CountDownLatch> initializeBuildLatch,
RuleKeyCacheScope<RuleKey> ruleKeyCacheScope,
AtomicReference<Build> buildReference)
throws IOException, InterruptedException {
LocalBuildExecutor builder =
new LocalBuildExecutor(
params.createBuilderArgs(),
getExecutionContext(),
actionGraphAndResolver,
new LocalCachingBuildEngineDelegate(params.getFileHashCache()),
executor,
isKeepGoing(),
useDistributedBuild,
isDownloadHeavyBuild,
ruleKeyCacheScope,
getBuildEngineMode(),
ruleKeyLogger,
remoteBuildRuleCompletionWaiter);
buildReference.set(builder.getBuild());
// TODO(alisdair): ensure that all Stampede local builds re-use same calculator
localRuleKeyCalculator.set(builder.getCachingBuildEngine().getRuleKeyCalculator());
if (initializeBuildLatch.isPresent()) {
// Signal to other threads that lastBuild has now been set.
initializeBuildLatch.get().countDown();
}
List<String> targetStrings =
FluentIterable.from(buildTargets)
.append(getAdditionalTargetsToBuild(actionGraphAndResolver.getResolver()))
.transform(target -> target.getFullyQualifiedName())
.toList();
int code =
builder.buildLocallyAndReturnExitCode(
targetStrings, getPathToBuildReport(params.getBuckConfig()));
builder.shutdown();
return ExitCode.map(code);
}
RuleKeyCacheScope<RuleKey> getDefaultRuleKeyCacheScope(
CommandRunnerParams params, ActionGraphAndResolver actionGraphAndResolver) {
return getDefaultRuleKeyCacheScope(
params,
new RuleKeyCacheRecycler.SettingsAffectingCache(
params.getBuckConfig().getKeySeed(), actionGraphAndResolver.getActionGraph()));
}
@Override
protected ExecutionContext.Builder getExecutionContextBuilder(CommandRunnerParams params) {
return super.getExecutionContextBuilder(params)
.setTargetDevice(Optional.empty())
.setCodeCoverageEnabled(isCodeCoverageEnabled())
.setDebugEnabled(isDebugEnabled())
.setShouldReportAbsolutePaths(shouldReportAbsolutePaths());
}
@SuppressWarnings("unused")
protected Iterable<BuildTarget> getAdditionalTargetsToBuild(BuildRuleResolver resolver) {
return ImmutableList.of();
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
public boolean isSourceControlStatsGatheringEnabled() {
return true;
}
Build getBuild() {
return Preconditions.checkNotNull(lastBuild.get());
}
public ImmutableList<BuildTarget> getBuildTargets() {
Preconditions.checkState(buildTargetsHaveBeenCalculated);
return ImmutableList.copyOf(buildTargets);
}
@Override
public String getShortDescription() {
return "builds the specified target";
}
@Override
public Iterable<BuckEventListener> getEventListeners(
Map<ExecutorPool, ListeningExecutorService> executorPool,
ScheduledExecutorService scheduledExecutorService) {
ImmutableList.Builder<BuckEventListener> listeners = ImmutableList.builder();
if (useDistributedBuild) {
distBuildClientEventListener = new DistBuildClientEventListener();
listeners.add(distBuildClientEventListener);
}
return listeners.build();
}
private static class AsyncJobStateAndCells {
final DistBuildFileHashes distributedBuildFileHashes;
final ListenableFuture<BuildJobState> asyncJobState;
final DistBuildCellIndexer distBuildCellIndexer;
AsyncJobStateAndCells(
DistBuildFileHashes distributedBuildFileHashes,
ListenableFuture<BuildJobState> asyncJobState,
DistBuildCellIndexer cellIndexer) {
this.distributedBuildFileHashes = distributedBuildFileHashes;
this.asyncJobState = asyncJobState;
this.distBuildCellIndexer = cellIndexer;
}
// Cancels any ongoing Future operations
protected void cancel() {
distributedBuildFileHashes.cancel();
asyncJobState.cancel(true);
}
}
public static class ActionGraphCreationException extends Exception {
public ActionGraphCreationException(String message) {
super(message);
}
}
}
| src/com/facebook/buck/cli/BuildCommand.java | /*
* Copyright 2012-present Facebook, Inc.
*
* 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.facebook.buck.cli;
import static com.facebook.buck.distributed.ClientStatsTracker.DistBuildClientStat.LOCAL_FILE_HASH_COMPUTATION;
import static com.facebook.buck.distributed.ClientStatsTracker.DistBuildClientStat.LOCAL_GRAPH_CONSTRUCTION;
import static com.facebook.buck.distributed.ClientStatsTracker.DistBuildClientStat.LOCAL_PREPARATION;
import static com.facebook.buck.distributed.ClientStatsTracker.DistBuildClientStat.PERFORM_LOCAL_BUILD;
import static com.facebook.buck.distributed.ClientStatsTracker.DistBuildClientStat.POST_BUILD_ANALYSIS;
import static com.facebook.buck.distributed.ClientStatsTracker.DistBuildClientStat.POST_DISTRIBUTED_BUILD_LOCAL_STEPS;
import static com.facebook.buck.util.concurrent.MostExecutors.newMultiThreadExecutor;
import com.facebook.buck.artifact_cache.config.ArtifactCacheBuckConfig;
import com.facebook.buck.cli.output.Mode;
import com.facebook.buck.command.Build;
import com.facebook.buck.command.LocalBuildExecutor;
import com.facebook.buck.command.LocalBuildExecutorInvoker;
import com.facebook.buck.config.BuckConfig;
import com.facebook.buck.distributed.AnalysisResults;
import com.facebook.buck.distributed.BuckVersionUtil;
import com.facebook.buck.distributed.BuildJobStateSerializer;
import com.facebook.buck.distributed.ClientStatsTracker;
import com.facebook.buck.distributed.DistBuildCellIndexer;
import com.facebook.buck.distributed.DistBuildClientStatsEvent;
import com.facebook.buck.distributed.DistBuildConfig;
import com.facebook.buck.distributed.DistBuildFileHashes;
import com.facebook.buck.distributed.DistBuildPostBuildAnalysis;
import com.facebook.buck.distributed.DistBuildService;
import com.facebook.buck.distributed.DistBuildState;
import com.facebook.buck.distributed.DistBuildTargetGraphCodec;
import com.facebook.buck.distributed.RuleKeyNameAndType;
import com.facebook.buck.distributed.build_client.DistBuildControllerArgs;
import com.facebook.buck.distributed.build_client.DistBuildControllerInvocationArgs;
import com.facebook.buck.distributed.build_client.LogStateTracker;
import com.facebook.buck.distributed.build_client.StampedeBuildClient;
import com.facebook.buck.distributed.thrift.BuckVersion;
import com.facebook.buck.distributed.thrift.BuildJobState;
import com.facebook.buck.distributed.thrift.BuildJobStateFileHashEntry;
import com.facebook.buck.distributed.thrift.BuildJobStateFileHashes;
import com.facebook.buck.distributed.thrift.BuildMode;
import com.facebook.buck.distributed.thrift.RuleKeyLogEntry;
import com.facebook.buck.distributed.thrift.StampedeId;
import com.facebook.buck.event.BuckEventListener;
import com.facebook.buck.event.ConsoleEvent;
import com.facebook.buck.event.listener.DistBuildClientEventListener;
import com.facebook.buck.io.file.MoreFiles;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.log.CommandThreadFactory;
import com.facebook.buck.log.Logger;
import com.facebook.buck.log.thrift.ThriftRuleKeyLogger;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.parser.BuildTargetParser;
import com.facebook.buck.parser.BuildTargetPatternParser;
import com.facebook.buck.parser.DefaultParserTargetNodeFactory;
import com.facebook.buck.parser.ParserConfig;
import com.facebook.buck.parser.ParserTargetNodeFactory;
import com.facebook.buck.parser.exceptions.BuildFileParseException;
import com.facebook.buck.parser.exceptions.BuildTargetException;
import com.facebook.buck.rules.ActionAndTargetGraphs;
import com.facebook.buck.rules.ActionGraphAndResolver;
import com.facebook.buck.rules.BuildEvent;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.CachingBuildEngine;
import com.facebook.buck.rules.DefaultSourcePathResolver;
import com.facebook.buck.rules.LocalCachingBuildEngineDelegate;
import com.facebook.buck.rules.NoOpRemoteBuildRuleCompletionWaiter;
import com.facebook.buck.rules.ParallelRuleKeyCalculator;
import com.facebook.buck.rules.RemoteBuildRuleCompletionWaiter;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.TargetGraphAndBuildTargets;
import com.facebook.buck.rules.TargetNode;
import com.facebook.buck.rules.TargetNodeFactory;
import com.facebook.buck.rules.coercer.ConstructorArgMarshaller;
import com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory;
import com.facebook.buck.rules.coercer.PathTypeCoercer;
import com.facebook.buck.rules.coercer.TypeCoercerFactory;
import com.facebook.buck.rules.keys.DefaultRuleKeyFactory;
import com.facebook.buck.rules.keys.RuleKeyCacheRecycler;
import com.facebook.buck.rules.keys.RuleKeyCacheScope;
import com.facebook.buck.rules.keys.RuleKeyFieldLoader;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.ExecutorPool;
import com.facebook.buck.util.CloseableMemoizedSupplier;
import com.facebook.buck.util.CommandLineException;
import com.facebook.buck.util.ExitCode;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.ListeningProcessExecutor;
import com.facebook.buck.util.MoreExceptions;
import com.facebook.buck.util.ObjectMappers;
import com.facebook.buck.util.cache.FileHashCache;
import com.facebook.buck.util.concurrent.MostExecutors;
import com.facebook.buck.util.concurrent.WeightedListeningExecutorService;
import com.facebook.buck.versions.VersionException;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
public class BuildCommand extends AbstractCommand {
private static final Logger LOG = Logger.get(BuildCommand.class);
private static final String KEEP_GOING_LONG_ARG = "--keep-going";
private static final String BUILD_REPORT_LONG_ARG = "--build-report";
private static final String JUST_BUILD_LONG_ARG = "--just-build";
private static final String DEEP_LONG_ARG = "--deep";
private static final String OUT_LONG_ARG = "--out";
private static final String POPULATE_CACHE_LONG_ARG = "--populate-cache";
private static final String SHALLOW_LONG_ARG = "--shallow";
private static final String REPORT_ABSOLUTE_PATHS = "--report-absolute-paths";
private static final String SHOW_OUTPUT_LONG_ARG = "--show-output";
private static final String SHOW_FULL_OUTPUT_LONG_ARG = "--show-full-output";
private static final String SHOW_JSON_OUTPUT_LONG_ARG = "--show-json-output";
private static final String SHOW_FULL_JSON_OUTPUT_LONG_ARG = "--show-full-json-output";
private static final String SHOW_RULEKEY_LONG_ARG = "--show-rulekey";
private static final String DISTRIBUTED_LONG_ARG = "--distributed";
private static final String BUCK_BINARY_STRING_ARG = "--buck-binary";
private static final String RULEKEY_LOG_PATH_LONG_ARG = "--rulekeys-log-path";
private static final String BUCK_GIT_COMMIT_KEY = "buck.git_commit";
private static final int STAMPEDE_EXECUTOR_SHUTDOWN_TIMEOUT_MILLIS = 100;
@Option(name = KEEP_GOING_LONG_ARG, usage = "Keep going when some targets can't be made.")
private boolean keepGoing = false;
@Option(name = BUILD_REPORT_LONG_ARG, usage = "File where build report will be written.")
@Nullable
private Path buildReport = null;
@Nullable
@Option(
name = JUST_BUILD_LONG_ARG,
usage = "For debugging, limits the build to a specific target in the action graph.",
hidden = true
)
private String justBuildTarget = null;
@Option(
name = DEEP_LONG_ARG,
usage =
"Perform a \"deep\" build, which makes the output of all transitive dependencies"
+ " available.",
forbids = SHALLOW_LONG_ARG
)
private boolean deepBuild = false;
@Option(
name = POPULATE_CACHE_LONG_ARG,
usage =
"Performs a cache population, which makes the output of all unchanged "
+ "transitive dependencies available (if these outputs are available "
+ "in the remote cache). Does not build changed or unavailable dependencies locally.",
forbids = {SHALLOW_LONG_ARG, DEEP_LONG_ARG}
)
private boolean populateCacheOnly = false;
@Option(
name = SHALLOW_LONG_ARG,
usage =
"Perform a \"shallow\" build, which only makes the output of all explicitly listed"
+ " targets available.",
forbids = DEEP_LONG_ARG
)
private boolean shallowBuild = false;
@Option(
name = REPORT_ABSOLUTE_PATHS,
usage = "Reports errors using absolute paths to the source files instead of relative paths."
)
private boolean shouldReportAbsolutePaths = false;
@Option(
name = SHOW_OUTPUT_LONG_ARG,
usage = "Print the path to the output for each of the built rules relative to the cell."
)
private boolean showOutput;
@Option(name = OUT_LONG_ARG, usage = "Copies the output of the lone build target to this path.")
@Nullable
private Path outputPathForSingleBuildTarget;
@Option(
name = SHOW_FULL_OUTPUT_LONG_ARG,
usage = "Print the absolute path to the output for each of the built rules."
)
private boolean showFullOutput;
@Option(name = SHOW_JSON_OUTPUT_LONG_ARG, usage = "Show output in JSON format.")
private boolean showJsonOutput;
@Option(name = SHOW_FULL_JSON_OUTPUT_LONG_ARG, usage = "Show full output in JSON format.")
private boolean showFullJsonOutput;
@Option(name = SHOW_RULEKEY_LONG_ARG, usage = "Print the rulekey for each of the built rules.")
private boolean showRuleKey;
@Option(
name = DISTRIBUTED_LONG_ARG,
usage = "Whether to run in distributed build mode. (experimental)",
hidden = true
)
private boolean useDistributedBuild = false;
@Nullable
@Option(
name = DistBuildRunCommand.BUILD_STATE_FILE_ARG_NAME,
usage = DistBuildRunCommand.BUILD_STATE_FILE_ARG_USAGE,
hidden = true
)
private String distributedBuildStateFile = null;
@Nullable
@Option(
name = BUCK_BINARY_STRING_ARG,
usage = "Buck binary to use on a distributed build instead of the current git version.",
hidden = true
)
private String buckBinary = null;
@Nullable
@Option(
name = RULEKEY_LOG_PATH_LONG_ARG,
usage = "If set, log a binary representation of rulekeys to this file."
)
private String ruleKeyLogPath = null;
@Argument private List<String> arguments = new ArrayList<>();
private boolean buildTargetsHaveBeenCalculated;
@Nullable private DistBuildClientEventListener distBuildClientEventListener;
public List<String> getArguments() {
return arguments;
}
public boolean isCodeCoverageEnabled() {
return false;
}
public boolean isDebugEnabled() {
return false;
}
protected Mode getOutputMode() {
if (this.showFullOutput) {
return Mode.FULL;
} else if (this.showOutput) {
return Mode.SIMPLE;
} else {
return Mode.NONE;
}
}
public BuildCommand() {
this(ImmutableList.of());
}
public BuildCommand(List<String> arguments) {
this.arguments.addAll(arguments);
}
public Optional<CachingBuildEngine.BuildMode> getBuildEngineMode() {
Optional<CachingBuildEngine.BuildMode> mode = Optional.empty();
if (deepBuild) {
mode = Optional.of(CachingBuildEngine.BuildMode.DEEP);
}
if (populateCacheOnly) {
mode = Optional.of(CachingBuildEngine.BuildMode.POPULATE_FROM_REMOTE_CACHE);
}
if (shallowBuild) {
mode = Optional.of(CachingBuildEngine.BuildMode.SHALLOW);
}
return mode;
}
public boolean isKeepGoing() {
return keepGoing;
}
protected boolean shouldReportAbsolutePaths() {
return shouldReportAbsolutePaths;
}
public void setKeepGoing(boolean keepGoing) {
this.keepGoing = keepGoing;
}
public boolean isUseDistributedBuild() {
return useDistributedBuild;
}
public void setUseDistributedBuild(boolean useDistributedBuild) {
this.useDistributedBuild = useDistributedBuild;
}
/** @return an absolute path or {@link Optional#empty()}. */
public Optional<Path> getPathToBuildReport(BuckConfig buckConfig) {
return Optional.ofNullable(
buckConfig.resolvePathThatMayBeOutsideTheProjectFilesystem(buildReport));
}
private final AtomicReference<Build> lastBuild = new AtomicReference<>(null);
private final SettableFuture<ParallelRuleKeyCalculator<RuleKey>> localRuleKeyCalculator =
SettableFuture.create();
private ImmutableSet<BuildTarget> buildTargets = ImmutableSet.of();
/**
* Create the serializable {@link BuildJobState} for distributed builds.
*
* @param buildTargets - Top level targets.
* @param params - Client side parameters.
* @param executor - Executor for async ops.
* @param poolSupplier - the supplier of an executor for parallel action graph construction
* @return - New instance of serializable {@link BuildJobState}.
* @throws InterruptedException
* @throws IOException
*/
public static ListenableFuture<BuildJobState> getAsyncDistBuildState(
List<String> buildTargets,
CommandRunnerParams params,
WeightedListeningExecutorService executor,
CloseableMemoizedSupplier<ForkJoinPool, RuntimeException> poolSupplier)
throws InterruptedException, IOException {
BuildCommand buildCommand = new BuildCommand(buildTargets);
buildCommand.assertArguments(params);
ActionAndTargetGraphs graphs = null;
try {
graphs = buildCommand.createGraphs(params, executor, Optional.empty(), poolSupplier);
} catch (ActionGraphCreationException e) {
throw BuildFileParseException.createForUnknownParseError(e.getMessage());
}
return buildCommand.computeDistBuildState(params, graphs, executor, Optional.empty())
.asyncJobState;
}
@Override
public ExitCode runWithoutHelp(CommandRunnerParams params)
throws IOException, InterruptedException {
assertArguments(params);
ListeningProcessExecutor processExecutor = new ListeningProcessExecutor();
try (CommandThreadManager pool =
new CommandThreadManager("Build", getConcurrencyLimit(params.getBuckConfig()));
BuildPrehook prehook =
new BuildPrehook(
processExecutor,
params.getCell(),
params.getBuckEventBus(),
params.getBuckConfig(),
params.getEnvironment()); ) {
prehook.startPrehookScript();
return run(params, pool, ImmutableSet.of());
}
}
/** @throw CommandLineException if arguments provided are incorrect */
protected void assertArguments(CommandRunnerParams params) {
if (!getArguments().isEmpty()) {
return;
}
String message = "Must specify at least one build target.";
ImmutableSet<String> aliases = params.getBuckConfig().getAliases().keySet();
if (!aliases.isEmpty()) {
// If there are aliases defined in .buckconfig, suggest that the user
// build one of them. We show the user only the first 10 aliases.
message +=
String.format(
"%nTry building one of the following targets:%n%s",
Joiner.on(' ').join(Iterators.limit(aliases.iterator(), 10)));
}
throw new CommandLineException(message);
}
protected ExitCode run(
CommandRunnerParams params,
CommandThreadManager commandThreadManager,
ImmutableSet<String> additionalTargets)
throws IOException, InterruptedException {
if (!additionalTargets.isEmpty()) {
this.arguments.addAll(additionalTargets);
}
BuildEvent.Started started = postBuildStartedEvent(params);
ExitCode exitCode = ExitCode.SUCCESS;
try (CloseableMemoizedSupplier<ForkJoinPool, RuntimeException> poolSupplier =
getForkJoinPoolSupplier(params.getBuckConfig())) {
exitCode = executeBuildAndProcessResult(params, commandThreadManager, poolSupplier);
} catch (ActionGraphCreationException e) {
params.getConsole().printBuildFailure(e.getMessage());
exitCode = ExitCode.PARSE_ERROR;
} finally {
params.getBuckEventBus().post(BuildEvent.finished(started, exitCode));
}
return exitCode;
}
private BuildEvent.Started postBuildStartedEvent(CommandRunnerParams params) {
// Post the build started event, setting it to the Parser recorded start time if appropriate.
BuildEvent.Started started = BuildEvent.started(getArguments());
if (params.getParser().getParseStartTime().isPresent()) {
params.getBuckEventBus().post(started, params.getParser().getParseStartTime().get());
} else {
params.getBuckEventBus().post(started);
}
return started;
}
private ActionAndTargetGraphs createGraphs(
CommandRunnerParams params,
ListeningExecutorService executorService,
Optional<ThriftRuleKeyLogger> ruleKeyLogger,
CloseableMemoizedSupplier<ForkJoinPool, RuntimeException> poolSupplier)
throws ActionGraphCreationException, IOException, InterruptedException {
TargetGraphAndBuildTargets unversionedTargetGraph =
createUnversionedTargetGraph(params, executorService);
Optional<TargetGraphAndBuildTargets> versionedTargetGraph = Optional.empty();
try {
if (params.getBuckConfig().getBuildVersions()) {
versionedTargetGraph = Optional.of(toVersionedTargetGraph(params, unversionedTargetGraph));
}
} catch (VersionException e) {
throw new ActionGraphCreationException(MoreExceptions.getHumanReadableOrLocalizedMessage(e));
}
TargetGraphAndBuildTargets targetGraphForLocalBuild =
ActionAndTargetGraphs.getTargetGraphForLocalBuild(
unversionedTargetGraph, versionedTargetGraph);
checkSingleBuildTargetSpecifiedForOutBuildMode(targetGraphForLocalBuild);
ActionGraphAndResolver actionGraph =
createActionGraphAndResolver(params, targetGraphForLocalBuild, ruleKeyLogger, poolSupplier);
return ActionAndTargetGraphs.builder()
.setUnversionedTargetGraph(unversionedTargetGraph)
.setVersionedTargetGraph(versionedTargetGraph)
.setActionGraphAndResolver(actionGraph)
.build();
}
private void checkSingleBuildTargetSpecifiedForOutBuildMode(
TargetGraphAndBuildTargets targetGraphAndBuildTargets) throws ActionGraphCreationException {
// Ideally, we would error out of this before we build the entire graph, but it is possible
// that `getArguments().size()` is 1 but `targetGraphAndBuildTargets.getBuildTargets().size()`
// is greater than 1 if the lone argument is a wildcard build target that ends in "...".
// As such, we have to get the result of createTargetGraph() before we can do this check.
if (outputPathForSingleBuildTarget != null
&& targetGraphAndBuildTargets.getBuildTargets().size() != 1) {
throw new CommandLineException(
String.format(
"When using %s you must specify exactly one build target, but you specified %s",
OUT_LONG_ARG, targetGraphAndBuildTargets.getBuildTargets()));
}
}
private ExitCode executeBuildAndProcessResult(
CommandRunnerParams params,
CommandThreadManager commandThreadManager,
CloseableMemoizedSupplier<ForkJoinPool, RuntimeException> poolSupplier)
throws IOException, InterruptedException, ActionGraphCreationException {
ExitCode exitCode = ExitCode.SUCCESS;
final ActionAndTargetGraphs graphs;
if (useDistributedBuild) {
DistBuildConfig distBuildConfig = new DistBuildConfig(params.getBuckConfig());
ClientStatsTracker distBuildClientStatsTracker =
new ClientStatsTracker(distBuildConfig.getBuildLabel());
distBuildClientStatsTracker.startTimer(LOCAL_PREPARATION);
distBuildClientStatsTracker.startTimer(LOCAL_GRAPH_CONSTRUCTION);
graphs =
createGraphs(
params,
commandThreadManager.getListeningExecutorService(),
Optional.empty(),
poolSupplier);
distBuildClientStatsTracker.stopTimer(LOCAL_GRAPH_CONSTRUCTION);
try (RuleKeyCacheScope<RuleKey> ruleKeyCacheScope =
getDefaultRuleKeyCacheScope(params, graphs.getActionGraphAndResolver())) {
try {
exitCode =
executeDistBuild(
params,
distBuildConfig,
graphs,
commandThreadManager.getWeightedListeningExecutorService(),
params.getCell().getFilesystem(),
params.getFileHashCache(),
distBuildClientStatsTracker,
ruleKeyCacheScope);
} catch (Throwable ex) {
String stackTrace = Throwables.getStackTraceAsString(ex);
distBuildClientStatsTracker.setBuckClientErrorMessage(ex.toString() + "\n" + stackTrace);
distBuildClientStatsTracker.setBuckClientError(true);
throw ex;
} finally {
if (distBuildClientStatsTracker.hasStampedeId()) {
params
.getBuckEventBus()
.post(new DistBuildClientStatsEvent(distBuildClientStatsTracker.generateStats()));
} else {
LOG.error(
"Failed to published DistBuildClientStatsEvent as no Stampede ID was received");
}
}
if (exitCode == ExitCode.SUCCESS) {
exitCode = processSuccessfulBuild(params, graphs, ruleKeyCacheScope);
}
}
} else {
try (ThriftRuleKeyLogger ruleKeyLogger = createRuleKeyLogger().orElse(null)) {
Optional<ThriftRuleKeyLogger> optionalRuleKeyLogger = Optional.ofNullable(ruleKeyLogger);
graphs =
createGraphs(
params,
commandThreadManager.getListeningExecutorService(),
optionalRuleKeyLogger,
poolSupplier);
try (RuleKeyCacheScope<RuleKey> ruleKeyCacheScope =
getDefaultRuleKeyCacheScope(params, graphs.getActionGraphAndResolver())) {
exitCode =
executeLocalBuild(
params,
graphs.getActionGraphAndResolver(),
commandThreadManager.getWeightedListeningExecutorService(),
optionalRuleKeyLogger,
new NoOpRemoteBuildRuleCompletionWaiter(),
false,
Optional.empty(),
ruleKeyCacheScope,
lastBuild);
if (exitCode == ExitCode.SUCCESS) {
exitCode = processSuccessfulBuild(params, graphs, ruleKeyCacheScope);
}
}
}
}
return exitCode;
}
/**
* Create a {@link ThriftRuleKeyLogger} depending on whether {@link BuildCommand#ruleKeyLogPath}
* is set or not
*/
private Optional<ThriftRuleKeyLogger> createRuleKeyLogger() throws IOException {
if (ruleKeyLogPath == null) {
return Optional.empty();
} else {
return Optional.of(ThriftRuleKeyLogger.create(Paths.get(ruleKeyLogPath)));
}
}
private ExitCode processSuccessfulBuild(
CommandRunnerParams params,
ActionAndTargetGraphs graphs,
RuleKeyCacheScope<RuleKey> ruleKeyCacheScope)
throws IOException {
if (params.getBuckConfig().createBuildOutputSymLinksEnabled()) {
symLinkBuildResults(params, graphs.getActionGraphAndResolver());
}
if (showOutput || showFullOutput || showJsonOutput || showFullJsonOutput || showRuleKey) {
showOutputs(params, graphs.getActionGraphAndResolver(), ruleKeyCacheScope);
}
if (outputPathForSingleBuildTarget != null) {
BuildTarget loneTarget =
Iterables.getOnlyElement(graphs.getTargetGraphForLocalBuild().getBuildTargets());
BuildRule rule = graphs.getActionGraphAndResolver().getResolver().getRule(loneTarget);
if (!rule.outputFileCanBeCopied()) {
params
.getConsole()
.printErrorText(
String.format(
"%s does not have an output that is compatible with `buck build --out`",
loneTarget));
return ExitCode.BUILD_ERROR;
} else {
SourcePath output =
Preconditions.checkNotNull(
rule.getSourcePathToOutput(),
"%s specified a build target that does not have an output file: %s",
OUT_LONG_ARG,
loneTarget);
ProjectFilesystem projectFilesystem = rule.getProjectFilesystem();
SourcePathResolver pathResolver =
DefaultSourcePathResolver.from(
new SourcePathRuleFinder(graphs.getActionGraphAndResolver().getResolver()));
projectFilesystem.copyFile(
pathResolver.getAbsolutePath(output), outputPathForSingleBuildTarget);
}
}
return ExitCode.SUCCESS;
}
private void symLinkBuildResults(
CommandRunnerParams params, ActionGraphAndResolver actionGraphAndResolver)
throws IOException {
// Clean up last buck-out/last.
Path lastOutputDirPath =
params.getCell().getFilesystem().getBuckPaths().getLastOutputDir().toAbsolutePath();
MoreFiles.deleteRecursivelyIfExists(lastOutputDirPath);
Files.createDirectories(lastOutputDirPath);
SourcePathRuleFinder ruleFinder =
new SourcePathRuleFinder(actionGraphAndResolver.getResolver());
SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
for (BuildTarget buildTarget : buildTargets) {
BuildRule rule = actionGraphAndResolver.getResolver().requireRule(buildTarget);
Optional<Path> outputPath =
TargetsCommand.getUserFacingOutputPath(
pathResolver, rule, params.getBuckConfig().getBuckOutCompatLink());
if (outputPath.isPresent()) {
Path absolutePath = outputPath.get();
Path destPath = lastOutputDirPath.relativize(absolutePath);
Path linkPath = lastOutputDirPath.resolve(absolutePath.getFileName());
// Don't overwrite existing symlink in case there are duplicate names.
if (!Files.exists(linkPath)) {
Files.createSymbolicLink(linkPath, destPath);
}
}
}
}
private AsyncJobStateAndCells computeDistBuildState(
final CommandRunnerParams params,
ActionAndTargetGraphs graphs,
final ListeningExecutorService executorService,
Optional<ClientStatsTracker> clientStatsTracker)
throws IOException, InterruptedException {
DistBuildCellIndexer cellIndexer = new DistBuildCellIndexer(params.getCell());
// Compute the file hashes.
ActionGraphAndResolver actionGraphAndResolver = graphs.getActionGraphAndResolver();
SourcePathRuleFinder ruleFinder =
new SourcePathRuleFinder(actionGraphAndResolver.getResolver());
SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
clientStatsTracker.ifPresent(tracker -> tracker.startTimer(LOCAL_FILE_HASH_COMPUTATION));
DistBuildFileHashes distributedBuildFileHashes =
new DistBuildFileHashes(
actionGraphAndResolver.getActionGraph(),
pathResolver,
ruleFinder,
params.getFileHashCache(),
cellIndexer,
executorService,
params.getRuleKeyConfiguration(),
params.getCell());
distributedBuildFileHashes
.getFileHashesComputationFuture()
.addListener(
() ->
clientStatsTracker.ifPresent(
tracker -> tracker.stopTimer(LOCAL_FILE_HASH_COMPUTATION)),
executorService);
// Distributed builds serialize and send the unversioned target graph,
// and then deserialize and version remotely.
TargetGraphAndBuildTargets targetGraphAndBuildTargets =
graphs.getTargetGraphForDistributedBuild();
TypeCoercerFactory typeCoercerFactory =
new DefaultTypeCoercerFactory(PathTypeCoercer.PathExistenceVerificationMode.DO_NOT_VERIFY);
ParserTargetNodeFactory<TargetNode<?, ?>> parserTargetNodeFactory =
DefaultParserTargetNodeFactory.createForDistributedBuild(
new ConstructorArgMarshaller(typeCoercerFactory),
new TargetNodeFactory(typeCoercerFactory),
params.getRuleKeyConfiguration());
DistBuildTargetGraphCodec targetGraphCodec =
new DistBuildTargetGraphCodec(
parserTargetNodeFactory,
input -> {
return params
.getParser()
.getRawTargetNode(
params.getBuckEventBus(),
params.getCell().getCell(input.getBuildTarget()),
false /* enableProfiling */,
executorService,
input);
},
targetGraphAndBuildTargets
.getBuildTargets()
.stream()
.map(t -> t.getFullyQualifiedName())
.collect(Collectors.toSet()));
return new AsyncJobStateAndCells(
distributedBuildFileHashes,
executorService.submit(
() -> {
try {
BuildJobState state =
DistBuildState.dump(
cellIndexer,
distributedBuildFileHashes,
targetGraphCodec,
targetGraphAndBuildTargets.getTargetGraph(),
buildTargets,
clientStatsTracker);
LOG.info("Finished computing serializable distributed build state.");
return state;
} catch (InterruptedException ex) {
LOG.warn(
ex,
"Failed computing serializable distributed build state as interrupted. Local build probably finished first.");
Thread.currentThread().interrupt();
throw ex;
}
}),
cellIndexer);
}
private ListeningExecutorService createStampedeControllerExecutorService(int maxThreads) {
CommandThreadFactory stampedeCommandThreadFactory =
new CommandThreadFactory("StampedeController");
return MoreExecutors.listeningDecorator(
newMultiThreadExecutor(stampedeCommandThreadFactory, maxThreads));
}
private ListeningExecutorService createStampedeLocalBuildExecutorService() {
CommandThreadFactory stampedeCommandThreadFactory =
new CommandThreadFactory("StampedeLocalBuild");
return MoreExecutors.listeningDecorator(
MostExecutors.newSingleThreadExecutor(stampedeCommandThreadFactory));
}
private ExitCode executeDistBuild(
CommandRunnerParams params,
DistBuildConfig distBuildConfig,
ActionAndTargetGraphs graphs,
WeightedListeningExecutorService executorService,
ProjectFilesystem filesystem,
FileHashCache fileHashCache,
ClientStatsTracker distBuildClientStats,
RuleKeyCacheScope<RuleKey> ruleKeyCacheScope)
throws IOException, InterruptedException {
Preconditions.checkNotNull(distBuildClientEventListener);
Preconditions.checkArgument(
(distBuildConfig.getPerformRuleKeyConsistencyCheck()
&& distBuildConfig.getLogMaterializationEnabled())
|| !distBuildConfig.getPerformRuleKeyConsistencyCheck(),
"Log materialization must be enabled to perform rule key consistency check.");
if (distributedBuildStateFile == null
&& distBuildConfig.getBuildMode().equals(BuildMode.DISTRIBUTED_BUILD_WITH_LOCAL_COORDINATOR)
&& !distBuildConfig.getMinionQueue().isPresent()) {
throw new HumanReadableException(
"Stampede Minion Queue name must be specified to use Local Coordinator Mode.");
}
BuildEvent.DistBuildStarted started = BuildEvent.distBuildStarted();
params.getBuckEventBus().post(started);
LOG.info("Starting async file hash computation and job state serialization.");
AsyncJobStateAndCells stateAndCells =
computeDistBuildState(params, graphs, executorService, Optional.of(distBuildClientStats));
ListenableFuture<BuildJobState> asyncJobState = stateAndCells.asyncJobState;
DistBuildCellIndexer distBuildCellIndexer = stateAndCells.distBuildCellIndexer;
if (distributedBuildStateFile != null) {
BuildJobState jobState;
try {
jobState = asyncJobState.get();
} catch (ExecutionException e) {
throw new RuntimeException("Failed to compute DistBuildState.", e);
}
// Read all files inline if we're dumping state to a file.
for (BuildJobStateFileHashes cell : jobState.getFileHashes()) {
ProjectFilesystem cellFilesystem =
Preconditions.checkNotNull(
distBuildCellIndexer.getLocalFilesystemsByCellIndex().get(cell.getCellIndex()));
for (BuildJobStateFileHashEntry entry : cell.getEntries()) {
cellFilesystem
.readFileIfItExists(cellFilesystem.resolve(entry.getPath().getPath()))
.ifPresent(contents -> entry.setContents(contents.getBytes()));
}
}
Path stateDumpPath = Paths.get(distributedBuildStateFile);
BuildJobStateSerializer.serialize(jobState, filesystem.newFileOutputStream(stateDumpPath));
return ExitCode.SUCCESS;
}
BuckVersion buckVersion = getBuckVersion();
Preconditions.checkArgument(params.getInvocationInfo().isPresent());
distBuildClientStats.setIsLocalFallbackBuildEnabled(
distBuildConfig.isSlowLocalBuildFallbackModeEnabled());
try (DistBuildService distBuildService = DistBuildFactory.newDistBuildService(params)) {
ListeningExecutorService stampedeControllerExecutor =
createStampedeControllerExecutorService(distBuildConfig.getControllerMaxThreadCount());
ListeningExecutorService stampedeLocalBuildExecutor =
createStampedeLocalBuildExecutorService();
LogStateTracker distBuildLogStateTracker =
DistBuildFactory.newDistBuildLogStateTracker(
params.getInvocationInfo().get().getLogDirectoryPath(), filesystem, distBuildService);
DistBuildControllerArgs.Builder distBuildControllerArgsBuilder =
DistBuildControllerArgs.builder()
.setBuilderExecutorArgs(params.createBuilderArgs())
.setBuckEventBus(params.getBuckEventBus())
.setTopLevelTargets(buildTargets)
.setBuildGraphs(graphs)
.setCachingBuildEngineDelegate(
Optional.of(new LocalCachingBuildEngineDelegate(params.getFileHashCache())))
.setAsyncJobState(asyncJobState)
.setDistBuildCellIndexer(distBuildCellIndexer)
.setDistBuildService(distBuildService)
.setDistBuildLogStateTracker(distBuildLogStateTracker)
.setBuckVersion(buckVersion)
.setDistBuildClientStats(distBuildClientStats)
.setScheduler(params.getScheduledExecutor())
.setMaxTimeoutWaitingForLogsMillis(
distBuildConfig.getMaxWaitForRemoteLogsToBeAvailableMillis())
.setLogMaterializationEnabled(distBuildConfig.getLogMaterializationEnabled())
.setBuildLabel(distBuildConfig.getBuildLabel());
LocalBuildExecutorInvoker localBuildExecutorInvoker =
new LocalBuildExecutorInvoker() {
@Override
public int executeLocalBuild(
boolean isDownloadHeavyBuild,
RemoteBuildRuleCompletionWaiter remoteBuildRuleCompletionWaiter,
CountDownLatch initializeBuildLatch,
AtomicReference<Build> buildReference)
throws IOException, InterruptedException {
return BuildCommand.this
.executeLocalBuild(
params,
graphs.getActionGraphAndResolver(),
executorService,
Optional.empty(),
remoteBuildRuleCompletionWaiter,
isDownloadHeavyBuild,
Optional.of(initializeBuildLatch),
ruleKeyCacheScope,
buildReference)
.getCode();
}
};
DistBuildControllerInvocationArgs distBuildControllerInvocationArgs =
DistBuildControllerInvocationArgs.builder()
.setExecutorService(stampedeControllerExecutor)
.setProjectFilesystem(filesystem)
.setFileHashCache(fileHashCache)
.setInvocationInfo(params.getInvocationInfo().get())
.setBuildMode(distBuildConfig.getBuildMode())
.setNumberOfMinions(distBuildConfig.getNumberOfMinions())
.setRepository(distBuildConfig.getRepository())
.setTenantId(distBuildConfig.getTenantId())
.setRuleKeyCalculatorFuture(localRuleKeyCalculator)
.build();
// TODO(alisdair): ensure minion build status recorded even if local build finishes first.
boolean waitForDistBuildThreadToFinishGracefully =
distBuildConfig.getLogMaterializationEnabled();
StampedeBuildClient stampedeBuildClient =
new StampedeBuildClient(
params.getBuckEventBus(),
stampedeLocalBuildExecutor,
stampedeControllerExecutor,
distBuildService,
started,
localBuildExecutorInvoker,
distBuildControllerArgsBuilder,
distBuildControllerInvocationArgs,
waitForDistBuildThreadToFinishGracefully);
distBuildClientStats.startTimer(PERFORM_LOCAL_BUILD);
// Perform either a single phase build that waits for all remote artifacts before proceeding,
// or a two stage build where local build first races against remote, and depending on
// progress either completes first or falls back to build that waits for remote artifacts.
boolean skipRacingBuild =
distBuildConfig.shouldAlwaysWaitForRemoteBuildBeforeProceedingLocally();
int localExitCode =
stampedeBuildClient.build(
skipRacingBuild, distBuildConfig.isSlowLocalBuildFallbackModeEnabled());
// All local/distributed build steps are now finished.
StampedeId stampedeId = stampedeBuildClient.getStampedeId();
int distributedBuildExitCode = stampedeBuildClient.getDistBuildExitCode();
distBuildClientStats.setStampedeId(stampedeId.getId());
distBuildClientStats.setDistributedBuildExitCode(distributedBuildExitCode);
// Set local build stats
distBuildClientStats.setPerformedLocalBuild(true);
distBuildClientStats.stopTimer(PERFORM_LOCAL_BUILD);
distBuildClientStats.setLocalBuildExitCode(localExitCode);
// If local build finished before hashing was complete, it's important to cancel
// related Futures to avoid this operation blocking forever.
stateAndCells.cancel();
// stampedeControllerExecutor is now redundant. Kill it as soon as possible.
killExecutor(
stampedeControllerExecutor,
("Stampede controller executor service still running after build finished"
+ " and timeout elapsed. Terminating.."));
killExecutor(
stampedeLocalBuildExecutor,
("Stampede local build executor service still running after build finished"
+ " and timeout elapsed. Terminating.."));
// Publish details about all default rule keys that were cache misses.
// A non-zero value suggests a problem that needs investigating.
try {
Set<String> cacheMissRequestKeys =
distBuildClientEventListener.getDefaultCacheMissRequestKeys();
ArtifactCacheBuckConfig artifactCacheBuckConfig =
ArtifactCacheBuckConfig.of(distBuildConfig.getBuckConfig());
List<RuleKeyLogEntry> ruleKeyLogs =
distBuildService.fetchRuleKeyLogs(
cacheMissRequestKeys,
artifactCacheBuckConfig.getRepository(),
artifactCacheBuckConfig.getScheduleType(),
true /* distributedBuildModeEnabled */);
params
.getBuckEventBus()
.post(distBuildClientEventListener.createDistBuildClientCacheResultsEvent(ruleKeyLogs));
} catch (Exception ex) {
LOG.error("Failed to publish distributed build client cache request event", ex);
}
boolean ruleKeyConsistencyChecksPassedOrSkipped =
performStampedePostBuildAnalysisAndRuleKeyConsistencyChecks(
params,
distBuildConfig,
filesystem,
distBuildClientStats,
stampedeId,
distributedBuildExitCode,
localExitCode,
distBuildLogStateTracker);
int finalExitCode = localExitCode;
if (!ruleKeyConsistencyChecksPassedOrSkipped) {
finalExitCode =
com.facebook.buck.distributed.ExitCode.RULE_KEY_CONSISTENCY_CHECK_FAILED.getCode();
}
// Post distributed build phase starts POST_DISTRIBUTED_BUILD_LOCAL_STEPS counter internally.
if (distributedBuildExitCode == 0) {
distBuildClientStats.stopTimer(POST_DISTRIBUTED_BUILD_LOCAL_STEPS);
}
if (distBuildClientStats.hasStampedeId()) {
params
.getBuckEventBus()
.post(new DistBuildClientStatsEvent(distBuildClientStats.generateStats()));
}
return ExitCode.map(finalExitCode);
}
}
private void killExecutor(
ListeningExecutorService stampedeControllerExecutor, String failureWarning)
throws InterruptedException {
stampedeControllerExecutor.shutdown();
if (!stampedeControllerExecutor.awaitTermination(
STAMPEDE_EXECUTOR_SHUTDOWN_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
LOG.warn(failureWarning);
stampedeControllerExecutor.shutdownNow();
}
}
private boolean performStampedePostBuildAnalysisAndRuleKeyConsistencyChecks(
CommandRunnerParams params,
DistBuildConfig distBuildConfig,
ProjectFilesystem filesystem,
ClientStatsTracker distBuildClientStats,
StampedeId stampedeId,
int distributedBuildExitCode,
int localBuildExitCode,
LogStateTracker distBuildLogStateTracker)
throws IOException {
// If we are pulling down remote logs, and the distributed build finished successfully,
// then perform analysis
if (distBuildConfig.getLogMaterializationEnabled()
&& distributedBuildExitCode == 0
&& localBuildExitCode == 0) {
distBuildClientStats.startTimer(POST_BUILD_ANALYSIS);
DistBuildPostBuildAnalysis postBuildAnalysis =
new DistBuildPostBuildAnalysis(
params.getInvocationInfo().get().getBuildId(),
stampedeId,
filesystem.resolve(params.getInvocationInfo().get().getLogDirectoryPath()),
distBuildLogStateTracker.getBuildSlaveLogsMaterializer().getMaterializedRunIds(),
DistBuildCommand.class.getSimpleName().toLowerCase());
LOG.info("Created DistBuildPostBuildAnalysis");
AnalysisResults results = postBuildAnalysis.runAnalysis();
Path analysisSummaryFile = postBuildAnalysis.dumpResultsToLogFile(results);
distBuildClientStats.stopTimer(POST_BUILD_ANALYSIS);
LOG.info(String.format("Dumped DistBuildPostBuildAnalysis to [%s]", analysisSummaryFile));
Path relativePathToSummaryFile = filesystem.getRootPath().relativize(analysisSummaryFile);
params
.getBuckEventBus()
.post(
ConsoleEvent.warning(
"Details of distributed build analysis: %s",
relativePathToSummaryFile.toString()));
LOG.info(
"Number of mismatching default rule keys: " + results.numMismatchingDefaultRuleKeys());
if (distBuildConfig.getPerformRuleKeyConsistencyCheck()
&& results.numMismatchingDefaultRuleKeys() > 0) {
params
.getBuckEventBus()
.post(
ConsoleEvent.severe(
"*** [%d] default rule keys mismatched between client and server. *** \nMismatching rule keys:",
results.numMismatchingDefaultRuleKeys()));
for (RuleKeyNameAndType ruleKeyNameAndType :
postBuildAnalysis.getMismatchingDefaultRuleKeys(results)) {
params
.getBuckEventBus()
.post(
ConsoleEvent.severe(
"MISMATCHING RULE: %s [%s]",
ruleKeyNameAndType.getRuleName(), ruleKeyNameAndType.getRuleType()));
}
return false; // Rule keys were not consistent
}
}
return true; // Rule keys were consistent, or test was skipped.
}
private BuckVersion getBuckVersion() throws IOException {
if (buckBinary == null) {
String gitHash = System.getProperty(BUCK_GIT_COMMIT_KEY, null);
if (gitHash == null) {
throw new CommandLineException(
String.format(
"Property [%s] is not set and the command line flag [%s] was not passed.",
BUCK_GIT_COMMIT_KEY, BUCK_BINARY_STRING_ARG));
}
return BuckVersionUtil.createFromGitHash(gitHash);
}
Path binaryPath = Paths.get(buckBinary);
if (!Files.isRegularFile(binaryPath)) {
throw new CommandLineException(
String.format(
"Buck binary [%s] passed under flag [%s] does not exist.",
binaryPath, BUCK_BINARY_STRING_ARG));
}
return BuckVersionUtil.createFromLocalBinary(binaryPath);
}
private void showOutputs(
CommandRunnerParams params,
ActionGraphAndResolver actionGraphAndResolver,
RuleKeyCacheScope<RuleKey> ruleKeyCacheScope)
throws IOException {
TreeMap<String, String> sortedJsonOutputs = new TreeMap<String, String>();
Optional<DefaultRuleKeyFactory> ruleKeyFactory = Optional.empty();
SourcePathRuleFinder ruleFinder =
new SourcePathRuleFinder(actionGraphAndResolver.getResolver());
SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
if (showRuleKey) {
RuleKeyFieldLoader fieldLoader = new RuleKeyFieldLoader(params.getRuleKeyConfiguration());
ruleKeyFactory =
Optional.of(
new DefaultRuleKeyFactory(
fieldLoader,
params.getFileHashCache(),
pathResolver,
ruleFinder,
ruleKeyCacheScope.getCache(),
Optional.empty()));
}
for (BuildTarget buildTarget : buildTargets) {
BuildRule rule = actionGraphAndResolver.getResolver().requireRule(buildTarget);
Optional<Path> outputPath =
TargetsCommand.getUserFacingOutputPath(
pathResolver, rule, params.getBuckConfig().getBuckOutCompatLink())
.map(
path ->
showFullOutput || showFullJsonOutput
? path
: params.getCell().getFilesystem().relativize(path));
params.getConsole().getStdOut().flush();
if (showJsonOutput || showFullJsonOutput) {
sortedJsonOutputs.put(
rule.getFullyQualifiedName(), outputPath.map(Object::toString).orElse(""));
} else {
params
.getConsole()
.getStdOut()
.printf(
"%s%s%s\n",
rule.getFullyQualifiedName(),
showRuleKey ? " " + ruleKeyFactory.get().build(rule).toString() : "",
showOutput || showFullOutput
? " " + outputPath.map(Object::toString).orElse("")
: "");
}
}
if (showJsonOutput || showFullJsonOutput) {
// Print the build rule information as JSON.
StringWriter stringWriter = new StringWriter();
ObjectMappers.WRITER.withDefaultPrettyPrinter().writeValue(stringWriter, sortedJsonOutputs);
String output = stringWriter.getBuffer().toString();
params.getConsole().getStdOut().println(output);
}
}
private TargetGraphAndBuildTargets createUnversionedTargetGraph(
CommandRunnerParams params, ListeningExecutorService executor)
throws IOException, InterruptedException, ActionGraphCreationException {
// Parse the build files to create a ActionGraph.
ParserConfig parserConfig = params.getBuckConfig().getView(ParserConfig.class);
try {
return params
.getParser()
.buildTargetGraphForTargetNodeSpecs(
params.getBuckEventBus(),
params.getCell(),
getEnableParserProfiling(),
executor,
parseArgumentsAsTargetNodeSpecs(params.getBuckConfig(), getArguments()),
parserConfig.getDefaultFlavorsMode());
} catch (BuildTargetException e) {
throw new ActionGraphCreationException(MoreExceptions.getHumanReadableOrLocalizedMessage(e));
}
}
private ActionGraphAndResolver createActionGraphAndResolver(
CommandRunnerParams params,
TargetGraphAndBuildTargets targetGraphAndBuildTargets,
Optional<ThriftRuleKeyLogger> ruleKeyLogger,
CloseableMemoizedSupplier<ForkJoinPool, RuntimeException> poolSupplier)
throws ActionGraphCreationException {
buildTargets = targetGraphAndBuildTargets.getBuildTargets();
buildTargetsHaveBeenCalculated = true;
ActionGraphAndResolver actionGraphAndResolver =
params
.getActionGraphCache()
.getActionGraph(
params.getBuckEventBus(),
targetGraphAndBuildTargets.getTargetGraph(),
params.getBuckConfig(),
params.getRuleKeyConfiguration(),
ruleKeyLogger,
poolSupplier);
// If the user specified an explicit build target, use that.
if (justBuildTarget != null) {
BuildTarget explicitTarget =
BuildTargetParser.INSTANCE.parse(
justBuildTarget,
BuildTargetPatternParser.fullyQualified(),
params.getCell().getCellPathResolver());
Iterable<BuildRule> actionGraphRules =
Preconditions.checkNotNull(actionGraphAndResolver.getActionGraph().getNodes());
ImmutableSet<BuildTarget> actionGraphTargets =
ImmutableSet.copyOf(Iterables.transform(actionGraphRules, BuildRule::getBuildTarget));
if (!actionGraphTargets.contains(explicitTarget)) {
throw new ActionGraphCreationException(
"Targets specified via `--just-build` must be a subset of action graph.");
}
buildTargets = ImmutableSet.of(explicitTarget);
}
return actionGraphAndResolver;
}
protected ExitCode executeLocalBuild(
CommandRunnerParams params,
ActionGraphAndResolver actionGraphAndResolver,
WeightedListeningExecutorService executor,
Optional<ThriftRuleKeyLogger> ruleKeyLogger,
RemoteBuildRuleCompletionWaiter remoteBuildRuleCompletionWaiter,
boolean isDownloadHeavyBuild,
Optional<CountDownLatch> initializeBuildLatch,
RuleKeyCacheScope<RuleKey> ruleKeyCacheScope,
AtomicReference<Build> buildReference)
throws IOException, InterruptedException {
LocalBuildExecutor builder =
new LocalBuildExecutor(
params.createBuilderArgs(),
getExecutionContext(),
actionGraphAndResolver,
new LocalCachingBuildEngineDelegate(params.getFileHashCache()),
executor,
isKeepGoing(),
useDistributedBuild,
isDownloadHeavyBuild,
ruleKeyCacheScope,
getBuildEngineMode(),
ruleKeyLogger,
remoteBuildRuleCompletionWaiter);
buildReference.set(builder.getBuild());
// TODO(alisdair): ensure that all Stampede local builds re-use same calculator
localRuleKeyCalculator.set(builder.getCachingBuildEngine().getRuleKeyCalculator());
if (initializeBuildLatch.isPresent()) {
// Signal to other threads that lastBuild has now been set.
initializeBuildLatch.get().countDown();
}
List<String> targetStrings =
FluentIterable.from(buildTargets)
.append(getAdditionalTargetsToBuild(actionGraphAndResolver.getResolver()))
.transform(target -> target.getFullyQualifiedName())
.toList();
int code =
builder.buildLocallyAndReturnExitCode(
targetStrings, getPathToBuildReport(params.getBuckConfig()));
builder.shutdown();
return ExitCode.map(code);
}
RuleKeyCacheScope<RuleKey> getDefaultRuleKeyCacheScope(
CommandRunnerParams params, ActionGraphAndResolver actionGraphAndResolver) {
return getDefaultRuleKeyCacheScope(
params,
new RuleKeyCacheRecycler.SettingsAffectingCache(
params.getBuckConfig().getKeySeed(), actionGraphAndResolver.getActionGraph()));
}
@Override
protected ExecutionContext.Builder getExecutionContextBuilder(CommandRunnerParams params) {
return super.getExecutionContextBuilder(params)
.setTargetDevice(Optional.empty())
.setCodeCoverageEnabled(isCodeCoverageEnabled())
.setDebugEnabled(isDebugEnabled())
.setShouldReportAbsolutePaths(shouldReportAbsolutePaths());
}
@SuppressWarnings("unused")
protected Iterable<BuildTarget> getAdditionalTargetsToBuild(BuildRuleResolver resolver) {
return ImmutableList.of();
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
public boolean isSourceControlStatsGatheringEnabled() {
return true;
}
Build getBuild() {
return Preconditions.checkNotNull(lastBuild.get());
}
public ImmutableList<BuildTarget> getBuildTargets() {
Preconditions.checkState(buildTargetsHaveBeenCalculated);
return ImmutableList.copyOf(buildTargets);
}
@Override
public String getShortDescription() {
return "builds the specified target";
}
@Override
public Iterable<BuckEventListener> getEventListeners(
Map<ExecutorPool, ListeningExecutorService> executorPool,
ScheduledExecutorService scheduledExecutorService) {
ImmutableList.Builder<BuckEventListener> listeners = ImmutableList.builder();
if (useDistributedBuild) {
distBuildClientEventListener = new DistBuildClientEventListener();
listeners.add(distBuildClientEventListener);
}
return listeners.build();
}
private static class AsyncJobStateAndCells {
final DistBuildFileHashes distributedBuildFileHashes;
final ListenableFuture<BuildJobState> asyncJobState;
final DistBuildCellIndexer distBuildCellIndexer;
AsyncJobStateAndCells(
DistBuildFileHashes distributedBuildFileHashes,
ListenableFuture<BuildJobState> asyncJobState,
DistBuildCellIndexer cellIndexer) {
this.distributedBuildFileHashes = distributedBuildFileHashes;
this.asyncJobState = asyncJobState;
this.distBuildCellIndexer = cellIndexer;
}
// Cancels any ongoing Future operations
protected void cancel() {
distributedBuildFileHashes.cancel();
asyncJobState.cancel(true);
}
}
public static class ActionGraphCreationException extends Exception {
public ActionGraphCreationException(String message) {
super(message);
}
}
}
| Add logging around cache miss rule key log fetching
Summary: This will allow us to see how long this step is taking.
Test Plan: ci
Reviewed By: shivanker
fbshipit-source-id: 6120150
| src/com/facebook/buck/cli/BuildCommand.java | Add logging around cache miss rule key log fetching |
|
Java | apache-2.0 | c30472f657c443ba109ed7de3534606953fbc83c | 0 | rcmoutinho/javatohtml | package br.com.javatohtml.core;
import static br.com.javatohtml.core.JavaToHtml.*;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* Unit test for {@link JavaToHtml}.
*
* @rcmoutinho
* @author rodrigo.moutinho
* @date 8 de fev de 2017
* @email [email protected]
*/
public class JavaToHtmlTest {
@Test
public void testCreatingA() {
assertEquals("<a></a>", a().toHtml());
}
@Test
public void testCreatingBr() {
assertEquals("<br />", br().toHtml());
}
@Test
public void testCreatingDiv() {
assertEquals("<div></div>", div().toHtml());
}
@Test
public void testCreatingEm() {
assertEquals("<em></em>", em().toHtml());
assertEquals("<em>text</em>", em("text").toHtml());
}
@Test
public void testCreatingH1() {
assertEquals("<h1></h1>", h1().toHtml());
}
@Test
public void testCreatingh2() {
assertEquals("<h2></h2>", h2().toHtml());
}
@Test
public void testCreatingh3() {
assertEquals("<h3></h3>", h3().toHtml());
}
@Test
public void testCreatinghr() {
assertEquals("<hr />", hr().toHtml());
}
@Test
public void testCreatingImg() {
assertEquals("<img />", img().toHtml());
}
@Test
public void testCreatingP() {
assertEquals("<p></p>", p().toHtml());
assertEquals("<p>text</p>", p("text").toHtml());
}
@Test
public void testCreatingSpan() {
assertEquals("<span></span>", span().toHtml());
}
@Test
public void testCreatingStrong() {
assertEquals("<strong></strong>", strong().toHtml());
assertEquals("<strong>text</strong>", strong("text").toHtml());
}
@Test
public void testCreatingTable() {
assertEquals("<table></table>", table().toHtml());
}
@Test
public void testCreatingTag() {
assertEquals("<name></name>", tag("name").toHtml());
}
@Test
public void testCreatingTbody() {
assertEquals("<tbody></tbody>", tbody().toHtml());
}
@Test
public void testCreatingTd() {
assertEquals("<td></td>", td().toHtml());
assertEquals("<td>text</td>", td("text").toHtml());
assertEquals("<td><span></span></td>", td(span()).toHtml());
}
@Test
public void testCreatingTfoot() {
assertEquals("<tfoot></tfoot>", tfoot().toHtml());
}
@Test
public void testCreatingTh() {
assertEquals("<th></th>", th().toHtml());
assertEquals("<th>text</th>", th("text").toHtml());
assertEquals("<th><span></span></th>", th(span()).toHtml());
}
@Test
public void testCreatingThead() {
assertEquals("<thead></thead>", thead().toHtml());
}
@Test
public void testCreatingTr() {
assertEquals("<tr></tr>", tr().toHtml());
}
}
| src/test/java/br/com/javatohtml/core/JavaToHtmlTest.java | package br.com.javatohtml.core;
/**
* Unit test for {@link JavaToHtml}.
*
* @rcmoutinho
* @author rodrigo.moutinho
* @date 8 de fev de 2017
* @email [email protected]
*/
public class JavaToHtmlTest {
}
| Unit tests for JavaToHtml
| src/test/java/br/com/javatohtml/core/JavaToHtmlTest.java | Unit tests for JavaToHtml |
|
Java | bsd-3-clause | 29122c88cb4a81e0f0d4e129f54f97b49668d9b6 | 0 | joansmith/basex,joansmith/basex,JensErat/basex,ksclarke/basex,deshmnnit04/basex,drmacro/basex,BaseXdb/basex,vincentml/basex,joansmith/basex,JensErat/basex,JensErat/basex,drmacro/basex,ksclarke/basex,ksclarke/basex,joansmith/basex,ksclarke/basex,drmacro/basex,vincentml/basex,ksclarke/basex,JensErat/basex,deshmnnit04/basex,JensErat/basex,JensErat/basex,BaseXdb/basex,dimitarp/basex,JensErat/basex,joansmith/basex,drmacro/basex,ksclarke/basex,deshmnnit04/basex,drmacro/basex,deshmnnit04/basex,vincentml/basex,dimitarp/basex,dimitarp/basex,joansmith/basex,dimitarp/basex,vincentml/basex,vincentml/basex,dimitarp/basex,drmacro/basex,deshmnnit04/basex,JensErat/basex,dimitarp/basex,drmacro/basex,JensErat/basex,joansmith/basex,BaseXdb/basex,deshmnnit04/basex,deshmnnit04/basex,ksclarke/basex,BaseXdb/basex,BaseXdb/basex,deshmnnit04/basex,drmacro/basex,ksclarke/basex,BaseXdb/basex,ksclarke/basex,dimitarp/basex,joansmith/basex,vincentml/basex,drmacro/basex,deshmnnit04/basex,ksclarke/basex,vincentml/basex,joansmith/basex,BaseXdb/basex,vincentml/basex,JensErat/basex,ksclarke/basex,dimitarp/basex,dimitarp/basex,deshmnnit04/basex,vincentml/basex,vincentml/basex,JensErat/basex,vincentml/basex,BaseXdb/basex,vincentml/basex,joansmith/basex,dimitarp/basex,deshmnnit04/basex,JensErat/basex,joansmith/basex,ksclarke/basex,BaseXdb/basex,BaseXdb/basex,dimitarp/basex,drmacro/basex,joansmith/basex,dimitarp/basex,deshmnnit04/basex,BaseXdb/basex,drmacro/basex,drmacro/basex,BaseXdb/basex | package org.basex.query.fs;
import static org.basex.util.Token.*;
import java.io.IOException;
import org.basex.BaseX;
import org.basex.core.Prop;
import org.basex.data.Data;
import org.basex.util.IntList;
import org.basex.util.Token;
import org.basex.util.TokenBuilder;
/**
* Preliminary collection of file system methods.
*
* @author Workgroup DBIS, University of Konstanz 2005-08, ISC License
* @author Christian Gruen
*/
public final class FSUtils {
/** Private constructor, preventing class instances. */
private FSUtils() { }
/**
* Checks if the specified node is a file.
* @param data data reference
* @param pre pre value
* @return result of comparison
*/
public static boolean isFile(final Data data, final int pre) {
return data.kind(pre) == Data.ELEM && data.tagID(pre) == data.fileID;
}
/**
* Checks if the specified node is a directory.
* @param data data reference
* @param pre pre value
* @return result of comparison
*/
public static boolean isDir(final Data data, final int pre) {
return data.kind(pre) == Data.ELEM && data.tagID(pre) == data.dirID;
}
/**
* Returns the size of a file.
* @param data data reference
* @param pre pre value
* @return file size
*/
public static long getSize(final Data data, final int pre) {
final byte[] att = data.attValue(data.sizeID, pre);
return att != null ? toLong(att) : 0;
}
/**
* Returns the path of a file.
* @param data data reference
* @param pre pre value
* @return file path.
*/
public static byte[] getPath(final Data data, final int pre) {
int p = pre;
final IntList il = new IntList();
while(p != 0) {
il.add(p);
final int kind = data.kind(p);
p = data.parent(p, kind);
}
final TokenBuilder tb = new TokenBuilder();
final int s = il.size;
for(int i = s - 2; i >= 0; i--) {
final byte[] node = replace(getName(data, il.get(i)), '\\', '/');
tb.add(node);
if(!endsWith(node, '/')) tb.add('/');
}
byte[] node = tb.finish();
while(endsWith(node, '/')) node = substring(node, 0, node.length - 1);
return node;
}
/**
* Returns the name of a file.
* @param data data reference
* @param pre pre value
* @return file name.
*/
public static byte[] getName(final Data data, final int pre) {
final byte[] att = data.attValue(data.nameID, pre);
return att != null ? att : EMPTY;
}
/**
* Returns the suffix of a file.
* @param data data reference
* @param pre pre value
* @return file name.
*/
public static byte[] getSuffix(final Data data, final int pre) {
final byte[] att = data.attValue(data.suffixID, pre);
return att != null ? att : EMPTY;
}
/**
* Returns all directories and files of a directory.
*
* @param data - the data table
* @param pre - pre value of the "parent" directory
* @return - all pre values of the dirs and files
*/
public static int[] getAllOfDir(final Data data, final int pre) {
// Den Elementtyp einmal speichern
int kind = data.kind(pre);
int n = pre;
// Wie weit das Verzeichnis reicht
int size = data.size(n, kind) + n;
// Zu erstem file/dir springen
n += data.attSize(n, kind);
// Ergebnisarray
// <HS> ..calculation size/5 is dubious as XML structure might change,
// (e.g. if file contents are included)..
IntList res = new IntList();
while(n < size) {
// pre speichern
res.add(n);
n += data.size(n, data.kind(n));
}
return res.finish();
}
/**
* Returns all files of a directory.
*
* @param data - the data table
* @param pre - pre value of the "parent" directory
* @return - all pre values of all files
*/
public static int[] getAllFiles(final Data data, final int pre) {
// Den Elementtyp einmal speichern
int kind = data.kind(pre);
int n = pre;
// Wie weit das Verzeichnis reicht
int size = data.size(n, kind) + n;
// Zu erstem file/dir springen
n += data.attSize(n, kind);
// Ergebnisarray
IntList res = new IntList();
while(n < size) {
if(isFile(data , n)) {
// pre speichern
res.add(n);
}
n += data.size(n, data.kind(n));
}
return res.finish();
}
/**
* Returns all directories of a directory.
*
* @param data - the data table
* @param pre - pre value of the "parent" directory
* @return - all pre values of all files
*/
public static int[] getAllDir(final Data data, final int pre) {
// Den Elementtyp einmal speichern
int kind = data.kind(pre);
int n = pre;
// Wie weit das Verzeichnis reicht
int size = data.size(n, kind) + n;
// Zu erstem file/dir springen
n += data.attSize(n, kind);
// Ergebnisarray
IntList res = new IntList();
while(n < size) {
if(isDir(data , n)) {
// pre speichern
res.add(n);
}
n += data.size(n, kind);
}
return res.finish();
}
/**
* Returns the pre value of a dir.
*
* @param data - the data table
* @param pre - pre value of the "parent" directory
* @param dir - directory name
* @param kind - kind value of dir (elem)
* @return - all pre values of all files
*/
public static int getSpecificFile(final Data data, final int pre,
final byte[] dir, final int kind) {
int n = pre;
// Wie weit das Verzeichnis reicht
int size = data.size(n, kind) + n;
// Zu erstem file/dir springen
n += data.attSize(n, data.kind(n));
while(n < size) {
if(isFile(data , n)) {
// pre speichern
if(Token.eq(getName(data, n), dir)) {
return n;
}
}
n += data.size(n, kind);
}
return -1;
}
/**
* Returns the pre value of a dir.
*
* @param data - the data table
* @param pre - pre value of the "parent" directory
* @param dir - directory name
* @param kind - kind value of dir (elem)
* @return - all pre values of all files
*/
public static int getSpecificDir(final Data data, final int pre,
final byte[] dir, final int kind) {
int n = pre;
// Wie weit das Verzeichnis reicht
int size = data.size(n, kind) + n;
// Zu erstem file/dir springen
n += data.attSize(n, data.kind(n));
while(n < size) {
if(isDir(data , n)) {
// pre speichern
// <CG> using byte comparison to avoid byte/string conversion
if(Token.eq(getName(data, n), dir)) {
return n;
}
}
n += data.size(n, kind);
}
return -1;
}
/**
* Test pathexpression.
*
* @param data - data table
* @param pre - pre value
* @param path - path expression
* @return pre value of the result dir
*/
public static int goToDir(final Data data, final int pre, final String path) {
int n = pre;
int kind = data.kind(pre);
// No path -> return the same dir
if(path.length() < 1) {
return pre;
}
// Seperate path expression
String[] paths = path.split("/");
for(String p : paths) {
// Parent directory
if(p.equals("..")) {
n = data.parent(n, kind);
// / was first char of the path - after split it's ""
} else if(p.equals("")) {
n = 3;
// if path equals "." do nothing else getDir
} else if(!p.equals(".")) {
n = getSpecificDir(data, n, Token.token(p), kind);
}
// if there is no such dir return -1
if(n == -1) {
return -1;
}
}
return n;
}
/**
* Splits the Options.
*
* @param options - Options
* @return String[] - all options stored in an array
*/
public static String[] readOptions(final String options) {
String[] opt = options.split(" ");
if(opt.length < 2) {
return null;
}
String[] res = new String[opt.length - 1];
for(int i = 0; i < res.length; i++) {
res[i] = opt[i + 1];
}
return res;
}
/**
* Opens the file which is defined by the specified pre value.
* @param data data reference
* @param pre pre value
*/
public static void launch(final Data data, final int pre) {
if(!data.deepfs || pre == -1 || !isFile(data, pre)) return;
final String path = Token.string(getPath(data, pre));
try {
final Runtime run = Runtime.getRuntime();
if(Prop.UNIX) {
run.exec(new String[] { "open", path });
} else {
run.exec("rundll32.exe url.dll,FileProtocolHandler " + path);
}
} catch(final IOException ex) {
BaseX.debug("Could not open \"%\"", path);
ex.printStackTrace();
}
}
}
| src/org/basex/query/fs/FSUtils.java | package org.basex.query.fs;
import static org.basex.util.Token.*;
import java.io.IOException;
import org.basex.BaseX;
import org.basex.core.Prop;
import org.basex.data.Data;
import org.basex.util.IntList;
import org.basex.util.Token;
import org.basex.util.TokenBuilder;
/**
* Preliminary collection of file system methods.
*
* @author Workgroup DBIS, University of Konstanz 2005-08, ISC License
* @author Christian Gruen
*/
public final class FSUtils {
/** Private constructor, preventing class instances. */
private FSUtils() { }
/**
* Checks if the specified node is a file.
* @param data data reference
* @param pre pre value
* @return result of comparison
*/
public static boolean isFile(final Data data, final int pre) {
return data.kind(pre) == Data.ELEM && data.tagID(pre) == data.fileID;
}
/**
* Checks if the specified node is a directory.
* @param data data reference
* @param pre pre value
* @return result of comparison
*/
public static boolean isDir(final Data data, final int pre) {
return data.kind(pre) == Data.ELEM && data.tagID(pre) == data.dirID;
}
/**
* Returns the size of a file.
* @param data data reference
* @param pre pre value
* @return file size
*/
public static long getSize(final Data data, final int pre) {
final byte[] att = data.attValue(data.sizeID, pre);
return att != null ? toLong(att) : 0;
}
/**
* Returns the path of a file.
* @param data data reference
* @param pre pre value
* @return file path.
*/
public static byte[] getPath(final Data data, final int pre) {
int p = pre;
final IntList il = new IntList();
while(p != 0) {
il.add(p);
final int kind = data.kind(p);
p = data.parent(p, kind);
}
final TokenBuilder tb = new TokenBuilder();
final int s = il.size;
for(int i = s - 2; i >= 0; i--) {
final byte[] node = replace(getName(data, il.get(i)), '\\', '/');
tb.add(node);
if(!endsWith(node, '/')) tb.add('/');
}
byte[] node = tb.finish();
while(endsWith(node, '/')) node = substring(node, 0, node.length - 1);
return node;
}
/**
* Returns the name of a file.
* @param data data reference
* @param pre pre value
* @return file name.
*/
public static byte[] getName(final Data data, final int pre) {
final byte[] att = data.attValue(data.nameID, pre);
return att != null ? att : EMPTY;
}
/**
* Returns the suffix of a file.
* @param data data reference
* @param pre pre value
* @return file name.
*/
public static byte[] getSuffix(final Data data, final int pre) {
final byte[] att = data.attValue(data.suffixID, pre);
return att != null ? att : EMPTY;
}
/**
* Returns all directories and files of a directory.
*
* @param data - the data table
* @param pre - pre value of the "parent" directory
* @return - all pre values of the dirs and files
*/
public static int[] getAllOfDir(final Data data, final int pre) {
// Den Elementtyp einmal speichern
int kind = data.kind(pre);
int n = pre;
// Wie weit das Verzeichnis reicht
int size = data.size(n, kind) + n;
// Zu erstem file/dir springen
n += data.attSize(n, data.kind(n));
// Ergebnisarray
int[] res = new int[((size - n) / 5) + 1];
int i = 0;
while(n < size) {
// pre speichern
res[i++] = n;
n += data.size(n, data.kind(n));
}
return res;
}
/**
* Returns all files of a directory.
*
* @param data - the data table
* @param pre - pre value of the "parent" directory
* @return - all pre values of all files
*/
public static int[] getAllFiles(final Data data, final int pre) {
// Den Elementtyp einmal speichern
int kind = data.kind(pre);
int n = pre;
// Wie weit das Verzeichnis reicht
int size = data.size(n, kind) + n;
// Zu erstem file/dir springen
n += data.attSize(n, data.kind(n));
// Ergebnisarray
int[] res = new int[((size - n) / 5) + 1];
int i = 0;
while(n < size) {
if(isFile(data , n)) {
// pre speichern
res[i++] = n;
}
n += data.size(n, data.kind(n));
}
return res;
}
/**
* Returns all directories of a directory.
*
* @param data - the data table
* @param pre - pre value of the "parent" directory
* @return - all pre values of all files
*/
public static int[] getAllDir(final Data data, final int pre) {
// Den Elementtyp einmal speichern
int kind = data.kind(pre);
int n = pre;
// Wie weit das Verzeichnis reicht
int size = data.size(n, kind) + n;
// Zu erstem file/dir springen
n += data.attSize(n, kind);
// Ergebnisarray
int[] res = new int[((size - n) / 5) + 1];
int i = 0;
while(n < size) {
if(isDir(data , n)) {
// pre speichern
res[i++] = n;
}
n += data.size(n, kind);
}
return res;
}
/**
* Returns the pre value of a dir.
*
* @param data - the data table
* @param pre - pre value of the "parent" directory
* @param dir - directory name
* @param kind - kind value of dir (elem)
* @return - all pre values of all files
*/
public static int getSpecificFile(final Data data, final int pre,
final String dir, final int kind) {
int n = pre;
// Wie weit das Verzeichnis reicht
int size = data.size(n, kind) + n;
// Zu erstem file/dir springen
n += data.attSize(n, data.kind(n));
while(n < size) {
if(isFile(data , n)) {
// pre speichern
if(Token.string(getName(data, n)).equals(dir)) {
return n;
}
}
n += data.size(n, kind);
}
return -1;
}
/**
* Returns the pre value of a dir.
*
* @param data - the data table
* @param pre - pre value of the "parent" directory
* @param dir - directory name
* @param kind - kind value of dir (elem)
* @return - all pre values of all files
*/
public static int getSpecificDir(final Data data, final int pre,
final String dir, final int kind) {
int n = pre;
// Wie weit das Verzeichnis reicht
int size = data.size(n, kind) + n;
// Zu erstem file/dir springen
n += data.attSize(n, data.kind(n));
while(n < size) {
if(isDir(data , n)) {
// pre speichern
if(Token.string(getName(data, n)).equals(dir)) {
return n;
}
}
n += data.size(n, kind);
}
return -1;
}
/**
* Test pathexpression.
*
* @param data - data table
* @param pre - pre value
* @param path - path expression
* @return pre value of the result dir
*/
public static int goToDir(final Data data, final int pre, final String path) {
int n = pre;
int kind = data.kind(pre);
// No path -> return the same dir
if(path.length() < 1) {
return pre;
}
// Seperate path expression
String[] paths = path.split("/");
for(String p : paths) {
// Parent directory
if(p.equalsIgnoreCase("..")) {
n = data.parent(n, kind);
// / was first char of the path - after split it's ""
} else if(p.equalsIgnoreCase("")) {
n = 3;
// if path equals "." do nothing else getDir
} else if(!p.equalsIgnoreCase(".")) {
n = getSpecificDir(data, n, p, kind);
}
// if there is no such dir return -1
if(n == -1) {
return -1;
}
}
return n;
}
/**
* Splits the Options.
*
* @param options - Options
* @return String[] - all options stored in an array
*/
public static String[] readOptions(final String options) {
String[] opt = options.split(" ");
if(opt.length < 2) {
return null;
}
String[] res = new String[opt.length - 1];
for(int i = 0; i < res.length; i++) {
res[i] = opt[i + 1];
}
return res;
}
/**
* Opens the file which is defined by the specified pre value.
* @param data data reference
* @param pre pre value
*/
public static void launch(final Data data, final int pre) {
if(!data.deepfs || pre == -1 || !isFile(data, pre)) return;
final String path = Token.string(getPath(data, pre));
try {
final Runtime run = Runtime.getRuntime();
if(Prop.UNIX) {
run.exec(new String[] { "open", path });
} else {
run.exec("rundll32.exe url.dll,FileProtocolHandler " + path);
}
} catch(final IOException ex) {
BaseX.debug("Could not open \"%\"", path);
ex.printStackTrace();
}
}
}
| just some trifles
| src/org/basex/query/fs/FSUtils.java | just some trifles |
|
Java | mit | 61190766a2020605afa6809b66b8376dee1281b5 | 0 | jruby/jruby-rack,jhstatewide/jruby-rack,jhstatewide/jruby-rack,jhstatewide/jruby-rack,jhstatewide/jruby-rack,jruby/jruby-rack,jruby/jruby-rack,jruby/jruby-rack,jruby/jruby-rack,jruby/jruby-rack | /*
* Copyright (c) 2010-2012 Engine Yard, Inc.
* Copyright (c) 2007-2009 Sun Microsystems, Inc.
* This source code is available under the MIT license.
* See the file LICENSE.txt for details.
*/
package org.jruby.rack.ext;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.rack.RackEnvironment;
import org.jruby.rack.servlet.RewindableInputStream;
import org.jruby.rack.util.ExceptionUtils;
/**
* Native (Java) implementation of a Rack input.
* Available in Ruby as the class <code>JRuby::Rack::Input</code>.
*
* @author nicksieger
*/
@SuppressWarnings("serial")
public class Input extends RubyObject {
static final ObjectAllocator ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new Input(runtime, klass);
}
};
static RubyClass getClass(final Ruby runtime) {
final RubyModule _JRuby_Rack = (RubyModule)
runtime.getModule("JRuby").getConstantAt("Rack");
return (RubyClass) _JRuby_Rack.getConstantAt("Input");
}
protected boolean rewindable;
private InputStream input;
protected int length = 0;
public Input(Ruby runtime, RubyClass klass) {
super(runtime, klass);
}
private void initialize(final RackEnvironment env) {
this.rewindable = env.getContext().getConfig().isRewindable();
try {
setInput( env.getInput() );
}
catch (IOException e) {
throw ExceptionUtils.newIOError(getRuntime(), e);
}
this.length = env.getContentLength();
}
@JRubyMethod(required = 1)
public IRubyObject initialize(final ThreadContext context, final IRubyObject input) {
final Object arg = JavaEmbedUtils.rubyToJava(input);
if ( arg instanceof InputStream ) {
setInput( (InputStream) arg );
}
else if ( arg instanceof RackEnvironment ) {
initialize((RackEnvironment) arg);
}
return context.nil;
}
/**
* gets must be called without arguments and return a string, or nil on EOF.
*/
@JRubyMethod()
public IRubyObject gets(final ThreadContext context) {
try {
final int NEWLINE = 10;
final byte[] bytes = readUntil(NEWLINE, 0);
if ( bytes != null ) {
return context.runtime.newString(new ByteList(bytes, false));
}
else {
return context.nil;
}
}
catch (IOException e) {
throw ExceptionUtils.newIOError(context.runtime, e);
}
}
/**
* read behaves like IO#read. Its signature is read([length, [buffer]]). If given,
* length must be an non-negative Integer (>= 0) or nil, and buffer must be a
* String and may not be nil. If length is given and not nil, then this method
* reads at most length bytes from the input stream. If length is not given or
* nil, then this method reads all data until EOF. When EOF is reached, this
* method returns nil if length is given and not nil, or "" if length is not
* given or is nil. If buffer is given, then the read data will be placed into
* buffer instead of a newly created String object.
*/
@JRubyMethod(optional = 2)
public IRubyObject read(final ThreadContext context, final IRubyObject[] args) {
int readLen = 0;
if ( args.length > 0 ) {
long len = args[0].convertToInteger("to_i").getLongValue();
readLen = (int) Math.min(len, Integer.MAX_VALUE);
}
final RubyString buffer = args.length > 1 ? args[1].convertToString() : null;
try {
final byte[] bytes = readUntil(MATCH_NONE, readLen);
if ( bytes != null ) {
if ( buffer != null ) {
buffer.clear();
buffer.cat(bytes);
return buffer;
}
return context.runtime.newString(new ByteList(bytes, false));
}
return readLen > 0 ? context.nil : RubyString.newEmptyString(context.runtime);
}
catch (IOException e) {
throw ExceptionUtils.newIOError(context.runtime, e);
}
}
/**
* each must be called without arguments and only yield Strings.
*/
@JRubyMethod
public IRubyObject each(final ThreadContext context, final Block block) {
final IRubyObject nil = context.runtime.getNil();
IRubyObject line;
while ( ( line = gets(context) ) != nil ) {
block.yield(context, line);
}
return nil;
}
/**
* rewind must be called without arguments. It rewinds the input stream back
* to the beginning. It must not raise Errno::ESPIPE: that is, it may not be
* a pipe or a socket. Therefore, handler developers must buffer the input
* data into some rewindable object if the underlying input stream is not rewindable.
*/
@JRubyMethod
public IRubyObject rewind(final ThreadContext context) {
if ( input != null ) {
try { // inputStream.rewind if inputStream.respond_to?(:rewind)
final Method rewind = getRewindMethod(input);
if ( rewind != null ) rewind.invoke(input, (Object[]) null);
}
catch (IllegalArgumentException e) {
throw ExceptionUtils.newArgumentError(context.runtime, e);
}
catch (InvocationTargetException e) {
final Throwable target = e.getCause();
if ( target instanceof IOException ) {
throw ExceptionUtils.newIOError(context.runtime, (IOException) target);
}
throw ExceptionUtils.newRuntimeError(context.runtime, target);
}
catch (IllegalAccessException e) { /* NOOP */ }
}
return context.nil;
}
/**
* Returns the size of the input.
*/
@JRubyMethod
public IRubyObject size(final ThreadContext context) {
return context.runtime.newFixnum(length);
}
/**
* Close the input. Exposed only to the Java side because the Rack spec says
* that application code must not call close, so we don't expose a close method to Ruby.
*/
public void close() {
try {
input.close();
}
catch (IOException e) { /* ignore */ }
}
protected void setInput(InputStream input) {
if ( input != null && rewindable && getRewindMethod(input) == null ) {
input = new RewindableInputStream(input);
}
this.input = input;
}
// NOTE: a bit useless now since we're only using RewindableInputStream
// but it should work with a custom stream as well thus left as is ...
private static Method getRewindMethod(InputStream input) {
try {
return input.getClass().getMethod("rewind", (Class<?>[]) null);
}
catch (NoSuchMethodException e) { /* NOOP */ }
catch (SecurityException e) { /* NOOP */ }
return null;
}
private static final int MATCH_NONE = Integer.MAX_VALUE;
private byte[] readUntil(final int match, final int count) throws IOException {
ByteArrayOutputStream bs = null;
int b; long i = 0;
do {
b = input.read();
if ( b == -1 ) break; // EOF
if (bs == null) {
bs = new ByteArrayOutputStream( count == 0 ? 128 : count );
}
bs.write(b);
if ( ++i == count ) break; // read count bytes
} while ( b != match );
return bs == null ? null : bs.toByteArray();
}
}
| src/main/java/org/jruby/rack/ext/Input.java | /*
* Copyright (c) 2010-2012 Engine Yard, Inc.
* Copyright (c) 2007-2009 Sun Microsystems, Inc.
* This source code is available under the MIT license.
* See the file LICENSE.txt for details.
*/
package org.jruby.rack.ext;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.rack.RackEnvironment;
import org.jruby.rack.servlet.RewindableInputStream;
import org.jruby.rack.util.ExceptionUtils;
/**
* Native (Java) implementation of a Rack input.
* Available in Ruby as the class <code>JRuby::Rack::Input</code>.
*
* @author nicksieger
*/
@SuppressWarnings("serial")
public class Input extends RubyObject {
static final ObjectAllocator ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new Input(runtime, klass);
}
};
static RubyClass getClass(final Ruby runtime) {
final RubyModule _JRuby_Rack = (RubyModule)
runtime.getModule("JRuby").getConstantAt("Rack");
return (RubyClass) _JRuby_Rack.getConstantAt("Input");
}
protected boolean rewindable;
private InputStream input;
protected int length = 0;
public Input(Ruby runtime, RubyClass klass) {
super(runtime, klass);
}
private void initialize(final RackEnvironment env) {
this.rewindable = env.getContext().getConfig().isRewindable();
try {
setInput( env.getInput() );
}
catch (IOException e) {
throw ExceptionUtils.newIOError(getRuntime(), e);
}
this.length = env.getContentLength();
}
@JRubyMethod(required = 1)
public IRubyObject initialize(final ThreadContext context, final IRubyObject input) {
final Object arg = JavaEmbedUtils.rubyToJava(input);
if ( arg instanceof InputStream ) {
setInput( (InputStream) arg );
}
else if ( arg instanceof RackEnvironment ) {
initialize((RackEnvironment) arg);
}
return context.nil;
}
/**
* gets must be called without arguments and return a string, or nil on EOF.
*/
@JRubyMethod()
public IRubyObject gets(final ThreadContext context) {
try {
final int NEWLINE = 10;
final byte[] bytes = readUntil(NEWLINE, 0);
if ( bytes != null ) {
return context.runtime.newString(new ByteList(bytes, false));
}
else {
return context.nil;
}
}
catch (IOException io) {
throw context.runtime.newIOErrorFromException(io);
}
}
/**
* read behaves like IO#read. Its signature is read([length, [buffer]]). If given,
* length must be an non-negative Integer (>= 0) or nil, and buffer must be a
* String and may not be nil. If length is given and not nil, then this method
* reads at most length bytes from the input stream. If length is not given or
* nil, then this method reads all data until EOF. When EOF is reached, this
* method returns nil if length is given and not nil, or "" if length is not
* given or is nil. If buffer is given, then the read data will be placed into
* buffer instead of a newly created String object.
*/
@JRubyMethod(optional = 2)
public IRubyObject read(final ThreadContext context, final IRubyObject[] args) {
int readLen = 0;
if ( args.length > 0 ) {
long len = args[0].convertToInteger("to_i").getLongValue();
readLen = (int) Math.min(len, Integer.MAX_VALUE);
}
final RubyString buffer = args.length > 1 ? args[1].convertToString() : null;
try {
final byte[] bytes = readUntil(MATCH_NONE, readLen);
if ( bytes != null ) {
if ( buffer != null ) {
buffer.clear();
buffer.cat(bytes);
return buffer;
}
return context.runtime.newString(new ByteList(bytes, false));
}
return readLen > 0 ? context.nil : RubyString.newEmptyString(context.runtime);
}
catch (IOException io) {
throw context.runtime.newIOErrorFromException(io);
}
}
/**
* each must be called without arguments and only yield Strings.
*/
@JRubyMethod
public IRubyObject each(final ThreadContext context, final Block block) {
final IRubyObject nil = context.runtime.getNil();
IRubyObject line;
while ( ( line = gets(context) ) != nil ) {
block.yield(context, line);
}
return nil;
}
/**
* rewind must be called without arguments. It rewinds the input stream back
* to the beginning. It must not raise Errno::ESPIPE: that is, it may not be
* a pipe or a socket. Therefore, handler developers must buffer the input
* data into some rewindable object if the underlying input stream is not rewindable.
*/
@JRubyMethod
public IRubyObject rewind(final ThreadContext context) {
if ( input != null ) {
try { // inputStream.rewind if inputStream.respond_to?(:rewind)
final Method rewind = getRewindMethod(input);
if ( rewind != null ) rewind.invoke(input, (Object[]) null);
}
catch (IllegalArgumentException e) {
throw context.runtime.newArgumentError(e.getMessage());
}
catch (InvocationTargetException e) {
final Throwable target = e.getCause();
if ( target instanceof IOException ) {
throw context.runtime.newIOErrorFromException((IOException) target);
}
throw context.runtime.newRuntimeError(target.getMessage());
}
catch (IllegalAccessException e) { /* NOOP */ }
}
return context.nil;
}
/**
* Returns the size of the input.
*/
@JRubyMethod
public IRubyObject size(final ThreadContext context) {
return context.runtime.newFixnum(length);
}
/**
* Close the input. Exposed only to the Java side because the Rack spec says
* that application code must not call close, so we don't expose a close method to Ruby.
*/
public void close() {
try {
input.close();
}
catch (IOException e) { /* ignore */ }
}
protected void setInput(InputStream input) {
if ( input != null && rewindable && getRewindMethod(input) == null ) {
input = new RewindableInputStream(input);
}
this.input = input;
}
// NOTE: a bit useless now since we're only using RewindableInputStream
// but it should work with a custom stream as well thus left as is ...
private static Method getRewindMethod(InputStream input) {
try {
return input.getClass().getMethod("rewind", (Class<?>[]) null);
}
catch (NoSuchMethodException e) { /* NOOP */ }
catch (SecurityException e) { /* NOOP */ }
return null;
}
private static final int MATCH_NONE = Integer.MAX_VALUE;
private byte[] readUntil(final int match, final int count) throws IOException {
ByteArrayOutputStream bs = null;
int b; long i = 0;
do {
b = input.read();
if ( b == -1 ) break; // EOF
if (bs == null) {
bs = new ByteArrayOutputStream( count == 0 ? 128 : count );
}
bs.write(b);
if ( ++i == count ) break; // read count bytes
} while ( b != match );
return bs == null ? null : bs.toByteArray();
}
}
| use our exception utils when constructing a RaiseException | src/main/java/org/jruby/rack/ext/Input.java | use our exception utils when constructing a RaiseException |
|
Java | mit | 10b2791e0520b797224b23d20a74885489537bd8 | 0 | hckrtst/TIJ | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package iotester;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Sanket K<[email protected]>
*/
public class IOTester {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Simply read a byte at a time, type more than one character
// and see what happens
System.out.println("Como estas...type something");
int a = 0;
try {
a = System.in.read();
} catch(IOException ex) {
System.out.println("Bad user!");
}
System.out.println("You said:" + (char)a);
// Read two integers from standard input
System.out.print("Type some more: ");
int b = 0,c = 0;
Scanner sc;
sc = new Scanner(System.in);
try {
b = sc.nextInt();
c = sc.nextInt();
System.out.println("You typed " + b + " and " + c);
} catch (InputMismatchException ex) {
System.out.println("Bad user!");
}
// Read a line at a time now
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String line;
try {
while((line = bufferedReader.readLine()) != null && line.length() > 0) {
System.out.println("Got line = " + line);
}
} catch (IOException ex) {
Logger.getLogger(IOTester.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
bufferedReader.close();
} catch (IOException ex) {
Logger.getLogger(IOTester.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
| IOTester/src/iotester/IOTester.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package iotester;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
* @author Sanket K<[email protected]>
*/
public class IOTester {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Como estas...type something");
int a = 0;
try {
a = System.in.read();
} catch(IOException ex) {
System.out.println("Bad user!");
}
System.out.println("You said:" + (char)a);
System.out.print("Type some more: ");
int b = 0,c = 0;
Scanner sc;
sc = new Scanner(System.in);
try {
b = sc.nextInt();
c = sc.nextInt();
System.out.println("You typed " + b + " and " + c);
} catch (InputMismatchException ex) {
System.out.println("Bad user!");
}
}
}
| BufferedReader example
| IOTester/src/iotester/IOTester.java | BufferedReader example |
|
Java | mit | e20cad0ecad8403da0d37bc3b973e8a966d5c167 | 0 | cs2103aug2014-t09-4j/main | //@author A0116320Y
package bakatxt.international;
import java.util.LinkedList;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import bakatxt.core.Database;
import bakatxt.core.Task;
public class BakaTongue {
private static final String BUNDLE_NAME = "bakatxt.international.BakaLanguage";
private static final String SPACE = " ";
private static final String HEADER = "LANGUAGE";
private static final String[] LANGUAGES = { "English", "中文", "한국어", "HINDI" };
private static Locale currentLocale = new Locale("en", "US");
private static ResourceBundle resBundle = ResourceBundle.getBundle(
BUNDLE_NAME, currentLocale);
/**
* Retrieves the information from the specified resource bundle
*
* @param key
* of the <code>String</code> to be retrieved
* @return <code>String</code> from the resource bundle, or
* <code>!KEY!</code> if the key does not exists.
*/
public static String getString(String key) {
try {
return resBundle.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
/**
* Sets the resource bundle according to the language specified.
*
* @param language
* <code>String</code> chosen by the user
*
* @return <code>true</code> if the language specified exists and is
* applied, <code>false</code> when language does not exist and
* default English is applied.
*/
public static boolean setLanguage(String language) {
boolean isSuccessful = true;
switch (language.toLowerCase().trim()) {
case "english" :
case "1" :
currentLocale = new Locale("en", "US");
break;
case "中文" :
case "chinese" :
case "2" :
currentLocale = new Locale("zh", "CN");
break;
case "한국어" :
case "korean" :
case "3" :
currentLocale = new Locale("ko", "KR");
break;
case "hindi" :
case "4" :
currentLocale = new Locale("hi", "IN");
break;
case "wah lao" :
case "singlish" :
currentLocale = new Locale("en", "SG");
break;
default :
currentLocale = new Locale("en", "US");
isSuccessful = false;
}
resBundle = ResourceBundle.getBundle(BUNDLE_NAME, currentLocale);
Database.getInstance().updateLocale(currentLocale.toString());
return isSuccessful;
}
/**
* Enable setting of language directly based on specifying locale and
* region. Used to set language from preferences stored in the storage file.
*
* @param lang
* <code>String</code> containing locale language code
* @param region
* <code>String</code> containing locale region code
*/
public static void setLanguage(String lang, String region) {
currentLocale = new Locale(lang.trim(), region.trim());
resBundle = ResourceBundle.getBundle(BUNDLE_NAME, currentLocale);
}
/**
* Enables pseudo translation of user commands by direct translation of user
* command input from other languages to English. Only replaces identifying
* elements such as commands and delimiters.
*
* @param input
* <code>String</code> containing the user command
* @return <code>String</code> containing the original input with replaced
* <code>String</code> of identifiers.
*/
public static String toEnglish(String input) {
Set<String> keys = resBundle.keySet();
Locale target = new Locale("en", "US");
if (target.equals(currentLocale)) {
return input;
}
ResourceBundle resTarget = ResourceBundle
.getBundle(BUNDLE_NAME, target);
for (String key : keys) {
String international = resBundle.getString(key);
String english = resTarget.getString(key) + SPACE;
int commandLength = international.length();
if (key.contains("COMMAND")) {
if (isAcceptable(input, commandLength)
&& isSameCommand(input, international, commandLength)) {
input = input.substring(0, commandLength).toUpperCase()
+ input.substring(commandLength);
input = input.replace(international, english);
}
} else if (key.contains("USER_PROMPT") || key.contains("ALERT")) {
continue;
} else {
input = input.replace(international, english);
}
}
return input;
}
/**
* Checks if the command identified is in English.
*
* @param input
* from the user containing the Command <code>String</code>
* @param international
* Command from the English resource bundle
* @param commandLength
* <code>length</code> of the Command <code>String</code>
*
* @return <code>true</code> if the Commands are equal, <code>false</code>
* otherwise.
*/
private static boolean isSameCommand(String input, String international,
int commandLength) {
return input.substring(0, commandLength).toUpperCase()
.equals(international);
}
/**
* Checks if the input is of sufficient length
*
* @param input
* to be checked
* @param commandLength
* length of the command to be checked against
*
* @return <code>true</code> if acceptable, <code>false</code> otherwise
*/
private static boolean isAcceptable(String input, int commandLength) {
return input.length() >= commandLength;
}
/**
* Packages the languages into a <code>LinkedList</code> to be displayed to
* the user as choices.
*
* @return <code>LinkedList</code> containing pseudo-Tasks with information
* about the languages.
*/
public static LinkedList<Task> languageChoices() {
LinkedList<Task> choices = new LinkedList<Task>();
for (int i=0; i<LANGUAGES.length; i++) {
Task language = new Task(LANGUAGES[i]);
language.setDate(HEADER);
choices.add(language);
}
return choices;
}
}
| src/bakatxt/international/BakaTongue.java | //@author A0116320Y
package bakatxt.international;
import java.util.LinkedList;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import bakatxt.core.Database;
import bakatxt.core.Task;
public class BakaTongue {
private static final String BUNDLE_NAME = "bakatxt.international.BakaLanguage";
private static final String SPACE = " ";
private static final String HEADER = "LANGUAGE";
private static final String[] LANGUAGES = { "English", "中文", "한국어", "HINDI" };
private static Locale currentLocale = new Locale("en", "US");
private static ResourceBundle resBundle = ResourceBundle.getBundle(
BUNDLE_NAME, currentLocale);
private BakaTongue() {
}
public static String getString(String key) {
try {
return resBundle.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
public static boolean setLanguage(String language) {
boolean isSuccessful = true;
switch (language.toLowerCase().trim()) {
case "english" :
case "1" :
currentLocale = new Locale("en", "US");
break;
case "中文" :
case "chinese" :
case "2" :
currentLocale = new Locale("zh", "CN");
break;
case "한국어" :
case "korean" :
case "3" :
currentLocale = new Locale("ko", "KR");
break;
case "hindi" :
case "4" :
currentLocale = new Locale("hi", "IN");
break;
case "wah lao" :
case "singlish" :
currentLocale = new Locale("en", "SG");
break;
default :
currentLocale = new Locale("en", "US");
isSuccessful = false;
}
resBundle = ResourceBundle.getBundle(BUNDLE_NAME, currentLocale);
Database.getInstance().updateLocale(currentLocale.toString());
return isSuccessful;
}
public static void setLanguage(String lang, String region) {
currentLocale = new Locale(lang.trim(), region.trim());
resBundle = ResourceBundle.getBundle(BUNDLE_NAME, currentLocale);
}
public static String toEnglish(String input) {
Set<String> keys = resBundle.keySet();
Locale target = new Locale("en", "US");
if (target.equals(currentLocale)) {
return input;
}
ResourceBundle resTarget = ResourceBundle
.getBundle(BUNDLE_NAME, target);
for (String key : keys) {
String international = resBundle.getString(key);
String english = resTarget.getString(key) + SPACE;
int commandLength = international.length();
if (key.contains("COMMAND")) {
if (isAcceptable(input, commandLength)
&& isSameCommand(input, international, commandLength)) {
input = input.substring(0, commandLength).toUpperCase()
+ input.substring(commandLength);
input = input.replace(international, english);
}
} else if (key.contains("USER_PROMPT") || key.contains("ALERT")) {
continue;
} else {
input = input.replace(international, english);
}
}
return input;
}
private static boolean isSameCommand(String input, String international,
int commandLength) {
return input.substring(0, commandLength).toUpperCase()
.equals(international);
}
private static boolean isAcceptable(String input, int commandLength) {
return input.length() >= commandLength;
}
public static LinkedList<Task> languageChoices() {
LinkedList<Task> choices = new LinkedList<Task>();
for (int i=0; i<LANGUAGES.length; i++) {
Task language = new Task(LANGUAGES[i]);
language.setDate(HEADER);
choices.add(language);
}
return choices;
}
}
| Add comments for BakaTongue
| src/bakatxt/international/BakaTongue.java | Add comments for BakaTongue |
|
Java | mit | 23718274dcfe428c02dcdea9d111f6651a9fbc71 | 0 | meraki-analytics/Orianna,robrua/Orianna | package com.robrua.orianna.api.dto;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.robrua.orianna.api.core.RiotAPI;
import com.robrua.orianna.type.api.MultiRateLimiter;
import com.robrua.orianna.type.api.RateLimit;
import com.robrua.orianna.type.api.RateLimiter;
import com.robrua.orianna.type.api.SingleRateLimiter;
import com.robrua.orianna.type.core.common.QueueType;
import com.robrua.orianna.type.core.common.Region;
import com.robrua.orianna.type.core.common.Season;
import com.robrua.orianna.type.dto.currentgame.CurrentGameInfo;
import com.robrua.orianna.type.dto.featuredgames.FeaturedGames;
import com.robrua.orianna.type.dto.game.RecentGames;
import com.robrua.orianna.type.dto.league.League;
import com.robrua.orianna.type.dto.match.MatchDetail;
import com.robrua.orianna.type.dto.matchhistory.PlayerHistory;
import com.robrua.orianna.type.dto.staticdata.ChampionSpell;
import com.robrua.orianna.type.dto.staticdata.Item;
import com.robrua.orianna.type.dto.staticdata.ItemList;
import com.robrua.orianna.type.dto.staticdata.LanguageStrings;
import com.robrua.orianna.type.dto.staticdata.MapInfoList;
import com.robrua.orianna.type.dto.staticdata.Mastery;
import com.robrua.orianna.type.dto.staticdata.MasteryList;
import com.robrua.orianna.type.dto.staticdata.Realm;
import com.robrua.orianna.type.dto.staticdata.Rune;
import com.robrua.orianna.type.dto.staticdata.RuneList;
import com.robrua.orianna.type.dto.staticdata.SummonerSpell;
import com.robrua.orianna.type.dto.staticdata.SummonerSpellList;
import com.robrua.orianna.type.dto.stats.PlayerStatsSummaryList;
import com.robrua.orianna.type.dto.stats.RankedStats;
import com.robrua.orianna.type.dto.status.Shard;
import com.robrua.orianna.type.dto.status.ShardStatus;
import com.robrua.orianna.type.dto.summoner.MasteryPages;
import com.robrua.orianna.type.dto.summoner.RunePages;
import com.robrua.orianna.type.dto.summoner.Summoner;
import com.robrua.orianna.type.dto.team.Team;
import com.robrua.orianna.type.exception.APIException;
import com.robrua.orianna.type.exception.OriannaException;
/**
* Queries the <a href="http://developer.riotgames.com/api/methods">LoL REST
* API</a> for information, returning Java objects matching the exact API spec
*
* @author Rob Rua (FatalElement - NA) ([email protected])
*/
public abstract class BaseRiotAPI {
static final Map<String, String> API_VERSIONS;
private static String APIKey;
private static final CloseableHttpClient CLIENT = HttpClients.createDefault();
static final Gson GSON = new GsonBuilder().registerTypeAdapter(ChampionSpell.class, new ChampionSpellDeserializer())
.registerTypeAdapter(SummonerSpell.class, new SummonerSpellDeserializer()).create();
static Region mirror, region;
private static RateLimiter rateLimiter = RiotAPI.getDefaultDevelopmentRateLimiter();
static {
API_VERSIONS = new HashMap<>();
API_VERSIONS.put("champion", "v1.2");
API_VERSIONS.put("current-game", "v1.0");
API_VERSIONS.put("featured-games", "v1.0");
API_VERSIONS.put("game", "v1.3");
API_VERSIONS.put("league", "v2.5");
API_VERSIONS.put("static-data", "v1.2");
API_VERSIONS.put("status", "v1.0");
API_VERSIONS.put("match", "v2.2");
API_VERSIONS.put("matchhistory", "v2.2");
API_VERSIONS.put("stats", "v1.3");
API_VERSIONS.put("summoner", "v1.4");
API_VERSIONS.put("team", "v2.4");
}
/**
* Uses Apache HttpClient to make a GET request to the server and return the
* JSON response. Blocks if necessary to meet rate limits. Throws an
* APIException if the server sends an error code.
*
* @param request
* the latter part of the request (everything following /api/lol/
* but without params)
* @param params
* the parameters to use for the request. API Key is
* automatically added in this method.
* @param staticServer
* whether to query the static data sever or not (regional
* server)
* @return the JSON response from the API
*/
static String get(final String request, final Map<String, String> params, final boolean staticServer) {
// Check that mirror, region, and API key are set
if(region == null) {
throw new OriannaException("Must set region for the API using setRegion before the server can be queried!");
}
if(mirror == null) {
throw new OriannaException("Must set mirror for the API using setRegion before the server can be queried!");
}
if(APIKey == null) {
throw new OriannaException("Must set API key for using setAPIKey before the server can be queried!");
}
// Convert params for Apache HTTP
final List<NameValuePair> param = new ArrayList<>();
param.add(new BasicNameValuePair("api_key", APIKey));
if(params != null) {
for(final String name : params.keySet()) {
param.add(new BasicNameValuePair(name, params.get(name)));
}
}
// Build URI for request
final String server = staticServer ? "global" : mirror.toString().toLowerCase();
final String rgn = staticServer ? "static-data/" + region.toString().toLowerCase() : region.toString().toLowerCase();
// Make request
try {
final URI uri = new URIBuilder().setScheme("https").setHost(server + ".api.pvp.net").setPath("/api/lol/" + rgn + "/" + request)
.setParameters(param).build();
return get(uri, staticServer);
}
catch(final URISyntaxException e) {
throw new OriannaException("Generated http request wasn't valid! Report this to the Orianna team.");
}
}
/**
* Uses Apache HttpClient to make a GET request to the server and return the
* JSON response. Blocks if necessary to meet rate limits. Throws an
* APIException if the server sends an error code.
*
* @param uri
* the URI to send the request to
* @param staticServer
* whether to query the static data sever or not (regional
* server)
* @return the JSON response from the API
*/
static String get(final URI uri, final boolean staticServer) {
// Wait for a call to be available if this is a call to a rate
// limited server
if(!staticServer) {
rateLimiter.waitForCall();
}
// Send request to Riot and register call
try {
final CloseableHttpResponse response = CLIENT.execute(new HttpGet(uri));
try {
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
EntityUtils.consume(entity);
// Handle API errors
if(response.getStatusLine().getStatusCode() != 200) {
throw new APIException(uri.toString(), response.getStatusLine().getStatusCode());
}
return content;
} finally {
response.close();
}
} catch(IOException e) {
throw new OriannaException("Request to Riot server failed! Report this to the Orianna team.");
} finally {
if(!staticServer) {
rateLimiter.registerCall();
}
}
}
/**
* @param queueType
* the queue type to get the challenger league for
* @return the challenger league
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3243">Riot
* API Specification</a>
*/
public static League getChallenger(final QueueType queueType) {
return LeagueAPI.getChallenger(queueType);
}
/**
* @param ID
* the champion's ID
* @return the champion
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3256">Riot
* API Specification</a>
*/
public static com.robrua.orianna.type.dto.staticdata.Champion getChampion(final long ID) {
return StaticDataAPI.getChampion(ID);
}
/**
* @return the list all of champions
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3260">Riot
* API Specification</a>
*/
public static com.robrua.orianna.type.dto.staticdata.ChampionList getChampions() {
return StaticDataAPI.getChampions();
}
/**
* @param ID
* the ID of the champion to look up
* @return the champion
* @see <a
* href="https://developer.riotgames.com/api/methods#!/958/3289">Riot
* API Specification</a>
*/
public static com.robrua.orianna.type.dto.champion.Champion getChampionStatus(final long ID) {
return ChampionAPI.getChampionStatus(ID);
}
/**
* @param freeToPlay
* whether to only return free champions
* @return all champions
* @see <a
* href="https://developer.riotgames.com/api/methods#!/958/3290">Riot
* API Specification</a>
*/
public static com.robrua.orianna.type.dto.champion.ChampionList getChampionStatuses(final boolean freeToPlay) {
return ChampionAPI.getChampionStatuses(freeToPlay);
}
/**
* @param summonerID
* summoner to look up current game for
* @return the summoner's current game
* @see <a
* href="https://developer.riotgames.com/api/methods#!/956/3287">Riot
* API Specification</a>
*/
public static CurrentGameInfo getCurrentGame(final long summonerID) {
return CurrentGameAPI.getCurrentGame(summonerID);
}
/**
* @return the featured games
* @see <a
* href="https://developer.riotgames.com/api/methods#!/957/3288">Riot
* API Specification</a>
*/
public static FeaturedGames getFeaturedGames() {
return FeaturedGamesAPI.getFeaturedGames();
}
/**
* @param ID
* the item's ID
* @return the item
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3253">Riot
* API Specification</a>
*/
public static Item getItem(final long ID) {
return StaticDataAPI.getItem(ID);
}
/**
* @return the list of all items
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3248">Riot
* API Specification</a>
*/
public static ItemList getItems() {
return StaticDataAPI.getItems();
}
/**
* @return the languages
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3258">Riot
* API Specification</a>
*/
public static List<String> getLanguages() {
return StaticDataAPI.getLanguages();
}
/**
* @return the language strings
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3250">Riot
* API Specification</a>
*/
public static LanguageStrings getLanguageStrings() {
return StaticDataAPI.getLanguageStrings();
}
/**
* @return the map information
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3262">Riot
* API Specification</a>
*/
public static MapInfoList getMapInformation() {
return StaticDataAPI.getMapInformation();
}
/**
* @return the list of all masteries
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3251">Riot
* API Specification</a>
*/
public static MasteryList getMasteries() {
return StaticDataAPI.getMasteries();
}
/**
* @param ID
* the mastery's ID
* @return the mastery
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3252">Riot
* API Specification</a>
*/
public static Mastery getMastery(final long ID) {
return StaticDataAPI.getMastery(ID);
}
/**
* @param ID
* the ID of the match to look up
* @return the match
* @see <a
* href="https://developer.riotgames.com/api/methods#!/967/3313">Riot
* API Specification</a>
*/
public static MatchDetail getMatch(final long ID) {
return MatchAPI.getMatch(ID);
}
/**
* Gets the 15 most recent matches for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID) {
return MatchHistoryAPI.getMatchHistory(summonerID);
}
/**
* Gets the 15 most recent matches after beginIndex for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @param beginIndex
* the game index to start from
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID, final int beginIndex) {
return MatchHistoryAPI.getMatchHistory(summonerID, beginIndex);
}
/**
* Gets the 15 most recent matches after beginIndex for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @param beginIndex
* the game index to start from
* @param championIDs
* the champions to limit games to
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID, final int beginIndex, final List<Long> championIDs) {
return MatchHistoryAPI.getMatchHistory(summonerID, beginIndex, championIDs);
}
/**
* Gets the 15 most recent matches after beginIndex for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @param beginIndex
* the game index to start from
* @param queueType
* the queue type to limit games to (only ranked queues)
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID, final int beginIndex, final QueueType queueType) {
return MatchHistoryAPI.getMatchHistory(summonerID, beginIndex, queueType);
}
/**
* Gets the 15 most recent matches after beginIndex for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @param beginIndex
* the game index to start from
* @param queueType
* the queue type to limit games to (only ranked queues)
* @param championIDs
* the champions to limit games to
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID, final int beginIndex, final QueueType queueType, final List<Long> championIDs) {
return MatchHistoryAPI.getMatchHistory(summonerID, beginIndex, queueType, championIDs);
}
/**
* Gets the 15 most recent matches for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @param championIDs
* the champions to limit games to
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID, final List<Long> championIDs) {
return MatchHistoryAPI.getMatchHistory(summonerID, championIDs);
}
/**
* Gets the 15 most recent matches for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @param queueType
* the queue type to limit games to (only ranked queues)
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID, final QueueType queueType) {
return MatchHistoryAPI.getMatchHistory(summonerID, queueType);
}
/**
* Gets the 15 most recent matches for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @param queueType
* the queue type to limit games to (only ranked queues)
* @param championIDs
* the champions to limit games to
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID, final QueueType queueType, final List<Long> championIDs) {
return MatchHistoryAPI.getMatchHistory(summonerID, queueType, championIDs);
}
/**
* @param summonerID
* the ID of the summoner to get ranked stats for
* @return the ranked stats for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/961/3297">Riot
* API Specification</a>
*/
public static RankedStats getRankedStats(final long summonerID) {
return StatsAPI.getRankedStats(summonerID);
}
/**
* @param summonerID
* the ID of the summoner to get ranked stats for
* @param season
* the season to get stats for
* @return the ranked stats for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/961/3297">Riot
* API Specification</a>
*/
public static RankedStats getRankedStats(final long summonerID, final Season season) {
return StatsAPI.getRankedStats(summonerID, season);
}
/**
* @return the realm
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3259">Riot
* API Specification</a>
*/
public static Realm getRealm() {
return StaticDataAPI.getRealm();
}
/**
* @param summonerID
* the ID of the summoner to look up recent games for
* @return the summoner's recent games
* @see <a
* href="https://developer.riotgames.com/api/methods#!/959/3291">Riot
* API Specification</a>
*/
public static RecentGames getRecentGames(final long summonerID) {
return GameAPI.getRecentGames(summonerID);
}
/**
* Uses Apache HttpClient to make a GET request to the server and return the
* JSON response. Blocks if necessary to meet rate limits. Throws an
* APIException if the server sends an error code.
*
* @param request
* the latter part of the request (everything following the host)
* @param params
* the parameters to use for the request. API Key is
* automatically added in this method.
* @param staticServer
* whether to query the static data sever or not (regional
* server)
* @return the JSON response from the API
*/
static String getRoot(final String request, final Map<String, String> params, final boolean staticServer) {
// Check that mirror, region, and API key are set
if(mirror == null) {
throw new OriannaException("Must set mirror for the API using setRegion before the server can be queried!");
}
if(APIKey == null) {
throw new OriannaException("Must set API key for using setAPIKey before the server can be queried!");
}
// Convert params for Apache HTTP
final List<NameValuePair> param = new ArrayList<>();
param.add(new BasicNameValuePair("api_key", APIKey));
if(params != null) {
for(final String name : params.keySet()) {
param.add(new BasicNameValuePair(name, params.get(name)));
}
}
// Make request
try {
final String server = staticServer ? "global" : mirror.toString().toLowerCase();
final URI uri = new URIBuilder().setScheme("https").setHost(server + ".api.pvp.net").setPath(request).setParameters(param).build();
return get(uri, staticServer);
}
catch(final URISyntaxException e) {
throw new OriannaException("Generated http request wasn't valid! Report this to the Orianna team.");
}
}
/**
* @param ID
* the rune's ID
* @return the rune
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3255">Riot
* API Specification</a>
*/
public static Rune getRune(final long ID) {
return StaticDataAPI.getRune(ID);
}
/**
* @return the list of all runes
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3249">Riot
* API Specification</a>
*/
public static RuneList getRunes() {
return StaticDataAPI.getRunes();
}
/**
* @param region
* the region's shard to get
* @return the shard
* @see <a
* href="https://developer.riotgames.com/api/methods#!/908/3142">Riot
* API Specification</a>
*/
public static ShardStatus getShard(final Region region) {
return StatusAPI.getShard(region);
}
/**
* @return the list of all shards
* @see <a
* href="https://developer.riotgames.com/api/methods#!/908/3143">Riot
* API Specification</a>
*/
public static List<Shard> getShards() {
return StatusAPI.getShards();
}
/**
* @param summonerID
* the ID of the summoner to get stats for
* @return the stats for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/961/3298">Riot
* API Specification</a>
*/
public static PlayerStatsSummaryList getStats(final long summonerID) {
return StatsAPI.getStats(summonerID);
}
/**
* @param summonerID
* the ID of the summoner to get stats for
* @param season
* the season to get stats for
* @return the stats for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/961/3298">Riot
* API Specification</a>
*/
public static PlayerStatsSummaryList getStats(final long summonerID, final Season season) {
return StatsAPI.getStats(summonerID, season);
}
/**
* @param summonerIDs
* the summoners to get league entries for
* @return the summoners' league entries
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3245">Riot
* API Specification</a>
*/
public static Map<Long, List<League>> getSummonerLeagueEntries(final List<Long> summonerIDs) {
return LeagueAPI.getSummonerLeagueEntries(summonerIDs);
}
/**
* @param summonerIDs
* the summoners to get league entries for
* @return the summoners' league entries
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3245">Riot
* API Specification</a>
*/
public static Map<Long, List<League>> getSummonerLeagueEntries(final long... summonerIDs) {
return LeagueAPI.getSummonerLeagueEntries(summonerIDs);
}
/**
* @param summonerIDs
* the summoners to get leagues for
* @return the summoners' league
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3241">Riot
* API Specification</a>
*/
public static Map<Long, List<League>> getSummonerLeagues(final List<Long> summonerIDs) {
return LeagueAPI.getSummonerLeagues(summonerIDs);
}
/**
* @param summonerIDs
* the summoners to get leagues for
* @return the summoners' league
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3241">Riot
* API Specification</a>
*/
public static Map<Long, List<League>> getSummonerLeagues(final long... summonerIDs) {
return LeagueAPI.getSummonerLeagues(summonerIDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get
* @return the summoners
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3293">Riot
* API Specification</a>
*/
public static Map<Long, Summoner> getSummonersByID(final List<Long> summonerIDs) {
return SummonerAPI.getSummonersByID(summonerIDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get
* @return the summoners
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3293">Riot
* API Specification</a>
*/
public static Map<Long, Summoner> getSummonersByID(final long... summonerIDs) {
return SummonerAPI.getSummonersByID(summonerIDs);
}
/**
* @param summonerNames
* the names of the summoners to get
* @return the summoners
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3292">Riot
* API Specification</a>
*/
public static Map<String, Summoner> getSummonersByName(final List<String> summonerNames) {
return SummonerAPI.getSummonersByName(summonerNames);
}
/**
* @param summonerNames
* the names of the summoners to get
* @return the summoners
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3292">Riot
* API Specification</a>
*/
public static Map<String, Summoner> getSummonersByName(final String... summonerNames) {
return SummonerAPI.getSummonersByName(summonerNames);
}
/**
* @param summonerIDs
* the IDs of the summoners to get masteries for
* @return the summoners' masteries
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3295">Riot
* API Specification</a>
*/
public static Map<Long, MasteryPages> getSummonersMasteries(final List<Long> summonerIDs) {
return SummonerAPI.getSummonersMasteries(summonerIDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get masteries for
* @return the summoners' masteries
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3295">Riot
* API Specification</a>
*/
public static Map<Long, MasteryPages> getSummonersMasteries(final long... summonerIDs) {
return SummonerAPI.getSummonersMasteries(summonerIDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get names of
* @return the summoners' names
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3296">Riot
* API Specification</a>
*/
public static Map<Long, String> getSummonersNames(final List<Long> summonerIDs) {
return SummonerAPI.getSummonersNames(summonerIDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get names of
* @return the summoners' names
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3296">Riot
* API Specification</a>
*/
public static Map<Long, String> getSummonersNames(final long... summonerIDs) {
return SummonerAPI.getSummonersNames(summonerIDs);
}
/**
* @param ID
* the summoner spell's ID
* @return the summoner spell
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3254">Riot
* API Specification</a>
*/
public static SummonerSpell getSummonerSpell(final long ID) {
return StaticDataAPI.getSummonerSpell(ID);
}
/**
* @return the list of all summoner spells
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3261">Riot
* API Specification</a>
*/
public static SummonerSpellList getSummonerSpells() {
return StaticDataAPI.getSummonerSpells();
}
/**
* @param summonerIDs
* the IDs of the summoners to get runes for
* @return the summoners' runes
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3294">Riot
* API Specification</a>
*/
public static Map<Long, RunePages> getSummonersRunes(final List<Long> summonerIDs) {
return SummonerAPI.getSummonersRunes(summonerIDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get runes for
* @return the summoners' runes
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3294">Riot
* API Specification</a>
*/
public static Map<Long, RunePages> getSummonersRunes(final long... summonerIDs) {
return SummonerAPI.getSummonersRunes(summonerIDs);
}
/**
* @param teamIDs
* the summoners to get leagues for
* @return the team's leagues
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3242">Riot
* API Specification</a>
*/
public static Map<String, List<League>> getTeamLeagueEntries(final List<String> teamIDs) {
return LeagueAPI.getTeamLeagueEntries(teamIDs);
}
/**
* @param teamIDs
* the summoners to get leagues for
* @return the team's leagues
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3242">Riot
* API Specification</a>
*/
public static Map<String, List<League>> getTeamLeagueEntries(final String... teamIDs) {
return LeagueAPI.getTeamLeagueEntries(teamIDs);
}
/**
* @param teamIDs
* the summoners to get leagues for
* @return the team's leagues
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3242">Riot
* API Specification</a>
*/
public static Map<String, List<League>> getTeamLeagues(final List<String> teamIDs) {
return LeagueAPI.getTeamLeagues(teamIDs);
}
/**
* @param teamIDs
* the summoners to get leagues for
* @return the team's leagues
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3242">Riot
* API Specification</a>
*/
public static Map<String, List<League>> getTeamLeagues(final String... teamIDs) {
return LeagueAPI.getTeamLeagues(teamIDs);
}
/**
* @param IDs
* the IDs of the teams
* @return the teams
* @see <a
* href="https://developer.riotgames.com/api/methods#!/937/3246">Riot
* API Specification</a>
*/
public static Map<String, Team> getTeamsByID(final List<String> IDs) {
return TeamAPI.getTeamsByID(IDs);
}
/**
* @param IDs
* the IDs of the teams
* @return the teams
* @see <a
* href="https://developer.riotgames.com/api/methods#!/937/3246">Riot
* API Specification</a>
*/
public static Map<String, Team> getTeamsByID(final String... IDs) {
return TeamAPI.getTeamsByID(IDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get teams for
* @return the summoners' teams
* @see <a
* href="https://developer.riotgames.com/api/methods#!/937/3247">Riot
* API Specification</a>
*/
public static Map<Long, List<Team>> getTeamsBySummoner(final List<Long> summonerIDs) {
return TeamAPI.getTeamsBySummoner(summonerIDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get teams for
* @return the summoners' teams
* @see <a
* href="https://developer.riotgames.com/api/methods#!/937/3247">Riot
* API Specification</a>
*/
public static Map<Long, List<Team>> getTeamsBySummoner(final long... summonerIDs) {
return TeamAPI.getTeamsBySummoner(summonerIDs);
}
/**
* @return the versions
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3257">Riot
* API Specification</a>
*/
public static List<String> getVersions() {
return StaticDataAPI.getVersions();
}
/**
* Sets the API Key to use for queries
*
* @param newAPIKey
* the API Key to use for queries
*/
public static void setAPIKey(final String newAPIKey) {
APIKey = newAPIKey;
}
/**
* Sets the server mirror to hit for queries
*
* @param newMirror
* the server mirror to hit for queries
*/
public static void setMirror(final Region newMirror) {
mirror = newMirror;
}
/**
* Sets multiple new rate limits for the API, removing any old ones
*
* @param limits
* the rate limits to apply
*/
public static void setRateLimit(final Collection<RateLimit> limits) {
rateLimiter = new MultiRateLimiter(limits);
}
/**
* Sets a new rate limit for the API, removing any old ones
*
* @param callsPerEpoch
* the number of calls allowed in each epoch
* @param secondsPerEpoch
* the number of seconds in each epoch
*/
public static void setRateLimit(final int callsPerEpoch, final int secondsPerEpoch) {
rateLimiter = new SingleRateLimiter(callsPerEpoch, secondsPerEpoch);
}
/**
* Sets a new rate limit for the API, removing any old ones
*
* @param limit
* the rate limit
*/
public static void setRateLimit(final RateLimit limit) {
rateLimiter = new SingleRateLimiter(limit);
}
/**
* Sets multiple new rate limits for the API, removing any old ones
*
* @param limits
* the rate limits to apply
*/
public static void setRateLimit(final RateLimit... limits) {
rateLimiter = new MultiRateLimiter(limits);
}
/**
* Sets the region to get information from the API for
*
* @param newRegion
* the region to get information from the API for
*/
public static void setRegion(final Region newRegion) {
region = newRegion;
}
}
| src/com/robrua/orianna/api/dto/BaseRiotAPI.java | package com.robrua.orianna.api.dto;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.robrua.orianna.api.core.RiotAPI;
import com.robrua.orianna.type.api.MultiRateLimiter;
import com.robrua.orianna.type.api.RateLimit;
import com.robrua.orianna.type.api.RateLimiter;
import com.robrua.orianna.type.api.SingleRateLimiter;
import com.robrua.orianna.type.core.common.QueueType;
import com.robrua.orianna.type.core.common.Region;
import com.robrua.orianna.type.core.common.Season;
import com.robrua.orianna.type.dto.currentgame.CurrentGameInfo;
import com.robrua.orianna.type.dto.featuredgames.FeaturedGames;
import com.robrua.orianna.type.dto.game.RecentGames;
import com.robrua.orianna.type.dto.league.League;
import com.robrua.orianna.type.dto.match.MatchDetail;
import com.robrua.orianna.type.dto.matchhistory.PlayerHistory;
import com.robrua.orianna.type.dto.staticdata.ChampionSpell;
import com.robrua.orianna.type.dto.staticdata.Item;
import com.robrua.orianna.type.dto.staticdata.ItemList;
import com.robrua.orianna.type.dto.staticdata.LanguageStrings;
import com.robrua.orianna.type.dto.staticdata.MapInfoList;
import com.robrua.orianna.type.dto.staticdata.Mastery;
import com.robrua.orianna.type.dto.staticdata.MasteryList;
import com.robrua.orianna.type.dto.staticdata.Realm;
import com.robrua.orianna.type.dto.staticdata.Rune;
import com.robrua.orianna.type.dto.staticdata.RuneList;
import com.robrua.orianna.type.dto.staticdata.SummonerSpell;
import com.robrua.orianna.type.dto.staticdata.SummonerSpellList;
import com.robrua.orianna.type.dto.stats.PlayerStatsSummaryList;
import com.robrua.orianna.type.dto.stats.RankedStats;
import com.robrua.orianna.type.dto.status.Shard;
import com.robrua.orianna.type.dto.status.ShardStatus;
import com.robrua.orianna.type.dto.summoner.MasteryPages;
import com.robrua.orianna.type.dto.summoner.RunePages;
import com.robrua.orianna.type.dto.summoner.Summoner;
import com.robrua.orianna.type.dto.team.Team;
import com.robrua.orianna.type.exception.APIException;
import com.robrua.orianna.type.exception.OriannaException;
/**
* Queries the <a href="http://developer.riotgames.com/api/methods">LoL REST
* API</a> for information, returning Java objects matching the exact API spec
*
* @author Rob Rua (FatalElement - NA) ([email protected])
*/
public abstract class BaseRiotAPI {
static final Map<String, String> API_VERSIONS;
private static String APIKey;
private static final CloseableHttpClient CLIENT = HttpClients.createDefault();
static final Gson GSON = new GsonBuilder().registerTypeAdapter(ChampionSpell.class, new ChampionSpellDeserializer())
.registerTypeAdapter(SummonerSpell.class, new SummonerSpellDeserializer()).create();
static Region mirror, region;
private static RateLimiter rateLimiter = RiotAPI.getDefaultDevelopmentRateLimiter();
static {
API_VERSIONS = new HashMap<>();
API_VERSIONS.put("champion", "v1.2");
API_VERSIONS.put("current-game", "v1.0");
API_VERSIONS.put("featured-games", "v1.0");
API_VERSIONS.put("game", "v1.3");
API_VERSIONS.put("league", "v2.5");
API_VERSIONS.put("static-data", "v1.2");
API_VERSIONS.put("status", "v1.0");
API_VERSIONS.put("match", "v2.2");
API_VERSIONS.put("matchhistory", "v2.2");
API_VERSIONS.put("stats", "v1.3");
API_VERSIONS.put("summoner", "v1.4");
API_VERSIONS.put("team", "v2.4");
}
/**
* Uses Apache HttpClient to make a GET request to the server and return the
* JSON response. Blocks if necessary to meet rate limits. Throws an
* APIException if the server sends an error code.
*
* @param request
* the latter part of the request (everything following /api/lol/
* but without params)
* @param params
* the parameters to use for the request. API Key is
* automatically added in this method.
* @param staticServer
* whether to query the static data sever or not (regional
* server)
* @return the JSON response from the API
*/
static String get(final String request, final Map<String, String> params, final boolean staticServer) {
// Check that mirror, region, and API key are set
if(region == null) {
throw new OriannaException("Must set region for the API using setRegion before the server can be queried!");
}
if(mirror == null) {
throw new OriannaException("Must set mirror for the API using setRegion before the server can be queried!");
}
if(APIKey == null) {
throw new OriannaException("Must set API key for using setAPIKey before the server can be queried!");
}
// Convert params for Apache HTTP
final List<NameValuePair> param = new ArrayList<>();
param.add(new BasicNameValuePair("api_key", APIKey));
if(params != null) {
for(final String name : params.keySet()) {
param.add(new BasicNameValuePair(name, params.get(name)));
}
}
// Build URI for request
final String server = staticServer ? "global" : mirror.toString().toLowerCase();
final String rgn = staticServer ? "static-data/" + region.toString().toLowerCase() : region.toString().toLowerCase();
// Make request
try {
final URI uri = new URIBuilder().setScheme("https").setHost(server + ".api.pvp.net").setPath("/api/lol/" + rgn + "/" + request)
.setParameters(param).build();
return get(uri, staticServer);
}
catch(final URISyntaxException e) {
throw new OriannaException("Generated http request wasn't valid! Report this to the Orianna team.");
}
}
/**
* Uses Apache HttpClient to make a GET request to the server and return the
* JSON response. Blocks if necessary to meet rate limits. Throws an
* APIException if the server sends an error code.
*
* @param uri
* the URI to send the request to
* @param staticServer
* whether to query the static data sever or not (regional
* server)
* @return the JSON response from the API
*/
static String get(final URI uri, final boolean staticServer) {
try {
// Wait for a call to be available if this is a call to a rate
// limited server
if(!staticServer) {
rateLimiter.waitForCall();
}
// Send request to Riot and register call
final CloseableHttpResponse response = CLIENT.execute(new HttpGet(uri));
if(!staticServer) {
rateLimiter.registerCall();
}
// Handle API errors
if(response.getStatusLine().getStatusCode() != 200) {
throw new APIException(uri.toString(), response.getStatusLine().getStatusCode());
}
// Read response into a string, return, and clean up Apache Http
// resources
try {
final HttpEntity entity = response.getEntity();
if(entity != null) {
final InputStream inStream = entity.getContent();
try {
final BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
final StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString().trim();
}
finally {
inStream.close();
}
}
else {
// Error reading the stream
throw new OriannaException("Request to Riot server failed! Report this to the Orianna team.");
}
}
finally {
response.close();
}
}
catch(final IOException e) {
throw new OriannaException("Request to Riot server failed! Report this to the Orianna team.");
}
}
/**
* @param queueType
* the queue type to get the challenger league for
* @return the challenger league
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3243">Riot
* API Specification</a>
*/
public static League getChallenger(final QueueType queueType) {
return LeagueAPI.getChallenger(queueType);
}
/**
* @param ID
* the champion's ID
* @return the champion
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3256">Riot
* API Specification</a>
*/
public static com.robrua.orianna.type.dto.staticdata.Champion getChampion(final long ID) {
return StaticDataAPI.getChampion(ID);
}
/**
* @return the list all of champions
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3260">Riot
* API Specification</a>
*/
public static com.robrua.orianna.type.dto.staticdata.ChampionList getChampions() {
return StaticDataAPI.getChampions();
}
/**
* @param ID
* the ID of the champion to look up
* @return the champion
* @see <a
* href="https://developer.riotgames.com/api/methods#!/958/3289">Riot
* API Specification</a>
*/
public static com.robrua.orianna.type.dto.champion.Champion getChampionStatus(final long ID) {
return ChampionAPI.getChampionStatus(ID);
}
/**
* @param freeToPlay
* whether to only return free champions
* @return all champions
* @see <a
* href="https://developer.riotgames.com/api/methods#!/958/3290">Riot
* API Specification</a>
*/
public static com.robrua.orianna.type.dto.champion.ChampionList getChampionStatuses(final boolean freeToPlay) {
return ChampionAPI.getChampionStatuses(freeToPlay);
}
/**
* @param summonerID
* summoner to look up current game for
* @return the summoner's current game
* @see <a
* href="https://developer.riotgames.com/api/methods#!/956/3287">Riot
* API Specification</a>
*/
public static CurrentGameInfo getCurrentGame(final long summonerID) {
return CurrentGameAPI.getCurrentGame(summonerID);
}
/**
* @return the featured games
* @see <a
* href="https://developer.riotgames.com/api/methods#!/957/3288">Riot
* API Specification</a>
*/
public static FeaturedGames getFeaturedGames() {
return FeaturedGamesAPI.getFeaturedGames();
}
/**
* @param ID
* the item's ID
* @return the item
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3253">Riot
* API Specification</a>
*/
public static Item getItem(final long ID) {
return StaticDataAPI.getItem(ID);
}
/**
* @return the list of all items
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3248">Riot
* API Specification</a>
*/
public static ItemList getItems() {
return StaticDataAPI.getItems();
}
/**
* @return the languages
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3258">Riot
* API Specification</a>
*/
public static List<String> getLanguages() {
return StaticDataAPI.getLanguages();
}
/**
* @return the language strings
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3250">Riot
* API Specification</a>
*/
public static LanguageStrings getLanguageStrings() {
return StaticDataAPI.getLanguageStrings();
}
/**
* @return the map information
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3262">Riot
* API Specification</a>
*/
public static MapInfoList getMapInformation() {
return StaticDataAPI.getMapInformation();
}
/**
* @return the list of all masteries
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3251">Riot
* API Specification</a>
*/
public static MasteryList getMasteries() {
return StaticDataAPI.getMasteries();
}
/**
* @param ID
* the mastery's ID
* @return the mastery
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3252">Riot
* API Specification</a>
*/
public static Mastery getMastery(final long ID) {
return StaticDataAPI.getMastery(ID);
}
/**
* @param ID
* the ID of the match to look up
* @return the match
* @see <a
* href="https://developer.riotgames.com/api/methods#!/967/3313">Riot
* API Specification</a>
*/
public static MatchDetail getMatch(final long ID) {
return MatchAPI.getMatch(ID);
}
/**
* Gets the 15 most recent matches for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID) {
return MatchHistoryAPI.getMatchHistory(summonerID);
}
/**
* Gets the 15 most recent matches after beginIndex for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @param beginIndex
* the game index to start from
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID, final int beginIndex) {
return MatchHistoryAPI.getMatchHistory(summonerID, beginIndex);
}
/**
* Gets the 15 most recent matches after beginIndex for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @param beginIndex
* the game index to start from
* @param championIDs
* the champions to limit games to
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID, final int beginIndex, final List<Long> championIDs) {
return MatchHistoryAPI.getMatchHistory(summonerID, beginIndex, championIDs);
}
/**
* Gets the 15 most recent matches after beginIndex for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @param beginIndex
* the game index to start from
* @param queueType
* the queue type to limit games to (only ranked queues)
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID, final int beginIndex, final QueueType queueType) {
return MatchHistoryAPI.getMatchHistory(summonerID, beginIndex, queueType);
}
/**
* Gets the 15 most recent matches after beginIndex for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @param beginIndex
* the game index to start from
* @param queueType
* the queue type to limit games to (only ranked queues)
* @param championIDs
* the champions to limit games to
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID, final int beginIndex, final QueueType queueType, final List<Long> championIDs) {
return MatchHistoryAPI.getMatchHistory(summonerID, beginIndex, queueType, championIDs);
}
/**
* Gets the 15 most recent matches for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @param championIDs
* the champions to limit games to
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID, final List<Long> championIDs) {
return MatchHistoryAPI.getMatchHistory(summonerID, championIDs);
}
/**
* Gets the 15 most recent matches for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @param queueType
* the queue type to limit games to (only ranked queues)
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID, final QueueType queueType) {
return MatchHistoryAPI.getMatchHistory(summonerID, queueType);
}
/**
* Gets the 15 most recent matches for the summoner
*
* @param summonerID
* the ID of the summoner to get match history for
* @param queueType
* the queue type to limit games to (only ranked queues)
* @param championIDs
* the champions to limit games to
* @return the match history for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/966/3312">Riot
* API Specification</a>
*/
public static PlayerHistory getMatchHistory(final long summonerID, final QueueType queueType, final List<Long> championIDs) {
return MatchHistoryAPI.getMatchHistory(summonerID, queueType, championIDs);
}
/**
* @param summonerID
* the ID of the summoner to get ranked stats for
* @return the ranked stats for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/961/3297">Riot
* API Specification</a>
*/
public static RankedStats getRankedStats(final long summonerID) {
return StatsAPI.getRankedStats(summonerID);
}
/**
* @param summonerID
* the ID of the summoner to get ranked stats for
* @param season
* the season to get stats for
* @return the ranked stats for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/961/3297">Riot
* API Specification</a>
*/
public static RankedStats getRankedStats(final long summonerID, final Season season) {
return StatsAPI.getRankedStats(summonerID, season);
}
/**
* @return the realm
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3259">Riot
* API Specification</a>
*/
public static Realm getRealm() {
return StaticDataAPI.getRealm();
}
/**
* @param summonerID
* the ID of the summoner to look up recent games for
* @return the summoner's recent games
* @see <a
* href="https://developer.riotgames.com/api/methods#!/959/3291">Riot
* API Specification</a>
*/
public static RecentGames getRecentGames(final long summonerID) {
return GameAPI.getRecentGames(summonerID);
}
/**
* Uses Apache HttpClient to make a GET request to the server and return the
* JSON response. Blocks if necessary to meet rate limits. Throws an
* APIException if the server sends an error code.
*
* @param request
* the latter part of the request (everything following the host)
* @param params
* the parameters to use for the request. API Key is
* automatically added in this method.
* @param staticServer
* whether to query the static data sever or not (regional
* server)
* @return the JSON response from the API
*/
static String getRoot(final String request, final Map<String, String> params, final boolean staticServer) {
// Check that mirror, region, and API key are set
if(mirror == null) {
throw new OriannaException("Must set mirror for the API using setRegion before the server can be queried!");
}
if(APIKey == null) {
throw new OriannaException("Must set API key for using setAPIKey before the server can be queried!");
}
// Convert params for Apache HTTP
final List<NameValuePair> param = new ArrayList<>();
param.add(new BasicNameValuePair("api_key", APIKey));
if(params != null) {
for(final String name : params.keySet()) {
param.add(new BasicNameValuePair(name, params.get(name)));
}
}
// Make request
try {
final String server = staticServer ? "global" : mirror.toString().toLowerCase();
final URI uri = new URIBuilder().setScheme("https").setHost(server + ".api.pvp.net").setPath(request).setParameters(param).build();
return get(uri, staticServer);
}
catch(final URISyntaxException e) {
throw new OriannaException("Generated http request wasn't valid! Report this to the Orianna team.");
}
}
/**
* @param ID
* the rune's ID
* @return the rune
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3255">Riot
* API Specification</a>
*/
public static Rune getRune(final long ID) {
return StaticDataAPI.getRune(ID);
}
/**
* @return the list of all runes
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3249">Riot
* API Specification</a>
*/
public static RuneList getRunes() {
return StaticDataAPI.getRunes();
}
/**
* @param region
* the region's shard to get
* @return the shard
* @see <a
* href="https://developer.riotgames.com/api/methods#!/908/3142">Riot
* API Specification</a>
*/
public static ShardStatus getShard(final Region region) {
return StatusAPI.getShard(region);
}
/**
* @return the list of all shards
* @see <a
* href="https://developer.riotgames.com/api/methods#!/908/3143">Riot
* API Specification</a>
*/
public static List<Shard> getShards() {
return StatusAPI.getShards();
}
/**
* @param summonerID
* the ID of the summoner to get stats for
* @return the stats for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/961/3298">Riot
* API Specification</a>
*/
public static PlayerStatsSummaryList getStats(final long summonerID) {
return StatsAPI.getStats(summonerID);
}
/**
* @param summonerID
* the ID of the summoner to get stats for
* @param season
* the season to get stats for
* @return the stats for that summoner
* @see <a
* href="https://developer.riotgames.com/api/methods#!/961/3298">Riot
* API Specification</a>
*/
public static PlayerStatsSummaryList getStats(final long summonerID, final Season season) {
return StatsAPI.getStats(summonerID, season);
}
/**
* @param summonerIDs
* the summoners to get league entries for
* @return the summoners' league entries
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3245">Riot
* API Specification</a>
*/
public static Map<Long, List<League>> getSummonerLeagueEntries(final List<Long> summonerIDs) {
return LeagueAPI.getSummonerLeagueEntries(summonerIDs);
}
/**
* @param summonerIDs
* the summoners to get league entries for
* @return the summoners' league entries
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3245">Riot
* API Specification</a>
*/
public static Map<Long, List<League>> getSummonerLeagueEntries(final long... summonerIDs) {
return LeagueAPI.getSummonerLeagueEntries(summonerIDs);
}
/**
* @param summonerIDs
* the summoners to get leagues for
* @return the summoners' league
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3241">Riot
* API Specification</a>
*/
public static Map<Long, List<League>> getSummonerLeagues(final List<Long> summonerIDs) {
return LeagueAPI.getSummonerLeagues(summonerIDs);
}
/**
* @param summonerIDs
* the summoners to get leagues for
* @return the summoners' league
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3241">Riot
* API Specification</a>
*/
public static Map<Long, List<League>> getSummonerLeagues(final long... summonerIDs) {
return LeagueAPI.getSummonerLeagues(summonerIDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get
* @return the summoners
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3293">Riot
* API Specification</a>
*/
public static Map<Long, Summoner> getSummonersByID(final List<Long> summonerIDs) {
return SummonerAPI.getSummonersByID(summonerIDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get
* @return the summoners
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3293">Riot
* API Specification</a>
*/
public static Map<Long, Summoner> getSummonersByID(final long... summonerIDs) {
return SummonerAPI.getSummonersByID(summonerIDs);
}
/**
* @param summonerNames
* the names of the summoners to get
* @return the summoners
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3292">Riot
* API Specification</a>
*/
public static Map<String, Summoner> getSummonersByName(final List<String> summonerNames) {
return SummonerAPI.getSummonersByName(summonerNames);
}
/**
* @param summonerNames
* the names of the summoners to get
* @return the summoners
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3292">Riot
* API Specification</a>
*/
public static Map<String, Summoner> getSummonersByName(final String... summonerNames) {
return SummonerAPI.getSummonersByName(summonerNames);
}
/**
* @param summonerIDs
* the IDs of the summoners to get masteries for
* @return the summoners' masteries
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3295">Riot
* API Specification</a>
*/
public static Map<Long, MasteryPages> getSummonersMasteries(final List<Long> summonerIDs) {
return SummonerAPI.getSummonersMasteries(summonerIDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get masteries for
* @return the summoners' masteries
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3295">Riot
* API Specification</a>
*/
public static Map<Long, MasteryPages> getSummonersMasteries(final long... summonerIDs) {
return SummonerAPI.getSummonersMasteries(summonerIDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get names of
* @return the summoners' names
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3296">Riot
* API Specification</a>
*/
public static Map<Long, String> getSummonersNames(final List<Long> summonerIDs) {
return SummonerAPI.getSummonersNames(summonerIDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get names of
* @return the summoners' names
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3296">Riot
* API Specification</a>
*/
public static Map<Long, String> getSummonersNames(final long... summonerIDs) {
return SummonerAPI.getSummonersNames(summonerIDs);
}
/**
* @param ID
* the summoner spell's ID
* @return the summoner spell
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3254">Riot
* API Specification</a>
*/
public static SummonerSpell getSummonerSpell(final long ID) {
return StaticDataAPI.getSummonerSpell(ID);
}
/**
* @return the list of all summoner spells
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3261">Riot
* API Specification</a>
*/
public static SummonerSpellList getSummonerSpells() {
return StaticDataAPI.getSummonerSpells();
}
/**
* @param summonerIDs
* the IDs of the summoners to get runes for
* @return the summoners' runes
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3294">Riot
* API Specification</a>
*/
public static Map<Long, RunePages> getSummonersRunes(final List<Long> summonerIDs) {
return SummonerAPI.getSummonersRunes(summonerIDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get runes for
* @return the summoners' runes
* @see <a
* href="https://developer.riotgames.com/api/methods#!/960/3294">Riot
* API Specification</a>
*/
public static Map<Long, RunePages> getSummonersRunes(final long... summonerIDs) {
return SummonerAPI.getSummonersRunes(summonerIDs);
}
/**
* @param teamIDs
* the summoners to get leagues for
* @return the team's leagues
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3242">Riot
* API Specification</a>
*/
public static Map<String, List<League>> getTeamLeagueEntries(final List<String> teamIDs) {
return LeagueAPI.getTeamLeagueEntries(teamIDs);
}
/**
* @param teamIDs
* the summoners to get leagues for
* @return the team's leagues
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3242">Riot
* API Specification</a>
*/
public static Map<String, List<League>> getTeamLeagueEntries(final String... teamIDs) {
return LeagueAPI.getTeamLeagueEntries(teamIDs);
}
/**
* @param teamIDs
* the summoners to get leagues for
* @return the team's leagues
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3242">Riot
* API Specification</a>
*/
public static Map<String, List<League>> getTeamLeagues(final List<String> teamIDs) {
return LeagueAPI.getTeamLeagues(teamIDs);
}
/**
* @param teamIDs
* the summoners to get leagues for
* @return the team's leagues
* @see <a
* href="https://developer.riotgames.com/api/methods#!/936/3242">Riot
* API Specification</a>
*/
public static Map<String, List<League>> getTeamLeagues(final String... teamIDs) {
return LeagueAPI.getTeamLeagues(teamIDs);
}
/**
* @param IDs
* the IDs of the teams
* @return the teams
* @see <a
* href="https://developer.riotgames.com/api/methods#!/937/3246">Riot
* API Specification</a>
*/
public static Map<String, Team> getTeamsByID(final List<String> IDs) {
return TeamAPI.getTeamsByID(IDs);
}
/**
* @param IDs
* the IDs of the teams
* @return the teams
* @see <a
* href="https://developer.riotgames.com/api/methods#!/937/3246">Riot
* API Specification</a>
*/
public static Map<String, Team> getTeamsByID(final String... IDs) {
return TeamAPI.getTeamsByID(IDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get teams for
* @return the summoners' teams
* @see <a
* href="https://developer.riotgames.com/api/methods#!/937/3247">Riot
* API Specification</a>
*/
public static Map<Long, List<Team>> getTeamsBySummoner(final List<Long> summonerIDs) {
return TeamAPI.getTeamsBySummoner(summonerIDs);
}
/**
* @param summonerIDs
* the IDs of the summoners to get teams for
* @return the summoners' teams
* @see <a
* href="https://developer.riotgames.com/api/methods#!/937/3247">Riot
* API Specification</a>
*/
public static Map<Long, List<Team>> getTeamsBySummoner(final long... summonerIDs) {
return TeamAPI.getTeamsBySummoner(summonerIDs);
}
/**
* @return the versions
* @see <a
* href="https://developer.riotgames.com/api/methods#!/938/3257">Riot
* API Specification</a>
*/
public static List<String> getVersions() {
return StaticDataAPI.getVersions();
}
/**
* Sets the API Key to use for queries
*
* @param newAPIKey
* the API Key to use for queries
*/
public static void setAPIKey(final String newAPIKey) {
APIKey = newAPIKey;
}
/**
* Sets the server mirror to hit for queries
*
* @param newMirror
* the server mirror to hit for queries
*/
public static void setMirror(final Region newMirror) {
mirror = newMirror;
}
/**
* Sets multiple new rate limits for the API, removing any old ones
*
* @param limits
* the rate limits to apply
*/
public static void setRateLimit(final Collection<RateLimit> limits) {
rateLimiter = new MultiRateLimiter(limits);
}
/**
* Sets a new rate limit for the API, removing any old ones
*
* @param callsPerEpoch
* the number of calls allowed in each epoch
* @param secondsPerEpoch
* the number of seconds in each epoch
*/
public static void setRateLimit(final int callsPerEpoch, final int secondsPerEpoch) {
rateLimiter = new SingleRateLimiter(callsPerEpoch, secondsPerEpoch);
}
/**
* Sets a new rate limit for the API, removing any old ones
*
* @param limit
* the rate limit
*/
public static void setRateLimit(final RateLimit limit) {
rateLimiter = new SingleRateLimiter(limit);
}
/**
* Sets multiple new rate limits for the API, removing any old ones
*
* @param limits
* the rate limits to apply
*/
public static void setRateLimit(final RateLimit... limits) {
rateLimiter = new MultiRateLimiter(limits);
}
/**
* Sets the region to get information from the API for
*
* @param newRegion
* the region to get information from the API for
*/
public static void setRegion(final Region newRegion) {
region = newRegion;
}
}
| Properly consume apache http resources | src/com/robrua/orianna/api/dto/BaseRiotAPI.java | Properly consume apache http resources |
|
Java | mit | b3ff1a29b8d4fa75f71b54d2d6a2387699bd8fbd | 0 | m-seikou/logbook-kai,m-seikou/logbook-kai,m-seikou/logbook-kai | package logbook.internal;
import java.util.stream.Stream;
/**
* 海域
*/
public enum SeaArea {
識別札1("前路掃討部隊", 1,4),
識別札2("遠征偵察部隊", 2,8),
識別札3("遠征艦隊先遣隊", 3,10),
識別札4("地中海連合艦隊", 4,12),
識別札5("トーチ作戦英軍部隊", 5,14),
識別札6("トーチ作戦英軍部隊", 6,16),
識別札7("中央任務部隊", 7,18),
識別札8("西方任務部隊", 8,20),
識別札9("西方先遣部隊", 9,22),
識別札10("識別札10", 10,20);
/**
* 名前
*/
private final String name;
/**
* 海域(イベント海域のお札)
*/
private final int area;
private final int imageIndex;
SeaArea(String name, int area, int imageIndex) {
this.name = name;
this.area = area;
this.imageIndex = imageIndex;
}
/**
* 名前を取得します。
*
* @return 名前
*/
public String getName() {
return this.name;
}
/**
* 海域(イベント海域のお札)を取得します。
*
* @return 海域(イベント海域のお札)
*/
public int getArea() {
return this.area;
}
public int getImageIndex() {
return imageIndex;
}
@Override
public String toString() {
return this.name;
}
/**
* イベント海域を取得します
*
* @param area お札
* @return 海域
*/
public static SeaArea fromArea(int area) {
return Stream.of(SeaArea.values()).filter(s -> s.getArea() == area).findAny().orElse(null);
}
}
| src/main/java/logbook/internal/SeaArea.java | package logbook.internal;
import java.util.stream.Stream;
/**
* 海域
*/
public enum SeaArea {
識別札1("前路掃討部隊", 1,4),
識別札2("遠征偵察部隊", 2,6),
識別札3("遠征艦隊先遣隊", 3,8),
識別札4("地中海連合艦隊", 4,10),
識別札5("識別札5", 5,12),
識別札6("識別札6", 6,14),
識別札7("識別札7", 7,16),
識別札8("識別札8", 8,18),
識別札9("識別札9", 9,20),
識別札10("識別札10", 10,22);
/**
* 名前
*/
private final String name;
/**
* 海域(イベント海域のお札)
*/
private final int area;
private final int imageIndex;
SeaArea(String name, int area, int imageIndex) {
this.name = name;
this.area = area;
this.imageIndex = imageIndex;
}
/**
* 名前を取得します。
*
* @return 名前
*/
public String getName() {
return this.name;
}
/**
* 海域(イベント海域のお札)を取得します。
*
* @return 海域(イベント海域のお札)
*/
public int getArea() {
return this.area;
}
public int getImageIndex() {
return imageIndex;
}
@Override
public String toString() {
return this.name;
}
/**
* イベント海域を取得します
*
* @param area お札
* @return 海域
*/
public static SeaArea fromArea(int area) {
return Stream.of(SeaArea.values()).filter(s -> s.getArea() == area).findAny().orElse(null);
}
}
| 2922夏イベント札対応
| src/main/java/logbook/internal/SeaArea.java | 2922夏イベント札対応 |
|
Java | mit | 9640113e13039e24b4245f7054acc21a1f6dcd7a | 0 | intirix/openmm-frontend-android | package net.sf.openmm.frontend2;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.net.Uri;
import android.util.Log;
import android.view.Display;
import android.webkit.MimeTypeMap;
public class OpenMMUtil
{
private static final String TAG = OpenMMUtil.class.getSimpleName();
public static int BACKGROUND_COLOR = 0xFF3385FF;
static final String PREF_NAME = "OpenMM2";
public static SharedPreferences getPrefs( Context act )
{
return act.getSharedPreferences( OpenMMUtil.PREF_NAME, 0 );
}
/**
* Get the server url
* @param act
* @return
*/
public static String getServerUrl( Activity act )
{
return getPrefs( act ).getString( "server.url", "http://localhost:3760" ) + "/openmm";
}
/**
* Get the server url with username/password
* @param act
* @return
*/
public static String getServerAccessUrl( Activity act )
{
return getServerUrl( act ).replace( "://", "://" + getServerUsername( act ) + ':' + getServerPassword( act ) + '@' );
}
/**
* Get the server password
* @param act
* @return
*/
public static String getServerPassword( Context act )
{
return getPrefs( act ).getString( "server.password", "password" );
}
/**
* Get the server username
* @param act
* @return
*/
public static String getServerUsername( Context act )
{
return getPrefs( act ).getString( "server.username", "admin" );
}
/**
* Get the number of rows to display
* @param act
* @return
*/
public static int getDisplayRows( Activity act )
{
return getPrefs( act ).getInt( "display.rows", 9 );
}
public static int getDisplayWidth( Activity act )
{
final Display display = act.getWindowManager().getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
return size.x;
}
public static int getTextViewHeight( Activity act )
{
final Display display = act.getWindowManager().getDefaultDisplay();
final Point size = new Point();
display.getSize( size );
final int height = size.y;
final int numRows = getPrefs( act ).getInt( "display.rows", 9 );
final int TEXT_VIEW_HEIGHT = height / numRows;
return TEXT_VIEW_HEIGHT;
}
public static int getTextMaxHeight( Activity act )
{
return getTextViewHeight( act ) * 9 / 10;
}
/**
* Play a url
* @param activity
* @param url
* @param ext
*/
public static void playUrl( Activity act, String url, String ext )
{
Log.d( TAG, "playUrl(" + url + ',' + ext + ')' );
final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension( ext );
final Intent mediaIntent = new Intent( Intent.ACTION_VIEW );
mediaIntent.setDataAndType( Uri.parse( url ), mimeType );
act.startActivity( mediaIntent );
}
/**
* Start an activity
* @param act
* @param i
*/
public static void startActivityForResult( Activity act, Intent i )
{
if ( act.getIntent().hasExtra( "ACT_INDEX" ) )
{
int myIndex = act.getIntent().getIntExtra( "ACT_INDEX", 1 );
i.putExtra( "ACT_INDEX", myIndex + 1 );
Log.d( TAG, "Starting activity from " + act.getClass().getSimpleName() + '[' + ( myIndex + 1 ) + ']' );
act.startActivityForResult( i, myIndex + 1 );
}
else
{
i.putExtra( "ACT_INDEX", 1 );
Log.d( TAG, "Starting activity from " + act.getClass().getSimpleName() + '[' + 1 + ']' );
act.startActivityForResult( i, 1 );
}
}
}
| src/net/sf/openmm/frontend2/OpenMMUtil.java | package net.sf.openmm.frontend2;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.net.Uri;
import android.util.Log;
import android.view.Display;
import android.webkit.MimeTypeMap;
public class OpenMMUtil
{
private static final String TAG = OpenMMUtil.class.getSimpleName();
public static int BACKGROUND_COLOR = 0xFF3385FF;
static final String PREF_NAME = "OpenMM2";
public static SharedPreferences getPrefs( Context act )
{
return act.getSharedPreferences( OpenMMUtil.PREF_NAME, 0 );
}
/**
* Get the server url
* @param act
* @return
*/
public static String getServerUrl( Activity act )
{
return getPrefs( act ).getString( "server.url", "http://localhost:3760" );
}
/**
* Get the server url with username/password
* @param act
* @return
*/
public static String getServerAccessUrl( Activity act )
{
return getServerUrl( act ).replace( "://", "://" + getServerUsername( act ) + ':' + getServerPassword( act ) + '@' );
}
/**
* Get the server password
* @param act
* @return
*/
public static String getServerPassword( Context act )
{
return getPrefs( act ).getString( "server.password", "password" );
}
/**
* Get the server username
* @param act
* @return
*/
public static String getServerUsername( Context act )
{
return getPrefs( act ).getString( "server.username", "admin" );
}
/**
* Get the number of rows to display
* @param act
* @return
*/
public static int getDisplayRows( Activity act )
{
return getPrefs( act ).getInt( "display.rows", 9 );
}
public static int getDisplayWidth( Activity act )
{
final Display display = act.getWindowManager().getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
return size.x;
}
public static int getTextViewHeight( Activity act )
{
final Display display = act.getWindowManager().getDefaultDisplay();
final Point size = new Point();
display.getSize( size );
final int height = size.y;
final int numRows = getPrefs( act ).getInt( "display.rows", 9 );
final int TEXT_VIEW_HEIGHT = height / numRows;
return TEXT_VIEW_HEIGHT;
}
public static int getTextMaxHeight( Activity act )
{
return getTextViewHeight( act ) * 9 / 10;
}
/**
* Play a url
* @param activity
* @param url
* @param ext
*/
public static void playUrl( Activity act, String url, String ext )
{
Log.d( TAG, "playUrl(" + url + ',' + ext + ')' );
final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension( ext );
final Intent mediaIntent = new Intent( Intent.ACTION_VIEW );
mediaIntent.setDataAndType( Uri.parse( url ), mimeType );
act.startActivity( mediaIntent );
}
/**
* Start an activity
* @param act
* @param i
*/
public static void startActivityForResult( Activity act, Intent i )
{
if ( act.getIntent().hasExtra( "ACT_INDEX" ) )
{
int myIndex = act.getIntent().getIntExtra( "ACT_INDEX", 1 );
i.putExtra( "ACT_INDEX", myIndex + 1 );
Log.d( TAG, "Starting activity from " + act.getClass().getSimpleName() + '[' + ( myIndex + 1 ) + ']' );
act.startActivityForResult( i, myIndex + 1 );
}
else
{
i.putExtra( "ACT_INDEX", 1 );
Log.d( TAG, "Starting activity from " + act.getClass().getSimpleName() + '[' + 1 + ']' );
act.startActivityForResult( i, 1 );
}
}
}
| Updated to use new context root
| src/net/sf/openmm/frontend2/OpenMMUtil.java | Updated to use new context root |
|
Java | mit | e2309bd7d38693f59b68a775034c4c5c4b8990e9 | 0 | asampley/CMPUT301,CMPUT301W16T15/Shareo | package cmput301w16t15.shareo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.honorato.multistatetogglebutton.MultiStateToggleButton;
import org.honorato.multistatetogglebutton.ToggleButton;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import mvc.AppUserSingleton;
import mvc.Bid;
import mvc.Thing;
import mvc.User;
/**
* Fragment: bids main page.
* offered and bids are the two options using the multistatetoggle button.
*/
public class BidsFragment extends Fragment implements Observer {
private User mUser;
private ListView mList;
private ArrayAdapter mListAdapter;
private TextView mEmptyMessage;
private int mPosition = 0;
private List<?> data;
public BidsFragment() {
// Required empty public constructor
}
public static BidsFragment newInstance() {
return new BidsFragment();
}
/*
* The listview renders either the items I am bidding on, or my items other's are bidding on
* Based on mSelectedMode this function renders the appropriate data in the listivew
* */
private void setAdapterBasedOnTab() {
switch (mPosition) {
case 0:
new GetOffersTask().execute();
break;
case 1:
new GetBidsTask().execute();
break;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// user singleton...used for getting data
mUser = AppUserSingleton.getInstance().getUser();
//mUser.addObserver(this);
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_bids, container, false);
mList = (ListView) v.findViewById(R.id.listview);
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
if (mPosition == 0) {
AcceptDeclineBidsFragment adbf = new AcceptDeclineBidsFragment();
final Bundle bundle = new Bundle();
bundle.putInt("pos", position);
bundle.putSerializable("myThing", (Thing) data.get(position));
adbf.setArguments(bundle);
adbf.show(getFragmentManager(), "accept_decline");
} else {
ViewBidFragment vgf = new ViewBidFragment();
final Bundle bundle = new Bundle();
bundle.putSerializable("myThing", (Bid) data.get(position));
vgf.setArguments(bundle);
vgf.show(getFragmentManager(), "viewGame");
}
}
});
mEmptyMessage = (TextView) v.findViewById(R.id.empty_notice);
MultiStateToggleButton button = (MultiStateToggleButton) v.findViewById(R.id.mstb_multi_id);
button.setElements(R.array.bids_choices, 0);
button.setOnValueChangedListener(new ToggleButton.OnValueChangedListener() {
@Override
public void onValueChanged(int position) {
mPosition = position;
setAdapterBasedOnTab();
}
});
setAdapterBasedOnTab();
return v;
}
@Override
public void update(Observable observable, Object data) {
mListAdapter.notifyDataSetChanged();
}
class GetBidsTask extends AsyncTask<String, Void, List<Bid>> {
@Override
protected List<Bid> doInBackground(String... params) {
return mUser.getBids();
}
@Override
protected void onPostExecute(List<Bid> d) {
data = d;
mListAdapter = new CustomAdapters.BasicBidAdapter(getActivity(), R.layout.minimal_thing_row, d);
mList.setAdapter(mListAdapter);
if (d.size() == 0) {
mEmptyMessage.setVisibility(View.VISIBLE);
} else {
mEmptyMessage.setVisibility(View.GONE);
}
}
}
class GetOffersTask extends AsyncTask<String, Void, List<Thing>> {
@Override
protected List<Thing> doInBackground(String... params) {
return mUser.getOffers();
}
@Override
protected void onPostExecute(List<Thing> d) {
data = d;
mListAdapter = new CustomAdapters.BasicThingAdapter(getActivity(), R.layout.minimal_thing_row, d);
mList.setAdapter(mListAdapter);
if (d.size() == 0) {
mEmptyMessage.setVisibility(View.VISIBLE);
} else {
mEmptyMessage.setVisibility(View.GONE);
}
}
}
}
| app/src/main/java/cmput301w16t15/shareo/BidsFragment.java | package cmput301w16t15.shareo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.honorato.multistatetogglebutton.MultiStateToggleButton;
import org.honorato.multistatetogglebutton.ToggleButton;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import mvc.AppUserSingleton;
import mvc.Bid;
import mvc.Thing;
import mvc.User;
/**
* Fragment: bids main page.
* offered and bids are the two options using the multistatetoggle button.
*/
public class BidsFragment extends Fragment implements Observer {
private User mUser;
private ListView mList;
private ArrayAdapter mListAdapter;
private TextView mEmptyMessage;
private int mPosition = 0;
public BidsFragment() {
// Required empty public constructor
}
public static BidsFragment newInstance() {
return new BidsFragment();
}
/*
* The listview renders either the items I am bidding on, or my items other's are bidding on
* Based on mSelectedMode this function renders the appropriate data in the listivew
* */
private void setAdapterBasedOnTab() {
switch (mPosition) {
case 0:
new GetOffersTask().execute();
break;
case 1:
new GetBidsTask().execute();
break;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// user singleton...used for getting data
mUser = AppUserSingleton.getInstance().getUser();
//mUser.addObserver(this);
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_bids, container, false);
mList = (ListView) v.findViewById(R.id.listview);
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
if (mPosition == 0) {
AcceptDeclineBidsFragment adbf = new AcceptDeclineBidsFragment();
final Bundle bundle = new Bundle();
bundle.putInt("pos", position);
try {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
bundle.putSerializable("myThing", (Thing) mList.getItemAtPosition(position));
}
});
t.start();
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
adbf.setArguments(bundle);
adbf.show(getFragmentManager(), "accept_decline");
} else {
ViewBidFragment vgf = new ViewBidFragment();
final Bundle bundle = new Bundle();
// start new thread to avoid network on main thread.
try {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
bundle.putSerializable("myThing", (Bid) mList.getItemAtPosition(position));
}
});
t.start();
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
vgf.setArguments(bundle);
vgf.show(getFragmentManager(), "viewGame");
}
}
});
mEmptyMessage = (TextView) v.findViewById(R.id.empty_notice);
MultiStateToggleButton button = (MultiStateToggleButton) v.findViewById(R.id.mstb_multi_id);
button.setElements(R.array.bids_choices, 0);
button.setOnValueChangedListener(new ToggleButton.OnValueChangedListener() {
@Override
public void onValueChanged(int position) {
mPosition = position;
setAdapterBasedOnTab();
}
});
setAdapterBasedOnTab();
return v;
}
@Override
public void update(Observable observable, Object data) {
mListAdapter.notifyDataSetChanged();
}
class GetBidsTask extends AsyncTask<String, Void, List<Bid>> {
@Override
protected List<Bid> doInBackground(String... params) {
return mUser.getBids();
}
@Override
protected void onPostExecute(List<Bid> d) {
mListAdapter = new CustomAdapters.BasicBidAdapter(getActivity(), R.layout.minimal_thing_row, d);
mList.setAdapter(mListAdapter);
if (d.size() == 0) {
mEmptyMessage.setVisibility(View.VISIBLE);
} else {
mEmptyMessage.setVisibility(View.GONE);
}
}
}
class GetOffersTask extends AsyncTask<String, Void, List<Thing>> {
@Override
protected List<Thing> doInBackground(String... params) {
return mUser.getOffers();
}
@Override
protected void onPostExecute(List<Thing> d) {
mListAdapter = new CustomAdapters.BasicThingAdapter(getActivity(), R.layout.minimal_thing_row, d);
mList.setAdapter(mListAdapter);
if (d.size() == 0) {
mEmptyMessage.setVisibility(View.VISIBLE);
} else {
mEmptyMessage.setVisibility(View.GONE);
}
}
}
}
| store data in member to avoid network call
| app/src/main/java/cmput301w16t15/shareo/BidsFragment.java | store data in member to avoid network call |
|
Java | mit | 0c2f301e972da83e3055a9117c1cdbf6ecfed72d | 0 | qw3rtman/jbin | import java.io.*;
import java.util.Scanner;
public class jbin
{
public static void jarToBinary(String jar, String binary) throws IOException, InterruptedException
{
try {
try {
File binaryFile = new File(binary);
// Deletes file if exists.
binaryFile.delete();
// Creates blank file.
binaryFile.createNewFile();
} catch (FileNotFoundException e) {
} catch (IOException e) {
System.out.println("Error reading file '" + binary + "'.");
}
// Creates executable binary.
try {
byte[] buffer = new byte[(int) (new File(jar)).length()];
FileInputStream shebangInputStream = new FileInputStream("shebang.txt");
FileInputStream jarInputStream = new FileInputStream(jar);
int shebangRead = 0;
int jarRead = 0;
while((jarRead = jarInputStream.read(buffer)) != -1 && (shebangRead = shebangInputStream.read(buffer)) != -1) {
FileOutputStream outputStream = new FileOutputStream(binary);
outputStream.write(buffer);
outputStream.close();
}
shebangInputStream.close();
jarInputStream.close();
} catch (FileNotFoundException e) {
System.out.println("Unable to open file '" + jar + "'.");
} catch (IOException e) {
System.out.println("Error reading file '" + jar + "'.");
}
// Allow execution.
try {
File binaryFile = new File(binary);
binaryFile.setExecutable(true);
} catch (SecurityException e) { // If permissions are not sufficient.
System.out.println("Unable to set '" + binary + "' to executable.");
System.out.println("Do this manually with: chmod +x " + binary);
}
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
public static void sourceToJAR(String main, )
{
}
public static void main(String[] args) throws IOException, InterruptedException {
if (args.length == 2) {
jbin.jarToBinary(args[0], args[1]);
}
}
}
| src/jbin.java | import java.io.*;
import java.util.Scanner;
public class jbin
{
public static void jarToBinary(String jar, String binary) throws IOException, InterruptedException
{
try {
// Deletes file if exists.
try {
File binaryFile = new File(binary);
binaryFile.delete();
} catch (FileNotFoundException e) {
} catch (IOException e) {
System.out.println("Error reading file '" + binary + "'.");
}
// Creates blank file.
Process pTouch = Runtime.getRuntime().exec(new String[]{"touch", binary});
pTouch.waitFor();
// Creates executable binary.
try {
byte[] buffer = new byte[(int) (new File(jar)).length()];
FileInputStream shebangInputStream = new FileInputStream("shebang.txt");
FileInputStream jarInputStream = new FileInputStream(jar);
int shebangRead = 0;
int jarRead = 0;
while((jarRead = jarInputStream.read(buffer)) != -1 && (shebangRead = shebangInputStream.read(buffer)) != -1) {
FileOutputStream outputStream = new FileOutputStream(binary);
outputStream.write(buffer);
outputStream.close();
}
shebangInputStream.close();
jarInputStream.close();
} catch (FileNotFoundException e) {
System.out.println("Unable to open file '" + jar + "'.");
} catch (IOException e) {
System.out.println("Error reading file '" + jar + "'.");
}
// Allow execution.
try {
File binaryFile = new File(binary);
binaryFile.setExecutable(true);
} catch (SecurityException e) { // If permissions are not sufficient.
System.out.println("Unable to set '" + binary + "' to executable.");
System.out.println("Do this manually with: chmod +x " + binary);
}
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
public static void sourceToJAR(String main, )
{
}
public static void main(String[] args) throws IOException, InterruptedException {
if (args.length == 2) {
jbin.jarToBinary(args[0], args[1]);
}
}
}
| Group delete and create new file into same try block and replace create new file with Java File API.
| src/jbin.java | Group delete and create new file into same try block and replace create new file with Java File API. |
|
Java | epl-1.0 | 38e1fd79c34f7b7b8b15655201804c123a03d005 | 0 | spring-projects/eclipse-integration-commons,spring-projects/eclipse-integration-commons,spring-projects/eclipse-integration-commons | /*******************************************************************************
* Copyright (c) 2012 - 2013 GoPivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* GoPivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.preferences;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;
import org.eclipse.core.runtime.IProduct;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.springsource.ide.eclipse.commons.core.HttpUtil;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
/**
* An instance of this class provides a mechanism to retrieve String properties.
* This is similar to a Java system properties. However it has support for reading these
* properties from a fixed url. This allows us to change the properties after release.
* <p>
* Properties in this class can come from 3 different sources, listed here in
* decreasing order of priority:
*
* 1) Java System properties (set via -Dmy.prop.name=value) in STS.ini
* (properties set this way override anything else).
* 2) loaded from fixed url
* 3) default values hard-coded in this class.
* (used only if property was not set via either 1 or 2).
*
* @since 3.4.M1
*
* @author Kris De Volder
*/
public class StsProperties {
private static final String PROPERTIES_URL_PROPERTY = "sts.properties.url";
/**
* The properties url is normally defined as a property on the active product {@link IProduct}).
* See the product plugin i.e. 'org.springsource.sts' and 'org.springsource.ggts' for toolsuite-distribution repo.
* <p>
* If STS or GGTS is installed from update site then product may actually be STS or GGTS. In that case
* the 'no_product.properties' url will be used.
*/
private static final String NO_PRODUCT_PROPERTIES = "http://dist.springsource.com/release/STS/discovery/no_product.properties";
//Note: there is also a class called 'ResourceProvider'.. which reads various properties
// from eclipse extension points. This is different because the STSProperties themselves
// are read from an external url.
//The ResourceProvider only allows properties to defined by extensions contained in plugins
// installed into the Ecliple platform.
/**
* This class is a singleton. This holds the instance once created.
*/
private static StsProperties instance = null;
public static StsProperties getInstance(IProgressMonitor mon) {
if (instance==null) {
StsProperties newInstance = new StsProperties(determineUrl(), mon);
instance = newInstance;
}
return instance;
}
private final Properties props;
private StsProperties(String url, IProgressMonitor mon) {
props = createProperties();
if (url!=null) {
try {
InputStream content = HttpUtil.stream(new URI(url), mon);
if (content != null) {
try {
props.load(content);
} finally {
content.close();
}
}
} catch (Throwable e) {
//Catch and log all exceptions. This should never fail to initialise *something* usable.
CorePlugin.warn("Couldn't read sts properties from '"+url+"' internal default values will be used");
}
}
}
/**
* Determines the URL from where the properties file shall be read.
*/
private static String determineUrl() {
//Allow easy overriding by setting a system property:
String url = System.getProperty(PROPERTIES_URL_PROPERTY);
if (url==null) {
IProduct product = Platform.getProduct();
if (product!=null) {
url = product.getProperty(PROPERTIES_URL_PROPERTY);
}
}
if (url==null) {
url = NO_PRODUCT_PROPERTIES;
}
return url;
}
protected Properties createProperties() {
Properties props = new Properties();
// Default properties (guarantees certain properties have a value no
// matter what).
props.put("spring.site.url", "http://springsource.org");
props.put("spring.initializr.form.url", "http://start.springframework.io/");
props.put("spring.initializr.download.url", "http://start.springframework.io/starter.zip");
//Urls used in the dashboard. For each XXX.url=... property, if
// - XXX.url.label is defined that label will be used for the corresponding
// dashboard tab instead of the html page title (title tends to be too long).
// - XXX.url.external is defined that url will always be openened in an external browser.
//Switch to enable new dash
props.put("sts.new.dashboard.enabled", "false");
//Points to where the content for the dash is. If a platform url it will be interpreted as a directory to be
// copied and 'instantiated' by substituting StsProperties. If a non-platform url then it will
// passed directly to the browser without further processing.
// This default value points to a bundled STS dashboard welcome page.
props.put("dashboard.welcome.url", "platform:/plugin/org.springsource.ide.eclipse.commons.gettingstarted/resources/welcome");
//Forum:
props.put("sts.forum.url", "http://forum.springsource.org/forumdisplay.php?32-SpringSource-Tool-Suite");
props.put("sts.forum.url.label", "Forum");
props.put("sts.forum.url.external", "true");
//Tracker:
props.put("sts.tracker.url", "https://issuetracker.springsource.com/browse/STS");
props.put("sts.tracker.url.label", "Issues");
props.put("sts.tracker.url.external", "true");
//Docs
props.put("spring.docs.url", "http://www.springsource.org/documentation");
props.put("spring.docs.url.label", "Spring Docs");
props.put("spring.docs.url.external", "true");
//Blog
props.put("spring.blog.url", "http://blog.springsource.org");
props.put("spring.blog.url.label", "Blog");
props.put("spring.blog.url.external", "true");
//Guides
props.put("spring.guides.url", "http://www.springsource.org/get-started");
props.put("spring.guides.url.label", "Guides");
props.put("spring.guides.url.external", "true");
//future value: "${spring.site.url}/guides"
//New and Noteworthy
props.put("sts.nan.url", "http://static.springsource.org/sts/nan/latest/NewAndNoteworthy.html");
//props.put("sts.nan.url.external", "true");
return props;
}
/**
* Procudes names of properties that have explicitly been set, either from properties file
* or by the explicitly provided defaults. More precisely this does not return
* properties simply inherited from Java system properties.
*/
public Collection<String> getExplicitProperties() {
ArrayList<String> keys = new ArrayList<String>();
for (Object string : props.keySet()) {
if (string instanceof String) {
keys.add((String) string);
}
}
return keys;
}
public String get(String key) {
String value = System.getProperty(key);
if (value == null) {
value = props.getProperty(key);
}
return value;
}
public boolean get(String key, boolean deflt) {
String value = get(key);
if (value!=null) {
return Boolean.valueOf(value);
}
return deflt;
}
}
| org.springsource.ide.eclipse.commons.core/src/org/springsource/ide/eclipse/commons/core/preferences/StsProperties.java | /*******************************************************************************
* Copyright (c) 2012 - 2013 GoPivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* GoPivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.preferences;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;
import org.eclipse.core.runtime.IProduct;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.springsource.ide.eclipse.commons.core.HttpUtil;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
/**
* An instance of this class provides a mechanism to retrieve String properties.
* This is similar to a Java system properties. However it has support for reading these
* properties from a fixed url. This allows us to change the properties after release.
* <p>
* Properties in this class can come from 3 different sources, listed here in
* decreasing order of priority:
*
* 1) Java System properties (set via -Dmy.prop.name=value) in STS.ini
* (properties set this way override anything else).
* 2) loaded from fixed url
* 3) default values hard-coded in this class.
* (used only if property was not set via either 1 or 2).
*
* @since 3.4.M1
*
* @author Kris De Volder
*/
public class StsProperties {
private static final String PROPERTIES_URL_PROPERTY = "sts.properties.url";
/**
* The properties url is normally defined as a property on the active product {@link IProduct}).
* See the product plugin i.e. 'org.springsource.sts' and 'org.springsource.ggts' for toolsuite-distribution repo.
* <p>
* If STS or GGTS is installed from update site then product may actually be STS or GGTS. In that case
* the 'no_product.properties' url will be used.
*/
private static final String NO_PRODUCT_PROPERTIES = "http://dist.springsource.com/release/STS/discovery/no_product.properties";
//Note: there is also a class called 'ResourceProvider'.. which reads various properties
// from eclipse extension points. This is different because the STSProperties themselves
// are read from an external url.
//The ResourceProvider only allows properties to defined by extensions contained in plugins
// installed into the Ecliple platform.
/**
* This class is a singleton. This holds the instance once created.
*/
private static StsProperties instance = null;
public static StsProperties getInstance(IProgressMonitor mon) {
if (instance==null) {
StsProperties newInstance = new StsProperties(determineUrl(), mon);
instance = newInstance;
}
return instance;
}
private final Properties props;
private StsProperties(String url, IProgressMonitor mon) {
props = createProperties();
if (url!=null) {
try {
InputStream content = HttpUtil.stream(new URI(url), mon);
if (content != null) {
try {
props.load(content);
} finally {
content.close();
}
}
} catch (Throwable e) {
//Catch and log all exceptions. This should never fail to initialise *something* usable.
CorePlugin.warn("Couldn't read sts properties from '"+url+"' internal default values will be used");
}
}
}
/**
* Determines the URL from where the properties file shall be read.
*/
private static String determineUrl() {
//Allow easy overriding by setting a system property:
String url = System.getProperty(PROPERTIES_URL_PROPERTY);
if (url==null) {
IProduct product = Platform.getProduct();
if (product!=null) {
url = product.getProperty(PROPERTIES_URL_PROPERTY);
}
}
if (url==null) {
url = NO_PRODUCT_PROPERTIES;
}
return url;
}
protected Properties createProperties() {
Properties props = new Properties();
// Default properties (guarantees certain properties have a value no
// matter what).
props.put("spring.site.url", "http://springsource.org");
props.put("spring.initializr.form.url", "http://start.springframework.io/");
props.put("spring.initializr.download.url", "http://start.springframework.io/starter.zip");
//Urls used in the dashboard. For each XXX.url=... property, if
// - XXX.url.label is defined that label will be used for the corresponding
// dashboard tab instead of the html page title (title tends to be too long).
// - XXX.url.external is defined that url will always be openened in an external browser.
//Switch to enable new dash
props.put("sts.new.dashboard.enabled", "false");
//Points to where the content for the dash is. If a platform url it will be interpreted as a directory to be
// copied and 'instantiated' by substituting StsProperties. If a non-platform url then it will
// passed directly to the browser without further processing.
// This default value points to a bundled STS dashboard welcome page.
props.put("dashboard.welcome.url", "platform:/plugin/org.springsource.ide.eclipse.commons.gettingstarted/resources/welcome");
//Forum:
props.put("sts.forum.url", "http://forum.springsource.org/forumdisplay.php?32-SpringSource-Tool-Suite");
props.put("sts.forum.url.label", "Forum");
props.put("sts.forum.url.external", "true");
//Tracker:
props.put("sts.tracker.url", "https://issuetracker.springsource.com/browse/STS");
props.put("sts.tracker.url.label", "Issues");
props.put("sts.tracker.url.external", "true");
//Docs
props.put("spring.docs.url", "http://www.springsource.org/documentation");
props.put("spring.docs.url.label", "Spring Docs");
props.put("spring.docs.url.external", "true");
//Blog
props.put("spring.blog.url", "http://blog.springsource.org");
props.put("spring.blog.url.label", "Blog");
props.put("spring.blog.url.external", "true");
//Guides
props.put("spring.guides.url", "http://www.springsource.org/get-started");
props.put("spring.guides.url.label", "Guides");
props.put("spring.guides.url.external", "true");
//future value: "${spring.site.url}/guides"
//New and Noteworthy
props.put("sts.nan.url", "http://static.springsource.org/sts/nan/latest/NewAndNoteworthy.html");
props.put("spring.guides.url.external", "true");
return props;
}
/**
* Procudes names of properties that have explicitly been set, either from properties file
* or by the explicitly provided defaults. More precisely this does not return
* properties simply inherited from Java system properties.
*/
public Collection<String> getExplicitProperties() {
ArrayList<String> keys = new ArrayList<String>();
for (Object string : props.keySet()) {
if (string instanceof String) {
keys.add((String) string);
}
}
return keys;
}
public String get(String key) {
String value = System.getProperty(key);
if (value == null) {
value = props.getProperty(key);
}
return value;
}
public boolean get(String key, boolean deflt) {
String value = get(key);
if (value!=null) {
return Boolean.valueOf(value);
}
return deflt;
}
}
| Small fix to StsProperties default | org.springsource.ide.eclipse.commons.core/src/org/springsource/ide/eclipse/commons/core/preferences/StsProperties.java | Small fix to StsProperties default |
|
Java | mpl-2.0 | 6e179f16075848be417f2501cb4305450f431054 | 0 | johan12345/substitution-schedule-parser,johan12345/substitution-schedule-parser,vertretungsplanme/substitution-schedule-parser,vertretungsplanme/substitution-schedule-parser | /*
* substitution-schedule-parser - Java library for parsing schools' substitution schedules
* Copyright (c) 2016 Johan v. Forstner
*
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package me.vertretungsplan.parser;
import me.vertretungsplan.exception.CredentialInvalidException;
import me.vertretungsplan.objects.Substitution;
import me.vertretungsplan.objects.SubstitutionSchedule;
import me.vertretungsplan.objects.SubstitutionScheduleData;
import me.vertretungsplan.objects.SubstitutionScheduleDay;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.*;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Contains common code used by {@link UntisInfoParser}, {@link UntisInfoHeadlessParser}, {@link UntisMonitorParser}
* and {@link UntisSubstitutionParser}.
*
* <h4>Configuration parameters</h4>
* These parameters can be supplied in {@link SubstitutionScheduleData#setData(JSONObject)} in addition to the
* parameters specified in the documentation of the parser itself.
*
* <dl>
* <dt><code>columns</code> (Array of Strings, required)</dt>
* <dd>The order of columns used in the substitutions table. Entries can be: <code>"lesson", "subject",
* "previousSubject", "type", "type-entfall", "room", "previousRoom", "teacher", "previousTeacher", desc",
* "desc-type", "substitutionFrom", "teacherTo", "class", "ignore"</code> (<code>"class"</code> only works when
* <code>classInExtraLine</code> is <code>false</code>.
* </dd>
*
* <dt><code>lastChangeLeft</code> (Boolean, optional)</dt>
* <dd>Whether the date of last change is in the top left corner instead of in the <code>.mon_head</code> table.
* Default: <code>false</code></dd>
*
* <dt><code>classInExtraLine</code> (Boolean, optional)</dt>
* <dd>Whether the changes in the table are grouped using headers containing the class name(s). Default:
* <code>false</code></dd>
*
* <dt><code>teacherInExtraLine</code> (Boolean, optional)</dt>
* <dd>Whether the changes in the table are grouped using headers containing the teacher name. Default:
* <code>false</code></dd>
*
* <dt><code>classesSeparated</code> (Boolean, optional)</dt>
* <dd>Whether the class names are separated by commas. If this is set to <code>false</code>, combinations like "5abcde"
* are attempted to be accounted for using an ugly algorithm based on RegExes generated from {@link #getAllClasses()}.
* Default: <code>true</code></dd>
*
* <dt><code>excludeClasses</code> (Array of Strings, optional)</dt>
* <dd>Substitutions for classes from this Array are ignored when reading the schedule. By default, only the class
* <code>"-----"</code> is ignored.</dd>
*
* <dt><code>classRegex</code> (String, optional)</dt>
* <dd>RegEx to modify the classes set on the schedule (in {@link #getSubstitutionSchedule()}, not
* {@link #getAllClasses()}. The RegEx is matched against the class using {@link Matcher#find()}. If the RegEx
* contains a group, the content of the first group {@link Matcher#group(int)} is used as the resulting class.
* Otherwise, {@link Matcher#group()} is used. If the RegEx cannot be matched ({@link Matcher#find()} returns
* <code>false</code>), the class is set to an empty string.
* </dd>
*
* <dt><code>typeAutoDetection</code> (Boolean, optional)</dt>
* <dd>If there is no type column and the detection using desc-type did not work, this sets whether the type may be
* automatically set to "Entfall" (cancellation) depending on the values of other columns.
* Default: <code>true</code></dd>
*
* <dt><code>allClassesCourses</code> (Array of Strings, optional)</dt>
* <dd>If a class included in this array is given on the schedule, this will be replaced by a list of all classes.
* This is useful for courses that all or multiple classes can attend, but that are saved as a separate class in Untis.
* Default: empty</dd>
*
* </dl>
*/
public abstract class UntisCommonParser extends BaseParser {
private static final String[] EXCLUDED_CLASS_NAMES = new String[]{"-----"};
private static final String PARAM_LAST_CHANGE_LEFT = "lastChangeLeft";
private static final String PARAM_LAST_CHANGE_SELECTOR = "lastChangeSelector"; // only used in UntisMonitorParser
private static final String PARAM_CLASS_IN_EXTRA_LINE = "classInExtraLine";
private static final String PARAM_TEACHER_IN_EXTRA_LINE = "teacherInExtraLine";
private static final String PARAM_COLUMNS = "columns";
private static final String PARAM_CLASSES_SEPARATED = "classesSeparated";
private static final String PARAM_EXCLUDE_CLASSES = "excludeClasses";
private static final String PARAM_TYPE_AUTO_DETECTION = "typeAutoDetection";
private static final String PARAM_MERGE_WITH_DIFFERENT_TYPE = "mergeWithDifferentType";
private static final String PARAM_ALL_CLASSES_COURSES = "allClassesCourses";
private static final String PARAM_EXCLUDE_TEACHERS = "excludeTeachers";
private static ColumnTypeDetector detector;
private static ColumnTypeDetector getDetector() throws IOException, JSONException {
if (detector == null) {
detector = new ColumnTypeDetector();
}
return detector;
}
UntisCommonParser(SubstitutionScheduleData scheduleData, CookieProvider cookieProvider) {
super(scheduleData, cookieProvider);
}
static String findLastChange(Element doc, SubstitutionScheduleData scheduleData) {
String lastChange = null;
boolean lastChangeLeft = false;
if (scheduleData != null) {
if (scheduleData.getData().has("stand_links")) {
// backwards compatibility
lastChangeLeft = scheduleData.getData().optBoolean("stand_links", false);
} else {
lastChangeLeft = scheduleData.getData().optBoolean(PARAM_LAST_CHANGE_LEFT, false);
}
}
if (doc.select("table.mon_head").size() > 0) {
Element monHead = doc.select("table.mon_head").first();
lastChange = findLastChangeFromMonHeadTable(monHead);
} else if (lastChangeLeft) {
final String bodyHtml = doc.select("body").size() > 0 ? doc.select("body").html() : doc.html();
lastChange = bodyHtml.substring(0, bodyHtml.indexOf("<p>") - 1);
} else {
List<Node> childNodes;
if (doc instanceof Document) {
childNodes = ((Document) doc).body().childNodes();
} else {
childNodes = doc.childNodes();
}
for (Node node : childNodes) {
if (node instanceof Comment) {
Comment comment = (Comment) node;
if (comment.getData().contains("<table class=\"mon_head\">")) {
Document commentedDoc = Jsoup.parse(comment.getData());
Element monHead = commentedDoc.select("table.mon_head").first();
lastChange = findLastChangeFromMonHeadTable(monHead);
break;
}
}
}
}
return lastChange;
}
private static String findLastChangeFromMonHeadTable(Element monHead) {
if (monHead.select("td[align=right]").size() == 0) return null;
String lastChange = null;
Pattern pattern = Pattern.compile("\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d \\d\\d:\\d\\d");
Matcher matcher = pattern.matcher(monHead.select("td[align=right]").first().text());
if (matcher.find()) {
lastChange = matcher.group();
} else if (monHead.text().contains("Stand: ")) {
lastChange = monHead.text().substring(monHead.text().indexOf("Stand:") + "Stand:".length()).trim();
}
return lastChange;
}
private static boolean equalsOrNull(String a, String b) {
return a == null || b == null || a.equals(b);
}
/**
* Parses an Untis substitution schedule table
*
* @param table the <code>table</code> Element from the HTML document
* @param data {@link SubstitutionScheduleData#getData()}
* @param day the {@link SubstitutionScheduleDay} where the substitutions will be stored
*/
void parseSubstitutionScheduleTable(Element table, JSONObject data,
SubstitutionScheduleDay day, List<String> allClasses)
throws JSONException, CredentialInvalidException, IOException {
parseSubstitutionScheduleTable(table, data, day, null, allClasses, false);
}
private void parseSubstitutionScheduleTable(Element table, JSONObject data,
SubstitutionScheduleDay day, String defaultClass, List<String>
allClasses)
throws CredentialInvalidException, IOException, JSONException {
parseSubstitutionScheduleTable(table, data, day, defaultClass, allClasses, false);
}
/**
* Parses an Untis substitution schedule table
*
* @param table the <code>table</code> Element from the HTML document
* @param data {@link SubstitutionScheduleData#getData()}
* @param day the {@link SubstitutionScheduleDay} where the substitutions will be stored
* @param defaultClass the class that should be set if there is no class column in the table
*/
private void parseSubstitutionScheduleTable(Element table, JSONObject data,
SubstitutionScheduleDay day, String defaultClass, List<String>
allClasses, boolean untisSubst)
throws JSONException, CredentialInvalidException, IOException {
Elements headerRows = table.select("tr:has(th)");
List<String> columnTitles = new ArrayList<>();
if (headerRows.size() > 0) {
Elements headers = headerRows.get(0).select("th");
for (int i = 0; i < headers.size(); i++) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (Element headerRow : headerRows) {
final String text = headerRow.select("th").get(i).text().replace("\u00a0", " ").trim();
if (first) {
if (!text.equals("")) first = false;
} else {
builder.append(" ");
}
builder.append(text);
}
columnTitles.add(builder.toString());
}
}
debuggingDataHandler.columnTitles(columnTitles);
final JSONArray columnsJson = data.optJSONArray(PARAM_COLUMNS);
List<String> columns = new ArrayList<>();
if (columnsJson != null && (columnTitles.size() == 0 || columnTitles.size() == columnsJson.length())) {
for (int i = 0; i < columnsJson.length(); i++) columns.add(columnsJson.getString(i));
} else {
for (String title : columnTitles) {
String type = getDetector().getColumnType(title, columnTitles);
if (type != null) {
columns.add(type);
} else {
if (columnsJson != null && columnsJson.length() == columnTitles.size()) {
columns.clear();
for (int i = 0; i < columnsJson.length(); i++) columns.add(columnsJson.getString(i));
} else {
throw new IOException("unknown column title: " + title);
}
break;
}
}
}
if (data.optBoolean(PARAM_CLASS_IN_EXTRA_LINE)
|| data.optBoolean("class_in_extra_line")) { // backwards compatibility
for (Element element : table.select("td.inline_header")) {
String className = getClassName(element.text(), data);
if (isValidClass(className, data)) {
parseWithExtraLine(data, day, columns, element, className, null);
}
}
} else if (data.optBoolean(PARAM_TEACHER_IN_EXTRA_LINE)) {
for (Element element : table.select("td.inline_header")) {
String teacherName = getClassName(element.text(), data);
parseWithExtraLine(data, day, columns, element, null, teacherName);
}
} else {
boolean hasType = false;
for (String column : columns) {
if (column.equals("type")) {
hasType = true;
}
}
int skipLines = 0;
for (Element zeile : table
.select("tr.list.odd:not(:has(td.inline_header)), "
+ "tr.list.even:not(:has(td.inline_header)), "
+ "tr:has(td[align=center]):gt(0)")) {
if (skipLines > 0) {
skipLines--;
continue;
}
final Element previousLine = zeile.previousElementSibling();
if (isGroupMessage(zeile) && previousLine != null && previousLine.select(".inline_header").size() > 0) {
addGroupMessage(day, getClassName(previousLine.text(), data), zeile);
continue;
}
Substitution v = new Substitution();
String klassen = defaultClass != null ? defaultClass : "";
String course = null;
int i = 0;
for (Element spalte : zeile.select("td")) {
String text = spalte.text();
String type = columns.get(i);
if (isEmpty(text) && !type.equals("type-entfall") && !type.equals("teacher")) {
i++;
continue;
}
int skipLinesForThisColumn = 0;
Element nextLine = zeile.nextElementSibling();
boolean continueSkippingLines = true;
while (continueSkippingLines) {
if (nextLine != null && nextLine.children().size() == zeile.children().size()) {
Element columnInNextLine = nextLine.child(spalte
.elementSiblingIndex());
String nextLineText = columnInNextLine.text().replaceAll("\u00A0", "").trim();
if (nextLineText.equals(
nextLine.text().replaceAll("\u00A0", "").trim())) {
if (untisSubst && i == 0 && !allClasses.contains(nextLineText.split(",")[0])) {
// this is a message, not a continuation of the first column
if (!day.getMessages().contains(nextLineText)) {
day.addMessage(nextLineText);
continueSkippingLines = false;
}
} else {
// Continued in the next line
text += " " + columnInNextLine.text();
skipLinesForThisColumn++;
nextLine = nextLine.nextElementSibling();
}
} else {
continueSkippingLines = false;
}
} else {
continueSkippingLines = false;
}
}
if (skipLinesForThisColumn > skipLines) skipLines = skipLinesForThisColumn;
switch (type) {
case "lesson":
v.setLesson(text);
break;
case "subject":
handleSubject(v, spalte, false);
if (course != null) {
v.setSubject((v.getSubject() != null ? v.getSubject() + " " : "") + course);
course = null;
}
break;
case "course":
if (v.getSubject() != null) {
v.setSubject(v.getSubject() + " " + text);
} else {
course = text;
}
break;
case "previousSubject":
handleSubject(v, spalte, true);
break;
case "type":
v.setType(text);
v.setColor(colorProvider.getColor(text));
break;
case "type-entfall":
if (text.equals("x")) {
v.setType("Entfall");
v.setColor(colorProvider.getColor("Entfall"));
} else if (!hasType && v.getType() == null) {
v.setType("Vertretung");
v.setColor(colorProvider.getColor("Vertretung"));
}
break;
case "room":
handleRoom(v, spalte, false);
break;
case "previousRoom":
handleRoom(v, spalte, true);
break;
case "desc":
v.setDesc(text);
break;
case "desc-type":
String recognizedType = recognizeType(text);
v.setType(recognizedType);
if (text.equals(recognizedType)) {
v.setDesc(null);
} else {
v.setDesc(text);
}
v.setColor(colorProvider.getColor(recognizedType));
break;
case "teacher":
if (text.equals("+")) {
v.setType("Eigenverantw. Arbeiten");
v.setColor(colorProvider.getColor(v.getType()));
} else if (!isEmpty(text)) {
handleTeacher(v, spalte, data, false);
}
break;
case "previousTeacher":
handleTeacher(v, spalte, data, true);
break;
case "substitutionFrom":
v.setSubstitutionFrom(text);
break;
case "teacherTo":
v.setTeacherTo(text);
break;
case "class":
klassen = text;
break;
case "ignore":
break;
case "date": // used by UntisSubstitutionParser
break;
default:
throw new IllegalArgumentException("Unknown column type: " + type);
}
i++;
}
if (course != null) {
v.setSubject(course);
}
if (v.getLesson() == null || v.getLesson().equals("")) {
continue;
}
autoDetectType(data, zeile, v);
handleClasses(data, v, klassen, allClasses);
if (data.optBoolean(PARAM_MERGE_WITH_DIFFERENT_TYPE, false)) {
boolean found = false;
for (Substitution subst : day.getSubstitutions()) {
if (subst.equalsExcludingType(v)) {
found = true;
if (v.getType().equals("Vertretung")) {
subst.setType("Vertretung");
subst.setColor(colorProvider.getColor("Vertretung"));
}
break;
}
}
if (!found) {
day.addSubstitution(v);
}
} else {
day.addSubstitution(v);
}
}
}
}
static void handleClasses(JSONObject data, Substitution v, String klassen, List<String> allClasses)
throws JSONException, CredentialInvalidException {
List<String> affectedClasses;
if (data.has(PARAM_ALL_CLASSES_COURSES)) {
JSONArray arr = data.getJSONArray(PARAM_ALL_CLASSES_COURSES);
for (int i = 0; i < arr.length(); i++) {
String s = arr.getString(i);
if (klassen.equals(s)) {
v.getClasses().addAll(allClasses);
return;
}
}
}
// Detect things like "7"
Pattern singlePattern = Pattern.compile("(\\d{1,2})");
Matcher singleMatcher = singlePattern.matcher(klassen);
// Detect things like "5-12"
Pattern rangePattern = Pattern.compile("(\\d+) ?- ?(\\d+)");
Matcher rangeMatcher = rangePattern.matcher(klassen);
boolean singleClassLooksLikeRange = false;
if (allClasses != null) {
for (String klass : allClasses) {
// disable range detection if single classes (e.g. "05-1") look like a range
if (rangePattern.matcher(klass).matches()) {
singleClassLooksLikeRange = true;
break;
}
}
}
Pattern pattern2 = Pattern.compile("^(\\d+).*");
if (rangeMatcher.matches() && !singleClassLooksLikeRange) {
affectedClasses = new ArrayList<>();
int min = Integer.parseInt(rangeMatcher.group(1));
int max = Integer.parseInt(rangeMatcher.group(2));
for (String klasse : allClasses) {
Matcher matcher2 = pattern2.matcher(klasse);
if (matcher2.matches()) {
int num = Integer.parseInt(matcher2.group(1));
if (min <= num && num <= max) affectedClasses.add(klasse);
}
}
} else if (singleMatcher.matches()) {
affectedClasses = new ArrayList<>();
int grade = Integer.parseInt(singleMatcher.group(1));
for (String klasse : allClasses) {
Matcher matcher2 = pattern2.matcher(klasse);
if (matcher2.matches() && grade == Integer.parseInt(matcher2.group(1))) {
affectedClasses.add(klasse);
}
}
} else {
if (data.optBoolean(PARAM_CLASSES_SEPARATED, true)
&& data.optBoolean("classes_separated", true)) { // backwards compatibility
affectedClasses = Arrays.asList(klassen.split(", "));
} else {
affectedClasses = new ArrayList<>();
if (allClasses.contains(klassen)) {
affectedClasses.add(klassen);
} else if (klassen.matches("([\\d]{1,2}[a-zA-Z]+)+")) {
// we have something like 8ab9abc -> 8a, 8b, 9a, 9b, 9c
Pattern pattern = Pattern.compile("([\\d]{1,2})([a-zA-Z]+)");
Matcher matcher = pattern.matcher(klassen);
while (matcher.find()) {
String base = matcher.group(1);
for (char letter : matcher.group(2).toCharArray()) {
if (allClasses.contains(base + letter)) {
affectedClasses.add(base + letter);
}
}
}
} else if (singleClassLooksLikeRange && klassen.matches("(\\d{1,2})-(\\d+)")) {
// we have something like 09-234 -> 09-2, 09-3, 09-4
Pattern pattern = Pattern.compile("(\\d{1,2})-(\\d+)");
Matcher matcher = pattern.matcher(klassen);
if (matcher.find()) {
String base = matcher.group(1);
for (char number : matcher.group(2).toCharArray()) {
if (allClasses.contains(base + "-" + number)) {
affectedClasses.add(base + "-" + number);
}
}
} else {
affectedClasses.add(klassen);
}
} else {
// fallback solution for backwards compatibility
for (String klasse : allClasses) {
StringBuilder regex = new StringBuilder();
for (char character : klasse.toCharArray()) {
if (character == '?') {
regex.append("\\?");
} else {
regex.append(character);
}
regex.append(".*");
}
if (klassen.matches(regex.toString())) {
affectedClasses.add(klasse);
}
}
}
}
}
for (String klasse : affectedClasses) {
String name = getClassName(klasse, data);
if (isValidClass(name, data)) {
v.getClasses().add(name);
}
}
}
private void parseWithExtraLine(JSONObject data, SubstitutionScheduleDay day, List<String> columns, Element element,
String className, String teacherName) {
Element zeile = null;
try {
zeile = element.parent().nextElementSibling();
if (zeile.select("td") == null) {
zeile = zeile.nextElementSibling();
}
int skipLines = 0;
while (zeile != null
&& !zeile.select("td").attr("class")
.equals("list inline_header")) {
if (skipLines > 0) {
skipLines--;
zeile = zeile.nextElementSibling();
continue;
}
if (isGroupMessage(zeile)) {
addGroupMessage(day, className != null ? className : teacherName, zeile);
zeile = zeile.nextElementSibling();
continue;
}
Substitution v = new Substitution();
String klassen = null;
String course = null;
int i = 0;
for (Element spalte : zeile.select("td")) {
String text = spalte.text();
String type = columns.get(i);
if (isEmpty(text) && !type.equals("teacher")) {
i++;
continue;
}
int skipLinesForThisColumn = 0;
Element nextLine = zeile.nextElementSibling();
boolean continueSkippingLines = true;
while (continueSkippingLines) {
if (nextLine != null && nextLine.children().size() == zeile.children().size()) {
Element columnInNextLine = nextLine.child(spalte
.elementSiblingIndex());
if (columnInNextLine.text().replaceAll("\u00A0", "").trim().equals(
nextLine.text().replaceAll("\u00A0", "").trim())) {
// Continued in the next line
text += " " + columnInNextLine.text();
skipLinesForThisColumn++;
nextLine = nextLine.nextElementSibling();
} else {
continueSkippingLines = false;
}
} else {
continueSkippingLines = false;
}
}
if (skipLinesForThisColumn > skipLines) skipLines = skipLinesForThisColumn;
switch (type) {
case "lesson":
v.setLesson(text);
break;
case "subject":
handleSubject(v, spalte, false);
if (course != null) {
v.setSubject((v.getSubject() != null ? v.getSubject() + " " : "") + course);
course = null;
}
break;
case "course":
if (v.getSubject() != null) {
v.setSubject(v.getSubject() + " " + text);
} else {
course = text;
}
break;
case "previousSubject":
handleSubject(v, spalte, true);
break;
case "type":
v.setType(text);
v.setColor(colorProvider.getColor(text));
break;
case "type-entfall":
if (text.equals("x")) {
v.setType("Entfall");
v.setColor(colorProvider.getColor("Entfall"));
} else if (v.getType() == null) {
v.setType("Vertretung");
v.setColor(colorProvider.getColor("Vertretung"));
}
break;
case "room":
handleRoom(v, spalte, false);
break;
case "teacher":
if (text.equals("+")) {
v.setType("Eigenverantw. Arbeiten");
v.setColor(colorProvider.getColor(v.getType()));
} else if (!isEmpty(text) && teacherName == null) {
handleTeacher(v, spalte, data, false);
} // otherwise ignore - teacher is in extra line
break;
case "previousTeacher":
handleTeacher(v, spalte, data, true);
break;
case "desc":
v.setDesc(text);
break;
case "desc-type":
String recognizedType = recognizeType(text);
v.setType(recognizedType);
if (text.equals(recognizedType)) {
v.setDesc(null);
} else {
v.setDesc(text);
}
v.setColor(colorProvider.getColor(recognizedType));
break;
case "previousRoom":
handleRoom(v, spalte, true);
break;
case "substitutionFrom":
v.setSubstitutionFrom(text);
break;
case "teacherTo":
v.setTeacherTo(text);
break;
case "ignore":
break;
case "date": // used by UntisSubstitutionParser
break;
case "class":
if (className == null) {
klassen = getClassName(text, data);
} // otherwise ignore - class is in extra line
break;
default:
throw new IllegalArgumentException("Unknown column type: " + type);
}
i++;
}
if (course != null) {
v.setSubject(course);
}
autoDetectType(data, zeile, v);
if (className != null) {
v.getClasses().add(className);
} else if (klassen != null) {
handleClasses(data, v, klassen, getAllClasses());
}
if (teacherName != null && !data.optBoolean(PARAM_EXCLUDE_TEACHERS)) {
v.setTeacher(teacherName);
}
if (v.getLesson() != null && !v.getLesson().equals("")) {
day.addSubstitution(v);
}
zeile = zeile.nextElementSibling();
}
} catch (Throwable e) {
e.printStackTrace();
}
}
private void addGroupMessage(SubstitutionScheduleDay day, String groupName, Element zeile) {
String message = "<b>" + groupName + ":</b> " + zeile.select("td").first().text();
day.addMessage(message);
}
private boolean isGroupMessage(Element zeile) {
return zeile.select("td").size() == 1 && zeile.select("td").first().hasAttr("colspan");
}
private void autoDetectType(JSONObject data, Element zeile, Substitution v) {
if (v.getType() == null) {
if (data.optBoolean(PARAM_TYPE_AUTO_DETECTION, true)) {
if ((zeile.select("strike").size() > 0 &&
equalsOrNull(v.getSubject(), v.getPreviousSubject()) &&
equalsOrNull(v.getTeacher(), v.getPreviousTeacher()))
|| (v.getSubject() == null && (v.getRoom() == null || v.getRoom().equals(v.getPreviousRoom()))
&& v.getTeacher() == null && v.getPreviousSubject() != null)) {
v.setType("Entfall");
v.setColor(colorProvider.getColor("Entfall"));
} else {
v.setType("Vertretung");
v.setColor(colorProvider.getColor("Vertretung"));
}
} else {
v.setType("Vertretung");
v.setColor(colorProvider.getColor("Vertretung"));
}
}
}
static void handleTeacher(Substitution subst, Element cell, JSONObject data, boolean previousTeacher) {
if (data.optBoolean(PARAM_EXCLUDE_TEACHERS)) return;
cell = getContentElement(cell);
if (cell.select("s").size() > 0) {
subst.setPreviousTeachers(splitTeachers(cell.select("s").text(), data));
if (cell.ownText().length() > 0) {
subst.setTeachers(splitTeachers(cell.ownText().replaceFirst("^\\?", "").replaceFirst("→", ""), data));
}
} else {
if (previousTeacher) {
subst.setPreviousTeachers(splitTeachers(cell.text(), data));
} else {
subst.setTeachers(splitTeachers(cell.text(), data));
}
}
}
private static Set<String> splitTeachers(String s, JSONObject data) {
Set<String> teachers = new HashSet<>();
if (data.optBoolean("splitTeachers", true)) {
teachers.addAll(Arrays.asList(s.split(", ")));
} else {
teachers.add(s);
}
return teachers;
}
static void handleRoom(Substitution subst, Element cell, boolean previousRoom) {
cell = getContentElement(cell);
if (cell.select("s").size() > 0) {
subst.setPreviousRoom(cell.select("s").text());
if (cell.ownText().length() > 0) {
subst.setRoom(cell.ownText().replaceFirst("^\\?", "").replaceFirst("→", ""));
}
} else {
if (previousRoom) {
subst.setPreviousRoom(cell.text());
} else {
subst.setRoom(cell.text());
}
}
}
private static Element getContentElement(Element cell) {
if (cell.ownText().isEmpty() && cell.select("> span").size() == 1) {
cell = cell.select("> span").first();
}
return cell;
}
static void handleSubject(Substitution subst, Element cell, boolean previousSubject) {
cell = getContentElement(cell);
if (cell.select("s").size() > 0) {
subst.setPreviousSubject(cell.select("s").text());
if (cell.ownText().length() > 0) {
subst.setSubject(cell.ownText().replaceFirst("^\\?", "").replaceFirst("→", ""));
}
} else {
if (previousSubject) {
subst.setPreviousSubject(cell.text());
} else {
subst.setSubject(cell.text());
}
}
}
private boolean isEmpty(String text) {
final String trim = text.replaceAll("\u00A0", "").trim();
return trim.equals("") || trim.equals("---") || trim.equals("+");
}
/**
* Parses a "Nachrichten zum Tag" ("daily news") table from an Untis schedule
*
* @param table the <code>table</code>-Element to be parsed
* @param day the {@link SubstitutionScheduleDay} where the messages should be stored
*/
private void parseMessages(Element table, SubstitutionScheduleDay day) {
Elements zeilen = table
.select("tr:not(:contains(Nachrichten zum Tag))");
for (Element i : zeilen) {
Elements spalten = i.select("td");
String info = "";
for (Element b : spalten) {
info += "\n"
+ TextNode.createFromEncoded(b.html(), null)
.getWholeText();
}
info = info.substring(1); // remove first \n
day.addMessage(info);
}
}
SubstitutionScheduleDay parseMonitorDay(Element doc, JSONObject data) throws
JSONException, CredentialInvalidException, IOException {
SubstitutionScheduleDay day = new SubstitutionScheduleDay();
String date = doc.select(".mon_title").first().text().replaceAll(" \\(Seite \\d+ / \\d+\\)", "");
day.setDateString(date);
day.setDate(ParserUtils.parseDate(date));
Pattern weekTypePattern =
Pattern.compile("Woche [A-Z]|[^\\s]*unterricht Gruppe .*|Unterrichts[^\\s]* Gruppe .*");
Matcher matcher = weekTypePattern.matcher(date);
if (matcher.find()) {
day.setComment(matcher.group());
}
if (!scheduleData.getData().has(PARAM_LAST_CHANGE_SELECTOR)) {
String lastChange = findLastChange(doc, scheduleData);
day.setLastChangeString(lastChange);
day.setLastChange(ParserUtils.parseDateTime(lastChange));
}
// NACHRICHTEN
if (doc.select("table.info").size() > 0) {
parseMessages(doc.select("table.info").first(), day);
}
// VERTRETUNGSPLAN
if (doc.select("table:has(tr.list)").size() > 0) {
parseSubstitutionScheduleTable(doc.select("table:has(tr.list)").first(), data, day, getAllClasses());
}
return day;
}
private static boolean isValidClass(String klasse, JSONObject data) throws JSONException {
return klasse != null && !Arrays.asList(EXCLUDED_CLASS_NAMES).contains(klasse) &&
!(data.has(PARAM_EXCLUDE_CLASSES) &&
contains(data.getJSONArray(PARAM_EXCLUDE_CLASSES), klasse)) &&
!(data.has("exclude_classes") && // backwards compatibility
contains(data.getJSONArray("exclude_classes"), klasse));
}
@Override
public List<String> getAllClasses() throws IOException, JSONException, CredentialInvalidException {
return getClassesFromJson();
}
void parseDay(SubstitutionScheduleDay day, Element next, SubstitutionSchedule v, String klasse, List<String>
allClasses) throws
JSONException, CredentialInvalidException, IOException {
if (next.children().size() == 0) {
next = next.nextElementSibling();
}
if (next.className().equals("subst") || next.select(".list").size() > 0
|| next.text().contains("Vertretungen sind nicht freigegeben")
|| next.text().contains("Keine Vertretungen")) {
//Vertretungstabelle
if (next.text().contains("Vertretungen sind nicht freigegeben")) {
return;
}
parseSubstitutionScheduleTable(next, scheduleData.getData(), day, klasse, allClasses);
} else {
//Nachrichten
parseMessages(next, day);
next = next.nextElementSibling().nextElementSibling();
parseSubstitutionScheduleTable(next, scheduleData.getData(), day, klasse, allClasses);
}
v.addDay(day);
}
void parseMultipleMonitorDays(SubstitutionSchedule v, Document doc, JSONObject data)
throws JSONException, CredentialInvalidException, IOException {
if (doc.select(".mon_head").size() > 1) {
for (int j = 0; j < doc.select(".mon_head").size(); j++) {
Document doc2 = Document.createShell(doc.baseUri());
doc2.body().appendChild(doc.select(".mon_head").get(j).clone());
Element next = doc.select(".mon_head").get(j).nextElementSibling();
if (next != null && next.tagName().equals("center")) {
doc2.body().appendChild(next.select(".mon_title").first().clone());
if (next.select("table:has(tr.list)").size() > 0) {
doc2.body().appendChild(next.select("table:has(tr.list)").first());
}
if (next.select("table.info").size() > 0) {
doc2.body().appendChild(next.select("table.info").first());
}
} else if (doc.select(".mon_title").size() - 1 >= j) {
doc2.body().appendChild(doc.select(".mon_title").get(j).clone());
doc2.body().appendChild(doc.select("table:has(tr.list)").get(j).clone());
} else {
continue;
}
SubstitutionScheduleDay day = parseMonitorDay(doc2, data);
v.addDay(day);
}
} else if (doc.select(".mon_title").size() > 1) {
for (int j = 0; j < doc.select(".mon_title").size(); j++) {
Document doc2 = Document.createShell(doc.baseUri());
doc2.body().appendChild(doc.select(".mon_title").get(j).clone());
Element next = doc.select(".mon_title").get(j).nextElementSibling();
while (next != null && !next.tagName().equals("center")) {
doc2.body().appendChild(next);
next = doc.select(".mon_title").get(j).nextElementSibling();
}
SubstitutionScheduleDay day = parseMonitorDay(doc2, data);
v.addDay(day);
}
} else {
SubstitutionScheduleDay day = parseMonitorDay(doc, data);
v.addDay(day);
}
}
protected void parseSubstitutionTable(SubstitutionSchedule v, String lastChange, Document doc)
throws CredentialInvalidException, IOException, JSONException {
parseSubstitutionTable(v, lastChange, doc, null);
}
/**
* Parses an Untis substitution table ({@link UntisSubstitutionParser}).
*
* @param v
* @param lastChange
* @param doc
* @throws JSONException
* @throws CredentialInvalidException
*/
protected void parseSubstitutionTable(SubstitutionSchedule v, String lastChange, Document doc, String className)
throws JSONException, CredentialInvalidException, IOException {
JSONObject data = scheduleData.getData();
LocalDateTime lastChangeDate = ParserUtils.parseDateTime(lastChange);
Pattern dayPattern = Pattern.compile("\\d\\d?.\\d\\d?. / \\w+");
int dateColumn = -1;
JSONArray columns = data.getJSONArray("columns");
for (int i = 0; i < columns.length(); i++) {
if (columns.getString(i).equals("date")) {
dateColumn = i;
break;
}
}
Element table = doc.select("table[rules=all], table:has(tr:has(td[align=center]))").first();
if (table == null || table.text().replace("\u00a0", "").trim().equals("Keine Vertretungen")) {
return;
}
if (dateColumn == -1) {
SubstitutionScheduleDay day = new SubstitutionScheduleDay();
day.setLastChangeString(lastChange);
day.setLastChange(lastChangeDate);
String title = doc.select("font[size=5], font[size=4], font[size=3] b").text();
Matcher matcher = dayPattern.matcher(title);
if (matcher.find()) {
String date = matcher.group();
day.setDateString(date);
day.setDate(ParserUtils.parseDate(date));
}
parseSubstitutionScheduleTable(table, data, day, className, getAllClasses(), true);
v.addDay(day);
} else {
for (Element line : table
.select("tr.list.odd:not(:has(td.inline_header)), "
+ "tr.list.even:not(:has(td.inline_header)), "
+ "tr:has(td[align=center]):gt(0)")) {
SubstitutionScheduleDay day = null;
String date = line.select("td").get(dateColumn).text().replace("\u00a0", "").trim();
if (date.isEmpty()) continue;
if (date.indexOf("-") > 0) {
date = date.substring(0, date.indexOf("-") - 1).trim();
}
LocalDate parsedDate = ParserUtils.parseDate(date);
for (SubstitutionScheduleDay search : v.getDays()) {
if (Objects.equals(search.getDate(), parsedDate)
|| Objects.equals(search.getDateString(), date)) {
day = search;
break;
}
}
if (day == null) {
day = new SubstitutionScheduleDay();
day.setDateString(date);
day.setDate(parsedDate);
day.setLastChangeString(lastChange);
day.setLastChange(lastChangeDate);
v.addDay(day);
}
parseSubstitutionScheduleTable(line, data, day, className, getAllClasses(), true);
}
}
}
}
| parser/src/main/java/me/vertretungsplan/parser/UntisCommonParser.java | /*
* substitution-schedule-parser - Java library for parsing schools' substitution schedules
* Copyright (c) 2016 Johan v. Forstner
*
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package me.vertretungsplan.parser;
import me.vertretungsplan.exception.CredentialInvalidException;
import me.vertretungsplan.objects.Substitution;
import me.vertretungsplan.objects.SubstitutionSchedule;
import me.vertretungsplan.objects.SubstitutionScheduleData;
import me.vertretungsplan.objects.SubstitutionScheduleDay;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.*;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Contains common code used by {@link UntisInfoParser}, {@link UntisInfoHeadlessParser}, {@link UntisMonitorParser}
* and {@link UntisSubstitutionParser}.
*
* <h4>Configuration parameters</h4>
* These parameters can be supplied in {@link SubstitutionScheduleData#setData(JSONObject)} in addition to the
* parameters specified in the documentation of the parser itself.
*
* <dl>
* <dt><code>columns</code> (Array of Strings, required)</dt>
* <dd>The order of columns used in the substitutions table. Entries can be: <code>"lesson", "subject",
* "previousSubject", "type", "type-entfall", "room", "previousRoom", "teacher", "previousTeacher", desc",
* "desc-type", "substitutionFrom", "teacherTo", "class", "ignore"</code> (<code>"class"</code> only works when
* <code>classInExtraLine</code> is <code>false</code>.
* </dd>
*
* <dt><code>lastChangeLeft</code> (Boolean, optional)</dt>
* <dd>Whether the date of last change is in the top left corner instead of in the <code>.mon_head</code> table.
* Default: <code>false</code></dd>
*
* <dt><code>classInExtraLine</code> (Boolean, optional)</dt>
* <dd>Whether the changes in the table are grouped using headers containing the class name(s). Default:
* <code>false</code></dd>
*
* <dt><code>teacherInExtraLine</code> (Boolean, optional)</dt>
* <dd>Whether the changes in the table are grouped using headers containing the teacher name. Default:
* <code>false</code></dd>
*
* <dt><code>classesSeparated</code> (Boolean, optional)</dt>
* <dd>Whether the class names are separated by commas. If this is set to <code>false</code>, combinations like "5abcde"
* are attempted to be accounted for using an ugly algorithm based on RegExes generated from {@link #getAllClasses()}.
* Default: <code>true</code></dd>
*
* <dt><code>excludeClasses</code> (Array of Strings, optional)</dt>
* <dd>Substitutions for classes from this Array are ignored when reading the schedule. By default, only the class
* <code>"-----"</code> is ignored.</dd>
*
* <dt><code>classRegex</code> (String, optional)</dt>
* <dd>RegEx to modify the classes set on the schedule (in {@link #getSubstitutionSchedule()}, not
* {@link #getAllClasses()}. The RegEx is matched against the class using {@link Matcher#find()}. If the RegEx
* contains a group, the content of the first group {@link Matcher#group(int)} is used as the resulting class.
* Otherwise, {@link Matcher#group()} is used. If the RegEx cannot be matched ({@link Matcher#find()} returns
* <code>false</code>), the class is set to an empty string.
* </dd>
*
* <dt><code>typeAutoDetection</code> (Boolean, optional)</dt>
* <dd>If there is no type column and the detection using desc-type did not work, this sets whether the type may be
* automatically set to "Entfall" (cancellation) depending on the values of other columns.
* Default: <code>true</code></dd>
*
* <dt><code>allClassesCourses</code> (Array of Strings, optional)</dt>
* <dd>If a class included in this array is given on the schedule, this will be replaced by a list of all classes.
* This is useful for courses that all or multiple classes can attend, but that are saved as a separate class in Untis.
* Default: empty</dd>
*
* </dl>
*/
public abstract class UntisCommonParser extends BaseParser {
private static final String[] EXCLUDED_CLASS_NAMES = new String[]{"-----"};
private static final String PARAM_LAST_CHANGE_LEFT = "lastChangeLeft";
private static final String PARAM_LAST_CHANGE_SELECTOR = "lastChangeSelector"; // only used in UntisMonitorParser
private static final String PARAM_CLASS_IN_EXTRA_LINE = "classInExtraLine";
private static final String PARAM_TEACHER_IN_EXTRA_LINE = "teacherInExtraLine";
private static final String PARAM_COLUMNS = "columns";
private static final String PARAM_CLASSES_SEPARATED = "classesSeparated";
private static final String PARAM_EXCLUDE_CLASSES = "excludeClasses";
private static final String PARAM_TYPE_AUTO_DETECTION = "typeAutoDetection";
private static final String PARAM_MERGE_WITH_DIFFERENT_TYPE = "mergeWithDifferentType";
private static final String PARAM_ALL_CLASSES_COURSES = "allClassesCourses";
private static final String PARAM_EXCLUDE_TEACHERS = "excludeTeachers";
private static ColumnTypeDetector detector;
private static ColumnTypeDetector getDetector() throws IOException, JSONException {
if (detector == null) {
detector = new ColumnTypeDetector();
}
return detector;
}
UntisCommonParser(SubstitutionScheduleData scheduleData, CookieProvider cookieProvider) {
super(scheduleData, cookieProvider);
}
static String findLastChange(Element doc, SubstitutionScheduleData scheduleData) {
String lastChange = null;
boolean lastChangeLeft = false;
if (scheduleData != null) {
if (scheduleData.getData().has("stand_links")) {
// backwards compatibility
lastChangeLeft = scheduleData.getData().optBoolean("stand_links", false);
} else {
lastChangeLeft = scheduleData.getData().optBoolean(PARAM_LAST_CHANGE_LEFT, false);
}
}
if (doc.select("table.mon_head").size() > 0) {
Element monHead = doc.select("table.mon_head").first();
lastChange = findLastChangeFromMonHeadTable(monHead);
} else if (lastChangeLeft) {
final String bodyHtml = doc.select("body").size() > 0 ? doc.select("body").html() : doc.html();
lastChange = bodyHtml.substring(0, bodyHtml.indexOf("<p>") - 1);
} else {
List<Node> childNodes;
if (doc instanceof Document) {
childNodes = ((Document) doc).body().childNodes();
} else {
childNodes = doc.childNodes();
}
for (Node node : childNodes) {
if (node instanceof Comment) {
Comment comment = (Comment) node;
if (comment.getData().contains("<table class=\"mon_head\">")) {
Document commentedDoc = Jsoup.parse(comment.getData());
Element monHead = commentedDoc.select("table.mon_head").first();
lastChange = findLastChangeFromMonHeadTable(monHead);
break;
}
}
}
}
return lastChange;
}
private static String findLastChangeFromMonHeadTable(Element monHead) {
if (monHead.select("td[align=right]").size() == 0) return null;
String lastChange = null;
Pattern pattern = Pattern.compile("\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d \\d\\d:\\d\\d");
Matcher matcher = pattern.matcher(monHead.select("td[align=right]").first().text());
if (matcher.find()) {
lastChange = matcher.group();
} else if (monHead.text().contains("Stand: ")) {
lastChange = monHead.text().substring(monHead.text().indexOf("Stand:") + "Stand:".length()).trim();
}
return lastChange;
}
private static boolean equalsOrNull(String a, String b) {
return a == null || b == null || a.equals(b);
}
/**
* Parses an Untis substitution schedule table
*
* @param table the <code>table</code> Element from the HTML document
* @param data {@link SubstitutionScheduleData#getData()}
* @param day the {@link SubstitutionScheduleDay} where the substitutions will be stored
*/
void parseSubstitutionScheduleTable(Element table, JSONObject data,
SubstitutionScheduleDay day, List<String> allClasses)
throws JSONException, CredentialInvalidException, IOException {
parseSubstitutionScheduleTable(table, data, day, null, allClasses, false);
}
private void parseSubstitutionScheduleTable(Element table, JSONObject data,
SubstitutionScheduleDay day, String defaultClass, List<String>
allClasses)
throws CredentialInvalidException, IOException, JSONException {
parseSubstitutionScheduleTable(table, data, day, defaultClass, allClasses, false);
}
/**
* Parses an Untis substitution schedule table
*
* @param table the <code>table</code> Element from the HTML document
* @param data {@link SubstitutionScheduleData#getData()}
* @param day the {@link SubstitutionScheduleDay} where the substitutions will be stored
* @param defaultClass the class that should be set if there is no class column in the table
*/
private void parseSubstitutionScheduleTable(Element table, JSONObject data,
SubstitutionScheduleDay day, String defaultClass, List<String>
allClasses, boolean untisSubst)
throws JSONException, CredentialInvalidException, IOException {
Elements headerRows = table.select("tr:has(th)");
List<String> columnTitles = new ArrayList<>();
if (headerRows.size() > 0) {
Elements headers = headerRows.get(0).select("th");
for (int i = 0; i < headers.size(); i++) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (Element headerRow : headerRows) {
final String text = headerRow.select("th").get(i).text().replace("\u00a0", " ").trim();
if (first) {
if (!text.equals("")) first = false;
} else {
builder.append(" ");
}
builder.append(text);
}
columnTitles.add(builder.toString());
}
}
debuggingDataHandler.columnTitles(columnTitles);
final JSONArray columnsJson = data.optJSONArray(PARAM_COLUMNS);
List<String> columns = new ArrayList<>();
if (columnsJson != null && (columnTitles.size() == 0 || columnTitles.size() == columnsJson.length())) {
for (int i = 0; i < columnsJson.length(); i++) columns.add(columnsJson.getString(i));
} else {
for (String title : columnTitles) {
String type = getDetector().getColumnType(title, columnTitles);
if (type != null) {
columns.add(type);
} else {
if (columnsJson != null && columnsJson.length() == columnTitles.size()) {
columns.clear();
for (int i = 0; i < columnsJson.length(); i++) columns.add(columnsJson.getString(i));
} else {
throw new IOException("unknown column title: " + title);
}
break;
}
}
}
if (data.optBoolean(PARAM_CLASS_IN_EXTRA_LINE)
|| data.optBoolean("class_in_extra_line")) { // backwards compatibility
for (Element element : table.select("td.inline_header")) {
String className = getClassName(element.text(), data);
if (isValidClass(className, data)) {
parseWithExtraLine(data, day, columns, element, className, null);
}
}
} else if (data.optBoolean(PARAM_TEACHER_IN_EXTRA_LINE)) {
for (Element element : table.select("td.inline_header")) {
String teacherName = getClassName(element.text(), data);
parseWithExtraLine(data, day, columns, element, null, teacherName);
}
} else {
boolean hasType = false;
for (String column : columns) {
if (column.equals("type")) {
hasType = true;
}
}
int skipLines = 0;
for (Element zeile : table
.select("tr.list.odd:not(:has(td.inline_header)), "
+ "tr.list.even:not(:has(td.inline_header)), "
+ "tr:has(td[align=center]):gt(0)")) {
if (skipLines > 0) {
skipLines--;
continue;
}
final Element previousLine = zeile.previousElementSibling();
if (isGroupMessage(zeile) && previousLine != null && previousLine.select(".inline_header").size() > 0) {
addGroupMessage(day, getClassName(previousLine.text(), data), zeile);
continue;
}
Substitution v = new Substitution();
String klassen = defaultClass != null ? defaultClass : "";
String course = null;
int i = 0;
for (Element spalte : zeile.select("td")) {
String text = spalte.text();
String type = columns.get(i);
if (isEmpty(text) && !type.equals("type-entfall") && !type.equals("teacher")) {
i++;
continue;
}
int skipLinesForThisColumn = 0;
Element nextLine = zeile.nextElementSibling();
boolean continueSkippingLines = true;
while (continueSkippingLines) {
if (nextLine != null && nextLine.children().size() == zeile.children().size()) {
Element columnInNextLine = nextLine.child(spalte
.elementSiblingIndex());
String nextLineText = columnInNextLine.text().replaceAll("\u00A0", "").trim();
if (nextLineText.equals(
nextLine.text().replaceAll("\u00A0", "").trim())) {
if (untisSubst && i == 0 && !allClasses.contains(nextLineText.split(",")[0])) {
// this is a message, not a continuation of the first column
if (!day.getMessages().contains(nextLineText)) {
day.addMessage(nextLineText);
continueSkippingLines = false;
}
} else {
// Continued in the next line
text += " " + columnInNextLine.text();
skipLinesForThisColumn++;
nextLine = nextLine.nextElementSibling();
}
} else {
continueSkippingLines = false;
}
} else {
continueSkippingLines = false;
}
}
if (skipLinesForThisColumn > skipLines) skipLines = skipLinesForThisColumn;
switch (type) {
case "lesson":
v.setLesson(text);
break;
case "subject":
handleSubject(v, spalte, false);
if (course != null) {
v.setSubject((v.getSubject() != null ? v.getSubject() + " " : "") + course);
course = null;
}
break;
case "course":
if (v.getSubject() != null) {
v.setSubject(v.getSubject() + " " + text);
} else {
course = text;
}
break;
case "previousSubject":
handleSubject(v, spalte, true);
break;
case "type":
v.setType(text);
v.setColor(colorProvider.getColor(text));
break;
case "type-entfall":
if (text.equals("x")) {
v.setType("Entfall");
v.setColor(colorProvider.getColor("Entfall"));
} else if (!hasType && v.getType() == null) {
v.setType("Vertretung");
v.setColor(colorProvider.getColor("Vertretung"));
}
break;
case "room":
handleRoom(v, spalte, false);
break;
case "previousRoom":
handleRoom(v, spalte, true);
break;
case "desc":
v.setDesc(text);
break;
case "desc-type":
String recognizedType = recognizeType(text);
v.setType(recognizedType);
if (text.equals(recognizedType)) {
v.setDesc(null);
} else {
v.setDesc(text);
}
v.setColor(colorProvider.getColor(recognizedType));
break;
case "teacher":
if (text.equals("+")) {
v.setType("Eigenverantw. Arbeiten");
v.setColor(colorProvider.getColor(v.getType()));
} else if (!isEmpty(text)) {
handleTeacher(v, spalte, data, false);
}
break;
case "previousTeacher":
handleTeacher(v, spalte, data, true);
break;
case "substitutionFrom":
v.setSubstitutionFrom(text);
break;
case "teacherTo":
v.setTeacherTo(text);
break;
case "class":
klassen = text;
break;
case "ignore":
break;
case "date": // used by UntisSubstitutionParser
break;
default:
throw new IllegalArgumentException("Unknown column type: " + type);
}
i++;
}
if (course != null) {
v.setSubject(course);
}
if (v.getLesson() == null || v.getLesson().equals("")) {
continue;
}
autoDetectType(data, zeile, v);
handleClasses(data, v, klassen, allClasses);
if (data.optBoolean(PARAM_MERGE_WITH_DIFFERENT_TYPE, false)) {
boolean found = false;
for (Substitution subst : day.getSubstitutions()) {
if (subst.equalsExcludingType(v)) {
found = true;
if (v.getType().equals("Vertretung")) {
subst.setType("Vertretung");
subst.setColor(colorProvider.getColor("Vertretung"));
}
break;
}
}
if (!found) {
day.addSubstitution(v);
}
} else {
day.addSubstitution(v);
}
}
}
}
static void handleClasses(JSONObject data, Substitution v, String klassen, List<String> allClasses)
throws JSONException, CredentialInvalidException {
List<String> affectedClasses;
if (data.has(PARAM_ALL_CLASSES_COURSES)) {
JSONArray arr = data.getJSONArray(PARAM_ALL_CLASSES_COURSES);
for (int i = 0; i < arr.length(); i++) {
String s = arr.getString(i);
if (klassen.equals(s)) {
v.getClasses().addAll(allClasses);
return;
}
}
}
// Detect things like "7"
Pattern singlePattern = Pattern.compile("(\\d{1,2})");
Matcher singleMatcher = singlePattern.matcher(klassen);
// Detect things like "5-12"
Pattern rangePattern = Pattern.compile("(\\d+) ?- ?(\\d+)");
Matcher rangeMatcher = rangePattern.matcher(klassen);
boolean singleClassLooksLikeRange = false;
if (allClasses != null) {
for (String klass : allClasses) {
// disable range detection if single classes (e.g. "05-1") look like a range
if (rangePattern.matcher(klass).matches()) {
singleClassLooksLikeRange = true;
break;
}
}
}
Pattern pattern2 = Pattern.compile("^(\\d+).*");
if (rangeMatcher.matches() && !singleClassLooksLikeRange) {
affectedClasses = new ArrayList<>();
int min = Integer.parseInt(rangeMatcher.group(1));
int max = Integer.parseInt(rangeMatcher.group(2));
for (String klasse : allClasses) {
Matcher matcher2 = pattern2.matcher(klasse);
if (matcher2.matches()) {
int num = Integer.parseInt(matcher2.group(1));
if (min <= num && num <= max) affectedClasses.add(klasse);
}
}
} else if (singleMatcher.matches()) {
affectedClasses = new ArrayList<>();
int grade = Integer.parseInt(singleMatcher.group(1));
for (String klasse : allClasses) {
Matcher matcher2 = pattern2.matcher(klasse);
if (matcher2.matches() && grade == Integer.parseInt(matcher2.group(1))) {
affectedClasses.add(klasse);
}
}
} else {
if (data.optBoolean(PARAM_CLASSES_SEPARATED, true)
&& data.optBoolean("classes_separated", true)) { // backwards compatibility
affectedClasses = Arrays.asList(klassen.split(", "));
} else {
affectedClasses = new ArrayList<>();
if (allClasses.contains(klassen)) {
affectedClasses.add(klassen);
}
if (klassen.matches("([\\d]{1,2}[a-zA-Z]+)+")) {
// we have something like 8ab9abc -> 8a, 8b, 9a, 9b, 9c
Pattern pattern = Pattern.compile("([\\d]{1,2})([a-zA-Z]+)");
Matcher matcher = pattern.matcher(klassen);
while (matcher.find()) {
String base = matcher.group(1);
for (char letter : matcher.group(2).toCharArray()) {
if (allClasses.contains(base + letter)) {
affectedClasses.add(base + letter);
}
}
}
} else if (singleClassLooksLikeRange && klassen.matches("(\\d{1,2})-(\\d+)")) {
// we have something like 09-234 -> 09-2, 09-3, 09-4
Pattern pattern = Pattern.compile("(\\d{1,2})-(\\d+)");
Matcher matcher = pattern.matcher(klassen);
if (matcher.find()) {
String base = matcher.group(1);
for (char number : matcher.group(2).toCharArray()) {
if (allClasses.contains(base + "-" + number)) {
affectedClasses.add(base + "-" + number);
}
}
} else {
affectedClasses.add(klassen);
}
} else {
// fallback solution for backwards compatibility
for (String klasse : allClasses) { // TODO: is there a better way?
StringBuilder regex = new StringBuilder();
for (char character : klasse.toCharArray()) {
if (character == '?') {
regex.append("\\?");
} else {
regex.append(character);
}
regex.append(".*");
}
if (klassen.matches(regex.toString())) {
affectedClasses.add(klasse);
}
}
}
}
}
for (String klasse : affectedClasses) {
String name = getClassName(klasse, data);
if (isValidClass(name, data)) {
v.getClasses().add(name);
}
}
}
private void parseWithExtraLine(JSONObject data, SubstitutionScheduleDay day, List<String> columns, Element element,
String className, String teacherName) {
Element zeile = null;
try {
zeile = element.parent().nextElementSibling();
if (zeile.select("td") == null) {
zeile = zeile.nextElementSibling();
}
int skipLines = 0;
while (zeile != null
&& !zeile.select("td").attr("class")
.equals("list inline_header")) {
if (skipLines > 0) {
skipLines--;
zeile = zeile.nextElementSibling();
continue;
}
if (isGroupMessage(zeile)) {
addGroupMessage(day, className != null ? className : teacherName, zeile);
zeile = zeile.nextElementSibling();
continue;
}
Substitution v = new Substitution();
String klassen = null;
String course = null;
int i = 0;
for (Element spalte : zeile.select("td")) {
String text = spalte.text();
String type = columns.get(i);
if (isEmpty(text) && !type.equals("teacher")) {
i++;
continue;
}
int skipLinesForThisColumn = 0;
Element nextLine = zeile.nextElementSibling();
boolean continueSkippingLines = true;
while (continueSkippingLines) {
if (nextLine != null && nextLine.children().size() == zeile.children().size()) {
Element columnInNextLine = nextLine.child(spalte
.elementSiblingIndex());
if (columnInNextLine.text().replaceAll("\u00A0", "").trim().equals(
nextLine.text().replaceAll("\u00A0", "").trim())) {
// Continued in the next line
text += " " + columnInNextLine.text();
skipLinesForThisColumn++;
nextLine = nextLine.nextElementSibling();
} else {
continueSkippingLines = false;
}
} else {
continueSkippingLines = false;
}
}
if (skipLinesForThisColumn > skipLines) skipLines = skipLinesForThisColumn;
switch (type) {
case "lesson":
v.setLesson(text);
break;
case "subject":
handleSubject(v, spalte, false);
if (course != null) {
v.setSubject((v.getSubject() != null ? v.getSubject() + " " : "") + course);
course = null;
}
break;
case "course":
if (v.getSubject() != null) {
v.setSubject(v.getSubject() + " " + text);
} else {
course = text;
}
break;
case "previousSubject":
handleSubject(v, spalte, true);
break;
case "type":
v.setType(text);
v.setColor(colorProvider.getColor(text));
break;
case "type-entfall":
if (text.equals("x")) {
v.setType("Entfall");
v.setColor(colorProvider.getColor("Entfall"));
} else if (v.getType() == null) {
v.setType("Vertretung");
v.setColor(colorProvider.getColor("Vertretung"));
}
break;
case "room":
handleRoom(v, spalte, false);
break;
case "teacher":
if (text.equals("+")) {
v.setType("Eigenverantw. Arbeiten");
v.setColor(colorProvider.getColor(v.getType()));
} else if (!isEmpty(text) && teacherName == null) {
handleTeacher(v, spalte, data, false);
} // otherwise ignore - teacher is in extra line
break;
case "previousTeacher":
handleTeacher(v, spalte, data, true);
break;
case "desc":
v.setDesc(text);
break;
case "desc-type":
String recognizedType = recognizeType(text);
v.setType(recognizedType);
if (text.equals(recognizedType)) {
v.setDesc(null);
} else {
v.setDesc(text);
}
v.setColor(colorProvider.getColor(recognizedType));
break;
case "previousRoom":
handleRoom(v, spalte, true);
break;
case "substitutionFrom":
v.setSubstitutionFrom(text);
break;
case "teacherTo":
v.setTeacherTo(text);
break;
case "ignore":
break;
case "date": // used by UntisSubstitutionParser
break;
case "class":
if (className == null) {
klassen = getClassName(text, data);
} // otherwise ignore - class is in extra line
break;
default:
throw new IllegalArgumentException("Unknown column type: " + type);
}
i++;
}
if (course != null) {
v.setSubject(course);
}
autoDetectType(data, zeile, v);
if (className != null) {
v.getClasses().add(className);
} else if (klassen != null) {
handleClasses(data, v, klassen, getAllClasses());
}
if (teacherName != null && !data.optBoolean(PARAM_EXCLUDE_TEACHERS)) {
v.setTeacher(teacherName);
}
if (v.getLesson() != null && !v.getLesson().equals("")) {
day.addSubstitution(v);
}
zeile = zeile.nextElementSibling();
}
} catch (Throwable e) {
e.printStackTrace();
}
}
private void addGroupMessage(SubstitutionScheduleDay day, String groupName, Element zeile) {
String message = "<b>" + groupName + ":</b> " + zeile.select("td").first().text();
day.addMessage(message);
}
private boolean isGroupMessage(Element zeile) {
return zeile.select("td").size() == 1 && zeile.select("td").first().hasAttr("colspan");
}
private void autoDetectType(JSONObject data, Element zeile, Substitution v) {
if (v.getType() == null) {
if (data.optBoolean(PARAM_TYPE_AUTO_DETECTION, true)) {
if ((zeile.select("strike").size() > 0 &&
equalsOrNull(v.getSubject(), v.getPreviousSubject()) &&
equalsOrNull(v.getTeacher(), v.getPreviousTeacher()))
|| (v.getSubject() == null && (v.getRoom() == null || v.getRoom().equals(v.getPreviousRoom()))
&& v.getTeacher() == null && v.getPreviousSubject() != null)) {
v.setType("Entfall");
v.setColor(colorProvider.getColor("Entfall"));
} else {
v.setType("Vertretung");
v.setColor(colorProvider.getColor("Vertretung"));
}
} else {
v.setType("Vertretung");
v.setColor(colorProvider.getColor("Vertretung"));
}
}
}
static void handleTeacher(Substitution subst, Element cell, JSONObject data, boolean previousTeacher) {
if (data.optBoolean(PARAM_EXCLUDE_TEACHERS)) return;
cell = getContentElement(cell);
if (cell.select("s").size() > 0) {
subst.setPreviousTeachers(splitTeachers(cell.select("s").text(), data));
if (cell.ownText().length() > 0) {
subst.setTeachers(splitTeachers(cell.ownText().replaceFirst("^\\?", "").replaceFirst("→", ""), data));
}
} else {
if (previousTeacher) {
subst.setPreviousTeachers(splitTeachers(cell.text(), data));
} else {
subst.setTeachers(splitTeachers(cell.text(), data));
}
}
}
private static Set<String> splitTeachers(String s, JSONObject data) {
Set<String> teachers = new HashSet<>();
if (data.optBoolean("splitTeachers", true)) {
teachers.addAll(Arrays.asList(s.split(", ")));
} else {
teachers.add(s);
}
return teachers;
}
static void handleRoom(Substitution subst, Element cell, boolean previousRoom) {
cell = getContentElement(cell);
if (cell.select("s").size() > 0) {
subst.setPreviousRoom(cell.select("s").text());
if (cell.ownText().length() > 0) {
subst.setRoom(cell.ownText().replaceFirst("^\\?", "").replaceFirst("→", ""));
}
} else {
if (previousRoom) {
subst.setPreviousRoom(cell.text());
} else {
subst.setRoom(cell.text());
}
}
}
private static Element getContentElement(Element cell) {
if (cell.ownText().isEmpty() && cell.select("> span").size() == 1) {
cell = cell.select("> span").first();
}
return cell;
}
static void handleSubject(Substitution subst, Element cell, boolean previousSubject) {
cell = getContentElement(cell);
if (cell.select("s").size() > 0) {
subst.setPreviousSubject(cell.select("s").text());
if (cell.ownText().length() > 0) {
subst.setSubject(cell.ownText().replaceFirst("^\\?", "").replaceFirst("→", ""));
}
} else {
if (previousSubject) {
subst.setPreviousSubject(cell.text());
} else {
subst.setSubject(cell.text());
}
}
}
private boolean isEmpty(String text) {
final String trim = text.replaceAll("\u00A0", "").trim();
return trim.equals("") || trim.equals("---") || trim.equals("+");
}
/**
* Parses a "Nachrichten zum Tag" ("daily news") table from an Untis schedule
*
* @param table the <code>table</code>-Element to be parsed
* @param day the {@link SubstitutionScheduleDay} where the messages should be stored
*/
private void parseMessages(Element table, SubstitutionScheduleDay day) {
Elements zeilen = table
.select("tr:not(:contains(Nachrichten zum Tag))");
for (Element i : zeilen) {
Elements spalten = i.select("td");
String info = "";
for (Element b : spalten) {
info += "\n"
+ TextNode.createFromEncoded(b.html(), null)
.getWholeText();
}
info = info.substring(1); // remove first \n
day.addMessage(info);
}
}
SubstitutionScheduleDay parseMonitorDay(Element doc, JSONObject data) throws
JSONException, CredentialInvalidException, IOException {
SubstitutionScheduleDay day = new SubstitutionScheduleDay();
String date = doc.select(".mon_title").first().text().replaceAll(" \\(Seite \\d+ / \\d+\\)", "");
day.setDateString(date);
day.setDate(ParserUtils.parseDate(date));
Pattern weekTypePattern =
Pattern.compile("Woche [A-Z]|[^\\s]*unterricht Gruppe .*|Unterrichts[^\\s]* Gruppe .*");
Matcher matcher = weekTypePattern.matcher(date);
if (matcher.find()) {
day.setComment(matcher.group());
}
if (!scheduleData.getData().has(PARAM_LAST_CHANGE_SELECTOR)) {
String lastChange = findLastChange(doc, scheduleData);
day.setLastChangeString(lastChange);
day.setLastChange(ParserUtils.parseDateTime(lastChange));
}
// NACHRICHTEN
if (doc.select("table.info").size() > 0) {
parseMessages(doc.select("table.info").first(), day);
}
// VERTRETUNGSPLAN
if (doc.select("table:has(tr.list)").size() > 0) {
parseSubstitutionScheduleTable(doc.select("table:has(tr.list)").first(), data, day, getAllClasses());
}
return day;
}
private static boolean isValidClass(String klasse, JSONObject data) throws JSONException {
return klasse != null && !Arrays.asList(EXCLUDED_CLASS_NAMES).contains(klasse) &&
!(data.has(PARAM_EXCLUDE_CLASSES) &&
contains(data.getJSONArray(PARAM_EXCLUDE_CLASSES), klasse)) &&
!(data.has("exclude_classes") && // backwards compatibility
contains(data.getJSONArray("exclude_classes"), klasse));
}
@Override
public List<String> getAllClasses() throws IOException, JSONException, CredentialInvalidException {
return getClassesFromJson();
}
void parseDay(SubstitutionScheduleDay day, Element next, SubstitutionSchedule v, String klasse, List<String>
allClasses) throws
JSONException, CredentialInvalidException, IOException {
if (next.children().size() == 0) {
next = next.nextElementSibling();
}
if (next.className().equals("subst") || next.select(".list").size() > 0
|| next.text().contains("Vertretungen sind nicht freigegeben")
|| next.text().contains("Keine Vertretungen")) {
//Vertretungstabelle
if (next.text().contains("Vertretungen sind nicht freigegeben")) {
return;
}
parseSubstitutionScheduleTable(next, scheduleData.getData(), day, klasse, allClasses);
} else {
//Nachrichten
parseMessages(next, day);
next = next.nextElementSibling().nextElementSibling();
parseSubstitutionScheduleTable(next, scheduleData.getData(), day, klasse, allClasses);
}
v.addDay(day);
}
void parseMultipleMonitorDays(SubstitutionSchedule v, Document doc, JSONObject data)
throws JSONException, CredentialInvalidException, IOException {
if (doc.select(".mon_head").size() > 1) {
for (int j = 0; j < doc.select(".mon_head").size(); j++) {
Document doc2 = Document.createShell(doc.baseUri());
doc2.body().appendChild(doc.select(".mon_head").get(j).clone());
Element next = doc.select(".mon_head").get(j).nextElementSibling();
if (next != null && next.tagName().equals("center")) {
doc2.body().appendChild(next.select(".mon_title").first().clone());
if (next.select("table:has(tr.list)").size() > 0) {
doc2.body().appendChild(next.select("table:has(tr.list)").first());
}
if (next.select("table.info").size() > 0) {
doc2.body().appendChild(next.select("table.info").first());
}
} else if (doc.select(".mon_title").size() - 1 >= j) {
doc2.body().appendChild(doc.select(".mon_title").get(j).clone());
doc2.body().appendChild(doc.select("table:has(tr.list)").get(j).clone());
} else {
continue;
}
SubstitutionScheduleDay day = parseMonitorDay(doc2, data);
v.addDay(day);
}
} else if (doc.select(".mon_title").size() > 1) {
for (int j = 0; j < doc.select(".mon_title").size(); j++) {
Document doc2 = Document.createShell(doc.baseUri());
doc2.body().appendChild(doc.select(".mon_title").get(j).clone());
Element next = doc.select(".mon_title").get(j).nextElementSibling();
while (next != null && !next.tagName().equals("center")) {
doc2.body().appendChild(next);
next = doc.select(".mon_title").get(j).nextElementSibling();
}
SubstitutionScheduleDay day = parseMonitorDay(doc2, data);
v.addDay(day);
}
} else {
SubstitutionScheduleDay day = parseMonitorDay(doc, data);
v.addDay(day);
}
}
protected void parseSubstitutionTable(SubstitutionSchedule v, String lastChange, Document doc)
throws CredentialInvalidException, IOException, JSONException {
parseSubstitutionTable(v, lastChange, doc, null);
}
/**
* Parses an Untis substitution table ({@link UntisSubstitutionParser}).
*
* @param v
* @param lastChange
* @param doc
* @throws JSONException
* @throws CredentialInvalidException
*/
protected void parseSubstitutionTable(SubstitutionSchedule v, String lastChange, Document doc, String className)
throws JSONException, CredentialInvalidException, IOException {
JSONObject data = scheduleData.getData();
LocalDateTime lastChangeDate = ParserUtils.parseDateTime(lastChange);
Pattern dayPattern = Pattern.compile("\\d\\d?.\\d\\d?. / \\w+");
int dateColumn = -1;
JSONArray columns = data.getJSONArray("columns");
for (int i = 0; i < columns.length(); i++) {
if (columns.getString(i).equals("date")) {
dateColumn = i;
break;
}
}
Element table = doc.select("table[rules=all], table:has(tr:has(td[align=center]))").first();
if (table == null || table.text().replace("\u00a0", "").trim().equals("Keine Vertretungen")) {
return;
}
if (dateColumn == -1) {
SubstitutionScheduleDay day = new SubstitutionScheduleDay();
day.setLastChangeString(lastChange);
day.setLastChange(lastChangeDate);
String title = doc.select("font[size=5], font[size=4], font[size=3] b").text();
Matcher matcher = dayPattern.matcher(title);
if (matcher.find()) {
String date = matcher.group();
day.setDateString(date);
day.setDate(ParserUtils.parseDate(date));
}
parseSubstitutionScheduleTable(table, data, day, className, getAllClasses(), true);
v.addDay(day);
} else {
for (Element line : table
.select("tr.list.odd:not(:has(td.inline_header)), "
+ "tr.list.even:not(:has(td.inline_header)), "
+ "tr:has(td[align=center]):gt(0)")) {
SubstitutionScheduleDay day = null;
String date = line.select("td").get(dateColumn).text().replace("\u00a0", "").trim();
if (date.isEmpty()) continue;
if (date.indexOf("-") > 0) {
date = date.substring(0, date.indexOf("-") - 1).trim();
}
LocalDate parsedDate = ParserUtils.parseDate(date);
for (SubstitutionScheduleDay search : v.getDays()) {
if (Objects.equals(search.getDate(), parsedDate)
|| Objects.equals(search.getDateString(), date)) {
day = search;
break;
}
}
if (day == null) {
day = new SubstitutionScheduleDay();
day.setDateString(date);
day.setDate(parsedDate);
day.setLastChangeString(lastChange);
day.setLastChange(lastChangeDate);
v.addDay(day);
}
parseSubstitutionScheduleTable(line, data, day, className, getAllClasses(), true);
}
}
}
}
| Fix bug in handleClasses:
If class exactly matches one of the classes in the list, don't try to match it to other classes.
| parser/src/main/java/me/vertretungsplan/parser/UntisCommonParser.java | Fix bug in handleClasses: |
|
Java | agpl-3.0 | 34c9652962970150c7183c48fa45b70cb7854fec | 0 | Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge | package nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.adapter.fossil;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.UUID;
import nodomain.freeyourgadget.gadgetbridge.GBException;
import nodomain.freeyourgadget.gadgetbridge.Logging;
import nodomain.freeyourgadget.gadgetbridge.devices.qhybrid.NotificationConfiguration;
import nodomain.freeyourgadget.gadgetbridge.devices.qhybrid.PackageConfigHelper;
import nodomain.freeyourgadget.gadgetbridge.entities.NotificationFilter;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.GenericItem;
import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.QHybridSupport;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.adapter.WatchAdapter;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.Request;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.FossilRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.RequestMtuRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.SetDeviceStateRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.configuration.ConfigurationGetRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.configuration.ConfigurationPutRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.connection.SetConnectionParametersRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.file.FileCloseRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.file.FileDeleteRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.file.FilePutRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.file.FileVerifyRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.notification.NotificationFilterPutRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.notification.PlayNotificationRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.misfit.AnimationRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.misfit.MoveHandsRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.misfit.ReleaseHandsControlRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.misfit.RequestHandControlRequest;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
public class FossilWatchAdapter extends WatchAdapter {
private ArrayList<Request> requestQueue = new ArrayList<>();
private FossilRequest fossilRequest;
public FossilWatchAdapter(QHybridSupport deviceSupport) {
super(deviceSupport);
}
@Override
public void initialize() {
// playPairingAnimation();
// queueWrite(new FileDeleteRequest((short) 0x0200));
queueWrite(new RequestMtuRequest(512));
queueWrite(new ConfigurationGetRequest(this));
// queueWrite(new SetConnectionParametersRequest());
syncNotificationSettings();
queueWrite(new SetDeviceStateRequest(GBDevice.State.INITIALIZED));
}
@Override
public void playPairingAnimation() {
queueWrite(new AnimationRequest());
}
@Override
public void playNotification(NotificationConfiguration config) {
if (config.getPackageName() == null) {
log("package name in notification not set");
return;
}
queueWrite(new PlayNotificationRequest(config.getPackageName(), this));
}
@Override
public void setTime() {
long millis = System.currentTimeMillis();
TimeZone zone = new GregorianCalendar().getTimeZone();
queueWrite(
new ConfigurationPutRequest(
new ConfigurationPutRequest.TimeConfigItem(
(int) (millis / 1000 + getDeviceSupport().getTimeOffset() * 60),
(short) (millis % 1000),
(short) ((zone.getRawOffset() + (zone.inDaylightTime(new Date()) ? 1 : 0)) / 60000)
),
this)
);
}
@Override
public void overwriteButtons() {
FilePutRequest uploadFileRequest = new FilePutRequest((short) 0x0600, new byte[]{
(byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x10, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x0C, (byte) 0x00, (byte) 0x00, (byte) 0x20, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x0C, (byte) 0x00, (byte) 0x00,
(byte) 0x30, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x0C, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x0C, (byte) 0x2E, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01,
(byte) 0x00, (byte) 0x06, (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x03, (byte) 0x00, (byte) 0x02, (byte) 0x01, (byte) 0x0F, (byte) 0x00, (byte) 0x8B, (byte) 0x00, (byte) 0x00, (byte) 0x93, (byte) 0x00, (byte) 0x01,
(byte) 0x08, (byte) 0x01, (byte) 0x14, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0xFE, (byte) 0x08, (byte) 0x00, (byte) 0x93, (byte) 0x00, (byte) 0x02, (byte) 0x01, (byte) 0x00, (byte) 0xBF, (byte) 0xD5, (byte) 0x54, (byte) 0xD1,
(byte) 0x00
}, this);
queueWrite(uploadFileRequest);
}
@Override
public void setActivityHand(double progress) {
queueWrite(new ConfigurationPutRequest(
new ConfigurationPutRequest.CurrentStepCountConfigItem(Math.min(999999, (int) (1000000 * progress))),
this
));
}
@Override
public void setHands(short hour, short minute) {
queueWrite(new MoveHandsRequest(false, minute, hour, (short) -1));
}
public void vibrate(nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.misfit.PlayNotificationRequest.VibrationType vibration) {
// queueWrite(new nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.misfit.PlayNotificationRequest(vibration, -1, -1));
}
@Override
public void vibrateFindMyDevicePattern() {
}
@Override
public void requestHandsControl() {
queueWrite(new RequestHandControlRequest());
}
@Override
public void releaseHandsControl() {
queueWrite(new ReleaseHandsControlRequest());
}
@Override
public void setStepGoal(int stepGoal) {
queueWrite(new ConfigurationPutRequest(new ConfigurationPutRequest.DailyStepGoalConfigItem(stepGoal), this));
}
@Override
public void setVibrationStrength(short strength) {
ConfigurationPutRequest.ConfigItem vibrationItem = new ConfigurationPutRequest.VibrationStrengthConfigItem((byte)strength);
queueWrite(
new ConfigurationPutRequest(new ConfigurationPutRequest.ConfigItem[]{vibrationItem}, this)
);
// queueWrite(new FileVerifyRequest((short) 0x0800));
}
@Override
public void syncNotificationSettings() {
log("syncing notification settings...");
try {
PackageConfigHelper helper = new PackageConfigHelper(getContext());
final ArrayList<NotificationConfiguration> configurations = helper.getNotificationConfigurations();
if (configurations.size() == 1) configurations.add(configurations.get(0));
queueWrite(new NotificationFilterPutRequest(configurations, FossilWatchAdapter.this) {
@Override
public void onFilePut(boolean success) {
super.onFilePut(success);
if (!success) {
GB.toast("error writing notification settings", Toast.LENGTH_SHORT, GB.ERROR);
getDeviceSupport().getDevice().setState(GBDevice.State.NOT_CONNECTED);
getDeviceSupport().getDevice().sendDeviceUpdateIntent(getContext());
}
getDeviceSupport().getDevice().setState(GBDevice.State.INITIALIZED);
getDeviceSupport().getDevice().sendDeviceUpdateIntent(getContext());
}
});
} catch (GBException e) {
e.printStackTrace();
}
}
@Override
public void onTestNewFunction() {
queueWrite(new ConfigurationPutRequest(new ConfigurationPutRequest.ConfigItem[0], this));
}
@Override
public boolean supportsFindDevice() {
return false;
}
@Override
public boolean supportsExtendedVibration() {
String modelNumber = getDeviceSupport().getDevice().getModel();
switch (modelNumber) {
case "HW.0.0":
return true;
case "HL.0.0":
return false;
}
throw new UnsupportedOperationException("model " + modelNumber + " not supported");
}
@Override
public boolean supportsActivityHand() {
String modelNumber = getDeviceSupport().getDevice().getModel();
switch (modelNumber) {
case "HW.0.0":
return true;
case "HL.0.0":
return false;
}
throw new UnsupportedOperationException("Model " + modelNumber + " not supported");
}
@Override
public String getModelName() {
String modelNumber = getDeviceSupport().getDevice().getModel();
switch (modelNumber) {
case "HW.0.0":
return "Q Commuter";
case "HL.0.0":
return "Q Activist";
}
return "unknwon Q";
}
@Override
public void onFetchActivityData() {
// queueWrite(new ConfigurationPutRequest(new ConfigurationPutRequest.ConfigItem[0], this));
setVibrationStrength((byte) 50);
// queueWrite(new FileCloseRequest((short) 0x0800));
// queueWrite(new ConfigurationGetRequest(this));
}
@Override
public boolean onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
switch (characteristic.getUuid().toString()) {
case "3dda0006-957f-7d4a-34a6-74696673696d": {
handleBackgroundCharacteristic(characteristic);
break;
}
case "3dda0002-957f-7d4a-34a6-74696673696d":
case "3dda0004-957f-7d4a-34a6-74696673696d":
case "3dda0003-957f-7d4a-34a6-74696673696d": {
if (fossilRequest != null) {
boolean requestFinished;
try {
if(characteristic.getUuid().toString().equals("3dda0003-957f-7d4a-34a6-74696673696d")){
byte requestType = (byte)(characteristic.getValue()[0] & 0x0F);
if(requestType != 0x0A && requestType != fossilRequest.getType()){
// throw new RuntimeException("Answer type " + requestType + " does not match current request " + fossilRequest.getType());
}
}
fossilRequest.handleResponse(characteristic);
requestFinished = fossilRequest.isFinished();
} catch (RuntimeException e) {
e.printStackTrace();
getDeviceSupport().notifiyException(e);
GB.toast(fossilRequest.getName() + " failed", Toast.LENGTH_SHORT, GB.ERROR);
requestFinished = true;
}
if (requestFinished) {
log(fossilRequest.getName() + " finished");
fossilRequest = null;
} else {
return true;
}
}
try {
queueWrite(requestQueue.remove(0));
} catch (IndexOutOfBoundsException e) {
log("requestsQueue empty");
}
}
}
return true;
}
private void handleBackgroundCharacteristic(BluetoothGattCharacteristic characteristic){
byte[] value = characteristic.getValue();
switch (value[1]){
case 2: {
byte syncId = value[2];
getDeviceSupport().getDevice().addDeviceInfo(new GenericItem(QHybridSupport.ITEM_LAST_HEARTBEAT, DateFormat.getTimeInstance().format(new Date())));
break;
}
case 8: {
break;
}
}
}
private void log(String message) {
Log.d("FossilWatchAdapter", message);
}
public void queueWrite(Request request) {
this.queueWrite(request, false);
}
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
super.onMtuChanged(gatt, mtu, status);
((RequestMtuRequest)fossilRequest).setFinished(true);
try {
queueWrite(requestQueue.remove(0));
} catch (IndexOutOfBoundsException e) {
}
}
//TODO split to multiple methods instead of switch
public void queueWrite(Request request, boolean priorise) {
if(request instanceof RequestMtuRequest){
//TODO mtu on older devices
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
new TransactionBuilder("requestMtu")
.requestMtu(512)
.queue(getDeviceSupport().getQueue());
this.fossilRequest = (FossilRequest) request;
}
return;
}else if(request instanceof SetDeviceStateRequest){
log("setting device state: " + ((SetDeviceStateRequest)request).getDeviceState());
getDeviceSupport().getDevice().setState(((SetDeviceStateRequest)request).getDeviceState());
getDeviceSupport().getDevice().sendDeviceUpdateIntent(getContext());
try {
queueWrite(requestQueue.remove(0));
} catch (IndexOutOfBoundsException e) {
}
return;
} else if (request.isBasicRequest()) {
try {
queueWrite(requestQueue.remove(0));
} catch (IndexOutOfBoundsException e) {
}
} else {
if (fossilRequest != null && !fossilRequest.isFinished()) {
log("queing request: " + request.getName());
if (priorise) {
requestQueue.add(0, request);
} else {
requestQueue.add(request);
}
return;
}
log("executing request: " + request.getName());
if (request instanceof FossilRequest) this.fossilRequest = (FossilRequest) request;
}
new TransactionBuilder(request.getClass().getSimpleName()).write(getDeviceSupport().getCharacteristic(request.getRequestUUID()), request.getRequestData()).queue(getDeviceSupport().getQueue());
}
}
| app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/qhybrid/adapter/fossil/FossilWatchAdapter.java | package nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.adapter.fossil;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.UUID;
import nodomain.freeyourgadget.gadgetbridge.GBException;
import nodomain.freeyourgadget.gadgetbridge.Logging;
import nodomain.freeyourgadget.gadgetbridge.devices.qhybrid.NotificationConfiguration;
import nodomain.freeyourgadget.gadgetbridge.devices.qhybrid.PackageConfigHelper;
import nodomain.freeyourgadget.gadgetbridge.entities.NotificationFilter;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.GenericItem;
import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.QHybridSupport;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.adapter.WatchAdapter;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.Request;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.FossilRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.RequestMtuRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.SetDeviceStateRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.configuration.ConfigurationGetRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.configuration.ConfigurationPutRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.connection.SetConnectionParametersRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.file.FileCloseRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.file.FileDeleteRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.file.FilePutRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.file.FileVerifyRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.notification.NotificationFilterPutRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.fossil.notification.PlayNotificationRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.misfit.AnimationRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.misfit.MoveHandsRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.misfit.ReleaseHandsControlRequest;
import nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.misfit.RequestHandControlRequest;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
public class FossilWatchAdapter extends WatchAdapter {
private ArrayList<Request> requestQueue = new ArrayList<>();
private FossilRequest fossilRequest;
public FossilWatchAdapter(QHybridSupport deviceSupport) {
super(deviceSupport);
}
@Override
public void initialize() {
// playPairingAnimation();
// queueWrite(new FileDeleteRequest((short) 0x0200));
queueWrite(new RequestMtuRequest(512));
queueWrite(new ConfigurationGetRequest(this));
// queueWrite(new SetConnectionParametersRequest());
syncNotificationSettings();
queueWrite(new SetDeviceStateRequest(GBDevice.State.INITIALIZED));
}
@Override
public void playPairingAnimation() {
queueWrite(new AnimationRequest());
}
@Override
public void playNotification(NotificationConfiguration config) {
if (config.getPackageName() == null) {
log("package name in notification not set");
return;
}
queueWrite(new PlayNotificationRequest(config.getPackageName(), this));
}
@Override
public void setTime() {
long millis = System.currentTimeMillis();
TimeZone zone = new GregorianCalendar().getTimeZone();
queueWrite(
new ConfigurationPutRequest(
new ConfigurationPutRequest.TimeConfigItem(
(int) (millis / 1000 + getDeviceSupport().getTimeOffset() * 60),
(short) (millis % 1000),
(short) ((zone.getRawOffset() + (zone.inDaylightTime(new Date()) ? 1 : 0)) / 60000)
),
this)
);
}
@Override
public void overwriteButtons() {
FilePutRequest uploadFileRequest = new FilePutRequest((short) 0x0600, new byte[]{
(byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x10, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x0C, (byte) 0x00, (byte) 0x00, (byte) 0x20, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x0C, (byte) 0x00, (byte) 0x00,
(byte) 0x30, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x0C, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x0C, (byte) 0x2E, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01,
(byte) 0x00, (byte) 0x06, (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x03, (byte) 0x00, (byte) 0x02, (byte) 0x01, (byte) 0x0F, (byte) 0x00, (byte) 0x8B, (byte) 0x00, (byte) 0x00, (byte) 0x93, (byte) 0x00, (byte) 0x01,
(byte) 0x08, (byte) 0x01, (byte) 0x14, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0xFE, (byte) 0x08, (byte) 0x00, (byte) 0x93, (byte) 0x00, (byte) 0x02, (byte) 0x01, (byte) 0x00, (byte) 0xBF, (byte) 0xD5, (byte) 0x54, (byte) 0xD1,
(byte) 0x00
}, this);
queueWrite(uploadFileRequest);
}
@Override
public void setActivityHand(double progress) {
queueWrite(new ConfigurationPutRequest(
new ConfigurationPutRequest.CurrentStepCountConfigItem(Math.min(999999, (int) (1000000 * progress))),
this
));
}
@Override
public void setHands(short hour, short minute) {
queueWrite(new MoveHandsRequest(false, minute, hour, (short) -1));
}
public void vibrate(nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.misfit.PlayNotificationRequest.VibrationType vibration) {
// queueWrite(new nodomain.freeyourgadget.gadgetbridge.service.devices.qhybrid.requests.misfit.PlayNotificationRequest(vibration, -1, -1));
}
@Override
public void vibrateFindMyDevicePattern() {
}
@Override
public void requestHandsControl() {
queueWrite(new RequestHandControlRequest());
}
@Override
public void releaseHandsControl() {
queueWrite(new ReleaseHandsControlRequest());
}
@Override
public void setStepGoal(int stepGoal) {
queueWrite(new ConfigurationPutRequest(new ConfigurationPutRequest.DailyStepGoalConfigItem(stepGoal), this));
}
@Override
public void setVibrationStrength(short strength) {
ConfigurationPutRequest.ConfigItem vibrationItem = new ConfigurationPutRequest.VibrationStrengthConfigItem((byte)strength);
queueWrite(
new ConfigurationPutRequest(new ConfigurationPutRequest.ConfigItem[]{vibrationItem, vibrationItem, vibrationItem}, this)
);
// queueWrite(new FileVerifyRequest((short) 0x0800));
}
@Override
public void syncNotificationSettings() {
log("syncing notification settings...");
try {
PackageConfigHelper helper = new PackageConfigHelper(getContext());
final ArrayList<NotificationConfiguration> configurations = helper.getNotificationConfigurations();
if (configurations.size() == 1) configurations.add(configurations.get(0));
queueWrite(new NotificationFilterPutRequest(configurations, FossilWatchAdapter.this) {
@Override
public void onFilePut(boolean success) {
super.onFilePut(success);
if (!success) {
GB.toast("error writing notification settings", Toast.LENGTH_SHORT, GB.ERROR);
getDeviceSupport().getDevice().setState(GBDevice.State.NOT_CONNECTED);
getDeviceSupport().getDevice().sendDeviceUpdateIntent(getContext());
}
getDeviceSupport().getDevice().setState(GBDevice.State.INITIALIZED);
getDeviceSupport().getDevice().sendDeviceUpdateIntent(getContext());
}
});
} catch (GBException e) {
e.printStackTrace();
}
}
@Override
public void onTestNewFunction() {
queueWrite(new ConfigurationPutRequest(new ConfigurationPutRequest.ConfigItem[0], this));
}
@Override
public boolean supportsFindDevice() {
return false;
}
@Override
public boolean supportsExtendedVibration() {
String modelNumber = getDeviceSupport().getDevice().getModel();
switch (modelNumber) {
case "HW.0.0":
return true;
case "HL.0.0":
return false;
}
throw new UnsupportedOperationException("model " + modelNumber + " not supported");
}
@Override
public boolean supportsActivityHand() {
String modelNumber = getDeviceSupport().getDevice().getModel();
switch (modelNumber) {
case "HW.0.0":
return true;
case "HL.0.0":
return false;
}
throw new UnsupportedOperationException("Model " + modelNumber + " not supported");
}
@Override
public String getModelName() {
String modelNumber = getDeviceSupport().getDevice().getModel();
switch (modelNumber) {
case "HW.0.0":
return "Q Commuter";
case "HL.0.0":
return "Q Activist";
}
return "unknwon Q";
}
@Override
public void onFetchActivityData() {
// queueWrite(new ConfigurationPutRequest(new ConfigurationPutRequest.ConfigItem[0], this));
setVibrationStrength((byte) 50);
// queueWrite(new FileCloseRequest((short) 0x0800));
// queueWrite(new ConfigurationGetRequest(this));
}
@Override
public boolean onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
switch (characteristic.getUuid().toString()) {
case "3dda0006-957f-7d4a-34a6-74696673696d": {
handleBackgroundCharacteristic(characteristic);
break;
}
case "3dda0002-957f-7d4a-34a6-74696673696d":
case "3dda0004-957f-7d4a-34a6-74696673696d":
case "3dda0003-957f-7d4a-34a6-74696673696d": {
if (fossilRequest != null) {
boolean requestFinished;
try {
if(characteristic.getUuid().toString().equals("3dda0003-957f-7d4a-34a6-74696673696d")){
byte requestType = (byte)(characteristic.getValue()[0] & 0x0F);
if(requestType != 0x0A && requestType != fossilRequest.getType()){
// throw new RuntimeException("Answer type " + requestType + " does not match current request " + fossilRequest.getType());
}
}
fossilRequest.handleResponse(characteristic);
requestFinished = fossilRequest.isFinished();
} catch (RuntimeException e) {
e.printStackTrace();
getDeviceSupport().notifiyException(e);
GB.toast(fossilRequest.getName() + " failed", Toast.LENGTH_SHORT, GB.ERROR);
requestFinished = true;
}
if (requestFinished) {
log(fossilRequest.getName() + " finished");
fossilRequest = null;
} else {
return true;
}
}
try {
queueWrite(requestQueue.remove(0));
} catch (IndexOutOfBoundsException e) {
log("requestsQueue empty");
}
}
}
return true;
}
private void handleBackgroundCharacteristic(BluetoothGattCharacteristic characteristic){
byte[] value = characteristic.getValue();
switch (value[1]){
case 2: {
byte syncId = value[2];
getDeviceSupport().getDevice().addDeviceInfo(new GenericItem(QHybridSupport.ITEM_LAST_HEARTBEAT, DateFormat.getTimeInstance().format(new Date())));
break;
}
case 8: {
break;
}
}
}
private void log(String message) {
Log.d("FossilWatchAdapter", message);
}
public void queueWrite(Request request) {
this.queueWrite(request, false);
}
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
super.onMtuChanged(gatt, mtu, status);
((RequestMtuRequest)fossilRequest).setFinished(true);
try {
queueWrite(requestQueue.remove(0));
} catch (IndexOutOfBoundsException e) {
}
}
//TODO split to multiple methods instead of switch
public void queueWrite(Request request, boolean priorise) {
if(request instanceof RequestMtuRequest){
//TODO mtu on older devices
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
new TransactionBuilder("requestMtu")
.requestMtu(512)
.queue(getDeviceSupport().getQueue());
this.fossilRequest = (FossilRequest) request;
}
return;
}else if(request instanceof SetDeviceStateRequest){
log("setting device state: " + ((SetDeviceStateRequest)request).getDeviceState());
getDeviceSupport().getDevice().setState(((SetDeviceStateRequest)request).getDeviceState());
getDeviceSupport().getDevice().sendDeviceUpdateIntent(getContext());
try {
queueWrite(requestQueue.remove(0));
} catch (IndexOutOfBoundsException e) {
}
return;
} else if (request.isBasicRequest()) {
try {
queueWrite(requestQueue.remove(0));
} catch (IndexOutOfBoundsException e) {
}
} else {
if (fossilRequest != null && !fossilRequest.isFinished()) {
log("queing request: " + request.getName());
if (priorise) {
requestQueue.add(0, request);
} else {
requestQueue.add(request);
}
return;
}
log("executing request: " + request.getName());
if (request instanceof FossilRequest) this.fossilRequest = (FossilRequest) request;
}
new TransactionBuilder(request.getClass().getSimpleName()).write(getDeviceSupport().getCharacteristic(request.getRequestUUID()), request.getRequestData()).queue(getDeviceSupport().getQueue());
}
}
| fixed duplicate vibration settings
| app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/qhybrid/adapter/fossil/FossilWatchAdapter.java | fixed duplicate vibration settings |
|
Java | agpl-3.0 | 5b4d38633f432e438cb138bad6622bcc406b8eb4 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | ae4c85fe-2e61-11e5-9284-b827eb9e62be | hello.java | ae46de10-2e61-11e5-9284-b827eb9e62be | ae4c85fe-2e61-11e5-9284-b827eb9e62be | hello.java | ae4c85fe-2e61-11e5-9284-b827eb9e62be |
|
Java | lgpl-2.1 | 73896f294256faf653d4b28f8a0b90c9f11d748a | 0 | SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer | /* ClassChooserPanel2.java
*
* Created on May 13, 2007, 3:46 PM */
package net.sf.jaer.util;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultListModel;
import javax.swing.InputMap;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.ListCellRenderer;
import javax.swing.SwingWorker;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
/**
* A panel that finds subclasses of a class, displays them in a left list,
* displays another list given as a parameter in the right panel, and accepts a
* list of default class names. The user can choose which classes and these are
* returned by a call to getList. The list of available classes is built in the
* background.
*
* @author tobi
*/
public class ClassChooserPanel extends javax.swing.JPanel {
private static final Logger log = Logger.getLogger("net.sf.jaer.util");
private static final String MISSING_DESCRIPTION_MESSAGE = "<html>No description available - provide one using @Description annotation, as in <pre>@Description(\"Example class\") \n public class MyClass</pre></html>";
private FilterableListModel chosenClassesListModel, availClassesListModel;
private ArrayList<String> revertCopy, defaultClassNames, availAllList;
private DescriptionMap descriptionMap = new DescriptionMap();
private class ClassDescription {
String description = null;
DevelopmentStatus.Status developmentStatus = null;
public ClassDescription(String description, DevelopmentStatus.Status developmentStatus) {
this.description = description;
this.developmentStatus = developmentStatus;
}
}
class DescriptionMap extends HashMap<String, ClassDescription> {
ClassDescription get(String name) {
if (name == null) {
return null;
}
if (super.get(name) == null) {
put(name);
}
return super.get(name);
}
void put(String name) {
if (name == null) {
return;
}
if (containsKey(name)) {
return;
}
try {
Class c = Class.forName(name);
if (c == null) {
log.warning("tried to put class " + name + " but there is no such class");
return;
}
String descriptionString = null;
if (c.isAnnotationPresent(Description.class)) {
Description des = (Description) c.getAnnotation(Description.class);
descriptionString = des.value();
}
DevelopmentStatus.Status devStatus = null;
if (c.isAnnotationPresent(DevelopmentStatus.class)) {
DevelopmentStatus des = (DevelopmentStatus) c.getAnnotation(DevelopmentStatus.class);
devStatus = des.value();
}
ClassDescription des = new ClassDescription(descriptionString, devStatus);
put(name, des);
} catch (Exception e) {
log.warning("trying to put class named " + name + " caught " + e.toString());
}
}
}
/**
* Creates new form ClassChooserPanel
*
* @param subclassOf a Class that will be used to search the classpath for
* subclasses of subClassOf.
* @param classNames a list of names, which is filled in by the actions of
* the user with the chosen classes
* @param defaultClassNames the list on the right is replaced by this lixt
* if the user pushes the Defaults button.
*/
public ClassChooserPanel(final Class subclassOf, ArrayList<String> classNames, ArrayList<String> defaultClassNames) {
initComponents();
availFilterTextField.requestFocusInWindow();
this.defaultClassNames = defaultClassNames;
final SubclassFinder.SubclassFinderWorker worker = new SubclassFinder.SubclassFinderWorker(subclassOf);
final DefaultListModel tmpList = new DefaultListModel();
tmpList.addElement("scanning...");
availClassJList.setModel(tmpList);
worker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
// System.out.println(evt.getPropertyName() + " " + evt.getNewValue());
if ((evt != null) && evt.getNewValue().equals(SwingWorker.StateValue.DONE)) {
try {
availAllList = worker.get();
if (availAllList == null) {
log.warning("got empty list of classes - something wrong here, aborting dialog");
return;
}
Collections.sort(availAllList, new ClassNameSorter());
availClassesListModel = new FilterableListModel(availAllList);
availClassJList.setModel(availClassesListModel);
availClassJList.setCellRenderer(new MyCellRenderer());
Action addAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
Object o = availClassJList.getSelectedValue();
if (o == null) {
return;
}
int last = chosenClassesListModel.getSize() - 1;
chosenClassesListModel.add(last + 1, o);
classJList.setSelectedIndex(last + 1);
}
};
addAction(availClassJList, addAction);
if (!availFilterTextField.getText().isEmpty()) {
// user started to select a class before list was populated
String s = availFilterTextField.getText();
availClassesListModel.filter(s);
}
} catch (Exception ex) {
Logger.getLogger(ClassChooserPanel.class.getName()).log(Level.SEVERE, null, ex);
} finally {
setCursor(Cursor.getDefaultCursor());
}
} else if ((evt != null) && (evt.getNewValue() instanceof Integer)) {
int progress = (Integer) evt.getNewValue();
String s = String.format("Scanning %d/100...", progress);
tmpList.removeAllElements();
tmpList.addElement(s);
}
}
});
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
worker.execute();
Action removeAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
int index = classJList.getSelectedIndex();
chosenClassesListModel.removeElementAt(index);
int size = chosenClassesListModel.getSize();
if (size == 0) { //Nobody's left, disable firing.
removeClassButton.setEnabled(false);
} else { //Select an index.
if (index == chosenClassesListModel.getSize()) {
//removed item in last position
index--;
}
classJList.setSelectedIndex(index);
classJList.ensureIndexIsVisible(index);
}
}
};
addAction(classJList, removeAction);
revertCopy = new ArrayList<>(classNames);
chosenClassesListModel = new FilterableListModel(classNames);
classJList.setModel(chosenClassesListModel);
classJList.setCellRenderer(new MyCellRenderer());
}
public JPanel getFilterTypeOptionsPanel() {
return filterTypeOptionsPanel;
}
private class ClassNameSorter implements Comparator {
@Override
public int compare(Object o1, Object o2) {
if ((o1 instanceof String) && (o2 instanceof String)) {
return shortName((String) o1).compareTo(shortName((String) o2));
} else {
return -1;
}
}
}
private DevelopmentStatus.Status getClassDevelopmentStatus(String className) {
ClassDescription des = descriptionMap.get(className);
if (des == null) {
return null;
}
return des.developmentStatus;
}
private String getClassDescription(String className) {
ClassDescription des = descriptionMap.get(className);
if (des == null) {
return null;
}
return des.description;
}
private class MyCellRenderer extends JLabel implements ListCellRenderer {
// This is the only method defined by ListCellRenderer.
// We just reconfigure the JLabel each time we're called.
/**
* @param list The JList we're painting.
* @param value The value returned by
* list.getModel().getElementAt(index).
* @param index The cells index.
* @param isSelected True if the specified cell was selected.
* @param cellHasFocus True if the specified cell has the focus.
*/
@Override
public Component getListCellRendererComponent(JList list, Object obj, int index, boolean isSelected, boolean cellHasFocus) {
String fullclassname = obj.toString();
String shortname = shortName(fullclassname);//.substring(fullclassname.lastIndexOf('.') + 1);
setText(shortname);
Color foreground, background;
if (isSelected) {
background = list.getSelectionBackground();
DevelopmentStatus.Status develStatus = getClassDevelopmentStatus(fullclassname);
String des = getClassDescription(fullclassname);
ClassNameTF.setText(fullclassname);
if (develStatus == DevelopmentStatus.Status.Experimental) {
foreground = Color.ORANGE;
develStatusTF.setText(develStatus.toString());
} else if (develStatus == DevelopmentStatus.Status.InDevelopment) {
foreground = Color.PINK;
develStatusTF.setText(develStatus.toString());
} else if (develStatus == DevelopmentStatus.Status.Stable) {
foreground = Color.BLUE;
develStatusTF.setText(develStatus.toString());
} else {
foreground = Color.LIGHT_GRAY;
develStatusTF.setText("unknown");
}
if (des != null) {
setToolTipText(fullclassname + ": " + des);
descPane.setContentType("text/html");
descPane.setText("<html>" + shortname + ": " + des);
} else {
foreground = Color.GRAY;
setToolTipText(fullclassname);
descPane.setText(MISSING_DESCRIPTION_MESSAGE);
}
} else {
background = list.getBackground();
DevelopmentStatus.Status develStatus = getClassDevelopmentStatus(fullclassname);
if (develStatus == DevelopmentStatus.Status.Experimental) {
foreground = Color.ORANGE;
} else if (develStatus == DevelopmentStatus.Status.InDevelopment) {
foreground = Color.PINK;
} else if (develStatus == DevelopmentStatus.Status.Stable) {
foreground = Color.BLUE;
} else {
foreground = Color.LIGHT_GRAY;
}
if (getClassDescription(fullclassname) == null) {
foreground = Color.GRAY;
}
}
setEnabled(list.isEnabled());
setOpaque(true);
setForeground(foreground);
setBackground(background);
return this;
}
}
private String shortName(String s) {
int i = s.lastIndexOf('.');
if ((i < 0) || (i == (s.length() - 1))) {
return s;
}
return s.substring(i + 1);
}
// extends DefaultListModel to add a text filter
public class FilterableListModel extends DefaultListModel {
Vector origList = new Vector();
String filterString = null;
FilterableListModel(List<String> list) {
super();
for (String s : list) {
this.addElement(s);
}
origList.addAll(list);
}
synchronized void resetList() {
clear();
for (Object o : origList) {
addElement(o);
}
}
synchronized void filter(String s) {
if ((s == null) || s.equals("")) {
resetList();
return;
}
filterString = s.toLowerCase();
resetList();
Vector v = new Vector(); // list to prune out
// must build a list of stuff to prune, then prune
Enumeration en = elements();
while (en.hasMoreElements()) {
Object o = en.nextElement();
String st = ((String) o).toLowerCase();
int ind = st.indexOf(filterString);
if (ind == -1) {
v.add(o);
}
}
// prune list
for (Object o : v) {
removeElement(o);
}
}
synchronized void clearFilter() {
filter(null);
}
}
public FilterableListModel getChosenClassesListModel() {
return chosenClassesListModel;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
availClassPanel = new javax.swing.JPanel();
filterPanel = new javax.swing.JPanel();
filterLabel = new javax.swing.JLabel();
availFilterTextField = new javax.swing.JTextField();
filterTypeOptionsPanel = new javax.swing.JPanel();
clearFilterBut = new javax.swing.JButton();
availClassDesciptionPanel = new javax.swing.JScrollPane();
availClassJList = new javax.swing.JList();
chosenClassPanel = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
classJList = new javax.swing.JList();
addClassButton = new javax.swing.JButton();
removeClassButton = new javax.swing.JButton();
removeAllButton = new javax.swing.JButton();
descPanel = new javax.swing.JPanel();
ClassDescSP = new javax.swing.JScrollPane();
descPane = new javax.swing.JTextPane();
devlStatusLbl = new javax.swing.JLabel();
develStatusTF = new javax.swing.JTextField();
ClassNameLbl = new javax.swing.JLabel();
ClassNameTF = new javax.swing.JTextField();
moveUpButton = new javax.swing.JButton();
revertButton = new javax.swing.JButton();
moveDownButton = new javax.swing.JButton();
defaultsButton = new javax.swing.JButton();
setPreferredSize(new java.awt.Dimension(580, 686));
availClassPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Available classes"));
availClassPanel.setToolTipText("<html>If your class doesn't show up here, rebuild the project to get it into jAER.jar (or some other jar on the classpath). <p> Yyour class must be concrete (not abstract). <p> Finally, if your class lives in a separate JAR archive, make sure your archive classpath is not on the excluded list in the class ListClasses.");
availClassPanel.setPreferredSize(new java.awt.Dimension(400, 300));
filterLabel.setText("Filter");
availFilterTextField.setToolTipText("type any part of your filter name or description here to filter list");
availFilterTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
availFilterTextFieldActionPerformed(evt);
}
});
availFilterTextField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
availFilterTextFieldKeyTyped(evt);
}
});
clearFilterBut.setText("X");
clearFilterBut.setIconTextGap(0);
clearFilterBut.setMargin(new java.awt.Insets(2, 1, 1, 2));
clearFilterBut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearFilterButActionPerformed(evt);
}
});
javax.swing.GroupLayout filterPanelLayout = new javax.swing.GroupLayout(filterPanel);
filterPanel.setLayout(filterPanelLayout);
filterPanelLayout.setHorizontalGroup(
filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addGap(2, 2, 2)
.addGroup(filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addComponent(filterLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(availFilterTextField)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(clearFilterBut))
.addComponent(filterTypeOptionsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
filterPanelLayout.setVerticalGroup(
filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addGap(2, 2, 2)
.addGroup(filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(filterLabel)
.addComponent(availFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(clearFilterBut))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(filterTypeOptionsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(42, 42, 42))
);
availClassDesciptionPanel.setBorder(null);
availClassJList.setToolTipText("If your class doesn't show up here, rebuild the project to get it into jAER.jar (or some other jar on the classpath)");
availClassDesciptionPanel.setViewportView(availClassJList);
availClassJList.getAccessibleContext().setAccessibleDescription("");
javax.swing.GroupLayout availClassPanelLayout = new javax.swing.GroupLayout(availClassPanel);
availClassPanel.setLayout(availClassPanelLayout);
availClassPanelLayout.setHorizontalGroup(
availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(availClassPanelLayout.createSequentialGroup()
.addGap(2, 2, 2)
.addGroup(availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(availClassDesciptionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(availClassPanelLayout.createSequentialGroup()
.addComponent(filterPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(2, 2, 2))))
);
availClassPanelLayout.setVerticalGroup(
availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, availClassPanelLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(filterPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(availClassDesciptionPanel))
);
chosenClassPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Selected classes"));
chosenClassPanel.setToolTipText("These classes will be available to choose.");
chosenClassPanel.setPreferredSize(new java.awt.Dimension(400, 300));
jScrollPane3.setBorder(null);
classJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
classJList.setToolTipText("These classes will be available to choose.");
classJList.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
classJListMouseClicked(evt);
}
});
jScrollPane3.setViewportView(classJList);
classJList.getAccessibleContext().setAccessibleDescription("");
javax.swing.GroupLayout chosenClassPanelLayout = new javax.swing.GroupLayout(chosenClassPanel);
chosenClassPanel.setLayout(chosenClassPanelLayout);
chosenClassPanelLayout.setHorizontalGroup(
chosenClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
);
chosenClassPanelLayout.setVerticalGroup(
chosenClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, chosenClassPanelLayout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE))
);
addClassButton.setMnemonic('a');
addClassButton.setText(">");
addClassButton.setToolTipText("Add the filter to the list of available filters");
addClassButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
addClassButton.setMaximumSize(null);
addClassButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addClassButtonActionPerformed(evt);
}
});
removeClassButton.setMnemonic('r');
removeClassButton.setText("<");
removeClassButton.setToolTipText("Remove the filter from the list of selected filters");
removeClassButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
removeClassButton.setMaximumSize(null);
removeClassButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeClassButtonActionPerformed(evt);
}
});
removeAllButton.setText("<<");
removeAllButton.setToolTipText("Remove all filters from the list of selected filters");
removeAllButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
removeAllButton.setMaximumSize(null);
removeAllButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeAllButtonActionPerformed(evt);
}
});
descPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Class description"));
ClassDescSP.setBorder(null);
descPane.setEditable(false);
descPane.setBorder(null);
ClassDescSP.setViewportView(descPane);
devlStatusLbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
devlStatusLbl.setText("Development status:");
develStatusTF.setEditable(false);
develStatusTF.setBackground(new java.awt.Color(255, 255, 255));
develStatusTF.setToolTipText("Shows DevelopmentStatus of class as annotated with DevelopmentStatus");
develStatusTF.setBorder(null);
ClassNameLbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
ClassNameLbl.setText("Full class name:");
ClassNameTF.setEditable(false);
ClassNameTF.setBackground(new java.awt.Color(255, 255, 255));
ClassNameTF.setToolTipText("Shows the full classname of a class and hence its location in the jAER project");
ClassNameTF.setBorder(null);
javax.swing.GroupLayout descPanelLayout = new javax.swing.GroupLayout(descPanel);
descPanel.setLayout(descPanelLayout);
descPanelLayout.setHorizontalGroup(
descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, descPanelLayout.createSequentialGroup()
.addGap(2, 2, 2)
.addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(ClassDescSP)
.addGroup(descPanelLayout.createSequentialGroup()
.addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(ClassNameLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(devlStatusLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(4, 4, 4)
.addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ClassNameTF, javax.swing.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE)
.addComponent(develStatusTF, javax.swing.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE))))
.addGap(2, 2, 2))
);
descPanelLayout.setVerticalGroup(
descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(descPanelLayout.createSequentialGroup()
.addComponent(ClassDescSP, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(devlStatusLbl)
.addComponent(develStatusTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ClassNameLbl)
.addComponent(ClassNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10))
);
moveUpButton.setMnemonic('u');
moveUpButton.setText("Move up");
moveUpButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
moveUpButton.setMaximumSize(null);
moveUpButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
moveUpButtonActionPerformed(evt);
}
});
revertButton.setMnemonic('e');
revertButton.setText("Revert");
revertButton.setToolTipText("Revert changes to the list");
revertButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
revertButton.setMaximumSize(null);
revertButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
revertButtonActionPerformed(evt);
}
});
moveDownButton.setMnemonic('d');
moveDownButton.setText("Move down");
moveDownButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
moveDownButton.setMaximumSize(null);
moveDownButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
moveDownButtonActionPerformed(evt);
}
});
defaultsButton.setMnemonic('d');
defaultsButton.setText("Add Defaults");
defaultsButton.setToolTipText("Adds the defaults to the end of the selected classes list");
defaultsButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
defaultsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
defaultsButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(descPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(availClassPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 236, Short.MAX_VALUE)
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(defaultsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(removeClassButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(removeAllButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(moveUpButton, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(revertButton, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(moveDownButton, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(addClassButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10)
.addComponent(chosenClassPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE))))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {addClassButton, defaultsButton, moveDownButton, moveUpButton, removeAllButton, removeClassButton, revertButton});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(67, 67, 67)
.addComponent(addClassButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(removeClassButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(removeAllButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(moveUpButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(moveDownButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(revertButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(defaultsButton))
.addComponent(availClassPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
.addComponent(chosenClassPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(descPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void defaultsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_defaultsButtonActionPerformed
// chosenClassesListModel.clear();
int i = 0;
for (String s : defaultClassNames) { // add them in reverse order because they were added to the list
chosenClassesListModel.insertElementAt(s, i++);
// chosenClassesListModel.addElement(s);
}
}//GEN-LAST:event_defaultsButtonActionPerformed
private void removeAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeAllButtonActionPerformed
chosenClassesListModel.clear();
}//GEN-LAST:event_removeAllButtonActionPerformed
private void revertButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_revertButtonActionPerformed
chosenClassesListModel.clear();
for (String s : revertCopy) {
chosenClassesListModel.addElement(s);
}
}//GEN-LAST:event_revertButtonActionPerformed
private void addClassButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addClassButtonActionPerformed
Object o = availClassJList.getSelectedValue();
if (o == null) {
return;
}
int last = chosenClassesListModel.getSize() - 1;
chosenClassesListModel.add(last + 1, o);
classJList.setSelectedIndex(last + 1);
}//GEN-LAST:event_addClassButtonActionPerformed
private void moveDownButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveDownButtonActionPerformed
int last = chosenClassesListModel.getSize() - 1;
int index = classJList.getSelectedIndex();
if (index == last) {
return;
}
Object o = chosenClassesListModel.getElementAt(index);
chosenClassesListModel.removeElementAt(index);
chosenClassesListModel.insertElementAt(o, index + 1);
classJList.setSelectedIndex(index + 1);
}//GEN-LAST:event_moveDownButtonActionPerformed
private void moveUpButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveUpButtonActionPerformed
int index = classJList.getSelectedIndex();
if (index == 0) {
return;
}
Object o = chosenClassesListModel.getElementAt(index);
chosenClassesListModel.removeElementAt(index);
chosenClassesListModel.insertElementAt(o, index - 1);
classJList.setSelectedIndex(index - 1);
}//GEN-LAST:event_moveUpButtonActionPerformed
private void removeClassButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeClassButtonActionPerformed
int index = classJList.getSelectedIndex();
chosenClassesListModel.removeElementAt(index);
int size = chosenClassesListModel.getSize();
if (size == 0) { //Nobody's left, disable firing.
removeClassButton.setEnabled(false);
} else { //Select an index.
if (index == chosenClassesListModel.getSize()) {
//removed item in last position
index--;
}
classJList.setSelectedIndex(index);
classJList.ensureIndexIsVisible(index);
}
}//GEN-LAST:event_removeClassButtonActionPerformed
private void classJListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_classJListMouseClicked
moveDownButton.setEnabled(true);
moveUpButton.setEnabled(true);
}//GEN-LAST:event_classJListMouseClicked
private void clearFilterButActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearFilterButActionPerformed
availFilterTextField.setText("");
availClassesListModel.clearFilter();
}//GEN-LAST:event_clearFilterButActionPerformed
private void availFilterTextFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_availFilterTextFieldKeyTyped
if (availClassesListModel == null) {
return;
}
String s = availFilterTextField.getText();
availClassesListModel.filter(s);
}//GEN-LAST:event_availFilterTextFieldKeyTyped
private void availFilterTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_availFilterTextFieldActionPerformed
if (availClassesListModel == null) {
return;
}
String s = availFilterTextField.getText();
availClassesListModel.filter(s);
}//GEN-LAST:event_availFilterTextFieldActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane ClassDescSP;
private javax.swing.JLabel ClassNameLbl;
private javax.swing.JTextField ClassNameTF;
private javax.swing.JButton addClassButton;
private javax.swing.JScrollPane availClassDesciptionPanel;
private javax.swing.JList availClassJList;
private javax.swing.JPanel availClassPanel;
private javax.swing.JTextField availFilterTextField;
private javax.swing.JPanel chosenClassPanel;
private javax.swing.JList classJList;
private javax.swing.JButton clearFilterBut;
private javax.swing.JButton defaultsButton;
private javax.swing.JTextPane descPane;
private javax.swing.JPanel descPanel;
private javax.swing.JTextField develStatusTF;
private javax.swing.JLabel devlStatusLbl;
private javax.swing.JLabel filterLabel;
private javax.swing.JPanel filterPanel;
private javax.swing.JPanel filterTypeOptionsPanel;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JButton moveDownButton;
private javax.swing.JButton moveUpButton;
private javax.swing.JButton removeAllButton;
private javax.swing.JButton removeClassButton;
private javax.swing.JButton revertButton;
// End of variables declaration//GEN-END:variables
// from http://forum.java.sun.com/thread.jspa?forumID=57&threadID=626866
private static final KeyStroke ENTER = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
public static void addAction(JList source, Action action) {
// Handle enter key
InputMap im = source.getInputMap();
im.put(ENTER, ENTER);
source.getActionMap().put(ENTER, action);
// Handle mouse double click
source.addMouseListener(new ActionMouseListener());
}
// Implement Mouse Listener
static class ActionMouseListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
JList list = (JList) e.getSource();
Action action = list.getActionMap().get(ENTER);
if (action != null) {
ActionEvent event = new ActionEvent(
list,
ActionEvent.ACTION_PERFORMED,
"");
action.actionPerformed(event);
}
}
}
}
public class ClassNameWithDescriptionAndDevelopmentStatus {
String className;
Description description;
DevelopmentStatus developmentStatus;
public ClassNameWithDescriptionAndDevelopmentStatus(String className, Description description, DevelopmentStatus developmentStatus) {
this.className = className;
this.description = description;
this.developmentStatus = developmentStatus;
}
public ClassNameWithDescriptionAndDevelopmentStatus(Class clazz) {
}
public String toString(){
return className;
}
}
}
| src/net/sf/jaer/util/ClassChooserPanel.java | /* ClassChooserPanel2.java
*
* Created on May 13, 2007, 3:46 PM */
package net.sf.jaer.util;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultListModel;
import javax.swing.InputMap;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.ListCellRenderer;
import javax.swing.SwingWorker;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
/**
* A panel that finds subclasses of a class, displays them in a left list,
* displays another list given as a parameter in the right panel, and accepts a
* list of default class names. The user can choose which classes and these are
* returned by a call to getList. The list of available classes is built in the
* background.
*
* @author tobi
*/
public class ClassChooserPanel extends javax.swing.JPanel {
private static final Logger log = Logger.getLogger("net.sf.jaer.util");
private static final String MISSING_DESCRIPTION_MESSAGE = "<html>No description available - provide one using @Description annotation, as in <pre>@Description(\"Example class\") \n public class MyClass</pre></html>";
private FilterableListModel chosenClassesListModel, availClassesListModel;
private ArrayList<String> revertCopy, defaultClassNames, availAllList;
private DescriptionMap descriptionMap = new DescriptionMap();
private class ClassDescription {
String description = null;
DevelopmentStatus.Status developmentStatus = null;
public ClassDescription(String description, DevelopmentStatus.Status developmentStatus) {
this.description = description;
this.developmentStatus = developmentStatus;
}
}
class DescriptionMap extends HashMap<String, ClassDescription> {
ClassDescription get(String name) {
if (name == null) {
return null;
}
if (super.get(name) == null) {
put(name);
}
return super.get(name);
}
void put(String name) {
if (name == null) {
return;
}
if (containsKey(name)) {
return;
}
try {
Class c = Class.forName(name);
if (c == null) {
log.warning("tried to put class " + name + " but there is no such class");
return;
}
String descriptionString = null;
if (c.isAnnotationPresent(Description.class)) {
Description des = (Description) c.getAnnotation(Description.class);
descriptionString = des.value();
}
DevelopmentStatus.Status devStatus = null;
if (c.isAnnotationPresent(DevelopmentStatus.class)) {
DevelopmentStatus des = (DevelopmentStatus) c.getAnnotation(DevelopmentStatus.class);
devStatus = des.value();
}
ClassDescription des = new ClassDescription(descriptionString, devStatus);
put(name, des);
} catch (Exception e) {
log.warning("trying to put class named " + name + " caught " + e.toString());
}
}
}
/**
* Creates new form ClassChooserPanel
*
* @param subclassOf a Class that will be used to search the classpath for
* subclasses of subClassOf.
* @param classNames a list of names, which is filled in by the actions of
* the user with the chosen classes
* @param defaultClassNames the list on the right is replaced by this lixt
* if the user pushes the Defaults button.
*/
public ClassChooserPanel(final Class subclassOf, ArrayList<String> classNames, ArrayList<String> defaultClassNames) {
initComponents();
availFilterTextField.requestFocusInWindow();
this.defaultClassNames = defaultClassNames;
final SubclassFinder.SubclassFinderWorker worker = new SubclassFinder.SubclassFinderWorker(subclassOf);
final DefaultListModel tmpList = new DefaultListModel();
tmpList.addElement("scanning...");
availClassJList.setModel(tmpList);
worker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
// System.out.println(evt.getPropertyName() + " " + evt.getNewValue());
if ((evt != null) && evt.getNewValue().equals(SwingWorker.StateValue.DONE)) {
try {
availAllList = worker.get();
if (availAllList == null) {
log.warning("got empty list of classes - something wrong here, aborting dialog");
return;
}
Collections.sort(availAllList, new ClassNameSorter());
availClassesListModel = new FilterableListModel(availAllList);
availClassJList.setModel(availClassesListModel);
availClassJList.setCellRenderer(new MyCellRenderer());
Action addAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
Object o = availClassJList.getSelectedValue();
if (o == null) {
return;
}
int last = chosenClassesListModel.getSize() - 1;
chosenClassesListModel.add(last + 1, o);
classJList.setSelectedIndex(last + 1);
}
};
addAction(availClassJList, addAction);
if (!availFilterTextField.getText().isEmpty()) {
// user started to select a class before list was populated
String s = availFilterTextField.getText();
availClassesListModel.filter(s);
}
} catch (Exception ex) {
Logger.getLogger(ClassChooserPanel.class.getName()).log(Level.SEVERE, null, ex);
} finally {
setCursor(Cursor.getDefaultCursor());
}
} else if ((evt != null) && (evt.getNewValue() instanceof Integer)) {
int progress = (Integer) evt.getNewValue();
String s = String.format("Scanning %d/100...", progress);
tmpList.removeAllElements();
tmpList.addElement(s);
}
}
});
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
worker.execute();
Action removeAction = new AbstractAction() {
@Override
public void actionPerformed(final ActionEvent e) {
int index = classJList.getSelectedIndex();
chosenClassesListModel.removeElementAt(index);
int size = chosenClassesListModel.getSize();
if (size == 0) { //Nobody's left, disable firing.
removeClassButton.setEnabled(false);
} else { //Select an index.
if (index == chosenClassesListModel.getSize()) {
//removed item in last position
index--;
}
classJList.setSelectedIndex(index);
classJList.ensureIndexIsVisible(index);
}
}
};
addAction(classJList, removeAction);
revertCopy = new ArrayList<>(classNames);
chosenClassesListModel = new FilterableListModel(classNames);
classJList.setModel(chosenClassesListModel);
classJList.setCellRenderer(new MyCellRenderer());
}
public JPanel getFilterTypeOptionsPanel() {
return filterTypeOptionsPanel;
}
private class ClassNameSorter implements Comparator {
@Override
public int compare(Object o1, Object o2) {
if ((o1 instanceof String) && (o2 instanceof String)) {
return shortName((String) o1).compareTo(shortName((String) o2));
} else {
return -1;
}
}
}
private DevelopmentStatus.Status getClassDevelopmentStatus(String className) {
ClassDescription des = descriptionMap.get(className);
if (des == null) {
return null;
}
return des.developmentStatus;
}
private String getClassDescription(String className) {
ClassDescription des = descriptionMap.get(className);
if (des == null) {
return null;
}
return des.description;
}
private class MyCellRenderer extends JLabel implements ListCellRenderer {
// This is the only method defined by ListCellRenderer.
// We just reconfigure the JLabel each time we're called.
/**
* @param list The JList we're painting.
* @param value The value returned by
* list.getModel().getElementAt(index).
* @param index The cells index.
* @param isSelected True if the specified cell was selected.
* @param cellHasFocus True if the specified cell has the focus.
*/
@Override
public Component getListCellRendererComponent(JList list, Object obj, int index, boolean isSelected, boolean cellHasFocus) {
String fullclassname = obj.toString();
String shortname = shortName(fullclassname);//.substring(fullclassname.lastIndexOf('.') + 1);
setText(shortname);
Color foreground, background;
if (isSelected) {
background = list.getSelectionBackground();
DevelopmentStatus.Status develStatus = getClassDevelopmentStatus(fullclassname);
String des = getClassDescription(fullclassname);
ClassNameTF.setText(fullclassname);
if (develStatus == DevelopmentStatus.Status.Experimental) {
foreground = Color.ORANGE;
develStatusTF.setText(develStatus.toString());
} else if (develStatus == DevelopmentStatus.Status.InDevelopment) {
foreground = Color.PINK;
develStatusTF.setText(develStatus.toString());
} else if (develStatus == DevelopmentStatus.Status.Stable) {
foreground = Color.BLUE;
develStatusTF.setText(develStatus.toString());
} else {
foreground = Color.LIGHT_GRAY;
develStatusTF.setText("unknown");
}
if (des != null) {
setToolTipText(fullclassname + ": " + des);
descPane.setContentType("text/html");
descPane.setText("<html>" + shortname + ": " + des);
} else {
foreground = Color.GRAY;
setToolTipText(fullclassname);
descPane.setText(MISSING_DESCRIPTION_MESSAGE);
}
} else {
background = list.getBackground();
DevelopmentStatus.Status develStatus = getClassDevelopmentStatus(fullclassname);
if (develStatus == DevelopmentStatus.Status.Experimental) {
foreground = Color.ORANGE;
} else if (develStatus == DevelopmentStatus.Status.InDevelopment) {
foreground = Color.PINK;
} else if (develStatus == DevelopmentStatus.Status.Stable) {
foreground = Color.BLUE;
} else {
foreground = Color.LIGHT_GRAY;
}
if (getClassDescription(fullclassname) == null) {
foreground = Color.GRAY;
}
}
setEnabled(list.isEnabled());
setOpaque(true);
setForeground(foreground);
setBackground(background);
return this;
}
}
private String shortName(String s) {
int i = s.lastIndexOf('.');
if ((i < 0) || (i == (s.length() - 1))) {
return s;
}
return s.substring(i + 1);
}
// extends DefaultListModel to add a text filter
public class FilterableListModel extends DefaultListModel {
Vector origList = new Vector();
String filterString = null;
FilterableListModel(List<String> list) {
super();
for (String s : list) {
this.addElement(s);
}
origList.addAll(list);
}
synchronized void resetList() {
clear();
for (Object o : origList) {
addElement(o);
}
}
synchronized void filter(String s) {
if ((s == null) || s.equals("")) {
resetList();
return;
}
filterString = s.toLowerCase();
resetList();
Vector v = new Vector(); // list to prune out
// must build a list of stuff to prune, then prune
Enumeration en = elements();
while (en.hasMoreElements()) {
Object o = en.nextElement();
String st = ((String) o).toLowerCase();
int ind = st.indexOf(filterString);
if (ind == -1) {
v.add(o);
}
}
// prune list
for (Object o : v) {
removeElement(o);
}
}
synchronized void clearFilter() {
filter(null);
}
}
public FilterableListModel getChosenClassesListModel() {
return chosenClassesListModel;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
availClassPanel = new javax.swing.JPanel();
filterPanel = new javax.swing.JPanel();
filterLabel = new javax.swing.JLabel();
availFilterTextField = new javax.swing.JTextField();
filterTypeOptionsPanel = new javax.swing.JPanel();
clearFilterBut = new javax.swing.JButton();
availClassDesciptionPanel = new javax.swing.JScrollPane();
availClassJList = new javax.swing.JList();
chosenClassPanel = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
classJList = new javax.swing.JList();
addClassButton = new javax.swing.JButton();
removeClassButton = new javax.swing.JButton();
removeAllButton = new javax.swing.JButton();
descPanel = new javax.swing.JPanel();
ClassDescSP = new javax.swing.JScrollPane();
descPane = new javax.swing.JTextPane();
devlStatusLbl = new javax.swing.JLabel();
develStatusTF = new javax.swing.JTextField();
ClassNameLbl = new javax.swing.JLabel();
ClassNameTF = new javax.swing.JTextField();
moveUpButton = new javax.swing.JButton();
revertButton = new javax.swing.JButton();
moveDownButton = new javax.swing.JButton();
defaultsButton = new javax.swing.JButton();
setPreferredSize(new java.awt.Dimension(580, 686));
availClassPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Available classes"));
availClassPanel.setToolTipText("<html>If your class doesn't show up here, rebuild the project to get it into jAER.jar (or some other jar on the classpath). <p> Yyour class must be concrete (not abstract). <p> Finally, if your class lives in a separate JAR archive, make sure your archive classpath is not on the excluded list in the class ListClasses.");
availClassPanel.setPreferredSize(new java.awt.Dimension(400, 300));
filterLabel.setText("Filter");
availFilterTextField.setToolTipText("type any part of your filter name or description here to filter list");
availFilterTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
availFilterTextFieldActionPerformed(evt);
}
});
availFilterTextField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
availFilterTextFieldKeyTyped(evt);
}
});
clearFilterBut.setText("X");
clearFilterBut.setIconTextGap(0);
clearFilterBut.setMargin(new java.awt.Insets(2, 1, 1, 2));
clearFilterBut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearFilterButActionPerformed(evt);
}
});
javax.swing.GroupLayout filterPanelLayout = new javax.swing.GroupLayout(filterPanel);
filterPanel.setLayout(filterPanelLayout);
filterPanelLayout.setHorizontalGroup(
filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addGap(2, 2, 2)
.addGroup(filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addComponent(filterLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(availFilterTextField)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(clearFilterBut))
.addComponent(filterTypeOptionsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
filterPanelLayout.setVerticalGroup(
filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addGap(2, 2, 2)
.addGroup(filterPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(filterLabel)
.addComponent(availFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(clearFilterBut))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(filterTypeOptionsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(42, 42, 42))
);
availClassDesciptionPanel.setBorder(null);
availClassJList.setToolTipText("If your class doesn't show up here, rebuild the project to get it into jAER.jar (or some other jar on the classpath)");
availClassDesciptionPanel.setViewportView(availClassJList);
availClassJList.getAccessibleContext().setAccessibleDescription("");
javax.swing.GroupLayout availClassPanelLayout = new javax.swing.GroupLayout(availClassPanel);
availClassPanel.setLayout(availClassPanelLayout);
availClassPanelLayout.setHorizontalGroup(
availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(availClassPanelLayout.createSequentialGroup()
.addGap(2, 2, 2)
.addGroup(availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(availClassDesciptionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(availClassPanelLayout.createSequentialGroup()
.addComponent(filterPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(2, 2, 2))))
);
availClassPanelLayout.setVerticalGroup(
availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, availClassPanelLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(filterPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(availClassDesciptionPanel))
);
chosenClassPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Selected classes"));
chosenClassPanel.setToolTipText("These classes will be available to choose.");
chosenClassPanel.setPreferredSize(new java.awt.Dimension(400, 300));
jScrollPane3.setBorder(null);
classJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
classJList.setToolTipText("These classes will be available to choose.");
classJList.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
classJListMouseClicked(evt);
}
});
jScrollPane3.setViewportView(classJList);
classJList.getAccessibleContext().setAccessibleDescription("");
javax.swing.GroupLayout chosenClassPanelLayout = new javax.swing.GroupLayout(chosenClassPanel);
chosenClassPanel.setLayout(chosenClassPanelLayout);
chosenClassPanelLayout.setHorizontalGroup(
chosenClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
);
chosenClassPanelLayout.setVerticalGroup(
chosenClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, chosenClassPanelLayout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE))
);
addClassButton.setMnemonic('a');
addClassButton.setText(">");
addClassButton.setToolTipText("Add the filter to the list of available filters");
addClassButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
addClassButton.setMaximumSize(null);
addClassButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addClassButtonActionPerformed(evt);
}
});
removeClassButton.setMnemonic('r');
removeClassButton.setText("<");
removeClassButton.setToolTipText("Remove the filter from the list of selected filters");
removeClassButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
removeClassButton.setMaximumSize(null);
removeClassButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeClassButtonActionPerformed(evt);
}
});
removeAllButton.setText("<<");
removeAllButton.setToolTipText("Remove all filters from the list of selected filters");
removeAllButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
removeAllButton.setMaximumSize(null);
removeAllButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeAllButtonActionPerformed(evt);
}
});
descPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Class description"));
ClassDescSP.setBorder(null);
descPane.setEditable(false);
descPane.setBorder(null);
ClassDescSP.setViewportView(descPane);
devlStatusLbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
devlStatusLbl.setText("Development status:");
develStatusTF.setEditable(false);
develStatusTF.setBackground(new java.awt.Color(255, 255, 255));
develStatusTF.setToolTipText("Shows DevelopmentStatus of class as annotated with DevelopmentStatus");
develStatusTF.setBorder(null);
ClassNameLbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
ClassNameLbl.setText("Full class name:");
ClassNameTF.setEditable(false);
ClassNameTF.setBackground(new java.awt.Color(255, 255, 255));
ClassNameTF.setToolTipText("Shows the full classname of a class and hence its location in the jAER project");
ClassNameTF.setBorder(null);
javax.swing.GroupLayout descPanelLayout = new javax.swing.GroupLayout(descPanel);
descPanel.setLayout(descPanelLayout);
descPanelLayout.setHorizontalGroup(
descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, descPanelLayout.createSequentialGroup()
.addGap(2, 2, 2)
.addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(ClassDescSP)
.addGroup(descPanelLayout.createSequentialGroup()
.addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(ClassNameLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(devlStatusLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(4, 4, 4)
.addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ClassNameTF, javax.swing.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE)
.addComponent(develStatusTF, javax.swing.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE))))
.addGap(2, 2, 2))
);
descPanelLayout.setVerticalGroup(
descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(descPanelLayout.createSequentialGroup()
.addComponent(ClassDescSP, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(devlStatusLbl)
.addComponent(develStatusTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ClassNameLbl)
.addComponent(ClassNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10))
);
moveUpButton.setMnemonic('u');
moveUpButton.setText("Move up");
moveUpButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
moveUpButton.setMaximumSize(null);
moveUpButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
moveUpButtonActionPerformed(evt);
}
});
revertButton.setMnemonic('e');
revertButton.setText("Revert");
revertButton.setToolTipText("Revert changes to the list");
revertButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
revertButton.setMaximumSize(null);
revertButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
revertButtonActionPerformed(evt);
}
});
moveDownButton.setMnemonic('d');
moveDownButton.setText("Move down");
moveDownButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
moveDownButton.setMaximumSize(null);
moveDownButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
moveDownButtonActionPerformed(evt);
}
});
defaultsButton.setMnemonic('d');
defaultsButton.setText("Add Defaults");
defaultsButton.setToolTipText("Adds the defaults to the end of the selected classes list");
defaultsButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
defaultsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
defaultsButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(descPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(availClassPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 236, Short.MAX_VALUE)
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(defaultsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(removeClassButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(removeAllButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(moveUpButton, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(revertButton, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(moveDownButton, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(addClassButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10)
.addComponent(chosenClassPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE))))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {addClassButton, defaultsButton, moveDownButton, moveUpButton, removeAllButton, removeClassButton, revertButton});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(67, 67, 67)
.addComponent(addClassButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(removeClassButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(removeAllButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(moveUpButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(moveDownButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(revertButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(defaultsButton))
.addComponent(availClassPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
.addComponent(chosenClassPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(descPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void defaultsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_defaultsButtonActionPerformed
// chosenClassesListModel.clear();
int i=0;
for (String s : defaultClassNames) { // add them in reverse order because they were added to the list
chosenClassesListModel.insertElementAt(s, i++);
// chosenClassesListModel.addElement(s);
}
}//GEN-LAST:event_defaultsButtonActionPerformed
private void removeAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeAllButtonActionPerformed
chosenClassesListModel.clear();
}//GEN-LAST:event_removeAllButtonActionPerformed
private void revertButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_revertButtonActionPerformed
chosenClassesListModel.clear();
for (String s : revertCopy) {
chosenClassesListModel.addElement(s);
}
}//GEN-LAST:event_revertButtonActionPerformed
private void addClassButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addClassButtonActionPerformed
Object o = availClassJList.getSelectedValue();
if (o == null) {
return;
}
int last = chosenClassesListModel.getSize() - 1;
chosenClassesListModel.add(last + 1, o);
classJList.setSelectedIndex(last + 1);
}//GEN-LAST:event_addClassButtonActionPerformed
private void moveDownButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveDownButtonActionPerformed
int last = chosenClassesListModel.getSize() - 1;
int index = classJList.getSelectedIndex();
if (index == last) {
return;
}
Object o = chosenClassesListModel.getElementAt(index);
chosenClassesListModel.removeElementAt(index);
chosenClassesListModel.insertElementAt(o, index + 1);
classJList.setSelectedIndex(index + 1);
}//GEN-LAST:event_moveDownButtonActionPerformed
private void moveUpButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveUpButtonActionPerformed
int index = classJList.getSelectedIndex();
if (index == 0) {
return;
}
Object o = chosenClassesListModel.getElementAt(index);
chosenClassesListModel.removeElementAt(index);
chosenClassesListModel.insertElementAt(o, index - 1);
classJList.setSelectedIndex(index - 1);
}//GEN-LAST:event_moveUpButtonActionPerformed
private void removeClassButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeClassButtonActionPerformed
int index = classJList.getSelectedIndex();
chosenClassesListModel.removeElementAt(index);
int size = chosenClassesListModel.getSize();
if (size == 0) { //Nobody's left, disable firing.
removeClassButton.setEnabled(false);
} else { //Select an index.
if (index == chosenClassesListModel.getSize()) {
//removed item in last position
index--;
}
classJList.setSelectedIndex(index);
classJList.ensureIndexIsVisible(index);
}
}//GEN-LAST:event_removeClassButtonActionPerformed
private void classJListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_classJListMouseClicked
moveDownButton.setEnabled(true);
moveUpButton.setEnabled(true);
}//GEN-LAST:event_classJListMouseClicked
private void clearFilterButActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearFilterButActionPerformed
availFilterTextField.setText("");
availClassesListModel.clearFilter();
}//GEN-LAST:event_clearFilterButActionPerformed
private void availFilterTextFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_availFilterTextFieldKeyTyped
if (availClassesListModel == null) {
return;
}
String s = availFilterTextField.getText();
availClassesListModel.filter(s);
}//GEN-LAST:event_availFilterTextFieldKeyTyped
private void availFilterTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_availFilterTextFieldActionPerformed
if (availClassesListModel == null) {
return;
}
String s = availFilterTextField.getText();
availClassesListModel.filter(s);
}//GEN-LAST:event_availFilterTextFieldActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane ClassDescSP;
private javax.swing.JLabel ClassNameLbl;
private javax.swing.JTextField ClassNameTF;
private javax.swing.JButton addClassButton;
private javax.swing.JScrollPane availClassDesciptionPanel;
private javax.swing.JList availClassJList;
private javax.swing.JPanel availClassPanel;
private javax.swing.JTextField availFilterTextField;
private javax.swing.JPanel chosenClassPanel;
private javax.swing.JList classJList;
private javax.swing.JButton clearFilterBut;
private javax.swing.JButton defaultsButton;
private javax.swing.JTextPane descPane;
private javax.swing.JPanel descPanel;
private javax.swing.JTextField develStatusTF;
private javax.swing.JLabel devlStatusLbl;
private javax.swing.JLabel filterLabel;
private javax.swing.JPanel filterPanel;
private javax.swing.JPanel filterTypeOptionsPanel;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JButton moveDownButton;
private javax.swing.JButton moveUpButton;
private javax.swing.JButton removeAllButton;
private javax.swing.JButton removeClassButton;
private javax.swing.JButton revertButton;
// End of variables declaration//GEN-END:variables
// from http://forum.java.sun.com/thread.jspa?forumID=57&threadID=626866
private static final KeyStroke ENTER = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
public static void addAction(JList source, Action action) {
// Handle enter key
InputMap im = source.getInputMap();
im.put(ENTER, ENTER);
source.getActionMap().put(ENTER, action);
// Handle mouse double click
source.addMouseListener(new ActionMouseListener());
}
// Implement Mouse Listener
static class ActionMouseListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
JList list = (JList) e.getSource();
Action action = list.getActionMap().get(ENTER);
if (action != null) {
ActionEvent event = new ActionEvent(
list,
ActionEvent.ACTION_PERFORMED,
"");
action.actionPerformed(event);
}
}
}
}
}
| added inner class (so far unused) to hold classname, description and development status together for enchancing the class chooser dialog filtering capabilities.
git-svn-id: fe6b3b33f0410f5f719dcd9e0c58b92353e7a5d3@6454 b7f4320f-462c-0410-a916-d9f35bb82d52
| src/net/sf/jaer/util/ClassChooserPanel.java | added inner class (so far unused) to hold classname, description and development status together for enchancing the class chooser dialog filtering capabilities. |
|
Java | lgpl-2.1 | 08851c4f0976a0e2481f0b354a3f4be3727a1cb5 | 0 | 4ment/beast-mcmc,maxbiostat/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,4ment/beast-mcmc,codeaudit/beast-mcmc,maxbiostat/beast-mcmc,4ment/beast-mcmc,maxbiostat/beast-mcmc,codeaudit/beast-mcmc,codeaudit/beast-mcmc,4ment/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,beast-dev/beast-mcmc,4ment/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,adamallo/beast-mcmc,codeaudit/beast-mcmc,maxbiostat/beast-mcmc,maxbiostat/beast-mcmc,4ment/beast-mcmc,codeaudit/beast-mcmc,codeaudit/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,maxbiostat/beast-mcmc | package dr.inference.trace;
import dr.evolution.io.Importer;
import dr.evolution.io.NexusImporter;
import dr.evolution.io.TreeImporter;
import dr.evolution.tree.Tree;
import dr.evomodel.coalescent.VDdemographicFunction;
import dr.evomodel.coalescent.VariableDemographicModel;
import dr.evomodelxml.LoggerParser;
import dr.stats.DiscreteStatistics;
import dr.util.HeapSort;
import dr.util.TabularData;
import dr.xml.*;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
/**
* @author Joseph Heled
*/
public class EBSPAnalysis extends TabularData {
private double[] xPoints;
private double[] means;
private double[] medians;
private double[][] hpdLower;
private double[][] hpdHigh;
private double[] HPDLevels;
// each bin covers xPoints[-1]/coalBins.length
private int[] coalBins;
private boolean quantiles;
EBSPAnalysis(File log, File[] treeFiles, VariableDemographicModel.Type modelType,
String firstColumnName, String firstIndicatorColumnName,
String rootHeightColumnName, int coalPointBins, double burnIn,
double[] inHPDLevels, boolean quantiles, boolean logSpace, boolean mid,
int restrictToNchanges)
throws IOException, Importer.ImportException, TraceException {
LogFileTraces ltraces = new LogFileTraces(log.getCanonicalPath(), log);
ltraces.loadTraces();
ltraces.setBurnIn(0);
final int runLengthIncludingBurnin = ltraces.getStateCount();
int intBurnIn = (int) Math.floor(burnIn < 1 ? runLengthIncludingBurnin * burnIn : burnIn);
final int nStates = runLengthIncludingBurnin - intBurnIn;
//intBurnIn *= ltraces.getStepSize();
ltraces.setBurnIn(intBurnIn * ltraces.getStepSize());
assert ltraces.getStateCount() == nStates;
this.quantiles = quantiles;
HPDLevels = (inHPDLevels != null) ? inHPDLevels : new double[]{0.95};
int populationFirstColumn = -1;
int indicatorsFirstColumn = -1;
int rootHeightColumn = -1;
for (int n = 0; n < ltraces.getTraceCount(); ++n) {
final String traceName = ltraces.getTraceName(n);
if (traceName.equals(firstColumnName)) {
populationFirstColumn = n;
} else if (traceName.equals(firstIndicatorColumnName)) {
indicatorsFirstColumn = n;
} else if (rootHeightColumnName != null && traceName.equals(rootHeightColumnName)) {
rootHeightColumn = n;
}
}
if (populationFirstColumn < 0 || indicatorsFirstColumn < 0) {
throw new TraceException("incorrect trace column names: unable to find populations/indicators");
}
double binSize = 0;
if (coalPointBins > 0) {
if (rootHeightColumn < 0) {
throw new TraceException("incorrect tree height column");
}
double hSum = -0;
double[] h = new double[1];
for (int ns = 0; ns < nStates; ++ns) {
ltraces.getStateValues(ns, h, rootHeightColumn);
hSum += h[0];
}
binSize = hSum / (nStates * coalPointBins);
coalBins = new int[coalPointBins];
Arrays.fill(coalBins, 0);
}
TreeImporter[] treeImporters = new TreeImporter[treeFiles.length];
final boolean isStepWise = modelType == VariableDemographicModel.Type.STEPWISE;
int nIndicators = 0;
for (int k = 0; k < treeFiles.length; ++k) {
// System.err.println("burnin " + treeFiles[k] + "(" + k + ")");
treeImporters[k] = new NexusImporter(new FileReader(treeFiles[k]));
assert intBurnIn > 0;
for (int z = 0; z < intBurnIn - 1; ++z) {
treeImporters[k].importNextTree();
}
nIndicators += treeImporters[k].importNextTree().getExternalNodeCount() - 1;
}
if (isStepWise) {
nIndicators -= 1;
}
final int nXaxisPoints = nIndicators + (isStepWise ? 1 : 0) + 1;
xPoints = new double[nXaxisPoints];
Arrays.fill(xPoints, 0.0);
int nDataPoints = 0;
VDdemographicFunction[] allDemog = new VDdemographicFunction[nStates];
{
double[] indicators = new double[nIndicators];
double[] pop = new double[nIndicators + 1];
Tree[] tt = new Tree[treeFiles.length];
boolean match = true;
for (int ns = 0; ns < nStates; ++ns) {
ltraces.getStateValues(ns, indicators, indicatorsFirstColumn);
ltraces.getStateValues(ns, pop, populationFirstColumn);
if(match){
for (int nt = 0; nt < tt.length; ++nt) {
tt[nt] = treeImporters[nt].importNextTree();
}
}
//Get tree state number
String name1 = tt[0].getId();
int state1 = Integer.parseInt(name1.substring(name1.indexOf('_')+1, name1.length()));
int state2 = state1;
if (tt.length > 1) {
String name2 = tt[1].getId();
state2 = Integer.parseInt(name1.substring(name2.indexOf('_')+1, name2.length()));
}
if (state1 != state2){ //... can this happen at all?
throw new TraceException("NEXUS tree files have different rates or corrupted!!!!"); //Not too sure what kind of message is appropriate here.
}else if((ns+intBurnIn)*ltraces.getStepSize() == state1){ //Check if log state matches tree state
match = true;
final VDdemographicFunction demoFunction =
new VDdemographicFunction(tt, modelType, indicators, pop, logSpace, mid);
if (demoFunction.numberOfChanges() == restrictToNchanges) {
continue;
}
double[] xs = demoFunction.allTimePoints();
for (int k = 0; k < xs.length; ++k) {
xPoints[k + 1] += xs[k];
}
if (coalPointBins > 0) {
for (double x : xs) {
coalBins[Math.min((int) (x / binSize), coalBins.length - 1)]++;
}
}
allDemog[nDataPoints] = demoFunction;
++nDataPoints;
demoFunction.freeze();
}else{
match = false;
}
}
for (int k = 0; k < xPoints.length; ++k) {
xPoints[k] /= nStates;
}
if(nStates != nDataPoints){ //Warning if log file ant tree files
// have different rates
System.err.println("Different Rates is \"main\" and \"tree\" log files");
}
if(nDataPoints < 10){ //Warning if number of states is not sufficient
// enough to do the analysis
System.err.println("Warning!!! Not Sufficient number of data points");
}
}
double[] popValues = new double[nDataPoints];
means = new double[nXaxisPoints];
medians = new double[nXaxisPoints];
hpdLower = new double[HPDLevels.length][];
hpdHigh = new double[HPDLevels.length][];
for (int i = 0; i < HPDLevels.length; ++i) {
hpdLower[i] = new double[nXaxisPoints];
hpdHigh[i] = new double[nXaxisPoints];
}
for (int nx = 0; nx < xPoints.length; ++nx) {
final double x = xPoints[nx];
for (int ns = 0; ns < nDataPoints; ++ns) {
popValues[ns] = allDemog[ns].getDemographic(x);
}
int[] indices = new int[popValues.length];
HeapSort.sort(popValues, indices);
means[nx] = DiscreteStatistics.mean(popValues);
for (int i = 0; i < HPDLevels.length; ++i) {
if (quantiles) {
hpdLower[i][nx] = DiscreteStatistics.quantile((1 - HPDLevels[i]) / 2, popValues, indices);
hpdHigh[i][nx] = DiscreteStatistics.quantile((1 + HPDLevels[i]) / 2, popValues, indices);
} else {
final double[] hpd = DiscreteStatistics.HPDInterval(HPDLevels[i], popValues, indices);
hpdLower[i][nx] = hpd[0];
hpdHigh[i][nx] = hpd[1];
}
}
medians[nx] = DiscreteStatistics.median(popValues, indices);
}
}
private final String[] columnNames = {"time", "mean", "median"};
public int nColumns() {
return columnNames.length + 2 * HPDLevels.length + (coalBins != null ? 1 : 0);
}
public String columnName(int nColumn) {
final int fixed = columnNames.length;
if (nColumn < fixed) {
return columnNames[nColumn];
}
nColumn -= fixed;
if (nColumn < 2 * HPDLevels.length) {
final double p = HPDLevels[nColumn / 2];
final String s = (nColumn % 2 == 0) ? "lower" : "upper";
return (quantiles ? "cpd " : "hpd ") + s + " " + Math.round(p * 100);
}
assert (nColumn - 2 * HPDLevels.length) == 0;
return "bins";
}
public int nRows() {
return Math.max(xPoints.length, (coalBins != null ? coalBins.length : 0));
}
public Object data(int nRow, int nColumn) {
switch (nColumn) {
case 0: {
if (nRow < xPoints.length) {
return xPoints[nRow];
}
break;
}
case 1: {
if (nRow < means.length) {
return means[nRow];
}
break;
}
case 2: {
if (nRow < medians.length) {
return medians[nRow];
}
break;
}
default: {
final int j = nColumn - columnNames.length;
if (j < 2 * HPDLevels.length) {
if (nRow < xPoints.length) {
final int k = j / 2;
if (0 <= k && k < HPDLevels.length) {
if (j % 2 == 0) {
return hpdLower[k][nRow];
} else {
return hpdHigh[k][nRow];
}
}
}
} else {
if (nRow < coalBins.length) {
return coalBins[nRow];
}
}
break;
}
}
return "";
}
// should be local to PARSER, but this makes them non-accesible from the outside in Java.
public static final String VD_ANALYSIS = "VDAnalysis";
public static final String FILE_NAME = "fileName";
public static final String BURN_IN = "burnIn";
public static final String HPD_LEVELS = "Confidencelevels";
public static final String QUANTILES = "useQuantiles";
public static final String LOG_SPACE = VariableDemographicModel.LOG_SPACE;
public static final String USE_MIDDLE = VariableDemographicModel.USE_MIDPOINTS;
public static final String N_CHANGES = "nChanges";
public static final String TREE_LOG = "treeOfLoci";
public static final String LOG_FILE_NAME = "logFileName";
public static final String TREE_FILE_NAMES = "treeFileNames";
public static final String MODEL_TYPE = "populationModelType";
public static final String POPULATION_FIRST_COLUMN = "populationFirstColumn";
public static final String INDICATORS_FIRST_COLUMN = "indicatorsFirstColumn";
public static final String ROOTHEIGHT_COLUMN = "rootheightColumn";
public static final String NBINS = "nBins";
public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() {
private String getElementText(XMLObject xo, String childName) throws XMLParseException {
return ((XMLObject) xo.getChild(childName)).getStringChild(0);
}
public String getParserName() {
return VD_ANALYSIS;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
try {
// 10% is brun-in default
double burnin = xo.getAttribute(BURN_IN, 0.1);
if (burnin < 0)
throw new XMLParseException("burnIn should be either between 0 and 1 or a positive number");
final double[] hpdLevels = xo.hasAttribute(HPD_LEVELS) ? xo.getDoubleArrayAttribute(HPD_LEVELS) : null;
final File log = LoggerParser.getFile(getElementText(xo, LOG_FILE_NAME));
final XMLObject treeFileNames = (XMLObject) xo.getChild(TREE_FILE_NAMES);
final int nTrees = treeFileNames.getChildCount();
File[] treeFiles = new File[nTrees];
for (int k = 0; k < nTrees; ++k) {
treeFiles[k] = LoggerParser.getFile(((XMLObject) treeFileNames.getChild(k)).getStringChild(0));
}
String modelTypeName = getElementText(xo, MODEL_TYPE).trim().toUpperCase();
String populationFirstColumn = getElementText(xo, POPULATION_FIRST_COLUMN);
String indicatorsFirstColumn = getElementText(xo, INDICATORS_FIRST_COLUMN);
VariableDemographicModel.Type modelType = VariableDemographicModel.Type.valueOf(modelTypeName);
String rootHeightColumn = null;
int nBins = -1;
if (xo.hasAttribute(NBINS)) {
if (xo.getChild(ROOTHEIGHT_COLUMN) != null) {
rootHeightColumn = getElementText(xo, ROOTHEIGHT_COLUMN);
nBins = xo.getIntegerAttribute(NBINS);
}
}
final boolean quantiles = xo.getAttribute(QUANTILES, false);
final boolean logSpace = xo.getAttribute(LOG_SPACE, false);
final boolean useMid = xo.getAttribute(USE_MIDDLE, false);
final int onlyNchanges = xo.getAttribute(N_CHANGES, -1);
return new EBSPAnalysis(log, treeFiles, modelType,
populationFirstColumn, indicatorsFirstColumn,
rootHeightColumn, nBins,
burnin, hpdLevels, quantiles, logSpace, useMid, onlyNchanges);
} catch (java.io.IOException ioe) {
throw new XMLParseException(ioe.getMessage());
} catch (Importer.ImportException e) {
throw new XMLParseException(e.toString());
} catch (TraceException e) {
throw new XMLParseException(e.toString());
}
}
//************************************************************************
// AbstractXMLObjectParser implementation
//************************************************************************
public String getParserDescription() {
return "reconstruct population graph from EBSP run.";
}
public Class getReturnType() {
return EBSPAnalysis.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
AttributeRule.newDoubleRule(BURN_IN, true, "The number of states (not sampled states, but" +
" actual states) that are discarded from the beginning of the trace and are excluded from " +
"the analysis"),
AttributeRule.newDoubleArrayRule(HPD_LEVELS, true),
AttributeRule.newBooleanRule(QUANTILES, true),
AttributeRule.newBooleanRule(LOG_SPACE, true),
AttributeRule.newBooleanRule(USE_MIDDLE, true),
AttributeRule.newIntegerRule(NBINS, true),
AttributeRule.newIntegerRule(N_CHANGES, true),
new ElementRule(LOG_FILE_NAME, String.class, "The name of a BEAST log file"),
new ElementRule(TREE_FILE_NAMES,
new XMLSyntaxRule[]{
new ElementRule(TREE_LOG, String.class, "The name of a BEAST trees log file", 1, Integer.MAX_VALUE)
}),
new ElementRule(MODEL_TYPE, String.class, "population model type (stepwise, linear ..."),
new ElementRule(POPULATION_FIRST_COLUMN, String.class, "Name of first column of population size"),
new ElementRule(INDICATORS_FIRST_COLUMN, String.class, "Name of first column of population indicators"),
new ElementRule(ROOTHEIGHT_COLUMN, String.class, "Name of trace column of root height", true),
};
};
}
| src/dr/inference/trace/EBSPAnalysis.java | package dr.inference.trace;
import dr.evolution.io.Importer;
import dr.evolution.io.NexusImporter;
import dr.evolution.io.TreeImporter;
import dr.evolution.tree.Tree;
import dr.evomodel.coalescent.VDdemographicFunction;
import dr.evomodel.coalescent.VariableDemographicModel;
import dr.evomodelxml.LoggerParser;
import dr.stats.DiscreteStatistics;
import dr.util.HeapSort;
import dr.util.TabularData;
import dr.xml.*;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
/**
* @author Joseph Heled
*/
public class EBSPAnalysis extends TabularData {
private double[] xPoints;
private double[] means;
private double[] medians;
private double[][] hpdLower;
private double[][] hpdHigh;
private double[] HPDLevels;
// each bin covers xPoints[-1]/coalBins.length
private int[] coalBins;
private boolean quantiles;
EBSPAnalysis(File log, File[] treeFiles, VariableDemographicModel.Type modelType,
String firstColumnName, String firstIndicatorColumnName,
String rootHeightColumnName, int coalPointBins, double burnIn,
double[] inHPDLevels, boolean quantiles, boolean logSpace, boolean mid,
int restrictToNchanges)
throws IOException, Importer.ImportException, TraceException {
LogFileTraces ltraces = new LogFileTraces(log.getCanonicalPath(), log);
ltraces.loadTraces();
ltraces.setBurnIn(0);
final int runLengthIncludingBurnin = ltraces.getStateCount();
int intBurnIn = (int) Math.floor(burnIn < 1 ? runLengthIncludingBurnin * burnIn : burnIn);
final int nStates = runLengthIncludingBurnin - intBurnIn;
//intBurnIn *= ltraces.getStepSize();
ltraces.setBurnIn(intBurnIn * ltraces.getStepSize());
assert ltraces.getStateCount() == nStates;
this.quantiles = quantiles;
HPDLevels = (inHPDLevels != null) ? inHPDLevels : new double[]{0.95};
int populationFirstColumn = -1;
int indicatorsFirstColumn = -1;
int rootHeightColumn = -1;
for (int n = 0; n < ltraces.getTraceCount(); ++n) {
final String traceName = ltraces.getTraceName(n);
if (traceName.equals(firstColumnName)) {
populationFirstColumn = n;
} else if (traceName.equals(firstIndicatorColumnName)) {
indicatorsFirstColumn = n;
} else if (rootHeightColumnName != null && traceName.equals(rootHeightColumnName)) {
rootHeightColumn = n;
}
}
if (populationFirstColumn < 0 || indicatorsFirstColumn < 0) {
throw new TraceException("incorrect trace column names: unable to find populations/indicators");
}
double binSize = 0;
if (coalPointBins > 0) {
if (rootHeightColumn < 0) {
throw new TraceException("incorrect tree height column");
}
double hSum = -0;
double[] h = new double[1];
for (int ns = 0; ns < nStates; ++ns) {
ltraces.getStateValues(ns, h, rootHeightColumn);
hSum += h[0];
}
binSize = hSum / (nStates * coalPointBins);
coalBins = new int[coalPointBins];
Arrays.fill(coalBins, 0);
}
TreeImporter[] treeImporters = new TreeImporter[treeFiles.length];
final boolean isStepWise = modelType == VariableDemographicModel.Type.STEPWISE;
int nIndicators = 0;
for (int k = 0; k < treeFiles.length; ++k) {
// System.err.println("burnin " + treeFiles[k] + "(" + k + ")");
treeImporters[k] = new NexusImporter(new FileReader(treeFiles[k]));
assert intBurnIn > 0;
for (int z = 0; z < intBurnIn - 1; ++z) {
treeImporters[k].importNextTree();
}
nIndicators += treeImporters[k].importNextTree().getExternalNodeCount() - 1;
}
if (isStepWise) {
nIndicators -= 1;
}
final int nXaxisPoints = nIndicators + (isStepWise ? 1 : 0) + 1;
xPoints = new double[nXaxisPoints];
Arrays.fill(xPoints, 0.0);
int nDataPoints = 0;
VDdemographicFunction[] allDemog = new VDdemographicFunction[nStates];
{
double[] indicators = new double[nIndicators];
double[] pop = new double[nIndicators + 1];
Tree[] tt = new Tree[treeFiles.length];
boolean match = true;
for (int ns = 0; ns < nStates; ++ns) {
ltraces.getStateValues(ns, indicators, indicatorsFirstColumn);
ltraces.getStateValues(ns, pop, populationFirstColumn);
if(match){
for (int nt = 0; nt < tt.length; ++nt) {
tt[nt] = treeImporters[nt].importNextTree();
}
}
//Get tree state number
String name1 = tt[0].getId();
int state1 = Integer.parseInt(name1.substring(name1.indexOf('_')+1, name1.length()));
String name2 = tt[1].getId();
int state2 = Integer.parseInt(name1.substring(name2.indexOf('_')+1, name2.length()));
if (state1 != state2){ //... can this happen at all?
throw new TraceException("NEXUS tree files have different rates or corrupted!!!!"); //Not too sure what kind of message is appropriate here.
}else if((ns+intBurnIn)*ltraces.getStepSize() == state1){ //Check if log state matches tree state
match = true;
final VDdemographicFunction demoFunction =
new VDdemographicFunction(tt, modelType, indicators, pop, logSpace, mid);
if (demoFunction.numberOfChanges() == restrictToNchanges) {
continue;
}
double[] xs = demoFunction.allTimePoints();
for (int k = 0; k < xs.length; ++k) {
xPoints[k + 1] += xs[k];
}
if (coalPointBins > 0) {
for (double x : xs) {
coalBins[Math.min((int) (x / binSize), coalBins.length - 1)]++;
}
}
allDemog[nDataPoints] = demoFunction;
++nDataPoints;
demoFunction.freeze();
}else{
match = false;
}
}
for (int k = 0; k < xPoints.length; ++k) {
xPoints[k] /= nStates;
}
if(nStates != nDataPoints){ //Warning if log file ant tree files
// have different rates
System.err.println("Different Rates is \"main\" and \"tree\" log files");
}
if(nDataPoints < 10){ //Warning if number of states is not sufficient
// enough to do the analysis
System.err.println("Warning!!! Not Sufficient number of data points");
}
}
double[] popValues = new double[nDataPoints];
means = new double[nXaxisPoints];
medians = new double[nXaxisPoints];
hpdLower = new double[HPDLevels.length][];
hpdHigh = new double[HPDLevels.length][];
for (int i = 0; i < HPDLevels.length; ++i) {
hpdLower[i] = new double[nXaxisPoints];
hpdHigh[i] = new double[nXaxisPoints];
}
for (int nx = 0; nx < xPoints.length; ++nx) {
final double x = xPoints[nx];
for (int ns = 0; ns < nDataPoints; ++ns) {
popValues[ns] = allDemog[ns].getDemographic(x);
}
int[] indices = new int[popValues.length];
HeapSort.sort(popValues, indices);
means[nx] = DiscreteStatistics.mean(popValues);
for (int i = 0; i < HPDLevels.length; ++i) {
if (quantiles) {
hpdLower[i][nx] = DiscreteStatistics.quantile((1 - HPDLevels[i]) / 2, popValues, indices);
hpdHigh[i][nx] = DiscreteStatistics.quantile((1 + HPDLevels[i]) / 2, popValues, indices);
} else {
final double[] hpd = DiscreteStatistics.HPDInterval(HPDLevels[i], popValues, indices);
hpdLower[i][nx] = hpd[0];
hpdHigh[i][nx] = hpd[1];
}
}
medians[nx] = DiscreteStatistics.median(popValues, indices);
}
}
private final String[] columnNames = {"time", "mean", "median"};
public int nColumns() {
return columnNames.length + 2 * HPDLevels.length + (coalBins != null ? 1 : 0);
}
public String columnName(int nColumn) {
final int fixed = columnNames.length;
if (nColumn < fixed) {
return columnNames[nColumn];
}
nColumn -= fixed;
if (nColumn < 2 * HPDLevels.length) {
final double p = HPDLevels[nColumn / 2];
final String s = (nColumn % 2 == 0) ? "lower" : "upper";
return (quantiles ? "cpd " : "hpd ") + s + " " + Math.round(p * 100);
}
assert (nColumn - 2 * HPDLevels.length) == 0;
return "bins";
}
public int nRows() {
return Math.max(xPoints.length, (coalBins != null ? coalBins.length : 0));
}
public Object data(int nRow, int nColumn) {
switch (nColumn) {
case 0: {
if (nRow < xPoints.length) {
return xPoints[nRow];
}
break;
}
case 1: {
if (nRow < means.length) {
return means[nRow];
}
break;
}
case 2: {
if (nRow < medians.length) {
return medians[nRow];
}
break;
}
default: {
final int j = nColumn - columnNames.length;
if (j < 2 * HPDLevels.length) {
if (nRow < xPoints.length) {
final int k = j / 2;
if (0 <= k && k < HPDLevels.length) {
if (j % 2 == 0) {
return hpdLower[k][nRow];
} else {
return hpdHigh[k][nRow];
}
}
}
} else {
if (nRow < coalBins.length) {
return coalBins[nRow];
}
}
break;
}
}
return "";
}
// should be local to PARSER, but this makes them non-accesible from the outside in Java.
public static final String VD_ANALYSIS = "VDAnalysis";
public static final String FILE_NAME = "fileName";
public static final String BURN_IN = "burnIn";
public static final String HPD_LEVELS = "Confidencelevels";
public static final String QUANTILES = "useQuantiles";
public static final String LOG_SPACE = VariableDemographicModel.LOG_SPACE;
public static final String USE_MIDDLE = VariableDemographicModel.USE_MIDPOINTS;
public static final String N_CHANGES = "nChanges";
public static final String TREE_LOG = "treeOfLoci";
public static final String LOG_FILE_NAME = "logFileName";
public static final String TREE_FILE_NAMES = "treeFileNames";
public static final String MODEL_TYPE = "populationModelType";
public static final String POPULATION_FIRST_COLUMN = "populationFirstColumn";
public static final String INDICATORS_FIRST_COLUMN = "indicatorsFirstColumn";
public static final String ROOTHEIGHT_COLUMN = "rootheightColumn";
public static final String NBINS = "nBins";
public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() {
private String getElementText(XMLObject xo, String childName) throws XMLParseException {
return ((XMLObject) xo.getChild(childName)).getStringChild(0);
}
public String getParserName() {
return VD_ANALYSIS;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
try {
// 10% is brun-in default
double burnin = xo.getAttribute(BURN_IN, 0.1);
if (burnin < 0)
throw new XMLParseException("burnIn should be either between 0 and 1 or a positive number");
final double[] hpdLevels = xo.hasAttribute(HPD_LEVELS) ? xo.getDoubleArrayAttribute(HPD_LEVELS) : null;
final File log = LoggerParser.getFile(getElementText(xo, LOG_FILE_NAME));
final XMLObject treeFileNames = (XMLObject) xo.getChild(TREE_FILE_NAMES);
final int nTrees = treeFileNames.getChildCount();
File[] treeFiles = new File[nTrees];
for (int k = 0; k < nTrees; ++k) {
treeFiles[k] = LoggerParser.getFile(((XMLObject) treeFileNames.getChild(k)).getStringChild(0));
}
String modelTypeName = getElementText(xo, MODEL_TYPE).trim().toUpperCase();
String populationFirstColumn = getElementText(xo, POPULATION_FIRST_COLUMN);
String indicatorsFirstColumn = getElementText(xo, INDICATORS_FIRST_COLUMN);
VariableDemographicModel.Type modelType = VariableDemographicModel.Type.valueOf(modelTypeName);
String rootHeightColumn = null;
int nBins = -1;
if (xo.hasAttribute(NBINS)) {
if (xo.getChild(ROOTHEIGHT_COLUMN) != null) {
rootHeightColumn = getElementText(xo, ROOTHEIGHT_COLUMN);
nBins = xo.getIntegerAttribute(NBINS);
}
}
final boolean quantiles = xo.getAttribute(QUANTILES, false);
final boolean logSpace = xo.getAttribute(LOG_SPACE, false);
final boolean useMid = xo.getAttribute(USE_MIDDLE, false);
final int onlyNchanges = xo.getAttribute(N_CHANGES, -1);
return new EBSPAnalysis(log, treeFiles, modelType,
populationFirstColumn, indicatorsFirstColumn,
rootHeightColumn, nBins,
burnin, hpdLevels, quantiles, logSpace, useMid, onlyNchanges);
} catch (java.io.IOException ioe) {
throw new XMLParseException(ioe.getMessage());
} catch (Importer.ImportException e) {
throw new XMLParseException(e.toString());
} catch (TraceException e) {
throw new XMLParseException(e.toString());
}
}
//************************************************************************
// AbstractXMLObjectParser implementation
//************************************************************************
public String getParserDescription() {
return "reconstruct population graph from EBSP run.";
}
public Class getReturnType() {
return EBSPAnalysis.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
AttributeRule.newDoubleRule(BURN_IN, true, "The number of states (not sampled states, but" +
" actual states) that are discarded from the beginning of the trace and are excluded from " +
"the analysis"),
AttributeRule.newDoubleArrayRule(HPD_LEVELS, true),
AttributeRule.newBooleanRule(QUANTILES, true),
AttributeRule.newBooleanRule(LOG_SPACE, true),
AttributeRule.newBooleanRule(USE_MIDDLE, true),
AttributeRule.newIntegerRule(NBINS, true),
AttributeRule.newIntegerRule(N_CHANGES, true),
new ElementRule(LOG_FILE_NAME, String.class, "The name of a BEAST log file"),
new ElementRule(TREE_FILE_NAMES,
new XMLSyntaxRule[]{
new ElementRule(TREE_LOG, String.class, "The name of a BEAST trees log file", 1, Integer.MAX_VALUE)
}),
new ElementRule(MODEL_TYPE, String.class, "population model type (stepwise, linear ..."),
new ElementRule(POPULATION_FIRST_COLUMN, String.class, "Name of first column of population size"),
new ElementRule(INDICATORS_FIRST_COLUMN, String.class, "Name of first column of population indicators"),
new ElementRule(ROOTHEIGHT_COLUMN, String.class, "Name of trace column of root height", true),
};
};
}
| Fixed issue in EBSPAnalysis where it assumed at least 2 tree files even if single-locus analysis. | src/dr/inference/trace/EBSPAnalysis.java | Fixed issue in EBSPAnalysis where it assumed at least 2 tree files even if single-locus analysis. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.