answer
stringlengths
17
10.2M
package info.justaway; import android.app.Activity; import android.app.Application; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Typeface; import android.os.AsyncTask; import android.os.StrictMode; import android.support.v4.util.LongSparseArray; import android.util.TypedValue; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import java.util.ArrayList; import java.util.HashMap; import de.greenrobot.event.EventBus; import info.justaway.adapter.MyUserStreamAdapter; import info.justaway.display.FadeInRoundedBitmapDisplayer; import info.justaway.event.AccountChangePostEvent; import info.justaway.event.AccountChangePreEvent; import info.justaway.event.connection.CleanupEvent; import info.justaway.event.action.EditorEvent; import info.justaway.event.connection.ConnectEvent; import info.justaway.event.connection.DisconnectEvent; import info.justaway.listener.MyConnectionLifeCycleListener; import info.justaway.model.Row; import info.justaway.settings.MuteSettings; import info.justaway.task.FavoriteTask; import info.justaway.task.RetweetTask; import info.justaway.task.UnFavoriteTask; import info.justaway.task.UnRetweetTask; import twitter4j.DirectMessage; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.TwitterStream; import twitter4j.TwitterStreamFactory; import twitter4j.User; import twitter4j.UserList; import twitter4j.UserMentionEntity; import twitter4j.auth.AccessToken; import twitter4j.conf.ConfigurationBuilder; /** * * * @author aska */ public class JustawayApplication extends Application { private static JustawayApplication sApplication; private static ImageLoader sImageLoader; private static DisplayImageOptions sRoundedDisplayImageOptions; private static MuteSettings sMuteSettings; private static Typeface sFontello; private ResponseList<UserList> mUserLists; private static ProgressDialog mProgressDialog; public ResponseList<UserList> getUserLists() { return mUserLists; } public void setUserLists(ResponseList<UserList> userLists) { mUserLists = userLists; } public UserList getUserList(long id) { if (mUserLists == null) { return null; } for (UserList userList : mUserLists) { if (userList.getId() == id) { return userList; } } return null; } public static JustawayApplication getApplication() { return sApplication; } public static Typeface getFontello() { return sFontello; } @Override public void onCreate() { super.onCreate(); sApplication = this; // Twitter4J user stream shutdown() NetworkOnMainThreadException if (!BuildConfig.DEBUG) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build()); } DisplayImageOptions defaultOptions = new DisplayImageOptions .Builder() .cacheInMemory(true) .cacheOnDisc(true) .resetViewBeforeLoading(true) .build(); ImageLoaderConfiguration config = new ImageLoaderConfiguration .Builder(this) .defaultDisplayImageOptions(defaultOptions) .build(); ImageLoader.getInstance().init(config); sImageLoader = ImageLoader.getInstance(); sRoundedDisplayImageOptions = new DisplayImageOptions.Builder() .cacheInMemory(true) .cacheOnDisc(true) .resetViewBeforeLoading(true) .displayer(new FadeInRoundedBitmapDisplayer(5)) .build(); sFontello = Typeface.createFromAsset(getAssets(), "fontello.ttf"); if (BuildConfig.DEBUG) { Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler(sApplication)); } resetDisplaySettings(); getAccessToken(); sMuteSettings = new MuteSettings(); warmUpUserIconMap(); } public void displayImage(String url, ImageView view) { String tag = (String) view.getTag(); if (tag != null && tag.equals(url)) { return; } view.setTag(url); sImageLoader.displayImage(url, view); } public void displayRoundedImage(String url, ImageView view) { String tag = (String) view.getTag(); if (tag != null && tag.equals(url)) { return; } view.setTag(url); if (getUserIconRoundedOn()) { sImageLoader.displayImage(url, view, sRoundedDisplayImageOptions); } else { sImageLoader.displayImage(url, view); } } public MuteSettings getMuteSettings() { return sMuteSettings; } public static Boolean isMute(Row row) { if (row.isStatus()) { return sMuteSettings.isMute(row.getStatus()); } else { return false; } } /** * userIdDiskCache */ private HashMap<String, String> mUserIconMap = new HashMap<String, String>(); public void displayUserIcon(User user, final ImageView view) { String url; if (getUserIconSize().equals("bigger")) { url = user.getBiggerProfileImageURL(); } else if (getUserIconSize().equals("normal")) { url = user.getProfileImageURL(); } else if (getUserIconSize().equals("mini")) { url = user.getMiniProfileImageURL(); } else { view.setVisibility(View.GONE); return; } if (getUserIconRoundedOn()) { displayRoundedImage(url, view); } else { displayImage(url, view); } } /** * userId */ public void displayUserIcon(final long userId, final ImageView view) { String url = mUserIconMap.get(String.valueOf(userId)); if (url != null) { displayRoundedImage(url, view); return; } // URL view.setImageDrawable(null); } private static final String PREF_NAME_USER_ICON_MAP = "user_icon_map"; private static final String PREF_KEY_USER_ICON_MAP = "data/v2"; @SuppressWarnings("unchecked") public void warmUpUserIconMap() { ArrayList<AccessToken> accessTokens = getAccessTokens(); if (accessTokens == null || accessTokens.size() == 0) { return; } final SharedPreferences preferences = getSharedPreferences(PREF_NAME_USER_ICON_MAP, Context.MODE_PRIVATE); final Gson gson = new Gson(); String json = preferences.getString(PREF_KEY_USER_ICON_MAP, null); if (json != null) { mUserIconMap = gson.fromJson(json, mUserIconMap.getClass()); } final long userIds[] = new long[accessTokens.size()]; int i = 0; for (AccessToken accessToken : accessTokens) { userIds[i] = accessToken.getUserId(); i++; } new AsyncTask<Void, Void, ResponseList<User>>() { @Override protected ResponseList<User> doInBackground(Void... voids) { try { return getTwitter().lookupUsers(userIds); } catch (TwitterException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(ResponseList<User> users) { if (users == null) { return; } mUserIconMap.clear(); for (User user : users) { mUserIconMap.put(String.valueOf(user.getId()), user.getBiggerProfileImageURL()); } String exportJson = gson.toJson(mUserIconMap); SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.putString(PREF_KEY_USER_ICON_MAP, exportJson); editor.commit(); } }.execute(); } /* * * * @see android.app.Application#onTerminate() */ @Override public void onTerminate() { super.onTerminate(); } /* * * * @see android.app.Application#onLowMemory() */ @Override public void onLowMemory() { super.onLowMemory(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } /** * * * @param text */ public static void showToast(String text) { Toast.makeText(sApplication, text, Toast.LENGTH_SHORT).show(); } public static void showToast(int id) { String text = sApplication.getString(id); Toast.makeText(sApplication, text, Toast.LENGTH_SHORT).show(); } public static void showProgressDialog(Context context, String message) { mProgressDialog = new ProgressDialog(context); mProgressDialog.setMessage(message); mProgressDialog.show(); } public static void dismissProgressDialog() { if (mProgressDialog != null) mProgressDialog.dismiss(); } private static final String TABS = "tabs-"; private ArrayList<Tab> mTabs = new ArrayList<Tab>(); public ArrayList<Tab> loadTabs() { mTabs.clear(); SharedPreferences preferences = getSharedPreferences("settings", Context.MODE_PRIVATE); String json = preferences.getString(TABS.concat(String.valueOf(getUserId())).concat("/v2"), null); if (json != null) { Gson gson = new Gson(); TabData tabData = gson.fromJson(json, TabData.class); mTabs = tabData.tabs; } if (mTabs.size() == 0) { mTabs = generalTabs(); } return mTabs; } public void saveTabs(ArrayList<Tab> tabs) { TabData tabData = new TabData(); tabData.tabs = tabs; Gson gson = new Gson(); String json = gson.toJson(tabData); SharedPreferences preferences = getSharedPreferences("settings", Context.MODE_PRIVATE); Editor editor = preferences.edit(); editor.remove(TABS.concat(String.valueOf(getUserId()))); editor.putString(TABS.concat(String.valueOf(getUserId())).concat("/v2"), json); editor.commit(); mTabs = tabs; } public ArrayList<Tab> generalTabs() { ArrayList<Tab> tabs = new ArrayList<Tab>(); tabs.add(new Tab(-1L)); tabs.add(new Tab(-2L)); tabs.add(new Tab(-3L)); return tabs; } public static class TabData { ArrayList<Tab> tabs; } public static class Tab { public Long id; public String name; public Tab(Long id) { this.id = id; } public String getName() { if (id == -1L) { return getApplication().getString(R.string.title_main); } else if (id == -2L) { return getApplication().getString(R.string.title_interactions); } else if (id == -3L) { return getApplication().getString(R.string.title_direct_messages); } else { return name; } } public int getIcon() { if (id == -1L) { return R.string.fontello_home; } else if (id == -2L) { return R.string.fontello_at; } else if (id == -3L) { return R.string.fontello_mail; } else { return R.string.fontello_list; } } } public boolean hasTabId(Long findTab) { for (Tab tab : mTabs) { if (tab.id.equals(findTab)) { return true; } } return false; } private static final String QUICK_MODE = "quickMode"; public void setQuickMod(Boolean quickMode) { SharedPreferences preferences = getSharedPreferences("settings", Context.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putBoolean(QUICK_MODE, quickMode); editor.commit(); } public Boolean getQuickMode() { SharedPreferences preferences = getSharedPreferences("settings", Context.MODE_PRIVATE); return preferences.getBoolean(QUICK_MODE, false); } private static final String STREAMING_MODE = "streamingMode"; public void setStreamingMode(Boolean streamingMode) { SharedPreferences preferences = getSharedPreferences("settings", Context.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putBoolean(STREAMING_MODE, streamingMode); editor.commit(); } public Boolean getStreamingMode() { SharedPreferences preferences = getSharedPreferences("settings", Context.MODE_PRIVATE); return preferences.getBoolean(STREAMING_MODE, true); } private static final String PREF_NAME_SETTINGS = "settings"; private int mFontSize; private String mLongTapAction; private String mThemeName; private Boolean mUserIconRounded; private Boolean mDisplayThumbnail; private String mUserIconSize; private int mPageCount; public boolean getKeepScreenOn() { SharedPreferences preferences = getSharedPreferences(PREF_NAME_SETTINGS, Context.MODE_PRIVATE); return preferences.getBoolean("keep_screen_on", true); } public int getFontSize() { return mFontSize; } public String getLongTapAction() { return mLongTapAction; } public void setTheme(Activity activity) { if (mThemeName.equals("black")) { activity.setTheme(R.style.BlackTheme); } else { activity.setTheme(R.style.WhiteTheme); } } public void setThemeTextColor(Activity activity, TextView view, int resourceId) { TypedValue outValue = new TypedValue(); Resources.Theme theme = activity.getTheme(); if (theme != null) { theme.resolveAttribute(resourceId, outValue, true); view.setTextColor(outValue.data); } } public String getThemeName() { return mThemeName; } public int getThemeTextColor(Activity activity, int resourceId) { TypedValue outValue = new TypedValue(); Resources.Theme theme = activity.getTheme(); if (theme != null) { theme.resolveAttribute(resourceId, outValue, true); } return outValue.data; } public void resetDisplaySettings() { SharedPreferences preferences = getSharedPreferences(PREF_NAME_SETTINGS, Context.MODE_PRIVATE); mFontSize = Integer.parseInt(preferences.getString("font_size", "12")); mLongTapAction = preferences.getString("long_tap", "nothing"); mThemeName = preferences.getString("themeName", "black"); mUserIconRounded = preferences.getBoolean("user_icon_rounded_on", true); mUserIconSize = preferences.getString("user_icon_size", "bigger"); mDisplayThumbnail = preferences.getBoolean("display_thumbnail_on", true); mPageCount = Integer.parseInt(preferences.getString("page_count", "200")); } public boolean getUserIconRoundedOn() { if (mUserIconRounded != null) { return mUserIconRounded; } SharedPreferences preferences = getSharedPreferences(PREF_NAME_SETTINGS, Context.MODE_PRIVATE); mUserIconRounded = preferences.getBoolean("user_icon_rounded_on", true); return mUserIconRounded; } public String getUserIconSize() { if (mUserIconSize != null) { return mUserIconSize; } SharedPreferences preferences = getSharedPreferences(PREF_NAME_SETTINGS, Context.MODE_PRIVATE); mUserIconSize = preferences.getString("user_icon_size", "bigger"); return mUserIconSize; } public boolean getDisplayThumbnailOn() { if (mDisplayThumbnail != null) { return mDisplayThumbnail; } SharedPreferences preferences = getSharedPreferences(PREF_NAME_SETTINGS, Context.MODE_PRIVATE); mDisplayThumbnail = preferences.getBoolean("display_thumbnail_on", true); return mDisplayThumbnail; } public int getPageCount() { if (mPageCount > 0) { return mPageCount; } SharedPreferences preferences = getSharedPreferences(PREF_NAME_SETTINGS, Context.MODE_PRIVATE); mPageCount = Integer.parseInt(preferences.getString("page_count", "200")); return mPageCount; } /** * Twitter */ private static final String TOKENS = "tokens"; private static final String PREF_NAME = "twitter_access_token"; private AccessToken mAccessToken; private Twitter mTwitter; public long getUserId() { if (mAccessToken == null) { return -1L; } return mAccessToken.getUserId(); } public String getScreenName() { if (mAccessToken == null) { return ""; } return mAccessToken.getScreenName(); } private String getConsumerKey() { return getString(R.string.twitter_consumer_key); } private String getConsumerSecret() { return getString(R.string.twitter_consumer_secret); } /** * Twitter * * @return Twitter */ public Boolean hasAccessToken() { return getAccessToken() != null; } public ArrayList<AccessToken> getAccessTokens() { SharedPreferences preferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); String json = preferences.getString(TOKENS, null); if (json == null) { return null; } Gson gson = new Gson(); JustawayApplication.AccountSettings accountSettings = gson.fromJson(json, JustawayApplication.AccountSettings.class); return accountSettings.accessTokens; } /** * Twitter * * @return Twitter */ public AccessToken getAccessToken() { if (mAccessToken != null) { return mAccessToken; } SharedPreferences preferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); String json = preferences.getString(TOKENS, null); if (json == null) { return null; } Gson gson = new Gson(); AccountSettings accountSettings = gson.fromJson(json, AccountSettings.class); mAccessToken = accountSettings.accessTokens.get(accountSettings.index); return mAccessToken; } /** * Twitter * * @param accessToken Twitter */ public void setAccessToken(AccessToken accessToken) { mAccessToken = accessToken; getTwitter().setOAuthAccessToken(mAccessToken); SharedPreferences preferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); String json = preferences.getString(TOKENS, null); Gson gson = new Gson(); AccountSettings accountSettings; if (json != null) { accountSettings = gson.fromJson(json, AccountSettings.class); boolean existUser = false; int i = 0; for (AccessToken sharedAccessToken : accountSettings.accessTokens) { if (accessToken.getUserId() == sharedAccessToken.getUserId()) { accountSettings.accessTokens.set(i, accessToken); accountSettings.index = i; existUser = true; } i++; } if (!existUser) { accountSettings.index = accountSettings.accessTokens.size(); accountSettings.accessTokens.add(mAccessToken); } } else { accountSettings = new AccountSettings(); accountSettings.accessTokens = new ArrayList<AccessToken>(); accountSettings.accessTokens.add(mAccessToken); } String exportJson = gson.toJson(accountSettings); Editor editor = preferences.edit(); editor.putString(TOKENS, exportJson); editor.commit(); } public static class AccountSettings { int index; ArrayList<AccessToken> accessTokens; } /** * Twitter() * * @return Twitter */ public Twitter getTwitter() { if (mTwitter != null) { return mTwitter; } Twitter twitter = getTwitterInstance(); AccessToken token = getAccessToken(); if (token != null) { twitter.setOAuthAccessToken(token); this.mTwitter = twitter; } return twitter; } /** * Twitter * * @return Twitter */ public Twitter getTwitterInstance() { TwitterFactory factory = new TwitterFactory(); Twitter twitter = factory.getInstance(); twitter.setOAuthConsumer(getConsumerKey(), getConsumerSecret()); return twitter; } /** * TwitterStream * * @return TwitterStream */ public TwitterStream getTwitterStream() { AccessToken token = getAccessToken(); if (token == null) { return null; } ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); twitter4j.conf.Configuration conf = configurationBuilder.setOAuthConsumerKey(getConsumerKey()) .setOAuthConsumerSecret(getConsumerSecret()).setOAuthAccessToken(token.getToken()) .setOAuthAccessTokenSecret(token.getTokenSecret()).build(); return new TwitterStreamFactory(conf).getInstance(); } private TwitterStream mTwitterStream; private boolean mTwitterStreamConnected; private MyUserStreamAdapter mUserStreamAdapter; public void startStreaming() { if (mTwitterStream != null) { if (!mTwitterStreamConnected) { mTwitterStream.user(); } return; } mTwitterStream = getTwitterStream(); mUserStreamAdapter = new MyUserStreamAdapter(); mTwitterStream.addListener(mUserStreamAdapter); mTwitterStream.addConnectionLifeCycleListener(new MyConnectionLifeCycleListener()); mTwitterStream.user(); } public void restartStreaming() { if (!getStreamingMode()) { return; } if (mTwitterStream != null) { mUserStreamAdapter.stop(); EventBus.getDefault().post(new AccountChangePreEvent()); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { mTwitterStream.cleanUp(); mTwitterStream.shutdown(); mTwitterStream.setOAuthAccessToken(getAccessToken()); mTwitterStream.user(); return null; } @Override protected void onPostExecute(Void status) { mUserStreamAdapter.start(); EventBus.getDefault().post(new AccountChangePostEvent()); } }.execute(); } else { startStreaming(); } } public void stopStreaming() { if (mTwitterStream == null) { return; } new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { mTwitterStream.cleanUp(); mTwitterStream.shutdown(); return null; } @Override protected void onPostExecute(Void status) { } }.execute(); } @SuppressWarnings("UnusedDeclaration") public void onEventMainThread(ConnectEvent event) { mTwitterStreamConnected = true; } @SuppressWarnings("UnusedDeclaration") public void onEventMainThread(DisconnectEvent event) { mTwitterStreamConnected = false; } @SuppressWarnings("UnusedDeclaration") public void onEventMainThread(CleanupEvent event) { mTwitterStreamConnected = false; } public void removeAccessToken(int position) { SharedPreferences preferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); String json = preferences.getString(TOKENS, null); Gson gson = new Gson(); AccountSettings accountSettings = gson.fromJson(json, AccountSettings.class); accountSettings.accessTokens.remove(position); if (accountSettings.index > position) { accountSettings.index } String exportJson = gson.toJson(accountSettings); Editor editor = preferences.edit(); editor.putString(TOKENS, exportJson); editor.commit(); } private LongSparseArray<Boolean> mIsFavMap = new LongSparseArray<Boolean>(); private LongSparseArray<Long> mRtIdMap = new LongSparseArray<Long>(); public void setFav(Long id) { mIsFavMap.put(id, true); } public void removeFav(Long id) { mIsFavMap.remove(id); } public Boolean isFav(Status status) { if (mIsFavMap.get(status.getId(), false)) { return true; } Status retweet = status.getRetweetedStatus(); return retweet != null && (mIsFavMap.get(retweet.getId(), false)); } public void setRtId(Long sourceId, Long retweetId) { if (retweetId != null) { mRtIdMap.put(sourceId, retweetId); } else { mRtIdMap.remove(sourceId); } } public Long getRtId(Status status) { Long id = mRtIdMap.get(status.getId()); if (id != null) { return id; } Status retweet = status.getRetweetedStatus(); if (retweet != null) { return mRtIdMap.get(retweet.getId()); } return null; } public void doFavorite(Long statusId) { new FavoriteTask(statusId).execute(); } public void doDestroyFavorite(Long statusId) { new UnFavoriteTask(statusId).execute(); } public void doRetweet(Long statusId) { new RetweetTask(statusId).execute(); } public void doDestroyRetweet(Status status) { if (status.getUser().getId() == getUserId()) { // RTStatus Status retweet = status.getRetweetedStatus(); if (retweet != null) { new UnRetweetTask(retweet.getId(), status.getId()).execute(); } } else { // StatusRT Long retweetedStatusId = -1L; Long statusId = mRtIdMap.get(status.getId()); if (statusId != null && statusId > 0) { // StatusRT retweetedStatusId = status.getId(); } else { Status retweet = status.getRetweetedStatus(); if (retweet != null) { statusId = mRtIdMap.get(retweet.getId()); if (statusId != null && statusId > 0) { // StatusRTStatusRT retweetedStatusId = retweet.getId(); } } } if (statusId != null && statusId == 0L) { JustawayApplication.showToast(R.string.toast_destroy_retweet_progress); } else if (statusId != null && statusId > 0) { new UnRetweetTask(retweetedStatusId, statusId).execute(); } } } public void doReply(Status status, Context context) { UserMentionEntity[] mentions = status.getUserMentionEntities(); String text; if (status.getUser().getId() == getUserId() && mentions.length == 1) { text = "@" + mentions[0].getScreenName() + " "; } else { text = "@" + status.getUser().getScreenName() + " "; } if (context instanceof MainActivity) { EventBus.getDefault().post(new EditorEvent(text, status, text.length(), null)); } else { Intent intent = new Intent(context, PostActivity.class); intent.putExtra("status", text); intent.putExtra("selection", text.length()); intent.putExtra("inReplyToStatus", status); context.startActivity(intent); } } public void doReplyAll(Status status, Context context) { UserMentionEntity[] mentions = status.getUserMentionEntities(); String text = ""; int selection_start = 0; if (status.getUser().getId() != getUserId()) { text = "@" + status.getUser().getScreenName() + " "; selection_start = text.length(); } for (UserMentionEntity mention : mentions) { if (status.getUser().getId() == mention.getId()) { continue; } if (getUserId() == mention.getId()) { continue; } text = text.concat("@" + mention.getScreenName() + " "); if (selection_start == 0) { selection_start = text.length(); } } if (context instanceof MainActivity) { EventBus.getDefault().post(new EditorEvent(text, status, selection_start, text.length())); } else { Intent intent = new Intent(context, PostActivity.class); intent.putExtra("status", text); intent.putExtra("selection", selection_start); intent.putExtra("selection_stop", text.length()); intent.putExtra("inReplyToStatus", status); context.startActivity(intent); } } public void doReplyDirectMessage(DirectMessage directMessage, Context context) { String text; if (getUserId() == directMessage.getSender().getId()) { text = "D " + directMessage.getRecipient().getScreenName() + " "; } else { text = "D " + directMessage.getSender().getScreenName() + " "; } if (context instanceof MainActivity) { EventBus.getDefault().post(new EditorEvent(text, null, text.length(), null)); } else { Intent intent = new Intent(context, PostActivity.class); intent.putExtra("status", text); intent.putExtra("selection", text.length()); context.startActivity(intent); } } public void doQuote(Status status, Context context) { String text = " https://twitter.com/" + status.getUser().getScreenName() + "/status/" + String.valueOf(status.getId()); if (context instanceof MainActivity) { EventBus.getDefault().post(new EditorEvent(text, status, null, null)); } else { Intent intent = new Intent(context, PostActivity.class); intent.putExtra("status", text); intent.putExtra("inReplyToStatus", status); context.startActivity(intent); } } public void showKeyboard(final View view) { showKeyboard(view, 200); } public void showKeyboard(final View view, int delay) { view.postDelayed(new Runnable() { @Override public void run() { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.showSoftInput(view, 0); } }, delay); } @SuppressWarnings("unused") public void hideKeyboard(View view) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } public String getClientName(String source) { String[] tokens = source.split("[<>]"); if (tokens.length > 1) { return tokens[2]; } else { return tokens[0]; } } public boolean isMentionForMe(Status status) { long userId = getUserId(); UserMentionEntity[] mentions = status.getUserMentionEntities(); for (UserMentionEntity mention : mentions) { if (mention.getId() == userId) { return true; } } return false; } }
package roart.filesystem; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.Arrays; import java.util.List; import roart.common.config.MyConfig; import roart.common.constants.EurekaConstants; import roart.common.filesystem.FileSystemBooleanResult; import roart.common.filesystem.FileSystemByteResult; import roart.common.filesystem.FileSystemConstructorParam; import roart.common.filesystem.FileSystemConstructorResult; import roart.common.filesystem.FileSystemFileObjectParam; import roart.common.filesystem.FileSystemFileObjectResult; import roart.common.filesystem.FileSystemPathParam; import roart.common.filesystem.FileSystemPathResult; import roart.common.model.FileObject; import roart.eureka.util.EurekaUtil; import roart.service.ControlService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.discovery.DiscoveryClient; public class FileSystemAccess { private String url; private Logger log = LoggerFactory.getLogger(this.getClass()); private DiscoveryClient discoveryClient; public String getAppName() { return null; } public String constructor(String url) { this.url = url; FileSystemConstructorParam param = new FileSystemConstructorParam(); param.nodename = ControlService.nodename; param.conf = MyConfig.conf; //FileSystemConstructorResult result = EurekaUtil.sendMe(FileSystemConstructorResult.class, param, getAppName(), EurekaConstants.CONSTRUCTOR); FileSystemConstructorResult result = EurekaUtil.sendMe(FileSystemConstructorResult.class, url, param, EurekaConstants.CONSTRUCTOR); return result.error; } public String destructor() { FileSystemConstructorParam param = new FileSystemConstructorParam(); param.nodename = ControlService.nodename; param.conf = MyConfig.conf; FileSystemConstructorResult result = EurekaUtil.sendMe(FileSystemConstructorResult.class, url, param, EurekaConstants.DESTRUCTOR); return result.error; } public List<FileObject> listFiles(FileObject f) { FileSystemFileObjectParam param = new FileSystemFileObjectParam(); param.nodename = ControlService.nodename; param.conf = MyConfig.conf; param.fo = f; FileSystemFileObjectResult result = EurekaUtil.sendMe(FileSystemFileObjectResult.class, url, param, EurekaConstants.LISTFILES); return Arrays.asList(result.getFileObject()); } public boolean exists(FileObject f) { FileSystemFileObjectParam param = new FileSystemFileObjectParam(); param.nodename = ControlService.nodename; param.conf = MyConfig.conf; param.fo = f; FileSystemBooleanResult result = EurekaUtil.sendMe(FileSystemBooleanResult.class, url, param, EurekaConstants.EXIST); return result.bool; } public String getAbsolutePath(FileObject f) { FileSystemFileObjectParam param = new FileSystemFileObjectParam(); param.nodename = ControlService.nodename; param.conf = MyConfig.conf; param.fo = f; FileSystemPathResult result = EurekaUtil.sendMe(FileSystemPathResult.class, url, param, EurekaConstants.GETABSOLUTEPATH); return result.getPath(); } public boolean isDirectory(FileObject f) { FileSystemFileObjectParam param = new FileSystemFileObjectParam(); param.nodename = ControlService.nodename; param.conf = MyConfig.conf; param.fo = f; FileSystemBooleanResult result = EurekaUtil.sendMe(FileSystemBooleanResult.class, url, param, EurekaConstants.ISDIRECTORY); return result.bool; } public InputStream getInputStream(FileObject f) { FileSystemFileObjectParam param = new FileSystemFileObjectParam(); param.nodename = ControlService.nodename; param.conf = MyConfig.conf; param.fo = f; FileSystemByteResult result = EurekaUtil.sendMe(FileSystemByteResult.class, url, param, EurekaConstants.GETINPUTSTREAM); return new ByteArrayInputStream(result.bytes); } public FileObject getParent(FileObject f) { FileSystemFileObjectParam param = new FileSystemFileObjectParam(); param.nodename = ControlService.nodename; param.conf = MyConfig.conf; param.fo = f; FileSystemFileObjectResult result = EurekaUtil.sendMe(FileSystemFileObjectResult.class, url, param, EurekaConstants.GETPARENT); return result.getFileObject()[0]; } public FileObject get(String string) { FileSystemPathParam param = new FileSystemPathParam(); param.nodename = ControlService.nodename; param.conf = MyConfig.conf; param.path = string; FileSystemFileObjectResult result = EurekaUtil.sendMe(FileSystemFileObjectResult.class, url, param, EurekaConstants.GET); return result.getFileObject()[0]; } public String getLocalFilesystemFile(String filename) { FileObject file = FileSystemDao.get(filename); String fn = FileSystemDao.getAbsolutePath(file); if (fn.charAt(4) == ':') { fn = fn.substring(5); } return fn; } }
package betterwithaddons.handler; import betterwithaddons.interaction.InteractionBWA; import betterwithaddons.item.ModItems; import betterwithaddons.lib.Reference; import betterwithaddons.util.InventoryUtil; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import net.minecraft.client.resources.I18n; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagLong; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.oredict.OreDictionary; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.stream.Collectors; public class RotHandler { public static final String CREATION_TIME_TAG = "TimeOfCreation"; private LinkedList<EntityItem> TrackedItems = new LinkedList<>(); private LinkedList<EntityItem> TrackedItemsAdd = new LinkedList<>(); private Iterator<EntityItem> TrackedItemsIterator; public static final ResourceLocation ROT = new ResourceLocation(Reference.MOD_ID, "rot"); //@CapabilityInject(Rot.class) //public static Capability<Rot> ROT_CAP; public static final long ONE_DAY = 24000; public static long MINECRAFT_DATE = -1; static Multimap<Item,RotInfo> rottingItems = HashMultimap.create(); public static class RotInfo { ItemStack itemStack; ItemStack rottedStack; String baseName; long spoilTime; public RotInfo(ItemStack matchStack) { this(matchStack, InteractionBWA.MISC_ROT_TIME, "food", new ItemStack(ModItems.ROTTEN_FOOD)); } public RotInfo(ItemStack matchStack, long spoilTime, String baseName, ItemStack rotStack) { this.itemStack = matchStack; this.spoilTime = spoilTime; this.baseName = baseName; this.rottedStack = rotStack; } public boolean matches(ItemStack stack) { return stack.getItem() == itemStack.getItem() && (stack.getMetadata() == itemStack.getMetadata() || itemStack.getMetadata() == OreDictionary.WILDCARD_VALUE); } public boolean shouldSpoil(ItemStack stack, long creationDate) { return matches(stack) && MINECRAFT_DATE >= creationDate + spoilTime; } public ItemStack getRottenStack(ItemStack stack) { ItemStack returnStack = rottedStack.copy(); returnStack.setCount(stack.getCount()); return returnStack; } public String getUnlocalizedName(ItemStack stack, long creationDate) { double rotPercent = (MINECRAFT_DATE - creationDate) / (double)spoilTime; int rotPercentInt = Math.min(100,(int)(rotPercent * 100.0)); String returnKey = getLocalizationKey(stack.getUnlocalizedName(),rotPercentInt); if(returnKey == null) returnKey = getLocalizationKey(baseName,rotPercentInt); return returnKey != null ? returnKey : (baseName + ".rot"); } protected String getLocalizationKey(String baseName, int percent) { percent = (percent / 25) * 25; String testkey = baseName + ".rot." + percent; if(I18n.hasKey(testkey)) return testkey; return null; } } public static void addRottingItem(ItemStack matchItem) { addRottingItem(matchItem, InteractionBWA.MISC_ROT_TIME, "food", new ItemStack(ModItems.ROTTEN_FOOD)); } public static void addRottingItem(ItemStack matchItem, long timeToRot) { addRottingItem(matchItem, timeToRot, "food", new ItemStack(ModItems.ROTTEN_FOOD)); } public static void addRottingItem(ItemStack matchItem, long timeToRot, String baseName, ItemStack rottedItem) { rottingItems.put(matchItem.getItem(),new RotInfo(matchItem,timeToRot,baseName,rottedItem)); } //For adding custom filtering and behavior public static void addRottingItem(Item item, RotInfo rotInfo) { rottingItems.put(item,rotInfo); } public static void removeRottingItem(ItemStack matchItem) { ArrayList<RotInfo> toRemove = rottingItems.get(matchItem.getItem()).stream().filter(rotInfo -> rotInfo.matches(matchItem)).collect(Collectors.toCollection(ArrayList::new)); for (RotInfo info: toRemove) { rottingItems.remove(matchItem.getItem(),info); } } public static boolean isRottingItem(ItemStack stack) { return rottingItems.containsKey(stack.getItem()); } @SubscribeEvent public void onEntityJoin(EntityJoinWorldEvent event) { Entity entity = event.getEntity(); World world = event.getWorld(); if(entity instanceof EntityItem) { ItemStack stack = ((EntityItem) entity).getItem(); if(!stack.isEmpty() && isRottingItem(stack)) { if(!entity.isDead) TrackedItemsAdd.add((EntityItem)entity); } } } @SubscribeEvent public void worldTick(TickEvent.WorldTickEvent tickEvent) { World world = tickEvent.world; if(!world.isRemote && tickEvent.phase == TickEvent.Phase.END) { if(world.provider.getDimension() == 0) MINECRAFT_DATE = (tickEvent.world.getTotalWorldTime() / ONE_DAY) * ONE_DAY; handleRottingWorldItems(); } } @SubscribeEvent public void onPlayerTick(TickEvent.PlayerTickEvent event) { EntityPlayer player = event.player; World world = player.world; if(!world.isRemote && world.getTotalWorldTime() % 20 == 0 && event.phase == TickEvent.Phase.END) { for(int slot = 0; slot < player.inventory.getSizeInventory(); slot++) { ItemStack stack = player.inventory.getStackInSlot(slot); if(!stack.isEmpty() && isRottingItem(stack)) { long timeOfCreation = getCreationDate(stack); if(timeOfCreation == -1) { timeOfCreation = MINECRAFT_DATE; setCreationDate(stack,timeOfCreation); } for(RotInfo info : rottingItems.get(stack.getItem())) { if(info.shouldSpoil(stack,timeOfCreation)) { ItemStack containerItem = stack.getItem().getContainerItem(stack); containerItem.setCount(stack.getCount()); ItemStack rottenItem = info.getRottenStack(stack); if(containerItem.isEmpty()) player.inventory.setInventorySlotContents(slot,rottenItem); else { player.inventory.setInventorySlotContents(slot,containerItem); InventoryUtil.addItemToPlayer(player,rottenItem); } break; } } } } } } @SubscribeEvent(priority = EventPriority.HIGHEST) @SideOnly(Side.CLIENT) public void onToolTip(ItemTooltipEvent event) { ItemStack stack = event.getItemStack(); if(isRottingItem(stack)) { long timeOfCreation = getCreationDate(stack); if(timeOfCreation == -1) return; for(RotInfo info : rottingItems.get(stack.getItem())) { if(info.matches(stack)) { String prefix = I18n.format(info.getUnlocalizedName(stack, timeOfCreation)); if(prefix.length() > 0) prefix = prefix + " "; event.getToolTip().set(0,prefix + event.getToolTip().get(0)); break; } } } } private void handleRottingWorldItems() { if(TrackedItemsIterator == null || !TrackedItemsIterator.hasNext()) { for (EntityItem entity : TrackedItemsAdd) { rotOneItem(entity); TrackedItems.add(entity); } TrackedItemsAdd.clear(); TrackedItemsIterator = TrackedItems.iterator(); } else { EntityItem entity = TrackedItemsIterator.next(); World world = entity.world; ItemStack stack = entity.getItem(); boolean remove = false; if(entity.isDead || stack.isEmpty() || !isRottingItem(stack)) remove = true; else { rotOneItem(entity); } if(remove) TrackedItemsIterator.remove(); } } private void rotOneItem(EntityItem entity) { World world = entity.world; ItemStack stack = entity.getItem(); if(!isRottingItem(stack)) return; //Rot rot = stack.getCapability(ROT_CAP,null); long timeOfCreation = getCreationDate(stack); if(timeOfCreation == -1) { timeOfCreation = MINECRAFT_DATE; setCreationDate(stack,timeOfCreation); } for(RotInfo info : rottingItems.get(stack.getItem())) { if(info.shouldSpoil(stack,timeOfCreation)) { ItemStack containerItem = stack.getItem().getContainerItem(stack); containerItem.setCount(stack.getCount()); ItemStack rottenItem = info.getRottenStack(stack); if(containerItem.isEmpty()) { entity.setItem(rottenItem); if(rottenItem.isEmpty()) entity.setDead(); } else { entity.setItem(containerItem); if(!rottenItem.isEmpty()) { EntityItem result = new EntityItem(world, entity.posX, entity.posY, entity.posZ, rottenItem); result.setDefaultPickupDelay(); world.spawnEntity(result); } } break; } } } public static long getCreationDate(ItemStack stack) { if(!isRottingItem(stack)) return -1; NBTTagCompound compound = stack.getTagCompound(); return compound != null && compound.hasKey(CREATION_TIME_TAG) ? compound.getLong(CREATION_TIME_TAG) : -1; } public static void setCreationDate(ItemStack stack, long value) { if(!isRottingItem(stack)) return; stack.setTagInfo(CREATION_TIME_TAG,new NBTTagLong(value)); } /*public static void registerCapability() { CapabilityManager.INSTANCE.register(Rot.class, new Capability.IStorage<Rot>() { @Nullable @Override public NBTBase writeNBT(Capability<Rot> capability, Rot instance, EnumFacing side) { return instance.serializeNBT(); } @Override public void readNBT(Capability<Rot> capability, Rot instance, EnumFacing side, NBTBase nbt) { instance.deserializeNBT((NBTTagCompound)nbt); } }, Rot::new); } public static class Rot implements ICapabilitySerializable<NBTTagCompound> { public long timeOfCreation = -1; public Rot() { timeOfCreation = MINECRAFT_DATE; } @Override public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) { return capability == ROT_CAP; } @Nullable @Override public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) { return hasCapability(capability, facing) ? (T) this : null; } @Override public NBTTagCompound serializeNBT() { NBTTagCompound nbt = new NBTTagCompound(); if(timeOfCreation != -1) nbt.setLong("TimeOfCreation", timeOfCreation); return nbt; } @Override public void deserializeNBT(NBTTagCompound nbt) { if(nbt.hasKey("TimeOfCreation")) timeOfCreation = nbt.getLong("TimeOfCreation"); } }*/ @SubscribeEvent public void rotAttachCapability(AttachCapabilitiesEvent<ItemStack> event) { ItemStack stack = event.getObject(); if(isRottingItem(stack) && MINECRAFT_DATE != -1) //All items instead? { NBTTagCompound compound = stack.getTagCompound(); if(compound == null || !compound.hasKey(CREATION_TIME_TAG)) stack.setTagInfo(CREATION_TIME_TAG,new NBTTagLong(MINECRAFT_DATE)); //event.addCapability(ROT,new Rot()); } } }
package models.ciphers; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Transposition extends AbstractBlockCipher implements CipherInterface { private static final String DESC = "Transposition Cipher"; private static final String NAME = "Transposition Cipher"; @Override public String encrypt(String plaintext, String key) { key = key.toLowerCase(); if (checkKey(key)) { plaintext = pad(plaintext, key.length()); ArrayList<Integer> intKey = convertToKey(key); // <- never = 3, 1, 5, 2, 4 List<List<Character>> rect = getRectangle(plaintext, key.length()); rect = flip(rect); rect = mix(rect, intKey); rect = flip(rect); // 01. 02. 03. 04. // 1, 2, 3, 4, 5 1 [w, o, i, m] 3 [a, s, a, a] 3, 1, 5, 2, 4 // [w, h, a, t, d] 2 [h, e, s, e] 1 [w, o, i, m] [a, w, d, h, t] // [o, e, s, t, h] -> 3 [a, s, a, a] -> 5 [d, h, l, g] -> [s, o, h, e, t] // [i, s, a, l, l] 4 [t, t, l, n] 2 [h, e, s, e] [a, i, l, s, l] // [m, e, a, n, g] 5 [d, h, l, g] 4 [t, t, l, n] [a, m, g, e, n] StringBuilder ciphertext = new StringBuilder(); for (List<Character> row : rect) { for (Character ch : row) { ciphertext.append(ch); } } return ciphertext.toString(); } return "Failed."; } @Override public String decrypt(String ciphertext, String key) { key = key.toLowerCase(); ArrayList<Integer> intKey = convertToKey(key); if (checkKey(key)) { List<List<Character>> rect = getRectangle(ciphertext, key.length()); rect = flip(rect); rect = unmix(rect, intKey); rect = flip(rect); // 04. 03. 02. 01. // 1, 2, 3, 4, 5 1 [w, o, i, m] 3 [a, s, a, a] 3, 1, 5, 2, 4 // [w, h, a, t, d] 2 [h, e, s, e] 1 [w, o, i, m] [a, w, d, h, t] // [o, e, s, t, h] <- 3 [a, s, a, a] <- 5 [d, h, l, g] <- [s, o, h, e, t] // [i, s, a, l, l] 4 [t, t, l, n] 2 [h, e, s, e] [a, i, l, s, l] // [m, e, a, n, g] 5 [d, h, l, g] 4 [t, t, l, n] [a, m, g, e, n] StringBuilder plaintext = new StringBuilder(); for (List<Character> row : rect) { for (Character ch : row) { plaintext.append(ch); } } return plaintext.toString(); // return unpad(plaintext.toString(), key.length()); } return "Failed."; } @Override public String getDescription() { return null; } @Override public String getName() { return null; } private List<List<Character>> getRectangle(String plaintext, int keylength) { List<List<Character>> rectangle = new ArrayList<>(); int counter = 0; List<Character> row = new ArrayList<>(); for (Character c : plaintext.toCharArray()) { row.add(c); if (++counter >= keylength) { rectangle.add(row); row = new ArrayList<>(); counter = 0; } } if (counter != 0) rectangle.add(row); return rectangle; } private List<List<Character>> flip(List<List<Character>> input) { List<List<Character>> output = new ArrayList<>(); List<Character> newRow; int maxCols = input.get(0).size(); for (int i = 0; i < maxCols; ++i) { newRow = new ArrayList<>(); for (List<Character> row : input) { if (i < row.size()) newRow.add(row.get(i)); } output.add(newRow); } return output; } private List<List<Character>> mix(List<List<Character>> input, ArrayList<Integer> key) { List<List<Character>> output = new ArrayList<>(); for (Integer x : key) { output.add(input.get(x - 1)); } return output; } private List<List<Character>> unmix(List<List<Character>> input, ArrayList<Integer> key) { List<List<Character>> output = new ArrayList<>(); int current = 1; int row = 0; while (current <= key.size()) { row = 0; for (Integer k : key) { if (k == current) { output.add(input.get(row)); } ++row; } ++current; } return output; } private ArrayList<Integer> convertToKey(String key) { String temp = key.toLowerCase(); String sorted = sortString(temp); ArrayList<Integer> intKey = new ArrayList<>(temp.length()); ArrayList<Integer> returnable = new ArrayList<>(); for (int i = 1; i <= temp.length(); ++i) { intKey.add(i); } int ret, index; for (Character c : temp.toCharArray()) { index = find(c, sorted); //get index of the first c in sorted; //remove first instance of c sorted = sorted.replaceFirst(c.toString(), ""); //remove c from sorted; // System.out.println("index = " + index); ret = intKey.get(index); intKey.remove(index); // System.out.println("key = " + sorted); // System.out.println("intKey = " + intKey); // System.out.println("ret = " + ret); returnable.add(ret); } return returnable; } //returns the first instance of ch in str private int find(Character ch, String str) { int count = 0; for (Character c : str.toCharArray()) { if (ch == c) return count; ++count; } return -1; } private String sortString(String key) { char[] temp = key.toCharArray(); Arrays.sort(temp); return new String(temp); } @Override public Boolean checkKey(String key) { int original = key.length(); key = removeDuplicates(key).trim(); // System.out.println("original = " + original); // System.out.println("key.length() = " + key.length()); if (original != key.length()) return false; return super.checkKey(key); } }
package ch.tkuhn.memetools; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; public class ApsMetadataEntry { private String id; private String date; private Map<String,String> title; private List<Map<String,Object>> authors; @SerializedName("abstract") private Map<String,String> abstractText; public static ApsMetadataEntry load(File file) throws FileNotFoundException { BufferedReader br = new BufferedReader(new FileReader(file)); return new Gson().fromJson(br, ApsMetadataEntry.class); } public String getId() { return id; } public String getDate() { return date; } public List<String> getNormalizedAuthors() { List<String> nAuthors = new ArrayList<String>(); if (authors != null) { for (Map<String,Object> m : authors) { if (!m.containsKey("type") || !"Person".equals(m.get("type")) || !m.containsKey("firstname") || !m.containsKey("surname")) { nAuthors.add(null); continue; } String f = m.get("firstname").toString().toLowerCase(); String s = m.get("surname").toString().toLowerCase(); if (f.isEmpty() || s.isEmpty()) { nAuthors.add(null); continue; } nAuthors.add(f.substring(0, 1) + "." + s); } } return nAuthors; } public String getNormalizedTitle() { if (title == null || !title.containsKey("value")) return null; String n = title.get("value"); if (n == null) return null; if (title.containsKey("format") && title.get("format").startsWith("html")) { n = preprocessHtml(n); } return MemeUtils.normalize(n); } public String getNormalizedAbstract() { if (abstractText == null || !abstractText.containsKey("value")) return null; String n = abstractText.get("value"); if (n == null) return null; if (abstractText.containsKey("format") && abstractText.get("format").startsWith("html")) { n = preprocessHtml(n); } return MemeUtils.normalize(n); } public String preprocessHtml(String htmlText) { htmlText = htmlText.replaceAll("</?[a-z]+ ?.*?/?>", ""); return htmlText; } }
package co.mewf.humpty.config; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import co.mewf.humpty.spi.PipelineElement; import com.moandjiezana.toml.Toml; public class Configuration { public static enum Mode { PRODUCTION, DEVELOPMENT, EXTERNAL; } public static class Options { public static final Options EMPTY = new Options(Collections.emptyMap()); private final Map<String, Object> options; public Options(Map<String, Object> options) { this.options = options; } @SuppressWarnings("unchecked") public <T> T get(String key, T defaultValue) { return options.containsKey(key) ? (T) options.get(key) : defaultValue; } public <T> Optional<T> get(String key) { return Optional.ofNullable(get(key, null)); } public boolean containsKey(String key) { return options.containsKey(key); } public Map<String, Object> toMap() { return new HashMap<>(options); } } public static class GlobalOptions { private String assetsDir; private String buildDir; private String digestFile; public Path getAssetsDir() { return Paths.get(assetsDir != null ? assetsDir : "assets"); } public Path getBuildDir() { return Paths.get(buildDir != null ? buildDir : "src/main/resources/META-INF/resources"); } public Path getDigestFile() { return Paths.get("humpty-digest.toml"); } public Path getWatchFile() { return Paths.get("humpty-watch.toml"); } } private List<Bundle> bundle = new ArrayList<>(); private Map<String, Object> options; private GlobalOptions globalOptions; public static Configuration load(String tomlPath) { if (tomlPath.startsWith("/")) { tomlPath = tomlPath.substring(1); } return load(new Toml().parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(tomlPath))); } public static Configuration load(Path tomlPath) { return load(new Toml().parse(tomlPath.toFile())); } @SuppressWarnings("unchecked") private static Configuration load(Toml toml) { Configuration configuration = toml.to(Configuration.class); configuration.globalOptions = toml.getTable("options").to(GlobalOptions.class); Map<String, List<String>> map = toml.to(Map.class); map.entrySet().stream() .filter(e -> !e.getKey().toString().equals("options")) .filter(e -> !e.getKey().toString().equals("bundle")) .map(e -> { String key = e.getKey().toString().substring(1, e.getKey().toString().length() -1); Bundle bundle; if (e.getValue() instanceof List) { bundle = new Bundle(key, (List<String>) e.getValue()); } else { List<String> assets = (List<String>) ((Map<String, Object>) e.getValue()).get("assets"); bundle = new Bundle(key, assets); } return bundle; }) .forEach(configuration.bundle::add); configuration.bundle.forEach(Bundle::normaliseAssets); return configuration; } public List<Bundle> getBundles() { return bundle; } @SuppressWarnings("unchecked") public Configuration.Options getOptionsFor(PipelineElement pipelineElement) { String name = pipelineElement.getName(); if (options == null || !options.containsKey(name)) { return Options.EMPTY; } return new Options((Map<String, Object>) options.get(name)); } public Configuration.GlobalOptions getGlobalOptions() { return globalOptions; } }
package org.appwork.scheduler; import java.lang.reflect.Modifier; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; /** * @author daniel * */ public abstract class DelayedRunnable implements Runnable { public static String getCaller() { final Throwable stackTrace = new Throwable().fillInStackTrace(); try { for (final StackTraceElement element : stackTrace.getStackTrace()) { final String currentClassName = element.getClassName(); final Class<?> currentClass = Class.forName(currentClassName, true, Thread.currentThread().getContextClassLoader()); if (Modifier.isAbstract(currentClass.getModifiers())) { /* we dont want the abstract class to be used */ continue; } if (Modifier.isInterface(currentClass.getModifiers())) { /* we dont want the interface class to be used */ continue; } return currentClassName; } } catch (final Throwable e2) { } return null; } /** * return a ScheduledExecutorService with deamon Threads, * allowCoreThreadTimeOut(true) and maxPoolSize(1) */ public static ScheduledExecutorService getNewScheduledExecutorService() { final String caller = DelayedRunnable.getCaller(); final ScheduledThreadPoolExecutor ret = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { @Override public Thread newThread(final Runnable r) { final Thread thread = new Thread(r); if (caller != null) { thread.setName("Scheduler:" + caller); } thread.setDaemon(true); return thread; } }); ret.setMaximumPoolSize(1); ret.setKeepAliveTime(10000, TimeUnit.MILLISECONDS); ret.allowCoreThreadTimeOut(true); return ret; } private final ScheduledExecutorService service; private final long delayInMS; private final AtomicLong lastRunRequest = new AtomicLong(0); private final AtomicLong firstRunRequest = new AtomicLong(0); private final AtomicBoolean delayerSet = new AtomicBoolean(false); private final long maxInMS; private final AtomicBoolean delayerEnabled = new AtomicBoolean(true); public DelayedRunnable(final long minDelayInMS) { this(DelayedRunnable.getNewScheduledExecutorService(), minDelayInMS); } public DelayedRunnable(final long minDelayInMS, final long maxDelayInMS) { this(DelayedRunnable.getNewScheduledExecutorService(), minDelayInMS, maxDelayInMS); } public DelayedRunnable(final ScheduledExecutorService service, final long delayInMS) { this(service, delayInMS, -1); } public DelayedRunnable(final ScheduledExecutorService service, final long minDelayInMS, final long maxDelayInMS) { this.service = service; this.delayInMS = minDelayInMS; this.maxInMS = maxDelayInMS; if (this.delayInMS <= 0) { throw new IllegalArgumentException("minDelay must be >0"); } if (this.maxInMS == 0) { throw new IllegalArgumentException("maxDelay must be !=0"); } } abstract public void delayedrun(); public String getID() { return null; } public boolean isDelayerEnabled() { return this.delayerEnabled.get(); } public void resetAndStart() { this.run(); } @Override public void run() { if (this.isDelayerEnabled() == false) { DelayedRunnable.this.delayedrun(); return; } this.lastRunRequest.set(System.currentTimeMillis()); if (this.delayerSet.getAndSet(true) == true) { return; } this.firstRunRequest.compareAndSet(0, System.currentTimeMillis()); this.service.schedule(new Runnable() { private void delayAgain(final long currentTime, Long nextDelay, final long minDif, final long thisRequestRun) { if (DelayedRunnable.this.delayerSet.get() == false) { return; } if (nextDelay == null) { nextDelay = Math.max(0, DelayedRunnable.this.delayInMS - minDif); } if (nextDelay < 10) { this.runNow(currentTime, thisRequestRun, minDif); return; } DelayedRunnable.this.service.schedule(this, nextDelay, TimeUnit.MILLISECONDS); } public void run() { if (DelayedRunnable.this.delayerSet.get() == false) { return; } final long thisRunRequest = DelayedRunnable.this.lastRunRequest.get(); final long currentTime = System.currentTimeMillis(); final long minDif = currentTime - thisRunRequest; if (minDif >= DelayedRunnable.this.delayInMS) { /* minDelay reached, run now */ this.runNow(currentTime, thisRunRequest, minDif); return; } final long firstRunRequest = DelayedRunnable.this.firstRunRequest.get(); Long nextDelay = null; if (DelayedRunnable.this.maxInMS > 0) { final long maxDif = currentTime - firstRunRequest; if (maxDif >= DelayedRunnable.this.maxInMS) { /* maxDelay reached, run now */ this.runNow(currentTime, thisRunRequest, minDif); return; } final long delay = DelayedRunnable.this.maxInMS - maxDif; nextDelay = Math.min(delay, DelayedRunnable.this.delayInMS); } this.delayAgain(currentTime, nextDelay, minDif, thisRunRequest); } private void runNow(final long currentTime, final long thisRunRequest, final long minDif) { DelayedRunnable.this.delayedrun(); if (thisRunRequest != DelayedRunnable.this.lastRunRequest.get()) { DelayedRunnable.this.firstRunRequest.set(currentTime); this.delayAgain(currentTime, DelayedRunnable.this.delayInMS, minDif, thisRunRequest); } else { this.stop(); } } private void stop() { DelayedRunnable.this.firstRunRequest.set(0); DelayedRunnable.this.delayerSet.set(false); } }, DelayedRunnable.this.delayInMS, TimeUnit.MILLISECONDS); } public void setDelayerEnabled(final boolean b) { if (this.delayerEnabled.getAndSet(b) == b) { return; } if (!b) { this.stop(); } } public void stop() { this.delayerSet.set(false); } }
package com.almasb.fxgl.app; import com.almasb.ents.Entity; import com.almasb.ents.EntityWorldListener; import com.almasb.fxeventbus.EventBus; import com.almasb.fxgl.devtools.DeveloperTools; import com.almasb.fxgl.devtools.profiling.Profiler; import com.almasb.fxgl.event.*; import com.almasb.fxgl.gameplay.GameWorld; import com.almasb.fxgl.gameplay.SaveLoadManager; import com.almasb.fxgl.input.FXGLInputEvent; import com.almasb.fxgl.input.InputModifier; import com.almasb.fxgl.input.UserAction; import com.almasb.fxgl.io.DataFile; import com.almasb.fxgl.io.SaveFile; import com.almasb.fxgl.logging.Logger; import com.almasb.fxgl.logging.SystemLogger; import com.almasb.fxgl.physics.PhysicsWorld; import com.almasb.fxgl.scene.*; import com.almasb.fxgl.scene.menu.MenuEventListener; import com.almasb.fxgl.settings.UserProfile; import com.almasb.fxgl.settings.UserProfileSavable; import com.almasb.fxgl.ui.UIFactory; import com.almasb.fxgl.util.ExceptionHandler; import com.almasb.fxgl.util.FXGLUncaughtExceptionHandler; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.concurrent.Task; import javafx.event.EventHandler; import javafx.geometry.Point2D; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.stage.Stage; import java.time.LocalDateTime; /** * To use FXGL extend this class and implement necessary methods. * The initialization process can be seen below (irrelevant phases are omitted): * <p> * <ol> * <li>Instance fields of YOUR subclass of GameApplication</li> * <li>initSettings()</li> * <li>Services configuration (after this you can safely call FXGL.getService())</li> * <li>initAchievements()</li> * <li>initInput()</li> * <li>preInit()</li> * <p>The following phases are NOT executed on UI thread</p> * <li>initAssets()</li> * <li>initGame() OR loadState()</li> * <li>initPhysics()</li> * <li>initUI()</li> * <li>Start of main game loop execution on UI thread</li> * </ol> * <p> * Unless explicitly stated, methods are not thread-safe and must be * executed on JavaFX Application (UI) Thread. * * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com) */ public abstract class GameApplication extends FXGLApplication implements UserProfileSavable { private static Logger log = SystemLogger.INSTANCE; { log.debug("Starting JavaFX"); setDefaultUncaughtExceptionHandler(new FXGLUncaughtExceptionHandler()); } /** * Set handler for runtime uncaught exceptions. * * @param handler exception handler */ public final void setDefaultUncaughtExceptionHandler(ExceptionHandler handler) { Thread.setDefaultUncaughtExceptionHandler((thread, error) -> { pause(); log.fatal("Uncaught Exception:"); log.fatal(SystemLogger.INSTANCE.errorTraceAsString(error)); log.fatal("Application will now exit"); handler.handle(error); exit(); }); } private ObjectProperty<ApplicationState> state = new SimpleObjectProperty<>(ApplicationState.STARTUP); /** * @return current application state */ public final ApplicationState getState() { return state.get(); } private void setState(ApplicationState appState) { log.debug("State: " + getState() + " -> " + appState); state.set(appState); switch (appState) { case INTRO: getDisplay().setScene(introScene); break; case LOADING: getDisplay().setScene(loadingScene); break; case MAIN_MENU: getDisplay().setScene(mainMenuScene); break; case GAME_MENU: getDisplay().setScene(gameMenuScene); break; case PLAYING: getDisplay().setScene(getGameScene()); break; case PAUSED: // no need to do anything break; default: log.warning("Attempted to set illegal state: " + appState); break; } } private GameWorld gameWorld; private PhysicsWorld physicsWorld; private GameScene gameScene; /** * @return game world */ public final GameWorld getGameWorld() { return gameWorld; } /** * @return physics world */ public final PhysicsWorld getPhysicsWorld() { return physicsWorld; } /** * @return game scene */ public final GameScene getGameScene() { return gameScene; } private SceneFactory sceneFactory; /** * Override to provide custom intro/loading/menu scenes. * * @return scene factory */ protected SceneFactory initSceneFactory() { return new SceneFactory(); } /** * Intro scene, this is shown when the application started, * before menus and game. */ private IntroScene introScene; /** * This scene is shown during app initialization, * i.e. when assets / game are loaded on bg thread. */ private LoadingScene loadingScene; /** * Main menu, this is the menu shown at the start of game. */ private FXGLMenu mainMenuScene; /** * In-game menu, this is shown when menu key pressed during the game. */ private FXGLMenu gameMenuScene; /** * Main game profiler. */ private Profiler profiler; /** * Override to register your achievements. * * <pre> * Example: * * AchievementManager am = getAchievementManager(); * am.registerAchievement(new Achievement("Score Master", "Score 20000 points")); * </pre> */ protected void initAchievements() { } /** * Initialize input, i.e. bind key presses, bind mouse buttons. * * <p> * Note: This method is called prior to any game init to * register input mappings in the menus. * </p> * <pre> * Example: * * Input input = getInput(); * input.addAction(new UserAction("Move Left") { * protected void onAction() { * playerControl.moveLeft(); * } * }, KeyCode.A); * </pre> */ protected abstract void initInput(); /** * This is called after core services are initialized * but before any game init. Called only once * per application lifetime. */ protected void preInit() { } /** * Initialize game assets, such as Texture, Sound, Music, etc. */ protected abstract void initAssets(); /** * Called when MenuEvent.SAVE occurs. * Note: if you enable menus, you are responsible for providing * appropriate serialization of your game state, even if it's ad-hoc null. * * @return data with required info about current state * @throws UnsupportedOperationException if was not overridden */ protected DataFile saveState() { log.warning("Called saveState(), but it wasn't overridden!"); throw new UnsupportedOperationException("Default implementation is not available"); } /** * Called when MenuEvent.LOAD occurs. * Note: if you enable menus, you are responsible for providing * appropriate deserialization of your game state, even if it's ad-hoc no-op. * * @param dataFile previously saved data * @throws UnsupportedOperationException if was not overridden */ protected void loadState(DataFile dataFile) { log.warning("Called loadState(), but it wasn't overridden!"); throw new UnsupportedOperationException("Default implementation is not available"); } /** * Initialize game objects. */ protected abstract void initGame(); /** * Initialize collision handlers, physics properties. */ protected abstract void initPhysics(); /** * Initialize UI objects. */ protected abstract void initUI(); /** * Main loop update phase, most of game logic. * * @param tpf time per frame */ protected abstract void onUpdate(double tpf); private void initGlobalEventHandlers() { log.debug("Initializing global event handlers"); EventBus bus = getEventBus(); Font fpsFont = UIFactory.newFont(24); getMasterTimer().setUpdateListener(event -> { getInput().onUpdateEvent(event); getAudioPlayer().onUpdateEvent(event); getGameWorld().onUpdateEvent(event); getPhysicsWorld().onUpdateEvent(event); getGameScene().onUpdateEvent(event); onUpdate(event.tpf()); // notify rest bus.fireEvent(event); if (getSettings().isFPSShown()) { GraphicsContext g = getGameScene().getGraphicsContext(); g.setFont(fpsFont); g.setFill(Color.RED); String text = String.format("FPS: [%d]\nPerformance: [%d]", getMasterTimer().getFPS(), getMasterTimer().getPerformanceFPS()); g.fillText(text, 0, getHeight() - 40); } }); // Save/Load events bus.addEventHandler(SaveEvent.ANY, event -> { getInput().save(event.getProfile()); getDisplay().save(event.getProfile()); getAudioPlayer().save(event.getProfile()); getAchievementManager().save(event.getProfile()); getMasterTimer().save(event.getProfile()); }); bus.addEventHandler(LoadEvent.ANY, event -> { getInput().load(event.getProfile()); getDisplay().load(event.getProfile()); getAudioPlayer().load(event.getProfile()); getAchievementManager().load(event.getProfile()); if (event.getEventType() != LoadEvent.RESTORE_SETTINGS) { getMasterTimer().load(event.getProfile()); } }); bus.addEventHandler(FXGLEvent.PAUSE, event -> { getInput().onPause(); getMasterTimer().onPause(); setState(ApplicationState.PAUSED); }); bus.addEventHandler(FXGLEvent.RESUME, event -> { getInput().onResume(); getMasterTimer().onResume(); setState(ApplicationState.PLAYING); }); bus.addEventHandler(FXGLEvent.RESET, event -> { getGameWorld().reset(); getGameScene().onWorldReset(); getInput().onReset(); getMasterTimer().onReset(); }); bus.addEventHandler(FXGLEvent.EXIT, event -> { saveProfile(); }); getGameWorld().addWorldListener(getPhysicsWorld()); getGameWorld().addWorldListener(getGameScene()); // we need to add this listener // to publish entity events via our event bus getGameWorld().addWorldListener(new EntityWorldListener() { @Override public void onEntityAdded(Entity entity) { bus.fireEvent(WorldEvent.entityAdded(entity)); } @Override public void onEntityRemoved(Entity entity) { bus.fireEvent(WorldEvent.entityRemoved(entity)); } }); // Scene getGameScene().addEventHandler(MouseEvent.ANY, event -> { FXGLInputEvent e = new FXGLInputEvent(event, getGameScene().screenToGame(new Point2D(event.getSceneX(), event.getSceneY()))); getInput().onInputEvent(e); }); getGameScene().addEventHandler(KeyEvent.ANY, event -> { getInput().onInputEvent(new FXGLInputEvent(event, Point2D.ZERO)); }); bus.addEventHandler(NotificationEvent.ANY, event -> { getAudioPlayer().onNotificationEvent(event); }); bus.addEventHandler(AchievementEvent.ANY, event -> { getNotificationService().onAchievementEvent(event); }); // FXGL App bus.addEventHandler(DisplayEvent.CLOSE_REQUEST, e -> exit()); bus.addEventHandler(DisplayEvent.DIALOG_OPENED, e -> { if (getState() == ApplicationState.INTRO || getState() == ApplicationState.LOADING) return; if (!isMenuOpen()) pause(); getInput().onReset(); }); bus.addEventHandler(DisplayEvent.DIALOG_CLOSED, e -> { if (getState() == ApplicationState.INTRO || getState() == ApplicationState.LOADING) return; if (!isMenuOpen()) resume(); }); } /** * @return true if any menu is open */ public boolean isMenuOpen() { return getState() == ApplicationState.GAME_MENU || getState() == ApplicationState.MAIN_MENU; } /** * @return true if game is paused or menu is open */ public boolean isPaused() { return isMenuOpen() || getState() == ApplicationState.PAUSED; } private boolean canSwitchGameMenu = true; private void onMenuKey(boolean pressed) { if (!pressed) { canSwitchGameMenu = true; return; } if (canSwitchGameMenu) { if (getState() == ApplicationState.GAME_MENU) { canSwitchGameMenu = false; resume(); } else if (getState() == ApplicationState.PLAYING) { canSwitchGameMenu = false; pause(); setState(ApplicationState.GAME_MENU); } else { log.warning("Menu key pressed in unknown state: " + getState()); } } } /** * Creates Main and Game menu scenes. * Registers them with the Display service. * Adds key binding so that scenes can be switched on menu key press. */ private void configureMenu() { mainMenuScene = sceneFactory.newMainMenu(this); gameMenuScene = sceneFactory.newGameMenu(this); MenuEventHandler handler = new MenuEventHandler(); mainMenuScene.setListener(handler); gameMenuScene.setListener(handler); getDisplay().registerScene(mainMenuScene); getDisplay().registerScene(gameMenuScene); EventHandler<KeyEvent> menuKeyHandler = event -> { if (event.getCode() == getSettings().getMenuKey()) { onMenuKey(event.getEventType() == KeyEvent.KEY_PRESSED); } }; getGameScene().addEventHandler(KeyEvent.ANY, menuKeyHandler); gameMenuScene.addEventHandler(KeyEvent.ANY, menuKeyHandler); } private class MenuEventHandler implements MenuEventListener { @Override public void onNewGame() { startNewGame(); } @Override public void onContinue() { saveLoadManager.loadLastModifiedSaveFileTask() .then(file -> saveLoadManager.loadTask(file)) .onSuccess(GameApplication.this::startLoadedGame) .onFailure(getDefaultCheckedExceptionHandler()) .executeAsyncWithDialogFX(getExecutor(), new ProgressDialog("Loading...")); } @Override public void onResume() { resume(); } private void doSave(String saveFileName) { DataFile dataFile = saveState(); SaveFile saveFile = new SaveFile(saveFileName, LocalDateTime.now()); saveLoadManager.saveTask(dataFile, saveFile) .onFailure(getDefaultCheckedExceptionHandler()) .executeAsyncWithDialogFX(getExecutor(), new ProgressDialog("Saving data: " + saveFileName)); } @Override public void onSave() { getDisplay().showInputBox("Enter save file name", DialogPane.ALPHANUM, saveFileName -> { if (saveLoadManager.saveFileExists(saveFileName)) { getDisplay().showConfirmationBox("Overwrite save [" + saveFileName + "]?", yes -> { if (yes) doSave(saveFileName); }); } else { doSave(saveFileName); } }); } @Override public void onLoad(SaveFile saveFile) { getDisplay().showConfirmationBox("Load save [" + saveFile.getName() + "]?\n" + "Unsaved progress will be lost!", yes -> { if (yes) { saveLoadManager.loadTask(saveFile) .onSuccess(GameApplication.this::startLoadedGame) .onFailure(getDefaultCheckedExceptionHandler()) .executeAsyncWithDialogFX(getExecutor(), new ProgressDialog("Loading: " + saveFile.getName())); } }); } @Override public void onDelete(SaveFile saveFile) { getDisplay().showConfirmationBox("Delete save [" + saveFile.getName() + "]?", yes -> { if (yes) { saveLoadManager.deleteSaveFileTask(saveFile) .onFailure(getDefaultCheckedExceptionHandler()) .executeAsyncWithDialogFX(getExecutor(), new ProgressDialog("Deleting: " + saveFile.getName())); } }); } @Override public void onLogout() { getDisplay().showConfirmationBox("Log out?", yes -> { if (yes) { saveProfile(); showProfileDialog(); } }); } @Override public void onMultiplayer() { showMultiplayerDialog(); } @Override public void onExit() { getDisplay().showConfirmationBox("Exit the game?", yes -> { if (yes) exit(); }); } @Override public void onExitToMainMenu() { getDisplay().showConfirmationBox("Exit to Main Menu?\n" + "All unsaved progress will be lost!", yes -> { if (yes) { pause(); reset(); setState(ApplicationState.MAIN_MENU); } }); } } private void configureIntro() { introScene = sceneFactory.newIntro(); introScene.setOnFinished(this::showGame); getDisplay().registerScene(introScene); } /** * Called right before the main stage is shown. */ private void onStageShow() { if (getSettings().isIntroEnabled()) { configureIntro(); setState(ApplicationState.INTRO); introScene.startIntro(); } else { showGame(); } } private void showGame() { if (getSettings().isMenuEnabled()) { configureMenu(); setState(ApplicationState.MAIN_MENU); // we haven't shown the dialog yet so show now if (getSettings().isIntroEnabled()) showProfileDialog(); } else { startNewGame(); } } private void showMultiplayerDialog() { Button btnHost = UIFactory.newButton("Host..."); btnHost.setOnAction(e -> { getDisplay().showMessageBox("NOT SUPPORTED YET"); }); Button btnConnect = UIFactory.newButton("Connect..."); btnConnect.setOnAction(e -> { getDisplay().showMessageBox("NOT SUPPORTED YET"); }); getDisplay().showBox("Multiplayer Options", UIFactory.newText(""), btnHost, btnConnect); } /** * Show profile dialog so that user selects existing or creates new profile. * The dialog is only dismissed when profile is chosen either way. */ private void showProfileDialog() { ChoiceBox<String> profilesBox = UIFactory.newChoiceBox(FXCollections.observableArrayList()); Button btnNew = UIFactory.newButton("NEW"); Button btnSelect = UIFactory.newButton("SELECT"); btnSelect.disableProperty().bind(profilesBox.valueProperty().isNull()); Button btnDelete = UIFactory.newButton("DELETE"); btnDelete.disableProperty().bind(profilesBox.valueProperty().isNull()); btnNew.setOnAction(e -> { getDisplay().showInputBox("New Profile", DialogPane.ALPHANUM, name -> { profileName = name; saveLoadManager = new SaveLoadManager(profileName); getEventBus().fireEvent(new ProfileSelectedEvent(profileName, false)); saveProfile(); }); }); btnSelect.setOnAction(e -> { profileName = profilesBox.getValue(); saveLoadManager = new SaveLoadManager(profileName); saveLoadManager.loadProfileTask() .onSuccess(profile -> { boolean ok = loadFromProfile(profile); if (!ok) { getDisplay().showErrorBox("Profile is corrupted: " + profileName, this::showProfileDialog); } else { saveLoadManager.loadLastModifiedSaveFileTask() .onSuccess(file -> { getEventBus().fireEvent(new ProfileSelectedEvent(profileName, true)); }) .onFailure(error -> { getEventBus().fireEvent(new ProfileSelectedEvent(profileName, false)); }) .executeAsyncWithDialogFX(getExecutor(), new ProgressDialog("Loading last save file")); } }) .onFailure(error -> { getDisplay().showErrorBox("Profile is corrupted: " + profileName + "\nError: " + error.toString(), this::showProfileDialog); }) .executeAsyncWithDialogFX(getExecutor(), new ProgressDialog("Loading Profile: "+ profileName)); }); btnDelete.setOnAction(e -> { String name = profilesBox.getValue(); SaveLoadManager.deleteProfileTask(name) .onSuccess(n -> showProfileDialog()) .onFailure(error -> getDisplay().showErrorBox(error.toString(), this::showProfileDialog)) .executeAsyncWithDialogFX(getExecutor(), new ProgressDialog("Deleting profile: " + name)); }); SaveLoadManager.loadProfileNamesTask() .onSuccess(names -> { profilesBox.getItems().addAll(names); if (!profilesBox.getItems().isEmpty()) { profilesBox.getSelectionModel().selectFirst(); } getDisplay().showBox("Select profile or create new", profilesBox, btnSelect, btnNew, btnDelete); }) .onFailure(e -> { log.warning(e.toString()); getDisplay().showBox("Select profile or create new", profilesBox, btnSelect, btnNew, btnDelete); }) .executeAsyncWithDialogFX(getExecutor(), new ProgressDialog("Loading profiles")); } private void bindScreenshotKey() { getInput().addAction(new UserAction("Screenshot") { @Override protected void onActionBegin() { boolean ok = getDisplay().saveScreenshot(); getNotificationService().pushNotification(ok ? "Screenshot saved" : "Screenshot failed"); } }, KeyCode.P); } private void bindDeveloperKey() { getInput().addAction(new UserAction("Developer Options") { @Override protected void onActionBegin() { log.debug("Scene graph contains " + DeveloperTools.INSTANCE.getChildrenSize(getGameScene().getRoot()) + " nodes"); } }, KeyCode.DIGIT0, InputModifier.CTRL); } private void initFXGL() { initAchievements(); // we call this early to process user input bindings // so we can correctly display them in menus bindScreenshotKey(); bindDeveloperKey(); initInput(); // scan for annotated methods and register them too getInput().scanForUserActions(this); initGlobalEventHandlers(); defaultProfile = createProfile(); preInit(); } @Override public final void start(Stage stage) throws Exception { super.start(stage); // services are now ready, switch to normal logger log = FXGL.getLogger(GameApplication.class); log.debug("Starting Game Application"); gameWorld = FXGL.getInstance(GameWorld.class); physicsWorld = FXGL.getInstance(PhysicsWorld.class); gameScene = FXGL.getInstance(GameScene.class); sceneFactory = initSceneFactory(); loadingScene = sceneFactory.newLoadingScene(); getDisplay().registerScene(loadingScene); getDisplay().registerScene(getGameScene()); initFXGL(); onStageShow(); stage.show(); if (getSettings().isMenuEnabled() && !getSettings().isIntroEnabled()) showProfileDialog(); if (getSettings().isProfilingEnabled()) { profiler = FXGL.newProfiler(); profiler.start(); getEventBus().addEventHandler(FXGLEvent.EXIT, e -> { profiler.stop(); profiler.print(); }); } } /** * Initialize user application. */ private void initApp(Task<?> initTask) { log.debug("Initializing App"); // on first run this is no-op, as for rest this ensures // that even without menus and during direct calls to start*Game() // the system is clean pause(); reset(); setState(ApplicationState.LOADING); loadingScene.bind(initTask); log.debug("Starting FXGL Init Thread"); Thread thread = new Thread(initTask, "FXGL Init Thread"); thread.start(); } /** * (Re-)initializes the user application as new and starts the game. */ protected void startNewGame() { log.debug("Starting new game"); initApp(new InitAppTask(this)); } /** * (Re-)initializes the user application from the given data file and starts the game. * * @param dataFile save data to loadTask from */ protected void startLoadedGame(DataFile dataFile) { log.debug("Starting loaded game"); initApp(new InitAppTask(this, dataFile)); } /** * Stores the default profile data. This is used to restore default settings. */ private UserProfile defaultProfile; /** * Stores current selected profile name for this game. */ private String profileName; /** * Create a user profile with current settings. * * @return user profile */ public final UserProfile createProfile() { UserProfile profile = new UserProfile(getSettings().getTitle(), getSettings().getVersion()); save(profile); getEventBus().fireEvent(new SaveEvent(profile)); return profile; } /** * Load from given user profile. * * @param profile the profile * @return true if loaded successfully, false if couldn't load */ public final boolean loadFromProfile(UserProfile profile) { if (!profile.isCompatible(getSettings().getTitle(), getSettings().getVersion())) return false; load(profile); getEventBus().fireEvent(new LoadEvent(LoadEvent.LOAD_PROFILE, profile)); return true; } /** * Restores default settings, e.g. audio, video, controls. */ public final void restoreDefaultSettings() { getEventBus().fireEvent(new LoadEvent(LoadEvent.RESTORE_SETTINGS, defaultProfile)); } private SaveLoadManager saveLoadManager; /** * @return save load manager */ public SaveLoadManager getSaveLoadManager() { if (saveLoadManager == null) { throw new IllegalStateException("SaveLoadManager is not ready"); } return saveLoadManager; } private void saveProfile() { // if it is null then we are running without menus if (profileName != null) { saveLoadManager.saveProfileTask(createProfile()) .onFailure(e -> log.warning("Failed to save profile: " + profileName + " - " + e)) // we execute synchronously to avoid incomplete save since we might be shutting down .execute(); } } @Override public void save(UserProfile profile) { // if there is a need for data save // log.debug("Saving data to profile"); // UserProfile.Bundle bundle = new UserProfile.Bundle("game"); // bundle.put("...", ...); // bundle.log(); // profile.putBundle(bundle); } @Override public void load(UserProfile profile) { // log.debug("Loading data from profile"); // UserProfile.Bundle bundle = profile.getBundle("game"); // bundle.log(); } }
package org.bouncycastle.asn1; import java.io.IOException; import java.util.Enumeration; /** * BER TaggedObject - in ASN.1 notation this is any object preceded by * a [n] where n is some number - these are assumed to follow the construction * rules (as with sequences). */ public class BERTaggedObject extends DERTaggedObject { /** * @param tagNo the tag number for this object. * @param obj the tagged object. */ public BERTaggedObject( int tagNo, DEREncodable obj) { super(tagNo, obj); } /** * @param explicit true if an explicitly tagged object. * @param tagNo the tag number for this object. * @param obj the tagged object. */ public BERTaggedObject( boolean explicit, int tagNo, DEREncodable obj) { super(explicit, tagNo, obj); } /** * create an implicitly tagged object that contains a zero * length sequence. */ public BERTaggedObject( int tagNo) { super(false, tagNo, new BERSequence()); } void encode( DEROutputStream out) throws IOException { if (out instanceof ASN1OutputStream || out instanceof BEROutputStream) { out.writeTag(CONSTRUCTED | TAGGED, tagNo); out.write(0x80); if (!empty) { if (!explicit) { Enumeration e; if (obj instanceof ASN1OctetString) { if (obj instanceof BERConstructedOctetString) { e = ((BERConstructedOctetString)obj).getObjects(); } else { ASN1OctetString octs = (ASN1OctetString)obj; BERConstructedOctetString berO = new BERConstructedOctetString(octs.getOctets()); e = berO.getObjects(); } } else if (obj instanceof ASN1Sequence) { e = ((ASN1Sequence)obj).getObjects(); } else if (obj instanceof ASN1Set) { e = ((ASN1Set)obj).getObjects(); } else { throw new RuntimeException("not implemented: " + obj.getClass().getName()); } while (e.hasMoreElements()) { out.writeObject(e.nextElement()); } } else { out.writeObject(obj); } } out.write(0x00); out.write(0x00); } else { super.encode(out); } } }
package org.freecompany.redline.ant; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.net.URL; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.freecompany.redline.Builder; import org.freecompany.redline.header.Architecture; import org.freecompany.redline.header.Header; import org.freecompany.redline.header.Os; import org.freecompany.redline.header.RpmType; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.ArchiveFileSet; import org.apache.tools.ant.types.TarFileSet; import org.apache.tools.ant.types.ZipFileSet; import org.freecompany.redline.payload.Directive; import static org.freecompany.redline.Util.normalizePath; import static org.freecompany.redline.header.Architecture.NOARCH; import static org.freecompany.redline.header.Os.LINUX; import static org.freecompany.redline.header.RpmType.BINARY; /** * Ant task for creating an RPM file. */ public class RedlineTask extends Task { public static final String NAMESPACE = "http://freecompany.org/namespace/redline"; protected String name; protected String version; protected String group; protected String release = "1"; protected String host; protected String summary = ""; protected String description = ""; protected String license = ""; protected String packager = System.getProperty( "user.name", ""); protected String distribution = ""; protected String vendor = ""; protected String url = ""; protected String sourcePackage = null; protected String provides; protected RpmType type = BINARY; protected Architecture architecture = NOARCH; protected Os os = LINUX; protected File destination; protected List< ArchiveFileSet> filesets = new ArrayList< ArchiveFileSet>(); protected List< Link> links = new ArrayList< Link>(); protected List< Depends> depends = new ArrayList< Depends>(); protected File preInstallScript; protected File postInstallScript; protected File preUninstallScript; protected File postUninstallScript; public RedlineTask() { try { host = InetAddress.getLocalHost().getHostName(); } catch ( UnknownHostException e) { host = ""; } } @Override public void execute() throws BuildException { if ( name == null) throw new BuildException( "Attribute 'name' is required."); if ( version == null) throw new BuildException( "Attribute 'version' is required."); if ( group == null) throw new BuildException( "Attribute 'group' is required."); Builder builder = new Builder(); builder.setPackage( name, version, release); builder.setType( type); builder.setPlatform( architecture, os); builder.setGroup( group); builder.setBuildHost( host); builder.setSummary( summary); builder.setDescription( description); builder.setLicense( license); builder.setPackager( packager); builder.setDistribution( distribution); builder.setVendor( vendor); builder.setUrl( url); builder.setProvides( provides == null ? name : provides); if (sourcePackage != null) { builder.addHeaderEntry(Header.HeaderTag.SOURCERPM, sourcePackage); } try { builder.setPreInstallScript( preInstallScript); builder.setPostInstallScript( postInstallScript); builder.setPreUninstallScript( preUninstallScript); builder.setPostUninstallScript( postUninstallScript); for ( ArchiveFileSet fileset : filesets) { File archive = fileset.getSrc( getProject()); String prefix = normalizePath( fileset.getPrefix( getProject())); if ( !prefix.endsWith( "/")) prefix += "/"; DirectoryScanner scanner = fileset.getDirectoryScanner( getProject()); int dirmode = fileset.getDirMode( getProject()) & 07777; String username = null; String group = null; Directive directive = null; if (fileset instanceof TarFileSet) { TarFileSet tarFileSet = (TarFileSet)fileset; username = tarFileSet.getUserName(); group = tarFileSet.getGroup(); if (fileset instanceof RpmFileSet) { RpmFileSet rpmFileSet = (RpmFileSet)fileset; directive = rpmFileSet.getDirective(); } } // include any directories, including empty ones, duplicates will be ignored when we scan included files for (String entry : scanner.getIncludedDirectories()) { String dir = normalizePath(prefix + entry); if (!entry.equals("")) builder.addDirectory(dir, dirmode, directive, username, group, true); } for ( String entry : scanner.getIncludedFiles()) { if ( archive != null) { URL url = new URL( "jar:" + archive.toURL() + "!/" + entry); builder.addURL( prefix + entry, url, fileset.getFileMode( getProject()) & 07777, dirmode, directive, username, group); } else { File file = new File( scanner.getBasedir(), entry); builder.addFile(prefix + entry, file, fileset.getFileMode( getProject()) & 07777, dirmode, directive, username, group); } } } for ( Link link : links) builder.addLink( link.getPath(), link.getTarget(), link.getPermissions()); for ( Depends dependency : depends) builder.addDependencyMore( dependency.getName(), dependency.getVersion()); log( "Created rpm: " + builder.build( destination)); } catch ( IOException e) { throw new BuildException( "Error packaging distribution files.", e); } catch ( NoSuchAlgorithmException e) { throw new BuildException( "This system does not support MD5 digests.", e); } } public void restrict( String name) { for ( Iterator< Depends> i = depends.iterator(); i.hasNext();) { final Depends dependency = i.next(); if ( dependency.getName().equals( name)) i.remove(); } } public void setName( String name) { this.name = name; } public void setType( String type) { this.type = RpmType.valueOf( type); } public void setArchitecture( String architecture) { this.architecture = Architecture.valueOf( architecture); } public void setOs( String os) { this.os = Os.valueOf( os); } public void setVersion( String version) { this.version = version; } public void setRelease( String release) { this.release = release; } public void setGroup( String group) { this.group = group; } public void setHost( String host) { this.host = host; } public void setSummary( String summary) { this.summary = summary; } public void setDescription( String description) { this.description = description; } public void setLicense( String license) { this.license = license; } public void setPackager( String packager) { this.packager = packager; } public void setDistribution( String distribution) { this.distribution = distribution; } public void setVendor( String vendor) { this.vendor = vendor; } public void setUrl( String url) { this.url = url; } public void setProvides( String provides) { this.provides = provides; } public void setDestination( File destination) { this.destination = destination; } public void addZipfileset( ZipFileSet fileset) { filesets.add( fileset); } public void addTarfileset( TarFileSet fileset) { filesets.add( fileset); } public void addRpmfileset( RpmFileSet fileset) { filesets.add( fileset); } public void addLink( Link link) { links.add( link); } public void addDepends( Depends dependency) { depends.add( dependency); } public void setPreInstallScript( File preInstallScript) { this.preInstallScript = preInstallScript; } public void setPostInstallScript( File postInstallScript) { this.postInstallScript = postInstallScript; } public void setPreUninstallScript( File preUninstallScript) { this.preUninstallScript = preUninstallScript; } public void setPostUninstallScript( File postUninstallScript) { this.postUninstallScript = postUninstallScript; } public void setSourcePackage( String sourcePackage) { this.sourcePackage = sourcePackage; } }
package com.analogmountains.flume; import static com.analogmountains.flume.MongoSinkConstants.BATCH_SIZE; import static com.analogmountains.flume.MongoSinkConstants.COLLECTION; import static com.analogmountains.flume.MongoSinkConstants.DATABASE; import static com.analogmountains.flume.MongoSinkConstants.DEFAULT_BATCH_SIZE; import static com.analogmountains.flume.MongoSinkConstants.HOSTNAMES; import static com.analogmountains.flume.MongoSinkConstants.PASSWORD; import static com.analogmountains.flume.MongoSinkConstants.USER; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.flume.Channel; import org.apache.flume.Context; import org.apache.flume.Event; import org.apache.flume.EventDeliveryException; import org.apache.flume.Transaction; import org.apache.flume.conf.Configurable; import org.apache.flume.instrumentation.SinkCounter; import org.apache.flume.sink.AbstractSink; import org.bson.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Throwables; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class MongoSink extends AbstractSink implements Configurable { private static final Logger logger = LoggerFactory.getLogger(MongoSink.class); private MongoClient client; private MongoCollection<Document> collection; private List<ServerAddress> seeds; private MongoCredential credential; private String databaseName; private String collectionName; private int batchSize = DEFAULT_BATCH_SIZE; private SinkCounter sinkCounter; @Override public Status process() throws EventDeliveryException { Status status = Status.READY; List<Document> documents = new ArrayList<Document>(batchSize); Channel channel = getChannel(); Transaction transaction = channel.getTransaction(); try { transaction.begin(); long count; for (count = 0; count < batchSize; ++count) { Event event = channel.take(); if (event == null) { break; } String jsonEvent = new String(event.getBody(), StandardCharsets.UTF_8); documents.add(Document.parse(jsonEvent)); } if (count <= 0) { sinkCounter.incrementBatchEmptyCount(); status = Status.BACKOFF; } else { if (count < batchSize) { sinkCounter.incrementBatchUnderflowCount(); status = Status.BACKOFF; } else { sinkCounter.incrementBatchCompleteCount(); } sinkCounter.addToEventDrainAttemptCount(count); collection.insertMany(documents); } transaction.commit(); sinkCounter.addToEventDrainSuccessCount(count); } catch (Throwable t) { try { transaction.rollback(); } catch (Exception e) { logger.error("Exception during transaction rollback.", e); } logger.error("Failed to commit transaction. Transaction rolled back.", t); if (t instanceof Error || t instanceof RuntimeException) { Throwables.propagate(t); } else { throw new EventDeliveryException( "Failed to commit transaction. Transaction rolled back.", t); } } finally { if (transaction != null) { transaction.close(); } } return status; } @Override public synchronized void start() { logger.info("Starting MongoDB sink"); sinkCounter.start(); try { client = new MongoClient(seeds, Arrays.asList(credential)); MongoDatabase database = client.getDatabase(databaseName); collection = database.getCollection(collectionName); sinkCounter.incrementConnectionCreatedCount(); } catch (Exception e) { logger.error("Exception while connecting to MongoDB", e); sinkCounter.incrementConnectionFailedCount(); if (client != null) { client.close(); sinkCounter.incrementConnectionClosedCount(); } } super.start(); logger.info("MongoDB sink started"); } @Override public synchronized void stop() { logger.info("Stopping MongoDB sink"); if (client != null) { client.close(); } sinkCounter.incrementConnectionClosedCount(); sinkCounter.stop(); super.stop(); logger.info("MongoDB sink stopped"); } @Override public void configure(Context context) { seeds = getSeeds(context.getString(HOSTNAMES)); credential = getCredential(context); databaseName = context.getString(DATABASE); collectionName = context.getString(COLLECTION); batchSize = context.getInteger(BATCH_SIZE, DEFAULT_BATCH_SIZE); if (sinkCounter == null) { sinkCounter = new SinkCounter(getName()); } } private List<ServerAddress> getSeeds(String seedsString) { List<ServerAddress> seeds = new LinkedList<ServerAddress>(); String[] seedStrings = StringUtils.deleteWhitespace(seedsString).split(","); for (String seed : seedStrings) { String[] hostAndPort = seed.split(":"); String host = hostAndPort[0]; int port; if (hostAndPort.length == 2) { port = Integer.parseInt(hostAndPort[1]); } else { port = 27017; } seeds.add(new ServerAddress(host, port)); } return seeds; } private MongoCredential getCredential(Context context) { String user = context.getString(USER); String database = context.getString(DATABASE); String password = context.getString(PASSWORD); return MongoCredential.createCredential(user, database, password.toCharArray()); } }
package org.broad.igv.bigwig; import org.broad.igv.Globals; import org.broad.igv.bbfile.*; import org.broad.igv.data.*; import org.broad.igv.feature.*; import org.broad.igv.feature.genome.Genome; import org.broad.igv.track.FeatureSource; import org.broad.igv.track.TrackType; import org.broad.igv.track.WindowFunction; import org.broad.igv.ui.color.ColorUtilities; import org.broad.igv.util.ParsingUtils; import org.broad.igv.util.collections.FloatArrayList; import org.broad.igv.util.collections.IntArrayList; import org.broad.tribble.Feature; import java.io.IOException; import java.util.*; /** * A hybrid source, implements both DataSource and FeatureSource. Way of the future? * * @author jrobinso * @date Jun 19, 2011 */ public class BigWigDataSource extends AbstractDataSource implements FeatureSource { final int screenWidth = 1000; // TODO use actual screen width Collection<WindowFunction> availableWindowFunctions = Arrays.asList(WindowFunction.min, WindowFunction.mean, WindowFunction.max); WindowFunction windowFunction = WindowFunction.mean; BBFileReader reader; private BBZoomLevels levels; // Feature visibility window (for bigBed) int featureVisiblityWindow = -1; private List<LocusScore> wholeGenomeScores; // Lookup table to support chromosome aliasing. TODO -- move this up to a higher level, to share private Map<String, String> chrNameMap = new HashMap(); public BigWigDataSource(BBFileReader reader, Genome genome) throws IOException { super(genome); this.reader = reader; levels = reader.getZoomLevels(); // Assume 1000 pixel screen, pick visibility level to be @ highest resolution zoom. // TODO -- something smarter, like scaling by actual density if (levels.getZoomHeaderCount() > 0) { BBZoomLevelHeader firstLevel = levels.getZoomLevelHeaders().get(0); featureVisiblityWindow = firstLevel.getReductionLevel() * 2000; } if (genome != null) { Collection<String> chrNames = reader.getChromosomeNames(); for (String chr : chrNames) { String igvChr = genome.getChromosomeAlias(chr); if (igvChr != null && !igvChr.equals(chr)) { chrNameMap.put(igvChr, chr); } } } } public double getDataMax() { return 100; } public double getDataMin() { return 0; } public TrackType getTrackType() { return TrackType.OTHER; } public void setWindowFunction(WindowFunction statType) { // Invalidate caches wholeGenomeScores = null; this.windowFunction = statType; } public boolean isLogNormalized() { return false; } public void refreshData(long timestamp) { } @Override public int getLongestFeature(String chr) { return 0; } public WindowFunction getWindowFunction() { return windowFunction; } public Collection<WindowFunction> getAvailableWindowFunctions() { return availableWindowFunctions; } @Override protected List<LocusScore> getPrecomputedSummaryScores(String chr, int start, int end, int zoom) { if (chr.equals(Globals.CHR_ALL)) { return getWholeGenomeScores(); } else { return getZoomSummaryScores(chr, start, end, zoom); } } /** * Return the zoom level that most closely matches the given resolution. Resolution is in BP / Pixel. * * * @param resolution * @return */ private BBZoomLevelHeader getZoomLevelForScale(double resolution) { final ArrayList<BBZoomLevelHeader> headers = levels.getZoomLevelHeaders(); BBZoomLevelHeader lastLevel = null; for (BBZoomLevelHeader zlHeader : headers) { int reductionLevel = zlHeader.getReductionLevel(); if (reductionLevel > resolution) { return lastLevel == null ? zlHeader : lastLevel; } lastLevel = zlHeader; } return headers.get(headers.size() - 1); } private BBZoomLevelHeader getLowestResolutionLevel() { final ArrayList<BBZoomLevelHeader> headers = levels.getZoomLevelHeaders(); return headers.get(headers.size() - 1); } protected List<LocusScore> getZoomSummaryScores(String chr, int start, int end, int zoom) { Chromosome c = genome.getChromosome(chr); if (c == null) return null; double nBins = Math.pow(2, zoom); double scale = c.getLength() / (nBins * 700); BBZoomLevelHeader zlHeader = getZoomLevelForScale(scale); int bbLevel = zlHeader.getZoomLevel(); int reductionLevel = zlHeader.getReductionLevel(); // If we are at the highest precomputed resolution compare to the requested resolution. If they differ // by more than a factor of 2 compute "on the fly" String tmp = chrNameMap.get(chr); String querySeq = tmp == null ? chr : tmp; if (reader.isBigBedFile() || bbLevel > 1 || (bbLevel == 1 && (reductionLevel / scale) < 2)) { ArrayList<LocusScore> scores = new ArrayList(1000); ZoomLevelIterator zlIter = reader.getZoomLevelIterator(bbLevel, querySeq, start, querySeq, end, false); while (zlIter.hasNext()) { ZoomDataRecord rec = zlIter.next(); float v = getValue(rec); BasicScore bs = new BasicScore(rec.getChromStart(), rec.getChromEnd(), v); scores.add(bs); } return scores; } else { // No precomputed scores for this resolution level return null; } } private float getValue(ZoomDataRecord rec) { float v; switch (windowFunction) { case min: v = rec.getMinVal(); break; case max: v = rec.getMaxVal(); break; default: v = rec.getMeanVal(); } return v; } RawDataInterval currentInterval = null; @Override protected synchronized DataTile getRawData(String chr, int start, int end) { if (chr.equals(Globals.CHR_ALL)) { return null; } if (currentInterval != null && currentInterval.contains(chr, start, end)) { return currentInterval.tile; } // TODO -- fetch data directly in arrays to avoid creation of multiple "WigItem" objects? IntArrayList startsList = new IntArrayList(100000); IntArrayList endsList = new IntArrayList(100000); FloatArrayList valuesList = new FloatArrayList(100000); String chrAlias = chrNameMap.containsKey(chr) ? chrNameMap.get(chr) : chr; Iterator<WigItem> iter = reader.getBigWigIterator(chrAlias, start, chrAlias, end, false); while (iter.hasNext()) { WigItem wi = iter.next(); startsList.add(wi.getStartBase()); endsList.add(wi.getEndBase()); valuesList.add(wi.getWigValue()); } DataTile tile = new DataTile(startsList.toArray(), endsList.toArray(), valuesList.toArray(), null); currentInterval = new RawDataInterval(chr, start, end, tile); return tile; } private List<LocusScore> getWholeGenomeScores() { if (genome.getHomeChromosome().equals(Globals.CHR_ALL)) { if (wholeGenomeScores == null) { double scale = genome.getLength() / screenWidth; wholeGenomeScores = new ArrayList<LocusScore>(); for (Chromosome chr : genome.getChromosomes()) { BBZoomLevelHeader lowestResHeader = this.getZoomLevelForScale(scale); int lastGenomeEnd = -1; String chrName = chr.getName(); int end = chr.getLength(); String tmp = chrNameMap.get(chrName); String querySeq = tmp == null ? chrName : tmp; ZoomLevelIterator zlIter = reader.getZoomLevelIterator( lowestResHeader.getZoomLevel(), querySeq, 0, querySeq, end, false); while (zlIter.hasNext()) { ZoomDataRecord rec = zlIter.next(); int genomeStart = genome.getGenomeCoordinate(chrName, rec.getChromStart()); if (genomeStart < lastGenomeEnd) { continue; } int genomeEnd = genome.getGenomeCoordinate(chrName, rec.getChromEnd()); float value = getValue(rec); wholeGenomeScores.add(new BasicScore(genomeStart, genomeEnd, value)); lastGenomeEnd = genomeEnd; } } } return wholeGenomeScores; } else { return null; } } public Iterator getFeatures(String chr, int start, int end) throws IOException { String tmp = chrNameMap.get(chr); String querySeq = tmp == null ? chr : tmp; BigBedIterator bedIterator = reader.getBigBedIterator(querySeq, start, chr, end, false); return new WrappedIterator(bedIterator); } public List<LocusScore> getCoverageScores(String chr, int start, int end, int zoom) { String tmp = chrNameMap.get(chr); String querySeq = tmp == null ? chr : tmp; return this.getSummaryScoresForRange(querySeq, start, end, zoom); } public int getFeatureWindowSize() { return this.featureVisiblityWindow; } public void setFeatureWindowSize(int size) { this.featureVisiblityWindow = size; } public Class getFeatureClass() { return null; //To change body of implemented methods use File | Settings | File Templates. } public static class WrappedIterator implements Iterator<Feature> { BigBedIterator bedIterator; public WrappedIterator(BigBedIterator bedIterator) { this.bedIterator = bedIterator; } public boolean hasNext() { return bedIterator.hasNext(); //To change body of implemented methods use File | Settings | File Templates. } public Feature next() { BedFeature feat = bedIterator.next(); BasicFeature feature = new BasicFeature(feat.getChromosome(), feat.getStartBase(), feat.getEndBase()); String[] restOfFields = feat.getRestOfFields(); if (restOfFields != null && restOfFields.length > 0) { decode(feature, restOfFields); } return feature; } public void remove() { //To change body of implemented methods use File | Settings | File Templates. } } static class RawDataInterval { String chr; int start; int end; DataTile tile; RawDataInterval(String chr, int start, int end, DataTile tile) { this.chr = chr; this.start = start; this.end = end; this.tile = tile; } public boolean contains(String chr, int start, int end) { return chr.equals(this.chr) && start >= this.start && end <= this.end; } } /////////// Decoder for BED features private static void decode(BasicFeature feature, String[] restOfFields) { int tokenCount = restOfFields.length; // The rest of the columns are optional. Stop parsing upon encountering // a non-expected value // Name if (tokenCount > 0) { String name = restOfFields[0].replaceAll("\"", ""); feature.setName(name); feature.setIdentifier(name); } // Score if (tokenCount > 1) { try { float score = Float.parseFloat(restOfFields[1]); feature.setScore(score); } catch (NumberFormatException numberFormatException) { // Unexpected, but does not invalidate the previous values. // Stop parsing the line here but keep the feature // Don't log, would just slow parsing down. return; } } // Strand if (tokenCount > 2) { String strandString = restOfFields[2].trim(); char strand = (strandString.length() == 0) ? ' ' : strandString.charAt(0); if (strand == '-') { feature.setStrand(Strand.NEGATIVE); } else if (strand == '+') { feature.setStrand(Strand.POSITIVE); } else { feature.setStrand(Strand.NONE); } } if (tokenCount > 5) { String colorString = restOfFields[5]; feature.setColor(ColorUtilities.stringToColor(colorString)); } // Coding information is optional if (tokenCount > 8) { Strand strand = feature.getStrand(); int cdStart = Integer.parseInt(restOfFields[3]); int cdEnd = Integer.parseInt(restOfFields[4]); int exonCount = Integer.parseInt(restOfFields[6]); String[] exonSizes = new String[exonCount]; String[] startsBuffer = new String[exonCount]; ParsingUtils.split(restOfFields[7], exonSizes, ','); ParsingUtils.split(restOfFields[8], startsBuffer, ','); int exonNumber = (strand == Strand.NEGATIVE ? exonCount : 1); int start = feature.getStart(); String chr = feature.getChr(); if (startsBuffer.length == exonSizes.length) { for (int i = 0; i < startsBuffer.length; i++) { int exonStart = start + Integer.parseInt(startsBuffer[i]); int exonEnd = exonStart + Integer.parseInt(exonSizes[i]); Exon exon = new Exon(chr, exonStart, exonEnd, strand); exon.setCodingStart(cdStart); exon.setCodingEnd(cdEnd); exon.setNumber(exonNumber); feature.addExon(exon); if (strand == Strand.NEGATIVE) { exonNumber } else { exonNumber++; } } } } } }
package org.broad.igv.util; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.log4j.Logger; import org.broad.igv.gs.GSLoginDialog; import org.broad.igv.gs.GSUtils; import org.broad.igv.ui.IGV; import java.awt.*; import java.io.*; import java.net.URL; /** * New version of IGVHttpUtils built on Apache HttpClient 4.1. Currently this version is only used for GenomeSpace * connections, which was its intention, but eventually all client connections will use this class and IGVHttpUtils * will be eliminated. * * @author jrobinso * @date Jun 9, 2011 */ public class IGVHttpClientUtils { private static Logger log = Logger.getLogger(IGVHttpClientUtils.class); static DefaultHttpClient client = new DefaultHttpClient(); public static void setProxy(String proxyHost, int proxyPort, boolean auth, String user, String pw) { if (client == null) client = new DefaultHttpClient(); if (proxyHost != null) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); log.info("Proxy settings: " + proxyHost + ":" + proxyPort); } if (auth) { client.getCredentialsProvider().setCredentials( new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(user, pw)); } } /** * Shutdown client and free all resources. Called upon application exit. */ public static void shutdown() { client.getConnectionManager().shutdown(); client = null; } public static boolean downloadFile(String url, File outputFile) throws IOException { log.info("Downloading " + url + " to " + outputFile.getAbsolutePath()); HttpGet httpget = new HttpGet(url); HttpResponse response = client.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { final long contentLength = entity.getContentLength(); log.info("Content length = " + contentLength); InputStream is = null; OutputStream out = null; try { is = entity.getContent(); out = new FileOutputStream(outputFile); byte[] buf = new byte[64 * 1024]; int downloaded = 0; int bytesRead = 0; while ((bytesRead = is.read(buf)) != -1) { out.write(buf, 0, bytesRead); downloaded += bytesRead; } log.info("Download complete. Total bytes downloaded = " + downloaded); } finally { if (is != null) is.close(); if (out != null) { out.flush(); out.close(); } } long fileLength = outputFile.length(); log.info("File length = " + fileLength); return contentLength <= 0 || contentLength == fileLength; } return false; } /** * Execute a get on the url and return the response stream. It is the responsibility of the caller to * close the stream. * * @param url * @return * @throws IOException */ public static InputStream openGSConnectionStream(URL url) throws IOException { HttpResponse response = executeGet(url); return response.getEntity().getContent(); } /** * Execute a get on the url and return the header field value. * * @param url * @return * @throws IOException */ public static String getGSHeaderField(URL url, String key) throws IOException { HttpResponse response = executeGet(url); return response.getFirstHeader(key).getValue(); } private static HttpResponse executeGet(URL url) throws IOException { if (client == null) client = new DefaultHttpClient(); HttpGet getMethod = null; try { if (GSUtils.isGenomeSpace(url)) { GSUtils.checkForCookie(client, url); } getMethod = new HttpGet(url.toExternalForm()); //getMethod.setDoAuthentication(true); client.getParams().setParameter("http.protocol.allow-circular-redirects", true); HttpResponse response = client.execute(getMethod); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { getMethod.abort(); // Try again client.getCredentialsProvider().clear(); login(url); return executeGet(url); } if (statusCode != 200) { getMethod.abort(); throw new RuntimeException("Error connecting. Status code = " + statusCode); } return response; } catch (RuntimeException e) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection immediately. THis happens automatically for an IOException if (getMethod != null) getMethod.abort(); throw e; } } private static void login(URL url) { Frame owner = IGV.hasInstance() ? IGV.getMainFrame() : null; String userpass = getGSUserPass(owner); if (userpass == null) { throw new RuntimeException("Access denied to: " + url.toString()); } UsernamePasswordCredentials GENOME_SPACE_CREDS = new UsernamePasswordCredentials(userpass); String host = GSUtils.isGenomeSpace(url) ? GSUtils.GENOME_SPACE_ID_SERVER : url.getHost(); client.getCredentialsProvider().setCredentials( new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM), GENOME_SPACE_CREDS); if (GSUtils.isGenomeSpace(url)) { // Get the genomespace token try { HttpGet httpget = new HttpGet(GSUtils.identityServerUrl); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(httpget, responseHandler); if (responseBody != null && responseBody.length() > 0) { String[] tokens = userpass.split(":"); String user = tokens[0]; GSUtils.saveLoginForSSO(responseBody, user); } } catch (IOException e) { log.error("Error fetching GS token", e); } } } public static String getGSUserPass(Frame owner) { GSLoginDialog dlg = new GSLoginDialog(owner); dlg.setVisible(true); if (dlg.isCanceled()) { return null; } else { final String userString = dlg.getUsername(); final String userPass = new String(dlg.getPassword()); return userString + ":" + userPass; } } }
package org.ensembl.healthcheck; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import org.ensembl.healthcheck.testcase.EnsTestCase; import org.ensembl.healthcheck.util.DBUtils; import org.ensembl.healthcheck.util.Utils; /** * ReportManager is the main class for reporting in the Ensj Healthcheck system. It provides methods for storing reports - single * items of information - and retrieving them in various formats. */ public class ReportManager { /** A hash of lists keyed on the test name. */ protected static Map reportsByTest = new HashMap(); /** A hash of lists keyed on the database name */ protected static Map reportsByDatabase = new HashMap(); /** The logger to use for this class */ protected static Logger logger = Logger.getLogger("HealthCheckLogger"); /** * The maximum number of lines to store to prevent very verbose test cases causing memory problems */ protected static final int MAX_BUFFER_SIZE = 2000; private static boolean bufferSizeWarningPrinted = false; private static Reporter reporter; private static boolean usingDatabase = false; private static Connection outputDatabaseConnection; private static long sessionID = -1; // hide constructor to stop instantiation private ReportManager() { } /** * Set the reporter for this ReportManager. * * @param rep * The Reporter to set. */ public static void setReporter(Reporter rep) { reporter = rep; } /** * Should be called before a test case is run. * * @param testCase * The testcase to be run. * @param dbre * The database that testCase will run on. */ public static void startTestCase(EnsTestCase testCase, DatabaseRegistryEntry dbre) { if (reporter != null) { reporter.startTestCase(testCase, dbre); } } /** * Should be called immediately after a test case has run. * * @param testCase * The testcase that was run. * @param result * The result of the test case. * @param dbre * The database which the test case was run on. */ public static void finishTestCase(EnsTestCase testCase, boolean result, DatabaseRegistryEntry dbre) { if (reporter != null) { reporter.finishTestCase(testCase, result, dbre); } } /** * Add a test case report. * * @param report * The ReportLine to add. */ public static void add(ReportLine report) { if (usingDatabase) { checkAndAddToDatabase(report); return; } String testCaseName = report.getTestCaseName(); String databaseName = report.getDatabaseName(); ArrayList lines; // add to each hash if (testCaseName != null && testCaseName.length() > 0) { // create the lists if they're not there already if (reportsByTest.get(testCaseName) == null) { lines = new ArrayList(); lines.add(report); reportsByTest.put(testCaseName, lines); } else { // get the relevant list, update it, and re-add it lines = (ArrayList) reportsByTest.get(testCaseName); // prevent the buffer getting too big if (lines.size() > MAX_BUFFER_SIZE) { if (!bufferSizeWarningPrinted) { System.err.println("\n\nReportManager has reached its maximum buffer size (" + MAX_BUFFER_SIZE + " lines) - no more output will be stored\n"); bufferSizeWarningPrinted = true; } } else { // buffer small enough, add it lines.add(report); reportsByTest.put(testCaseName, lines); } } } else { logger.warning("Cannot add report with test case name not set"); } if (databaseName != null && databaseName.length() > 0) { // create the lists if they're not there already if (reportsByDatabase.get(databaseName) == null) { lines = new ArrayList(); lines.add(report); reportsByDatabase.put(databaseName, lines); } else { // get the relevant list, update it, and re-add it lines = (ArrayList) reportsByDatabase.get(databaseName); lines.add(report); reportsByDatabase.put(databaseName, lines); } } if (reporter != null) { reporter.message(report); } } // add /** * Convenience method for storing reports, intended to be easy to call from an EnsTestCase. * * @param testCase * The test case filing the report. * @param con * The database connection involved. * @param level * The level of this report. * @param message * The message to be reported. */ public static void report(EnsTestCase testCase, Connection con, int level, String message) { // this may be called when there is no DB connection String dbName = (con == null) ? "no_database" : DBUtils.getShortDatabaseName(con); add(new ReportLine(testCase.getTestName(), dbName, level, message, testCase.getTeamResponsible(), testCase.getSecondTeamResponsible())); } // report /** * Convenience method for storing reports, intended to be easy to call from an EnsTestCase. * * @param testCase * The test case filing the report. * @param dbName * The name of the database involved. * @param level * The level of this report. * @param message * The message to be reported. */ public static void report(EnsTestCase testCase, String dbName, int level, String message) { add(new ReportLine(testCase.getTestName(), dbName, level, message, testCase.getTeamResponsible(), testCase.getSecondTeamResponsible())); } // report /** * Store a ReportLine with a level of ReportLine.INFO. * * @param testCase * The test case filing the report. * @param con * The database connection involved. * @param message * The message to be reported. */ public static void problem(EnsTestCase testCase, Connection con, String message) { report(testCase, con, ReportLine.PROBLEM, message); } // problem /** * Store a ReportLine with a level of ReportLine.PROBLEM. * * @param testCase * The test case filing the report. * @param dbName * The name of the database involved. * @param message * The message to be reported. */ public static void problem(EnsTestCase testCase, String dbName, String message) { report(testCase, dbName, ReportLine.PROBLEM, message); } // problem /** * Store a ReportLine with a level of ReportLine.INFO. * * @param testCase * The test case filing the report. * @param con * The database connection involved. * @param message * The message to be reported. */ public static void info(EnsTestCase testCase, Connection con, String message) { report(testCase, con, ReportLine.INFO, message); } // info /** * Store a ReportLine with a level of ReportLine.INFO. * * @param testCase * The test case filing the report. * @param dbName * The name of the database involved. * @param message * The message to be reported. */ public static void info(EnsTestCase testCase, String dbName, String message) { report(testCase, dbName, ReportLine.INFO, message); } // info /** * Store a ReportLine with a level of ReportLine.SUMMARY. * * @param testCase * The test case filing the report. * @param con * The database connection involved. * @param message * The message to be reported. */ public static void warning(EnsTestCase testCase, Connection con, String message) { report(testCase, con, ReportLine.WARNING, message); } // summary /** * Store a ReportLine with a level of ReportLine.SUMMARY. * * @param testCase * The test case filing the report. * @param dbName * The name of the database involved. * @param message * The message to be reported. */ public static void warning(EnsTestCase testCase, String dbName, String message) { report(testCase, dbName, ReportLine.WARNING, message); } // summary /** * Store a ReportLine with a level of ReportLine.CORRECT. * * @param testCase * The test case filing the report. * @param con * The database connection involved. * @param message * The message to be reported. */ public static void correct(EnsTestCase testCase, Connection con, String message) { report(testCase, con, ReportLine.CORRECT, message); } // summary /** * Store a ReportLine with a level of ReportLine.CORRECT. * * @param testCase * The test case filing the report. * @param dbName * The name of the database involved. * @param message * The message to be reported. */ public static void correct(EnsTestCase testCase, String dbName, String message) { report(testCase, dbName, ReportLine.CORRECT, message); } // summary /** * Get a HashMap of all the reports, keyed on test case name. * * @return The HashMap of all the reports, keyed on test case name. */ public static Map getAllReportsByTestCase() { return reportsByTest; } // getAllReportsByTestCase /** * Get a HashMap of all the reports, keyed on test case name. * * @param level * The ReportLine level (e.g. PROBLEM) to filter on. * @return The HashMap of all the reports, keyed on test case name. */ public static Map getAllReportsByTestCase(int level) { return filterMap(reportsByTest, level); } // getAllReportsByTestCase /** * Get a HashMap of all the reports, keyed on database name. * * @return The HashMap of all the reports, keyed on database name. */ public static Map getAllReportsByDatabase() { return reportsByDatabase; } // getReportsByDatabase /** * Get a HashMap of all the reports, keyed on test case name. * * @param level * The ReportLine level (e.g. PROBLEM) to filter on. * @return The HashMap of all the reports, keyed on test case name. */ public static Map getAllReportsByDatabase(int level) { return filterMap(reportsByDatabase, level); } // getAllReportsByTestCase /** * Get a list of all the reports corresponding to a particular test case. * * @return A List of the results (as a list) corresponding to test. * @param testCaseName * The test case to filter by. * @param level * The minimum level of report to include, e.g. ReportLine.INFO */ public static List getReportsByTestCase(String testCaseName, int level) { List allReports = (List) reportsByTest.get(testCaseName); return filterList(allReports, level); } // getReportsByTestCase /** * Get a list of all the reports corresponding to a particular database. * * @param databaseName * The database to report on. * @param level * The minimum level of report to include, e.g. ReportLine.INFO * @return A List of the ReportLines corresponding to database. */ public static List getReportsByDatabase(String databaseName, int level) { return filterList((List) reportsByDatabase.get(databaseName), level); } // getReportsByDatabase /** * Filter a list of ReportLines so that only certain entries are returned. * * @param list * The list to filter. * @param level * All reports with a priority above this level will be returned. * @return A list of the ReportLines that have a level >= that specified. */ public static List filterList(List list, int level) { ArrayList result = new ArrayList(); if (list != null) { Iterator it = list.iterator(); while (it.hasNext()) { ReportLine line = (ReportLine) it.next(); if (line.getLevel() >= level) { result.add(line); } } } return result; } // filterList /** * Filter a HashMap of lists of ReportLines so that only certain entries are returned. * * @param map * The list to filter. * @param level * All reports with a priority above this level will be returned. * @return A HashMap with the same keys as map, but with the lists filtered by level. */ public static Map filterMap(Map map, int level) { HashMap result = new HashMap(); Set keySet = map.keySet(); Iterator it = keySet.iterator(); while (it.hasNext()) { String key = (String) it.next(); List list = (List) map.get(key); result.put(key, filterList(list, level)); } return result; } // filterList /** * Count how many tests passed and failed for a particular database. A test is considered to have passed if there are no reports * of level ReportLine.PROBLEM. * * @param database * The database to check. * @return An array giving the number of passes and then fails for this database. */ public static int[] countPassesAndFailsDatabase(String database) { int[] result = new int[2]; List testsRun = new ArrayList(); // get all of them to build a list of the tests that were run List reports = getReportsByDatabase(database, ReportLine.ALL); Iterator it = reports.iterator(); while (it.hasNext()) { ReportLine line = (ReportLine) it.next(); String test = line.getTestCaseName(); if (!testsRun.contains(test)) { testsRun.add(test); } } // count those that failed List testsFailed = new ArrayList(); reports = getReportsByDatabase(database, ReportLine.PROBLEM); it = reports.iterator(); while (it.hasNext()) { ReportLine line = (ReportLine) it.next(); String test = line.getTestCaseName(); if (!testsFailed.contains(test)) { testsFailed.add(test); } } result[1] = testsFailed.size(); result[0] = testsRun.size() - testsFailed.size(); // if it didn't // fail, it passed return result; } /** * Count how many databases passed a particular test. A test is considered to have passed if there are no reports of level * ReportLine.PROBLEM. * * @param test * The test to check. * @return An array giving the number of databases that passed [0] and failed [1] this test. */ public static int[] countPassesAndFailsTest(String test) { int[] result = new int[2]; List allDBs = new ArrayList(); // get all of them to build a list of the tests that were run List reports = getReportsByTestCase(test, ReportLine.ALL); Iterator it = reports.iterator(); while (it.hasNext()) { ReportLine line = (ReportLine) it.next(); String database = line.getDatabaseName(); if (!allDBs.contains(database)) { allDBs.add(database); } } // count those that failed List dbsFailed = new ArrayList(); reports = getReportsByTestCase(test, ReportLine.PROBLEM); it = reports.iterator(); while (it.hasNext()) { ReportLine line = (ReportLine) it.next(); String database = line.getDatabaseName(); if (!dbsFailed.contains(database)) { dbsFailed.add(database); } } result[1] = dbsFailed.size(); result[0] = allDBs.size() - dbsFailed.size(); // if it didn't fail, it // passed return result; } /** * Count how many tests passed and failed. A test is considered to have passed if there are no reports of level * ReportLine.PROBLEM. * * @return An array giving the number of passes and then fails. */ public static int[] countPassesAndFailsAll() { int[] result = new int[2]; Map allByDB = getAllReportsByDatabase(); Set dbs = allByDB.keySet(); Iterator it = dbs.iterator(); while (it.hasNext()) { String database = (String) it.next(); int[] dbResult = countPassesAndFailsDatabase(database); result[0] += dbResult[0]; result[1] += dbResult[1]; } return result; } /** * Check if all the a particular database passed a particular test. * * @param test * The test to check. * @param database * The database to check. * @return true if database passed test (i.e. had no problems). */ public static boolean databasePassed(String test, String database) { List reports = getReportsByTestCase(test, ReportLine.PROBLEM); Iterator it = reports.iterator(); while (it.hasNext()) { ReportLine line = (ReportLine) it.next(); if (database.equals(line.getDatabaseName())) { return false; } } return true; } /** * Check if all the databases passed a particular test. * * @param test * The test to check. * @return true if none of the databases failed this test (i.e. had no problems) */ public static boolean allDatabasesPassed(String test) { List reports = getReportsByTestCase(test, ReportLine.PROBLEM); if (reports.size() > 0) { return false; } return true; } /** * Get a list of all the reports corresponding to a particular database and test case. * * @return A List of the results (as a list) corresponding to test and database. * @param test * The test case to filter by. * @param database * The database. */ public static List getReports(String test, String database) { List result = new ArrayList(); List allReports = (List) reportsByTest.get(test); Iterator it = allReports.iterator(); while (it.hasNext()) { ReportLine line = (ReportLine) it.next(); if (database.equals(line.getDatabaseName())) { result.add(line); } } return result; } // getReports /** * Flag to state whether a database is being used as the output destination. */ public static boolean usingDatabase() { return usingDatabase; } /** * Set up connection to a database for output. Sets usingDatabase to true. */ public static void connectToOutputDatabase() { logger.info("Connecting to " + System.getProperty("output.databaseURL") + System.getProperty("output.database") + " as " + System.getProperty("output.user") + " password " + System.getProperty("output.password")); outputDatabaseConnection = DBUtils.openConnection(System.getProperty("output.driver"), System.getProperty("output.databaseURL") + System.getProperty("output.database"), System.getProperty("output.user"), System.getProperty("output.password")); usingDatabase = true; } /** * Create a new entry in the session table. Store the ID of the created session in sessionID. */ public static void createDatabaseSession() { // build comma-separated list of hosts StringBuffer buf = new StringBuffer(); Iterator<DatabaseServer> it = DBUtils.getMainDatabaseServers().iterator(); while (it.hasNext()) { DatabaseServer server = (DatabaseServer)it.next(); buf.append(String.format("%s:%s", server.getHost(), server.getPort())); if (it.hasNext()) { buf.append(","); } } String hosts = buf.toString(); String sql = String.format("INSERT INTO session (host, config, db_release) VALUES (\'%s\',\'%s\',\'%s\')", hosts, System.getProperty("output.databases"), System.getProperty("output.release")); try { Statement stmt = outputDatabaseConnection.createStatement(); stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); ResultSet rs = stmt.getGeneratedKeys(); if (rs.next()) { sessionID = rs.getLong(1); logger.fine("Created new session with ID " + sessionID); } stmt.close(); } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } if (sessionID == -1) { logger.severe("Could not get new session ID"); logger.severe(sql); } } /** * End a database session. Write the end time into the database. */ public static void endDatabaseSession() { String sql = "UPDATE session SET end_time=NOW() WHERE session_id=" + sessionID; try { Statement stmt = outputDatabaseConnection.createStatement(); stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); stmt.close(); } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } } /** * Delete all previous data. */ public static void deletePrevious() { String[] tables = { "session", "report", "annotation" }; for (int i = 0; i < tables.length; i++) { String sql = "DELETE FROM " + tables[i]; try { Statement stmt = outputDatabaseConnection.createStatement(); stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); stmt.close(); } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } } } /** * Update a report in the database. Two possible actions: 1. If the report already exists and hasn't changed, just update it. 2. * If the report is new, add a new record. */ public static void checkAndAddToDatabase(ReportLine report) { long reportID = reportExistsInDatabase(report); if (reportID > -1) { updateReportInDatabase(report, reportID); } else { addReportToDatabase(report); } } /** * Check if a report exists (i.e. same database, testcase, result and text). * * @return -1 if the report does not exist, report_id if it does. */ public static long reportExistsInDatabase(ReportLine report) { String sql = "SELECT report_id FROM report WHERE database_name=? AND testcase=? AND result=? AND text=?"; long reportID = -1; try { PreparedStatement stmt = outputDatabaseConnection.prepareStatement(sql); stmt.setString(1, report.getDatabaseName()); stmt.setString(2, report.getShortTestCaseName()); stmt.setString(3, report.getLevelAsString()); stmt.setString(4, report.getMessage()); ResultSet rs = stmt.executeQuery(); if (rs != null) { if (rs.first()) { reportID = rs.getLong(1); } else { reportID = -1; // probably signifies an empty ResultSet } } rs.close(); stmt.close(); } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } if (reportID > -1) { logger.finest("Report already exists (ID " + reportID + "): " + report.getDatabaseName() + " " + report.getTestCaseName() + " " + report.getLevelAsString() + " " + report.getMessage()); } else { logger.finest("Report does not already exist: " + report.getDatabaseName() + " " + report.getTestCaseName() + " " + report.getLevelAsString() + " " + report.getMessage()); } return reportID; } /** * Store a report in the database. */ public static void addReportToDatabase(ReportLine report) { if (outputDatabaseConnection == null) { logger.severe("No connection to output database!"); return; } logger.fine("Adding report for: " + report.getDatabaseName() + " " + report.getTestCaseName() + " " + report.getLevelAsString() + " " + report.getMessage()); String sql = "INSERT INTO report (first_session_id, last_session_id, database_name, species, database_type, testcase, result, text, timestamp, team_responsible, created) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, NOW())"; try { PreparedStatement stmt = outputDatabaseConnection.prepareStatement(sql); stmt.setLong(1, sessionID); stmt.setLong(2, sessionID); stmt.setString(3, report.getDatabaseName()); // EG Store species name and db type from explicit report line, not from database stmt.setString(4, report.getSpeciesName()); stmt.setString(5, report.getType().toString()); stmt.setString(6, report.getShortTestCaseName()); stmt.setString(7, report.getLevelAsString()); stmt.setString(8, report.getMessage()); stmt.setString(9, report.getPrintableTeamResponsibleString()); stmt.executeUpdate(); stmt.close(); } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } } /** * Update the last_session_id of a report in the database. */ public static void updateReportInDatabase(ReportLine report, long reportID) { if (outputDatabaseConnection == null) { logger.severe("No connection to output database!"); return; } logger.fine("Updating report for: " + report.getDatabaseName() + " " + report.getTestCaseName() + " " + report.getLevelAsString() + " " + report.getMessage() + ", new last_session_id=" + sessionID); String sql = "UPDATE report SET last_session_id=?, timestamp=NOW() WHERE report_id=?"; try { PreparedStatement stmt = outputDatabaseConnection.prepareStatement(sql); stmt.setLong(1, sessionID); stmt.setLong(2, reportID); stmt.executeUpdate(); stmt.close(); } catch (SQLException e) { System.err.println("Error executing:\n" + sql); e.printStackTrace(); } } public static long getSessionID() { return sessionID; } public static void setSessionID(long sessionID) { ReportManager.sessionID = sessionID; } } // ReportManager
package com.checkmarx.jenkins; import com.checkmarx.cxconsole.CxConsoleLauncher; import com.checkmarx.cxviewer.ws.generated.CxCLIWebService; import com.checkmarx.cxviewer.ws.generated.CxCLIWebServiceSoap; import com.checkmarx.cxviewer.ws.resolver.CxClientType; import com.checkmarx.cxviewer.ws.resolver.CxWSResolver; import com.checkmarx.cxviewer.ws.resolver.CxWSResolverSoap; import com.checkmarx.cxviewer.ws.resolver.CxWSResponseDiscovery; import com.sun.xml.internal.ws.wsdl.parser.InaccessibleWSDLException; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import hudson.util.FormValidation; import net.sf.json.JSONObject; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.SimpleLayout; import org.apache.log4j.WriterAppender; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; /** * The main entry point for Checkmarx plugin. This class implements the Builder * build stage that scans the source code. * * @author Denis Krivitski * @since 3/10/13 */ public class CxScanBuilder extends Builder { // Persistent plugin configuration parameters private String serverUrl; private String username; private String password; private String projectName; private String preset; private boolean presetSpecified; private String includeExtensions; private String locationPathExclude; private boolean visibleToOthers; private boolean incremental; private String sourceEncoding; private String comment; // Private variables // Constructors @DataBoundConstructor public CxScanBuilder(String serverUrl, String username, String password, String projectName, String preset, boolean presetSpecified, String includeExtensions, String locationPathExclude, boolean visibleToOthers, boolean incremental, String sourceEncoding, String comment) { this.serverUrl = serverUrl; this.username = username; this.password = password; this.projectName = projectName; this.preset = preset; this.presetSpecified = presetSpecified; this.includeExtensions = includeExtensions; this.locationPathExclude = locationPathExclude; this.visibleToOthers = visibleToOthers; this.incremental = incremental; this.sourceEncoding = sourceEncoding; // TODO: Convert string to enum this.comment = comment; } // Configuration fields getters public String getServerUrl() { return serverUrl; } public String getUsername() { return username; } public String getPassword() { return password; } public String getProjectName() { return projectName; } public String getPreset() { return preset; } public boolean isPresetSpecified() { return presetSpecified; } public String getIncludeExtensions() { return includeExtensions; } public String getLocationPathExclude() { return locationPathExclude; } public boolean isVisibleToOthers() { return visibleToOthers; } public boolean isIncremental() { return incremental; } public String getSourceEncoding() { return sourceEncoding; } public String getComment() { return comment; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { //boolean result = super.perform(build, launcher, listener); WriterAppender appender = new WriterAppender(new PatternLayout(),listener.getLogger()); Logger.getLogger("com.checkmarx.cxconsole").addAppender(appender); Logger.getLogger("com.checkmarx.cxviewer").addAppender(appender); System.out.println("Hello Jenkins"); listener.getLogger().println("Hello Jenkins logger"); listener.getLogger().flush(); CxConsoleLauncher.main(new String[]{"Scan"}); return true;//result; } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl)super.getDescriptor(); } /*public String getIconPath() { PluginWrapper wrapper = Hudson.getInstance().getPluginManager().getPlugin([YOUR-PLUGIN-MAIN-CLASS].class); return Hudson.getInstance().getRootUrl() + "plugin/"+ wrapper.getShortName()+"/"; }*/ public String getMyString() { return "Hello Jenkins!"; } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { public static String DEFAULT_INCLUDE_EXTENSION = ".java, .c, .cs"; // TODO: set real default value public static String DEFAULT_EXCLUDE_FOLDERS = "target, work, src/main/resources"; private String webServiceUrl; public boolean isApplicable(Class<? extends AbstractProject> aClass) { return true; } // Field value validators public FormValidation doCheckServerUrl(@QueryParameter String value) { try { this.webServiceUrl = null; this.webServiceUrl = resolveWebServiceURL(value); return FormValidation.ok(); } catch (Exception e) { return FormValidation.error(e.getMessage()); } } public FormValidation doCheckPassword(@QueryParameter String value, @QueryParameter String username) { String password = value; if (this.webServiceUrl==null) { return FormValidation.warning("Server URL not set"); } return FormValidation.warning("Username:" + username + " pass:" + password); } private String resolveWebServiceURL(String serverUrl) throws Exception { final String WS_RESOLVER_PATH = "/cxwebinterface/cxWSResolver.asmx"; final int WS_CLI_INTERFACE_VERSION = 0; final String NO_CONNECTION_ERROR_MESSAGE = "Checkmarx server did not respond on the specified URL"; try { URL url = new URL(serverUrl); if (!url.getPath().isEmpty()) { throw new Exception("URL Must not contain path"); } if (url.getQuery()!=null) { throw new Exception("URL Must not contain query parameters"); } url = new URL(url.toString() + WS_RESOLVER_PATH); CxWSResolver cxWSResolver = new CxWSResolver(url); CxWSResolverSoap cxWSResolverSoap = cxWSResolver.getCxWSResolverSoap(); CxWSResponseDiscovery cxWSResponseDiscovery = cxWSResolverSoap.getWebServiceUrl(CxClientType.CLI,WS_CLI_INTERFACE_VERSION); if (cxWSResponseDiscovery.isIsSuccesfull()) { return cxWSResponseDiscovery.getServiceURL(); } else { throw new Exception(NO_CONNECTION_ERROR_MESSAGE); } } catch (InaccessibleWSDLException e) { throw new Exception(NO_CONNECTION_ERROR_MESSAGE); } } /** * This human readable name is used in the configuration screen. */ public String getDisplayName() { return "Execute Checkmarx Scan"; } @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { // To persist global configuration information, // set that to properties and call save(). // ^Can also use req.bindJSON(this, formData); // (easier when there are many fields; need set* methods for this, like setUseFrench) // save(); return super.configure(req,formData); } } }
package com.cloudbees.jenkins; import com.cloudbees.jenkins.GitHubPushTrigger.DescriptorImpl; import hudson.Extension; import hudson.model.AbstractProject; import hudson.model.Hudson; import hudson.model.RootAction; import hudson.model.UnprotectedRootAction; import hudson.security.ACL; import hudson.triggers.Trigger; import hudson.util.AdaptedIterator; import hudson.util.Iterators.FilterIterator; import net.sf.json.JSONObject; import org.acegisecurity.Authentication; import org.acegisecurity.context.SecurityContextHolder; import org.kohsuke.github.GitHub; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.util.logging.Level.*; /** * Receives github hook. * * @author Kohsuke Kawaguchi */ @Extension public class GitHubWebHook implements UnprotectedRootAction { private static final Pattern REPOSITORY_NAME_PATTERN = Pattern.compile("https?: public String getIconFileName() { return null; } public String getDisplayName() { return null; } public String getUrlName() { return "github-webhook"; } /** * Logs in as the given user and returns the connection object. */ public Iterable<GitHub> login(String host, String userName) { if (host.equals("github.com")) { final List<Credential> l = DescriptorImpl.get().getCredentials(); // if the username is not an organization, we should have the right user account on file for (Credential c : l) { if (c.username.equals(userName)) try { return Collections.singleton(c.login()); } catch (IOException e) { LOGGER.log(WARNING,"Failed to login with username="+c.username,e); return Collections.emptyList(); } } // otherwise try all the credentials since we don't know which one would work return new Iterable<GitHub>() { public Iterator<GitHub> iterator() { return new FilterIterator<GitHub>( new AdaptedIterator<Credential,GitHub>(l) { protected GitHub adapt(Credential c) { try { return c.login(); } catch (IOException e) { LOGGER.log(WARNING,"Failed to login with username="+c.username,e); return null; } } }) { protected boolean filter(GitHub g) { return g!=null; } }; } }; } else { return Collections.<GitHub> emptyList(); } } /** * 1 push to 2 branches will result in 2 pushes. */ public void doIndex(StaplerRequest req) { processGitHubPayload(req.getParameter("payload"),GitHubPushTrigger.class); } public void processGitHubPayload(String payload, Class<? extends Trigger> triggerClass) { JSONObject o = JSONObject.fromObject(payload); JSONObject repository = o.getJSONObject("repository"); String repoUrl = repository.getString("url"); String repoName = repository.getString("name"); // 'foo' portion of the above URL String ownerName = repository.getJSONObject("owner").getString("name"); // 'kohsuke' portion of the above URL LOGGER.info("Received POST for "+repoUrl); LOGGER.fine("Full details of the POST was "+o.toString()); Matcher matcher = REPOSITORY_NAME_PATTERN.matcher(repoUrl); if (matcher.matches()) { // run in high privilege to see all the projects anonymous users don't see. // this is safe because when we actually schedule a build, it's a build that can // happen at some random time anyway. Authentication old = SecurityContextHolder.getContext().getAuthentication(); SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM); try { GitHubRepositoryName changedRepository = new GitHubRepositoryName(matcher.group(1), ownerName, repoName); for (AbstractProject<?,?> job : Hudson.getInstance().getAllItems(AbstractProject.class)) { GitHubTrigger trigger = (GitHubTrigger) job.getTrigger(triggerClass); if (trigger!=null) { LOGGER.fine("Considering to poke "+job.getFullDisplayName()); if (trigger.getGitHubRepositories().contains(changedRepository)) { LOGGER.info("Poked "+job.getFullDisplayName()); trigger.onPost(); } else LOGGER.fine("Skipped "+job.getFullDisplayName()+" because it doesn't have a matching repository."); } } } finally { SecurityContextHolder.getContext().setAuthentication(old); } } else { LOGGER.warning("Malformed repo url "+repoUrl); } } private static final Logger LOGGER = Logger.getLogger(GitHubWebHook.class.getName()); public static GitHubWebHook get() { return Hudson.getInstance().getExtensionList(RootAction.class).get(GitHubWebHook.class); } static { // hide "Bad input type: "search", creating a text input" from createElementNS Logger.getLogger(com.gargoylesoftware.htmlunit.html.InputElementFactory.class.getName()).setLevel(WARNING); } }
package com.codingbat.recursion1; /** * The class Recursion1 is contains solution for Recursion-1 section. */ public class Recursion1 { /** * Given n of 1 or more, return the factorial of n, which is n * (n-1) * (n-2) ... 1. Compute the * result recursively (without loops). * * @param number the input number * @return the above mentioned new number */ public int factorial(int number) { if (number == 0 || number == 1) { return 1; } return number * factorial(number - 1); } /** * We have a number of bunnies and each bunny has two big floppy ears. We want to compute the * total number of ears across all the bunnies recursively (without loops or multiplication). * * @param bunnies the number of bunnies * @return the above mentioned new number */ public int bunnyEars(int bunnies) { if (bunnies == 0) { return 0; } return 2 + bunnyEars(bunnies - 1); } /** * The fibonacci sequence is a famous bit of mathematics, and it happens to have a recursive * definition. The first two values in the sequence are 0 and 1 (essentially 2 base cases). Each * subsequent value is the sum of the previous two values, so the whole sequence is: 0, 1, 1, 2, * 3, 5, 8, 13, 21 and so on. Define a recursive fibonacci(n) method that returns the nth * fibonacci number, with n=0 representing the start of the sequence. * * @param fibonacciIndex the fibonacci index * @return the above mentioned new number */ public int fibonacci(int fibonacciIndex) { if (fibonacciIndex == 0) { return 0; } if (fibonacciIndex == 1) { return 1; } return fibonacci(fibonacciIndex - 1) + fibonacci(fibonacciIndex - 2); } /** * We have triangle made of blocks. The topmost row has 1 block, the next row down has 2 blocks, * the next row has 3 blocks, and so on. Compute recursively (no loops or multiplication) the * total number of blocks in such a triangle with the given number of rows. * * @param rows the rows of triangles * @return the above mentioned new number */ public int triangle(int rows) { if (rows == 0) { return 0; } return rows + triangle(rows - 1); } /** * Given a non-negative int n, return the sum of its digits recursively (no loops). Note that mod * (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the * rightmost digit (126 / 10 is 12). * * @param number the input number * @return the above mentioned new number */ public int sumDigits(int number) { int rightmostDigit = number % 10; int rightmostDigitRemoved = number / 10; if (rightmostDigitRemoved == 0) { return rightmostDigit; } return rightmostDigit + sumDigits(rightmostDigitRemoved); } /** * Given a non-negative int n, return the count of the occurrences of 7 as a digit, so for example * 717 yields 2. (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), * while divide (/) by 10 removes the rightmost digit (126 / 10 is 12). * * @param number the input number * @return the above mentioned new number */ public int count7(int number) { int rightmostDigit = number % 10; int rightmostDigitRemoved = number / 10; if (rightmostDigit == 7) { return 1 + count7(rightmostDigitRemoved); } if (rightmostDigitRemoved == 0) { return 0; } return count7(rightmostDigitRemoved); } /** * Given a non-negative int n, compute recursively (no loops) the count of the occurrences of 8 as * a digit, except that an 8 with another 8 immediately to its left counts double, so 8818 yields * 4. Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 * removes the rightmost digit (126 / 10 is 12). * * @param number the input number * @return the above mentioned new number */ public int count8(int number) { int rightmostDigit = number % 10; int rightmostDigitRemoved = number / 10; int beforeRightmostDigit = rightmostDigitRemoved % 10; if (beforeRightmostDigit == 8 && rightmostDigit == 8) { return 2 + count8(rightmostDigitRemoved); } if (beforeRightmostDigit != 8 && rightmostDigit == 8) { return 1 + count8(rightmostDigitRemoved); } if (rightmostDigitRemoved == 0) { return 0; } return count8(rightmostDigitRemoved); } /** * Given base and n that are both 1 or more, compute recursively (no loops) the value of base to * the n power, so powerN(3, 2) is 9 (3 squared). * * @param base the base number * @param exponent the exponent * @return the above mentioned new number */ public int powerN(int base, int exponent) { if (exponent == 1) { return base; } return base * powerN(base, exponent - 1); } /** * Given a string, compute recursively (no loops) the number of lowercase 'x' chars in the string. * * @param text the input string * @return the above mentioned new number */ public int countX(String text) { if (text.length() == 0) { return 0; } String substring = text.substring(1); if (text.charAt(0) == 'x') { return 1 + countX(substring); } return countX(substring); } /** * Given a string, compute recursively (no loops) the number of times lowercase "hi" appears in * the string. * * @param text the input {@link String} * @return the above mentioned new number */ public int countHi(String text) { if (text.length() == 0) { return 0; } String substring = text.substring(1); if (text.startsWith("hi")) { return 1 + countHi(substring); } return countHi(substring); } /** * Given a string, compute recursively (no loops) a new string where all the lowercase 'x' chars * have been changed to 'y' chars. * * @param text the input {@link String} * @return the above mentioned new {@link String} */ public String changeXY(String str) { String front = ""; if (str.length() == 0) { return front; } if (str.charAt(0) == 'x') { return 'y' + changeXY(str.substring(1)); } return str.charAt(0) + changeXY(str.substring(1)); } /** * Given a string, compute recursively (no loops) a new string where all appearances of "pi" have * been replaced by "3.14". * * @param str the input {@link String} * @return the above mentioned new {@link String} */ public String changePi(String str) { if (str.length() == 0) { return ""; } if (str.startsWith("pi")) { return "3.14" + changePi(str.substring(2)); } return str.charAt(0) + changePi(str.substring(1)); } /** * Given a string, compute recursively a new string where all the 'x' chars have been removed. * * @param str the input {@link String} * @return the above mentioned new {@link String} */ public String noX(String str) { if (str.length() == 0) { return ""; } if (str.charAt(0) == 'x') { return noX(str.substring(1)); } return str.charAt(0) + noX(str.substring(1)); } /** * Given an array of ints, compute recursively if the array contains a 6. We'll use the convention * of considering only the part of the array that begins at the given index. In this way, a * recursive call can pass index+1 to move down the array. The initial call will pass in index as * 0. * * @param nums the array of numbers * @param index the starting index * @return true, if the above mentioned conditions fulfilled */ public boolean array6(int[] nums, int index) { if (nums.length == 0 || nums.length == index) { return false; } if (nums[index] == 6) { return true; } return array6(nums, index + 1); } /** * Given an array of ints, compute recursively the number of times that the value 11 appears in * the array. We'll use the convention of considering only the part of the array that begins at * the given index. In this way, a recursive call can pass index+1 to move down the array. The * initial call will pass in index as 0. * * @param nums the array of numbers * @param index the starting index * @return the above mentioned new number */ public int array11(int[] nums, int index) { if (nums.length == 0 || nums.length == index) { return 0; } if (nums[index] == 11) { return 1 + array11(nums, index + 1); } return array11(nums, index + 1); } /** * Given an array of ints, compute recursively if the array contains somewhere a value followed in * the array by that value times 10. We'll use the convention of considering only the part of the * array that begins at the given index. In this way, a recursive call can pass index+1 to move * down the array. The initial call will pass in index as 0. * * @param nums the array of numbers * @param index the starting index * @return true, if above mentioned conditions fulfilled */ public boolean array220(int[] nums, int index) { if (nums.length < 2 || nums.length == index + 1) { return false; } if (nums[index] * 10 == nums[index + 1]) { return true; } return array220(nums, index + 1); } /** * Given a string, compute recursively a new string where all the adjacent chars are now separated * by a "*". * * @param str the input text * @return the above mentioned new {@link String} */ public String allStar(String str) { if (str.length() == 0) { return ""; } if (str.length() == 1) { return str; } return str.charAt(0) + "*" + allStar(str.substring(1)); } /** * Given a string, compute recursively a new string where identical chars that are adjacent in the * original string are separated from each other by a "*". * * @param str the input text * @return the above mentioned new {@link String} */ public String pairStar(String str) { if (str.length() == 0) { return ""; } if (str.length() == 1) { return str; } if (str.charAt(0) == str.charAt(1)) { return str.charAt(0) + "*" + pairStar(str.substring(1)); } return str.charAt(0) + pairStar(str.substring(1)); } /** * Given a string, compute recursively a new string where all the lowercase 'x' chars have been * moved to the end of the string. * * @param str the input text * @return the above mentioned new {@link String} */ public String endX(String str) { if (str.length() == 0) { return ""; } if (str.length() == 1) { return str; } if (str.charAt(0) == 'x') { return endX(str.substring(1)) + str.charAt(0); } return str.charAt(0) + endX(str.substring(1)); } /** * We'll say that a "pair" in a string is two instances of a char separated by a char. So "AxA" * the A's make a pair. Pair's can overlap, so "AxAxA" contains 3 pairs -- 2 for A and 1 for x. * Recursively compute the number of pairs in the given string. * * @param str the input text * @return the above mentioned new number */ public int countPairs(String str) { if (str.length() < 3) { return 0; } int foundPair = 0; if (str.charAt(0) == str.charAt(2)) { foundPair = 1; } return foundPair + countPairs(str.substring(1)); } /** * Count recursively the total number of "abc" and "aba" substrings that appear in the given * string. * * @param str the input text * @return the above mentioned new number */ public int countAbc(String str) { if (str.length() < 3) { return 0; } int foundedAbcOrAba = 0; if (str.startsWith("abc") || str.startsWith("aba")) { foundedAbcOrAba = 1; } return foundedAbcOrAba + countAbc(str.substring(1)); } /** * Given a string, compute recursively (no loops) the number of "11" substrings in the string. The * "11" substrings should not overlap. * * @param str the input text * @return the above mentioned new number */ public int count11(String str) { if (str.length() < 2) { return 0; } if (str.startsWith("11")) { return 1 + count11(str.substring(2)); } return count11(str.substring(1)); } /** * Given a string, return recursively a "cleaned" string where adjacent chars that are the same * have been reduced to a single char. So "yyzzza" yields "yza". * * @param str the input text * @return the above mentioned new {@link String} */ public String stringClean(String str) { if (str.length() < 2) { return str; } if (str.charAt(0) == str.charAt(1)) { return stringClean(str.substring(1)); } return str.charAt(0) + stringClean(str.substring(1)); } /** * Given a string, compute recursively the number of times lowercase "hi" appears in the string, * however do not count "hi" that have an 'x' immedately before them. * * @param str the input text * @return the above mentioned new number */ public int countHi2(String str) { if (str.length() < 2) { return 0; } if (str.startsWith("xhi")) { return countHi2(str.substring(3)); } if (str.startsWith("hi")) { return 1 + countHi2(str.substring(2)); } return countHi2(str.substring(1)); } /** * Given a string that contains a single pair of parenthesis, compute recursively a new string * made of only of the parenthesis and their contents, so "xyz(abc)123" yields "(abc)". * * @param str the input text * @return the above mentioned new {@link String} */ public String parenBit(String str) { if (str.charAt(0) != '(') { return parenBit(str.substring(1)); } if (str.charAt(str.length() - 1) != ')') { return parenBit(str.substring(0, str.length() - 1)); } return str; } }
package org.hcilab.bcistub.core; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Calendar; import org.hcilab.bcistub.data.BCIState; public class CSVLogHandler { private PrintWriter out; private Calendar rightNow = Calendar.getInstance(); public CSVLogHandler(String folder, String filename){ File theDir = new File(folder); // if the directory does not exist, create it if (!theDir.exists()) { System.out.println("creating directory: " + folder); boolean result = false; try{ theDir.mkdir(); result = true; } catch(SecurityException se){ //handle it } if(result) { System.out.println("DIR created"); } } try { out = new PrintWriter(folder + "/log_"+filename+"_"+ rightNow.getTimeInMillis() + ".csv"); out.append("timestamp" + "," + "excitement" +"," + "frustration" + "," + "meditation" + "," + "engagementBoredom" + "," + "blink" + "," + "clench" + "," + "laugh" + "," + "smile" + "," + "eyebrow" + "," + "furrowBrow" + "," + "lookLeft" + "," + "lookRight" + "," + "smirkLeft" + "," + "smirkRight" + "," + "winkLeft" + "," + "winkRight" + "\n"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private int makeint(boolean b){ return b?1:0; } public void log(BCIState pState) { if((out != null) && (pState != null)) { out.append(pState.getTimestamp() + "," + pState.getExcitement() +"," + pState.getFrustration() + "," + pState.getMeditation() + "," + pState.getEngagementBoredom()+ "," + makeint(pState.isBlink()) + "," + pState.getClench() + "," + pState.getLaugh() + "," + pState.getSmile() + "," + pState.getEyebrow() + "," + pState.getFurrowBrow() + "," + makeint(pState.isLookLeft()) + "," + makeint(pState.isLookRight()) + "," + pState.getSmirkleft() + "," + pState.getSmirkright() + "," + makeint(pState.isWinkLeft()) + "," + makeint(pState.isWinkRight()) + "," +"\n"); out.flush(); //pState.flush(); } } }
package com.comandante.creeper; import com.comandante.creeper.Items.*; import com.comandante.creeper.entity.EntityManager; import com.comandante.creeper.managers.GameManager; import com.comandante.creeper.merchant.*; import com.comandante.creeper.merchant.GrimulfWizard; import com.comandante.creeper.npc.Npc; import com.comandante.creeper.npc.NpcExporter; import com.comandante.creeper.spawner.ItemSpawner; import com.comandante.creeper.spawner.NpcSpawner; import com.comandante.creeper.spawner.SpawnRule; import com.comandante.creeper.spawner.SpawnRuleBuilder; import com.comandante.creeper.spells.*; import com.comandante.creeper.world.Area; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.io.FileNotFoundException; import java.util.List; import java.util.Map; import java.util.Set; public class ConfigureNpc { public static void configureAllNpcs(GameManager gameManager) throws FileNotFoundException { EntityManager entityManager = gameManager.getEntityManager(); List<Npc> npcsFromFile = NpcExporter.getNpcsFromFile(gameManager); for (Npc npc: npcsFromFile) { Main.startUpMessage("Added " + npc.getName()); entityManager.addEntity(npc); Set<SpawnRule> spawnRules = npc.getSpawnRules(); for (SpawnRule spawnRule: spawnRules) { entityManager.addEntity(new NpcSpawner(npc, gameManager, spawnRule)); } } } public static void configure(EntityManager entityManager, GameManager gameManager) throws FileNotFoundException { configureAllNpcs(gameManager); Main.startUpMessage("Adding beer"); ItemSpawner itemSpawner = new ItemSpawner(ItemType.BEER, new SpawnRuleBuilder().setArea(Area.NEWBIE_ZONE).setSpawnIntervalTicks(600).setMaxInstances(100).setMaxPerRoom(5).setRandomPercent(40).createSpawnRule(), gameManager); ItemSpawner itemSpawner1 = new ItemSpawner(ItemType.BEER, new SpawnRuleBuilder().setArea(Area.FANCYHOUSE_ZONE).setSpawnIntervalTicks(600).setMaxInstances(12).setMaxPerRoom(2).setRandomPercent(50).createSpawnRule(), gameManager); ItemSpawner itemSpawner2 = new ItemSpawner(ItemType.BEER, new SpawnRuleBuilder().setArea(Area.HOUSE_ZONE).setSpawnIntervalTicks(600).setMaxInstances(12).setMaxPerRoom(2).setRandomPercent(50).createSpawnRule(), gameManager); ItemSpawner itemSpawner3 = new ItemSpawner(ItemType.PURPLE_DRANK, new SpawnRuleBuilder().setArea(Area.FANCYHOUSE_ZONE).setSpawnIntervalTicks(600).setMaxInstances(30).setMaxPerRoom(5).setRandomPercent(50).createSpawnRule(), gameManager); ItemSpawner itemSpawner4 = new ItemSpawner(ItemType.PURPLE_DRANK, new SpawnRuleBuilder().setArea(Area.HOUSE_ZONE).setSpawnIntervalTicks(600).setMaxInstances(30).setMaxPerRoom(5).setRandomPercent(50).createSpawnRule(), gameManager); ItemSpawner itemSpawner5 = new ItemSpawner(ItemType.KEY, new SpawnRuleBuilder().setArea(Area.LOBBY).setSpawnIntervalTicks(600).setMaxInstances(1).setMaxPerRoom(1).setRandomPercent(5).createSpawnRule(), gameManager); entityManager.addEntity(itemSpawner); entityManager.addEntity(itemSpawner1); entityManager.addEntity(itemSpawner2); entityManager.addEntity(itemSpawner3); entityManager.addEntity(itemSpawner4); entityManager.addEntity(itemSpawner5); Map<Integer, MerchantItemForSale> itemsForSale = Maps.newLinkedHashMap(); itemsForSale.put(1, new MerchantItemForSale(ItemType.BEER, 8)); itemsForSale.put(2, new MerchantItemForSale(ItemType.PURPLE_DRANK, 80)); itemsForSale.put(3, new MerchantItemForSale(ItemType.LEATHER_SATCHEL, 25000)); itemsForSale.put(4, new MerchantItemForSale(ItemType.BIGGERS_SKIN_SATCHEL, 250000)); itemsForSale.put(5, new MerchantItemForSale(ItemType.STRENGTH_ELIXIR, 2000)); itemsForSale.put(6, new MerchantItemForSale(ItemType.CHRONIC_JOOSE, 4000)); itemsForSale.put(7, new MerchantItemForSale(ItemType.GUCCI_PANTS, 80000000)); LloydBartender lloydBartender = new LloydBartender(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), itemsForSale); gameManager.getRoomManager().addMerchant(64, lloydBartender); Map<Integer, MerchantItemForSale> nigelForSale = Maps.newLinkedHashMap(); nigelForSale.put(1, new MerchantItemForSale(ItemType.BEER, 6)); NigelBartender nigelBartender = new NigelBartender(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), nigelForSale); gameManager.getRoomManager().addMerchant(377, nigelBartender); Map<Integer, MerchantItemForSale> blacksmithItems = Maps.newHashMap(); blacksmithItems.put(1, new MerchantItemForSale(ItemType.BROAD_SWORD, 1000)); blacksmithItems.put(2, new MerchantItemForSale(ItemType.IRON_BOOTS, 800)); blacksmithItems.put(3, new MerchantItemForSale(ItemType.IRON_BRACERS, 400)); blacksmithItems.put(4, new MerchantItemForSale(ItemType.IRON_HELMET, 500)); blacksmithItems.put(5, new MerchantItemForSale(ItemType.IRON_CHEST_PLATE, 1500)); blacksmithItems.put(6, new MerchantItemForSale(ItemType.IRON_LEGGINGS, 1100)); blacksmithItems.put(7, new MerchantItemForSale(ItemType.PHANTOM_SWORD, 7000)); blacksmithItems.put(8, new MerchantItemForSale(ItemType.PHANTOM_HELMET, 3500)); blacksmithItems.put(9, new MerchantItemForSale(ItemType.PHANTOM_BOOTS, 3000)); blacksmithItems.put(10, new MerchantItemForSale(ItemType.PHANTOM_BRACERS, 1500)); blacksmithItems.put(11, new MerchantItemForSale(ItemType.PHANTOM_LEGGINGS, 4000)); blacksmithItems.put(12, new MerchantItemForSale(ItemType.MITHRIL_SWORD, 14000)); blacksmithItems.put(13, new MerchantItemForSale(ItemType.MITHRIL_HELMET, 7000)); blacksmithItems.put(14, new MerchantItemForSale(ItemType.MITHRIL_CHESTPLATE, 10000)); blacksmithItems.put(15, new MerchantItemForSale(ItemType.MITHRIL_BOOTS, 6000)); blacksmithItems.put(16, new MerchantItemForSale(ItemType.MITHRIL_BRACERS, 4000)); blacksmithItems.put(17, new MerchantItemForSale(ItemType.MITHRIL_LEGGINGS, 8000)); blacksmithItems.put(18, new MerchantItemForSale(ItemType.PYAMITE_SWORD, 20000)); blacksmithItems.put(19, new MerchantItemForSale(ItemType.PYAMITE_HELMET, 14000)); blacksmithItems.put(20, new MerchantItemForSale(ItemType.PYAMITE_CHESTPLATE, 20000)); blacksmithItems.put(21, new MerchantItemForSale(ItemType.PYAMITE_BOOTS, 12000)); blacksmithItems.put(22, new MerchantItemForSale(ItemType.PYAMITE_BRACERS, 8000)); blacksmithItems.put(23, new MerchantItemForSale(ItemType.PYAMITE_LEGGINGS, 16000)); blacksmithItems.put(24, new MerchantItemForSale(ItemType.VULCERIUM_SWORD, 160000)); blacksmithItems.put(25, new MerchantItemForSale(ItemType.VULCERIUM_HELMET, 37000)); blacksmithItems.put(26, new MerchantItemForSale(ItemType.VULCERIUM_CHESTPLATE, 52000)); blacksmithItems.put(27, new MerchantItemForSale(ItemType.VULCERIUM_BOOTS, 38000)); blacksmithItems.put(28, new MerchantItemForSale(ItemType.VULCERIUM_BRACERS, 29000)); blacksmithItems.put(29, new MerchantItemForSale(ItemType.VULCERIUM_LEGGINGS, 52000)); blacksmithItems.put(30, new MerchantItemForSale(ItemType.BISMUTH_SWORD, 3000000)); blacksmithItems.put(31, new MerchantItemForSale(ItemType.BISMUTH_HELMET, 2400000)); blacksmithItems.put(32, new MerchantItemForSale(ItemType.LEATHER_SATCHEL, 25000)); Map<Integer, MerchantItemForSale> grimulfItems = Maps.newHashMap(); grimulfItems.put(1, new MerchantItemForSale(ItemType.MARIJUANA, 100)); grimulfItems.put(2, new MerchantItemForSale(ItemType.TAPPERHET_SWORD, 60000)); grimulfItems.put(3, new MerchantItemForSale(ItemType.BIGGERS_SKIN_SATCHEL, 250000)); grimulfItems.put(4, new MerchantItemForSale(ItemType.DWARF_BOOTS_OF_AGILITY, 10000)); // grimulfItems.put(5, new MerchantItemForSale(ItemType.GOLDEN_WAND, 4000000000)); grimulfItems.put(5, new MerchantItemForSale(ItemType.MITHAEM_LEAF, 1400000000)); Map<Integer, MerchantItemForSale> ketilItems = Maps.newHashMap(); ketilItems.put(1, new MerchantItemForSale(ItemType.BEER, 12)); ketilItems.put(2, new MerchantItemForSale(ItemType.PURPLE_DRANK, 120)); ketilItems.put(3, new MerchantItemForSale(ItemType.MARIJUANA, 100)); ketilItems.put(4, new MerchantItemForSale(ItemType.PYAMITE_ICEAXE, 10000000)); ketilItems.put(5, new MerchantItemForSale(ItemType.STRENGTH_ELIXIR, 3000)); ketilItems.put(6, new MerchantItemForSale(ItemType.CHRONIC_JOOSE, 5500)); Map<Integer, MerchantItemForSale> blackbeardItems = Maps.newHashMap(); blackbeardItems.put(1, new MerchantItemForSale(ItemType.IRON_LOCKPICKING_SET, 8000000)); blackbeardItems.put(2, new MerchantItemForSale(ItemType.PYAMITE_LOCKPICKING_SET, 8000000)); blackbeardItems.put(3, new MerchantItemForSale(ItemType.SPOOL_OF_CLIMBING_ROPE, 8000000)); blackbeardItems.put(4, new MerchantItemForSale(ItemType.BLACK_CLOAK, 8000000)); blackbeardItems.put(5, new MerchantItemForSale(ItemType.SMELTING_CRUCIBLE, 8000000)); blackbeardItems.put(6, new MerchantItemForSale(ItemType.LEATHER_SHOES, 8000000)); Map<Integer, MerchantItemForSale> wentworthItems = Maps.newHashMap(); wentworthItems.put(1, new MerchantItemForSale(ItemType.GENTLEMANS_TOP_HAT, 8000000)); wentworthItems.put(2, new MerchantItemForSale(ItemType.LEATHER_GLOVES, 8000000)); wentworthItems.put(3, new MerchantItemForSale(ItemType.WOOL_SCARF, 8000000)); wentworthItems.put(4, new MerchantItemForSale(ItemType.LEATHER_BELT, 8000000)); wentworthItems.put(5, new MerchantItemForSale(ItemType.SILK_SASH, 8000000)); wentworthItems.put(6, new MerchantItemForSale(ItemType.LEATHER_SCABBARD, 8000000)); wentworthItems.put(7, new MerchantItemForSale(ItemType.BYSENSKIN_SCABBARD, 19000000)); wentworthItems.put(8, new MerchantItemForSale(ItemType.IRON_SPECTACLES, 8000000)); wentworthItems.put(9, new MerchantItemForSale(ItemType.GOLDEN_SPECTACLES, 40000000)); wentworthItems.put(10, new MerchantItemForSale(ItemType.NOBLEMANS_SHOULDER_CLASP, 200000000)); wentworthItems.put(11, new MerchantItemForSale(ItemType.WOODSMANS_TUNIC, 8000000)); wentworthItems.put(12, new MerchantItemForSale(ItemType.PLAIN_WHITE_ROBE, 8000000)); wentworthItems.put(13, new MerchantItemForSale(ItemType.FINE_POWDERED_WIG, 30000000)); wentworthItems.put(14, new MerchantItemForSale(ItemType.HABROK_FEATHER_HAT, 10000000)); wentworthItems.put(15, new MerchantItemForSale(ItemType.POLISHED_IRON_CODPIECE, 30000000)); wentworthItems.put(16, new MerchantItemForSale(ItemType.GOLDEN_CODPIECE, 950000000)); BlackbeardRogue rogueshop = new BlackbeardRogue(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), blackbeardItems); gameManager.getRoomManager().addMerchant(864, rogueshop); Blacksmith blacksmith = new Blacksmith(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), blacksmithItems); gameManager.getRoomManager().addMerchant(66, blacksmith); gameManager.getRoomManager().addMerchant(253, blacksmith); JimBanker jimBanker = new JimBanker(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), null); gameManager.getRoomManager().addMerchant(65, jimBanker); gameManager.getRoomManager().addMerchant(209, jimBanker); LockerRoomGuy lockerRoomGuy = new LockerRoomGuy(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), null); gameManager.getRoomManager().addMerchant(63, lockerRoomGuy); GrimulfWizard grimulfWizard = new GrimulfWizard(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), grimulfItems); gameManager.getRoomManager().addMerchant(102, grimulfWizard); WentworthTailor wentworthTailor = new WentworthTailor(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), wentworthItems); gameManager.getRoomManager().addMerchant(865, wentworthTailor); KetilCommissary ketilCommissary = new KetilCommissary(gameManager, new Loot(18, 26, Sets.<ItemType>newHashSet()), ketilItems); gameManager.getRoomManager().addMerchant(420, ketilCommissary); ForageBuilder marijuanaForageBuilder = new ForageBuilder(); marijuanaForageBuilder.setItemType(ItemType.MARIJUANA); marijuanaForageBuilder.setMinAmt(1); marijuanaForageBuilder.setMaxAmt(3); marijuanaForageBuilder.setPctOfSuccess(40); marijuanaForageBuilder.setForageExperience(4); marijuanaForageBuilder.setCoolDownTicks(600); gameManager.getForageManager().addForageToArea(Area.WESTERN9_ZONE, marijuanaForageBuilder); gameManager.getForageManager().addForageToArea(Area.NORTH3_ZONE, marijuanaForageBuilder); gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE2_ZONE, marijuanaForageBuilder); gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE1_ZONE, marijuanaForageBuilder); ForageBuilder hazeForageBuilder = new ForageBuilder(); hazeForageBuilder.setItemType(ItemType.HAZE); hazeForageBuilder.setMinAmt(1); hazeForageBuilder.setMaxAmt(3); hazeForageBuilder.setPctOfSuccess(5); hazeForageBuilder.setForageExperience(10); hazeForageBuilder.setCoolDownTicks(600); gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE8_ZONE, hazeForageBuilder); gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE9_ZONE, hazeForageBuilder); gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE10_ZONE, hazeForageBuilder); gameManager.getForageManager().addForageToArea(Area.NORTH12_ZONE, hazeForageBuilder); gameManager.getForageManager().addForageToArea(Area.SOUTH2_ZONE, hazeForageBuilder); gameManager.getForageManager().addForageToArea(Area.SOUTH3_ZONE, hazeForageBuilder); gameManager.getForageManager().addForageToArea(Area.SOUTH4_ZONE, hazeForageBuilder); ForageBuilder aexirianForageBuilder = new ForageBuilder(); aexirianForageBuilder.setItemType(ItemType.AEXIRIAN_ROOT); aexirianForageBuilder.setMinAmt(1); aexirianForageBuilder.setMaxAmt(3); aexirianForageBuilder.setPctOfSuccess(5); aexirianForageBuilder.setForageExperience(10); aexirianForageBuilder.setCoolDownTicks(600); gameManager.getForageManager().addForageToArea(Area.WESTERN4_ZONE, aexirianForageBuilder); gameManager.getForageManager().addForageToArea(Area.WESTERN5_ZONE, aexirianForageBuilder); ForageBuilder mithaemForageBuilder = new ForageBuilder(); mithaemForageBuilder.setItemType(ItemType.MITHAEM_LEAF); mithaemForageBuilder.setMinAmt(1); mithaemForageBuilder.setMaxAmt(3); mithaemForageBuilder.setPctOfSuccess(5); mithaemForageBuilder.setForageExperience(10); mithaemForageBuilder.setCoolDownTicks(600); gameManager.getForageManager().addForageToArea(Area.TISLAND3_ZONE, mithaemForageBuilder); gameManager.getForageManager().addForageToArea(Area.TISLAND4_ZONE, mithaemForageBuilder); ForageBuilder duriccaForageBuilder = new ForageBuilder(); duriccaForageBuilder.setItemType(ItemType.DURICCA_ROOT); duriccaForageBuilder.setMinAmt(1); duriccaForageBuilder.setMaxAmt(3); duriccaForageBuilder.setPctOfSuccess(5); duriccaForageBuilder.setForageExperience(10); duriccaForageBuilder.setCoolDownTicks(600); gameManager.getForageManager().addForageToArea(Area.TOFT1_ZONE, duriccaForageBuilder); gameManager.getForageManager().addForageToArea(Area.TOFT2_ZONE, duriccaForageBuilder); ForageBuilder pondeselForageBuilder = new ForageBuilder(); pondeselForageBuilder.setItemType(ItemType.PONDESEL_BERRY); pondeselForageBuilder.setMinAmt(1); pondeselForageBuilder.setMaxAmt(3); pondeselForageBuilder.setPctOfSuccess(5); pondeselForageBuilder.setForageExperience(10); pondeselForageBuilder.setCoolDownTicks(600); gameManager.getForageManager().addForageToArea(Area.TISLAND6_ZONE, pondeselForageBuilder); gameManager.getForageManager().addForageToArea(Area.TISLAND7_ZONE, pondeselForageBuilder); ForageBuilder vikalionusForageBuilder = new ForageBuilder(); vikalionusForageBuilder.setItemType(ItemType.VIKALIONUS_CAP); vikalionusForageBuilder.setMinAmt(1); vikalionusForageBuilder.setMaxAmt(3); vikalionusForageBuilder.setPctOfSuccess(5); vikalionusForageBuilder.setForageExperience(10); vikalionusForageBuilder.setCoolDownTicks(600); gameManager.getForageManager().addForageToArea(Area.NORTH12_ZONE, vikalionusForageBuilder); gameManager.getForageManager().addForageToArea(Area.NORTH13_ZONE, vikalionusForageBuilder); ForageBuilder loornsForageBuilder = new ForageBuilder(); loornsForageBuilder.setItemType(ItemType.LOORNS_LACE); loornsForageBuilder.setMinAmt(1); loornsForageBuilder.setMaxAmt(3); loornsForageBuilder.setPctOfSuccess(5); loornsForageBuilder.setForageExperience(10); loornsForageBuilder.setCoolDownTicks(600); gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE4_ZONE, loornsForageBuilder); gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE5_ZONE, loornsForageBuilder); ForageBuilder tournearesForageBuilder = new ForageBuilder(); tournearesForageBuilder.setItemType(ItemType.TOURNEARES_LEAF); tournearesForageBuilder.setMinAmt(1); tournearesForageBuilder.setMaxAmt(3); tournearesForageBuilder.setPctOfSuccess(5); tournearesForageBuilder.setForageExperience(10); tournearesForageBuilder.setCoolDownTicks(600); gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE6_ZONE, tournearesForageBuilder); gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE7_ZONE, tournearesForageBuilder); ForageBuilder haussianForageBuilder = new ForageBuilder(); haussianForageBuilder.setItemType(ItemType.HAUSSIAN_BERRY); haussianForageBuilder.setMinAmt(1); haussianForageBuilder.setMaxAmt(3); haussianForageBuilder.setPctOfSuccess(5); haussianForageBuilder.setForageExperience(10); haussianForageBuilder.setCoolDownTicks(600); gameManager.getForageManager().addForageToArea(Area.WESTERN2_ZONE, haussianForageBuilder); gameManager.getForageManager().addForageToArea(Area.WESTERN3_ZONE, haussianForageBuilder); ForageBuilder pertilliumForageBuilder = new ForageBuilder(); pertilliumForageBuilder.setItemType(ItemType.PERTILLIUM_ROOT); pertilliumForageBuilder.setMinAmt(1); pertilliumForageBuilder.setMaxAmt(3); pertilliumForageBuilder.setPctOfSuccess(5); pertilliumForageBuilder.setForageExperience(10); pertilliumForageBuilder.setCoolDownTicks(600); gameManager.getForageManager().addForageToArea(Area.WESTERN4_ZONE, pertilliumForageBuilder); gameManager.getForageManager().addForageToArea(Area.WESTERN5_ZONE, pertilliumForageBuilder); ForageBuilder hycianthisForageBuilder = new ForageBuilder(); hycianthisForageBuilder.setItemType(ItemType.HYCIANTHIS_BARK); hycianthisForageBuilder.setMinAmt(1); hycianthisForageBuilder.setMaxAmt(3); hycianthisForageBuilder.setPctOfSuccess(5); hycianthisForageBuilder.setForageExperience(10); hycianthisForageBuilder.setCoolDownTicks(600); gameManager.getForageManager().addForageToArea(Area.NORTH10_ZONE, hycianthisForageBuilder); gameManager.getForageManager().addForageToArea(Area.NORTH11_ZONE, hycianthisForageBuilder); ForageBuilder punilareForageBuilder = new ForageBuilder(); punilareForageBuilder.setItemType(ItemType.PUNILARE_FERN); punilareForageBuilder.setMinAmt(1); punilareForageBuilder.setMaxAmt(3); punilareForageBuilder.setPctOfSuccess(5); punilareForageBuilder.setForageExperience(10); punilareForageBuilder.setCoolDownTicks(600); gameManager.getForageManager().addForageToArea(Area.SOUTH1_ZONE, punilareForageBuilder); gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE14_ZONE, punilareForageBuilder); ForageBuilder keakiarForageBuilder = new ForageBuilder(); keakiarForageBuilder.setItemType(ItemType.KEAKIAR_CAP); keakiarForageBuilder.setMinAmt(1); keakiarForageBuilder.setMaxAmt(3); keakiarForageBuilder.setPctOfSuccess(5); keakiarForageBuilder.setForageExperience(10); keakiarForageBuilder.setCoolDownTicks(600); gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE15_ZONE, keakiarForageBuilder); gameManager.getForageManager().addForageToArea(Area.NORTH14_ZONE, keakiarForageBuilder); ForageBuilder dirtyBombForageBuilder = new ForageBuilder(); dirtyBombForageBuilder.setItemType(ItemType.DIRTY_BOMB); dirtyBombForageBuilder.setMinAmt(1); dirtyBombForageBuilder.setMaxAmt(3); dirtyBombForageBuilder.setPctOfSuccess(2); dirtyBombForageBuilder.setForageExperience(100); dirtyBombForageBuilder.setCoolDownTicks(600); gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE15_ZONE, dirtyBombForageBuilder); gameManager.getForageManager().addForageToArea(Area.NORTH14_ZONE, dirtyBombForageBuilder); gameManager.getForageManager().addForageToArea(Area.SOUTH1_ZONE, dirtyBombForageBuilder); gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE14_ZONE, dirtyBombForageBuilder); gameManager.getForageManager().addForageToArea(Area.NORTH10_ZONE, dirtyBombForageBuilder); gameManager.getForageManager().addForageToArea(Area.NORTH11_ZONE, dirtyBombForageBuilder); gameManager.getForageManager().addForageToArea(Area.WESTERN4_ZONE, dirtyBombForageBuilder); gameManager.getForageManager().addForageToArea(Area.WESTERN5_ZONE, dirtyBombForageBuilder); gameManager.getForageManager().addForageToArea(Area.WESTERN2_ZONE, dirtyBombForageBuilder); gameManager.getForageManager().addForageToArea(Area.WESTERN3_ZONE, dirtyBombForageBuilder); gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE6_ZONE, dirtyBombForageBuilder); gameManager.getForageManager().addForageToArea(Area.BLOODRIDGE7_ZONE, dirtyBombForageBuilder); SpellRegistry.addSpell(new LightningSpell(gameManager)); SpellRegistry.addSpell(new ClumsinessSpell(gameManager)); SpellRegistry.addSpell(new RestoreSpell(gameManager)); SpellRegistry.addSpell(new AidsSpell(gameManager)); } }
package org.ice4j.attribute; import org.ice4j.*; /** * The LIFETIME attribute is used to know the lifetime * of TURN allocations. * * @author Sebastien Vincent * @author Aakash Garg */ public class LifetimeAttribute extends Attribute { /** * Attribute name. */ public static final String NAME = "LIFETIME"; /** * The length of the data contained by this attribute. */ public static final char DATA_LENGTH = 4; /** * Lifetime value. */ int lifetime = 0; /** * Constructor. */ LifetimeAttribute() { super(LIFETIME); } /** * Compares two STUN Attributes. Attributes are considered equal when their * type, length, and all data are the same. * @param obj the object to compare this attribute with. * @return true if the attributes are equal and false otherwise. */ @Override public boolean equals(Object obj) { if (! (obj instanceof LifetimeAttribute) || obj == null) return false; if (obj == this) return true; LifetimeAttribute att = (LifetimeAttribute) obj; if (att.getAttributeType() != getAttributeType() || att.getDataLength() != getDataLength() /* compare data */ || att.lifetime != lifetime ) return false; return true; } /** * Returns the human readable name of this attribute. Attribute names do * not really matter from the protocol point of view. They are only used * for debugging and readability. * @return this attribute's name. */ @Override public String getName() { return NAME; } /** * Returns the length of this attribute's body. * @return the length of this attribute's value (8 bytes). */ @Override public char getDataLength() { return DATA_LENGTH; } /** * Returns a binary representation of this attribute. * @return a binary representation of this attribute. */ @Override public byte[] encode() { byte binValue[] = new byte[HEADER_LENGTH + DATA_LENGTH]; //Type binValue[0] = (byte)(getAttributeType() >> 8); binValue[1] = (byte)(getAttributeType() & 0x00FF); //Length binValue[2] = (byte)(getDataLength() >> 8); binValue[3] = (byte)(getDataLength() & 0x00FF); //Data binValue[4] = (byte)((lifetime >> 24) & 0xff); binValue[5] = (byte)((lifetime >> 16) & 0xff); binValue[6] = (byte)((lifetime >> 8) & 0xff); binValue[7] = (byte)((lifetime) & 0xff); return binValue; } /** * Sets this attribute's fields according to attributeValue array. * @param attributeValue a binary array containing this attribute's field * values and NOT containing the attribute header. * @param offset the position where attribute values begin (most often * offset is equal to the index of the first byte after * length) * @param length the length of the binary array. * @throws StunException if attrubteValue contains invalid data. */ @Override void decodeAttributeBody(byte[] attributeValue, char offset, char length) throws StunException { if(length != 4) { throw new StunException("length invalid"); } lifetime = ((attributeValue[offset + 0] << 24) & 0xff000000) + ((attributeValue[offset + 1] << 16) & 0x00ff0000) + ((attributeValue[offset + 2] << 8) & 0x0000ff00) + (attributeValue[offset + 3] & 0x000000ff); } /** * Set the lifetime. * @param lifetime lifetime */ public void setLifetime(int lifetime) { this.lifetime = lifetime; } /** * Get the lifetime. * @return lifetime */ public int getLifetime() { return lifetime; } }
package org.jgroups.protocols.raft; import org.apache.commons.io.FileUtils; import org.iq80.leveldb.*; import org.jgroups.Address; import org.jgroups.util.Util; import java.io.File; import java.io.IOException; import java.util.Map; import static org.fusesource.leveldbjni.JniDBFactory.*; import static org.jgroups.util.IntegerHelper.fromByteArrayToInt; import static org.jgroups.util.IntegerHelper.fromIntToByteArray; public class LevelDBLog implements Log { private static final byte[] FIRSTAPPLIED = "FA".getBytes(); private static final byte[] LASTAPPLIED = "LA".getBytes(); private static final byte[] CURRENTTERM = "CT".getBytes(); private static final byte[] COMMITINDEX = "CX".getBytes(); private static final byte[] VOTEDFOR = "VF".getBytes(); private DB db; private File dbFileName; private Integer currentTerm = 0; private Address votedFor; private Integer commitIndex = 0; private Integer lastApplied = 0; private Integer firstApplied = -1; @Override public void init(String log_name, Map<String,String> args) throws Exception { Options options = new Options(); options.createIfMissing(true); //String dir=Util.checkForMac()? File.separator + "tmp" : System.getProperty("java.io.tmpdir", File.separator + "tmp"); //filename=dir + File.separator + log_name; this.dbFileName = new File(log_name); db = factory.open(dbFileName, options); if (isANewRAFTLog()) { System.out.println("LOG is new, must be initialized"); initLogWithMetadata(); } else { System.out.println("LOG is existent, must not be initialized"); readMetadataFromLog(); } checkForConsistency(); } @Override public void close() { try { db.close(); } catch (IOException e) { //@todo proper logging, etc e.printStackTrace(); } } @Override public void delete() { this.close(); try { FileUtils.deleteDirectory(dbFileName); } catch (IOException e) { e.printStackTrace(); } } @Override public int currentTerm() { return currentTerm; } @Override public Log currentTerm(int new_term) { currentTerm = new_term; db.put(CURRENTTERM, fromIntToByteArray(currentTerm)); return this; } @Override public Address votedFor() { return votedFor; } @Override public Log votedFor(Address member) { votedFor = member; try { db.put(VOTEDFOR, Util.streamableToByteBuffer(member)); } catch (Exception e) { e.printStackTrace(); // todo: better error handling } return this; } @Override public int firstApplied() { return firstApplied; } @Override public int commitIndex() { return commitIndex; } @Override public Log commitIndex(int new_index) { commitIndex = new_index; try { db.put(COMMITINDEX, fromIntToByteArray(commitIndex)); } catch (Exception e) { e.printStackTrace(); // todo: better error handling } return this; } @Override public int lastApplied() { return lastApplied; } @Override public void append(int index, boolean overwrite, LogEntry... entries) { WriteBatch batch = db.createWriteBatch(); for (LogEntry entry : entries) { try { updateFirstApplied(index, batch); if (overwrite) { appendEntry(index, entry, batch); } else { appendEntryIfAbsent(index, entry, batch); } updateLastApplied(index, batch); updateCurrentTerm(entry, batch); db.write(batch); index++; } catch(Exception ex) { ex.printStackTrace(); // todo: better error handling } finally { try { batch.close(); } catch (IOException e) { e.printStackTrace(); // todo: better error handling } } } } @Override public AppendResult append(int prev_index, int prev_term, LogEntry[] entries) { if (checkIfPreviousEntryHasDifferentTerm(prev_index, prev_term)) { return new AppendResult(false, prev_index); } append(prev_index, true, entries); return new AppendResult(true, lastApplied); } private boolean checkIfPreviousEntryHasDifferentTerm(int prev_index, int prev_term) { LogEntry prev_entry = getLogEntry(prev_index); return prev_entry.term != prev_term; } private LogEntry getLogEntry(int index) { byte[] entryBytes = db.get(fromIntToByteArray(index)); LogEntry entry = null; try { if (entryBytes != null) entry = (LogEntry) Util.streamableFromByteBuffer(LogEntry.class, entryBytes); } catch (Exception e) { e.printStackTrace(); } return entry; } @Override public void forEach(Function function, int start_index, int end_index) { start_index = Math.max(start_index, firstApplied); end_index = Math.min(end_index, lastApplied); for (int i=start_index; i<=end_index; i++) { LogEntry entry = getLogEntry(i); System.out.println(entry); //function.apply(...) } } @Override public void forEach(Function function) { if (firstApplied == -1) { return; } this.forEach(function, firstApplied, lastApplied); } // Useful in debugging public byte[] print(byte[] bytes) { return db.get(bytes); } // Useful in debugging public void printMetadata() throws Exception { System.out.println(" System.out.println("RAFT Log Metadata"); System.out.println(" byte[] firstAppliedBytes = db.get(FIRSTAPPLIED); System.out.println("First Applied: " + fromByteArrayToInt(firstAppliedBytes)); byte[] lastAppliedBytes = db.get(LASTAPPLIED); System.out.println("Last Applied: " + fromByteArrayToInt(lastAppliedBytes)); byte[] currentTermBytes = db.get(CURRENTTERM); System.out.println("Current Term: " + fromByteArrayToInt(currentTermBytes)); byte[] commitIndexBytes = db.get(COMMITINDEX); System.out.println("Commit Index: " + fromByteArrayToInt(commitIndexBytes)); //Address votedFor = (Address)Util.streamableFromByteBuffer(Address.class, db.get(VOTEDFOR)); //System.out.println("Voted for: " + votedFor); } private void appendEntryIfAbsent(int index, LogEntry entry, WriteBatch batch) throws Exception { if (db.get(fromIntToByteArray(index))!= null) { throw new IllegalStateException("Entry at index " + index + " already exists"); } else { appendEntry(index, entry, batch); } } private void appendEntry(int index, LogEntry entry, WriteBatch batch) throws Exception { batch.put(fromIntToByteArray(index), Util.streamableToByteBuffer(entry)); } private void updateCurrentTerm(LogEntry entry, WriteBatch batch) { currentTerm=entry.term; batch.put(CURRENTTERM, fromIntToByteArray(currentTerm)); } private void updateLastApplied(int index, WriteBatch batch) { lastApplied = index; batch.put(LASTAPPLIED, fromIntToByteArray(lastApplied)); } private void updateFirstApplied(int index, WriteBatch batch) { if (firstApplied == -1) { firstApplied = index; batch.put(FIRSTAPPLIED, fromIntToByteArray(firstApplied)); } } private boolean isANewRAFTLog() { return (db.get(FIRSTAPPLIED) == null); } private void initLogWithMetadata() { WriteBatch batch = db.createWriteBatch(); try { batch.put(FIRSTAPPLIED, fromIntToByteArray(-1)); batch.put(LASTAPPLIED, fromIntToByteArray(0)); batch.put(CURRENTTERM, fromIntToByteArray(0)); batch.put(COMMITINDEX, fromIntToByteArray(0)); //batch.put(VOTEDFOR, Util.streamableToByteBuffer(Util.createRandomAddress(""))); db.write(batch); } catch (Exception ex) { ex.printStackTrace(); // todo: better error handling } finally { try { batch.close(); } catch (IOException e) { e.printStackTrace(); // todo: better error handling } } } private void readMetadataFromLog() throws Exception { firstApplied = fromByteArrayToInt(db.get(FIRSTAPPLIED)); lastApplied = fromByteArrayToInt(db.get(LASTAPPLIED)); currentTerm = fromByteArrayToInt(db.get(CURRENTTERM)); commitIndex = fromByteArrayToInt(db.get(COMMITINDEX)); //votedFor = (Address)Util.streamableFromByteBuffer(Address.class, db.get(VOTEDFOR)); } private void checkForConsistency() throws Exception { int loggedFirstApplied = fromByteArrayToInt(db.get(FIRSTAPPLIED)); int loggedLastApplied = fromByteArrayToInt(db.get(LASTAPPLIED)); int loggedCurrentTerm = fromByteArrayToInt(db.get(CURRENTTERM)); int loggedCommitIndex = fromByteArrayToInt(db.get(COMMITINDEX)); assert (firstApplied == loggedFirstApplied); assert (lastApplied == loggedLastApplied); assert (currentTerm == loggedCurrentTerm); assert (commitIndex == loggedCommitIndex); //check if last appended entry contains the correct term LogEntry lastAppendedEntry = getLogEntry(lastApplied); assert (lastAppendedEntry.term == currentTerm); } }
package com.github.susom.database; import java.util.Map; import org.slf4j.MDC; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.WorkerExecutor; /** * This is a convenience class to work-around issues with using the SLF4J * MDC class. It provides versions of async functionality that preserve * the MDC across the event and worker threads. * * @author garricko */ public class VertxUtil { /** * Wrap a Handler in a way that will preserve the SLF4J MDC context. * The context from the current thread at the time of this method call * will be cached and restored within the wrapper at the time the * handler is invoked. */ public static <T> Handler<T> mdc(Handler<T> handler) { Map mdc = MDC.getCopyOfContextMap(); return t -> { Map restore = MDC.getCopyOfContextMap(); try { if (mdc == null) { MDC.clear(); } else { MDC.setContextMap(mdc); } handler.handle(t); } finally { if (restore == null) { MDC.clear(); } else { MDC.setContextMap(restore); } } }; } /** * Equivalent to {@link Vertx#executeBlocking(Handler, Handler)}, * but preserves the {@link MDC} correctly. */ public static <T> void executeBlocking(Vertx vertx, Handler<Future<T>> future, Handler<AsyncResult<T>> handler) { executeBlocking(vertx, future, true, handler); } /** * Equivalent to {@link Vertx#executeBlocking(Handler, boolean, Handler)}, * but preserves the {@link MDC} correctly. */ public static <T> void executeBlocking(Vertx vertx, Handler<Future<T>> future, boolean ordered, Handler<AsyncResult<T>> handler) { vertx.executeBlocking(mdc(future), ordered, mdc(handler)); } /** * Equivalent to {@link Vertx#executeBlocking(Handler, Handler)}, * but preserves the {@link MDC} correctly. */ public static <T> void executeBlocking(WorkerExecutor executor, Handler<Future<T>> future, Handler<AsyncResult<T>> handler) { executeBlocking(executor, future, true, handler); } /** * Equivalent to {@link Vertx#executeBlocking(Handler, boolean, Handler)}, * but preserves the {@link MDC} correctly. */ public static <T> void executeBlocking(WorkerExecutor executor, Handler<Future<T>> future, boolean ordered, Handler<AsyncResult<T>> handler) { executor.executeBlocking(mdc(future), ordered, mdc(handler)); } }
package com.ilamstone.publicfortests; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.UUID; import java.util.logging.Logger; import java.util.stream.Collectors; import org.assertj.core.internal.asm.Opcodes; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Handle; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.util.TraceClassVisitor; public class PFTGen { private static final Logger log = Logger.getLogger(PFTGen.class.getName()); private static final Method defineClass; static { try { defineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class); } catch (NoSuchMethodException e) { System.err.println("NoSuchMethodException: defineClass on ClassLoader"); throw new RuntimeException("Unrecoverable Error", e); } defineClass.setAccessible(true); } private static final Set<Method> EMPTY_METHODS = Collections.emptySet(); private static final Set<Class<?>> EMPTY_CLASSES = Collections.emptySet(); static class TransformVisitor extends ClassVisitor { final Class<?> originalClass; final String originalClassInternalName; final String newClassInternalName; final ClassNode node = new ClassNode(); final Set<String> pftMethods; final Set<String> extraIfaces; public TransformVisitor(Class<?> originalClass, Set<Method> methods, Set<Class<?>> interfaces) { super(Opcodes.ASM5); this.cv = node; this.originalClass = originalClass; this.originalClassInternalName = Type.getInternalName(originalClass); this.newClassInternalName = originalClass.getPackage().getName().replace('.', '/') + "/GeneratedClass" + UUID.randomUUID(); pftMethods = methods.stream().map(m -> m.getName() + Type.getMethodDescriptor(m)).collect(Collectors.toSet()); extraIfaces = interfaces.stream().map(Type::getInternalName).collect(Collectors.toSet()); } @Override public void visit(int version, int access, String name, String signature, String superName, String[] originalInterfaces) { ArrayList<String> newIfaces = new ArrayList<String>(); for (String iface : originalInterfaces) { newIfaces.add(iface); } newIfaces.addAll(extraIfaces); super.visit(version, access, newClassInternalName, signature, superName, newIfaces.toArray(new String[newIfaces.size()])); } class TransformMethodVisitor extends MethodVisitor { public TransformMethodVisitor(MethodVisitor delegate) { super(Opcodes.ASM5, delegate); } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { if (originalClassInternalName.equals(owner)) { // We need to rewrite references to the original class to our new class. // This will probably be mostly INVOKESPECIALS, but also INVOKESTATICS as well. // In either case, refer to the method in our new class. Without this classes won't // verify when they call their own private methods. owner = newClassInternalName; } super.visitMethodInsn(opcode, owner, name, desc, itf); } @Override public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) { Object[] newArgs = new Object[bsmArgs.length]; for (int i = 0; i < bsmArgs.length; i++) { Object o = bsmArgs[i]; if (o instanceof Handle) { Handle h = (Handle)o; if (originalClassInternalName.equals(h.getOwner())) { newArgs[i] = new Handle(h.getTag(), newClassInternalName, h.getName(), h.getDesc(), h.isInterface()); } else { newArgs[i] = o; } } else { newArgs[i] = o; } } super.visitInvokeDynamicInsn(name, desc, bsm, newArgs); } @Override public void visitFieldInsn(int opcode, String owner, String name, String desc) { if (originalClassInternalName.equals(owner)) { owner = newClassInternalName; } super.visitFieldInsn(opcode, owner, name, desc); } } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (pftMethods.contains(name + desc)) { access = access & ~Opcodes.ACC_PRIVATE & ~Opcodes.ACC_PROTECTED; access = access | Opcodes.ACC_PUBLIC; } return new TransformMethodVisitor(cv.visitMethod(access, name, desc, signature, exceptions)); } public ClassNode getNode() { return this.node; } } /* * This is just a POJO that holds a set of methods and a set of interfaces. * It's used as the return value from findPftMethodsAndInterfaces. */ static class PftMethodsAndInterfaces { HashSet<Method> methods = new HashSet<Method>(); HashSet<Class<?>> interfaces = new HashSet<Class<?>>(); } /* * Find all methods in the given class that are annotated with the {@link PublicForTests} annotation. * * @param originalClass The class to search. * * @return A {@link PftMethodsAndInterfaces} containing the found methods and the interfaces from the annotations. */ static PftMethodsAndInterfaces findPftMethodsAndInterfaces(Class<?> originalClass) { PftMethodsAndInterfaces pftmi = new PftMethodsAndInterfaces(); for (Method m : originalClass.getDeclaredMethods()) { PublicForTests pft = m.getAnnotation(PublicForTests.class); if (pft != null) { try { Class<?> ifaceClass = Class.forName(pft.value()); pftmi.methods.add(m); pftmi.interfaces.add(ifaceClass); } catch (ClassNotFoundException e) { log.warning(() -> "Testing interface '" + pft.value() + "' not found for method '" + m.toGenericString() + "'"); log.warning(() -> " This method will not be made public; This may cause ClassCastExceptions later on..."); } } } return pftmi; } /* * Main worker method of this class. Uses a {@link TransformVisitor} to generate an ASM `ClassNode`. * * @param clz The original class. * @param extraMethods Additional methods to make public (additional to those marked with {@literal @}PublicForTests). * @param extraInterfaces Additional interfaces to implement (additional to those marked with {@literal @}PublicForTests). * @param trace If non-null, the resulting class will be dumped (with a `TraceClassVisitor` to the given stream. * * @return The generated `ClassNode`. This can be visited by a `ClassWriter` to actually generate bytecode. * * @throws IOException If the original class cannot be read. */ static ClassNode generateNewClassNode(Class<?> clz, Set<Method> extraMethods, Set<Class<?>> extraInterfaces, PrintStream trace) throws IOException { String clzInternalName = Type.getInternalName(clz); ClassReader reader = new ClassReader(clzInternalName); // Find the annotated methods (and their interfaces) PftMethodsAndInterfaces pftmi = findPftMethodsAndInterfaces(clz); // And add in any extra methods/interfaces we've geen given... if (extraMethods != null) { pftmi.methods.addAll(extraMethods); } if (extraInterfaces != null) { pftmi.interfaces.addAll(extraInterfaces); } TransformVisitor visitor = new TransformVisitor(clz, pftmi.methods, pftmi.interfaces); reader.accept(visitor, ClassReader.SKIP_DEBUG); if (trace != null) { visitor.getNode().accept(new TraceClassVisitor(new PrintWriter(System.out))); } return visitor.getNode(); } static byte[] generateBytecode(ClassNode node) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); node.accept(writer); return writer.toByteArray(); } static Class<?> defineClass(ClassLoader loader, ClassNode node) { byte[] code = generateBytecode(node); try { return (Class<?>)defineClass.invoke(loader, node.name.replace('/', '.'), code, 0, code.length); } catch (InvocationTargetException e) { System.err.println("InvocationTargetException: in defineClass: " + e.getMessage()); throw new RuntimeException("Unrecoverable Error", e); } catch (IllegalAccessException e) { System.err.println("IllegalAccessException: in defineClass: " + e.getMessage()); throw new RuntimeException("Unrecoverable Error", e); } } /** * Generates a new class based on `clz` and then defines it in the given classloader. Any methods in `clz` * marked with the {@link PublicForTests} annotation will be made public, along with any methods supplied * in the `extraMethods` Set. * * The resulting class will implement all interfaces supplied in by the {@link PublicForTests} annotations, * along with any interfaces supplied in the `extraInterfaces` Set. * * @param clz The original class. * @param extraMethods Additional methods to make public (additional to those marked with {@literal @}PublicForTests). * @param extraInterfaces Additional interfaces to implement (additional to those marked with {@literal @}PublicForTests). * @param trace If non-null, the resulting class will be dumped (with a `TraceClassVisitor` to the given stream. * * @return The new `Class` object. */ @SuppressWarnings("unchecked") public static <I> Class<I> getTestingClass(ClassLoader loader, Class<?> clz, Set<Method> extraMethods, Set<Class<?>> extraInterfaces, PrintStream trace) { try { return (Class<I>)defineClass(loader, generateNewClassNode(clz, extraMethods, extraInterfaces, trace)); } catch (IOException e) { System.err.println("IOException: in getTestingClass: " + e.getMessage()); throw new RuntimeException("Unrecoverable Error", e); } } public static <I> Class<I> getTestingClass(ClassLoader loader, Class<?> clz, Set<Method> extraMethods, Set<Class<?>> extraInterfaces) { return getTestingClass(loader, clz, extraMethods, extraInterfaces, null); } public static <I> Class<I> getTestingClass(Class<?> clz, Set<Method> extraMethods, Set<Class<?>> extraInterfaces) { return getTestingClass(PFTGen.class.getClassLoader(), clz, extraMethods, extraInterfaces, null); } public static <I> Class<I> getTestingClass(ClassLoader loader, Class<?> clz) { return getTestingClass(loader, clz, EMPTY_METHODS, EMPTY_CLASSES, null); } public static <I> Class<I> getTestingClass(Class<?> clz, PrintStream trace) { return getTestingClass(PFTGen.class.getClassLoader(), clz, EMPTY_METHODS, EMPTY_CLASSES, trace); } public static <I> Class<I> getTestingClass(Class<?> clz) { return getTestingClass(PFTGen.class.getClassLoader(), clz); } }
package org.ojalgo.matrix.store; import org.ojalgo.ProgrammingError; import org.ojalgo.constant.PrimitiveMath; import org.ojalgo.scalar.Scalar; /** * IdentityStore * * @author apete */ final class IdentityStore<N extends Number> extends FactoryStore<N> { private IdentityStore(final org.ojalgo.matrix.store.PhysicalStore.Factory<N, ?> factory, final int rowsCount, final int columnsCount) { super(factory, rowsCount, columnsCount); ProgrammingError.throwForIllegalInvocation(); } IdentityStore(final PhysicalStore.Factory<N, ?> factory, final int dimension) { super(factory, dimension, dimension); } @Override public MatrixStore<N> conjugate() { return this; } public double doubleValue(final long aRow, final long aCol) { if (aRow == aCol) { return PrimitiveMath.ONE; } else { return PrimitiveMath.ZERO; } } public int firstInColumn(final int col) { return col; } public int firstInRow(final int row) { return row; } public N get(final long aRow, final long aCol) { if (aRow == aCol) { return this.physical().scalar().one().getNumber(); } else { return this.physical().scalar().zero().getNumber(); } } @Override public int limitOfColumn(final int col) { return col + 1; } @Override public int limitOfRow(final int row) { return row + 1; } @Override public MatrixStore<N> multiply(final MatrixStore<N> right) { return right.copy(); } public Scalar<N> toScalar(final long row, final long column) { if (row == column) { return this.physical().scalar().one(); } else { return this.physical().scalar().zero(); } } @Override public MatrixStore<N> transpose() { return this; } @Override protected void addNonZerosTo(final ElementsConsumer<N> consumer) { consumer.fillDiagonal(0L, 0L, this.physical().scalar().one().getNumber()); } }
package com.imcode.imcms.api; import com.imcode.imcms.domain.dto.DocumentStoredFieldsDTO; import lombok.Data; @Data public class ValidationLink { private boolean pageFound; private boolean hostFound; private boolean hostReachable; private String url; private EditLink editLink; private DocumentStoredFieldsDTO documentData; }
package org.opencms.ui.apps; import org.opencms.file.CmsObject; import org.opencms.file.CmsProject; import org.opencms.main.CmsBroadcast; import org.opencms.main.CmsLog; import org.opencms.main.CmsSessionInfo; import org.opencms.main.OpenCms; import org.opencms.ui.A_CmsUI; import org.opencms.ui.CmsVaadinErrorHandler; import org.opencms.ui.CmsVaadinUtils; import org.opencms.ui.I_CmsAppView; import org.opencms.ui.apps.CmsWorkplaceAppManager.NavigationState; import org.opencms.ui.components.I_CmsWindowCloseListener; import org.opencms.ui.components.extensions.CmsHistoryExtension; import org.opencms.ui.components.extensions.CmsPollServerExtension; import org.opencms.ui.components.extensions.CmsWindowCloseExtension; import org.opencms.ui.contextmenu.CmsContextMenuItemProviderGroup; import org.opencms.ui.contextmenu.I_CmsContextMenuItemProvider; import org.opencms.util.CmsExpiringValue; import org.opencms.util.CmsStringUtil; import org.opencms.workplace.CmsWorkplaceManager; import org.opencms.workplace.CmsWorkplaceSettings; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.commons.collections.Buffer; import org.apache.commons.logging.Log; import com.vaadin.annotations.PreserveOnRefresh; import com.vaadin.annotations.Theme; import com.vaadin.navigator.NavigationStateManager; import com.vaadin.navigator.Navigator; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener; import com.vaadin.navigator.ViewDisplay; import com.vaadin.navigator.ViewProvider; import com.vaadin.server.Page; import com.vaadin.server.Page.BrowserWindowResizeEvent; import com.vaadin.server.Page.BrowserWindowResizeListener; import com.vaadin.server.VaadinRequest; import com.vaadin.server.WrappedHttpSession; import com.vaadin.ui.AbstractComponent; import com.vaadin.ui.Component; import com.vaadin.ui.Notification; import com.vaadin.ui.Notification.Type; import com.vaadin.ui.Window; /** * The workplace ui.<p> */ @Theme("opencms") @PreserveOnRefresh public class CmsAppWorkplaceUi extends A_CmsUI implements ViewDisplay, ViewProvider, ViewChangeListener, I_CmsWindowCloseListener { /** * View which directly changes the state to the launchpad.<p> */ class LaunchpadRedirectView implements View { /** Serial version id. */ private static final long serialVersionUID = 1L; /** * @see com.vaadin.navigator.View#enter(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent) */ public void enter(ViewChangeEvent event) { A_CmsUI.get().getNavigator().navigateTo(CmsAppHierarchyConfiguration.APP_ID); } } /** The editor window name, used for page and sitemap editor. */ public static final String EDITOR_WINDOW_NAME = "opencms_edit_window"; /** The OpenCms window title prefix. */ public static final String WINDOW_TITLE_PREFIX = "OpenCms - "; /** Logger instance for this class. */ private static final Log LOG = CmsLog.getLog(CmsAppWorkplaceUi.class); /** Menu item manager. */ private static CmsContextMenuItemProviderGroup m_workplaceMenuItemProvider; /** The serial version id. */ private static final long serialVersionUID = -5606711048683809028L; static { m_workplaceMenuItemProvider = new CmsContextMenuItemProviderGroup(); m_workplaceMenuItemProvider.addProvider(CmsDefaultMenuItemProvider.class); m_workplaceMenuItemProvider.initialize(); } /** Launch pad redirect view. */ protected View m_launchRedirect = new LaunchpadRedirectView(); /** The cached views. */ private Map<String, I_CmsAppView> m_cachedViews; /** The current view in case it implements view change listener. */ private View m_currentView; /** The has errors flag. */ private boolean m_hasErrors; /** The history extension. */ private CmsHistoryExtension m_history; /** Cache for workplace locale. */ private CmsExpiringValue<Locale> m_localeCache = new CmsExpiringValue<Locale>(1000); /** The navigation state manager. */ private NavigationStateManager m_navigationStateManager; /** Flag indicating that the view is being refreshed. */ private boolean m_refreshing; /** * Gets the current UI instance.<p> * * @return the current UI instance */ public static CmsAppWorkplaceUi get() { return (CmsAppWorkplaceUi)A_CmsUI.get(); } /** * Sets the window title adding an OpenCms prefix.<p> * * @param title the window title */ public static void setWindowTitle(String title) { get().getPage().setTitle(WINDOW_TITLE_PREFIX + title); } /** * @see com.vaadin.navigator.ViewChangeListener#afterViewChange(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent) */ public void afterViewChange(ViewChangeEvent event) { if ((m_currentView != null) && (m_currentView instanceof ViewChangeListener)) { ((ViewChangeListener)m_currentView).afterViewChange(event); } } /** * @see com.vaadin.navigator.ViewChangeListener#beforeViewChange(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent) */ public boolean beforeViewChange(ViewChangeEvent event) { cacheView(m_currentView); if ((m_currentView != null) && (m_currentView instanceof ViewChangeListener)) { return ((ViewChangeListener)m_currentView).beforeViewChange(event); } return true; } /** * Call to add a new browser history entry.<p> * * @param state the current app view state */ public void changeCurrentAppState(String state) { String completeState = m_navigationStateManager.getState(); String view = getViewName(completeState); String newCompleteState = view; if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(state)) { newCompleteState += NavigationState.PARAM_SEPARATOR + state; } m_navigationStateManager.setState(newCompleteState); } /** * Changes to the given project. Will update session and workplace settings.<p> * * @param project the project to change to */ public void changeProject(CmsProject project) { if (!getCmsObject().getRequestContext().getCurrentProject().equals(project)) { getCmsObject().getRequestContext().setCurrentProject(project); getWorkplaceSettings().setProject(project.getUuid()); OpenCms.getSessionManager().updateSessionInfo(getCmsObject(), getHttpSession()); } } /** * Changes to the given site. Will update session and workplace settings.<p> * * @param siteRoot the site to change to */ public void changeSite(String siteRoot) { if (!getCmsObject().getRequestContext().getSiteRoot().equals(siteRoot)) { getCmsObject().getRequestContext().setSiteRoot(siteRoot); getWorkplaceSettings().setSite(siteRoot); OpenCms.getSessionManager().updateSessionInfo(getCmsObject(), getHttpSession()); } } /** * Checks for new broadcasts.<p> */ public void checkBroadcasts() { CmsSessionInfo info = OpenCms.getSessionManager().getSessionInfo(getHttpSession()); Buffer queue = info.getBroadcastQueue(); if (!queue.isEmpty()) { StringBuffer broadcasts = new StringBuffer(); while (!queue.isEmpty()) { CmsBroadcast broadcastMessage = (CmsBroadcast)queue.remove(); String from = broadcastMessage.getUser() != null ? broadcastMessage.getUser().getName() : CmsVaadinUtils.getMessageText(org.opencms.workplace.Messages.GUI_LABEL_BROADCAST_FROM_SYSTEM_0); String date = CmsVaadinUtils.getWpMessagesForCurrentLocale().getDateTime( broadcastMessage.getSendTime()); String content = broadcastMessage.getMessage(); broadcasts.append("<p><em>").append(date).append("</em><br />"); broadcasts.append( CmsVaadinUtils.getMessageText( org.opencms.workplace.Messages.GUI_LABEL_BROADCASTMESSAGEFROM_0)).append(" <b>").append( from).append("</b>:<br />"); broadcasts.append(content).append("<br /></p>"); } Notification notification = new Notification( CmsVaadinUtils.getMessageText(Messages.GUI_BROADCAST_TITLE_0), broadcasts.toString(), Type.ERROR_MESSAGE, true); notification.show(getPage()); } } /** * @see com.vaadin.ui.UI#detach() */ @Override public void detach() { clearCachedViews(); super.detach(); } /** * Disables the global keyboard shortcuts.<p> */ public void disableGlobalShortcuts() { if (m_currentView instanceof I_CmsAppView) { ((I_CmsAppView)m_currentView).disableGlobalShortcuts(); } } /** * Enables the global keyboard shortcuts.<p> */ public void enableGlobalShortcuts() { if (m_currentView instanceof I_CmsAppView) { ((I_CmsAppView)m_currentView).enableGlobalShortcuts(); } } /** * Returns the state parameter of the current app.<p> * * @return the state parameter of the current app */ public String getAppState() { NavigationState state = new NavigationState(m_navigationStateManager.getState()); return state.getParams(); } /** * Returns the HTTP session.<p> * * @return the HTTP session */ public HttpSession getHttpSession() { return ((WrappedHttpSession)getSession().getSession()).getHttpSession(); } /** * @see com.vaadin.ui.AbstractComponent#getLocale() */ @Override public Locale getLocale() { Locale result = m_localeCache.get(); if (result == null) { CmsObject cms = getCmsObject(); result = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); m_localeCache.set(result); } return result; } /** * Gets the menu item provider for the workplace.<p> * * @return the menu item provider */ public I_CmsContextMenuItemProvider getMenuItemProvider() { return m_workplaceMenuItemProvider; } /** * @see com.vaadin.navigator.ViewProvider#getView(java.lang.String) */ public View getView(String viewName) { if (m_cachedViews.containsKey(viewName)) { return m_cachedViews.get(viewName); } I_CmsWorkplaceAppConfiguration appConfig = OpenCms.getWorkplaceAppManager().getAppConfiguration(viewName); if (appConfig != null) { return new CmsAppView(appConfig); } else { LOG.warn("Nonexistant view '" + viewName + "' requested"); return m_launchRedirect; } } /** * @see com.vaadin.navigator.ViewProvider#getViewName(java.lang.String) */ public String getViewName(String viewAndParameters) { NavigationState state = new NavigationState(viewAndParameters); return state.getViewName(); } /** * Returns the workplace settings.<p> * * @return the workplace settings */ public CmsWorkplaceSettings getWorkplaceSettings() { return (CmsWorkplaceSettings)getSession().getSession().getAttribute( CmsWorkplaceManager.SESSION_WORKPLACE_SETTINGS); } /** * Executes the history back function.<p> */ public void historyBack() { m_history.historyBack(); } /** * Executes the history forward function.<p> */ public void historyForward() { m_history.historyForward(); } /** * Sets the has errors flag.<p> */ public void onError() { m_hasErrors = true; } /** * @see org.opencms.ui.components.I_CmsWindowCloseListener#onWindowClose() */ public void onWindowClose() { if ((m_currentView != null) && (m_currentView instanceof I_CmsWindowCloseListener)) { ((I_CmsWindowCloseListener)m_currentView).onWindowClose(); } cacheView(m_currentView); } /** * Reloads the current UI.<p> */ public void reload() { if (m_currentView instanceof I_CmsAppView) { Component component = ((I_CmsAppView)m_currentView).reinitComponent(); setContent(component); ((I_CmsAppView)m_currentView).enter(getAppState()); } } /** * @see com.vaadin.ui.UI#setLastHeartbeatTimestamp(long) */ @Override public void setLastHeartbeatTimestamp(long lastHeartbeat) { super.setLastHeartbeatTimestamp(lastHeartbeat); // check for new broadcasts on every heart beat checkBroadcasts(); } /** * Navigates to the given app.<p> * * @param appConfig the app configuration */ public void showApp(I_CmsWorkplaceAppConfiguration appConfig) { getNavigator().navigateTo(appConfig.getId()); } /** * Navigates to the given app.<p> * * @param appConfig the app configuration * @param state the app state to call */ public void showApp(I_CmsWorkplaceAppConfiguration appConfig, String state) { getNavigator().navigateTo(appConfig.getId() + "/" + state); } /** * Navigates to the home screen.<p> */ public void showHome() { getNavigator().navigateTo(CmsAppHierarchyConfiguration.APP_ID); } /** * @see com.vaadin.navigator.ViewDisplay#showView(com.vaadin.navigator.View) */ public void showView(View view) { for (Window window : A_CmsUI.get().getWindows()) { window.close(); } // remove current component form the view change listeners m_currentView = view; Component component = null; if (view instanceof I_CmsAppView) { component = ((I_CmsAppView)view).getComponent(); } else if (view instanceof Component) { component = (Component)view; } if (component != null) { setContent(component); } } /** * @see com.vaadin.ui.UI#init(com.vaadin.server.VaadinRequest) */ @Override protected void init(VaadinRequest req) { super.init(req); getSession().setErrorHandler(new CmsVaadinErrorHandler(this)); m_cachedViews = new HashMap<String, I_CmsAppView>(); m_navigationStateManager = new Navigator.UriFragmentManager(getPage()); Navigator navigator = new Navigator(this, m_navigationStateManager, this); navigator.addProvider(this); setNavigator(navigator); Page.getCurrent().addBrowserWindowResizeListener(new BrowserWindowResizeListener() { private static final long serialVersionUID = 1L; public void browserWindowResized(BrowserWindowResizeEvent event) { markAsDirtyRecursive(); } }); m_history = new CmsHistoryExtension(getCurrent()); CmsWindowCloseExtension windowClose = new CmsWindowCloseExtension(getCurrent()); windowClose.addWindowCloseListener(this); navigator.addViewChangeListener(this); navigateToFragment(); } /** * @see com.vaadin.ui.UI#refresh(com.vaadin.server.VaadinRequest) */ @Override protected void refresh(VaadinRequest request) { if (m_hasErrors) { m_refreshing = true; m_hasErrors = false; clearCachedViews(); navigateToFragment(); m_refreshing = false; } } /** * Caches the given view in case it implements the I_CmsAppView interface and is cachable.<p> * * @param view the view to cache */ private void cacheView(View view) { if (!m_refreshing && (view instanceof I_CmsAppView) && ((I_CmsAppView)view).isCachable()) { m_cachedViews.put(((I_CmsAppView)view).getName(), (I_CmsAppView)view); } } /** * Clears the cached views.<p> */ private void clearCachedViews() { m_cachedViews.clear(); } /** * Initializes client polling to avoid session expiration<p> * * @param component the view component */ @SuppressWarnings("unused") private void initializeClientPolling(Component component) { if (component instanceof AbstractComponent) { new CmsPollServerExtension((AbstractComponent)component); } } /** * Navigates to the current URI fragment.<p> */ private void navigateToFragment() { String fragment = getPage().getUriFragment(); if (fragment != null) { getNavigator().navigateTo(fragment); } else { showHome(); } } }
package org.openid4java.message; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.util.*; import java.util.List; import java.net.URLDecoder; /** * A list of parameters that are part of an OpenID message. Please note that you can have multiple parameters with * the same name. * * @author Marius Scurtescu, Johnny Bufu */ public class ParameterList implements Serializable { private static Log _log = LogFactory.getLog(ParameterList.class); private static final boolean DEBUG = _log.isDebugEnabled(); Map _parameterMap; public ParameterList() { _parameterMap = new LinkedHashMap(); if (DEBUG) _log.debug("Created empty parameter list."); } public ParameterList(ParameterList that) { if (DEBUG) _log.debug("Cloning parameter list:\n" + that); this._parameterMap = new LinkedHashMap(that._parameterMap); } /** * Constructs a ParameterList from a Map of parameters, ideally obtained * with ServletRequest.getParameterMap(). The parameter keys and values * must be in URL-decoded format. * * @param parameterMap Map<String,String[]> or Map<String,String> */ public ParameterList(Map parameterMap) { _parameterMap = new LinkedHashMap(); Iterator keysIter = parameterMap.keySet().iterator(); while (keysIter.hasNext()) { String name = (String) keysIter.next(); Object v = parameterMap.get(name); String value; if (v instanceof String[]) { String[] values = (String[]) v; if (values.length > 1 && name.startsWith("openid.")) throw new IllegalArgumentException( "Multiple parameters with the same name: " + values); value = values.length > 0 ? values[0] : null; } else if (v instanceof String) { value = (String) v; } else { value=""; _log.error("Can extract parameter value; unexpected type: " + v.getClass().getName()); } set(new Parameter(name, value)); } if (DEBUG) _log.debug("Creating parameter list:\n" + this); } public void copyOf(ParameterList that) { if (DEBUG) _log.debug("Copying parameter list:\n" + that); this._parameterMap = new LinkedHashMap(that._parameterMap); } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; final ParameterList that = (ParameterList) obj; return _parameterMap.equals(that._parameterMap); } public int hashCode() { return _parameterMap.hashCode(); } public void set(Parameter parameter) { _parameterMap.put(parameter.getKey(), parameter); } public void addParams(ParameterList params) { Iterator iter = params.getParameters().iterator(); while (iter.hasNext()) set((Parameter) iter.next()); } public Parameter getParameter(String name) { return (Parameter) _parameterMap.get(name); } public String getParameterValue(String name) { Parameter param = getParameter(name); return param != null ? param.getValue() : null; } public List getParameters() { return new ArrayList(_parameterMap.values()); } public void removeParameters(String name) { _parameterMap.remove(name); } public boolean hasParameter(String name) { return _parameterMap.containsKey(name); } /** * Create a parameter list based on a URL encoded HTTP query string. */ public static ParameterList createFromQueryString(String queryString) throws MessageException { if (DEBUG) _log.debug("Creating parameter list from query string: " + queryString); ParameterList parameterList = new ParameterList(); StringTokenizer tokenizer = new StringTokenizer(queryString, "&"); while (tokenizer.hasMoreTokens()) { String keyValue = tokenizer.nextToken(); int posEqual = keyValue.indexOf('='); if (posEqual == -1) throw new MessageException("Invalid query parameter, = missing: " + keyValue); try { String key = URLDecoder.decode(keyValue.substring(0, posEqual), "UTF-8"); String value = URLDecoder.decode(keyValue.substring(posEqual + 1), "UTF-8"); parameterList.set(new Parameter(key, value)); } catch (UnsupportedEncodingException e) { throw new MessageException("Cannot URL decode query parameter: " + keyValue, e); } } return parameterList; } public static ParameterList createFromKeyValueForm(String keyValueForm) throws MessageException { if (DEBUG) _log.debug("Creating parameter list from key-value form:\n" + keyValueForm); ParameterList parameterList = new ParameterList(); StringTokenizer tokenizer = new StringTokenizer(keyValueForm, "\n"); while (tokenizer.hasMoreTokens()) { String keyValue = tokenizer.nextToken(); int posColon = keyValue.indexOf(':'); if (posColon == -1) throw new MessageException("Invalid Key-Value form, colon missing: " + keyValue); String key = keyValue.substring(0, posColon); String value = keyValue.substring(posColon + 1); parameterList.set(new Parameter(key, value)); } return parameterList; } // todo: same as Message.keyValueFormEncoding() public String toString() { StringBuffer allParams = new StringBuffer(""); List parameters = getParameters(); Iterator iterator = parameters.iterator(); while (iterator.hasNext()) { Parameter parameter = (Parameter) iterator.next(); allParams.append(parameter.getKey()); allParams.append(':'); allParams.append(parameter.getValue()); allParams.append('\n'); } return allParams.toString(); } }
package com.jgardella.app.backend; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Iterator; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFSheet; public class XLSParser { static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd h:mm a"); public static Event parseXLS(File xlsFile) throws IOException, InvalidFormatException { Event event = null; InputStream fis = new FileInputStream(xlsFile); XSSFWorkbook workbook = new XSSFWorkbook(fis); XSSFSheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); rowIterator.next(); // skip first row (headers) while(rowIterator.hasNext()) { Row row = rowIterator.next(); if(row.getRowNum() == 1) // create event from first row with data { String str_eventDate = row.getCell(0).getRichStringCellValue().getString(); // if the hour is a single digit, there is an extra space in the date. // remove it so it can be parsed correctly. // remove any excessive spacing, while we're at it str_eventDate = str_eventDate.replaceAll(" +", " "); LocalDateTime eventDate = LocalDateTime.parse(str_eventDate, TIME_FORMAT); event = new Event(xlsFile.getName().substring(0, xlsFile.getName().indexOf('.')), xlsFile.getParentFile().getName(), eventDate); } if(row.getCell(1) != null) { // create member and add to event attendance int id = (int) row.getCell(1).getNumericCellValue(); String lastName = row.getCell(2).getRichStringCellValue().getString(); String firstName = row.getCell(3).getRichStringCellValue().getString(); event.addMemberToAttendance(new Member(firstName, lastName, id)); } } workbook.close(); return event; } }
package org.quinto.swing.table.view; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Rectangle; import java.awt.Toolkit; 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.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JViewport; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.TableColumnModelEvent; import javax.swing.event.TableColumnModelListener; import javax.swing.event.TableModelEvent; import javax.swing.plaf.TableHeaderUI; import javax.swing.plaf.TableUI; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import org.apache.log4j.Logger; import org.quinto.swing.table.model.IModelFieldGroup; import org.quinto.swing.table.model.ModelData; import org.quinto.swing.table.model.ModelField; import org.quinto.swing.table.model.Utils; public class JBroTable extends JTable { private static final Logger LOGGER = Logger.getLogger( JBroTable.class ); private static final Pattern BR_PATTERN = Pattern.compile( "<br>|<br/>", Pattern.CASE_INSENSITIVE ); private static final Pattern TAG_PATTERN = Pattern.compile( "<[^<>]++>" ); private Integer headerHeight; private HeaderHeightWatcher headerHeightWatcher; private Integer currentLevel; private JScrollPane scrollPane; /** * This field points to a main table for a fixed table * (fixed table is just a non-scrollable part of the main table). * This field is null for a regular table. */ private JBroTable masterTable; public JBroTable() { this( null ); } public JBroTable( ModelData data ) { super( new JBroTableModel( data ) ); super.setUI( new JBroTableUI() ); checkFieldWidths(); refresh(); } @Override public void setUI( TableUI ui ) { JBroTableUI oldUI = getUI(); if ( oldUI != null || ui instanceof JBroTableUI ) { super.setUI( ui ); if ( !( ui instanceof JBroTableUI ) ) { if ( ui != null ) ui.uninstallUI( this ); this.ui = oldUI; oldUI.setNoDefaults( true ); oldUI.installUI( this ); oldUI.setNoDefaults( false ); firePropertyChange( "UI", ui, oldUI ); refresh(); } } } @Override public JBroTableUI getUI() { return ( JBroTableUI )super.getUI(); } /** * Set the whole header height. * @param headerHeight the whole header height, {@code null} means to let Swing determine it * @deprecated use {@link JBroTableHeader#setRowHeight( int, java.lang.Integer )} instead */ @Deprecated public void setHeaderHeight( Integer headerHeight ) { if ( headerHeight == null ) { if ( headerHeightWatcher != null ) { getColumnModel().removeColumnModelListener( headerHeightWatcher ); } } else if ( this.headerHeight == null ) { getColumnModel().addColumnModelListener( headerHeightWatcher = new HeaderHeightWatcher() ); } this.headerHeight = headerHeight; updateHeaderSize(); } /** * Get the whole header height. * @return the whole header height. Zero value may mean that the height is determined by Swing * @deprecated use {@link JBroTableHeader#getRowHeight( int )} instead */ @Deprecated public int getHeaderHeight() { return headerHeight == null ? 0 : headerHeight; } private void refresh() { revalidate(); repaint( getVisibleRect() ); } @Override public JBroTableModel getModel() { return ( JBroTableModel )super.getModel(); } public ModelData getData() { return getModel().getData(); } public void updateHeaderSize() { if ( headerHeight == null || headerHeight < 0 ) { return; } JTableHeader header = getTableHeader(); int h = headerHeight; TableColumnModel cmodel = getColumnModel(); Font font = header.getFont(); FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics( font ); for ( int c = 0; c < cmodel.getColumnCount(); c++ ) { TableColumn column = cmodel.getColumn( c ); String text = String.valueOf( column.getHeaderValue() ); if ( text != null && text.length() >= 6 && text.charAt( 0 ) == '<' && text.substring( 0, 6 ).equalsIgnoreCase( "<html>" ) ) { text = BR_PATTERN.matcher( text ).replaceAll( "\n" ); text = TAG_PATTERN.matcher( text ).replaceAll( "" ); } text = Utils.getTextWithWordWraps( text, fm, column.getWidth() - 8 ); int newLines = 0; if ( text != null ) { char chars[] = text.toCharArray(); for ( char ch : chars ) if ( ch == '\n' ) newLines++; } int height = ( newLines + 1 ) * fm.getHeight() + 6; if ( height > h ) h = height; } TableHeaderUI ui = header.getUI(); if ( ui instanceof JBroTableHeaderUI ) { JBroTableHeaderUI gui = ( JBroTableHeaderUI )ui; Dimension d = gui.getPreferredSize( header ); if ( h > d.height ) { int levels = gui.getHeader().getLevelsQuantity(); int lastRowHeight = gui.getRowHeight( levels - 1 ); gui.setRowHeight( levels - 1, lastRowHeight + h - d.height ); } } header.setPreferredSize( new Dimension( cmodel.getTotalColumnWidth(), h ) ); } private void checkFieldWidths() { ModelData data = getData(); if ( data == null ) return; ModelField fields[] = data.getFields(); if ( fields == null ) return; boolean changed = false; boolean tableIsJustAFixedPart = getMasterTable() != null; for ( int i = columnModel.getColumnCount() - 1; i >= 0; i TableColumn column = columnModel.getColumn( i ); int modelIndex = column.getModelIndex(); ModelField field = fields[ modelIndex ]; if ( field.isVisible() && field.isFixed() == tableIsJustAFixedPart ) { String headerValue = field.getCaption(); if ( !Utils.equals( headerValue, column.getHeaderValue() ) ) { column.setHeaderValue( headerValue ); changed = true; } Integer defaultWidth = field.getDefaultWidth(); if ( defaultWidth != null && defaultWidth >= 0 ) { defaultWidth = Math.min( Math.max( defaultWidth, column.getMinWidth() ), column.getMaxWidth() ); if ( defaultWidth != column.getPreferredWidth() ) { column.setPreferredWidth( defaultWidth ); changed = true; } } } else { changed = true; removeColumn( column ); } } if ( changed ) tableStructureChanged(); } /** * Set new data. * @param data new array of data */ public void setData( ModelData data ) { getModel().setData( data ); checkFieldWidths(); refresh(); } @Override public void setModel( TableModel dataModel ) { super.setModel( dataModel ); checkFieldWidths(); refresh(); } /** * Set new order of columns (including visibility). Does not affect table model. * @param newFields a list of new fields identifiers */ public void reorderFields( String newFields[] ) { ModelData data = getData(); ModelField modelFields[] = data.getFields(); // Column indexes in model LinkedHashMap< String, Integer > modelPositions = ModelField.getIndexes( modelFields ); // Current order of visible columns LinkedHashSet< Integer > iold = new LinkedHashSet< Integer >( modelFields.length ); for ( int i = 0; i < columnModel.getColumnCount(); i++ ) { TableColumn column = columnModel.getColumn( i ); iold.add( column.getModelIndex() ); } // New order of visible columns LinkedHashSet< Integer > inew = new LinkedHashSet< Integer >( modelFields.length ); for ( int i = 0; i < newFields.length; i++ ) { if ( newFields[ i ] == null ) { continue; } Integer pos = modelPositions.get( newFields[ i ] ); // Fields list doesn't correspond to current data array if ( pos == null ) { LOGGER.warn( "reorderFields called on obsolete data model. Call setData first." ); return; } inew.add( pos ); } ArrayList< ModelField > manageable = null; // Delete absent columns for ( Iterator< Integer > it = iold.iterator(); it.hasNext(); ) { Integer pos = it.next(); if ( !inew.contains( pos ) ) { ModelField field = modelFields[ pos ]; if ( field.isManageable() ) { it.remove(); field.setVisible( false ); removeColumn( columnModel.getColumn( convertColumnIndexToView( pos ) ) ); } else { field.setManageable( true ); if ( manageable == null ) manageable = new ArrayList< ModelField >(); manageable.add( field ); // Exceptional event: unmanageable column was hidden. It should become visible again. // This situation is really rare (API doesn't allow this to happen), so performance is not an issue. // Traversing the whole list to find initial column position. ArrayList< Integer > swap = new ArrayList< Integer >( inew.size() + 1 ); swap.addAll( inew ); for ( int i = 0; i < swap.size(); i++ ) { Integer p = swap.get( i ); if ( p.compareTo( pos ) > 0 ) { swap.add( i, pos ); break; } } if ( swap.size() <= inew.size() ) swap.add( pos ); inew.clear(); inew.addAll( swap ); } } } // Add new columns for ( Iterator< Integer > it = inew.iterator(); it.hasNext(); ) { Integer pos = it.next(); if ( !iold.contains( pos ) ) { ModelField field = modelFields[ pos ]; if ( field.isManageable() ) { iold.add( pos ); field.setVisible( true ); int coords[] = data.getIndexOfModelFieldGroup( field.getIdentifier() ); addColumn( new JBroTableColumn( coords[ 0 ], coords[ 1 ], pos, field.getRowspan() ) ); } else it.remove(); } } int newVisibleIndexes[] = new int[ inew.size() ]; int n = 0; for ( Integer pos : inew ) { newVisibleIndexes[ n++ ] = convertColumnIndexToView( pos ); } // Permutations for ( int i = 0; i < newVisibleIndexes.length; i++ ) { int pos = newVisibleIndexes[ i ]; while ( pos != i ) { int posPos = newVisibleIndexes[ pos ]; swapColumns( posPos, pos ); newVisibleIndexes[ pos ] = pos; newVisibleIndexes[ i ] = posPos; pos = posPos; } } if ( manageable != null ) for ( ModelField field : manageable ) field.setManageable( false ); checkFieldWidths(); } /** * Swap two columns positions (does not affect model). * @param first swapping column * @param second swapping column */ public void swapColumns( int first, int second ) { if ( first > second ) { int t = first; first = second; second = t; } else if ( first == second ) { return; } moveColumn( first, second ); moveColumn( second - 1, first ); } /** * A list of visible columns in the view order separated by ";". One extra ";" is added at the end. * @return a list of visible columns */ public String getFieldsOrder() { ModelData data = getData(); if ( data == null ) { return ""; } ModelField fields[] = data.getFields(); if ( fields == null ) { return ""; } StringBuilder result = new StringBuilder(); for ( int i = 0; i < columnModel.getColumnCount(); i++ ) { result.append( fields[ columnModel.getColumn( i ).getModelIndex() ].getIdentifier() ).append( ';' ); } return result.toString(); } /** * Set a list of columns. * @param fieldsOrder a list of visible columns in the view order separated by ";", must end with ";" */ public void setFieldsOrder( String fieldsOrder ) { if ( fieldsOrder == null ) { fieldsOrder = ""; } reorderFields( fieldsOrder.split( ";" ) ); } /** * A list of pairs ( Identifier, column width in pixels ). * <p>A separator inside a pair is ":".<br> * Pairs separator is ";".<br> * No extra ";" at the end.<br> * Columns have the view order. Only visible columns are printed.<br> * The model order fields can be obtained using method {@link #getColumnsWidths()}.</p> * @return a list of fields and their widths */ public String getFieldsOrderAndWidths() { ModelData data = getData(); if ( data == null ) { return ""; } ModelField fields[] = data.getFields(); if ( fields == null ) { return ""; } StringBuilder result = new StringBuilder(); for ( int i = 0; i < columnModel.getColumnCount(); i++ ) { TableColumn column = columnModel.getColumn( i ); if ( result.length() != 0 ) { result.append( ';' ); } result.append( fields[ column.getModelIndex() ].getIdentifier() ) .append( ':' ) .append( column.getPreferredWidth() ); } return result.toString(); } /** * Set a list of fields and the width of each of them. * @param colWidths a list of pairs ( Identifier, column width ) in format of method {@link #getFieldsOrderAndWidths()} */ public void setFieldsOrderAndWidths( String colWidths ) { reorderFields( setColumnsWidths( colWidths, true ) ); } /** * A list of pairs ( Identifier, field width in pixels ). * <p>The output format is described at method {@link #getFieldsOrderAndWidths()}.<br> * Fields are printed in the model order. Only visible fields are included.<br> * The view order list can be obtained by method {@link #getFieldsOrderAndWidths()}.</p> * @return a list of fields and their widths */ public String getColumnsWidths() { StringBuilder result = new StringBuilder(); TableColumnModel colModel = getColumnModel(); ModelField[] fields = getData().getFields(); for ( int a = 0; a < fields.length; a++ ) { int idx = convertColumnIndexToView( a ); if ( idx >= 0 ) { if ( result.length() != 0 ) { result.append( ';' ); } result.append( fields[ a ].getIdentifier() ) .append( ':' ) .append( colModel.getColumn( idx ).getPreferredWidth() ); } } return result.toString(); } /** * Set widths of columns. The order and visibility of columns wouldn't be touched. * @param colWidths a list of pairs ( Identifier, column width ) in format of method {@link #getFieldsOrderAndWidths()} */ public void setColumnsWidths( String colWidths ) { setColumnsWidths( colWidths, false ); } private String[] setColumnsWidths( String colWidths, boolean addIfAbsent ) { if ( colWidths == null || colWidths.isEmpty() ) { return new String[ 0 ]; } String[] widths = colWidths.split( ";" ); if ( widths == null || widths.length == 0 ) { return new String[ 0 ]; } Pattern pattern = Pattern.compile( "(\\S+):(\\d+)" ); ModelField[] fields = getData().getFields(); LinkedHashMap< String, Integer > fieldIndexes = ModelField.getIndexes( fields ); ArrayList< String > ret = new ArrayList< String >(); for ( String width : widths ) { Matcher matcher = pattern.matcher( width ); if ( matcher.matches() ) { String colName = matcher.group( 1 ); int colWidth = Integer.parseInt( matcher.group( 2 ) ); Integer origIdx = fieldIndexes.get( colName ); if ( origIdx == null ) { continue; } ret.add( colName ); int fIdx = convertColumnIndexToView( origIdx ); if ( fIdx < 0 ) { if ( addIfAbsent ) { addColumn( new TableColumn( origIdx ) ); ModelField field = fields[ origIdx ]; if ( field.isManageable() ) field.setVisible( true ); fIdx = convertColumnIndexToView( origIdx ); } else continue; } TableColumn column = columnModel.getColumn( fIdx ); column.setPreferredWidth( colWidth ); } } return ret.toArray( new String[ ret.size() ] ); } /** * Get index of column in table header by field identifier. * @param identifier field identifier. * @return index of column in the view order */ public int convertColumnIndexToView( String identifier ) { return convertColumnIndexToView( getData().getIndexOfModelField( identifier ) ); } @Override public void columnMoved( TableColumnModelEvent e ) { } /** * Value in a cell located at the given row and a column identified by name. * @param row row number * @param identifier column identifier * @return cell value */ public Object getValueAt( int row, String identifier ) { return getData().getValue( row, identifier ); } @Override protected JBroTableColumnModel createDefaultColumnModel() { return new JBroTableColumnModel( this ); } @Override public void createDefaultColumnsFromModel() { TableColumnModel m = getColumnModel(); if ( !( m instanceof JBroTableColumnModel ) ) { super.createDefaultColumnsFromModel(); return; } JBroTableColumnModel gcm = ( JBroTableColumnModel )m; gcm.clear(); ModelData data = getData(); if ( data == null ) return; Iterable< IModelFieldGroup > groups = data.getAllFieldGroupsFromTop( true ); for ( IModelFieldGroup fieldGroup : groups ) { int groupCoords[] = data.getIndexOfModelFieldGroup( fieldGroup.getIdentifier() ); int groupLevel = groupCoords[ 1 ]; int groupX = groupCoords[ 0 ]; gcm.addColumn( fieldGroup, groupX, groupLevel ); } } @Override protected JTableHeader createDefaultTableHeader() { TableColumnModel m = getColumnModel(); if ( !( m instanceof JBroTableColumnModel ) ) return super.createDefaultTableHeader(); JBroTableColumnModel gcm = ( JBroTableColumnModel )m; return new JBroTableHeader( gcm ); } @Override public void columnSelectionChanged( ListSelectionEvent e ) { if ( getRowSelectionAllowed() ) { int leadRow = selectionModel.getLeadSelectionIndex(); if ( leadRow >= 0 && leadRow < getRowCount() ) { Rectangle first = getUI().getSpanCoordinates( e.getFirstIndex(), leadRow ); Rectangle last = getUI().getSpanCoordinates( e.getLastIndex(), leadRow ); first = first.x < 0 || first.y < 0 ? last : last.x < 0 || last.y < 0 ? first : first.union( last ); if ( first.x >= 0 && first.width > 1 ) { e = new ListSelectionEvent( e.getSource(), first.x, first.x + first.width - 1, e.getValueIsAdjusting() ); } } } super.columnSelectionChanged( e ); } void setCurrentLevel( Integer currentLevel ) { this.currentLevel = currentLevel; } @Override public TableColumnModel getColumnModel() { return currentLevel == null ? super.getColumnModel() : getTableHeader().getColumnModel( currentLevel ); } @Override public JBroTableHeader getTableHeader() { return ( JBroTableHeader )super.getTableHeader(); } @Override public void valueChanged( ListSelectionEvent e ) { super.valueChanged( e ); getUI().onRowsSelected( e.getFirstIndex(), e.getLastIndex() ); } /** * This method creates (if it doesn't exist yet) and returns a scroll pane that contains a viewport * with fixed columns. This scroll pane may have a null viewport if a model contains no visible * fixed columns. * <p>To obtain a left fixed table, call {@link #getSlaveTable}.</p> * @return a scroll pane with a fixed left part (if required) */ public JScrollPane getScrollPane() { if ( scrollPane != null ) return scrollPane; scrollPane = new JScrollPane( this ); if ( getMasterTable() == null ) { updateScrollPane(); addPropertyChangeListener( new PropertyChangeListener() { @Override public void propertyChange( PropertyChangeEvent e ) { JViewport viewport = scrollPane.getRowHeader(); if ( viewport == null ) return; Component comp = viewport.getView(); if ( !( comp instanceof JBroTable ) ) return; JBroTable fixed = ( JBroTable )comp; String property = e.getPropertyName(); if ( "selectionModel".equals( property ) ) fixed.setSelectionModel( getSelectionModel() ); else if ( "rowSorter".equals( property ) ) fixed.setRowSorter( getRowSorter() ); else if ( "model".equals( property ) ) fixed.setModel( getModel() ); } } ); } return scrollPane; } @Override public void tableChanged( TableModelEvent e ) { super.tableChanged( e ); if ( e == null || e.getFirstRow() == TableModelEvent.HEADER_ROW ) tableStructureChanged(); } private void tableStructureChanged() { updateScrollPane(); JBroTableHeader header = getTableHeader(); if ( header != null ) { header.updateUI(); header.repaint(); } } /** * If this table is just a fixed (non-scrollable) part then this method would return main part. * @return main table for a fixed one, otherwise null */ public JBroTable getMasterTable() { return masterTable; } /** * If this table has fixed columns then this method would return a fixed (non-scrollable) part. * @return fixed part for a main table, otherwise null */ public JBroTable getSlaveTable() { if ( getScrollPane() == null ) return null; JViewport viewport = getScrollPane().getRowHeader(); if ( viewport == null ) return null; Component ret = viewport.getView(); if ( !( ret instanceof JBroTable ) ) return null; return ( JBroTable )ret; } @Override public boolean hasFocus() { return masterTable == null ? super.hasFocus() : masterTable.hasFocus(); } private void updateScrollPane() { if ( scrollPane == null || getMasterTable() != null ) return; ModelData data = getData(); boolean hasFixed = false; if ( data != null ) { for ( ModelField field : data.getFields() ) { if ( field.isFixed() && field.isVisible() ) { hasFixed = true; break; } } } if ( !hasFixed ) { if ( scrollPane.getRowHeader() != null ) { scrollPane.setCorner( JScrollPane.UPPER_LEFT_CORNER, null ); scrollPane.setRowHeader( null ); } return; } if ( scrollPane.getRowHeader() == null ) { JBroTable fixed = newInstance(); fixed.masterTable = this; fixed.setModel( getModel() ); fixed.setSelectionModel( getSelectionModel() ); fixed.setRowSorter( getRowSorter() ); fixed.setAutoResizeMode( getAutoResizeMode() ); fixed.setFocusable( false ); fixed.setUpdateSelectionOnSort( false ); fixed.setPreferredScrollableViewportSize( fixed.getPreferredSize() ); MouseAdapter ma = new MouseAdapter() { private TableColumn column; private int columnWidth; private int pressedX; @Override public void mousePressed( MouseEvent e ) { JTableHeader header = ( JTableHeader )e.getComponent(); TableColumnModel tcm = header.getColumnModel(); int columnIndex = tcm.getColumnIndexAtX( e.getX() - 3 ); if ( columnIndex == tcm.getColumnCount() - 1 && header.getCursor() == JBroTableHeaderUI.RESIZE_CURSOR && header.getTable().getAutoResizeMode() != JTable.AUTO_RESIZE_OFF ) { column = tcm.getColumn( columnIndex ); columnWidth = column.getWidth(); pressedX = e.getX(); } } @Override public void mouseReleased( MouseEvent e ) { column = null; columnWidth = 0; pressedX = 0; } @Override public void mouseDragged( MouseEvent e ) { JTableHeader header = ( JTableHeader )e.getComponent(); JTable table = header.getTable(); if ( column != null ) { int width = columnWidth - pressedX + e.getX(); column.setPreferredWidth( width ); } table.setPreferredScrollableViewportSize( table.getPreferredSize() ); } }; JBroTableHeader header = fixed.getTableHeader(); header.addMouseListener( ma ); header.addMouseMotionListener( ma ); scrollPane.setRowHeaderView( fixed ); scrollPane.setCorner( JScrollPane.UPPER_LEFT_CORNER, fixed.getTableHeader() ); scrollPane.getRowHeader().addChangeListener( new ChangeListener() { @Override public void stateChanged( ChangeEvent e ) { JViewport viewport = ( JViewport )e.getSource(); scrollPane.getVerticalScrollBar().setValue( viewport.getViewPosition().y ); } } ); } } /** * This method should be overridden for proper creation of fixed non-scrollable part of the table. * @return new instance of an inherited class */ protected JBroTable newInstance() { return new JBroTable(); } private class HeaderHeightWatcher implements TableColumnModelListener { @Override public void columnAdded( TableColumnModelEvent evt ) { updateHeaderSize(); } @Override public void columnRemoved( TableColumnModelEvent evt ) { updateHeaderSize(); } @Override public void columnMoved( TableColumnModelEvent evt ) { updateHeaderSize(); } @Override public void columnMarginChanged( ChangeEvent evt ) { updateHeaderSize(); } @Override public void columnSelectionChanged( ListSelectionEvent evt ) { } } }
package org.texastorque.texastorque2015; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.texastorque.texastorque2015.auto.AutoPicker; import org.texastorque.texastorque2015.feedback.Feedback; import org.texastorque.texastorque2015.feedback.SensorFeedback; import org.texastorque.texastorque2015.input.DriverInput; import org.texastorque.texastorque2015.input.Input; import org.texastorque.texastorque2015.output.Output; import org.texastorque.texastorque2015.output.RobotOutput; import org.texastorque.texastorque2015.subsystem.Arms; import org.texastorque.texastorque2015.subsystem.Drivebase; import org.texastorque.texastorque2015.subsystem.Elevator; import org.texastorque.texastorque2015.subsystem.Intake; import org.texastorque.torquelib.base.TorqueIterative; import org.texastorque.torquelib.util.Parameters; public class Robot extends TorqueIterative { //Subsystems Drivebase drivebase; Elevator elevator; Arms arms; Intake intake; //Input Input activeInput; DriverInput driverInput; //Output Output activeOutput; RobotOutput robotOutput; //Feedback Feedback activeFeedback; SensorFeedback sensorFeedback; private volatile int numcycles; @Override public void robotInit() { Parameters.makeFile(); Parameters.load(); drivebase = new Drivebase(); elevator = new Elevator(); driverInput = new DriverInput(); robotOutput = new RobotOutput(); sensorFeedback = new SensorFeedback(); AutoPicker.init(); numcycles = 0; } //Update Input, Output, Feedback for all subsystems. private void updateIO(){ drivebase.setInput(activeInput); drivebase.setOutput(activeOutput); drivebase.setFeedback(activeFeedback); elevator.setInput(activeInput); elevator.setOutput(activeOutput); elevator.setFeedback(activeFeedback); arms.setInput(activeInput); arms.setOutput(activeOutput); arms.setFeedback(activeFeedback); intake.setInput(activeInput); intake.setOutput(activeOutput); intake.setFeedback(activeFeedback); } //Load params for all subsystems. private void loadParams() { Parameters.load(); drivebase.loadParams(); elevator.loadParams(); arms.loadParams(); intake.loadParams(); } //Push all sybsystems to dashboard. private void pushToDashboard() { drivebase.pushToDashboard(); elevator.pushToDashboard(); arms.pushToDashboard(); intake.pushToDashboard(); } @Override public void teleopInit() { activeInput = driverInput; activeOutput = robotOutput; activeFeedback = sensorFeedback; updateIO(); loadParams(); drivebase.setOutputEnabled(true); numcycles = 0; } @Override public void teleopPeriodic() { activeInput.run(); pushToDashboard(); } @Override public void teleopContinuous() { activeFeedback.run(); drivebase.run(); SmartDashboard.putNumber("NumCycles", numcycles++); } @Override public void autonomousInit() { activeInput = AutoPicker.getAutonomous(); activeOutput = robotOutput; activeFeedback = sensorFeedback; updateIO(); loadParams(); drivebase.setOutputEnabled(true); activeInput.setFeedback(activeFeedback); Thread autoThread = new Thread(activeInput); autoThread.start(); numcycles = 0; } @Override public void autonomousPeriodic() { pushToDashboard(); } @Override public void autonomousContinuous() { activeFeedback.run(); drivebase.run(); SmartDashboard.putNumber("NumCycles", numcycles++); } }
package com.khoubyari.example.domain; import java.time.LocalDateTime; public class Status { private final Boolean isUpdateNeeded; private final LocalDateTime timestamp; private final boolean runHealthCheckNow; private static final String data = "get-process"; private static final String cronSchedule = " 0 08 * * * "; public Status(Boolean isUpdateNeeded) { this.isUpdateNeeded = isUpdateNeeded; timestamp = LocalDateTime.now(); runHealthCheckNow = false; } public Boolean isUpdateNeeded() { return isUpdateNeeded; } public LocalDateTime getTimestamp() { /*TODO LocalDateTime time = ...; ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo"); long epoch = time.atZone(zoneId).toEpochSecond();*/ return timestamp; } public static String getData() { return data; } public static String getCronSchedule() { return cronSchedule; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Status status = (Status) o; if (isUpdateNeeded != null ? !isUpdateNeeded.equals(status.isUpdateNeeded) : status.isUpdateNeeded != null) return false; return !(timestamp != null ? !timestamp.equals(status.timestamp) : status.timestamp != null); } @Override public int hashCode() { int result = isUpdateNeeded != null ? isUpdateNeeded.hashCode() : 0; result = 31 * result + (timestamp != null ? timestamp.hashCode() : 0); return result; } @Override public String toString() { return "Status{" + "isUpdateNeeded=" + isUpdateNeeded + ", timestamp=" + timestamp + '}'; } }
package com.maestrano.helpers; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class MnoDateHelper { private static final SimpleDateFormat DF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); public static Date fromIso8601(String dateStr) throws ParseException { return DF.parse(dateStr.replaceAll("Z$", "+0000")); } public static String toIso8601(Date dateObj) { DF.setTimeZone(TimeZone.getTimeZone("UTC")); return DF.format(dateObj).replaceAll("\\+0000$","Z"); } }
package com.ociweb.gl.api; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ociweb.gl.impl.BuilderImpl; import com.ociweb.gl.impl.schema.MessagePrivate; import com.ociweb.gl.impl.schema.MessagePubSub; import com.ociweb.gl.impl.schema.TrafficOrderSchema; import com.ociweb.pronghorn.network.ServerCoordinator; import com.ociweb.pronghorn.network.config.HTTPContentTypeDefaults; import com.ociweb.pronghorn.network.module.AbstractAppendablePayloadResponseStage; import com.ociweb.pronghorn.network.schema.ClientHTTPRequestSchema; import com.ociweb.pronghorn.network.schema.ServerResponseSchema; import com.ociweb.pronghorn.pipe.DataOutputBlobWriter; import com.ociweb.pronghorn.pipe.Pipe; import com.ociweb.pronghorn.pipe.PipeConfig; import com.ociweb.pronghorn.pipe.PipeConfigManager; import com.ociweb.pronghorn.pipe.PipeWriter; import com.ociweb.pronghorn.stage.scheduling.GraphManager; import com.ociweb.pronghorn.util.Appendables; import com.ociweb.pronghorn.util.TrieParser; import com.ociweb.pronghorn.util.TrieParserReader; import com.ociweb.pronghorn.util.field.MessageConsumer; /** * Represents a dedicated channel for communicating with a single device * or resource on an IoT system. */ public class MsgCommandChannel<B extends BuilderImpl> { private final Logger logger = LoggerFactory.getLogger(MsgCommandChannel.class); private Pipe<TrafficOrderSchema> goPipe; private Pipe<MessagePubSub> messagePubSub; private Pipe<ClientHTTPRequestSchema> httpRequest; private Pipe<ServerResponseSchema>[] netResponse; private Pipe<MessagePubSub>[] exclusivePubSub; private static final byte[] RETURN_NEWLINE = "\r\n".getBytes(); private int lastResponseWriterFinished = 1;//starting in the "end" state private String[] exclusiveTopics = new String[0];//TODO: make empty protected AtomicBoolean aBool = new AtomicBoolean(false); protected static final long MS_TO_NS = 1_000_000; private Object listener; public static final int DYNAMIC_MESSAGING = 1<<0; public static final int STATE_MACHINE = DYNAMIC_MESSAGING;//state machine is based on DYNAMIC_MESSAGING; public static final int NET_REQUESTER = 1<<1; public static final int NET_RESPONDER = 1<<2; public static final int ALL = DYNAMIC_MESSAGING | NET_REQUESTER | NET_RESPONDER; protected final B builder; public int maxHTTPContentLength; protected Pipe<?>[] optionalOutputPipes; public int initFeatures; //this can be modified up to the moment that we build the pipes. private String[] privateTopics = null; private Pipe<MessagePrivate>[] privateTopicPipes = null; private TrieParser privateTopicsTrie = null; private TrieParserReader privateTopicsTrieReader = null; protected PipeConfigManager pcm; private final int parallelInstanceId; public MsgCommandChannel(GraphManager gm, B hardware, int parallelInstanceId, PipeConfigManager pcm ) { this(gm,hardware,ALL, parallelInstanceId, pcm); } public MsgCommandChannel(GraphManager gm, B builder, int features, int parallelInstanceId, PipeConfigManager pcm ) { this.initFeatures = features;//this is held so we can check at every method call that its configured right this.builder = builder; this.pcm = pcm; this.parallelInstanceId = parallelInstanceId; } public void ensureDynamicMessaging() { if (null!=this.goPipe) { throw new UnsupportedOperationException("Too late, this method must be called in define behavior."); } this.initFeatures |= DYNAMIC_MESSAGING; } public void ensureDynamicMessaging(int queueLength, int maxMessageSize) { if (null!=this.goPipe) { throw new UnsupportedOperationException("Too late, this method must be called in define behavior."); } this.initFeatures |= DYNAMIC_MESSAGING; PipeConfig<MessagePubSub> config = pcm.getConfig(MessagePubSub.class); if (queueLength>config.minimumFragmentsOnPipe() || maxMessageSize>config.maxVarLenSize()) { this.pcm.addConfig(queueLength, maxMessageSize, MessagePubSub.class); } } public void ensureHTTPClientRequesting() { if (null!=this.goPipe) { throw new UnsupportedOperationException("Too late, this method must be called in define behavior."); } this.initFeatures |= NET_REQUESTER; } public void ensureHTTPClientRequesting(int queueLength, int maxMessageSize) { if (null!=this.goPipe) { throw new UnsupportedOperationException("Too late, this method must be called in define behavior."); } this.initFeatures |= NET_REQUESTER; PipeConfig<ClientHTTPRequestSchema> config = pcm.getConfig(ClientHTTPRequestSchema.class); if (queueLength>config.minimumFragmentsOnPipe() || maxMessageSize>config.maxVarLenSize()) { this.pcm.addConfig(queueLength, maxMessageSize, ClientHTTPRequestSchema.class); } } public void ensureHTTPServerResponse() { if (null!=this.goPipe) { throw new UnsupportedOperationException("Too late, this method must be called in define behavior."); } this.initFeatures |= NET_RESPONDER; } public void ensureHTTPServerResponse(int queueLength, int maxMessageSize) { if (null!=this.goPipe) { throw new UnsupportedOperationException("Too late, this method must be called in define behavior."); } this.initFeatures |= NET_RESPONDER; PipeConfig<ServerResponseSchema> config = pcm.getConfig(ServerResponseSchema.class); if (queueLength>config.minimumFragmentsOnPipe() || maxMessageSize>config.maxVarLenSize()) { this.pcm.addConfig(queueLength, maxMessageSize, ServerResponseSchema.class); } } public void ensureCommandCountRoom(int queueLength) { if (null!=this.goPipe) { throw new UnsupportedOperationException("Too late, this method must be called in define behavior."); } PipeConfig<TrafficOrderSchema> goConfig = this.pcm.getConfig(TrafficOrderSchema.class); if (queueLength>goConfig.minimumFragmentsOnPipe() ) { this.pcm.addConfig(queueLength, 0, TrafficOrderSchema.class); } } private void buildAllPipes() { if (null == this.goPipe) { this.messagePubSub = ((this.initFeatures & DYNAMIC_MESSAGING) == 0) ? null : newPubSubPipe(pcm.getConfig(MessagePubSub.class), builder); this.httpRequest = ((this.initFeatures & NET_REQUESTER) == 0) ? null : newNetRequestPipe(pcm.getConfig(ClientHTTPRequestSchema.class), builder); //we always need a go pipe this.goPipe = newGoPipe(pcm.getConfig(TrafficOrderSchema.class)); //build pipes for sending out the REST server responses Pipe<ServerResponseSchema>[] netResponse = null; if ((this.initFeatures & NET_RESPONDER) != 0) { //int parallelInstanceId = hardware.ac if (-1 == parallelInstanceId) { //we have only a single instance of this object so we must have 1 pipe for each parallel track int p = builder.parallelism(); netResponse = ( Pipe<ServerResponseSchema>[])new Pipe[p]; while (--p>=0) { netResponse[p] = builder.newNetResponsePipe(pcm.getConfig(ServerResponseSchema.class), p); } } else { //we have multiple instances of this object so each only has 1 pipe netResponse = ( Pipe<ServerResponseSchema>[])new Pipe[1]; netResponse[0] = builder.newNetResponsePipe(pcm.getConfig(ServerResponseSchema.class), parallelInstanceId); } } this.netResponse = netResponse; if (null != this.netResponse) { int x = this.netResponse.length; while(--x>=0) { if (!Pipe.isInit(netResponse[x])) { //hack for now. netResponse[x].initBuffers(); } } } int e = this.exclusiveTopics.length; this.exclusivePubSub = (Pipe<MessagePubSub>[])new Pipe[e]; while (--e>=0) { exclusivePubSub[e] = newPubSubPipe(pcm.getConfig(MessagePubSub.class), builder); } int temp = 0; if (null!=netResponse && netResponse.length>0) { int x = netResponse.length; int min = Integer.MAX_VALUE; while (--x>=0) { min = Math.min(min, netResponse[x].maxVarLen); } temp= min; } this.maxHTTPContentLength = temp; } } protected boolean goHasRoom() { return PipeWriter.hasRoomForWrite(goPipe); } public Pipe<?>[] getOutputPipes() { //we wait till this last possible moment before building. buildAllPipes(); int length = 0; if (null != messagePubSub) { //Index needed plust i2c index needed. length++; } if (null != httpRequest) { length++; } if (null != netResponse) { length+=netResponse.length; } if (null != goPipe) {//last length++; } length += exclusivePubSub.length; if (null!=optionalOutputPipes) { length+=optionalOutputPipes.length; } if (null!=privateTopicPipes) { length+=privateTopicPipes.length; } int idx = 0; Pipe[] results = new Pipe[length]; System.arraycopy(exclusivePubSub, 0, results, 0, exclusivePubSub.length); idx+=exclusivePubSub.length; if (null != messagePubSub) { results[idx++] = messagePubSub; } if (null != httpRequest) { results[idx++] = httpRequest; } if (null != netResponse) { System.arraycopy(netResponse, 0, results, idx, netResponse.length); idx+=netResponse.length; } if (null!=optionalOutputPipes) { System.arraycopy(optionalOutputPipes, 0, results, idx, optionalOutputPipes.length); idx+=optionalOutputPipes.length; } if (null!=privateTopicPipes) { System.arraycopy(privateTopicPipes, 0, results, idx, privateTopicPipes.length); idx+=privateTopicPipes.length; } if (null != goPipe) {//last results[idx++] = goPipe; } return results; } private static <B extends BuilderImpl> Pipe<MessagePubSub> newPubSubPipe(PipeConfig<MessagePubSub> config, B builder) { return new Pipe<MessagePubSub>(config) { @SuppressWarnings("unchecked") @Override protected DataOutputBlobWriter<MessagePubSub> createNewBlobWriter() { return new PubSubWriter(this); } }; } private static <B extends BuilderImpl> Pipe<ClientHTTPRequestSchema> newNetRequestPipe(PipeConfig<ClientHTTPRequestSchema> config, B builder) { return new Pipe<ClientHTTPRequestSchema>(config) { @SuppressWarnings("unchecked") @Override protected DataOutputBlobWriter<ClientHTTPRequestSchema> createNewBlobWriter() { return new PayloadWriter<ClientHTTPRequestSchema>(this); } }; } private Pipe<TrafficOrderSchema> newGoPipe(PipeConfig<TrafficOrderSchema> goPipeConfig) { return new Pipe<TrafficOrderSchema>(goPipeConfig); } public static void setListener(MsgCommandChannel c, Object listener) { if (null != c.listener && c.listener!=listener) { throw new UnsupportedOperationException("Bad Configuration, A CommandChannel can only be held and used by a single listener lambda/class"); } c.listener = listener; } protected boolean enterBlockOk() { return aBool.compareAndSet(false, true); } protected boolean exitBlockOk() { return aBool.compareAndSet(true, false); } /** * Causes this channel to delay processing any actions until the specified * amount of time has elapsed. * * @param durationNanos Nanos to delay * * @return True if blocking was successful, and false otherwise. */ public boolean block(long durationNanos) { assert(enterBlockOk()) : "Concurrent usage error, ensure this never called concurrently"; try { if (goHasRoom()) { MsgCommandChannel.publishBlockChannel(durationNanos, this); return true; } else { return false; } } finally { assert(exitBlockOk()) : "Concurrent usage error, ensure this never called concurrently"; } } public boolean blockUntil(long msTime) { assert(enterBlockOk()) : "Concurrent usage error, ensure this never called concurrently"; try { if (goHasRoom()) { MsgCommandChannel.publishBlockChannelUntil(msTime, this); return true; } else { return false; } } finally { assert(exitBlockOk()) : "Concurrent usage error, ensure this never called concurrently"; } } /** * Submits an HTTP GET request asynchronously. * * The response to this HTTP GET will be sent to any HTTPResponseListeners * associated with the listener for this command channel. * * @param domain Root domain to submit the request to (e.g., google.com) * @param port Port to submit the request to. * @param path Route on the domain to submit the request to (e.g., /api/hello) * * @return True if the request was successfully submitted, and false otherwise. */ public boolean httpGet(CharSequence domain, int port, CharSequence path) { return httpGet(domain,port,path,(HTTPResponseListener)listener); } /** * Submits an HTTP GET request asynchronously. * * @param host Root domain to submit the request to (e.g., google.com) * @param port Port to submit the request to. * @param route Route on the domain to submit the request to (e.g., /api/hello) * @param listener {@link HTTPResponseListener} that will handle the response. * * @return True if the request was successfully submitted, and false otherwise. */ private boolean httpGet(CharSequence host, int port, CharSequence route, HTTPResponseListener listener) { return httpGet(host, port, route, builder.behaviorId((HTTPResponseListener)listener)); } public boolean httpGet(CharSequence host, CharSequence route) { return httpGet(host, builder.isClientTLS()?443:80, route, (HTTPResponseListener)listener); } public boolean httpGet(CharSequence host, CharSequence route, int behaviorId) { return httpGet(host, builder.isClientTLS()?443:80, route, behaviorId); } public boolean httpGet(CharSequence host, int port, CharSequence route, int behaviorId) { assert(builder.isUseNetClient()); assert((this.initFeatures & NET_REQUESTER)!=0) : "must turn on NET_REQUESTER to use this method"; if (PipeWriter.hasRoomForWrite(goPipe) && PipeWriter.tryWriteFragment(httpRequest, ClientHTTPRequestSchema.MSG_HTTPGET_100)) { PipeWriter.writeInt(httpRequest, ClientHTTPRequestSchema.MSG_HTTPGET_100_FIELD_PORT_1, port); PipeWriter.writeUTF8(httpRequest, ClientHTTPRequestSchema.MSG_HTTPGET_100_FIELD_HOST_2, host); PipeWriter.writeUTF8(httpRequest, ClientHTTPRequestSchema.MSG_HTTPGET_100_FIELD_PATH_3, route); PipeWriter.writeInt(httpRequest, ClientHTTPRequestSchema.MSG_HTTPGET_100_FIELD_LISTENER_10, behaviorId); PipeWriter.writeUTF8(httpRequest, ClientHTTPRequestSchema.MSG_HTTPGET_100_FIELD_HEADERS_7, ""); PipeWriter.publishWrites(httpRequest); publishGo(1, builder.netIndex(), this); return true; } return false; } /** * Submits an HTTP POST request asynchronously. * * The response to this HTTP POST will be sent to any HTTPResponseListeners * associated with the listener for this command channel. * * @param domain Root domain to submit the request to (e.g., google.com) * @param port Port to submit the request to. * @param route Route on the domain to submit the request to (e.g., /api/hello) * * @return True if the request was successfully submitted, and false otherwise. */ public PayloadWriter httpPost(CharSequence domain, int port, CharSequence route) { return httpPost(domain,port,route,(HTTPResponseListener)listener); } /** * Submits an HTTP POST request asynchronously. * * @param host Root domain to submit the request to (e.g., google.com) * @param port Port to submit the request to. * @param route Route on the domain to submit the request to (e.g., /api/hello) * @param listener {@link HTTPResponseListener} that will handle the response. * * @return True if the request was successfully submitted, and false otherwise. */ public PayloadWriter<ClientHTTPRequestSchema> httpPost(CharSequence host, int port, CharSequence route, HTTPResponseListener listener) { assert((this.initFeatures & NET_REQUESTER)!=0) : "must turn on NET_REQUESTER to use this method"; if (PipeWriter.hasRoomForWrite(goPipe) && PipeWriter.tryWriteFragment(httpRequest, ClientHTTPRequestSchema.MSG_HTTPPOST_101)) { PipeWriter.writeInt(httpRequest, ClientHTTPRequestSchema.MSG_HTTPPOST_101_FIELD_PORT_1, port); PipeWriter.writeUTF8(httpRequest, ClientHTTPRequestSchema.MSG_HTTPPOST_101_FIELD_HOST_2, host); PipeWriter.writeUTF8(httpRequest, ClientHTTPRequestSchema.MSG_HTTPPOST_101_FIELD_PATH_3, route); PipeWriter.writeInt(httpRequest, ClientHTTPRequestSchema.MSG_HTTPPOST_101_FIELD_LISTENER_10, System.identityHashCode(listener)); publishGo(1, builder.netIndex(), this); PayloadWriter<ClientHTTPRequestSchema> pw = (PayloadWriter<ClientHTTPRequestSchema>) Pipe.outputStream(httpRequest); pw.openField(ClientHTTPRequestSchema.MSG_HTTPPOST_101_FIELD_PAYLOAD_5, this); return pw; } else { return null; } } /** * Subscribes the listener associated with this command channel to * a topic. * * @param topic Topic to subscribe to. * * @return True if the topic was successfully subscribed to, and false * otherwise. */ public boolean subscribe(CharSequence topic) { assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag"; if (null==listener || null == goPipe) { throw new UnsupportedOperationException("Can not subscribe before startup. Call addSubscription when registering listener."); } return subscribe(topic, (PubSubListener)listener); } /** * Subscribes a listener to a topic on this command channel. * * @param topic Topic to subscribe to. * @param listener Listener to subscribe. * * @return True if the topic was successfully subscribed to, and false * otherwise. */ public boolean subscribe(CharSequence topic, PubSubListener listener) { assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag"; assert(null!=goPipe) : "must turn on Dynamic Messaging for this channel"; if (PipeWriter.hasRoomForWrite(goPipe) && PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_SUBSCRIBE_100)) { PipeWriter.writeInt(messagePubSub, MessagePubSub.MSG_SUBSCRIBE_100_FIELD_SUBSCRIBERIDENTITYHASH_4, System.identityHashCode(listener)); PipeWriter.writeUTF8(messagePubSub, MessagePubSub.MSG_SUBSCRIBE_100_FIELD_TOPIC_1, topic); PipeWriter.publishWrites(messagePubSub); builder.releasePubSubTraffic(1, this); return true; } return false; } /** * Unsubscribes the listener associated with this command channel from * a topic. * * @param topic Topic to unsubscribe from. * * @return True if the topic was successfully unsubscribed from, and false otherwise. */ public boolean unsubscribe(CharSequence topic) { assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag"; return unsubscribe(topic, (PubSubListener)listener); } /** * Unsubscribes a listener from a topic. * * @param topic Topic to unsubscribe from. * @param listener Listener to unsubscribe. * * @return True if the topic was successfully unsubscribed from, and false otherwise. */ public boolean unsubscribe(CharSequence topic, PubSubListener listener) { assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag"; if (PipeWriter.hasRoomForWrite(goPipe) && PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_UNSUBSCRIBE_101)) { PipeWriter.writeInt(messagePubSub, MessagePubSub.MSG_SUBSCRIBE_100_FIELD_SUBSCRIBERIDENTITYHASH_4, System.identityHashCode(listener)); PipeWriter.writeUTF8(messagePubSub, MessagePubSub.MSG_UNSUBSCRIBE_101_FIELD_TOPIC_1, topic); PipeWriter.publishWrites(messagePubSub); builder.releasePubSubTraffic(1, this); return true; } return false; } /** * Changes the state of this command channel's state machine. * * @param state State to transition to. * * @return True if the state was successfully transitioned, and false otherwise. */ public <E extends Enum<E>> boolean changeStateTo(E state) { assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag"; assert(builder.isValidState(state)); if (!builder.isValidState(state)) { throw new UnsupportedOperationException("no match "+state.getClass()); } if (PipeWriter.hasRoomForWrite(goPipe) && PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_CHANGESTATE_70)) { PipeWriter.writeInt(messagePubSub, MessagePubSub.MSG_CHANGESTATE_70_FIELD_ORDINAL_7, state.ordinal()); PipeWriter.publishWrites(messagePubSub); builder.releasePubSubTraffic(1, this); return true; } return false; } public void presumePublishTopic(CharSequence topic, PubSubWritable writable) { assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag"; if (publishTopic(topic, writable)) { return; } else { logger.warn("unable to publish on topic {} must wait.",topic); while (!publishTopic(topic, writable)) { Thread.yield(); } } } /** * Opens a topic on this channel for writing. * * @param topic Topic to open. * * @return {@link PayloadWriter} attached to the given topic. */ public boolean publishTopic(CharSequence topic, PubSubWritable writable) { assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag"; assert(writable != null); assert(isNotPrivate(topic)) : "private topics may not be selected by CharSequence."; if (PipeWriter.hasRoomForWrite(goPipe) && PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103)) { PipeWriter.writeUTF8(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1, topic); PubSubWriter pw = (PubSubWriter) Pipe.outputStream(messagePubSub); pw.openField(MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3,this); writable.write(pw); pw.publish(); publishGo(1,builder.pubSubIndex(), this); return true; } else { return false; } } public boolean publishTopic(CharSequence topic) { assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag"; assert(isNotPrivate(topic)) : "private topics may not be selected by CharSequence."; if (PipeWriter.hasRoomForWrite(goPipe) && PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103)) { PipeWriter.writeUTF8(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1, topic); PubSubWriter pw = (PubSubWriter) Pipe.outputStream(messagePubSub); pw.openField(MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3,this); pw.publish(); publishGo(1,builder.pubSubIndex(), this); return true; } else { return false; } } //TODO: add privateTopic support // public boolean publishTopic(byte[] topic, PubSubWritable writable) { // assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag"; // assert(writable != null); // int token = (int)privateTopicsTrieReader.query(privateTopicsTrieReader, // privateTopicsTrie, // topic, 0, topic.length, Integer.MAX_VALUE); // if (token>=0) { // //this is a private topic // Pipe<MessagePrivate> output = privateTopicPipes[token]; // if (PipeWriter.tryWriteFragment(output, MessagePrivate.MSG_PUBLISH_1)) { //// PubSubWriter pw = (PubSubWriter) Pipe.outputStream(output); //// pw.openField(MessagePrivate.MSG_PUBLISH_1_FIELD_PAYLOAD_3,this); //// writable.write(pw);//TODO: cool feature, writable to return false to abandon write.. //// pw.publish(); // throw new UnsupportedOperationException(); // //return true; // } else { // return false; // } else { // //should not be called when DYNAMIC_MESSAGING is not on. // //this is a public topic // if (PipeWriter.hasRoomForWrite(goPipe) && // PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103)) { // PipeWriter.writeBytes(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1, topic); // PubSubWriter pw = (PubSubWriter) Pipe.outputStream(messagePubSub); // pw.openField(MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3,this); // writable.write(pw);//TODO: cool feature, writable to return false to abandon write.. // pw.publish(); // publishGo(1,builder.pubSubIndex(), this); // return true; // } else { // return false; public void presumePublishTopic(TopicWritable topic, PubSubWritable writable) { assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag"; if (publishTopic(topic, writable)) { return; } else { logger.warn("unable to publish on topic {} must wait.",topic); while (!publishTopic(topic, writable)) { Thread.yield(); } } } public boolean publishTopic(TopicWritable topic, PubSubWritable writable) { assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag"; assert(writable != null); assert(isNotPrivate(topic)) : "private topics may not be dynamicaly constructed."; if (PipeWriter.hasRoomForWrite(goPipe) && PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103)) { PubSubWriter pw = (PubSubWriter) Pipe.outputStream(messagePubSub); pw.openField(MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1,this); topic.write(pw); pw.closeHighLevelField(MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1); pw.openField(MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3,this); writable.write(pw); pw.publish(); publishGo(1,builder.pubSubIndex(), this); return true; } else { return false; } } public boolean publishTopic(TopicWritable topic) { assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag"; assert(isNotPrivate(topic)) : "private topics may not be dynamicaly constructed."; if (PipeWriter.hasRoomForWrite(goPipe) && PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103)) { PubSubWriter pw = (PubSubWriter) Pipe.outputStream(messagePubSub); pw.openField(MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1,this); topic.write(pw); pw.closeHighLevelField(MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1); pw.openField(MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3,this); pw.publish(); publishGo(1,builder.pubSubIndex(), this); return true; } else { return false; } } private boolean isNotPrivate(TopicWritable topic) { StringBuilder target = new StringBuilder(); topic.write(target); String topicString = target.toString(); return isNotPrivate(topicString); } private boolean isNotPrivate(CharSequence topicString) { if (null == privateTopics) { return true; } int i = privateTopics.length; while (--i>=0) { if (topicString.equals(privateTopics[i])) { return false; } } return true; } public void presumePublishStructuredTopic(CharSequence topic, PubSubStructuredWritable writable) { assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag"; if (publishStructuredTopic(topic, writable)) { return; } else { logger.warn("unable to publish on topic {} must wait.",topic); while (!publishStructuredTopic(topic, writable)) { Thread.yield(); } } } public boolean copyStructuredTopic(CharSequence topic, MessageReader reader, MessageConsumer consumer) { assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag"; int pos = reader.absolutePosition(); if (consumer.process(reader) && PipeWriter.hasRoomForWrite(goPipe) && PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103) ) { PipeWriter.writeUTF8(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1, topic); PubSubWriter pw = (PubSubWriter) Pipe.outputStream(messagePubSub); pw.openField(MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3,this); reader.absolutePosition(pos);//restore position as unread //direct copy from one to the next reader.readInto(pw, reader.available()); pw.publish(); publishGo(1,builder.pubSubIndex(), this); return true; } else { reader.absolutePosition(pos);//restore position as unread return false; } } public boolean publishStructuredTopic(CharSequence topic, PubSubStructuredWritable writable) { assert((0 != (initFeatures & DYNAMIC_MESSAGING))) : "CommandChannel must be created with DYNAMIC_MESSAGING flag"; assert(writable != null); assert(null != goPipe); assert(null != messagePubSub); if (PipeWriter.hasRoomForWrite(goPipe) && PipeWriter.tryWriteFragment(messagePubSub, MessagePubSub.MSG_PUBLISH_103)) { PipeWriter.writeUTF8(messagePubSub, MessagePubSub.MSG_PUBLISH_103_FIELD_TOPIC_1, topic); PubSubWriter pw = (PubSubWriter) Pipe.outputStream(messagePubSub); pw.openField(MessagePubSub.MSG_PUBLISH_103_FIELD_PAYLOAD_3,this); writable.write(pw); //TODO: cool feature, writable to return false to abandon write.. pw.publish(); publishGo(1,builder.pubSubIndex(), this); return true; } else { return false; } } public boolean publishHTTPResponse(HTTPFieldReader w, int statusCode) { assert((0 != (initFeatures & NET_RESPONDER))) : "CommandChannel must be created with NET_RESPONDER flag"; //logger.info("Building response for connection {} sequence {} ",w.getConnectionId(),w.getSequenceCode()); return publishHTTPResponse(w.getConnectionId(), w.getSequenceCode(), statusCode, HTTPFieldReader.END_OF_RESPONSE | HTTPFieldReader.CLOSE_CONNECTION, null, NetWritable.NO_OP); //no type and no body so use null } public boolean publishHTTPResponse(HTTPFieldReader w, int statusCode, final int context, HTTPContentTypeDefaults contentType, NetWritable writable) { assert((0 != (initFeatures & NET_RESPONDER))) : "CommandChannel must be created with NET_RESPONDER flag"; return publishHTTPResponse(w.getConnectionId(), w.getSequenceCode(), statusCode, context, contentType, writable); } //these fields are needed for holding the position data for the first block of two //this is required so we can go back to fill in length after the second block //length is known private long block1PositionOfLen; private int block1HeaderBlobPosition; //this is not thread safe but works because command channels are only used by same thread public boolean publishHTTPResponse(long connectionId, long sequenceCode, int statusCode, final int context, HTTPContentTypeDefaults contentType, NetWritable writable) { assert((0 != (initFeatures & NET_RESPONDER))) : "CommandChannel must be created with NET_RESPONDER flag"; final int sequenceNo = 0xFFFFFFFF & (int)sequenceCode; final int parallelIndex = 0xFFFFFFFF & (int)(sequenceCode>>32); assert(1==lastResponseWriterFinished) : "Previous write was not ended can not start another."; Pipe<ServerResponseSchema> pipe = netResponse.length>1 ? netResponse[parallelIndex] : netResponse[0]; //logger.trace("try new publishHTTPResponse"); if (!Pipe.hasRoomForWrite(pipe)) { return false; } //message 1 which contains the headers holdEmptyBlock(connectionId, sequenceNo, pipe); //begin message 2 which contains the body NetResponseWriter outputStream = (NetResponseWriter)Pipe.outputStream(pipe); Pipe.addMsgIdx(pipe, ServerResponseSchema.MSG_TOCHANNEL_100); Pipe.addLongValue(connectionId, pipe); Pipe.addIntValue(sequenceNo, pipe); outputStream = (NetResponseWriter)Pipe.outputStream(pipe); lastResponseWriterFinished = 1&(context>>ServerCoordinator.END_RESPONSE_SHIFT); //NB: context passed in here is looked at to know if this is END_RESPONSE and if so //then the length is added if not then the header will designate chunked. outputStream.openField(statusCode, context, contentType); writable.write(outputStream); if (0 == lastResponseWriterFinished) { // for chunking we must end this block outputStream.write(RETURN_NEWLINE); } outputStream.publishWithHeader(block1HeaderBlobPosition, block1PositionOfLen); //closeLowLevelField and publish return true; } private void holdEmptyBlock(long connectionId, final int sequenceNo, Pipe<ServerResponseSchema> pipe) { Pipe.addMsgIdx(pipe, ServerResponseSchema.MSG_TOCHANNEL_100); Pipe.addLongValue(connectionId, pipe); Pipe.addIntValue(sequenceNo, pipe); NetResponseWriter outputStream = (NetResponseWriter)Pipe.outputStream(pipe); block1HeaderBlobPosition = Pipe.getWorkingBlobHeadPosition(pipe); DataOutputBlobWriter.openFieldAtPosition(outputStream, block1HeaderBlobPosition); //no context, that will come in the second message //for the var field we store this as meta then length block1PositionOfLen = 1+Pipe.workingHeadPosition(pipe); DataOutputBlobWriter.closeLowLevelMaxVarLenField(outputStream); assert(pipe.maxVarLen == Pipe.slab(pipe)[((int)block1PositionOfLen) & Pipe.slabMask(pipe)]) : "expected max var field length"; Pipe.addIntValue(0, pipe); //no context, that will come in the second message //the full blob size of this message is very large to ensure we have room later... //this call allows for the following message to be written after this messages blob data int consumed = Pipe.writeTrailingCountOfBytesConsumed(outputStream.getPipe()); assert(pipe.maxVarLen == consumed); Pipe.confirmLowLevelWrite(pipe); //Stores this publish until the next message is complete and published Pipe.storeUnpublishedWrites(outputStream.getPipe()); //logger.info("new empty block at {} {} ",block1HeaderBlobPosition, block1PositionOfLen); } public boolean publishHTTPResponseContinuation(HTTPFieldReader w, int context, NetWritable writable) { return publishHTTPResponseContinuation(w.getConnectionId(),w.getSequenceCode(), context, writable); } public boolean publishHTTPResponseContinuation(long connectionId, long sequenceCode, int context, NetWritable writable) { assert((0 != (initFeatures & NET_RESPONDER))) : "CommandChannel must be created with NET_RESPONDER flag"; final int sequenceNo = 0xFFFFFFFF & (int)sequenceCode; final int parallelIndex = 0xFFFFFFFF & (int)(sequenceCode>>32); assert(0==lastResponseWriterFinished) : "Unable to find write in progress, nothing to continue with"; Pipe<ServerResponseSchema> pipe = netResponse.length>1 ? netResponse[parallelIndex] : netResponse[0]; //logger.trace("calling publishHTTPResponseContinuation"); if (!Pipe.hasRoomForWrite(pipe)) { return false; } //message 1 which contains the chunk length holdEmptyBlock(connectionId, sequenceNo, pipe); //message 2 which contains the chunk Pipe.addMsgIdx(pipe, ServerResponseSchema.MSG_TOCHANNEL_100); Pipe.addLongValue(connectionId, pipe); Pipe.addIntValue(sequenceNo, pipe); NetResponseWriter outputStream = (NetResponseWriter)Pipe.outputStream(pipe); outputStream.openField(context); writable.write(outputStream); //this is not the end of the data so we must close this block outputStream.write(RETURN_NEWLINE); lastResponseWriterFinished = 1&(context>>ServerCoordinator.END_RESPONSE_SHIFT); if (1 == lastResponseWriterFinished) { //this is the end of the data, we must close the block //and add the zero trailer //this adds 3, note the publishWithChunkPrefix also takes this into account Appendables.appendHexDigitsRaw(outputStream, 0); outputStream.write(AbstractAppendablePayloadResponseStage.RETURN_NEWLINE); //TODO: add trailing headers here. (no request for this feature yet) outputStream.write(AbstractAppendablePayloadResponseStage.RETURN_NEWLINE); } outputStream.publishWithChunkPrefix(block1HeaderBlobPosition, block1PositionOfLen); return true; } public static void publishGo(int count, int pipeIdx, MsgCommandChannel<?> gcc) { assert(pipeIdx>=0); TrafficOrderSchema.publishGo(gcc.goPipe, pipeIdx, count); } public static void publishBlockChannel(long durationNanos, MsgCommandChannel<?> gcc) { TrafficOrderSchema.publishBlockChannel(gcc.goPipe, durationNanos); } public static void publishBlockChannelUntil(long timeMS, MsgCommandChannel<?> gcc) { TrafficOrderSchema.publishBlockChannelUntil(gcc.goPipe, timeMS); } public String[] privateTopics() { return privateTopics; } public void privateTopics(String... topic) { privateTopics = topic; int i = topic.length; privateTopicPipes = new Pipe[i]; PipeConfig<MessagePrivate> config = pcm.getConfig(MessagePrivate.class); while (--i >= 0) { privateTopicPipes[i] = new Pipe(config); } int j= topic.length; privateTopicsTrie = new TrieParser(j,1,false,false,false);//a topic is case-sensitive while (--j>=0) { privateTopicsTrie.setUTF8Value(topic[j], j);//to matching pipe index } privateTopicsTrieReader = new TrieParserReader(0,true); } public boolean isGoPipe(Pipe<TrafficOrderSchema> target) { return target==goPipe; } }
package com.platform.common.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.commons.lang3.time.DateFormatUtils; public class DateUtils extends org.apache.commons.lang3.time.DateUtils { private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"}; public static String getDate() { return getDate("yyyy-MM-dd"); } public static String getDateTime() { return getDate("yyyy-MM-dd HH:mm:ss"); } public static String getDate(String pattern) { return DateFormatUtils.format(new Date(), pattern); } public static String formatDate(Date date, String... pattern) { String formatDate = null; if (pattern != null && pattern.length > 0) { formatDate = DateFormatUtils.format(date, pattern[0]); } else { formatDate = DateFormatUtils.format(date, "yyyy-MM-dd"); } return formatDate; } public static String formatDateTime(Date date) { return formatDate(date, "yyyy-MM-dd HH:mm:ss"); } /** * HH:mm:ss */ public static String getTime() { return formatDate(new Date(), "HH:mm:ss"); } /** * yyyy */ public static String getYear() { return formatDate(new Date(), "yyyy"); } public static String getMonth() { return formatDate(new Date(), "MM"); } public static String getDay() { return formatDate(new Date(), "dd"); } public static String getWeek() { return formatDate(new Date(), "E"); } public static Date parseDate(Object str) { if (str==null || StringUtils.isEmpty(str.toString())){ return null; } try { return parseDate(str.toString(), parsePatterns); } catch (ParseException e) { return null; } } /** * * @param date * @return */ public static long pastDays(Date date) { long t = new Date().getTime()-date.getTime(); return t/(24*60*60*1000); } /** * * @param date * @return */ public static long pastHour(Date date) { long t = new Date().getTime()-date.getTime(); return t/(60*60*1000); } /** * * @param date * @return */ public static long pastMinutes(Date date) { long t = new Date().getTime()-date.getTime(); return t/(60*1000); } /** * ,::. * @param timeMillis * @return */ public static String formatDateTime(long timeMillis){ long day = timeMillis/(24*60*60*1000); long hour = (timeMillis/(60*60*1000)-day*24); long min = ((timeMillis/(60*1000))-day*24*60-hour*60); long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60); long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000); return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss; } /** * * @param before * @param after * @return */ public static double getDistanceOfTwoDate(Date before, Date after) { long beforeTime = before.getTime(); long afterTime = after.getTime(); return (afterTime - beforeTime) / (1000 * 60 * 60 * 24); } /** * * @param year * @return */ public boolean isLeapYear(int year) { boolean leap; if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) { leap = true; } else { leap = false; } } else { leap = true; } } else { leap = false; } return leap; } /** * * @param: @param identity */ public static Date identityToBirthday(String identity){ try { String birthday = identity.substring(6,14); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); return sdf.parse(birthday); } catch (Exception e) { return null; } } /** * * @param: @param identity */ public static Integer identityToAge(String identity){ try { Date birthDay=identityToBirthday(identity); Calendar cal = Calendar.getInstance(); if (cal.before(birthDay)) { throw new IllegalArgumentException("!"); } int yearNow = cal.get(Calendar.YEAR); int monthNow = cal.get(Calendar.MONTH) + 1; int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); cal.setTime(birthDay); int yearBirth = cal.get(Calendar.YEAR); int monthBirth = cal.get(Calendar.MONTH)+1; int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); int age = yearNow - yearBirth; if (monthNow <= monthBirth) { if (monthNow == monthBirth) { if (dayOfMonthNow < dayOfMonthBirth) { age } } else { age } } if(age<0){ return null; } return age; } catch (Exception e) { return null; } } public static Integer birthdayToAge(String birthday){ try { Date birthDay=parseDate(birthday,"yyyy-MM-dd"); Calendar cal = Calendar.getInstance(); if (cal.before(birthDay)) { throw new IllegalArgumentException("!"); } int yearNow = cal.get(Calendar.YEAR); int monthNow = cal.get(Calendar.MONTH) + 1; int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); cal.setTime(birthDay); int yearBirth = cal.get(Calendar.YEAR); int monthBirth = cal.get(Calendar.MONTH)+1; int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); int age = yearNow - yearBirth; if (monthNow <= monthBirth) { if (monthNow == monthBirth) { if (dayOfMonthNow < dayOfMonthBirth) { age } } else { age } } if(age<0){ return null; } return age; } catch (Exception e) { return null; } } public static Date getMondayOfCurrentWeek(){ Calendar c = Calendar.getInstance(); c.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY); return c.getTime(); } public static Date getSundayOfCurrentWeek(){ Calendar c = Calendar.getInstance(); c.set(Calendar.DAY_OF_WEEK,Calendar.SATURDAY); c.add(Calendar.DAY_OF_WEEK,1); return c.getTime(); } /** * * @Title: getDayOfCurrentMonth */ public static Date getFirstDayOfCurrentMonth(){ Calendar c = Calendar.getInstance(); c.set(Calendar.DAY_OF_MONTH,1); return c.getTime(); } public static Date getLastDayOfCurrentMonth(){ Calendar c = Calendar.getInstance(); c.add(Calendar.MONTH, 1); c.set(Calendar.DAY_OF_MONTH, 1); c.add(Calendar.DAY_OF_MONTH, -1); return c.getTime(); } /** * *@param lmp */ public static String YCQ(Date lmp){ Calendar cal = Calendar.getInstance(); cal.setTime(lmp); if(cal.get(Calendar.MONTH) > 3){ cal.add(Calendar.MONTH,-3); cal.add(Calendar.YEAR,1); }else{ cal.add(Calendar.MONTH,9); } cal.add(Calendar.DAY_OF_MONTH,7); return formatDate(cal.getTime(), "yyyy-MM-dd"); } /** * *@param edc */ public static String MCYJ(Date edc){ Calendar cal = Calendar.getInstance(); cal.setTime(edc); if(cal.get(Calendar.MONTH) < 10){ cal.add(Calendar.MONTH,3); cal.add(Calendar.YEAR,-1); }else{ cal.add(Calendar.MONTH,-9); } cal.add(Calendar.DAY_OF_MONTH,-7); return formatDate(cal.getTime(), "yyyy-MM-dd"); } /** * * @param: @param dateStr */ public static String dateTOWeekday(String dateStr){ Calendar calendar = Calendar.getInstance(); Date date = parseDate(dateStr); calendar.setTime(date); int number = calendar.get(Calendar.DAY_OF_WEEK)-1; String[] str = {"","","","","","",""}; return str[number]; } public static int[] getYearMonthDay(Date oldBirthday){ Calendar birthday = Calendar.getInstance(); birthday.setTime(oldBirthday); Calendar now = Calendar.getInstance(); int day = now.get(Calendar.DAY_OF_MONTH) - birthday.get(Calendar.DAY_OF_MONTH); int month = now.get(Calendar.MONTH) - birthday.get(Calendar.MONTH); int year = now.get(Calendar.YEAR) - birthday.get(Calendar.YEAR); if(day<0){ month -= 1; now.add(Calendar.MONTH, -1); day = day + now.getActualMaximum(Calendar.DAY_OF_MONTH); } if(month<0){ month = (month+12)%12; year } if(year<0){ day=0; month=0; year=0; } return new int[]{year,month,day}; } }
package com.robothand.highqualitybot; import java.io.File; import java.io.FileNotFoundException; import java.util.Hashtable; import java.util.Scanner; /** * Config.java * * Reads in properties from a specified configuration file, and provides access to the values. */ public class Config { private final File configFile; public String TOKEN; public String PREFIX; public Config(String path) throws FileNotFoundException { // set default values PREFIX = "."; configFile = new File(path); Scanner s = new Scanner(configFile); while (s.hasNextLine()) { String[] split = s.nextLine().split("="); String key, value; if (split.length < 2 || split[0].trim().startsWith(" continue; } key = split[0].trim(); value = split[1].trim(); // place the property if it is known switch (key) { case "token": TOKEN = value; break; case "prefix": PREFIX = value; break; default: System.out.println("Info: Unknown property \"" + key + "\", ignoring."); } // Check for values that would need user input if (TOKEN == null) { Scanner c = new Scanner(System.in); System.out.println("Warning: OAuth token not set in config. Please enter your token below:"); System.out.print("> "); TOKEN = c.nextLine(); System.out.println("Token set. Recommend setting in config file for future runs."); } } } }
package com.rultor.agents.req; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.jcabi.aspects.Immutable; import com.jcabi.log.Logger; import com.jcabi.ssh.SSH; import com.jcabi.xml.XML; import com.rultor.agents.AbstractAgent; import com.rultor.spi.Profile; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.Locale; import java.util.Map; import lombok.EqualsAndHashCode; import lombok.ToString; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.CharEncoding; import org.xembly.Directive; import org.xembly.Directives; /** * Merges. * * @author Yegor Bugayenko (yegor@teamed.io) * @version $Id$ * @since 1.0 */ @Immutable @ToString @EqualsAndHashCode(callSuper = false, of = "profile") public final class StartsRequest extends AbstractAgent { /** * Default port value to be used with Decrypt. */ private static final String DEFAULT_PORT = "80"; /** * HTTP proxy port system property key. */ private static final String PORT_KEY = "http.proxyPort"; /** * HTTP proxy host system property key. */ private static final String HOST_KEY = "http.proxyHost"; /** * Profile. */ private final transient Profile profile; /** * Ctor. * @param prof Profile */ public StartsRequest(final Profile prof) { super( "/talk/request[@id and type and not(success)]", "/talk[not(daemon)]" ); this.profile = prof; } @Override public Iterable<Directive> process(final XML xml) throws IOException { final XML req = xml.nodes("//request").get(0); final String type = req.xpath("type/text()").get(0); final String hash = req.xpath("@id").get(0); String script; try { script = this.script( req, type, xml.xpath("/talk/@name").get(0) ); Logger.info( this, "request %s/%s started for %s", type, hash, xml.xpath("/talk/@name ").get(0) ); } catch (final Profile.ConfigException ex) { script = Logger.format( "cat <<EOT\n%[exception]s\nEOT\nexit -1", ex ); } return new Directives().xpath("/talk") .add("daemon") .attr("id", hash) .add("title").set(type).up() .add("script").set(script); } /** * Make a script. * @param req Request * @param type Its type * @param name Name of talk * @return Script * @throws IOException If fails */ @SuppressWarnings("unchecked") private String script(final XML req, final String type, final String name) throws IOException { return Joiner.on('\n').join( Iterables.concat( Iterables.transform( Sets.union( this.vars(req, type).entrySet(), Sets.newHashSet( Maps.immutableEntry( "container", name.replaceAll("[^a-zA-Z0-9_.-]", "_") .toLowerCase(Locale.ENGLISH) ) ) ), new Function<Map.Entry<String, String>, String>() { @Override public String apply( final Map.Entry<String, String> input) { return String.format( "%s=%s", input.getKey(), StartsRequest.escape(input.getValue()) ); } } ), Collections.singleton(this.asRoot()), Collections.singleton( IOUtils.toString( this.getClass().getResourceAsStream("_head.sh"), CharEncoding.UTF_8 ) ), this.decryptor().commands(), Collections.singleton( IOUtils.toString( this.getClass().getResourceAsStream( String.format("%s.sh", type) ), CharEncoding.UTF_8 ) ) ) ); } /** * Obtain proxy settings and create a Decrypt instance. * @return Decrypt instance. */ private Decrypt decryptor() { return new Decrypt( this.profile, System.getProperty(HOST_KEY, ""), Integer.parseInt(System.getProperty(PORT_KEY, DEFAULT_PORT)) ); } /** * Get start script for as_root config. * @return Script * @throws IOException If fails * @since 1.37 */ private String asRoot() throws IOException { return String.format( "as_root=%b", !this.profile.read().nodes( "/p/entry[@key='docker']/entry[@key='as_root' and .='true']" ).isEmpty() ); } /** * Get variables from script. * @param req Request * @param type Its type * @return Vars * @throws IOException If fails */ private Map<String, String> vars(final XML req, final String type) throws IOException { final ImmutableMap.Builder<String, String> vars = new ImmutableMap.Builder<>(); for (final XML arg : req.nodes("args/arg")) { vars.put( arg.xpath("@name").get(0), arg.xpath("text()").get(0) ); } final DockerRun docker = new DockerRun( this.profile, String.format("/p/entry[@key='%s']", type) ); vars.put( "scripts", new Brackets( Iterables.concat( StartsRequest.export(docker.envs(vars.build())), docker.script() ) ).toString() ); vars.put( "vars", new Brackets( Iterables.transform( docker.envs(vars.build()), new Function<String, String>() { @Override public String apply(final String input) { return String.format("--env=%s", input); } } ) ).toString() ); final Profile.Defaults def = new Profile.Defaults(this.profile); vars.put( "image", def.text( "/p/entry[@key='docker']/entry[@key='image']", "yegor256/rultor" ) ); vars.put( "directory", def.text("/p/entry[@key='docker']/entry[@key='directory']") ); if (!this.profile.read().nodes("/p/entry[@key='merge']").isEmpty()) { vars.put( "squash", def.text( "/p/entry[@key='merge']/entry[@key='squash']", Boolean.FALSE.toString() ).toLowerCase(Locale.ENGLISH) ); vars.put( "ff", def.text( "/p/entry[@key='merge']/entry[@key='fast-forward']", "default" ).toLowerCase(Locale.ENGLISH) ); vars.put( "rebase", def.text( "/p/entry[@key='merge']/entry[@key='rebase']", Boolean.FALSE.toString() ).toLowerCase(Locale.ENGLISH) ); } return vars.build(); } /** * Escape var. * @param raw The variable * @return Escaped one */ private static String escape(final String raw) { final String esc; if (raw.matches("\\(.*\\)")) { esc = raw; } else { esc = SSH.escape(raw); } return esc; } /** * Export env vars. * @param envs List of them * @return Formatted lines */ private static Iterable<String> export(final Iterable<String> envs) { final Collection<String> lines = new LinkedList<>(); for (final String env : envs) { lines.add(String.format("export %s", env)); lines.add(";"); } return lines; } }
// Depot library - a Java relational persistence library // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.depot.impl; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import com.samskivert.depot.DatabaseException; import com.samskivert.depot.PersistentRecord; import com.samskivert.depot.expression.SQLExpression; import com.samskivert.depot.util.*; // TupleN /** * Contains a set of selection expressions which are to be projected (selected) from a set of * tables. Handles the necessary type conversions to turn the results into typed tuples. */ public abstract class Projector<T extends PersistentRecord,R> { public static <T extends PersistentRecord, V> Projector<T,V> create ( Class<T> ptype, SQLExpression<V> column) { return new Projector<T, V>(ptype, new SQLExpression<?>[] { column }) { @Override public V createObject (Object[] results) { @SuppressWarnings("unchecked") V result = (V)results[0]; return result; } }; } public static <T extends PersistentRecord, V1, V2> Projector<T,Tuple2<V1,V2>> create ( Class<T> ptype, SQLExpression<V1> col1, SQLExpression<V2> col2) { return new Projector<T, Tuple2<V1,V2>>(ptype, new SQLExpression<?>[] { col1, col2 }) { @Override public Tuple2<V1,V2> createObject (Object[] results) { @SuppressWarnings("unchecked") V1 r1 = (V1)results[0]; @SuppressWarnings("unchecked") V2 r2 = (V2)results[1]; return new Tuple2<V1,V2>(r1, r2); } }; } public static <T extends PersistentRecord, V1, V2, V3> Projector<T,Tuple3<V1,V2,V3>> create ( Class<T> ptype, SQLExpression<V1> col1, SQLExpression<V2> col2, SQLExpression<V3> col3) { return new Projector<T, Tuple3<V1,V2,V3>>( ptype, new SQLExpression<?>[] { col1, col2, col3 }) { @Override public Tuple3<V1,V2,V3> createObject (Object[] results) { @SuppressWarnings("unchecked") V1 r1 = (V1)results[0]; @SuppressWarnings("unchecked") V2 r2 = (V2)results[1]; @SuppressWarnings("unchecked") V3 r3 = (V3)results[2]; return new Tuple3<V1,V2,V3>(r1, r2, r3); } }; } public static <T extends PersistentRecord, V1, V2, V3, V4> Projector<T,Tuple4<V1,V2,V3,V4>> create ( Class<T> ptype, SQLExpression<V1> col1, SQLExpression<V2> col2, SQLExpression<V3> col3, SQLExpression<V4> col4) { return new Projector<T, Tuple4<V1,V2,V3,V4>>( ptype, new SQLExpression<?>[] { col1, col2, col3, col4 }) { @Override public Tuple4<V1,V2,V3,V4> createObject (Object[] results) { @SuppressWarnings("unchecked") V1 r1 = (V1)results[0]; @SuppressWarnings("unchecked") V2 r2 = (V2)results[1]; @SuppressWarnings("unchecked") V3 r3 = (V3)results[2]; @SuppressWarnings("unchecked") V4 r4 = (V4)results[3]; return new Tuple4<V1,V2,V3,V4>(r1, r2, r3, r4); } }; } public static <T extends PersistentRecord, V1, V2, V3, V4, V5> Projector<T,Tuple5<V1,V2,V3,V4,V5>> create ( Class<T> ptype, SQLExpression<V1> col1, SQLExpression<V2> col2, SQLExpression<V3> col3, SQLExpression<V4> col4, SQLExpression<V5> col5) { return new Projector<T, Tuple5<V1,V2,V3,V4,V5>>( ptype, new SQLExpression<?>[] { col1, col2, col3, col4, col5 }) { @Override public Tuple5<V1,V2,V3,V4,V5> createObject (Object[] results) { @SuppressWarnings("unchecked") V1 r1 = (V1)results[0]; @SuppressWarnings("unchecked") V2 r2 = (V2)results[1]; @SuppressWarnings("unchecked") V3 r3 = (V3)results[2]; @SuppressWarnings("unchecked") V4 r4 = (V4)results[3]; @SuppressWarnings("unchecked") V5 r5 = (V5)results[4]; return new Tuple5<V1,V2,V3,V4,V5>(r1, r2, r3, r4, r5); } }; } public static <T extends PersistentRecord, V> Projector<T,V> create ( Class<T> ptype, final Class<V> resultType, SQLExpression<?>... selexps) { return new Projector<T, V>(ptype, selexps) { public V createObject (Object[] results) { try { return _ctor.newInstance(results); } catch (InstantiationException e) { throw new DatabaseException("Invalid constructor supplied for projection", e); } catch (IllegalAccessException e) { throw new DatabaseException("Invalid constructor supplied for projection", e); } catch (InvocationTargetException e) { Throwable t = e.getCause(); if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new DatabaseException("Error constructing result object", t); } } } @SuppressWarnings("unchecked") protected Constructor<V> _ctor = (Constructor<V>)resultType.getConstructors()[0]; }; } public final Class<T> ptype; public final SQLExpression<?>[] selexps; public abstract R createObject (Object[] results); protected Projector (Class<T> ptype, SQLExpression<?>[] selexps) { this.ptype = ptype; this.selexps = selexps; } }
package com.sri.ai.praise.demo; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.border.EmptyBorder; import com.google.common.annotations.Beta; import com.sri.ai.praise.lbp.LBPConfiguration; import com.sri.ai.util.Util; /** * * @author oreilly * */ @Beta public class OptionsPanel extends JPanel { private static final long serialVersionUID = 1L; private static final String SYNCHRONOUS = "SYNCHRONOUS"; private static final String ASYNC_INDIVIDUAL = "ASYNC INDIVIDUAL"; private static final String ASYNC_GROUP = "ASYNC GROUP"; JFormattedTextField domainSizeTextField = null; JComboBox scheduleComboBox; JCheckBox chckbxJustificationToConsole; JCheckBox chckbxJustificationToJustTab; JCheckBox chckbxTraceToConsole; JCheckBox chckbxTraceToTrace; JCheckBox chckbxJustificationEnabled; JCheckBox chckbxTraceEnabled; JCheckBox chckbxOverrideModel; JCheckBox chckbxKnownDomainSize; JCheckBox chckbxAssumeDomainsAlwaysLarge; /** * Create the panel. */ public OptionsPanel() { setBorder(new EmptyBorder(0, 5, 0, 0)); initialize(); postGUIInitialization(); } public LBPConfiguration.BeliefPropagationUpdateSchedule getSelectedSchedule() { LBPConfiguration.BeliefPropagationUpdateSchedule result = null; String scheduleName = scheduleComboBox.getItemAt(scheduleComboBox.getSelectedIndex()).toString(); if (scheduleName.equals(SYNCHRONOUS)) { result = LBPConfiguration.BeliefPropagationUpdateSchedule.SYNCHRONOUS; } else if (scheduleName.equals(ASYNC_INDIVIDUAL)) { result = LBPConfiguration.BeliefPropagationUpdateSchedule.ASYNCHRONOUS_INDIVIDUAL_BASED_CYCLE_DETECTION; } else if (scheduleName.equals(ASYNC_GROUP)) { result = LBPConfiguration.BeliefPropagationUpdateSchedule.ASYNCHRONOUS_GROUP_BASED_CYCLE_DETECTION; } else { Util.fatalError("Missing Schedule Mapping."); } return result; } // PRIVATE private void initialize() { setLayout(new BorderLayout(0, 0)); JPanel optionsPanel = new JPanel(); add(optionsPanel, BorderLayout.NORTH); optionsPanel.setBorder(null); optionsPanel.setLayout(new BoxLayout(optionsPanel, BoxLayout.Y_AXIS)); JLabel lblOptions = new JLabel("Options"); lblOptions.setFont(new Font("SansSerif", Font.BOLD, 12)); optionsPanel.add(lblOptions); JSeparator separator_5 = new JSeparator(); optionsPanel.add(separator_5); JSeparator separator_4 = new JSeparator(); optionsPanel.add(separator_4); JPanel schedulePanel = new JPanel(); schedulePanel.setAlignmentX(Component.LEFT_ALIGNMENT); optionsPanel.add(schedulePanel); schedulePanel.setLayout(new BoxLayout(schedulePanel, BoxLayout.X_AXIS)); JLabel lblSchedule = new JLabel("Schedule:"); schedulePanel.add(lblSchedule); scheduleComboBox = new JComboBox(); scheduleComboBox.setPreferredSize(new Dimension(100, 25)); schedulePanel.add(scheduleComboBox); chckbxOverrideModel = new JCheckBox("Override Model's Domain Sizes (i.e. sort sizes)"); chckbxOverrideModel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (chckbxOverrideModel.isSelected()) { chckbxKnownDomainSize.setEnabled(true); domainSizeTextField.setEnabled(true); chckbxAssumeDomainsAlwaysLarge.setEnabled(true); } else { chckbxKnownDomainSize.setEnabled(false); domainSizeTextField.setEnabled(false); chckbxAssumeDomainsAlwaysLarge.setEnabled(false); } } }); chckbxOverrideModel.setPreferredSize(new Dimension(18, 25)); optionsPanel.add(chckbxOverrideModel); JPanel knownSizePanel = new JPanel(); knownSizePanel.setAlignmentX(Component.LEFT_ALIGNMENT); FlowLayout flowLayout = (FlowLayout) knownSizePanel.getLayout(); flowLayout.setVgap(0); flowLayout.setHgap(0); flowLayout.setAlignment(FlowLayout.LEFT); optionsPanel.add(knownSizePanel); JLabel lblNewLabel = new JLabel(" "); knownSizePanel.add(lblNewLabel); chckbxKnownDomainSize = new JCheckBox("Known Domain Size"); chckbxKnownDomainSize.setSelected(true); chckbxKnownDomainSize.setEnabled(false); knownSizePanel.add(chckbxKnownDomainSize); domainSizeTextField = new JFormattedTextField(); domainSizeTextField.setEnabled(false); domainSizeTextField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { Integer size = new Integer(10); try { size = new Integer(domainSizeTextField.getText()); if (size < 1) { size = 1; domainSizeTextField.setValue(size); } } catch (NumberFormatException nfe) { domainSizeTextField.setValue(size); } } }); domainSizeTextField.setPreferredSize(new Dimension(80, 25)); domainSizeTextField.setValue(new Integer(10)); knownSizePanel.add(domainSizeTextField); JPanel assumePanel = new JPanel(); assumePanel.setAlignmentX(Component.LEFT_ALIGNMENT); FlowLayout flowLayout_1 = (FlowLayout) assumePanel.getLayout(); flowLayout_1.setVgap(0); flowLayout_1.setHgap(0); flowLayout_1.setAlignment(FlowLayout.LEFT); optionsPanel.add(assumePanel); JLabel label_4 = new JLabel(" "); assumePanel.add(label_4); chckbxAssumeDomainsAlwaysLarge = new JCheckBox("Assume Domains Always Large"); assumePanel.add(chckbxAssumeDomainsAlwaysLarge); chckbxAssumeDomainsAlwaysLarge.setPreferredSize(new Dimension(240, 25)); JSeparator separator_1 = new JSeparator(); optionsPanel.add(separator_1); chckbxJustificationEnabled = new JCheckBox("Justification Enabled"); chckbxJustificationEnabled.setSelected(true); chckbxJustificationEnabled.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (chckbxJustificationEnabled.isSelected()) { chckbxJustificationToConsole.setEnabled(true); chckbxJustificationToJustTab.setEnabled(true); } else { chckbxJustificationToConsole.setEnabled(false); chckbxJustificationToJustTab.setEnabled(false); } } }); chckbxJustificationEnabled.setPreferredSize(new Dimension(175, 25)); optionsPanel.add(chckbxJustificationEnabled); JPanel justOutToConsolePanel = new JPanel(); FlowLayout flowLayout_2 = (FlowLayout) justOutToConsolePanel.getLayout(); flowLayout_2.setVgap(0); flowLayout_2.setHgap(0); flowLayout_2.setAlignment(FlowLayout.LEFT); justOutToConsolePanel.setAlignmentX(0.0f); optionsPanel.add(justOutToConsolePanel); JLabel label = new JLabel(" "); justOutToConsolePanel.add(label); chckbxJustificationToConsole = new JCheckBox("Output to Console Tab"); chckbxJustificationToConsole.setPreferredSize(new Dimension(200, 25)); justOutToConsolePanel.add(chckbxJustificationToConsole); JPanel justOutToJustPanel = new JPanel(); FlowLayout flowLayout_3 = (FlowLayout) justOutToJustPanel.getLayout(); flowLayout_3.setVgap(0); flowLayout_3.setHgap(0); flowLayout_3.setAlignment(FlowLayout.LEFT); justOutToJustPanel.setAlignmentX(0.0f); optionsPanel.add(justOutToJustPanel); JLabel label_1 = new JLabel(" "); justOutToJustPanel.add(label_1); chckbxJustificationToJustTab = new JCheckBox("Output to Justification Tab"); chckbxJustificationToJustTab.setSelected(true); chckbxJustificationToJustTab.setPreferredSize(new Dimension(200, 25)); justOutToJustPanel.add(chckbxJustificationToJustTab); JSeparator separator_2 = new JSeparator(); optionsPanel.add(separator_2); chckbxTraceEnabled = new JCheckBox("Trace Enabled"); chckbxTraceEnabled.setSelected(true); chckbxTraceEnabled.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (chckbxTraceEnabled.isSelected()) { chckbxTraceToConsole.setEnabled(true); chckbxTraceToTrace.setEnabled(true); } else { chckbxTraceToConsole.setEnabled(false); chckbxTraceToTrace.setEnabled(false); } } }); chckbxTraceEnabled.setPreferredSize(new Dimension(141, 25)); optionsPanel.add(chckbxTraceEnabled); JPanel traceOutToConsolePanel = new JPanel(); FlowLayout flowLayout_4 = (FlowLayout) traceOutToConsolePanel.getLayout(); flowLayout_4.setVgap(0); flowLayout_4.setHgap(0); flowLayout_4.setAlignment(FlowLayout.LEFT); traceOutToConsolePanel.setAlignmentX(0.0f); optionsPanel.add(traceOutToConsolePanel); JLabel label_2 = new JLabel(" "); traceOutToConsolePanel.add(label_2); chckbxTraceToConsole = new JCheckBox("Output to Console Tab"); chckbxTraceToConsole.setPreferredSize(new Dimension(200, 25)); traceOutToConsolePanel.add(chckbxTraceToConsole); JPanel traceOutputToTracePanel = new JPanel(); FlowLayout flowLayout_5 = (FlowLayout) traceOutputToTracePanel.getLayout(); flowLayout_5.setVgap(0); flowLayout_5.setHgap(0); flowLayout_5.setAlignment(FlowLayout.LEFT); traceOutputToTracePanel.setAlignmentX(0.0f); optionsPanel.add(traceOutputToTracePanel); JLabel label_3 = new JLabel(" "); traceOutputToTracePanel.add(label_3); chckbxTraceToTrace = new JCheckBox("Output to Trace Tab"); chckbxTraceToTrace.setSelected(true); chckbxTraceToTrace.setPreferredSize(new Dimension(200, 25)); traceOutputToTracePanel.add(chckbxTraceToTrace); } private void postGUIInitialization() { scheduleComboBox.addItem(SYNCHRONOUS); scheduleComboBox.addItem(ASYNC_INDIVIDUAL); scheduleComboBox.addItem(ASYNC_GROUP); // Don't select by default. chckbxJustificationEnabled.doClick(); chckbxTraceEnabled.doClick(); } }
package controller; import handler.ConfigHandler; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.Event; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.stage.FileChooser; import javafx.stage.Modality; import javafx.stage.Stage; import misc.Job; import misc.Logger; import model.JobSetupDialogModel; import org.apache.commons.lang3.exception.ExceptionUtils; import view.JobSetupDialogView; import javax.swing.*; import java.awt.*; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Iterator; import java.util.List; public class JobSetupDialogController extends Stage implements EventHandler { // todo JavaDoc private final JobSetupDialogView view; // todo JavaDoc private final JobSetupDialogModel model; /** The object that handles settings for encoding, decoding, compression, and a number of other features. */ private final ConfigHandler configHandler; /** * Construct a new job setup dialog controller. * @param configHandler The object that handles settings for encoding, decoding, compression, and a number of other features. */ public JobSetupDialogController(final Stage primaryStage, final ConfigHandler configHandler) { this.configHandler = configHandler; view = new JobSetupDialogView(primaryStage, this, configHandler); model = new JobSetupDialogModel(); // Setup Stage: final Scene scene = new Scene(view); scene.getStylesheets().add("global.css"); scene.getRoot().getStyleClass().add("main-root"); this.initModality(Modality.APPLICATION_MODAL); this.setTitle("Job Creator"); this.getIcons().add(new Image("icon.png")); this.setScene(scene); } @Override public void handle(Event event) { final Object source = event.getSource(); // The button to open the handler selection dialog. if(source.equals(view.getButton_addFiles())) { final FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Job File Selection"); final List<File> selectedFiles = fileChooser.showOpenMultipleDialog(this); if(selectedFiles != null) { model.getList_files().addAll(selectedFiles); // Add all of the files to the list: for(final File f : selectedFiles) { view.getListView_selectedFiles().getItems().add(f.getAbsolutePath()); } } } // The button to remove all files that are currently selected on the scrollpane_selectedFiles. if(source.equals(view.getButton_removeSelectedFiles())) { // If a copy of the observable list is not made, then errors can occur. // These errors are caused by the ObservableList updating as items are being removed. // This causes items that shouldn't be removed to be removed. final ObservableList<String> copy = FXCollections.observableArrayList(view.getListView_selectedFiles().getSelectionModel().getSelectedItems()); view.getListView_selectedFiles().getItems().removeAll(copy); // Remove Jobs from the Model while updating // the IDs of all Jobs. final Iterator<File> it = model.getList_files().iterator(); while(it.hasNext()) { final File f = it.next(); if(view.getListView_selectedFiles().getItems().contains(f.getAbsolutePath()) == false) { it.remove(); } } view.getListView_selectedFiles().getSelectionModel().clearSelection(); } // The button to remove all files from the list. if(source.equals(view.getButton_clearAllFiles())) { model.getList_files().clear(); view.getListView_selectedFiles().getItems().clear(); view.getListView_selectedFiles().getSelectionModel().clearSelection(); } // The radio button that says that each of the currently selected files should be archived as a single archive before encoding. if(source.equals(view.getRadioButton_singleArchive_yes())) { // Ensure that both the single and individual archive options aren't // selected at the same time. view.getRadioButton_individualArchives_no().setSelected(true); } // The radio button that says that each handler should be archived individually before encoding each of them individually. if(source.equals(view.getRadioButton_individualArchives_yes())) { // Ensure that both the single and individual archive options aren't // selected at the same time. view.getRadioButton_singleArchive_no().setSelected(true); } // The button to select the folder to output the archive to if the "Yes" radio button is selected. if(source.equals(view.getButton_selectOutputDirectory())) { final JFileChooser fileChooser = new JFileChooser(); fileChooser.setDragEnabled(false); fileChooser.setMultiSelectionEnabled(false); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setDialogTitle("Directory Slection"); fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); fileChooser.setApproveButtonText("Accept"); fileChooser.setApproveButtonToolTipText("Accept the selected directory."); try { int returnVal = fileChooser.showOpenDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION) { view.getTextField_outputDirectory().setText(fileChooser.getSelectedFile().getPath() + "/"); } } catch(final HeadlessException e) { Logger.writeLog(e.getMessage() + "\n\n" + ExceptionUtils.getStackTrace(e), Logger.LOG_TYPE_WARNING); } } // The button to close the JobCreationDialog without creating a Job. if(source.equals(view.getButton_accept())) { if(areSettingsCorrect() == false) { final String name = view.getField_jobName().getText(); final String description = view.getTextArea_jobDescription().getText(); final String outputDirectory = view.getTextField_outputDirectory().getText(); final List<File> files = model.getList_files(); final boolean isEncodeJob = view.getIsEncodeJob(); final boolean combineAllFilesIntoSingleArchive = view.getRadioButton_singleArchive_yes().isSelected(); final boolean combineIntoIndividualArchives = view.getRadioButton_individualArchives_yes().isSelected(); final Job job = new Job(name, description, outputDirectory, files, isEncodeJob, combineAllFilesIntoSingleArchive, combineIntoIndividualArchives); model.setJob(job); this.close(); } } // The button to close the JobCreationDialog while creating a Job. if(source.equals(view.getButton_cancel())) { model.setJob(null); this.close(); } updateEstimatedDurationLabel(); } // todo Javadoc public boolean areSettingsCorrect() { boolean wasErrorFound = false; // Reset the error states and tooltips of any components // that can have an error state set. // Set the password fields back to their normal look: view.getField_jobName().getStylesheets().remove("field_error.css"); view.getField_jobName().getStylesheets().add("global.css"); view.getField_jobName().setTooltip(null); view.getTextField_outputDirectory().getStylesheets().remove("field_error.css"); view.getTextField_outputDirectory().getStylesheets().add("global.css"); view.getTextField_outputDirectory().setTooltip(new Tooltip("The directory in which to place the en/decoded file(s).")); // Check to see that the Job has been given a name. if(view.getField_jobName().getText().isEmpty()) { view.getField_jobName().getStylesheets().remove("global.css"); view.getField_jobName().getStylesheets().add("field_error.css"); final String errorText = "Error - You need to enter a name for the Job."; view.getField_jobName().setTooltip(new Tooltip(errorText)); wasErrorFound = true; } // Check to see that the output directory exists: if(view.getTextField_outputDirectory().getText().isEmpty() || Files.exists(Paths.get(view.getTextField_outputDirectory().getText())) == false) { view.getTextField_outputDirectory().getStylesheets().remove("global.css"); view.getTextField_outputDirectory().getStylesheets().add("field_error.css"); final Tooltip currentTooltip = view.getTextField_outputDirectory().getTooltip(); final String errorText = "Error - You need to set an output directory for the Job."; view.getField_jobName().setTooltip(new Tooltip(currentTooltip.getText() + "\n\n" + errorText)); wasErrorFound = true; } if(Files.isDirectory(Paths.get(view.getTextField_outputDirectory().getText())) == false) { view.getTextField_outputDirectory().getStylesheets().remove("global.css"); view.getTextField_outputDirectory().getStylesheets().add("field_error.css"); final Tooltip currentTooltip = view.getTextField_outputDirectory().getTooltip(); final String errorText = "Error - You need to set a valid output directory for the Job."; view.getField_jobName().setTooltip(new Tooltip(currentTooltip.getText() + "\n\n" + errorText)); wasErrorFound = true; } return wasErrorFound; } // todo JavaDoc public void updateEstimatedDurationLabel() { if(model.getJob() != null) { view.getLabel_job_estimatedDurationInMinutes().setText("Estimated Time - " + model.getJob().getEstimatedDurationInMinutes() + " Minutes"); } else { view.getLabel_job_estimatedDurationInMinutes().setText("Estimated Time - Unknown"); } } ////////////////////////////////////////////////////////// Getters // todo JavaDoc public JobSetupDialogView getView() { return view; } // todo JavaDoc public JobSetupDialogModel getModel() { return model; } }
package de.ddb.pdc.metadata; import java.util.ArrayList; import java.util.LinkedHashMap; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; /** * Implementation of the {@link MetaFetcher} interface. */ public class MetaFetcherImpl implements MetaFetcher { private static final String URL = "https: private static final String APIURL = "https://api.deutsche-digitale-bibliothek.de"; private static final String SEARCH = "/search?"; private static final String AUTH = "oauth_consumer_key="; private static final String SORTROWS = "&sort=RELEVANCE&rows="; private static final String QUERY = "&query="; private static final String ITEM = "/items/"; private static final String AIP = "/aip?"; private RestTemplate restTemplate; private String authKey; /** * Creates a new MetaFetcherImpl. * * @param restTemplate RestTemplate to use for issuing requests * @param authKey authentication Key for the DDB API */ public MetaFetcherImpl(RestTemplate restTemplate, String authKey) { this.restTemplate = restTemplate; this.authKey = authKey; } /** * {@inheritDoc} */ public DDBItem[] searchForItems(String query, int maxCount) throws RestClientException { String modifiedQuery = query.replace(" ", "+"); String url = APIURL + SEARCH + AUTH + authKey + SORTROWS + maxCount + QUERY + modifiedQuery; ResultsOfJSON roj = restTemplate.getForObject(url, ResultsOfJSON.class); return getDDBItems(roj); } /** * {@inheritDoc} */ public void fetchMetadata(DDBItem ddbItem) throws RestClientException { String url = APIURL + ITEM + ddbItem.getId() + AIP + AUTH + authKey; ResultsOfJSON roj = restTemplate.getForObject(url, ResultsOfJSON.class); fillDDBItemMetadataFromDDB(ddbItem, roj); } /** * @param ddbItem filled with information * @param roj store information of the ddb aip request */ private void fillDDBItemMetadataFromDDB(DDBItem ddbItem, ResultsOfJSON roj) { RDFItem rdfitem = roj.getEdm().getRdf(); String publishedYear = (String) rdfitem.getProvidedCHO().get("issued"); int year = 8000; try { if (publishedYear != null) { year = Integer.parseInt(publishedYear.split(",")[0]); } } catch (NumberFormatException e) { //test } ddbItem.setPublishedYear(year); // some Agent input are represented at ArrayList or LinkedHashMap if (rdfitem.getAgent().getClass() == ArrayList.class) { ArrayList<LinkedHashMap> alAgent = (ArrayList) rdfitem.getAgent(); for (int idx = 0; idx < alAgent.size(); idx++) { if (alAgent.get(idx).get("@about").toString().startsWith("http")) { String authorid = alAgent.get(idx).get("@about").toString() .replace("http://d-nb.info/gnd/", ""); Author author = new Author(authorid); ddbItem.setAuthor(author); } } } // till now no testdata where author in LinkedHashMap if (rdfitem.getAgent().getClass() == LinkedHashMap.class) { //LinkedHashMap lhmAgent = (LinkedHashMap) rdf.get("Agent"); } ddbItem.setInstitute((String) rdfitem.getAggregation().get("provider")); } /** * @param roj results of the ddb search query * @return a list of ddbitems from roj */ private DDBItem[] getDDBItems(ResultsOfJSON roj) { int maxResults = roj.getResults().size(); DDBItem[] ddbItems = new DDBItem[maxResults]; int idx = 0; for (SearchResultItem rsi : roj.getResults()) { DDBItem ddbItem = new DDBItem(rsi.getId()); ddbItem.setTitle(deleteMatchTags(rsi.getTitle())); ddbItem.setSubtitle(deleteMatchTags(rsi.getSubtitle())); ddbItem.setImageUrl(URL + rsi.getThumbnail()); ddbItem.setCategory(rsi.getCategory()); ddbItem.setMedia(rsi.getMedia()); ddbItem.setType(rsi.getType()); ddbItems[idx] = ddbItem; idx++; } return ddbItems; } /** * Deletes the "<match>...</match>" markers in metadata values of search * result items. These are added by the DDB API to simplify highlighting * of matching substrings, but we don't need or want them. */ public static String deleteMatchTags(String string) { return string.replace("<match>", "").replace("</match>", ""); } }
package de.lessvoid.nifty.effects.impl; import java.util.logging.Logger; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.effects.EffectImpl; import de.lessvoid.nifty.effects.EffectProperties; import de.lessvoid.nifty.effects.Falloff; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.render.NiftyRenderEngine; import de.lessvoid.nifty.tools.TargetElementResolver; /** * Move - move stuff around. * @author void */ public class Move implements EffectImpl { private Logger log = Logger.getLogger(Move.class.getName()); private static final String LEFT = "left"; private static final String RIGHT = "right"; private static final String TOP = "top"; private static final String BOTTOM = "bottom"; private String direction; private long offset = 0; private long startOffset = 0; private int offsetDir = 0; private float offsetY; private float startOffsetY; private int startOffsetX; private float offsetX; private boolean withTarget = false; private boolean fromOffset = false; private boolean toOffset = false; public void activate(final Nifty nifty, final Element element, final EffectProperties parameter) { String mode = parameter.getProperty("mode"); direction = parameter.getProperty("direction"); if (LEFT.equals(direction)) { offset = element.getX() + element.getWidth(); } else if (RIGHT.equals(direction)) { offset = nifty.getRenderEngine().getWidth() - element.getX(); } else if (TOP.equals(direction)) { offset = element.getY() + element.getHeight(); } else if (BOTTOM.equals(direction)) { offset = nifty.getRenderEngine().getHeight() - element.getY(); } else { offset = 0; } if ("out".equals(mode)) { startOffset = 0; offsetDir = -1; withTarget = false; } else if ("in".equals(mode)) { startOffset = offset; offsetDir = 1; withTarget = false; } else if ("fromPosition".equals(mode)) { withTarget = true; } else if ("toPosition".equals(mode)) { withTarget = true; } else if ("fromOffset".equals(mode)) { fromOffset = true; startOffsetX = Integer.valueOf(parameter.getProperty("offsetX", "0")); startOffsetY = Integer.valueOf(parameter.getProperty("offsetY", "0")); offsetX = startOffsetX * -1; offsetY = startOffsetY * -1; } else if ("toOffset".equals(mode)) { toOffset = true; startOffsetX = 0; startOffsetY = 0; offsetX = Integer.valueOf(parameter.getProperty("offsetX", "0")); offsetY = Integer.valueOf(parameter.getProperty("offsetY", "0")); } String target = parameter.getProperty("targetElement"); if (target != null) { TargetElementResolver resolver = new TargetElementResolver(nifty.getCurrentScreen(), element); Element targetElement = resolver.resolve(target); if (targetElement == null) { log.warning("move effect for element [" + element.getId() + "] was unable to find target element [" + target + "] at screen [" + nifty.getCurrentScreen().getScreenId() + "]"); return; } if ("fromPosition".equals(mode)) { startOffsetX = targetElement.getX() - element.getX(); startOffsetY = targetElement.getY() - element.getY(); offsetX = -(targetElement.getX() - element.getX()); offsetY = -(targetElement.getY() - element.getY()); } else if ("toPosition".equals(mode)) { startOffsetX = 0; startOffsetY = 0; offsetX = (targetElement.getX() - element.getX()); offsetY = (targetElement.getY() - element.getY()); } } } public void execute( final Element element, final float normalizedTime, final Falloff falloff, final NiftyRenderEngine r) { if (fromOffset || toOffset) { float moveToX = startOffsetX + normalizedTime * offsetX; float moveToY = startOffsetY + normalizedTime * offsetY; r.moveTo(moveToX, moveToY); } else if (withTarget) { float moveToX = startOffsetX + normalizedTime * offsetX; float moveToY = startOffsetY + normalizedTime * offsetY; r.moveTo(moveToX, moveToY); } else { if (LEFT.equals(direction)) { r.moveTo(-startOffset + offsetDir * normalizedTime * offset, 0); } else if (RIGHT.equals(direction)) { r.moveTo(startOffset - offsetDir * normalizedTime * offset, 0); } else if (TOP.equals(direction)) { r.moveTo(0, -startOffset + offsetDir * normalizedTime * offset); } else if (BOTTOM.equals(direction)) { r.moveTo(0, startOffset - offsetDir * normalizedTime * offset); } } } public void deactivate() { } }
package de.prob2.ui; import java.io.IOException; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob2.ui.animations.AnimationsView; import de.prob2.ui.history.HistoryView; import de.prob2.ui.modelchecking.ModelcheckingController; import de.prob2.ui.operations.OperationsView; import javafx.beans.value.ObservableValue; import javafx.event.EventType; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.Point2D; import javafx.scene.Cursor; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.SnapshotParameters; import javafx.scene.control.Accordion; import javafx.scene.control.SplitPane; import javafx.scene.control.TitledPane; import javafx.scene.image.ImageView; import javafx.scene.input.DragEvent; import javafx.scene.input.Dragboard; import javafx.scene.input.MouseEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.BorderPane; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import org.apache.commons.lang.ObjectUtils; @Singleton public class NewAnimationPerspective extends BorderPane { // TODO (real) DragDrop/Docking // TODO reverting to accordion @FXML private OperationsView operations; @FXML private TitledPane operationsTP; @FXML private HistoryView history; @FXML private TitledPane historyTP; @FXML private ModelcheckingController modelcheck; @FXML private TitledPane modelcheckTP; @FXML private AnimationsView animations; @FXML private TitledPane animationsTP; @FXML private VBox vBox; @FXML private Accordion accordion; private boolean dragged; @Inject public NewAnimationPerspective() { try { FXMLLoader loader = ProB2.injector.getInstance(FXMLLoader.class); loader.setLocation(getClass().getResource("new_animation_perspective.fxml")); loader.setRoot(this); loader.setController(this); loader.load(); parentProperty().addListener((ObservableValue<? extends Parent> ov, Parent previousParent, Parent nextParent)-> { onDrag(); }); } catch (IOException e) { e.printStackTrace(); } } @FXML public void initialize() { double initialSize = 250; operations.setPrefSize(initialSize,initialSize); history.setPrefSize(initialSize,initialSize); modelcheck.setPrefSize(initialSize,initialSize); animations.setPrefSize(initialSize,initialSize); } private void onDrag() { registerDrag(operations,operationsTP); registerDrag(history,historyTP); registerDrag(modelcheck,modelcheckTP); registerDrag(animations,animationsTP); } private void registerDrag(final Node node, final TitledPane nodeTP){ node.setOnMouseEntered(s -> this.setCursor(Cursor.OPEN_HAND)); node.setOnMousePressed(s -> this.setCursor(Cursor.CLOSED_HAND)); node.setOnMouseDragEntered(s -> { dragged = true; //System.out.println("Drag entered"); s.consume(); }); node.setOnMouseReleased(s -> { this.setCursor(Cursor.DEFAULT); if (dragged){ dragDropped(node,nodeTP); //System.out.println("Drag released"); } dragged = false; s.consume(); }); node.setOnDragDetected(s -> { //System.out.println("Drag detected"); operations.startFullDrag(); s.consume(); }); } private void dragDropped(final Node node, final TitledPane nodeTP){ //System.out.println(node.getClass().toString() + " dragged, isResizable() = "+node.isResizable()); if (vBox.getChildren().contains(node)) { if (this.getRight() == null) { this.setRight(node); } else if (this.getTop() == null) { this.setTop(node); } else if (this.getBottom() == null) { this.setBottom(node); } else if (this.getLeft() == null) { this.setLeft(node); } vBox.getChildren().remove(node); } else { vBox.getChildren().add(node); this.getChildren().remove(node); } } }
package de.retest.recheck.ui.diff; import static java.util.Collections.reverse; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.TreeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.retest.recheck.Properties; import de.retest.recheck.ui.descriptors.Element; public final class Alignment { private static final Logger logger = LoggerFactory.getLogger( Alignment.class ); private final Map<Element, Element> alignment; private final Map<Element, Element> expectedMapOfElementTree = new HashMap<>(); private final Map<Element, Element> actualMapOfElementTree = new HashMap<>(); private final Double minimumMatch = getRequiredMinimumMatch(); private Alignment( final Element expectedComponent, final Element actualComponent ) { final List<Element> expectedComponents = flattenLeafElements( expectedComponent, expectedMapOfElementTree ); final List<Element> actualComponents = flattenLeafElements( actualComponent, actualMapOfElementTree ); logger.debug( "Creating assignment of old to new components, trying to find differences. We are comparing {} with {} components.", expectedComponents.size(), actualComponents.size() ); alignment = createAlignment( expectedComponents, toMapping( actualComponents ) ); addParentAlignment(); } private void addParentAlignment() { final Map<Element, Element> alignmentCopy = new HashMap<>( alignment ); for ( final Map.Entry<Element, Element> alignmentPair : alignmentCopy.entrySet() ) { final List<Element> expectedParents = getParents( alignmentPair.getKey(), expectedMapOfElementTree ); final List<Element> actualParents = getParents( alignmentPair.getValue(), actualMapOfElementTree ); final Map<Element, Element> parentAlignment = createAlignment( expectedParents, toMapping( actualParents ) ); for ( final Map.Entry<Element, Element> parentAlignmentPair : parentAlignment.entrySet() ) { final Element aligned = alignment.get( parentAlignmentPair.getKey() ); if ( aligned == null ) { alignment.put( parentAlignmentPair.getKey(), parentAlignmentPair.getValue() ); continue; } if ( parentAlignmentPair.getValue() == null ) { continue; } if ( match( parentAlignmentPair.getKey(), parentAlignmentPair.getValue() ) > match( parentAlignmentPair.getKey(), aligned ) ) { alignment.put( parentAlignmentPair.getKey(), parentAlignmentPair.getValue() ); } } } } private List<Element> getParents( final Element element, final Map<Element, Element> treeMap ) { final List<Element> result = new ArrayList<>(); Element parent = treeMap.get( element ); while ( parent != null ) { result.add( parent ); parent = treeMap.get( parent ); } return result; } public static Alignment createAlignment( final Element expectedComponent, final Element actualComponent ) { return new Alignment( expectedComponent, actualComponent ); } private static List<Element> flattenLeafElements( final Element element, final Map<Element, Element> mapOfElementTree ) { final List<Element> flattened = new ArrayList<>(); for ( final Element childElement : element.getContainedElements() ) { mapOfElementTree.put( childElement, element ); if ( !childElement.hasContainedElements() ) { flattened.add( childElement ); } else { flattened.addAll( flattenLeafElements( childElement, mapOfElementTree ) ); } } return flattened; } static Map<Element, Element> toMapping( final List<Element> actualElements ) { final Map<Element, Element> result = new LinkedHashMap<>(); for ( final Element element : actualElements ) { final Element oldMapping = result.put( element, element ); if ( oldMapping != null ) { throw new RuntimeException( "Elements should be unique, but those returned the same hash: " + element + " - " + oldMapping ); } } return result; } private Map<Element, Element> createAlignment( final List<Element> expectedComponents, final Map<Element, Element> actualComponents ) { final Map<Element, Match> matches = new HashMap<>(); final Stack<Element> componentsToAlign = toStack( expectedComponents ); final Map<Element, Element> alignment = new HashMap<>(); while ( !componentsToAlign.isEmpty() ) { // Align components from expected with best match. final Element expected = componentsToAlign.pop(); final TreeSet<Match> bestMatches = getBestMatches( expected, actualComponents ); Match bestMatch = bestMatches.pollFirst(); while ( bestMatch != null ) { // If a best match has multiple alignments, delete all but overall best. if ( matches.containsKey( bestMatch.element ) ) { final Match previousMatch = matches.get( bestMatch.element ); if ( bestMatch.similarity <= previousMatch.similarity ) { assert bestMatch.similarity != 1.0 : "bestMatch and previousMatch have a match of 100%? At least paths should differ! " + bestMatch.element.getIdentifyingAttributes().toFullString() + " == " + previousMatch.element.getIdentifyingAttributes().toFullString(); // Case: bestMatch is already taken for other element. bestMatch = bestMatches.pollFirst(); continue; } else { // Case: bestMatch takes this element. alignment.remove( previousMatch.element ); componentsToAlign.add( previousMatch.element ); break; } } else { break; } } if ( bestMatch == null ) { alignment.put( expected, null ); continue; } if ( bestMatch.similarity < minimumMatch ) { logger.debug( "Best match {} is below threshold with {} similarity.", bestMatch.element, bestMatch.similarity ); alignment.put( expected, null ); continue; } alignment.put( expected, bestMatch.element ); matches.put( bestMatch.element, new Match( bestMatch.similarity, expected ) ); } return alignment; } private static Double getRequiredMinimumMatch() { final String value = System.getProperty( Properties.ELEMENT_MATCH_THRESHOLD_PROPERTY ); if ( value == null ) { return Properties.ELEMENT_MATCH_THRESHOLD_DEFAULT; } try { return Double.parseDouble( value ); } catch ( final NumberFormatException e ) { logger.error( "Exception parsing value {} of property {} to double, using default {} instead.", value, Properties.ELEMENT_MATCH_THRESHOLD_PROPERTY, Properties.ELEMENT_MATCH_THRESHOLD_DEFAULT ); return Properties.ELEMENT_MATCH_THRESHOLD_DEFAULT; } } private static Stack<Element> toStack( final List<Element> expectedElements ) { final Stack<Element> componentsToAlign = new Stack<>(); componentsToAlign.addAll( expectedElements ); reverse( componentsToAlign ); return componentsToAlign; } private static TreeSet<Match> getBestMatches( final Element expected, final Map<Element, Element> actualElements ) { final TreeSet<Match> result = new TreeSet<>(); final Element identityResult = actualElements.get( expected ); if ( identityResult != null ) { // Try to first get the same element from actuals. This should be the standard case and thus cheapest. result.add( new Match( 1.0, identityResult ) ); } else { for ( final Element element : actualElements.keySet() ) { final double similarity = match( expected, element ); if ( similarity == 1.0d ) { result.add( new Match( similarity, element ) ); return result; } result.add( new Match( similarity, element ) ); } } return result; } private static double match( final Element expected, final Element bestMatch ) { return expected.getIdentifyingAttributes().match( bestMatch.getIdentifyingAttributes() ); } /** * Get the aligned actual element to an expected element. * * @param element * expected element * @return aligned actual element */ public Element get( final Element element ) { return alignment.get( element ); } @Override public String toString() { return alignment.toString(); } @Override public int hashCode() { return alignment.hashCode(); } @Override public boolean equals( final Object other ) { if ( other instanceof Alignment ) { return alignment.equals( ((Alignment) other).alignment ); } return false; } }
package edu.jhu.hlt.optimize; import java.util.Arrays; import org.apache.commons.math3.util.FastMath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.jhu.hlt.optimize.function.DifferentiableBatchFunction; import edu.jhu.hlt.util.Prm; import edu.jhu.prim.arrays.DoubleArrays; import edu.jhu.prim.arrays.IntArrays; import edu.jhu.prim.util.Lambda.FnIntDoubleToVoid; import edu.jhu.prim.vector.IntDoubleVector; /** * AdaGrad with a Composite Objective Mirror Descent update and L1 regularizer with lazy updates (Duchi et al., 2011). * * @author mgormley */ public class AdaGradComidL2 extends SGD implements Optimizer<DifferentiableBatchFunction> { /** Options for this optimizer. */ public static class AdaGradComidL2Prm extends SGDPrm { private static final long serialVersionUID = 1L; /** The scaling parameter for the learning rate. */ public double eta = 0.1; /** * The amount added (delta) to the sum of squares outside the square * root. This is to combat the issue of tiny gradients throwing the hole * optimization off early on. */ public double constantAddend = 1e-9; /** The weight on the l2 regularizer. */ public double l2Lambda = 0.0; /** Initial sum of squares value. */ public double initialSumSquares = 0; public AdaGradComidL2Prm() { // Schedule must be null. this.sched = null; } } private static final long serialVersionUID = 1L; private static final Logger log = LoggerFactory.getLogger(AdaGradComidL2.class); private final AdaGradComidL2Prm prm; // The iteration of the last step taken for each model parameter. private int[] iterOfLastStep; // Sum of squares of gradients up to current time for each parameter. private double[] gradSumSquares; /** * Constructs an SGD optimizer. */ public AdaGradComidL2(AdaGradComidL2Prm prm) { super(prm); if (!(prm.sched == null || prm.sched instanceof EmptyGainSchedule)) { log.warn("Schedule for AdaGrad should be set to null. Ignoring it."); } this.prm = prm; this.prm.sched = new EmptyGainSchedule(); } @Override public AdaGradComidL2 copy() { AdaGradComidL2 sgd = new AdaGradComidL2(Prm.clonePrm(this.prm)); sgd.iterOfLastStep = IntArrays.copyOf(this.iterOfLastStep); sgd.gradSumSquares = DoubleArrays.copyOf(this.gradSumSquares); return sgd; } /** * Initializes all the parameters for optimization. */ @Override protected void init(DifferentiableBatchFunction function, IntDoubleVector point) { super.init(function, point); this.iterOfLastStep = new int[function.getNumDimensions()]; Arrays.fill(iterOfLastStep, -1); this.gradSumSquares = new double[function.getNumDimensions()]; Arrays.fill(gradSumSquares, prm.initialSumSquares); } @Override protected void takeGradientStep(final IntDoubleVector point, final IntDoubleVector gradient, final boolean maximize, final int iterCount) { gradient.iterate(new FnIntDoubleToVoid() { @Override public void call(int i, double g_ti) { g_ti = maximize ? -g_ti : g_ti; assert !Double.isNaN(g_ti); // Get the old learning rate. double h_t0ii = prm.constantAddend + Math.sqrt(gradSumSquares[i]); // Update the sum of squares. gradSumSquares[i] += g_ti * g_ti; assert !Double.isNaN(gradSumSquares[i]); // Get the new learning rate. double h_tii = prm.constantAddend + Math.sqrt(gradSumSquares[i]); // Definitions int t0 = iterOfLastStep[i]; int t = iterCount-1; double x_t0i = point.get(i); // Lazy update. double x_ti = FastMath.pow(h_t0ii / (prm.eta * prm.l2Lambda + h_t0ii), t - t0) * x_t0i; // Main update. double x_t1i = (h_tii*x_ti - prm.eta*g_ti) / (prm.eta * prm.l2Lambda + h_tii); iterOfLastStep[i] = iterCount; assert !Double.isNaN(x_t1i); assert !Double.isInfinite(x_t1i); point.set(i, x_t1i); // Commented for speed. //log.debug(String.format("t=%d t0=%d i=%d g_ti=%.3g x_t0i=%.3g x_ti=%.3g x_t1i=%.3g", t, t0, i, g_ti, x_t0i, x_ti, x_t1i)); } }); } @Override protected double getEta0() { return prm.eta; } @Override protected void setEta0(double eta0) { prm.eta = eta0; } }
package edu.jhu.rebar.file; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.jhu.hlt.concrete.Concrete.Communication; import edu.jhu.hlt.concrete.ConcreteException; import edu.jhu.hlt.concrete.io.ProtocolBufferReader; import edu.jhu.hlt.concrete.io.ProtocolBufferWriter; import edu.jhu.hlt.concrete.util.ProtoFactory; import edu.jhu.rebar.Corpus; import edu.jhu.rebar.IndexedCommunication; import edu.jhu.rebar.ProtoIndex; import edu.jhu.rebar.ProtoIndex.ModificationTarget; import edu.jhu.rebar.RebarException; import edu.jhu.rebar.Stage; /** * @author max * */ public class FileBackedCorpus implements Corpus { private static final Logger logger = LoggerFactory .getLogger(FileBackedCorpus.class); private final Path pathOnDisk; private final Path stagesPath; private final Path commsPath; private final Connection conn; private final Set<String> commIdSet; public FileBackedCorpus(Path pathOnDisk, Set<String> commIdSet, Connection conn) throws RebarException { this.pathOnDisk = pathOnDisk; this.stagesPath = this.pathOnDisk.resolve("stages"); this.commsPath = this.pathOnDisk.resolve("communications"); this.conn = conn; this.commIdSet = commIdSet; } public FileBackedCorpus(Path pathOnDisk, Connection conn) throws RebarException { this.pathOnDisk = pathOnDisk; this.stagesPath = this.pathOnDisk.resolve("stages"); this.commsPath = this.pathOnDisk.resolve("communications"); this.conn = conn; this.commIdSet = this.queryCommIdSet(); } public Path getPath() { return this.pathOnDisk; } public Set<String> getCommIdSet() { return Collections.unmodifiableSet(this.commIdSet); } @Override public String getName() { return this.pathOnDisk.getFileName().toString(); } @Override public void close() throws RebarException { try { this.conn.close(); } catch (SQLException e) { throw new RebarException(e); } } @Override public Stage makeStage(String stageName, String stageVersion, Set<Stage> dependencies, String description, boolean deleteIfExists) throws RebarException { try { if (deleteIfExists) if (this.hasStage(stageName, stageVersion)) this.deleteStage(this.getStage(stageName, stageVersion)); // if we don't want to delete and the stage exists, throw an // exception. if (this.hasStage(stageName, stageVersion) && !deleteIfExists) throw new RebarException("Stage: " + stageName + " already exists!"); PreparedStatement ps = this.conn.prepareStatement( "INSERT INTO stages VALUES (?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); ps.setString(1, null); ps.setString(2, stageName); ps.setString(3, stageVersion); ps.setString(4, description); ps.execute(); ResultSet rs = ps.getGeneratedKeys(); int id; if (rs.next()) id = rs.getInt(1); else throw new SQLException( "Creating stage failed; didn't get an id back after insert."); if (dependencies.size() > 0) { PreparedStatement depStmt = this.conn .prepareStatement("INSERT INTO dependencies VALUES (?, ?)"); for (Stage dep : dependencies) { depStmt.setInt(1, id); depStmt.setInt(2, dep.getStageId()); depStmt.addBatch(); } depStmt.executeBatch(); } return new FileStage(stageName, stageVersion, id, this.pathOnDisk, dependencies, description, false); } catch (SQLException e) { throw new RebarException(e); } } @Override public void markStagePublic(Stage stage) throws RebarException { // TODO Auto-generated method stub } @Override public Stage getStage(String stageName, String stageVersion) throws RebarException { return this.queryStage(stageName, stageVersion); } @Override public Stage getStage(int stageId) throws RebarException { return this.queryStage(stageId); } @Override public Stage getStage(String stageString) throws RebarException { String[] splits = stageString.split(" "); return this.queryStage(splits[0], splits[1]); } @Override public SortedSet<Stage> getStages() throws RebarException { return this.getStagesInCorpus(); } @Override public boolean hasStage(String stageName, String stageVersion) throws RebarException { return this.queryStageExists(stageName, stageVersion); } @Override public void deleteStage(Stage stage) throws RebarException { // TODO Auto-generated method stub } @Override public Collection<String> readComIdSet(File filename) throws RebarException { // TODO Auto-generated method stub return null; } @Override public void registerComIdSet(String name, Collection<String> idSet) throws RebarException { // TODO Auto-generated method stub } @Override public Collection<String> lookupComIdSet(String name) throws RebarException { // TODO Auto-generated method stub return null; } @Override public Collection<String> getComIdSetNames() throws RebarException { // TODO Auto-generated method stub return null; } @Override public Initializer makeInitializer() throws RebarException { // TODO return null; // return new FileCorpusInitializer(this.pathOnDisk.resolve("raw"), // this.getConnection()); } public class FileCorpusReader implements Reader { private final Path commPath; private final Set<Stage> stagesToLoad; public FileCorpusReader(FileBackedCorpus corpus) { this(corpus, new TreeSet<Stage>()); } public FileCorpusReader(FileBackedCorpus corpus, Set<Stage> stagesToLoad) { this.commPath = FileBackedCorpus.this.commsPath; this.stagesToLoad = stagesToLoad; } @Override public IndexedCommunication loadCommunication(String comid) throws RebarException { Path pathToComm = this.commPath.resolve(comid + ".pb"); if (!Files.exists(pathToComm)) throw new RebarException("Comm: " + comid + " doesn't exist."); try { File commFile = pathToComm.toFile(); ProtocolBufferReader pbr = new ProtocolBufferReader( new FileInputStream(commFile), Communication.class); Communication comm = (Communication) pbr.next(); pbr.close(); IndexedCommunication ic = new IndexedCommunication(comm, new ProtoIndex(comm), null); return ic; } catch (ConcreteException | IOException e) { throw new RebarException(e); } } @Override public Iterator<IndexedCommunication> loadCommunications( Collection<String> subset) throws RebarException { if (!commIdSet.containsAll(subset)) throw new RebarException("One or more subset comms " + " were not in this corpus' communication ID set."); try { List<IndexedCommunication> commSet = new ArrayList<>(); DirectoryStream<Path> ds = Files .newDirectoryStream(this.commPath); Iterator<Path> pathIter = ds.iterator(); while (pathIter.hasNext()) { Path nextPath = pathIter.next(); String fileName = nextPath.getFileName().toString(); // remove ".pb" from filename String commId = fileName .substring(0, fileName.length() - 3); if (subset.contains(commId)) { Communication c = ProtoFactory .readCommunicationFromPath(nextPath); IndexedCommunication ic = new IndexedCommunication(c, new ProtoIndex(c), null); commSet.add(ic); } } ds.close(); return commSet.iterator(); } catch (IOException | ConcreteException e) { throw new RebarException(e); } } @Override public Iterator<IndexedCommunication> loadCommunications() throws RebarException { return loadCommunications(commIdSet); } @Override public void close() throws RebarException { // nothing to do here. } @Override public Collection<Stage> getInputStages() throws RebarException { return this.stagesToLoad; } @Override public Corpus getCorpus() { return FileBackedCorpus.this; } } @Override public Reader makeReader(Collection<Stage> stages) throws RebarException { Set<Stage> stageSet = new TreeSet<>(); stageSet.addAll(stages); return new FileCorpusReader(this, stageSet); } @Override public Reader makeReader(Stage[] stages) throws RebarException { Set<Stage> stageSet = new TreeSet<>(); List<Stage> stageList = Arrays.asList(stages); stageSet.addAll(stageList); return new FileCorpusReader(this, stageSet); } @Override public Reader makeReader(Stage stage) throws RebarException { if (!this.hasStage(stage.getStageName(), stage.getStageVersion())) throw new RebarException("Stage: " + stage.getStageName() + " doesn't exist."); Set<Stage> stageSet = new TreeSet<>(); stageSet.add(stage); return new FileCorpusReader(this, stageSet); } @Override public Reader makeReader() throws RebarException { return new FileCorpusReader(this); } @Override public Reader makeReader(Collection<Stage> stages, boolean loadStageOwnership) throws RebarException { return this.makeReader(stages); } @Override public Reader makeReader(Stage[] stages, boolean loadStageOwnership) throws RebarException { return this.makeReader(stages); } @Override public Reader makeReader(Stage stage, boolean loadStageOwnership) throws RebarException { return this.makeReader(stage); } @Override public Reader makeReader(boolean loadStageOwnership) throws RebarException { return this.makeReader(); } @Override public long getNumCommunications() throws RebarException { return this.commIdSet.size(); } public class FileCorpusWriter implements Writer { private Stage stage; private Path stagePath; private File stageOutputFile; private ProtocolBufferWriter pbw; public FileCorpusWriter (Stage stage, Path stagePath) throws RebarException { try { this.stage = stage; this.stagePath = stagePath; Path outputStagePath = this.stagePath .resolve(this.stage.getStageName()) .resolve(this.stage.getStageVersion()) .resolve("stage.pb"); this.stageOutputFile = outputStagePath.toFile(); this.pbw = new ProtocolBufferWriter( new BufferedOutputStream( new FileOutputStream(this.stageOutputFile, true))); } catch (FileNotFoundException e) { throw new RebarException(e); } } @Override public void saveCommunication(IndexedCommunication comm) throws RebarException { Map<ModificationTarget, byte[]> delta = comm.getIndex().getUnsavedModifications(); } @Override public void flush() throws RebarException { // TODO Auto-generated method stub } @Override public void close() throws RebarException { // TODO Auto-generated method stub } @Override public Stage getOutputStage() { return this.stage; } } @Override public Writer makeWriter(Stage stage) throws RebarException { return null; } @Override public DiffWriter makeDiffWriter(Stage stage) throws RebarException { // TODO Auto-generated method stub return null; } private int queryStageId(String stageName, String stageVersion) throws RebarException { PreparedStatement ps = null; try { ps = this.conn .prepareStatement("SELECT id FROM stages WHERE name = ? AND version = ?"); ps.setString(1, stageName); ps.setString(2, stageVersion); ResultSet rs = ps.executeQuery(); if (rs.next()) return rs.getInt(1); else throw new SQLException("Didn't get an id for stage: " + stageName + " and version: " + stageVersion); } catch (SQLException ioe) { throw new RebarException(ioe); } finally { if (ps != null) try { ps.close(); } catch (SQLException e) { logger.debug("Failed to close statement.", e); } } } private boolean queryStageExists(String stageName, String stageVersion) throws RebarException { PreparedStatement ps = null; try { ps = this.conn .prepareStatement("SELECT id FROM stages WHERE name = ? AND version = ?"); ps.setString(1, stageName); ps.setString(2, stageVersion); ResultSet rs = ps.executeQuery(); return rs.next(); } catch (SQLException ioe) { throw new RebarException(ioe); } finally { if (ps != null) try { ps.close(); } catch (SQLException e) { logger.debug("Failed to close statement.", e); } } } private FileStage queryStage(int stageId) throws RebarException { PreparedStatement ps = null; try { Set<Stage> dependencies = this.queryStageDependencies(stageId); ps = this.conn .prepareStatement("SELECT name, version, description FROM stages WHERE id = ?"); ps.setInt(1, stageId); ResultSet rs = ps.executeQuery(); if (rs.next()) { String name = rs.getString(1); String vers = rs.getString(2); String desc = rs.getString(3); return new FileStage(name, vers, stageId, this.pathOnDisk, dependencies, desc, true); } else throw new SQLException("Didn't find id: " + stageId); } catch (SQLException ioe) { throw new RebarException(ioe); } finally { if (ps != null) try { ps.close(); } catch (SQLException e) { logger.debug("Failed to close statement.", e); } } } private FileStage queryStage(String stageName, String stageVersion) throws RebarException { PreparedStatement ps = null; try { int stageId = this.queryStageId(stageName, stageVersion); Set<Stage> dependencies = this.queryStageDependencies(stageId); ps = this.conn .prepareStatement("SELECT description FROM stages WHERE id = ?"); ps.setInt(1, stageId); ResultSet rs = ps.executeQuery(); if (rs.next()) { String desc = rs.getString(1); return new FileStage(stageName, stageVersion, stageId, this.pathOnDisk, dependencies, desc, true); } else throw new SQLException("Didn't get an id for stage: " + stageName + " and version: " + stageVersion); } catch (SQLException ioe) { throw new RebarException(ioe); } finally { if (ps != null) try { ps.close(); } catch (SQLException e) { logger.debug("Failed to close statement.", e); } } } private List<Integer> queryDependencyIds(int stageId) throws RebarException { List<Integer> intList = new ArrayList<>(); PreparedStatement ps = null; try { ps = this.conn .prepareStatement("SELECT dependency_id FROM dependencies WHERE stage_id = ?"); ps.setInt(1, stageId); ResultSet rs = ps.executeQuery(); while (rs.next()) intList.add(rs.getInt(1)); rs.close(); return intList; } catch (SQLException ioe) { throw new RebarException(ioe); } finally { if (ps != null) try { ps.close(); } catch (SQLException e) { logger.debug("Failed to close statement.", e); } } } private SortedSet<Stage> getStagesInCorpus() throws RebarException { try { SortedSet<Stage> corpusStages = new TreeSet<>(); PreparedStatement ps = this.conn .prepareStatement("SELECT id, name, version, description FROM stages"); ResultSet rs = ps.executeQuery(); while (rs.next()) { int stageId = rs.getInt("id"); String stageName = rs.getString("name"); String stageVersion = rs.getString("version"); String stageDesc = rs.getString("description"); corpusStages.add(new FileStage(stageName, stageVersion, stageId, this.pathOnDisk, this .queryStageDependencies(stageId), stageDesc, true)); } return corpusStages; } catch (SQLException e) { throw new RebarException(e); } } private Set<Stage> queryStageDependencies(int stageId) throws RebarException { Set<Stage> stages = new TreeSet<>(); PreparedStatement ps = null; try { ps = this.conn.prepareStatement("SELECT dependency_id " + "FROM dependencies WHERE stage_id = ?"); ps.setInt(1, stageId); ResultSet rs = ps.executeQuery(); while (rs.next()) { int depId = rs.getInt(1); // recurse to find dependencies until we've satisfied them. Set<Stage> deps = this.queryStageDependencies(depId); String depName = rs.getString(2); String depVersion = rs.getString(3); String description = rs.getString(4); stages.add(new FileStage(depName, depVersion, depId, this.pathOnDisk, deps, description, true)); } return stages; } catch (SQLException ioe) { throw new RebarException(ioe); } finally { if (ps != null) try { ps.close(); } catch (SQLException e) { logger.debug("Failed to close statement.", e); } } } private Set<String> queryCommunicationIds() throws RebarException { Set<String> stages = new TreeSet<>(); PreparedStatement ps = null; try { ps = this.conn.prepareStatement("SELECT guid " + "FROM comm_ids"); ResultSet rs = ps.executeQuery(); while (rs.next()) { stages.add(rs.getString(1)); } return stages; } catch (SQLException ioe) { throw new RebarException(ioe); } finally { if (ps != null) try { ps.close(); } catch (SQLException e) { logger.debug("Failed to close statement.", e); } } } private Set<String> queryCommIdSet() throws RebarException { try { Set<String> commIdSet = new TreeSet<>(); PreparedStatement ps = this.conn .prepareStatement("SELECT guid FROM comm_ids"); ResultSet rs = ps.executeQuery(); while (rs.next()) { commIdSet.add(rs.getString(1)); } ps.close(); return commIdSet; } catch (SQLException e) { throw new RebarException(e); } } }
package edu.neu.ccs.pyramid.experiment; import edu.neu.ccs.pyramid.active_learning.BestVsSecond; import edu.neu.ccs.pyramid.classification.boosting.lktb.LKTBConfig; import edu.neu.ccs.pyramid.classification.boosting.lktb.LKTreeBoost; import edu.neu.ccs.pyramid.configuration.Config; import edu.neu.ccs.pyramid.dataset.*; import edu.neu.ccs.pyramid.elasticsearch.SingleLabelIndex; import edu.neu.ccs.pyramid.dataset.IdTranslator; import edu.neu.ccs.pyramid.eval.Accuracy; import edu.neu.ccs.pyramid.feature.*; import edu.neu.ccs.pyramid.feature_extraction.*; import edu.neu.ccs.pyramid.util.Pair; import edu.neu.ccs.pyramid.util.Sampling; import org.apache.commons.lang3.time.StopWatch; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.index.query.MatchQueryBuilder; import org.elasticsearch.search.SearchHit; import java.io.*; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Exp3 { public static void main(String[] args) throws Exception{ if (args.length !=1){ throw new IllegalArgumentException("please specify the config file"); } Config config = new Config(args[0]); System.out.println(config); SingleLabelIndex index = loadIndex(config); train(config,index); index.close(); } static void train(Config config, SingleLabelIndex index) throws Exception{ int numDocsInIndex = index.getNumDocs(); String[] trainIndexIds = sampleTrain(config,index); System.out.println("number of training documents = "+trainIndexIds.length); IdTranslator trainIdTranslator = loadIdTranslator(trainIndexIds); FeatureMappers featureMappers = new FeatureMappers(); LabelTranslator labelTranslator = loadLabelTranslator(config, index); if (config.getBoolean("useInitialFeatures")){ addInitialFeatures(config,index,featureMappers,trainIndexIds); } ClfDataSet trainDataSet = loadTrainData(config,index,featureMappers, trainIdTranslator, labelTranslator); System.out.println("in training set :"); showDistribution(config,trainDataSet,labelTranslator); trainModel(config,trainDataSet,featureMappers,index, trainIdTranslator); //only keep used columns ClfDataSet trimmedTrainDataSet = DataSetUtil.trim(trainDataSet,featureMappers.getTotalDim()); DataSetUtil.setFeatureMappers(trimmedTrainDataSet,featureMappers); saveDataSet(config, trimmedTrainDataSet, config.getString("archive.trainingSet")); if (config.getBoolean("archive.dumpFields")){ dumpTrainFeatures(config,index,trainIdTranslator); } String[] testIndexIds = sampleTest(numDocsInIndex,trainIndexIds); IdTranslator testIdTranslator = loadIdTranslator(testIndexIds); ClfDataSet testDataSet = loadTestData(config,index,featureMappers,testIdTranslator,labelTranslator); DataSetUtil.setFeatureMappers(testDataSet,featureMappers); File serializedModel = new File(config.getString("archive.folder"),config.getString("archive.model")); LKTreeBoost lkTreeBoost = LKTreeBoost.deserialize(serializedModel); System.out.println("accuracy on test set = "+Accuracy.accuracy(lkTreeBoost,testDataSet)); saveDataSet(config, testDataSet, config.getString("archive.testSet")); if (config.getBoolean("archive.dumpFields")){ dumpTestFeatures(config,index,testIdTranslator); } } static SingleLabelIndex loadIndex(Config config) throws Exception{ System.out.println("connecting to index ..."); SingleLabelIndex.Builder builder = new SingleLabelIndex.Builder() .setIndexName(config.getString("index.indexName")) .setClusterName(config.getString("index.clusterName")) .setClientType(config.getString("index.clientType")) .setLabelField(config.getString("index.labelField")) .setExtLabelField(config.getString("index.extLabelField")) .setDocumentType(config.getString("index.documentType")); if (config.getString("index.clientType").equals("transport")){ String[] hosts = config.getString("index.hosts").split(Pattern.quote(",")); String[] ports = config.getString("index.ports").split(Pattern.quote(",")); builder.addHostsAndPorts(hosts,ports); } SingleLabelIndex index = builder.build(); System.out.println("connected to index "+index.getIndexName()); System.out.println("there are "+index.getNumDocs()+" documents in the index."); // for (int i=0;i<index.getNumDocs();i++){ // System.out.println(i); // System.out.println(index.getLabel(""+i)); return index; } /** * * @param config * @param index * @param featureMappers * @param idTranslator separate for training and test * @param totalDim * @return * @throws Exception */ static ClfDataSet loadData(Config config, SingleLabelIndex index, FeatureMappers featureMappers, IdTranslator idTranslator, int totalDim, LabelTranslator labelTranslator) throws Exception{ int numDataPoints = idTranslator.numData(); int numClasses = config.getInt("numClasses"); ClfDataSet dataSet = ClfDataSetBuilder.getBuilder() .numDataPoints(numDataPoints).numFeatures(totalDim) .numClasses(numClasses).dense(!config.getBoolean("featureMatrix.sparse")) .missingValue(config.getBoolean("featureMatrix.missingValue")) .build(); for(int i=0;i<numDataPoints;i++){ String dataIndexId = idTranslator.toExtId(i); int label = index.getLabel(dataIndexId); dataSet.setLabel(i,label); } String[] dataIndexIds = idTranslator.getAllExtIds(); featureMappers.getCategoricalFeatureMappers().stream().parallel(). forEach(categoricalFeatureMapper -> { String featureName = categoricalFeatureMapper.getFeatureName(); String source = categoricalFeatureMapper.getSource(); if (source.equalsIgnoreCase("field")){ for (String id: dataIndexIds){ int algorithmId = idTranslator.toIntId(id); String category = index.getStringField(id,featureName); // might be a new category unseen in training if (categoricalFeatureMapper.hasCategory(category)){ int featureIndex = categoricalFeatureMapper.getFeatureIndex(category); dataSet.setFeatureValue(algorithmId,featureIndex,1); } } } }); featureMappers.getNumericalFeatureMappers().stream().parallel(). forEach(numericalFeatureMapper -> { String featureName = numericalFeatureMapper.getFeatureName(); String source = numericalFeatureMapper.getSource(); int featureIndex = numericalFeatureMapper.getFeatureIndex(); if (source.equalsIgnoreCase("field")){ for (String id: dataIndexIds){ int algorithmId = idTranslator.toIntId(id); float value = index.getFloatField(id,featureName); dataSet.setFeatureValue(algorithmId,featureIndex,value); } } if (source.equalsIgnoreCase("matching_score")){ SearchResponse response = null; //todo assume unigram, so slop doesn't matter response = index.matchPhrase(index.getBodyField(), featureName, dataIndexIds, 0); SearchHit[] hits = response.getHits().getHits(); for (SearchHit hit: hits){ String indexId = hit.getId(); float score = hit.getScore(); int algorithmId = idTranslator.toIntId(indexId); dataSet.setFeatureValue(algorithmId,featureIndex,score); } } }); DataSetUtil.setIdTranslator(dataSet,idTranslator); DataSetUtil.setLabelTranslator(dataSet, labelTranslator); return dataSet; } static ClfDataSet loadTrainData(Config config, SingleLabelIndex index, FeatureMappers featureMappers, IdTranslator idTranslator, LabelTranslator labelTranslator) throws Exception{ System.out.println("creating training set"); //todo fix int totalDim = config.getInt("maxNumColumns"); System.out.println("allocating "+totalDim+" columns for training set"); ClfDataSet dataSet = loadData(config,index,featureMappers,idTranslator,totalDim,labelTranslator); System.out.println("training set created"); return dataSet; } static ClfDataSet loadTestData(Config config, SingleLabelIndex index, FeatureMappers featureMappers, IdTranslator idTranslator, LabelTranslator labelTranslator) throws Exception{ System.out.println("creating test set"); int totalDim = featureMappers.getTotalDim(); ClfDataSet dataSet = loadData(config,index,featureMappers,idTranslator,totalDim,labelTranslator); System.out.println("test set created"); return dataSet; } static void trainModel(Config config, ClfDataSet dataSet, FeatureMappers featureMappers, SingleLabelIndex index, IdTranslator trainIdTranslator) throws Exception{ String archive = config.getString("archive.folder"); int numIterations = config.getInt("train.numIterations"); int numClasses = config.getInt("numClasses"); int numLeaves = config.getInt("train.numLeaves"); double learningRate = config.getDouble("train.learningRate"); int trainMinDataPerLeaf = config.getInt("train.minDataPerLeaf"); String modelName = config.getString("archive.model"); int numDocsToSelect = config.getInt("extraction.numDocsToSelect"); int numUnigramsToExtract = config.getInt("extraction.numUnigramsToExtract"); double extractionFrequency = config.getDouble("extraction.frequency"); if (extractionFrequency>1 || extractionFrequency<0){ throw new IllegalArgumentException("0<=extraction.frequency<=1"); } LabelTranslator labelTranslator = dataSet.getSetting().getLabelTranslator(); StopWatch stopWatch = new StopWatch(); stopWatch.start(); System.out.println("training model "); LKTBConfig trainConfig = new LKTBConfig.Builder(dataSet) .learningRate(learningRate).minDataPerLeaf(trainMinDataPerLeaf) .numLeaves(numLeaves) .build(); LKTreeBoost lkTreeBoost = new LKTreeBoost(numClasses); lkTreeBoost.setPriorProbs(dataSet); lkTreeBoost.setTrainConfig(trainConfig); // TermSplitExtractor splitExtractor = new TermSplitExtractor(index, trainIdTranslator, // numUnigramsToExtract) // .setMinDataPerLeaf(config.getInt("extraction.splitExtractor.minDataPerLeaf")); // TermTfidfExtractor tfidfExtractor = new TermTfidfExtractor(index,trainIdTranslator, // numUnigramsToExtract). // setMinDf(config.getInt("extraction.tfidfExtractor.minDf")); TermTfidfSplitExtractor termExtractor = new TermTfidfSplitExtractor(index, trainIdTranslator,numUnigramsToExtract). setMinDf(config.getInt("extraction.termExtractor.minDf")). setNumSurvivors(config.getInt("extraction.termExtractor.numSurvivors")). setMinDataPerLeaf(config.getInt("extraction.termExtractor.minDataPerLeaf")); PhraseSplitExtractor phraseExtractor = new PhraseSplitExtractor(index,trainIdTranslator) .setMinDataPerLeaf(config.getInt("extraction.phraseExtractor.minDataPerLeaf")) .setMinDf(config.getInt("extraction.phraseExtractor.minDf")) .setTopN(config.getInt("extraction.phraseExtractor.topN")); DFStats dfStats = loadDFStats(config,index,trainIdTranslator); List<Set<String>> seedsForAllClasses = new ArrayList<>(); for (int i=0;i<numClasses;i++){ //todo parameters Set<String> set = new HashSet<>(); set.addAll(dfStats.getSortedTerms(i,config.getInt("seeds.initial.minDf"),config.getInt("seeds.initial.size"))); seedsForAllClasses.add(set); } //todo fix options List<DFStat> initialSeeds = loadInitialSeeds(config,index,trainIdTranslator); for (DFStat dfStat: initialSeeds){ String term = dfStat.getPhrase(); int label = dfStat.getBestMatchedClass(); seedsForAllClasses.get(label).add(term); } Set<String> blackList = new HashSet<>(); //start the matrix with the seeds //may have duplicates, but should not be a big deal for(Set<String> seeds: seedsForAllClasses){ for (String term: seeds){ int featureIndex = featureMappers.nextAvailable(); SearchResponse response = index.match(index.getBodyField(), term,trainIdTranslator.getAllExtIds(), MatchQueryBuilder.Operator.AND); for (SearchHit hit: response.getHits().getHits()){ String indexId = hit.getId(); int algorithmId = trainIdTranslator.toIntId(indexId); float score = hit.getScore(); dataSet.setFeatureValue(algorithmId, featureIndex,score); } NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder(). setFeatureIndex(featureIndex).setFeatureName(term). setSource("matching_score").build(); featureMappers.addMapper(mapper); blackList.add(term); } } // //todo // List<Integer> validationSet = new ArrayList<>(); // for (int i=0;i<trainIndex.getNumDocs();i++){ // validationSet.add(i); for (int iteration=0;iteration<numIterations;iteration++){ System.out.println("iteration "+iteration); lkTreeBoost.calGradients(); boolean condition1 = (featureMappers.getTotalDim() +numUnigramsToExtract*numClasses*3 +config.getInt("extraction.phraseExtractor.topN")*numClasses*3 <dataSet.getNumFeatures()); boolean condition2 = (Math.random()<extractionFrequency); //should start with some feature boolean condition3 = (iteration==0); boolean shouldExtractFeatures = condition1&&condition2||condition3; if (!shouldExtractFeatures){ if (!condition1){ System.out.println("we have reached the max number of columns " + "and will not extract new features"); } if (!condition2){ System.out.println("no feature extraction is scheduled for this round"); } } /** * from easy set */ if (shouldExtractFeatures&&config.getBoolean("extraction.fromEasySet")){ //generate easy set FocusSet focusSet = new FocusSet(numClasses); for (int k=0;k<numClasses;k++){ double[] gradient = lkTreeBoost.getGradient(k); Comparator<Pair<Integer,Double>> comparator = Comparator.comparing(Pair::getSecond); List<Integer> easyExamples = IntStream.range(0,gradient.length) .mapToObj(i -> new Pair<>(i,gradient[i])) .filter(pair -> pair.getSecond()>0) .sorted(comparator) .limit(numDocsToSelect) .map(Pair::getFirst) .collect(Collectors.toList()); for(Integer doc: easyExamples){ focusSet.add(doc,k); } } List<Integer> validationSet = focusSet.getAll(); for (int k=0;k<numClasses;k++){ double[] allGradients = lkTreeBoost.getGradient(k); List<Double> gradientsForValidation = validationSet.stream() .map(i -> allGradients[i]).collect(Collectors.toList()); List<String> goodTerms = null; goodTerms = termExtractor.getGoodTerms(focusSet, validationSet, blackList, k, gradientsForValidation); // if(config.getString("extraction.Extractor").equalsIgnoreCase("splitExtractor")){ // goodTerms = splitExtractor.getGoodTerms(focusSet, // validationSet, // blackList, k, gradientsForValidation); // } else if (config.getString("extraction.Extractor").equalsIgnoreCase("tfidfExtractor")){ // goodTerms = tfidfExtractor.getGoodTerms(focusSet,blackList,k); // } else if (config.getString("extraction.Extractor").equalsIgnoreCase("termExtractor")){ // goodTerms = termExtractor.getGoodTerms(focusSet, // validationSet, // blackList, k, gradientsForValidation); // } else { // throw new RuntimeException("ngram extractor is not specified correctly"); seedsForAllClasses.get(k).addAll(goodTerms); List<String> focusSetIndexIds = focusSet.getDataClassK(k) .parallelStream().map(trainIdTranslator::toExtId) .collect(Collectors.toList()); System.out.println("easy set for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):"); System.out.println(focusSetIndexIds.toString()); System.out.println("terms extracted from easy set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):"); System.out.println(goodTerms); //phrases System.out.println("seeds for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):"); System.out.println(seedsForAllClasses.get(k)); List<String> goodPhrases = phraseExtractor.getGoodPhrases(focusSet,validationSet,blackList,k, gradientsForValidation,seedsForAllClasses.get(k)); System.out.println("phrases extracted from easy set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):"); System.out.println(goodPhrases); blackList.addAll(goodPhrases); for (String ngram:goodTerms){ int featureIndex = featureMappers.nextAvailable(); SearchResponse response = index.match(index.getBodyField(), ngram,trainIdTranslator.getAllExtIds(), MatchQueryBuilder.Operator.AND); for (SearchHit hit: response.getHits().getHits()){ String indexId = hit.getId(); int algorithmId = trainIdTranslator.toIntId(indexId); float score = hit.getScore(); dataSet.setFeatureValue(algorithmId, featureIndex,score); } NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder(). setFeatureIndex(featureIndex).setFeatureName(ngram). setSource("matching_score").build(); featureMappers.addMapper(mapper); blackList.add(ngram); } for (String phrase:goodPhrases){ int featureIndex = featureMappers.nextAvailable(); SearchResponse response = index.matchPhrase(index.getBodyField(), phrase,trainIdTranslator.getAllExtIds(), 0); for (SearchHit hit: response.getHits().getHits()){ String indexId = hit.getId(); int algorithmId = trainIdTranslator.toIntId(indexId); float score = hit.getScore(); dataSet.setFeatureValue(algorithmId, featureIndex,score); } NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder(). setFeatureIndex(featureIndex).setFeatureName(phrase). setSource("matching_score").build(); featureMappers.addMapper(mapper); } } } /** * hard set */ if (shouldExtractFeatures&&config.getBoolean("extraction.fromHardSet")){ //generate focus set FocusSet focusSet = new FocusSet(numClasses); for (int k=0;k<numClasses;k++){ double[] gradient = lkTreeBoost.getGradient(k); Comparator<Pair<Integer,Double>> comparator = Comparator.comparing(Pair::getSecond); List<Integer> hardExamples = IntStream.range(0,gradient.length) .mapToObj(i -> new Pair<>(i,gradient[i])) .filter(pair -> pair.getSecond()>0) .sorted(comparator.reversed()) .limit(numDocsToSelect) .map(Pair::getFirst) .collect(Collectors.toList()); for(Integer doc: hardExamples){ focusSet.add(doc,k); } } List<Integer> validationSet = focusSet.getAll(); for (int k=0;k<numClasses;k++){ double[] allGradients = lkTreeBoost.getGradient(k); List<Double> gradientsForValidation = validationSet.stream() .map(i -> allGradients[i]).collect(Collectors.toList()); List<String> goodTerms = null; goodTerms = termExtractor.getGoodTerms(focusSet, validationSet, blackList, k, gradientsForValidation); // if(config.getString("extraction.Extractor").equalsIgnoreCase("splitExtractor")){ // goodTerms = splitExtractor.getGoodTerms(focusSet, // validationSet, // blackList, k, gradientsForValidation); // } else if (config.getString("extraction.Extractor").equalsIgnoreCase("tfidfExtractor")){ // goodTerms = tfidfExtractor.getGoodTerms(focusSet,blackList,k); // } else if (config.getString("extraction.Extractor").equalsIgnoreCase("termExtractor")){ // goodTerms = termExtractor.getGoodTerms(focusSet, // validationSet, // blackList, k, gradientsForValidation); // } else { // throw new RuntimeException("ngram extractor is not specified correctly"); seedsForAllClasses.get(k).addAll(goodTerms); List<String> focusSetIndexIds = focusSet.getDataClassK(k) .parallelStream().map(trainIdTranslator::toExtId) .collect(Collectors.toList()); System.out.println("hard set for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):"); System.out.println(focusSetIndexIds.toString()); System.out.println("terms extracted from hard set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):"); System.out.println(goodTerms); //phrases System.out.println("seeds for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):"); System.out.println(seedsForAllClasses.get(k)); List<String> goodPhrases = phraseExtractor.getGoodPhrases(focusSet,validationSet,blackList,k, gradientsForValidation,seedsForAllClasses.get(k)); System.out.println("phrases extracted from hard set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):"); System.out.println(goodPhrases); blackList.addAll(goodPhrases); for (String ngram:goodTerms){ int featureIndex = featureMappers.nextAvailable(); SearchResponse response = index.match(index.getBodyField(), ngram,trainIdTranslator.getAllExtIds(), MatchQueryBuilder.Operator.AND); for (SearchHit hit: response.getHits().getHits()){ String indexId = hit.getId(); int algorithmId = trainIdTranslator.toIntId(indexId); float score = hit.getScore(); dataSet.setFeatureValue(algorithmId, featureIndex,score); } NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder(). setFeatureIndex(featureIndex).setFeatureName(ngram). setSource("matching_score").build(); featureMappers.addMapper(mapper); blackList.add(ngram); } for (String phrase:goodPhrases){ int featureIndex = featureMappers.nextAvailable(); SearchResponse response = index.matchPhrase(index.getBodyField(), phrase,trainIdTranslator.getAllExtIds(), 0); for (SearchHit hit: response.getHits().getHits()){ String indexId = hit.getId(); int algorithmId = trainIdTranslator.toIntId(indexId); float score = hit.getScore(); dataSet.setFeatureValue(algorithmId, featureIndex,score); } NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder(). setFeatureIndex(featureIndex).setFeatureName(phrase). setSource("matching_score").build(); featureMappers.addMapper(mapper); } } } /** * uncertain set */ if (shouldExtractFeatures&&config.getBoolean("extraction.fromUncertainSet")){ //generate focus set FocusSet focusSet = new FocusSet(numClasses); Comparator<Pair<Integer,BestVsSecond>> comparator = Comparator.comparing(pair -> pair.getSecond().getDifference()); List<Integer> examples = IntStream.range(0,dataSet.getNumDataPoints()) .mapToObj(i -> new Pair<>(i,new BestVsSecond(lkTreeBoost.getClassProbs(i)))) .filter(pair -> (dataSet.getLabels()[pair.getFirst()]==pair.getSecond().getBestClass()) ||(dataSet.getLabels()[pair.getFirst()]==pair.getSecond().getSecondClass())) .sorted(comparator).map(Pair::getFirst) .limit(numClasses*numDocsToSelect).collect(Collectors.toList()); for (Integer dataPoint: examples){ int label = dataSet.getLabels()[dataPoint]; focusSet.add(dataPoint,label); } List<Integer> validationSet = focusSet.getAll(); for (int k=0;k<numClasses;k++){ double[] allGradients = lkTreeBoost.getGradient(k); List<Double> gradientsForValidation = validationSet.stream() .map(i -> allGradients[i]).collect(Collectors.toList()); List<String> goodTerms = null; goodTerms = termExtractor.getGoodTerms(focusSet, validationSet, blackList, k, gradientsForValidation); // if(config.getString("extraction.Extractor").equalsIgnoreCase("splitExtractor")){ // goodTerms = splitExtractor.getGoodTerms(focusSet, // validationSet, // blackList, k, gradientsForValidation); // } else if (config.getString("extraction.Extractor").equalsIgnoreCase("tfidfExtractor")){ // goodTerms = tfidfExtractor.getGoodTerms(focusSet,blackList,k); // } else if (config.getString("extraction.Extractor").equalsIgnoreCase("termExtractor")){ // goodTerms = termExtractor.getGoodTerms(focusSet, // validationSet, // blackList, k, gradientsForValidation); // } else { // throw new RuntimeException("ngram extractor is not specified correctly"); seedsForAllClasses.get(k).addAll(goodTerms); List<String> focusSetIndexIds = focusSet.getDataClassK(k) .parallelStream().map(trainIdTranslator::toExtId) .collect(Collectors.toList()); System.out.println("uncertain set for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):"); System.out.println(focusSetIndexIds.toString()); System.out.println("terms extracted from uncertain set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):"); System.out.println(goodTerms); //phrases System.out.println("seeds for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):"); System.out.println(seedsForAllClasses.get(k)); List<String> goodPhrases = phraseExtractor.getGoodPhrases(focusSet,validationSet,blackList,k, gradientsForValidation,seedsForAllClasses.get(k)); System.out.println("phrases extracted from uncertain set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):"); System.out.println(goodPhrases); blackList.addAll(goodPhrases); for (String ngram:goodTerms){ int featureIndex = featureMappers.nextAvailable(); SearchResponse response = index.match(index.getBodyField(), ngram,trainIdTranslator.getAllExtIds(), MatchQueryBuilder.Operator.AND); for (SearchHit hit: response.getHits().getHits()){ String indexId = hit.getId(); int algorithmId = trainIdTranslator.toIntId(indexId); float score = hit.getScore(); dataSet.setFeatureValue(algorithmId, featureIndex,score); } NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder(). setFeatureIndex(featureIndex).setFeatureName(ngram). setSource("matching_score").build(); featureMappers.addMapper(mapper); blackList.add(ngram); } for (String phrase:goodPhrases){ int featureIndex = featureMappers.nextAvailable(); SearchResponse response = index.matchPhrase(index.getBodyField(), phrase,trainIdTranslator.getAllExtIds(), 0); for (SearchHit hit: response.getHits().getHits()){ String indexId = hit.getId(); int algorithmId = trainIdTranslator.toIntId(indexId); float score = hit.getScore(); dataSet.setFeatureValue(algorithmId, featureIndex,score); } NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder(). setFeatureIndex(featureIndex).setFeatureName(phrase). setSource("matching_score").build(); featureMappers.addMapper(mapper); } } } int[] activeFeatures = IntStream.range(0, featureMappers.getTotalDim()).toArray(); lkTreeBoost.setActiveFeatures(activeFeatures); lkTreeBoost.fitRegressors(); } File serializedModel = new File(archive,modelName); lkTreeBoost.serialize(serializedModel); System.out.println("model saved to "+serializedModel.getAbsolutePath()); System.out.println("accuracy on training set = "+ Accuracy.accuracy(lkTreeBoost, dataSet)); System.out.println("time spent = "+stopWatch); } static String[] sampleTrain(Config config, SingleLabelIndex index){ System.out.println("deciding which documents should go into the training set ..."); int numDocsInIndex = index.getNumDocs(); String[] trainIds = null; if (config.getString("split.fashion").equalsIgnoreCase("fixed")){ String splitField = config.getString("index.splitField"); trainIds = IntStream.range(0, numDocsInIndex).parallel() .filter(i -> index.getStringField("" + i, splitField). equalsIgnoreCase("train")). mapToObj(i -> "" + i).collect(Collectors.toList()). toArray(new String[0]); } else if (config.getString("split.fashion").equalsIgnoreCase("random")){ double trainPercentage = config.getDouble("split.random.trainPercentage"); int[] labels = new int[numDocsInIndex]; for (int i=0;i<labels.length;i++){ labels[i] = index.getLabel(""+i); } List<Integer> sample = Sampling.stratified(labels, trainPercentage); trainIds = new String[sample.size()]; for (int i=0;i<trainIds.length;i++){ trainIds[i] = ""+sample.get(i); } } else { throw new RuntimeException("illegal split fashion"); } System.out.println("done"); return trainIds; } static String[] sampleTest(int numDocsInIndex, String[] trainIndexIds){ Set<String> test = new HashSet<>(numDocsInIndex); for (int i=0;i<numDocsInIndex;i++){ test.add(""+i); } List<String> _trainIndexIds = new ArrayList<>(trainIndexIds.length); for (String id: trainIndexIds){ _trainIndexIds.add(id); } test.removeAll(_trainIndexIds); return test.toArray(new String[0]); } static IdTranslator loadIdTranslator(String[] indexIds) throws Exception{ IdTranslator idTranslator = new IdTranslator(); for (int i=0;i<indexIds.length;i++){ idTranslator.addData(i,""+indexIds[i]); } return idTranslator; } // todo: can be optimized static LabelTranslator loadLabelTranslator(Config config, SingleLabelIndex index) throws Exception{ System.out.println("loading label translator ..."); int numClasses = config.getInt("numClasses"); int numDocs = index.getNumDocs(); Map<Integer, String> map = new HashMap<>(numClasses); List<Pair<Integer,String>> pairList = IntStream.range(0,numDocs).parallel() .mapToObj(i -> new Pair<>(index.getLabel(""+i),index.getExtLabel("" + i))) .collect(Collectors.toList()); for (Pair<Integer,String> pair: pairList){ map.put(pair.getFirst(),pair.getSecond()); } System.out.println("loaded"); return new LabelTranslator(map); } private static boolean matchPrefixes(String name, Set<String> prefixes){ for (String prefix: prefixes){ if (name.startsWith(prefix)){ return true; } } return false; } /** * * @param config * @param index * @param featureMappers to be updated * @param ids pull features from train ids * @throws Exception */ static void addInitialFeatures(Config config, SingleLabelIndex index, FeatureMappers featureMappers, String[] ids) throws Exception{ String featureFieldPrefix = config.getString("index.featureFieldPrefix"); Set<String> prefixes = Arrays.stream(featureFieldPrefix.split(",")).map(String::trim).collect(Collectors.toSet()); Set<String> allFields = index.listAllFields(); List<String> featureFields = allFields.stream(). filter(field -> matchPrefixes(field,prefixes)). collect(Collectors.toList()); System.out.println("all possible initial features:"+featureFields); for (String field: featureFields){ String featureType = index.getFieldType(field); if (featureType.equalsIgnoreCase("string")){ CategoricalFeatureMapperBuilder builder = new CategoricalFeatureMapperBuilder(); builder.setFeatureName(field); builder.setStart(featureMappers.nextAvailable()); builder.setSource("field"); for (String id: ids){ String category = index.getStringField(id, field); builder.addCategory(category); } boolean toAdd = true; CategoricalFeatureMapper mapper = builder.build(); if (config.getBoolean("categFeature.filter")){ double threshold = config.getDouble("categFeature.percentThreshold"); int numCategories = mapper.getNumCategories(); if (numCategories> ids.length*threshold){ toAdd=false; System.out.println("field "+field+" has too many categories " +"("+numCategories+"), omitted."); } } if(toAdd){ featureMappers.addMapper(mapper); } } else { NumericalFeatureMapperBuilder builder = new NumericalFeatureMapperBuilder(); builder.setFeatureName(field); builder.setFeatureIndex(featureMappers.nextAvailable()); builder.setSource("field"); NumericalFeatureMapper mapper = builder.build(); featureMappers.addMapper(mapper); } } } static void showDistribution(Config config, ClfDataSet dataSet, LabelTranslator labelTranslator){ int numClasses = config.getInt("numClasses"); int[] counts = new int[numClasses]; int[] labels = dataSet.getLabels(); for (int i=0;i<dataSet.getNumDataPoints();i++){ int label = labels[i]; counts[label] += 1; } System.out.println("label distribution:"); for (int i=0;i<numClasses;i++){ System.out.print(i+"("+labelTranslator.toExtLabel(i)+"):"+counts[i]+", "); } System.out.println(""); } static void saveDataSet(Config config, ClfDataSet dataSet, String name) throws Exception{ String archive = config.getString("archive.folder"); File dataFile = new File(archive,name); TRECFormat.save(dataSet, dataFile); DataSetUtil.dumpDataPointSettings(dataSet, new File(dataFile, "data_settings.txt")); DataSetUtil.dumpFeatureSettings(dataSet,new File(dataFile,"feature_settings.txt")); System.out.println("data set saved to "+dataFile.getAbsolutePath()); } static DFStats loadDFStats(Config config, SingleLabelIndex index, IdTranslator trainIdTranslator) throws IOException { System.out.println("loading initial unigram seeds"); DFStats dfStats = new DFStats(config.getInt("numClasses")); String[] trainIds = trainIdTranslator.getAllExtIds(); dfStats.update(index,trainIds); dfStats.sort(); System.out.println("loaded"); return dfStats; } static List<DFStat> loadInitialSeeds(Config config, SingleLabelIndex index, IdTranslator trainIdTranslator) throws Exception{ File seedsFile = new File(config.getString("seeds.file")); List<String> seeds = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(seedsFile))){ String line = null; while ((line=br.readLine())!=null){ seeds.add(line); } } return seeds.stream().parallel() .map(seed -> new DFStat(config.getInt("numClasses"),seed,index, trainIdTranslator.getAllExtIds())) .collect(Collectors.toList()); } static void dumpTrainFeatures(Config config, SingleLabelIndex index, IdTranslator idTranslator) throws Exception{ String archive = config.getString("archive.folder"); String trecFile = new File(archive,config.getString("archive.trainingSet")).getAbsolutePath(); String file = new File(trecFile,"dumped_fields.txt").getAbsolutePath(); dumpFeatures(config,index,idTranslator,file); } static void dumpTestFeatures(Config config, SingleLabelIndex index, IdTranslator idTranslator) throws Exception{ String archive = config.getString("archive.folder"); String trecFile = new File(archive,config.getString("archive.testSet")).getAbsolutePath(); String file = new File(trecFile,"dumped_fields.txt").getAbsolutePath(); dumpFeatures(config,index,idTranslator,file); } static void dumpFeatures(Config config, SingleLabelIndex index, IdTranslator idTranslator, String fileName) throws Exception{ String[] fields = config.getString("archive.dumpedFields").split(","); int numDocs = idTranslator.numData(); try(BufferedWriter bw = new BufferedWriter(new FileWriter(fileName)) ){ for (int intId=0;intId<numDocs;intId++){ bw.write("intId="); bw.write(""+intId); bw.write(","); bw.write("extId="); String extId = idTranslator.toExtId(intId); bw.write(extId); bw.write(","); for (int i=0;i<fields.length;i++){ String field = fields[i]; bw.write(field+"="); bw.write(index.getStringField(extId,field)); if (i!=fields.length-1){ bw.write(","); } } bw.write("\n"); } } } }
package edu.uiowa.icts.util; /** * @author rrlorent * @since August 1, 2014 */ public class DataTableHeader { private String data = null; private String name = null; private Boolean searchable = false; private Boolean orderable = false; private String searchValue = null; private Boolean searchRegex = false; public String getData() { return data; } public void setData( String data ) { this.data = data; } /** * @deprecated use setData( String data ) instead */ @Deprecated public void setData( Integer data ) { this.data = "" + data; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public Boolean getSearchable() { return searchable; } public void setSearchable( Boolean searchable ) { this.searchable = searchable; } public Boolean getOrderable() { return orderable; } public void setOrderable( Boolean orderable ) { this.orderable = orderable; } public String getSearchValue() { return searchValue; } public void setSearchValue( String searchValue ) { this.searchValue = searchValue; } public Boolean getSearchRegex() { return searchRegex; } public void setSearchRegex( Boolean searchRegex ) { this.searchRegex = searchRegex; } @Override public String toString() { return "DataTableHeader [data=" + data + ", name=" + name + ", searchable=" + searchable + ", orderable=" + orderable + ", searchValue=" + searchValue + ", searchRegex=" + searchRegex + "]"; } }
package edu.upc.caminstech.equipstic; import org.apache.commons.lang3.builder.CompareToBuilder; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @JsonInclude(Include.NON_NULL) public class Unitat implements Comparable<Unitat> { private final long idUnitat; private final String codiUnitat; private final String identificador; private final String nom; private final Estat estat; @JsonCreator public Unitat( @JsonProperty("idUnitat") long idUnitat, @JsonProperty(value = "codiUnitat", required = false) String codiUnitat, @JsonProperty(value = "identificador", required = false) String identificador, @JsonProperty(value = "nom", required = false) String nom, @JsonProperty(value = "estat", required = false) Estat estat) { this.idUnitat = idUnitat; this.codiUnitat = codiUnitat; this.identificador = identificador; this.nom = nom; this.estat = estat; } public Unitat(long idUnitat) { this(idUnitat, null, null, null, null); } public long getIdUnitat() { return idUnitat; } /** * Retorna el codi UPC de la Unitat Estructural. */ public String getCodiUnitat() { return codiUnitat; } /** * Retorna les sigles de la unitat. */ public String getIdentificador() { return identificador; } public String getNom() { return nom; } public Estat getEstat() { return estat; } @Override public String toString() { return String.format("[Unitat idUnitat: %s, codiUnitat: %s, identificador: %s, nom: %s]", idUnitat, codiUnitat, identificador, nom); } @Override public boolean equals(Object obj) { if (!(obj instanceof Unitat)) { return false; } return this.idUnitat == ((Unitat) obj).idUnitat; } @Override public int hashCode() { return Long.hashCode(idUnitat); } @Override public int compareTo(Unitat o) { if (o == null) { return -1; } if (o == this) { return 0; } return new CompareToBuilder().append(this.identificador, o.identificador).append(this.idUnitat, o.idUnitat) .toComparison(); } }
package eu.mivrenik.particles; import java.util.Locale; import java.util.logging.Logger; import eu.mivrenik.particles.scene.NewExperimentScene; import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; /** * Main application class that is used as entry point. */ public class AppEntryPoint extends Application { private static final Logger LOG = Logger.getLogger(AppEntryPoint.class.getName()); /** * Application entry point. * * @param args * Launch arguments */ public static void main(final String[] args) { Locale.setDefault(Locale.US); launch(args); } /** * Initialise main view stage. */ @Override public final void start(final Stage stage) throws Exception { LOG.info("Starting particles in box application"); Scene scene = NewExperimentScene.newInstance(); stage.setTitle("New experiment"); stage.setScene(scene); stage.show(); // Restrict resizing stage.setMinHeight(scene.getHeight()); stage.setMinWidth(scene.getWidth()); } }
package eu.ortlepp.blogbuilder.tools; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.logging.Logger; import eu.ortlepp.blogbuilder.model.Document; import eu.ortlepp.blogbuilder.model.freemarker.DocumentWrapper; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; /** * A writer for HTML files. Writes the processed Markdown files to HTML files. * * @author Thorsten Ortlepp */ public class Writer { /** A logger to write out messages to the user. */ private static final Logger LOGGER = Logger.getLogger(Writer.class.getName()); /** The target directory (where the HTML files are created). */ private final Path target; /** The configuration of the Freemarker template engine. */ private final Configuration fmConfig; /** Static data / information from the configuration file. */ private final Map<String, String> blogInfo; /** Get access to configuration read from the properties file. */ private final Config config; /** * Constructor, initializes the Freemarker template engine and loads the static data. * * @param target The target directory (where the HTML files are created) * @param templates The directory which contains the templates */ public Writer(Path target, Path templates) { this.target = target; config = Config.getInstance(); /* Initialize Freemarker */ fmConfig = new Configuration(Configuration.VERSION_2_3_25); try { fmConfig.setDirectoryForTemplateLoading(templates.toFile()); fmConfig.setDefaultEncoding("UTF-8"); fmConfig.setLocale(Locale.getDefault()); fmConfig.setObjectWrapper(new DocumentWrapper(fmConfig.getIncompatibleImprovements())); } catch (IOException ex) { LOGGER.severe("Initializing Freemarker failed!"); throw new RuntimeException(ex); } /* Load static data from configuration */ blogInfo = new HashMap<String, String>(); blogInfo.put("title", config.getTitle()); blogInfo.put("author", config.getAuthor()); } /** * Write documents of the list to HTML files. The template for blog posts is used. * * @param blogposts The list of blog posts */ public void writeBlogPosts(List<Document> blogposts) { int written = writeDocuments(blogposts, "post", "page_blogpost.ftl"); LOGGER.info(String.format("%d blog posts written", written)); } /** * Write documents of the list to HTML files. The template for simple pages is used. * * @param pages The list of simple pages */ public void writePages(List<Document> pages) { int written = writeDocuments(pages, "page", "page_page.ftl"); LOGGER.info(String.format("%d pages written", written)); } /** * Write documents to HTML files. All documents of the list are processed and written to disk. * * @param documents The list of documents to write * @param key The key which makes the document accessible in the template * @param template The template file to use for the HTML files * @return Returns the number of HTML files that were written */ public int writeDocuments(List<Document> documents, String key, String template) { int counter = 0; Map<String, Object> content = new HashMap<String, Object>(); content.put("blog", blogInfo); for (Document document : documents) { /* Set the document */ if (content.containsKey(key)) { content.replace(key, document); } else { content.put(key, document); } /* The absolute path of the file */ Path file = Paths.get(target.toString(), document.getPath()); try { /* Create directories */ Files.createDirectories(file.getParent()); /* Write file to disk using the Freemarker template */ if (writeFile(content, file.toFile(), template)) { counter++; LOGGER.info(String.format("Wrote %s", document.getPath())); } } catch (IOException ex) { LOGGER.severe(String.format("Creating directories failed: %s", ex.getMessage())); } } return counter; } /** * Write index pages for blog posts. For each index page a limited number of blog posts is used. * * @param blogposts The list of blog posts */ public void writeIndex(List<Document> blogposts) { Map<String, Object> content = new HashMap<String, Object>(); content.put("blog", blogInfo); int postsPerPage = config.getIndexPosts(); /* Calculate the number of index pages */ int pages = blogposts.size() / postsPerPage; if (blogposts.size() % postsPerPage > 0) { pages++; } /* Create the filenames for pagination */ String[] filenames = new String[pages + 2]; filenames[0] = ""; filenames[1] = String.format("%s.html", config.getIndexFile()); filenames[filenames.length - 1] = ""; for (int i = 1; i < pages; i++) { filenames[i + 1] = String.format("%s-%d.html", config.getIndexFile(), i); } /* Counter for the number of blog posts that were already added to an index page */ int added = 0; /* Create all index pages */ for (int i = 0; i < pages; i++) { List<Document> posts = new ArrayList<Document>(); /* Get blog posts for the page */ for (int j = added; j < (i + 1) * postsPerPage; j++) { if (added < blogposts.size()) { posts.add(blogposts.get(added)); added++; } else { break; } } /* Set the document */ if (content.containsKey("posts")) { content.replace("posts", posts); content.replace("index_newer", filenames[i]); content.replace("index_older", filenames[i + 2]); } else { content.put("posts", posts); content.put("index_newer", filenames[i]); content.put("index_older", filenames[i + 2]); } /* Write file to disk using the Freemarker template */ if (writeFile(content, new File(target.toFile(), filenames[i + 1]), "page_index.ftl")) { LOGGER.info(String.format("Wrote index page %s", filenames[i + 1])); } } } /** * Writer that writes out the content of a single document to an HTML file. A template is used to write the file. * * @param content The content of the document * @param file The name of the HTML file * @param template The template to use for the HTML file * @return Success flag: true = file written successfully, false = error while writing the file */ private boolean writeFile(Map<String, Object> content, File file, String template) { try (java.io.Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8")))) { Template fmTemplate = fmConfig.getTemplate(template); fmTemplate.process(content, out); } catch (IOException | TemplateException ex) { LOGGER.severe(String.format("Error while writing %s: %s", file.getName(), ex.getMessage())); return false; } return true; } }
package fucksocks.server; import fucksocks.client.SocksProxy; import fucksocks.common.SSLConfiguration; import fucksocks.common.methods.NoAuthenticationRequiredMethod; import fucksocks.common.methods.SocksMethod; import fucksocks.common.methods.UsernamePasswordMethod; import fucksocks.server.manager.MemoryBasedUserManager; import fucksocks.server.manager.UserManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import static com.google.common.base.Preconditions.checkNotNull; /** * The class <code>SocksServerBuilder</code> is a tool class to build an {@link SocksProxyServer}. * * @author Youchao Feng * @version 1.0 * @date Aug 27, 2015 * @since JDK1.7 */ public class SocksServerBuilder { private static final Logger logger = LoggerFactory.getLogger(SocksServerBuilder.class); private static final int DEFAULT_PORT = 1080; private Class<? extends SocksHandler> socksHandlerClass; private Set<SocksMethod> socksMethods; private UserManager userManager; private SocksProxy proxy; private int timeout; private int bindPort = DEFAULT_PORT; private boolean daemon = false; private ExecutorService executorService; private SessionManager sessionManager = new BasicSessionManager(); private SSLConfiguration sslConfiguration; /** * Creates a <code>SocksServerBuilder</code> with a <code>Class<? extends {@link * SocksHandler}</code> * instance. * * @param socksHandlerClass <code>java.lang.Class<? extends {@link SocksHandler}</code> instance. */ private SocksServerBuilder(Class<? extends SocksHandler> socksHandlerClass) { this.socksHandlerClass = checkNotNull(socksHandlerClass, "Argument [socksHandlerClass] may not be null"); userManager = new MemoryBasedUserManager(); } /** * Builds a {@link SocksProxyServer} which support SOCKS5 protocol. * This SOCKS5 server will accept all requests from clients with no authentication. * * @return Instance of {@link SocksProxyServer}. */ public static SocksProxyServer buildAnonymousSocks5Server() { return buildAnonymousSocks5Server(DEFAULT_PORT); } /** * Builds a {@link SocksProxyServer} which support SOCKS5 protocol bind at a specified port. * This SOCKS5 server will accept all requests from clients with no authentication. * * @param bindPort The port that server listened. * @return Instance of {@link SocksProxyServer}. */ public static SocksProxyServer buildAnonymousSocks5Server(int bindPort) { return newSocks5ServerBuilder().setSocksMethods(new NoAuthenticationRequiredMethod()) .setBindPort(bindPort).build(); } /** * Builds a SSL based {@link SocksProxyServer} with no authentication required. * * @param bindPort The port that server listened. * @param configuration SSL configuration * @return Instance of {@link SocksProxyServer} */ public static SocksProxyServer buildAnonymousSSLSocks5Server(int bindPort, SSLConfiguration configuration) { return newSocks5ServerBuilder().setSocksMethods(new NoAuthenticationRequiredMethod()) .setBindPort(bindPort).useSSL(configuration).build(); } public static SocksProxyServer buildAnonymousSSLSocks5Server(SSLConfiguration configuration) { return buildAnonymousSSLSocks5Server(DEFAULT_PORT, configuration); } /** * Creates a <code>SocksServerBuilder</code> instance with specified Class instance of {@link * SocksHandler}. * * @param socksHandlerClass Class instance of {@link SocksHandler}. * @return Instance of {@link SocksServerBuilder}. */ public static SocksServerBuilder newBuilder(Class<? extends SocksHandler> socksHandlerClass) { checkNotNull(socksHandlerClass, "Argument [socksHandlerClass] may not be null"); return new SocksServerBuilder(socksHandlerClass); } /** * Calls {@link #newBuilder(Class)} with an argument <code>Socks5Handler.class</code>; * * @return Instance of {@link SocksServerBuilder}. */ public static SocksServerBuilder newSocks5ServerBuilder() { return new SocksServerBuilder(Socks5Handler.class); } /** * Add {@link SocksMethod}. * * @param methods Instance of {@link SocksMethod}. * @return Instance of {@link SocksServerBuilder}. */ public SocksServerBuilder addSocksMethods(SocksMethod... methods) { if (socksMethods == null) { socksMethods = new HashSet<>(); } Collections.addAll(socksMethods, methods); return this; } /** * Set SOCKS methods that SOCKS server will support. * * @param methods Instance of {@link SocksMethod}. * @return Instance of {@link SocksServerBuilder}. */ public SocksServerBuilder setSocksMethods(SocksMethod... methods) { if (socksMethods == null) { socksMethods = new HashSet<>(); } Collections.addAll(socksMethods, methods); return this; } public SocksServerBuilder setSocksMethods(Set<SocksMethod> methods) { socksMethods = checkNotNull(methods, "Argument [methods] may not be null"); return this; } public SocksServerBuilder setUserManager(UserManager userManager) { this.userManager = checkNotNull(userManager, "Argument [userManager] may not be null"); return this; } public SocksServerBuilder setProxy(SocksProxy proxy) { this.proxy = proxy; return this; } public SocksServerBuilder setTimeout(int timeout) { this.timeout = timeout; return this; } public SocksServerBuilder setTimeout(long timeout, TimeUnit timeUnit) { this.timeout = (int) timeUnit.toMillis(timeout); return this; } public SocksServerBuilder setBindPort(int bindPort) { this.bindPort = bindPort; return this; } public SocksServerBuilder setExecutorService(ExecutorService executorService) { this.executorService = checkNotNull(executorService); return this; } public SocksServerBuilder setDaemon(boolean daemon) { this.daemon = daemon; return this; } public SocksServerBuilder setSessionManager(SessionManager sessionManager) { this.sessionManager = checkNotNull(sessionManager); return this; } public SocksServerBuilder useSSL(SSLConfiguration sslConfiguration) { this.sslConfiguration = sslConfiguration; return this; } public SocksProxyServer build() { SocksProxyServer proxyServer = null; if (sslConfiguration == null) { proxyServer = new BasicSocksProxyServer(socksHandlerClass); } else { proxyServer = new SSLSocksProxyServer(socksHandlerClass, sslConfiguration); } proxyServer.setTimeout(timeout); proxyServer.setBindPort(bindPort); proxyServer.setDaemon(daemon); proxyServer.setSessionManager(sessionManager); if (socksMethods == null) { socksMethods = new HashSet<>(); socksMethods.add(new NoAuthenticationRequiredMethod()); } SocksMethod[] methods = new SocksMethod[socksMethods.size()]; int i = 0; for (SocksMethod method : socksMethods) { if (method instanceof UsernamePasswordMethod) { if (userManager == null) { userManager = new MemoryBasedUserManager(); userManager.addUser("fucksocks", "fucksocks"); } ((UsernamePasswordMethod) method).setAuthenticator(new UsernamePasswordAuthenticator (userManager)); } methods[i] = method; i++; } if (executorService != null) { proxyServer.setExecutorService(executorService); } proxyServer.setSupportMethods(methods); if (proxy != null) { proxyServer.setProxy(proxy); } return proxyServer; } }
package peergos.server; import peergos.server.corenode.*; import peergos.server.mutable.*; import peergos.server.social.*; import peergos.server.storage.*; import peergos.shared.*; import peergos.shared.user.*; public class NonWriteThroughNetwork { public static NetworkAccess build(NetworkAccess source) { NonWriteThroughStorage storage = new NonWriteThroughStorage(source.dhtClient); NonWriteThroughMutablePointers mutable = new NonWriteThroughMutablePointers(source.mutable, storage); return new NetworkAccess( new NonWriteThroughCoreNode(source.coreNode, storage), new NonWriteThroughSocialNetwork(source.social, storage), storage, mutable, new MutableTreeImpl(mutable, storage), source.instanceAdmin, source.usernames, false); } }
package hu.unideb.inf.dejavu.gui; import hu.unideb.inf.dejavu.DejaVu; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.TextField; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.stage.Stage; import javafx.stage.StageStyle; public class SignInMenu extends DVMenu { public SignInMenu(final String args) { super(); setHgap(10); setVgap(10); add(new DVText(args, Font.font("Verdana", FontWeight.BOLD, 20)), 3, 2); add(new DVText("Név:", Font.font("Verdana", 10)), 2, 4); final TextField name = new TextField(); name.setPromptText("Név"); add(name, 3, 4); add(new DVText("Jelszó:", Font.font("Verdana", 10)), 2, 5); final TextField pass = new TextField(); pass.setPromptText("Jelszó"); add(pass, 3, 5); final DVButton signIn = new DVButton(args, 1); signIn.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent arg0) { if (args.equals("Bejelentkezés") && DejaVu.game.loadProfile(name.getText(), pass.getText())) { DejaVu.setNewMenu(new MainMenu()); WelcomeMenu.signIn.setDisable(false); WelcomeMenu.newProfile.setDisable(false); ((Stage) signIn.getScene().getWindow()).close(); } else if (args.equals("Új profil") && DejaVu.game.addProfile(name.getText(), pass.getText())) { DejaVu.setNewMenu(new MainMenu()); WelcomeMenu.signIn.setDisable(false); WelcomeMenu.newProfile.setDisable(false); ((Stage) signIn.getScene().getWindow()).close(); } else { final Stage stage = new Stage(); final int width = 250, height = 130; DVMenu error = new DVMenu(); error.setHgap(5); error.setVgap(5); ExitToolbar exit = new ExitToolbar(stage); ExitToolbar.toolbarButtons.closeButton .setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent arg0) { WelcomeMenu.signIn.setDisable(false); WelcomeMenu.newProfile.setDisable(false); stage.close(); } }); final DVButton OK = new DVButton("OK", 1); OK.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent arg0) { ((Stage) OK.getScene().getWindow()).close(); } }); DVText message = new DVText( "Hibás felhasználónév vagy jelszó!", Font.font( "Verdana", 14)); error.setTop(exit); error.add(message, 1, 1); error.add(OK, 1, 10); stage.initStyle(StageStyle.TRANSPARENT); Scene scene = new Scene(error, width, height); scene.setFill(Color.TRANSPARENT); stage.setMaxHeight(height); stage.setMinHeight(height); stage.setMaxWidth(width); stage.setMinWidth(width); stage.setAlwaysOnTop(true); stage.setScene(scene); stage.centerOnScreen(); stage.show(); } } }); add(signIn, 8, 6); } }
package peerjDocxFormatter; import java.io.*; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.docx4j.TraversalUtil; import org.docx4j.finders.SectPrFinder; import org.docx4j.model.structure.PageDimensions; import org.docx4j.model.structure.PageSizePaper; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart; import org.docx4j.openpackaging.parts.relationships.Namespaces; import org.docx4j.relationships.Relationship; import org.docx4j.wml.CTBackground; import org.docx4j.wml.PPr; import org.docx4j.wml.PPrBase.Spacing; import org.docx4j.wml.STPageOrientation; import org.docx4j.wml.SectPr; import org.docx4j.wml.SectPr.PgMar; import org.docx4j.wml.SectPr.PgSz; import org.docx4j.wml.CTLineNumber; import org.docx4j.wml.STLineNumberRestart; import org.docx4j.wml.ObjectFactory; public class PeerJDocxFormatter { @SuppressWarnings("deprecation") public static void main (String[] args) { String version = "0.0.1"; HelpFormatter formatter = new HelpFormatter(); Options options = new Options(); options.addOption("h", false, "help"); options.addOption("m", true, "margins left,top,right,bottom"); options.addOption("l", true, "line numbering distance"); options.addOption("r", false, "remove headers and footers"); Option input = new Option("i", true, "input docx file"); input.setRequired(true); options.addOption(input); Option output = new Option("o", true, "output docx file"); output.setRequired(true); options.addOption(output); options.addOption("v", false, "version"); boolean removeHeaderFooters = true; double lineNumberingDistance = 0; PgMar pageMargins = null; String inputFilename = null; String outputFilename = null; File inputFile = null; CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse( options, args); if (cmd.hasOption("h")) { formatter.printHelp( "java -jar PeerJDocxFormatter.jar", options ); System.out.println("PeerJDocxFormatter Version: " + version); return; } if (cmd.hasOption("v")) { System.out.println("PeerJDocxFormatter Version: " + version); return; } // required options inputFilename = cmd.getOptionValue("i"); outputFilename = cmd.getOptionValue("o"); try { inputFile = new File(inputFilename); if (!inputFile.isFile()) { throw new Exception("File doesn't exist"); } } catch (Exception e) { System.out.println(String.format("%s file does not exist", inputFilename)); System.exit(1); } // optional removeHeaderFooters = cmd.hasOption("r"); if (cmd.hasOption("l")) { lineNumberingDistance = Double.parseDouble(cmd.getOptionValue("l")); } if (cmd.hasOption("m")) { String marginOption = cmd.getOptionValue("m"); String[] margins = marginOption.split(","); pageMargins = new PgMar(); pageMargins.setLeft(cmToDxa(Double.parseDouble(margins[0]))); pageMargins.setTop(cmToDxa(Double.parseDouble(margins[1]))); pageMargins.setRight(cmToDxa(Double.parseDouble(margins[2]))); pageMargins.setBottom(cmToDxa(Double.parseDouble(margins[3]))); } } catch (Exception e) { formatter.printHelp( "java -jar PeerJDocxFormatter.jar", options ); System.out.println("PeerJDocxFormatter Version: " + version); e.printStackTrace(); return; } try { WordprocessingMLPackage wordMLPackage; wordMLPackage = WordprocessingMLPackage.load(inputFile); MainDocumentPart mdp = wordMLPackage.getMainDocumentPart(); ObjectFactory wmlObjectFactory = new ObjectFactory(); CTBackground background = wmlObjectFactory.createCTBackground(); background.setColor("FFFFFF"); mdp.getJaxbElement().setBackground(background); SectPrFinder finder = new SectPrFinder(mdp); new TraversalUtil(mdp.getContent(), finder); for (SectPr sectPr : finder.getOrderedSectPrList()) { // always force us letter, but keep page orientation if (sectPr.getPgSz().getOrient() == STPageOrientation.LANDSCAPE) { sectPr.setPgSz(getUSLetterLandscapePageSize()); } else { sectPr.setPgSz(getUSLetterPortraitPageSize()); } // TODO: Double spacing? if (pageMargins != null) { sectPr.setPgMar(pageMargins); } if (removeHeaderFooters) { // remove header/footer references sectPr.getEGHdrFtrReferences().clear(); } if (lineNumberingDistance > 0) { CTLineNumber lineNumbering = getLineNumbering(cmToDxa(lineNumberingDistance)); sectPr.setLnNumType(lineNumbering); } else if (lineNumberingDistance < 0) { CTLineNumber lineNumbering = removeLineNumbering(); sectPr.setLnNumType(lineNumbering); } } if (removeHeaderFooters) { removeHeaderFooters(mdp); } /* Needs further investigation ClassFinder pFinder = new ClassFinder(P.class); new TraversalUtil(mdp.getContent(), pFinder); for (Object p: pFinder.results) { ((P)p).setPPr(setDoubleSpacing()); } */ File outputFile = new File(outputFilename); wordMLPackage.save(outputFile); if (!outputFile.isFile()) { throw new Exception("Failed to generate output file"); } System.out.println(String.format("Finished converting %s", outputFilename)); } catch (Exception e) { System.out.println(String.format("Error!! Failed converting %s", outputFilename)); e.printStackTrace(); System.exit(1); } } private static BigInteger cmToDxa(double cm) { double points = cm * 28.3464567; double dxa = points * 20; return BigInteger.valueOf((long)dxa); } @SuppressWarnings("unused") private static PPr setDoubleSpacing() { // not exactly, changes to fixed 1.0cm // leaving out for now Spacing s = new Spacing(); s.setLine(cmToDxa(1)); PPr ppr = new PPr(); ppr.setSpacing(s); //System.out.println(String.format("Spacing %s", ppr.getSpacing().g)); return ppr; } private static CTLineNumber getLineNumbering(BigInteger distance) { CTLineNumber n = new CTLineNumber(); n.setCountBy(BigInteger.valueOf(1)); n.setDistance(distance); n.setStart(BigInteger.valueOf(1)); n.setRestart(STLineNumberRestart.CONTINUOUS); return n; } private static CTLineNumber removeLineNumbering() { CTLineNumber n = new CTLineNumber(); return n; } private static PgSz getUSLetterLandscapePageSize() { PageDimensions page = new PageDimensions(); page.setPgSize(PageSizePaper.LETTER, true); return page.getPgSz(); } private static PgSz getUSLetterPortraitPageSize() { PageDimensions page = new PageDimensions(); page.setPgSize(PageSizePaper.LETTER, false); return page.getPgSz(); } private static void removeHeaderFooters(MainDocumentPart mdp) { // Remove rels List<Relationship> hfRels = new ArrayList<Relationship>(); for (Relationship rel : mdp.getRelationshipsPart().getRelationships().getRelationship() ) { if (rel.getType().equals(Namespaces.HEADER) || rel.getType().equals(Namespaces.FOOTER)) { hfRels.add(rel); } } for (Relationship rel : hfRels ) { mdp.getRelationshipsPart().removeRelationship(rel); } } }
package hu.unideb.inf.dejavu.gui; import hu.unideb.inf.dejavu.DejaVu; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.stage.Stage; import javafx.stage.StageStyle; public class SignInMenu extends DVMenu { public SignInMenu(final String args) { super(); setHgap(10); setVgap(10); add(new DVText(args, Font.font("Verdana", FontWeight.BOLD, 20)), 3, 2); add(new DVText("Név:", Font.font("Verdana", 10)), 2, 4); final TextField name = new TextField(); name.setPromptText("Név"); add(name, 3, 4); add(new DVText("Jelszó:", Font.font("Verdana", 10)), 2, 5); final PasswordField pass = new PasswordField(); pass.setPromptText("Jelszó"); add(pass, 3, 5); final DVButton signIn = new DVButton(args, 1); signIn.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent arg0) { if (args.equals("Bejelentkezés") && DejaVu.game.loadProfile(name.getText(), pass.getText())) { boolean load = false; if (DejaVu.game.isStatusExist()) { } if (load && DejaVu.game.filesExist()) { DejaVu.setNewMenu(new MainMenu()); } else { DejaVu.game.removeStatus(); DejaVu.setNewMenu(new MainMenu()); } WelcomeMenu.signIn.setDisable(false); WelcomeMenu.newProfile.setDisable(false); ((Stage) signIn.getScene().getWindow()).close(); } else if (args.equals("Új profil") && DejaVu.game.addProfile(name.getText(), pass.getText())) { DejaVu.setNewMenu(new MainMenu()); WelcomeMenu.signIn.setDisable(false); WelcomeMenu.newProfile.setDisable(false); ((Stage) signIn.getScene().getWindow()).close(); } else { final Stage stage = new Stage(); final int width = 250, height = 130; DVMenu error = new DVMenu(); error.setHgap(5); error.setVgap(5); ExitToolbar exit = new ExitToolbar(stage); ExitToolbar.toolbarButtons.closeButton .setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent arg0) { WelcomeMenu.signIn.setDisable(false); WelcomeMenu.newProfile.setDisable(false); stage.close(); } }); final DVButton OK = new DVButton("OK", 1); OK.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent arg0) { ((Stage) OK.getScene().getWindow()).close(); } }); DVText message = new DVText( "Hibás felhasználónév vagy jelszó!", Font.font( "Verdana", 14)); error.setTop(exit); error.add(message, 1, 1); error.add(OK, 1, 10); stage.initStyle(StageStyle.TRANSPARENT); Scene scene = new Scene(error, width, height); scene.setFill(Color.TRANSPARENT); stage.setMaxHeight(height); stage.setMinHeight(height); stage.setMaxWidth(width); stage.setMinWidth(width); stage.setAlwaysOnTop(true); stage.setScene(scene); stage.centerOnScreen(); stage.show(); } } }); add(signIn, 8, 6); } }
package hudson.remoting; import java.io.IOException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import static hudson.remoting.Util.*; /** * {@link ResourceImageRef} that directly encapsulates the resource as {@code byte[]}. * * <p> * This is used when {@link ResourceImageInJar} cannot be used because we couldn't identify the jar file. * * @author Kohsuke Kawaguchi */ class ResourceImageDirect extends ResourceImageRef { /** * The actual resource. */ private final byte[] payload; ResourceImageDirect(byte[] payload) { this.payload = payload; } ResourceImageDirect(URL resource) throws IOException { this(Util.readFully(resource.openStream())); } @Override Future<byte[]> resolve(Channel channel, String resourcePath) throws IOException, InterruptedException { LOGGER.log(Level.FINE, resourcePath+" image is direct"); return new AsyncFutureImpl<byte[]>(payload); } @Override Future<URLish> resolveURL(Channel channel, String resourcePath) throws IOException, InterruptedException { return new AsyncFutureImpl<URLish>(URLish.from(makeResource(resourcePath, payload))); } private static final Logger LOGGER = Logger.getLogger(ResourceImageDirect.class.getName()); private static final long serialVersionUID = 1L; }
package io.github.bonigarcia.wdm; import static io.github.bonigarcia.wdm.WdmConfig.getBoolean; import static io.github.bonigarcia.wdm.WdmConfig.getString; import static java.io.File.separator; import static java.lang.Runtime.getRuntime; import static java.lang.System.getProperty; import static java.nio.file.Files.createTempDirectory; import static java.nio.file.Files.delete; import static java.nio.file.Files.move; import static java.util.UUID.randomUUID; import static org.apache.commons.io.FileUtils.copyInputStreamToFile; import static org.apache.commons.io.FileUtils.listFiles; import static org.rauschig.jarchivelib.ArchiveFormat.TAR; import static org.rauschig.jarchivelib.ArchiverFactory.createArchiver; import static org.rauschig.jarchivelib.CompressionType.BZIP2; import static org.rauschig.jarchivelib.CompressionType.GZIP; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Collection; import java.util.Enumeration; import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.rauschig.jarchivelib.Archiver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Downloader class. * * @author Boni Garcia (boni.gg@gmail.com) * @since 1.0.0 */ public class Downloader { protected static final Logger log = LoggerFactory .getLogger(Downloader.class); private static final String HOME = "~"; private BrowserManager browserManager; private WdmHttpClient httpClient; private boolean override = getBoolean("wdm.override"); public Downloader(BrowserManager browserManager) { this(browserManager, new WdmHttpClient.Builder().build()); } public Downloader(BrowserManager browserManager, WdmHttpClient httpClient) { this.browserManager = browserManager; this.httpClient = httpClient; } public synchronized void download(URL url, String version, String export, List<String> driverName) throws IOException, InterruptedException { File targetFile = new File(getTarget(version, url)); File binary = null; // Check if binary exists boolean download = !targetFile.getParentFile().exists() || (targetFile.getParentFile().exists() && targetFile.getParentFile().list().length == 0) || override; if (download) { File temporaryFile = new File(targetFile.getParentFile(), randomUUID().toString()); log.debug("Downloading {} to {}", url, targetFile); WdmHttpClient.Get get = new WdmHttpClient.Get(url) .addHeader("User-Agent", "Mozilla/5.0") .addHeader("Connection", "keep-alive"); try { copyInputStreamToFile(httpClient.execute(get).getContent(), temporaryFile); } catch (IOException e) { deleteFile(temporaryFile); throw e; } renameFile(temporaryFile, targetFile); if (!export.contains("edge")) { binary = extract(targetFile); } else { binary = targetFile; } if (targetFile.getName().toLowerCase().endsWith(".msi")) { binary = extractMsi(targetFile); } } else { // Check if existing binary is valid Collection<File> listFiles = listFiles(targetFile.getParentFile(), null, true); for (File file : listFiles) { for (String s : driverName) { if (file.getName().startsWith(s) && file.canExecute()) { binary = file; log.debug( "Using binary driver previously downloaded {}", binary); download = false; break; } else { download = true; } } if (!download) { break; } } } if (export != null && binary != null) { browserManager.exportDriver(export, binary.toString()); } } public File extract(File compressedFile) throws IOException { log.trace("Compressed file {}", compressedFile); if (compressedFile.getName().toLowerCase().endsWith("tar.bz2")) { unBZip2(compressedFile); } else if (compressedFile.getName().toLowerCase().endsWith("tar.gz")) { unTarGz(compressedFile); } else if (compressedFile.getName().toLowerCase().endsWith("gz")) { unGzip(compressedFile); } else { unZip(compressedFile); } deleteFile(compressedFile); File result = browserManager.postDownload(compressedFile) .getAbsoluteFile(); setFileExecutable(result); log.trace("Resulting binary file {}", result); return result; } public File unZip(File compressedFile) throws IOException { File file = null; try (ZipFile zipFolder = new ZipFile(compressedFile)) { Enumeration<?> enu = zipFolder.entries(); while (enu.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) enu.nextElement(); String name = zipEntry.getName(); long size = zipEntry.getSize(); long compressedSize = zipEntry.getCompressedSize(); log.trace("Unzipping {} (size: {} KB, compressed size: {} KB)", name, size, compressedSize); file = new File( compressedFile.getParentFile() + separator + name); if (!file.exists() || override) { if (name.endsWith("/")) { file.mkdirs(); continue; } File parent = file.getParentFile(); if (parent != null) { parent.mkdirs(); } try (InputStream is = zipFolder.getInputStream(zipEntry)) { File temporaryFile = new File(parent, randomUUID().toString()); copyInputStreamToFile(is, temporaryFile); renameFile(temporaryFile, file); } setFileExecutable(file); } else { log.debug("{} already exists", file); } } } return file; } public File unGzip(File archive) throws IOException { log.trace("UnGzip {}", archive); String fileName = archive.getName(); int iDash = fileName.indexOf('-'); if (iDash != -1) { fileName = fileName.substring(0, iDash); } int iDot = fileName.indexOf('.'); if (iDot != -1) { fileName = fileName.substring(0, iDot); } File target = new File(archive.getParentFile() + separator + fileName); try (GZIPInputStream in = new GZIPInputStream( new FileInputStream(archive))) { try (FileOutputStream out = new FileOutputStream(target)) { for (int c = in.read(); c != -1; c = in.read()) { out.write(c); } } } if (!target.getName().toLowerCase().contains(".exe") && target.exists()) { setFileExecutable(target); } return target; } public File unTarGz(File archive) throws IOException { Archiver archiver = createArchiver(TAR, GZIP); archiver.extract(archive, archive.getParentFile()); log.trace("unTarGz {}", archive); return archive; } public File unBZip2(File archive) throws IOException { Archiver archiver = createArchiver(TAR, BZIP2); archiver.extract(archive, archive.getParentFile()); log.trace("Unbzip2 {}", archive); return archive; } public String getTarget(String version, URL url) throws IOException { log.trace("getTarget {} {}", version, url); String zip = url.getFile().substring(url.getFile().lastIndexOf('/')); int iFirst = zip.indexOf('_'); int iSecond = zip.indexOf('-'); int iLast = zip.length(); if (iFirst != zip.lastIndexOf('_')) { iLast = zip.lastIndexOf('_'); } else if (iSecond != -1) { iLast = iSecond; } String folder = zip.substring(0, iLast).replace(".zip", "") .replace(".tar.bz2", "").replace(".tar.gz", "") .replace(".msi", "").replace(".exe", "") .replace("_", separator); String target = browserManager.preDownload( getTargetPath() + folder + separator + version + zip, version); log.trace("Target file for URL {} version {} = {}", url, version, target); return target; } public String getTargetPath() { String targetPath = getString("wdm.targetPath"); if (targetPath.contains(HOME)) { targetPath = targetPath.replace(HOME, getProperty("user.home")); } // Create repository folder if not exits File repository = new File(targetPath); if (!repository.exists()) { repository.mkdirs(); } return targetPath; } public void forceDownload() { this.override = true; } public File extractMsi(File msi) throws IOException, InterruptedException { File tmpMsi = new File( createTempDirectory(msi.getName()).toFile().getAbsoluteFile() + separator + msi.getName()); move(msi.toPath(), tmpMsi.toPath()); log.trace("Temporal msi file: {}", tmpMsi); Process process = getRuntime().exec(new String[] { "msiexec", "/a", tmpMsi.toString(), "/qb", "TARGETDIR=" + msi.getParent() }); try { process.waitFor(); } finally { process.destroy(); } deleteFile(tmpMsi); deleteFile(msi); Collection<File> listFiles = listFiles(new File(msi.getParent()), new String[] { "exe" }, true); return listFiles.iterator().next(); } protected void setFileExecutable(File file) { log.trace("Setting file {} as exectable", file); if (!file.setExecutable(true)) { log.warn("Error setting file {} as executable", file); } } protected void renameFile(File from, File to) { log.trace("Renaming file from {} to {}", from, to); if (!from.renameTo(to)) { log.warn("Error renaming file from {} to {}", from, to); } } protected void deleteFile(File file) throws IOException { log.trace("Deleting file {}", file); delete(file.toPath()); } }
package jmh.barker; import java.util.Arrays; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; @State(Scope.Thread) @Warmup(iterations = 4, time = 1, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 8, time = 4, timeUnit = TimeUnit.SECONDS) @Fork(value = 1,jvmArgsAppend = "-Xmx512M") @OutputTimeUnit(TimeUnit.NANOSECONDS) @BenchmarkMode(Mode.SampleTime) public class BinarySearchVsLinearScan { @Param({ "8", "64"}) private int len; private long[] longs; private int lowVal; private int midVal; private int highVal; @Setup public void setup() { longs = new long[len]; for (int i = 0; i < len; i++) longs[i] = i; lowVal = 3; midVal = len / 2; highVal = len - 1; } @Benchmark public long lowIndex_LinearScan() { long expectedVal = longs[lowVal]; for (int i = 0; i < longs.length; i++) { if (longs[i] == expectedVal) return i; } return -1; } @Benchmark public long lowIndex_BinarySearch() { long expectedVal = longs[lowVal]; return Arrays.binarySearch(longs, expectedVal); } @Benchmark public long midIndex_LinearScan() { long expectedVal = longs[midVal]; for (int i = 0; i < longs.length; i++) { if (longs[i] == expectedVal) return i; } return -1; } @Benchmark public long midIndex_BinarySearch() { long expectedVal = longs[midVal]; return Arrays.binarySearch(longs, expectedVal); } @Benchmark public long highIndex_LinearScan() { // we can check if the expectedVal is greater than the mid value (assuming values are ordered!), // and if it is higher than the mid, we can walk the array in reverse long expectedVal = longs[highVal]; for (int i = longs.length - 1; i >= 0; i { if (longs[i] == expectedVal) return i; } return -1; } @Benchmark public long highIndex_BinarySearch() { long expectedVal = longs[highVal]; return Arrays.binarySearch(longs, expectedVal); } }
package main.java.latexee.declareast; import main.java.antlrgen.DeclarationGrammarParser.ImportantPairContext; import main.java.antlrgen.DeclarationGrammarParser.MiscPairContext; import main.java.antlrgen.DeclarationGrammarParser.PairContext; import org.antlr.v4.runtime.tree.ParseTree; public class MacroDeclaration extends DeclareNode { private String macroName; //the name of the macro - the characters following \ private Integer arguments; private boolean hasOptionalArgument = false; private String optionalValue; public MacroDeclaration(String meaning, String macroname, int arguments) { super(); this.meaning=meaning; this.macroName=macroname; this.arguments=arguments; } public MacroDeclaration(ParseTree tree){ fillAttributes(tree); if( this.meaning == null || this.contentDictionary==null){ //Yesterday, this was a formality. Today it guards us from the hell of nullpointers. throw new RuntimeException("OpenMath meaning was not instantiated on macro declaration: "+tree.getText()); } if(this.arguments==null){ throw new RuntimeException("Number of arguments was not instantiated on macro declaration: "+tree.getText()); } if(this.macroName==null){ throw new RuntimeException("Macro name was not instantiated on macro declaration: "+tree.getText()); } if(this.arguments<0){ throw new RuntimeException("Negative amount of arguments given for macro declaration: "+tree.getText()); } } private void fillAttributes(ParseTree tree){ if(tree instanceof ImportantPairContext){ String key = tree.getChild(0).getText(); String value = tree.getChild(2).getText(); switch(key){ case "macro": this.macroName=tree.getChild(3).getText(); break; case "argspec": String nrOfArgs = tree.getChild(3).getText(); this.arguments=Integer.parseInt(nrOfArgs); if(tree.getChildCount()==8){ this.hasOptionalArgument=true; this.optionalValue = tree.getChild(6).getText(); } break; case "meaning": this.contentDictionary=value; this.meaning=tree.getChild(4).getText(); break; default: this.miscellaneous.put(key, value); break; } } else if(tree instanceof MiscPairContext){ String key = tree.getChild(0).getText(); String value = tree.getChild(2).getText(); this.miscellaneous.put(key, value); } for(int i=0;i<tree.getChildCount();i++){ fillAttributes(tree.getChild(i)); } } public boolean hasOptionalArgument() { return hasOptionalArgument; } public String getOptionalValue() { return optionalValue; } @Override public String toGrammarRule() { String highestLevelRule = "highestLevel"; StringBuilder sb = new StringBuilder(); sb.append("\'\\\\"+this.macroName+"\'"); for(int i=0;i<arguments;i++){ sb.append("\'{\'"); sb.append(highestLevelRule); sb.append("\'}\'"); } sb.append(" #"+this.macroName+"AllArgs\n"); if(this.hasOptionalArgument){ sb.append("|\'\\\\"+this.macroName+"\'"); for(int i=0;i<arguments-1;i++){ sb.append("\'{\'"); sb.append(highestLevelRule); sb.append("\'}\'"); } sb.append(" #"+this.macroName+"Optional\n"); } return sb.toString(); } }
package mesosphere.marathon.client; import java.util.List; import javax.inject.Named; import mesosphere.marathon.client.model.v2.App; import mesosphere.marathon.client.model.v2.DeleteAppTaskResponse; import mesosphere.marathon.client.model.v2.DeleteAppTasksResponse; import mesosphere.marathon.client.model.v2.Deployment; import mesosphere.marathon.client.model.v2.GetAppResponse; import mesosphere.marathon.client.model.v2.GetAppTasksResponse; import mesosphere.marathon.client.model.v2.GetAppsResponse; import mesosphere.marathon.client.model.v2.GetEventSubscriptionRegisterResponse; import mesosphere.marathon.client.model.v2.GetEventSubscriptionsResponse; import mesosphere.marathon.client.model.v2.GetServerInfoResponse; import mesosphere.marathon.client.model.v2.GetTasksResponse; import mesosphere.marathon.client.model.v2.Group; import mesosphere.marathon.client.model.v2.Result; import mesosphere.marathon.client.utils.MarathonException; import feign.RequestLine; public interface Marathon { // Apps @RequestLine("GET /v2/apps") GetAppsResponse getApps() throws MarathonException; @RequestLine("GET /v2/apps/{id}") GetAppResponse getApp(@Named("id") String id) throws MarathonException; @RequestLine("GET /v2/apps/{id}/tasks") GetAppTasksResponse getAppTasks(@Named("id") String id); @RequestLine("GET /v2/tasks") GetTasksResponse getTasks() throws MarathonException; @RequestLine("POST /v2/apps") App createApp(App app) throws MarathonException; @RequestLine("PUT /v2/apps/{app_id}") void updateApp(@Named("app_id") String appId, App app) throws MarathonException; @RequestLine("POST /v2/apps/{id}/restart?force={force}") void restartApp(@Named("id") String id,@Named("force") boolean force) throws MarathonException; @RequestLine("DELETE /v2/apps/{id}") Result deleteApp(@Named("id") String id) throws MarathonException; @RequestLine("DELETE /v2/apps/{app_id}/tasks?host={host}&scale={scale}") DeleteAppTasksResponse deleteAppTasks(@Named("app_id") String appId, @Named("host") String host, @Named("scale") String scale) throws MarathonException; @RequestLine("DELETE /v2/apps/{app_id}/tasks/{task_id}?scale={scale}") DeleteAppTaskResponse deleteAppTask(@Named("app_id") String appId, @Named("task_id") String taskId, @Named("scale") String scale) throws MarathonException; // Groups @RequestLine("POST /v2/groups") Result createGroup(Group group) throws MarathonException; @RequestLine("DELETE /v2/groups/{id}") Result deleteGroup(@Named("id") String id) throws MarathonException; @RequestLine("GET /v2/groups/{id}") Group getGroup(@Named("id") String id) throws MarathonException; // Tasks // Deployments @RequestLine("GET /v2/deployments") List<Deployment> getDeployments() throws MarathonException; @RequestLine("DELETE /v2/deployments/{deploymentId}") void cancelDeploymentAndRollback(@Named("deploymentId") String id) throws MarathonException; @RequestLine("DELETE /v2/deployments/{deploymentId}?force=true") void cancelDeployment(@Named("deploymentId") String id) throws MarathonException; // Event Subscriptions @RequestLine("POST /v2/eventSubscriptions?callbackUrl={url}") public GetEventSubscriptionRegisterResponse register(@Named("url") String url) throws MarathonException; @RequestLine("DELETE /v2/eventSubscriptions?callbackUrl={url}") public GetEventSubscriptionRegisterResponse unregister(@Named("url") String url) throws MarathonException; @RequestLine("GET /v2/eventSubscriptions") public GetEventSubscriptionsResponse subscriptions() throws MarathonException; // Queue // Server Info @RequestLine("GET /v2/info") GetServerInfoResponse getServerInfo() throws MarathonException; // Miscellaneous }
package mho.wheels.iterables; import mho.wheels.math.Combinatorics; import mho.wheels.math.MathUtils; import mho.wheels.ordering.Ordering; import mho.wheels.structures.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import java.util.function.Function; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.ordering.Ordering.fromInt; import static mho.wheels.ordering.Ordering.lt; /** * <tt>Iterable</tt>s that randomly generate all (or some important subset) of a type's values. */ public class RandomProvider extends IterableProvider { public static final int DEFAULT_BIG_INTEGER_MEAN_BIT_SIZE = 64; public static final int DEFAULT_BIG_DECIMAL_MEAN_SCALE = (int) Math.round(Math.log10(2) * DEFAULT_BIG_INTEGER_MEAN_BIT_SIZE); public static final int DEFAULT_MEAN_LIST_SIZE = 10; public static final int DEFAULT_SPECIAL_ELEMENT_RATIO = 50; private int bigIntegerMeanBitSize = DEFAULT_BIG_INTEGER_MEAN_BIT_SIZE; private int bigDecimalMeanScale = DEFAULT_BIG_DECIMAL_MEAN_SCALE; private int meanListSize = DEFAULT_MEAN_LIST_SIZE; private int specialElementRatio = DEFAULT_SPECIAL_ELEMENT_RATIO; protected final @NotNull Random generator; public RandomProvider() { generator = new Random(); } public RandomProvider(@NotNull Random generator) { this.generator = generator; } public int getBigIntegerMeanBitSize() { return bigIntegerMeanBitSize; } public int getBigDecimalMeanScale() { return bigDecimalMeanScale; } public int getMeanListSize() { return meanListSize; } public int getSpecialElementRatio() { return specialElementRatio; } public RandomProvider copy() { RandomProvider copy = new RandomProvider(generator); copy.bigIntegerMeanBitSize = bigIntegerMeanBitSize; copy.bigDecimalMeanScale = bigDecimalMeanScale; copy.meanListSize = meanListSize; copy.specialElementRatio = specialElementRatio; return copy; } public RandomProvider withBigIntegerMeanBitSize(int bigIntegerMeanBitSize) { RandomProvider newRandomProvider = copy(); newRandomProvider.bigIntegerMeanBitSize = bigIntegerMeanBitSize; return newRandomProvider; } public RandomProvider withBigDecimalMeanScale(int bigDecimalMeanScale) { RandomProvider newRandomProvider = copy(); newRandomProvider.bigDecimalMeanScale = bigDecimalMeanScale; return newRandomProvider; } public RandomProvider withMeanListSize(int meanListSize) { RandomProvider newRandomProvider = copy(); newRandomProvider.meanListSize = meanListSize; return newRandomProvider; } public RandomProvider withSpecialElementRatio(int specialElementRatio) { RandomProvider newRandomProvider = copy(); newRandomProvider.specialElementRatio = specialElementRatio; return newRandomProvider; } /** * An <tt>Iterator</tt> that generates both <tt>Boolean</tt>s from a uniform distribution. Does not support * removal. * * Length is infinite */ @Override public @NotNull Iterable<Boolean> booleans() { return () -> new Iterator<Boolean>() { @Override public boolean hasNext() { return true; } @Override public Boolean next() { return generator.nextBoolean(); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * An <tt>Iterator</tt> that generates all <tt>Ordering</tt>s from a uniform distribution. Does not support * removal. * * Length is infinite */ @Override public @NotNull Iterable<Ordering> orderings() { return () -> new Iterator<Ordering>() { @Override public boolean hasNext() { return true; } @Override public Ordering next() { return fromInt(generator.nextInt(3) - 1); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * An <tt>Iterable</tt> that generates all <tt>RoundingMode</tt>s from a uniform distribution. Does not support * removal. * * Length is infinite */ @Override public @NotNull Iterable<RoundingMode> roundingModes() { Function<Integer, RoundingMode> lookup = i -> { switch (i) { case 0: return RoundingMode.UNNECESSARY; case 1: return RoundingMode.UP; case 2: return RoundingMode.DOWN; case 3: return RoundingMode.CEILING; case 4: return RoundingMode.FLOOR; case 5: return RoundingMode.HALF_UP; case 6: return RoundingMode.HALF_DOWN; default: return RoundingMode.HALF_EVEN; } }; return map(lookup, randomIntsPow2(3)); } private @NotNull Iterable<Integer> randomIntsPow2(int bits) { int mask = (1 << bits) - 1; return map(i -> i & mask, integers()); } private @NotNull Iterable<Long> randomLongsPow2(int bits) { long mask = (1L << bits) - 1; return map(l -> l & mask, longs()); } private @NotNull Iterable<BigInteger> randomBigIntegersPow2(int bits) { return map(MathUtils::fromBits, lists(bits, booleans())); } private @NotNull Iterable<Integer> randomInts(int n) { return filter( i -> i < n, randomIntsPow2(MathUtils.ceilingLog(BigInteger.valueOf(2), BigInteger.valueOf(n)).intValueExact()) ); } private @NotNull Iterable<Long> randomLongs(long n) { return filter( l -> l < n, randomLongsPow2(MathUtils.ceilingLog(BigInteger.valueOf(2), BigInteger.valueOf(n)).intValueExact()) ); } private @NotNull Iterable<BigInteger> randomBigIntegers(@NotNull BigInteger n) { return filter( i -> lt(i, n), randomBigIntegersPow2(MathUtils.ceilingLog(BigInteger.valueOf(2), n).intValueExact()) ); } //2^7 - a @Override public @NotNull Iterable<Byte> rangeUp(byte a) { return map(i -> (byte) (i + a), randomInts(128 - a)); } //2^15 - a @Override public @NotNull Iterable<Short> rangeUp(short a) { return map(i -> (short) (i + a), randomInts(32768 - a)); } //2^31 - a @Override public @NotNull Iterable<Integer> rangeUp(int a) { return map(l -> (int) (l + a), randomLongs((1L << 31) - a)); } //2^63 - a @Override public @NotNull Iterable<Long> rangeUp(long a) { return map( i -> i.add(BigInteger.valueOf(a)).longValueExact(), randomBigIntegers(BigInteger.ONE.shiftLeft(63).subtract(BigInteger.valueOf(a))) ); } @Override public @NotNull Iterable<BigInteger> rangeUp(@NotNull BigInteger a) { return map(i -> i.add(a), naturalBigIntegers()); } //2^16 - a @Override public @NotNull Iterable<Character> rangeUp(char a) { return map(i -> (char) (i + a), randomInts(65536 - a)); } @Override public @NotNull Iterable<Byte> rangeDown(byte a) { return map(i -> (byte) (i - 128), randomInts(a + 129)); } @Override public @NotNull Iterable<Short> rangeDown(short a) { return map(i -> (short) (i - 32768), randomInts(a + 32769)); } @Override public @NotNull Iterable<Integer> rangeDown(int a) { return map(l -> (int) (l - (1L << 31)), randomLongs(a + (1L << 31) + 1)); } @Override public @NotNull Iterable<Long> rangeDown(long a) { return map( i -> i.subtract(BigInteger.ONE.shiftLeft(63)).longValueExact(), randomBigIntegers(BigInteger.valueOf(a).add(BigInteger.ONE).add(BigInteger.ONE.shiftLeft(63))) ); } @Override public @NotNull Iterable<BigInteger> rangeDown(@NotNull BigInteger a) { return map(i -> i.add(BigInteger.ONE).add(a), negativeBigIntegers()); } @Override public @NotNull Iterable<Character> rangeDown(char a) { return range('\0', a); } //b - a + 1 @Override public @NotNull Iterable<Byte> range(byte a, byte b) { if (a > b) return new ArrayList<>(); return map(i -> (byte) (i + a), randomInts((int) b - a + 1)); } //b - a + 1 @Override public @NotNull Iterable<Short> range(short a, short b) { if (a > b) return new ArrayList<>(); return map(i -> (short) (i + a), randomInts((int) b - a + 1)); } //b - a + 1 @Override public @NotNull Iterable<Integer> range(int a, int b) { if (a > b) return new ArrayList<>(); return map(i -> (int) (i + a), randomLongs(b - a + 1)); } //b - a + 1 public @NotNull Iterable<Long> range(long a, long b) { if (a > b) return new ArrayList<>(); return map( i -> i.add(BigInteger.valueOf(a)).longValueExact(), randomBigIntegers(BigInteger.valueOf(b).subtract(BigInteger.valueOf(a)).add(BigInteger.ONE)) ); } //b - a + 1 @Override public @NotNull Iterable<BigInteger> range(@NotNull BigInteger a, @NotNull BigInteger b) { if (Ordering.gt(a, b)) return new ArrayList<>(); return map(i -> i.add(a), randomBigIntegers(b.subtract(a).add(BigInteger.ONE))); } @Override public @NotNull Iterable<Character> range(char a, char b) { if (a > b) return new ArrayList<>(); return map(i -> (char) (i + a), randomInts(b - a + 1)); } public @NotNull <T> Iterable<T> uniformSample(@NotNull List<T> xs) { if (isEmpty(xs)) return new ArrayList<>(); return map(xs::get, range(0, xs.size() - 1)); } public @NotNull Iterable<Character> uniformSample(@NotNull String s) { if (s.isEmpty()) return new ArrayList<>(); return map(s::charAt, range(0, s.length() - 1)); } public @NotNull <T> Iterable<T> geometricSample(int meanIndex, @NotNull Iterable<T> xs) { if (isEmpty(xs)) return new ArrayList<>(); CachedIterable<T> cxs = new CachedIterable<>(xs); return map( NullableOptional::get, filter( NullableOptional::isPresent, (Iterable<NullableOptional<T>>) map(i -> cxs.get(i), naturalIntegersGeometric(meanIndex)) ) ); } /** * An <tt>Iterable</tt> that generates all positive <tt>Byte</tt>s from a uniform distribution. Does not support * removal. * * Length is infinite */ @Override public @NotNull Iterable<Byte> positiveBytes() { return () -> new Iterator<Byte>() { @Override public boolean hasNext() { return true; } @Override public Byte next() { return (byte) (generator.nextInt(Byte.MAX_VALUE) + 1); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * An <tt>Iterable</tt> that generates all positive <tt>Short</tt>s from a uniform distribution. Does not support * removal. * * Length is infinite */ @Override public @NotNull Iterable<Short> positiveShorts() { return () -> new Iterator<Short>() { @Override public boolean hasNext() { return true; } @Override public Short next() { return (short) (generator.nextInt(Short.MAX_VALUE) + 1); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * An <tt>Iterable</tt> that generates all positive <tt>Integer</tt>s from a uniform distribution. Does not support * removal. * * Length is infinite */ @Override public @NotNull Iterable<Integer> positiveIntegers() { return () -> new Iterator<Integer>() { @Override public boolean hasNext() { return true; } @Override public Integer next() { return generator.nextInt(Integer.MAX_VALUE) + 1; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * An <tt>Iterable</tt> that generates all positive <tt>Long</tt>s from a uniform distribution from a uniform * distribution. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<Long> positiveLongs() { return () -> new Iterator<Long>() { @Override public boolean hasNext() { return true; } @Override public Long next() { long next; do { next = Math.abs(generator.nextLong()); } while (next < 0); return next; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * @return An <tt>Iterable</tt> that generates all positive <tt>BigInteger</tt>s. The bit size is chosen from a * geometric distribution with mean approximately <tt>meanBitSize</tt> (The ratio between the actual mean and * <tt>meanBitSize</tt> decreases as <tt>meanBitSize</tt> increases). Does not support removal. * * <ul> * <li><tt>meanBitSize</tt> must be greater than 2.</li> * <li>The is an infinite pseudorandom sequence of all <tt>BigIntegers</tt></li> * </ul> * * Length is infinite */ public @NotNull Iterable<BigInteger> positiveBigIntegers() { if (bigIntegerMeanBitSize <= 2) throw new IllegalArgumentException("meanBitSize must be greater than 2."); return () -> new Iterator<BigInteger>() { @Override public boolean hasNext() { return true; } @Override public BigInteger next() { List<Boolean> bits = new ArrayList<>(); bits.add(true); while (true) { if (generator.nextDouble() < 1.0 / (bigIntegerMeanBitSize - 1)) { break; } else { bits.add(generator.nextBoolean()); } } return MathUtils.fromBigEndianBits(bits); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * An <tt>Iterable</tt> that generates all negative <tt>Byte</tt>s from a uniform distribution. Does not support * removal. * * Length is infinite */ @Override public @NotNull Iterable<Byte> negativeBytes() { return () -> new Iterator<Byte>() { @Override public boolean hasNext() { return true; } @Override public Byte next() { return (byte) (-1 - generator.nextInt(Byte.MAX_VALUE + 1)); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * An <tt>Iterable</tt> that generates all negative <tt>Short</tt>s from a uniform distribution. Does not support * removal. * * Length is infinite */ @Override public @NotNull Iterable<Short> negativeShorts() { return () -> new Iterator<Short>() { @Override public boolean hasNext() { return true; } @Override public Short next() { return (short) (-1 - generator.nextInt(Short.MAX_VALUE + 1)); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * An <tt>Iterable</tt> that generates all negative <tt>Integer</tt>s from a uniform distribution. Does not support * removal. * * Length is infinite */ @Override public @NotNull Iterable<Integer> negativeIntegers() { return filter(i -> i < 0, integers()); } /** * An <tt>Iterable</tt> that generates all negative <tt>Long</tt>s from a uniform distribution. Does not support * removal. * * Length is infinite */ @Override public @NotNull Iterable<Long> negativeLongs() { return filter(l -> l < 0, longs()); } /** * @return An <tt>Iterable</tt> that generates all negative <tt>BigInteger</tt>s. The bit size is chosen from a * geometric distribution with mean approximately <tt>meanBitSize</tt> (The ratio between the actual mean and * <tt>meanBitSize</tt> decreases as <tt>meanBitSize</tt> increases). Does not support removal. * * <ul> * <li><tt>meanBitSize</tt> must be greater than 2.</li> * <li>The result is an infinite pseudorandom sequence of all <tt>BigIntegers</tt>.</li> * </ul> * * Length is infinite */ @Override public @NotNull Iterable<BigInteger> negativeBigIntegers() { return map(BigInteger::negate, positiveBigIntegers()); } /** * An <tt>Iterable</tt> that generates all natural <tt>Byte</tt>s (including 0) from a uniform distribution. Does * not support removal. * * Length is infinite */ @Override public @NotNull Iterable<Byte> naturalBytes() { return map(Integer::byteValue, randomIntsPow2(7)); } /** * An <tt>Iterable</tt> that generates all natural <tt>Short</tt>s (including 0) from a uniform distribution. Does * not support removal. * * Length is infinite */ @Override public @NotNull Iterable<Short> naturalShorts() { return map(Integer::shortValue, randomIntsPow2(15)); } /** * An <tt>Iterable</tt> that generates all natural <tt>Integer</tt>s (including 0) from a uniform distribution. * Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<Integer> naturalIntegers() { return randomIntsPow2(31); } /** * An <tt>Iterable</tt> that generates all natural <tt>Long</tt>s (including 0) from a uniform distribution. Does * not support removal. * * Length is infinite */ @Override public @NotNull Iterable<Long> naturalLongs() { return randomLongsPow2(63); } /** * @return An <tt>Iterable</tt> that generates all natural <tt>BigInteger</tt>s (including 0). The bit size is * chosen from a geometric distribution with mean approximately <tt>meanBitSize</tt> (The ratio between the actual * mean and <tt>meanBitSize</tt> decreases as <tt>meanBitSize</tt> increases). Does not support removal. * * <ul> * <li><tt>meanBitSize</tt> must be greater than 2.</li> * <li>The result is an infinite pseudorandom sequence of all <tt>BigIntegers</tt>.</li> * </ul> * * Length is infinite */ @Override public @NotNull Iterable<BigInteger> naturalBigIntegers() { if (bigIntegerMeanBitSize <= 2) throw new IllegalArgumentException("meanBitSize must be greater than 2."); return () -> new Iterator<BigInteger>() { @Override public boolean hasNext() { return true; } @Override public BigInteger next() { List<Boolean> bits = new ArrayList<>(); while (true) { if (generator.nextDouble() < 1.0 / (bigIntegerMeanBitSize - 1)) { break; } else { bits.add(generator.nextBoolean()); } } return MathUtils.fromBigEndianBits(bits); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * An <tt>Iterable</tt> that generates all <tt>Byte</tt>s from a uniform distribution. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<Byte> bytes() { return map(Integer::byteValue, randomIntsPow2(8)); } /** * An <tt>Iterable</tt> that generates all <tt>Short</tt>s from a uniform distribution. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<Short> shorts() { return map(Integer::shortValue, randomIntsPow2(16)); } /** * An <tt>Iterable</tt> that generates all <tt>Integer</tt>s from a uniform distribution. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<Integer> integers() { return () -> new Iterator<Integer>() { @Override public boolean hasNext() { return true; } @Override public Integer next() { return generator.nextInt(); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * An <tt>Iterable</tt> that generates all <tt>Long</tt>s from a uniform distribution. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<Long> longs() { return () -> new Iterator<Long>() { @Override public boolean hasNext() { return true; } @Override public Long next() { return generator.nextLong(); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * @return An <tt>Iterable</tt> that generates all <tt>BigInteger</tt>s. The bit size is chosen from a geometric * distribution with mean approximately <tt>meanBitSize</tt> (The ratio between the actual mean and * <tt>meanBitSize</tt> decreases as <tt>meanBitSize</tt> increases). Does not support removal. * * <ul> * <li><tt>meanBitSize</tt> must be greater than 2.</li> * <li>The result is an infinite pseudorandom sequence of all <tt>BigIntegers</tt>.</li> * </ul> * * Length is infinite */ @Override public @NotNull Iterable<BigInteger> bigIntegers() { if (bigIntegerMeanBitSize <= 2) throw new IllegalArgumentException("meanBitSize must be greater than 2."); return () -> new Iterator<BigInteger>() { private final Iterator<BigInteger> it = naturalBigIntegers().iterator(); @Override public boolean hasNext() { return true; } @Override public BigInteger next() { BigInteger nbi = it.next(); if (generator.nextBoolean()) { nbi = nbi.negate().subtract(BigInteger.ONE); } return nbi; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * @return An <tt>Iterable</tt> that generates all natural <tt>Integer</tt>s chosen from a geometric distribution * with mean approximately <tt>meanSize</tt> (The ratio between the actual mean and <tt>meanSize</tt> decreases as * <tt>meanSize</tt> increases). Does not support removal. * * <ul> * <li><tt>meanSize</tt> must be greater than 1.</li> * <li>The result is an infinite pseudorandom sequence of all natural <tt>Integers</tt>.</li> * </ul> * * Length is infinite * * @param meanSize the approximate mean bit size of the <tt>Integer</tt>s generated */ public @NotNull Iterable<Integer> naturalIntegersGeometric(int meanSize) { if (meanSize <= 1) throw new IllegalArgumentException("meanSize must be greater than 1."); return () -> new Iterator<Integer>() { @Override public boolean hasNext() { return true; } @Override public Integer next() { int i = 0; while (generator.nextDouble() >= 1.0 / meanSize) { i++; } return i; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * @return An <tt>Iterable</tt> that generates all positive <tt>Integer</tt>s chosen from a geometric distribution * with mean approximately <tt>meanSize</tt> (The ratio between the actual mean and <tt>meanSize</tt> decreases as * <tt>meanSize</tt> increases). Does not support removal. * * <ul> * <li><tt>meanSize</tt> must be greater than 2.</li> * <li>The result is an infinite pseudorandom sequence of all positive <tt>Integers</tt>.</li> * </ul> * * Length is infinite * * @param meanSize the approximate mean size of the <tt>Integer</tt>s generated */ public @NotNull Iterable<Integer> positiveIntegersGeometric(int meanSize) { if (meanSize <= 2) throw new IllegalArgumentException("meanSize must be greater than 2."); return () -> new Iterator<Integer>() { @Override public boolean hasNext() { return true; } @Override public Integer next() { int i = 1; while (generator.nextDouble() >= 1.0 / (meanSize - 1)) { i++; } return i; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * @return An <tt>Iterable</tt> that generates all negative <tt>Integer</tt>s chosen from a geometric distribution * with absolute mean approximately <tt>meanSize</tt> (The ratio between the actual absolute mean and * <tt>meanSize</tt> decreases as <tt>meanSize</tt> increases). Does not support removal. * * <ul> * <li><tt>meanSize</tt> must be greater than 2.</li> * <li>The result is an infinite pseudorandom sequence of all negative <tt>Integers</tt>.</li> * </ul> * * Length is infinite * * @param meanSize the approximate absolute mean size of the <tt>Integer</tt>s generated */ public @NotNull Iterable<Integer> negativeIntegersGeometric(int meanSize) { return map(i -> -i, positiveIntegersGeometric(meanSize)); } /** * @return An <tt>Iterable</tt> that generates all <tt>Integer</tt>s chosen from a geometric distribution with * absolute mean approximately <tt>meanSize</tt> (The ratio between the actual absolute mean and <tt>meanSize</tt> * decreases as <tt>meanSize</tt> increases). Does not support removal. * * <ul> * <li><tt>meanSize</tt> must be greater than 1.</li> * <li>The result is an infinite pseudorandom sequence of all <tt>Integers</tt>.</li> * </ul> * * Length is infinite * * @param meanSize the approximate mean bit size of the <tt>Integer</tt>s generated */ public @NotNull Iterable<Integer> integersGeometric(int meanSize) { if (meanSize <= 1) throw new IllegalArgumentException("meanSize must be greater than 1."); return () -> new Iterator<Integer>() { private final Iterator<Integer> it = naturalIntegersGeometric(meanSize).iterator(); @Override public boolean hasNext() { return true; } @Override public Integer next() { Integer ni = it.next(); if (generator.nextBoolean()) { ni = -ni - 1; } return ni; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * An <tt>Iterable</tt> that generates all ASCII <tt>Character</tt>s from a uniform distribution. Does not support * removal. * * Length is infinite */ @Override public @NotNull Iterable<Character> asciiCharacters() { return map(i -> (char) (int) i, randomIntsPow2(7)); } /** * An <tt>Iterable</tt> that generates all <tt>Character</tt>s from a uniform distribution. Does not support * removal. * * Length is infinite */ @Override public @NotNull Iterable<Character> characters() { return map(i -> (char) (int) i, randomIntsPow2(16)); } /** * An <tt>Iterable</tt> that generates all ordinary (neither NaN nor infinite) positive floats from a uniform * distribution. Does not support removal. * * Length is infinite. */ @Override public @NotNull Iterable<Float> positiveOrdinaryFloats() { return map(Math::abs, filter( f -> Float.isFinite(f) && !Float.isNaN(f) && !f.equals(-0.0f) && !f.equals(0.0f), floats() )); } /** * @return An <tt>Iterable</tt> that generates all ordinary (neither NaN nor infinite) negative floats from a * uniform distribution. Negative zero is not included. Does not support removal. * * Length is infinite. */ @Override public @NotNull Iterable<Float> negativeOrdinaryFloats() { return map(f -> -f, positiveOrdinaryFloats()); } /** * An <tt>Iterable</tt> that generates all ordinary (neither NaN nor infinite) floats from a uniform distribution. * Does not support removal. * * Length is infinite. */ @Override public @NotNull Iterable<Float> ordinaryFloats() { return filter(f -> Float.isFinite(f) && !Float.isNaN(f) && !f.equals(-0.0f), floats()); } /** * An <tt>Iterable</tt> that generates all <tt>Float</tt>s from a uniform distribution. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<Float> floats() { return () -> new Iterator<Float>() { @Override public boolean hasNext() { return true; } @Override public Float next() { float next; boolean problematicNaN; do { int floatBits = generator.nextInt(); next = Float.intBitsToFloat(floatBits); problematicNaN = Float.isNaN(next) && floatBits != 0x7fc00000; } while (problematicNaN); return next; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } /** * An <tt>Iterable</tt> that generates all ordinary (neither NaN nor infinite) positive floats from a uniform * distribution. Does not support removal. * * Length is infinite. */ @Override public @NotNull Iterable<Double> positiveOrdinaryDoubles() { return map(Math::abs, filter( d -> Double.isFinite(d) && !Double.isNaN(d) && !d.equals(-0.0) && !d.equals(0.0), doubles() )); } /** * @return An <tt>Iterable</tt> that generates all ordinary (neither NaN nor infinite) negative floats from a * uniform distribution. Negative zero is not included. Does not support removal. * * Length is infinite. */ @Override public @NotNull Iterable<Double> negativeOrdinaryDoubles() { return map(d -> -d, positiveOrdinaryDoubles()); } /** * An <tt>Iterable</tt> that generates all ordinary (neither NaN nor infinite) floats from a uniform distribution. * Does not support removal. * * Length is infinite. */ @Override public @NotNull Iterable<Double> ordinaryDoubles() { return filter(d -> Double.isFinite(d) && !Double.isNaN(d) && !d.equals(-0.0), doubles()); } /** * An <tt>Iterable</tt> that generates all <tt>Double</tt>s from a uniform distribution. Does not support removal. * * Length is infinite */ @Override public @NotNull Iterable<Double> doubles() { return () -> new Iterator<Double>() { @Override public boolean hasNext() { return true; } @Override public Double next() { double next; boolean problematicNaN; do { long doubleBits = generator.nextLong(); next = Double.longBitsToDouble(doubleBits); problematicNaN = Double.isNaN(next) && doubleBits != 0x7ff8000000000000L; } while (problematicNaN); return next; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } @Override public @NotNull Iterable<BigDecimal> positiveBigDecimals() { return map( p -> new BigDecimal(p.a, p.b), pairs(negativeBigIntegers(), integersGeometric(bigDecimalMeanScale)) ); } @Override public @NotNull Iterable<BigDecimal> negativeBigDecimals() { return map( p -> new BigDecimal(p.a, p.b), pairs(negativeBigIntegers(), integersGeometric(bigDecimalMeanScale)) ); } @Override public @NotNull Iterable<BigDecimal> bigDecimals() { return map(p -> new BigDecimal(p.a, p.b), pairs(bigIntegers(), integersGeometric(bigDecimalMeanScale))); } public @NotNull <T> Iterable<T> addSpecialElement(@Nullable T x, @NotNull Iterable<T> xs) { return () -> new Iterator<T>() { private Iterator<T> xsi = xs.iterator(); private Iterator<Integer> specialSelector = randomInts(specialElementRatio).iterator(); boolean specialSelection = specialSelector.next() == 0; @Override public boolean hasNext() { return specialSelection || xsi.hasNext(); } @Override public T next() { boolean previousSelection = specialSelection; specialSelection = specialSelector.next() == 0; return previousSelection ? x : xsi.next(); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } @Override public @NotNull <T> Iterable<T> withNull(@NotNull Iterable<T> xs) { return addSpecialElement(null, xs); } @Override public @NotNull <T> Iterable<Optional<T>> optionals(@NotNull Iterable<T> xs) { return addSpecialElement(Optional.<T>empty(), map(Optional::of, xs)); } @Override public @NotNull <T> Iterable<NullableOptional<T>> nullableOptionals(@NotNull Iterable<T> xs) { return addSpecialElement(NullableOptional.<T>empty(), map(NullableOptional::of, xs)); } @Override public @NotNull <A, B> Iterable<Pair<A, B>> dependentPairs( @NotNull Iterable<A> xs, @NotNull Function<A, Iterable<B>> f ) { return Combinatorics.dependentPairs( xs, x -> geometricSample(meanListSize, f.apply(x)), (BigInteger i) -> { List<BigInteger> list = MathUtils.demux(2, i); return new Pair<>(list.get(0), list.get(1)); } ); } @Override public @NotNull <A, B> Iterable<Pair<A, B>> dependentPairsLogarithmic( @NotNull Iterable<A> xs, @NotNull Function<A, Iterable<B>> f ) { return Combinatorics.dependentPairs( xs, x -> geometricSample(meanListSize, f.apply(x)), MathUtils::logarithmicDemux ); } @Override public @NotNull <A, B> Iterable<Pair<A, B>> dependentPairsSquareRoot( @NotNull Iterable<A> xs, @NotNull Function<A, Iterable<B>> f ) { return Combinatorics.dependentPairs( xs, x -> geometricSample(meanListSize, f.apply(x)), MathUtils::squareRootDemux ); } @Override public @NotNull <A, B> Iterable<Pair<A, B>> dependentPairsExponential( @NotNull Iterable<A> xs, @NotNull Function<A, Iterable<B>> f ) { return Combinatorics.dependentPairs( xs, x -> geometricSample(meanListSize, f.apply(x)), i -> { Pair<BigInteger, BigInteger> p = MathUtils.logarithmicDemux(i); return new Pair<>(p.b, p.a); } ); } @Override public @NotNull <A, B> Iterable<Pair<A, B>> dependentPairsSquare( @NotNull Iterable<A> xs, @NotNull Function<A, Iterable<B>> f ) { return Combinatorics.dependentPairs( xs, x -> geometricSample(meanListSize, f.apply(x)), i -> { Pair<BigInteger, BigInteger> p = MathUtils.squareRootDemux(i); return new Pair<>(p.b, p.a); } ); } @Override public @NotNull <A, B> Iterable<Pair<A, B>> pairs(@NotNull Iterable<A> as, @NotNull Iterable<B> bs) { return zip(as, bs); } @Override public @NotNull <A, B, C> Iterable<Triple<A, B, C>> triples( @NotNull Iterable<A> as, @NotNull Iterable<B> bs, @NotNull Iterable<C> cs ) { return zip3(as, bs, cs); } @Override public @NotNull <A, B, C, D> Iterable<Quadruple<A, B, C, D>> quadruples( @NotNull Iterable<A> as, @NotNull Iterable<B> bs, @NotNull Iterable<C> cs, @NotNull Iterable<D> ds ) { return zip4(as, bs, cs, ds); } @Override public @NotNull <A, B, C, D, E> Iterable<Quintuple<A, B, C, D, E>> quintuples( @NotNull Iterable<A> as, @NotNull Iterable<B> bs, @NotNull Iterable<C> cs, @NotNull Iterable<D> ds, @NotNull Iterable<E> es ) { return zip5(as, bs, cs, ds, es); } @Override public @NotNull <A, B, C, D, E, F> Iterable<Sextuple<A, B, C, D, E, F>> sextuples( @NotNull Iterable<A> as, @NotNull Iterable<B> bs, @NotNull Iterable<C> cs, @NotNull Iterable<D> ds, @NotNull Iterable<E> es, @NotNull Iterable<F> fs ) { return zip6(as, bs, cs, ds, es, fs); } @Override public @NotNull <A, B, C, D, E, F, G> Iterable<Septuple<A, B, C, D, E, F, G>> septuples( @NotNull Iterable<A> as, @NotNull Iterable<B> bs, @NotNull Iterable<C> cs, @NotNull Iterable<D> ds, @NotNull Iterable<E> es, @NotNull Iterable<F> fs, @NotNull Iterable<G> gs ) { return zip7(as, bs, cs, ds, es, fs, gs); } @Override public @NotNull <T> Iterable<Pair<T, T>> pairs(@NotNull Iterable<T> xs) { List<Iterable<T>> xss = demux(2, xs); return zip(xss.get(0), xss.get(1)); } @Override public @NotNull <T> Iterable<Triple<T, T, T>> triples(@NotNull Iterable<T> xs) { List<Iterable<T>> xss = demux(3, xs); return zip3(xss.get(0), xss.get(1), xss.get(2)); } @Override public @NotNull <T> Iterable<Quadruple<T, T, T, T>> quadruples(@NotNull Iterable<T> xs) { List<Iterable<T>> xss = demux(4, xs); return zip4(xss.get(0), xss.get(1), xss.get(2), xss.get(3)); } @Override public @NotNull <T> Iterable<Quintuple<T, T, T, T, T>> quintuples(@NotNull Iterable<T> xs) { List<Iterable<T>> xss = demux(5, xs); return zip5(xss.get(0), xss.get(1), xss.get(2), xss.get(3), xss.get(4)); } @Override public @NotNull <T> Iterable<Sextuple<T, T, T, T, T, T>> sextuples(@NotNull Iterable<T> xs) { List<Iterable<T>> xss = demux(6, xs); return zip6(xss.get(0), xss.get(1), xss.get(2), xss.get(3), xss.get(4), xss.get(5)); } @Override public @NotNull <T> Iterable<Septuple<T, T, T, T, T, T, T>> septuples(@NotNull Iterable<T> xs) { List<Iterable<T>> xss = demux(7, xs); return zip7(xss.get(0), xss.get(1), xss.get(2), xss.get(3), xss.get(4), xss.get(5), xss.get(6)); } @Override public @NotNull <T> Iterable<List<T>> lists(int size, @NotNull Iterable<T> xs) { return transpose(demux(size, xs)); } @Override public @NotNull <T> Iterable<List<T>> listsAtLeast(int minSize, @NotNull Iterable<T> xs) { if (isEmpty(xs)) return Arrays.asList(new ArrayList<T>()); return () -> new Iterator<List<T>>() { private final Iterator<T> xsi = cycle(xs).iterator(); private final Iterator<Integer> sizes = naturalIntegersGeometric(meanListSize).iterator(); @Override public boolean hasNext() { return true; } @Override public List<T> next() { int size = sizes.next() + minSize; List<T> list = new ArrayList<>(); for (int i = 0; i < size; i++) { list.add(xsi.next()); } return list; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } @Override public @NotNull <T> Iterable<List<T>> lists(@NotNull Iterable<T> xs) { if (isEmpty(xs)) return Arrays.asList(new ArrayList<T>()); return () -> new Iterator<List<T>>() { private final Iterator<T> xsi = cycle(xs).iterator(); private final Iterator<Integer> sizes = naturalIntegersGeometric(meanListSize).iterator(); @Override public boolean hasNext() { return true; } @Override public List<T> next() { int size = sizes.next(); List<T> list = new ArrayList<>(); for (int i = 0; i < size; i++) { list.add(xsi.next()); } return list; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } @Override public @NotNull Iterable<String> strings(int size, @NotNull Iterable<Character> cs) { return map(IterableUtils::charsToString, transpose(demux(size, cs))); } @Override public @NotNull Iterable<String> stringsAtLeast(int minSize, @NotNull Iterable<Character> cs) { if (isEmpty(cs)) return Arrays.asList(""); return () -> new Iterator<String>() { private final Iterator<Character> csi = cycle(cs).iterator(); private final Iterator<Integer> sizes = naturalIntegersGeometric(meanListSize).iterator(); @Override public boolean hasNext() { return true; } @Override public String next() { int size = sizes.next() + minSize; StringBuilder sb = new StringBuilder(); for (int i = 0; i < size; i++) { sb.append(csi.next()); } return sb.toString(); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } @Override public @NotNull Iterable<String> strings(int size) { return strings(size, characters()); } @Override public @NotNull Iterable<String> stringsAtLeast(int minSize) { return stringsAtLeast(minSize, characters()); } @Override public @NotNull Iterable<String> strings(@NotNull Iterable<Character> cs) { if (isEmpty(cs)) return Arrays.asList(""); return () -> new Iterator<String>() { private final Iterator<Character> csi = cycle(cs).iterator(); private final Iterator<Integer> sizes = naturalIntegersGeometric(meanListSize).iterator(); @Override public boolean hasNext() { return true; } @Override public String next() { int size = sizes.next(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < size; i++) { sb.append(csi.next()); } return sb.toString(); } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; } @Override public @NotNull Iterable<String> strings() { return strings(characters()); } }
package mpei.bkm.protegeplugin.menu; import mpei.bkm.converters.UnconvertableException; import mpei.bkm.converters.text2scheme.Text2SchemeContainerConverter; import mpei.bkm.model.lss.Attribute; import mpei.bkm.model.lss.datatypespecification.datatypes.*; import mpei.bkm.model.lss.objectspecification.concept.BKMClass; import mpei.bkm.model.lss.objectspecification.concept.BinaryLink; import mpei.bkm.model.lss.objectspecification.concept.Concept; import mpei.bkm.model.lss.objectspecification.concepttypes.BKMClassType; import mpei.bkm.model.lss.objectspecification.concepttypes.ConceptType; import mpei.bkm.model.lss.objectspecification.concepttypes.UnionConceptType; import mpei.bkm.model.lss.objectspecification.intervalrestrictions.AtomRestriction; import mpei.bkm.model.lss.objectspecification.intervalrestrictions.number.*; import mpei.bkm.parsing.structurescheme.SchemeContainer; import org.protege.editor.core.ui.util.UIUtil; import org.protege.editor.owl.OWLEditorKit; import org.protege.editor.owl.model.event.EventType; import org.protege.editor.owl.ui.action.ProtegeOWLAction; import org.semanticweb.owlapi.model.*; import uk.ac.manchester.cs.owl.owlapi.*; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.*; public class BKMMenu extends ProtegeOWLAction { private static final long serialVersionUID = 2452385628012488946L; private OWLEditorKit editorKit; public void initialise() throws Exception { editorKit = getOWLEditorKit(); } public void dispose() throws Exception { } static Map<PrimitiveDataType.PRIMITIVEDATATYPE,IRI> bkmPrimitiveMap = new HashMap<PrimitiveDataType.PRIMITIVEDATATYPE, IRI>(); static { bkmPrimitiveMap.put(PrimitiveDataType.PRIMITIVEDATATYPE.String,IRI.create("http://www.w3.org/2001/XMLSchema#string")); bkmPrimitiveMap.put(PrimitiveDataType.PRIMITIVEDATATYPE.Integer,IRI.create("http://www.w3.org/2001/XMLSchema#integer")); bkmPrimitiveMap.put(PrimitiveDataType.PRIMITIVEDATATYPE.Boolean,IRI.create("http://www.w3.org/2001/XMLSchema#boolean")); bkmPrimitiveMap.put(PrimitiveDataType.PRIMITIVEDATATYPE.Number,IRI.create("http://www.w3.org/2001/XMLSchema#float")); bkmPrimitiveMap.put(PrimitiveDataType.PRIMITIVEDATATYPE.Char,IRI.create("http://www.w3.org/2001/XMLSchema#string")); } public void loadIntoOntology(OWLOntology owlOntology, SchemeContainer schemeContainer) { List<OWLClass> owlClassList = new ArrayList<OWLClass>(); List<OWLAxiom> owlAxioms = new ArrayList<OWLAxiom>(); Map<OWLObjectProperty,String> classRangesToAdd = new HashMap<OWLObjectProperty, String>(); Map<OWLObjectProperty,List<String>> unionClasses = new HashMap<OWLObjectProperty, List<String>>(); Map<String, OWLClass> nameClassMapping = new HashMap<String, OWLClass>(); Map<OWLClass, List> exactRestrictions = new HashMap<OWLClass,List>(); Set<List> linkIntervalRestrictions = new HashSet<List>(); for (Concept concept : schemeContainer.getScheme().getConceptSet()) { OWLClass owlClass = new OWLClassImpl(IRI.create("#" + concept.getName())); nameClassMapping.put(concept.getName(), owlClass); owlAxioms.add(new OWLDeclarationAxiomImpl( owlClass,Collections.EMPTY_SET )); owlClassList.add(owlClass); exactRestrictions.put(owlClass, new ArrayList()); if (concept instanceof BinaryLink) { BinaryLink link = (BinaryLink)concept; String leftName = link.getLeft().getConceptAttribute().getName(); OWLObjectProperty left = new OWLObjectPropertyImpl( IRI.create("#" + link.getName() + "_" + leftName) ); linkIntervalRestrictions.add(Arrays.asList(owlClass, left, link.getRestriction().getLeft(), leftName)); owlAxioms.add(new OWLDeclarationAxiomImpl(left,Collections.EMPTY_SET)); String rightName = link.getRight().getConceptAttribute().getName(); OWLObjectProperty right = new OWLObjectPropertyImpl( IRI.create("#" + link.getName() + "_" + rightName) ); owlAxioms.add(new OWLDeclarationAxiomImpl(right, Collections.EMPTY_SET)); owlAxioms.add(new OWLObjectPropertyDomainAxiomImpl( left, owlClass, Collections.EMPTY_SET)); owlAxioms.add(new OWLObjectPropertyDomainAxiomImpl( right, owlClass, Collections.EMPTY_SET)); linkIntervalRestrictions.add(Arrays.asList(owlClass, right, link.getRestriction().getRight(), rightName)); } for (Attribute attribute : concept.getAttributes()) { if (attribute.getType() instanceof DataType) { OWLDataProperty owlProperty = new OWLDataPropertyImpl( IRI.create("#" + concept.getName() + "_" + attribute.getName()) ); owlAxioms.add(new OWLDeclarationAxiomImpl( owlProperty,Collections.EMPTY_SET )); owlAxioms.add(new OWLDataPropertyDomainAxiomImpl( owlProperty, owlClass, Collections.EMPTY_SET)); if (attribute.getType() instanceof PrimitiveDataType) { PrimitiveDataType.PRIMITIVEDATATYPE t = ((PrimitiveDataType) attribute.getType()).getType(); OWLDatatype type = new OWLDatatypeImpl(bkmPrimitiveMap.get(t)); owlAxioms.add(new OWLDataPropertyRangeAxiomImpl( owlProperty, type, Collections.EMPTY_SET)); exactRestrictions.get(owlClass).addAll(Arrays.asList(owlProperty, type)); } if (attribute.getType() instanceof StarDataType && ((StarDataType) attribute.getType()).getType() instanceof PrimitiveDataType) { PrimitiveDataType.PRIMITIVEDATATYPE t = ((PrimitiveDataType)((StarDataType) attribute.getType()).getType()).getType(); OWLDatatype type = new OWLDatatypeImpl(bkmPrimitiveMap.get(t)); owlAxioms.add(new OWLDataPropertyRangeAxiomImpl( owlProperty, type, Collections.EMPTY_SET)); } if (attribute.getType() instanceof EnumType) { Set<OWLLiteral> enums = new HashSet<OWLLiteral>(); OWLDatatype stringType = new OWLDatatypeImpl(bkmPrimitiveMap.get(PrimitiveDataType.PRIMITIVEDATATYPE.String)); for (String value : ((EnumType) attribute.getType()).getValues()) { enums.add(new OWLLiteralImpl(value,null,stringType)); } owlAxioms.add(new OWLDataPropertyRangeAxiomImpl( owlProperty, new OWLDataOneOfImpl(enums), Collections.EMPTY_SET)); } if (attribute.getType() instanceof UnionDataType) { DataType leftDataType = ((UnionDataType) attribute.getType()).getLeft(); DataType rightDataType = ((UnionDataType) attribute.getType()).getRight(); if (leftDataType instanceof PrimitiveDataType && rightDataType instanceof PrimitiveDataType) { PrimitiveDataType.PRIMITIVEDATATYPE left = ((PrimitiveDataType) leftDataType).getType(); PrimitiveDataType.PRIMITIVEDATATYPE right = ((PrimitiveDataType) rightDataType).getType(); OWLDataUnionOf owlDataUnionOf = new OWLDataUnionOfImpl( new HashSet<OWLDataRange>(Arrays.asList( new OWLDatatypeImpl(bkmPrimitiveMap.get(left)), new OWLDatatypeImpl(bkmPrimitiveMap.get(right))) )); owlAxioms.add(new OWLDataPropertyRangeAxiomImpl( owlProperty, owlDataUnionOf, Collections.EMPTY_SET)); } } } if (attribute.getType() instanceof ConceptType) { OWLObjectProperty owlProperty = new OWLObjectPropertyImpl( IRI.create("#" + concept.getName() + "_" + attribute.getName()) ); owlAxioms.add(new OWLDeclarationAxiomImpl( owlProperty, Collections.EMPTY_SET )); owlAxioms.add(new OWLObjectPropertyDomainAxiomImpl( owlProperty, owlClass, Collections.EMPTY_SET)); if (attribute.getType() instanceof BKMClassType) { classRangesToAdd.put(owlProperty, ((BKMClassType) attribute.getType()).getBKMClass().getName()); exactRestrictions.get(owlClass).addAll(Arrays.asList(owlProperty, ((BKMClassType) attribute.getType()).getBKMClass().getName())); } if (attribute.getType() instanceof UnionConceptType) { ConceptType leftConceptType = ((UnionConceptType) attribute.getType()).getLeft(); ConceptType rightConceptType = ((UnionConceptType) attribute.getType()).getRight(); if (leftConceptType instanceof BKMClassType && rightConceptType instanceof BKMClassType) { unionClasses.put(owlProperty, Arrays.asList( ((BKMClassType) leftConceptType).getBKMClass().getName(), ((BKMClassType) rightConceptType).getBKMClass().getName()) ); } } } } } owlAxioms.add(new OWLDisjointClassesAxiomImpl(new HashSet<OWLClassExpression>(owlClassList),Collections.EMPTY_SET)); for (BKMClass bkmClass : schemeContainer.getCollections().allDeclaredBKMClasses) { OWLClass subOwlClass = nameClassMapping.get(bkmClass); if (bkmClass.getIsa() != null) { OWLClass superOwlClass = nameClassMapping.get(bkmClass.getIsa().getName()); owlAxioms.add(new OWLSubClassOfAxiomImpl(subOwlClass,superOwlClass,Collections.EMPTY_SET)); } } for (Map.Entry<OWLObjectProperty, String> e : classRangesToAdd.entrySet()) { OWLClass owlClass = nameClassMapping.get(e.getValue()); if (owlClass != null && owlClass.getIRI().getFragment().equals(e.getValue())) { owlAxioms.add(new OWLObjectPropertyRangeAxiomImpl( e.getKey(), owlClass, Collections.EMPTY_SET)); } } E: for(Map.Entry<OWLClass,List> e: exactRestrictions.entrySet()) { if (e.getValue().size() < 2) { continue; } Set<OWLClassExpression> equiProps = new HashSet<OWLClassExpression>(); equiProps.add(e.getKey()); Set<OWLClassExpression> propertyCardinalities = new HashSet<OWLClassExpression>(); for (int i = 0; i <= (e.getValue()).size() / 2; i+=2) { // i: property // i + 1:class name if (e.getValue().get(i+1) instanceof String) { OWLObjectProperty ope = (OWLObjectProperty) e.getValue().get(i); OWLClass owlClass = nameClassMapping.get(e.getValue().get(i+1)); if (owlClass == null) { continue E; } propertyCardinalities.add(new OWLObjectExactCardinalityImpl(ope, 1, owlClass)); } else { OWLDataProperty ope = (OWLDataProperty) e.getValue().get(i); OWLDatatype type = (OWLDatatype) e.getValue().get(i + 1); propertyCardinalities.add(new OWLDataExactCardinalityImpl(ope, 1, type)); } } equiProps.add(new OWLObjectIntersectionOfImpl(propertyCardinalities)); owlAxioms.add(new OWLEquivalentClassesAxiomImpl(equiProps, Collections.EMPTY_SET)); } for(List e: linkIntervalRestrictions) { if (e.size() < 4) continue; // 0: owl class (BKM link) // 1: property // 2: BKM Interval restriction // 3: class name Set<OWLClassExpression> equiProps = new HashSet<OWLClassExpression>(); equiProps.add((OWLClassExpression) e.get(0)); Set<OWLClassExpression> propertyCardinalities = new HashSet<OWLClassExpression>(); OWLObjectProperty ope = (OWLObjectProperty) e.get(1); OWLClass owlClass = nameClassMapping.get(e.get(3)); if (owlClass == null) continue; AtomRestriction atomRestriction = (AtomRestriction) e.get(2); Integer min = null, max = null; if (atomRestriction instanceof IntervalAtomRestriction) { min = ((IntervalAtomRestriction)atomRestriction).getFrom(); max = ((IntervalAtomRestriction)atomRestriction).getTo(); } else if (atomRestriction instanceof GTAtomRestriction) { min = ((GTAtomRestriction)atomRestriction).getValue() + 1; } else if (atomRestriction instanceof GEAtomRestriction) { min = ((GEAtomRestriction)atomRestriction).getValue(); } else if (atomRestriction instanceof LTAtomRestriction) { max = ((LTAtomRestriction)atomRestriction).getValue() - 1; } else if (atomRestriction instanceof LEAtomRestriction) { max = ((LEAtomRestriction)atomRestriction).getValue(); } else if (atomRestriction instanceof EQAtomRestriction) { Integer exact = ((EQAtomRestriction)atomRestriction).getValue(); propertyCardinalities.add(new OWLObjectExactCardinalityImpl(ope, exact, owlClass)); } if (min != null) { propertyCardinalities.add(new OWLObjectMinCardinalityImpl(ope, min, owlClass)); } if (max != null) { propertyCardinalities.add(new OWLObjectMaxCardinalityImpl(ope, max, owlClass)); } if (propertyCardinalities.size() > 0) { equiProps.addAll(propertyCardinalities); owlAxioms.add(new OWLEquivalentClassesAxiomImpl(equiProps, Collections.EMPTY_SET)); } } U: for (Map.Entry<OWLObjectProperty, List<String>> e : unionClasses.entrySet()) { Set<OWLClass> unionOfOWLClasses = new HashSet<OWLClass>(); for (String bkmClassName : e.getValue()) { OWLClass owlClass = nameClassMapping.get(bkmClassName); if (owlClass == null) continue U; unionOfOWLClasses.add(owlClass); } OWLObjectUnionOf owlObjectUnionOf = new OWLObjectUnionOfImpl(unionOfOWLClasses); owlAxioms.add(new OWLObjectPropertyRangeAxiomImpl( (OWLObjectPropertyExpression) e.getKey(), owlObjectUnionOf, Collections.EMPTY_SET )); } for (OWLAxiom owlAxiom : owlAxioms) { getOWLModelManager().applyChange(new AddAxiom(owlOntology,owlAxiom)); } getOWLModelManager().fireEvent(EventType.ONTOLOGY_CREATED); getOWLModelManager().fireEvent(EventType.ACTIVE_ONTOLOGY_CHANGED); } public void actionPerformed(ActionEvent arg0) { try { //getOWLModelManager().setLoadErrorHandler(); File file = UIUtil.openFile(new JDialog(), "Open BKM file", "Open BKM file", new HashSet<String>(Arrays.asList("bkm"))); if (file != null) { try { translateBKMFile(file); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { } } private void translateBKMFile(File file) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(file)); String line; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } Text2SchemeContainerConverter converter = new Text2SchemeContainerConverter(); SchemeContainer schemeContainer = converter.convert(sb.toString()); String errors = null; String incompleteness = null; if (converter.getErrors().size() > 0) { errors = "Found errors:\n" + String.join("\n", converter.getErrors()); } if (converter.getIncompleteness().size() > 0) { incompleteness = "Found incompleteness:\n" + String.join("\n", converter.getIncompleteness()); } if (errors != null || incompleteness != null) { if (errors == null) { errors = incompleteness; } else if (incompleteness != null) { errors += incompleteness; } errors += "\nTry to convert to OWL anyway?"; String[] options = {"Yes", "No"}; int continueAnswer = JOptionPane.showOptionDialog(new JDialog(), errors, "Errors and incompleteness", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1] ); if (continueAnswer == JOptionPane.NO_OPTION) { return; } } IRI filiIRI = IRI.create(("http: System.getProperty("user.name") + "/" + schemeContainer.getScheme().getName()).replace(" ", "_")); OWLOntologyID bkm2OWLOntologyID = new OWLOntologyID(filiIRI); for (OWLOntology owlOntology : getOWLModelManager().getOntologies()) { if (bkm2OWLOntologyID.equals(owlOntology.getOntologyID())) { getOWLModelManager().removeOntology(owlOntology); } } OWLOntology owlOntology = getOWLModelManager().createNewOntology( bkm2OWLOntologyID, filiIRI.toURI()); loadIntoOntology(owlOntology, schemeContainer); } catch (IOException e) { JOptionPane.showMessageDialog(new JDialog(), e.getMessage(), "Error when reading BKM file.", JOptionPane.ERROR_MESSAGE); } catch (UnconvertableException e) { JOptionPane.showMessageDialog(new JDialog(), e.getMessage(), "Error when translating BKM file.", JOptionPane.ERROR_MESSAGE); } catch (OWLOntologyCreationException e) { JOptionPane.showMessageDialog(new JDialog(), e.getMessage(), "Error when creating OWL ontology from BKM file.", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(new JDialog(), "Unknown error when reading BKM file.", "Error when reading BKM file.", JOptionPane.ERROR_MESSAGE); } /* final OWLOntology currentOntology = getOWLModelManager().getActiveOntology(); final OWLWorkspace editorWindow = editorKit.getOWLWorkspace(); JDialog cellfieDialog = WorkspacePanel.createDialog(currentOntology, workbookPath, editorKit, dialogManager); cellfieDialog.setLocationRelativeTo(editorWindow); cellfieDialog.setVisible(true); */ } }
package net.darkhax.bookshelf.lib; import java.util.Random; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public final class Constants { // Mod Constants public static final String MOD_ID = "bookshelf"; public static final String MOD_NAME = "Bookshelf"; public static final String VERSION_NUMBER = "1.4.4.0"; public static final String PROXY_CLIENT = "net.darkhax.bookshelf.client.ProxyClient"; public static final String PROXY_COMMON = "net.darkhax.bookshelf.common.ProxyCommon"; // System Constants public static final Logger LOG = LogManager.getLogger(MOD_NAME); public static final Random RANDOM = new Random(); public static final String NEW_LINE = System.getProperty("line.separator"); /** * Utility classes, such as this one, are not meant to be instantiated. Java adds an * implicit public constructor to every class which does not define at lease one * explicitly. Hence why this constructor was added. */ private Constants () { throw new IllegalAccessError("Utility class"); } }
package net.shadowfacts.foodies.item; import cpw.mods.fml.common.registry.GameRegistry; /** * Helper class for registering items. * @author shadowfacts */ public class FItems { // Foods public static Food toast; public static Food tomato; public static void preInit() { // Create Items toast = new Food(7, 0.7f).setUnlocalizedName("foodToast").setTextureName("foodToast"); tomato = new Food(1, 0.1f).setUnlocalizedName("fruitTomato").setTextureName("fruitTomato"); // Register items GameRegistry.registerItem(toast, "foodToast"); GameRegistry.registerItem(tomato, "fruitTomato"); } public static void load() { } public static void postInit() { } }
package ohtuhatut.profile; import java.net.URI; import java.net.URISyntaxException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import javax.sql.DataSource; import ohtuhatut.repository.ReferenceListRepository; import ohtuhatut.repository.ReferenceRepository; import org.apache.commons.dbcp.BasicDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Profile; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaDialect; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; @Configuration @Profile("production") public class ProductionProfile { @Autowired private ReferenceListRepository referenceListRepository; @Autowired private ReferenceRepository referenceRepository; @Bean @Primary @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { return DataSourceBuilder.create().build(); } @Bean @Primary public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws URISyntaxException { LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setJpaDialect(new HibernateJpaDialect()); HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setGenerateDdl(true); factory.setJpaVendorAdapter(vendorAdapter); factory.setPersistenceUnitName("production"); factory.setPackagesToScan("ohtuhatut.domain"); factory.afterPropertiesSet(); return factory; } /* private static Connection getConnection() throws URISyntaxException, SQLException { URI dbUri = new URI(System.getenv("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath(); return DriverManager.getConnection(dbUrl, username, password); } */ /* @Bean public PlatformTransactionManager transactionManager() throws URISyntaxException { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); return transactionManager; } @Bean public DataSource dataSource() throws URISyntaxException { URI dbUri = new URI(System.getenv("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath(); BasicDataSource basicDataSource = new BasicDataSource(); basicDataSource.setDriverClassName("org.postgresql.Driver"); basicDataSource.setUrl(dbUrl); basicDataSource.setUsername(username); basicDataSource.setPassword(password); return basicDataSource; } */ }
package org.arrah.framework.ndtable; /* * This is a util for Report Table Model class * it will define join, sort or match condition * for RTM class * */ import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Vector; import net.sourceforge.openforecast.DataSet; import org.apache.lucene.document.Document; import org.apache.lucene.search.Query; import org.arrah.framework.analytics.FuzzyVector; import org.arrah.framework.dataquality.SimilarityCheckLucene; import org.arrah.framework.dataquality.SimilarityCheckLucene.Hits; import org.arrah.framework.rdbms.DataDictionaryPDF; import org.jfree.data.time.Day; import org.jfree.data.time.Hour; import org.jfree.data.time.Millisecond; import org.jfree.data.time.Minute; import org.jfree.data.time.Month; import org.jfree.data.time.Quarter; import org.jfree.data.time.Second; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.Week; import org.jfree.data.time.Year; import org.jfree.data.xy.XYSeries; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; public class RTMUtil { /* * It will join two tables based on two column Indexes based on fuzzy logic */ public static ReportTableModel joinTables(ReportTableModel leftT, int indexL, ReportTableModel rightT, int indexR, int joinType, float distance) { Vector<Object> lvc = new Vector<Object>(); Vector<Object> rvc = new Vector<Object>(); int lrow_c = leftT.getModel().getRowCount(); int rrow_c = rightT.getModel().getRowCount(); for (int i = 0; i < lrow_c; i++) { lvc.addElement(leftT.getModel().getValueAt(i, indexL)); } for (int i = 0; i < rrow_c; i++) { rvc.addElement(rightT.getModel().getValueAt(i, indexR)); } int rcolc = rightT.getModel().getColumnCount(); int lcolc = leftT.getModel().getColumnCount(); for (int i = 0; (i < rcolc); i++) { // For left outer joint first create it if (i == indexR) continue; leftT.addColumn(rightT.getModel().getColumnName(i)); } // Need Fuzzy Vector FuzzyVector fz = null; if (joinType == 4 || joinType == 5 || joinType == 6) { fz = new FuzzyVector(rvc); } switch (joinType) { case 0: case 4: // (Fuzzy) Left Outer Join with Cardinality 1:1 is default for (int i = 0; i < lrow_c; i++) { int i_find = -1; //initialized if (joinType == 4) i_find = fz.indexOf(lvc.get(i),distance,0); else i_find = rvc.indexOf(lvc.get(i)); if (i_find != -1) { int curC = lcolc; for (int j = 0; (j < rcolc); j++) { if (j == indexR) // Skip matching index continue; leftT.getModel().setValueAt( rightT.getModel().getValueAt(i_find, j), i, curC++); } } } return leftT; case 1: case 5:// (Fuzzy) Inner Join with Cardinality 1:1 is default Vector<Integer> markdel = new Vector<Integer>(); for (int i = 0; i < lrow_c; i++) { int i_find = -1; //initialized if (joinType == 5) i_find = fz.indexOf(lvc.get(i),distance,0); else i_find = rvc.indexOf(lvc.get(i)); if (i_find != -1) { int curC = lcolc; for (int j = 0; (j < rcolc); j++) { if (j == indexR) // Skip matching index continue; leftT.getModel().setValueAt( rightT.getModel().getValueAt(i_find, j), i, curC++); } } else { markdel.add(i); // should be deleted for inner join } } // left outer join completed // Now delete what is mark for deleted leftT.removeMarkedRows(markdel); return leftT; case 2: case 6:// (Fuzzy) Diff Join Vector<Integer> markdel_d = new Vector<Integer>(); for (int i = 0; i < lrow_c; i++) { int i_find = -1; //initialized if (joinType == 6) i_find = fz.indexOf(lvc.get(i),distance,0); else i_find = rvc.indexOf(lvc.get(i)); if (i_find != -1) { markdel_d.add(i); // should be deleted for diff join } } // left outer join completed // Now delete what is mark for deleted leftT.removeMarkedRows(markdel_d); return leftT; case 3: // Cartesian Join for (int i = 0; i < lrow_c; i++) { int i_find = 0; // Start from index 0 Vector<Integer> foundR = new Vector<Integer>(); boolean firstrec = false; Object o_l = leftT.getModel().getValueAt(i, indexL); while ( (i_find = (rvc.indexOf(o_l,i_find))) != -1) { foundR.add(i_find); i_find++; } for (int fIndex : foundR) { int curC = lcolc; if (firstrec == false) { for (int j = 0; (j < rcolc); j++) { if (j == indexR) // Skip matching index continue; leftT.getModel().setValueAt( rightT.getModel().getValueAt(fIndex, j), i, curC++); } firstrec = true; } else { // now Cartesian so add rows Object[] cartRow = leftT.getRow(i); i++; // increase the index and row count leftT.getModel().insertRow(i, cartRow); lrow_c++; for (int j = 0; (j < rcolc); j++) { if (j == indexR) // Skip matching index continue; leftT.getModel().setValueAt( rightT.getModel().getValueAt(fIndex, j), i, curC++); } } } // Cartesian row loop } // Inner loop for Cartesian return leftT; default : break; } return leftT; } // This function will return Hashtable with Lookup information public static Hashtable<Object,Object> lookupInfo( ReportTableModel rightT, int indexR, int indexInfo) { Hashtable<Object,Object> lookup = new Hashtable<Object,Object>(); int rrow_c = rightT.getModel().getRowCount(); for (int i = 0; i < rrow_c; i++) { Object key = rightT.getModel().getValueAt(i, indexR); Object value = rightT.getModel().getValueAt(i, indexInfo); if (key != null && value != null) lookup.put(key, value); } return lookup; } // This function will return Hashtable with with key and rowno id public static Hashtable<Object,Object> lookupIndex( ReportTableModel rightT, int indexR) { Hashtable<Object,Object> lookup = new Hashtable<Object,Object>(); int rrow_c = rightT.getModel().getRowCount(); for (int i = 0; i < rrow_c; i++) { Object key = rightT.getModel().getValueAt(i, indexR); if (key != null ) lookup.put(key, i); } return lookup; } /* * It will look for the conditions in table based on column Index. Int will * tell what types of condition (<, >, = , Like% etc) it is looking for. * condV will have the value of the condition if any. */ public static Vector<Integer> matchCondition(ReportTableModel _rt, int colI, int cond, String condV) { if (_rt == null) { System.out.println("\n ERROR:Table not Set for Filtering"); return null; } int rowC = _rt.getModel().getRowCount(); if (colI < 0) return null; // Column not found if (cond < 2) return null; // No condition is chosen Vector<Integer> result_v = new Vector<Integer>(); for (int i = 0; i < rowC; i++) { switch (cond) { case 2: // Null Object obj = _rt.getModel().getValueAt(i, colI); if (obj == null) result_v.add(i); break; case 3: // Not Null obj = _rt.getModel().getValueAt(i, colI); if (obj != null) result_v.add(i); break; case 4: // Like case 5: // Not Like boolean found = false; obj = _rt.getModel().getValueAt(i, colI); if (obj == null || condV == null || "".equals(condV)) break; if ((condV.startsWith("\'")) && condV.endsWith("\'")) { if ((condV.length() - 1) > 0) condV = condV.substring(1, condV.length() - 1); } if ((condV.startsWith("%")) && condV.endsWith("%")) { if (condV.length() == 1) // show all if only % found = true; else { String condV_s = condV.substring(1, condV.length() - 1); found = obj.toString().contains(condV_s); } } else if (condV.startsWith("%")) { String condV_s = condV.substring(1, condV.length()); found = obj.toString().endsWith(condV_s); } else if (condV.endsWith("%")) { String condV_s = condV.substring(0, condV.length() - 1); found = obj.toString().startsWith(condV_s); } else found = obj.toString().contains(condV); if (cond == 4 && found == true) result_v.add(i); if (cond == 5 && found == false) result_v.add(i); break; case 6: // Equal to case 7: // Not Equal to case 8: // greater than > case 9: // Greater than equal to >= case 10: // less than < case 11: // less than equal to <= found = false; obj = _rt.getModel().getValueAt(i, colI); if (obj == null || condV == null || "".equals(condV)) break; if ((condV.startsWith("\'")) && condV.endsWith("\'")) { if ((condV.length() - 1) > 0) condV = condV.substring(1, condV.length() - 1); } if (obj instanceof Date) { SimpleDateFormat simpledateformat = new SimpleDateFormat( "dd/MM/yyyy hh:mm:ss"); simpledateformat.setLenient(true); Date date = simpledateformat.parse(condV, new ParsePosition(0)); if (date == null) { System.out.println("\n ERROR:Could not Parse " + condV + " for Date object"); System.out .println("\n Date Format is dd/MM/yyyy hh:mm:ss"); return null; } if (cond == 6) found = (date.compareTo((Date) obj) == 0) ? true : false; else if (cond == 7) found = (date.compareTo((Date) obj) != 0) ? true : false; else if (cond == 8) found = (date.compareTo((Date) obj) > 0) ? true : false; else if (cond == 9) found = (date.compareTo((Date) obj) >= 0) ? true : false; else if (cond == 10) found = (date.compareTo((Date) obj) < 0) ? true : false; else if (cond == 10) found = (date.compareTo((Date) obj) <= 0) ? true : false; } else if (obj instanceof Number) { try { Double num = Double.parseDouble(condV); if (cond == 6) found = (((Number) obj).doubleValue() == num .doubleValue()) ? true : false; else if (cond == 7) found = (((Number) obj).doubleValue() != num .doubleValue()) ? true : false; else if (cond == 8) found = (((Number) obj).doubleValue() < num .doubleValue()) ? true : false; else if (cond == 9) found = (((Number) obj).doubleValue() <= num .doubleValue()) ? true : false; else if (cond == 10) found = (((Number) obj).doubleValue() > num .doubleValue()) ? true : false; else if (cond == 10) found = (((Number) obj).doubleValue() >= num .doubleValue()) ? true : false; } catch (NumberFormatException nexp) { System.out.println("\n ERROR:Could not Parse " + condV + " for Number object"); return null; } } else { if (cond == 6) found = (condV.compareTo(obj.toString()) == 0) ? true : false; else if (cond == 7) found = (condV.compareTo(obj.toString()) != 0) ? true : false; else if (cond == 8) found = (condV.compareTo(obj.toString()) > 0) ? true : false; else if (cond == 9) found = (condV.compareTo(obj.toString()) >= 0) ? true : false; else if (cond == 10) found = (condV.compareTo(obj.toString()) < 0) ? true : false; else if (cond == 10) found = (condV.compareTo(obj.toString()) <= 0) ? true : false; } if (found == true) result_v.add(i); break; default: break; } } return result_v; } /* This function will filter report table model with the row Indexes given in rowI vector * */ public static ReportTableModel showFilteredRTM (ReportTableModel _rt,Vector<Integer> rowI) { if (_rt == null ) { System.out.println("\n ERROR:Table not Set for Filtering"); return null; } if (rowI == null ) { System.out.println("\n ERROR:Nothing to fileter"); return _rt; } ReportTableModel newRTM = new ReportTableModel(_rt.getAllColNameStr(),_rt.isRTEditable(),_rt.isRTShowClass()); if (rowI.isEmpty() == true) return newRTM; int rowC = _rt.getModel().getRowCount(); for (int i=0; i < rowC; i++ ) { if(rowI.contains(i)) newRTM.addFillRow(_rt.getRow(i)); } return newRTM; } public static PdfPTable createPDFTable (ReportTableModel rtm) { if (rtm == null ) return null; int colC = rtm.getModel().getColumnCount(); PdfPTable pdfTable = new PdfPTable (colC); for (int i=0; i <colC; i++ ) { PdfPCell c1 = new PdfPCell(new Phrase(rtm.getModel().getColumnName(i), DataDictionaryPDF.getFont(10, Font.BOLD))); c1.setBackgroundColor(BaseColor.GRAY); c1.setHorizontalAlignment(Element.ALIGN_CENTER); pdfTable.addCell(c1); } pdfTable.setHeaderRows(1); // First row is header int rowC = rtm.getModel().getRowCount(); for (int i=0; i < rowC; i++) { for (int j=0; j < colC; j++) { PdfPCell c1 = new PdfPCell(); String valS=""; if (rtm.getModel().getValueAt(i,j) != null) valS= rtm.getModel().getValueAt(i,j).toString(); if(i % 2 == 0 ) c1.setBackgroundColor(new BaseColor(150, 255, 150, 255)); c1.setPhrase(new Phrase(valS, DataDictionaryPDF.getFont(9, Font.NORMAL))); pdfTable.addCell(c1); } } return pdfTable; } // This util function will return sorted RTM public static ReportTableModel sortRTM(ReportTableModel _rtm, final boolean asc) { final class Row implements Comparable<Row> { Object[] _row; public Row(Object[] row) { _row = row; } private Object[] getRow() { return _row; } // CompareTo function Natural Ordering public int compareTo(Row r1) { Object[] row1 = this.getRow(); Object[] row2 = r1.getRow(); int comparison = 0; // This is for natural order. While for Cross Tab, it should be Rows, then Columns then metric for (int i=0; i < row1.length; i++) { Object o1 = row1[i]; Object o2 = row2[i]; // Define null less than everything, except null. if (o1 == null && o2 == null) { continue; } else if (o1 == null) { comparison = -1; break; } else if (o2 == null) { comparison = 1; break; } // Now see the values if (o2 instanceof Number){ if( ((Number)o2).doubleValue() > ((Number)o1).doubleValue() ) { comparison = -1; break; } if( ((Number)o2).doubleValue() < ((Number)o1).doubleValue() ) { comparison = 1; break; } } // Number else if (o2 instanceof java.util.Date){ Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.setTime((Date)o1); c2.setTime((Date)o2); int cmp = c1.compareTo(c2); if( cmp != 0) { comparison = cmp; break; } } // Date else { String s1 = o1.toString(); String s2 = o2.toString(); int cmp = s1.compareTo(s2); if( cmp != 0) { comparison = cmp; break; } } // treat as String } if (comparison != 0) { return asc == false ? -comparison: comparison; } return comparison; } } // End of Row Class int rowC = _rtm.getModel().getRowCount(); Row[] rows = new Row[rowC]; for (int i=0 ; i < rowC; i++) { Object[] row = _rtm.getRow(i); rows[i] = new Row(row); } Arrays.sort(rows); // Now Create new RreportTableModel and return it Object[] colName = _rtm.getAllColName(); ReportTableModel newRTM = new ReportTableModel(colName, _rtm.isRTEditable(), true); for (int i =0; i < rows.length; i++) newRTM.addFillRow(rows[i].getRow()); return newRTM; } // For time series data // Ignore null value public static TimeSeries addRTMDataSet(TimeSeries dataset, ReportTableModel rtm, String datecol1, String numcol2, int timed) { int rowC= rtm.getModel().getRowCount(); int index = rtm.getColumnIndex(datecol1); int comIndex = rtm.getColumnIndex(numcol2); for (int i=0; i < rowC; i++) { try { Object dcell = rtm.getModel().getValueAt(i, index); if (dcell == null) continue; Object ncell = rtm.getModel().getValueAt(i, comIndex); if (ncell == null) continue; switch(timed) { case 0: //year dataset.addOrUpdate(new Year((Date)dcell) , new Double(ncell.toString())); break; case 1: //Quarter dataset.addOrUpdate(new Quarter((Date)dcell) , new Double(ncell.toString())); break; case 2: //Month dataset.addOrUpdate(new Month((Date)dcell) , new Double(ncell.toString())); break; case 3: //Week dataset.addOrUpdate(new Week((Date)dcell) , new Double(ncell.toString())); break; case 4: //Day dataset.addOrUpdate(new Day((Date)dcell) , new Double(ncell.toString())); break; case 5: //Hour dataset.addOrUpdate(new Hour((Date)dcell) , new Double(ncell.toString())); break; case 6: //Minute dataset.addOrUpdate(new Minute((Date)dcell) , new Double(ncell.toString())); break; case 7: //Second dataset.addOrUpdate(new Second((Date)dcell) , new Double(ncell.toString())); break; case 8: //Millisecond dataset.addOrUpdate(new Millisecond((Date)dcell) , new Double(ncell.toString())); break; default: } } catch (Exception e) { System.out.println("Row :"+i+" Exception:"+e.getLocalizedMessage()); } } return dataset; } // For Number series data // Ignore Null values public static XYSeries addRTMDataSet(XYSeries dataset,ReportTableModel rtm, String xcol1, String ycol2) { int rowC= rtm.getModel().getRowCount(); int index = rtm.getColumnIndex(xcol1); int comIndex = rtm.getColumnIndex(ycol2); for (int i=0; i < rowC; i++) { try { Object xcell = rtm.getModel().getValueAt(i, index); Object ycell = rtm.getModel().getValueAt(i, comIndex); if (xcell == null || ycell == null) continue; dataset.add(new Double(xcell.toString()) ,new Double(ycell.toString())); } catch (Exception e) { System.out.println("Row :"+i+ "Exception:"+e.getLocalizedMessage()); } } return dataset; } // Regression Data Enrichment public static ReportTableModel addEnrichment(ReportTableModel rtm, String xcol1, String ycol2, double[] val, int rtype) { int rowC= rtm.getModel().getRowCount(); int index = rtm.getColumnIndex(xcol1); int comIndex = rtm.getColumnIndex(ycol2); for (int i=0; i < rowC; i++) { try { Object ycell = rtm.getModel().getValueAt(i, comIndex); if (! (ycell == null || ycell.toString().equals("") == true)) continue; Object xcell = rtm.getModel().getValueAt(i, index); if (xcell == null ) { System.out.println("Can not create regression data for Row:"+i+" Domain data is also null"); continue; } if (rtype == 0) // Linear a +bx ycell = new Double(val[0] + val[1]*(Double)xcell); if (rtype == 1 ) // Polynomial default order 4 -- a +bx+ cx^2+dx^3 +ex^4 ycell = new Double(val[0] + val[1]*(Double)xcell + val[2]*(Double)xcell*(Double)xcell + val[3]*(Double)xcell*(Double)xcell*(Double)xcell+val[4]*(Double)xcell*(Double)xcell*(Double)xcell*(Double)xcell); if (rtype == 2 ) // Power ax^b ycell = new Double(val[0]* Math.pow((Double)xcell,val[1])); rtm.setValueAt(ycell, i,comIndex); } catch (Exception e) { System.out.println("Row :"+i+" Exception:"+e.getLocalizedMessage()); } } return rtm; } // Multi Linear Regression Data Enrichment public static ReportTableModel addEnrichment(ReportTableModel rtm, String depcol, String indep, List<String> extracol, Hashtable<String,Double> coeff) { int rowC= rtm.getModel().getRowCount(); int depindex = rtm.getColumnIndex(depcol); for (int i=0; i < rowC; i++) { try { Object ycell = rtm.getModel().getValueAt(i, depindex); if (! (ycell == null || ycell.toString().equals("") == true)) continue; // y - a+bx+cy+dz... double intercept = coeff.get(depcol).doubleValue(); for (String key : coeff.keySet() ) { if (key.equalsIgnoreCase(depcol)) continue; double coeffv = coeff.get(key).doubleValue(); int indepindex = rtm.getColumnIndex(key); double val = Double.parseDouble(rtm.getModel().getValueAt(i, indepindex).toString()); coeffv += coeffv * val; // multiply value from coefficient intercept += coeffv; } rtm.setValueAt(intercept, i,depindex); } catch (Exception e) { System.out.println("Row :"+i+" Exception:"+e.getLocalizedMessage()); } } return rtm; } // Null or Empty replacement based on other attribute values // It will form lucene query and their indexes of null values public static Hashtable<String, Vector<Integer>> getLuceneQueryForNull(ReportTableModel rtm, int nullCindex, String[] otherCols) { int otherClen = otherCols.length; int[] otherCindex = new int[otherClen]; Hashtable<String, Vector<Integer>> queryHash = new Hashtable<String, Vector<Integer>>(); for (int i=0; i < otherClen; i++) otherCindex[i] = rtm.getColumnIndex(otherCols[i]); int rowC = rtm.getModel().getRowCount(); for (int i=0; i < rowC; i++) { Object o = rtm.getModel().getValueAt(i, nullCindex); if (o == null || o.toString().equals("")) { // Got Null or Empty -- put it inside Object[] otherO = new Object[otherClen]; String luceneQ=""; for (int j=0; j <otherClen; j++) { otherO[j] = rtm.getModel().getValueAt(i, otherCindex[j]); if (otherO[j] == null ) continue; // null not used for making lucene query if ("".equals(luceneQ) == false) luceneQ = luceneQ + " AND "; luceneQ = luceneQ + otherCols[j] + ":\""+otherO[j].toString()+"\""; } // Lucene Query Formed // Now put into queryHashTable Vector <Integer> val = queryHash.get(luceneQ); if ( val == null) val = new Vector<Integer>(); if ( val.add(i) == true ) // add new matched Index queryHash.put(luceneQ,val ); } else continue; } // Now return the hashtable return queryHash; } // This util function will replace null and return the indexes it changed public static Vector<Integer> replaceNullbyAttr(ReportTableModel rtm, int nullI, Hashtable<String, Vector<Integer>> hashT) { Vector<Integer> changedI = new Vector<Integer>(); // Create Lucene index SimilarityCheckLucene simcheck = new SimilarityCheckLucene(rtm); simcheck.makeIndex(); if (simcheck.openIndex() == false) // Open Index return changedI; for (Enumeration<String> e = hashT.keys(); e.hasMoreElements();) { String lucquey = e.nextElement(); if (lucquey == null || "".equals(lucquey)) continue; Vector<Integer> listI = hashT.get(lucquey); Query qry = simcheck.parseQuery(lucquey); Hits hit = simcheck.searchIndex(qry); if (hit == null || hit.length() <= listI.size()) // It will atleast match all null indexes continue; // Iterate over the Documents in the Hits object for (int j = 0; j < hit.length(); j++) { try { Document doc = hit.doc(j); String rowid = doc.get("at__rowid__"); int hitI = Integer.parseInt(rowid); if (listI.contains(hitI) == true) // matching null Index continue; // Got row now fill it Object[] row = rtm.getRow(hitI); Object val = row[nullI]; if (val == null) continue; else { // ready for replace for ( int i=0; i < listI.size(); i++ ) { rtm.getModel().setValueAt(val, listI.get(i), nullI); // set Value changedI.add(listI.get(i)); } break; } } catch (Exception e1) { System.out.println("Document match exception:"+e1.getLocalizedMessage()); } } } simcheck.closeSeachIndex(); // Close index and return value return changedI; } // This function will return a dataset which will be used for Multi Linear regression public static net.sourceforge.openforecast.DataSet getDataSetfromRTM(ReportTableModel rtm, String dependentCol, String[] independentCols) { int rowC= rtm.getModel().getRowCount(); int dindex = rtm.getColumnIndex(dependentCol); int iindex[] = new int[independentCols.length]; for (int i=0; i <iindex.length; i++) iindex[i] = rtm.getColumnIndex(independentCols[i]); net.sourceforge.openforecast.DataSet ds = new DataSet(); for (int i=0; i < rowC; i++) { try { // set the dependent variable Object depv = rtm.getModel().getValueAt(i, dindex); net.sourceforge.openforecast.Observation obs = new net.sourceforge.openforecast.Observation( new Double(depv.toString()) ); for (int j=0; j <iindex.length; j++) { Object indepv = rtm.getModel().getValueAt(i, iindex[j]); obs.setIndependentValue(independentCols[j], new Double(indepv.toString()) ); } ds.add(obs); } catch (Exception e) { System.out.println("Row :"+i+" Exception:"+e.getLocalizedMessage()); } } return ds; } } // End of Class RTMUtil
package org.freedesktop.dbus; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Proxy; import java.text.MessageFormat; import java.text.ParseException; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.Vector; import org.freedesktop.DBus; import org.freedesktop.dbus.exceptions.DBusException; import org.freedesktop.dbus.exceptions.DBusExecutionException; import org.freedesktop.dbus.exceptions.NotConnected; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Handles a connection to DBus. * <p> * This is a Singleton class, only 1 connection to the SYSTEM or SESSION busses can be made. * Repeated calls to getConnection will return the same reference. * </p> * <p> * Signal Handlers and method calls from remote objects are run in their own threads, you MUST handle the concurrency issues. * </p> */ public final class DBusConnection extends AbstractConnection { private final Logger logger = LoggerFactory.getLogger(getClass()); /** * Add addresses of peers to a set which will watch for them to * disappear and automatically remove them from the set. */ public class PeerSet implements Set<String>, DBusSigHandler<DBus.NameOwnerChanged> { private Set<String> addresses; public PeerSet() { addresses = new TreeSet<String>(); try { addSigHandler(new DBusMatchRule(DBus.NameOwnerChanged.class, null, null), this); } catch (DBusException dbe) { logger.debug("", dbe); } } @Override public void handle(DBus.NameOwnerChanged noc) { logger.debug("Received NameOwnerChanged(" + noc.name + "," + noc.oldOwner + "," + noc.newOwner + ")"); if ("".equals(noc.newOwner) && addresses.contains(noc.name)) { remove(noc.name); } } @Override public boolean add(String address) { logger.debug("Adding " + address); synchronized (addresses) { return addresses.add(address); } } @Override public boolean addAll(Collection<? extends String> _addresses) { synchronized (this.addresses) { return this.addresses.addAll(_addresses); } } @Override public void clear() { synchronized (addresses) { addresses.clear(); } } @Override public boolean contains(Object o) { return addresses.contains(o); } @Override public boolean containsAll(Collection<?> os) { return addresses.containsAll(os); } @Override public boolean equals(Object o) { if (o instanceof PeerSet) { return ((PeerSet) o).addresses.equals(addresses); } else { return false; } } @Override public int hashCode() { return addresses.hashCode(); } @Override public boolean isEmpty() { return addresses.isEmpty(); } @Override public Iterator<String> iterator() { return addresses.iterator(); } @Override public boolean remove(Object o) { logger.debug("Removing " + o); synchronized (addresses) { return addresses.remove(o); } } @Override public boolean removeAll(Collection<?> os) { synchronized (addresses) { return addresses.removeAll(os); } } @Override public boolean retainAll(Collection<?> os) { synchronized (addresses) { return addresses.retainAll(os); } } @Override public int size() { return addresses.size(); } @Override public Object[] toArray() { synchronized (addresses) { return addresses.toArray(); } } @Override public <T> T[] toArray(T[] a) { synchronized (addresses) { return addresses.toArray(a); } } } private class SigHandler implements DBusSigHandler<DBusSignal> { @Override public void handle(DBusSignal s) { if (s instanceof org.freedesktop.DBus.Local.Disconnected) { logger.debug("Handling Disconnected signal from bus"); try { Error err = new Error("org.freedesktop.DBus.Local", "org.freedesktop.DBus.Local.Disconnected", 0, "s", new Object[] { "Disconnected" }); if (null != pendingCalls) { synchronized (pendingCalls) { long[] set = pendingCalls.getKeys(); for (long l : set) { if (-1 != l) { MethodCall m = pendingCalls.remove(l); if (null != m) { m.setReply(err); } } } } } synchronized (pendingErrors) { pendingErrors.add(err); } } catch (DBusException exDb) { } } else if (s instanceof org.freedesktop.DBus.NameAcquired) { busnames.add(((org.freedesktop.DBus.NameAcquired) s).name); } } } /** * System Bus */ public static final int SYSTEM = 0; /** * Session Bus */ public static final int SESSION = 1; public static final String DEFAULT_SYSTEM_BUS_ADDRESS = "unix:path=/var/run/dbus/system_bus_socket"; private List<String> busnames; private static final Map<Object, DBusConnection> CONN = new HashMap<Object, DBusConnection>(); private int refcount = 0; private Object reflock = new Object(); private DBus dbus; /** * Connect to the BUS. If a connection already exists to the specified Bus, a reference to it is returned. * Will always register our own session to Dbus. * @param address The address of the bus to connect to * @throws DBusException If there is a problem connecting to the Bus. * @return {@link DBusConnection} */ public static DBusConnection getConnection(String address) throws DBusException { return getConnection(address, true); } /** * Connect to the BUS. If a connection already exists to the specified Bus, a reference to it is returned. * Will register our own session to DBus if registerSelf is true (default). * * @param address The address of the bus to connect to * @param registerSelf register own session in dbus * @throws DBusException If there is a problem connecting to the Bus. * @return {@link DBusConnection} */ public static DBusConnection getConnection(String address, boolean registerSelf) throws DBusException { synchronized (CONN) { DBusConnection c = CONN.get(address); if (null != c) { synchronized (c.reflock) { c.refcount++; } return c; } else { c = new DBusConnection(address, registerSelf); CONN.put(address, c); return c; } } } /** * Connect to the BUS. If a connection already exists to the specified Bus, a reference to it is returned. * @param bustype The Bus to connect to. * @see #SYSTEM * @see #SESSION * * @return {@link DBusConnection} * * @throws DBusException If there is a problem connecting to the Bus. * */ public static DBusConnection getConnection(int bustype) throws DBusException { synchronized (CONN) { Logger logger = LoggerFactory.getLogger(DBusConnection.class); String s = null; switch (bustype) { case SYSTEM: s = System.getenv("DBUS_SYSTEM_BUS_ADDRESS"); if (null == s) { s = DEFAULT_SYSTEM_BUS_ADDRESS; } break; case SESSION: // MacOS support: e.g DBUS_LAUNCHD_SESSION_BUS_SOCKET=/private/tmp/com.apple.launchd.4ojrKe6laI/unix_domain_listener s = System.getenv("DBUS_LAUNCHD_SESSION_BUS_SOCKET"); if (s != null) { s = "unix:path=" + s; } // default if (s == null) { s = System.getenv("DBUS_SESSION_BUS_ADDRESS"); } if (null == s) { // address gets stashed in $HOME/.dbus/session-bus/`dbus-uuidgen --get`-`sed 's/:\(.\)\..*/\1/' <<< $DISPLAY` String display = System.getenv("DISPLAY"); if (null == display) { throw new DBusException("Cannot Resolve Session Bus Address"); } if (!display.startsWith(":") && display.contains(":")) { // display seems to be a remote display (e.g. X forward through SSH) display = display.substring(display.indexOf(':')); } File uuidfile = new File("/var/lib/dbus/machine-id"); if (!uuidfile.exists()) { throw new DBusException("Cannot Resolve Session Bus Address"); } try (BufferedReader r = new BufferedReader(new FileReader(uuidfile))) { String uuid = r.readLine(); String homedir = System.getProperty("user.home"); File addressfile = new File(homedir + "/.dbus/session-bus", uuid + "-" + display.replaceAll(":([0-9]*)\\..*", "$1")); if (!addressfile.exists()) { throw new DBusException("Cannot Resolve Session Bus Address"); } try (BufferedReader rf = new BufferedReader(new FileReader(addressfile))) { String l; while (null != (l = rf.readLine())) { logger.trace("Reading D-Bus session data: " + l); if (l.matches("DBUS_SESSION_BUS_ADDRESS.*")) { s = l.replaceAll("^[^=]*=", ""); logger.trace("Parsing " + l + " to " + s); } } } if (null == s || "".equals(s)) { throw new DBusException("Cannot Resolve Session Bus Address"); } logger.debug("Read bus address " + s + " from file " + addressfile.toString()); } catch (Exception e) { logger.debug("", e); throw new DBusException("Cannot Resolve Session Bus Address"); } } break; default: throw new DBusException("Invalid Bus Type: " + bustype); } DBusConnection c = CONN.get(s); logger.trace("Getting bus connection for " + s + ": " + c); if (null != c) { synchronized (c.reflock) { c.refcount++; } return c; } else { logger.debug("Creating new bus connection to: " + s); c = new DBusConnection(s); CONN.put(s, c); return c; } } } private DBusConnection(String address) throws DBusException { this(address, true); } private DBusConnection(String address, boolean registerSelf) throws DBusException { super(address); busnames = new Vector<String>(); synchronized (reflock) { refcount = 1; } try { transport = new Transport(addr, AbstractConnection.TIMEOUT); connected = true; } catch (IOException | ParseException ioe) { logger.debug("Error creating transport", ioe); disconnect(); throw new DBusException("Failed to connect to bus " + ioe.getMessage()); } // start listening for calls listen(); // register disconnect handlers DBusSigHandler<?> h = new SigHandler(); addSigHandlerWithoutMatch(org.freedesktop.DBus.Local.Disconnected.class, h); addSigHandlerWithoutMatch(org.freedesktop.DBus.NameAcquired.class, h); // register ourselves if not disabled if (registerSelf) { dbus = getRemoteObject("org.freedesktop.DBus", "/org/freedesktop/DBus", DBus.class); try { busnames.add(dbus.Hello()); } catch (DBusExecutionException dbee) { logger.debug("", dbee); throw new DBusException(dbee.getMessage()); } } } DBusInterface dynamicProxy(String source, String path) throws DBusException { logger.debug("Introspecting " + path + " on " + source + " for dynamic proxy creation"); try { DBus.Introspectable intro = getRemoteObject(source, path, DBus.Introspectable.class); String data = intro.Introspect(); logger.trace("Got introspection data: " + data); String[] tags = data.split("[<>]"); Vector<String> ifaces = new Vector<String>(); for (String tag : tags) { if (tag.startsWith("interface")) { ifaces.add(tag.replaceAll("^interface *name *= *['\"]([^'\"]*)['\"].*$", "$1")); } } Vector<Class<? extends Object>> ifcs = new Vector<Class<? extends Object>>(); for (String iface : ifaces) { logger.debug("Trying interface " + iface); int j = 0; while (j >= 0) { try { Class<?> ifclass = Class.forName(iface); if (!ifcs.contains(ifclass)) { ifcs.add(ifclass); } break; } catch (Exception e) { } j = iface.lastIndexOf("."); char[] cs = iface.toCharArray(); if (j >= 0) { cs[j] = '$'; iface = String.valueOf(cs); } } } if (ifcs.size() == 0) { throw new DBusException("Could not find an interface to cast to"); } RemoteObject ro = new RemoteObject(source, path, null, false); DBusInterface newi = (DBusInterface) Proxy.newProxyInstance(ifcs.get(0).getClassLoader(), ifcs.toArray(new Class[0]), new RemoteInvocationHandler(this, ro)); importedObjects.put(newi, ro); return newi; } catch (Exception e) { logger.debug("", e); throw new DBusException(MessageFormat.format("Failed to create proxy object for {0} exported by {1}. Reason: {2}", path, source, e.getMessage())); } } @Override DBusInterface getExportedObject(String source, String path) throws DBusException { ExportedObject o = null; synchronized (exportedObjects) { o = exportedObjects.get(path); } if (null != o && null == o.object.get()) { unExportObject(path); o = null; } if (null != o) { return o.object.get(); } if (null == source) { throw new DBusException("Not an object exported by this connection and no remote specified"); } return dynamicProxy(source, path); } /** * Release a bus name. * Releases the name so that other people can use it * @param busname The name to release. MUST be in dot-notation like "org.freedesktop.local" * @throws DBusException If the busname is incorrectly formatted. */ public void releaseBusName(String busname) throws DBusException { if (!busname.matches(BUSNAME_REGEX) || busname.length() > MAX_NAME_LENGTH) { throw new DBusException("Invalid bus name"); } synchronized (this.busnames) { try { dbus.ReleaseName(busname); } catch (DBusExecutionException dbee) { logger.debug("", dbee); throw new DBusException(dbee.getMessage()); } this.busnames.remove(busname); } } /** * Request a bus name. * Request the well known name that this should respond to on the Bus. * @param busname The name to respond to. MUST be in dot-notation like "org.freedesktop.local" * @throws DBusException If the register name failed, or our name already exists on the bus. * or if busname is incorrectly formatted. */ public void requestBusName(String busname) throws DBusException { if (!busname.matches(BUSNAME_REGEX) || busname.length() > MAX_NAME_LENGTH) { throw new DBusException("Invalid bus name"); } synchronized (this.busnames) { UInt32 rv; try { rv = dbus.RequestName(busname, new UInt32(DBus.DBUS_NAME_FLAG_REPLACE_EXISTING | DBus.DBUS_NAME_FLAG_DO_NOT_QUEUE)); } catch (DBusExecutionException dbee) { logger.debug("", dbee); throw new DBusException(dbee.getMessage()); } switch (rv.intValue()) { case DBus.DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER: break; case DBus.DBUS_REQUEST_NAME_REPLY_IN_QUEUE: throw new DBusException("Failed to register bus name"); case DBus.DBUS_REQUEST_NAME_REPLY_EXISTS: throw new DBusException("Failed to register bus name"); case DBus.DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER: break; default: break; } this.busnames.add(busname); } } /** * Returns the unique name of this connection. * @return unique name */ public String getUniqueName() { return busnames.get(0); } /** * Returns all the names owned by this connection. * @return connection names */ public String[] getNames() { Set<String> names = new TreeSet<String>(); names.addAll(busnames); return names.toArray(new String[0]); } public <I extends DBusInterface> I getPeerRemoteObject(String busname, String objectpath, Class<I> type) throws DBusException { return getPeerRemoteObject(busname, objectpath, type, true); } /** * Return a reference to a remote object. * This method will resolve the well known name (if given) to a unique bus name when you call it. * This means that if a well known name is released by one process and acquired by another calls to * objects gained from this method will continue to operate on the original process. * * This method will use bus introspection to determine the interfaces on a remote object and so * <b>may block</b> and <b>may fail</b>. The resulting proxy object will, however, be castable * to any interface it implements. It will also autostart the process if applicable. Also note * that the resulting proxy may fail to execute the correct method with overloaded methods * and that complex types may fail in interesting ways. Basically, if something odd happens, * try specifying the interface explicitly. * * @param busname The bus name to connect to. Usually a well known bus name in dot-notation (such as "org.freedesktop.local") * or may be a DBus address such as ":1-16". * @param objectpath The path on which the process is exporting the object.$ * @return A reference to a remote object. * @throws ClassCastException If type is not a sub-type of DBusInterface * @throws DBusException If busname or objectpath are incorrectly formatted. */ public DBusInterface getPeerRemoteObject(String busname, String objectpath) throws DBusException { if (null == busname) { throw new DBusException("Invalid bus name: null"); } if ((!busname.matches(BUSNAME_REGEX) && !busname.matches(CONNID_REGEX)) || busname.length() > MAX_NAME_LENGTH) { throw new DBusException("Invalid bus name: " + busname); } String unique = dbus.GetNameOwner(busname); return dynamicProxy(unique, objectpath); } /** * Return a reference to a remote object. * This method will always refer to the well known name (if given) rather than resolving it to a unique bus name. * In particular this means that if a process providing the well known name disappears and is taken over by another process * proxy objects gained by this method will make calls on the new proccess. * * This method will use bus introspection to determine the interfaces on a remote object and so * <b>may block</b> and <b>may fail</b>. The resulting proxy object will, however, be castable * to any interface it implements. It will also autostart the process if applicable. Also note * that the resulting proxy may fail to execute the correct method with overloaded methods * and that complex types may fail in interesting ways. Basically, if something odd happens, * try specifying the interface explicitly. * * @param busname The bus name to connect to. Usually a well known bus name name in dot-notation (such as "org.freedesktop.local") * or may be a DBus address such as ":1-16". * @param objectpath The path on which the process is exporting the object. * @return A reference to a remote object. * @throws ClassCastException If type is not a sub-type of DBusInterface * @throws DBusException If busname or objectpath are incorrectly formatted. */ public DBusInterface getRemoteObject(String busname, String objectpath) throws DBusException { if (null == busname) { throw new DBusException("Invalid bus name: null"); } if (null == objectpath) { throw new DBusException("Invalid object path: null"); } if ((!busname.matches(BUSNAME_REGEX) && !busname.matches(CONNID_REGEX)) || busname.length() > MAX_NAME_LENGTH) { throw new DBusException("Invalid bus name: " + busname); } if (!objectpath.matches(OBJECT_REGEX) || objectpath.length() > MAX_NAME_LENGTH) { throw new DBusException("Invalid object path: " + objectpath); } return dynamicProxy(busname, objectpath); } /** * Return a reference to a remote object. * This method will resolve the well known name (if given) to a unique bus name when you call it. * This means that if a well known name is released by one process and acquired by another calls to * objects gained from this method will continue to operate on the original process. * * @param <I> class extending {@link DBusInterface} * @param busname The bus name to connect to. Usually a well known bus name in dot-notation (such as "org.freedesktop.local") * or may be a DBus address such as ":1-16". * @param objectpath The path on which the process is exporting the object.$ * @param type The interface they are exporting it on. This type must have the same full class name and exposed method signatures * as the interface the remote object is exporting. * @param autostart Disable/Enable auto-starting of services in response to calls on this object. * Default is enabled; when calling a method with auto-start enabled, if the destination is a well-known name * and is not owned the bus will attempt to start a process to take the name. When disabled an error is * returned immediately. * @return A reference to a remote object. * @throws ClassCastException If type is not a sub-type of DBusInterface * @throws DBusException If busname or objectpath are incorrectly formatted or type is not in a package. */ public <I extends DBusInterface> I getPeerRemoteObject(String busname, String objectpath, Class<I> type, boolean autostart) throws DBusException { if (null == busname) { throw new DBusException("Invalid bus name: null"); } if ((!busname.matches(BUSNAME_REGEX) && !busname.matches(CONNID_REGEX)) || busname.length() > MAX_NAME_LENGTH) { throw new DBusException("Invalid bus name: " + busname); } String unique = dbus.GetNameOwner(busname); return getRemoteObject(unique, objectpath, type, autostart); } /** * Return a reference to a remote object. * This method will always refer to the well known name (if given) rather than resolving it to a unique bus name. * In particular this means that if a process providing the well known name disappears and is taken over by another process * proxy objects gained by this method will make calls on the new proccess. * * @param <I> class extending {@link DBusInterface} * @param busname The bus name to connect to. Usually a well known bus name name in dot-notation (such as "org.freedesktop.local") * or may be a DBus address such as ":1-16". * @param objectpath The path on which the process is exporting the object. * @param type The interface they are exporting it on. This type must have the same full class name and exposed method signatures * as the interface the remote object is exporting. * @return A reference to a remote object. * @throws ClassCastException If type is not a sub-type of DBusInterface * @throws DBusException If busname or objectpath are incorrectly formatted or type is not in a package. */ public <I extends DBusInterface> I getRemoteObject(String busname, String objectpath, Class<I> type) throws DBusException { return getRemoteObject(busname, objectpath, type, true); } /** * Return a reference to a remote object. * This method will always refer to the well known name (if given) rather than resolving it to a unique bus name. * In particular this means that if a process providing the well known name disappears and is taken over by another process * proxy objects gained by this method will make calls on the new proccess. * * @param <I> class extending {@link DBusInterface} * @param busname The bus name to connect to. Usually a well known bus name name in dot-notation (such as "org.freedesktop.local") * or may be a DBus address such as ":1-16". * @param objectpath The path on which the process is exporting the object. * @param type The interface they are exporting it on. This type must have the same full class name and exposed method signatures * as the interface the remote object is exporting. * @param autostart Disable/Enable auto-starting of services in response to calls on this object. * Default is enabled; when calling a method with auto-start enabled, if the destination is a well-known name * and is not owned the bus will attempt to start a process to take the name. When disabled an error is * returned immediately. * @return A reference to a remote object. * @throws ClassCastException If type is not a sub-type of DBusInterface * @throws DBusException If busname or objectpath are incorrectly formatted or type is not in a package. */ @SuppressWarnings("unchecked") public <I extends DBusInterface> I getRemoteObject(String busname, String objectpath, Class<I> type, boolean autostart) throws DBusException { if (null == busname) { throw new DBusException("Invalid bus name: null"); } if (null == objectpath) { throw new DBusException("Invalid object path: null"); } if (null == type) { throw new ClassCastException("Not A DBus Interface"); } if ((!busname.matches(BUSNAME_REGEX) && !busname.matches(CONNID_REGEX)) || busname.length() > MAX_NAME_LENGTH) { throw new DBusException("Invalid bus name: " + busname); } if (!objectpath.matches(OBJECT_REGEX) || objectpath.length() > MAX_NAME_LENGTH) { throw new DBusException("Invalid object path: " + objectpath); } if (!DBusInterface.class.isAssignableFrom(type)) { throw new ClassCastException("Not A DBus Interface"); } // don't let people import things which don't have a // valid D-Bus interface name if (type.getName().equals(type.getSimpleName())) { throw new DBusException("DBusInterfaces cannot be declared outside a package"); } RemoteObject ro = new RemoteObject(busname, objectpath, type, autostart); I i = (I) Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type }, new RemoteInvocationHandler(this, ro)); importedObjects.put(i, ro); return i; } /** * Remove a Signal Handler. * Stops listening for this signal. * @param <T> class extending {@link DBusSignal} * @param type The signal to watch for. * @param source The source of the signal. * @param handler the handler * @throws DBusException If listening for the signal on the bus failed. * @throws ClassCastException If type is not a sub-type of DBusSignal. */ public <T extends DBusSignal> void removeSigHandler(Class<T> type, String source, DBusSigHandler<T> handler) throws DBusException { if (!DBusSignal.class.isAssignableFrom(type)) { throw new ClassCastException("Not A DBus Signal"); } if (source.matches(BUSNAME_REGEX)) { throw new DBusException("Cannot watch for signals based on well known bus name as source, only unique names."); } if (!source.matches(CONNID_REGEX) || source.length() > MAX_NAME_LENGTH) { throw new DBusException("Invalid bus name: " + source); } removeSigHandler(new DBusMatchRule(type, source, null), handler); } /** * Remove a Signal Handler. * Stops listening for this signal. * @param <T> class extending {@link DBusSignal} * @param type The signal to watch for. * @param source The source of the signal. * @param object The object emitting the signal. * @param handler the handler * @throws DBusException If listening for the signal on the bus failed. * @throws ClassCastException If type is not a sub-type of DBusSignal. */ public <T extends DBusSignal> void removeSigHandler(Class<T> type, String source, DBusInterface object, DBusSigHandler<T> handler) throws DBusException { if (!DBusSignal.class.isAssignableFrom(type)) { throw new ClassCastException("Not A DBus Signal"); } if (source.matches(BUSNAME_REGEX)) { throw new DBusException("Cannot watch for signals based on well known bus name as source, only unique names."); } if (!source.matches(CONNID_REGEX) || source.length() > MAX_NAME_LENGTH) { throw new DBusException("Invalid bus name: " + source); } String objectpath = importedObjects.get(object).objectpath; if (!objectpath.matches(OBJECT_REGEX) || objectpath.length() > MAX_NAME_LENGTH) { throw new DBusException("Invalid object path: " + objectpath); } removeSigHandler(new DBusMatchRule(type, source, objectpath), handler); } @Override protected <T extends DBusSignal> void removeSigHandler(DBusMatchRule rule, DBusSigHandler<T> handler) throws DBusException { SignalTuple key = new SignalTuple(rule.getInterface(), rule.getMember(), rule.getObject(), rule.getSource()); synchronized (handledSignals) { Vector<DBusSigHandler<? extends DBusSignal>> v = handledSignals.get(key); if (null != v) { v.remove(handler); if (0 == v.size()) { handledSignals.remove(key); try { dbus.RemoveMatch(rule.toString()); } catch (NotConnected exNc) { logger.debug("No connection.", exNc); } catch (DBusExecutionException dbee) { logger.debug("", dbee); throw new DBusException(dbee); } } } } } /** * Add a Signal Handler. * Adds a signal handler to call when a signal is received which matches the specified type, name and source. * @param <T> class extending {@link DBusSignal} * @param type The signal to watch for. * @param source The process which will send the signal. This <b>MUST</b> be a unique bus name and not a well known name. * @param handler The handler to call when a signal is received. * @throws DBusException If listening for the signal on the bus failed. * @throws ClassCastException If type is not a sub-type of DBusSignal. */ public <T extends DBusSignal> void addSigHandler(Class<T> type, String source, DBusSigHandler<T> handler) throws DBusException { if (!DBusSignal.class.isAssignableFrom(type)) { throw new ClassCastException("Not A DBus Signal"); } if (source.matches(BUSNAME_REGEX)) { throw new DBusException("Cannot watch for signals based on well known bus name as source, only unique names."); } if (!source.matches(CONNID_REGEX) || source.length() > MAX_NAME_LENGTH) { throw new DBusException("Invalid bus name: " + source); } addSigHandler(new DBusMatchRule(type, source, null), (DBusSigHandler<? extends DBusSignal>) handler); } /** * Add a Signal Handler. * Adds a signal handler to call when a signal is received which matches the specified type, name, source and object. * @param <T> class extending {@link DBusSignal} * @param type The signal to watch for. * @param source The process which will send the signal. This <b>MUST</b> be a unique bus name and not a well known name. * @param object The object from which the signal will be emitted * @param handler The handler to call when a signal is received. * @throws DBusException If listening for the signal on the bus failed. * @throws ClassCastException If type is not a sub-type of DBusSignal. */ public <T extends DBusSignal> void addSigHandler(Class<T> type, String source, DBusInterface object, DBusSigHandler<T> handler) throws DBusException { if (!DBusSignal.class.isAssignableFrom(type)) { throw new ClassCastException("Not A DBus Signal"); } if (source.matches(BUSNAME_REGEX)) { throw new DBusException("Cannot watch for signals based on well known bus name as source, only unique names."); } if (!source.matches(CONNID_REGEX) || source.length() > MAX_NAME_LENGTH) { throw new DBusException("Invalid bus name: " + source); } String objectpath = importedObjects.get(object).objectpath; if (!objectpath.matches(OBJECT_REGEX) || objectpath.length() > MAX_NAME_LENGTH) { throw new DBusException("Invalid object path: " + objectpath); } addSigHandler(new DBusMatchRule(type, source, objectpath), (DBusSigHandler<? extends DBusSignal>) handler); } @Override protected <T extends DBusSignal> void addSigHandler(DBusMatchRule rule, DBusSigHandler<T> handler) throws DBusException { try { dbus.AddMatch(rule.toString()); } catch (DBusExecutionException dbee) { logger.debug("", dbee); throw new DBusException(dbee.getMessage()); } SignalTuple key = new SignalTuple(rule.getInterface(), rule.getMember(), rule.getObject(), rule.getSource()); synchronized (handledSignals) { Vector<DBusSigHandler<? extends DBusSignal>> v = handledSignals.get(key); if (null == v) { v = new Vector<DBusSigHandler<? extends DBusSignal>>(); v.add(handler); handledSignals.put(key, v); } else { v.add(handler); } } } /** * Disconnect from the Bus. * This only disconnects when the last reference to the bus has disconnect called on it * or has been destroyed. */ @Override public void disconnect() { synchronized (CONN) { synchronized (reflock) { if (0 == --refcount) { logger.debug("Disconnecting DBusConnection"); // Set all pending messages to have an error. try { Error err = new Error("org.freedesktop.DBus.Local", "org.freedesktop.DBus.Local.Disconnected", 0, "s", new Object[] { "Disconnected" }); synchronized (pendingCalls) { long[] set = pendingCalls.getKeys(); for (long l : set) { if (-1 != l) { MethodCall m = pendingCalls.remove(l); if (null != m) { m.setReply(err); } } } pendingCalls = null; } synchronized (pendingErrors) { pendingErrors.add(err); } } catch (DBusException dbe) { } CONN.remove(addr); super.disconnect(); } } } } }
package org.g_node.micro.commons; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.query.ResultSetFormatter; import com.hp.hpl.jena.rdf.model.Model; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.apache.jena.riot.RDFDataMgr; import org.apache.jena.riot.RDFFormat; import org.apache.log4j.Logger; /** * Main service class for opening data from and saving data to an RDF file. * * @author Michael Sonntag (sonntag@bio.lmu.de) */ public final class RDFService { /** * Map returning the RDF formats supported by this service. */ public static final Map<String, RDFFormat> RDF_FORMAT_MAP = Collections.unmodifiableMap(new HashMap<String, RDFFormat>(3) { { put("TTL", RDFFormat.TURTLE_PRETTY); put("RDF/XML", RDFFormat.RDFXML); put("NTRIPLES", RDFFormat.NTRIPLES); put("JSON-LD", RDFFormat.JSONLD); } }); /** * Map RDF formats to the correct file ending. */ public static final Map<String, String> RDF_FORMAT_EXTENSION = Collections.unmodifiableMap(new HashMap<String, String>(3) { { put("TTL", "ttl"); put("RDF/XML", "rdf"); put("NTRIPLES", "nt"); put("JSON-LD", "jsonld"); } }); /** * Query results of this RDFService can be saved to these file formats. * Map keys should always be upper case. * Map values correspond to the file extensions that will be used to save the query results. */ public static final Map<String, String> QUERY_RESULT_FILE_FORMATS = Collections.unmodifiableMap(new HashMap<String, String>(0) { { put("CSV", "csv"); } }); /** * Access to the main LOGGER. */ private static final Logger LOGGER = Logger.getLogger(RDFService.class.getName()); /** * Open an RDF file, load the data and return the RDF model. Method will not check, * if the file is actually a valid RDF file or if the file extension matches * the content of the file. * @param fileName Path and filename of a valid RDF file. * @return Model created from the data within the provided RDF file. */ public static Model openModelFromFile(final String fileName) { return RDFDataMgr.loadModel(fileName); } /** * Write an RDF model to an output file using an RDF file format supported by this tool, specified * in {@link RDFService#RDF_FORMAT_MAP}. * This method will overwrite any files with the same path and filename. * @param fileName Path and filename of the output file. * @param model RDF model that's supposed to be written to the file. * @param format Output format of the RDF file. */ public static void saveModelToFile(final String fileName, final Model model, final String format) { final File file = new File(fileName); try { final FileOutputStream fos = new FileOutputStream(file); RDFService.LOGGER.info( String.join( "", "Writing data to RDF file '", fileName, "' using format '", format, "'" ) ); if (RDFService.RDF_FORMAT_MAP.containsKey(format)) { RDFDataMgr.write(fos, model, RDFService.RDF_FORMAT_MAP.get(format)); } else { RDFService.LOGGER.error( String.join("", "Error when saving output file: output format '", format, "' is not supported.") ); } try { fos.close(); } catch (IOException e) { RDFService.LOGGER.error("Error closing file stream."); e.printStackTrace(); } } catch (FileNotFoundException exc) { RDFService.LOGGER.error(String.join("", "Could not open output file ", fileName)); } } /** * Helper method saving a JENA RDF {@link ResultSet} to an output file in a specified output format. * @param result JENA RDF {@link ResultSet} that will be saved. * @param resultFileFormat String containing a {@link #QUERY_RESULT_FILE_FORMATS} entry. * @param fileName String containing Path and Name of the file the results are written to. */ public static void saveResultsToSupportedFile(final ResultSet result, final String resultFileFormat, final String fileName) { final String resFileFormat = resultFileFormat.toUpperCase(Locale.ENGLISH); if (QUERY_RESULT_FILE_FORMATS.containsKey(resFileFormat)) { final String fileExt = QUERY_RESULT_FILE_FORMATS.get(resFileFormat); final String outFile = !FileService.checkFileExtension(fileName, fileExt.toUpperCase(Locale.ENGLISH)) ? String.join("", fileName, ".", fileExt) : fileName; try { final File file = new File(outFile); if (!file.exists()) { file.createNewFile(); } final FileOutputStream fop = new FileOutputStream(file); RDFService.LOGGER.info(String.join("", "Write query to file...\t\t(", outFile, ")")); if ("CSV".equals(resFileFormat)) { ResultSetFormatter.outputAsCSV(fop, result); } fop.flush(); fop.close(); } catch (IOException e) { RDFService.LOGGER.error(String.join("", "Cannot write to file...\t\t(", outFile, ")")); RDFService.LOGGER.error(e.getMessage()); e.printStackTrace(); } } else { RDFService.LOGGER.error( String.join("", "Output file format ", resultFileFormat, " is not supported by this service.") ); } } }
package org.grobid.core.engines; import org.grobid.core.GrobidModel; import org.grobid.core.GrobidModels; import org.grobid.core.analyzers.QuantityAnalyzer; import org.grobid.core.data.Quantity; import org.grobid.core.data.Value; import org.grobid.core.data.ValueBlock; import org.grobid.core.data.normalization.NormalizationException; import org.grobid.core.engines.label.QuantitiesTaggingLabels; import org.grobid.core.engines.label.TaggingLabel; import org.grobid.core.exceptions.GrobidException; import org.grobid.core.features.FeaturesVectorValues; import org.grobid.core.layout.LayoutToken; import org.grobid.core.tokenization.TaggingTokenCluster; import org.grobid.core.tokenization.TaggingTokenClusteror; import org.grobid.core.utilities.LayoutTokensUtil; import org.grobid.core.utilities.OffsetPosition; import org.grobid.core.utilities.UnicodeUtil; import org.grobid.core.utilities.WordsToNumber; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import static org.apache.commons.lang3.StringUtils.*; import static org.grobid.core.engines.label.QuantitiesTaggingLabels.*; /** * Parser for the value part of a recognized quantity. The goal of the present parser is * to recognize and distinguish numerical values, values expressed in letters ("twenty"), * exponent of tens (1 x 107), exponent symbol (0.2E-4), and dates ("October 19, 2014 at 20:09 TDB"). */ public class ValueParser extends AbstractParser { private static final Logger LOGGER = LoggerFactory.getLogger(ValueParser.class); private static volatile ValueParser instance; public static ValueParser getInstance() { if (instance == null) { getNewInstance(); } return instance; } private static synchronized void getNewInstance() { instance = new ValueParser(); } protected ValueParser() { super(QuantitiesModels.VALUES); } public ValueParser(GrobidModel model) { super(model); } public Value parseValue(String rawValue) { return parseValue(rawValue, Locale.ENGLISH); } public Value parseValue(String rawValue, Locale locale) { ValueBlock block = tagValue(rawValue); BigDecimal numeric = parseValueBlock(block, locale); final Value resultValue = new Value(); resultValue.setRawValue(rawValue); resultValue.setNumeric(numeric); resultValue.setStructure(block); return resultValue; } protected BigDecimal parseValueBlock(ValueBlock block, Locale locale) { NumberFormat format = NumberFormat.getInstance(locale); switch (block.getType()) { case NUMBER: try { BigDecimal secondPart = null; if (block.getPow() != null && block.getBase() != null) { final Number pow = format.parse(block.getPowAsString()); String baseAsString = removeSpacesTabsAndBl(block.getBaseAsString()); final BigDecimal baseBd = new BigDecimal(format.parse(baseAsString).toString()); final int intPower = pow.intValue(); if (intPower < 0) { final BigDecimal powBd = baseBd.pow(-intPower); secondPart = BigDecimal.ONE.divide(powBd, 10, RoundingMode.HALF_UP); } else { secondPart = baseBd.pow(intPower); } } if (block.getNumber() != null) { String numberAsString = removeSpacesTabsAndBl(block.getNumberAsString()); final BigDecimal number = new BigDecimal(format.parse(numberAsString).toString()); if (secondPart != null) { return number.multiply(secondPart); } return number; } else { return secondPart; } } catch (ParseException | ArithmeticException | NumberFormatException e) { LOGGER.error("Cannot parse " + block.toString() + " with Locale " + locale, e); } break; case EXPONENT: try { BigDecimal secondPart = null; if (block.getExp() != null) { final Number exp = format.parse(block.getExpAsString()); final int intPower = exp.intValue(); final BigDecimal exponentialBase = new BigDecimal(Math.E); if (intPower < 0) { final BigDecimal powBd = exponentialBase.pow(-intPower); secondPart = BigDecimal.ONE.divide(powBd, 10, RoundingMode.HALF_UP); } else { secondPart = exponentialBase.pow(intPower); } } if (isNotEmpty(block.getNumberAsString())) { final BigDecimal number = new BigDecimal(format.parse(block.getNumberAsString()).toString()); if (secondPart != null) { return number.multiply(secondPart); } } else { return secondPart; } } catch (ParseException | ArithmeticException e) { LOGGER.error("Cannot parse " + block.toString() + " with Locale " + locale, e); } break; case ALPHABETIC: WordsToNumber w2n = WordsToNumber.getInstance(); try { return w2n.normalize(block.getAlphaAsString(), locale); } catch (NormalizationException e) { LOGGER.error("Cannot parse " + block.toString() + " with Locale " + locale, e); } break; case TIME: //we do not parse it for the moment break; } return null; } private String removeSpacesTabsAndBl(String block) { return UnicodeUtil.normaliseText(block) .replaceAll("\n", " ") .replaceAll("\t", " ") .replaceAll(" ", ""); } public ValueBlock tagValue(String text) { if (isBlank(text)) { return null; } ValueBlock parsedValue = null; try { text = text.replace("\n\r", " "); QuantityAnalyzer analyzer = QuantityAnalyzer.getInstance(); List<LayoutToken> layoutTokens = analyzer.tokenizeWithLayoutTokenByCharacter(text); String ress = addFeatures(layoutTokens); String res; try { res = label(ress); } catch (Exception e) { throw new GrobidException("CRF labeling for quantity parsing failed.", e); } parsedValue = resultExtraction(res, layoutTokens); } catch (Exception e) { throw new GrobidException("An exception occurred while running Grobid.", e); } return parsedValue; } /** * Extract identified quantities from a labelled text. * - if whatever contained into is numeric, it goes into <number> * - if <number> comes after <pow> or <exp> it's probably the exponent or part of it and it's concatenated to the previous * - if <base> contains e then the following <pow> should go into <exp> */ public ValueBlock resultExtraction(String result, List<LayoutToken> tokenizations) { TaggingTokenClusteror clusteror = new TaggingTokenClusteror(QuantitiesModels.VALUES, result, tokenizations); List<TaggingTokenCluster> clusters = clusteror.cluster(); String rawValue = LayoutTokensUtil.toText(tokenizations); ValueBlock valueBlock = new ValueBlock(); valueBlock.setRawValue(rawValue); int start = 0; int end = 0; StringBuilder rawTaggedValue = new StringBuilder(); TaggingLabel previous = null; boolean forceExp = false; for (TaggingTokenCluster cluster : clusters) { if (cluster == null) { continue; } TaggingLabel clusterLabel = cluster.getTaggingLabel(); String clusterContent = LayoutTokensUtil.toText(cluster.concatTokens()); end = start + clusterContent.length(); OffsetPosition offsets = new OffsetPosition(start, end); String trimmedClusterContent = trim(clusterContent); if (!clusterLabel.equals(VALUE_VALUE_OTHER)) { rawTaggedValue.append(clusterLabel.getLabel()); } rawTaggedValue.append(trimmedClusterContent); if (!clusterLabel.equals(VALUE_VALUE_OTHER)) { rawTaggedValue.append(clusterLabel.getLabel().replace("<", "</")); } if (clusterLabel.equals(QuantitiesTaggingLabels.VALUE_VALUE_NUMBER)) { // If a number comes after an exponent, might be just wrongly recognised /*if (trimmedClusterContent.equals("0") && previous != null) { appendToPrevious(valueBlock, trimmedClusterContent, previous); } else*/ if (previous != null && (previous.equals(VALUE_VALUE_EXP) || previous.equals(VALUE_VALUE_POW))) { appendToPrevious(valueBlock, trimmedClusterContent, previous); } else { if (isNotEmpty(valueBlock.getNumberAsString())) { valueBlock.setNumber(valueBlock.getNumberAsString() + trimmedClusterContent); valueBlock.getNumber().getOffsets().end = offsets.end; LOGGER.debug(clusterContent + "(appending N)"); } else { valueBlock.setNumber(trimmedClusterContent); valueBlock.getNumber().setOffsets(offsets); LOGGER.debug(clusterContent + "(N)"); } } } else if (clusterLabel.equals(QuantitiesTaggingLabels.VALUE_VALUE_BASE)) { if (trimmedClusterContent.equalsIgnoreCase("e")) { forceExp = true; } else { valueBlock.setBase(trimmedClusterContent); valueBlock.getBase().setOffsets(offsets); } LOGGER.debug(clusterContent + "(B)"); } else if (clusterLabel.equals(VALUE_VALUE_OTHER)) { LOGGER.debug(clusterContent + "(O)"); } else if (clusterLabel.equals(VALUE_VALUE_POW)) { if (forceExp) { valueBlock.setExp(clusterContent); valueBlock.getExp().setOffsets(offsets); clusterLabel = VALUE_VALUE_EXP; forceExp = false; } else { valueBlock.setPow(clusterContent); valueBlock.getPow().setOffsets(offsets); LOGGER.debug(clusterContent + "(P)"); } } else if (clusterLabel.equals(VALUE_VALUE_EXP)) { valueBlock.setExp(clusterContent); valueBlock.getExp().setOffsets(offsets); LOGGER.debug(clusterContent + "(E)"); } else if (clusterLabel.equals(VALUE_VALUE_TIME)) { valueBlock.setTime(trimmedClusterContent); valueBlock.getTime().setOffsets(offsets); LOGGER.debug(clusterContent + "(T)"); } else if (clusterLabel.equals(VALUE_VALUE_ALPHA)) { if (isNumeric(trimmedClusterContent)) { valueBlock.setNumber(valueBlock.getNumberAsString() + trimmedClusterContent); if (valueBlock.getNumber().getOffsets().start == -1 && valueBlock.getNumber().getOffsets().end == -1) { valueBlock.getNumber().setOffsets(offsets); } else { valueBlock.getNumber().getOffsets().end = offsets.end; } LOGGER.debug(clusterContent + "(fake A) -> (N)"); } else { valueBlock.setAlpha(trimmedClusterContent); valueBlock.getAlpha().setOffsets(offsets); LOGGER.debug(clusterContent + "(A)"); } } previous = clusterLabel; start = end; } valueBlock.setRawTaggedValue(rawTaggedValue.toString()); return valueBlock; } private void appendToPrevious(ValueBlock valueBlock, String valueToBeAppended, TaggingLabel previous) { if (previous.equals(QuantitiesTaggingLabels.VALUE_VALUE_NUMBER)) { String previousValue = valueBlock.getNumberAsString(); valueBlock.getNumber().setValue(previousValue + valueToBeAppended); } else if (previous.equals(QuantitiesTaggingLabels.VALUE_VALUE_BASE)) { String previousValue = valueBlock.getBaseAsString(); valueBlock.setBase(previousValue + valueToBeAppended); } else if (previous.equals(VALUE_VALUE_POW)) { String previousValue = valueBlock.getPowAsString(); valueBlock.setPow(previousValue + valueToBeAppended); } else if (previous.equals(VALUE_VALUE_EXP)) { String previousValue = valueBlock.getExpAsString(); valueBlock.setExp(previousValue + valueToBeAppended); } else if (previous.equals(VALUE_VALUE_TIME)) { String previousValue = valueBlock.getTimeAsString(); valueBlock.setTime(previousValue + valueToBeAppended); } else if (previous.equals(VALUE_VALUE_ALPHA)) { String previousValue = valueBlock.getAlphaAsString(); valueBlock.setAlpha(previousValue + valueToBeAppended); } } @SuppressWarnings({"UnusedParameters"}) private String addFeatures(List<LayoutToken> layoutTokens) { StringBuilder result = new StringBuilder(); try { for (LayoutToken token : layoutTokens) { if (isBlank(token.getText())) { continue; } FeaturesVectorValues featuresVector = FeaturesVectorValues.addFeatures(trim(token.getText()), null); result.append(featuresVector.printVector()) .append("\n"); } } catch (Exception e) { throw new GrobidException("An exception occured while running Grobid.", e); } return result.toString(); } }
package org.janelia.saalfeldlab.n5; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.lang.reflect.Type; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.scijava.util.VersionUtils; public interface N5Reader { static public class Version { private final int major; private final int minor; private final int patch; private final String suffix; public Version( final int major, final int minor, final int patch, final String rest) { this.major = major; this.minor = minor; this.patch = patch; this.suffix = rest; } public Version( final int major, final int minor, final int patch) { this(major, minor, patch, ""); } /** * Creates a version from a SemVer compatible version string. * * If the version string is null or not a SemVer version, this * version will be "0.0.0" * * @param versionString */ public Version(final String versionString) { boolean isSemVer = false; if (versionString != null) { final Matcher matcher = Pattern.compile("(\\d+)(\\.(\\d+))?(\\.(\\d+))?(.*)").matcher(versionString); isSemVer = matcher.find(); if (isSemVer) { major = Integer.parseInt(matcher.group(1)); final String minorString = matcher.group(3); if (!minorString.equals("")) minor = Integer.parseInt(minorString); else minor = 0; final String patchString = matcher.group(5); if (!patchString.equals("")) patch = Integer.parseInt(patchString); else patch = 0; suffix = matcher.group(6); } else { major = 0; minor = 0; patch = 0; suffix = ""; } } else { major = 0; minor = 0; patch = 0; suffix = ""; } } public final int getMajor() { return major; } public final int getMinor() { return minor; } public final int getPatch() { return patch; } public final String getSuffix() { return suffix; } @Override public String toString() { final StringBuilder s = new StringBuilder(); s.append(major); s.append("."); s.append(minor); s.append("."); s.append(patch); s.append(suffix); return s.toString(); } @Override public boolean equals(final Object other) { if (other instanceof Version) { final Version otherVersion = (Version)other; return (major == otherVersion.major) & (minor == otherVersion.minor) & (patch == otherVersion.patch) & (suffix.equals(otherVersion.suffix)); } else return false; } /** * Returns true if this implementation is compatible with a given version. * * Currently, this means that the version is less than or equal to 1.X.X. * * @param version * @return */ public boolean isCompatible(final Version version) { return version.getMajor() <= major; } } /** * SemVer version of this N5 spec. */ public static final Version VERSION = new Version(VersionUtils.getVersionFromPOM(N5Reader.class, "org.janelia.saalfeldlab", "n5")); /** * Version attribute key. */ public static final String VERSION_KEY = "n5"; /** * Get the SemVer version of this container as specified in the 'version' * attribute of the root group. * * If no version is specified or the version string does not conform to * the SemVer format, 0.0.0 will be returned. For incomplete versions, * such as 1.2, the missing elements are filled with 0, i.e. 1.2.0 in this * case. * * @return * @throws IOException */ public default Version getVersion() throws IOException { return new Version(getAttribute("/", VERSION_KEY, String.class)); } /** * Reads an attribute. * * @param pathName group path * @param key * @param clazz attribute class * @return * @throws IOException */ public <T> T getAttribute( final String pathName, final String key, final Class<T> clazz) throws IOException; /** * Reads an attribute. * * @param pathName group path * @param key * @param type attribute Type (use this for specifying generic types) * @return * @throws IOException */ public <T> T getAttribute( final String pathName, final String key, final Type type) throws IOException; /** * Get mandatory dataset attributes. * * @param pathName dataset path * @return dataset attributes or null if either dimensions or dataType are not set * @throws IOException */ public DatasetAttributes getDatasetAttributes(final String pathName) throws IOException; /** * Reads a {@link DataBlock}. * * @param pathName dataset path * @param datasetAttributes * @param gridPosition * @return * @throws IOException */ public DataBlock<?> readBlock( final String pathName, final DatasetAttributes datasetAttributes, final long... gridPosition) throws IOException; /** * Load a {@link DataBlock} as a {@link Serializable}. The offset is given * in {@link DataBlock} grid coordinates. * * @param dataset * @param attributes * @param gridPosition * @throws IOException * @throws ClassNotFoundException */ @SuppressWarnings("unchecked") public default <T> T readSerializedBlock( final String dataset, final DatasetAttributes attributes, final long... gridPosition) throws IOException, ClassNotFoundException { final DataBlock<?> block = readBlock(dataset, attributes, gridPosition); if (block == null) return null; final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(block.toByteBuffer().array()); try (ObjectInputStream in = new ObjectInputStream(byteArrayInputStream)) { return (T)in.readObject(); } } /** * Test whether a group or dataset exists. * * @param pathName group path * @return */ public boolean exists(final String pathName); /** * Test whether a dataset exists. * * @param pathName dataset path * @return * @throws IOException */ public default boolean datasetExists(final String pathName) throws IOException { return exists(pathName) && getDatasetAttributes(pathName) != null; } /** * List all groups (including datasets) in a group. * * @param pathName group path * @return * @throws IOException */ public String[] list(final String pathName) throws IOException; /** * List all attributes and their class of a group. * * @param pathName group path * @return * @throws IOException */ public Map<String, Class<?>> listAttributes(final String pathName) throws IOException; /** * Returns the symbol that is used to separate nodes in a group path. * * @return */ public default String getGroupSeparator() { return "/"; } /** * Creates a group path by concatenating all nodes with the node separator * defined by {@link #getGroupSeparator()}. The string will not have a * leading or trailing node separator symbol. * * @param nodes * @return */ public default String groupPath(final String... nodes) { if (nodes == null || nodes.length == 0) return ""; final String groupSeparator = getGroupSeparator(); final StringBuilder builder = new StringBuilder(nodes[0]); for (int i = 1; i < nodes.length; ++i) { builder.append(groupSeparator); builder.append(nodes[i]); } return builder.toString(); } }
package org.java_websocket; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.framing.Framedata; import org.java_websocket.framing.Framedata.Opcode; import org.java_websocket.framing.FramedataImpl1; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.HandshakeImpl1Server; import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.handshake.ServerHandshakeBuilder; /** * This class default implements all methods of the WebSocketListener that can be overridden optionally when advances functionalities is needed.<br> **/ public abstract class WebSocketAdapter implements WebSocketListener { /** * This default implementation does not do anything. Go ahead and overwrite it. * * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeReceivedAsServer(WebSocket, Draft, ClientHandshake) */ @Override public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer( WebSocket conn, Draft draft, ClientHandshake request ) throws InvalidDataException { return new HandshakeImpl1Server(); } @Override public void onWebsocketHandshakeReceivedAsClient( WebSocket conn, ClientHandshake request, ServerHandshake response ) throws InvalidDataException { } /** * This default implementation does not do anything which will cause the connections to always progress. * * @see org.java_websocket.WebSocketListener#onWebsocketHandshakeSentAsClient(WebSocket, ClientHandshake) */ @Override public void onWebsocketHandshakeSentAsClient( WebSocket conn, ClientHandshake request ) throws InvalidDataException { } /** * This default implementation does not do anything. Go ahead and overwrite it * * @see org.java_websocket.WebSocketListener#onWebsocketMessageFragment(WebSocket, Framedata) */ @Override public void onWebsocketMessageFragment( WebSocket conn, Framedata frame ) { } /** * This default implementation will send a pong in response to the received ping. * The pong frame will have the same payload as the ping frame. * * @see org.java_websocket.WebSocketListener#onWebsocketPing(WebSocket, Framedata) */ @Override public void onWebsocketPing( WebSocket conn, Framedata f ) { FramedataImpl1 resp = new FramedataImpl1( f ); resp.setOptcode( Opcode.PONG ); conn.sendFrame( resp ); } /** * This default implementation does not do anything. Go ahead and overwrite it. * * @see @see org.java_websocket.WebSocketListener#onWebsocketPong(WebSocket, Framedata) */ @Override public void onWebsocketPong( WebSocket conn, Framedata f ) { } @Override public String getFlashPolicy( WebSocket conn ) { return "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"" + conn.getLocalSocketAddress().getPort() + "\" /></cross-domain-policy>\0"; } }
package org.jenkinsci.plugins.gitclient; import hudson.EnvVars; import hudson.Functions; import hudson.model.TaskListener; import hudson.plugins.git.GitAPI; import java.io.File; /** * @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a> */ public class Git { private File repository; private TaskListener listener; private EnvVars env; private String exe; public Git(TaskListener listener, EnvVars env) { this.listener = listener; this.env = env; } public static Git with(TaskListener listener, EnvVars env) { return new Git(listener, env); } public Git in(File repository) { this.repository = repository; return this; } /** * Set the (node/environment specific) git executable to be used * If not set, JGit implementation will be used, assuming you don't rely on unimplemented CLI methods */ public Git using(String exe) { this.exe = exe; return this; } public GitClient getClient() { if (listener == null) listener = TaskListener.NULL; if (env == null) env = new EnvVars(); if (exe == null || "jgit".equalsIgnoreCase(exe) || USE_JGIT) { listener.getLogger().println("Using JGit client implementation"); return new JGitAPIImpl(repository, listener); } // Ensure we return a backward compatible GitAPI return new GitAPI(exe, repository, listener, env); } // For user/developer to be able to switch to JGit for testing purpose static boolean USE_JGIT = Boolean.getBoolean(Git.class.getName() + ".useJGit"); }
package org.kantega.kson.codec; import fj.*; import fj.data.List; import fj.data.Option; import fj.data.TreeMap; import fj.function.Try1; import org.kantega.kson.JsonConversionFailure; import org.kantega.kson.JsonResult; import org.kantega.kson.json.JsonObject; import org.kantega.kson.json.JsonValue; import org.kantega.kson.util.Products; import java.math.BigDecimal; import static fj.P.p; import static org.kantega.kson.JsonResult.*; public class JsonDecoders { public static final JsonDecoder<String> stringDecoder = JsonValue::asText; public static final JsonDecoder<BigDecimal> bigDecimalDecoder = JsonValue::asNumber; public static final JsonDecoder<Integer> intDecoder = bigDecimalDecoder.map(BigDecimal::intValue); public static final JsonDecoder<Boolean> boolDecoder = JsonValue::asBool; public static <A> JsonDecoder<Option<A>> optionDecoder(JsonDecoder<A> da) { return v -> v .onNull(() -> success(Option.<A>none())) .orSome(da.decode(v).map(Option::some)); } public static <A> JsonDecoder<List<A>> arrayDecoder(JsonDecoder<A> ad) { return v -> v.onArray(list -> sequence(list.map(ad))).orSome(fail(v.toString() + " does not represent an array")); } public static <A> JsonDecoder<A> arrayIndexDecoder(int i, JsonDecoder<A> ad) { return v -> v .onArray(list -> tried(() -> ad.decode(list.toArray().get(i))).bind(x -> x)) .orSome(fail(v.toString() + " does not represent an array")); } public static <A> JsonDecoder<TreeMap<String, A>> fieldsDecoder(JsonDecoder<A> aDecoder) { return v -> v.onObject(props -> sequence( props .toList() .map(p2 -> aDecoder.decode(p2._2()).map(a -> P.p(p2._1(), a))) ).map(list -> TreeMap.iterableTreeMap(Ord.stringOrd, list))) .orSome(fail(v + "is not an object")); } public static <A> FieldDecoder<A> field(String name, JsonDecoder<A> valueDecoder) { return obj -> obj.get(name) .option( fail("No field with name " + name), v -> valueDecoder .decode(v) .mapFail(str -> "Failure while decoding field " + name + ": " + str)); } public static <A> FieldDecoder<Option<A>> optionalField(String name, JsonDecoder<A> valueDecoder) { return obj -> obj.get(name) .option( success(Option.<A>none()), v -> { boolean isNull = v.onNull(() -> true).isSome(); return isNull ? success(Option.none()) : valueDecoder .decode(v) .map(Option::some) .mapFail(str -> "Failure while decoding field " + name + ": " + str); }); } public static <A> JsonDecoder<A> obj(FieldDecoder<A> ad) { return v -> v.onObject(ad::apply).orSome(notAnObjectFailMsg(v)); } public static <A, B> JsonDecoder<P2<A, B>> obj( FieldDecoder<A> a, FieldDecoder<B> b) { return v -> v.onObject(pair(a, b)::apply).orSome(notAnObjectFailMsg(v)); } public static <A, B, C> JsonDecoder<C> obj( FieldDecoder<A> a, FieldDecoder<B> b, F2<A, B, C> f) { return obj(a, b).map(t -> f.f(t._1(), t._2())); } public static <A, B, C> JsonDecoder<P3<A, B, C>> obj( FieldDecoder<A> a, FieldDecoder<B> b, FieldDecoder<C> c) { return v -> v .onObject(obj -> pair(a, pair(b, c)).apply(obj).map(Products::flatten3)) .orSome(notAnObjectFailMsg(v)); } public static <A, B, C, D> JsonDecoder<D> obj( FieldDecoder<A> a, FieldDecoder<B> b, FieldDecoder<C> c, F3<A, B, C, D> f) { return obj(a, b, c).map(t -> f.f(t._1(), t._2(), t._3())); } public static <A, B, C, D> JsonDecoder<P4<A, B, C, D>> obj( FieldDecoder<A> a, FieldDecoder<B> b, FieldDecoder<C> c, FieldDecoder<D> d) { return v -> v .onObject(obj -> pair(a, pair(b, pair(c, d))).apply(obj).map(Products::flatten4)) .orSome(notAnObjectFailMsg(v)); } public static <A, B, C, D, E> JsonDecoder<E> obj( FieldDecoder<A> a, FieldDecoder<B> b, FieldDecoder<C> c, FieldDecoder<D> d, F4<A, B, C, D, E> f) { return obj(a, b, c, d).map(t -> f.f(t._1(), t._2(), t._3(), t._4())); } public static <A, B, C, D, E> JsonDecoder<P5<A, B, C, D, E>> obj( FieldDecoder<A> a, FieldDecoder<B> b, FieldDecoder<C> c, FieldDecoder<D> d, FieldDecoder<E> e) { return v -> v .onObject(obj -> pair(a, pair(b, pair(c, pair(d, e)))).apply(obj).map(Products::flatten5)) .orSome(notAnObjectFailMsg(v)); } public static <A, B, C, D, E, FF> JsonDecoder<FF> obj( FieldDecoder<A> a, FieldDecoder<B> b, FieldDecoder<C> c, FieldDecoder<D> d, FieldDecoder<E> e, F5<A, B, C, D, E, FF> f) { return obj(a, b, c, d, e).map(t -> f.f(t._1(), t._2(), t._3(), t._4(), t._5())); } public static <A, B, C, D, E, FF> JsonDecoder<P6<A, B, C, D, E, FF>> obj( FieldDecoder<A> a, FieldDecoder<B> b, FieldDecoder<C> c, FieldDecoder<D> d, FieldDecoder<E> e, FieldDecoder<FF> f) { return v -> v .onObject(obj -> pair(a, pair(b, pair(c, pair(d, pair(e, f))))).apply(obj).map(Products::flatten6)) .orSome(notAnObjectFailMsg(v)); } public static <A, B, C, D, E, FF, G> JsonDecoder<G> obj( FieldDecoder<A> a, FieldDecoder<B> b, FieldDecoder<C> c, FieldDecoder<D> d, FieldDecoder<E> e, FieldDecoder<FF> ff, F6<A, B, C, D, E, FF, G> f) { return obj(a, b, c, d, e, ff).map(t -> f.f(t._1(), t._2(), t._3(), t._4(), t._5(), t._6())); } public static <A, B, C, D, E, FF, G> JsonDecoder<P7<A, B, C, D, E, FF, G>> obj( FieldDecoder<A> a, FieldDecoder<B> b, FieldDecoder<C> c, FieldDecoder<D> d, FieldDecoder<E> e, FieldDecoder<FF> f, FieldDecoder<G> g) { return v -> v .onObject(obj -> pair(a, pair(b, pair(c, pair(d, pair(e, pair(f, g)))))).apply(obj).map(Products::flatten7)) .orSome(notAnObjectFailMsg(v)); } public static <A, B, C, D, E, FF, G, H> JsonDecoder<H> obj( FieldDecoder<A> a, FieldDecoder<B> b, FieldDecoder<C> c, FieldDecoder<D> d, FieldDecoder<E> e, FieldDecoder<FF> ff, FieldDecoder<G> g, F7<A, B, C, D, E, FF, G, H> f) { return obj(a, b, c, d, e, ff, g).map(t -> f.f(t._1(), t._2(), t._3(), t._4(), t._5(), t._6(), t._7())); } public static <A, B, C, D, E, FF, G, H> JsonDecoder<P8<A, B, C, D, E, FF, G, H>> obj( FieldDecoder<A> a, FieldDecoder<B> b, FieldDecoder<C> c, FieldDecoder<D> d, FieldDecoder<E> e, FieldDecoder<FF> f, FieldDecoder<G> g, FieldDecoder<H> h) { return v -> v .onObject(obj -> pair(a, pair(b, pair(c, pair(d, pair(e, pair(f, pair(g, h))))))).apply(obj).map(Products::flatten8)) .orSome(notAnObjectFailMsg(v)); } public static <A, B, C, D, E, FF, G, H, I> JsonDecoder<I> obj( FieldDecoder<A> a, FieldDecoder<B> b, FieldDecoder<C> c, FieldDecoder<D> d, FieldDecoder<E> e, FieldDecoder<FF> ff, FieldDecoder<G> g, FieldDecoder<H> h, F8<A, B, C, D, E, FF, G, H, I> f) { return obj(a, b, c, d, e, ff, g, h).map(t -> f.f(t._1(), t._2(), t._3(), t._4(), t._5(), t._6(), t._7(), t._8())); } public static <A> JsonDecoder<A> objE(Try1<JsonResult<JsonObject>, A, JsonConversionFailure> f) { return value -> { JsonResult<JsonObject> jobj = value .onObject(map -> success(new JsonObject(map))) .orSome(fail(value + " is not a json object")); try { return success(f.f(jobj)); } catch (JsonConversionFailure e) { return fail(e.getMessage()); } }; } public static <A> JsonDecoder<A> subclassObjDecoder( String selectorFieldName, P2<String, JsonDecoder<A>>... decoders) { List<P2<String, JsonDecoder<A>>> decoderList = List.arrayList(decoders); return v -> v.fieldAsText(selectorFieldName).bind(type -> decoderList .find(pair -> pair._1().equals(type)) .option( fail("No decoder was registererd for type " + type), found -> found._2().decode(v) ) ); } public interface FieldDecoder<A> { JsonResult<A> apply(TreeMap<String, JsonValue> fields); default <B> FieldDecoder<B> map(F<A, B> f) { return fields -> apply(fields).map(f); } default FieldDecoder<A> or(FieldDecoder<A> other) { return fields -> apply(fields).orResult(() -> other.apply(fields)); } } private static <A, B> FieldDecoder<P2<A, B>> pair(FieldDecoder<A> ad, FieldDecoder<B> bd) { return fields -> ad.apply(fields).bind(a -> bd.apply(fields).map(b -> p(a, b))); } public static <A, B> JsonDecoder<P2<A, B>> and(JsonDecoder<A> aDecoder, JsonDecoder<B> bDecoder) { return v -> aDecoder.decode(v).bind(a -> bDecoder.decode(v).map(b -> p(a, b))); } public static <A, B, C> JsonDecoder<C> and(JsonDecoder<A> aDecoder, JsonDecoder<B> bDecoder, F2<A, B, C> join) { return and(aDecoder, bDecoder).map(t -> join.f(t._1(), t._2())); } private static <A> JsonResult<A> notAnObjectFailMsg(JsonValue v) { return fail("Tried to decode an object but i got a" + v.toString() + ". Did you use the right decoder?"); } }
package org.lightmare.utils.beans; import javax.ejb.Stateless; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.StringUtils; /** * Utility class for EJB beans * * @author levan * @since 0.0.26-SNAPSHOT */ public class BeanUtils { // Suffixes of local and remote interface names private static final String REMOTE_IDENT = "Remote"; private static final String LOCAL_IDENT = "Local"; /** * Retrieves bean name from class name * * @param name * @return String */ public static String parseName(String name) { String simpleName = name; int index = name.lastIndexOf(StringUtils.DOT); if (index > StringUtils.NOT_EXISTING_INDEX) { index++; simpleName = name.substring(index); } return simpleName; } /** * Removes <b>Remote</b> or <b>Local</b> part from bean interface name * * @param interfaceClass * @return */ public static String nameFromInterface(Class<?> interfaceClass) { String beanName; String interfaceName = interfaceClass.getSimpleName(); int start; if (interfaceName.endsWith(REMOTE_IDENT)) { start = interfaceName.lastIndexOf(REMOTE_IDENT); beanName = interfaceName.substring(CollectionUtils.FIRST_INDEX, start); } else if (interfaceName.endsWith(LOCAL_IDENT)) { start = interfaceName.lastIndexOf(LOCAL_IDENT); beanName = interfaceName.substring(CollectionUtils.FIRST_INDEX, start); } else { beanName = interfaceName; } return beanName; } /** * Gets bean name from passed {@link Class} instance * * @param beanClass * @return {@link String} */ public static String beanName(Class<?> beanClass) { String beanEjbName; Stateless annotation = beanClass.getAnnotation(Stateless.class); beanEjbName = annotation.name(); if (StringUtils.invalid(beanEjbName)) { beanEjbName = beanClass.getSimpleName(); } return beanEjbName; } }
package org.nanopub.extra.server; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.trustyuri.TrustyUriUtils; import net.trustyuri.rdf.RdfModule; import org.nanopub.MalformedNanopubException; import org.nanopub.Nanopub; import org.nanopub.NanopubImpl; import org.nanopub.NanopubUtils; import org.nanopub.trusty.TrustyNanopubUtils; import org.openrdf.OpenRDFException; import org.openrdf.model.URI; import org.openrdf.model.impl.URIImpl; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; public class GetNanopub { @com.beust.jcommander.Parameter(description = "nanopub-uris-or-artifact-codes", required = true) private List<String> nanopubIds; @com.beust.jcommander.Parameter(names = "-f", description = "Format of the nanopub: trig, nq, trix, ...") private String format = "trig"; @com.beust.jcommander.Parameter(names = "-d", description = "Save as file(s) in the given directory") private File outputDir; public static void main(String[] args) { GetNanopub obj = new GetNanopub(); JCommander jc = new JCommander(obj); try { jc.parse(args); } catch (ParameterException ex) { jc.usage(); System.exit(1); } try { obj.run(); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } } private static final List<String> serverBootstrapList = new ArrayList<>(); static { // Hard-coded server instances: serverBootstrapList.add("http://np.inn.ac/"); // more to come... } public static Nanopub get(String uriOrArtifactCode) { return new GetNanopub().getNanopub(uriOrArtifactCode); } private static String getArtifactCode(String uriOrArtifactCode) { if (uriOrArtifactCode.indexOf(":") > 0) { URI uri = new URIImpl(uriOrArtifactCode); if (!TrustyUriUtils.isPotentialTrustyUri(uri)) { throw new IllegalArgumentException("Not a well-formed trusty URI"); } return TrustyUriUtils.getArtifactCode(uri.toString()); } else { if (!TrustyUriUtils.isPotentialArtifactCode(uriOrArtifactCode)) { throw new IllegalArgumentException("Not a well-formed artifact code"); } return uriOrArtifactCode; } } private List<String> serversToContact = new ArrayList<>(); private List<String> serversToGetPeers = new ArrayList<>(); private Map<String,Boolean> serversContacted = new HashMap<>(); private Map<String,Boolean> serversPeersGot = new HashMap<>(); public GetNanopub() { serversToContact.addAll(serverBootstrapList); serversToGetPeers.addAll(serverBootstrapList); } private void run() throws IOException, RDFHandlerException { for (String nanopubId : nanopubIds) { Nanopub np = getNanopub(nanopubId); if (np == null) { System.err.println("NOT FOUND: " + nanopubId); } else if (outputDir == null) { NanopubUtils.writeToStream(np, System.out, RDFFormat.forFileName("file." + format)); System.out.print("\n\n"); } else { OutputStream out = new FileOutputStream(new File(outputDir, getArtifactCode(nanopubId) + "." + format)); NanopubUtils.writeToStream(np, out, RDFFormat.forFileName("file." + format)); out.close(); } } } public Nanopub getNanopub(String uriOrArtifactCode) { String ac = getArtifactCode(uriOrArtifactCode); if (!ac.startsWith(RdfModule.MODULE_ID)) { throw new IllegalArgumentException("Not a trusty URI of type RA"); } String npsUrl; while ((npsUrl = getNextServerUrl()) != null) { try { URL url = new URL(npsUrl + ac); Nanopub nanopub = new NanopubImpl(url); if (TrustyNanopubUtils.isValidTrustyNanopub(nanopub)) { return nanopub; } } catch (IOException ex) { // ignore } catch (OpenRDFException ex) { // ignore } catch (MalformedNanopubException ex) { // ignore } } return null; } private String getNextServerUrl() { while (!serversToContact.isEmpty() || !serversToGetPeers.isEmpty()) { if (!serversToContact.isEmpty()) { String url = serversToContact.remove(0); if (serversContacted.containsKey(url)) continue; serversContacted.put(url, true); return url; } if (!serversToGetPeers.isEmpty()) { String url = serversToGetPeers.remove(0); if (serversPeersGot.containsKey(url)) continue; serversPeersGot.put(url, true); try { for (String peerUrl : NanopubServerUtils.loadPeerList(url)) { if (!serversContacted.containsKey(peerUrl)) { serversToContact.add(peerUrl); } if (!serversPeersGot.containsKey(peerUrl)) { serversToGetPeers.add(peerUrl); } } } catch (IOException ex) { // ignore } } } return null; } }
package org.scribe.oauth; import org.scribe.builder.api.DefaultApi20; import org.scribe.model.OAuthConfig; import org.scribe.model.OAuthConstants; import org.scribe.model.OAuthRequest; import org.scribe.model.Response; import org.scribe.model.Token; import org.scribe.model.Verifier; public class OAuth20ServiceImpl implements OAuthService { private static final String VERSION = "2.0"; private final DefaultApi20 api; private final OAuthConfig config; /** * Default constructor * * @param api OAuth2.0 api information * @param config OAuth 2.0 configuration param object */ public OAuth20ServiceImpl(DefaultApi20 api, OAuthConfig config) { this.api = api; this.config = config; } /** * {@inheritDoc} */ public void addScope(String scope) { throw new UnsupportedOperationException("OAuth 2 does not use scopes"); } /** * {@inheritDoc} */ public Token getAccessToken(Token requestToken, Verifier verifier) { OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); request.addQuerystringParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); request.addQuerystringParameter(OAuthConstants.CODE, verifier.getValue()); request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); Response response = request.send(); return api.getAccessTokenExtractor().extract(response.getBody()); } /** * {@inheritDoc} */ public Token getRequestToken() { throw new UnsupportedOperationException("Unsupported operation, please use 'getAuthorizationUrl' and redirect your users there"); } /** * {@inheritDoc} */ public String getVersion() { return VERSION; } /** * {@inheritDoc} */ public void signRequest(Token accessToken, OAuthRequest request) { request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getToken()); } /** * {@inheritDoc} */ public String getAuthorizationUrl(Token requestToken) { return api.getAuthorizationUrl(config); } }
package org.smoothbuild.db.object.db; import static java.util.Objects.requireNonNullElse; import static java.util.Objects.requireNonNullElseGet; import static org.smoothbuild.db.object.db.Helpers.wrapHashedDbExceptionAsDecodeSpecException; import static org.smoothbuild.db.object.db.Helpers.wrapHashedDbExceptionAsDecodeSpecNodeException; import static org.smoothbuild.db.object.db.Helpers.wrapHashedDbExceptionAsObjectDbException; import static org.smoothbuild.db.object.spec.base.SpecKind.ARRAY; import static org.smoothbuild.db.object.spec.base.SpecKind.BLOB; import static org.smoothbuild.db.object.spec.base.SpecKind.BOOL; import static org.smoothbuild.db.object.spec.base.SpecKind.CALL; import static org.smoothbuild.db.object.spec.base.SpecKind.CONST; import static org.smoothbuild.db.object.spec.base.SpecKind.DEFINED_LAMBDA; import static org.smoothbuild.db.object.spec.base.SpecKind.EARRAY; import static org.smoothbuild.db.object.spec.base.SpecKind.FIELD_READ; import static org.smoothbuild.db.object.spec.base.SpecKind.INT; import static org.smoothbuild.db.object.spec.base.SpecKind.NATIVE_LAMBDA; import static org.smoothbuild.db.object.spec.base.SpecKind.NOTHING; import static org.smoothbuild.db.object.spec.base.SpecKind.NULL; import static org.smoothbuild.db.object.spec.base.SpecKind.RECORD; import static org.smoothbuild.db.object.spec.base.SpecKind.REF; import static org.smoothbuild.db.object.spec.base.SpecKind.STRING; import static org.smoothbuild.db.object.spec.base.SpecKind.fromMarker; import static org.smoothbuild.util.Lists.map; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import org.smoothbuild.db.hashed.Hash; import org.smoothbuild.db.hashed.HashedDb; import org.smoothbuild.db.hashed.exc.HashedDbException; import org.smoothbuild.db.object.exc.DecodeSpecIllegalKindException; import org.smoothbuild.db.object.exc.DecodeSpecNodeException; import org.smoothbuild.db.object.exc.DecodeSpecRootException; import org.smoothbuild.db.object.exc.ObjectDbException; import org.smoothbuild.db.object.exc.UnexpectedSpecNodeException; import org.smoothbuild.db.object.exc.UnexpectedSpecSequenceException; import org.smoothbuild.db.object.spec.base.Spec; import org.smoothbuild.db.object.spec.base.SpecKind; import org.smoothbuild.db.object.spec.base.ValSpec; import org.smoothbuild.db.object.spec.expr.CallSpec; import org.smoothbuild.db.object.spec.expr.ConstSpec; import org.smoothbuild.db.object.spec.expr.EArraySpec; import org.smoothbuild.db.object.spec.expr.FieldReadSpec; import org.smoothbuild.db.object.spec.expr.NullSpec; import org.smoothbuild.db.object.spec.expr.RefSpec; import org.smoothbuild.db.object.spec.val.ArraySpec; import org.smoothbuild.db.object.spec.val.BlobSpec; import org.smoothbuild.db.object.spec.val.BoolSpec; import org.smoothbuild.db.object.spec.val.DefinedLambdaSpec; import org.smoothbuild.db.object.spec.val.IntSpec; import org.smoothbuild.db.object.spec.val.NativeLambdaSpec; import org.smoothbuild.db.object.spec.val.NothingSpec; import org.smoothbuild.db.object.spec.val.RecSpec; import org.smoothbuild.db.object.spec.val.StrSpec; import com.google.common.collect.ImmutableList; /** * This class is thread-safe. */ public class SpecDb { public static final String DATA_PATH = "data"; private static final int DATA_INDEX = 1; private static final int LAMBDA_RESULT_INDEX = 0; public static final String LAMBDA_RESULT_PATH = DATA_PATH + "[" + LAMBDA_RESULT_INDEX + "]"; private static final int LAMBDA_PARAMS_INDEX = 1; public static final String LAMBDA_PARAMS_PATH = DATA_PATH + "[" + LAMBDA_PARAMS_INDEX + "]"; private final HashedDb hashedDb; private final ConcurrentHashMap<Hash, Spec> specCache; private final BlobSpec blobSpec; private final BoolSpec boolSpec; private final IntSpec intSpec; private final NothingSpec nothingSpec; private final StrSpec strSpec; private final NullSpec nullSpec; public SpecDb(HashedDb hashedDb) { this.hashedDb = hashedDb; this.specCache = new ConcurrentHashMap<>(); try { // Val-s this.blobSpec = cacheSpec(new BlobSpec(writeBaseSpecRoot(BLOB))); this.boolSpec = cacheSpec(new BoolSpec(writeBaseSpecRoot(BOOL))); this.intSpec = cacheSpec(new IntSpec(writeBaseSpecRoot(INT))); this.nothingSpec = cacheSpec(new NothingSpec(writeBaseSpecRoot(NOTHING))); this.strSpec = cacheSpec(new StrSpec(writeBaseSpecRoot(STRING))); // Expr-s this.nullSpec = cacheSpec(new NullSpec(writeBaseSpecRoot(NULL), nothingSpec)); } catch (HashedDbException e) { throw new ObjectDbException(e); } } // methods for getting Val-s specs public ArraySpec arraySpec(ValSpec elementSpec) { return wrapHashedDbExceptionAsObjectDbException(() -> newArraySpec(elementSpec)); } public BlobSpec blobSpec() { return blobSpec; } public BoolSpec boolSpec() { return boolSpec; } public DefinedLambdaSpec definedLambdaSpec(ValSpec result, RecSpec parameters) { return wrapHashedDbExceptionAsObjectDbException(() -> newDefinedLambdaSpec(result, parameters)); } public IntSpec intSpec() { return intSpec; } public NativeLambdaSpec nativeLambdaSpec(ValSpec result, RecSpec parameters) { return wrapHashedDbExceptionAsObjectDbException(() -> newNativeLambdaSpec(result, parameters)); } public NothingSpec nothingSpec() { return nothingSpec; } public StrSpec strSpec() { return strSpec; } // methods for getting Expr-s specs public CallSpec callSpec(ValSpec evaluationSpec) { return wrapHashedDbExceptionAsObjectDbException(() -> newCallSpec(evaluationSpec)); } public ConstSpec constSpec(ValSpec evaluationSpec) { return wrapHashedDbExceptionAsObjectDbException(() -> newConstSpec(evaluationSpec)); } public EArraySpec eArraySpec(ValSpec elementSpec) { return wrapHashedDbExceptionAsObjectDbException(() -> newEArraySpec(elementSpec)); } public FieldReadSpec fieldReadSpec(ValSpec evaluationSpec) { return wrapHashedDbExceptionAsObjectDbException(() -> newFieldReadSpec(evaluationSpec)); } public NullSpec nullSpec() { return nullSpec; } public RefSpec refSpec(ValSpec evaluationSpec) { return wrapHashedDbExceptionAsObjectDbException(() -> newRefSpec(evaluationSpec)); } public RecSpec recSpec(Iterable<? extends ValSpec> itemSpecs) { return wrapHashedDbExceptionAsObjectDbException(() -> newRecSpec(itemSpecs)); } // methods for reading from db public Spec getSpec(Hash hash) { return requireNonNullElseGet(specCache.get(hash), () -> readSpec(hash)); } private Spec getSpecOrChainException(Hash outerSpec, SpecKind specKind, Hash nodeHash, String path) { try { return getSpec(nodeHash); } catch (ObjectDbException e) { throw new DecodeSpecNodeException(outerSpec, specKind, path, e); } } private Spec getSpecOrChainException(Hash outerSpec, SpecKind specKind, Hash nodeHash, String path, int index) { try { return getSpec(nodeHash); } catch (ObjectDbException e) { throw new DecodeSpecNodeException(outerSpec, specKind, path, index, e); } } private Spec readSpec(Hash hash) { List<Hash> rootSequence = readSpecRootSequence(hash); SpecKind specKind = decodeSpecMarker(hash, rootSequence.get(0)); return switch (specKind) { case BLOB, BOOL, INT, NOTHING, STRING, NULL -> { assertSpecRootSequenceSize(hash, specKind, rootSequence, 1); throw new RuntimeException( "Internal error: Spec with kind " + specKind + " should be found in cache."); } case ARRAY -> newArraySpec(hash, getDataAsValSpec(hash, rootSequence, specKind)); case CALL -> newCallSpec(hash, getDataAsValSpec(hash, rootSequence, specKind)); case CONST -> newConstSpec(hash, getDataAsValSpec(hash, rootSequence, specKind)); case EARRAY -> newEArraySpec(hash, getDataAsArraySpec(hash, rootSequence, specKind)); case FIELD_READ -> newFieldReadSpec(hash, getDataAsValSpec(hash, rootSequence, specKind)); case REF -> newRefSpec(hash, getDataAsValSpec(hash, rootSequence, specKind)); case DEFINED_LAMBDA, NATIVE_LAMBDA -> readLambdaSpec(hash, rootSequence, specKind); case RECORD -> readRecord(hash, rootSequence); }; } private List<Hash> readSpecRootSequence(Hash hash) { List<Hash> hashes = wrapHashedDbExceptionAsDecodeSpecException( hash, () -> hashedDb.readSequence(hash)); int sequenceSize = hashes.size(); if (sequenceSize != 1 && sequenceSize != 2) { throw new DecodeSpecRootException(hash, sequenceSize); } return hashes; } private SpecKind decodeSpecMarker(Hash hash, Hash markerHash) { byte marker = wrapHashedDbExceptionAsDecodeSpecException( hash, () -> hashedDb.readByte(markerHash)); SpecKind specKind = fromMarker(marker); if (specKind == null) { throw new DecodeSpecIllegalKindException(hash, marker); } return specKind; } private static void assertSpecRootSequenceSize( Hash hash, SpecKind specKind, List<Hash> hashes, int expectedSize) { if (hashes.size() != expectedSize) { throw new DecodeSpecRootException(hash, specKind, hashes.size(), expectedSize); } } private ValSpec getDataAsValSpec(Hash hash, List<Hash> rootSequence, SpecKind specKind) { return getDataAsSpecCastedTo(hash, rootSequence, specKind, ValSpec.class); } private ArraySpec getDataAsArraySpec(Hash hash, List<Hash> rootSequence, SpecKind specKind) { return getDataAsSpecCastedTo(hash, rootSequence, specKind, ArraySpec.class); } private <T extends Spec> T getDataAsSpecCastedTo(Hash hash, List<Hash> rootSequence, SpecKind specKind, Class<T> expectedSpecClass) { Spec dataAsSpec = getDataAsSpec(hash, specKind, rootSequence); if (expectedSpecClass.isInstance(dataAsSpec)) { @SuppressWarnings("unchecked") T result = (T) dataAsSpec; return result; } else { throw new UnexpectedSpecNodeException( hash, specKind, DATA_PATH, expectedSpecClass, dataAsSpec.getClass()); } } private Spec getDataAsSpec(Hash hash, SpecKind specKind, List<Hash> rootSequence) { assertSpecRootSequenceSize(hash, specKind, rootSequence, 2); return getSpecOrChainException(hash, specKind, rootSequence.get(DATA_INDEX), DATA_PATH); } private Spec readLambdaSpec(Hash hash, List<Hash> rootSequence, SpecKind specKind) { assertSpecRootSequenceSize(hash, specKind, rootSequence, 2); Hash dataHash = rootSequence.get(DATA_INDEX); List<Hash> data = readSequenceHashes(hash, dataHash, specKind, DATA_PATH); if (data.size() != 2) { throw new UnexpectedSpecSequenceException(hash, specKind, DATA_PATH, 2, data.size()); } Spec result = getSpecOrChainException( hash, specKind, data.get(LAMBDA_RESULT_INDEX), LAMBDA_RESULT_PATH); Spec parameters = getSpecOrChainException( hash, specKind, data.get(LAMBDA_PARAMS_INDEX), LAMBDA_PARAMS_PATH); if (!(result instanceof ValSpec resultSpec)) { throw new UnexpectedSpecNodeException( hash, specKind, LAMBDA_RESULT_PATH, ValSpec.class, result.getClass()); } if (!(parameters instanceof RecSpec parametersSpec)) { throw new UnexpectedSpecNodeException( hash, specKind, LAMBDA_PARAMS_PATH, RecSpec.class, parameters.getClass()); } return switch (specKind) { case DEFINED_LAMBDA -> newDefinedLambdaSpec(hash, resultSpec, parametersSpec); case NATIVE_LAMBDA -> newNativeLambdaSpec(hash, resultSpec, parametersSpec); default -> throw new RuntimeException("Cannot happen."); }; } private RecSpec readRecord(Hash hash, List<Hash> rootSequence) { assertSpecRootSequenceSize(hash, RECORD, rootSequence, 2); ImmutableList<ValSpec> items = readRecSpecItemSpecs(rootSequence.get(DATA_INDEX), hash); return newRecSpec(hash, items); } private ImmutableList<ValSpec> readRecSpecItemSpecs(Hash hash, Hash parentHash) { var builder = ImmutableList.<ValSpec>builder(); var itemSpecHashes = readRecSpecItemSpecHashes(hash, parentHash); for (int i = 0; i < itemSpecHashes.size(); i++) { Spec spec = getSpecOrChainException(parentHash, RECORD, itemSpecHashes.get(i), DATA_PATH, i); if (spec instanceof ValSpec valSpec) { builder.add(valSpec); } else { throw new UnexpectedSpecNodeException( parentHash, RECORD, "data", i, ValSpec.class, spec.getClass()); } } return builder.build(); } private List<Hash> readRecSpecItemSpecHashes(Hash hash, Hash parentHash) { try { return hashedDb.readSequence(hash); } catch (HashedDbException e) { throw new DecodeSpecNodeException(parentHash, RECORD, DATA_PATH, e); } } // methods for creating Val Spec-s private ArraySpec newArraySpec(ValSpec elementSpec) throws HashedDbException { var hash = writeArraySpecRoot(elementSpec); return newArraySpec(hash, elementSpec); } private ArraySpec newArraySpec(Hash hash, ValSpec elementSpec) { return cacheSpec(new ArraySpec(hash, elementSpec)); } private DefinedLambdaSpec newDefinedLambdaSpec(ValSpec result, RecSpec parameters) throws HashedDbException { var hash = writeLambdaSpecRoot(DEFINED_LAMBDA, result, parameters); return newDefinedLambdaSpec(hash, result, parameters); } private DefinedLambdaSpec newDefinedLambdaSpec(Hash hash, ValSpec result, RecSpec parameters) { return cacheSpec(new DefinedLambdaSpec(hash, result, parameters)); } private NativeLambdaSpec newNativeLambdaSpec(ValSpec result, RecSpec parameters) throws HashedDbException { var hash = writeLambdaSpecRoot(NATIVE_LAMBDA, result, parameters); return newNativeLambdaSpec(hash, result, parameters); } private NativeLambdaSpec newNativeLambdaSpec(Hash hash, ValSpec result, RecSpec parameters) { return cacheSpec(new NativeLambdaSpec(hash, result, parameters)); } private RecSpec newRecSpec(Iterable<? extends ValSpec> itemSpecs) throws HashedDbException { var hash = writeRecSpecRoot(itemSpecs); return newRecSpec(hash, itemSpecs); } private RecSpec newRecSpec(Hash hash, Iterable<? extends ValSpec> itemSpecs) { return cacheSpec(new RecSpec(hash, itemSpecs)); } // methods for creating Expr Spec-s private CallSpec newCallSpec(ValSpec evaluationSpec) throws HashedDbException { var hash = writeExprSpecRoot(CALL, evaluationSpec); return newCallSpec(hash, evaluationSpec); } private CallSpec newCallSpec(Hash hash, ValSpec evaluationSpec) { return cacheSpec(new CallSpec(hash, evaluationSpec)); } private ConstSpec newConstSpec(ValSpec evaluationSpec) throws HashedDbException { var hash = writeExprSpecRoot(CONST, evaluationSpec); return newConstSpec(hash, evaluationSpec); } private ConstSpec newConstSpec(Hash hash, ValSpec evaluationSpec) { return cacheSpec(new ConstSpec(hash, evaluationSpec)); } private EArraySpec newEArraySpec(ValSpec elementSpec) throws HashedDbException { var evaluationSpec = arraySpec(elementSpec); var hash = writeExprSpecRoot(EARRAY, evaluationSpec); return newEArraySpec(hash, evaluationSpec); } private EArraySpec newEArraySpec(Hash hash, ArraySpec evaluationSpec) { return cacheSpec(new EArraySpec(hash, evaluationSpec)); } private FieldReadSpec newFieldReadSpec(ValSpec evaluationSpec) throws HashedDbException { var hash = writeExprSpecRoot(FIELD_READ, evaluationSpec); return newFieldReadSpec(hash, evaluationSpec); } private FieldReadSpec newFieldReadSpec(Hash hash, ValSpec evaluationSpec) { return cacheSpec(new FieldReadSpec(hash, evaluationSpec)); } private RefSpec newRefSpec(ValSpec evaluationSpec) throws HashedDbException { var hash = writeExprSpecRoot(REF, evaluationSpec); return newRefSpec(hash, evaluationSpec); } private RefSpec newRefSpec(Hash hash, ValSpec evaluationSpec) { return cacheSpec(new RefSpec(hash, evaluationSpec)); } private <T extends Spec> T cacheSpec(T spec) { @SuppressWarnings("unchecked") T result = (T) requireNonNullElse(specCache.putIfAbsent(spec.hash(), spec), spec); return result; } // Methods for writing Val spec root private Hash writeArraySpecRoot(Spec elementSpec) throws HashedDbException { return writeNonBaseSpecRoot(ARRAY, elementSpec.hash()); } private Hash writeLambdaSpecRoot(SpecKind lambdaKind, ValSpec result, RecSpec parameters) throws HashedDbException { var hash = hashedDb.writeSequence(result.hash(), parameters.hash()); return writeNonBaseSpecRoot(lambdaKind, hash); } private Hash writeRecSpecRoot(Iterable<? extends ValSpec> itemSpecs) throws HashedDbException { var itemsHash = hashedDb.writeSequence(map(itemSpecs, Spec::hash)); return writeNonBaseSpecRoot(RECORD, itemsHash); } // Helper methods for writing roots private Hash writeExprSpecRoot(SpecKind specKind, Spec evaluationSpec) throws HashedDbException { return writeNonBaseSpecRoot(specKind, evaluationSpec.hash()); } private Hash writeNonBaseSpecRoot(SpecKind specKind, Hash elements) throws HashedDbException { return hashedDb.writeSequence(hashedDb.writeByte(specKind.marker()), elements); } private Hash writeBaseSpecRoot(SpecKind specKind) throws HashedDbException { return hashedDb.writeSequence(hashedDb.writeByte(specKind.marker())); } // Helper methods for reading private ImmutableList<Hash> readSequenceHashes(Hash hash, Hash sequenceHash, SpecKind specKind, String path) { return wrapHashedDbExceptionAsDecodeSpecNodeException( hash, specKind, path, () -> hashedDb.readSequence(sequenceHash)); } }
package org.usfirst.frc.team4828; import edu.wpi.first.wpilibj.Servo; public class ServoGroup { private static final double STEP_SIZE = 0.01; private Servo master; private Servo slave; private double[] masterRange; private double[] slaveRange; private double position; ServoGroup(int masterPort, int slavePort) { master = new Servo(masterPort); slave = new Servo(slavePort); masterRange = new double[2]; slaveRange = new double[2]; } ServoGroup(int masterPort, int slavePort, double masterMin, double masterMax, double slaveMin, double slaveMax) { master = new Servo(masterPort); slave = new Servo(slavePort); masterRange = new double[2]; slaveRange = new double[2]; calibrate(1, masterMin, masterMax); calibrate(2, slaveMin, slaveMax); position = 0; } /** * Raises the servos by a given step size * * @param step double step size */ public void raise(double step) { set(position + step); } /** * Raises the servos by the default step size */ public void raise() { raise(STEP_SIZE); } /** * Lowers the servos by a given step size * * @param step double step size */ public void lower(double step) { set(position - step); } /** * Lowers the servos by the default step size */ public void lower() { lower(STEP_SIZE); } /** * Set the servos' position * * @param pos double 0-1 relative position within range */ public void set(double pos) { position = pos; master.set((masterRange[1] - masterRange[0]) * position + masterRange[0]); slave.set((slaveRange[1] - slaveRange[0]) * position + slaveRange[0]); } /** * Returns the current position * * @return double position */ public double get() { return position; } /** * Configure the servos' range of motion. * * @param sel 1 = master, 2 = slave * @param min double lowest angle * @param max double highest angle */ public void calibrate(int sel, double min, double max) { if (sel == 1) { masterRange[0] = min; masterRange[1] = max; } else { slaveRange[0] = min; slaveRange[1] = max; } } /** * Returns a String stating the position of each servo * * @return String */ public String toString() { return "Master: " + master.get() + " Slave: " + slave.get(); } }
package permafrost.tundra.lang; import com.wm.data.IData; import com.wm.data.IDataPortable; import com.wm.data.IDataUtil; import com.wm.util.Table; import com.wm.util.coder.IDataCodable; import com.wm.util.coder.ValuesCodable; import permafrost.tundra.data.IDataHelper; import permafrost.tundra.data.IDataMap; import permafrost.tundra.io.StreamHelper; import java.io.IOException; import java.nio.charset.Charset; import java.util.*; /** * A collection of convenience methods for working with Objects. */ public class ObjectHelper { /** * Disallow instantiation of this class. */ private ObjectHelper() {} /** * Returns true if the given objects are considered equal; correctly supports comparing com.wm.data.IData objects. * * @param firstObject The first object in the comparison. * @param secondObject The seconds object in the comparison. * @return True if the two objects are equal, otherwise false. */ public static boolean equal(Object firstObject, Object secondObject) { boolean result = true; if (firstObject != null && secondObject != null) { if (firstObject instanceof IData && secondObject instanceof IData) { result = IDataUtil.equals((IData)firstObject, (IData)secondObject); } else { result = firstObject.equals(secondObject); } } else { result = (firstObject == null && secondObject == null); } return result; } /** * Returns true if the given object is an instance of the given class. * * @param object The object to be checked against the given class. * @param className The name of the class the given object will be tested against. * @return True if the given object is an instance of the given class. * @throws ClassNotFoundException If the given class name is not found. */ public static boolean instance(Object object, String className) throws ClassNotFoundException { return className != null && instance(object, Class.forName(className)); } /** * Returns true if the given object is an instance of the given class. * * @param object The object to be checked against the given class. * @param klass The class the given object will be tested against. * @return True if the given object is an instance of the given class. */ public static boolean instance(Object object, Class klass) { return object != null && klass != null && klass.isInstance(object); } /** * Returns a string representation of the given object. * @param object The object to stringify. * @return A string representation of the given object. */ public static String stringify(Object object) { if (object == null) return null; String output; if (object instanceof Object[][]) { output = ArrayHelper.stringify((Object[][]) object); } else if (object instanceof Object[]) { output = ArrayHelper.stringify((Object[]) object); } else if (object instanceof IData || object instanceof IDataCodable || object instanceof IDataPortable || object instanceof ValuesCodable) { output = IDataHelper.toIData(object).toString(); } else if (object instanceof IData[] || object instanceof Table || object instanceof IDataCodable[] || object instanceof IDataPortable[] || object instanceof ValuesCodable[]) { output = ArrayHelper.stringify(IDataHelper.toIDataArray(object)); } else { output = object.toString(); } return output; } /** * Returns the nearest class which is an ancestor to the classes of the given objects. * @param objects One or more objects to return the nearest ancestor for. * @return The nearest ancestor class which is an ancestor to the classes of the given objects. */ public static Class<?> getNearestAncestor(Object ...objects) { return getNearestAncestor(toClassSet(objects)); } /** * Returns the nearest class which is an ancestor to all the classes in the given set. * @param classes A set of classes for which the nearest ancestor will be returned. * @return The nearest ancestor class which is an ancestor to all the classes in the given set. */ public static Class<?> getNearestAncestor(Collection<Class<?>> classes) { Class<?> nearest = null; Set<Class<?>> ancestors = getAncestors(classes); if (ancestors.size() > 0) { nearest = ancestors.iterator().next(); } if (nearest == null) nearest = Object.class; return nearest; } /** * Returns the nearest class which is an ancestor to all the classes in the given set. * @param classes A set of classes for which the nearest ancestor will be returned. * @return The nearest ancestor class which is an ancestor to all the classes in the given set. */ public static Class<?> getNearestAncestor(Class<?>... classes) { return getNearestAncestor(java.util.Arrays.asList(classes)); } /** * Returns the nearest class which is an ancestor to all the classes in the given set. * @param classNames A set of class names for which the nearest ancestor will be returned. * @return The nearest ancestor class which is an ancestor to all the classes in the given set. * @throws ClassNotFoundException If any of the class names cannot be found. */ public static Class<?> getNearestAncestor(String... classNames) throws ClassNotFoundException { return getNearestAncestor(toClassArray(classNames)); } /** * Returns all the common ancestor classes from the given set of classes. * @param classes A collection of classes. * @return All the common ancestor classes from the given set of class names. */ public static Set<Class<?>> getAncestors(Collection<Class<?>> classes) { Set<Class<?>> intersection = new LinkedHashSet<Class<?>>(); for (Class<?> klass : classes) { if (intersection.size() == 0) { intersection.addAll(getAncestors(klass)); } else { intersection.retainAll(getAncestors(klass)); } } return intersection; } /** * Returns all the common ancestor classes from the given set of classes. * @param classes A list of classes. * @return All the common ancestor classes from the given set of class names. */ public static Class<?>[] getAncestors(Class<?>... classes) { Set<Class<?>> ancestors = getAncestors(java.util.Arrays.asList(classes)); return ancestors.toArray(new Class<?>[ancestors.size()]); } /** * Returns all the common ancestor classes from the given set of class names. * @param classNames A list of class names. * @return All the common ancestor classes from the given set of class names. * @throws ClassNotFoundException If a class name cannot be found. */ public static Class<?>[] getAncestors(String... classNames) throws ClassNotFoundException { return getAncestors(toClassArray(classNames)); } /** * Returns all the ancestor classes from nearest to furthest for the given class. * @param objects One or more objects to fetch the ancestors classes of. * @return All the ancestor classes from nearest to furthest for the class of the given object. */ public static Set<Class<?>> getAncestors(Object ...objects) { return getAncestors(toClassSet(objects)); } /** * Returns all the ancestor classes from nearest to furthest for the given class. * @param object An object to fetch the ancestors classes of. * @return All the ancestor classes from nearest to furthest for the class of the given object. */ public static Set<Class<?>> getAncestors(Object object) { return object == null ? new TreeSet<Class<?>>() : getAncestors(object.getClass()); } /** * Returns all the ancestor classes from nearest to furthest for the given class. * @param klass A class to fetch the ancestors of. * @return All the ancestor classes from nearest to furthest for the given class. */ private static Set<Class<?>> getAncestors(Class<?> klass) { Set<Class<?>> ancestors = new LinkedHashSet<Class<?>>(); Set<Class<?>> parents = new LinkedHashSet<Class<?>>(); parents.add(klass); do { ancestors.addAll(parents); Set<Class<?>> children = new LinkedHashSet<Class<?>>(parents); parents.clear(); for (Class<?> child : children) { Class<?> parent = child.getSuperclass(); if (parent != null) parents.add(parent); Collections.addAll(parents, child.getInterfaces()); } } while (!parents.isEmpty()); return ancestors; } /** * Converts the given list of class names to a list of classes. * @param classNames A list of class names. * @return A list of classes that correspond to the given names. * @throws ClassNotFoundException If a class name cannot be not found. */ private static Class<?>[] toClassArray(String[] classNames) throws ClassNotFoundException { if (classNames == null) return null; Class<?>[] classes = new Class<?>[classNames.length]; for (int i = 0; i < classes.length; i++) { classes[i] = Class.forName(classNames[i]); } return classes; } /** * Converts the given list of objects to a set of classes. * @param objects One or more objects to return a set of classes for. * @return The set of classes for the given list of objects. */ private static Set<Class<?>> toClassSet(Object ...objects) { Set<Class<?>> classes = new LinkedHashSet<Class<?>>(); for (Object object : objects) { if (object != null) classes.add(object.getClass()); } return classes; } /** * Converts a string, byte array or stream to a string, byte array or stream. * @param object The object to be converted. * @param charsetName The character set to use. * @param mode The desired return type of the object. * @return The converted object. * @throws IOException If an I/O problem occurs. */ public static Object convert(Object object, String charsetName, String mode) throws IOException { return convert(object, CharsetHelper.normalize(charsetName), mode); } /** * Converts a string, byte array or stream to a string, byte array or stream. * @param object The object to be converted. * @param charset The character set to use. * @param mode The desired return type of the object. * @return The converted object. * @throws IOException If an I/O problem occurs. */ public static Object convert(Object object, Charset charset, String mode) throws IOException { return convert(object, charset, ObjectConvertMode.normalize(mode)); } /** * Converts a string, byte array or stream to a string, byte array or stream. * @param object The object to be converted. * @param mode The desired return type of the object. * @return The converted object. * @throws IOException If an I/O problem occurs. */ public static Object convert(Object object, String mode) throws IOException { return convert(object, ObjectConvertMode.normalize(mode)); } /** * Converts a string, byte array or stream to a string, byte array or stream. * @param object The object to be converted. * @param mode The desired return type of the object. * @return The converted object. * @throws IOException If an I/O problem occurs. */ public static Object convert(Object object, ObjectConvertMode mode) throws IOException { return convert(object, CharsetHelper.DEFAULT_CHARSET, mode); } /** * Converts a string, byte array or stream to a string, byte array or stream. * @param object The object to be converted. * @param charset The character set to use. * @param mode The desired return type of the object. * @return The converted object. * @throws IOException If an I/O problem occurs. */ public static Object convert(Object object, Charset charset, ObjectConvertMode mode) throws IOException { if (object == null) return null; mode = ObjectConvertMode.normalize(mode); if (mode == ObjectConvertMode.BYTES) { object = BytesHelper.normalize(object, charset); } else if (mode == ObjectConvertMode.STRING) { object = StringHelper.normalize(object, charset); } else if (mode == ObjectConvertMode.BASE64) { object = BytesHelper.base64Encode(BytesHelper.normalize(object, charset)); } else if (mode == ObjectConvertMode.STREAM){ object = StreamHelper.normalize(object, charset); } else { throw new IllegalArgumentException("Unsupported conversion mode specified: " + mode); } return object; } }
package prm4j.indexing.realtime; import java.lang.ref.WeakReference; import prm4j.Util; import prm4j.api.Parameter; import prm4j.indexing.BaseMonitor; import prm4j.indexing.staticdata.MetaNode; public class DefaultNode extends AbstractNode { private final MetaNode metaNode; private final MonitorSet[] monitorSets; private BaseMonitor monitor; private final WeakReference<Node> nodeRef; /** * @param metaNode * @param key * may be null, if node is root node * @param hashCode * hash code of the key */ public DefaultNode(MetaNode metaNode, LowLevelBinding key, int hashCode) { super(key, hashCode); this.metaNode = metaNode; monitorSets = new MonitorSet[metaNode.getMonitorSetCount()]; nodeRef = new WeakReference<Node>(this); } @Override public MetaNode getMetaNode() { return metaNode; } @Override public BaseMonitor getMonitor() { return monitor; } @Override public Node getOrCreateNode(LowLevelBinding binding) { binding.registerNode(nodeRef); return getOrCreate(binding, binding.hashCode()); } @Override public Node getNode(LowLevelBinding binding) { return get(binding, binding.hashCode()); } @Override public void setMonitor(BaseMonitor monitor) { this.monitor = monitor; } @Override public void remove(LowLevelBinding binding) { super.remove(binding, binding.hashCode()); } @Override public MonitorSet getMonitorSet(int monitorSetId) { // lazy creation MonitorSet monitorSet = monitorSets[monitorSetId]; if (monitorSet == null) { monitorSet = new MonitorSet(); monitorSets[monitorSetId] = monitorSet; } return monitorSet; } @Override public MonitorSet[] getMonitorSets() { return monitorSets; } @Override public String toString() { if (monitor != null) { // output e.g.: (p2=b, p3=c, p5=e) return Util.bindingsToString(monitor.getLowLevelBindings()); } else { // output e.g.: (p2=?, p3=?, p5=e) because we only now the key and the node parameter set final StringBuilder sb = new StringBuilder(); sb.append("("); int i = 0; final int max = metaNode.getNodeParameterList().size(); for (Parameter<?> parameter : metaNode.getNodeParameterList()) { if (++i < max) { sb.append(parameter).append("=?, "); } else { break; } } final String key = getKey() == null ? "" : getKey().toString(); sb.append(key).append(")"); return sb.toString(); } } }
package ru.technoserv.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.stereotype.Repository; import java.math.BigDecimal; import java.util.List; import java.util.Set; @Repository public class OracleEmployeeDao implements EmployeeDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public void create(Employee employee) { throw new RuntimeException("create() not implemented"); } @Override public Employee read(int empID) { String sql = "SELECT e.EMP_ID, e.LAST_NAME, e.FIRST_NAME, e.PATR_NAME, e.GENDER, e.BIRTHDAY, e.SALARY, d.DEPT_NAME, p.TITLE, g.DESCRIPTION " + "FROM DEPARTMENT d, EMPLOYEE e, POSITION p, GRADE g " + "WHERE ((d.DEPT_ID = e.DEPARTMENT_ID) AND (e.EMP_ID = 13) AND (p.POS_ID = e.POSITION_ID) AND (e.GRADE_ID = g.GRD_ID))"; return (Employee) jdbcTemplate.queryForObject(sql, new Object[]{empID}, new EmployeeRowMapper()); } @Override public void delete(int empID) { String sql = "DELETE FROM EMPLOYEE WHERE EMP_ID = ?"; jdbcTemplate.update(sql,empID); } @Override public List<Employee> getAllFromDept(String deptName) { throw new RuntimeException("getAllFromDept() not implemented"); } @Override public void deleteAllFromDept(String deptName) { String sql = "SELECT DEPT_ID FROM DEPARTMENT WHERE DEPT_NAME = ?"; SqlRowSet set = jdbcTemplate.queryForRowSet(sql, deptName); set.first(); int deptID = set.getInt("DEPT_ID"); sql = "DELETE FROM EMPLOYEE WHERE DEPARTMENT_ID = ?"; jdbcTemplate.update(sql, deptID); } @Override public void updateDept(int empID, String newDept) { String sql = "SELECT DEPT_ID FROM DEPARTMENT WHERE DEPT_NAME = ?"; SqlRowSet set = jdbcTemplate.queryForRowSet(sql, newDept); set.first(); int newDeptID = set.getInt("DEPT_ID"); sql = "UPDATE EMPLOYEE SET DEPARTMENT_ID = ? WHERE EMP_ID = ?"; jdbcTemplate.update(sql, newDeptID, empID); } @Override public void updatePosition(int empID, String newPosition) { throw new RuntimeException("updatePosition() not implemented"); } @Override public void updateGrade(int empID, String newGrade) { throw new RuntimeException("updateGrade() not implemented"); } @Override public void updateSalary(int empID, BigDecimal newSalary) { String sql = "UPDATE EMPLOYEE SET SALARY = ? WHERE EMP_ID = ?"; jdbcTemplate.update(sql,newSalary, empID); } // public void create(Employee employee) { // String sql = "INSERT INTO EMPLOYEE" + // "(FIRST_NAME, LAST_NAME) VALUES (?,?)"; // jdbcTemplate.update(sql,employee.getFirstName(), employee.getLastName()); // public Employee read(String firstName, String lastName) { // String sql = "SELECT * FROM EMPLOYEE WHERE FIRST_NAME = ? AND LAST_NAME = ?"; // return (Employee) jdbcTemplate.queryForObject(sql, // new Object[]{firstName, lastName}, new EmployeeRowMapper()); // public void delete(String firstName, String lastName) { // String sql = "DELETE FROM EMPLOYEE WHERE FIRST_NAME = ? AND LAST_NAME = ?"; // jdbcTemplate.update(sql, firstName, lastName); }
package scrum.client.calendar; import ilarkesto.gwt.client.Date; import ilarkesto.gwt.client.Gwt; import java.util.HashMap; import java.util.List; import java.util.Map; import scrum.client.common.AScrumWidget; import scrum.client.common.BlockListSelectionManager; import scrum.client.common.BlockListWidget; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.Widget; public class DayListWidget extends AScrumWidget { private SimplePanel wrapper; private BlockListSelectionManager selectionManager; private Map<Date, BlockListWidget<SimpleEvent>> lists; @Override protected Widget onInitialization() { selectionManager = new BlockListSelectionManager(); lists = new HashMap<Date, BlockListWidget<SimpleEvent>>(); wrapper = new SimplePanel(); showDate(Date.today()); return wrapper; } @Override protected void onUpdate() { for (Map.Entry<Date, BlockListWidget<SimpleEvent>> entry : lists.entrySet()) { List<SimpleEvent> events = cm.getCalendar().getEventsByDate(entry.getKey()); entry.getValue().setObjects(events); } } public void showDate(Date dateToShow) { lists.clear(); selectionManager.clear(); FlexTable table = new FlexTable(); table.setWidth("100%"); table.setCellPadding(2); table.setBorderWidth(1); int row = 0; Date date = dateToShow; Date end = dateToShow.addDays(14); int month = 0; int week = 0; while (date.compareTo(end) <= 0) { int m = date.getMonth(); if (m != month) { month = m; table.setWidget(row, 0, Gwt.createDiv("DayListWidget-month", Gwt.getMonthShort(month))); } int w = date.getWeek(); if (w != week) { week = w; table.setWidget(row, 1, Gwt.createDiv("DayListWidget-week", String.valueOf(week))); } else { // table.setWidget(row, 0, new Label(".")); // table.setWidget(row, 0, Gwt.createDiv("DayListWidget-week", String.valueOf(week))); } table.setWidget(row, 2, Gwt.createDiv("DayListWidget-date", Gwt.DTF_DAY.format(date.toJavaDate()))); table.setWidget(row, 3, Gwt .createDiv("DayListWidget-date", Gwt.DTF_WEEKDAY_SHORT.format(date.toJavaDate()))); table.setWidget(row, 4, createEventList(date)); date = date.nextDay(); row++; } wrapper.setWidget(table); } public void showEvent(SimpleEvent event) { showDate(event.getDate()); update(); selectionManager.select(event); } private Widget createEventList(Date date) { BlockListWidget<SimpleEvent> list = new BlockListWidget<SimpleEvent>(SimpleEventBlock.FACTORY); list.setSelectionManager(selectionManager); list.setAutoSorter(SimpleEvent.TIME_COMPARATOR); lists.put(date, list); return list; } }
package sds.assemble.controlflow; import sds.classfile.bytecode.BranchOpcode; import sds.classfile.bytecode.OpcodeInfo; import sds.classfile.bytecode.Opcodes; import sds.classfile.bytecode.SwitchOpcode; import static sds.classfile.bytecode.MnemonicTable.monitorenter; import static sds.classfile.bytecode.MnemonicTable.monitorexit; /** * This enum class is for type of * {@link CFNode <code>CFNode</code>}. * @author inagaki */ public enum CFNodeType { Normal, Entry, Exit, Switch, StringSwitch, SynchronizedEntry, SynchronizedExit, LoopEntry, LoopExit, End; /** * returns type of control flow node. * @param opcodes opcode sequence * @param end end of opcode * @return node type */ public static CFNodeType getType(Opcodes opcodes, OpcodeInfo end) { if(hasSomeSwitchOpcode(opcodes)) { return StringSwitch; } CFNodeType type; if((type = searchType(end)) != Normal) { return type; } // processing for for-each statement. int index = 0; int[] keys = opcodes.getKeys(); while((index < keys.length) && (type = searchType(opcodes.get(keys[index]))) == Normal) { index++; } return type; } private static boolean hasSomeSwitchOpcode(Opcodes opcodes) { int count = 0; for(OpcodeInfo info : opcodes.getAll()) { if(info instanceof SwitchOpcode) { count++; } } return count > 1; } private static CFNodeType searchType(OpcodeInfo op) { if(op instanceof BranchOpcode) { searchBranchType(op); } if(op instanceof SwitchOpcode) { return Switch; } if(op.getOpcodeType() == monitorenter) { return SynchronizedEntry; } if(op.getOpcodeType() == monitorexit) { return SynchronizedExit; } return isReturn(op) ? End : Normal; } private static CFNodeType searchBranchType(OpcodeInfo op) { BranchOpcode branch = (BranchOpcode)op; switch(branch.getOpcodeType()) { case jsr: case jsr_w: // todo break; case _goto: case goto_w: if(branch.getBranch() > 0) { return Exit; } return LoopExit; } return Entry; } private static boolean isReturn(OpcodeInfo op) { switch(op.getOpcodeType()) { case _return: case areturn: case ireturn: case freturn: case lreturn: case dreturn: return true; default: return false; } } }
package seedu.address.storage; import javax.xml.bind.annotation.XmlValue; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.tag.Tag; /** * JAXB-friendly adapted version of the Tag. */ public class XmlAdaptedTag { @XmlValue public String tagName; /** * Constructs an XmlAdaptedTag. * This is the no-arg constructor that is required by JAXB. */ public XmlAdaptedTag() {} /** * Converts a given Tag into this class for JAXB use. * * @param source future changes to this will not affect the created */ public XmlAdaptedTag(Tag source) { tagName = source.tagName; } public Tag toModelType() throws IllegalValueException { return new Tag(tagName); } }
package seedu.manager.logic.parser; import static seedu.manager.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.manager.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import seedu.manager.commons.exceptions.IllegalValueException; import seedu.manager.commons.util.StringUtil; import seedu.manager.logic.commands.*; /** * Parses user input. */ public class AMParser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); private static final Pattern ACTIVITY_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>\\S+)(?<arguments>.*)"); private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace private static final Pattern ACTIVITY_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("(?<name>[^/]+)"); // variable number of tags /** * Various token counts */ private static final int ADD_DEADLINE_TOKEN_COUNT = 2; private static final int ADD_EVENT_TOKEN_COUNT = 2; public AMParser() {} /** * Parses user input into command for execution. * * @param userInput full user input string * @return the command based on the user input */ public Command parseCommand(String userInput) { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); switch (commandWord) { case AddCommand.COMMAND_WORD: return prepareAdd(arguments); case SelectCommand.COMMAND_WORD: return prepareSelect(arguments); case DeleteCommand.COMMAND_WORD: return prepareDelete(arguments); case UpdateCommand.COMMAND_WORD: return prepareUpdate(arguments); case MarkCommand.COMMAND_WORD: return prepareMark(arguments); case ClearCommand.COMMAND_WORD: return new ClearCommand(); case SearchCommand.COMMAND_WORD: return prepareSearch(arguments); case ListCommand.COMMAND_WORD: return new ListCommand(); case ExitCommand.COMMAND_WORD: return new ExitCommand(); case HelpCommand.COMMAND_WORD: return new HelpCommand(); default: return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } } /** * Parses arguments in the context of the add person command. * * @param args full command args string * @return the prepared command */ private Command prepareAdd(String args){ final Matcher matcher = ACTIVITY_DATA_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } String[] deadlineTokens = args.trim().split("on"); String[] eventTokens = args.trim().split("from"); try { if (deadlineTokens.length == ADD_DEADLINE_TOKEN_COUNT) { return new AddCommand(deadlineTokens[0].trim(), deadlineTokens[1].trim()); } else if (eventTokens.length == ADD_EVENT_TOKEN_COUNT) { String[] eventTimeTokens = eventTokens[1].split("to"); if (eventTimeTokens.length == ADD_EVENT_TOKEN_COUNT) { return new AddCommand(eventTokens[0].trim(), eventTimeTokens[0].trim(), eventTimeTokens[1].trim()); } else { return new AddCommand(matcher.group("name")); } } else { return new AddCommand(matcher.group("name")); } } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Extracts the new person's tags from the add command's tag arguments string. * Merges duplicate tag strings. */ private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException { // no tags if (tagArguments.isEmpty()) { return Collections.emptySet(); } // replace first delimiter prefix, then split final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/")); return new HashSet<>(tagStrings); } /** * Parses arguments in the context of the delete person command. * * @param args full command args string * @return the prepared command */ private Command prepareDelete(String args) { Optional<Integer> index = parseIndex(args); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } return new DeleteCommand(index.get()); } /** * Parses arguments in the context of the update activity command. * * @param args full command args string * @return the prepared command */ private Command prepareUpdate(String args) { final Matcher matcher = ACTIVITY_INDEX_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, UpdateCommand.MESSAGE_USAGE)); } // Validate index format Optional<Integer> index = parseIndex(matcher.group("targetIndex")); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, UpdateCommand.MESSAGE_USAGE)); } String arguments = matcher.group("arguments").trim(); String[] deadlineTokens = arguments.split("on"); String[] eventTokens = arguments.split("from"); try { if (deadlineTokens.length == ADD_DEADLINE_TOKEN_COUNT) { return new UpdateCommand(index.get(), deadlineTokens[0].trim(), deadlineTokens[1].trim()); } else if (eventTokens.length == ADD_EVENT_TOKEN_COUNT) { String[] eventTimeTokens = eventTokens[1].split("to"); if (eventTimeTokens.length == ADD_EVENT_TOKEN_COUNT) { return new UpdateCommand(index.get(), eventTokens[0].trim(), eventTimeTokens[0].trim(), eventTimeTokens[1].trim()); } else { return new UpdateCommand(index.get(), arguments); } } else { return new UpdateCommand(index.get(), arguments); } } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the mark activity command. * * @param args full command args string * @return the prepared command */ private Command prepareMark(String args) { final Matcher matcher = ACTIVITY_INDEX_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkCommand.MESSAGE_USAGE)); } // Validate index format Optional<Integer> index = parseIndex(matcher.group("targetIndex")); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkCommand.MESSAGE_USAGE)); } String[] splitArgs = (matcher.group("arguments").trim()).split("as"); String wordStatus; if (splitArgs.length == 1) { wordStatus = (splitArgs[0]).trim(); } else { wordStatus = (splitArgs[1]).trim(); } String lowerCaseArgs = wordStatus.toLowerCase(); boolean status; if (lowerCaseArgs.equals("pending")) { status = false; } else if (lowerCaseArgs.equals("completed")) { status = true; } else { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkCommand.MESSAGE_USAGE)); } return new MarkCommand(index.get(), status); } /** * Parses arguments in the context of the select person command. * * @param args full command args string * @return the prepared command */ private Command prepareSelect(String args) { Optional<Integer> index = parseIndex(args); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE)); } return new SelectCommand(index.get()); } /** * Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index. * Returns an {@code Optional.empty()} otherwise. */ private Optional<Integer> parseIndex(String command) { final Matcher matcher = ACTIVITY_INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String index = matcher.group("targetIndex"); if(!StringUtil.isUnsignedInteger(index)){ return Optional.empty(); } return Optional.of(Integer.parseInt(index)); } /** * Parses arguments in the context of the find person command. * * @param args full command args string * @return the prepared command */ private Command prepareSearch(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SearchCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new SearchCommand(keywordSet); } }
package seedu.scheduler.logic.parser; import seedu.scheduler.logic.commands.*; import seedu.scheduler.commons.util.StringUtil; import seedu.scheduler.commons.exceptions.IllegalValueException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static seedu.scheduler.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.scheduler.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; /** * Parses user input. */ public class Parser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); private static final Pattern ENTRY_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)"); private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace //@@author A0139956L private static final Pattern PATH_DATA_ARGS_FORMAT = Pattern.compile("(?<name>[\\p{Alnum}|/]+)"); //@@author A0161210A private static final Pattern ENTRY_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("(?<name>[^/]+)?" + "(?<isStartTimePrivate>p?)(?:(from/|f/|st/)(?<startTime>[^/]+))?" + "(?<isEndTimePrivate>p?)(?:(to/|et/)(?<endTime>[^/]+))?" + "(?<isDatePrivate>p?)(?:(on/|sdate/|sd/|)(?<date>[^/]+))?" + "(?<isEndDatePrivate>p?)(?:(ed/|by/|edate/)(?<endDate>[^/]+))?" + "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags //@@author A0152962B private static final Pattern ENTRY_EDIT_ARGS_FORMAT = Pattern.compile("(?<targetIndex>\\d+)" + "(?<name>[^/]+)" + "(?<isStartTimePrivate>p?)(?:(from/|f/|st/)(?<startTime>[^/]+))?" + "(?<isEndTimePrivate>p?)(?:(to/|et/)(?<endTime>[^/]+))?" + "(?<isDatePrivate>p?)(?:(on/|date/|sd/|by/)(?<date>[^/]+))?" + "(?<isEndDatePrivate>p?)(?:(edate/|ed/)(?<endDate>[^/]+))?" + "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags private CommandManager commandManager = new CommandManager(); //@@author public Parser() { } /** * Parses user input into command for execution. * * @param userInput * full user input string * @return the command based on the user input */ public Command parseCommand(String userInput) { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); //@@author A0161210A switch (commandWord) { case AddCommand.COMMAND_WORD: return prepareAdd(arguments); case AddCommand.COMMAND_WORD2: return prepareAdd(arguments); case SelectCommand.COMMAND_WORD: return commandManager.stackCommand(prepareSelect(arguments)); case SelectCommand.COMMAND_WORD2: return commandManager.stackCommand(prepareSelect(arguments)); case DeleteCommand.COMMAND_WORD: return prepareDelete(arguments); case DeleteCommand.COMMAND_WORD2: return prepareDelete(arguments); case EditCommand.COMMAND_WORD: return prepareEdit(arguments); case EditCommand.COMMAND_WORD2: return prepareEdit(arguments); //@@author A0126090N case MarkedCommand.COMMAND_WORD: return prepareMarked(arguments); case MarkedCommand.COMMAND_WORD2: return prepareMarked(arguments); //@@author case ClearCommand.COMMAND_WORD: return commandManager.stackCommand(new ClearCommand()); case ClearCommand.COMMAND_WORD2: return commandManager.stackCommand(new ClearCommand()); case FindCommand.COMMAND_WORD: return commandManager.stackCommand(prepareFind(arguments)); case FindCommand.COMMAND_WORD2: return commandManager.stackCommand(prepareFind(arguments)); case ListCommand.COMMAND_WORD: return new ListCommand(); case ListCommand.COMMAND_WORD2: return new ListCommand(); //@@author //@@author A0139956L case PathCommand.COMMAND_WORD: return commandManager.stackCommand(preparePath(arguments)); case PathCommand.COMMAND_WORD2: return commandManager.stackCommand(preparePath(arguments)); //@@author case ExitCommand.COMMAND_WORD: return new ExitCommand(); case ExitCommand.COMMAND_WORD2: return new ExitCommand(); //@@author A0152962B case "undo": commandManager.undo(); return null; case "redo": commandManager.redo(); return null; //@@author case HelpCommand.COMMAND_WORD: return new HelpCommand(); case HelpCommand.COMMAND_WORD2: return new HelpCommand(); default: return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } } /** * Parses arguments in the context of the add entry command. * * @param args * full command args string * @return the prepared command */ private Command prepareAdd(String args) { final Matcher matcher = ENTRY_DATA_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } try { return commandManager.stackCommand(new AddCommand(matcher.group("name"), matcher.group("startTime"), matcher.group("endTime"), matcher.group("date"), matcher.group("endDate"), getTagsFromArgs(matcher.group("tagArguments")))); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Extracts the new entry's tags from the add command's tag arguments * string. Merges duplicate tag strings. */ private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException { // no tags if (tagArguments.isEmpty()) { return Collections.emptySet(); } // replace first delimiter prefix, then split final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/")); return new HashSet<>(tagStrings); } /** * Parses arguments in the context of the delete entry command. * * @param args * full command args string * @return the prepared command */ private Command prepareDelete(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } return commandManager.stackCommand(new DeleteCommand(index.get())); } //@@author A0152962B /** * Parses arguments into the context of the edit entry command. * * @param args full command args string * @return the newly prepared command */ private Command prepareEdit(String args) { final Matcher matcher = ENTRY_EDIT_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } try { return new EditCommand(Integer.parseInt(matcher.group("targetIndex")), matcher.group("name"), matcher.group("startTime"), matcher.group("endTime"), matcher.group("date"), matcher.group("endDate"), getTagsFromArgs(matcher.group("tagArguments"))); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } //@@author A0126090N /** * Parses arguments in the context of the completed entry command. * * @param args full command args string * @return the prepared command */ private Command prepareMarked(String args) { final Matcher matcher = ENTRY_EDIT_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if(!matcher.matches()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkedCommand.MESSAGE_USAGE)); } try { return new MarkedCommand( Integer.parseInt(matcher.group("targetIndex")), matcher.group("name"), matcher.group("startTime"), matcher.group("endTime"), matcher.group("date"), matcher.group("endDate"), getTagsFromArgs(matcher.group("tagArguments")) ); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } //@@author /** * Parses arguments in the context of the select entry command. * * @param args * full command args string * @return the prepared command */ private Command prepareSelect(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE)); } return new SelectCommand(index.get()); } //@@author /** * Returns the specified index in the {@code command} IF a positive unsigned * integer is given as the index. Returns an {@code Optional.empty()} * otherwise. */ private Optional<Integer> parseIndex(String command) { final Matcher matcher = ENTRY_INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String index = matcher.group("targetIndex"); if (!StringUtil.isUnsignedInteger(index)) { return Optional.empty(); } return Optional.of(Integer.parseInt(index)); } /** * Parses arguments in the context of the find entry command. * * @param args * full command args string * @return the prepared command */ private Command prepareFind(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new FindCommand(keywordSet); } //@@author A0139956L /** * Parses arguments in the context of the file path command. * * @param args full command args string * @return the prepared command */ private Command preparePath(String args) { final Matcher matcher = PATH_DATA_ARGS_FORMAT.matcher(args.trim()); //Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, PathCommand.MESSAGE_USAGE)); } else { String filePath = matcher.group("name").trim().replaceAll("/$", "") + ".xml"; //store input to filePath return new PathCommand(filePath); //push input to PathCommand } } //@@author }
package seedu.typed.schedule; import seedu.typed.model.task.DateTime; //@@author A0139379M public interface TimeExpression { /** * Checks if date falls within TimeExpression * i.e if 12/12/2017 falls within every Monday * or second tuesday of every month etc * * @params date * @return True if TimeExpression includes date **/ public boolean includes(DateTime date); /** * Returns the next DateTime * where it falls within the TimeExpression * * @param date * @return the next occurring DateTime object where * includes return true */ public DateTime nextOccurrence(DateTime date); }
package ut.programming.training; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; import org.apache.commons.lang3.StringUtils; public class Application { public int countWords(String words) { String[] separateWords = StringUtils.split(words, ' '); return (separateWords == null) ? 0 : separateWords.length; } public void greet() { List<String> greetings = new ArrayList<>(); greetings.add("Hello"); for (String greeting : greetings) { System.out.println("Greeting: " + greeting); } } public void dict() { Map<String, String> map = new HashMap<String, String>(); map.put("name", "Alex Unstoppable") System.out.println(map.get("dog")); } public Application() { System.out.println ("Inside Application"); } // method main(): ALWAYS the APPLICATION entry point public static void main (String[] args) { System.out.println ("Starting Application"); Application app = new Application(); app.greet(); int count = app.countWords("I have five words ha."); System.out.println("Word Count: " + count); app.dict(); } }
package valandur.webapi.hook; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.spongepowered.api.Platform; import org.spongepowered.api.Sponge; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Event; import org.spongepowered.api.event.EventListener; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; import org.spongepowered.api.event.advancement.AdvancementEvent; import org.spongepowered.api.event.block.InteractBlockEvent; import org.spongepowered.api.event.command.SendCommandEvent; import org.spongepowered.api.event.entity.DestructEntityEvent; import org.spongepowered.api.event.entity.ExpireEntityEvent; import org.spongepowered.api.event.entity.SpawnEntityEvent; import org.spongepowered.api.event.entity.living.humanoid.player.KickPlayerEvent; import org.spongepowered.api.event.filter.cause.First; import org.spongepowered.api.event.game.state.GameStartedServerEvent; import org.spongepowered.api.event.game.state.GameStoppedServerEvent; import org.spongepowered.api.event.game.state.GameStoppingEvent; import org.spongepowered.api.event.item.inventory.InteractInventoryEvent; import org.spongepowered.api.event.message.MessageChannelEvent; import org.spongepowered.api.event.network.ClientConnectionEvent; import org.spongepowered.api.event.user.BanUserEvent; import org.spongepowered.api.event.world.*; import org.spongepowered.api.text.Text; import org.spongepowered.api.util.Tuple; import valandur.webapi.WebAPI; import valandur.webapi.block.BlockOperationStatusChangeEvent; import valandur.webapi.config.BaseConfig; import valandur.webapi.config.HookConfig; import valandur.webapi.hook.filter.BaseWebHookFilter; import valandur.webapi.hook.filter.BlockTypeFilter; import valandur.webapi.hook.filter.ItemTypeFilter; import valandur.webapi.hook.filter.PlayerFilter; import valandur.webapi.util.Constants; import valandur.webapi.util.Timings; import java.io.*; import java.net.*; import java.nio.file.Path; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; /** * The web hook service provides access to the Web-API web hooks. */ public class WebHookService { private static final String configFileName = "hooks.conf"; private static String userAgent = Constants.NAME + "/" + Constants.VERSION; /** * Some base types of WebHooks that are included with the WebAPI */ public enum WebHookType { ALL, CUSTOM_COMMAND, CUSTOM_EVENT, INTERACTIVE_MESSAGE, ADVANCEMENT, BLOCK_OPERATION_STATUS, CHAT, COMMAND, GENERATE_CHUNK, EXPLOSION, INTERACT_BLOCK, INVENTORY_OPEN, INVENTORY_CLOSE, PLAYER_JOIN, PLAYER_LEAVE, PLAYER_DEATH, PLAYER_KICK, PLAYER_BAN, SERVER_START, SERVER_STOP, WORLD_SAVE, WORLD_LOAD, WORLD_UNLOAD, ENTITY_SPAWN, ENTITY_DESPAWN, ENTITY_EXPIRE } private Map<String, CommandWebHook> commandHooks = new HashMap<>(); private Map<WebHookType, List<WebHook>> eventHooks = new HashMap<>(); private Map<Class<? extends Event>, Tuple<List<WebHook>, EventListener>> customHooks = new HashMap<>(); private Map<String, Class<? extends BaseWebHookFilter>> filters = new HashMap<>(); public Map<String, CommandWebHook> getCommandHooks() { return commandHooks; } public void init() { Logger logger = WebAPI.getLogger(); logger.info("Initializing web hooks..."); // Remove existing listeners to prevent multiple subscriptions on config reload for (Tuple<List<WebHook>, EventListener> entry : customHooks.values()) { Sponge.getEventManager().unregisterListeners(entry.getSecond()); } // Save some basic data Platform platform = Sponge.getPlatform(); String mc = platform.getContainer(Platform.Component.GAME).getVersion().orElse("?"); String sponge = platform.getContainer(Platform.Component.IMPLEMENTATION).getVersion().orElse("?"); userAgent = Constants.NAME + "/" + Constants.VERSION + " Sponge/" + sponge + " Minecraft/" + mc + " Java/" + System.getProperty("java.version"); // Load filters logger.info("Loading filters..."); filters.clear(); // Add some default filters filters.put(BlockTypeFilter.name, BlockTypeFilter.class); filters.put(PlayerFilter.name, PlayerFilter.class); filters.put(ItemTypeFilter.name, ItemTypeFilter.class); logger.info("Done loading filters"); // Load config Path configPath = WebAPI.getConfigPath().resolve(configFileName).normalize(); HookConfig config = BaseConfig.load(configPath, new HookConfig()); // Clear hooks eventHooks.clear(); customHooks.clear(); commandHooks.clear(); // Add command hooks for (Map.Entry<String, CommandWebHook> entry : config.command.entrySet()) { if (!entry.getValue().isEnabled()) continue; commandHooks.put(entry.getKey(), entry.getValue()); } // Add event hooks for (Map.Entry<WebHookType, List<WebHook>> entry : config.events.asMap().entrySet()) { eventHooks.put( entry.getKey(), entry.getValue().stream().filter(WebHook::isEnabled).collect(Collectors.toList()) ); } // Add custom event hooks for (Map.Entry<String, List<WebHook>> entry : config.custom.entrySet()) { String className = entry.getKey(); try { Class c = Class.forName(className); if (!Event.class.isAssignableFrom(c)) throw new InvalidClassException("Class " + c.toString() + " must be a subclass of " + Event.class.toString() + " so that it can be used as a custom web hook"); Class<? extends Event> clazz = (Class<? extends Event>) c; WebHookEventListener listener = new WebHookEventListener(clazz); List<WebHook> hooks = entry.getValue().stream().filter(WebHook::isEnabled).collect(Collectors.toList()); Sponge.getEventManager().registerListener(WebAPI.getInstance(), clazz, listener); customHooks.put(clazz, new Tuple<>(hooks, listener)); } catch (ClassNotFoundException e) { logger.error("Could not find class for custom web hook: " + className); } catch (InvalidClassException e) { logger.error(e.getMessage()); } } } public Optional<Class<? extends BaseWebHookFilter>> getFilter(String name) { return filters.containsKey(name) ? Optional.of(filters.get(name)) : Optional.empty(); } /** * Trigger a WebHook of the specified type, sending along the specified data. * @param type The type of WebHook * @param data The data that is sent to the endpoints. */ public void notifyHooks(WebHookType type, Object data) { Timings.WEBHOOK_NOTIFY.startTimingIfSync(); List<WebHook> notifyHooks = new ArrayList<>(eventHooks.get(type)); notifyHooks.addAll(eventHooks.get(WebHookType.ALL)); for (WebHook hook : notifyHooks) { notifyHook(hook, type, null, data); } Timings.WEBHOOK_NOTIFY.stopTimingIfSync(); } public void notifyHook(CommandWebHook cmdHook, String source, Map<String, Object> data) { Timings.WEBHOOK_NOTIFY.startTimingIfSync(); for (WebHook hook : cmdHook.getHooks()) { notifyHook(hook, WebHookType.CUSTOM_COMMAND, source, data); } Timings.WEBHOOK_NOTIFY.stopTimingIfSync(); } /** * Trigger an event WebHook for the specified event. * @param clazz The class of event for which the WebHooks are triggered. * @param data The data that is sent to the endpoints. */ public void notifyHooks(Class<? extends Event> clazz, Object data) { Timings.WEBHOOK_NOTIFY.startTimingIfSync(); List<WebHook> notifyHooks = new ArrayList<>(customHooks.get(clazz).getFirst()); for (WebHook hook : notifyHooks) { notifyHook(hook, WebHookType.CUSTOM_EVENT, null, data); } Timings.WEBHOOK_NOTIFY.stopTimingIfSync(); } private void notifyHook(WebHook hook, WebHookType eventType, String source, Object data) { // First check the filter before we do any processing if (hook.getFilter() != null && !hook.getFilter().process(data)) { return; } final String address = hook.getAddress(); String stringData = ""; try { ObjectMapper om = WebAPI.getSerializeService().getDefaultObjectMapper( hook.getDataType() == WebHook.WebHookDataType.XML, hook.includeDetails(), hook.getPermissions() ); stringData = om.writeValueAsString(data); } catch (JsonProcessingException e) { e.printStackTrace(); } if (data != null) { try { stringData = hook.isForm() ? "body=" + URLEncoder.encode(stringData, "UTF-8") : stringData; } catch (Exception e) { e.printStackTrace(); WebAPI.sentryCapture(e); } } final String finalData = stringData; final Logger logger = WebAPI.getLogger(); CompletableFuture.runAsync(() -> { HttpURLConnection connection = null; try { //Create connection URL url = new URL(address); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(hook.getMethod()); for (WebHookHeader header : hook.getHeaders()) { connection.setRequestProperty(header.getName(), header.getValue()); } connection.setRequestProperty("User-Agent", userAgent); connection.setRequestProperty("X-WebAPI-Version", Constants.VERSION); connection.setRequestProperty("X-WebAPI-Event", eventType.toString()); if (source != null) connection.setRequestProperty("X-WebAPI-Source", source); connection.setRequestProperty("accept", "application/json"); connection.setRequestProperty("charset", "utf-8"); if (finalData != null) { connection.setRequestProperty("Content-Type", hook.getDataTypeHeader()); connection.setRequestProperty("Content-Length", Integer.toString(finalData.getBytes().length)); } connection.setUseCaches(false); //Send request if (finalData != null) { connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(finalData); wr.close(); } //Get Response int code = connection.getResponseCode(); if (code != 200) { logger.warn("Hook '" + hook.getAddress() + "' responded with code: " + code); return; } InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuilder response = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); String respString = response.toString().trim(); if (respString.isEmpty() || respString.equalsIgnoreCase("OK")) return; final WebHookResponse resp = new ObjectMapper().readValue(respString, WebHookResponse.class); Text msg = resp.getMessage(); WebAPI.runOnMain(() -> { for (String target : resp.getTargets()) { if (target.equalsIgnoreCase("server")) { Sponge.getServer().getBroadcastChannel().send(msg); continue; } Optional<Player> p = Sponge.getServer().getPlayer(UUID.fromString(target)); if (!p.isPresent()) continue; p.get().sendMessage(msg); } }); } catch (ConnectException e) { logger.warn("Could not connect to hook '" + hook.getAddress() + "': " + e.getMessage()); } catch (ProtocolException e) { logger.warn("Unknown protocol for hook '" + hook.getAddress() + "': " + e.getMessage()); } catch (MalformedURLException e) { logger.warn("Malformed URL for hook '" + hook.getAddress() + "': " + e.getMessage()); } catch (IOException e) { logger.warn("IO Error from hook '" + hook.getAddress() + "': " + e.getMessage()); } finally { if (connection != null) { connection.disconnect(); } } }); } // Server events @Listener(order = Order.POST) public void onServerStart(GameStartedServerEvent event) { notifyHooks(WebHookService.WebHookType.SERVER_START, event); } @Listener(order = Order.PRE) public void onServerStop(GameStoppingEvent event) { notifyHooks(WebHookService.WebHookType.SERVER_STOP, event); } @Listener(order = Order.POST) public void onWorldLoad(LoadWorldEvent event) { notifyHooks(WebHookService.WebHookType.WORLD_LOAD, event); } @Listener(order = Order.POST) public void onWorldUnload(UnloadWorldEvent event) { notifyHooks(WebHookService.WebHookType.WORLD_UNLOAD, event); } @Listener(order = Order.POST) public void onWorldSave(SaveWorldEvent event) { notifyHooks(WebHookService.WebHookType.WORLD_SAVE, event); } @Listener(order = Order.POST) public void onPlayerJoin(ClientConnectionEvent.Join event) { notifyHooks(WebHookService.WebHookType.PLAYER_JOIN, event); } @Listener(order = Order.PRE) public void onPlayerLeave(ClientConnectionEvent.Disconnect event) { notifyHooks(WebHookService.WebHookType.PLAYER_LEAVE, event); } @Listener(order = Order.PRE) public void onUserKick(KickPlayerEvent event) { notifyHooks(WebHookService.WebHookType.PLAYER_KICK, event); } @Listener(order = Order.PRE) public void onUserBan(BanUserEvent event) { notifyHooks(WebHookService.WebHookType.PLAYER_BAN, event); } @Listener(order = Order.POST) public void onEntitySpawn(SpawnEntityEvent event) { notifyHooks(WebHookService.WebHookType.ENTITY_SPAWN, event); } @Listener(order = Order.PRE) public void onEntityDespawn(DestructEntityEvent event) { Entity ent = event.getTargetEntity(); if (ent instanceof Player) { notifyHooks(WebHookService.WebHookType.PLAYER_DEATH, event); } else { notifyHooks(WebHookService.WebHookType.ENTITY_DESPAWN, event); } } @Listener(order = Order.PRE) public void onEntityExpire(ExpireEntityEvent event) { notifyHooks(WebHookService.WebHookType.ENTITY_EXPIRE, event); } @Listener(order = Order.POST) public void onPlayerChat(MessageChannelEvent.Chat event, @First Player player) { notifyHooks(WebHookService.WebHookType.CHAT, event); } @Listener(order = Order.POST) public void onMessage(MessageChannelEvent event) { notifyHooks(WebHookService.WebHookType.CHAT, event); } @Listener(order = Order.POST) public void onInteractBlock(InteractBlockEvent event) { notifyHooks(WebHookService.WebHookType.INTERACT_BLOCK, event); } @Listener(order = Order.POST) public void onInteractInventory(InteractInventoryEvent.Open event) { notifyHooks(WebHookService.WebHookType.INVENTORY_OPEN, event); } @Listener(order = Order.POST) public void onInteractInventory(InteractInventoryEvent.Close event) { notifyHooks(WebHookService.WebHookType.INVENTORY_CLOSE, event); } @Listener(order = Order.POST) public void onPlayerAdvancement(AdvancementEvent.Grant event) { notifyHooks(WebHookService.WebHookType.ADVANCEMENT, event); } @Listener(order = Order.POST) public void onGenerateChunk(GenerateChunkEvent event) { notifyHooks(WebHookService.WebHookType.GENERATE_CHUNK, event); } @Listener(order = Order.POST) public void onExplosion(ExplosionEvent event) { notifyHooks(WebHookService.WebHookType.EXPLOSION, event); } @Listener(order = Order.POST) public void onCommand(SendCommandEvent event) { notifyHooks(WebHookService.WebHookType.COMMAND, event); } @Listener(order = Order.POST) public void onBlockUpdateStatusChange(BlockOperationStatusChangeEvent event) { notifyHooks(WebHookService.WebHookType.BLOCK_OPERATION_STATUS, event); } }
package wasdev.sample.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import com.ibm.watson.developer_cloud.language_translation.v2.model.*; import com.ibm.watson.developer_cloud.language_translation.v2.*; import com.ibm.watson.developer_cloud.conversation.v1.*; import com.ibm.watson.developer_cloud.conversation.v1.model.*; import com.ibm.watson.developer_cloud.conversation.v1_experimental.model.*; import com.ibm.watson.developer_cloud.conversation.v1.ConversationService; /** * Servlet implementation class SimpleServlet */ @WebServlet("/SimpleServlet") public class SimpleServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String content = new String("This is English good morning!"); String param = request.getParameter("content"); getTranslatedResult(param); //response.setContentType("text/html"); //response.getWriter().print("result is " + result.toString()); //System.out.println("result is " + result); response.setContentType("application/json"); response.getWriter().print("V22 Dian Dian " + result.toString()); } private static LanguageTranslation service = new LanguageTranslation(); private static TranslationResult result; public static void getTranslatedResult(String content) { //System.getenv("VCAP_SERVICES"); //service.setUsernameAndPassword("d02a80d2-fb2a-4941-9d74-7ed0e72541c4", "i6YdoXRKCWEz"); service.setEndPoint("https://gateway.watsonplatform.net/language-translator/api"); service.setUsernameAndPassword("d02a80d2-fb2a-4941-9d74-7ed0e72541c4", "i6YdoXRKCWEz"); result = service.translate(content, Language.ENGLISH, Language.SPANISH).execute(); } /*private static ConversationService service = new ConversationService("2016-09-30"); public static void main(String[] args) { service }*/ }
package wasdev.sample.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import com.ibm.watson.developer_cloud.language_translation.v2.model.*; import com.ibm.watson.developer_cloud.language_translation.v2.*; import com.ibm.watson.developer_cloud.conversation.v1.*; import com.ibm.watson.developer_cloud.conversation.v1.model.*; import com.ibm.watson.developer_cloud.conversation.v1_experimental.model.*; import com.ibm.watson.developer_cloud.conversation.v1.ConversationService; /** * Servlet implementation class SimpleServlet */ @WebServlet("/SimpleServlet") public class SimpleServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { getTranslatedResult(); //response.setContentType("text/html"); //response.getWriter().print("result is " + result.toString()); //System.out.println("result is " + result); response.setContentType("application/json"); response.getWriter().print(result); } private static LanguageTranslation service = new LanguageTranslation(); private static TranslationResult result; public static void getTranslatedResult() { //System.getenv("VCAP_SERVICES"); //service.setUsernameAndPassword("d02a80d2-fb2a-4941-9d74-7ed0e72541c4", "i6YdoXRKCWEz"); service.setEndPoint("https://gateway.watsonplatform.net/language-translator/api"); service.setUsernameAndPassword("d02a80d2-fb2a-4941-9d74-7ed0e72541c4", "i6YdoXRKCWEz"); result = service.translate("This is English Good Morning!", Language.ENGLISH, Language.FRENCH).execute(); } /*private static ConversationService service = new ConversationService("2016-09-30"); public static void main(String[] args) { service }*/ }
package org.jasig.portal.properties; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.Properties; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Provides access to properties. * <p>It is important to understand that usage of this class is different from what you might * be used to in java.util.Properties. Specifically, when you get a Properties property, * if that property is not set, the return value is NULL. However, when you call the basic getters here, * if the property is not set, a RuntimeException is thrown. These methods will never return null (except * if you pass in null as the default return value for the methods that take a default).</p> * <p>There are methods to get properties as various primitive types, int, double, float, etc. * When you invoke one of these methods on a property that is found but cannot be parsed as * your desired type, a RuntimeException is thrown.</p> * <p>There are * corresponding methods which take as a second parameter a default value. These methods, instead of * throwing a RuntimeException when the property cannot be found, return the default value. You can * use the default value "null" to invoke getProperty() with semantics more like the java.util.Properties object. * These augmented accessors which take defaults will be, I hope, especially useful in static initializers. Providing a * default in your static initializer will keep your class from blowing up at initialization when your property cannot be found. * This seems especially advantageous when there is a plausible default value.</p> * <p>This class has a comprehensive JUnit testcase. Please keep the testcase up to date with any changes you make to this class.</p> * @author Ken Weiner, kweiner@unicon.net * @author howard.gilbert@yale.edu * @author andrew.petro@yale.edu * @version $Revision$ $Date$ * @since uPortal 2.0 */ public class PropertiesManager { protected static final Log log = LogFactory.getLog(PropertiesManager.class); public static final String PORTAL_PROPERTIES_FILE_SYSTEM_VARIABLE = "portal.properties"; private static final String PORTAL_PROPERTIES_FILE_NAME = "/properties/portal.properties"; private static Properties props = null; /** * A set of the names of properties that clients of this class attempt to access * but which were not set in the properties file. * This Set allows this class to report about missing properties and to * log each missing property only the first time it is requested. */ private static final Set missingProperties = Collections.synchronizedSet(new HashSet()); /** * Setter method to set the underlying Properties. * This is a public method to allow poor-man's static dependency injection of the Properties from wherever you want to get them. * If Properties have not been injected before any accessor method is invoked, PropertiesManager will invoke loadProperties() to attempt * to load its own properties. You might call this from a context listener, say. * If Properties have already been loaded or injected, this method will overwrite them. * @param props - Properties to be injected. */ public static synchronized void setProperties(Properties props){ PropertiesManager.props = props; } /** * Load up the portal properties. Right now the portal properties is a simple * .properties file with name value pairs. It may evolve to become an XML file * later on. */ protected static void loadProps() { Properties properties = new Properties(); try { String pfile = System.getProperty(PORTAL_PROPERTIES_FILE_SYSTEM_VARIABLE); if (pfile == null) { pfile = PORTAL_PROPERTIES_FILE_NAME; } properties.load(PropertiesManager.class.getResourceAsStream(pfile)); PropertiesManager.props = properties; } catch (Throwable t) { log.error("Unable to read portal.properties file.", t); } } /** * Returns the value of a property for a given name. * Any whitespace is trimmed off the beginning and * end of the property value. * Note that this method will never return null. * If the requested property cannot be found, this method throws an UndeclaredPortalException. * @param name the name of the requested property * @return value the value of the property matching the requested name * @throws MissingPropertyException - if the requested property cannot be found */ public static String getProperty(String name) throws MissingPropertyException{ if (log.isTraceEnabled()){ log.trace("entering getProperty(" + name + ")"); } if (PropertiesManager.props == null) loadProps(); String val = getPropertyUntrimmed(name); val = val.trim(); if (log.isTraceEnabled()){ log.trace("returning from getProperty(" + name + ") with return value [" + val + "]"); } return val; } /** * Returns the value of a property for a given name * including whitespace trailing the property value, but not including * whitespace leading the property value. * An UndeclaredPortalException is thrown if the property cannot be found. * This method will never return null. * @param name the name of the requested property * @return value the value of the property matching the requested name * @throws MissingPropertyException - (undeclared) if the requested property is not found */ public static String getPropertyUntrimmed(String name) throws MissingPropertyException { if (PropertiesManager.props == null) loadProps(); String val = props.getProperty(name); if (val == null) { boolean alreadyReported = registerMissingProperty(name); throw new MissingPropertyException(name, alreadyReported); } return val; } /** * Returns the value of a property for a given name. * This method can be used if the property is boolean in * nature and you want to make sure that <code>true</code> is * returned if the property is set to "true", "yes", "y", or "on" * (regardless of case), * and <code>false</code> is returned in all other cases. * @param name the name of the requested property * @return value <code>true</code> if property is set to "true", "yes", "y", or "on" regardless of case, otherwise <code>false</code> * @throws MissingPropertyException - when no property of the given name is declared. */ public static boolean getPropertyAsBoolean(String name) throws MissingPropertyException { if (PropertiesManager.props == null) loadProps(); boolean retValue = false; String value = getProperty(name); if (value != null) { if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("y") || value.equalsIgnoreCase("on")){ retValue = true; } else if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("no") || value.equalsIgnoreCase("n") || value.equalsIgnoreCase("off")){ retValue = false; } else { // this method's historical behavior, maintained here, is to return false for all values that did not match on of the true values above. log.error("property [" + name + "] is being accessed as a boolean but had non-canonical value [" + value + "]. Returning it as false, but this may be a property misconfiguration."); } } else { log.fatal("property [" + name + "] is being accessed as a boolean but was null. Returning false. However, it should not have been possible to get here because getProperty() throws a runtime exception or returns a non-null value."); } return retValue; } /** * Returns the value of a property for a given name as a <code>byte</code> * @param name the name of the requested property * @return value the property's value as a <code>byte</code> * @throws MissingPropertyException - if the property is not set * @throws BadPropertyException - if the property cannot be parsed as a byte */ public static byte getPropertyAsByte(String name) throws MissingPropertyException, BadPropertyException { if (PropertiesManager.props == null) loadProps(); try { return Byte.parseByte(getProperty(name)); } catch (NumberFormatException nfe) { throw new BadPropertyException(name, getProperty(name), "byte"); } } /** * Returns the value of a property for a given name as a <code>short</code> * @param name the name of the requested property * @return value the property's value as a <code>short</code> * @throws MissingPropertyException - if the property is not set * @throws BadPropertyException - if the property cannot be parsed as a short or is not set. */ public static short getPropertyAsShort(String name) throws MissingPropertyException, BadPropertyException { if (PropertiesManager.props == null) loadProps(); try { return Short.parseShort(getProperty(name)); } catch (NumberFormatException nfe){ throw new BadPropertyException(name, getProperty(name), "short"); } } /** * Returns the value of a property for a given name as an <code>int</code> * @param name the name of the requested property * @return value the property's value as an <code>int</code> * @throws MissingPropertyException - if the property is not set * @throws BadPropertyException - if the property cannot be parsed as an int */ public static int getPropertyAsInt(String name) throws MissingPropertyException, BadPropertyException { if (PropertiesManager.props == null) loadProps(); try { return Integer.parseInt(getProperty(name)); } catch (NumberFormatException nfe){ throw new BadPropertyException(name, getProperty(name), "int"); } } /** * Returns the value of a property for a given name as a <code>long</code> * @param name the name of the requested property * @return value the property's value as a <code>long</code> * @throws MissingPropertyException - if the property is not set * @throws BadPropertyException - if the property cannot be parsed as a long */ public static long getPropertyAsLong(String name) throws MissingPropertyException, BadPropertyException { if (PropertiesManager.props == null) loadProps(); try { return Long.parseLong(getProperty(name)); } catch (NumberFormatException nfe) { throw new BadPropertyException(name, getProperty(name), "long"); } } /** * Returns the value of a property for a given name as a <code>float</code> * @param name the name of the requested property * @return value the property's value as a <code>float</code> * @throws MissingPropertyException - if the property is not set * @throws BadPropertyException - if the property cannot be parsed as a float */ public static float getPropertyAsFloat(String name) throws MissingPropertyException, BadPropertyException { if (PropertiesManager.props == null) loadProps(); try { return Float.parseFloat(getProperty(name)); } catch (NumberFormatException nfe) { throw new BadPropertyException(name, getProperty(name), "float"); } } /** * Returns the value of a property for a given name as a <code>long</code> * @param name the name of the requested property * @return value the property's value as a <code>double</code> * @throws MissingPropertyException - if the property has not been set * @throws BadPropertyException - if the property cannot be parsed as a double or is not set. */ public static double getPropertyAsDouble(String name) throws MissingPropertyException, BadPropertyException { if (PropertiesManager.props == null) loadProps(); try { return Double.parseDouble(getProperty(name)); } catch (NumberFormatException nfe) { throw new BadPropertyException(name, getProperty(name), "double"); } } /** * Registers that a given property was sought but not found. * Currently adds the property to the set of missing properties and * logs if this is the first time the property has been requested. * @param name - the name of the missing property * @return true if the property was previously registered, false otherwise * */ private static boolean registerMissingProperty(String name) { final boolean previouslyReported = !PropertiesManager.missingProperties.add(name); if (!previouslyReported){ log.info("Property [" + name + "] was requested but not found."); } return previouslyReported; } /** * Get the value of the property with the given name. * If the named property is not found, returns the supplied default value. * This error handling behavior makes this method attractive for use in static initializers. * @param name - the name of the property to be retrieved. * @param defaultValue - a fallback default value which will be returned if the property cannot be found. * @return the value of the requested property, or the supplied default value if the named property cannot be found. * @since uPortal 2.4 */ public static String getProperty(String name, String defaultValue) { if (PropertiesManager.props == null) loadProps(); String returnValue = defaultValue; try { returnValue = getProperty(name); } catch (MissingPropertyException mpe){ // Do nothing, since we have already recorded and logged the missing property. } return returnValue; } /** * Get the value of a property for the given name * including any whitespace that may be at the beginning or end of the property value. * This method returns the supplied default value if the requested property cannot be found. * This error handling behavior makes this method attractive for use in static initializers. * @param name - the name of the requested property * @param defaultValue - a default value to fall back on if the property cannot be found * @return the value of the property with the given name, or the supplied default value if the property could not be found. * @since uPortal 2.4 */ public static String getPropertyUntrimmed(String name, String defaultValue) { if (PropertiesManager.props == null) loadProps(); String returnValue = defaultValue; try { returnValue = getPropertyUntrimmed(name); } catch (MissingPropertyException mpe) { // do nothing, since we have already logged the missing property } return returnValue; } /** * Get a property as a boolean, specifying a default value. * If for any reason we are unable to lookup the desired property, * this method returns the supplied default value. * This error handling behavior makes this method suitable for calling from static initializers. * @param name - the name of the property to be accessed * @param defaultValue - default value that will be returned in the event of any error * @return the looked up property value, or the defaultValue if any problem. * @since uPortal 2.4 */ public static boolean getPropertyAsBoolean(final String name, final boolean defaultValue){ if (PropertiesManager.props == null) loadProps(); boolean returnValue = defaultValue; try { returnValue = getPropertyAsBoolean(name); } catch (MissingPropertyException mpe) { // do nothing, since we already logged the missing property } return returnValue; } /** * Get the value of the given property as a byte, specifying a fallback default value. * If for any reason we are unable to lookup the desired property, * this method returns the supplied default value. * This error handling behavior makes this method suitable for calling from static initializers. * @param name - the name of the property to be accessed * @param defaultValue - the default value that will be returned in the event of any error * @return the looked up property value, or the defaultValue if any problem. * @since uPortal 2.4 */ public static byte getPropertyAsByte(final String name, final byte defaultValue) { if (PropertiesManager.props == null) loadProps(); byte returnValue = defaultValue; try { returnValue = getPropertyAsByte(name); } catch (Throwable t){ log.error("Could not retrieve or parse as byte property [" + name + "], defaulting to [" + defaultValue + "]", t); } return returnValue; } /** * Returns the value of a property for a given name as a short. * If for any reason the property cannot be looked up as a short, returns the supplied default value. * This error handling makes this method a good choice for static initializer calls. * @param name - the name of the requested property * @param defaultValue - a default value that will be returned in the event of any error * @return the property value as a short or the default value in the event of any error * @since uPortal 2.4 */ public static short getPropertyAsShort(String name, short defaultValue){ if (PropertiesManager.props == null) loadProps(); short returnValue = defaultValue; try { returnValue = getPropertyAsShort(name); } catch (Throwable t) { log.error("Could not retrieve or parse as short property [" + name + "], defaulting to given value [" + defaultValue + "]", t); } return returnValue; } /** * Get the value of a given property as an int. * If for any reason the property cannot be looked up as an int, returns the supplied default value. * This error handling makes this method a good choice for static initializer calls. * @param name - the name of the requested property * @param defaultValue - a fallback default value for the property * @return the value of the property as an int, or the supplied default value in the event of any problem. * @since uPortal 2.4 */ public static int getPropertyAsInt(String name, int defaultValue){ if (PropertiesManager.props == null) loadProps(); int returnValue = defaultValue; try { returnValue = getPropertyAsInt(name); } catch (Throwable t) { log.error("Could not retrieve or parse as int the property [" + name + "], defaulting to " + defaultValue, t); } return returnValue; } /** * Get the value of the given property as a long. * If for any reason the property cannot be looked up as a long, returns the supplied default value. * This error handling makes this method a good choice for static initializer calls. * @param name - the name of the requested property * @param defaultValue - a fallback default value that will be returned if there is any problem * @return the value of the property as a long, or the supplied default value if there is any problem. * @since uPortal 2.4 */ public static long getPropertyAsLong(String name, long defaultValue) { if (PropertiesManager.props == null) loadProps(); long returnValue = defaultValue; try { returnValue = getPropertyAsLong(name); } catch (Throwable t) { log.error("Could not retrieve or parse as long property [" + name + "], defaulting to " + defaultValue, t); } return returnValue; } /** * Get the value of the given property as a float. * If for any reason the property cannot be looked up as a float, returns the supplied default value. * This error handling makes this method a good choice for static initializer calls. * @param name - the name of the requested property * @param defaultValue - a fallback default value that will be returned if there is any problem * @return the value of the property as a float, or the supplied default value if there is any problem. * @since uPortal 2.4 */ public static float getPropertyAsFloat(String name, float defaultValue) { if (PropertiesManager.props == null) loadProps(); float returnValue = defaultValue; try { returnValue = getPropertyAsFloat(name); } catch (Throwable t) { log.error("Could not retrieve or parse as float property [" + name + "], defaulting to " + defaultValue, t); } return returnValue; } /** * Get the value of the given property as a double. * If for any reason the property cannot be looked up as a double, returns the specified default value. * This error handling makes this method a good choice for static initializer calls. * @param name - the name of the requested property * @param defaultValue - a fallback default value that will be returned if there is any problem * @return the value of the property as a double, or the supplied default value if there is any problem. * @since uPortal 2.4 */ public static double getPropertyAsDouble(String name, double defaultValue){ if (PropertiesManager.props == null) loadProps(); double returnValue = defaultValue; try { returnValue = getPropertyAsDouble(name); } catch (Throwable t) { log.error("Could not retrieve or parse as double property [" + name + "], defaulting to " + defaultValue, t); } return returnValue; } /** * Get a Set of the names of properties that have been requested but were not set. * @return a Set of the String names of missing properties. * @since uPortal 2.4 */ public static Set getMissingProperties(){ return PropertiesManager.missingProperties; } }
package scalac.transformer; import java.util.Collections; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import scalac.Global; import scalac.Phase; import scalac.PhaseDescriptor; import scalac.CompilationUnit; import scalac.ast.GenTransformer; import scalac.ast.Tree; import scalac.ast.Tree.Template; import scalac.symtab.Modifiers; import scalac.symtab.Scope; import scalac.symtab.Symbol; import scalac.symtab.Type; import scalac.util.Debug; import scalac.util.Name; import scalac.util.Names; /** * This phase does the following: * * - In every nested class, adds to each of its constructor a new * value parameter that contains a link to the outer class. * * - In every nested type, adds to each of its constructor a new type * parameter for every type parameter appearing in outer types. * * - In every class, adds a forwarding "super" method for every method * that is accessed via "super" in a nested class. * * - Replaces all prefixes of TypeRefs by localThisTypes. * * - Adds all missing qualifiers. */ // !!! needs to be cleaned public class ExplicitOuterClassesPhase extends Phase { // // Private Fields /** A map from constructor symbols to type transformers */ private final Map/*<Symbol,TypeTransformer>*/ transformers = new HashMap(); // // Public Constructors /** Initializes this instance. */ public ExplicitOuterClassesPhase(Global global,PhaseDescriptor descriptor){ super(global, descriptor); } // // Public Methods /** Applies this phase to the given compilation units. */ public void apply(CompilationUnit[] units) { treeTransformer.apply(units); } /** Applies this phase to the given type for the given symbol. */ public Type transformInfo(Symbol symbol, Type type) { if (symbol.isConstructor()) { Symbol clasz = symbol.constructorClass(); if (clasz.isClass() && !clasz.isCompoundSym()) return transformInfo(clasz, symbol, type); } return getTypeTransformerFor(symbol).apply(type); } // // Private Methods /** * Computes and returns the new type of the constructor. As a side * effect, creates and stores the type transformer corresponding * to this constructor. */ private Type transformInfo(Symbol clasz, Symbol constructor, Type type) { Symbol[] tparams = type.typeParams(); Symbol[] vparams = type.valueParams(); int depth = getClassDepth(clasz); Map/*<Symbol,Type>*/ table = new HashMap(); table.put(clasz, clasz.thisType()); for (int i = 0; i < tparams.length; i++) table.put(tparams[i], tparams[i].type()); Symbol[] owners = new Symbol[depth]; Symbol[][] tparamss = new Symbol[depth][]; Symbol vlink = null; if (depth > 0) { int count = depth; Symbol owner = clasz.owner(); for (int i = depth - 1; i >= 0; i owners[i] = owner; tparamss[i] = owner.typeParams(); count += tparamss[i].length; owner = owner.owner(); } // create outer value link vparams = Symbol.cloneArray(1, vparams); int vflags = Modifiers.SYNTHETIC; Name vname = Names.OUTER(constructor); vlink = constructor.newVParam(constructor.pos, vflags, vname); vlink.setInfo(clasz.owner().thisType()); vparams[0] = vlink; int o = 0; tparams = Symbol.cloneArray(count, tparams); for (int i = 0; i < depth; i++) { // create new type parameters for (int j = 0; j < tparamss[i].length; j++) { Symbol oldtparam = tparamss[i][j]; Symbol newtparam = oldtparam.cloneSymbol(constructor); newtparam.name = Names.OUTER(constructor, oldtparam); table.put(oldtparam, newtparam.type()); tparams[o++] = newtparam; } // create outer type links int tflags = Modifiers.PARAM | Modifiers.COVARIANT | Modifiers.SYNTHETIC | Modifiers.STABLE; Name tname = Names.OUTER(constructor, owners[i]); Symbol tlink = constructor.newTParam( constructor.pos, tflags, tname, owners[i].typeOfThis()); table.put(owners[i], tlink.type()); tparams[o++] = tlink; } } transformers.put(constructor, new TypeTransformer(table)); type = Type.typeRef(Type.NoPrefix, clasz, Symbol.type(tparams)); type = Type.MethodType(vparams, type); if (tparams.length > 0) type = Type.PolyType(tparams, type); return type; } /** Returns the type transformer for the given symbol. */ private TypeTransformer getTypeTransformerFor(Symbol symbol) { while (true) { Symbol test = symbol; if (test.isConstructor()) test = test.constructorClass(); // !!! isClassType -> isClass ? if (test.isClassType() && !test.isCompoundSym()) break; symbol = symbol.owner(); } // while (!symbol.isClassType() && !(symbol.isConstructor() && symbol.constructorClass().isClassType())) // !!! isClassType -> isClass ? // symbol = symbol.owner(); if (symbol.isClassType()) symbol = symbol.primaryConstructor(); if (symbol.constructorClass().isPackageClass()) return topLevelTypeTransformer; TypeTransformer context = (TypeTransformer)transformers.get(symbol); if (context == null) { symbol.nextInfo(); context = (TypeTransformer)transformers.get(symbol); assert context != null: Debug.show(symbol); } return context; } // // Private Functions /** * Returns the depth of the specified class. The depth of a class * is: * - -1 for a package class * - 0 for a top-level class * - the depth of the enclosing class plus 1 for an inner class */ private static int getClassDepth(Symbol clasz) { assert clasz.isClass() || clasz.isPackageClass(): Debug.show(clasz); int depth = -1; while (!clasz.isPackageClass()) { clasz = clasz.owner(); depth++; } return depth; } /** * Returns the type arguments of the flattened version of the * specified type reference. This functions takes and returns * non-transformed types. */ private static Type[] getFlatArgs(Type prefix, Symbol clasz, Type[] args) { int depth = getClassDepth(clasz); if (depth <= 0) return args; Type[] prefixes = new Type[depth]; Type[][] argss = new Type[depth][]; int count = collect(prefix, clasz, prefixes, argss); args = Type.cloneArray(count, args); for (int i = 0, o = 0; i < depth; i++) { for (int j = 0; j < argss[i].length; j++) args[o++] = argss[i][j]; args[o++] = prefixes[i]; } return args; } // where private static int collect(Type prefix, Symbol clasz, Type[] prefixes, Type[][] argss) { int count = prefixes.length; for (int i = prefixes.length - 1; i >= 0; i prefixes[i] = prefix; Symbol owner = clasz.owner(); Type base = prefix.baseType(owner); switch (base) { case TypeRef(Type type, Symbol symbol, Type[] args): assert symbol == owner: Debug.show(base); count += args.length; argss[i] = args; prefix = type; clasz = owner; continue; default: throw Debug.abortIllegalCase(base); } } return count; } // // Private Class - Type transformer /** The type transformer for top-level types */ private static final TypeTransformer topLevelTypeTransformer = new TypeTransformer(Collections.EMPTY_MAP); /** The type transformer */ private static final class TypeTransformer extends Type.MapOnlyTypes { private final Map/*<Symbol,Type>*/ tparams; public TypeTransformer(Map tparams) { this.tparams = tparams; } public Type apply(Type type) { switch (type) { case TypeRef(Type prefix, Symbol symbol, Type[] args): if (symbol.isParameter() && symbol.owner().isConstructor()) { assert prefix == Type.NoPrefix: type; assert args.length == 0: type; Object value = tparams.get(symbol); return value != null ? (Type)value : type; } if (symbol.isClass() && !symbol.isCompoundSym()) { args = map(getFlatArgs(prefix, symbol, args)); prefix = Type.NoPrefix; return Type.typeRef(prefix, symbol, args); } if (symbol.isPackageClass()) { args = Type.EMPTY_ARRAY; prefix = Type.NoPrefix; return Type.typeRef(prefix, symbol, args); } return Type.typeRef(apply(prefix), symbol, map(args)); case SingleType(Type prefix, Symbol symbol): if (symbol.owner().isPackageClass()) return Type.singleType(Type.NoPrefix, symbol); return Type.singleType(apply(prefix), symbol); case ThisType(Symbol clasz): Object value = tparams.get(clasz); if (value != null) return (Type)value; assert clasz.isCompoundSym() || clasz.isPackageClass(): Debug.show(clasz); return type; case CompoundType(Type[] parents, Scope members): // !!! this case should not be needed return Type.compoundType(map(parents), members, type.symbol()); default: return map(type); } } } // // Private Class - Tree transformer /** The tree transformer */ private final GenTransformer treeTransformer = new GenTransformer(global) { /** The current context */ private Context context; /** The current method */ private Symbol method; /** Transforms the given type. */ public Type transform(Type type) { return context.transformer.apply(type); } /** Transforms the given tree. */ public Tree transform(Tree tree) { if (global.debug) global.log("transforming " + tree);//debug switch (tree) { case ClassDef(_, _, _, _, _, Template impl): Symbol clasz = tree.symbol(); context = new Context(context, clasz, new HashMap(), new HashMap()); Tree[] parents = transform(impl.parents); Tree[] body = transform(impl.body); body = Tree.concat(body, genAccessMethods(false)); body = Tree.concat(body, genAccessMethods(true)); if (context.vfield != null) { body = Tree.cloneArray(1, body); body[0] = gen.ValDef( context.vfield, gen.Ident(context.vfield.pos, context.vparam)); } context = context.outer; return gen.ClassDef(clasz, parents, impl.symbol(), body); case DefDef(_, _, _, _, _, Tree rhs): Symbol method = tree.symbol(); Context backup = context; if (method.isConstructor()) context = context.getConstructorContext(method); this.method = method; rhs = transform(rhs); this.method = null; context = backup; return gen.DefDef(method, rhs); case Apply(Tree vfun, Tree[] vargs): switch (vfun) { case TypeApply(Tree tfun, Tree[] targs): if (!tfun.symbol().isConstructor()) break; return transform(tree, vargs, vfun, targs, tfun); default: if (!vfun.symbol().isConstructor()) break; return transform(tree, vargs, vfun, Tree.EMPTY_ARRAY,vfun); } return super.transform(tree); case This(_): return genOuterRef(tree.pos, tree.symbol()); case Select(Tree qualifier, _): Symbol symbol = tree.symbol(); if (symbol.owner().isStaticOwner()) // !!! qualifier ignored return gen.mkGlobalRef(tree.pos, symbol); Symbol access; switch (qualifier) { case Super(_, _): Symbol clasz = qualifier.symbol(); if (clasz == context.clasz) { access = symbol; qualifier = gen.Super(tree.pos, qualifier.symbol()); } else { access = getAccessSymbol(symbol, clasz); qualifier = genOuterRef(qualifier.pos, clasz); } break; default: access = getAccessSymbol(symbol, null); qualifier = transform(qualifier); break; } tree = gen.Select(tree.pos, qualifier, access); if (access != symbol && !symbol.isMethod()) tree = gen.mkApply__(tree); return tree; default: return super.transform(tree); } } /* Add outer type and value arguments to constructor calls. */ private Tree transform(Tree vapply, Tree[] vargs, Tree tapply, Tree[] targs, Tree tree) { switch (tree) { case Select(Tree qualifier, _): Symbol symbol = tree.symbol(); Symbol clasz = symbol.constructorClass(); if (getClassDepth(clasz) > 0) { Type[] types = Tree.typeOf(targs); types = getFlatArgs(qualifier.type(), clasz, types); targs = gen.mkTypes(tapply.pos, types); vargs = Tree.cloneArray(1, vargs); vargs[0] = qualifier; } else { assert !containsValue(qualifier): tree; } tree = gen.Ident(tree.pos, symbol); if (targs.length != 0) tree = gen.TypeApply(tapply.pos, tree, transform(targs)); return gen.Apply(vapply.pos, tree, transform(vargs)); default: throw Debug.abortIllegalCase(tree); } } /** * Returns the symbol to access the specified member from the * current context. If "svper" is non null, the member is * selected from the superclass of the specified class. The * returned symbol may be the same as the given one. */ private Symbol getAccessSymbol(Symbol member, Symbol svper) { if (member.isPublic() && svper == null) return member; Context context = this.context; for (; context != null; context = context.outer) if (svper != null ? context.clasz == svper : member.isPrivate() ? context.clasz == member.owner() // !!! This is incorrect without static access methods : context.clasz.isSubClass(member.owner())) break; assert context != null: Debug.show(this.context, member); if (context == this.context) return member; Map table = svper != null ? context.supers : context.selfs; Symbol access = (Symbol)table.get(member); if (access == null) { // !!! generate static access methods ? Name name = Names.ACCESS(member, svper != null); access = context.clasz.newAccessMethod(context.clasz.pos,name); global.nextPhase(); Type info = member.isMethod() ? member.info().cloneType(member, access) : Type.MethodType(Symbol.EMPTY_ARRAY, member.info()); access.setInfo(info); global.prevPhase(); table.put(member, access); context.clasz.nextInfo().members().enter(access); assert Debug.log("created access method: ", access); } return access; } /** Generates the trees of the access methods. */ private Tree[] genAccessMethods(boolean withSuper) { Map table = withSuper ? context.supers : context.selfs; if (table.size() == 0) return Tree.EMPTY_ARRAY; Tree[] trees = new Tree[table.size()]; Iterator entries = table.entrySet().iterator(); for (int i = 0; i < trees.length; i++) { Map.Entry entry = (Map.Entry)entries.next(); Symbol member = (Symbol)entry.getKey(); Symbol access = (Symbol)entry.getValue(); int pos = access.pos; Tree qualifier = withSuper ? gen.Super(pos, context.clasz) : gen.This(pos, context.clasz); Tree select = gen.Select(qualifier, member); Tree[] targs = gen.mkTypeRefs(pos, access.nextTypeParams()); Tree[] vargs = gen.mkLocalRefs(pos, access.nextValueParams()); Tree body = member.isMethod() ? gen.mkApplyTV(select, targs, vargs) : select; trees[i] = gen.DefDef(access, body); } return trees; } /** Returns a tree referencing the given outer class. */ private Tree genOuterRef(int pos, Symbol clasz) { if (context.clasz == clasz) return gen.This(pos, clasz); Tree tree = method == null || method.isConstructor() ? gen.Ident(pos, context.vparam) : gen.Select(gen.This(pos, context.clasz),context.getVField()); for (Context c = context.outer;; c = c.outer) { assert c != null: Debug.show(clasz, context.clasz); if (c.clasz == clasz) return tree; Symbol access = getAccessSymbol(c.getVField(), null); tree = gen.Apply(gen.Select(tree, access)); } } /** Tests whether the tree contains some value computation. */ private boolean containsValue(Tree tree) { switch (tree) { case This(_): return !tree.symbol().isPackageClass(); case Select(Tree qualifier, _): return containsValue(qualifier) || tree.symbol().isValue(); default: return false; } } }; // // Private Class - Tree transformer context /** This class represents the tree transformation context. */ private class Context { /** The outer context */ public final Context outer; /** The context class */ public final Symbol clasz; /** The context type transformer */ public final TypeTransformer transformer; /** The self access methods (maps members to accessors) */ public final Map/*<Symbol,Symbol>*/ selfs; /** The super access methods (maps members to accessors) */ public final Map/*<Symbol,Symbol>*/ supers; /** The context outer paramater (null if none) */ public final Symbol vparam; /** The context outer field (null if none or not yet used) */ private Symbol vfield; /** Initializes this instance. */ public Context(Context outer, Symbol symbol, Map selfs, Map supers) { this.outer = outer; this.clasz = symbol.constructorClass(); this.transformer = getTypeTransformerFor(symbol); this.selfs = selfs; this.supers = supers; this.vparam = outer != null ? symbol.nextValueParams()[0] : null; } /** Returns a context for the given constructor. */ public Context getConstructorContext(Symbol constructor) { assert constructor.constructorClass() == clasz; return new Context(outer, constructor, selfs, supers); } private Symbol getVField() { assert outer != null: Debug.show(clasz); if (vfield == null) { int flags = Modifiers.SYNTHETIC | Modifiers.PRIVATE | Modifiers.STABLE; vfield = clasz.newField(clasz.pos, flags, Names.OUTER(clasz)); vfield.setInfo(outer.clasz.thisType()); clasz.members().enterNoHide(vfield); } return vfield; } } // }
package BluebellAdventures.Characters; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.concurrent.CopyOnWriteArrayList; import javax.imageio.ImageIO; import BluebellAdventures.Characters.GameMap; import Megumin.Actions.Action; import Megumin.Actions.Effect; import Megumin.Nodes.Sprite; import Megumin.Point; public class Character extends Sprite { private int hp; private int mp; private int chargeBar; private int speed; private int unlockSpeed; private int attackScore; private int snackScore; private int key; // Constructors // public Character(String filename) throws IOException { super(filename, new Point(0, 0)); } public Character(String filename, Point position) throws IOException { super(ImageIO.read(new File(filename)), position); } public Character(BufferedImage image) { super(image, new Point(0, 0)); } public Character(BufferedImage image, Point position) { super(image, position); } public void render(Graphics2D g) { if (getVisible()) { g.setFont(new Font("TimesRoman", Font.BOLD, 35)); String hpString = ""; g.setColor(Color.white); g.drawString("Health: ", 100, 50); g.setColor(Color.red); g.drawString(hpString.substring(0, hp), 250, 50); String keyString = ""; g.setColor(Color.white); g.drawString("key: ", 400, 50); g.setColor(Color.yellow); g.drawString(keyString.substring(0, key), 500, 50); g.setColor(Color.white); g.drawString("Score: " + snackScore, 700, 50); super.render(g); } } @Override public boolean checkCrash(CopyOnWriteArrayList<Sprite> sprites, Action action) { boolean crash = false; GameMap map = GameMap.getInstance(); int x1 = getPosition().getX(); int y1 = getPosition().getY(); int w1 = getSize().getX(); int h1 = getSize().getY(); Iterator it = sprites.iterator(); while (it.hasNext()) { Sprite sprite = (Sprite)it.next(); int x2 = map.getPosition().getX() + sprite.getPosition().getX(); int y2 = map.getPosition().getY() + sprite.getPosition().getY(); int w2 = sprite.getSize().getX(); int h2 = sprite.getSize().getY(); //check whether crash area exist if (w2 == 0 || h2 == 0) { continue; } //check whether two rectangle intersect if (Math.max(Math.abs(x2 - (x1 + w1)), Math.abs(x2 + w2 - x1)) < w1 + w2 && Math.max(Math.abs(y2 - (y1 + h1)), Math.abs(y2 + h2 - y1)) < h1 + h2) { ((Effect)action).setSprite(sprite); runAction(action); crash = true; } } return crash; } // Get and Sets // public Character setHp(int hp) { this.hp = hp; return this; } public int getHp() { return hp; } public Character setMp(int mp) { this.mp = mp; return this; } public int getMp(){ return mp; } public Character setChargeBar(int chargeBar) { this.chargeBar = chargeBar; return this; } public int getChargeBar() { return chargeBar; } public Character setSpeed(int speed) { this.speed = speed; return this; } public int getSpeed() { return speed; } public Character setUnlockSpeed(int unlockSpeed) { this.unlockSpeed = unlockSpeed; return this; } public int getUnlockSpeed() { return unlockSpeed; } public Character setAttackScore(int attackScore) { this.attackScore = attackScore; return this; } public int getAttackScore() { return attackScore; } public Character setSnackScore(int snackScore) { this.snackScore = snackScore; return this; } public void addSnackScore(int snackScore) { this.snackScore += snackScore; } public int getSnackScore() { return snackScore; } public Character setKey(int key) { this.key = key; return this; } public int getKey() { return key; } public void addKey(int key) { this.key += key; } public void useKey(int key) { this.key -= key; } }
package us.kbase.workspace.database.mongo; import static java.util.Objects.requireNonNull; import static us.kbase.workspace.database.Util.checkString; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.time.Duration; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3Configuration; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.services.s3.presigner.model.PresignedPutObjectRequest; import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest; import us.kbase.typedobj.core.Restreamable; public class S3ClientWithPresign { // this isolates code that can't easily be mocked from the rest of the S3 blobstore. // all tests are in the S3BlobStore integration tests. private final S3Client client; private final S3Presigner presigner; private final CloseableHttpClient httpClient; /** Construct the client. * @param host the host the client will interact with. Schema must be http or https. * @param s3key the S3 access key. * @param s3secret the S3 access secret. * @param region the S3 region the client will contact. * @throws URISyntaxException if the URL is not a valid URI. */ public S3ClientWithPresign( final URL host, final String s3key, final String s3secret, final Region region) throws URISyntaxException { final AwsCredentials creds = AwsBasicCredentials.create( checkString(s3key, "s3key"), checkString(s3secret, "s3secret")); this.presigner = S3Presigner.builder() .credentialsProvider(StaticCredentialsProvider.create(creds)) .region(requireNonNull(region, "region")) .endpointOverride(requireNonNull(host, "host").toURI()) .serviceConfiguration( S3Configuration.builder().pathStyleAccessEnabled(true).build()) .build(); // the client is not actually used in the code here, but might as well build and provide // it here, as all the info needed to build it is required for the presigner this.client = S3Client.builder() .region(region) .endpointOverride(host.toURI()) .credentialsProvider(StaticCredentialsProvider.create(creds)) .serviceConfiguration( S3Configuration.builder().pathStyleAccessEnabled(true).build()) .httpClient(UrlConnectionHttpClient.create()) // Don't need to disable ssl .build(); final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(1000); //perhaps these should be configurable cm.setDefaultMaxPerRoute(1000); // TODO set timeouts for the client for 1/2m for conn req timeout and std timeout httpClient = HttpClients.custom().setConnectionManager(cm).build(); } /** Get the standard S3 client. * @return the S3 client. */ public S3Client getClient() { return client; } /** Load an object to S3 via a presigned url and standard HTTP streaming. * The bucket and key are not checked for correctness prior to the upload attempt. * @param bucket the bucket that will contain the object. * @param key the object key. * @param object the object data. * @throws IOException if an error occurs. */ public void presignAndPutObject( final String bucket, final String key, final Restreamable object) throws IOException { checkString(key, "key"); checkString(bucket, "bucket"); requireNonNull(object, "object"); // TODO CODE if this approach fixes the problem, pass in the PutObjectRequest instead // of the bucket and key final PutObjectPresignRequest put = PutObjectPresignRequest.builder() .signatureDuration(Duration.ofMinutes(15)) .putObjectRequest( PutObjectRequest.builder() .bucket(bucket) .key(key) .build() ).build(); final PresignedPutObjectRequest presignedPut = presigner.presignPutObject(put); final URL target = presignedPut.url(); try (final InputStream is = object.getInputStream()) { final HttpPut htp; try { htp = new HttpPut(target.toURI()); } catch (URISyntaxException e) { // this means the S3 SDK is generating urls that are invalid URIs, which is // pretty bizarre. // not sure how to test this. // since the URI contains credentials, we deliberately do not include the // source error or URI throw new RuntimeException("S3 presigned request builder generated invalid URI"); } final BasicHttpEntity ent = new BasicHttpEntity(); ent.setContent(new BufferedInputStream(is)); ent.setContentLength(object.getSize()); htp.setEntity(ent); // error handling is a pain here. If the stream is large, for Minio (and probably most // other S3 instances) the connection dies. If the stream is pretty small, // you can get an error back. final CloseableHttpResponse res = httpClient.execute(htp); try { if (res.getStatusLine().getStatusCode() > 399) { final byte[] buffer = new byte[1000]; try (final InputStream in = res.getEntity().getContent()) { new DataInputStream(in).readFully(buffer); } catch (EOFException e) { // do nothing } throw new IOException(String.format( "Error saving file to S3 (%s), truncated response follows:\n%s", res.getStatusLine().getStatusCode(), new String(buffer, StandardCharsets.UTF_8).trim())); } } finally { res.close(); } } } }
package vg.civcraft.mc.namelayer.command.commands; import java.util.List; import java.util.UUID; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.avaje.ebean.validation.Pattern; import vg.civcraft.mc.namelayer.NameAPI; import vg.civcraft.mc.namelayer.command.PlayerCommand; import vg.civcraft.mc.namelayer.group.Group; import vg.civcraft.mc.namelayer.group.GroupType; import vg.civcraft.mc.namelayer.group.groups.PrivateGroup; public class CreateGroup extends PlayerCommand{ public CreateGroup(String name) { super(name); setIdentifier("nlcg"); setDescription("This command is used to create a group (Public or Private). Password is optional."); setUsage("/nlcg <name> (GroupType- default PRIVATE) (password)"); setArguments(1,3); } @Override public boolean execute(CommandSender sender, String[] args) { if (!(sender instanceof Player)){ sender.sendMessage(ChatColor.DARK_BLUE + "Nice try console man, you can't bring me down. The computers won't win. " + "Dis a player commmand back off."); return true; } Player p = (Player) sender; String name = args[0]; if (gm.getGroup(name) != null){ p.sendMessage(ChatColor.RED + "That group is already taken."); return true; } String password = ""; if (args.length == 3) password = args[2]; else password = null; GroupType type = GroupType.PRIVATE; if (args.length == 2) { if(GroupType.getGroupType(args[1]) == null){ p.sendMessage(ChatColor.RED + "You have entered an invalid GroupType, use /nllgt to list GroupTypes."); return true; } type = GroupType.getGroupType(args[1]); } UUID uuid = NameAPI.getUUID(p.getName()); Group g = null; switch(type){ case PRIVATE: g = new PrivateGroup(name, uuid, false, password); break; default: g = new Group(name, uuid, false, password, type); } gm.createGroup(g); p.sendMessage(ChatColor.GREEN + "The group " + g.getName() + " was successfully created."); return true; } public List<String> tabComplete(CommandSender sender, String[] args) { return null; } }
package com.dumbster.smtp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.List; import com.dumbster.smtp.action.Connect; public class SmtpClientTransaction implements Runnable { private Socket socket; private List<SmtpMessage> receivedMail = new ArrayList<SmtpMessage>(); private List<SmtpMessage> serverMessages; public SmtpClientTransaction(Socket socket, List<SmtpMessage> messages) { this.socket = socket; this.serverMessages = messages; } private void handleTransaction() throws IOException { BufferedReader input = getSocketInput(); PrintWriter out = getSocketOutput(); SmtpRequest smtpRequest = initializeStateMachine(); SmtpResponse smtpResponse = smtpRequest.execute(); SmtpState smtpState = sendInitialResponse(out, smtpResponse); List<SmtpMessage> msgList = new ArrayList<SmtpMessage>(); SmtpMessage msg = new SmtpMessage(); while (smtpState != SmtpState.CONNECT) { String line = input.readLine(); if (line == null) { break; } SmtpRequest request = SmtpRequest.createRequest(line, smtpState); SmtpResponse response = request.execute(); smtpState = response.getNextState(); sendResponse(out, response); // Store input in message String params = request.getParams(); msg.store(response, params); // If message reception is complete save it if (smtpState == SmtpState.QUIT) { msgList.add(msg); System.out.println(msg); msg = new SmtpMessage(); } } receivedMail.addAll(msgList); } private SmtpState sendInitialResponse(PrintWriter out, SmtpResponse smtpResponse) { SmtpState smtpState; // Send initial response sendResponse(out, smtpResponse); smtpState = smtpResponse.getNextState(); return smtpState; } private SmtpRequest initializeStateMachine() { // Initialize the state machine SmtpState smtpState = SmtpState.CONNECT; SmtpRequest smtpRequest = new SmtpRequest(new Connect(), "", smtpState); return smtpRequest; } private BufferedReader getSocketInput() throws IOException { return new BufferedReader( new InputStreamReader(socket.getInputStream())); } private PrintWriter getSocketOutput() throws IOException { return new PrintWriter(socket.getOutputStream()); } private static void sendResponse(PrintWriter out, SmtpResponse smtpResponse) { if (smtpResponse.getCode() > 0) { int code = smtpResponse.getCode(); String message = smtpResponse.getMessage(); out.print(code + " " + message + "\r\n"); out.flush(); } } public List<SmtpMessage> getReceivedMail() { return receivedMail; } @Override public void run() { try { handleTransaction(); serverMessages.addAll(getReceivedMail()); } catch(Exception e) {} finally { try { socket.close(); } catch (Exception e2) {} } } }
package com.ecyrd.jspwiki; import java.util.Properties; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; public class DefaultURLConstructor implements URLConstructor { private WikiEngine m_engine; private String m_viewURLPattern = "%uWiki.jsp?page=%n"; /** Are URL styles relative or absolute? */ private boolean m_useRelativeURLStyle = true; public void initialize( WikiEngine engine, Properties properties ) { m_engine = engine; m_useRelativeURLStyle = "relative".equals( properties.getProperty( WikiEngine.PROP_REFSTYLE, "relative" ) ); } private final String doReplacement( String baseptrn, String name, boolean absolute ) { String baseurl = ""; if( absolute || !m_useRelativeURLStyle ) baseurl = m_engine.getBaseURL(); baseptrn = TextUtil.replaceString( baseptrn, "%u", baseurl ); baseptrn = TextUtil.replaceString( baseptrn, "%U", m_engine.getBaseURL() ); baseptrn = TextUtil.replaceString( baseptrn, "%n", m_engine.encodeName(name) ); return baseptrn; } /** * Constructs the actual URL based on the context. */ private String makeURL( String context, String name, boolean absolute ) { if( context.equals(WikiContext.VIEW) ) { if( name == null ) return makeURL("%uWiki.jsp","",absolute); // FIXME return doReplacement( m_viewURLPattern, name, absolute ); } else if( context.equals(WikiContext.EDIT) ) { return doReplacement( "%uEdit.jsp?page=%n", name, absolute ); } else if( context.equals(WikiContext.ATTACH) ) { return doReplacement( "%uattach/%n", name, absolute ); } else if( context.equals(WikiContext.INFO) ) { return doReplacement( "%uPageInfo.jsp?page=%n", name, absolute ); } else if( context.equals(WikiContext.DIFF) ) { return doReplacement( "%uDiff.jsp?page=%n", name, absolute ); } else if( context.equals(WikiContext.NONE) ) { return doReplacement( "%u%n", name, absolute ); } else if( context.equals(WikiContext.UPLOAD) ) { return doReplacement( "%uUpload.jsp?page=%n", name, absolute ); } else if( context.equals(WikiContext.COMMENT) ) { return doReplacement( "%uComment.jsp?page=%n", name, absolute ); } else if( context.equals(WikiContext.ERROR) ) { return doReplacement( "%uError.jsp", name, absolute ); } throw new InternalWikiException("Requested unsupported context "+context); } /** * Constructs the URL with a bunch of parameters. */ public String makeURL( String context, String name, boolean absolute, String parameters ) { if( parameters != null ) { if( context.equals(WikiContext.ATTACH) ) { parameters = "?"+parameters; } parameters = "&amp;"+parameters; } else { parameters = ""; } return makeURL( context, name, absolute )+parameters; } /** * Should parse the "page" parameter from the actual * request. */ public String parsePage( String context, HttpServletRequest request, String encoding ) throws UnsupportedEncodingException { String pagereq = m_engine.safeGetParameter( request, "page" ); if( context.equals(WikiContext.ATTACH) ) { pagereq = parsePageFromURL( request, encoding ); if( pagereq != null ) pagereq = TextUtil.urlDecodeUTF8(pagereq); } return pagereq; } /** * Takes the name of the page from the request URI. * The initial slash is also removed. If there is no page, * returns null. */ public static String parsePageFromURL( HttpServletRequest request, String encoding ) throws UnsupportedEncodingException { String name = request.getPathInfo(); if( name == null || name.length() <= 1 ) { return null; } else if( name.charAt(0) == '/' ) { name = name.substring(1); } name = new String(name.getBytes("ISO-8859-1"), encoding ); return name; } }
// ChargeRequest.java // Inner Fence Credit Card Terminal for Android // API 1.0.0 // below. // 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, // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // included in all copies or substantial portions of the Software. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // 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.innerfence.chargedemo; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class ChargeRequest { protected String _address; protected String _amount; protected String _city; protected String _company; protected String _country; protected String _currency; protected String _description; protected String _email; protected Bundle _extraParams; protected String _firstName; protected String _invoiceNumber; protected String _lastName; protected String _phone; protected String _state; protected String _zip; public ChargeRequest() { } public String getAddress() { return _address; } public void setAddress( String value ) { _address = value; } public String getAmount() { return _amount; } public void setAmount( String value ) { _amount = value; } public String getCity() { return _city; } public void setCity( String value ) { _city = value; } public String getCompany() { return _company; } public void setCompany( String value ) { _company = value; } public String getCountry() { return _country; } public void setCountry( String value ) { _country = value; } public String getCurrency() { return _currency; } public void setCurrency( String value ) { _currency = value; } public String getDescription() { return _description; } public void setDescription( String value ) { _description = value; } public String getEmail() { return _email; } public void setEmail( String value ) { _email = value; } public Bundle getExtraParams() { return _extraParams; } public void setExtraParams( Bundle value ) { _extraParams = value; } public String getFirstName() { return _firstName; } public void setFirstName( String value ) { _firstName = value; } public String getInvoiceNumber() { return _invoiceNumber; } public void setInvoiceNumber( String value ) { _invoiceNumber = value; } public String getLastName() { return _lastName; } public void setLastName( String value ) { _lastName = value; } public String getPhone() { return _phone; } public void setPhone( String value ) { _phone = value; } public String getState() { return _state; } public void setState( String value ) { _state = value; } public String getZip() { return _zip; } public void setZip( String value ) { _zip = value; } public void submit( Activity callingActivity ) { Bundle bundle = new Bundle(); bundle.putString( "address", _address ); bundle.putString( "amount", _amount ); bundle.putString( "city", _city ); bundle.putString( "company", _company ); bundle.putString( "country", _country ); bundle.putString( "currency", _currency ); bundle.putString( "description", _description ); bundle.putString( "email", _email ); bundle.putBundle( "extra_params", _extraParams ); bundle.putString( "first_name", _firstName ); bundle.putString( "invoice_number", _invoiceNumber ); bundle.putString( "last_name", _lastName ); bundle.putString( "phone", _phone ); bundle.putString( "state", _state ); bundle.putString( "zip", _zip ); // calling_app param is required to let Credit Card Terminal // that it was launched from a calling app. String callingApp = callingActivity.getPackageName(); bundle.putString( "calling_app", callingApp ); Intent intent = new Intent(); intent.setClassName("com.innerfence.ccterminal", "com.innerfence.ccterminal.TerminalActivity"); intent.putExtras( bundle ); callingActivity.startActivityForResult( intent, R.id.ccterminal_request_code ); } }
package com.jme.util.export.xml; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.jme.image.Texture; import com.jme.scene.state.RenderState; import com.jme.scene.state.TextureState; import com.jme.util.TextureKey; import com.jme.util.TextureManager; import com.jme.util.export.InputCapsule; import com.jme.util.export.Savable; import com.jme.util.geom.BufferUtils; /** * Part of the jME XML IO system as introduced in the google code jmexml project. * * @author Kai Rabien (hevee) - original author of the code.google.com jmexml project * @author Doug Daniels (dougnukem) - adjustments for jME 2.0 and Java 1.5 */ public class DOMInputCapsule implements InputCapsule { private Document doc; private Element currentElem; private XMLImporter importer; private boolean isAtRoot = true; private Map<String, Savable> referencedSavables = new HashMap<String, Savable>(); public DOMInputCapsule(Document doc, XMLImporter importer) { this.doc = doc; this.importer = importer; currentElem = doc.getDocumentElement(); } private static String decodeString(String s) { if (s == null) { return null; } s = s.replaceAll("\\&quot;", "\"").replaceAll("\\&lt;", "<").replaceAll("\\&amp;", "&"); return s; } private Element findFirstChildElement(Element parent) { Node ret = parent.getFirstChild(); while (ret != null && (!(ret instanceof Element))) { ret = ret.getNextSibling(); } return (Element) ret; } private Element findChildElement(Element parent, String name) { if (parent == null) { return null; } Node ret = parent.getFirstChild(); while (ret != null && (!(ret instanceof Element) || !ret.getNodeName().equals(name))) { ret = ret.getNextSibling(); } return (Element) ret; } private Element findNextSiblingElement(Element current) { Node ret = current.getNextSibling(); while (ret != null) { if (ret instanceof Element) { return (Element) ret; } ret = ret.getNextSibling(); } return null; } public byte readByte(String name, byte defVal) throws IOException { byte ret = defVal; try { return Byte.parseByte(currentElem.getAttribute(name)); } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public byte[] readByteArray(String name, byte[] defVal) throws IOException { byte[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); String[] strings = tmpEl.getAttribute("data").split("\\s+"); if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (strings.length != requiredSize) throw new IOException("Wrong number of bytes. size says " + requiredSize + ", data contains " + strings.length); } byte[] tmp = new byte[strings.length]; for (int i = 0; i < strings.length; i++) { tmp[i] = Byte.parseByte(strings[i]); } return tmp; } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public byte[][] readByteArray2D(String name, byte[][] defVal) throws IOException { byte[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); NodeList nodes = currentElem.getChildNodes(); List<byte[]> byteArrays = new ArrayList<byte[]>(); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("array")) { // Very unsafe assumption byteArrays.add(readByteArray(n.getNodeName(), null)); } } if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (byteArrays.size() != requiredSize) throw new IOException( "String array contains wrong element count. " + "Specified size " + requiredSize + ", data contains " + byteArrays.size()); } currentElem = (Element) currentElem.getParentNode(); return byteArrays.toArray(new byte[0][]); } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public int readInt(String name, int defVal) throws IOException { int ret = defVal; try { String s = currentElem.getAttribute(name); if (s.length() > 0) { ret = Integer.parseInt(s); } } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } return ret; } public int[] readIntArray(String name, int[] defVal) throws IOException { int[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); String[] strings = tmpEl.getAttribute("data").split("\\s+"); if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (strings.length != requiredSize) throw new IOException("Wrong number of ints. size says " + requiredSize + ", data contains " + strings.length); } int[] tmp = new int[strings.length]; for (int i = 0; i < tmp.length; i++) { tmp[i] = Integer.parseInt(strings[i]); } return tmp; } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public int[][] readIntArray2D(String name, int[][] defVal) throws IOException { int[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); NodeList nodes = currentElem.getChildNodes(); List<int[]> intArrays = new ArrayList<int[]>(); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("array")) { // Very unsafe assumption intArrays.add(readIntArray(n.getNodeName(), null)); } } if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (intArrays.size() != requiredSize) throw new IOException( "String array contains wrong element count. " + "Specified size " + requiredSize + ", data contains " + intArrays.size()); } currentElem = (Element) currentElem.getParentNode(); return intArrays.toArray(new int[0][]); } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public float readFloat(String name, float defVal) throws IOException { float ret = defVal; try { String s = currentElem.getAttribute(name); if (s.length() > 0) { ret = Float.parseFloat(s); } } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } return ret; } public float[] readFloatArray(String name, float[] defVal) throws IOException { float[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); String[] strings = tmpEl.getAttribute("data").split("\\s+"); if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (strings.length != requiredSize) throw new IOException("Wrong number of floats. size says " + requiredSize + ", data contains " + strings.length); } float[] tmp = new float[strings.length]; for (int i = 0; i < tmp.length; i++) { tmp[i] = Float.parseFloat(strings[i]); } return tmp; } catch (IOException ioe) { throw ioe; } catch (DOMException de) { throw new IOException(de); } } public float[][] readFloatArray2D(String name, float[][] defVal) throws IOException { /* Why does this one method ignore the 'size attr.? */ float[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } int size_outer = Integer.parseInt(tmpEl.getAttribute("size_outer")); int size_inner = Integer.parseInt(tmpEl.getAttribute("size_outer")); float[][] tmp = new float[size_outer][size_inner]; String[] strings = tmpEl.getAttribute("data").split("\\s+"); for (int i = 0; i < size_outer; i++) { tmp[i] = new float[size_inner]; for (int k = 0; k < size_inner; k++) { tmp[i][k] = Float.parseFloat(strings[i]); } } return tmp; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public double readDouble(String name, double defVal) throws IOException { double ret = defVal; try { ret = Double.parseDouble(currentElem.getAttribute(name)); } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } return ret; } public double[] readDoubleArray(String name, double[] defVal) throws IOException { double[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); String[] strings = tmpEl.getAttribute("data").split("\\s+"); if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (strings.length != requiredSize) throw new IOException("Wrong number of doubles. size says " + requiredSize + ", data contains " + strings.length); } double[] tmp = new double[strings.length]; for (int i = 0; i < tmp.length; i++) { tmp[i] = Double.parseDouble(strings[i]); } return tmp; } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public double[][] readDoubleArray2D(String name, double[][] defVal) throws IOException { double[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); NodeList nodes = currentElem.getChildNodes(); List<double[]> doubleArrays = new ArrayList<double[]>(); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("array")) { // Very unsafe assumption doubleArrays.add(readDoubleArray(n.getNodeName(), null)); } } if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (doubleArrays.size() != requiredSize) throw new IOException( "String array contains wrong element count. " + "Specified size " + requiredSize + ", data contains " + doubleArrays.size()); } currentElem = (Element) currentElem.getParentNode(); return doubleArrays.toArray(new double[0][]); } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public long readLong(String name, long defVal) throws IOException { long ret = defVal; try { ret = Long.parseLong(currentElem.getAttribute(name)); } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } return ret; } public long[] readLongArray(String name, long[] defVal) throws IOException { long[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); String[] strings = tmpEl.getAttribute("data").split("\\s+"); if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (strings.length != requiredSize) throw new IOException("Wrong number of longs. size says " + requiredSize + ", data contains " + strings.length); } long[] tmp = new long[strings.length]; for (int i = 0; i < tmp.length; i++) { tmp[i] = Long.parseLong(strings[i]); } return tmp; } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public long[][] readLongArray2D(String name, long[][] defVal) throws IOException { long[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); NodeList nodes = currentElem.getChildNodes(); List<long[]> longArrays = new ArrayList<long[]>(); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("array")) { // Very unsafe assumption longArrays.add(readLongArray(n.getNodeName(), null)); } } if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (longArrays.size() != requiredSize) throw new IOException( "String array contains wrong element count. " + "Specified size " + requiredSize + ", data contains " + longArrays.size()); } currentElem = (Element) currentElem.getParentNode(); return longArrays.toArray(new long[0][]); } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public short readShort(String name, short defVal) throws IOException { try { String attribute = currentElem.getAttribute(name); if (attribute == null || attribute.length() == 0) { return defVal; } return Short.parseShort(attribute); } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public short[] readShortArray(String name, short[] defVal) throws IOException { short[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); String[] strings = tmpEl.getAttribute("data").split("\\s+"); if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (strings.length != requiredSize) throw new IOException("Wrong number of shorts. size says " + requiredSize + ", data contains " + strings.length); } short[] tmp = new short[strings.length]; for (int i = 0; i < tmp.length; i++) { tmp[i] = Short.parseShort(strings[i]); } return tmp; } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public short[][] readShortArray2D(String name, short[][] defVal) throws IOException { short[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); NodeList nodes = currentElem.getChildNodes(); List<short[]> shortArrays = new ArrayList<short[]>(); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("array")) { // Very unsafe assumption shortArrays.add(readShortArray(n.getNodeName(), null)); } } if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (shortArrays.size() != requiredSize) throw new IOException( "String array contains wrong element count. " + "Specified size " + requiredSize + ", data contains " + shortArrays.size()); } currentElem = (Element) currentElem.getParentNode(); return shortArrays.toArray(new short[0][]); } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public boolean readBoolean(String name, boolean defVal) throws IOException { boolean ret = defVal; try { String s = currentElem.getAttribute(name); if (s.length() > 0) { ret = Boolean.parseBoolean(s); } } catch (DOMException de) { throw new IOException(de); } return ret; } public boolean[] readBooleanArray(String name, boolean[] defVal) throws IOException { boolean[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); String[] strings = tmpEl.getAttribute("data").split("\\s+"); if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (strings.length != requiredSize) throw new IOException("Wrong number of bools. size says " + requiredSize + ", data contains " + strings.length); } boolean[] tmp = new boolean[strings.length]; for (int i = 0; i < tmp.length; i++) { tmp[i] = Boolean.parseBoolean(strings[i]); } return tmp; } catch (IOException ioe) { throw ioe; } catch (DOMException de) { throw new IOException(de); } } public boolean[][] readBooleanArray2D(String name, boolean[][] defVal) throws IOException { boolean[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); NodeList nodes = currentElem.getChildNodes(); List<boolean[]> booleanArrays = new ArrayList<boolean[]>(); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("array")) { // Very unsafe assumption booleanArrays.add(readBooleanArray(n.getNodeName(), null)); } } if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (booleanArrays.size() != requiredSize) throw new IOException( "String array contains wrong element count. " + "Specified size " + requiredSize + ", data contains " + booleanArrays.size()); } currentElem = (Element) currentElem.getParentNode(); return booleanArrays.toArray(new boolean[0][]); } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public String readString(String name, String defVal) throws IOException { String ret = defVal; try { ret = decodeString(currentElem.getAttribute(name)); } catch (DOMException de) { throw new IOException(de); } return ret; } public String[] readStringArray(String name, String[] defVal) throws IOException { String[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); NodeList nodes = tmpEl.getChildNodes(); List<String> strings = new ArrayList<String>(); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("String")) { // Very unsafe assumption strings.add(((Element) n).getAttributeNode("value").getValue()); } } if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (strings.size() != requiredSize) throw new IOException( "String array contains wrong element count. " + "Specified size " + requiredSize + ", data contains " + strings.size()); } return strings.toArray(new String[0]); } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public String[][] readStringArray2D(String name, String[][] defVal) throws IOException { String[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); NodeList nodes = currentElem.getChildNodes(); List<String[]> stringArrays = new ArrayList<String[]>(); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("array")) { // Very unsafe assumption stringArrays.add(readStringArray(n.getNodeName(), null)); } } if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (stringArrays.size() != requiredSize) throw new IOException( "String array contains wrong element count. " + "Specified size " + requiredSize + ", data contains " + stringArrays.size()); } currentElem = (Element) currentElem.getParentNode(); return stringArrays.toArray(new String[0][]); } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public BitSet readBitSet(String name, BitSet defVal) throws IOException { BitSet ret = defVal; try { BitSet set = new BitSet(); String bitString = currentElem.getAttribute(name); String[] strings = bitString.split("\\s+"); for (int i = 0; i < strings.length; i++) { int isSet = Integer.parseInt(strings[i]); if (isSet == 1) { set.set(i); } } ret = set; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } return ret; } public Savable readSavable(String name, Savable defVal) throws IOException { Savable ret = defVal; if (name != null && name.equals("")) { System.out.println("-"); } if (false) { } else { try { Element tmpEl = null; if (name != null) { tmpEl = findChildElement(currentElem, name); if (tmpEl == null) { return defVal; } } else if (isAtRoot) { tmpEl = doc.getDocumentElement(); isAtRoot = false; } else { tmpEl = findFirstChildElement(currentElem); } currentElem = tmpEl; ret = readSavableFromCurrentElem(defVal); if (currentElem.getParentNode() instanceof Element) { currentElem = (Element) currentElem.getParentNode(); } else { currentElem = null; } } catch (IOException ioe) { throw ioe; } catch (Exception e) { throw new IOException(e); } } return ret; } private Savable readSavableFromCurrentElem(Savable defVal) throws InstantiationException, ClassNotFoundException, IOException, IllegalAccessException { Savable ret = defVal; Savable tmp = null; if (currentElem == null || currentElem.getNodeName().equals("null")) { return null; } String reference = currentElem.getAttribute("ref"); if (reference.length() > 0) { ret = referencedSavables.get(reference); } else { String className = currentElem.getNodeName(); if (defVal != null) { className = defVal.getClass().getName(); } else if (currentElem.hasAttribute("class")) { className = currentElem.getAttribute("class"); } tmp = (Savable) Thread.currentThread().getContextClassLoader().loadClass(className).newInstance(); String refID = currentElem.getAttribute("reference_ID"); if (refID.length() < 1) refID = currentElem.getAttribute("id"); if (refID.length() > 0) referencedSavables.put(refID, tmp); if (tmp != null) { tmp.read(importer); ret = tmp; } } return ret; } private TextureState readTextureStateFromCurrent() { Element el = currentElem; TextureState ret = null; try { ret = (TextureState) readSavableFromCurrentElem(null); //Renderer r = DisplaySystem.getDisplaySystem().getRenderer(); Savable[] savs = readSavableArray("texture", new Texture[0]); // TODO: Investigate why both readSavableFromCurentElem(null) // and readSavableArray("texture", new TExture[0]) both resolve // the texture file resource. Who know what other work they // duplicate. for (int i = 0; i < savs.length; i++) { Texture t = (Texture) savs[i]; TextureKey tKey = t.getTextureKey(); t = TextureManager.loadTexture(tKey); ret.setTexture(t, i); } currentElem = el; } catch (Exception e) { Logger.getLogger(DOMInputCapsule.class.getName()).log(Level.SEVERE, null, e); } return ret; } private Savable[] readRenderStateList(Element fromElement, Savable[] defVal) { Savable[] ret = defVal; try { int size = RenderState.StateType.values().length; Savable[] tmp = new Savable[size]; currentElem = findFirstChildElement(fromElement); while (currentElem != null) { Element el = currentElem; RenderState rs = null; if (el.getNodeName().equals("com.jme.scene.state.TextureState")) { rs = readTextureStateFromCurrent(); } else { rs = (RenderState) (readSavableFromCurrentElem(null)); } if (rs != null) { tmp[rs.getStateType().ordinal()] = rs; } currentElem = findNextSiblingElement(el); ret = tmp; } } catch (Exception e) { Logger.getLogger(DOMInputCapsule.class.getName()).log(Level.SEVERE, null, e); } return ret; } public Savable[] readSavableArray(String name, Savable[] defVal) throws IOException { Savable[] ret = defVal; try { Element tmpEl = findChildElement(currentElem, name); if (tmpEl == null) { return defVal; } if (name.equals("renderStateList")) { ret = readRenderStateList(tmpEl, defVal); } else { String sizeString = tmpEl.getAttribute("size"); List<Savable> savables = new ArrayList<Savable>(); for (currentElem = findFirstChildElement(tmpEl); currentElem != null; currentElem = findNextSiblingElement(currentElem)) { savables.add(readSavableFromCurrentElem(null)); } if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (savables.size() != requiredSize) throw new IOException("Wrong number of Savables. size says " + requiredSize + ", data contains " + savables.size()); } ret = savables.toArray(new Savable[0]); } currentElem = (Element) tmpEl.getParentNode(); return ret; } catch (IOException ioe) { throw ioe; } catch (Exception e) { throw new IOException(e); } } public Savable[][] readSavableArray2D(String name, Savable[][] defVal) throws IOException { Savable[][] ret = defVal; try { Element tmpEl = findChildElement(currentElem, name); if (tmpEl == null) { return defVal; } int size_outer = Integer.parseInt(tmpEl.getAttribute("size_outer")); int size_inner = Integer.parseInt(tmpEl.getAttribute("size_outer")); Savable[][] tmp = new Savable[size_outer][size_inner]; currentElem = findFirstChildElement(tmpEl); for (int i = 0; i < size_outer; i++) { for (int j = 0; j < size_inner; j++) { tmp[i][j] = (readSavableFromCurrentElem(null)); if (i == size_outer - 1 && j == size_inner - 1) { break; } currentElem = findNextSiblingElement(currentElem); } } ret = tmp; currentElem = (Element) tmpEl.getParentNode(); return ret; } catch (IOException ioe) { throw ioe; } catch (Exception e) { throw new IOException(e); } } public ArrayList<Savable> readSavableArrayList(String name, ArrayList defVal) throws IOException { ArrayList<Savable> ret = defVal; try { Element tmpEl = findChildElement(currentElem, name); if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); ArrayList<Savable> savables = new ArrayList<Savable>(); for (currentElem = findFirstChildElement(tmpEl); currentElem != null; currentElem = findNextSiblingElement(currentElem)) { savables.add(readSavableFromCurrentElem(null)); } if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (savables.size() != requiredSize) throw new IOException("Wrong number of Savable rrays. size says " + requiredSize + ", data contains " + savables.size()); } currentElem = (Element) tmpEl.getParentNode(); return savables; } catch (IOException ioe) { throw ioe; } catch (Exception e) { throw new IOException(e); } } public ArrayList<Savable>[] readSavableArrayListArray( String name, ArrayList[] defVal) throws IOException { ArrayList[] ret = defVal; try { Element tmpEl = findChildElement(currentElem, name); if (tmpEl == null) { return defVal; } currentElem = tmpEl; String sizeString = tmpEl.getAttribute("size"); ArrayList<Savable> sal; List<ArrayList<Savable>> savableArrayLists = new ArrayList<ArrayList<Savable>>(); int i = -1; while ((sal = readSavableArrayList("SavableArrayList_" + ++i, null)) != null) savableArrayLists.add(sal); if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (savableArrayLists.size() != requiredSize) throw new IOException( "String array contains wrong element count. " + "Specified size " + requiredSize + ", data contains " + savableArrayLists.size()); } currentElem = (Element) tmpEl.getParentNode(); return savableArrayLists.toArray(new ArrayList[0]); } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public ArrayList<Savable>[][] readSavableArrayListArray2D(String name, ArrayList[][] defVal) throws IOException { ArrayList[][] ret = defVal; try { Element tmpEl = findChildElement(currentElem, name); if (tmpEl == null) { return defVal; } currentElem = tmpEl; String sizeString = tmpEl.getAttribute("size"); ArrayList<Savable>[] arr; List<ArrayList<Savable>[]> sall = new ArrayList<ArrayList<Savable>[]>(); int i = -1; while ((arr = readSavableArrayListArray( "SavableArrayListArray_" + ++i, null)) != null) sall.add(arr); if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (sall.size() != requiredSize) throw new IOException( "String array contains wrong element count. " + "Specified size " + requiredSize + ", data contains " + sall.size()); } currentElem = (Element) tmpEl.getParentNode(); return sall.toArray(new ArrayList[0][]); } catch (IOException ioe) { throw ioe; } catch (Exception e) { throw new IOException(e); } } public ArrayList<FloatBuffer> readFloatBufferArrayList( String name, ArrayList<FloatBuffer> defVal) throws IOException { ArrayList<FloatBuffer> ret = defVal; try { Element tmpEl = findChildElement(currentElem, name); if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); ArrayList<FloatBuffer> tmp = new ArrayList<FloatBuffer>(); for (currentElem = findFirstChildElement(tmpEl); currentElem != null; currentElem = findNextSiblingElement(currentElem)) { tmp.add(readFloatBuffer(null, null)); } if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (tmp.size() != requiredSize) throw new IOException( "String array contains wrong element count. " + "Specified size " + requiredSize + ", data contains " + tmp.size()); } currentElem = (Element) tmpEl.getParentNode(); return tmp; } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public Map<? extends Savable, ? extends Savable> readSavableMap(String name, Map<? extends Savable, ? extends Savable> defVal) throws IOException { Map<Savable, Savable> ret; Element tempEl; if (name != null) { tempEl = findChildElement(currentElem, name); } else { tempEl = currentElem; } ret = new HashMap<Savable, Savable>(); NodeList nodes = tempEl.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().equals("MapEntry")) { Element elem = (Element) n; currentElem = elem; Savable key = readSavable(XMLExporter.ELEMENT_KEY, null); Savable val = readSavable(XMLExporter.ELEMENT_VALUE, null); ret.put(key, val); } } currentElem = (Element) tempEl.getParentNode(); return ret; } public Map<String, ? extends Savable> readStringSavableMap(String name, Map<String, ? extends Savable> defVal) throws IOException { Map<String, Savable> ret = null; Element tempEl; if (name != null) { tempEl = findChildElement(currentElem, name); } else { tempEl = currentElem; } if (tempEl != null) { ret = new HashMap<String, Savable>(); NodeList nodes = tempEl.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().equals("MapEntry")) { Element elem = (Element) n; currentElem = elem; String key = currentElem.getAttribute("key"); Savable val = readSavable("Savable", null); ret.put(key, val); } } } else { return defVal; } currentElem = (Element) tempEl.getParentNode(); return ret; } /** * reads from currentElem if name is null */ public FloatBuffer readFloatBuffer(String name, FloatBuffer defVal) throws IOException { FloatBuffer ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(currentElem, name); } else { tmpEl = currentElem; } if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); String[] strings = tmpEl.getAttribute("data").split("\\s+"); if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (strings.length != requiredSize) throw new IOException("Wrong number of float buffers. size says " + requiredSize + ", data contains " + strings.length); } FloatBuffer tmp = BufferUtils.createFloatBuffer(strings.length); for (String s : strings) tmp.put(Float.parseFloat(s)); tmp.flip(); return tmp; } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public IntBuffer readIntBuffer(String name, IntBuffer defVal) throws IOException { IntBuffer ret = defVal; try { Element tmpEl = findChildElement(currentElem, name); if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); String[] strings = tmpEl.getAttribute("data").split("\\s+"); if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (strings.length != requiredSize) throw new IOException("Wrong number of int buffers. size says " + requiredSize + ", data contains " + strings.length); } IntBuffer tmp = BufferUtils.createIntBuffer(strings.length); for (String s : strings) tmp.put(Integer.parseInt(s)); tmp.flip(); return tmp; } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public ByteBuffer readByteBuffer(String name, ByteBuffer defVal) throws IOException { ByteBuffer ret = defVal; try { Element tmpEl = findChildElement(currentElem, name); if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); String[] strings = tmpEl.getAttribute("data").split("\\s+"); if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (strings.length != requiredSize) throw new IOException("Wrong number of byte buffers. size says " + requiredSize + ", data contains " + strings.length); } ByteBuffer tmp = BufferUtils.createByteBuffer(strings.length); for (String s : strings) tmp.put(Byte.valueOf(s)); tmp.flip(); return tmp; } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public ShortBuffer readShortBuffer(String name, ShortBuffer defVal) throws IOException { ShortBuffer ret = defVal; try { Element tmpEl = findChildElement(currentElem, name); if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); String[] strings = tmpEl.getAttribute("data").split("\\s+"); if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (strings.length != requiredSize) throw new IOException("Wrong number of short buffers. size says " + requiredSize + ", data contains " + strings.length); } ShortBuffer tmp = BufferUtils.createShortBuffer(strings.length); for (String s : strings) tmp.put(Short.valueOf(s)); tmp.flip(); return tmp; } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public ArrayList<ByteBuffer> readByteBufferArrayList(String name, ArrayList<ByteBuffer> defVal) throws IOException { ArrayList<ByteBuffer> ret = defVal; try { Element tmpEl = findChildElement(currentElem, name); if (tmpEl == null) { return defVal; } String sizeString = tmpEl.getAttribute("size"); ArrayList<ByteBuffer> tmp = new ArrayList<ByteBuffer>(); for (currentElem = findFirstChildElement(tmpEl); currentElem != null; currentElem = findNextSiblingElement(currentElem)) { tmp.add(readByteBuffer(null, null)); } if (sizeString.length() > 0) { int requiredSize = Integer.parseInt(sizeString); if (tmp.size() != requiredSize) throw new IOException("Wrong number of short buffers. size says " + requiredSize + ", data contains " + tmp.size()); } currentElem = (Element) tmpEl.getParentNode(); return tmp; } catch (IOException ioe) { throw ioe; } catch (NumberFormatException nfe) { throw new IOException(nfe); } catch (DOMException de) { throw new IOException(de); } } public <T extends Enum<T>> T readEnum(String name, Class<T> enumType, T defVal) throws IOException { T ret = defVal; try { String eVal = currentElem.getAttribute(name); if (eVal != null && eVal.length() > 0) { ret = Enum.valueOf(enumType, eVal); } } catch (Exception e) { throw new IOException(e); } return ret; } }