answer
stringlengths
17
10.2M
package tw.kewang.hbase.domain; import java.lang.reflect.Field; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tw.kewang.hbase.annotations.Component; import tw.kewang.hbase.annotations.Domain; import tw.kewang.hbase.dao.Constants; public abstract class AbstractDomain { private static final Logger LOG = LoggerFactory .getLogger(AbstractDomain.class); private static final Pattern PATTERN = Pattern.compile("\\{([\\d\\w]+)\\}"); public String getRowkey() { Class<?> clazz = getClass(); Domain domain = clazz.getAnnotation(Domain.class); if (domain != null) { return buildRowkey(clazz, domain.rowkey()); } return null; } private String buildRowkey(Class<?> clazz, String rowkeyPattern) { Matcher matcher = PATTERN.matcher(rowkeyPattern); StringBuffer sb = new StringBuffer(); while (matcher.find()) { for (Field field : clazz.getDeclaredFields()) { field.setAccessible(true); Component component = field.getAnnotation(Component.class); if (component.name().equals(matcher.group(1))) { try { String value = castValue(field); if (value != null) { matcher.appendReplacement(sb, value); } } catch (Exception e) { LOG.error(Constants.EXCEPTION_PREFIX, e); } } } } matcher.appendTail(sb); return sb.toString(); } private String castValue(Field field) { Class<?> fieldClass = field.getType(); try { if (fieldClass.isAssignableFrom(String.class)) { return (String) field.get(this); } else if (fieldClass.isAssignableFrom(Long.class)) { return String.valueOf(field.get(this)); } else if (fieldClass.isAssignableFrom(Integer.class)) { return String.valueOf(field.get(this)); } else { return null; } } catch (Exception e) { LOG.error(Constants.EXCEPTION_PREFIX, e); } return null; } public Object getRawValues() { return null; } }
package mightypork.utils.config.propmgr; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Map.Entry; import java.util.TreeMap; import mightypork.utils.Convert; import mightypork.utils.config.propmgr.properties.BooleanProperty; import mightypork.utils.config.propmgr.properties.DoubleProperty; import mightypork.utils.config.propmgr.properties.IntegerProperty; import mightypork.utils.config.propmgr.properties.StringProperty; import mightypork.utils.config.propmgr.store.PropertyFile; import mightypork.utils.logging.Log; public class PropertyManager { private final TreeMap<String, Property<?>> entries = new TreeMap<>(); private final TreeMap<String, String> renameTable = new TreeMap<>(); private PropertyStore props; /** * Create property manager from file path and a header comment.<br> * This is the same as using a {@link PropertyFile} store. * * @param file property file * @param comment header comment. */ public PropertyManager(File file, String comment) { this(new PropertyFile(file, comment)); } /** * Create property manager based on provided {@link PropertyStore} * * @param props a property store implementation backing this property * manager */ public PropertyManager(PropertyStore props) { this.props = props; } /** * Load from file */ public void load() { props.load(); // rename keys (useful if keys change but value is to be kept) for (final Entry<String, String> entry : renameTable.entrySet()) { final String value = props.getProperty(entry.getKey()); if (value == null) continue; final String oldKey = entry.getKey(); final String newKey = entry.getValue(); props.removeProperty(oldKey); props.setProperty(newKey, value, entries.get(newKey).getComment()); } for (final Property<?> entry : entries.values()) { entry.fromString(props.getProperty(entry.getKey())); } } public void save() { try { final ArrayList<String> keyList = new ArrayList<>(); // validate entries one by one, replace with default when needed for (final Property<?> entry : entries.values()) { keyList.add(entry.getKey()); props.setProperty(entry.getKey(), entry.toString(), entry.getComment()); } // removed unused props for (final String key : props.keys()) { if (!keyList.contains(key)) { props.removeProperty(key); } } props.save(); } catch (final IOException ioe) { ioe.printStackTrace(); } } /** * Get a property entry (rarely used) * * @param k key * @return the entry */ public Property<?> getProperty(String k) { try { return entries.get(k); } catch (final Exception e) { Log.w(e); return null; } } /** * Get boolean property * * @param k key * @return the boolean found, or false */ public Boolean getBoolean(String k) { return Convert.toBoolean(getProperty(k).getValue()); } /** * Get numeric property * * @param k key * @return the int found, or null */ public Integer getInteger(String k) { return Convert.toInteger(getProperty(k).getValue()); } /** * Get numeric property as double * * @param k key * @return the double found, or null */ public Double getDouble(String k) { return Convert.toDouble(getProperty(k).getValue()); } /** * Get string property * * @param k key * @return the string found, or null */ public String getString(String k) { return Convert.toString(getProperty(k).getValue()); } /** * Get arbitrary property. Make sure it's of the right type! * * @param k key * @return the prioperty found */ @SuppressWarnings("unchecked") public <T> T getValue(String k) { try { return ((Property<T>) getProperty(k)).getValue(); } catch (final ClassCastException e) { return null; } } /** * Add a boolean property * * @param k key * @param d default value * @param comment the in-file comment */ public void putBoolean(String k, boolean d, String comment) { putProperty(new BooleanProperty(k, d, comment)); } /** * Add a numeric property (double) * * @param k key * @param d default value * @param comment the in-file comment */ public void putDouble(String k, double d, String comment) { putProperty(new DoubleProperty(k, d, comment)); } /** * Add a numeric property * * @param k key * @param d default value * @param comment the in-file comment */ public void putInteger(String k, int d, String comment) { putProperty(new IntegerProperty(k, d, comment)); } /** * Add a string property * * @param k key * @param d default value * @param comment the in-file comment */ public void putString(String k, String d, String comment) { putProperty(new StringProperty(k, d, comment)); } /** * Add a generic property (can be used with custom property types) * * @param prop property to add */ public <T> void putProperty(Property<T> prop) { entries.put(prop.getKey(), prop); } /** * Rename key before loading; value is preserved * * @param oldKey old key * @param newKey new key */ public void renameKey(String oldKey, String newKey) { renameTable.put(oldKey, newKey); return; } /** * Set value saved to certain key. * * @param key key * @param value the saved value */ public void setValue(String key, Object value) { getProperty(key).setValue(value); } /** * Set heading comment of the property store. * * @param fileComment comment text (can be multi-line) */ public void setFileComment(String fileComment) { props.setComment(fileComment); } }
package net.domesdaybook.matcher.bytes; import java.io.IOException; import net.domesdaybook.util.bytes.ByteUtilities; import java.util.BitSet; import java.util.Set; import net.domesdaybook.reader.Reader; import net.domesdaybook.reader.Window; /** * A SetBitsetMatcher is a {@link ByteMatcher} which * matches an arbitrary set of bytes. * <p> * It uses a BitSet as the underlying representation of the entire set of bytes, * so is not memory efficient for small numbers of sets of bytes. * * @author Matt Palmer */ public final class SetBitsetMatcher extends InvertibleMatcher { private static final String ILLEGAL_ARGUMENTS = "Null or empty Byte set passed in to ByteSetMatcher."; private final BitSet byteValues = new BitSet(256); /** * Constructs a SetBitsetMatcher from a set of bytes. * * @param values A set of bytes * @param inverted Whether matching is on the set of bytes or their inverse. */ public SetBitsetMatcher(final Set<Byte> values, final boolean inverted) { super(inverted); if (values == null || values.isEmpty()) { throw new IllegalArgumentException(ILLEGAL_ARGUMENTS); } for (final Byte b : values) { byteValues.set(b & 0xFF); } } /** * {@inheritDoc} */ @Override public boolean matches(final Reader reader, final long matchPosition) throws IOException{ final Window window = reader.getWindow(matchPosition); return window == null? false : (byteValues.get(window.getByte(reader.getWindowOffset(matchPosition)) & 0xFF) ^ inverted); } /** * {@inheritDoc} */ @Override public boolean matches(final byte[] bytes, final int matchPosition) { return (matchPosition >= 0 && matchPosition < bytes.length) && (byteValues.get((int) bytes[matchPosition] & 0xFF) ^ inverted); } /** * {@inheritDoc} */ @Override public boolean matchesNoBoundsCheck(final byte[] bytes, final int matchPosition) { return byteValues.get((int) bytes[matchPosition] & 0xFF) ^ inverted; } /** * {@inheritDoc} */ @Override public boolean matches(final byte theByte) { return byteValues.get((int) theByte & 0xFF) ^ inverted; } /** * {@inheritDoc} */ @Override public String toRegularExpression(final boolean prettyPrint) { StringBuilder regularExpression = new StringBuilder(); if (prettyPrint) { regularExpression.append(' '); } regularExpression.append('['); if (inverted) { regularExpression.append('^'); } int firstBitSetPosition = byteValues.nextSetBit(0); while (firstBitSetPosition >= 0 && firstBitSetPosition < 256) { int lastBitSetPosition = byteValues.nextClearBit(firstBitSetPosition) - 1; // If the next clear position doesn't exist, then all remaining values are set: if (lastBitSetPosition < 0) { lastBitSetPosition = 255; } // If we have a range of more than 1 contiguous set positions, // represent this as a range of values: if (lastBitSetPosition - firstBitSetPosition > 1) { final String minValue = ByteUtilities.byteToString(prettyPrint, firstBitSetPosition); final String maxValue = ByteUtilities.byteToString(prettyPrint, lastBitSetPosition); regularExpression.append(String.format("%s-%s", minValue, maxValue)); } else { // less than 2 contiguous set positions - just write out a single byte: final String byteVal = ByteUtilities.byteToString(prettyPrint, firstBitSetPosition); regularExpression.append(byteVal); lastBitSetPosition = firstBitSetPosition; } firstBitSetPosition = byteValues.nextSetBit(lastBitSetPosition + 1); } regularExpression.append(']'); if (prettyPrint) { regularExpression.append(' '); } return regularExpression.toString(); } /** * {@inheritDoc} */ @Override public byte[] getMatchingBytes() { final byte[] values = new byte[getNumberOfMatchingBytes()]; int byteIndex = 0; for (int value = 0; value < 256; value++) { if (byteValues.get(value) ^ inverted) { values[byteIndex++] = (byte) value; } } return values; } /** * {@inheritDoc} */ @Override public int getNumberOfMatchingBytes() { return inverted ? 256 - byteValues.cardinality() : byteValues.cardinality(); } }
package net.lacolaco.smileessence.activity; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; import net.lacolaco.smileessence.Application; import net.lacolaco.smileessence.IntentRouter; import net.lacolaco.smileessence.R; import net.lacolaco.smileessence.data.CommandSettingCache; import net.lacolaco.smileessence.entity.Account; import net.lacolaco.smileessence.entity.CommandSetting; import net.lacolaco.smileessence.entity.SearchQuery; import net.lacolaco.smileessence.logging.Logger; import net.lacolaco.smileessence.notification.NotificationType; import net.lacolaco.smileessence.notification.Notificator; import net.lacolaco.smileessence.preference.AppPreferenceHelper; import net.lacolaco.smileessence.preference.UserPreferenceHelper; import net.lacolaco.smileessence.twitter.OAuthSession; import net.lacolaco.smileessence.twitter.StatusFilter; import net.lacolaco.smileessence.twitter.TwitterApi; import net.lacolaco.smileessence.twitter.UserStreamListener; import net.lacolaco.smileessence.twitter.task.*; import net.lacolaco.smileessence.twitter.util.TwitterUtils; import net.lacolaco.smileessence.util.BitmapURLTask; import net.lacolaco.smileessence.util.NetworkHelper; import net.lacolaco.smileessence.util.Themes; import net.lacolaco.smileessence.util.UIHandler; import net.lacolaco.smileessence.view.*; import net.lacolaco.smileessence.view.adapter.*; import net.lacolaco.smileessence.view.dialog.ConfirmDialogFragment; import net.lacolaco.smileessence.viewmodel.MessageViewModel; import net.lacolaco.smileessence.viewmodel.StatusViewModel; import net.lacolaco.smileessence.viewmodel.UserListListAdapter; import net.lacolaco.smileessence.viewmodel.menu.MainActivityMenuHelper; import twitter4j.*; import twitter4j.auth.AccessToken; import java.util.HashMap; import java.util.List; public class MainActivity extends Activity { public static final int REQUEST_OAUTH = 10; public static final int REQUEST_GET_PICTURE_FROM_GALLERY = 11; public static final int REQUEST_GET_PICTURE_FROM_CAMERA = 12; public static final int PAGE_POST = 0; public static final int PAGE_HOME = 1; public static final int PAGE_MENTIONS = 2; public static final int PAGE_MESSAGES = 3; public static final int PAGE_HISTORY = 4; public static final int PAGE_SEARCH = 5; public static final int PAGE_USERLIST = 6; private static final String KEY_LAST_USED_SEARCH_QUERY = "lastUsedSearchQuery"; private static final String KEY_LAST_USED_ACCOUNT_ID = "lastUsedAccountID"; private static final String KEY_LAST_USER_LIST = "lastUsedUserList"; private ViewPager viewPager; private PageListAdapter pagerAdapter; private OAuthSession oauthSession; private Account currentAccount; private TwitterStream stream; private HashMap<Integer, CustomListAdapter<?>> adapterMap = new HashMap<>(); private boolean streaming = false; private Uri cameraTempFilePath; private AppPreferenceHelper getAppPreferenceHelper() { return new AppPreferenceHelper(this); } public Uri getCameraTempFilePath() { return cameraTempFilePath; } public void setCameraTempFilePath(Uri cameraTempFilePath) { this.cameraTempFilePath = cameraTempFilePath; } public Account getCurrentAccount() { return currentAccount; } public void setCurrentAccount(Account account) { this.currentAccount = account; } private String getLastSearch() { return getAppPreferenceHelper().getValue(KEY_LAST_USED_SEARCH_QUERY, ""); } private long getLastUsedAccountID() { String id = getAppPreferenceHelper().getValue(KEY_LAST_USED_ACCOUNT_ID, ""); if(TextUtils.isEmpty(id)) { return -1; } else { return Long.parseLong(id); } } private void setLastUsedAccountID(Account account) { getAppPreferenceHelper().putValue(KEY_LAST_USED_ACCOUNT_ID, account.getId()); } private String getLastUserList() { return getAppPreferenceHelper().getValue(KEY_LAST_USER_LIST, ""); } public PageListAdapter getPagerAdapter() { return pagerAdapter; } public int getThemeIndex() { return ((Application) getApplication()).getThemeIndex(); } public UserPreferenceHelper getUserPreferenceHelper() { return new UserPreferenceHelper(this); } public String getVersion() { return getString(R.string.app_version); } private boolean isAuthorized() { long lastUsedAccountID = getLastUsedAccountID(); return lastUsedAccountID >= 0 && Account.load(Account.class, lastUsedAccountID) != null; } /** * Returns which twitter stream is running * * @return */ public boolean isStreaming() { return streaming; } public void setStreaming(boolean streaming) { this.streaming = streaming; } @Override public boolean dispatchKeyEvent(KeyEvent event) { if(event.getAction() != KeyEvent.ACTION_DOWN) { return super.dispatchKeyEvent(event); } switch(event.getKeyCode()) { case KeyEvent.KEYCODE_BACK: { finish(); return false; } default: { return super.dispatchKeyEvent(event); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch(requestCode) { case REQUEST_OAUTH: { receiveOAuth(requestCode, resultCode, data); break; } case REQUEST_GET_PICTURE_FROM_GALLERY: case REQUEST_GET_PICTURE_FROM_CAMERA: { getImageUri(requestCode, resultCode, data); break; } } } private void getImageUri(int requestCode, int resultCode, Intent data) { if(resultCode != RESULT_OK) { Logger.error(requestCode); Notificator.publish(this, R.string.notice_select_image_failed); finish(); return; } Uri uri; if(requestCode == REQUEST_GET_PICTURE_FROM_GALLERY) { uri = data.getData(); } else { uri = getCameraTempFilePath(); } openPostPageWithImage(uri); } public void openPostPageWithImage(Uri uri) { try { Cursor c = getContentResolver().query(uri, null, null, null, null); c.moveToFirst(); String path = c.getString(c.getColumnIndex(MediaStore.MediaColumns.DATA)); PostState.getState().beginTransaction() .setMediaFilePath(path) .commitWithOpen(this); Notificator.publish(this, R.string.notice_select_image_succeeded); } catch(Exception e) { e.printStackTrace(); Notificator.publish(this, R.string.notice_select_image_failed, NotificationType.ALERT); } } private void receiveOAuth(int requestCode, int resultCode, Intent data) { if(resultCode != RESULT_OK) { Logger.error(requestCode); Notificator.publish(this, R.string.notice_error_authenticate); finish(); } else { AccessToken token = oauthSession.getAccessToken(data.getData()); Account account = new Account(token.getToken(), token.getTokenSecret(), token.getUserId(), token.getScreenName()); account.save(); setCurrentAccount(account); setLastUsedAccountID(account); startMainLogic(); } } @Override public void finish() { if(viewPager == null) { forceFinish(); } else if(viewPager.getCurrentItem() != PAGE_HOME) { viewPager.setCurrentItem(PAGE_HOME, true); } else { ConfirmDialogFragment.show(this, getString(R.string.dialog_confirm_finish_app), new Runnable() { @Override public void run() { forceFinish(); } }); } } private void forceFinish() { super.finish(); } public void startMainLogic() { initializeView(); initCommandSetting(); startTwitter(); } private void initCommandSetting() { List<CommandSetting> commandSettings = CommandSetting.getAll(); for(CommandSetting setting : commandSettings) { CommandSettingCache.getInstance().put(setting); } } private void initializeView() { ActionBar bar = getActionBar(); bar.setDisplayShowHomeEnabled(true); bar.setDisplayShowTitleEnabled(false); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); viewPager = (ViewPager) findViewById(R.id.viewPager); pagerAdapter = new PageListAdapter(this, viewPager); initializePages(); } private void initializePages() { addPage(getString(R.string.page_name_post), PostFragment.class, null, true); StatusListAdapter homeAdapter = new StatusListAdapter(this); StatusListAdapter mentionsAdapter = new StatusListAdapter(this); MessageListAdapter messagesAdapter = new MessageListAdapter(this); EventListAdapter historyAdapter = new EventListAdapter(this); SearchListAdapter searchAdapter = new SearchListAdapter(this); UserListListAdapter userListAdapter = new UserListListAdapter(this); addListPage(getString(R.string.page_name_home), HomeFragment.class, homeAdapter); addListPage(getString(R.string.page_name_mentions), MentionsFragment.class, mentionsAdapter); addListPage(getString(R.string.page_name_messages), MessagesFragment.class, messagesAdapter); addListPage(getString(R.string.page_name_history), HistoryFragment.class, historyAdapter); addListPage(getString(R.string.page_name_search), SearchFragment.class, searchAdapter); addListPage(getString(R.string.page_name_list), UserListFragment.class, userListAdapter); pagerAdapter.refreshListNavigation(); viewPager.setOffscreenPageLimit(pagerAdapter.getCount()); initPostState(); setSelectedPageIndex(PAGE_HOME, false); } public void addListPage(String name, Class<? extends CustomListFragment> fragmentClass, CustomListAdapter<?> adapter) { int nextPosition = pagerAdapter.getCount(); Bundle args = new Bundle(); args.putInt(CustomListFragment.ADAPTER_INDEX, nextPosition); if(addPage(name, fragmentClass, args, false)) { adapterMap.put(nextPosition, adapter); } } public boolean addPage(String name, Class<? extends Fragment> fragmentClass, Bundle args, boolean withNotify) { if(withNotify) { return this.pagerAdapter.addPage(name, fragmentClass, args); } else { return this.pagerAdapter.addPageWithoutNotify(name, fragmentClass, args); } } private void initPostState() { PostState.newState().beginTransaction().commit(); } public void setSelectedPageIndex(final int position, final boolean smooth) { new UIHandler() { @Override public void run() { viewPager.setCurrentItem(position, smooth); } }.post(); } public boolean startTwitter() { if(!startStream()) { return false; } int count = TwitterUtils.getPagingCount(this); Twitter twitter = TwitterApi.getTwitter(currentAccount); Paging paging = TwitterUtils.getPaging(count); initBlockUser(twitter); initUserListCache(twitter); initHome(twitter, paging); initMentions(twitter, paging); initMessages(twitter, paging); initSearch(twitter); initUserList(twitter); updateActionBarIcon(); return true; } private void initBlockUser(Twitter twitter) { new BlockIDsTask(twitter, this).execute(); } private void initHome(final Twitter twitter, final Paging paging) { new HomeTimelineTask(twitter, this, paging) { @Override protected void onPostExecute(twitter4j.Status[] statuses) { super.onPostExecute(statuses); StatusListAdapter adapter = (StatusListAdapter) getListAdapter(PAGE_HOME); for(twitter4j.Status status : statuses) { StatusViewModel statusViewModel = new StatusViewModel(status, currentAccount); adapter.addToBottom(statusViewModel); StatusFilter.filter(MainActivity.this, statusViewModel); } adapter.updateForce(); } }.execute(); } private void initMentions(final Twitter twitter, final Paging paging) { new MentionsTimelineTask(twitter, this, paging) { @Override protected void onPostExecute(twitter4j.Status[] statuses) { super.onPostExecute(statuses); StatusListAdapter adapter = (StatusListAdapter) getListAdapter(PAGE_MENTIONS); for(twitter4j.Status status : statuses) { adapter.addToBottom(new StatusViewModel(status, currentAccount)); } adapter.updateForce(); } }.execute(); } private void initMessages(final Twitter twitter, final Paging paging) { new DirectMessagesTask(twitter, this, paging) { @Override protected void onPostExecute(DirectMessage[] directMessages) { super.onPostExecute(directMessages); CustomListAdapter<?> adapter = getListAdapter(PAGE_MESSAGES); for(DirectMessage message : directMessages) { adapter.addToBottom(new MessageViewModel(message, currentAccount)); } adapter.updateForce(); } }.execute(); } private void initSearch(Twitter twitter) { String lastUsedSearchQuery = getLastSearch(); if(!TextUtils.isEmpty(lastUsedSearchQuery)) { startNewSearch(twitter, lastUsedSearchQuery); } } public void startNewSearch(final Twitter twitter, final String query) { SearchQuery.saveIfNotFound(query); saveLastSearch(query); final SearchListAdapter adapter = (SearchListAdapter) getListAdapter(PAGE_SEARCH); adapter.initSearch(query); adapter.clear(); adapter.updateForce(); new SearchTask(twitter, query, this) { @Override protected void onPostExecute(QueryResult queryResult) { super.onPostExecute(queryResult); if(queryResult != null) { List<twitter4j.Status> tweets = queryResult.getTweets(); for(int i = tweets.size() - 1; i >= 0; i { twitter4j.Status status = tweets.get(i); if(!status.isRetweet()) { StatusViewModel viewModel = new StatusViewModel(status, getCurrentAccount()); adapter.addToTop(viewModel); StatusFilter.filter(MainActivity.this, viewModel); } } adapter.setTopID(queryResult.getMaxId()); adapter.updateForce(); } } }.execute(); } public CustomListAdapter<?> getListAdapter(int i) { return adapterMap.get(i); } private void saveLastSearch(String query) { getAppPreferenceHelper().putValue(KEY_LAST_USED_SEARCH_QUERY, query); } private void initUserList(Twitter twitter) { String lastUserList = getLastUserList(); if(!TextUtils.isEmpty(lastUserList)) { startUserList(twitter, lastUserList); } } private void startUserList(Twitter twitter, String listFullName) { saveLastUserList(listFullName); final UserListListAdapter adapter = (UserListListAdapter) getListAdapter(PAGE_USERLIST); adapter.setListFullName(listFullName); adapter.clear(); adapter.updateForce(); new UserListStatusesTask(twitter, listFullName, this) { @Override protected void onPostExecute(twitter4j.Status[] statuses) { super.onPostExecute(statuses); for(twitter4j.Status status : statuses) { StatusViewModel statusViewModel = new StatusViewModel(status, getCurrentAccount()); adapter.addToBottom(statusViewModel); StatusFilter.filter(MainActivity.this, statusViewModel); } adapter.updateForce(); } }.execute(); } public void saveLastUserList(String lastUserList) { getAppPreferenceHelper().putValue(KEY_LAST_USER_LIST, lastUserList); } private void initUserListCache(Twitter twitter) { new GetUserListsTask(twitter).execute(); } public boolean startStream() { if(!new NetworkHelper(this).canConnect()) { return false; } if(stream != null) { stream.shutdown(); } stream = new TwitterApi(currentAccount).getTwitterStream(); UserStreamListener listener = new UserStreamListener(this); stream.addListener(listener); stream.addConnectionLifeCycleListener(listener); stream.user(); return true; } public void updateActionBarIcon() { Twitter twitter = new TwitterApi(currentAccount).getTwitter(); final ImageView homeIcon = (ImageView) findViewById(android.R.id.home); ShowUserTask userTask = new ShowUserTask(twitter, currentAccount.userID) { @Override protected void onPostExecute(User user) { super.onPostExecute(user); if(user != null) { String urlHttps = user.getProfileImageURLHttps(); homeIcon.setScaleType(ImageView.ScaleType.FIT_CENTER); new BitmapURLTask(urlHttps, homeIcon).execute(); } } }; userTask.execute(); } @Override public void onCreate(Bundle savedInstanceState) { setTheme(); super.onCreate(savedInstanceState); setContentView(R.layout.main); if(isAuthorized()) { setupAccount(); startMainLogic(); IntentRouter.onNewIntent(this, getIntent()); } else { startOAuthSession(); } Logger.debug("MainActivity:onCreate"); } private void setTheme() { ((Application) getApplication()).setThemeIndex(getUserPreferenceHelper().getValue(R.string.key_setting_theme, 0)); setTheme(Themes.getTheme(getThemeIndex())); } private void setupAccount() { Account account = Account.load(Account.class, getLastUsedAccountID()); setCurrentAccount(account); } private void startOAuthSession() { oauthSession = new OAuthSession(); String url = oauthSession.getAuthorizationURL(); if(!TextUtils.isEmpty(url)) { Intent intent = new Intent(this, WebViewActivity.class); intent.setData(Uri.parse(url)); startActivityForResult(intent, REQUEST_OAUTH); } else { new Notificator(this, R.string.notice_error_authenticate_request).makeToast().show(); finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MainActivityMenuHelper.addItemsToMenu(this, menu); return true; } @Override protected void onDestroy() { super.onDestroy(); if(stream != null) { stream.shutdown(); } Logger.debug("MainActivity:onDestroy"); } @Override protected void onNewIntent(Intent intent) { IntentRouter.onNewIntent(this, intent); super.onNewIntent(intent); } @Override public boolean onOptionsItemSelected(MenuItem item) { return MainActivityMenuHelper.onItemSelected(this, item); } @Override protected void onPause() { super.onPause(); Logger.debug("MainActivity:onPause"); Notificator.stopNotification(); } @Override protected void onResume() { super.onResume(); Logger.debug("MainActivity:onResume"); Notificator.startNotification(); } public void openPostPage() { setSelectedPageIndex(MainActivity.PAGE_POST); } public void setSelectedPageIndex(int position) { viewPager.setCurrentItem(position, true); } /** * Open search page */ public void openSearchPage() { setSelectedPageIndex(PAGE_SEARCH); } /** * Open search page with given query */ public void openSearchPage(final String query) { startNewSearch(TwitterApi.getTwitter(getCurrentAccount()), query); openSearchPage(); } public void openUserListPage(String listFullName) { startUserList(TwitterApi.getTwitter(getCurrentAccount()), listFullName); openUserListPage(); } private void openUserListPage() { setSelectedPageIndex(PAGE_USERLIST); } }
package net.maizegenetics.gbs.homology; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import net.maizegenetics.gbs.util.BaseEncoder; /** * Takes a key file and then sets up the methods to decode a tag * * Developer: ed * */ public class ParseBarcodeRead { private static int chunkSize = BaseEncoder.chunkSize; //String baseDir="E:/SolexaAnal/"; private int maximumMismatchInBarcodeAndOverhang = 0; private static String[] initialCutSiteRemnant = null; private static int readEndCutSiteRemnantLength; static String nullS = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; private static String[] likelyReadEnd = null; private static String theEnzyme = null; //Original design CWGGATCGGAAGAGCGGTTCAGCAGGAATGCCGAG -- Common Adapter //Redesign CWGAGATCGGAAGAGCGGTTCAGCAGGAATGCCGAG -- Common Adapter static int maxBarcodeLength = 10; private Barcode[] theBarcodes; private long[] quickBarcodeList; private HashMap<Long, Integer> quickMap; public ParseBarcodeRead(String keyFile, String enzyme, String flowcell, String lane) { if (enzyme != null) { chooseEnzyme(enzyme); } else { chooseEnzyme(getKeyFileEnzyme(keyFile)); } int totalBarcodes = setupBarcodeFiles(new File(keyFile), flowcell, lane); System.out.println("Total barcodes found in lane:" + totalBarcodes); } /** * Determines which cut sites to look for, and sets them, based on the enzyme used to generate the GBS library. * For two-enzyme GBS both enzymes MUST be specified and separated by a dash "-". e.g. PstI-MspI, SbfI-MspI * The enzyme pair "PstI-EcoT22I" uses the Elshire common adapter while PstI-MspI, PstI-TaqI, and SbfI-MspI use a Y adapter (Poland et al. 2012) * @param enzyme The name of the enzyme (case insensitive) */ //TODO these should all be private static final globals, then just use this set which one is active. public static void chooseEnzyme(String enzyme) { // Check for case-insensitive (?i) match to a known enzyme // The common adapter is: [readEndCutSiteRemnant]AGATCGGAAGAGCGGTTCAGCAGGAATGCCGAG if (enzyme.matches("(?i)apek[i1]")) { theEnzyme = "ApeKI"; initialCutSiteRemnant = new String[]{"CAGC", "CTGC"}; likelyReadEnd = new String[]{"GCAGC", "GCTGC", "GCAGAGAT", "GCTGAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 4; } else if (enzyme.matches("(?i)pst[i1]")) { theEnzyme = "PstI"; initialCutSiteRemnant = new String[]{"TGCAG"}; likelyReadEnd = new String[]{"CTGCAG", "CTGCAAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 5; } else if (enzyme.matches("(?i)ecot22[i1]")) { theEnzyme = "EcoT22I"; initialCutSiteRemnant = new String[]{"TGCAT"}; likelyReadEnd = new String[]{"ATGCAT", "ATGCAAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 5; } else if (enzyme.matches("(?i)pas[i1]")) { theEnzyme = "PasI"; initialCutSiteRemnant = new String[]{"CAGGG", "CTGGG"}; likelyReadEnd = new String[]{"CCCAGGG", "CCCTGGG", "CCCTGAGAT", "CCCAGAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 5; } else if (enzyme.matches("(?i)hpaii|(?i)hpa2")) { theEnzyme = "HpaII"; initialCutSiteRemnant = new String[]{"CGG"}; likelyReadEnd = new String[]{"CCGG", "CCGAGATCGG"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)msp[i1]")) { theEnzyme = "MspI"; // MspI and HpaII are isoschizomers (same recognition seq and overhang) initialCutSiteRemnant = new String[]{"CGG"}; likelyReadEnd = new String[]{"CCGG", "CCGAGATCGG"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)pst[i1]-ecot22[i1]")) { theEnzyme = "PstI-EcoT22I"; initialCutSiteRemnant = new String[]{"TGCAG", "TGCAT"}; likelyReadEnd = new String[]{"ATGCAT", "CTGCAG", "CTGCAAGAT", "ATGCAAGAT"}; // look for EcoT22I site, PstI site, or common adapter for PstI/EcoT22I readEndCutSiteRemnantLength = 5; } else if (enzyme.matches("(?i)pst[i1]-msp[i1]")) { theEnzyme = "PstI-MspI"; initialCutSiteRemnant = new String[]{"TGCAG"}; // corrected, change from CCGAGATC to CCGCTCAGG, as Y adapter was used for MspI -QS likelyReadEnd = new String[]{"CCGG", "CTGCAG", "CCGCTCAGG"}; // look for MspI site, PstI site, or common adapter for MspI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)pst[i1]-taq[i1]")) { theEnzyme = "PstI-TaqI"; // corrected, change from TCGAGATC to TCGCTCAGG, as Y adapter was used for TaqI -QS initialCutSiteRemnant = new String[]{"TGCAG"}; likelyReadEnd = new String[]{"TCGA", "CTGCAG", "TCGCTCAGG"}; // look for TaqI site, PstI site, or common adapter for TaqI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)sbf[i1]-msp[i1]")) { theEnzyme = "SbfI-MspI"; initialCutSiteRemnant = new String[]{"TGCAGG"}; // corrected, change from CCGAGATC to CCGCTCAGG, as Y adapter was used for MspI -QS likelyReadEnd = new String[]{"CCGG", "CCTGCAGG", "CCGCTCAGG"}; // look for MspI site, SbfI site, or common adapter for MspI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)asis[i1]-msp[i1]")) { theEnzyme = "AsiSI-MspI"; initialCutSiteRemnant = new String[]{"ATCGC"}; // likelyReadEnd for common adapter is CCGCTCAGG, as the Poland et al.(2012) Y adapter was used for MspI likelyReadEnd = new String[]{"CCGG", "GCGATCGC", "CCGCTCAGG"}; // look for MspI site, AsiSI site, or common adapter for MspI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)bsshii-msp[i1]|(?i)bssh2-msp[i1]")) { theEnzyme = "BssHII-MspI"; initialCutSiteRemnant = new String[]{"CGCGC"}; // likelyReadEnd for common adapter is CCGCTCAGG, as the Poland et al.(2012) Y adapter was used for MspI likelyReadEnd = new String[]{"CCGG", "GCGCGC", "CCGCTCAGG"}; // look for MspI site, BssHII site, or common adapter for MspI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)fse[i1]-msp[i1]")) { theEnzyme = "FseI-MspI"; initialCutSiteRemnant = new String[]{"CCGGCC"}; // likelyReadEnd for common adapter is CCGCTCAGG, as the Poland et al.(2012) Y adapter was used for MspI likelyReadEnd = new String[]{"CCGG", "GGCCGGCC", "CCGCTCAGG"}; // look for MspI site, FseI site, or common adapter for MspI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)sal[i1]-msp[i1]")) { theEnzyme = "SalI-MspI"; initialCutSiteRemnant = new String[]{"TCGAC"}; // likelyReadEnd for common adapter is CCGCTCAGG, as the Poland et al.(2012) Y adapter was used for MspI likelyReadEnd = new String[]{"CCGG", "GTCGAC", "CCGCTCAGG"}; // look for MspI site, SalI site, or common adapter for MspI readEndCutSiteRemnantLength = 3; } else if(enzyme.matches("(?i)apo[i1]")){ theEnzyme = "ApoI"; initialCutSiteRemnant = new String[]{"AATTG","AATTC"}; likelyReadEnd = new String[]{"AAATTC","AAATTT","GAATTC","GAATTT","AAATTAGAT","GAATTAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 5; } else if(enzyme.matches("(?i)BamH[i1l]")){ theEnzyme = "BamHI"; initialCutSiteRemnant = new String[]{"GATCC"}; // full cut site (from partial digest or chimera) or common adapter start likelyReadEnd = new String[]{"GGATCC", "AGATCGGAA", "AGATCGGAAGAGCGGTTCAGCAGGAATGCCGAG"}; readEndCutSiteRemnantLength = 5; } else { System.out.println("The software didn't recognize your cut site. " + "Currently, only ApeKI, PstI, EcoT22I, PasI, HpaII, or MspI are recognized for single enzyme digests, " + "or PstI-EcoT22I, PstI-MspI, PstI-TaqI, SbfI-MspI, AsiSI-MspI, BssHII-MspI, FseI-MspI, or SalI-MspI for two-enzyme digests."); System.out.println("For two-enzyme digest, enzyme names should be separated by a dash, e.g. PstI-MspI "); } System.out.println("Enzyme: " + theEnzyme); } private String getKeyFileEnzyme(String keyFileName) { String result = null; try { BufferedReader br = new BufferedReader(new FileReader(keyFileName), 65536); String temp; int currLine = 0; while (((temp = br.readLine()) != null)) { String[] s = temp.split("\\t"); //split by whitespace if (currLine > 0) { String enzymeName; if (s.length < 9) { enzymeName = ""; } else { enzymeName = s[8]; } if (!enzymeName.equals("")) { result = enzymeName; break; } } currLine++; } } catch (Exception e) { System.out.println("Couldn't open key file to read Enzyme: " + e); } return result; } /* Reads in an Illumina key file, creates a linear array of {@link Barcode} objects * representing the barcodes in the key file, then creates a hash map containing * indices from the linear array indexed by sequence. The names of barcode objects * follow the pattern samplename:flowcell:lane:well, since sample names alone are not unique. * * @param keyFile Illumina key file. * @param flowcell Only barcodes from this flowcell will be added to the array. * @param lane Only barcodes from this lane will be added to the array. * @return Number of barcodes in the array. */ private int setupBarcodeFiles(File keyFile, String flowcell, String lane) { try { BufferedReader br = new BufferedReader(new FileReader(keyFile), 65536); ArrayList<Barcode> theBarcodesArrayList = new ArrayList<Barcode>(); String temp; while (((temp = br.readLine()) != null)) { String[] s = temp.split("\\t"); //split by whitespace Barcode theBC = null; if (s[0].equals(flowcell) && s[1].equals(lane)) { String well = (s[6].length() < 2) ? (s[5] + '0' + s[6]) : s[5] + s[6]; if (s.length < 8 || s[7] == null || s[7].equals("")) { // use the plate and well theBC = new Barcode(s[2], initialCutSiteRemnant, s[3] + ":" + s[0] + ":" + s[1] + ":" + s[4] + ":" + well, flowcell, lane); } else { // use the "libraryPlateWellID" or whatever is in column H of the key file, IF it is an integer try { int libPrepID = Integer.parseInt(s[7]); theBC = new Barcode(s[2], initialCutSiteRemnant, s[3] + ":" + s[0] + ":" + s[1] + ":" + libPrepID, flowcell, lane); } catch (NumberFormatException nfe) { theBC = new Barcode(s[2], initialCutSiteRemnant, s[3] + ":" + s[0] + ":" + s[1] + ":" + s[4] + ":" + well, flowcell, lane); } } theBarcodesArrayList.add(theBC); System.out.println(theBC.barcodeS + " " + theBC.taxaName); } } theBarcodes = new Barcode[theBarcodesArrayList.size()]; theBarcodesArrayList.toArray(theBarcodes); Arrays.sort(theBarcodes); int nBL = theBarcodes[0].barOverLong.length; quickBarcodeList = new long[theBarcodes.length * nBL]; quickMap = new HashMap(); for (int i = 0; i < theBarcodes.length; i++) { for (int j = 0; j < nBL; j++) { quickBarcodeList[i * nBL + j] = theBarcodes[i].barOverLong[j]; quickMap.put(theBarcodes[i].barOverLong[j], i); } } Arrays.sort(quickBarcodeList); } catch (Exception e) { System.out.println("Error with setupBarcodeFiles: " + e); } return theBarcodes.length; } private Barcode findBestBarcode(String queryS, int maxDivergence) { long query = BaseEncoder.getLongFromSeq(queryS.substring(0, chunkSize)); //note because the barcodes are polyA after the sequence, they should always //sort ahead of the hit, this is the reason for the -(closestHit+2) int closestHit = Arrays.binarySearch(quickBarcodeList, query); /* THIS IS THE NEW PIPELINE APPROACH THAT DOES NOT WORK if(closestHit>-2) return null; //hit or perfect if((query&quickBarcodeList[-(closestHit+2)])!=quickBarcodeList[-(closestHit+2)]) return null; int index =quickMap.get(quickBarcodeList[-(closestHit+2)]); // System.out.println(theBarcodes[index].barcodeS); return theBarcodes[index]; //note to see if it is a perfect match you can just bit AND */ // Below is the old pipeline approach, which works (at least for maxDivergence of 0) if (closestHit < -1) { // should always be true, as the barcode+overhang is padded to 32 bases with polyA int index = quickMap.get(quickBarcodeList[-(closestHit + 2)]); if (theBarcodes[index].compareSequence(query, 1) == 0) { return theBarcodes[index]; } else if (maxDivergence == 0) { return null; // return null if not a perfect match } } else { return null; // should never go to this line } int maxLength = 0, minDiv = maxDivergence + 1, countBest = 0; Barcode bestBC = null; for (Barcode bc : theBarcodes) { int div = bc.compareSequence(query, maxDivergence + 1); if (div <= minDiv) { if ((div < minDiv) || (bc.barOverLength > maxLength)) { minDiv = div; maxLength = bc.barOverLength; bestBC = bc; countBest = 1; } else { //it is a tie, so return that not resolvable bestBC = null; countBest++; } } } return bestBC; } /** * The barcode libraries used for this study can include two types of extraneous sequence * at the end of reads. The first are chimeras created with the free ends. These will * recreate the restriction site. The second are short regions (less than 64bp), so that will they * will contain a portion of site and the universal adapter. * This finds the first of site in likelyReadEnd, keeps the restriction site overhang and then sets everything * to polyA afterwards * @param seq An unprocessed tag sequence. * @param maxLength The maximum number of bp in the processed sequence. * @return returnValue A ReadBarcodeResult object containing the unprocessed tag, Cut site position, Processed tag, and Poly-A padded tag. */ public static ReadBarcodeResult removeSeqAfterSecondCutSite(String seq, byte maxLength) { //this looks for a second restriction site or the common adapter start, and then turns the remaining sequence to AAAA int cutSitePosition = 9999; ReadBarcodeResult returnValue = new ReadBarcodeResult(seq); //Look for cut sites, starting at a point past the length of the initial cut site remnant that all reads begin with String match = null; for (String potentialCutSite : likelyReadEnd) { int p = seq.indexOf(potentialCutSite, 1); if ((p > 1) && (p < cutSitePosition)) { cutSitePosition = p; match = potentialCutSite; } } if (theEnzyme.equalsIgnoreCase("ApeKI") && cutSitePosition == 2 && (match.equalsIgnoreCase("GCAGC") || match.equalsIgnoreCase("GCTGC"))) { // overlapping ApeKI cut site: GCWGCWGC seq = seq.substring(3, seq.length()); // trim off the initial GCW from GCWGCWGC cutSitePosition = 9999; returnValue.unprocessedSequence = seq; for (String potentialCutSite : likelyReadEnd) { int p = seq.indexOf(potentialCutSite, 1); if ((p > 1) && (p < cutSitePosition)) { cutSitePosition = p; } } } if (cutSitePosition < maxLength) { // Cut site found //Trim tag to sequence up to & including the cut site returnValue.length = (byte) (cutSitePosition + readEndCutSiteRemnantLength); returnValue.processedSequence = seq.substring(0, cutSitePosition + readEndCutSiteRemnantLength); } else { if (seq.length() <= 0) { //If cut site is missing because there is no sequence returnValue.processedSequence = ""; returnValue.length = 0; } else { //If cut site is missing because it is beyond the end of the sequence (or not present at all) returnValue.length = (byte) Math.min(seq.length(), maxLength); returnValue.processedSequence = (seq.substring(0, returnValue.length)); } } //Pad sequences shorter than max. length with A if (returnValue.length < maxLength) { returnValue.paddedSequence = returnValue.processedSequence + nullS; returnValue.paddedSequence = returnValue.paddedSequence.substring(0, maxLength); } else { //Truncate sequences longer than max. length returnValue.paddedSequence = returnValue.processedSequence.substring(0, maxLength); returnValue.length = maxLength; } return returnValue; } /** * * @param seqS * @param qualS * @param fastq * @param minQual * @return If barcode and cut site was found returns the result and processed sequence, if the barcode and cut site were not found return null */ public ReadBarcodeResult parseReadIntoTagAndTaxa(String seqS, String qualS, boolean fastq, int minQual) { long[] read = new long[2]; if ((minQual > 0) && (qualS != null)) { int firstBadBase = BaseEncoder.getFirstLowQualityPos(qualS, minQual); if (firstBadBase < (maxBarcodeLength + 2 * chunkSize)) { return null; } } int miss = -1; if (fastq) { miss = seqS.indexOf('N'); } else { miss = seqS.indexOf('.'); } if ((miss != -1) && (miss < (maxBarcodeLength + 2 * chunkSize))) { return null; //bad sequence so skip } Barcode bestBarcode = findBestBarcode(seqS, maximumMismatchInBarcodeAndOverhang); if (bestBarcode == null) { return null; //overhang missing so skip } String genomicSeq = seqS.substring(bestBarcode.barLength, seqS.length()); ReadBarcodeResult tagProcessingResults = removeSeqAfterSecondCutSite(genomicSeq, (byte) (2 * chunkSize)); String hap = tagProcessingResults.paddedSequence; //this is slow 20% of total time. Tag, cut site processed, padded with poly-A read = BaseEncoder.getLongArrayFromSeq(hap); int pos = tagProcessingResults.length; //TODO this instantiation should also include the orginal unprocessedSequence, processedSequence, and paddedSequence - the the object encode it ReadBarcodeResult rbr = new ReadBarcodeResult(read, (byte) pos, bestBarcode.getTaxaName()); return rbr; } public int getBarCodeCount() { return theBarcodes.length; } public Barcode getTheBarcodes(int index) { return theBarcodes[index]; } public String[] getTaxaNames() { String[] result = new String[getBarCodeCount()]; for (int i = 0; i < result.length; i++) { result[i] = getTheBarcodes(i).getTaxaName(); } return result; } static public String[] getInitialCutSiteRemnant() { return initialCutSiteRemnant; } }
package nu.validator.servlet; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.SequenceInputStream; import java.net.SocketTimeoutException; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import nu.validator.checker.LanguageDetectingChecker; import nu.validator.checker.XmlPiChecker; import nu.validator.checker.jing.CheckerSchema; import nu.validator.checker.schematronequiv.Assertions; import nu.validator.gnu.xml.aelfred2.FatalSAXException; import nu.validator.gnu.xml.aelfred2.SAXDriver; import nu.validator.htmlparser.common.DocumentMode; import nu.validator.htmlparser.common.DocumentModeHandler; import nu.validator.htmlparser.common.Heuristics; import nu.validator.htmlparser.common.XmlViolationPolicy; import nu.validator.htmlparser.sax.HtmlParser; import nu.validator.htmlparser.sax.HtmlSerializer; import nu.validator.htmlparser.sax.XmlSerializer; import nu.validator.io.BoundedInputStream; import nu.validator.io.DataUri; import nu.validator.io.StreamBoundException; import nu.validator.localentities.LocalCacheEntityResolver; import nu.validator.messages.GnuMessageEmitter; import nu.validator.messages.JsonMessageEmitter; import nu.validator.messages.MessageEmitterAdapter; import nu.validator.messages.TextMessageEmitter; import nu.validator.messages.TooManyErrorsException; import nu.validator.messages.XhtmlMessageEmitter; import nu.validator.messages.XmlMessageEmitter; import nu.validator.servlet.imagereview.ImageCollector; import nu.validator.servlet.OutlineBuildingXMLReaderWrapper.Section; import nu.validator.source.SourceCode; import nu.validator.spec.Spec; import nu.validator.spec.html5.Html5SpecBuilder; import nu.validator.xml.AttributesImpl; import nu.validator.xml.AttributesPermutingXMLReaderWrapper; import nu.validator.xml.BaseUriTracker; import nu.validator.xml.CharacterUtil; import nu.validator.xml.CombineContentHandler; import nu.validator.xml.ContentTypeParser; import nu.validator.xml.ContentTypeParser.NonXmlContentTypeException; import nu.validator.xml.DataUriEntityResolver; import nu.validator.xml.IdFilter; import nu.validator.xml.NamespaceDroppingXMLReaderWrapper; import nu.validator.xml.NullEntityResolver; import nu.validator.xml.PrudentHttpEntityResolver; import nu.validator.xml.PrudentHttpEntityResolver.ResourceNotRetrievableException; import nu.validator.xml.SystemErrErrorHandler; import nu.validator.xml.TypedInputSource; import nu.validator.xml.WiretapXMLReaderWrapper; import nu.validator.xml.XhtmlSaxEmitter; import nu.validator.xml.customelements.NamespaceChangingSchemaWrapper; import nu.validator.xml.templateelement.TemplateElementDroppingSchemaWrapper; import nu.validator.xml.dataattributes.DataAttributeDroppingSchemaWrapper; import nu.validator.xml.langattributes.XmlLangAttributeDroppingSchemaWrapper; import nu.validator.xml.roleattributes.RoleAttributeFilteringSchemaWrapper; import org.xml.sax.ContentHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.ext.LexicalHandler; import com.thaiopensource.relaxng.impl.CombineValidator; import com.thaiopensource.util.PropertyMap; import com.thaiopensource.util.PropertyMapBuilder; import com.thaiopensource.validate.IncorrectSchemaException; import com.thaiopensource.validate.Schema; import com.thaiopensource.validate.SchemaReader; import com.thaiopensource.validate.SchemaResolver; import com.thaiopensource.validate.ValidateProperty; import com.thaiopensource.validate.Validator; import com.thaiopensource.validate.auto.AutoSchemaReader; import com.thaiopensource.validate.prop.rng.RngProperty; import com.thaiopensource.validate.prop.wrap.WrapProperty; import com.thaiopensource.validate.rng.CompactSchemaReader; import org.apache.http.conn.ConnectTimeoutException; import org.apache.log4j.Logger; import com.ibm.icu.text.Normalizer; /** * @version $Id: VerifierServletTransaction.java,v 1.10 2005/07/24 07:32:48 * hsivonen Exp $ * @author hsivonen */ class VerifierServletTransaction implements DocumentModeHandler, SchemaResolver { private enum OutputFormat { HTML, XHTML, TEXT, XML, JSON, RELAXED, SOAP, UNICORN, GNU } private static final Logger log4j = Logger.getLogger(VerifierServletTransaction.class); private static final Pattern SPACE = Pattern.compile("\\s+"); private static final Pattern JS_IDENTIFIER = Pattern.compile("[\\p{Lu}\\p{Ll}\\p{Lt}\\p{Lm}\\p{Lo}\\p{Nl}_\\$][\\p{Lu}\\p{Ll}\\p{Lt}\\p{Lm}\\p{Lo}\\p{Nl}_\\$\\p{Mn}\\p{Mc}\\p{Nd}\\p{Pc}]*"); private static final String[] JS_RESERVED_WORDS = { "abstract", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "export", "extends", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "typeof", "var", "void", "volatile", "while", "with" }; private static final String[] CHARSETS = { "UTF-8", "UTF-16", "Windows-1250", "Windows-1251", "Windows-1252", "Windows-1253", "Windows-1254", "Windows-1255", "Windows-1256", "Windows-1257", "Windows-1258", "ISO-8859-1", "ISO-8859-2", "ISO-8859-3", "ISO-8859-4", "ISO-8859-5", "ISO-8859-6", "ISO-8859-7", "ISO-8859-8", "ISO-8859-9", "ISO-8859-13", "ISO-8859-15", "KOI8-R", "TIS-620", "GBK", "GB18030", "Big5", "Big5-HKSCS", "Shift_JIS", "ISO-2022-JP", "EUC-JP", "ISO-2022-KR", "EUC-KR" }; private static final char[][] CHARSET_DESCRIPTIONS = { "UTF-8 (Global)".toCharArray(), "UTF-16 (Global)".toCharArray(), "Windows-1250 (Central European)".toCharArray(), "Windows-1251 (Cyrillic)".toCharArray(), "Windows-1252 (Western)".toCharArray(), "Windows-1253 (Greek)".toCharArray(), "Windows-1254 (Turkish)".toCharArray(), "Windows-1255 (Hebrew)".toCharArray(), "Windows-1256 (Arabic)".toCharArray(), "Windows-1257 (Baltic)".toCharArray(), "Windows-1258 (Vietnamese)".toCharArray(), "ISO-8859-1 (Western)".toCharArray(), "ISO-8859-2 (Central European)".toCharArray(), "ISO-8859-3 (South European)".toCharArray(), "ISO-8859-4 (Baltic)".toCharArray(), "ISO-8859-5 (Cyrillic)".toCharArray(), "ISO-8859-6 (Arabic)".toCharArray(), "ISO-8859-7 (Greek)".toCharArray(), "ISO-8859-8 (Hebrew)".toCharArray(), "ISO-8859-9 (Turkish)".toCharArray(), "ISO-8859-13 (Baltic)".toCharArray(), "ISO-8859-15 (Western)".toCharArray(), "KOI8-R (Russian)".toCharArray(), "TIS-620 (Thai)".toCharArray(), "GBK (Chinese, simplified)".toCharArray(), "GB18030 (Chinese, simplified)".toCharArray(), "Big5 (Chinese, traditional)".toCharArray(), "Big5-HKSCS (Chinese, traditional)".toCharArray(), "Shift_JIS (Japanese)".toCharArray(), "ISO-2022-JP (Japanese)".toCharArray(), "EUC-JP (Japanese)".toCharArray(), "ISO-2022-KR (Korean)".toCharArray(), "EUC-KR (Korean)".toCharArray() }; protected static final int HTML5_SCHEMA = 3; protected static final int XHTML1STRICT_SCHEMA = 2; protected static final int XHTML1TRANSITIONAL_SCHEMA = 1; protected static final int XHTML5_SCHEMA = 7; private static final char[] SERVICE_TITLE; private static final char[] LIVING_VERSION = "Living Validator".toCharArray(); private static final char[] VERSION; private static final char[] RESULTS_TITLE; private static final char[] FOR = " for ".toCharArray(); private static final char[] ABOUT_THIS_SERVICE = "About this Service".toCharArray(); private static final char[] SIMPLE_UI = "Simplified Interface".toCharArray(); private static final byte[] CSS_CHECKING_PROLOG = "<!DOCTYPE html><html lang=''><title>s</title><style>\n" .getBytes(); private static final byte[] CSS_CHECKING_EPILOG = "\n</style>".getBytes(); private static final String USER_AGENT; private static Spec html5spec; private static int[] presetDoctypes; private static String[] presetLabels; private static String[] presetUrls; private static String[] presetNamespaces; // XXX SVG!!! private static final String[] KNOWN_CONTENT_TYPES = { "application/atom+xml", "application/docbook+xml", "application/xhtml+xml", "application/xv+xml", "image/svg+xml" }; private static final String[] NAMESPACES_FOR_KNOWN_CONTENT_TYPES = { "http: "http: "http: private static final String[] ALL_CHECKERS = { "http: "http://c.validator.nu/text-content/", "http://c.validator.nu/unchecked/", "http: "http: "http://c.validator.nu/microdata/", "http://c.validator.nu/langdetect/" }; private static final String[] ALL_CHECKERS_HTML4 = { "http: "http: private long start = System.currentTimeMillis(); protected final HttpServletRequest request; private final HttpServletResponse response; protected String document = null; private ParserMode parser = ParserMode.AUTO; private String profile = ""; private boolean laxType = false; private boolean aboutLegacyCompat = false; private boolean xhtml1Doctype = false; private boolean html4Doctype = false; protected ContentHandler contentHandler; protected XhtmlSaxEmitter emitter; protected MessageEmitterAdapter errorHandler; protected final AttributesImpl attrs = new AttributesImpl(); private OutputStream out; private PropertyMap jingPropertyMap; protected LocalCacheEntityResolver entityResolver; private static long lastModified; private static String[] preloadedSchemaUrls; private static Schema[] preloadedSchemas; private final static String cannotRecover = "Cannot recover after last" + " error. Any further errors will be ignored."; private final static String changingEncoding = "Changing encoding at this" + " point would need non-streamable behavior."; private final static String[] DENY_LIST = System.getProperty( "nu.validator.servlet.deny-list", "").split("\\s+"); private final static String ABOUT_PAGE = System.getProperty( "nu.validator.servlet.about-page", "https://about.validator.nu/"); private final static String HTML5_FACET = (VerifierServlet.HTML5_HOST.isEmpty() ? "" : ("//" + VerifierServlet.HTML5_HOST)) + VerifierServlet.HTML5_PATH; private final static String STYLE_SHEET = System.getProperty( "nu.validator.servlet.style-sheet", "style.css"); private final static String ICON = System.getProperty( "nu.validator.servlet.icon", "icon.png"); private final static String SCRIPT = System.getProperty( "nu.validator.servlet.script", "script.js"); private static final long SIZE_LIMIT = Integer.parseInt(System.getProperty( "nu.validator.servlet.max-file-size", "2097152")); private static String systemFilterString = ""; private final static String FILTER_FILE = System.getProperty( "nu.validator.servlet.filterfile", "resources/message-filters.txt"); protected String schemaUrls = null; protected Validator validator = null; private BufferingRootNamespaceSniffer bufferingRootNamespaceSniffer = null; private String contentType = null; protected HtmlParser htmlParser = null; protected SAXDriver xmlParser = null; protected XMLReader reader; protected TypedInputSource documentInput; protected PrudentHttpEntityResolver httpRes; protected DataUriEntityResolver dataRes; protected ContentTypeParser contentTypeParser; private Set<String> loadedValidatorUrls = new HashSet<>(); private boolean checkNormalization = false; private boolean rootNamespaceSeen = false; private OutputFormat outputFormat; private String postContentType; private boolean methodIsGet; private SourceCode sourceCode = new SourceCode(); private Deque<Section> outline; private Deque<Section> headingOutline; private boolean showSource; private boolean showOutline; private boolean checkErrorPages; private boolean schemaIsDefault; private String userAgent; private BaseUriTracker baseUriTracker = null; private String charsetOverride = null; private Set<String> filteredNamespaces = new LinkedHashSet<>(); // linked private LexicalHandler lexicalHandler; // for // stability protected ImageCollector imageCollector; private boolean externalSchema = false; private boolean externalSchematron = false; private String schemaListForStats = null; static { try { log4j.debug("Starting static initializer."); lastModified = 0; BufferedReader r = new BufferedReader(new InputStreamReader(LocalCacheEntityResolver.getPresetsAsStream(), "UTF-8")); String line; List<String> doctypes = new LinkedList<>(); List<String> namespaces = new LinkedList<>(); List<String> labels = new LinkedList<>(); List<String> urls = new LinkedList<>(); Properties props = new Properties(); log4j.debug("Reading miscellaneous properties."); props.load(VerifierServlet.class.getClassLoader().getResourceAsStream( "nu/validator/localentities/files/misc.properties")); SERVICE_TITLE = (System.getProperty( "nu.validator.servlet.service-name", props.getProperty("nu.validator.servlet.service-name", "Validator.nu")) + " ").toCharArray(); RESULTS_TITLE = (System.getProperty( "nu.validator.servlet.results-title", props.getProperty( "nu.validator.servlet.results-title", "Validation results"))).toCharArray(); VERSION = (System.getProperty("nu.validator.servlet.version", props.getProperty("nu.validator.servlet.version", "Living Validator"))).toCharArray(); USER_AGENT = (System.getProperty("nu.validator.servlet.user-agent", props.getProperty("nu.validator.servlet.user-agent", "Validator.nu/LV"))); log4j.debug("Starting to loop over config file lines."); while ((line = r.readLine()) != null) { if ("".equals(line.trim())) { break; } String s[] = line.split("\t"); doctypes.add(s[0]); namespaces.add(s[1]); labels.add(s[2]); urls.add(s[3]); } log4j.debug("Finished reading config."); String[] presetDoctypesAsStrings = doctypes.toArray(new String[0]); presetNamespaces = namespaces.toArray(new String[0]); presetLabels = labels.toArray(new String[0]); presetUrls = urls.toArray(new String[0]); log4j.debug("Converted config to arrays."); for (int i = 0; i < presetNamespaces.length; i++) { String str = presetNamespaces[i]; if ("-".equals(str)) { presetNamespaces[i] = null; } else { presetNamespaces[i] = presetNamespaces[i].intern(); } } log4j.debug("Prepared namespace array."); presetDoctypes = new int[presetDoctypesAsStrings.length]; for (int i = 0; i < presetDoctypesAsStrings.length; i++) { presetDoctypes[i] = Integer.parseInt(presetDoctypesAsStrings[i]); } log4j.debug("Parsed doctype numbers into ints."); String prefix = System.getProperty("nu.validator.servlet.cachepathprefix"); log4j.debug("The cache path prefix is: " + prefix); ErrorHandler eh = new SystemErrErrorHandler(); LocalCacheEntityResolver er = new LocalCacheEntityResolver(new NullEntityResolver()); er.setAllowRnc(true); PropertyMapBuilder pmb = new PropertyMapBuilder(); pmb.put(ValidateProperty.ERROR_HANDLER, eh); pmb.put(ValidateProperty.ENTITY_RESOLVER, er); pmb.put(ValidateProperty.XML_READER_CREATOR, new VerifierServletXMLReaderCreator(eh, er)); RngProperty.CHECK_ID_IDREF.add(pmb); PropertyMap pMap = pmb.toPropertyMap(); log4j.debug("Parsing set up. Starting to read schemas."); SortedMap<String, Schema> schemaMap = new TreeMap<>(); schemaMap.put("http://c.validator.nu/table/", CheckerSchema.TABLE_CHECKER); schemaMap.put("http://hsivonen.iki.fi/checkers/table/", CheckerSchema.TABLE_CHECKER); schemaMap.put("http://c.validator.nu/nfc/", CheckerSchema.NORMALIZATION_CHECKER); schemaMap.put("http://hsivonen.iki.fi/checkers/nfc/", CheckerSchema.NORMALIZATION_CHECKER); schemaMap.put("http://c.validator.nu/debug/", CheckerSchema.DEBUG_CHECKER); schemaMap.put("http://hsivonen.iki.fi/checkers/debug/", CheckerSchema.DEBUG_CHECKER); schemaMap.put("http://c.validator.nu/text-content/", CheckerSchema.TEXT_CONTENT_CHECKER); schemaMap.put("http://hsivonen.iki.fi/checkers/text-content/", CheckerSchema.TEXT_CONTENT_CHECKER); schemaMap.put("http://c.validator.nu/usemap/", CheckerSchema.USEMAP_CHECKER); schemaMap.put("http://n.validator.nu/checkers/usemap/", CheckerSchema.USEMAP_CHECKER); schemaMap.put("http://c.validator.nu/unchecked/", CheckerSchema.UNCHECKED_SUBTREE_WARNER); schemaMap.put("http://s.validator.nu/html5/assertions.sch", CheckerSchema.ASSERTION_SCH); schemaMap.put("http://c.validator.nu/obsolete/", CheckerSchema.CONFORMING_BUT_OBSOLETE_WARNER); schemaMap.put("http://c.validator.nu/xml-pi/", CheckerSchema.XML_PI_CHECKER); schemaMap.put("http://c.validator.nu/unsupported/", CheckerSchema.UNSUPPORTED_CHECKER); schemaMap.put("http://c.validator.nu/microdata/", CheckerSchema.MICRODATA_CHECKER); schemaMap.put("http://c.validator.nu/rdfalite/", CheckerSchema.RDFALITE_CHECKER); schemaMap.put("http://c.validator.nu/langdetect/", CheckerSchema.LANGUAGE_DETECTING_CHECKER); for (String presetUrl : presetUrls) { for (String url : SPACE.split(presetUrl)) { if (schemaMap.get(url) == null && !isCheckerUrl(url)) { Schema sch = schemaByUrl(url, er, pMap); schemaMap.put(url, sch); } } } log4j.debug("Schemas read."); preloadedSchemaUrls = new String[schemaMap.size()]; preloadedSchemas = new Schema[schemaMap.size()]; int i = 0; for (Map.Entry<String, Schema> entry : schemaMap.entrySet()) { preloadedSchemaUrls[i] = entry.getKey().intern(); Schema s = entry.getValue(); String u = entry.getKey(); if (isDataAttributeDroppingSchema(u)) { s = new DataAttributeDroppingSchemaWrapper( s); } if (isXmlLangAllowingSchema(u)) { s = new XmlLangAttributeDroppingSchemaWrapper(s); } if (isRoleAttributeFilteringSchema(u)) { s = new RoleAttributeFilteringSchemaWrapper(s); } if (isTemplateElementDroppingSchema(u)) { s = new TemplateElementDroppingSchemaWrapper(s); } if (isCustomElementNamespaceChangingSchema(u)) { s = new NamespaceChangingSchemaWrapper(s); } preloadedSchemas[i] = s; i++; } log4j.debug("Reading spec."); html5spec = Html5SpecBuilder.parseSpec(LocalCacheEntityResolver.getHtml5SpecAsStream()); log4j.debug("Spec read."); if (new File(FILTER_FILE).isFile()) { log4j.debug("Reading filter file " + FILTER_FILE); try (BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(FILTER_FILE), "UTF-8"))) { StringBuilder sb = new StringBuilder(); String filterline; String pipe = ""; while ((filterline = reader.readLine()) != null) { if (filterline.startsWith(" continue; } sb.append(pipe); sb.append(filterline); pipe = "|"; } if (sb.length() != 0) { if ("".equals(systemFilterString)) { systemFilterString = sb.toString(); } else { systemFilterString += "|" + sb.toString(); } } } log4j.debug("Filter file read."); } } catch (Exception e) { throw new RuntimeException(e); } } @SuppressWarnings("deprecation") protected static String scrub(CharSequence s) { return Normalizer.normalize( CharacterUtil.prudentlyScrubCharacterData(s), Normalizer.NFC); } private static boolean isDataAttributeDroppingSchema(String key) { return ("http://s.validator.nu/xhtml5.rnc".equals(key) || "http://s.validator.nu/html5.rnc".equals(key) || "http://s.validator.nu/html5-all.rnc".equals(key) || "http://s.validator.nu/xhtml5-all.rnc".equals(key) || "http://s.validator.nu/html5-its.rnc".equals(key) || "http://s.validator.nu/xhtml5-rdfalite.rnc".equals(key) || "http://s.validator.nu/html5-rdfalite.rnc".equals(key)); } private static boolean isXmlLangAllowingSchema(String key) { return ("http://s.validator.nu/xhtml5.rnc".equals(key) || "http://s.validator.nu/html5.rnc".equals(key) || "http://s.validator.nu/html5-all.rnc".equals(key) || "http://s.validator.nu/xhtml5-all.rnc".equals(key) || "http://s.validator.nu/html5-its.rnc".equals(key) || "http://s.validator.nu/xhtml5-rdfalite.rnc".equals(key) || "http://s.validator.nu/html5-rdfalite.rnc".equals(key)); } private static boolean isRoleAttributeFilteringSchema(String key) { return ("http://s.validator.nu/xhtml5.rnc".equals(key) || "http://s.validator.nu/html5.rnc".equals(key) || "http://s.validator.nu/html5-all.rnc".equals(key) || "http://s.validator.nu/xhtml5-all.rnc".equals(key) || "http://s.validator.nu/html5-its.rnc".equals(key) || "http://s.validator.nu/xhtml5-rdfalite.rnc".equals(key) || "http://s.validator.nu/html5-rdfalite.rnc".equals(key)); } private static boolean isTemplateElementDroppingSchema(String key) { return ("http://s.validator.nu/xhtml5.rnc".equals(key) || "http://s.validator.nu/html5.rnc".equals(key) || "http://s.validator.nu/html5-all.rnc".equals(key) || "http://s.validator.nu/xhtml5-all.rnc".equals(key) || "http://s.validator.nu/html5-its.rnc".equals(key) || "http://s.validator.nu/xhtml5-rdfalite.rnc".equals(key) || "http://s.validator.nu/html5-rdfalite.rnc".equals(key)); } private static boolean isCustomElementNamespaceChangingSchema(String key) { return ("http://s.validator.nu/xhtml5.rnc".equals(key) || "http://s.validator.nu/html5.rnc".equals(key) || "http://s.validator.nu/html5-all.rnc".equals(key) || "http://s.validator.nu/xhtml5-all.rnc".equals(key) || "http://s.validator.nu/html5-its.rnc".equals(key) || "http://s.validator.nu/xhtml5-rdfalite.rnc".equals(key) || "http://s.validator.nu/html5-rdfalite.rnc".equals(key)); } private static boolean isCheckerUrl(String url) { if ("http://c.validator.nu/all/".equals(url) || "http://hsivonen.iki.fi/checkers/all/".equals(url)) { return true; } else if ("http://c.validator.nu/all-html4/".equals(url) || "http://hsivonen.iki.fi/checkers/all-html4/".equals(url)) { return true; } else if ("http://c.validator.nu/base/".equals(url)) { return true; } else if ("http://c.validator.nu/rdfalite/".equals(url)) { return true; } for (String checker : ALL_CHECKERS) { if (checker.equals(url)) { return true; } } return false; } /** * @param request * @param response */ VerifierServletTransaction(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; } protected boolean willValidate() { if (methodIsGet) { return document != null; } else { // POST return true; } } void service() throws ServletException, IOException { this.methodIsGet = "GET".equals(request.getMethod()) || "HEAD".equals(request.getMethod()); this.out = response.getOutputStream(); try { request.setCharacterEncoding("utf-8"); } catch (NoSuchMethodError e) { log4j.debug("Vintage Servlet API doesn't support setCharacterEncoding().", e); } if (!methodIsGet) { postContentType = request.getContentType(); if (postContentType == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Content-Type missing"); return; } else if (postContentType.trim().toLowerCase().startsWith( "application/x-www-form-urlencoded")) { response.sendError( HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "application/x-www-form-urlencoded not supported. Please use multipart/form-data."); return; } } String outFormat = request.getParameter("out"); if (outFormat == null) { outputFormat = OutputFormat.HTML; } else { if ("html".equals(outFormat)) { outputFormat = OutputFormat.HTML; } else if ("xhtml".equals(outFormat)) { outputFormat = OutputFormat.XHTML; } else if ("text".equals(outFormat)) { outputFormat = OutputFormat.TEXT; } else if ("gnu".equals(outFormat)) { outputFormat = OutputFormat.GNU; } else if ("xml".equals(outFormat)) { outputFormat = OutputFormat.XML; } else if ("json".equals(outFormat)) { outputFormat = OutputFormat.JSON; } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported output format"); return; } } if (!methodIsGet) { document = request.getHeader("Content-Location"); } if (document == null) { document = request.getParameter("doc"); } if (document == null) { document = request.getParameter("file"); } document = ("".equals(document)) ? null : document; if (document != null) { for (String domain : DENY_LIST) { if (!"".equals(domain) && document.contains(domain)) { response.sendError(429, "Too many requests"); return; } } if (document.contains("google.")) { response.sendRedirect(document); return; } } String callback = null; if (outputFormat == OutputFormat.JSON) { callback = request.getParameter("callback"); if (callback != null) { Matcher m = JS_IDENTIFIER.matcher(callback); if (m.matches()) { if (Arrays.binarySearch(JS_RESERVED_WORDS, callback) >= 0) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Callback is a reserved word."); return; } } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Callback is not a valid ECMA 262 IdentifierName."); return; } } } if (willValidate()) { response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); } else if (outputFormat == OutputFormat.HTML || outputFormat == OutputFormat.XHTML) { response.setDateHeader("Last-Modified", lastModified); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No input document"); return; } setup(); String filterString = systemFilterString; String filterPatternParam = request.getParameter("filterpattern"); if (filterPatternParam != null && !"".equals(filterPatternParam)) { if ("".equals(filterString)) { filterString = scrub(filterPatternParam); } else { filterString += "|" + scrub(filterPatternParam); } } String filterUrl = request.getParameter("filterurl"); if (filterUrl != null && !"".equals(filterUrl)) { try { InputSource filterFile = (new PrudentHttpEntityResolver(-1, true, null)) .resolveEntity(null, filterUrl); StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader( filterFile.getByteStream())); String line; String pipe = ""; while ((line = reader.readLine()) != null) { if (line.startsWith(" continue; } sb.append(pipe); sb.append(line); pipe = "|"; } if (sb.length() != 0) { if (!"".equals(filterString)) { filterString = scrub(sb.toString()); } else { filterString += "|" + scrub(sb.toString()); } } } catch (Exception e) { response.sendError(500, e.getMessage()); } } Pattern filterPattern = null; if (!"".equals(filterString)) { filterPattern = Pattern.compile(filterString); } if (request.getParameter("useragent") != null) { userAgent = scrub(request.getParameter("useragent")); } else { userAgent = USER_AGENT; } if (request.getParameter("acceptlanguage") != null) { request.setAttribute( "http://validator.nu/properties/accept-language", scrub(request.getParameter("acceptlanguage"))); } Object inputType = request.getAttribute("nu.validator.servlet.MultipartFormDataFilter.type"); showSource = (request.getParameter("showsource") != null); showSource = (showSource || "textarea".equals(inputType)); showOutline = (request.getParameter("showoutline") != null); if (request.getParameter("checkerrorpages") != null) { request.setAttribute( "http://validator.nu/properties/ignore-response-status", true); } if (request.getParameter("showimagereport") != null) { imageCollector = new ImageCollector(sourceCode); } String charset = request.getParameter("charset"); if (charset != null) { charset = scrub(charset.trim()); if (!"".equals(charset)) { charsetOverride = charset; } } String nsfilter = request.getParameter("nsfilter"); if (nsfilter != null) { for (String ns : SPACE.split(nsfilter)) { if (ns.length() > 0) { filteredNamespaces.add(ns); } } } boolean errorsOnly = ("error".equals(request.getParameter("level"))); boolean asciiQuotes = (request.getParameter("asciiquotes") != null); int lineOffset = 0; String lineOffsetStr = request.getParameter("lineoffset"); if (lineOffsetStr != null) { try { lineOffset = Integer.parseInt(lineOffsetStr); } catch (NumberFormatException e) { } } try { if (outputFormat == OutputFormat.HTML || outputFormat == OutputFormat.XHTML) { if (outputFormat == OutputFormat.HTML) { response.setContentType("text/html; charset=utf-8"); contentHandler = new HtmlSerializer(out); } else { response.setContentType("application/xhtml+xml"); contentHandler = new XmlSerializer(out); } emitter = new XhtmlSaxEmitter(contentHandler); errorHandler = new MessageEmitterAdapter(filterPattern, sourceCode, showSource, imageCollector, lineOffset, false, new XhtmlMessageEmitter(contentHandler)); PageEmitter.emit(contentHandler, this); } else { if (outputFormat == OutputFormat.TEXT) { response.setContentType("text/plain; charset=utf-8"); errorHandler = new MessageEmitterAdapter(filterPattern, sourceCode, showSource, null, lineOffset, false, new TextMessageEmitter(out, asciiQuotes)); } else if (outputFormat == OutputFormat.GNU) { response.setContentType("text/plain; charset=utf-8"); errorHandler = new MessageEmitterAdapter(filterPattern, sourceCode, showSource, null, lineOffset, false, new GnuMessageEmitter(out, asciiQuotes)); } else if (outputFormat == OutputFormat.XML) { response.setContentType("application/xml"); errorHandler = new MessageEmitterAdapter(filterPattern, sourceCode, showSource, null, lineOffset, false, new XmlMessageEmitter(new XmlSerializer(out))); } else if (outputFormat == OutputFormat.JSON) { if (callback == null) { response.setContentType("application/json; charset=utf-8"); } else { response.setContentType("application/javascript; charset=utf-8"); } errorHandler = new MessageEmitterAdapter(filterPattern, sourceCode, showSource, null, lineOffset, false, new JsonMessageEmitter( new nu.validator.json.Serializer(out), callback)); } else { throw new RuntimeException("Unreachable."); } errorHandler.setErrorsOnly(errorsOnly); validate(); } } catch (SAXException e) { log4j.debug("SAXException: " + e.getMessage()); } } /** * @throws ServletException */ protected void setup() throws ServletException { String preset = request.getParameter("preset"); if (preset != null && !"".equals(preset)) { schemaUrls = preset; } else { schemaUrls = request.getParameter("schema"); } if (schemaUrls == null) { schemaUrls = ""; } String parserStr = request.getParameter("parser"); if ("html".equals(parserStr)) { parser = ParserMode.HTML; } else if ("xmldtd".equals(parserStr)) { parser = ParserMode.XML_EXTERNAL_ENTITIES_NO_VALIDATION; } else if ("xml".equals(parserStr)) { parser = ParserMode.XML_NO_EXTERNAL_ENTITIES; } else if ("html5".equals(parserStr)) { parser = ParserMode.HTML; } // else auto laxType = (request.getParameter("laxtype") != null); } private boolean isHtmlUnsafePreset() { if ("".equals(schemaUrls)) { return false; } boolean preset = false; for (String presetUrl : presetUrls) { if (presetUrl.equals(schemaUrls)) { preset = true; break; } } if (!preset) { return false; } return !(schemaUrls.startsWith("http://s.validator.nu/xhtml10/xhtml-basic.rnc") || schemaUrls.startsWith("http://s.validator.nu/xhtml10/xhtml-strict.rnc") || schemaUrls.startsWith("http://s.validator.nu/xhtml10/xhtml-transitional.rnc") || schemaUrls.startsWith("http://s.validator.nu/xhtml10/xhtml-frameset.rnc") || schemaUrls.startsWith("http://s.validator.nu/html5.rnc") || schemaUrls.startsWith("http://s.validator.nu/html5-all.rnc") || schemaUrls.startsWith("http://s.validator.nu/html5-its.rnc") || schemaUrls.startsWith("http://s.validator.nu/html5-rdfalite.rnc")); } /** * @throws SAXException */ @SuppressWarnings({ "deprecation", "unchecked" }) void validate() throws SAXException { if (!willValidate()) { return; } boolean isHtmlOrXhtml = (outputFormat == OutputFormat.HTML || outputFormat == OutputFormat.XHTML); if (isHtmlOrXhtml) { try { out.flush(); } catch (IOException e1) { throw new SAXException(e1); } } httpRes = new PrudentHttpEntityResolver(SIZE_LIMIT, laxType, errorHandler, request); httpRes.setUserAgent(userAgent); dataRes = new DataUriEntityResolver(httpRes, laxType, errorHandler); contentTypeParser = new ContentTypeParser(errorHandler, laxType); entityResolver = new LocalCacheEntityResolver(dataRes); setAllowRnc(true); setAllowCss(true); try { this.errorHandler.start(document); PropertyMapBuilder pmb = new PropertyMapBuilder(); pmb.put(ValidateProperty.ERROR_HANDLER, errorHandler); pmb.put(ValidateProperty.ENTITY_RESOLVER, entityResolver); pmb.put(ValidateProperty.XML_READER_CREATOR, new VerifierServletXMLReaderCreator(errorHandler, entityResolver)); pmb.put(ValidateProperty.SCHEMA_RESOLVER, this); RngProperty.CHECK_ID_IDREF.add(pmb); jingPropertyMap = pmb.toPropertyMap(); tryToSetupValidator(); setAllowRnc(false); loadDocAndSetupParser(); setErrorProfile(); contentType = documentInput.getType(); if ("text/css".equals(contentType)) { String charset = "UTF-8"; if (documentInput.getEncoding() != null) { charset = documentInput.getEncoding(); } List<InputStream> streams = new ArrayList<>(); streams.add(new ByteArrayInputStream(CSS_CHECKING_PROLOG)); streams.add(documentInput.getByteStream()); streams.add(new ByteArrayInputStream(CSS_CHECKING_EPILOG)); Enumeration<InputStream> e = Collections.enumeration(streams); documentInput.setByteStream(new SequenceInputStream(e)); documentInput.setEncoding(charset); errorHandler.setLineOffset(-1); sourceCode.setIsCss(); parser = ParserMode.HTML; loadDocAndSetupParser(); } reader.setErrorHandler(errorHandler); sourceCode.initialize(documentInput); if (validator == null) { checkNormalization = true; } if (checkNormalization) { reader.setFeature( "http://xml.org/sax/features/unicode-normalization-checking", true); } WiretapXMLReaderWrapper wiretap = new WiretapXMLReaderWrapper( reader); ContentHandler recorder = sourceCode.getLocationRecorder(); if (baseUriTracker == null) { wiretap.setWiretapContentHander(recorder); } else { wiretap.setWiretapContentHander(new CombineContentHandler( recorder, baseUriTracker)); } wiretap.setWiretapLexicalHandler((LexicalHandler) recorder); reader = wiretap; if (htmlParser != null) { htmlParser.addCharacterHandler(sourceCode); htmlParser.setMappingLangToXmlLang(true); htmlParser.setErrorHandler(errorHandler.getExactErrorHandler()); htmlParser.setTreeBuilderErrorHandlerOverride(errorHandler); errorHandler.setHtml(true); } else if (xmlParser != null) { // this must be after wiretap! if (!filteredNamespaces.isEmpty()) { reader = new NamespaceDroppingXMLReaderWrapper(reader, filteredNamespaces); } xmlParser.setErrorHandler(errorHandler.getExactErrorHandler()); xmlParser.lockErrorHandler(); } else { throw new RuntimeException("Bug. Unreachable."); } reader = new AttributesPermutingXMLReaderWrapper(reader); // make // RNG // validation // better if (charsetOverride != null) { String charset = documentInput.getEncoding(); if (charset == null) { errorHandler.warning(new SAXParseException( "Overriding document character encoding from none to \u201C" + charsetOverride + "\u201D.", null)); } else { errorHandler.warning(new SAXParseException( "Overriding document character encoding from \u201C" + charset + "\u201D to \u201C" + charsetOverride + "\u201D.", null)); } documentInput.setEncoding(charsetOverride); } if (showOutline) { reader = new OutlineBuildingXMLReaderWrapper(reader, request, false); reader = new OutlineBuildingXMLReaderWrapper(reader, request, true); } reader.parse(documentInput); if (showOutline) { outline = (Deque<Section>) request.getAttribute( "http://validator.nu/properties/document-outline"); headingOutline = (Deque<Section>) request.getAttribute( "http://validator.nu/properties/heading-outline"); } } catch (CannotFindPresetSchemaException e) { } catch (ResourceNotRetrievableException e) { log4j.debug(e.getMessage()); } catch (NonXmlContentTypeException e) { log4j.debug(e.getMessage()); } catch (FatalSAXException e) { log4j.debug(e.getMessage()); } catch (SocketTimeoutException e) { errorHandler.ioError(new IOException(e.getMessage(), null)); } catch (ConnectTimeoutException e) { errorHandler.ioError(new IOException(e.getMessage(), null)); } catch (TooManyErrorsException e) { errorHandler.fatalError(e); } catch (SAXException e) { String msg = e.getMessage(); if (!cannotRecover.equals(msg) && !changingEncoding.equals(msg)) { log4j.debug("SAXException: " + e.getMessage()); } } catch (IOException e) { isHtmlOrXhtml = false; if (e.getCause() instanceof org.apache.http.TruncatedChunkException) { log4j.debug("TruncatedChunkException", e.getCause()); } else { errorHandler.ioError(e); } } catch (IncorrectSchemaException e) { log4j.debug("IncorrectSchemaException", e); errorHandler.schemaError(e); } catch (RuntimeException e) { isHtmlOrXhtml = false; log4j.error("RuntimeException, doc: " + document + " schema: " + schemaUrls + " lax: " + laxType, e); errorHandler.internalError( e, "Oops. That was not supposed to happen. A bug manifested itself in the application internals. Unable to continue. Sorry. The admin was notified."); } catch (Error e) { isHtmlOrXhtml = false; log4j.error("Error, doc: " + document + " schema: " + schemaUrls + " lax: " + laxType, e); errorHandler.internalError( e, "Oops. That was not supposed to happen. A bug manifested itself in the application internals. Unable to continue. Sorry. The admin was notified."); } finally { errorHandler.end(successMessage(), failureMessage(), (String) request.getAttribute( "http://validator.nu/properties/document-language")); gatherStatistics(); } if (isHtmlOrXhtml) { XhtmlOutlineEmitter outlineEmitter = new XhtmlOutlineEmitter( contentHandler, outline, headingOutline); outlineEmitter.emitHeadings(); outlineEmitter.emit(); emitDetails(); StatsEmitter.emit(contentHandler, this); } } private void gatherStatistics() { Statistics stats = Statistics.STATISTICS; if (stats == null) { return; } synchronized (stats) { stats.incrementTotal(); if (charsetOverride != null) { stats.incrementField(Statistics.Field.CUSTOM_ENC); } switch (parser) { case XML_EXTERNAL_ENTITIES_NO_VALIDATION: stats.incrementField(Statistics.Field.PARSER_XML_EXTERNAL); break; case AUTO: case HTML: case XML_NO_EXTERNAL_ENTITIES: default: break; } if (!filteredNamespaces.isEmpty()) { stats.incrementField(Statistics.Field.XMLNS_FILTER); } if (laxType) { stats.incrementField(Statistics.Field.LAX_TYPE); } if (aboutLegacyCompat) { stats.incrementField(Statistics.Field.ABOUT_LEGACY_COMPAT); } if (xhtml1Doctype) { stats.incrementField(Statistics.Field.XHTML1_DOCTYPE); } if (html4Doctype) { stats.incrementField(Statistics.Field.HTML4_DOCTYPE); } if (imageCollector != null) { stats.incrementField(Statistics.Field.IMAGE_REPORT); } if (showSource) { stats.incrementField(Statistics.Field.SHOW_SOURCE); } if (showOutline) { stats.incrementField(Statistics.Field.SHOW_OUTLINE); } if (methodIsGet) { stats.incrementField(Statistics.Field.INPUT_GET); } else { // POST stats.incrementField(Statistics.Field.INPUT_POST); Object inputType = request.getAttribute("nu.validator.servlet.MultipartFormDataFilter.type"); if ("textarea".equals(inputType)) { stats.incrementField(Statistics.Field.INPUT_TEXT_FIELD); } else if ("file".equals(inputType)) { stats.incrementField(Statistics.Field.INPUT_FILE_UPLOAD); } else { stats.incrementField(Statistics.Field.INPUT_ENTITY_BODY); } } if (documentInput != null && "text/css".equals(documentInput.getType())) { stats.incrementField(Statistics.Field.INPUT_CSS); } else if (documentInput != null && "image/svg+xml".equals(documentInput.getType())) { stats.incrementField(Statistics.Field.INPUT_SVG); } else if (htmlParser != null) { stats.incrementField(Statistics.Field.INPUT_HTML); } else if (xmlParser != null) { stats.incrementField(Statistics.Field.INPUT_XML); } else { stats.incrementField(Statistics.Field.INPUT_UNSUPPORTED); } switch (outputFormat) { case GNU: stats.incrementField(Statistics.Field.OUTPUT_GNU); break; case HTML: stats.incrementField(Statistics.Field.OUTPUT_HTML); break; case JSON: stats.incrementField(Statistics.Field.OUTPUT_JSON); break; case TEXT: stats.incrementField(Statistics.Field.OUTPUT_TEXT); break; case XHTML: stats.incrementField(Statistics.Field.OUTPUT_XHTML); break; case XML: stats.incrementField(Statistics.Field.OUTPUT_XML); break; case RELAXED: case SOAP: case UNICORN: default: break; } if (schemaListForStats == null) { stats.incrementField(Statistics.Field.LOGIC_ERROR); } else { boolean preset = false; for (int i = 0; i < presetUrls.length; i++) { if (presetUrls[i].equals(schemaListForStats)) { preset = true; if (externalSchema || externalSchematron) { stats.incrementField(Statistics.Field.LOGIC_ERROR); } else { stats.incrementField(Statistics.Field.PRESET_SCHEMA); /* * XXX WARNING WARNING: These mappings correspond to * values in the presets.txt file in the validator * source repo. They might be bogus if a custom * presets file is used instead. */ switch (i) { case 0: case 5: stats.incrementField(Statistics.Field.HTML5_SCHEMA); break; case 1: case 6: stats.incrementField(Statistics.Field.HTML5_RDFA_LITE_SCHEMA); break; case 2: stats.incrementField(Statistics.Field.HTML4_STRICT_SCHEMA); break; case 3: stats.incrementField(Statistics.Field.HTML4_TRANSITIONAL_SCHEMA); break; case 4: stats.incrementField(Statistics.Field.HTML4_FRAMESET_SCHEMA); break; case 7: stats.incrementField(Statistics.Field.XHTML1_COMPOUND_SCHEMA); break; case 8: stats.incrementField(Statistics.Field.SVG_SCHEMA); break; default: stats.incrementField(Statistics.Field.LOGIC_ERROR); break; } } break; } } if (!preset && !externalSchema) { stats.incrementField(Statistics.Field.BUILT_IN_NON_PRESET); } } if ("".equals(schemaUrls)) { stats.incrementField(Statistics.Field.AUTO_SCHEMA); if (externalSchema) { stats.incrementField(Statistics.Field.LOGIC_ERROR); } } else if (externalSchema) { if (externalSchematron) { stats.incrementField(Statistics.Field.EXTERNAL_SCHEMA_SCHEMATRON); } else { stats.incrementField(Statistics.Field.EXTERNAL_SCHEMA_NON_SCHEMATRON); } } else if (externalSchematron) { stats.incrementField(Statistics.Field.LOGIC_ERROR); } if (request.getAttribute( "http://validator.nu/properties/hgroup-found") != null && (boolean) request.getAttribute( "http://validator.nu/properties/hgroup-found")) { stats.incrementField(Statistics.Field.HGROUP_FOUND); } if (request.getAttribute( "http://validator.nu/properties/style-element-errors-found") != null && (boolean) request.getAttribute( "http://validator.nu/properties/style-element-errors-found")) { stats.incrementField(Statistics.Field.STYLE_ELEMENT_ERRORS_FOUND); } if (request.getAttribute( "http://validator.nu/properties/style-attribute-errors-found") != null && (boolean) request.getAttribute( "http://validator.nu/properties/style-attribute-errors-found")) { stats.incrementField(Statistics.Field.STYLE_ATTRIBUTE_ERRORS_FOUND); } if (request.getAttribute( "http://validator.nu/properties/lang-found") != null && (boolean) request.getAttribute( "http://validator.nu/properties/lang-found")) { stats.incrementField(Statistics.Field.LANG_FOUND); } if (request.getAttribute( "http://validator.nu/properties/lang-wrong") != null && (boolean) request.getAttribute( "http://validator.nu/properties/lang-wrong")) { stats.incrementField(Statistics.Field.LANG_WRONG); } if (request.getAttribute( "http://validator.nu/properties/lang-empty") != null && (boolean) request.getAttribute( "http://validator.nu/properties/lang-empty")) { stats.incrementField(Statistics.Field.LANG_EMPTY); } String fieldName; String language = (String) request.getAttribute( "http://validator.nu/properties/document-language"); if (!"".equals(language) && language != null) { fieldName = "DETECTEDLANG_" + language.toUpperCase(); if ("zh-hans".equals(language)) { fieldName = "DETECTEDLANG_ZH_HANS"; } else if ("zh-hant".equals(language)) { fieldName = "DETECTEDLANG_ZH_HANT"; } else if ("sr-latn".equals(language)) { fieldName = "DETECTEDLANG_SR_LATN"; } else if ("sr-cyrl".equals(language)) { fieldName = "DETECTEDLANG_SR_CYRL"; } else if ("uz-latn".equals(language)) { fieldName = "DETECTEDLANG_UZ_LATN"; } else if ("uz-cyrl".equals(language)) { fieldName = "DETECTEDLANG_UZ_CYRL"; } try { stats.incrementField(stats.getFieldFromName(fieldName)); } catch (IllegalArgumentException e) { log4j.error(e.getMessage(), e); } } String langVal = (String) request.getAttribute( "http://validator.nu/properties/lang-value"); if (langVal != null) { if ("".equals(langVal)) { stats.incrementField(Statistics.Field.LANG_EMPTY); } else { if (langVal.contains("_")) { fieldName = "LANG_" + langVal.replace("_", "__").toUpperCase(); } else { fieldName = "LANG_" + langVal.replace("-", "_").toUpperCase(); } try { stats.incrementField(stats.getFieldFromName(fieldName)); } catch (IllegalArgumentException e) { stats.incrementField(Statistics.Field.LANG_OTHER); } } } } } /** * @return * @throws SAXException */ protected String successMessage() throws SAXException { return "The document validates according to the specified schema(s)."; } protected String failureMessage() throws SAXException { return "There were errors."; } void emitDetails() throws SAXException { Object inputType = request.getAttribute("nu.validator.servlet.MultipartFormDataFilter.type"); String type = documentInput != null ? documentInput.getType() : ""; if ("text/html".equals(type) || "text/html-sandboxed".equals(type)) { attrs.clear(); emitter.startElementWithClass("div", "details"); if (schemaIsDefault) { emitter.startElementWithClass("p", "msgschema"); emitter.characters(String.format("Used the schema for %s.", getPresetLabel(HTML5_SCHEMA))); emitter.endElement("p"); } emitter.startElementWithClass("p", "msgmediatype"); if (!isHtmlUnsafePreset()) { emitter.characters("Used the HTML parser."); } if (methodIsGet && !"textarea".equals(inputType) && !"file".equals(inputType)) { String charset = documentInput.getEncoding(); if (charset != null) { emitter.characters(String.format( " Externally specified character encoding was %s.", charset)); } } emitter.endElement("div"); } } /** * @throws SAXException * @throws IOException * @throws IncorrectSchemaException */ protected void tryToSetupValidator() throws SAXException, IOException, IncorrectSchemaException { validator = validatorByUrls(schemaUrls); } protected void setErrorProfile() { profile = request.getParameter("profile"); HashMap<String, String> profileMap = new HashMap<>(); if ("pedagogical".equals(profile)) { profileMap.put("xhtml1", "warn"); } else if ("polyglot".equals(profile)) { profileMap.put("xhtml1", "warn"); profileMap.put("xhtml2", "warn"); } else { return; // presumed to be permissive } htmlParser.setErrorProfile(profileMap); } /** * @throws SAXException * @throws IOException * @throws IncorrectSchemaException * @throws SAXNotRecognizedException * @throws SAXNotSupportedException */ protected void loadDocAndSetupParser() throws SAXException, IOException, IncorrectSchemaException, SAXNotRecognizedException, SAXNotSupportedException { switch (parser) { case HTML: if (isHtmlUnsafePreset()) { String message = "The chosen preset schema is not appropriate for HTML."; SAXException se = new SAXException(message); errorHandler.schemaError(se); throw se; } setAllowGenericXml(false); setAllowHtml(true); setAcceptAllKnownXmlTypes(false); setAllowXhtml(false); loadDocumentInput(); newHtmlParser(); int schemaId; schemaId = HTML5_SCHEMA; htmlParser.setDocumentModeHandler(this); reader = htmlParser; if (validator == null) { validator = validatorByDoctype(schemaId); } if (validator != null) { reader.setContentHandler(validator.getContentHandler()); } break; case XML_NO_EXTERNAL_ENTITIES: case XML_EXTERNAL_ENTITIES_NO_VALIDATION: setAllowGenericXml(true); setAllowHtml(false); setAcceptAllKnownXmlTypes(true); setAllowXhtml(true); loadDocumentInput(); setupXmlParser(); break; default: setAllowGenericXml(true); setAllowHtml(true); setAcceptAllKnownXmlTypes(true); setAllowXhtml(true); loadDocumentInput(); String type = documentInput.getType(); if ("text/css".equals(type)) { break; } else if ("text/html".equals(type) || "text/html-sandboxed".equals(type)) { if (isHtmlUnsafePreset()) { String message = "The Content-Type was \u201C" + type + "\u201D, but the chosen preset schema is not appropriate for HTML."; SAXException se = new SAXException(message); errorHandler.schemaError(se); throw se; } newHtmlParser(); htmlParser.setDocumentModeHandler(this); reader = htmlParser; if (validator != null) { reader.setContentHandler(validator.getContentHandler()); } } else { if (contentType != null) { if ("application/xml".equals(contentType) || "text/xml".equals(contentType) || (Arrays.binarySearch(KNOWN_CONTENT_TYPES, contentType)) > -1) { errorHandler.info("The Content-Type was \u201C" + type + "\u201D. Using the XML parser (not resolving external entities)."); } } setupXmlParser(); } break; } } protected void newHtmlParser() { htmlParser = new HtmlParser(); htmlParser.setCommentPolicy(XmlViolationPolicy.ALLOW); htmlParser.setContentNonXmlCharPolicy(XmlViolationPolicy.ALLOW); htmlParser.setContentSpacePolicy(XmlViolationPolicy.ALTER_INFOSET); htmlParser.setNamePolicy(XmlViolationPolicy.ALLOW); htmlParser.setStreamabilityViolationPolicy(XmlViolationPolicy.FATAL); htmlParser.setXmlnsPolicy(XmlViolationPolicy.ALTER_INFOSET); htmlParser.setMappingLangToXmlLang(true); htmlParser.setHeuristics(Heuristics.ALL); } protected Validator validatorByDoctype(int schemaId) throws SAXException, IOException, IncorrectSchemaException { if (schemaId == 0) { return null; } for (int i = 0; i < presetDoctypes.length; i++) { if (presetDoctypes[i] == schemaId) { return validatorByUrls(presetUrls[i]); } } throw new RuntimeException("Doctype mappings not initialized properly."); } /** * @throws SAXNotRecognizedException * @throws SAXNotSupportedException */ protected void setupXmlParser() throws SAXNotRecognizedException, SAXNotSupportedException { xmlParser = new SAXDriver(); xmlParser.setCharacterHandler(sourceCode); if (lexicalHandler != null) { xmlParser.setProperty("http://xml.org/sax/properties/lexical-handler", lexicalHandler); } reader = new IdFilter(xmlParser); reader.setFeature("http://xml.org/sax/features/string-interning", true); reader.setFeature( "http://xml.org/sax/features/external-general-entities", parser == ParserMode.XML_EXTERNAL_ENTITIES_NO_VALIDATION); reader.setFeature( "http://xml.org/sax/features/external-parameter-entities", parser == ParserMode.XML_EXTERNAL_ENTITIES_NO_VALIDATION); if (parser == ParserMode.XML_EXTERNAL_ENTITIES_NO_VALIDATION) { reader.setEntityResolver(entityResolver); } else { reader.setEntityResolver(new NullEntityResolver()); } if (validator == null) { bufferingRootNamespaceSniffer = new BufferingRootNamespaceSniffer( this); reader.setContentHandler(bufferingRootNamespaceSniffer); } else { reader.setContentHandler(new RootNamespaceSniffer(this, validator.getContentHandler())); reader.setDTDHandler(validator.getDTDHandler()); } } /** * @param validator * @return * @throws SAXException * @throws IOException * @throws IncorrectSchemaException */ private Validator validatorByUrls(String schemaList) throws SAXException, IOException, IncorrectSchemaException { System.setProperty("nu.validator.schema.rdfa-full", "0"); schemaListForStats = schemaList; Validator v = null; String[] schemas = SPACE.split(schemaList); for (int i = schemas.length - 1; i > -1; i String url = schemas[i]; if ("http://s.validator.nu/html5-all.rnc".equals(url)) { System.setProperty("nu.validator.schema.rdfa-full", "1"); } if ("http://c.validator.nu/all/".equals(url) || "http://hsivonen.iki.fi/checkers/all/".equals(url)) { for (String checker : ALL_CHECKERS) { v = combineValidatorByUrl(v, checker); } } else if ("http://c.validator.nu/all-html4/".equals(url) || "http://hsivonen.iki.fi/checkers/all-html4/".equals(url)) { for (String checker : ALL_CHECKERS_HTML4) { v = combineValidatorByUrl(v, checker); } } else { v = combineValidatorByUrl(v, url); } } if (imageCollector != null && v != null) { v = new CombineValidator(imageCollector, v); } return v; } /** * @param val * @param url * @return * @throws SAXException * @throws IOException * @throws IncorrectSchemaException */ private Validator combineValidatorByUrl(Validator val, String url) throws SAXException, IOException, IncorrectSchemaException { if (!"".equals(url)) { Validator v = validatorByUrl(url); if (val == null) { val = v; } else { val = new CombineValidator(v, val); } } return val; } /** * @param url * @return * @throws SAXException * @throws IOException * @throws IncorrectSchemaException */ private Validator validatorByUrl(String url) throws SAXException, IOException, IncorrectSchemaException { if (loadedValidatorUrls.contains(url)) { return null; } loadedValidatorUrls.add(url); if ("http://s.validator.nu/xhtml5.rnc".equals(url) || "http://s.validator.nu/html5.rnc".equals(url) || "http://s.validator.nu/html5-all.rnc".equals(url) || "http://s.validator.nu/xhtml5-all.rnc".equals(url) || "http://s.validator.nu/html5-its.rnc".equals(url) || "http://s.validator.nu/xhtml5-rdfalite.rnc".equals(url) || "http://s.validator.nu/html5-rdfalite.rnc".equals(url)) { errorHandler.setSpec(html5spec); } Schema sch = resolveSchema(url, jingPropertyMap); Validator validator = sch.createValidator(jingPropertyMap); ContentHandler validatorContentHandler = validator.getContentHandler(); if (validatorContentHandler instanceof XmlPiChecker) { lexicalHandler = (LexicalHandler) validatorContentHandler; } if (validatorContentHandler instanceof Assertions) { Assertions assertions = (Assertions) validatorContentHandler; assertions.setRequest(request); assertions.setSourceIsCss(sourceCode.getIsCss()); } if (validatorContentHandler instanceof LanguageDetectingChecker) { LanguageDetectingChecker langdetect = (LanguageDetectingChecker) validatorContentHandler; langdetect.setRequest(request); langdetect.setHttpContentLanguageHeader( request.getHeader("Content-Language")); } return validator; } @Override public Schema resolveSchema(String url, PropertyMap options) throws SAXException, IOException, IncorrectSchemaException { int i = Arrays.binarySearch(preloadedSchemaUrls, url); if (i > -1) { Schema rv = preloadedSchemas[i]; if (options.contains(WrapProperty.ATTRIBUTE_OWNER)) { if (rv instanceof CheckerSchema) { errorHandler.error(new SAXParseException( "A non-schema checker cannot be used as an attribute schema.", null, url, -1, -1)); throw new IncorrectSchemaException(); } else { // ugly fall through } } else { return rv; } } externalSchema = true; TypedInputSource schemaInput = (TypedInputSource) entityResolver.resolveEntity( null, url); SchemaReader sr = null; if ("application/relax-ng-compact-syntax".equals(schemaInput.getType())) { sr = CompactSchemaReader.getInstance(); } else { sr = new AutoSchemaReader(); } Schema sch = sr.createSchema(schemaInput, options); if (Statistics.STATISTICS != null && "com.thaiopensource.validate.schematron.SchemaImpl".equals(sch.getClass().getName())) { externalSchematron = true; } return sch; } /** * @param url * @return * @throws SAXException * @throws IOException * @throws IncorrectSchemaException */ private static Schema schemaByUrl(String url, EntityResolver resolver, PropertyMap pMap) throws SAXException, IOException, IncorrectSchemaException { log4j.debug("Will load schema: " + url); TypedInputSource schemaInput; try { schemaInput = (TypedInputSource) resolver.resolveEntity( null, url); } catch (ClassCastException e) { log4j.fatal(url, e); throw e; } SchemaReader sr = null; if ("application/relax-ng-compact-syntax".equals(schemaInput.getType())) { sr = CompactSchemaReader.getInstance(); } else { sr = new AutoSchemaReader(); } Schema sch = sr.createSchema(schemaInput, pMap); return sch; } /** * @throws SAXException */ void emitTitle(boolean markupAllowed) throws SAXException { if (willValidate()) { emitter.characters(RESULTS_TITLE); emitter.characters(FOR); if (document != null && document.length() > 0) { emitter.characters(scrub(shortenDataUri(document))); } else if (request.getAttribute("nu.validator.servlet.MultipartFormDataFilter.filename") != null) { emitter.characters("uploaded file " + scrub(request.getAttribute( "nu.validator.servlet.MultipartFormDataFilter.filename").toString())); } else { emitter.characters("contents of text-input area"); } } else { emitter.characters(SERVICE_TITLE); if (markupAllowed && System.getProperty("nu.validator.servlet.service-name", "").equals("Validator.nu")) { emitter.startElement("span"); emitter.characters(LIVING_VERSION); emitter.endElement("span"); } } } protected String shortenDataUri(String uri) { if (DataUri.startsWithData(uri)) { return "data:\u2026"; } else { return uri; } } void emitForm() throws SAXException { attrs.clear(); attrs.addAttribute("method", "get"); // attrs.addAttribute("action", request.getRequestURL().toString()); if (isSimple()) { attrs.addAttribute("class", "simple"); } // attrs.addAttribute("onsubmit", "formSubmission()"); emitter.startElement("form", attrs); emitFormContent(); emitter.endElement("form"); } protected boolean isSimple() { return false; } /** * @throws SAXException */ protected void emitFormContent() throws SAXException { FormEmitter.emit(contentHandler, this); } void emitSchemaField() throws SAXException { attrs.clear(); attrs.addAttribute("name", "schema"); attrs.addAttribute("id", "schema"); // attrs.addAttribute("onchange", "schemaChanged();"); attrs.addAttribute( "pattern", "(?:(?:(?:https?://\\S+)|(?:data:\\S+))(?:\\s+(?:(?:https?://\\S+)|(?:data:\\S+)))*)?"); attrs.addAttribute("title", "Space-separated list of schema URLs. (Leave blank to let the service guess.)"); if (schemaUrls != null) { attrs.addAttribute("value", scrub(schemaUrls)); } emitter.startElement("input", attrs); emitter.endElement("input"); } void emitDocField() throws SAXException { attrs.clear(); attrs.addAttribute("type", "url"); attrs.addAttribute("name", "doc"); attrs.addAttribute("id", "doc"); attrs.addAttribute("pattern", "(?:(?:https?://.+)|(?:data:.+))?"); attrs.addAttribute("title", "Absolute URL (http, https or data only) of the document to be checked."); attrs.addAttribute("tabindex", "0"); attrs.addAttribute("autofocus", "autofocus"); if (document != null) { attrs.addAttribute("value", scrub(document)); } Object att = request.getAttribute("nu.validator.servlet.MultipartFormDataFilter.type"); if (att != null) { attrs.addAttribute("class", att.toString()); } emitter.startElement("input", attrs); emitter.endElement("input"); } /** * @throws SAXException * */ void emitSchemaDuration() throws SAXException { } /** * @throws SAXException * */ void emitDocDuration() throws SAXException { } /** * @throws SAXException * */ void emitTotalDuration() throws SAXException { emitter.characters("" + (System.currentTimeMillis() - start)); } /** * @throws SAXException * */ void emitPresetOptions() throws SAXException { for (int i = 0; i < presetUrls.length; i++) { emitter.option(presetLabels[i], presetUrls[i], false); } } /** * @throws SAXException * */ void emitParserOptions() throws SAXException { emitter.option("Automatically from Content-Type", "", (parser == ParserMode.AUTO)); emitter.option("HTML", "html", (parser == ParserMode.HTML)); emitter.option("XML; don\u2019t load external entities", "xml", (parser == ParserMode.XML_NO_EXTERNAL_ENTITIES)); emitter.option("XML; load external entities", "xmldtd", (parser == ParserMode.XML_EXTERNAL_ENTITIES_NO_VALIDATION)); } /** * @throws SAXException * */ void emitProfileOptions() throws SAXException { profile = request.getParameter("profile"); emitter.option("Permissive: only what the spec requires", "", ("".equals(profile))); emitter.option("Pedagogical: suitable for teaching purposes", "pedagogical", ("pedagogical".equals(profile))); emitter.option("Polyglot: works both as HTML and as XML", "polyglot", ("polyglot".equals(profile))); } /** * @throws SAXException * */ void emitLaxTypeField() throws SAXException { emitter.checkbox("laxtype", "yes", laxType); } /** * @throws SAXException * */ void emitShowSourceField() throws SAXException { emitter.checkbox("showsource", "yes", showSource); } /** * @throws SAXException * */ void emitShowOutlineField() throws SAXException { emitter.checkbox("showoutline", "yes", showOutline); } /** * @throws SAXException * */ void emitShowImageReportField() throws SAXException { emitter.checkbox("showimagereport", "yes", imageCollector != null); } void emitCheckErrorPagesField() throws SAXException { emitter.checkbox("checkerrorpages", "yes", checkErrorPages); } void rootNamespace(String namespace, Locator locator) throws SAXException { if (validator == null) { int index = -1; for (int i = 0; i < presetNamespaces.length; i++) { if (namespace.equals(presetNamespaces[i])) { index = i; break; } } if (index == -1) { String message = "Cannot find preset schema for namespace: \u201C" + namespace + "\u201D."; SAXException se = new SAXException(message); errorHandler.schemaError(se); throw new CannotFindPresetSchemaException(); } String label = presetLabels[index]; String urls = presetUrls[index]; errorHandler.info("Using the preset for " + label + " based on the root namespace."); try { validator = validatorByUrls(urls); } catch (IncorrectSchemaException | IOException e) { // At this point the schema comes from memory. throw new RuntimeException(e); } if (bufferingRootNamespaceSniffer == null) { throw new RuntimeException( "Bug! bufferingRootNamespaceSniffer was null."); } bufferingRootNamespaceSniffer.setContentHandler(validator.getContentHandler()); } if (!rootNamespaceSeen) { rootNamespaceSeen = true; if (contentType != null) { int i; if ((i = Arrays.binarySearch(KNOWN_CONTENT_TYPES, contentType)) > -1) { if (!NAMESPACES_FOR_KNOWN_CONTENT_TYPES[i].equals(namespace)) { String message = "".equals(namespace) ? "\u201C" + contentType + "\u201D is not an appropriate Content-Type for a document whose root element is not in a namespace." : "\u201C" + contentType + "\u201D is not an appropriate Content-Type for a document whose root namespace is \u201C" + namespace + "\u201D."; SAXParseException spe = new SAXParseException(message, locator); errorHandler.warning(spe); } } } } } @Override public void documentMode(DocumentMode mode, String publicIdentifier, String systemIdentifier) throws SAXException { if (systemIdentifier != null) { if ("about:legacy-compat".equals(systemIdentifier)) { aboutLegacyCompat = true; errorHandler.warning(new SAXParseException( "Documents should not use" + " \u201cabout:legacy-compat\u201d," + " except if generated by legacy systems" + " that can't output the standard" + " \u201c<!DOCTYPE html>\u201d doctype.", null)); } if (systemIdentifier.contains("http: xhtml1Doctype = true; } if (systemIdentifier.contains("http: html4Doctype = true; } } if (publicIdentifier != null) { if (publicIdentifier.contains("-//W3C//DTD HTML 4")) { html4Doctype = true; } } if (validator == null) { try { if ("yes".equals(request.getParameter("sniffdoctype"))) { if ("-//W3C//DTD XHTML 1.0 Transitional//EN".equals(publicIdentifier)) { errorHandler.info("XHTML 1.0 Transitional doctype seen. Appendix C is not supported. Proceeding anyway for your convenience. The parser is still an HTML parser, so namespace processing is not performed and \u201Cxml:*\u201D attributes are not supported. Using the schema for " + getPresetLabel(XHTML1TRANSITIONAL_SCHEMA) + "."); validator = validatorByDoctype(XHTML1TRANSITIONAL_SCHEMA); } else if ("-//W3C//DTD XHTML 1.0 Strict//EN".equals(publicIdentifier)) { errorHandler.info("XHTML 1.0 Strict doctype seen. Appendix C is not supported. Proceeding anyway for your convenience. The parser is still an HTML parser, so namespace processing is not performed and \u201Cxml:*\u201D attributes are not supported. Using the schema for " + getPresetLabel(XHTML1STRICT_SCHEMA) + "."); validator = validatorByDoctype(XHTML1STRICT_SCHEMA); } else if ("-//W3C//DTD HTML 4.01 Transitional//EN".equals(publicIdentifier)) { errorHandler.info("HTML 4.01 Transitional doctype seen. Using the schema for " + getPresetLabel(XHTML1TRANSITIONAL_SCHEMA) + "."); validator = validatorByDoctype(XHTML1TRANSITIONAL_SCHEMA); } else if ("-//W3C//DTD HTML 4.01//EN".equals(publicIdentifier)) { errorHandler.info("HTML 4.01 Strict doctype seen. Using the schema for " + getPresetLabel(XHTML1STRICT_SCHEMA) + "."); validator = validatorByDoctype(XHTML1STRICT_SCHEMA); } else if ("-//W3C//DTD HTML 4.0 Transitional//EN".equals(publicIdentifier)) { errorHandler.info("Legacy HTML 4.0 Transitional doctype seen. Please consider using HTML 4.01 Transitional instead. Proceeding anyway for your convenience with the schema for " + getPresetLabel(XHTML1TRANSITIONAL_SCHEMA) + "."); validator = validatorByDoctype(XHTML1TRANSITIONAL_SCHEMA); } else if ("-//W3C//DTD HTML 4.0//EN".equals(publicIdentifier)) { errorHandler.info("Legacy HTML 4.0 Strict doctype seen. Please consider using HTML 4.01 instead. Proceeding anyway for your convenience with the schema for " + getPresetLabel(XHTML1STRICT_SCHEMA) + "."); validator = validatorByDoctype(XHTML1STRICT_SCHEMA); } } if (validator == null) { schemaIsDefault = true; validator = validatorByDoctype(HTML5_SCHEMA); } } catch (IncorrectSchemaException | IOException e) { // At this point the schema comes from memory. throw new RuntimeException(e); } ContentHandler ch = validator.getContentHandler(); ch.setDocumentLocator(htmlParser.getDocumentLocator()); ch.startDocument(); reader.setContentHandler(ch); } } private String getPresetLabel(int schemaId) { for (int i = 0; i < presetDoctypes.length; i++) { if (presetDoctypes[i] == schemaId) { return presetLabels[i]; } } return "unknown"; } /** * @param acceptAllKnownXmlTypes * @see nu.validator.xml.ContentTypeParser#setAcceptAllKnownXmlTypes(boolean) */ protected void setAcceptAllKnownXmlTypes(boolean acceptAllKnownXmlTypes) { contentTypeParser.setAcceptAllKnownXmlTypes(acceptAllKnownXmlTypes); dataRes.setAcceptAllKnownXmlTypes(acceptAllKnownXmlTypes); httpRes.setAcceptAllKnownXmlTypes(acceptAllKnownXmlTypes); } /** * @param allowGenericXml * @see nu.validator.xml.ContentTypeParser#setAllowGenericXml(boolean) */ protected void setAllowGenericXml(boolean allowGenericXml) { contentTypeParser.setAllowGenericXml(allowGenericXml); httpRes.setAllowGenericXml(allowGenericXml); dataRes.setAllowGenericXml(allowGenericXml); } /** * @param allowHtml * @see nu.validator.xml.ContentTypeParser#setAllowHtml(boolean) */ protected void setAllowHtml(boolean allowHtml) { contentTypeParser.setAllowHtml(allowHtml); httpRes.setAllowHtml(allowHtml); dataRes.setAllowHtml(allowHtml); } /** * @param allowCss * @see nu.validator.xml.ContentTypeParser#setAllowCss(boolean) */ protected void setAllowCss(boolean allowCss) { contentTypeParser.setAllowCss(allowCss); httpRes.setAllowCss(allowCss); dataRes.setAllowCss(allowCss); } /** * @param allowRnc * @see nu.validator.xml.ContentTypeParser#setAllowRnc(boolean) */ protected void setAllowRnc(boolean allowRnc) { contentTypeParser.setAllowRnc(allowRnc); httpRes.setAllowRnc(allowRnc); dataRes.setAllowRnc(allowRnc); entityResolver.setAllowRnc(allowRnc); } /** * @param allowXhtml * @see nu.validator.xml.ContentTypeParser#setAllowXhtml(boolean) */ protected void setAllowXhtml(boolean allowXhtml) { contentTypeParser.setAllowXhtml(allowXhtml); httpRes.setAllowXhtml(allowXhtml); dataRes.setAllowXhtml(allowXhtml); } /** * @throws SAXException * @throws IOException */ protected void loadDocumentInput() throws SAXException, IOException { if (documentInput != null) { return; } if (methodIsGet) { documentInput = (TypedInputSource) entityResolver.resolveEntity( null, document); errorHandler.setLoggingOk(true); } else { // POST long len = request.getContentLength(); if (len > SIZE_LIMIT) { throw new StreamBoundException("Resource size exceeds limit."); } documentInput = contentTypeParser.buildTypedInputSource(document, null, postContentType); documentInput.setByteStream(len < 0 ? new BoundedInputStream( request.getInputStream(), SIZE_LIMIT, document) : request.getInputStream()); documentInput.setSystemId(request.getHeader("Content-Location")); } if (imageCollector != null) { baseUriTracker = new BaseUriTracker(documentInput.getSystemId(), documentInput.getLanguage()); imageCollector.initializeContext(baseUriTracker); } } void emitStyle() throws SAXException { attrs.clear(); attrs.addAttribute("href", STYLE_SHEET); attrs.addAttribute("rel", "stylesheet"); emitter.startElement("link", attrs); emitter.endElement("link"); } void emitIcon() throws SAXException { attrs.clear(); attrs.addAttribute("href", ICON); attrs.addAttribute("rel", "icon"); emitter.startElement("link", attrs); emitter.endElement("link"); } void emitScript() throws SAXException { attrs.clear(); attrs.addAttribute("src", SCRIPT); emitter.startElement("script", attrs); emitter.endElement("script"); } void emitAbout() throws SAXException { attrs.clear(); attrs.addAttribute("href", ABOUT_PAGE); emitter.startElement("a", attrs); emitter.characters(ABOUT_THIS_SERVICE); emitter.endElement("a"); } void emitVersion() throws SAXException { emitter.characters(VERSION); } void emitUserAgentInput() throws SAXException { attrs.clear(); attrs.addAttribute("name", "useragent"); attrs.addAttribute("list", "useragents"); attrs.addAttribute("value", userAgent); emitter.startElement("input", attrs); emitter.endElement("input"); } void emitAcceptLanguageInput() throws SAXException { attrs.clear(); attrs.addAttribute("id", "acceptlanguage"); attrs.addAttribute("name", "acceptlanguage"); emitter.startElement("input", attrs); emitter.endElement("input"); } void emitOtherFacetLink() throws SAXException { attrs.clear(); attrs.addAttribute("href", HTML5_FACET); emitter.startElement("a", attrs); emitter.characters(SIMPLE_UI); emitter.endElement("a"); } void emitNsfilterField() throws SAXException { attrs.clear(); attrs.addAttribute("name", "nsfilter"); attrs.addAttribute("id", "nsfilter"); attrs.addAttribute("pattern", "(?:.+:.+(?:\\s+.+:.+)*)?"); attrs.addAttribute("title", "Space-separated namespace URIs for vocabularies to be filtered out."); if (!filteredNamespaces.isEmpty()) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String ns : filteredNamespaces) { if (!first) { sb.append(' '); } sb.append(ns); first = false; } attrs.addAttribute("value", scrub(sb)); } emitter.startElement("input", attrs); emitter.endElement("input"); } void maybeEmitNsfilterField() throws SAXException { NsFilterEmitter.emit(contentHandler, this); } void emitCharsetOptions() throws SAXException { boolean found = false; for (int i = 0; i < CHARSETS.length; i++) { String charset = CHARSETS[i]; boolean selected = charset.equalsIgnoreCase(charsetOverride); // XXX // use // ASCII-caseinsensitivity emitter.option(CHARSET_DESCRIPTIONS[i], charset, selected); if (selected) { found = true; } } if (!found && charsetOverride != null) { emitter.option(charsetOverride, charsetOverride, true); } } void maybeEmitCharsetField() throws SAXException { CharsetEmitter.emit(contentHandler, this); } class CannotFindPresetSchemaException extends SAXException { CannotFindPresetSchemaException() { super(); } } }
package nu.validator.servlet; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import nu.validator.gnu.xml.aelfred2.SAXDriver; import nu.validator.htmlparser.common.DoctypeExpectation; import nu.validator.htmlparser.common.DocumentMode; import nu.validator.htmlparser.common.DocumentModeHandler; import nu.validator.htmlparser.common.XmlViolationPolicy; import nu.validator.htmlparser.sax.HtmlParser; import nu.validator.htmlparser.sax.HtmlSerializer; import nu.validator.io.BoundedInputStream; import nu.validator.io.StreamBoundException; import nu.validator.messages.GnuMessageEmitter; import nu.validator.messages.JsonMessageEmitter; import nu.validator.messages.MessageEmitterAdapter; import nu.validator.messages.TextMessageEmitter; import nu.validator.messages.TooManyErrorsException; import nu.validator.messages.XhtmlMessageEmitter; import nu.validator.messages.XmlMessageEmitter; import nu.validator.servlet.imagereview.ImageCollector; import nu.validator.source.SourceCode; import nu.validator.spec.Spec; import nu.validator.spec.html5.Html5SpecBuilder; import nu.validator.xml.AttributesImpl; import nu.validator.xml.AttributesPermutingXMLReaderWrapper; import nu.validator.xml.BaseUriTracker; import nu.validator.xml.CharacterUtil; import nu.validator.xml.CombineContentHandler; import nu.validator.xml.ContentTypeParser; import nu.validator.xml.DataUriEntityResolver; import nu.validator.xml.ForbiddenCharacterFilter; import nu.validator.xml.IdFilter; import nu.validator.xml.LocalCacheEntityResolver; import nu.validator.xml.NamespaceDroppingXMLReaderWrapper; import nu.validator.xml.NullEntityResolver; import nu.validator.xml.PrudentHttpEntityResolver; import nu.validator.xml.SystemErrErrorHandler; import nu.validator.xml.TypedInputSource; import nu.validator.xml.WiretapXMLReaderWrapper; import nu.validator.xml.XhtmlSaxEmitter; import nu.validator.xml.dataattributes.DataAttributeDroppingSchemaWrapper; import org.apache.log4j.Logger; import org.apache.xml.serializer.Method; import org.apache.xml.serializer.OutputPropertiesFactory; import org.apache.xml.serializer.Serializer; import org.apache.xml.serializer.SerializerFactory; import org.whattf.checker.jing.CheckerSchema; import org.whattf.io.DataUri; import org.xml.sax.ContentHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.ext.LexicalHandler; import com.ibm.icu.text.Normalizer; import com.oxygenxml.validate.nvdl.NvdlProperty; import com.thaiopensource.relaxng.impl.CombineValidator; import com.thaiopensource.util.PropertyMap; import com.thaiopensource.util.PropertyMapBuilder; import com.thaiopensource.validate.IncorrectSchemaException; import com.thaiopensource.validate.Schema; import com.thaiopensource.validate.SchemaReader; import com.thaiopensource.validate.SchemaResolver; import com.thaiopensource.validate.ValidateProperty; import com.thaiopensource.validate.Validator; import com.thaiopensource.validate.auto.AutoSchemaReader; import com.thaiopensource.validate.nrl.NrlProperty; import com.thaiopensource.validate.rng.CompactSchemaReader; import com.thaiopensource.validate.rng.RngProperty; /** * @version $Id: VerifierServletTransaction.java,v 1.10 2005/07/24 07:32:48 * hsivonen Exp $ * @author hsivonen */ class VerifierServletTransaction implements DocumentModeHandler, SchemaResolver { private enum OutputFormat { HTML, XHTML, TEXT, XML, JSON, RELAXED, SOAP, UNICORN, GNU } private static final Logger log4j = Logger.getLogger(VerifierServletTransaction.class); private static final Pattern SPACE = Pattern.compile("\\s+"); private static final Pattern JS_IDENTIFIER = Pattern.compile("[\\p{Lu}\\p{Ll}\\p{Lt}\\p{Lm}\\p{Lo}\\p{Nl}_\\$][\\p{Lu}\\p{Ll}\\p{Lt}\\p{Lm}\\p{Lo}\\p{Nl}_\\$\\p{Mn}\\p{Mc}\\p{Nd}\\p{Pc}]*"); private static final String[] JS_RESERVED_WORDS = { "abstract", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "export", "extends", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "typeof", "var", "void", "volatile", "while", "with" }; private static final String[] CHARSETS = { "UTF-8", "UTF-16", "Windows-1250", "Windows-1251", "Windows-1252", "Windows-1253", "Windows-1254", "Windows-1255", "Windows-1256", "Windows-1257", "Windows-1258", "ISO-8859-1", "ISO-8859-2", "ISO-8859-3", "ISO-8859-4", "ISO-8859-5", "ISO-8859-6", "ISO-8859-7", "ISO-8859-8", "ISO-8859-9", "ISO-8859-13", "ISO-8859-15", "KOI8-R", "TIS-620", "GBK", "GB18030", "Big5", "Big5-HKSCS", "Shift_JIS", "ISO-2022-JP", "EUC-JP", "ISO-2022-KR", "EUC-KR" }; private static final char[][] CHARSET_DESCRIPTIONS = { "UTF-8 (Global)".toCharArray(), "UTF-16 (Global)".toCharArray(), "Windows-1250 (Central European)".toCharArray(), "Windows-1251 (Cyrillic)".toCharArray(), "Windows-1252 (Western)".toCharArray(), "Windows-1253 (Greek)".toCharArray(), "Windows-1254 (Turkish)".toCharArray(), "Windows-1255 (Hebrew)".toCharArray(), "Windows-1256 (Arabic)".toCharArray(), "Windows-1257 (Baltic)".toCharArray(), "Windows-1258 (Vietnamese)".toCharArray(), "ISO-8859-1 (Western)".toCharArray(), "ISO-8859-2 (Central European)".toCharArray(), "ISO-8859-3 (South European)".toCharArray(), "ISO-8859-4 (Baltic)".toCharArray(), "ISO-8859-5 (Cyrillic)".toCharArray(), "ISO-8859-6 (Arabic)".toCharArray(), "ISO-8859-7 (Greek)".toCharArray(), "ISO-8859-8 (Hebrew)".toCharArray(), "ISO-8859-9 (Turkish)".toCharArray(), "ISO-8859-13 (Baltic)".toCharArray(), "ISO-8859-15 (Western)".toCharArray(), "KOI8-R (Russian)".toCharArray(), "TIS-620 (Thai)".toCharArray(), "GBK (Chinese, simplified)".toCharArray(), "GB18030 (Chinese, simplified)".toCharArray(), "Big5 (Chinese, traditional)".toCharArray(), "Big5-HKSCS (Chinese, traditional)".toCharArray(), "Shift_JIS (Japanese)".toCharArray(), "ISO-2022-JP (Japanese)".toCharArray(), "EUC-JP (Japanese)".toCharArray(), "ISO-2022-KR (Korean)".toCharArray(), "EUC-KR (Korean)".toCharArray() }; protected static final int HTML5_SCHEMA = 3; protected static final int XHTML1STRICT_SCHEMA = 2; protected static final int XHTML1TRANSITIONAL_SCHEMA = 1; protected static final int XHTML5_SCHEMA = 7; private static final char[] SERVICE_TITLE = (System.getProperty( "nu.validator.servlet.service-name", "Validator.nu") + " ").toCharArray(); private static final char[] VERSION = "3".toCharArray(); private static final char[] RESULTS_TITLE = "Validation results".toCharArray(); private static final char[] FOR = " for ".toCharArray(); private static final char[] ABOUT_THIS_SERVICE = "About this service".toCharArray(); private static final Map pathMap = new HashMap(); private static Spec html5spec; private static int[] presetDoctypes; private static String[] presetLabels; private static String[] presetUrls; private static String[] presetNamespaces; // XXX SVG!!! private static final String[] KNOWN_CONTENT_TYPES = { "application/atom+xml", "application/docbook+xml", "application/xhtml+xml", "application/xv+xml" }; private static final String[] NAMESPACES_FOR_KNOWN_CONTENT_TYPES = { "http: "http: private static final String[] ALL_CHECKERS = { "http: "http://c.validator.nu/text-content/", "http: private static final String[] ALL_CHECKERS_HTML4 = { "http: "http: private long start = System.currentTimeMillis(); protected final HttpServletRequest request; private final HttpServletResponse response; protected String document = null; private ParserMode parser = ParserMode.AUTO; private boolean laxType = false; protected ContentHandler contentHandler; protected XhtmlSaxEmitter emitter; protected MessageEmitterAdapter errorHandler; private AttributesImpl attrs = new AttributesImpl(); private OutputStream out; private PropertyMap jingPropertyMap; protected LocalCacheEntityResolver entityResolver; private static long lastModified; private static String[] preloadedSchemaUrls; private static Schema[] preloadedSchemas; private final static String ABOUT_PAGE = System.getProperty( "nu.validator.servlet.about-page", "http://about.validator.nu/"); private final static String STYLE_SHEET = System.getProperty( "nu.validator.servlet.style-sheet", "http://about.validator.nu/style.css"); private final static String SCRIPT = System.getProperty( "nu.validator.servlet.script", "http://about.validator.nu/script.js"); private static final long SIZE_LIMIT = Integer.parseInt(System.getProperty( "nu.validator.servlet.max-file-size", "2097152")); private String schemaUrls = null; protected Validator validator = null; private BufferingRootNamespaceSniffer bufferingRootNamespaceSniffer = null; private String contentType = null; protected HtmlParser htmlParser = null; protected SAXDriver xmlParser = null; protected XMLReader reader; protected TypedInputSource documentInput; protected PrudentHttpEntityResolver httpRes; protected DataUriEntityResolver dataRes; protected ContentTypeParser contentTypeParser; private Set<String> loadedValidatorUrls = new HashSet<String>(); private boolean checkNormalization = false; private boolean rootNamespaceSeen = false; private OutputFormat outputFormat; private String postContentType; private boolean methodIsGet; private SourceCode sourceCode = new SourceCode(); private boolean showSource; private BaseUriTracker baseUriTracker = null; private String charsetOverride = null; private Set<String> filteredNamespaces = new LinkedHashSet<String>(); // linked // for // stability protected ImageCollector imageCollector; static { try { log4j.debug("Starting static initializer."); String presetPath = System.getProperty("nu.validator.servlet.presetconfpath"); File presetFile = new File(presetPath); lastModified = presetFile.lastModified(); BufferedReader r = new BufferedReader(new InputStreamReader( new FileInputStream(presetFile), "UTF-8")); String line; List<String> doctypes = new LinkedList<String>(); List<String> namespaces = new LinkedList<String>(); List<String> labels = new LinkedList<String>(); List<String> urls = new LinkedList<String>(); log4j.debug("Starting to loop over config file lines."); while ((line = r.readLine()) != null) { if ("".equals(line.trim())) { break; } String s[] = line.split("\t"); doctypes.add(s[0]); namespaces.add(s[1]); labels.add(s[2]); urls.add(s[3]); } log4j.debug("Finished reading config."); String[] presetDoctypesAsStrings = doctypes.toArray(new String[0]); presetNamespaces = namespaces.toArray(new String[0]); presetLabels = labels.toArray(new String[0]); presetUrls = urls.toArray(new String[0]); log4j.debug("Converted config to arrays."); for (int i = 0; i < presetNamespaces.length; i++) { String str = presetNamespaces[i]; if ("-".equals(str)) { presetNamespaces[i] = null; } else { presetNamespaces[i] = presetNamespaces[i].intern(); } } log4j.debug("Prepared namespace array."); presetDoctypes = new int[presetDoctypesAsStrings.length]; for (int i = 0; i < presetDoctypesAsStrings.length; i++) { presetDoctypes[i] = Integer.parseInt(presetDoctypesAsStrings[i]); } log4j.debug("Parsed doctype numbers into ints."); String prefix = System.getProperty("nu.validator.servlet.cachepathprefix"); log4j.debug("The cache path prefix is: " + prefix); String cacheConfPath = System.getProperty("nu.validator.servlet.cacheconfpath"); log4j.debug("The cache config path is: " + cacheConfPath); r = new BufferedReader(new InputStreamReader(new FileInputStream( cacheConfPath), "UTF-8")); while ((line = r.readLine()) != null) { if ("".equals(line.trim())) { break; } String s[] = line.split("\t"); pathMap.put(s[0], prefix + s[1]); } log4j.debug("Cache config read."); ErrorHandler eh = new SystemErrErrorHandler(); LocalCacheEntityResolver er = new LocalCacheEntityResolver(pathMap, new NullEntityResolver()); er.setAllowRnc(true); PropertyMapBuilder pmb = new PropertyMapBuilder(); pmb.put(ValidateProperty.ERROR_HANDLER, eh); pmb.put(ValidateProperty.ENTITY_RESOLVER, er); pmb.put(ValidateProperty.XML_READER_CREATOR, new VerifierServletXMLReaderCreator(eh, er)); RngProperty.CHECK_ID_IDREF.add(pmb); PropertyMap pMap = pmb.toPropertyMap(); log4j.debug("Parsing set up. Starting to read schemas."); SortedMap<String, Schema> schemaMap = new TreeMap<String, Schema>(); for (int i = 0; i < presetUrls.length; i++) { String[] urls1 = SPACE.split(presetUrls[i]); for (int j = 0; j < urls1.length; j++) { String url = urls1[j]; if (schemaMap.get(url) == null && !isCheckerUrl(url)) { Schema sch = schemaByUrl(url, er, pMap); schemaMap.put(url, sch); } } } log4j.debug("Schemas read."); schemaMap.put("http://c.validator.nu/table/", CheckerSchema.TABLE_CHECKER); schemaMap.put("http://hsivonen.iki.fi/checkers/table/", CheckerSchema.TABLE_CHECKER); schemaMap.put("http://c.validator.nu/nfc/", CheckerSchema.NORMALIZATION_CHECKER); schemaMap.put("http://hsivonen.iki.fi/checkers/nfc/", CheckerSchema.NORMALIZATION_CHECKER); schemaMap.put("http://c.validator.nu/debug/", CheckerSchema.DEBUG_CHECKER); schemaMap.put("http://hsivonen.iki.fi/checkers/debug/", CheckerSchema.DEBUG_CHECKER); schemaMap.put("http://c.validator.nu/text-content/", CheckerSchema.TEXT_CONTENT_CHECKER); schemaMap.put("http://hsivonen.iki.fi/checkers/text-content/", CheckerSchema.TEXT_CONTENT_CHECKER); schemaMap.put("http://c.validator.nu/usemap/", CheckerSchema.USEMAP_CHECKER); schemaMap.put("http://n.validator.nu/checkers/usemap/", CheckerSchema.USEMAP_CHECKER); schemaMap.put("http://c.validator.nu/unchecked/", CheckerSchema.UNCHECKED_SUBTREE_WARNER); preloadedSchemaUrls = new String[schemaMap.size()]; preloadedSchemas = new Schema[schemaMap.size()]; int i = 0; for (Map.Entry<String, Schema> entry : schemaMap.entrySet()) { preloadedSchemaUrls[i] = entry.getKey().intern(); if (isDataAttributeDroppingSchema(entry.getKey())) { preloadedSchemas[i] = new DataAttributeDroppingSchemaWrapper(entry.getValue()); } else { preloadedSchemas[i] = entry.getValue(); } i++; } log4j.debug("Reading spec."); html5spec = Html5SpecBuilder.parseSpec(); log4j.debug("Spec read."); log4j.debug("Initialization complete."); } catch (Exception e) { throw new RuntimeException(e); } } protected static String scrub(CharSequence s) { return Normalizer.normalize( CharacterUtil.prudentlyScrubCharacterData(s), Normalizer.NFC); } private static boolean isDataAttributeDroppingSchema(String key) { return ("http: } private static boolean isCheckerUrl(String url) { if ("http://c.validator.nu/all/".equals(url) || "http://hsivonen.iki.fi/checkers/all/".equals(url)) { return true; } else if ("http://c.validator.nu/all-html4/".equals(url) || "http://hsivonen.iki.fi/checkers/all-html4/".equals(url)) { return true; } for (int i = 0; i < ALL_CHECKERS.length; i++) { if (ALL_CHECKERS[i].equals(url)) { return true; } } return false; } /** * @param request * @param response */ VerifierServletTransaction(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; } protected boolean willValidate() { if (methodIsGet) { return document != null; } else { // POST return true; } } void service() throws ServletException, IOException { this.methodIsGet = "GET".equals(request.getMethod()) || "HEAD".equals(request.getMethod()); this.out = response.getOutputStream(); request.setCharacterEncoding("utf-8"); if (!methodIsGet) { postContentType = request.getContentType(); if (postContentType == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Content-Type missing"); return; } else if (postContentType.trim().toLowerCase().startsWith( "application/x-www-form-urlencoded")) { response.sendError( HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "application/x-www-form-urlencoded not supported. Please use multipart/form-data."); return; } } String outFormat = request.getParameter("out"); if (outFormat == null) { outputFormat = OutputFormat.HTML; } else { if ("html".equals(outFormat)) { outputFormat = OutputFormat.HTML; } else if ("xhtml".equals(outFormat)) { outputFormat = OutputFormat.XHTML; } else if ("text".equals(outFormat)) { outputFormat = OutputFormat.TEXT; } else if ("gnu".equals(outFormat)) { outputFormat = OutputFormat.GNU; } else if ("xml".equals(outFormat)) { outputFormat = OutputFormat.XML; } else if ("json".equals(outFormat)) { outputFormat = OutputFormat.JSON; } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported output format"); return; } } if (!methodIsGet) { document = request.getHeader("Content-Location"); } if (document == null) { document = request.getParameter("doc"); } document = ("".equals(document)) ? null : document; String callback = null; if (outputFormat == OutputFormat.JSON) { callback = request.getParameter("callback"); if (callback != null) { Matcher m = JS_IDENTIFIER.matcher(callback); if (m.matches()) { if (Arrays.binarySearch(JS_RESERVED_WORDS, callback) >= 0) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Callback is a reserved word."); return; } } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Callback is not a valid ECMA 262 IdentifierName."); return; } } } if (willValidate()) { response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); } else if (outputFormat == OutputFormat.HTML || outputFormat == OutputFormat.XHTML) { response.setDateHeader("Last-Modified", lastModified); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No input document"); return; } setup(); showSource = (request.getParameter("showsource") != null); if (request.getParameter("showimagereport") != null) { imageCollector = new ImageCollector(sourceCode); } String charset = request.getParameter("charset"); if (charset != null) { charset = scrub(charset.trim()); if (!"".equals(charset)) { charsetOverride = charset; } } String nsfilter = request.getParameter("nsfilter"); if (nsfilter != null) { String[] nsfilterArr = SPACE.split(nsfilter); for (int i = 0; i < nsfilterArr.length; i++) { String ns = nsfilterArr[i]; if (ns.length() > 0) { filteredNamespaces.add(ns); } } } boolean errorsOnly = ("error".equals(request.getParameter("level"))); boolean asciiQuotes = (request.getParameter("asciiquotes") != null); int lineOffset = 0; String lineOffsetStr = request.getParameter("lineoffset"); if (lineOffsetStr != null) { try { lineOffset = Integer.parseInt(lineOffsetStr); } catch (NumberFormatException e) { } } try { if (outputFormat == OutputFormat.HTML || outputFormat == OutputFormat.XHTML) { if (outputFormat == OutputFormat.HTML) { response.setContentType("text/html; charset=utf-8"); contentHandler = new HtmlSerializer(out); } else { response.setContentType("application/xhtml+xml"); Properties props = OutputPropertiesFactory.getDefaultMethodProperties(Method.XML); Serializer ser = SerializerFactory.getSerializer(props); ser.setOutputStream(out); contentHandler = new ForbiddenCharacterFilter( ser.asContentHandler()); } emitter = new XhtmlSaxEmitter(contentHandler); errorHandler = new MessageEmitterAdapter(sourceCode, showSource, imageCollector, lineOffset, new XhtmlMessageEmitter(contentHandler)); PageEmitter.emit(contentHandler, this); } else { if (outputFormat == OutputFormat.TEXT) { response.setContentType("text/plain; charset=utf-8"); errorHandler = new MessageEmitterAdapter(sourceCode, showSource, null, lineOffset, new TextMessageEmitter(out, asciiQuotes)); } else if (outputFormat == OutputFormat.GNU) { response.setContentType("text/plain; charset=utf-8"); errorHandler = new MessageEmitterAdapter(sourceCode, showSource, null, lineOffset, new GnuMessageEmitter(out, asciiQuotes)); } else if (outputFormat == OutputFormat.XML) { response.setContentType("application/xml"); Properties props = OutputPropertiesFactory.getDefaultMethodProperties(Method.XML); Serializer ser = SerializerFactory.getSerializer(props); ser.setOutputStream(out); errorHandler = new MessageEmitterAdapter(sourceCode, showSource, null, lineOffset, new XmlMessageEmitter( new ForbiddenCharacterFilter( ser.asContentHandler()))); } else if (outputFormat == OutputFormat.JSON) { if (callback == null) { response.setContentType("application/json"); } else { response.setContentType("application/javascript"); } errorHandler = new MessageEmitterAdapter(sourceCode, showSource, null, lineOffset, new JsonMessageEmitter( new nu.validator.json.Serializer(out), callback)); } else { throw new RuntimeException("Unreachable."); } errorHandler.setErrorsOnly(errorsOnly); validate(); } } catch (SAXException e) { throw new ServletException(e); } } /** * @throws ServletException */ protected void setup() throws ServletException { String preset = request.getParameter("preset"); if (preset != null && !"".equals(preset)) { schemaUrls = preset; } else { schemaUrls = request.getParameter("schema"); } if (schemaUrls == null) { schemaUrls = ""; } String parserStr = request.getParameter("parser"); if ("html".equals(parserStr)) { parser = ParserMode.HTML_AUTO; } else if ("xmldtd".equals(parserStr)) { parser = ParserMode.XML_EXTERNAL_ENTITIES_NO_VALIDATION; } else if ("xml".equals(parserStr)) { parser = ParserMode.XML_NO_EXTERNAL_ENTITIES; } else if ("html5".equals(parserStr)) { parser = ParserMode.HTML; } else if ("html4".equals(parserStr)) { parser = ParserMode.HTML401_STRICT; } else if ("html4tr".equals(parserStr)) { parser = ParserMode.HTML401_TRANSITIONAL; } // else auto laxType = (request.getParameter("laxtype") != null); } private boolean isHtmlUnsafePreset() { if ("".equals(schemaUrls)) { return false; } boolean preset = false; for (int i = 0; i < presetUrls.length; i++) { if (presetUrls[i].equals(schemaUrls)) { preset = true; break; } } if (!preset) { return false; } return !(schemaUrls.startsWith("http://s.validator.nu/xhtml10/xhtml-basic.rnc") || schemaUrls.startsWith("http://s.validator.nu/xhtml10/xhtml-strict.rnc") || schemaUrls.startsWith("http://s.validator.nu/xhtml10/xhtml-transitional.rnc") || schemaUrls.startsWith("http://s.validator.nu/xhtml10/xhtml-frameset.rnc") || schemaUrls.startsWith("http: } /** * @throws SAXException */ @SuppressWarnings("deprecation") void validate() throws SAXException { if (!willValidate()) { return; } boolean isHtmlOrXhtml = (outputFormat == OutputFormat.HTML || outputFormat == OutputFormat.XHTML); if (isHtmlOrXhtml) { try { out.flush(); } catch (IOException e1) { throw new SAXException(e1); } } httpRes = new PrudentHttpEntityResolver(SIZE_LIMIT, laxType, errorHandler); dataRes = new DataUriEntityResolver(httpRes, laxType, errorHandler); contentTypeParser = new ContentTypeParser(errorHandler, laxType); entityResolver = new LocalCacheEntityResolver(pathMap, dataRes); setAllowRnc(true); try { this.errorHandler.start(document); PropertyMapBuilder pmb = new PropertyMapBuilder(); pmb.put(ValidateProperty.ERROR_HANDLER, errorHandler); pmb.put(ValidateProperty.ENTITY_RESOLVER, entityResolver); pmb.put(ValidateProperty.XML_READER_CREATOR, new VerifierServletXMLReaderCreator(errorHandler, entityResolver)); pmb.put(ValidateProperty.SCHEMA_RESOLVER, this); RngProperty.CHECK_ID_IDREF.add(pmb); jingPropertyMap = pmb.toPropertyMap(); tryToSetupValidator(); setAllowRnc(false); loadDocAndSetupParser(); reader.setErrorHandler(errorHandler); contentType = documentInput.getType(); sourceCode.initialize(documentInput); if (validator == null) { checkNormalization = true; } if (checkNormalization) { reader.setFeature( "http://xml.org/sax/features/unicode-normalization-checking", true); } WiretapXMLReaderWrapper wiretap = new WiretapXMLReaderWrapper( reader); ContentHandler recorder = sourceCode.getLocationRecorder(); if (baseUriTracker == null) { wiretap.setWiretapContentHander(recorder); } else { wiretap.setWiretapContentHander(new CombineContentHandler(recorder, baseUriTracker)); } wiretap.setWiretapLexicalHandler((LexicalHandler) recorder); reader = wiretap; if (htmlParser != null) { htmlParser.addCharacterHandler(sourceCode); htmlParser.setMappingLangToXmlLang(true); htmlParser.setErrorHandler(errorHandler.getExactErrorHandler()); htmlParser.setTreeBuilderErrorHandlerOverride(errorHandler); errorHandler.setHtml(true); } else if (xmlParser != null) { // this must be after wiretap! if (!filteredNamespaces.isEmpty()) { reader = new NamespaceDroppingXMLReaderWrapper(reader, filteredNamespaces); } xmlParser.setErrorHandler(errorHandler.getExactErrorHandler()); xmlParser.lockErrorHandler(); } else { throw new RuntimeException("Bug. Unreachable."); } reader = new AttributesPermutingXMLReaderWrapper(reader); // make RNG validation better if (charsetOverride != null) { String charset = documentInput.getEncoding(); if (charset == null) { errorHandler.warning(new SAXParseException( "Overriding document character encoding from none to \u201C" + charsetOverride + "\u201D.", null)); } else { errorHandler.warning(new SAXParseException( "Overriding document character encoding from \u201C" + charset + "\u201D to \u201C" + charsetOverride + "\u201D.", null)); } documentInput.setEncoding(charsetOverride); } reader.parse(documentInput); } catch (TooManyErrorsException e) { log4j.debug("TooManyErrorsException", e); errorHandler.fatalError(e); } catch (SAXException e) { log4j.debug("SAXException", e); } catch (IOException e) { isHtmlOrXhtml = false; log4j.info("IOException", e); errorHandler.ioError(e); } catch (IncorrectSchemaException e) { log4j.debug("IncorrectSchemaException", e); errorHandler.schemaError(e); } catch (RuntimeException e) { isHtmlOrXhtml = false; log4j.error("RuntimeException, doc: " + document + " schema: " + schemaUrls + " lax: " + laxType, e); errorHandler.internalError( e, "Oops. That was not supposed to happen. A bug manifested itself in the application internals. Unable to continue. Sorry. The admin was notified."); } catch (Error e) { isHtmlOrXhtml = false; log4j.error("Error, doc: " + document + " schema: " + schemaUrls + " lax: " + laxType, e); errorHandler.internalError( e, "Oops. That was not supposed to happen. A bug manifested itself in the application internals. Unable to continue. Sorry. The admin was notified."); } finally { errorHandler.end(successMessage(), failureMessage()); } if (isHtmlOrXhtml) { StatsEmitter.emit(contentHandler, this); } } /** * @return * @throws SAXException */ protected String successMessage() throws SAXException { return "The document validates according to the specified schema(s)."; } protected String failureMessage() throws SAXException { return "There were errors."; } /** * @throws SAXException * @throws IOException * @throws IncorrectSchemaException */ protected void tryToSetupValidator() throws SAXException, IOException, IncorrectSchemaException { validator = validatorByUrls(schemaUrls); } /** * @throws SAXException * @throws IOException * @throws IncorrectSchemaException * @throws SAXNotRecognizedException * @throws SAXNotSupportedException */ protected void loadDocAndSetupParser() throws SAXException, IOException, IncorrectSchemaException, SAXNotRecognizedException, SAXNotSupportedException { switch (parser) { case HTML_AUTO: case HTML: case HTML401_STRICT: case HTML401_TRANSITIONAL: if (isHtmlUnsafePreset()) { String message = "The chosen preset schema is not appropriate for HTML."; SAXException se = new SAXException(message); errorHandler.schemaError(se); throw se; } setAllowGenericXml(false); setAllowHtml(true); setAcceptAllKnownXmlTypes(false); setAllowXhtml(false); loadDocumentInput(); newHtmlParser(); DoctypeExpectation doctypeExpectation; int schemaId; switch (parser) { case HTML: doctypeExpectation = DoctypeExpectation.HTML; schemaId = HTML5_SCHEMA; break; case HTML401_STRICT: doctypeExpectation = DoctypeExpectation.HTML401_STRICT; schemaId = XHTML1STRICT_SCHEMA; break; case HTML401_TRANSITIONAL: doctypeExpectation = DoctypeExpectation.HTML401_TRANSITIONAL; schemaId = XHTML1TRANSITIONAL_SCHEMA; break; default: doctypeExpectation = DoctypeExpectation.AUTO; schemaId = 0; break; } htmlParser.setDoctypeExpectation(doctypeExpectation); htmlParser.setDocumentModeHandler(this); reader = htmlParser; if (validator == null) { validator = validatorByDoctype(schemaId); } if (validator != null) { reader.setContentHandler(validator.getContentHandler()); } break; case XML_NO_EXTERNAL_ENTITIES: case XML_EXTERNAL_ENTITIES_NO_VALIDATION: setAllowGenericXml(true); setAllowHtml(false); setAcceptAllKnownXmlTypes(true); setAllowXhtml(true); loadDocumentInput(); setupXmlParser(); break; default: setAllowGenericXml(true); setAllowHtml(true); setAcceptAllKnownXmlTypes(true); setAllowXhtml(true); loadDocumentInput(); if ("text/html".equals(documentInput.getType())) { if (isHtmlUnsafePreset()) { String message = "The Content-Type was \u201Ctext/html\u201D, but the chosen preset schema is not appropriate for HTML."; SAXException se = new SAXException(message); errorHandler.schemaError(se); throw se; } errorHandler.info("The Content-Type was \u201Ctext/html\u201D. Using the HTML parser."); newHtmlParser(); htmlParser.setDoctypeExpectation(DoctypeExpectation.AUTO); htmlParser.setDocumentModeHandler(this); reader = htmlParser; if (validator != null) { reader.setContentHandler(validator.getContentHandler()); } } else { errorHandler.info("The Content-Type was \u201C" + documentInput.getType() + "\u201D. Using the XML parser (not resolving external entities)."); setupXmlParser(); } break; } } protected void newHtmlParser() { htmlParser = new HtmlParser(); htmlParser.setStreamabilityViolationPolicy(XmlViolationPolicy.FATAL); htmlParser.setXmlnsPolicy(XmlViolationPolicy.ALTER_INFOSET); htmlParser.setMappingLangToXmlLang(true); htmlParser.setHtml4ModeCompatibleWithXhtml1Schemata(true); } protected Validator validatorByDoctype(int schemaId) throws SAXException, IOException, IncorrectSchemaException { if (schemaId == 0) { return null; } for (int i = 0; i < presetDoctypes.length; i++) { if (presetDoctypes[i] == schemaId) { return validatorByUrls(presetUrls[i]); } } throw new RuntimeException("Doctype mappings not initialized properly."); } /** * @param entityResolver2 * @return * @throws SAXNotRecognizedException * @throws SAXNotSupportedException */ protected void setupXmlParser() throws SAXNotRecognizedException, SAXNotSupportedException { xmlParser = new SAXDriver(); xmlParser.setCharacterHandler(sourceCode); reader = new IdFilter(xmlParser); reader.setFeature("http://xml.org/sax/features/string-interning", true); reader.setFeature( "http://xml.org/sax/features/external-general-entities", parser == ParserMode.XML_EXTERNAL_ENTITIES_NO_VALIDATION); reader.setFeature( "http://xml.org/sax/features/external-parameter-entities", parser == ParserMode.XML_EXTERNAL_ENTITIES_NO_VALIDATION); if (parser == ParserMode.XML_EXTERNAL_ENTITIES_NO_VALIDATION) { reader.setEntityResolver(entityResolver); } else { reader.setEntityResolver(new NullEntityResolver()); } if (validator == null) { bufferingRootNamespaceSniffer = new BufferingRootNamespaceSniffer( this); reader.setContentHandler(bufferingRootNamespaceSniffer); } else { reader.setContentHandler(new RootNamespaceSniffer(this, validator.getContentHandler())); reader.setDTDHandler(validator.getDTDHandler()); } } /** * @param validator * @return * @throws SAXException * @throws IOException * @throws IncorrectSchemaException */ private Validator validatorByUrls(String schemaList) throws SAXException, IOException, IncorrectSchemaException { Validator v = null; String[] schemas = SPACE.split(schemaList); for (int i = schemas.length - 1; i > -1; i String url = schemas[i]; if ("http://c.validator.nu/all/".equals(url) || "http://hsivonen.iki.fi/checkers/all/".equals(url)) { for (int j = 0; j < ALL_CHECKERS.length; j++) { v = combineValidatorByUrl(v, ALL_CHECKERS[j]); } } else if ("http://c.validator.nu/all-html4/".equals(url) || "http://hsivonen.iki.fi/checkers/all-html4/".equals(url)) { for (int j = 0; j < ALL_CHECKERS_HTML4.length; j++) { v = combineValidatorByUrl(v, ALL_CHECKERS_HTML4[j]); } } else { v = combineValidatorByUrl(v, url); } } if (imageCollector != null && v != null) { v = new CombineValidator(imageCollector, v); } return v; } /** * @param val * @param url * @return * @throws SAXException * @throws IOException * @throws IncorrectSchemaException */ private Validator combineValidatorByUrl(Validator val, String url) throws SAXException, IOException, IncorrectSchemaException { if (!"".equals(url)) { Validator v = validatorByUrl(url); if (val == null) { val = v; } else { val = new CombineValidator(v, val); } } return val; } /** * @param url * @return * @throws SAXException * @throws IOException * @throws IncorrectSchemaException */ private Validator validatorByUrl(String url) throws SAXException, IOException, IncorrectSchemaException { if (loadedValidatorUrls.contains(url)) { return null; } loadedValidatorUrls.add(url); if ("http://s.validator.nu/html5/html5full-aria.rnc".equals(url) || "http://s.validator.nu/xhtml5-aria-rdf-svg-mathml.rnc".equals(url) || "http://s.validator.nu/html5/html5full.rnc".equals(url) || "http://s.validator.nu/html5/xhtml5full-xhtml.rnc".equals(url)) { errorHandler.setSpec(html5spec); } Schema sch = resolveSchema(url, jingPropertyMap); Validator validator = sch.createValidator(jingPropertyMap); return validator; } public Schema resolveSchema(String url, PropertyMap options) throws SAXException, IOException, IncorrectSchemaException { int i = Arrays.binarySearch(preloadedSchemaUrls, url); if (i > -1) { Schema rv = preloadedSchemas[i]; if (options.contains(NvdlProperty.ATTRIBUTES_SCHEMA) || options.contains(NrlProperty.ATTRIBUTES_SCHEMA)) { if (rv instanceof CheckerSchema) { errorHandler.error(new SAXParseException("A non-schema checker cannot be used as an attribute schema.", null, url, -1, -1)); throw new IncorrectSchemaException(); } else { // ugly fall through } } else { return rv; } } TypedInputSource schemaInput = (TypedInputSource) entityResolver.resolveEntity( null, url); SchemaReader sr = null; if ("application/relax-ng-compact-syntax".equals(schemaInput.getType())) { sr = CompactSchemaReader.getInstance(); } else { sr = new AutoSchemaReader(); } Schema sch = sr.createSchema(schemaInput, options); return sch; } /** * @param url * @return * @throws SAXException * @throws IOException * @throws IncorrectSchemaException */ private static Schema schemaByUrl(String url, EntityResolver resolver, PropertyMap pMap) throws SAXException, IOException, IncorrectSchemaException { log4j.debug("Will load schema: " + url); TypedInputSource schemaInput = (TypedInputSource) resolver.resolveEntity( null, url); SchemaReader sr = null; if ("application/relax-ng-compact-syntax".equals(schemaInput.getType())) { sr = CompactSchemaReader.getInstance(); } else { sr = new AutoSchemaReader(); } Schema sch = sr.createSchema(schemaInput, pMap); return sch; } /** * @throws SAXException */ void emitTitle(boolean markupAllowed) throws SAXException { if (willValidate()) { emitter.characters(RESULTS_TITLE); if (document != null && document.length() > 0) { emitter.characters(FOR); emitter.characters(scrub(shortenDataUri(document))); } } else { emitter.characters(SERVICE_TITLE); if (markupAllowed) { emitter.startElement("span"); emitter.characters(VERSION); emitter.endElement("span"); } } } protected String shortenDataUri(String uri) { if (DataUri.startsWithData(uri)) { return "data:\u2026"; } else { return uri; } } void emitForm() throws SAXException { attrs.clear(); attrs.addAttribute("method", "get"); attrs.addAttribute("action", request.getRequestURL().toString()); if (isSimple()) { attrs.addAttribute("class", "simple"); } // attrs.addAttribute("onsubmit", "formSubmission()"); emitter.startElement("form", attrs); emitFormContent(); emitter.endElement("form"); } protected boolean isSimple() { return false; } /** * @throws SAXException */ protected void emitFormContent() throws SAXException { FormEmitter.emit(contentHandler, this); } void emitSchemaField() throws SAXException { attrs.clear(); attrs.addAttribute("name", "schema"); attrs.addAttribute("id", "schema"); // attrs.addAttribute("onchange", "schemaChanged();"); attrs.addAttribute("pattern", "(?:(?:(?:https?://\\S+)|(?:data:\\S+))(?:\\s+(?:(?:https?://\\S+)|(?:data:\\S+)))*)?"); attrs.addAttribute("title", "Space-separated list of schema IRIs. (Leave blank to let the service guess.)"); if (schemaUrls != null) { attrs.addAttribute("value", scrub(schemaUrls)); } emitter.startElement("input", attrs); emitter.endElement("input"); } void emitDocField() throws SAXException { attrs.clear(); attrs.addAttribute("type", "url"); attrs.addAttribute("name", "doc"); attrs.addAttribute("id", "doc"); attrs.addAttribute("pattern", "(?:(?:https?://.+)|(?:data:.+))?"); attrs.addAttribute("title", "Absolute IRI (http, https or data only) of the document to be checked."); if (document != null) { attrs.addAttribute("value", scrub(document)); } emitter.startElement("input", attrs); emitter.endElement("input"); } /** * @throws SAXException * */ void emitSchemaDuration() throws SAXException { } /** * @throws SAXException * */ void emitDocDuration() throws SAXException { } /** * @throws SAXException * */ void emitTotalDuration() throws SAXException { emitter.characters("" + (System.currentTimeMillis() - start)); } /** * @throws SAXException * */ void emitPresetOptions() throws SAXException { for (int i = 0; i < presetUrls.length; i++) { emitter.option(presetLabels[i], presetUrls[i], false); } } /** * @throws SAXException * */ void emitParserOptions() throws SAXException { emitter.option("Automatically from Content-Type", "", (parser == ParserMode.AUTO)); emitter.option("XML; don\u2019t load external entities", "xml", (parser == ParserMode.XML_NO_EXTERNAL_ENTITIES)); emitter.option("XML; load external entities", "xmldtd", (parser == ParserMode.XML_EXTERNAL_ENTITIES_NO_VALIDATION)); emitter.option("HTML; flavor from doctype", "html", (parser == ParserMode.HTML_AUTO)); emitter.option("HTML5", "html5", (parser == ParserMode.HTML)); emitter.option("HTML 4.01 Strict", "html4", (parser == ParserMode.HTML401_STRICT)); emitter.option("HTML 4.01 Transitional", "html4tr", (parser == ParserMode.HTML401_TRANSITIONAL)); } /** * @throws SAXException * */ void emitLaxTypeField() throws SAXException { emitter.checkbox("laxtype", "yes", laxType); } /** * @throws SAXException * */ void emitShowSourceField() throws SAXException { emitter.checkbox("showsource", "yes", showSource); } /** * @throws SAXException * */ void emitShowImageReportField() throws SAXException { emitter.checkbox("showimagereport", "yes", imageCollector != null); } void rootNamespace(String namespace, Locator locator) throws SAXException { if (validator == null) { int index = -1; for (int i = 0; i < presetNamespaces.length; i++) { if (namespace.equals(presetNamespaces[i])) { index = i; break; } } if (index == -1) { String message = "Cannot find preset schema for namespace: \u201C" + namespace + "\u201D."; SAXException se = new SAXException(message); errorHandler.schemaError(se); throw se; } String label = presetLabels[index]; String urls = presetUrls[index]; errorHandler.info("Using the preset for " + label + " based on the root namespace."); try { validator = validatorByUrls(urls); } catch (IOException ioe) { // At this point the schema comes from memory. throw new RuntimeException(ioe); } catch (IncorrectSchemaException e) { // At this point the schema comes from memory. throw new RuntimeException(e); } if (bufferingRootNamespaceSniffer == null) { throw new RuntimeException( "Bug! bufferingRootNamespaceSniffer was null."); } bufferingRootNamespaceSniffer.setContentHandler(validator.getContentHandler()); } if (!rootNamespaceSeen) { rootNamespaceSeen = true; if (contentType != null) { int i; if ((i = Arrays.binarySearch(KNOWN_CONTENT_TYPES, contentType)) > -1) { if (!NAMESPACES_FOR_KNOWN_CONTENT_TYPES[i].equals(namespace)) { String message = "\u201C" + contentType + "\u201D is not an appropriate Content-Type for a document whose root namespace is \u201C" + namespace + "\u201D."; SAXParseException spe = new SAXParseException(message, locator); errorHandler.warning(spe); } } } } } public void documentMode(DocumentMode mode, String publicIdentifier, String systemIdentifier, boolean html4SpecificAdditionalErrorChecks) throws SAXException { if (validator == null) { try { if ("-//W3C//DTD XHTML 1.0 Transitional//EN".equals(publicIdentifier)) { errorHandler.info("XHTML 1.0 Transitional doctype seen. Appendix C is not supported. Proceeding anyway for your convenience. The parser is still an HTML parser, so namespace processing is not performed and \u201Cxml:*\u201D attributes are not supported. Using the schema for XHTML 1.0 Transitional." + (html4SpecificAdditionalErrorChecks ? " HTML4-specific tokenization errors are enabled." : "")); validator = validatorByDoctype(XHTML1TRANSITIONAL_SCHEMA); } else if ("-//W3C//DTD XHTML 1.0 Strict//EN".equals(publicIdentifier)) { errorHandler.info("XHTML 1.0 Strict doctype seen. Appendix C is not supported. Proceeding anyway for your convenience. The parser is still an HTML parser, so namespace processing is not performed and \u201Cxml:*\u201D attributes are not supported. Using the schema for XHTML 1.0 Strict." + (html4SpecificAdditionalErrorChecks ? " HTML4-specific tokenization errors are enabled." : "")); validator = validatorByDoctype(XHTML1STRICT_SCHEMA); } else if ("-//W3C//DTD HTML 4.01 Transitional//EN".equals(publicIdentifier)) { errorHandler.info("HTML 4.01 Transitional doctype seen. Using the schema for XHTML 1.0 Transitional." + (html4SpecificAdditionalErrorChecks ? "" : " HTML4-specific tokenization errors are not enabled.")); validator = validatorByDoctype(XHTML1TRANSITIONAL_SCHEMA); } else if ("-//W3C//DTD HTML 4.01//EN".equals(publicIdentifier)) { errorHandler.info("HTML 4.01 Strict doctype seen. Using the schema for XHTML 1.0 Strict." + (html4SpecificAdditionalErrorChecks ? "" : " HTML4-specific tokenization errors are not enabled.")); validator = validatorByDoctype(XHTML1STRICT_SCHEMA); } else if ("-//W3C//DTD HTML 4.0 Transitional//EN".equals(publicIdentifier)) { errorHandler.info("Legacy HTML 4.0 Transitional doctype seen. Please consider using HTML 4.01 Transitional instead. Proceeding anyway for your convenience with the schema for XHTML 1.0 Transitional." + (html4SpecificAdditionalErrorChecks ? "" : " HTML4-specific tokenization errors are not enabled.")); validator = validatorByDoctype(XHTML1TRANSITIONAL_SCHEMA); } else if ("-//W3C//DTD HTML 4.0//EN".equals(publicIdentifier)) { errorHandler.info("Legacy HTML 4.0 Strict doctype seen. Please consider using HTML 4.01 instead. Proceeding anyway for your convenience with the schema for XHTML 1.0 Strict." + (html4SpecificAdditionalErrorChecks ? "" : " HTML4-specific tokenization errors are not enabled.")); validator = validatorByDoctype(XHTML1STRICT_SCHEMA); } else { errorHandler.info("Using the schema for HTML5." + (html4SpecificAdditionalErrorChecks ? " HTML4-specific tokenization errors are enabled." : "")); validator = validatorByDoctype(HTML5_SCHEMA); } } catch (IOException ioe) { // At this point the schema comes from memory. throw new RuntimeException(ioe); } catch (IncorrectSchemaException e) { // At this point the schema comes from memory. throw new RuntimeException(e); } ContentHandler ch = validator.getContentHandler(); ch.setDocumentLocator(htmlParser.getDocumentLocator()); ch.startDocument(); reader.setContentHandler(ch); } else { if (html4SpecificAdditionalErrorChecks) { errorHandler.info("HTML4-specific tokenization errors are enabled."); } } } /** * @param acceptAllKnownXmlTypes * @see nu.validator.xml.ContentTypeParser#setAcceptAllKnownXmlTypes(boolean) */ protected void setAcceptAllKnownXmlTypes(boolean acceptAllKnownXmlTypes) { contentTypeParser.setAcceptAllKnownXmlTypes(acceptAllKnownXmlTypes); dataRes.setAcceptAllKnownXmlTypes(acceptAllKnownXmlTypes); httpRes.setAcceptAllKnownXmlTypes(acceptAllKnownXmlTypes); } /** * @param allowGenericXml * @see nu.validator.xml.ContentTypeParser#setAllowGenericXml(boolean) */ protected void setAllowGenericXml(boolean allowGenericXml) { contentTypeParser.setAllowGenericXml(allowGenericXml); httpRes.setAllowGenericXml(allowGenericXml); dataRes.setAllowGenericXml(allowGenericXml); } /** * @param allowHtml * @see nu.validator.xml.ContentTypeParser#setAllowHtml(boolean) */ protected void setAllowHtml(boolean allowHtml) { contentTypeParser.setAllowHtml(allowHtml); httpRes.setAllowHtml(allowHtml); dataRes.setAllowHtml(allowHtml); } /** * @param allowRnc * @see nu.validator.xml.ContentTypeParser#setAllowRnc(boolean) */ protected void setAllowRnc(boolean allowRnc) { contentTypeParser.setAllowRnc(allowRnc); httpRes.setAllowRnc(allowRnc); dataRes.setAllowRnc(allowRnc); entityResolver.setAllowRnc(allowRnc); } /** * @param allowXhtml * @see nu.validator.xml.ContentTypeParser#setAllowXhtml(boolean) */ protected void setAllowXhtml(boolean allowXhtml) { contentTypeParser.setAllowXhtml(allowXhtml); httpRes.setAllowXhtml(allowXhtml); dataRes.setAllowXhtml(allowXhtml); } /** * @throws SAXException * @throws IOException */ protected void loadDocumentInput() throws SAXException, IOException { if (methodIsGet) { documentInput = (TypedInputSource) entityResolver.resolveEntity( null, document); errorHandler.setLoggingOk(true); } else { // POST long len = request.getContentLength(); if (len > SIZE_LIMIT) { throw new StreamBoundException("Resource size exceeds limit."); } documentInput = contentTypeParser.buildTypedInputSource(document, null, postContentType); documentInput.setByteStream(len < 0 ? new BoundedInputStream( request.getInputStream(), SIZE_LIMIT, document) : request.getInputStream()); documentInput.setSystemId(request.getHeader("Content-Location")); } if (imageCollector != null) { baseUriTracker = new BaseUriTracker(documentInput.getSystemId(), documentInput.getLanguage()); imageCollector.initializeContext(baseUriTracker); } } void emitStyle() throws SAXException { attrs.clear(); attrs.addAttribute("href", STYLE_SHEET); attrs.addAttribute("rel", "stylesheet"); emitter.startElement("link", attrs); emitter.endElement("link"); } void emitScript() throws SAXException { attrs.clear(); attrs.addAttribute("src", SCRIPT); emitter.startElement("script", attrs); emitter.endElement("script"); } void emitAbout() throws SAXException { attrs.clear(); attrs.addAttribute("href", ABOUT_PAGE); emitter.startElement("a", attrs); emitter.characters(ABOUT_THIS_SERVICE); emitter.endElement("a"); } void emitNsfilterField() throws SAXException { attrs.clear(); attrs.addAttribute("name", "nsfilter"); attrs.addAttribute("id", "nsfilter"); attrs.addAttribute("pattern", "(?:.+:.+(?:\\s+.+:.+)*)?"); attrs.addAttribute("title", "Space-separated namespace URIs for vocabularies to be filtered out."); if (!filteredNamespaces.isEmpty()) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String ns : filteredNamespaces) { if (!first) { sb.append(' '); } sb.append(ns); first = false; } attrs.addAttribute("value", scrub(sb)); } emitter.startElement("input", attrs); emitter.endElement("input"); } void maybeEmitNsfilterField() throws SAXException { NsFilterEmitter.emit(contentHandler, this); } void emitCharsetOptions() throws SAXException { boolean found = false; for (int i = 0; i < CHARSETS.length; i++) { String charset = CHARSETS[i]; boolean selected = charset.equalsIgnoreCase(charsetOverride); // XXX // use // ASCII-caseinsensitivity emitter.option(CHARSET_DESCRIPTIONS[i], charset, selected); if (selected) { found = true; } } if (!found && charsetOverride != null) { emitter.option(charsetOverride, charsetOverride, true); } } void maybeEmitCharsetField() throws SAXException { CharsetEmitter.emit(contentHandler, this); } }
package opendap.wcs.v2_0; import java.io.IOException; import javax.xml.bind.JAXBException; import javax.xml.stream.XMLStreamException; import org.jdom.JDOMException; import org.junit.*; import static org.junit.Assert.*; import opendap.dap4.DatasetTest; /** * Extends the Dataset Test to test DynamicCoverageDescription * @author Uday Kari * */ public class DynamicCoverageDescriptionTest extends DatasetTest { public DynamicCoverageDescriptionTest(String dmr) throws IOException, JDOMException, JAXBException, XMLStreamException { super (dmr); } @Test public void trySomething() { assertTrue(true); } }
package org.antlr.codebuff.validation; import org.antlr.codebuff.Corpus; import org.antlr.codebuff.FeatureMetaData; import org.antlr.codebuff.Formatter; import org.antlr.codebuff.InputDocument; import org.antlr.codebuff.Tool; import org.antlr.codebuff.Trainer; import org.antlr.codebuff.misc.BuffUtils; import org.antlr.codebuff.misc.LangDescriptor; import org.antlr.v4.runtime.misc.MultiMap; import java.util.ArrayList; import java.util.List; import static org.antlr.codebuff.misc.BuffUtils.mean; import static org.antlr.codebuff.misc.BuffUtils.median; import static org.antlr.codebuff.misc.BuffUtils.sumDoubles; import static org.antlr.codebuff.validation.Entropy.getCategoryRatios; import static org.antlr.codebuff.validation.Entropy.getNormalizedCategoryEntropy; public class CorpusConsistency { public static void main(String[] args) throws Exception { boolean report = false; if ( args.length>0 && args[0].equals("-report") ) { report = true; } for (LangDescriptor language : Tool.languages) { computeConsistency(language, report); } } public static void computeConsistency(LangDescriptor language, boolean report) throws Exception { if ( report ) { System.out.println(" System.out.println(language.name); System.out.println(" } Corpus corpus = new Corpus(language.corpusDir, language); corpus.train(); // a map of feature vector to list of exemplar indexes of that feature MultiMap<FeatureVectorAsObject,Integer> wsContextToIndex = new MultiMap<>(); MultiMap<FeatureVectorAsObject,Integer> hposContextToIndex = new MultiMap<>(); int n = corpus.featureVectors.size(); for (int i = 0; i<n; i++) { int[] features = corpus.featureVectors.get(i); wsContextToIndex.map(new FeatureVectorAsObject(features, Trainer.FEATURES_INJECT_WS), i); hposContextToIndex.map(new FeatureVectorAsObject(features, Trainer.FEATURES_HPOS), i); } int num_ambiguous_ws_vectors = 0; int num_ambiguous_hpos_vectors = 0; // Dump output grouped by ws vs hpos then feature vector then category if ( report ) System.out.println(" List<Double> ws_entropies = new ArrayList<>(); for (FeatureVectorAsObject fo : wsContextToIndex.keySet()) { List<Integer> exemplarIndexes = wsContextToIndex.get(fo); // we have group by feature vector, now group by cat with that set for ws MultiMap<Integer,Integer> wsCatToIndexes = new MultiMap<>(); for (Integer i : exemplarIndexes) { wsCatToIndexes.map(corpus.injectWhitespace.get(i), i); } if ( wsCatToIndexes.size()==1 ) continue; if ( report ) System.out.println("Feature vector has "+exemplarIndexes.size()+" exemplars"); List<Integer> catCounts = BuffUtils.map(wsCatToIndexes.values(), List::size); double wsEntropy = getNormalizedCategoryEntropy(getCategoryRatios(catCounts)); if ( report ) System.out.printf("entropy=%5.4f\n", wsEntropy); wsEntropy *= exemplarIndexes.size(); ws_entropies.add(wsEntropy); num_ambiguous_ws_vectors += exemplarIndexes.size(); if ( report ) System.out.print(Trainer.featureNameHeader(Trainer.FEATURES_INJECT_WS)); if ( report ) { for (Integer cat : wsCatToIndexes.keySet()) { List<Integer> indexes = wsCatToIndexes.get(cat); for (Integer i : indexes) { String display = getExemplarDisplay(Trainer.FEATURES_INJECT_WS, corpus, corpus.injectWhitespace, i); System.out.println(display); } System.out.println(); } } } if ( report ) System.out.println(" List<Double> hpos_entropies = new ArrayList<>(); for (FeatureVectorAsObject fo : hposContextToIndex.keySet()) { List<Integer> exemplarIndexes = hposContextToIndex.get(fo); // we have group by feature vector, now group by cat with that set for hpos MultiMap<Integer,Integer> hposCatToIndexes = new MultiMap<>(); for (Integer i : exemplarIndexes) { hposCatToIndexes.map(corpus.hpos.get(i), i); } if ( hposCatToIndexes.size()==1 ) continue; if ( report ) System.out.println("Feature vector has "+exemplarIndexes.size()+" exemplars"); List<Integer> catCounts = BuffUtils.map(hposCatToIndexes.values(), List::size); double hposEntropy = getNormalizedCategoryEntropy(getCategoryRatios(catCounts)); if ( report ) System.out.printf("entropy=%5.4f\n", hposEntropy); hposEntropy *= exemplarIndexes.size(); hpos_entropies.add(hposEntropy); num_ambiguous_hpos_vectors += exemplarIndexes.size(); if ( report ) System.out.print(Trainer.featureNameHeader(Trainer.FEATURES_HPOS)); if ( report ) { for (Integer cat : hposCatToIndexes.keySet()) { List<Integer> indexes = hposCatToIndexes.get(cat); for (Integer i : indexes) { String display = getExemplarDisplay(Trainer.FEATURES_HPOS, corpus, corpus.hpos, i); System.out.println(display); } System.out.println(); } } } System.out.println(); System.out.println(language.name); System.out.println("There are "+wsContextToIndex.size()+" unique ws feature vectors out of "+n+" = "+ String.format("%3.1f%%",100.0*wsContextToIndex.size()/n)); System.out.println("There are "+hposContextToIndex.size()+" unique hpos feature vectors out of "+n+" = "+ String.format("%3.1f%%",100.0*hposContextToIndex.size()/n)); float prob_ws_ambiguous = num_ambiguous_ws_vectors/(float) n; System.out.printf("num_ambiguous_ws_vectors = %5d/%5d = %5.3f\n", num_ambiguous_ws_vectors, n, prob_ws_ambiguous); float prob_hpos_ambiguous = num_ambiguous_hpos_vectors/(float) n; System.out.printf("num_ambiguous_hpos_vectors = %5d/%5d = %5.3f\n", num_ambiguous_hpos_vectors, n, prob_hpos_ambiguous); // Collections.sort(ws_entropies); // System.out.println("ws_entropies="+ws_entropies); System.out.println("ws median,mean = "+median(ws_entropies)+","+mean(ws_entropies)); double expected_ws_entropy = (sumDoubles(ws_entropies)/num_ambiguous_ws_vectors) * prob_ws_ambiguous; System.out.println("expected_ws_entropy="+expected_ws_entropy); System.out.println("hpos median,mean = "+median(hpos_entropies)+","+mean(hpos_entropies)); double expected_hpos_entropy = (sumDoubles(hpos_entropies)/num_ambiguous_hpos_vectors) * prob_hpos_ambiguous; System.out.println("expected_hpos_entropy="+expected_hpos_entropy); } public static String getExemplarDisplay(FeatureMetaData[] FEATURES, Corpus corpus, List<Integer> Y, int corpusVectorIndex) { int[] X = corpus.featureVectors.get(corpusVectorIndex); InputDocument doc = corpus.documentsPerExemplar.get(corpusVectorIndex); String features = Trainer._toString(FEATURES, doc, X); int line = X[Trainer.INDEX_INFO_LINE]; String lineText = doc.getLine(line); int col = X[Trainer.INDEX_INFO_CHARPOS]; // insert a dot right before char position if ( lineText!=null ) { lineText = lineText.substring(0, col)+'\u00B7'+lineText.substring(col, lineText.length()); } int cat = Y.get(corpusVectorIndex); String displayCat; if ( (cat&0xFF) == Trainer.CAT_INJECT_WS || (cat&0xFF) == Trainer.CAT_INJECT_NL) { displayCat = Formatter.getWSCategoryStr(cat); } else { displayCat = Formatter.getHPosCategoryStr(cat); } return String.format("%s %9s %s", features, displayCat, lineText); } }
package org.digidoc4j.impl.bdoc.xades; import static org.bouncycastle.cert.ocsp.RespID.HASH_SHA1; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.ocsp.ResponderID; import org.bouncycastle.asn1.x500.AttributeTypeAndValue; import org.bouncycastle.asn1.x500.RDN; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils; import org.bouncycastle.cert.ocsp.BasicOCSPResp; import org.bouncycastle.cert.ocsp.OCSPException; import org.bouncycastle.cert.ocsp.RespID; import org.bouncycastle.jcajce.provider.digest.SHA1; import org.bouncycastle.operator.DigestCalculator; import org.digidoc4j.SignatureProfile; import org.digidoc4j.X509Cert; import org.digidoc4j.exceptions.CertificateNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import eu.europa.esig.dss.x509.CertificateToken; import prototype.AlwaysValidOcspSource; public class TimemarkSignature extends BesSignature { private static final Logger logger = LoggerFactory.getLogger(TimemarkSignature.class); private X509Cert ocspCertificate; private BasicOCSPResp ocspResponse; private Date ocspResponseTime; public TimemarkSignature(XadesValidationReportGenerator xadesReportGenerator) { super(xadesReportGenerator); } @Override public SignatureProfile getProfile() { return SignatureProfile.LT_TM; } @Override public X509Cert getOCSPCertificate() { if (ocspCertificate != null) { return ocspCertificate; } initOcspResponse(); if (ocspResponse == null) { return null; } ocspCertificate = findOcspCertificate(); return ocspCertificate; } @Override public List<BasicOCSPResp> getOcspResponses() { return getDssSignature().getOCSPSource().getContainedOCSPResponses(); } @Override public Date getOCSPResponseCreationTime() { if (ocspResponseTime != null) { return ocspResponseTime; } initOcspResponse(); if (ocspResponse == null) { return null; } ocspResponseTime = ocspResponse.getProducedAt(); return ocspResponseTime; } @Override public Date getTrustedSigningTime() { return getOCSPResponseCreationTime(); } private void initOcspResponse() { if (ocspResponse == null) { ocspResponse = findOcspResponse(); if (ocspResponse == null) { logger.warn("Signature is missing OCSP response"); } } } private BasicOCSPResp findOcspResponse() { logger.debug("Finding OCSP response"); List<BasicOCSPResp> containedOCSPResponses = getOcspResponses(); if (containedOCSPResponses.isEmpty()) { logger.debug("Contained OCSP responses is empty"); return null; } if (containedOCSPResponses.size() > 1) { logger.warn("Signature contains more than one OCSP response: " + containedOCSPResponses.size() + ". Using the first one."); } return containedOCSPResponses.get(0); } private X509Cert findOcspCertificate() { try { RespID responderId = ocspResponse.getResponderId(); String primitiveName = getCN(responderId.toASN1Primitive().getName()); byte[] keyHash = responderId.toASN1Primitive().getKeyHash(); if ((keyHash != null && keyHash.length > 0) && (primitiveName == null || primitiveName.trim().length() == 0)) { logger.debug("Using keyHash {} for OCSP certificate match", keyHash); } else { logger.debug("Using ASN1Primitive {} for OCSP certificate match", primitiveName); } for (CertificateToken cert : getDssSignature().getCertificates()) { if ((keyHash != null && keyHash.length > 0) && (primitiveName == null || primitiveName.trim().length() == 0)) { ASN1Primitive skiPrimitive = JcaX509ExtensionUtils.parseExtensionValue(cert.getCertificate().getExtensionValue(Extension.subjectKeyIdentifier.getId())); byte[] keyIdentifier = ASN1OctetString.getInstance(skiPrimitive.getEncoded()).getOctets(); if (Arrays.equals(keyHash, keyIdentifier)) { return new X509Cert(cert.getCertificate()); } } else { String certCn = getCN(new X500Name(cert.getSubjectX500Principal().getName())); if (StringUtils.equals(certCn, primitiveName)) { return new X509Cert(cert.getCertificate()); } } } } catch (IOException e) { logger.error("Unable to wrap and extract SubjectKeyIdentifier from certificate - technical error. {}", e); } logger.error("OCSP certificate for was not found in TSL"); throw new CertificateNotFoundException("OCSP certificate for was not found in TSL"); } private String getCN(X500Name x500Name) { if (x500Name == null) return null; RDN[] rdNs = x500Name.getRDNs(new ASN1ObjectIdentifier("2.5.4.3")); if (rdNs == null || rdNs.length == 0) { return null; } AttributeTypeAndValue[] typesAndValues = rdNs[0].getTypesAndValues(); if (typesAndValues == null || typesAndValues.length == 0) { return null; } String name = typesAndValues[0].getValue().toString(); return name; } }
/* * @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a> * @author <a href="mailto:wehren@aei.mpg.de">Oliver Wehrens</a> * @version $Id$ */ package org.gridlab.gridsphere.layout; import org.gridlab.gridsphere.portletcontainer.GridSphereEvent; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * The LayoutManager is responsible for constructing a layout appropriate * to the user's layout preferences. */ public abstract class BaseLayoutManager extends BasePortletComponent implements LayoutManager, PortletFrameListener { protected List components = new ArrayList(); protected PortletInsets insets; public List init(List list) { list = super.init(list); Iterator it = components.iterator(); PortletLifecycle p = null; ComponentIdentifier compId; while (it.hasNext()) { compId = new ComponentIdentifier(); p = (PortletLifecycle)it.next(); compId.setPortletLifecycle(p); compId.setClassName(p.getClass().getName()); compId.setComponentID(list.size()); //PortletRender a = (PortletRender)p; list.add(compId); // invoke init on each component list = p.init(list); // If the component is a frame we want to be notified if (p instanceof PortletFrame) { PortletFrame f = (PortletFrame)p; f.addFrameListener(this); } } return list; } public void login(GridSphereEvent event) {} public void logout(GridSphereEvent event) {} public void destroy() {} public void actionPerformed(GridSphereEvent event) throws PortletLayoutException, IOException {} public void handleFrameMaximized(PortletFrameEvent event) { Iterator it = components.iterator(); PortletComponent p = null; int id = event.getID(); while (it.hasNext()) { p = (PortletComponent)it.next(); // check for the frame that has been maximized if (p.getComponentID() == id) { p.setWidth("100%"); } else { // If this is not the right frame, make it invisible p.setVisible(false); } } } public void handleFrameMinimized(PortletFrameEvent event) { Iterator it = components.iterator(); PortletComponent p = null; int id = event.getID(); while (it.hasNext()) { p = (PortletComponent)it.next(); if (p.getComponentID() == id) { p.setWidth(""); } p.setVisible(true); } } public void handleFrameResized(PortletFrameEvent event) { Iterator it = components.iterator(); PortletComponent p = null; int id = event.getID(); while (it.hasNext()) { p = (PortletComponent)it.next(); if (p.getComponentID() == id) { p.setWidth(""); } else { p.setVisible(true); } } } public void handleFrameEvent(PortletFrameEvent event) throws PortletLayoutException { if (event.getAction() == PortletFrameEvent.Action.FRAME_MAXIMIZED) { handleFrameMaximized(event); } else if (event.getAction() == PortletFrameEvent.Action.FRAME_MINIMIZED) { handleFrameMinimized(event); } else if (event.getAction() == PortletFrameEvent.Action.FRAME_RESIZED) { handleFrameResized(event); } } public void addPortletComponent(PortletComponent component) { components.add(component); } public void removePortletComponent(PortletComponent component) { components.remove(component); } public void setPortletComponents(ArrayList components) { this.components = components; } public List getPortletComponents() { return components; } public PortletInsets getPortletInsets() { return insets; } public void setPortletInsets(PortletInsets insets) { this.insets = insets; } }
/* * @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.layout; import org.gridlab.gridsphere.portlet.impl.SportletResponse; import org.gridlab.gridsphere.portletcontainer.GridSphereEvent; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.List; import java.util.ArrayList; public class PortletGridLayout extends BaseLayoutManager { private int numColumns; private int[] colSizes; private String columnString; public PortletGridLayout() {} public String getClassName() { return PortletGridLayout.class.getName(); } public void setColumns(String columnString) { this.columnString = columnString; } public String getColumns() { return columnString; } public List init(List list) { list = super.init(list); if (columnString != null) { StringTokenizer st = new StringTokenizer(columnString, ","); numColumns = st.countTokens(); colSizes = new int[numColumns]; int i = 0; while (st.hasMoreTokens()) { String col = st.nextToken(); colSizes[i] = Integer.parseInt(col); i++; } } else { numColumns = 1; colSizes = new int[1]; colSizes[0] = 100; } return list; } public void doRender(GridSphereEvent event) throws PortletLayoutException, IOException { SportletResponse res = event.getSportletResponse(); PrintWriter out = res.getWriter(); if (insets == null) insets = new PortletInsets(); //int j = 0, k = 0; //out.println("row: "+rows+" columns "+cols); int numComponents = components.size(); PortletComponent p = null; int portletsPerColumns = numComponents/numColumns; int portletCount = 0; System.out.println(" ================ portletspercolumn: "+portletsPerColumns); System.out.println(" ================ numcolumns: "+numColumns); System.out.println(" ================ numComponents: "+numComponents); // cycle through to find a max window for (int i=0;i<numComponents;i++) { p = (PortletComponent)components.get(i); if (p.getWidth().equals("100%")) { i=numComponents+1; } } // ok this one is maximized show only this window if (p.getWidth().equals("100%")) { // make another table around this, just for the padding out.println("<table border=\"0\" width=\"100%\" cellpadding=\"2\" cellspacing=\"0\"> "); out.println("<tr><td>"); p.doRender(event); out.println("</td></tr></table>"); } else { //out.println("<table width=\"" + gwidth + "%\" border=\"0\" cellspacing=\"2\" cellpadding=\"0\" bgcolor=\"#FFFFFF\">"); out.println("<table border=\"0\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\"> <!-- overall gridlayout table -->"); out.println("<tr> <!-- overall one row -->"); for (int i=0;i<numColumns;i++) { // new column out.println("<td width=\""+colSizes[i]+"%\" valign=\"top\"> <!-- this is a row -->"); // construct a table inside this column out.println("<table border=\"0\" width=\"100%\" cellpadding=\"2\" cellspacing=\"0\"> <!-- this is table inside row ("+i+")-->"); // now render the portlets in this column //out.println("<tr>"); for (int j=1;j<=portletsPerColumns;j++) { out.println("<tr><td>"); p = (PortletComponent)components.get(portletCount); if (p.isVisible()) { p.doRender(event); } out.println("</td></tr>"); portletCount++; // if we have some (1) portlet left because of odd number of // portlets to display just render the last ones in that column here if ((portletCount<numComponents) && (i==numColumns-1) && (j==portletsPerColumns)) { j } } // close this row again out.println("</table> <!-- end table inside row -->"); out.println("</td>"); } out.println("</tr> <!-- end overall one row -->"); out.println("</table> <!-- end overall gridlayout table -->"); } } }
/* * @author <a href="mailto:novotny@gridsphere.org">Jason Novotny</a> * @version $Id: LoginPortlet.java 5087 2006-08-18 22:52:23Z novotny $ */ package org.gridsphere.portlets.core.login; import org.gridsphere.layout.PortletPageFactory; import org.gridsphere.portlet.impl.PortletURLImpl; import org.gridsphere.portlet.impl.SportletProperties; import org.gridsphere.portlet.service.PortletServiceException; import org.gridsphere.provider.event.jsr.ActionFormEvent; import org.gridsphere.provider.event.jsr.RenderFormEvent; import org.gridsphere.provider.portlet.jsr.ActionPortlet; import org.gridsphere.provider.portletui.beans.HiddenFieldBean; import org.gridsphere.provider.portletui.beans.MessageBoxBean; import org.gridsphere.provider.portletui.beans.PasswordBean; import org.gridsphere.provider.portletui.beans.TextFieldBean; import org.gridsphere.services.core.filter.PortalFilter; import org.gridsphere.services.core.filter.PortalFilterService; import org.gridsphere.services.core.mail.MailMessage; import org.gridsphere.services.core.mail.MailService; import org.gridsphere.services.core.portal.PortalConfigService; import org.gridsphere.services.core.request.Request; import org.gridsphere.services.core.request.RequestService; import org.gridsphere.services.core.security.auth.AuthModuleService; import org.gridsphere.services.core.security.auth.AuthenticationException; import org.gridsphere.services.core.security.auth.AuthorizationException; import org.gridsphere.services.core.security.auth.modules.LoginAuthModule; import org.gridsphere.services.core.security.password.PasswordEditor; import org.gridsphere.services.core.security.password.PasswordManagerService; import org.gridsphere.services.core.security.role.PortletRole; import org.gridsphere.services.core.security.role.RoleManagerService; import org.gridsphere.services.core.user.User; import org.gridsphere.services.core.user.UserManagerService; import javax.portlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.security.cert.X509Certificate; import java.util.*; public class LoginPortlet extends ActionPortlet { private static String FORGOT_PASSWORD_LABEL = "forgotpassword"; private static String ACTIVATE_ACCOUNT_LABEL = "activateaccount"; private static long REQUEST_LIFETIME = 1000 * 60 * 60 * 24 * 3; // 3 days public static final String LOGIN_ERROR_FLAG = "LOGIN_FAILED"; public static final Integer LOGIN_ERROR_UNKNOWN = new Integer(-1); public static final String DO_VIEW_USER_EDIT_LOGIN = "login/createaccount.jsp"; //edit user public static final String DO_FORGOT_PASSWORD = "login/forgotpassword.jsp"; public static final String DO_NEW_PASSWORD = "login/newpassword.jsp"; private UserManagerService userManagerService = null; private RoleManagerService roleService = null; private PasswordManagerService passwordManagerService = null; private PortalConfigService portalConfigService = null; private RequestService requestService = null; private MailService mailService = null; private AuthModuleService authModuleService = null; private PortalFilterService portalFilterService = null; private String notificationURL = null; private String newpasswordURL = null; private String activateAccountURL = null; private String denyAccountURL = null; private String redirectURL = null; private String logoutURL = null; public void init(PortletConfig config) throws PortletException { super.init(config); userManagerService = (UserManagerService) createPortletService(UserManagerService.class); roleService = (RoleManagerService) createPortletService(RoleManagerService.class); passwordManagerService = (PasswordManagerService) createPortletService(PasswordManagerService.class); requestService = (RequestService) createPortletService(RequestService.class); mailService = (MailService) createPortletService(MailService.class); portalConfigService = (PortalConfigService) createPortletService(PortalConfigService.class); portalFilterService = (PortalFilterService) createPortletService(PortalFilterService.class); authModuleService = (AuthModuleService) createPortletService(AuthModuleService.class); DEFAULT_VIEW_PAGE = "doViewUser"; } public void doViewUser(RenderFormEvent event) throws PortletException { log.debug("in LoginPortlet: doViewUser"); PortletRequest request = event.getRenderRequest(); RenderResponse response = event.getRenderResponse(); if (notificationURL == null) notificationURL = response.createActionURL().toString(); if (newpasswordURL == null) { PortletURL url = response.createActionURL(); ((PortletURLImpl) url).setAction("newpassword"); newpasswordURL = url.toString(); } if (redirectURL == null) { PortletURL url = response.createRenderURL(); ((PortletURLImpl) url).setLayout(PortletPageFactory.USER_PAGE); redirectURL = url.toString(); } if (logoutURL == null) { PortletURL url = response.createRenderURL(); logoutURL = url.toString(); } if (activateAccountURL == null) { PortletURL url = response.createActionURL(); ((PortletURLImpl) url).setAction("approveAccount"); activateAccountURL = url.toString(); } if (denyAccountURL == null) { PortletURL url = response.createActionURL(); ((PortletURLImpl) url).setAction("denyAccount"); denyAccountURL = url.toString(); } PasswordBean pass = event.getPasswordBean("password"); pass.setValue(""); // Check certificates String x509supported = portalConfigService.getProperty(PortalConfigService.SUPPORT_X509_AUTH); if ((x509supported != null) && (x509supported.equalsIgnoreCase("true"))) { X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate"); if (certs != null && certs.length > 0) { request.setAttribute("certificate", certs[0].getSubjectDN().toString()); } } String remUser = portalConfigService.getProperty(PortalConfigService.REMEMBER_USER); if ((remUser != null) && (remUser.equalsIgnoreCase("TRUE"))) { request.setAttribute("remUser", "true"); } Boolean useSecureLogin = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.USE_HTTPS_LOGIN)); request.setAttribute("useSecureLogin", useSecureLogin.toString()); boolean canUserCreateAccount = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.CAN_USER_CREATE_ACCOUNT)).booleanValue(); if (canUserCreateAccount) request.setAttribute("canUserCreateAcct", "true"); boolean dispUser = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.SEND_USER_FORGET_PASSWORD)).booleanValue(); if (dispUser) request.setAttribute("dispPass", "true"); String errorMsg = (String) request.getPortletSession(true).getAttribute(LOGIN_ERROR_FLAG); if (errorMsg != null) { createErrorMessage(event, errorMsg); request.getPortletSession(true).removeAttribute(LOGIN_ERROR_FLAG); } Boolean useUserName = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.USE_USERNAME_FOR_LOGIN)); if (useUserName) request.setAttribute("useUserName", "true"); setNextState(request, "login/login.jsp"); } public void doCancel(ActionFormEvent event) throws PortletException { setNextState(event.getActionRequest(), DEFAULT_VIEW_PAGE); } public void gs_login(ActionFormEvent event) throws PortletException { log.debug("in LoginPortlet: gs_login"); PortletRequest req = event.getActionRequest(); try { login(event); } catch (AuthorizationException err) { log.debug(err.getMessage()); req.getPortletSession(true).setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } catch (AuthenticationException err) { log.debug(err.getMessage()); req.getPortletSession(true).setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } setNextState(req, DEFAULT_VIEW_PAGE); } /** * Handles login requests * * @param event a <code>GridSphereEvent</code> * @throws org.gridsphere.services.core.security.auth.AuthenticationException * if auth fails * @throws org.gridsphere.services.core.security.auth.AuthorizationException * if authz fails */ protected void login(ActionFormEvent event) throws AuthenticationException, AuthorizationException { ActionRequest req = event.getActionRequest(); ActionResponse res = event.getActionResponse(); User user = login(req); Long now = Calendar.getInstance().getTime().getTime(); user.setLastLoginTime(now); Integer numLogins = user.getNumLogins(); if (numLogins == null) numLogins = 0; numLogins++; user.setNumLogins(numLogins); user.setAttribute(PortalConfigService.LOGIN_NUMTRIES, "0"); userManagerService.saveUser(user); req.setAttribute(SportletProperties.PORTLET_USER, user); req.getPortletSession(true).setAttribute(SportletProperties.PORTLET_USER, user.getID(), PortletSession.APPLICATION_SCOPE); String query = event.getAction().getParameter("queryString"); if (query != null) { //redirectURL.setParameter("cid", query); } //req.setAttribute(SportletProperties.LAYOUT_PAGE, PortletPageFactory.USER_PAGE); String realuri = redirectURL.toString().substring("http".length()); Boolean useSecureRedirect = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.USE_HTTPS_REDIRECT)); if (useSecureRedirect.booleanValue()) { realuri = "https" + realuri; } else { realuri = "http" + realuri; } List<PortalFilter> portalFilters = portalFilterService.getPortalFilters(); for (PortalFilter filter : portalFilters) { filter.doAfterLogin((HttpServletRequest) req, (HttpServletResponse) res); } log.debug("in login redirecting to portal: " + realuri.toString()); try { if (req.getParameter("ajax") != null) { //res.setContentType("text/html"); //res.getWriter().print(realuri.toString()); } else { res.sendRedirect(realuri.toString()); } } catch (IOException e) { log.error("Unable to perform a redirect!", e); } } public User login(PortletRequest req) throws AuthenticationException, AuthorizationException { String loginName = req.getParameter("username"); String loginPassword = req.getParameter("password"); String certificate = null; X509Certificate[] certs = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate"); if (certs != null && certs.length > 0) { certificate = certificateTransform(certs[0].getSubjectDN().toString()); } User user = null; // if using client certificate, then don't use login modules if (certificate == null) { if ((loginName == null) || (loginPassword == null)) { throw new AuthorizationException(getLocalizedText(req, "LOGIN_AUTH_BLANK")); } // first get user Boolean useUserName = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.USE_USERNAME_FOR_LOGIN)); if (useUserName) { user = userManagerService.getUserByUserName(loginName); } else { user = userManagerService.getUserByEmail(loginName); } } else { log.debug("Using certificate for login :" + certificate); List userList = userManagerService.getUsersByAttribute("certificate", certificate, null); if (!userList.isEmpty()) { user = (User) userList.get(0); } } if (user == null) throw new AuthorizationException(getLocalizedText(req, "LOGIN_AUTH_NOUSER")); // tried one to many times using same name int defaultNumTries = Integer.valueOf(portalConfigService.getProperty(PortalConfigService.LOGIN_NUMTRIES)).intValue(); int numTriesInt; String numTries = (String) user.getAttribute(PortalConfigService.LOGIN_NUMTRIES); if (numTries == null) { numTriesInt = 1; } else { numTriesInt = Integer.valueOf(numTries).intValue(); } System.err.println("num tries = " + numTriesInt); if ((defaultNumTries != -1) && (numTriesInt >= defaultNumTries)) { disableAccount(req); throw new AuthorizationException(getLocalizedText(req, "LOGIN_TOOMANY_ATTEMPTS")); } String accountStatus = (String) user.getAttribute(User.DISABLED); if ((accountStatus != null) && ("TRUE".equalsIgnoreCase(accountStatus))) throw new AuthorizationException(getLocalizedText(req, "LOGIN_AUTH_DISABLED")); // If authorized via certificates no other authorization needed if (certificate != null) return user; // second invoke the appropriate auth module List<LoginAuthModule> modules = authModuleService.getActiveAuthModules(); Collections.sort(modules); AuthenticationException authEx = null; Iterator it = modules.iterator(); log.debug("in login: Active modules are: "); boolean success = false; while (it.hasNext()) { success = false; LoginAuthModule mod = (LoginAuthModule) it.next(); log.debug(mod.getModuleName()); try { mod.checkAuthentication(user, loginPassword); success = true; } catch (AuthenticationException e) { String errMsg = mod.getModuleError(e.getMessage(), req.getLocale()); if (errMsg != null) { authEx = new AuthenticationException(errMsg); } else { authEx = e; } } if (success) break; } if (!success) { numTriesInt++; user.setAttribute(PortalConfigService.LOGIN_NUMTRIES, String.valueOf(numTriesInt)); userManagerService.saveUser(user); throw authEx; } return user; } /** * Transform certificate subject from : * CN=Engbert Heupers, O=sara, O=users, O=dutchgrid * to : * /O=dutchgrid/O=users/O=sara/CN=Engbert Heupers * * @param certificate string * @return certificate string */ private String certificateTransform(String certificate) { String ls[] = certificate.split(", "); StringBuffer res = new StringBuffer(); for (int i = ls.length - 1; i >= 0; i res.append("/"); res.append(ls[i]); } return res.toString(); } protected String getLocalizedText(HttpServletRequest req, String key) { Locale locale = req.getLocale(); ResourceBundle bundle = ResourceBundle.getBundle("gridsphere.resources.Portlet", locale); return bundle.getString(key); } public void disableAccount(PortletRequest req) { //PortletRequest req = event.getRenderRequest(); String loginName = req.getParameter("username"); User user = userManagerService.getUserByUserName(loginName); if (user != null) { user.setAttribute(User.DISABLED, "true"); userManagerService.saveUser(user); MailMessage mailToUser = new MailMessage(); StringBuffer body = new StringBuffer(); body.append(getLocalizedText(req, "LOGIN_DISABLED_MSG1")).append(" ").append(getLocalizedText(req, "LOGIN_DISABLED_MSG2")).append("\n\n"); mailToUser.setBody(body.toString()); mailToUser.setSubject(getLocalizedText(req, "LOGIN_DISABLED_SUBJECT")); mailToUser.setEmailAddress(user.getEmailAddress()); MailMessage mailToAdmin = new MailMessage(); StringBuffer body2 = new StringBuffer(); body2.append(getLocalizedText(req, "LOGIN_DISABLED_ADMIN_MSG")).append(" ").append(user.getUserName()); mailToAdmin.setBody(body2.toString()); mailToAdmin.setSubject(getLocalizedText(req, "LOGIN_DISABLED_SUBJECT") + " " + user.getUserName()); String portalAdminEmail = portalConfigService.getProperty(PortalConfigService.PORTAL_ADMIN_EMAIL); mailToAdmin.setEmailAddress(portalAdminEmail); try { mailService.sendMail(mailToUser); mailService.sendMail(mailToAdmin); } catch (PortletServiceException e) { log.error("Unable to send mail message!", e); //createErrorMessage(event, this.getLocalizedText(req, "LOGIN_FAILURE_MAIL")); } } } public void doNewUser(RenderFormEvent evt) throws PortletException { boolean canUserCreateAccount = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.CAN_USER_CREATE_ACCOUNT)).booleanValue(); if (!canUserCreateAccount) return; RenderRequest req = evt.getRenderRequest(); RenderResponse res = evt.getRenderResponse(); MessageBoxBean msg = evt.getMessageBoxBean("msg"); String savePasswds = portalConfigService.getProperty(PortalConfigService.SAVE_PASSWORDS); if (savePasswds.equals(Boolean.TRUE.toString())) { req.setAttribute("savePass", "true"); } String adminApproval = portalConfigService.getProperty("ADMIN_ACCOUNT_APPROVAL"); if (adminApproval.equals(Boolean.TRUE.toString())) { msg.setKey("LOGIN_ACCOUNT_CREATE_APPROVAL"); } else { msg.setKey("LOGIN_CREATE_ACCT"); } res.setTitle("Create Account"); setNextState(req, DO_VIEW_USER_EDIT_LOGIN); log.debug("in doViewNewUser"); } public void doConfirmEditUser(ActionFormEvent evt) throws PortletException { PortletRequest req = evt.getActionRequest(); String savePasswds = portalConfigService.getProperty(PortalConfigService.SAVE_PASSWORDS); if (savePasswds.equals(Boolean.TRUE.toString())) { req.setAttribute("savePass", "true"); } boolean canUserCreateAccount = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.CAN_USER_CREATE_ACCOUNT)).booleanValue(); if (!canUserCreateAccount) return; try { //check if the user is new or not validateUser(evt); //new and valid user and will save it notifyNewUser(evt); setNextState(req, DEFAULT_VIEW_PAGE); } catch (PortletException e) { //invalid user, an exception was thrown //back to edit log.error("Could not create account: ", e); setNextState(req, "doNewUser"); } } private void validateUser(ActionFormEvent event) throws PortletException { log.debug("Entering validateUser()"); PortletRequest req = event.getActionRequest(); // Validate user name String userName = event.getTextFieldBean("userName").getValue(); if (userName.equals("")) { createErrorMessage(event, this.getLocalizedText(req, "USER_NAME_BLANK") + "<br />"); throw new PortletException("user name is blank!"); } if (this.userManagerService.existsUserName(userName)) { createErrorMessage(event, this.getLocalizedText(req, "USER_EXISTS") + "<br />"); throw new PortletException("user exists already"); } // Validate full name String firstName = event.getTextFieldBean("firstName").getValue(); if (firstName.equals("")) { createErrorMessage(event, this.getLocalizedText(req, "USER_GIVENNAME_BLANK") + "<br />"); throw new PortletException("first name is blank"); } String lastName = event.getTextFieldBean("lastName").getValue(); if (lastName.equals("")) { createErrorMessage(event, this.getLocalizedText(req, "USER_FAMILYNAME_BLANK") + "<br />"); throw new PortletException("last name is blank"); } // Validate e-mail String eMail = event.getTextFieldBean("emailAddress").getValue(); if (eMail.equals("")) { createErrorMessage(event, this.getLocalizedText(req, "USER_NEED_EMAIL") + "<br />"); throw new PortletException("email is blank"); } else if ((eMail.indexOf("@") < 0)) { createErrorMessage(event, this.getLocalizedText(req, "USER_NEED_EMAIL") + "<br />"); throw new PortletException("email address invalid"); } else if ((eMail.indexOf(".") < 0)) { createErrorMessage(event, this.getLocalizedText(req, "USER_NEED_EMAIL") + "<br />"); throw new PortletException("email address invalid"); } //Validate password String savePasswds = portalConfigService.getProperty(PortalConfigService.SAVE_PASSWORDS); if (savePasswds.equals(Boolean.TRUE.toString())) { if (isInvalidPassword(event)) throw new PortletException("password no good!"); } //retrieve the response String response = event.getTextFieldBean("captchaTF").getValue(); String captchaValue = (String) req.getPortletSession(true).getAttribute(nl.captcha.servlet.Constants.SIMPLE_CAPCHA_SESSION_KEY, PortletSession.APPLICATION_SCOPE); if (!response.equals(captchaValue)) { createErrorMessage(event, this.getLocalizedText(req, "USER_CAPTCHA_MISMATCH")); throw new PortletException("captcha challenge mismatch!"); } log.debug("Exiting validateUser()"); } private boolean isInvalidPassword(ActionFormEvent event) { PortletRequest req = event.getActionRequest(); // Validate password String passwordValue = event.getPasswordBean("password").getValue(); String confirmPasswordValue = event.getPasswordBean("confirmPassword").getValue(); if (passwordValue == null) { createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_NOTSET")); return true; } // Otherwise, password must match confirmation if (!passwordValue.equals(confirmPasswordValue)) { createErrorMessage(event, (this.getLocalizedText(req, "USER_PASSWORD_MISMATCH")) + "<br />"); return true; // If they do match, then validate password with our service } else { passwordValue = passwordValue.trim(); if (passwordValue.length() == 0) { createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_BLANK")); return true; } if (passwordValue.length() < 5) { createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_TOOSHORT")); return true; } } return false; } private User saveUser(Request request) { log.debug("Entering saveUser()"); // Account request // Create edit account request User newuser = this.userManagerService.createUser(); // Edit account attributes newuser.setUserName(request.getAttribute("userName")); newuser.setFirstName(request.getAttribute("firstName")); newuser.setLastName(request.getAttribute("lastName")); newuser.setFullName(request.getAttribute("lastName") + ", " + request.getAttribute("firstName")); newuser.setEmailAddress(request.getAttribute("emailAddress")); newuser.setOrganization(request.getAttribute("organization")); long now = Calendar.getInstance().getTime().getTime(); newuser.setAttribute(User.CREATEDATE, String.valueOf(now)); // Submit changes this.userManagerService.saveUser(newuser); String savePasswds = portalConfigService.getProperty(PortalConfigService.SAVE_PASSWORDS); if (savePasswds.equals(Boolean.TRUE.toString())) { PasswordEditor editor = passwordManagerService.editPassword(newuser); String password = request.getAttribute("password"); editor.setValue(password); passwordManagerService.saveHashedPassword(editor); } // Save user role saveUserRole(newuser); log.debug("Exiting saveUser()"); return newuser; } private void saveUserRole(User user) { log.debug("Entering saveUserRole()"); List<PortletRole> defaultRoles = roleService.getDefaultRoles(); for (PortletRole role : defaultRoles) { roleService.addUserToRole(user, role); } } public void displayForgotPassword(ActionFormEvent event) { boolean sendMail = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.SEND_USER_FORGET_PASSWORD)).booleanValue(); if (sendMail) { PortletRequest req = event.getActionRequest(); setNextState(req, DO_FORGOT_PASSWORD); } } public void notifyUser(ActionFormEvent evt) { PortletRequest req = evt.getActionRequest(); User user; TextFieldBean emailTF = evt.getTextFieldBean("emailTF"); if (emailTF.getValue().equals("")) { createErrorMessage(evt, this.getLocalizedText(req, "LOGIN_NO_EMAIL")); return; } else { user = userManagerService.getUserByEmail(emailTF.getValue()); } if (user == null) { createErrorMessage(evt, this.getLocalizedText(req, "LOGIN_NOEXIST")); return; } // create a request Request request = requestService.createRequest(FORGOT_PASSWORD_LABEL); long now = Calendar.getInstance().getTime().getTime(); request.setLifetime(new Date(now + REQUEST_LIFETIME)); request.setUserID(user.getID()); requestService.saveRequest(request); MailMessage mailToUser = new MailMessage(); mailToUser.setEmailAddress(emailTF.getValue()); String subjectHeader = portalConfigService.getProperty("LOGIN_FORGOT_SUBJECT"); if (subjectHeader == null) subjectHeader = getLocalizedText(req, "MAIL_SUBJECT_HEADER"); mailToUser.setSubject(subjectHeader); StringBuffer body = new StringBuffer(); String forgotMail = portalConfigService.getProperty("LOGIN_FORGOT_BODY"); if (forgotMail == null) forgotMail = getLocalizedText(req, "LOGIN_FORGOT_MAIL"); body.append(forgotMail).append("\n\n"); body.append(newpasswordURL).append("&reqid=").append(request.getOid()); mailToUser.setBody(body.toString()); try { mailService.sendMail(mailToUser); createSuccessMessage(evt, this.getLocalizedText(req, "LOGIN_SUCCESS_MAIL")); } catch (PortletServiceException e) { log.error("Unable to send mail message!", e); createErrorMessage(evt, this.getLocalizedText(req, "LOGIN_FAILURE_MAIL")); setNextState(req, DEFAULT_VIEW_PAGE); } } public void notifyNewUser(ActionFormEvent evt) throws PortletException { PortletRequest req = evt.getActionRequest(); TextFieldBean emailTF = evt.getTextFieldBean("emailAddress"); // create a request Request request = requestService.createRequest(ACTIVATE_ACCOUNT_LABEL); long now = Calendar.getInstance().getTime().getTime(); request.setLifetime(new Date(now + REQUEST_LIFETIME)); // request.setUserID(user.getID()); request.setAttribute("userName", evt.getTextFieldBean("userName").getValue()); request.setAttribute("firstName", evt.getTextFieldBean("firstName").getValue()); request.setAttribute("lastName", evt.getTextFieldBean("lastName").getValue()); request.setAttribute("emailAddress", evt.getTextFieldBean("emailAddress").getValue()); request.setAttribute("organization", evt.getTextFieldBean("organization").getValue()); // put hashed pass in request String savePasswds = portalConfigService.getProperty(PortalConfigService.SAVE_PASSWORDS); if (savePasswds.equals(Boolean.TRUE.toString())) { String pass = evt.getPasswordBean("password").getValue(); pass = passwordManagerService.getHashedPassword(pass); request.setAttribute("password", pass); } requestService.saveRequest(request); MailMessage mailToUser = new MailMessage(); StringBuffer body = new StringBuffer(); String activateURL = activateAccountURL + "&reqid=" + request.getOid(); String denyURL = denyAccountURL + "&reqid=" + request.getOid(); // check if this account request should be approved by an administrator boolean accountApproval = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.ADMIN_ACCOUNT_APPROVAL)).booleanValue(); if (accountApproval) { String admin = portalConfigService.getProperty(PortalConfigService.PORTAL_ADMIN_EMAIL); mailToUser.setEmailAddress(admin); String mailSubject = portalConfigService.getProperty("LOGIN_ACCOUNT_APPROVAL_ADMIN_MAILSUBJECT"); if (mailSubject == null) mailSubject = getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ADMIN_MAILSUBJECT"); mailToUser.setSubject(mailSubject); String adminBody = portalConfigService.getProperty("LOGIN_ACCOUNT_APPROVAL_ADMIN_MAIL"); if (adminBody == null) adminBody = getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ADMIN_MAIL"); body.append(adminBody).append("\n\n"); body.append(getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ALLOW")).append("\n\n"); body.append(activateURL).append("\n\n"); body.append(getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_DENY")).append("\n\n"); body.append(denyURL).append("\n\n"); } else { mailToUser.setEmailAddress(emailTF.getValue()); String mailSubjectHeader = portalConfigService.getProperty("LOGIN_ACTIVATE_SUBJECT"); String loginActivateMail = portalConfigService.getProperty("LOGIN_ACTIVATE_BODY"); if (mailSubjectHeader == null) mailSubjectHeader = getLocalizedText(req, "LOGIN_ACTIVATE_SUBJECT"); mailToUser.setSubject(mailSubjectHeader); if (loginActivateMail == null) loginActivateMail = getLocalizedText(req, "LOGIN_ACTIVATE_MAIL"); body.append(loginActivateMail).append("\n\n"); body.append(activateURL).append("\n\n"); } body.append(getLocalizedText(req, "USERNAME")).append("\t"); body.append(evt.getTextFieldBean("userName").getValue()).append("\n"); body.append(getLocalizedText(req, "GIVENNAME")).append("\t"); body.append(evt.getTextFieldBean("firstName").getValue()).append("\n"); body.append(getLocalizedText(req, "FAMILYNAME")).append("\t"); body.append(evt.getTextFieldBean("lastName").getValue()).append("\n"); body.append(getLocalizedText(req, "ORGANIZATION")).append("\t"); body.append(evt.getTextFieldBean("organization").getValue()).append("\n"); body.append(getLocalizedText(req, "EMAILADDRESS")).append("\t"); body.append(evt.getTextFieldBean("emailAddress").getValue()).append("\n"); mailToUser.setBody(body.toString()); try { mailService.sendMail(mailToUser); } catch (PortletServiceException e) { createErrorMessage(evt, this.getLocalizedText(req, "LOGIN_FAILURE_MAIL")); throw new PortletException("Unable to send mail message!", e); } boolean adminRequired = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.ADMIN_ACCOUNT_APPROVAL)); if (adminRequired) { createSuccessMessage(evt, this.getLocalizedText(req, "LOGIN_ACCT_ADMIN_MAIL")); } else { createSuccessMessage(evt, this.getLocalizedText(req, "LOGIN_ACCT_MAIL")); } } public void newpassword(ActionFormEvent evt) { PortletRequest req = evt.getActionRequest(); String id = req.getParameter("reqid"); Request request = requestService.getRequest(id, FORGOT_PASSWORD_LABEL); if (request != null) { HiddenFieldBean reqid = evt.getHiddenFieldBean("reqid"); reqid.setValue(id); setNextState(req, DO_NEW_PASSWORD); } else { setNextState(req, DEFAULT_VIEW_PAGE); } } private void doEmailAction(ActionFormEvent event, String msg, boolean createAccount) { PortletRequest req = event.getActionRequest(); String id = req.getParameter("reqid"); User user = null; Request request = requestService.getRequest(id, ACTIVATE_ACCOUNT_LABEL); if (request != null) { requestService.deleteRequest(request); String subject = ""; String body = ""; if (createAccount) { user = saveUser(request); createSuccessMessage(event, msg + " " + user.getUserName()); // send the user an email subject = portalConfigService.getProperty("LOGIN_ACCOUNT_APPROVAL_ACCOUNT_CREATED"); if (subject == null) subject = getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ACCOUNT_CREATED"); body = portalConfigService.getProperty("LOGIN_ACCOUNT_APPROVAL_ACCOUNT_CREATED_BODY"); if (body == null) body = getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ACCOUNT_CREATED"); } else { createSuccessMessage(event, msg); // send the user an email subject = portalConfigService.getProperty("LOGIN_ACCOUNT_APPROVAL_ACCOUNT_DENY"); if (subject == null) subject = getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ACCOUNT_DENY"); body = portalConfigService.getProperty("LOGIN_ACCOUNT_APPROVAL_ACCOUNT_DENY_BODY"); if (body == null) body = getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ACCOUNT_DENY"); } MailMessage mailToUser = new MailMessage(); mailToUser.setEmailAddress(user.getEmailAddress()); mailToUser.setSubject(subject); StringBuffer msgbody = new StringBuffer(); msgbody.append(body).append("\n\n"); msgbody.append(notificationURL); mailToUser.setBody(body.toString()); try { mailService.sendMail(mailToUser); } catch (PortletServiceException e) { log.error("Error: " + e.getMessage()); createErrorMessage(event, this.getLocalizedText(req, "LOGIN_FAILURE_MAIL")); } } setNextState(req, "doViewUser"); } public void activate(ActionFormEvent event) { PortletRequest req = event.getActionRequest(); String msg = this.getLocalizedText(req, "USER_NEW_ACCOUNT") + "<br>" + this.getLocalizedText(req, "USER_PLEASE_LOGIN"); doEmailAction(event, msg, true); } public void approveAccount(ActionFormEvent event) { PortletRequest req = event.getActionRequest(); String msg = this.getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ACCOUNT_CREATED"); doEmailAction(event, msg, true); } public void denyAccount(ActionFormEvent event) { PortletRequest req = event.getActionRequest(); String msg = this.getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ACCOUNT_DENY"); doEmailAction(event, msg, false); } public void doSavePass(ActionFormEvent event) { PortletRequest req = event.getActionRequest(); HiddenFieldBean reqid = event.getHiddenFieldBean("reqid"); String id = reqid.getValue(); Request request = requestService.getRequest(id, FORGOT_PASSWORD_LABEL); if (request != null) { String uid = request.getUserID(); User user = userManagerService.getUser(uid); passwordManagerService.editPassword(user); String passwordValue = event.getPasswordBean("password").getValue(); String confirmPasswordValue = event.getPasswordBean("confirmPassword").getValue(); if (passwordValue == null) { createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_NOTSET")); setNextState(req, DO_NEW_PASSWORD); return; } // Otherwise, password must match confirmation if (!passwordValue.equals(confirmPasswordValue)) { createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_MISMATCH")); setNextState(req, DO_NEW_PASSWORD); // If they do match, then validate password with our service } else { if (passwordValue.length() == 0) { createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_BLANK")); setNextState(req, DO_NEW_PASSWORD); } else if (passwordValue.length() < 5) { System.err.println("length < 5 password= " + passwordValue); createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_TOOSHORT")); setNextState(req, DO_NEW_PASSWORD); } else { // save password //System.err.println("saving password= " + passwordValue); PasswordEditor editPasswd = passwordManagerService.editPassword(user); editPasswd.setValue(passwordValue); editPasswd.setDateLastModified(Calendar.getInstance().getTime()); passwordManagerService.savePassword(editPasswd); createSuccessMessage(event, this.getLocalizedText(req, "USER_PASSWORD_SUCCESS")); requestService.deleteRequest(request); } } } } }
package org.lockss.plugin.base; import java.io.IOException; import org.lockss.daemon.PluginException; import org.lockss.plugin.*; import org.lockss.util.HeaderUtil; import org.lockss.util.Logger; import org.lockss.util.PatternStringMap; /** * <p> * This ContentValidator is to allow validation of mime type based on the URL pattern. * The plugin can define those patters for which they want mime type validation and map them to the * expected mime type for each pattern. * Default is that this validator simply logs a warning. The plugin can override that and set * any of the other validation exceptions to be used for a mismatch. * </p> * * @author Alexandra Ohlson * @since 1.74 * @see MimeTypeContentValidotarFactory */ public class MimeTypeContentValidator implements ContentValidator { private static final Logger log = Logger.getLogger(MimeTypeContentValidator.class); protected ContentValidationException exception; protected ArchivalUnit au; protected String contentType; //not used - provided by factory // Cached here as might be used several times in quick succession protected PatternStringMap urlMimeValidationMap = null; public MimeTypeContentValidator(ArchivalUnit au, String contentType) { this.exception = new ContentValidationException.LogOnly("URL Mime Type Mismatch"); this.au = au; this.contentType = contentType; //don't think we need this for this implementation } PatternStringMap getUrlMimeValidationMap() { if (urlMimeValidationMap == null) { urlMimeValidationMap = au.makeUrlMimeValidationMap(); } // will be EMPTY not null after creation attempt return urlMimeValidationMap; } @Override public void validate(CachedUrl cu) throws ContentValidationException, PluginException, IOException { if (cu != null) { String url = cu.getUrl(); String expectedMime = getUrlMimeValidationMap().getMatch(url); if (expectedMime != null) { String actualMime = null; log.debug("Expected mime type: " + expectedMime + " for " + url); try { // this requires a close actualMime = HeaderUtil.getMimeTypeFromContentType(cu.getContentType()); } finally { AuUtil.safeRelease(cu); } if (!expectedMatchesActualMime(expectedMime,actualMime,cu)) { throw getMimeTypeException(); } } } } // default is a straight case-insensitive string comparison - we know expected is not null // plugin could override this for a more complicated equivalence, which is why the cu is passed along protected boolean expectedMatchesActualMime(String expectedMime, String actualMime, CachedUrl cu) { return expectedMime.equalsIgnoreCase(actualMime); } protected ContentValidationException getMimeTypeException() { return this.exception; } // plugin could override this to use a different type of exception protected void setMimeTypeException(ContentValidationException exc) { this.exception = exc; } }
package org.movabletype.api.client; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import org.movabletype.api.client.pojo.Asset; import org.movabletype.api.client.pojo.AssetItems; import org.movabletype.api.client.pojo.Authentication; import org.movabletype.api.client.pojo.Category; import org.movabletype.api.client.pojo.CategoryItems; import org.movabletype.api.client.pojo.CreateUser; import org.movabletype.api.client.pojo.Entry; import org.movabletype.api.client.pojo.EntryItems; import org.movabletype.api.client.pojo.Site; import org.movabletype.api.client.pojo.SiteItems; import org.movabletype.api.client.pojo.Status; import org.movabletype.api.client.pojo.User; import org.movabletype.api.client.pojo.UserItems; import org.movabletype.api.client.pojo.Version; import org.movabletype.api.client.request.AssetSearchParam; import org.movabletype.api.client.request.CategorySearchParam; import org.movabletype.api.client.request.EntrySearchParam; import org.movabletype.api.client.request.SiteSearchParam; import org.movabletype.api.client.request.UploadParam; import org.movabletype.api.client.request.UserSearchParam; public interface MovableTypeApiClient { Version getVersion() throws KeyManagementException, NoSuchAlgorithmException, IOException; void setVersion(String version); void setEndpoint(String endpoint); String getEndpoint(); int getResponseCode() throws IOException; String getResponseMessage() throws IOException; String getResponseBody() throws IOException; Authentication getAuthentication(); Status deleteToken() throws KeyManagementException, NoSuchAlgorithmException, IOException; Status signOut() throws KeyManagementException, NoSuchAlgorithmException, IOException; Site createWebsite(Site site) throws KeyManagementException, NoSuchAlgorithmException, IOException; Site createBlog(int site_id, Site site) throws KeyManagementException, NoSuchAlgorithmException, IOException; Site deleteSite(int site_id) throws KeyManagementException, NoSuchAlgorithmException, IOException; Site getSite(int site_id, String fields) throws KeyManagementException, NoSuchAlgorithmException, IOException; SiteItems searchSites(SiteSearchParam siteSearchParam) throws KeyManagementException, NoSuchAlgorithmException, IOException; Site updateSite(int site_id, Site site) throws KeyManagementException, NoSuchAlgorithmException, IOException; Entry postEntry(int site_id, Entry entry) throws KeyManagementException, NoSuchAlgorithmException, IOException; Entry deleteEntry(int site_id, Integer entry_id) throws KeyManagementException, NoSuchAlgorithmException, IOException; EntryItems getEntries(int site_id) throws KeyManagementException, NoSuchAlgorithmException, IOException; Entry getEntry(int site_id, int entry_id, String fields) throws KeyManagementException, NoSuchAlgorithmException, IOException; EntryItems searchEntry(EntrySearchParam search) throws KeyManagementException, NoSuchAlgorithmException, IOException; Entry updateEntry(int site_id, int entry_id, Entry entry) throws KeyManagementException, NoSuchAlgorithmException, IOException; Asset uploadAsset(UploadParam upload) throws IOException, KeyManagementException, NoSuchAlgorithmException; Asset deleteAsset(int site_id, int asset_id) throws KeyManagementException, NoSuchAlgorithmException, IOException; Asset getAsset(int site_id, int asset_id, String fields) throws KeyManagementException, NoSuchAlgorithmException, IOException; AssetItems searchAsset(int site_id, AssetSearchParam search) throws KeyManagementException, NoSuchAlgorithmException, IOException; Category createCategory(int site_id, Category category) throws KeyManagementException, NoSuchAlgorithmException, IOException; Category deleteCategory(int site_id, int category_id) throws KeyManagementException, NoSuchAlgorithmException, IOException; Category getCategory(int site_id, int category_id, String fields) throws KeyManagementException, NoSuchAlgorithmException, IOException; CategoryItems searchCategory(int site_id, CategorySearchParam search) throws KeyManagementException, NoSuchAlgorithmException, IOException; Category updateCategory(int site_id, int category_id, Category category) throws KeyManagementException, NoSuchAlgorithmException, IOException; User createUser(CreateUser createUser) throws KeyManagementException, NoSuchAlgorithmException, IOException; User deleteUser(int user_id) throws KeyManagementException, NoSuchAlgorithmException, IOException; UserItems searchUser(UserSearchParam userSearchParam) throws KeyManagementException, NoSuchAlgorithmException, IOException; User updateUser(User user) throws KeyManagementException, NoSuchAlgorithmException, IOException; User getUser(String user_id, String fields) throws KeyManagementException, NoSuchAlgorithmException, IOException; Status unlockUser(int user_id) throws KeyManagementException, NoSuchAlgorithmException, IOException; }
package org.nikialeksey.gameengine.ai.behaviortree; import java.util.ArrayList; import java.util.Collections; import java.util.UUID; public abstract class Node { private String uuid; private ArrayList<Node> children; public Node(Node... nodes) { this.uuid = UUID.randomUUID().toString(); this.children = new ArrayList<Node>(nodes.length); Collections.addAll(children, nodes); } public ArrayList<Node> getChildren() { return this.children; } public String getUUID(){return this.uuid;} protected Status btExecute(Tick tick) { this.btEnter(tick); this.btOpen(tick); Status status = this.btTick(tick); if (status != Status.RUNNING) { this.btClose(tick); } this.btExit(tick); return status; } private void btEnter(Tick tick) { tick.enterNode(this); this.enter(tick); } private void btOpen(Tick tick) { tick.openNode(this); tick.getBlackboard().put("isOpen", true, tick.getBehaviorTree().getUUID(), this.getUUID()); this.open(tick); } private Status btTick(Tick tick) { tick.tickNode(this); return this.tick(tick); } private void btClose(Tick tick) { tick.closeNode(this); tick.getBlackboard().put("isOpen", false, tick.getBehaviorTree().getUUID(), this.getUUID()); this.close(tick); } private void btExit(Tick tick) { tick.exitNode(this); this.exit(tick); } public abstract void enter(Tick tick); public abstract void open(Tick tick); public abstract Status tick(Tick tick); public abstract void close(Tick tick); public abstract void exit(Tick tick); }
package org.nschmidt.ldparteditor.data; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.widgets.Event; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector4f; import org.nschmidt.ldparteditor.composites.Composite3D; import org.nschmidt.ldparteditor.enums.ObjectMode; import org.nschmidt.ldparteditor.enums.Threshold; import org.nschmidt.ldparteditor.enums.View; import org.nschmidt.ldparteditor.helpers.composite3d.PerspectiveCalculator; import org.nschmidt.ldparteditor.helpers.math.HashBiMap; import org.nschmidt.ldparteditor.helpers.math.MathHelper; import org.nschmidt.ldparteditor.helpers.math.PowerRay; import org.nschmidt.ldparteditor.helpers.math.ThreadsafeTreeMap; import org.nschmidt.ldparteditor.helpers.math.Vector3d; import org.nschmidt.ldparteditor.i18n.I18n; import org.nschmidt.ldparteditor.logger.NLogger; import org.nschmidt.ldparteditor.shells.editor3d.Editor3DWindow; import org.nschmidt.ldparteditor.text.DatParser; import org.nschmidt.ldparteditor.text.StringHelper; public class VM01SelectHelper extends VM01Select { protected VM01SelectHelper(DatFile linkedDatFile) { super(linkedDatFile); } /** * * @param c3d * @param addSomething * @return {@code true} if the selection did not use a rubber band */ public synchronized boolean selectVertices(final Composite3D c3d, boolean addSomething) { final boolean noTrans = Editor3DWindow.getWindow().hasNoTransparentSelection(); final boolean noCondlineVerts = !c3d.isShowingCondlineControlPoints(); if (!c3d.getKeys().isCtrlPressed() && !addSomething || addSomething) { clearSelection2(); } final Vector4f selectionStart = new Vector4f(c3d.getSelectionStart()); final Vector4f selectionWidth = new Vector4f(c3d.getSelectionWidth()); final Vector4f selectionHeight = new Vector4f(c3d.getSelectionHeight()); final Vector4f selectionDepth; final boolean needRayTest; { boolean needRayTest2 = false; if (Math.abs(selectionWidth.x) < 0.001f && Math.abs(selectionWidth.y) < 0.001f && Math.abs(selectionWidth.z) < 0.001f) needRayTest2 = true; if (Math.abs(selectionHeight.x) < 0.001f && Math.abs(selectionHeight.y) < 0.001f && Math.abs(selectionHeight.z) < 0.001f) needRayTest2 = true; needRayTest = needRayTest2; } if (needRayTest) { Vector4f zAxis4f = new Vector4f(0, 0, c3d.hasNegDeterminant() ^ c3d.isWarpedSelection() ? -1f : 1f, 1f); Matrix4f ovr_inverse2 = Matrix4f.invert(c3d.getRotation(), null); Matrix4f.transform(ovr_inverse2, zAxis4f, zAxis4f); selectionDepth = (Vector4f) new Vector4f(zAxis4f.x, zAxis4f.y, zAxis4f.z, 0f).normalise(); selectionDepth.w = 1f; final float discr = 1f / c3d.getZoom(); final long complexity = c3d.isShowingHiddenVertices() ? vertexLinkedToPositionInFile.size() : vertexLinkedToPositionInFile.size() * ((long) triangles.size() + (long) quads.size()); if (complexity < View.NUM_CORES * 100L) { for (Vertex vertex : vertexLinkedToPositionInFile.keySet()) { if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; MathHelper.crossProduct(selectionDepth, Vector4f.sub(vertex.toVector4f(), selectionStart, null), selectionWidth); if (selectionWidth.x * selectionWidth.x + selectionWidth.y * selectionWidth.y + selectionWidth.z * selectionWidth.z < discr) { selectVertices_helper(c3d, vertex, selectionDepth, powerRay, noTrans, needRayTest); } } } else { // Multithreaded selection for many faces backupSelection(); final int chunks = View.NUM_CORES; final Thread[] threads = new Thread[chunks]; final AtomicBoolean dialogCanceled = new AtomicBoolean(false); final Vertex[] verts = vertexLinkedToPositionInFile.keySet().toArray(new Vertex[0]); final int iterations = verts.length; int lastend = 0; for (int j = 0; j < chunks; ++j) { final int[] i = new int[1]; final int[] start = new int[] { lastend }; lastend = Math.round(iterations / chunks * (j + 1)); final int[] end = new int[] { lastend }; if (j == chunks - 1) { end[0] = iterations; } i[0] = j; threads[j] = new Thread(new Runnable() { @Override public void run() { final PowerRay powerRay = new PowerRay(); int s = start[0]; int e = end[0]; Vector4f result = new Vector4f(); for (int k = s; k < e; k++) { Vertex vertex = verts[k]; if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; MathHelper.crossProduct(selectionDepth, Vector4f.sub(vertex.toVector4f(), selectionStart, null), result); if (result.x * result.x + result.y * result.y + result.z * result.z < discr) { if (dialogCanceled.get()) return; selectVertices_helper(c3d, vertex, selectionDepth, powerRay, noTrans, needRayTest); } } } }); threads[j].start(); } boolean isRunning = true; int counter = 0; while (isRunning) { try { Thread.sleep(100); counter++; if (counter == 50) break; } catch (InterruptedException e) { } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) isRunning = true; } } if (counter == 50) { linkedDatFile.setDrawSelection(false); try { new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor m) throws InvocationTargetException, InterruptedException { try { m.beginTask(I18n.VM_Selecting, IProgressMonitor.UNKNOWN); boolean isRunning = true; while (isRunning) { try { Thread.sleep(100); } catch (InterruptedException e) { } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) { isRunning = true; } } if (m.isCanceled()) { dialogCanceled.set(true); } } } finally { if (m.isCanceled()) { restoreSelection(); } else { backupSelectionClear(); } m.done(); } } }); }catch (InvocationTargetException consumed) { } catch (InterruptedException consumed) { } linkedDatFile.setDrawSelection(true); } } } else { selectionDepth = new Vector4f(); MathHelper.crossProduct(selectionHeight, selectionWidth, selectionDepth); selectionDepth.w = 0f; selectionDepth.normalise(); if (c3d.hasNegDeterminant() ^ c3d.isWarpedSelection()) { selectionDepth.negate(); } selectionDepth.w = 1f; final long complexity = c3d.isShowingHiddenVertices() ? vertexLinkedToPositionInFile.size() : vertexLinkedToPositionInFile.size() * ((long) triangles.size() + (long) quads.size()); if (complexity < View.NUM_CORES * 100L) { float[][] A = new float[3][3]; float[] b = new float[3]; for (Vertex vertex : vertexLinkedToPositionInFile.keySet()) { if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; A[0][0] = selectionWidth.x; A[1][0] = selectionWidth.y; A[2][0] = selectionWidth.z; A[0][1] = selectionHeight.x; A[1][1] = selectionHeight.y; A[2][1] = selectionHeight.z; A[0][2] = selectionDepth.x; A[1][2] = selectionDepth.y; A[2][2] = selectionDepth.z; b[0] = vertex.x - selectionStart.x; b[1] = vertex.y - selectionStart.y; b[2] = vertex.z - selectionStart.z; b = MathHelper.gaussianElimination(A, b); if (b[0] <= 1f && b[0] >= 0f && b[1] >= 0f && b[1] <= 1f) { selectVertices_helper(c3d, vertex, selectionDepth, powerRay, noTrans, needRayTest); } } } else { // Multithreaded selection for many, many faces backupSelection(); final int chunks = View.NUM_CORES; final Thread[] threads = new Thread[chunks]; final AtomicBoolean dialogCanceled = new AtomicBoolean(false); final Vertex[] verts = vertexLinkedToPositionInFile.keySet().toArray(new Vertex[0]); final int iterations = verts.length; int lastend = 0; for (int j = 0; j < chunks; ++j) { final int[] i = new int[1]; final int[] start = new int[] { lastend }; lastend = Math.round(iterations / chunks * (j + 1)); final int[] end = new int[] { lastend }; if (j == chunks - 1) { end[0] = iterations; } i[0] = j; threads[j] = new Thread(new Runnable() { @Override public void run() { final PowerRay powerRay = new PowerRay(); int s = start[0]; int e = end[0]; float[][] A = new float[3][3]; float[] b = new float[3]; for (int k = s; k < e; k++) { Vertex vertex = verts[k]; if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; A[0][0] = selectionWidth.x; A[1][0] = selectionWidth.y; A[2][0] = selectionWidth.z; A[0][1] = selectionHeight.x; A[1][1] = selectionHeight.y; A[2][1] = selectionHeight.z; A[0][2] = selectionDepth.x; A[1][2] = selectionDepth.y; A[2][2] = selectionDepth.z; b[0] = vertex.x - selectionStart.x; b[1] = vertex.y - selectionStart.y; b[2] = vertex.z - selectionStart.z; b = MathHelper.gaussianElimination(A, b); if (b[0] <= 1f && b[0] >= 0f && b[1] >= 0f && b[1] <= 1f) { if (dialogCanceled.get()) return; selectVertices_helper(c3d, vertex, selectionDepth, powerRay, noTrans, needRayTest); } } } }); threads[j].start(); } boolean isRunning = true; int counter = 0; while (isRunning) { try { Thread.sleep(100); counter++; if (counter == 50) break; } catch (InterruptedException e) { } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) isRunning = true; } } if (counter == 50) { linkedDatFile.setDrawSelection(false); try { new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor m) throws InvocationTargetException, InterruptedException { try { m.beginTask(I18n.VM_Selecting, IProgressMonitor.UNKNOWN); boolean isRunning = true; while (isRunning) { try { Thread.sleep(100); } catch (InterruptedException e) { } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) isRunning = true; } if (m.isCanceled()) { dialogCanceled.set(true); } } } finally { if (m.isCanceled()) { restoreSelection(); } else { backupSelectionClear(); } m.done(); } } }); }catch (InvocationTargetException consumed) { } catch (InterruptedException consumed) { } linkedDatFile.setDrawSelection(true); } } } if (addSomething) { TreeSet<Vertex> nearVertices = new TreeSet<Vertex>(); TreeSet<Vertex> nearVertices2 = new TreeSet<Vertex>(); float zoom = c3d.getZoom(); NLogger.debug(getClass(), zoom); BigDecimal EPSILON; EPSILON = new BigDecimal(".0005"); //$NON-NLS-1$ EPSILON = EPSILON.multiply(EPSILON, Threshold.mc).multiply(EPSILON, Threshold.mc).multiply(new BigDecimal(3)).divide(new BigDecimal(zoom), Threshold.mc); NLogger.debug(getClass(), "EPSILON around selection is {0}", EPSILON); //$NON-NLS-1$ for (Vertex v : selectedVertices) { Vector3d v1 = new Vector3d(v); boolean isNear = false; for (Vertex key : nearVertices2) { Vector3d v2 = new Vector3d(key); BigDecimal dist = Vector3d.distSquare(v1, v2); if (dist.compareTo(EPSILON) < 0f) { isNear = true; break; } } nearVertices2.add(v); if (!isNear) { nearVertices.add(v); } } selectedVertices.clear(); selectedVertices.addAll(nearVertices); } else if (Editor3DWindow.getWindow().isMovingAdjacentData() && Editor3DWindow.getWindow().getWorkingType() == ObjectMode.VERTICES) { { HashMap<GData, Integer> occurMap = new HashMap<GData, Integer>(); for (Vertex vertex : selectedVertices) { Set<VertexManifestation> occurences = vertexLinkedToPositionInFile.get(vertex); if (occurences == null) continue; for (VertexManifestation vm : occurences) { GData g = vm.getGdata(); int val = 1; if (occurMap.containsKey(g)) { val = occurMap.get(g); val++; } occurMap.put(g, val); switch (g.type()) { case 2: GData2 line = (GData2) g; if (val == 2) { selectedLines.add(line); selectedData.add(g); } break; case 3: GData3 triangle = (GData3) g; if (val == 3) { selectedTriangles.add(triangle); selectedData.add(g); } break; case 4: GData4 quad = (GData4) g; if (val == 4) { selectedQuads.add(quad); selectedData.add(g); } break; case 5: GData5 condline = (GData5) g; if (val == 4) { selectedCondlines.add(condline); selectedData.add(g); } break; } } } } } return needRayTest; } /** * ONLY FOR SELECT SUBFILES * @param c3d */ private synchronized void selectVertices2(final Composite3D c3d) { final boolean noTrans = Editor3DWindow.getWindow().hasNoTransparentSelection(); final boolean noCondlineVerts = !c3d.isShowingCondlineControlPoints(); final Vector4f selectionStart = new Vector4f(c3d.getSelectionStart()); final Vector4f selectionWidth = new Vector4f(c3d.getSelectionWidth()); final Vector4f selectionHeight = new Vector4f(c3d.getSelectionHeight()); final Vector4f selectionDepth; boolean needRayTest = false; if (Math.abs(selectionWidth.x) < 0.001f && Math.abs(selectionWidth.y) < 0.001f && Math.abs(selectionWidth.z) < 0.001f) needRayTest = true; if (Math.abs(selectionHeight.x) < 0.001f && Math.abs(selectionHeight.y) < 0.001f && Math.abs(selectionHeight.z) < 0.001f) needRayTest = true; if (needRayTest) { Vector4f zAxis4f = new Vector4f(0, 0, c3d.hasNegDeterminant() ^ c3d.isWarpedSelection() ? -1f : 1f, 1f); Matrix4f ovr_inverse2 = Matrix4f.invert(c3d.getRotation(), null); Matrix4f.transform(ovr_inverse2, zAxis4f, zAxis4f); selectionDepth = (Vector4f) new Vector4f(zAxis4f.x, zAxis4f.y, zAxis4f.z, 0f).normalise(); selectionDepth.w = 1f; final float discr = 1f / c3d.getZoom(); final long complexity = c3d.isShowingHiddenVertices() ? vertexLinkedToPositionInFile.size() : vertexLinkedToPositionInFile.size() * ((long) triangles.size() + (long) quads.size()); if (complexity < View.NUM_CORES * 100L) { for (Vertex vertex : vertexLinkedToPositionInFile.keySet()) { if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; MathHelper.crossProduct(selectionDepth, Vector4f.sub(vertex.toVector4f(), selectionStart, null), selectionWidth); if (selectionWidth.x * selectionWidth.x + selectionWidth.y * selectionWidth.y + selectionWidth.z * selectionWidth.z < discr) { selectVertices2_helper(c3d, vertex, selectionDepth, powerRay, noTrans); } } } else { // Multithreaded selection for many faces backupSelection(); final int chunks = View.NUM_CORES; final Thread[] threads = new Thread[chunks]; final AtomicBoolean dialogCanceled = new AtomicBoolean(false); final Vertex[] verts = vertexLinkedToPositionInFile.keySet().toArray(new Vertex[0]); final int iterations = verts.length; int lastend = 0; for (int j = 0; j < chunks; ++j) { final int[] i = new int[1]; final int[] start = new int[] { lastend }; lastend = Math.round(iterations / chunks * (j + 1)); final int[] end = new int[] { lastend }; if (j == chunks - 1) { end[0] = iterations; } i[0] = j; threads[j] = new Thread(new Runnable() { @Override public void run() { final PowerRay powerRay = new PowerRay(); int s = start[0]; int e = end[0]; Vector4f result = new Vector4f(); for (int k = s; k < e; k++) { Vertex vertex = verts[k]; if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; MathHelper.crossProduct(selectionDepth, Vector4f.sub(vertex.toVector4f(), selectionStart, null), result); if (result.x * result.x + result.y * result.y + result.z * result.z < discr) { if (dialogCanceled.get()) return; selectVertices2_helper(c3d, vertex, selectionDepth, powerRay, noTrans); } } } }); threads[j].start(); } boolean isRunning = true; int counter = 0; while (isRunning) { try { Thread.sleep(100); counter++; if (counter == 50) break; } catch (InterruptedException e) { } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) isRunning = true; } } if (counter == 50) { linkedDatFile.setDrawSelection(false); try { new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor m) throws InvocationTargetException, InterruptedException { try { m.beginTask(I18n.VM_Selecting, IProgressMonitor.UNKNOWN); boolean isRunning = true; while (isRunning) { try { Thread.sleep(100); } catch (InterruptedException e) { } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) isRunning = true; } if (m.isCanceled()) { dialogCanceled.set(true); } } } finally { if (m.isCanceled()) { restoreSelection(); } else { backupSelectionClear(); } m.done(); } } }); }catch (InvocationTargetException consumed) { } catch (InterruptedException consumed) { } linkedDatFile.setDrawSelection(true); } } } else { selectionDepth = new Vector4f(); MathHelper.crossProduct(selectionHeight, selectionWidth, selectionDepth); selectionDepth.w = 0f; selectionDepth.normalise(); if (c3d.hasNegDeterminant() ^ c3d.isWarpedSelection()) { selectionDepth.negate(); } selectionDepth.w = 1f; final long complexity = c3d.isShowingHiddenVertices() ? vertexLinkedToPositionInFile.size() : vertexLinkedToPositionInFile.size() * ((long) triangles.size() + (long) quads.size()); if (complexity < View.NUM_CORES * 100L) { float[][] A = new float[3][3]; float[] b = new float[3]; for (Vertex vertex : vertexLinkedToPositionInFile.keySet()) { if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; A[0][0] = selectionWidth.x; A[1][0] = selectionWidth.y; A[2][0] = selectionWidth.z; A[0][1] = selectionHeight.x; A[1][1] = selectionHeight.y; A[2][1] = selectionHeight.z; A[0][2] = selectionDepth.x; A[1][2] = selectionDepth.y; A[2][2] = selectionDepth.z; b[0] = vertex.x - selectionStart.x; b[1] = vertex.y - selectionStart.y; b[2] = vertex.z - selectionStart.z; b = MathHelper.gaussianElimination(A, b); if (b[0] <= 1f && b[0] >= 0f && b[1] >= 0f && b[1] <= 1f) { selectVertices2_helper(c3d, vertex, selectionDepth, powerRay, noTrans); } } } else { // Multithreaded selection for many faces backupSelection(); final int chunks = View.NUM_CORES; final Thread[] threads = new Thread[chunks]; final AtomicBoolean dialogCanceled = new AtomicBoolean(false); final Vertex[] verts = vertexLinkedToPositionInFile.keySet().toArray(new Vertex[0]); final int iterations = verts.length; int lastend = 0; for (int j = 0; j < chunks; ++j) { final int[] i = new int[1]; final int[] start = new int[] { lastend }; lastend = Math.round(iterations / chunks * (j + 1)); final int[] end = new int[] { lastend }; if (j == chunks - 1) { end[0] = iterations; } i[0] = j; threads[j] = new Thread(new Runnable() { @Override public void run() { final PowerRay powerRay = new PowerRay(); int s = start[0]; int e = end[0]; float[][] A = new float[3][3]; float[] b = new float[3]; for (int k = s; k < e; k++) { Vertex vertex = verts[k]; if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; A[0][0] = selectionWidth.x; A[1][0] = selectionWidth.y; A[2][0] = selectionWidth.z; A[0][1] = selectionHeight.x; A[1][1] = selectionHeight.y; A[2][1] = selectionHeight.z; A[0][2] = selectionDepth.x; A[1][2] = selectionDepth.y; A[2][2] = selectionDepth.z; b[0] = vertex.x - selectionStart.x; b[1] = vertex.y - selectionStart.y; b[2] = vertex.z - selectionStart.z; b = MathHelper.gaussianElimination(A, b); if (b[0] <= 1f && b[0] >= 0f && b[1] >= 0f && b[1] <= 1f) { if (dialogCanceled.get()) return; selectVertices2_helper(c3d, vertex, selectionDepth, powerRay, noTrans); } } } }); threads[j].start(); } boolean isRunning = true; int counter = 0; while (isRunning) { try { Thread.sleep(100); counter++; if (counter == 50) break; } catch (InterruptedException e) { } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) isRunning = true; } } if (counter == 50) { linkedDatFile.setDrawSelection(false); try { new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor m) throws InvocationTargetException, InterruptedException { try { m.beginTask(I18n.VM_Selecting, IProgressMonitor.UNKNOWN); boolean isRunning = true; while (isRunning) { try { Thread.sleep(100); } catch (InterruptedException e) { } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) isRunning = true; } if (m.isCanceled()) { dialogCanceled.set(true); } } } finally { if (m.isCanceled()) { restoreSelection(); } else { backupSelectionClear(); } m.done(); } } }); }catch (InvocationTargetException consumed) { } catch (InterruptedException consumed) { } linkedDatFile.setDrawSelection(true); } } } } private void selectVertices_helper(final Composite3D c3d, final Vertex vertex, final Vector4f rayDirection, PowerRay powerRay, boolean noTrans, boolean needRayTest) { final Set<GData3> tris = triangles.keySet(); final Set<GData4> qs = quads.keySet(); if (c3d.isShowingHiddenVertices()) { if (selectedVertices.contains(vertex)) { if (needRayTest || c3d.getKeys().isAltPressed()) { selectedVertices.remove(vertex); } } else { selectedVertices.add(vertex); if (Editor3DWindow.getWindow().getWorkingType() == ObjectMode.VERTICES) lastSelectedVertex = vertex; } } else { final Vector4f point = vertex.toVector4f(); boolean vertexIsShown = true; for (GData3 triangle : tris) { if (noTrans && triangle.a < 1f || hiddenData.contains(triangle)) continue; Vertex[] tverts = triangles.get(triangle); if (!tverts[0].equals(vertex) && !tverts[1].equals(vertex) && !tverts[2].equals(vertex)) { if (powerRay.TRIANGLE_INTERSECT(point, rayDirection, tverts[0], tverts[1], tverts[2])) { vertexIsShown = false; break; } } } if (vertexIsShown) { for (GData4 quad : qs) { if (noTrans && quad.a < 1f || hiddenData.contains(quad)) continue; Vertex[] tverts = quads.get(quad); if (!tverts[0].equals(vertex) && !tverts[1].equals(vertex) && !tverts[2].equals(vertex) && !tverts[3].equals(vertex)) { if (powerRay.TRIANGLE_INTERSECT(point, rayDirection, tverts[0], tverts[1], tverts[2]) || powerRay.TRIANGLE_INTERSECT(point, rayDirection, tverts[2], tverts[3], tverts[0])) { vertexIsShown = false; break; } } } } if (vertexIsShown) { if (selectedVertices.contains(vertex)) { if (needRayTest || c3d.getKeys().isAltPressed()) { selectedVertices.remove(vertex); } } else { selectedVertices.add(vertex); if (Editor3DWindow.getWindow().getWorkingType() == ObjectMode.VERTICES) lastSelectedVertex = vertex; } } } } private void selectVertices2_helper(final Composite3D c3d, final Vertex vertex, final Vector4f rayDirection, PowerRay powerRay, boolean noTrans) { final Set<GData3> tris = triangles.keySet(); final Set<GData4> qs = quads.keySet(); if (c3d.isShowingHiddenVertices()) { selectedVerticesForSubfile.add(vertex); } else { final Vector4f point = vertex.toVector4f(); boolean vertexIsShown = true; for (GData3 triangle : tris) { if (noTrans && triangle.a < 1f || hiddenData.contains(triangle)) continue; Vertex[] tverts = triangles.get(triangle); if (!tverts[0].equals(vertex) && !tverts[1].equals(vertex) && !tverts[2].equals(vertex)) { if (powerRay.TRIANGLE_INTERSECT(point, rayDirection, tverts[0], tverts[1], tverts[2])) { vertexIsShown = false; break; } } } if (vertexIsShown) { for (GData4 quad : qs) { if (noTrans && quad.a < 1f || hiddenData.contains(quad)) continue; Vertex[] tverts = quads.get(quad); if (!tverts[0].equals(vertex) && !tverts[1].equals(vertex) && !tverts[2].equals(vertex) && !tverts[3].equals(vertex)) { if (powerRay.TRIANGLE_INTERSECT(point, rayDirection, tverts[0], tverts[1], tverts[2]) || powerRay.TRIANGLE_INTERSECT(point, rayDirection, tverts[2], tverts[3], tverts[0])) { vertexIsShown = false; break; } } } } if (vertexIsShown) { selectedVerticesForSubfile.add(vertex); } } } private boolean isVertexVisible(Composite3D c3d, Vertex vertex, Vector4f rayDirection, boolean noTrans) { if (!c3d.isShowingHiddenVertices()) { final Vector4f point = vertex.toVector4f(); Vertex[] triQuadVerts = new Vertex[4]; int i = 0; for (GData3 triangle : triangles.keySet()) { if (noTrans && triangle.a < 1f || hiddenData.contains(triangle)) continue; i = 0; for (Vertex tvertex : triangles.get(triangle)) { triQuadVerts[i] = tvertex; i++; } if (!triQuadVerts[0].equals(vertex) && !triQuadVerts[1].equals(vertex) && !triQuadVerts[2].equals(vertex)) { if (powerRay.TRIANGLE_INTERSECT(point, rayDirection, triQuadVerts[0], triQuadVerts[1], triQuadVerts[2])) { return false; } } } for (GData4 quad : quads.keySet()) { if (noTrans && quad.a < 1f || hiddenData.contains(quad)) continue; i = 0; for (Vertex tvertex : quads.get(quad)) { triQuadVerts[i] = tvertex; i++; } if (!triQuadVerts[0].equals(vertex) && !triQuadVerts[1].equals(vertex) && !triQuadVerts[2].equals(vertex) && !triQuadVerts[3].equals(vertex)) { if (powerRay.TRIANGLE_INTERSECT(point, rayDirection, triQuadVerts[0], triQuadVerts[1], triQuadVerts[2]) || powerRay.TRIANGLE_INTERSECT(point, rayDirection, triQuadVerts[2], triQuadVerts[3], triQuadVerts[0])) { return false; } } } } return true; } public synchronized void selectLines(Composite3D c3d) { final boolean noTrans = Editor3DWindow.getWindow().hasNoTransparentSelection(); if (!c3d.getKeys().isCtrlPressed()) { clearSelection2(); } Set<Vertex> selectedVerticesTemp = Collections.newSetFromMap(new ThreadsafeTreeMap<Vertex, Boolean>()); selectedVerticesTemp.addAll(selectedVertices); selectedVertices.clear(); Vector4f selectionWidth = new Vector4f(c3d.getSelectionWidth()); Vector4f selectionHeight = new Vector4f(c3d.getSelectionHeight()); selectVertices(c3d, false); boolean allVertsFromLine = false; boolean needRayTest = false; if (Math.abs(selectionWidth.x) < 0.001f && Math.abs(selectionWidth.y) < 0.001f && Math.abs(selectionWidth.z) < 0.001f) needRayTest = true; if (Math.abs(selectionHeight.x) < 0.001f && Math.abs(selectionHeight.y) < 0.001f && Math.abs(selectionHeight.z) < 0.001f) needRayTest = true; if (selectedVertices.size() < 2 || needRayTest) { if (selectedVertices.size() == 1) { Vertex selectedVertex = selectedVertices.iterator().next(); for (GData2 line : lines.keySet()) { if (hiddenData.contains(line)) continue; for (Vertex tvertex : lines.get(line)) { if (selectedVertex.equals(tvertex)) { if (selectedLines.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedLines.remove(line); } else { selectedData.add(line); selectedLines.add(line); } } } } for (GData5 line : condlines.keySet()) { if (hiddenData.contains(line)) continue; for (Vertex tvertex : condlines.get(line)) { if (selectedVertex.equals(tvertex)) { if (selectedCondlines.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedCondlines.remove(line); } else { selectedData.add(line); selectedCondlines.add(line); } } } } } else { Vector4f selectionStart = new Vector4f(c3d.getSelectionStart()); Vector4f selectionDepth = new Vector4f(); Vector4f zAxis4f = new Vector4f(0, 0, 1f, 1f); Matrix4f ovr_inverse2 = Matrix4f.invert(c3d.getRotation(), null); Matrix4f.transform(ovr_inverse2, zAxis4f, zAxis4f); selectionDepth = (Vector4f) new Vector4f(zAxis4f.x, zAxis4f.y, zAxis4f.z, 0f).normalise(); selectionDepth.w = 1f; // selectionDepth = ray direction // Line from Ray // x(t) = s + dt float discr = 1f / c3d.getZoom(); float[] s = new float[3]; s[0] = selectionStart.x; s[1] = selectionStart.y; s[2] = selectionStart.z; float[] d = new float[3]; d[0] = selectionDepth.x; d[1] = selectionDepth.y; d[2] = selectionDepth.z; // Segment line // x(u) = a + (b - a)u // Difference // x(t) - x(u) = (s - a) + dt + (a - b)u // x(t) - x(u) = e + dt + f u float[] a = new float[3]; float[] e = new float[3]; float[] f = new float[3]; float[][] M = new float[2][2]; float[] b = new float[] { 0f, 0f }; // NLogger.debug(getClass(), discr); for (GData2 line : lines.keySet()) { if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : lines.get(line)) { if (allVertsFromLine) { f[0] = a[0] - tvertex.x; f[1] = a[1] - tvertex.y; f[2] = a[2] - tvertex.z; } else { a[0] = tvertex.x; a[1] = tvertex.y; a[2] = tvertex.z; e[0] = s[0] - a[0]; e[1] = s[1] - a[1]; e[2] = s[2] - a[2]; } allVertsFromLine = true; } M[0][0] = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; M[0][1] = d[0] * f[0] + d[1] * f[1] + d[2] * f[2]; M[1][0] = M[0][1]; M[1][1] = f[0] * f[0] + f[1] * f[1] + f[2] * f[2]; b[0] = -(d[0] * e[0] + d[1] * e[1] + d[2] * e[2]); // constant b[1] = -(e[0] * f[0] + e[1] * f[1] + e[2] * f[2]); // constant try { float[] solution = MathHelper.gaussianElimination(M, b); if (solution[1] >= 0f && solution[1] <= 1f) { float distanceSquared = (float) (Math.pow(e[0] + d[0] * solution[0] + f[0] * solution[1], 2) + Math.pow(e[1] + d[1] * solution[0] + f[1] * solution[1], 2) + Math.pow(e[2] + d[2] * solution[0] + f[2] * solution[1], 2)); if (distanceSquared < discr) { if (!isVertexVisible(c3d, new Vertex(MathHelper.getNearestPointToLineSegment(a[0], a[1], a[2], a[0] - f[0], a[1] - f[1], a[2] - f[2], s[0], s[1], s[2])), selectionDepth, noTrans)) continue; // Vertex[] v = lines.get(line); // if (!(isVertexVisible(c3d, v[0], selectionDepth, noTrans) && isVertexVisible(c3d, v[1], selectionDepth, noTrans))) // continue; if (selectedLines.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedLines.remove(line); } else { selectedData.add(line); selectedLines.add(line); } } } } catch (RuntimeException re1) { } } for (GData5 line : condlines.keySet()) { if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : condlines.get(line)) { if (allVertsFromLine) { f[0] = a[0] - tvertex.x; f[1] = a[1] - tvertex.y; f[2] = a[2] - tvertex.z; break; } else { a[0] = tvertex.x; a[1] = tvertex.y; a[2] = tvertex.z; e[0] = s[0] - a[0]; e[1] = s[1] - a[1]; e[2] = s[2] - a[2]; } allVertsFromLine = true; } M[0][0] = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; M[0][1] = d[0] * f[0] + d[1] * f[1] + d[2] * f[2]; M[1][0] = M[0][1]; M[1][1] = f[0] * f[0] + f[1] * f[1] + f[2] * f[2]; b[0] = -(d[0] * e[0] + d[1] * e[1] + d[2] * e[2]); // constant b[1] = -(e[0] * f[0] + e[1] * f[1] + e[2] * f[2]); // constant try { float[] solution = MathHelper.gaussianElimination(M, b); if (solution[1] >= 0f && solution[1] <= 1f) { float distanceSquared = (float) (Math.pow(e[0] + d[0] * solution[0] + f[0] * solution[1], 2) + Math.pow(e[1] + d[1] * solution[0] + f[1] * solution[1], 2) + Math.pow( e[2] + d[2] * solution[0] + f[2] * solution[1], 2)); if (distanceSquared < discr) { if (!isVertexVisible(c3d, new Vertex(MathHelper.getNearestPointToLineSegment(a[0], a[1], a[2], a[0] - f[0], a[1] - f[1], a[2] - f[2], s[0], s[1], s[2])), selectionDepth, noTrans)) continue; // Vertex[] v = condlines.get(line); // if (!(isVertexVisible(c3d, v[0], selectionDepth, noTrans) && isVertexVisible(c3d, v[1], selectionDepth, noTrans))) // continue; if (selectedCondlines.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedCondlines.remove(line); } else { selectedData.add(line); selectedCondlines.add(line); } } } } catch (RuntimeException re2) { } } } } else { for (GData2 line : lines.keySet()) { if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : lines.get(line)) { if (!selectedVertices.contains(tvertex)) break; if (allVertsFromLine) { if (selectedLines.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedLines.remove(line); } else { selectedData.add(line); selectedLines.add(line); } } allVertsFromLine = true; } } for (GData5 line : condlines.keySet()) { if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : condlines.get(line)) { if (!selectedVertices.contains(tvertex)) break; if (allVertsFromLine) { if (selectedCondlines.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedCondlines.remove(line); } else { selectedData.add(line); selectedCondlines.add(line); } } allVertsFromLine = true; } } } selectedVertices.clear(); selectedVertices.addAll(selectedVerticesTemp); } /** * ONLY FOR SELECT SUBFILES * @param c3d * @param selectionHeight * @param selectionWidth */ private synchronized void selectLines2(Composite3D c3d, Vector4f selectionWidth, Vector4f selectionHeight) { final boolean noTrans = Editor3DWindow.getWindow().hasNoTransparentSelection(); Set<Vertex> tmpVerts = Collections.newSetFromMap(new ThreadsafeTreeMap<Vertex, Boolean>()); tmpVerts.addAll(selectedVerticesForSubfile); selectedVerticesForSubfile.clear(); selectVertices2(c3d); boolean allVertsFromLine = false; boolean needRayTest = false; if (Math.abs(selectionWidth.x) < 0.001f && Math.abs(selectionWidth.y) < 0.001f && Math.abs(selectionWidth.z) < 0.001f) needRayTest = true; if (Math.abs(selectionHeight.x) < 0.001f && Math.abs(selectionHeight.y) < 0.001f && Math.abs(selectionHeight.z) < 0.001f) needRayTest = true; if (selectedVerticesForSubfile.size() < 2 || needRayTest) { if (selectedVerticesForSubfile.size() == 1) { Vertex selectedVertex = selectedVerticesForSubfile.iterator().next(); for (GData2 line : lines.keySet()) { if (hiddenData.contains(line)) continue; for (Vertex tvertex : lines.get(line)) { if (selectedVertex.equals(tvertex)) { selectedLinesForSubfile.add(line); } } } for (GData5 line : condlines.keySet()) { if (hiddenData.contains(line)) continue; for (Vertex tvertex : condlines.get(line)) { if (selectedVertex.equals(tvertex)) { selectedCondlinesForSubfile.add(line); } } } } else { Vector4f selectionStart = new Vector4f(c3d.getSelectionStart()); Vector4f selectionDepth = new Vector4f(); Vector4f zAxis4f = new Vector4f(0, 0, 1f, 1f); Matrix4f ovr_inverse2 = Matrix4f.invert(c3d.getRotation(), null); Matrix4f.transform(ovr_inverse2, zAxis4f, zAxis4f); selectionDepth = (Vector4f) new Vector4f(zAxis4f.x, zAxis4f.y, zAxis4f.z, 0f).normalise(); selectionDepth.w = 1f; // selectionDepth = ray direction // Line from Ray // x(t) = s + dt float discr = 1f / c3d.getZoom(); float[] s = new float[3]; s[0] = selectionStart.x; s[1] = selectionStart.y; s[2] = selectionStart.z; float[] d = new float[3]; d[0] = selectionDepth.x; d[1] = selectionDepth.y; d[2] = selectionDepth.z; // Segment line // x(u) = a + (b - a)u // Difference // x(t) - x(u) = (s - a) + dt + (a - b)u // x(t) - x(u) = e + dt + f u float[] a = new float[3]; float[] e = new float[3]; float[] f = new float[3]; float[][] M = new float[2][2]; float[] b = new float[] { 0f, 0f }; // NLogger.debug(getClass(), discr); for (GData2 line : lines.keySet()) { if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : lines.get(line)) { if (allVertsFromLine) { f[0] = a[0] - tvertex.x; f[1] = a[1] - tvertex.y; f[2] = a[2] - tvertex.z; } else { a[0] = tvertex.x; a[1] = tvertex.y; a[2] = tvertex.z; e[0] = s[0] - a[0]; e[1] = s[1] - a[1]; e[2] = s[2] - a[2]; } allVertsFromLine = true; } M[0][0] = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; M[0][1] = d[0] * f[0] + d[1] * f[1] + d[2] * f[2]; M[1][0] = M[0][1]; M[1][1] = f[0] * f[0] + f[1] * f[1] + f[2] * f[2]; b[0] = -(d[0] * e[0] + d[1] * e[1] + d[2] * e[2]); // constant b[1] = -(e[0] * f[0] + e[1] * f[1] + e[2] * f[2]); // constant try { float[] solution = MathHelper.gaussianElimination(M, b); if (solution[1] >= 0f && solution[1] <= 1f) { float distanceSquared = (float) (Math.pow(e[0] + d[0] * solution[0] + f[0] * solution[1], 2) + Math.pow(e[1] + d[1] * solution[0] + f[1] * solution[1], 2) + Math.pow( e[2] + d[2] * solution[0] + f[2] * solution[1], 2)); if (distanceSquared < discr) { if (!isVertexVisible(c3d, new Vertex(MathHelper.getNearestPointToLineSegment(a[0], a[1], a[2], a[0] - f[0], a[1] - f[1], a[2] - f[2], s[0], s[1], s[2])), selectionDepth, noTrans)) continue; // Vertex[] v = lines.get(line); // if (!(isVertexVisible(c3d, v[0], selectionDepth, noTrans) && isVertexVisible(c3d, v[1], selectionDepth, noTrans))) // continue; selectedLinesForSubfile.add(line); } } } catch (RuntimeException re1) { } } for (GData5 line : condlines.keySet()) { if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : condlines.get(line)) { if (allVertsFromLine) { f[0] = a[0] - tvertex.x; f[1] = a[1] - tvertex.y; f[2] = a[2] - tvertex.z; break; } else { a[0] = tvertex.x; a[1] = tvertex.y; a[2] = tvertex.z; e[0] = s[0] - a[0]; e[1] = s[1] - a[1]; e[2] = s[2] - a[2]; } allVertsFromLine = true; } M[0][0] = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; M[0][1] = d[0] * f[0] + d[1] * f[1] + d[2] * f[2]; M[1][0] = M[0][1]; M[1][1] = f[0] * f[0] + f[1] * f[1] + f[2] * f[2]; b[0] = -(d[0] * e[0] + d[1] * e[1] + d[2] * e[2]); // constant b[1] = -(e[0] * f[0] + e[1] * f[1] + e[2] * f[2]); // constant try { float[] solution = MathHelper.gaussianElimination(M, b); if (solution[1] >= 0f && solution[1] <= 1f) { float distanceSquared = (float) (Math.pow(e[0] + d[0] * solution[0] + f[0] * solution[1], 2) + Math.pow(e[1] + d[1] * solution[0] + f[1] * solution[1], 2) + Math.pow( e[2] + d[2] * solution[0] + f[2] * solution[1], 2)); if (distanceSquared < discr) { if (!isVertexVisible(c3d, new Vertex(MathHelper.getNearestPointToLineSegment(a[0], a[1], a[2], a[0] - f[0], a[1] - f[1], a[2] - f[2], s[0], s[1], s[2])), selectionDepth, noTrans)) continue; // Vertex[] v = condlines.get(line); // if (!(isVertexVisible(c3d, v[0], selectionDepth, noTrans) && isVertexVisible(c3d, v[1], selectionDepth, noTrans))) // continue; selectedCondlinesForSubfile.add(line); } } } catch (RuntimeException re2) { } } } } else { for (GData2 line : lines.keySet()) { if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : lines.get(line)) { if (!selectedVerticesForSubfile.contains(tvertex)) break; if (allVertsFromLine) { selectedLinesForSubfile.add(line); } allVertsFromLine = true; } } for (GData5 line : condlines.keySet()) { if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : condlines.get(line)) { if (!selectedVerticesForSubfile.contains(tvertex)) break; if (allVertsFromLine) { selectedCondlinesForSubfile.add(line); } allVertsFromLine = true; } } } selectedVerticesForSubfile.clear(); selectedVerticesForSubfile.addAll(tmpVerts); } public synchronized void selectFaces(Composite3D c3d, Event event) { if (!c3d.getKeys().isCtrlPressed()) { clearSelection2(); } Set<Vertex> selectedVerticesTemp = Collections.newSetFromMap(new ThreadsafeTreeMap<Vertex, Boolean>()); selectedVerticesTemp.addAll(selectedVertices); selectedVertices.clear(); boolean allVertsFromLine = false; Vector4f selectionWidth = new Vector4f(c3d.getSelectionWidth()); Vector4f selectionHeight = new Vector4f(c3d.getSelectionHeight()); selectVertices(c3d, false); boolean needRayTest = false; if (Math.abs(selectionWidth.x) < 0.001f && Math.abs(selectionWidth.y) < 0.001f && Math.abs(selectionWidth.z) < 0.001f) needRayTest = true; if (Math.abs(selectionHeight.x) < 0.001f && Math.abs(selectionHeight.y) < 0.001f && Math.abs(selectionHeight.z) < 0.001f) needRayTest = true; if (selectedVertices.size() < 2 || needRayTest) { if (selectedVertices.size() == 1) { Vertex selectedVertex = selectedVertices.iterator().next(); for (GData3 line : triangles.keySet()) { if (hiddenData.contains(line)) continue; for (Vertex tvertex : triangles.get(line)) { if (selectedVertex.equals(tvertex)) { if (selectedTriangles.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedTriangles.remove(line); } else { selectedData.add(line); selectedTriangles.add(line); } } } } for (GData4 line : quads.keySet()) { if (hiddenData.contains(line)) continue; for (Vertex tvertex : quads.get(line)) { if (selectedVertex.equals(tvertex)) { if (selectedQuads.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedQuads.remove(line); } else { selectedData.add(line); selectedQuads.add(line); } } } } } else { GData selection = selectFaces_helper(c3d, event); if (selection != null) { if (selection.type() == 4) { GData4 gd4 = (GData4) selection; if (selectedQuads.contains(gd4)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(gd4); if (needRayTest || c3d.getKeys().isAltPressed()) selectedQuads.remove(gd4); } else { selectedData.add(gd4); selectedQuads.add(gd4); } } else { GData3 gd3 = (GData3) selection; if (selectedTriangles.contains(gd3)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(gd3); if (needRayTest || c3d.getKeys().isAltPressed()) selectedTriangles.remove(gd3); } else { selectedData.add(gd3); selectedTriangles.add(gd3); } } } } } else { for (GData3 line : triangles.keySet()) { if (hiddenData.contains(line)) continue; allVertsFromLine = true; for (Vertex tvertex : triangles.get(line)) { if (!selectedVertices.contains(tvertex)) { allVertsFromLine = false; break; } } if (allVertsFromLine) { if (selectedTriangles.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedTriangles.remove(line); } else { selectedData.add(line); selectedTriangles.add(line); } } } for (GData4 line : quads.keySet()) { if (hiddenData.contains(line)) continue; allVertsFromLine = true; for (Vertex tvertex : quads.get(line)) { if (!selectedVertices.contains(tvertex)) { allVertsFromLine = false; break; } } if (allVertsFromLine) { if (selectedQuads.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedQuads.remove(line); } else { selectedData.add(line); selectedQuads.add(line); } } } } selectedVertices.clear(); selectedVertices.addAll(selectedVerticesTemp); } /** * ONLY FOR SELECT SUBFILES * @param c3d * @param event * @param selectionHeight * @param selectionWidth */ private synchronized void selectFaces2(Composite3D c3d, Event event, Vector4f selectionWidth, Vector4f selectionHeight) { Set<Vertex> selVert4sTemp = Collections.newSetFromMap(new ThreadsafeTreeMap<Vertex, Boolean>()); selVert4sTemp.addAll(selectedVerticesForSubfile); selectedVerticesForSubfile.clear(); selectVertices2(c3d); boolean allVertsFromLine = false; boolean needRayTest = false; if (Math.abs(selectionWidth.x) < 0.001f && Math.abs(selectionWidth.y) < 0.001f && Math.abs(selectionWidth.z) < 0.001f) needRayTest = true; if (Math.abs(selectionHeight.x) < 0.001f && Math.abs(selectionHeight.y) < 0.001f && Math.abs(selectionHeight.z) < 0.001f) needRayTest = true; if (selectedVerticesForSubfile.size() < 2 || needRayTest) { if (selectedVerticesForSubfile.size() == 1) { Vertex selectedVertex = selectedVerticesForSubfile.iterator().next(); for (GData3 line : triangles.keySet()) { if (hiddenData.contains(line)) continue; for (Vertex tvertex : triangles.get(line)) { if (selectedVertex.equals(tvertex)) { selectedTrianglesForSubfile.add(line); } } } for (GData4 line : quads.keySet()) { if (hiddenData.contains(line)) continue; for (Vertex tvertex : quads.get(line)) { if (selectedVertex.equals(tvertex)) { selectedQuadsForSubfile.add(line); } } } } else { GData selection = selectFaces_helper(c3d, event); if (selection != null) { if (selection.type() == 4) { GData4 gd4 = (GData4) selection; selectedQuadsForSubfile.add(gd4); } else { GData3 gd3 = (GData3) selection; selectedTrianglesForSubfile.add(gd3); } } } } else { for (GData3 line : triangles.keySet()) { if (hiddenData.contains(line)) continue; allVertsFromLine = true; for (Vertex tvertex : triangles.get(line)) { if (!selectedVerticesForSubfile.contains(tvertex)) { allVertsFromLine = false; break; } } if (allVertsFromLine) { selectedTrianglesForSubfile.add(line); } } for (GData4 line : quads.keySet()) { if (hiddenData.contains(line)) continue; allVertsFromLine = true; for (Vertex tvertex : quads.get(line)) { if (!selectedVerticesForSubfile.contains(tvertex)) { allVertsFromLine = false; break; } } if (allVertsFromLine) { selectedQuadsForSubfile.add(line); } } } selectedVerticesForSubfile.clear(); selectedVerticesForSubfile.addAll(selVert4sTemp); } private synchronized GData selectFaces_helper(Composite3D c3d, Event event) { final boolean noTrans = Editor3DWindow.getWindow().hasNoTransparentSelection(); PerspectiveCalculator perspective = c3d.getPerspectiveCalculator(); Matrix4f viewport_rotation = c3d.getRotation(); Vector4f zAxis4f = new Vector4f(0, 0, -1f, 1f); Matrix4f ovr_inverse2 = Matrix4f.invert(viewport_rotation, null); Matrix4f.transform(ovr_inverse2, zAxis4f, zAxis4f); Vector4f rayDirection = (Vector4f) new Vector4f(zAxis4f.x, zAxis4f.y, zAxis4f.z, 0f).normalise(); rayDirection.w = 1f; Vertex[] triQuadVerts = new Vertex[4]; int i = 0; Vector4f orig = perspective.get3DCoordinatesFromScreen(event.x, event.y); Vector4f point = new Vector4f(orig); double minDist = Double.MAX_VALUE; final double[] dist = new double[1]; GData result = null; for (GData3 triangle : triangles.keySet()) { if (hiddenData.contains(triangle)) continue; if (noTrans && triangle.a < 1f && !c3d.isShowingHiddenVertices()) continue; i = 0; for (Vertex tvertex : triangles.get(triangle)) { triQuadVerts[i] = tvertex; i++; } if (powerRay.TRIANGLE_INTERSECT(orig, rayDirection, triQuadVerts[0], triQuadVerts[1], triQuadVerts[2], point, dist)) { if (dist[0] < minDist) { if (triangle.isTriangle) minDist = dist[0]; if (triangle.isTriangle || result == null) result = triangle; } } } for (GData4 quad : quads.keySet()) { if (hiddenData.contains(quad)) continue; if (noTrans && quad.a < 1f && !c3d.isShowingHiddenVertices()) continue; i = 0; for (Vertex tvertex : quads.get(quad)) { triQuadVerts[i] = tvertex; i++; } if (powerRay.TRIANGLE_INTERSECT(orig, rayDirection, triQuadVerts[0], triQuadVerts[1], triQuadVerts[2], point, dist) || powerRay.TRIANGLE_INTERSECT(orig, rayDirection, triQuadVerts[2], triQuadVerts[3], triQuadVerts[0], point, dist)) { if (dist[0] < minDist) { minDist = dist[0]; result = quad; } } } return result; } public synchronized void selectWholeSubfiles() { HashSet<GData1> subfilesToAdd = new HashSet<GData1>(); for (GData g : selectedData) { subfilesToAdd.add(getSubfile(g)); } subfilesToAdd.remove(View.DUMMY_REFERENCE); for (GData1 g : subfilesToAdd) { removeSubfileFromSelection(g); } for (GData1 g : subfilesToAdd) { addSubfileToSelection(g); } } public void removeSubfileFromSelection(GData1 subf) { selectedData.remove(subf); selectedSubfiles.remove(subf); Set<VertexInfo> vis = lineLinkedToVertices.get(subf); if (vis == null) return; for (VertexInfo vertexInfo : vis) { selectedVertices.remove(vertexInfo.getVertex()); GData g = vertexInfo.getLinkedData(); selectedData.remove(g); switch (g.type()) { case 2: selectedLines.remove(g); break; case 3: selectedTriangles.remove(g); break; case 4: selectedQuads.remove(g); break; case 5: selectedCondlines.remove(g); break; default: break; } } } public void addSubfileToSelection(GData1 subf) { selectedData.add(subf); selectedSubfiles.add(subf); Set<VertexInfo> vis = lineLinkedToVertices.get(subf); if (vis == null) return; for (VertexInfo vertexInfo : vis) { selectedVertices.add(vertexInfo.getVertex()); GData g = vertexInfo.getLinkedData(); selectedData.add(g); switch (g.type()) { case 2: selectedLines.add((GData2) g); break; case 3: selectedTriangles.add((GData3) g); break; case 4: selectedQuads.add((GData4) g); break; case 5: selectedCondlines.add((GData5) g); break; default: break; } } } public synchronized void selectSubfiles(Composite3D c3d, Event event) { selectedVerticesForSubfile.clear(); selectedLinesForSubfile.clear(); selectedTrianglesForSubfile.clear(); selectedQuadsForSubfile.clear(); selectedCondlinesForSubfile.clear(); HashSet<GData1> backupSubfiles = new HashSet<GData1>(selectedSubfiles); if (!c3d.getKeys().isCtrlPressed()) { clearSelection2(); backupSubfiles.clear(); } backupSelection(); clearSelection(); { final Vector4f selectionWidth = new Vector4f(c3d.getSelectionWidth()); final Vector4f selectionHeight = new Vector4f(c3d.getSelectionHeight()); selectFaces2(c3d, event, selectionWidth, selectionHeight); selectLines2(c3d, selectionWidth, selectionHeight); } // Determine which subfiles were selected selectedData.addAll(selectedLinesForSubfile); selectedData.addAll(selectedTrianglesForSubfile); selectedData.addAll(selectedQuadsForSubfile); selectedData.addAll(selectedCondlinesForSubfile); selectedVerticesForSubfile.clear(); selectedLinesForSubfile.clear(); selectedTrianglesForSubfile.clear(); selectedQuadsForSubfile.clear(); selectedCondlinesForSubfile.clear(); if (NLogger.DEBUG) { NLogger.debug(getClass(), "Selected data:"); //$NON-NLS-1$ for (GData g : selectedData) { NLogger.debug(getClass(), g.toString()); } } NLogger.debug(getClass(), "Subfiles in selection:"); //$NON-NLS-1$ HashSet<GData1> subs = new HashSet<GData1>(); for (GData g : selectedData) { GData1 s = getSubfile(g); if (!View.DUMMY_REFERENCE.equals(s)) { subs.add(s); } } for (GData g : subs) { NLogger.debug(getClass(), g.toString()); } selectedData.clear(); NLogger.debug(getClass(), "Subfiles in selection, to add/remove:"); //$NON-NLS-1$ HashSet<GData1> subsToAdd = new HashSet<GData1>(); HashSet<GData1> subsToRemove = new HashSet<GData1>(); if (c3d.getKeys().isCtrlPressed()) { for (GData1 subf : backupSubfiles) { if (subs.contains(subf)) { subsToRemove.add(subf); } else { subsToAdd.add(subf); } } for (GData1 subf : subs) { if (!subsToRemove.contains(subf)) { subsToAdd.add(subf); } } } else { subsToAdd.addAll(subs); } restoreSelection(); NLogger.debug(getClass(), "Subfiles in selection (REMOVE)"); //$NON-NLS-1$ for (GData1 g : subsToRemove) { NLogger.debug(getClass(), g.toString()); removeSubfileFromSelection(g); } NLogger.debug(getClass(), "Subfiles in selection (ADD)"); //$NON-NLS-1$ for (GData1 g : subsToAdd) { NLogger.debug(getClass(), g.toString()); addSubfileToSelection(g); } } public Vector4f getSelectionCenter() { final Set<Vertex> objectVertices = Collections.newSetFromMap(new ThreadsafeTreeMap<Vertex, Boolean>()); objectVertices.addAll(selectedVertices); // 1. Object Based Selection for (GData2 line : selectedLines) { Vertex[] verts = lines.get(line); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } for (GData3 triangle : selectedTriangles) { Vertex[] verts = triangles.get(triangle); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } for (GData4 quad : selectedQuads) { Vertex[] verts = quads.get(quad); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } for (GData5 condline : selectedCondlines) { Vertex[] verts = condlines.get(condline); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } // 2. Subfile Based Selection if (!selectedSubfiles.isEmpty()) { for (GData1 subf : selectedSubfiles) { Set<VertexInfo> vis = lineLinkedToVertices.get(subf); if (vis == null) continue; for (VertexInfo vertexInfo : vis) { objectVertices.add(vertexInfo.getVertex()); } } } if (!objectVertices.isEmpty()) { float x = 0f; float y = 0f; float z = 0f; for (Vertex vertex : objectVertices) { x = x + vertex.x; y = y + vertex.y; z = z + vertex.z; } float count = objectVertices.size(); return new Vector4f(x / count, y / count, z / count, 1f); } else { return new Vector4f(0f, 0f, 0f, 1f); } } public void toggleTEXMAP() { toggleHelper("0 !: "); //$NON-NLS-1$ } public void toggleComment() { toggleHelper("0 // "); //$NON-NLS-1$ } private void toggleHelper(final String token) { final String token2 = token.substring(0, 4); HashBiMap<Integer, GData> dpl = linkedDatFile.getDrawPerLine_NOCLONE(); for (GData g : selectedData) { final GData b = g.getBefore(); final GData n = g.getNext(); final String oldStr = g.toString(); final String lineToParse; if (oldStr.startsWith(token)) { lineToParse = oldStr.substring(5); } else if (oldStr.startsWith(token2)) { lineToParse = oldStr.substring(4); } else { lineToParse = token + oldStr; } Integer line = dpl.getKey(g); if (remove(g)) { linkedDatFile.setDrawChainTail(b); } Set<String> alreadyParsed = new HashSet<String>(); alreadyParsed.add(linkedDatFile.getShortName()); GData pasted; if (StringHelper.isNotBlank(lineToParse)) { ArrayList<ParsingResult> result = DatParser.parseLine(lineToParse, -1, 0, 0.5f, 0.5f, 0.5f, 1.0f, View.DUMMY_REFERENCE, View.ID, View.ACCURATE_ID, linkedDatFile, false, alreadyParsed, false); pasted = result.get(0).getGraphicalData(); if (pasted == null) pasted = new GData0(lineToParse); } else { pasted = new GData0(lineToParse); } b.setNext(pasted); pasted.setNext(n); dpl.put(line, pasted); linkedDatFile.setDrawChainTail(dpl.getValue(dpl.size())); } } }
package org.objectweb.proactive.core.component; import org.objectweb.fractal.api.NoSuchInterfaceException; import org.objectweb.fractal.api.type.InterfaceType; import org.objectweb.proactive.core.ProActiveRuntimeException; import org.objectweb.proactive.core.component.controller.ComponentParametersController; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A bindings container. * This class stores the following bindings for a given component : * - thisComponent.clientInterface --> serverComponent.serverInterface * (it also takes in charge collective bindings, ie 1 client to serveral servers) * - thisParallelComponent.serverInterface --> serverComponents.serverInterface * (in the case of a parallel component, requests on a server port are forwarded to * the inner components) * * * @author Matthieu Morel */ public class Bindings implements Serializable { // In case of collective bindings, the interfaces of the collection can be : // 1. named (as in Fractal 2.0 spec) : they are mapped in clientInterfaceBindings according to their name // 2. anonymous : they are put in a list which is mapped in clientInterfaceBindings with the type name of the collective interface private HashMap clientInterfaceBindings; private HashMap parallelInternalClientInterfaceBindings; // key = interfaceName ; value = binding // if collective binding : key = interfaceName ; value = Vector (Binding objects) public Bindings() { clientInterfaceBindings = new HashMap(); } /** * @param binding the binding to add */ public void add(Binding binding) { try { InterfaceType client_itf_type = (InterfaceType) binding.getClientInterface() .getFcItfType(); if (client_itf_type.isFcCollectionItf()) { addCollectiveBindingOnExternalClientItf(binding); } else if (((ComponentParametersController) binding.getClientInterface() .getFcItfOwner().getFcInterface(Constants.COMPONENT_PARAMETERS_CONTROLLER)).getComponentParameters() .getHierarchicalType().equals(Constants.PARALLEL)) { addCollectiveBindingOnInternalClientItf(binding); } else { clientInterfaceBindings.put(client_itf_type.getFcItfName(), binding); } } catch (NoSuchInterfaceException nsie) { throw new ProActiveRuntimeException("interface not found : " + nsie.getMessage()); } } // returns either a Binding or a List of Binding objects (collection interface case) /** * removes the binding on the given client interface */ public Object remove(String clientItfName) { return clientInterfaceBindings.remove(clientItfName); } public Object get(String clientItfName) { return clientInterfaceBindings.get(clientItfName); } /** * tests if binding exists on the given interface * @param clientItfName the client inteface to check * @return true if binding exists */ public boolean containsBindingOn(String clientItfName) { return clientInterfaceBindings.containsKey(clientItfName); } // /** // * returns all the bindings, including the bindings for the // * collective interfaces (meaning there can be several Binding objects // * with the same client interface) // * // * @return all the bindings // */ // public Binding[] getBindings() { // Vector list_of_bindings = new Vector(); // Enumeration enum = clientInterfaceBindings.elements(); // while (enum.hasMoreElements()) { // Object elem = enum.nextElement(); // if (elem instanceof Collection) { // // a collective binding : add all the elements of the corresponding collection // list_of_bindings.addAll((Collection) elem); // } else { // list_of_bindings.addElement(elem); // list_of_bindings.trimToSize(); // return (Binding[]) (list_of_bindings.toArray(new Binding[list_of_bindings.size()])); /** * Returns the names of the external client bindings for this component. * In case of a collective interface, the names of each of its constituing interfaces are not returned ; * only the name of the collective interface is returned. */ public String[] getExternalClientBindings() { return (String[]) clientInterfaceBindings.keySet().toArray(new String[clientInterfaceBindings.keySet() .size()]); } private void addCollectiveBinding(Map bindingsTable, Binding binding) { String client_itf_name = binding.getClientInterfaceName(); if (binding.getClientInterface().getFcItfName().equals(client_itf_name)) { if (bindingsTable.containsKey(client_itf_name)) { // there should be a List for containing the bindings associated ((List) bindingsTable.get(client_itf_name)).add(binding); } else { // we create a List for keeping the bindings ArrayList bindings_collection = new ArrayList(); bindings_collection.add(binding); bindingsTable.put(client_itf_name, bindings_collection); } } else { bindingsTable.put(client_itf_name, binding); } } private void addCollectiveBindingOnExternalClientItf(Binding binding) { addCollectiveBinding(clientInterfaceBindings, binding); } private void addCollectiveBindingOnInternalClientItf(Binding binding) { if (parallelInternalClientInterfaceBindings == null) { parallelInternalClientInterfaceBindings = new HashMap(); } addCollectiveBinding(parallelInternalClientInterfaceBindings, binding); } }
package org.plantuml.idea.toolwindow; import com.intellij.find.EditorSearchSession; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ColoredSideBorder; import com.intellij.ui.JBColor; import com.intellij.ui.PopupHandler; import com.intellij.ui.scale.ScaleContext; import com.intellij.ui.scale.ScaleType; import com.intellij.util.ui.ImageUtil; import com.intellij.util.ui.JBImageIcon; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.plantuml.idea.action.context.*; import org.plantuml.idea.lang.settings.PlantUmlSettings; import org.plantuml.idea.rendering.ImageItem; import org.plantuml.idea.rendering.RenderRequest; import org.plantuml.idea.rendering.RenderResult; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.LinkedHashMap; public class PlantUmlImageLabel extends JLabel { private static final AnAction[] AN_ACTIONS = { new SaveDiagramToFileContextAction(), new CopyDiagramToClipboardContextAction(), Separator.getInstance(), new CopyDiagramAsTxtToClipboardContextAction(), new CopyDiagramAsUnicodeTxtToClipboardContextAction(), Separator.getInstance(), new CopyDiagramAsLatexToClipboardContextAction(), new CopyDiagramAsTikzCodeToClipboardContextAction(), Separator.getInstance(), new ExternalOpenDiagramAsPNGAction(), new ExternalOpenDiagramAsSVGAction(), Separator.getInstance(), new CopyPlantUmlServerLinkContextAction() }; private static final ActionPopupMenu ACTION_POPUP_MENU = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.UNKNOWN, new ActionGroup() { @NotNull @Override public AnAction[] getChildren(@Nullable AnActionEvent e) { return AN_ACTIONS; } }); private static Logger logger = Logger.getInstance(PlantUmlImageLabel.class); private final Project project; private final RenderResult renderResult; private RenderRequest renderRequest; private ImageItem imageWithData; private Image originalImage; private FileEditorManager fileEditorManager; private LocalFileSystem localFileSystem; public PlantUmlImageLabel(Project project, JPanel parent, ImageItem imageWithData, int i, RenderRequest renderRequest, RenderResult renderResult, FileEditorManager fileEditorManager, LocalFileSystem localFileSystem) { this.imageWithData = imageWithData; this.project = project; this.renderResult = renderResult; setup(parent, this.imageWithData, i, renderRequest); this.fileEditorManager = fileEditorManager; this.localFileSystem = localFileSystem; } public ImageItem getImageWithData() { return imageWithData; } public int getPage() { return imageWithData.getPage(); } public RenderRequest getRenderRequest() { return renderRequest; } public void setup(JPanel parent, @NotNull ImageItem imageWithData, int i, RenderRequest renderRequest) { setOpaque(true); setBackground(JBColor.WHITE); if (imageWithData.hasImage()) { setDiagram(parent, imageWithData, renderRequest, this); } else { setText("page not rendered, probably plugin error, please report it and try to hit reload"); } this.renderRequest = renderRequest; } private void setDiagram(JPanel parent, @NotNull final ImageItem imageItem, RenderRequest renderRequest, final JLabel label) { originalImage = imageItem.getImage(); Image scaledImage; ScaleContext ctx = ScaleContext.create(parent); scaledImage = ImageUtil.ensureHiDPI(originalImage, ctx); // scaledImage = ImageLoader.scaleImage(scaledImage, ctx.getScale(JBUI.ScaleType.SYS_SCALE)); label.setIcon(new JBImageIcon(scaledImage)); label.addMouseListener(new PopupHandler() { @Override public void invokePopup(Component comp, int x, int y) { ACTION_POPUP_MENU.getComponent().show(comp, x, y); } }); //Removing all children from image label and creating transparent buttons for each item with url label.removeAll(); boolean showUrlLinksBorder = PlantUmlSettings.getInstance().isShowUrlLinksBorder(); for (ImageItem.LinkData linkData : imageItem.getLinks()) { JLabel button = new JLabel(); if (showUrlLinksBorder) { button.setBorder(new ColoredSideBorder(Color.RED, Color.RED, Color.RED, Color.RED, 1)); } Rectangle area = linkData.getClickArea(); int tolerance = 1; double scale = ctx.getScale(ScaleType.SYS_SCALE); int x = (int) ((double) area.x / scale) - 2 * tolerance; int width = (int) ((area.width) / scale) + 4 * tolerance; int y = (int) (area.y / scale); int height = (int) ((area.height) / scale) + 5 * tolerance; area = new Rectangle(x, y, width, height); button.setLocation(area.getLocation()); button.setSize(area.getSize()); button.setCursor(new Cursor(Cursor.HAND_CURSOR)); //When user clicks on item, url is opened in default system browser button.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { long start = System.currentTimeMillis(); String text = linkData.getText(); try { if (linkData.isLink()) { if (isWebReferenceUrl(text)) { Desktop.getDesktop().browse(URI.create(text)); } else { if (openFile(new File(renderRequest.getBaseDir(), text))) return; navigator.findNextSourceAndNavigate(text); } } else { navigator.findNextSourceAndNavigate(text); } } catch ( Exception ex) { logger.warn(ex); } logger.debug("mousePressed ", (System.currentTimeMillis() - start), "ms"); } }); label.add(button); } } LinkNavigator navigator = new LinkNavigator(); class LinkNavigator { public String lastText = ""; public File lastFile = null; private int lastIndex = 0; private void findNextSourceAndNavigate(String text) { boolean continuing = continuing(text); if (!continuing) { reset(); } if (continuing) { if (renderResult.includedFilesContains(lastFile)) { if (navigateToIncludedFile(text)) { return; } } else { if (navigateToEditor(text, renderRequest.getSourceFile())) { return; } reset(); if (navigateToIncludedFile(text)) { return; } } } reset(); if (navigateToEditor(text, renderRequest.getSourceFile())) { return; } if (navigateToIncludedFile(text)) { return; } } private boolean continuing(String text) { return lastText.equals(text) && (FileUtil.filesEqual(lastFile, renderRequest.getSourceFile()) || renderResult.includedFilesContains(lastFile) ); } private void reset() { lastIndex = 0; lastFile = null; lastText = ""; } private boolean navigateToIncludedFile(String text) { LinkedHashMap<File, Long> includedFiles = renderResult.getIncludedFiles(); ArrayList<File> files = new ArrayList<>(includedFiles.keySet()); int from = 0; if (lastFile != null) { from = files.indexOf(lastFile); } for (int j = from; j < files.size(); j++) { File file = files.get(j); if (navigateToEditor(text, file)) { return true; } lastIndex = 0; } return false; } private boolean navigateToEditor(String text, File file) { VirtualFile virtualFile = localFileSystem.findFileByPath(file.getAbsolutePath()); if (virtualFile != null) { Document document = FileDocumentManager.getInstance().getDocument(virtualFile); if (document != null) { String documentText = document.getText(); int i = documentText.indexOf(text, lastIndex); if (i >= 0) { return navigateToEditor(file, virtualFile, text, i); } } } return false; } private boolean navigateToEditor(File file, VirtualFile virtualFile, String text, int i) { FileEditor[] fileEditors = fileEditorManager.openFile(virtualFile, true, true); if (fileEditors.length != 0) { FileEditor fileEditor = fileEditors[0]; if (fileEditor instanceof TextEditor) { Editor editor = ((TextEditor) fileEditor).getEditor(); editor.getCaretModel().moveToOffset(i); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().setSelection(i, i + text.length()); if (PlantUmlSettings.getInstance().isLinkOpensSearchBar()) { EditorSearchSession editorSearchSession = EditorSearchSession.get(editor); if (editorSearchSession != null) { if (!text.equals(editorSearchSession.getTextInField())) { editorSearchSession.setTextInField(text); } } else { AnAction find = ActionManager.getInstance().getAction("Find"); if (find != null) { DataContext dataContext = DataManager.getInstance().getDataContext(editor.getComponent()); AnActionEvent anActionEvent = AnActionEvent.createFromDataContext("plantuml image", find.getTemplatePresentation(), dataContext); find.actionPerformed(anActionEvent); } } } } } lastFile = file; lastText = text; lastIndex = i + text.length(); return true; } @Override public String toString() { return "LinkNavigator{" + "lastText='" + lastText + '\'' + ", lastFile=" + lastFile + ", lastIndex=" + lastIndex + '}'; } } private boolean openFile(File file) { if (file.exists()) { VirtualFile virtualFile = localFileSystem.findFileByPath(file.getAbsolutePath()); if (virtualFile == null) { return false; } FileEditor[] fileEditors = fileEditorManager.openFile(virtualFile, true, true); return fileEditors.length > 0; } return false; } public static boolean isWebReferenceUrl(String url) { return url.startsWith("www.") || url.startsWith("http: } public Image getOriginalImage() { return originalImage; } }
package pitt.search.semanticvectors; import java.lang.IllegalArgumentException; import java.io.IOException; import java.util.Hashtable; import java.util.Enumeration; import java.util.Random; import org.apache.lucene.index.*; import org.apache.lucene.analysis.standard.StandardAnalyzer; import java.util.LinkedList; import java.io.IOException; /** * Command line utility for creating bilingual semantic vector indexes. */ public class BuildBilingualIndex{ // These can be modified with command line arguments. static int seedLength = 20; static int nonAlphabet = 0; static int minFreq = 10; /** * Prints the following usage message: * <code> * <br> BuildBilingualIndex class in package pitt.search.semanticvectors * <br> Usage: java pitt.search.semanticvectors.BuildBilingualIndex PATH_TO_LUCENE_INDEX LANG1 LANG2 * <br> BuildBilingualIndex creates files termvectors_LANGn.bin and docvectors_LANGn.bin, * <br> in local directory, where LANG1 and LANG2 are obtained from fields in index. * </code> */ public static void usage(){ String usageMessage = "\nBuildBilingualIndex class in package pitt.search.semanticvectors" + "\nUsage: java pitt.search.semanticvectors.BuildBilingualIndex " + "PATH_TO_LUCENE_INDEX LANG1 LANG2" + "\nBuildBilingualIndex creates files termvectors_LANGn.bin and docvectors_LANGn.bin," + "\nin local directory, where LANG1 and LANG2 are obtained from fields in index."; System.out.println(usageMessage); } /** * Builds term vector and document vector stores from a Lucene index. * @param args * @see BuildBilingualIndex#usage */ public static void main (String[] args) throws IllegalArgumentException { try { args = Flags.parseCommandLineFlags(args); } catch (IllegalArgumentException e) { usage(); throw e; } // Only three arguments should remain, the path to Lucene index and the language pair. if (args.length != 3) { usage(); throw (new IllegalArgumentException("After parsing command line flags, there were " + args.length + " arguments, instead of the expected 3.")); } String luceneIndex = args[args.length - 3]; String lang1 = args[args.length - 2]; String lang2 = args[args.length - 1]; String termFile1 = "termvectors_" + lang1 + ".bin"; String termFile2 = "termvectors_" + lang2 + ".bin"; String docFile1 = "docvectors_" + lang1 + ".bin"; String docFile2 = "docvectors_" + lang2 + ".bin"; String[] fields1 = new String[] {"contents_" + lang1}; String[] fields2 = new String[] {"contents_" + lang2}; System.err.println("seedLength = " + Flags.seedlength); System.err.println("Vector length = " + Flags.dimension); System.err.println("Non-alphabet characters = " + Flags.maxnonalphabetchars); System.err.println("Minimum frequency = " + Flags.minfrequency); try{ TermVectorsFromLucene vecStore1 = new TermVectorsFromLucene(luceneIndex, Flags.seedlength, Flags.minfrequency, Flags.maxnonalphabetchars, null, fields1); VectorStoreWriter vecWriter = new VectorStoreWriter(); System.err.println("Writing term vectors to " + termFile1); vecWriter.WriteVectors(termFile1, vecStore1); DocVectors docVectors = new DocVectors(vecStore1); System.err.println("Writing doc vectors to " + docFile1); vecWriter.WriteVectors(docFile1, docVectors.makeWriteableVectorStore()); VectorStore basicDocVectors = vecStore1.getBasicDocVectors(); System.out.println("Keeping basic doc vectors, number: " + basicDocVectors.getNumVectors()); TermVectorsFromLucene vecStore2 = new TermVectorsFromLucene(luceneIndex, Flags.seedlength, Flags.minfrequency, Flags.maxnonalphabetchars, basicDocVectors, fields2); System.err.println("Writing term vectors to " + termFile2); vecWriter.WriteVectors(termFile2, vecStore2); docVectors = new DocVectors(vecStore2); System.err.println("Writing doc vectors to " + docFile2); vecWriter.WriteVectors(docFile2, docVectors.makeWriteableVectorStore()); } catch (IOException e) { e.printStackTrace(); } } }
package ru.thewizardplusplus.wizardbudget; import java.io.*; import java.util.*; import java.text.*; import javax.xml.parsers.*; import org.xmlpull.v1.*; import org.w3c.dom.*; import org.xml.sax.*; import android.content.*; import android.webkit.*; import android.database.sqlite.*; import android.database.*; import android.os.*; import android.util.*; public class BackupManager { public BackupManager(Context context) { this.context = context; } @JavascriptInterface public String backup() { String filename = ""; try { File directory = new File( Environment.getExternalStorageDirectory(), BACKUPS_DIRECTORY ); directory.mkdirs(); Date current_date = new Date(); SimpleDateFormat file_suffix_format = new SimpleDateFormat( "yyyy-MM-dd-HH-mm-ss", Locale.US ); String file_suffix = file_suffix_format.format(current_date); File file = new File( directory, "database_dump_" + file_suffix + ".xml" ); FileWriter writter = new FileWriter(file); try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(writter); serializer.setFeature( "http://xmlpull.org/v1/doc/features.html#indent-output", true ); serializer.startDocument("utf-8", true); serializer.startTag("", "budget"); serializer.attribute( "", "version", String.valueOf(BACKUP_VERSION) ); Settings settings = Settings.getCurrent(context); serializer.startTag("", "preferences"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_CREDIT_CARD_TAG ); serializer.attribute("", "value", settings.getCreditCardTag()); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_COLLECT_STATS ); serializer.attribute( "", "value", settings.isCollectStats() ? "true" : "false" ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_PARSE_SMS ); serializer.attribute( "", "value", settings.isParseSms() ? "true" : "false" ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_SMS_NUMBER_PATTERN ); serializer.attribute( "", "value", settings.getSmsNumberPatternString() ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_SMS_SPENDING_PATTERN ); serializer.attribute( "", "value", settings.getSmsSpendingPatternString() ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_SMS_SPENDING_COMMENT ); serializer.attribute( "", "value", settings.getSmsSpendingComment() ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_SMS_INCOME_PATTERN ); serializer.attribute( "", "value", settings.getSmsIncomePatternString() ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_SMS_INCOME_COMMENT ); serializer.attribute( "", "value", settings.getSmsIncomeComment() ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_SMS_RESIDUE_PATTERN ); serializer.attribute( "", "value", settings.getSmsResiduePatternString() ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_SMS_NEGATIVE_CORRECTION_COMMENT ); serializer.attribute( "", "value", settings.getSmsNegativeCorrectionComment() ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_SMS_POSITIVE_CORRECTION_COMMENT ); serializer.attribute( "", "value", settings.getSmsPositiveCorrectionComment() ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_SAVE_BACKUP_TO_DROPBOX ); serializer.attribute( "", "value", settings.isSaveBackupToDropbox() ? "true" : "false" ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_ANALYSIS_HARVEST ); serializer.attribute( "", "value", settings.isAnalysisHarvest() ? "true" : "false" ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_HARVEST_USERNAME ); serializer.attribute( "", "value", settings.getHarvestUsername() ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_HARVEST_SUBDOMAIN ); serializer.attribute( "", "value", settings.getHarvestSubdomain() ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_WORKING_OFF_LIMIT ); serializer.attribute( "", "value", String.valueOf(settings.getWorkingOffLimit()) ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_BACKUP_NOTIFICATION ); serializer.attribute( "", "value", settings.isBackupNotification() ? "true" : "false" ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_RESTORE_NOTIFICATION ); serializer.attribute( "", "value", settings.isRestoreNotification() ? "true" : "false" ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_SMS_PARSING_NOTIFICATION ); serializer.attribute( "", "value", settings.isSmsParsingNotification() ? "true" : "false" ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_SMS_IMPORT_NOTIFICATION ); serializer.attribute( "", "value", settings.isSmsImportNotification() ? "true" : "false" ); serializer.endTag("", "preference"); serializer.startTag("", "preference"); serializer.attribute( "", "name", Settings.SETTING_NAME_DROPBOX_NOTIFICATION ); serializer.attribute( "", "value", settings.isDropboxNotification() ? "true" : "false" ); serializer.endTag("", "preference"); serializer.endTag("", "preferences"); SQLiteDatabase database = Utils.getDatabase(context); serializer.startTag("", "spendings"); Cursor cursor = database.query( "spendings", new String[]{"timestamp", "amount", "comment"}, null, null, null, null, "timestamp" ); boolean moved = cursor.moveToFirst(); while (moved) { serializer.startTag("", "spending"); Date date = new Date(cursor.getLong(0) * 1000L); String formatted_date = XML_DATE_FORMAT.format(date); serializer.attribute("", "date", formatted_date); serializer.attribute( "", "amount", String.valueOf(cursor.getDouble(1)) ); serializer.attribute("", "comment", cursor.getString(2)); serializer.endTag("", "spending"); moved = cursor.moveToNext(); } serializer.endTag("", "spendings"); serializer.startTag("", "buys"); cursor = database.query( "buys", new String[]{"name", "cost", "priority", "status"}, null, null, null, null, "status, priority DESC" ); moved = cursor.moveToFirst(); while (moved) { serializer.startTag("", "buy"); serializer.attribute("", "name", cursor.getString(0)); serializer.attribute( "", "cost", String.valueOf(cursor.getDouble(1)) ); serializer.attribute( "", "priority", String.valueOf(cursor.getLong(2)) ); long status = cursor.getLong(3); serializer.attribute( "", "purchased", status == 0 ? "false" : "true" ); serializer.endTag("", "buy"); moved = cursor.moveToNext(); } serializer.endTag("", "buys"); database.close(); serializer.endTag("", "budget"); serializer.endDocument(); if (Settings.getCurrent(context).isBackupNotification()) { DateFormat notification_timestamp_format = DateFormat .getDateTimeInstance( DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US ); String notification_timestamp = notification_timestamp_format .format(current_date); Utils.showNotification( context, context.getString(R.string.app_name), "Backuped at " + notification_timestamp + ".", file ); } filename = file.getAbsolutePath(); } finally { writter.close(); } } catch (IOException exception) {} return filename; } public void restore(InputStream in) { String spending_sql = ""; String buy_sql = ""; try { Element budget = DocumentBuilderFactory .newInstance() .newDocumentBuilder() .parse(in) .getDocumentElement(); budget.normalize(); Settings settings = Settings.getCurrent(context); NodeList preference_list = budget.getElementsByTagName( "preference" ); for (int i = 0; i < preference_list.getLength(); i++) { if ( preference_list.item(i).getNodeType() == Node.ELEMENT_NODE ) { Element preference = (Element)preference_list.item(i); if ( !preference.hasAttribute("name") || !preference.hasAttribute("value") ) { continue; } String name = preference.getAttribute("name"); String value = preference.getAttribute("value"); boolean boolean_value = value.equals("true"); if (name.equals(Settings.SETTING_NAME_CREDIT_CARD_TAG)) { settings.setCreditCardTag(value); } else if (name.equals(Settings.SETTING_NAME_COLLECT_STATS)) { settings.setCollectStats(boolean_value); } else if (name.equals(Settings.SETTING_NAME_PARSE_SMS)) { settings.setParseSms(boolean_value); } else if ( name.equals(Settings.SETTING_NAME_SMS_NUMBER_PATTERN) ) { settings.setSmsNumberPattern(value); } else if ( name.equals(Settings.SETTING_NAME_SMS_SPENDING_PATTERN) ) { settings.setSmsSpendingPattern(value); } else if ( name.equals(Settings.SETTING_NAME_SMS_SPENDING_COMMENT) ) { settings.setSmsSpendingComment(value); } else if ( name.equals(Settings.SETTING_NAME_SMS_INCOME_PATTERN) ) { settings.setSmsIncomePattern(value); } else if ( name.equals(Settings.SETTING_NAME_SMS_INCOME_COMMENT) ) { settings.setSmsIncomeComment(value); } else if ( name.equals(Settings.SETTING_NAME_SMS_RESIDUE_PATTERN) ) { settings.setSmsResiduePattern(value); } else if ( name.equals(Settings.SETTING_NAME_SMS_NEGATIVE_CORRECTION_COMMENT) ) { settings.setSmsNegativeCorrectionComment(value); } else if ( name.equals(Settings.SETTING_NAME_SMS_POSITIVE_CORRECTION_COMMENT) ) { settings.setSmsPositiveCorrectionComment(value); } else if ( name.equals( Settings.SETTING_NAME_SAVE_BACKUP_TO_DROPBOX ) ) { settings.setSaveBackupToDropbox(boolean_value); } else if ( name.equals(Settings.SETTING_NAME_ANALYSIS_HARVEST) ) { settings.setAnalysisHarvest(boolean_value); } else if ( name.equals(Settings.SETTING_NAME_HARVEST_USERNAME) ) { settings.setHarvestUsername(value); } else if ( name.equals(Settings.SETTING_NAME_HARVEST_SUBDOMAIN) ) { settings.setHarvestSubdomain(value); } else if ( name.equals(Settings.SETTING_NAME_WORKING_OFF_LIMIT) ) { settings.setWorkingOffLimit(Double.valueOf(value)); } else if ( name.equals(Settings.SETTING_NAME_BACKUP_NOTIFICATION) ) { settings.setBackupNotification(boolean_value); } else if ( name.equals(Settings.SETTING_NAME_RESTORE_NOTIFICATION) ) { settings.setRestoreNotification(boolean_value); } else if ( name.equals( Settings.SETTING_NAME_SMS_PARSING_NOTIFICATION ) ) { settings.setSmsParsingNotification(boolean_value); } else if ( name.equals( Settings.SETTING_NAME_SMS_IMPORT_NOTIFICATION ) ) { settings.setSmsImportNotification(boolean_value); } else if ( name.equals(Settings.SETTING_NAME_DROPBOX_NOTIFICATION) ) { settings.setDropboxNotification(boolean_value); } } } settings.save(); NodeList spending_list = budget.getElementsByTagName("spending"); for (int i = 0; i < spending_list.getLength(); i++) { if (spending_list.item(i).getNodeType() == Node.ELEMENT_NODE) { Element spending = (Element)spending_list.item(i); if ( !spending.hasAttribute("date") || !spending.hasAttribute("amount") || !spending.hasAttribute("comment") ) { continue; } long timestamp = 0; try { Date date = XML_DATE_FORMAT.parse( spending.getAttribute("date") ); timestamp = date.getTime() / 1000L; } catch (java.text.ParseException exception) { continue; } if (!spending_sql.isEmpty()) { spending_sql += ","; } spending_sql += "(" + String.valueOf(timestamp) + "," + spending.getAttribute("amount") + "," + DatabaseUtils.sqlEscapeString( spending.getAttribute("comment") ) + ")"; } } NodeList buy_list = budget.getElementsByTagName("buy"); for (int i = 0; i < buy_list.getLength(); i++) { if (buy_list.item(i).getNodeType() == Node.ELEMENT_NODE) { Element buy = (Element)buy_list.item(i); if ( !buy.hasAttribute("name") || !buy.hasAttribute("cost") || !buy.hasAttribute("priority") || !buy.hasAttribute("purchased") ) { continue; } String status = buy.getAttribute("purchased").equals("false") ? "0" : "1"; if (!buy_sql.isEmpty()) { buy_sql += ","; } buy_sql += "(" + DatabaseUtils.sqlEscapeString( buy.getAttribute("name") ) + "," + buy.getAttribute("cost") + "," + buy.getAttribute("priority") + "," + status + ")"; } } } catch (ParserConfigurationException exception) { return; } catch (SAXException exception) { return; } catch (IOException exception) { return; } catch (DOMException exception) { return; } if (!spending_sql.isEmpty() || !buy_sql.isEmpty()) { SQLiteDatabase database = Utils.getDatabase(context); if (!spending_sql.isEmpty()) { database.execSQL("DELETE FROM spendings"); database.execSQL( "INSERT INTO spendings" + "(timestamp, amount, comment)" + "VALUES" + spending_sql ); } if (!buy_sql.isEmpty()) { database.execSQL("DELETE FROM buys"); database.execSQL( "INSERT INTO buys" + "(name, cost, priority, status)" + "VALUES" + buy_sql ); } database.close(); if (Settings.getCurrent(context).isRestoreNotification()) { Date current_date = new Date(); DateFormat notification_timestamp_format = DateFormat .getDateTimeInstance( DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US ); String notification_timestamp = notification_timestamp_format .format(current_date); Utils.showNotification( context, context.getString(R.string.app_name), "Restored at " + notification_timestamp + ".", null ); } } } private static final String BACKUPS_DIRECTORY = "#wizard-budget"; private static final long BACKUP_VERSION = 5; private static final SimpleDateFormat XML_DATE_FORMAT = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.US ); private Context context; }
package soot.jimple.infoflow.android; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import soot.Body; import soot.Local; import soot.MethodOrMethodContext; import soot.PackManager; import soot.RefType; import soot.Scene; import soot.SceneTransformer; import soot.SootClass; import soot.SootMethod; import soot.Transform; import soot.Type; import soot.Unit; import soot.Value; import soot.jimple.DefinitionStmt; import soot.jimple.IdentityStmt; import soot.jimple.InstanceInvokeExpr; import soot.jimple.IntConstant; import soot.jimple.InvokeExpr; import soot.jimple.ReturnVoidStmt; import soot.jimple.Stmt; import soot.jimple.infoflow.android.data.AndroidMethod; import soot.jimple.toolkits.callgraph.ReachableMethods; import soot.toolkits.graph.ExceptionalUnitGraph; import soot.toolkits.scalar.SimpleLiveLocals; import soot.toolkits.scalar.SmartLocalDefs; /** * Analyzes the classes in the APK file to find custom implementations of the * well-known Android callback and handler interfaces. * * @author Steven Arzt * */ public class AnalyzeJimpleClass { private final Set<String> entryPointClasses; private final Set<String> androidCallbacks; private final Map<String, Set<AndroidMethod>> callbackMethods = new HashMap<String, Set<AndroidMethod>>(); private final Map<String, Set<AndroidMethod>> callbackWorklist = new HashMap<String, Set<AndroidMethod>>(); private final Map<SootClass, Set<Integer>> layoutClasses = new HashMap<SootClass, Set<Integer>>(); public AnalyzeJimpleClass(Set<String> entryPointClasses) throws IOException { this.entryPointClasses = entryPointClasses; this.androidCallbacks = loadAndroidCallbacks(); } public AnalyzeJimpleClass(Set<String> entryPointClasses, Set<String> androidCallbacks) { this.entryPointClasses = entryPointClasses; this.androidCallbacks = new HashSet<String>(); } /** * Loads the set of interfaces that are used to implement Android callback * handlers from a file on disk * @return A set containing the names of the interfaces that are used to * implement Android callback handlers */ private Set<String> loadAndroidCallbacks() throws IOException { Set<String> androidCallbacks = new HashSet<String>(); BufferedReader rdr = null; try { rdr = new BufferedReader(new FileReader("AndroidCallbacks.txt")); String line; while ((line = rdr.readLine()) != null) if (!line.isEmpty()) androidCallbacks.add(line); } finally { if (rdr != null) rdr.close(); } return androidCallbacks; } /** * Collects the callback methods for all Android default handlers * implemented in the source code. * Note that this operation runs inside Soot, so this method only registers * a new phase that will be executed when Soot is next run */ public void collectCallbackMethods() { Transform transform = new Transform("wjtp.ajc", new SceneTransformer() { protected void internalTransform(String phaseName, @SuppressWarnings("rawtypes") Map options) { // Find the mappings between classes and layouts findClassLayoutMappings(); // Process the callback classes directly reachable from the // entry points for (String className : entryPointClasses) { SootClass sc = Scene.v().getSootClass(className); List<MethodOrMethodContext> methods = new ArrayList<MethodOrMethodContext>(); methods.addAll(sc.getMethods()); // Check for callbacks registered in the code analyzeRechableMethods(sc, methods); // Check for method overrides analyzeMethodOverrideCallbacks(sc); } System.out.println("Callback analysis done."); } }); PackManager.v().getPack("wjtp").add(transform); } /** * Incrementally collects the callback methods for all Android default * handlers implemented in the source code. This just processes the contents * of the worklist. * Note that this operation runs inside Soot, so this method only registers * a new phase that will be executed when Soot is next run */ public void collectCallbackMethodsIncremental() { Transform transform = new Transform("wjtp.ajc", new SceneTransformer() { protected void internalTransform(String phaseName, @SuppressWarnings("rawtypes") Map options) { // Process the worklist from last time System.out.println("Running incremental callback analysis for " + callbackWorklist.size() + " components..."); Map<String, Set<AndroidMethod>> workListCopy = new HashMap<String, Set<AndroidMethod>> (callbackWorklist); for (Entry<String, Set<AndroidMethod>> entry : workListCopy.entrySet()) { List<MethodOrMethodContext> entryClasses = new LinkedList<MethodOrMethodContext>(); for (AndroidMethod am : entry.getValue()) entryClasses.add(Scene.v().getMethod(am.getSignature())); analyzeRechableMethods(Scene.v().getSootClass(entry.getKey()), entryClasses); callbackWorklist.remove(entry.getKey()); } System.out.println("Incremental callback analysis done."); } }); PackManager.v().getPack("wjtp").add(transform); } private void analyzeRechableMethods(SootClass lifecycleElement, List<MethodOrMethodContext> methods) { ReachableMethods rm = new ReachableMethods(Scene.v().getCallGraph(), methods); rm.update(); // Scan for listeners in the class hierarchy Iterator<MethodOrMethodContext> reachableMethods = rm.listener(); while (reachableMethods.hasNext()) { SootMethod method = reachableMethods.next().method(); analyzeMethodForCallbackRegistrations(lifecycleElement, method); } } /** * Analyzes the given method and looks for callback registrations * @param lifecycleElement The lifecycle element (activity, etc.) with which * to associate the found callbacks * @param method The method in which to look for callbacks */ private void analyzeMethodForCallbackRegistrations(SootClass lifecycleElement, SootMethod method) { // Do not analyze system classes if (method.getDeclaringClass().getName().startsWith("android.") || method.getDeclaringClass().getName().startsWith("java.")) return; if (!method.isConcrete()) return; ExceptionalUnitGraph graph = new ExceptionalUnitGraph(method.retrieveActiveBody()); SmartLocalDefs smd = new SmartLocalDefs(graph, new SimpleLiveLocals(graph)); // Iterate over all statement and find callback registration methods Set<SootClass> callbackClasses = new HashSet<SootClass>(); for (Unit u : method.retrieveActiveBody().getUnits()) { Stmt stmt = (Stmt) u; // Callback registrations are always instance invoke expressions if (stmt.containsInvokeExpr() && stmt.getInvokeExpr() instanceof InstanceInvokeExpr) { InstanceInvokeExpr iinv = (InstanceInvokeExpr) stmt.getInvokeExpr(); for (int i = 0; i < iinv.getArgCount(); i++) { Value arg = iinv.getArg(i); Type argType = iinv.getArg(i).getType(); Type paramType = iinv.getMethod().getParameterType(i); if (paramType instanceof RefType && argType instanceof RefType) { if (androidCallbacks.contains(((RefType) paramType).getSootClass().getName())) { // We have a formal parameter type that corresponds to one of the Android // callback interfaces. Look for definitions of the parameter to estimate // the actual type. if (arg instanceof Local) for (Unit def : smd.getDefsOfAt((Local) arg, u)) { assert def instanceof DefinitionStmt; Type tp = ((DefinitionStmt) def).getRightOp().getType(); if (tp instanceof RefType) { SootClass callbackClass = ((RefType) tp).getSootClass(); if (callbackClass.isInterface()) for (SootClass impl : Scene.v().getActiveHierarchy().getImplementersOf(callbackClass)) for (SootClass c : Scene.v().getActiveHierarchy().getSubclassesOfIncluding(impl)) callbackClasses.add(c); else for (SootClass c : Scene.v().getActiveHierarchy().getSubclassesOfIncluding(callbackClass)) callbackClasses.add(c); } } } } } } } // Analyze all found callback classes for (SootClass callbackClass : callbackClasses) analyzeClass(callbackClass, lifecycleElement); } /** * Finds the mappings between classes and their respective layout files */ private void findClassLayoutMappings() { Iterator<MethodOrMethodContext> rmIterator = Scene.v().getReachableMethods().listener(); while (rmIterator.hasNext()) { SootMethod sm = rmIterator.next().method(); if (!sm.isConcrete()) continue; for (Unit u : sm.retrieveActiveBody().getUnits()) if (u instanceof Stmt) { Stmt stmt = (Stmt) u; if (stmt.containsInvokeExpr()) { InvokeExpr inv = stmt.getInvokeExpr(); if (inv.getMethod().getName().equals("setContentView") && inv.getMethod().getDeclaringClass().getName().equals("android.app.Activity")) { for (Value val : inv.getArgs()) if (val instanceof IntConstant) { IntConstant constVal = (IntConstant) val; if (this.layoutClasses.containsKey(sm.getDeclaringClass())) this.layoutClasses.get(sm.getDeclaringClass()).add(constVal.value); else { Set<Integer> layoutIDs = new HashSet<Integer>(); layoutIDs.add(constVal.value); this.layoutClasses.put(sm.getDeclaringClass(), layoutIDs); } } } } } } } /** * Analyzes the given class to find callback methods * @param sootClass The class to analyze * @param lifecycleElement The lifecycle element (activity, service, etc.) * to which the callback methods belong */ private void analyzeClass(SootClass sootClass, SootClass lifecycleElement) { // Do not analyze system classes if (sootClass.getName().startsWith("android.") || sootClass.getName().startsWith("java.")) return; // Check for callback handlers implemented via interfaces analyzeClassInterfaceCallbacks(sootClass, sootClass, lifecycleElement); } private void analyzeMethodOverrideCallbacks(SootClass sootClass) { if (!sootClass.isConcrete()) return; if (sootClass.isInterface()) return; // There are also some classes that implement interesting callback methods. // We model this as follows: Whenever the user overwrites a method in an // Android OS class, we treat it as a potential callback. Set<String> systemMethods = new HashSet<String>(10000); for (SootClass parentClass : Scene.v().getActiveHierarchy().getSuperclassesOf(sootClass)) { if (parentClass.getName().startsWith("android.")) for (SootMethod sm : parentClass.getMethods()) if (!sm.isConstructor()) systemMethods.add(sm.getSubSignature()); } // Iterate over all user-implemented methods. If they are inherited // from a system class, they are callback candidates. for (SootClass parentClass : Scene.v().getActiveHierarchy().getSubclassesOfIncluding(sootClass)) { if (parentClass.getName().startsWith("android.")) continue; for (SootMethod method : parentClass.getMethods()) { if (!systemMethods.contains(method.getSubSignature())) continue; // This is a real callback method checkAndAddMethod(method, sootClass); } } } private SootMethod getMethodFromHierarchyEx(SootClass c, String methodSignature) { if (c.declaresMethod(methodSignature)) return c.getMethod(methodSignature); if (c.hasSuperclass()) return getMethodFromHierarchyEx(c.getSuperclass(), methodSignature); throw new RuntimeException("Could not find method"); } private void analyzeClassInterfaceCallbacks(SootClass baseClass, SootClass sootClass, SootClass lifecycleElement) { // We cannot create instances of abstract classes anyway, so there is no // reason to look for interface implementations if (!baseClass.isConcrete()) return; // For a first take, we consider all classes in the android.* packages // to be part of the operating system if (baseClass.getName().startsWith("android.")) return; // If we are a class, one of our superclasses might implement an Android // interface if (sootClass.hasSuperclass()) analyzeClassInterfaceCallbacks(baseClass, sootClass.getSuperclass(), lifecycleElement); // Do we implement one of the well-known interfaces? for (SootClass i : collectAllInterfaces(sootClass)) { if (androidCallbacks.contains(i.getName())) for (SootMethod sm : i.getMethods()) checkAndAddMethod(getMethodFromHierarchyEx(baseClass, sm.getSubSignature()), lifecycleElement); } } /** * Checks whether the given Soot method comes from a system class. If not, * it is added to the list of callback methods. * @param method The method to check and add * @param baseClass The base class (activity, service, etc.) to which this * callback method belongs */ private void checkAndAddMethod(SootMethod method, SootClass baseClass) { AndroidMethod am = new AndroidMethod(method); // Do not call system methods if (am.getClassName().startsWith("android.") || am.getClassName().startsWith("java.")) return; // Skip empty methods if (method.isConcrete() && isEmpty(method.retrieveActiveBody())) return; boolean isNew; if (this.callbackMethods.containsKey(baseClass.getName())) isNew = this.callbackMethods.get(baseClass.getName()).add(am); else { Set<AndroidMethod> methods = new HashSet<AndroidMethod>(); isNew = methods.add(am); this.callbackMethods.put(baseClass.getName(), methods); } if (isNew) if (this.callbackWorklist.containsKey(baseClass.getName())) this.callbackWorklist.get(baseClass.getName()).add(am); else { Set<AndroidMethod> methods = new HashSet<AndroidMethod>(); isNew = methods.add(am); this.callbackWorklist.put(baseClass.getName(), methods); } } private boolean isEmpty(Body activeBody) { for (Unit u : activeBody.getUnits()) if (!(u instanceof IdentityStmt || u instanceof ReturnVoidStmt)) return false; return true; } private Set<SootClass> collectAllInterfaces(SootClass sootClass) { Set<SootClass> interfaces = new HashSet<SootClass>(sootClass.getInterfaces()); for (SootClass i : sootClass.getInterfaces()) interfaces.addAll(collectAllInterfaces(i)); return interfaces; } public Map<String, Set<AndroidMethod>> getCallbackMethods() { return this.callbackMethods; } public Map<SootClass, Set<Integer>> getLayoutClasses() { return this.layoutClasses; } }
package com.github.nsnjson; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.node.*; import org.junit.*; import java.util.Optional; import static com.github.nsnjson.format.Format.*; public abstract class AbstractFormatTest extends AbstractTest { @Test public void testNull() { processTestNull(getNull(), getNullPresentation()); } @Test public void testNumberInt() { NumericNode value = getNumberInt(); processTestNumberInt(value, getNumberIntPresentation(value)); } @Test public void testNumberLong() { NumericNode value = getNumberLong(); processTestNumberLong(value, getNumberLongPresentation(value)); } @Test public void testNumberDouble() { NumericNode value = getNumberDouble(); processTestNumberDouble(value, getNumberDoublePresentation(value)); } @Test public void testEmptyString() { TextNode value = getEmptyString(); processTestString(value, getStringPresentation(value)); } @Test public void testString() { TextNode value = getString(); processTestString(value, getStringPresentation(value)); } @Test public void testBooleanTrue() { BooleanNode value = getBooleanTrue(); processTestBoolean(value, getBooleanPresentation(value)); } @Test public void testBooleanFalse() { BooleanNode value = getBooleanFalse(); processTestBoolean(value, getBooleanPresentation(value)); } @Test public void testEmptyArray() { ArrayNode array = getEmptyArray(); processTestArray(array, getArrayPresentation(array)); } @Test public void testArray() { ArrayNode array = getArray(); processTestArray(array, getArrayPresentation(array)); } @Test public void testEmptyObject() { ObjectNode object = getEmptyObject(); processTestObject(object, getObjectPresentation(object)); } @Test public void testObject() { ObjectNode object = getObject(); processTestObject(object, getObjectPresentation(object)); } protected abstract void processTestNull(NullNode value, JsonNode presentation); protected abstract void processTestNumberInt(NumericNode value, JsonNode presentation); protected abstract void processTestNumberLong(NumericNode value, JsonNode presentation); protected abstract void processTestNumberDouble(NumericNode value, JsonNode presentation); protected abstract void processTestString(TextNode value, JsonNode presentation); protected abstract void processTestBoolean(BooleanNode value, JsonNode presentation); protected abstract void processTestArray(ArrayNode array, JsonNode presentation); protected abstract void processTestObject(ObjectNode object, JsonNode presentation); protected static JsonNode assertAndGetPresentation(Optional<JsonNode> presentationOption) { Assert.assertTrue(presentationOption.isPresent()); return presentationOption.get(); } protected static JsonNode assertAndGetValue(Optional<JsonNode> valueOption) { Assert.assertTrue(valueOption.isPresent()); return valueOption.get(); } private static JsonNode getNullPresentation() { ObjectNode presentation = new ObjectMapper().createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_NULL); return presentation; } private static JsonNode getNumberIntPresentation(NumericNode value) { ObjectNode presentation = new ObjectMapper().createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentation.put(FIELD_VALUE, value.asInt()); return presentation; } private static JsonNode getNumberLongPresentation(NumericNode value) { ObjectNode presentation = new ObjectMapper().createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentation.put(FIELD_VALUE, value.asLong()); return presentation; } private static JsonNode getNumberDoublePresentation(NumericNode value) { ObjectNode presentation = new ObjectMapper().createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentation.put(FIELD_VALUE, value.asDouble()); return presentation; } private static JsonNode getStringPresentation(TextNode value) { ObjectNode presentation = new ObjectMapper().createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_STRING); presentation.put(FIELD_VALUE, value.asText()); return presentation; } private static JsonNode getBooleanPresentation(BooleanNode value) { ObjectNode presentation = new ObjectMapper().createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentation.put(FIELD_VALUE, value.asBoolean() ? BOOLEAN_TRUE : BOOLEAN_FALSE); return presentation; } private static JsonNode getArrayPresentation(ArrayNode array) { ObjectMapper objectMapper = new ObjectMapper(); ArrayNode presentationOfArrayItems = objectMapper.createArrayNode(); for (JsonNode value : array) { Optional<JsonNode> itemPresentationOption = Optional.empty(); if (value instanceof NullNode) { itemPresentationOption = Optional.of(getNullPresentation()); } else if (value instanceof NumericNode) { NumericNode numericValue = (NumericNode) value; if (numericValue.isInt()) { itemPresentationOption = Optional.of(getNumberIntPresentation(numericValue)); } else if (numericValue.isLong()) { itemPresentationOption = Optional.of(getNumberLongPresentation(numericValue)); } else if (numericValue.isDouble()) { itemPresentationOption = Optional.of(getNumberDoublePresentation(numericValue)); } } else if (value instanceof TextNode) { TextNode stringValue = (TextNode) value; itemPresentationOption = Optional.of(getStringPresentation(stringValue)); } else if (value instanceof BooleanNode) { BooleanNode booleanValue = (BooleanNode) value; itemPresentationOption = Optional.of(getBooleanPresentation(booleanValue)); } if (itemPresentationOption.isPresent()) { presentationOfArrayItems.add(itemPresentationOption.get()); } } ObjectNode presentation = objectMapper.createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_ARRAY); presentation.set(FIELD_VALUE, presentationOfArrayItems); return presentation; } private static JsonNode getObjectPresentation(ObjectNode object) { ObjectMapper objectMapper = new ObjectMapper(); ArrayNode presentationOfObjectFields = objectMapper.createArrayNode(); object.fieldNames().forEachRemaining(name -> { JsonNode value = object.get(name); Optional<JsonNode> fieldPresentationOption = Optional.empty(); if (value instanceof NullNode) { fieldPresentationOption = Optional.of(getFieldPresentation(name, getNullPresentation())); } else if (value instanceof NumericNode) { NumericNode numericValue = (NumericNode) value; if (numericValue.isInt()) { fieldPresentationOption = Optional.of(getFieldPresentation(name, getNumberIntPresentation(numericValue))); } else if (numericValue.isLong()) { fieldPresentationOption = Optional.of(getFieldPresentation(name, getNumberLongPresentation(numericValue))); } else if (numericValue.isDouble()) { fieldPresentationOption = Optional.of(getFieldPresentation(name, getNumberDoublePresentation(numericValue))); } } else if (value instanceof TextNode) { TextNode stringValue = (TextNode) value; fieldPresentationOption = Optional.of(getFieldPresentation(name, getStringPresentation(stringValue))); } else if (value instanceof BooleanNode) { BooleanNode booleanValue = (BooleanNode) value; fieldPresentationOption = Optional.of(getFieldPresentation(name, getBooleanPresentation(booleanValue))); } if (fieldPresentationOption.isPresent()) { presentationOfObjectFields.add(fieldPresentationOption.get()); } }); ObjectNode presentation = objectMapper.createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_OBJECT); presentation.set(FIELD_VALUE, presentationOfObjectFields); return presentation; } private static JsonNode getFieldPresentation(String name, JsonNode valuePresentation) { ObjectNode presentation = new ObjectMapper().createObjectNode(); presentation.put(FIELD_NAME, name); valuePresentation.fieldNames().forEachRemaining((valueProperty) -> { presentation.set(valueProperty, valuePresentation.get(valueProperty)); }); return presentation; } }
package com.lucidworks.spark; import org.apache.spark.sql.DataFrame; import org.apache.spark.sql.Row; import org.apache.spark.sql.SQLContext; import org.apache.spark.sql.SaveMode; import org.apache.spark.sql.types.*; import org.junit.Test; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.mllib.classification.LogisticRegressionModel; import org.apache.spark.mllib.classification.LogisticRegressionWithLBFGS; import org.apache.spark.mllib.classification.NaiveBayes; import org.apache.spark.mllib.classification.NaiveBayesModel; import org.apache.spark.sql.*; import org.apache.spark.mllib.regression.LabeledPoint; import org.apache.spark.mllib.linalg.Vectors; import org.apache.commons.io.FileUtils; import java.io.File; import java.util.*; import static org.junit.Assert.*; /** * Tests for the SolrRelation implementation. */ public class SolrRelationTest extends RDDProcessorTestBase { protected transient SQLContext sqlContext; @Test public void testFilterSupport() throws Exception { SQLContext sqlContext = new SQLContext(jsc); String[] testData = new String[] { "1,a,x,1000,[a;x],[1000]", "2,b,y,2000,[b;y],[2000]", "3,c,z,3000,[c;z],[3000]", "4,a,x,4000,[a;x],[4000]" }; String zkHost = cluster.getZkServer().getZkAddress(); String testCollection = "testFilterSupport"; deleteCollection(testCollection); deleteCollection("testFilterSupport2"); buildCollection(zkHost, testCollection, testData, 2); Map<String, String> options = new HashMap<String, String>(); options.put("zkhost", zkHost); options.put("collection", testCollection); DataFrame df = sqlContext.read().format("solr").options(options).load(); validateSchema(df); //df.show(); long count = df.count(); assertCount(testData.length, count, "*:*"); Row[] rows = df.collect(); for (int r=0; r < rows.length; r++) { Row row = rows[r]; List val = row.getList(row.fieldIndex("field4_ss")); assertNotNull(val); List list = new ArrayList(); list.addAll(val); // clone since we need to sort the entries for testing only Collections.sort(list); assertTrue(list.size() == 2); assertEquals(list.get(0), row.getString(row.fieldIndex("field1_s"))); assertEquals(list.get(1), row.getString(row.fieldIndex("field2_s"))); } count = df.filter(df.col("field1_s").equalTo("a")).count(); assertCount(2, count, "field1_s == a"); count = df.filter(df.col("field3_i").gt(3000)).count(); assertCount(1, count, "field3_i > 3000"); count = df.filter(df.col("field3_i").geq(3000)).count(); assertCount(2, count, "field3_i >= 3000"); count = df.filter(df.col("field3_i").lt(2000)).count(); assertCount(1, count, "field3_i < 2000"); count = df.filter(df.col("field3_i").leq(1000)).count(); assertCount(1, count, "field3_i <= 1000"); count = df.filter(df.col("field3_i").gt(2000).and(df.col("field2_s").equalTo("z"))).count(); assertCount(1, count, "field3_i > 2000 AND field2_s == z"); count = df.filter(df.col("field3_i").lt(2000).or(df.col("field1_s").equalTo("a"))).count(); assertCount(2, count, "field3_i < 2000 OR field1_s == a"); count = df.filter(df.col("field1_s").isNotNull()).count(); assertCount(4, count, "field1_s IS NOT NULL"); count = df.filter(df.col("field1_s").isNull()).count(); assertCount(0, count, "field1_s IS NULL"); // write to another collection to test writes String confName = "testConfig"; File confDir = new File("src/test/resources/conf"); int numShards = 2; int replicationFactor = 1; createCollection("testFilterSupport2", numShards, replicationFactor, 2, confName, confDir); options = new HashMap<String, String>(); options.put("zkhost", zkHost); options.put("collection", "testFilterSupport2"); df.write().format("solr").options(options).mode(SaveMode.Overwrite).save(); Thread.sleep(1000); DataFrame df2 = sqlContext.read().format("solr").options(options).load(); df2.show(); deleteCollection(testCollection); deleteCollection("testFilterSupport2"); } @Test public void testNestedDataFrames() throws Exception { SQLContext sqlContext = new SQLContext(jsc); String confName = "testConfig"; File confDir = new File("src/test/resources/conf"); int numShards = 2; int replicationFactor = 1; deleteCollection("testNested"); createCollection("testNested", numShards, replicationFactor, 2, confName, confDir); List<StructField> fields = new ArrayList<StructField>(); List<StructField> fields1 = new ArrayList<StructField>(); List<StructField> fields2 = new ArrayList<StructField>(); fields.add(DataTypes.createStructField("id", DataTypes.StringType, true)); fields.add(DataTypes.createStructField("testing_s", DataTypes.StringType, true)); fields1.add(DataTypes.createStructField("test1_s", DataTypes.StringType, true)); fields1.add(DataTypes.createStructField("test2_s", DataTypes.StringType, true)); fields2.add(DataTypes.createStructField("test11_s", DataTypes.StringType, true)); fields2.add(DataTypes.createStructField("test12_s", DataTypes.StringType, true)); fields2.add(DataTypes.createStructField("test13_s", DataTypes.StringType, true)); fields1.add(DataTypes.createStructField("testtype_s", DataTypes.createStructType(fields2) , true)); fields.add(DataTypes.createStructField("test_s", DataTypes.createStructType(fields1), true)); StructType schema = DataTypes.createStructType(fields); Row dm = RowFactory.create("7", "test", RowFactory.create("test1", "test2", RowFactory.create("test11", "test12", "test13"))); List<Row> list = new ArrayList<Row>(); list.add(dm); JavaRDD<Row> rdd = jsc.parallelize(list); DataFrame df = sqlContext.createDataFrame(rdd, schema); HashMap<String, String> options = new HashMap<String, String>(); String zkHost = cluster.getZkServer().getZkAddress(); options = new HashMap<String, String>(); options.put("zkhost", zkHost); options.put("collection", "testNested"); options.put("preserveschema", "Y"); df.write().format("solr").options(options).mode(SaveMode.Overwrite).save(); Thread.sleep(1000); DataFrame df2 = sqlContext.read().format("solr").options(options).load(); df2 = sqlContext.createDataFrame(df2.javaRDD(),df2.schema()); df.show(); df2.show(); df2.registerTempTable("DFTEST"); sqlContext.sql("SELECT test_s.testtype_s FROM DFTEST").show(); deleteCollection("testNested"); } @Test public void createMLModelLRParquet() throws Exception { List<LabeledPoint> list = new ArrayList<LabeledPoint>(); LabeledPoint zero = new LabeledPoint(0.0, Vectors.dense(1.0, 0.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0)); LabeledPoint one = new LabeledPoint(1.0, Vectors.dense(8.0,7.0,6.0,4.0,5.0,6.0,1.0,2.0,3.0)); list.add(zero); list.add(one); JavaRDD<LabeledPoint> data = jsc.parallelize(list); final LogisticRegressionModel model = new LogisticRegressionWithLBFGS() .setNumClasses(2) .run(data.rdd()); model.save(jsc.sc(), "LRParquet"); } @Test public void createMLModelNBParquet() throws Exception { List<LabeledPoint> list = new ArrayList<LabeledPoint>(); LabeledPoint zero = new LabeledPoint(0.0, Vectors.dense(1.0, 0.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0)); LabeledPoint one = new LabeledPoint(1.0, Vectors.dense(8.0,7.0,6.0,4.0,5.0,6.0,1.0,2.0,3.0)); list.add(zero); list.add(one); JavaRDD<LabeledPoint> data = jsc.parallelize(list); final NaiveBayesModel model = NaiveBayes.train(data.rdd(), 1.0); model.save(jsc.sc(), "NBParquet"); } @Test public void loadLRParquetIntoSolr() throws Exception { SQLContext sqlContext = new SQLContext(jsc); String confName = "testConfig"; File confDir = new File("src/test/resources/conf"); int numShards = 2; int replicationFactor = 1; deleteCollection("TestLR"); Thread.sleep(1000); createCollection("TestLR", numShards, replicationFactor, 2, confName, confDir); String zkHost = cluster.getZkServer().getZkAddress(); DataFrame dfLR = sqlContext.load("LRParquet/data/"); HashMap<String, String> options = new HashMap<String, String>(); options = new HashMap<String, String>(); options.put("zkhost", zkHost); options.put("collection", "TestLR"); options.put("preserveschema", "Y"); dfLR.write().format("solr").options(options).mode(SaveMode.Overwrite).save(); dfLR.show(); dfLR.printSchema(); Thread.sleep(5000); DataFrame dfLR2 = sqlContext.read().format("solr").options(options).load(); dfLR2.show(); dfLR2.printSchema(); assertCount(dfLR.count(), dfLR.intersect(dfLR2).count(), "compare dataframe count"); deleteCollection("TestLR"); Thread.sleep(1000); FileUtils.forceDelete(new File("LRParquet")); } @Test public void loadNBParquetIntoSolr() throws Exception { SQLContext sqlContext = new SQLContext(jsc); String confName = "testConfig"; File confDir = new File("src/test/resources/conf"); int numShards = 2; int replicationFactor = 1; deleteCollection("TestNB"); Thread.sleep(1000); createCollection("TestNB", numShards, replicationFactor, 2, confName, confDir); String zkHost = cluster.getZkServer().getZkAddress(); DataFrame dfNB = sqlContext.load("NBParquet/data/"); HashMap<String, String> options = new HashMap<String, String>(); options = new HashMap<String, String>(); options.put("zkhost", zkHost); options.put("preserveschema", "Y"); options.put("collection", "TestNB"); dfNB.write().format("solr").options(options).mode(SaveMode.Overwrite).save(); dfNB.show(); Thread.sleep(5000); DataFrame dfNB2 = sqlContext.read().format("solr").options(options).load(); dfNB2.show(); dfNB.printSchema(); dfNB2.printSchema(); assertCount(dfNB.count(), dfNB.intersect(dfNB2).count(), "compare dataframe count"); deleteCollection("TestNB"); Thread.sleep(1000); FileUtils.forceDelete(new File("NBParquet")); } protected void assertCount(long expected, long actual, String expr) { assertTrue("expected count == "+expected+" but got "+actual+" for "+expr, expected == actual); } protected void validateSchema(DataFrame df) { df.printSchema(); StructType schema = df.schema(); assertNotNull(schema); String[] expectedSchemaFields = new String[]{"id","field1_s","field2_s","field3_i","field4_ss","field5_ii"}; Map<String,StructField> schemaFields = new HashMap<String, StructField>(); for (StructField sf : schema.fields()) schemaFields.put(sf.name(), sf); for (String fieldName : expectedSchemaFields) { StructField field = schemaFields.get(fieldName); if (field == null) fail("Expected schema field '" + fieldName + "' not found! Schema is: " + schema.prettyJson()); DataType type = field.dataType(); if (fieldName.equals("id") || fieldName.endsWith("_s")) { assertEquals("Field '" + fieldName + "' should be a string but has type '" + type + "' instead!", "string", type.typeName()); } else if (fieldName.endsWith("_i")) { assertEquals("Field '" + fieldName + "' should be an integer but has type '" + type + "' instead!", "integer", type.typeName()); } else if (fieldName.endsWith("_ss")) { assertEquals("Field '"+fieldName+"' should be an array but has '"+type+"' instead!", "array", type.typeName()); ArrayType arrayType = (ArrayType)type; assertEquals("Field '"+fieldName+"' should have a string element type but has '"+arrayType.elementType()+ "' instead!", "string", arrayType.elementType().typeName()); } else if (fieldName.endsWith("_ii")) { assertEquals("Field '"+fieldName+"' should be an array but has '"+type+"' instead!", "array", type.typeName()); ArrayType arrayType = (ArrayType)type; assertEquals("Field '"+fieldName+"' should have an integer element type but has '"+arrayType.elementType()+ "' instead!", "integer", arrayType.elementType().typeName()); } } } }
package io.usethesource.vallang; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Random; import java.util.function.BiFunction; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; import io.usethesource.vallang.exceptions.FactParseError; import io.usethesource.vallang.exceptions.FactTypeUseException; import io.usethesource.vallang.io.StandardTextReader; import io.usethesource.vallang.random.RandomTypeGenerator; import io.usethesource.vallang.random.RandomValueGenerator; import io.usethesource.vallang.type.Type; import io.usethesource.vallang.type.TypeFactory; import io.usethesource.vallang.type.TypeStore; /** * This value provider generates automatically/randomly values for test parameters of type: * IValueFactory * TypeFactory * TypeStore * IValue * IList * ISet * IMap * IInteger * IReal * INumber * IRational * INode * IConstructor * ITuple * ISourceLocation * Type * * If the class under test has a static field called "store" of type TypeStore, then this * typestore will be passed to all parameters of type TypeStore instead of a fresh/empty TypeStore. * * If a parameter of a method under test is annotated with @ExpectedType("type") like so: * \@ParameterizedTest \@ArgumentsSource(ValueProvider.class) * public void myTest(\@ExpectedType("set[int]") ISet set) ... * * , then the ValueProvider will generate only instances which have as run-time type a * sub-type of the specified expected type. * */ public class ValueProvider implements ArgumentsProvider { private static final Random rnd = new Random(); private static final boolean enableAnnotations = true; private static final TypeFactory tf = TypeFactory.getInstance(); /** * We use this to accidentally generate arguments which are the same as the previous * once in a while: */ private IValue previous = null; /** * Every vallang test is run using all implementations of IValueFactory. */ private static final IValueFactory[] factories = { io.usethesource.vallang.impl.reference.ValueFactory.getInstance(), io.usethesource.vallang.impl.persistent.ValueFactory.getInstance() }; private static RandomTypeGenerator typeGen = new RandomTypeGenerator(rnd); /** * The random value generator is parametrized by the valuefactory at creation time. * We need to keep the reference due get better randomized results between (re-runs of) * individual tests. */ private static final RandomValueGenerator[] generators = { new RandomValueGenerator(factories[0], rnd, 5, 10, enableAnnotations), new RandomValueGenerator(factories[1], rnd, 5, 10, enableAnnotations) }; /** * This trivial class helps with streaming generated test inputs, and some other stuff. */ private static class Tuple<A,B> { public A a; public B b; public Tuple(A a, B b) { this.a = a; this.b = b; } public static <C,D> Tuple<C,D> of(C c, D d) { return new Tuple<>(c, d); } } /** * Maps Java class literals of sub-types of IValue to the corresponding function which will * generate a (random) instance of a type that all instances of such Java classes could have. * Only composite types will actually be random. */ private static final Map<Class<? extends IValue>, BiFunction<TypeStore, ExpectedType, Type>> types = Stream.<Tuple<Class<? extends IValue>, BiFunction<TypeStore, ExpectedType, Type>>>of( Tuple.of(IInteger.class, (ts, n) -> tf.integerType()), Tuple.of(IBool.class, (ts, n) -> tf.boolType()), Tuple.of(IReal.class, (ts, n) -> tf.realType()), Tuple.of(IRational.class, (ts, n) -> tf.rationalType()), Tuple.of(INumber.class, (ts, n) -> tf.numberType()), Tuple.of(IString.class, (ts, n) -> tf.stringType()), Tuple.of(ISourceLocation.class, (ts, n) -> tf.sourceLocationType()), Tuple.of(IValue.class, (ts, n) -> tf.valueType()), Tuple.of(INode.class, (ts, n) -> tf.nodeType()), Tuple.of(IList.class, (ts, n) -> tf.listType(tf.randomType())), Tuple.of(ISet.class, (ts, n) -> tf.setType(tf.randomType())), Tuple.of(ITuple.class, (ts, n) -> tf.tupleType(tf.randomType(), tf.randomType())), Tuple.of(IMap.class, (ts, n) -> tf.mapType(tf.randomType(), tf.randomType())), Tuple.of(IConstructor.class, (ts, n) -> randomADT(ts, n)) ).collect(Collectors.toMap(t -> t.a, t -> t.b)); @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { Method method = context.getTestMethod().get(); /* * If only factories and typestores are arguments, we generate as many tests as we have * value factory implementations (2). For the IValue argument we generate 100 tests and for * every additional IValue argument we multiply the number of tests by 10. */ long valueArity = Arrays.stream(method.getParameterTypes()).filter(x -> IValue.class.isAssignableFrom(x) || Type.class.isAssignableFrom(x)).count(); int numberOfTests = Math.max(1, 100 * (int) Math.pow(10, valueArity - 1)); return Stream.of( Tuple.of(factories[0], generators[0]), // every factory has its own generator Tuple.of(factories[1], generators[1]) ).flatMap(vf -> // all parameters share the same factory generateTypeStore(context).flatMap(ts -> Stream.iterate(arguments(method, vf, ts), p -> arguments(method, vf, ts)).limit(numberOfTests) ) ); } private static Type randomADT(TypeStore ts, ExpectedType n) { if (n != null) { Type result = readType(ts, n); if (result != null) { return result; } } Collection<Type> allADTs = ts.getAbstractDataTypes(); if (!allADTs.isEmpty()) { return allADTs.stream().skip(new Random().nextInt(allADTs.size())).findFirst().get(); } // note the side-effect in the type store! Type x = tf.abstractDataType(ts, "X"); tf.constructor(ts, x, "x"); return x; } /** * Generate the random argument for a single test method * @param method the declaration of the method under test * @param vf the valuefactory to use when generating values, also passed to parameters of type IValueFactory * @param ts the TypeStore to request ADTs from, randomly, also passed to parameters of type TypeStore * @return an Arguments instance for streaming into JUnits MethodSource interface. */ private Arguments arguments(Method method, Tuple<IValueFactory, RandomValueGenerator> vf, TypeStore ts) { previous = null; // never reuse arguments from a previous instance return Arguments.of(Arrays.stream(method.getParameters()).map(cl -> argument(vf, ts, cl.getType(), cl.getAnnotation(ExpectedType.class), cl.getAnnotation(NoAnnotations.class) != null)).toArray()); } /** * Generate an argument to a vallang test function. `cls` can be any sub-type of IValue, * or TypeStore or IValueFactory. * @param vf the valuefactory to use when generating values, also passed to parameters of type IValueFactory * @param ts the TypeStore to request ADTs from, randomly, also passed to parameters of type TypeStore * @param cls the class type of the parameter to generate an input for * @return a random object which is assignable to cls */ private Object argument(Tuple<IValueFactory, RandomValueGenerator> vf, TypeStore ts, Class<?> cls, ExpectedType expected, boolean noAnnotations) { if (cls.isAssignableFrom(IValueFactory.class)) { return vf.a; } else if (cls.isAssignableFrom(TypeStore.class)) { return ts; } else if (cls.isAssignableFrom(Type.class)) { return typeGen.next(5); } else if (cls.isAssignableFrom(TypeFactory.class)) { return TypeFactory.getInstance(); } else if (IValue.class.isAssignableFrom(cls)) { return generateValue(vf, ts, cls.asSubclass(IValue.class), expected, noAnnotations); } else { throw new IllegalArgumentException(cls + " is not assignable from IValue, IValueFactory, TypeStore or TypeFactory"); } } /** * Generate a random IValue instance * * @param vf the valuefactory/randomgenerator to use * @param ts the TypeStore to draw ADT constructors from * @param cl the `cl` (sub-type of `IValue`) to be assignable to * @param noAnnotations * @return an instance assignable to `cl` */ private IValue generateValue(Tuple<IValueFactory, RandomValueGenerator> vf, TypeStore ts, Class<? extends IValue> cl, ExpectedType expected, boolean noAnnotations) { Type expectedType = expected != null ? readType(ts, expected) : types.getOrDefault(cl, (x, n) -> tf.valueType()).apply(ts, expected); RandomValueGenerator gen = vf.b.setAnnotations(!noAnnotations); Random rnd = gen.getRandom(); if (previous != null && rnd.nextInt(4) == 0 && previous.getType().isSubtypeOf(expectedType)) { return rnd.nextBoolean() ? previous : reinstantiate(vf.a, ts, previous); } return (previous = gen.generate(expectedType, ts, Collections.emptyMap())); } private static Type readType(TypeStore ts, ExpectedType expected) { try { return tf.fromString(ts, new StringReader(expected.value())); } catch (IOException e) { return null; } } /** * Produces a value which equals the input `val` but is not the same object reference. * It does this by serializing the value and parsing it again with the same expected type. * @return a value equals to `val` (val.equals(returnValue)) but not reference equal (val != returnValue) */ private IValue reinstantiate(IValueFactory vf, TypeStore ts, IValue val) { try { return new StandardTextReader().read(vf, ts, val.getType(), new StringReader(val.toString())); } catch (FactTypeUseException | FactParseError | IOException e) { System.err.println("WARNING: value reinstantation via serialization failed for ["+val+"] because + \""+e.getMessage()+"\". Reusing reference."); return val; } } /** * Generates a TypeStore instance by importing the static `store` field of the class-under-test (if-present) * in a fresh TypeStore. Otherwise it generates a fresh and empty TypeStore. * @param context * @return */ private Stream<TypeStore> generateTypeStore(ExtensionContext context) { try { return Stream.of(new TypeStore((TypeStore) context.getRequiredTestClass().getField("store").get("null"))); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { return Stream.of(new TypeStore()); } } }
package laboratory.jdk.java.time; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; import java.time.MonthDay; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.Period; import java.time.YearMonth; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.LinkedList; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * * @since 2017-07-27 * @author fixalot */ public class JavaTimeTest { private static final Logger logger = LoggerFactory.getLogger(JavaTimeTest.class); @Test public void create() { logger.debug(String.valueOf(Instant.now())); logger.debug(String.valueOf(LocalDate.now())); // yyyy-MM-dd logger.debug(String.valueOf(LocalTime.now())); // HH:mm:ss.SSS Assert.assertEquals("1970-01-01T00:00:00Z", Instant.ofEpochMilli(0).toString()); Assert.assertEquals("2017-09-19T06:10:46.820Z", Instant.ofEpochMilli(1505801446820L).toString()); Assert.assertEquals("2009-02-13T23:20:23Z", Instant.ofEpochSecond(1234567223L).toString()); Assert.assertTrue(Instant.ofEpochMilli(915152400123L).equals(Instant.parse("1999-01-01T01:00:00.123Z"))); } @Test public void getLocalDate() { LocalDate a = LocalDate.now(); logger.debug(String.valueOf(a)); // yyyy-MM-dd Assert.assertEquals("2017-12-31", LocalDate.of(2017, Month.DECEMBER, 31).toString()); Assert.assertEquals("2017-04-10T23:49", LocalDateTime.of(2017, Month.APRIL, 10, 23, 49).toString()); } @Test public void getMonthDay() { MonthDay a = MonthDay.now(); logger.debug(String.valueOf(a)); // --MM-dd } @Test public void getYearMonth() { YearMonth a = YearMonth.now(); logger.debug(String.valueOf(a)); // yyyy-MM } @Test public void getOffsetDateTime() { Assert.assertEquals("2017-12-31T23:59:59.999999999Z", OffsetDateTime.of(LocalDate.of(2017, Month.DECEMBER, 31), LocalTime.MAX, ZoneOffset.UTC).toString()); Assert.assertEquals("2017-01-14T10:20:30Z", OffsetDateTime.of(2017, 1, 14, 10, 20, 30, 0, ZoneOffset.UTC).toString()); } @Test public void getOffsetTime() { Assert.assertEquals("22:58+18:00", OffsetTime.of(LocalTime.of(22, 58), ZoneOffset.MAX).toString()); Assert.assertEquals("22:58-18:00", OffsetTime.of(LocalTime.of(22, 58), ZoneOffset.MIN).toString()); Assert.assertEquals("22:58Z", OffsetTime.of(LocalTime.of(22, 58), ZoneOffset.UTC).toString()); } @Test public void splitDate() { LocalDate start = new GregorianCalendar(2016, 2, 5).getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate end = new GregorianCalendar(2016, 2, 11).getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); long periodDays = ChronoUnit.DAYS.between(start, end); List<LocalDate> list = new LinkedList<>(); for (int i = 0; i < periodDays; i++) { list.add(start.plusDays(i)); } Assert.assertEquals("[2016-03-05, 2016-03-06, 2016-03-07, 2016-03-08, 2016-03-09, 2016-03-10]", list.toString()); } @Test public void parseFromJavaUtilDate() { Calendar input = new GregorianCalendar(2016, 2, 5); Date date = input.getTime(); LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); Assert.assertEquals("2016-03-05", localDate.toString()); } @Test public void parseToJavaUtilDate() { // case logger.debug("testToJavaUtilDate: " + Date.from(Instant.now()).toString()); // case logger.debug("testToJavaUtilDate: " + Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant()).toString()); // case Date in = new Date(); LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault()); Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant()); logger.debug("testToJavaUtilDate: " + out.toString()); } @Test public void calculateDays() { LocalDate targetDay = LocalDate.of(2017, Month.DECEMBER, 31); LocalDate today = LocalDate.of(2017, Month.JANUARY, 24); Period period = Period.between(today, targetDay); long period2 = ChronoUnit.DAYS.between(today, targetDay); Assert.assertEquals("0 years, 11 months, 7 days later. (341 days total)", (period.getYears() + " years, " + period.getMonths() + " months, " + period.getDays() + " days later. (" + period2 + " days total)")); } }
package org.animotron.operator; import static org.animotron.Expression._; import static org.animotron.Expression.text; import org.animotron.ATest; import org.animotron.Expression; import org.animotron.instruction.string.AfterLast; import org.animotron.operator.compare.WITH; import org.animotron.operator.query.ANY; import org.animotron.operator.query.GET; import org.animotron.operator.query.SELF; import org.animotron.operator.relation.HAVE; import org.animotron.operator.relation.IS; import org.junit.Test; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * */ public class ConnectionTest extends ATest { @Test public void mimeType_usecase() throws Exception { System.out.println("Mime type use case ..."); new Expression( _(THE._, "mime-type", _(HAVE._, "extension") )); new Expression( _(THE._, "file", _(HAVE._, "name", text("file")), _(HAVE._, "path"), _(HAVE._, "path1", text("some.path")), _(IC._, "extension1", _(AfterLast._, text("."), _(SELF._, "path1"))), _(IC._, "extension", _(AfterLast._, text("."), _(SELF._, "path"))), _(IC._, "mime-type", _(ANY._, "mime-type", _(WITH._, "extension", _(SELF._, "extension")))) )); new Expression( _(THE._, "fileA", _(IS._, "file"), _(HAVE._, "path", text("/home/test.txt")) )); new Expression( _(THE._, "text-plain", _(IS._, "mime-type"), _(HAVE._, "type", text("text/plain")), _(HAVE._, "extension", text("txt"), text("text")) )); Expression A = new Expression( _(THE._, "A", _(GET._, "name", _(AN._, "fileA") ))); assertAnimo(A, "<the:A><have:name>file</have:name></the:A>"); Expression B = new Expression( _(THE._, "B", _(GET._, "path", _(AN._, "fileA") ))); assertAnimo(B, "<the:B><have:path>/home/test.txt</have:path></the:B>"); Expression C = new Expression( _(THE._, "C", _(GET._, "extension", _(AN._, "fileA") ))); assertAnimo(C, "<the:C><have:extension>txt</have:extension></the:C>"); Expression C1 = new Expression( _(THE._, "C1", _(GET._, "extension1", _(AN._, "fileA") ))); assertAnimo(C1, "<the:C1><have:extension1>path</have:extension1></the:C1>"); Expression D = new Expression( _(THE._, "D", _(GET._, "mime-type", _(AN._, "fileA") ))); assertAnimo(D, "<the:D><have:mime-type><the:text-plain><is:mime-type/><have:type>text/plain</have:type><have:extension>txttext</have:extension></the:text-plain></have:mime-type></the:D>"); Expression E = new Expression( _(THE._, "E", _(GET._, "type", _(GET._, "mime-type", _(AN._, "fileA") )))); assertAnimo(E, "<the:E><have:type>text/plain</have:type></the:E>"); //System.out.println("done."); } }
package org.cactoos.iterator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantReadWriteLock; import junit.framework.TestCase; import org.cactoos.list.ListOf; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; /** * Test for {@link SyncIterator}. * * @author Sven Diedrichsen (sven.diedrichsen@gmail.com) * @version $Id$ * @since 1.0 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) * @checkstyle TodoCommentCheck (500 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public final class SyncIteratorTest { @Test public void syncIteratorReturnsCorrectValuesWithExternalLock() { final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); MatcherAssert.assertThat( "Unexpected value found.", new ListOf<>( new SyncIterator<>( Arrays.asList("a", "b").iterator(), lock ) ).toArray(), Matchers.equalTo(new Object[]{"a", "b"}) ); } @Test public void syncIteratorReturnsCorrectValuesWithInternalLock() { MatcherAssert.assertThat( "Unexpected value found.", new ListOf<>( new SyncIterator<>( Arrays.asList("a", "b").iterator() ) ).toArray(), Matchers.equalTo(new Object[]{"a", "b"}) ); } @Test @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public void correctValuesForConcurrentNextNext() throws InterruptedException { for (int iter = 0; iter < 5000; iter += 1) { final List<String> list = Arrays.asList("a", "b"); final SyncIterator<String> iterator = new SyncIterator<>( list.iterator() ); final List<Object> sync = Collections.synchronizedList( new ArrayList<>(list.size()) ); final Runnable first = () -> { sync.add(iterator.next()); }; final Runnable second = () -> { sync.add(iterator.next()); }; final List<Runnable> test = new ArrayList<>(list.size()); test.add(first); test.add(second); new Concurrent(test).launch(); MatcherAssert.assertThat( "Missing the list items(s) (next()).", sync, Matchers.containsInAnyOrder("a", "b") ); } } @Test @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public void correctValuesForConcurrentNextHasNext() throws InterruptedException { for (int iter = 0; iter < 5000; iter += 1) { final List<String> list = Arrays.asList("a", "b"); final SyncIterator<String> iterator = new SyncIterator<>( list.iterator() ); final List<Object> sync = Collections.synchronizedList( new ArrayList<>(list.size()) ); final Runnable first = () -> { sync.add(iterator.next()); }; final Runnable second = () -> { sync.add(iterator.next()); }; final Runnable third = () -> { sync.add(iterator.hasNext()); }; final List<Runnable> test = new ArrayList<>(list.size() + 1); test.add(first); test.add(second); test.add(third); new Concurrent(test).launch(); MatcherAssert.assertThat( "Missing the list items(s) (next()).", sync, Matchers.allOf( Matchers.hasItem("a"), Matchers.hasItem("b") ) ); MatcherAssert.assertThat( "Missing hasNext() value.", sync, Matchers.anyOf( Matchers.hasItem(true), Matchers.hasItem(false) ) ); } } @Test @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public void correctValuesForConcurrentHasNextHasNext() throws InterruptedException { for (int iter = 0; iter < 5000; iter += 1) { final List<String> list = Arrays.asList("a", "b"); final SyncIterator<String> iterator = new SyncIterator<>( list.iterator() ); final List<Object> sync = Collections.synchronizedList( new ArrayList<>(list.size()) ); final Runnable first = () -> { sync.add(iterator.hasNext()); }; final Runnable second = () -> { sync.add(iterator.hasNext()); }; final List<Runnable> test = new ArrayList<>(list.size()); test.add(first); test.add(second); new Concurrent(test).launch(); MatcherAssert.assertThat( "Missing hasNext() value(s).", sync, Matchers.contains(true, true) ); } } /** * Tests runnables for concurrency issues. */ private final class Concurrent { /** * Runnables to run in different threads. */ private final List<? extends Runnable> runnables; /** * Collected exceptions. */ private final List<Throwable> exceptions; /** * Thread pool. */ private final ExecutorService pool; /** * All executor threads are ready. */ private final CountDownLatch ready; /** * Start countdown with first thread. */ private final CountDownLatch init; /** * All threads ready. */ private final CountDownLatch done; Concurrent(final List<? extends Runnable> runnables) { this.runnables = runnables; this.exceptions = Collections.synchronizedList( new ArrayList<Throwable>( runnables.size() ) ); this.pool = Executors.newFixedThreadPool(runnables.size()); this.ready = new CountDownLatch(runnables.size()); this.init = new CountDownLatch(1); this.done = new CountDownLatch(runnables.size()); } @SuppressWarnings({"PMD.ProhibitPlainJunitAssertionsRule", "PMD.AvoidCatchingThrowable"}) public void launch() throws InterruptedException { try { for (final Runnable runnable : this.runnables) { this.pool.submit( () -> { this.ready.countDown(); try { this.init.await(); runnable.run(); } catch (final Throwable ex) { this.exceptions.add(ex); } finally { this.done.countDown(); } }); } TestCase.assertTrue( "Timeout initializing threads! Perform longer thread init.", this.ready.await( this.runnables.size() * 20, TimeUnit.MILLISECONDS ) ); this.init.countDown(); TestCase.assertTrue( String.format( "Timeout! More than %d seconds", 10 ), this.done.await(100, TimeUnit.SECONDS) ); } finally { this.pool.shutdownNow(); } TestCase.assertTrue( String.format( "%s failed with exception(s) %s", "Error", this.exceptions.toString() ), this.exceptions.isEmpty() ); } } }
package org.mariadb.jdbc; import org.junit.Before; import org.junit.Test; import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class DatabaseMetadataTest extends BaseTest{ static { Logger.getLogger("").setLevel(Level.OFF); } @Before public void checkSupported() throws SQLException { requireMinimumVersion(5,1); } @Test public void primaryKeysTest() throws SQLException { Statement stmt = connection.createStatement(); stmt.execute("drop table if exists pk_test"); stmt.execute("create table pk_test (val varchar(20), id1 int not null, id2 int not null,primary key(id1, id2)) engine=innodb"); DatabaseMetaData dbmd = connection.getMetaData(); ResultSet rs = dbmd.getPrimaryKeys("test",null,"pk_test"); int i=0; while(rs.next()) { i++; assertEquals("test",rs.getString("table_cat")); assertEquals(null,rs.getString("table_schem")); assertEquals("pk_test",rs.getString("table_name")); assertEquals("id"+i,rs.getString("column_name")); assertEquals(i,rs.getShort("key_seq")); } assertEquals(2,i); } @Test public void primaryKeyTest2() throws SQLException { Statement stmt = connection.createStatement(); stmt.execute("drop table if exists t2"); stmt.execute("drop table if exists t1"); stmt.execute("CREATE TABLE t1 ( id1 integer, constraint pk primary key(id1))"); stmt.execute("CREATE TABLE t2 (id2a integer, id2b integer, constraint pk primary key(id2a, id2b), constraint fk1 foreign key(id2a) references t1(id1), constraint fk2 foreign key(id2b) references t1(id1))"); DatabaseMetaData dbmd = connection.getMetaData(); ResultSet rs = dbmd.getPrimaryKeys("test",null,"t2"); int i=0; while(rs.next()) { i++; assertEquals("test",rs.getString("table_cat")); assertEquals(null,rs.getString("table_schem")); assertEquals("t2",rs.getString("table_name")); assertEquals(i,rs.getShort("key_seq")); } assertEquals(2,i); stmt.execute("drop table if exists t2"); stmt.execute("drop table if exists t1"); } @Test public void datetimeTest() throws SQLException { Statement stmt = connection.createStatement(); stmt.execute("drop table if exists datetime_test"); stmt.execute("create table datetime_test (dt datetime)"); ResultSet rs = stmt.executeQuery("select * from datetime_test"); assertEquals(93,rs.getMetaData().getColumnType(1)); } @Test public void functionColumns() throws SQLException { Statement stmt = connection.createStatement(); DatabaseMetaData md = connection.getMetaData(); if (md.getDatabaseMajorVersion() < 5) return; if (md.getDatabaseMajorVersion() == 5 && md.getDatabaseMinorVersion() < 5) return; stmt.execute("DROP FUNCTION IF EXISTS hello"); stmt.execute("CREATE FUNCTION hello (s CHAR(20), i int) RETURNS CHAR(50) DETERMINISTIC RETURN CONCAT('Hello, ',s,'!')"); ResultSet rs = connection.getMetaData().getFunctionColumns(null, null, "hello", null); rs.next(); /* First row is for return value */ assertEquals(rs.getString("FUNCTION_CAT"),connection.getCatalog()); assertEquals(rs.getString("FUNCTION_SCHEM"), null); assertEquals(rs.getString("COLUMN_NAME"), null); /* No name, since it is return value */ assertEquals(rs.getInt("COLUMN_TYPE"), DatabaseMetaData.functionReturn); assertEquals(rs.getInt("DATA_TYPE"), java.sql.Types.CHAR); assertEquals(rs.getString("TYPE_NAME"), "char"); rs.next(); assertEquals(rs.getString("COLUMN_NAME"), "s"); /* input parameter 's' (CHAR) */ assertEquals(rs.getInt("COLUMN_TYPE"), DatabaseMetaData.functionColumnIn); assertEquals(rs.getInt("DATA_TYPE"), java.sql.Types.CHAR); assertEquals(rs.getString("TYPE_NAME"), "char"); rs.next(); assertEquals(rs.getString("COLUMN_NAME"), "i"); /* input parameter 'i' (INT) */ assertEquals(rs.getInt("COLUMN_TYPE"), DatabaseMetaData.functionColumnIn); assertEquals(rs.getInt("DATA_TYPE"), java.sql.Types.INTEGER); assertEquals(rs.getString("TYPE_NAME"), "int"); } /** Same as getImportedKeys, with one foreign key in a table in another catalog */ @Test public void getImportedKeys() throws Exception{ Statement st = connection.createStatement(); st.execute("DROP TABLE IF EXISTS product_order"); st.execute("DROP TABLE IF EXISTS t1.product "); st.execute("DROP TABLE IF EXISTS `cus``tomer`"); st.execute("DROP DATABASE IF EXISTS test1"); st.execute("CREATE DATABASE IF NOT EXISTS t1"); st.execute("CREATE TABLE t1.product (\n" + " category INT NOT NULL, id INT NOT NULL,\n" + " price DECIMAL,\n" + " PRIMARY KEY(category, id)\n" + ") ENGINE=INNODB"); st.execute("CREATE TABLE `cus``tomer` (\n" + " id INT NOT NULL,\n" + " PRIMARY KEY (id)\n" + ") ENGINE=INNODB"); st.execute("CREATE TABLE product_order (\n" + " no INT NOT NULL AUTO_INCREMENT,\n" + " product_category INT NOT NULL,\n" + " product_id INT NOT NULL,\n" + " customer_id INT NOT NULL,\n" + "\n" + " PRIMARY KEY(no),\n" + " INDEX (product_category, product_id),\n" + " INDEX (customer_id),\n" + "\n" + " FOREIGN KEY (product_category, product_id)\n" + " REFERENCES t1.product(category, id)\n" + " ON UPDATE CASCADE ON DELETE RESTRICT,\n" + "\n" + " FOREIGN KEY (customer_id)\n" + " REFERENCES `cus``tomer`(id)\n" + ") ENGINE=INNODB;" ) ; /* Test that I_S implementation is equivalent to parsing "show create table" . Get result sets using either method and compare (ignore minor differences INT vs SMALLINT */ ResultSet rs1 = ((MySQLDatabaseMetaData)connection.getMetaData()).getImportedKeysUsingShowCreateTable("test", null, "product_order"); ResultSet rs2 = ((MySQLDatabaseMetaData)connection.getMetaData()).getImportedKeysUsingInformationSchema("test", null, "product_order"); assertEquals(rs1.getMetaData().getColumnCount(), rs2.getMetaData().getColumnCount()); while(rs1.next()) { assertTrue(rs2.next()); for (int i = 1; i <= rs1.getMetaData().getColumnCount(); i++) { Object s1 = rs1.getObject(i); Object s2 = rs2.getObject(i); if (s1 instanceof Number && s2 instanceof Number) { assertEquals(((Number)s1).intValue(), ((Number)s2).intValue()); } else { if (s1 != null && s2 != null && !s1.equals(s2)) { assertTrue(false); } assertEquals(s1,s2); } } } /* Also compare metadata */ ResultSetMetaData md1 = rs1.getMetaData(); ResultSetMetaData md2 = rs2.getMetaData(); for (int i = 1; i <= md1.getColumnCount(); i++) { assertEquals(md1.getColumnLabel(i),md2.getColumnLabel(i)); } } @Test public void exportedKeysTest() throws SQLException { Statement stmt = connection.createStatement(); stmt.execute("drop table if exists fore_key0"); stmt.execute("drop table if exists fore_key1"); stmt.execute("drop table if exists prim_key"); stmt.execute("create table prim_key (id int not null primary key, " + "val varchar(20)) engine=innodb"); stmt.execute("create table fore_key0 (id int not null primary key, " + "id_ref0 int, foreign key (id_ref0) references prim_key(id)) engine=innodb"); stmt.execute("create table fore_key1 (id int not null primary key, " + "id_ref1 int, foreign key (id_ref1) references prim_key(id) on update cascade) engine=innodb"); DatabaseMetaData dbmd = connection.getMetaData(); ResultSet rs = dbmd.getExportedKeys("test",null,"prim_key"); int i =0 ; while(rs.next()) { assertEquals("id",rs.getString("pkcolumn_name")); assertEquals("fore_key"+i,rs.getString("fktable_name")); assertEquals("id_ref"+i,rs.getString("fkcolumn_name")); i++; } assertEquals(2,i); } @Test public void importedKeysTest() throws SQLException { Statement stmt = connection.createStatement(); stmt.execute("drop table if exists fore_key0"); stmt.execute("drop table if exists fore_key1"); stmt.execute("drop table if exists prim_key"); stmt.execute("create table prim_key (id int not null primary key, " + "val varchar(20)) engine=innodb"); stmt.execute("create table fore_key0 (id int not null primary key, " + "id_ref0 int, foreign key (id_ref0) references prim_key(id)) engine=innodb"); stmt.execute("create table fore_key1 (id int not null primary key, " + "id_ref1 int, foreign key (id_ref1) references prim_key(id) on update cascade) engine=innodb"); DatabaseMetaData dbmd = connection.getMetaData(); ResultSet rs = dbmd.getImportedKeys(connection.getCatalog(),null,"fore_key0"); int i = 0; while(rs.next()) { assertEquals("id",rs.getString("pkcolumn_name")); assertEquals("prim_key",rs.getString("pktable_name")); i++; } assertEquals(1,i); } @Test public void testGetCatalogs() throws SQLException { DatabaseMetaData dbmd = connection.getMetaData(); ResultSet rs = dbmd.getCatalogs(); boolean haveMysql = false; boolean haveInformationSchema = false; while(rs.next()) { String cat = rs.getString(1); if (cat.equalsIgnoreCase("mysql")) haveMysql = true; else if (cat.equalsIgnoreCase("information_schema")) haveInformationSchema = true; } assertTrue(haveMysql); assertTrue(haveInformationSchema); } @Test public void testGetTables() throws SQLException { DatabaseMetaData dbmd = connection.getMetaData(); ResultSet rs = dbmd.getTables(null,null,"prim_key",null); //mysql 5.5 not compatible if (!isMariadbServer()) requireMinimumVersion(5,6); System.out.println("isMariadbServer() = "+isMariadbServer() + " "+ dbmd.getDatabaseProductVersion()+" "+ dbmd.getDatabaseMajorVersion() + " "+dbmd.getDatabaseMinorVersion()); assertEquals(true,rs.next()); rs = dbmd.getTables("", null,"prim_key",null); assertEquals(true,rs.next()); } @Test public void testGetTables2() throws SQLException { DatabaseMetaData dbmd = connection.getMetaData(); ResultSet rs = dbmd.getTables("information_schema",null,"TABLE_PRIVILEGES",new String[]{"SYSTEM VIEW"}); assertEquals(true, rs.next()); assertEquals(false, rs.next()); rs = dbmd.getTables(null,null,"TABLE_PRIVILEGES",new String[]{"TABLE"}); assertEquals(false, rs.next()); } @Test public void testGetColumns() throws SQLException { DatabaseMetaData dbmd = connection.getMetaData(); ResultSet rs = dbmd.getColumns(null,null,"t1",null); while(rs.next()){ // System.out.println(rs.getString(3)); assertEquals("t1", rs.getString(3)); } } void testResultSetColumns(ResultSet rs, String spec) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); String[] tokens = spec.split(","); for(int i = 0; i < tokens.length; i++) { String[] a = tokens[i].trim().split(" "); String label = a[0]; String type = a[1]; int col = i +1; assertEquals(label,rsmd.getColumnLabel(col)); int t = rsmd.getColumnType(col); if (type.equals("String")) { assertTrue("invalid type " + t + " for " + rsmd.getColumnLabel(col) + ",expected String", t == java.sql.Types.VARCHAR || t == java.sql.Types.NULL || t == Types.LONGVARCHAR ); } else if (type.equals("int") || type.equals("short")) { assertTrue("invalid type " + t + "( " + rsmd.getColumnTypeName(col) + " ) for " + rsmd.getColumnLabel(col) + ",expected numeric", t == java.sql.Types.BIGINT || t == java.sql.Types.INTEGER || t == java.sql.Types.SMALLINT || t == java.sql.Types.TINYINT); } else if (type.equals("boolean")) { assertTrue("invalid type " + t + "( " + rsmd.getColumnTypeName(col) + " ) for " + rsmd.getColumnLabel(col) + ",expected boolean", t == java.sql.Types.BOOLEAN || t == java.sql.Types.BIT); } else if (type.equals("null")){ assertTrue("invalid type " + t + " for " + rsmd.getColumnLabel(col) + ",expected null", t == java.sql.Types.NULL); } else { assertTrue("invalid type '"+ type + "'", false); } } } @Test public void getAttributesBasic()throws Exception { testResultSetColumns( connection.getMetaData().getAttributes(null, null, null, null), "TYPE_CAT String,TYPE_SCHEM String,TYPE_NAME String," +"ATTR_NAME String,DATA_TYPE int,ATTR_TYPE_NAME String,ATTR_SIZE int,DECIMAL_DIGITS int," +"NUM_PREC_RADIX int,NULLABLE int,REMARKS String,ATTR_DEF String,SQL_DATA_TYPE int,SQL_DATETIME_SUB int," +"CHAR_OCTET_LENGTH int,ORDINAL_POSITION int,IS_NULLABLE String,SCOPE_CATALOG String,SCOPE_SCHEMA String," +"SCOPE_TABLE String,SOURCE_DATA_TYPE short"); } @Test public void identifierCaseSensitivity() throws Exception { connection.createStatement().execute("drop table if exists aB"); connection.createStatement().execute("drop table if exists AB"); if (connection.getMetaData().supportsMixedCaseIdentifiers()) { /* Case-sensitive identifier handling, we can create both t1 and T1 */ connection.createStatement().execute("create table aB(i int)"); connection.createStatement().execute("create table AB(i int)"); /* Check there is an entry for both T1 and t1 in getTables */ ResultSet rs = connection.getMetaData().getTables(null, null, "aB", null); assertTrue(rs.next()); assertFalse(rs.next()); rs = connection.getMetaData().getTables(null, null, "AB", null); assertTrue(rs.next()); assertFalse(rs.next()); } if (connection.getMetaData().storesMixedCaseIdentifiers()) { /* Case-insensitive, case-preserving */ connection.createStatement().execute("create table aB(i int)"); try { connection.createStatement().execute("create table AB(i int)"); fail("should not get there, since names are case-insensitive"); } catch (SQLException e) { } /* Check that table is stored case-preserving */ ResultSet rs = connection.getMetaData().getTables(null, null, "aB%", null); while(rs.next()) { String tableName = rs.getString("TABLE_NAME"); if (tableName.length() == 2) { assertEquals("aB",tableName); } } rs = connection.getMetaData().getTables(null, null, "AB", null); assertTrue(rs.next()); assertFalse(rs.next()); } if (connection.getMetaData().storesLowerCaseIdentifiers()) { /* case-insensitive, identifiers converted to lowercase */ /* Case-insensitive, case-preserving */ connection.createStatement().execute("create table aB(i int)"); try { connection.createStatement().execute("create table AB(i int)"); fail("should not get there, since names are case-insensitive"); } catch (SQLException e) { } /* Check that table is stored lowercase */ ResultSet rs = connection.getMetaData().getTables(null, null, "aB%", null); while(rs.next()) { String tableName = rs.getString("TABLE_NAME"); if (tableName.length() == 2) { assertEquals("ab",tableName); } } rs = connection.getMetaData().getTables(null, null, "AB", null); assertTrue(rs.next()); assertFalse(rs.next()); } assertFalse(connection.getMetaData().storesUpperCaseIdentifiers()); } @Test public void getBestRowIdentifierBasic()throws SQLException { testResultSetColumns( connection.getMetaData().getBestRowIdentifier(null, null, "", 0, true), "SCOPE short,COLUMN_NAME String,DATA_TYPE int, TYPE_NAME String," +"COLUMN_SIZE int,BUFFER_LENGTH int," +"DECIMAL_DIGITS short,PSEUDO_COLUMN short"); } @Test public void getClientInfoPropertiesBasic() throws Exception { testResultSetColumns( connection.getMetaData().getClientInfoProperties(), "NAME String, MAX_LEN int, DEFAULT_VALUE String, DESCRIPTION String"); } @Test public void getCatalogsBasic()throws SQLException { testResultSetColumns( connection.getMetaData().getCatalogs(), "TABLE_CAT String"); } @Test public void getColumnsBasic()throws SQLException { testResultSetColumns(connection.getMetaData().getColumns(null, null, null, null), "TABLE_CAT String,TABLE_SCHEM String,TABLE_NAME String,COLUMN_NAME String," +"DATA_TYPE int,TYPE_NAME String,COLUMN_SIZE int,BUFFER_LENGTH int," +"DECIMAL_DIGITS int,NUM_PREC_RADIX int,NULLABLE int," +"REMARKS String,COLUMN_DEF String,SQL_DATA_TYPE int," +"SQL_DATETIME_SUB int, CHAR_OCTET_LENGTH int," +"ORDINAL_POSITION int,IS_NULLABLE String," +"SCOPE_CATALOG String,SCOPE_SCHEMA String," +"SCOPE_TABLE String,SOURCE_DATA_TYPE null"); } @Test public void getProcedureColumnsBasic() throws SQLException { testResultSetColumns(connection.getMetaData().getProcedureColumns(null, null, null, null), "PROCEDURE_CAT String,PROCEDURE_SCHEM String,PROCEDURE_NAME String,COLUMN_NAME String ,COLUMN_TYPE short," +"DATA_TYPE int,TYPE_NAME String,PRECISION int,LENGTH int,SCALE short,RADIX short,NULLABLE short," +"REMARKS String,COLUMN_DEF String,SQL_DATA_TYPE int,SQL_DATETIME_SUB int ,CHAR_OCTET_LENGTH int," +"ORDINAL_POSITION int,IS_NULLABLE String,SPECIFIC_NAME String"); } @Test public void getFunctionColumnsBasic() throws SQLException { testResultSetColumns(connection.getMetaData().getFunctionColumns(null, null, null, null), "FUNCTION_CAT String,FUNCTION_SCHEM String,FUNCTION_NAME String,COLUMN_NAME String,COLUMN_TYPE short," +"DATA_TYPE int,TYPE_NAME String,PRECISION int,LENGTH int,SCALE short,RADIX short,NULLABLE short,REMARKS String," +"CHAR_OCTET_LENGTH int,ORDINAL_POSITION int,IS_NULLABLE String,SPECIFIC_NAME String"); } @Test public void getColumnPrivilegesBasic()throws SQLException { testResultSetColumns( connection.getMetaData().getColumnPrivileges(null, null,"", null), "TABLE_CAT String,TABLE_SCHEM String,TABLE_NAME String,COLUMN_NAME String," + "GRANTOR String,GRANTEE String,PRIVILEGE String,IS_GRANTABLE String"); } @Test public void getTablePrivilegesBasic()throws SQLException { testResultSetColumns( connection.getMetaData().getTablePrivileges(null, null, null), "TABLE_CAT String,TABLE_SCHEM String,TABLE_NAME String,GRANTOR String," +"GRANTEE String,PRIVILEGE String,IS_GRANTABLE String"); } @Test public void getVersionColumnsBasic()throws SQLException { testResultSetColumns( connection.getMetaData().getVersionColumns(null, null, null), "SCOPE short, COLUMN_NAME String,DATA_TYPE int,TYPE_NAME String," +"COLUMN_SIZE int,BUFFER_LENGTH int,DECIMAL_DIGITS short," +"PSEUDO_COLUMN short"); } @Test public void getPrimaryKeysBasic()throws SQLException { testResultSetColumns( connection.getMetaData().getPrimaryKeys(null, null, null), "TABLE_CAT String,TABLE_SCHEM String,TABLE_NAME String,COLUMN_NAME String,KEY_SEQ short,PK_NAME String" ); } @Test public void getImportedKeysBasic()throws SQLException { testResultSetColumns( connection.getMetaData().getImportedKeys(null, null, ""), "PKTABLE_CAT String,PKTABLE_SCHEM String,PKTABLE_NAME String, PKCOLUMN_NAME String,FKTABLE_CAT String," +"FKTABLE_SCHEM String,FKTABLE_NAME String,FKCOLUMN_NAME String,KEY_SEQ short,UPDATE_RULE short," +"DELETE_RULE short,FK_NAME String,PK_NAME String,DEFERRABILITY short"); } @Test public void getExportedKeysBasic()throws SQLException { testResultSetColumns( connection.getMetaData().getExportedKeys(null, null, ""), "PKTABLE_CAT String,PKTABLE_SCHEM String,PKTABLE_NAME String, PKCOLUMN_NAME String,FKTABLE_CAT String," +"FKTABLE_SCHEM String,FKTABLE_NAME String,FKCOLUMN_NAME String,KEY_SEQ short,UPDATE_RULE short," +"DELETE_RULE short,FK_NAME String,PK_NAME String,DEFERRABILITY short"); } @Test public void getCrossReferenceBasic()throws SQLException { testResultSetColumns( connection.getMetaData().getCrossReference(null, null, "", null, null, ""), "PKTABLE_CAT String,PKTABLE_SCHEM String,PKTABLE_NAME String, PKCOLUMN_NAME String,FKTABLE_CAT String," +"FKTABLE_SCHEM String,FKTABLE_NAME String,FKCOLUMN_NAME String,KEY_SEQ short,UPDATE_RULE short," +"DELETE_RULE short,FK_NAME String,PK_NAME String,DEFERRABILITY short"); } @Test public void getUDTsBasic() throws SQLException { testResultSetColumns( connection.getMetaData().getUDTs(null, null, null, null), "TYPE_CAT String,TYPE_SCHEM String,TYPE_NAME String,CLASS_NAME String,DATA_TYPE int," +"REMARKS String,BASE_TYPE short" ); } @Test public void getSuperTypesBasic() throws SQLException { testResultSetColumns( connection.getMetaData().getSuperTypes(null, null, null), "TYPE_CAT String,TYPE_SCHEM String,TYPE_NAME String,SUPERTYPE_CAT String," +"SUPERTYPE_SCHEM String,SUPERTYPE_NAME String"); } @Test public void getFunctionsBasic() throws SQLException { testResultSetColumns( connection.getMetaData().getFunctions(null, null, null), "FUNCTION_CAT String, FUNCTION_SCHEM String,FUNCTION_NAME String,REMARKS String,FUNCTION_TYPE short, " +"SPECIFIC_NAME String"); } @Test public void getSuperTablesBasic() throws SQLException { testResultSetColumns( connection.getMetaData().getSuperTables(null, null, null), "TABLE_CAT String,TABLE_SCHEM String,TABLE_NAME String, SUPERTABLE_NAME String") ; } @Test public void testGetSchemas2() throws SQLException { DatabaseMetaData dbmd = connection.getMetaData(); ResultSet rs = dbmd.getCatalogs(); boolean foundTestUnitsJDBC = false; while(rs.next()) { if(rs.getString(1).equals("test")) foundTestUnitsJDBC=true; } assertEquals(true,foundTestUnitsJDBC); } /* Verify default behavior for nullCatalogMeansCurrent (=true) */ @Test public void nullCatalogMeansCurrent() throws Exception { String catalog = connection.getCatalog(); ResultSet rs = connection.getMetaData().getColumns(null, null, null, null); while(rs.next()) { assertTrue(rs.getString("TABLE_CAT").equalsIgnoreCase(catalog)); } } /* Verify that "nullCatalogMeansCurrent=false" works (i.e information_schema columns are returned)*/ @Test public void nullCatalogMeansCurrent2() throws Exception { setConnection("&nullCatalogMeansCurrent=false"); boolean haveInformationSchema = false; try { ResultSet rs = connection.getMetaData().getColumns(null, null, null, null); while(rs.next()) { if (rs.getString("TABLE_CAT").equalsIgnoreCase("information_schema")) { haveInformationSchema = true; break; } } } finally { } assertTrue(haveInformationSchema); } @Test public void testGetTypeInfoBasic() throws SQLException { testResultSetColumns( connection.getMetaData().getTypeInfo(), "TYPE_NAME String,DATA_TYPE int,PRECISION int,LITERAL_PREFIX String," + "LITERAL_SUFFIX String,CREATE_PARAMS String, NULLABLE short,CASE_SENSITIVE boolean," + "SEARCHABLE short,UNSIGNED_ATTRIBUTE boolean,FIXED_PREC_SCALE boolean, AUTO_INCREMENT boolean," + "LOCAL_TYPE_NAME String,MINIMUM_SCALE short,MAXIMUM_SCALE short,SQL_DATA_TYPE int,SQL_DATETIME_SUB int," + "NUM_PREC_RADIX int"); } static void checkType(String name, int actualType, String colName, int expectedType) { if (name.equals(colName)) assertEquals(actualType, expectedType); } @Test public void getColumnsTest() throws SQLException { connection.createStatement().execute( "CREATE TABLE IF NOT EXISTS `manycols` (\n" + " `tiny` tinyint(4) DEFAULT NULL,\n" + " `tiny_uns` tinyint(3) unsigned DEFAULT NULL,\n" + " `small` smallint(6) DEFAULT NULL,\n" + " `small_uns` smallint(5) unsigned DEFAULT NULL,\n" + " `medium` mediumint(9) DEFAULT NULL,\n" + " `medium_uns` mediumint(8) unsigned DEFAULT NULL,\n" + " `int_col` int(11) DEFAULT NULL,\n" + " `int_col_uns` int(10) unsigned DEFAULT NULL,\n" + " `big` bigint(20) DEFAULT NULL,\n" + " `big_uns` bigint(20) unsigned DEFAULT NULL,\n" + " `decimal_col` decimal(10,5) DEFAULT NULL,\n" + " `fcol` float DEFAULT NULL,\n" + " `fcol_uns` float unsigned DEFAULT NULL,\n" + " `dcol` double DEFAULT NULL,\n" + " `dcol_uns` double unsigned DEFAULT NULL,\n" + " `date_col` date DEFAULT NULL,\n" + " `time_col` time DEFAULT NULL,\n" + " `timestamp_col` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE\n" + "CURRENT_TIMESTAMP,\n" + " `year_col` year(4) DEFAULT NULL,\n" + " `bit_col` bit(5) DEFAULT NULL,\n" + " `char_col` char(5) DEFAULT NULL,\n" + " `varchar_col` varchar(10) DEFAULT NULL,\n" + " `binary_col` binary(10) DEFAULT NULL,\n" + " `varbinary_col` varbinary(10) DEFAULT NULL,\n" + " `tinyblob_col` tinyblob,\n" + " `blob_col` blob,\n" + " `mediumblob_col` mediumblob,\n" + " `longblob_col` longblob,\n" + " `text_col` text,\n" + " `mediumtext_col` mediumtext,\n" + " `longtext_col` longtext\n" + ")" ); DatabaseMetaData dmd = connection.getMetaData(); ResultSet rs = dmd.getColumns(connection.getCatalog(), null, "manycols", null); while(rs.next()) { String columnName = rs.getString("column_name"); int type = rs.getInt("data_type"); String typeName = rs.getString("type_name"); assertTrue(typeName.indexOf("(") == -1); for(char c : typeName.toCharArray()) { assertTrue("bad typename " + typeName, c == ' ' || Character.isUpperCase(c)); } checkType(columnName, type, "tiny", Types.TINYINT); checkType(columnName, type, "tiny_uns", Types.TINYINT); checkType(columnName, type, "small", Types.SMALLINT); checkType(columnName, type, "small_uns", Types.SMALLINT); checkType(columnName, type, "medium", Types.INTEGER); checkType(columnName, type, "medium_uns", Types.INTEGER); checkType(columnName, type, "int_col", Types.INTEGER); checkType(columnName, type, "int_col_uns", Types.INTEGER); checkType(columnName, type, "big", Types.BIGINT); checkType(columnName, type, "big_uns", Types.BIGINT); checkType(columnName, type, "decimal_col",Types.DECIMAL); checkType(columnName, type, "fcol", Types.REAL); checkType(columnName, type, "fcol_uns", Types.REAL); checkType(columnName, type, "dcol", Types.DOUBLE); checkType(columnName, type, "dcol_uns", Types.DOUBLE); checkType(columnName, type, "date_col", Types.DATE); checkType(columnName, type, "time_col", Types.TIME); checkType(columnName, type, "timestamp_col", Types.TIMESTAMP); checkType(columnName, type, "year_col", Types.DATE); checkType(columnName, type, "bit_col", Types.BIT); checkType(columnName, type, "char_col", Types.CHAR); checkType(columnName, type, "varchar_col", Types.VARCHAR); checkType(columnName, type, "binary_col", Types.BINARY); checkType(columnName, type, "tinyblob_col", Types.LONGVARBINARY); checkType(columnName, type, "blob_col", Types.LONGVARBINARY); checkType(columnName, type, "longblob_col", Types.LONGVARBINARY); checkType(columnName, type, "mediumblob_col", Types.LONGVARBINARY); checkType(columnName, type, "text_col", Types.LONGVARCHAR); checkType(columnName, type, "mediumtext_col", Types.LONGVARCHAR); checkType(columnName, type, "longtext_col", Types.LONGVARCHAR); } } @Test public void yearIsShortType() throws Exception { setConnection("&yearIsDateType=false"); try { connection.createStatement().execute("CREATE TABLE IF NOT EXISTS ytab (y year)"); connection.createStatement().execute("insert into ytab values(72)"); ResultSet rs = connection.getMetaData().getColumns(connection.getCatalog(), null, "ytab", null); assertTrue(rs.next()); assertEquals(rs.getInt("DATA_TYPE"),Types.SMALLINT); ResultSet rs1 = connection.createStatement().executeQuery("select * from ytab"); assertEquals(rs1.getMetaData().getColumnType(1), Types.SMALLINT); assertTrue(rs1.next()); assertTrue(rs1.getObject(1) instanceof Short); assertEquals(rs1.getShort(1), 1972); } finally { } } /* CONJ-15 */ @Test public void maxCharLengthUTF8() throws Exception { connection.createStatement().execute("CREATE TABLE IF NOT EXISTS maxcharlength (maxcharlength char(1)) character set utf8"); DatabaseMetaData dmd = connection.getMetaData(); ResultSet rs = dmd.getColumns(connection.getCatalog(), null, "maxcharlength", null); assertTrue(rs.next()); assertEquals(rs.getInt("COLUMN_SIZE"),1); } @Test public void conj72() throws Exception { setConnection("&tinyInt1isBit=true"); try { connection.createStatement().execute("CREATE TABLE IF NOT EXISTS conj72 (t tinyint(1))"); connection.createStatement().execute("insert into conj72 values(1)"); ResultSet rs = connection.getMetaData().getColumns(connection.getCatalog(), null, "conj72", null); assertTrue(rs.next()); assertEquals(rs.getInt("DATA_TYPE"),Types.BIT); ResultSet rs1 = connection.createStatement().executeQuery("select * from conj72"); assertEquals(rs1.getMetaData().getColumnType(1), Types.BIT); } finally { } } }
package programminglife.gui; import javafx.scene.input.KeyCode; import javafx.stage.Stage; import org.junit.*; import org.testfx.api.FxRobot; import org.testfx.api.FxToolkit; import org.testfx.util.WaitForAsyncUtils; import programminglife.ProgrammingLife; import java.io.File; import java.net.URISyntaxException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static org.junit.Assert.assertTrue; /** * This test class is there to interactively test the GUI. It is capable of clicking on certain buttons and items * that are present within the GUI. It is important however not to move the mouse during this process!!! * This is only usable if you have a USA QWERTY layout on your keyboard!!! */ public class GuiControllerTest extends FxRobot { private static Stage primaryStage; private ProgrammingLife pl; private String f; private static String OS = System.getProperty("os.name").toLowerCase(); public GuiControllerTest() { try { f = new File(getClass().getResource("/test.gfa").toURI()).getAbsolutePath(); } catch (URISyntaxException e) { f = null; } } @BeforeClass public static void setUpClass() { try { primaryStage = FxToolkit.registerPrimaryStage(); } catch (TimeoutException e) { e.printStackTrace(); } } @Before public void setUp() { try { this.pl = (ProgrammingLife) FxToolkit.setupApplication(ProgrammingLife.class); WaitForAsyncUtils.waitFor(10, TimeUnit.SECONDS, primaryStage.showingProperty()); } catch (TimeoutException e) { e.printStackTrace(); } } @Test public void isActive() { assertTrue(primaryStage.isShowing()); } /** * This test will open a file that has been added to the test resources. It uses the FXML that is also used * by the main class and relies heavily on that class. */ @Test public void clickOnTest() { assertTrue(primaryStage.isShowing()); clickOn("#menuFile"); clickOn("#btnOpen"); sleep(1, TimeUnit.SECONDS); for (int i = 0; i < f.length(); i++) { KeyCode kc = KeyCode.getKeyCode(f.toUpperCase().charAt(i) + ""); switch (f.charAt(i)) { case ':': press(KeyCode.SHIFT).type(KeyCode.SEMICOLON); release(KeyCode.SHIFT); continue; case ')': press(KeyCode.SHIFT).type(KeyCode.DIGIT0); release(KeyCode.SHIFT); continue; case '(': press(KeyCode.SHIFT).type(KeyCode.DIGIT9); release(KeyCode.SHIFT); continue; case '*': press(KeyCode.SHIFT).type(KeyCode.DIGIT8); release(KeyCode.SHIFT); continue; case '&': press(KeyCode.SHIFT).type(KeyCode.DIGIT7); release(KeyCode.SHIFT); continue; case '^' : press(KeyCode.SHIFT).type(KeyCode.DIGIT6); release(KeyCode.SHIFT); continue; case '%' : press(KeyCode.SHIFT).type(KeyCode.DIGIT5); release(KeyCode.SHIFT); continue; case '$' : press(KeyCode.SHIFT).type(KeyCode.DIGIT4); release(KeyCode.SHIFT); continue; case ' press(KeyCode.SHIFT).type(KeyCode.DIGIT3); release(KeyCode.SHIFT); continue; case '@' : press(KeyCode.SHIFT).type(KeyCode.DIGIT2); release(KeyCode.SHIFT); continue; case '!' : press(KeyCode.SHIFT).type(KeyCode.DIGIT1); release(KeyCode.SHIFT); continue; case '_' : press(KeyCode.SHIFT).type(KeyCode.MINUS); release(KeyCode.SHIFT); continue; case '+' : press(KeyCode.SHIFT).type(KeyCode.EQUALS); release(KeyCode.SHIFT); continue; case '"' : press(KeyCode.SHIFT).type(KeyCode.QUOTE); release(KeyCode.SHIFT); continue; case '?' : press(KeyCode.SHIFT).type(KeyCode.SLASH); release(KeyCode.SHIFT); continue; case '>' : press(KeyCode.SHIFT).type(KeyCode.PERIOD); release(KeyCode.SHIFT); continue; case '<' : press(KeyCode.SHIFT).type(KeyCode.COMMA); release(KeyCode.SHIFT); continue; case '{' : press(KeyCode.SHIFT).type(KeyCode.OPEN_BRACKET); release(KeyCode.SHIFT); continue; case '}' : press(KeyCode.SHIFT).type(KeyCode.CLOSE_BRACKET); release(KeyCode.SHIFT); continue; case '~' : press(KeyCode.SHIFT).type(KeyCode.BACK_QUOTE); release(KeyCode.SHIFT); continue; case '`' : kc = KeyCode.BACK_QUOTE; break; case '[' : kc = KeyCode.OPEN_BRACKET; break; case ']' : kc = KeyCode.CLOSE_BRACKET; break; case '\'' : kc = KeyCode.QUOTE; break; case ',' : kc = KeyCode.COMMA; break; case '.' : kc = KeyCode.PERIOD; break; case '-' : kc = KeyCode.MINUS; break; case '=' : kc = KeyCode.EQUALS; break; case ' ' : kc = KeyCode.SPACE; break; case ';' : kc = KeyCode.SEMICOLON; break; case '/' : kc = KeyCode.SLASH; break; case '\\' : kc = KeyCode.BACK_SLASH; break; } type(kc); } type(KeyCode.ENTER); if(OS.contains("mac")) { sleep(500, TimeUnit.MILLISECONDS); type(KeyCode.ENTER); } sleep(5, TimeUnit.SECONDS); //backspace to remove the initial values. clickOn("#txtMaxDrawDepth").type(KeyCode.BACK_SPACE); clickOn("#txtMaxDrawDepth").type(KeyCode.DIGIT9); clickOn("#txtCenterNode").type(KeyCode.BACK_SPACE); clickOn("#txtCenterNode").type(KeyCode.DIGIT1); clickOn("#btnDraw"); clickOn("#btnZoomIn"); clickOn("#btnZoomOut"); clickOn("#btnZoomReset"); clickOn("#btnDrawRandom"); sleep(1, TimeUnit.SECONDS); clickOn("#menuHelp"); clickOn("#btnAbout"); sleep(500); type(KeyCode.ENTER); clickOn("#menuHelp"); clickOn("#btnInstructions"); sleep(500); type(KeyCode.ENTER); } }
package seedu.address.storage; import java.io.File; import org.junit.Test; import static org.junit.Assert.assertTrue; import guitests.AddressBookGuiTest; public class SaveCommandTest extends AddressBookGuiTest { private static final String TEST_SAVE_DIRECTORY = "src/test/data/testfile.xml"; @Test public void save_withDefaultTestPath() { assertSave(TEST_SAVE_DIRECTORY); } private void assertSave(String saveDirectory) { String saveCommand = "save " + saveDirectory; commandBox.runCommand(saveCommand); assertSaveFileExists(saveDirectory); } private void assertSaveFileExists(String saveDirectory) { File testSaveFile = new File(saveDirectory); assertTrue(testSaveFile.exists()); testSaveFile.delete(); } }
//@@author A0138848M package seedu.oneline.model.task; import static org.junit.Assert.*; import java.util.Calendar; import seedu.oneline.commons.exceptions.IllegalValueException; import org.apache.commons.lang.time.DateUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class TaskTimeTest { Calendar now; Calendar yesterday; Calendar tomorrow; int thisDay; int thisMonth; int thisYear; @Before public void setUp(){ now = Calendar.getInstance(); yesterday = Calendar.getInstance(); yesterday.add(Calendar.DATE, -1); tomorrow = Calendar.getInstance(); tomorrow.add(Calendar.DATE, -1); thisDay = now.get(Calendar.DAY_OF_MONTH); thisMonth = now.get(Calendar.MONTH); thisYear = now.get(Calendar.YEAR); } @Rule public ExpectedException thrown = ExpectedException.none(); private void IllegalValueExceptionThrown(String inputDateTime, String errorMessage) throws Exception{ thrown.expect(IllegalValueException.class); thrown.expectMessage(errorMessage); new TaskTime(inputDateTime); } // Tests for invalid datetime inputs to TaskTime constructor /** * Invalid equivalence partitions for datetime: null, other strings */ @Test public void constructor_nullDateTime_assertionThrown() { thrown.expect(AssertionError.class); try { new TaskTime(null); } catch (IllegalValueException e){ assert false; } } @Test public void constructor_unsupportedDateTimeFormats_assertionThrown() throws Exception { IllegalValueExceptionThrown("day after", TaskTime.MESSAGE_TASK_TIME_CONSTRAINTS); IllegalValueExceptionThrown("clearly not a time format", TaskTime.MESSAGE_TASK_TIME_CONSTRAINTS); IllegalValueExceptionThrown("T u e s d a y", TaskTime.MESSAGE_TASK_TIME_CONSTRAINTS); } // Tests for valid datetime inputs /** * Valid equivalence partitions for datetime: * - day month and year specified * - only day and month specified * - only day specified * - relative date specified * - empty string */ @Test public void constructor_emptyDateTime() { try { TaskTime t = new TaskTime(""); assert t.getDate() == null; } catch (Exception e) { assert false; } } @Test public void constructor_DMY() { String[] validFormats = new String[]{ "5 October 2016", "5 Oct 16", "Oct 5 16", "10/5/16", "10/05/16"}; try { for (String t : validFormats){ TaskTime tTime = new TaskTime(t); Calendar tCal = DateUtils.toCalendar(tTime.getDate()); assertTrue(tCal.get(Calendar.DAY_OF_MONTH) == 5); assertTrue(tCal.get(Calendar.MONTH) == Calendar.OCTOBER); assertTrue(tCal.get(Calendar.YEAR) == 2016); } } catch (Exception e) { assert false; } } /** * Equivalence partitions for fields with only date and month input * - day and month has passed in current year * - day and month has not passed in current year * - day and month is the current day */ @Test public void constructor_DM() { String[] validFormats = new String[]{ "5 October", "5 Oct", "10/5"}; try { for (String t : validFormats){ Calendar fifthOct = Calendar.getInstance(); fifthOct.set(thisYear, Calendar.OCTOBER, 5); TaskTime tTime = new TaskTime(t); Calendar tCal = DateUtils.toCalendar(tTime.getDate()); assertTrue(tCal.get(Calendar.DAY_OF_MONTH) == 5); assertTrue(tCal.get(Calendar.MONTH) == Calendar.OCTOBER); // checks if date refers to previous year if day has passed assertTrue(now.compareTo(fifthOct) > 0 ? tCal.get(Calendar.YEAR) == thisYear + 1 : tCal.get(Calendar.YEAR) == thisYear); } } catch (Exception e) { assert false; } } /** * Tests whether inputting a day and month that has passed will result * in next year's value in TaskTime object */ @Test public void constructor_DMhasPassed() { // construct a string that represents MM/DD // where MM/DD is the month and date of yesterday String yesterdayString = Integer.toString(yesterday.get(Calendar.DAY_OF_MONTH)) + " " + Integer.toString(yesterday.get(Calendar.MONTH)); try { TaskTime tTime = new TaskTime(yesterdayString); Calendar tCal = DateUtils.toCalendar(tTime.getDate()); assertTrue(tCal.get(Calendar.YEAR) == yesterday.get(Calendar.YEAR) + 1); } catch (Exception e) { assert false; } } /** * Tests whether inputting today's day and month causes * the year stored in TaskTime to remain the same as today's year */ @Test public void constructor_DMToday() { String todayString = Integer.toString(thisMonth) + " " + Integer.toString(thisDay); try { TaskTime tTime = new TaskTime(todayString); Calendar tCal = DateUtils.toCalendar(tTime.getDate()); assertTrue(tCal.get(Calendar.YEAR) == thisYear); } catch (Exception e) { assert false; } } /** * Tests whether inputting tomorrow's day and month causes * the year stored in TaskTime to remain the same as tomorrow's year */ @Test public void constructor_DMFuture() { // construct a string that represents MM/DD // where MM/DD is the month and date of tomorrow String tomorrowString = Integer.toString(tomorrow.get(Calendar.DAY_OF_MONTH)) + " " + Integer.toString(tomorrow.get(Calendar.MONTH)); try { TaskTime tTime = new TaskTime(tomorrowString); Calendar tCal = DateUtils.toCalendar(tTime.getDate()); assertTrue(tCal.get(Calendar.YEAR) == tomorrow.get(Calendar.YEAR)); } catch (Exception e) { assert false; } } }
package seedu.taskboss.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX; import static seedu.taskboss.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.common.eventbus.Subscribe; import seedu.taskboss.commons.core.EventsCenter; import seedu.taskboss.commons.events.model.TaskBossChangedEvent; import seedu.taskboss.commons.events.ui.JumpToListRequestEvent; import seedu.taskboss.commons.events.ui.ShowHelpRequestEvent; import seedu.taskboss.commons.exceptions.IllegalValueException; import seedu.taskboss.logic.commands.AddCommand; import seedu.taskboss.logic.commands.ClearCommand; import seedu.taskboss.logic.commands.Command; import seedu.taskboss.logic.commands.CommandResult; import seedu.taskboss.logic.commands.DeleteCommand; import seedu.taskboss.logic.commands.ExitCommand; import seedu.taskboss.logic.commands.FindCommand; import seedu.taskboss.logic.commands.HelpCommand; import seedu.taskboss.logic.commands.ListCommand; import seedu.taskboss.logic.commands.SelectCommand; import seedu.taskboss.logic.commands.exceptions.CommandException; import seedu.taskboss.logic.commands.exceptions.InvalidDatesException; import seedu.taskboss.logic.parser.DateTimeParser; import seedu.taskboss.model.Model; import seedu.taskboss.model.ModelManager; import seedu.taskboss.model.ReadOnlyTaskBoss; import seedu.taskboss.model.TaskBoss; import seedu.taskboss.model.category.Category; import seedu.taskboss.model.category.UniqueCategoryList; import seedu.taskboss.model.task.DateTime; import seedu.taskboss.model.task.Information; import seedu.taskboss.model.task.Name; import seedu.taskboss.model.task.PriorityLevel; import seedu.taskboss.model.task.ReadOnlyTask; import seedu.taskboss.model.task.Task; import seedu.taskboss.storage.StorageManager; public class LogicManagerTest { @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; // These are for checking the correctness of the events raised private ReadOnlyTaskBoss latestSavedTaskBoss; private boolean helpShown; private int targetedJumpIndex; @Subscribe private void handleLocalModelChangedEvent(TaskBossChangedEvent abce) { latestSavedTaskBoss = new TaskBoss(abce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setUp() { model = new ModelManager(); String tempTaskBossFile = saveFolder.getRoot().getPath() + "TempTaskBoss.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempTaskBossFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedTaskBoss = new TaskBoss(model.getTaskBoss()); // last saved // assumed to be up to date helpShown = false; targetedJumpIndex = -1; // non yet } @After public void tearDown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() throws IllegalValueException, InvalidDatesException { String invalidCommand = " "; assertCommandFailure(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } private void assertCommandSuccess(String inputCommand, String expectedMessage, ReadOnlyTaskBoss expectedTaskBoss, List<? extends ReadOnlyTask> expectedShownList) throws IllegalValueException, InvalidDatesException { assertCommandBehavior(false, inputCommand, expectedMessage, expectedTaskBoss, expectedShownList); } private void assertCommandFailure(String inputCommand, String expectedMessage) throws IllegalValueException, InvalidDatesException { TaskBoss expectedTaskBoss = new TaskBoss(model.getTaskBoss()); List<ReadOnlyTask> expectedShownList = new ArrayList<>(model.getFilteredTaskList()); assertCommandBehavior(true, inputCommand, expectedMessage, expectedTaskBoss, expectedShownList); } private void assertCommandBehavior(boolean isCommandExceptionExpected, String inputCommand, String expectedMessage, ReadOnlyTaskBoss expectedTaskBoss, List<? extends ReadOnlyTask> expectedShownList) throws IllegalValueException, InvalidDatesException { try { CommandResult result = logic.execute(inputCommand); assertFalse("CommandException expected but was not thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, result.feedbackToUser); } catch (CommandException e) { assertTrue("CommandException not expected but was thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, e.getMessage()); } // Confirm the ui display elements should contain the right data assertEquals(expectedShownList, model.getFilteredTaskList()); // Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedTaskBoss, model.getTaskBoss()); assertEquals(expectedTaskBoss, latestSavedTaskBoss); } @Test public void execute_unknownCommandWord() throws IllegalValueException, InvalidDatesException { String unknownCommand = "uicfhmowqewca"; assertCommandFailure(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() throws IllegalValueException, InvalidDatesException { assertCommandSuccess("help", HelpCommand.SHOWING_HELP_MESSAGE, new TaskBoss(), Collections.emptyList()); assertTrue(helpShown); } @Test public void execute_helpShortCommand() throws IllegalValueException, InvalidDatesException { assertCommandSuccess("h", HelpCommand.SHOWING_HELP_MESSAGE, new TaskBoss(), Collections.emptyList()); assertTrue(helpShown); } @Test public void execute_exit() throws IllegalValueException, InvalidDatesException { assertCommandSuccess("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT, new TaskBoss(), Collections.emptyList()); } @Test public void execute_exitShortCommand() throws IllegalValueException, InvalidDatesException { assertCommandSuccess("x", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT, new TaskBoss(), Collections.emptyList()); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generateTask(1)); model.addTask(helper.generateTask(2)); model.addTask(helper.generateTask(3)); assertCommandSuccess("clear", ClearCommand.MESSAGE_SUCCESS, new TaskBoss(), Collections.emptyList()); } @Test public void execute_add_invalidArgsFormat() throws IllegalValueException, InvalidDatesException { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); assertCommandFailure("add Valid Name p/Yes sd/today ed/tomorrow", expectedMessage); } @Test public void execute_add_invalidTaskData() throws IllegalValueException, InvalidDatesException { assertCommandFailure("add n/[]\\[;] p/Yes sd/today ed/tomorrow i/valid, information", Name.MESSAGE_NAME_CONSTRAINTS); assertCommandFailure("add n/Valid Name p/not_Yes_No sd/today ed/tomorrow i/valid, information", PriorityLevel.MESSAGE_PRIORITY_CONSTRAINTS); assertCommandFailure("add n/Valid Name p/Yes sd/today ed/tomorrow " + "i/valid, information c/invalid_-[.category", Category.MESSAGE_CATEGORY_CONSTRAINTS); assertCommandFailure("add n/Valid Name p/Yes sd/today to next week ed/tomorrow i/valid, information", DateTimeParser.getMultipleDatesError()); assertCommandFailure("add n/Valid Name p/Yes sd/invalid date ed/tomorroq i/valid, information", DateTime.MESSAGE_DATE_CONSTRAINTS); } @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); TaskBoss expectedAB = new TaskBoss(); expectedAB.addTask(toBeAdded); // execute command and verify result assertCommandSuccess(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); // setup starting state model.addTask(toBeAdded); // task already in internal TaskBoss // execute command and verify result assertCommandFailure(helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK); } @Test public void execute_list_showsAllTasks() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); TaskBoss expectedTB = helper.generateTaskBoss(2); List<? extends ReadOnlyTask> expectedList = expectedTB.getTaskList(); // prepare TaskBoss state helper.addToModel(model, 2); assertCommandSuccess("list", ListCommand.MESSAGE_SUCCESS, expectedTB, expectedList); } @Test public void execute_listShortCommand_showsAllTasks() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); TaskBoss expectedTB = helper.generateTaskBoss(2); List<? extends ReadOnlyTask> expectedList = expectedTB.getTaskList(); // prepare TaskBoss state helper.addToModel(model, 2); assertCommandSuccess("l", ListCommand.MESSAGE_SUCCESS, expectedTB, expectedList); } /** * Confirms the 'invalid argument index number behaviour' for the given * command targeting a single task in the shown list, using visible index. * * @param commandWord to test assuming it targets a single task in the last shown * list based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandFailure(commandWord, expectedMessage); // index missing assertCommandFailure(commandWord + " +1", expectedMessage); // index should be unsigned assertCommandFailure(commandWord + " -1", expectedMessage); // index should be unsigned assertCommandFailure(commandWord + " 0", expectedMessage); assertCommandFailure(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given * command targeting a single task in the shown list, using visible index. * * @param commandWord * to test assuming it targets a single task in the last shown * list based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<Task> taskList = helper.generateTaskList(2); // set AB state to 2 tasks model.resetData(new TaskBoss()); for (Task p : taskList) { model.addTask(p); } assertCommandFailure(commandWord + " 3", expectedMessage); } @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } @Test public void execute_select_jumpsToCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); TaskBoss expectedAB = helper.generateTaskBoss(threeTasks); helper.addToModel(model, threeTasks); assertCommandSuccess("select 2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1)); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); } @Test public void execute_delete_removesCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); TaskBoss expectedAB = helper.generateTaskBoss(threeTasks); expectedAB.removeTask(threeTasks.get(1)); helper.addToModel(model, threeTasks); assertCommandSuccess("delete 2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeTasks.get(1)), expectedAB, expectedAB.getTaskList()); } @Test public void execute_find_invalidArgsFormat() throws IllegalValueException, InvalidDatesException { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandFailure("find ", expectedMessage); } @Test public void execute_findName_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p1 = helper.generateTaskWithName("KE Y"); Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo"); List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2); TaskBoss expectedAB = helper.generateTaskBoss(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2); helper.addToModel(model, fourTasks); assertCommandSuccess("find n/KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_findName_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateTaskWithName("bla bla KEY bla"); Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p3 = helper.generateTaskWithName("key key"); Task p4 = helper.generateTaskWithName("KEy sduauo"); List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2); TaskBoss expectedAB = helper.generateTaskBoss(fourTasks); List<Task> expectedList = fourTasks; helper.addToModel(model, fourTasks); assertCommandSuccess("find n/KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_findName_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia"); Task pTarget3 = helper.generateTaskWithName("key key"); Task p1 = helper.generateTaskWithName("sduauo"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3); TaskBoss expectedAB = helper.generateTaskBoss(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourTasks); assertCommandSuccess("find n/key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_findStartDatetime_matchesOnlyIfKeywordPresentInOrder() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithStartDateTime("Monday, 13 March, 2017"); Task p1 = helper.generateTaskWithStartDateTime("16 March, 2017"); Task p2 = helper.generateTaskWithStartDateTime("Monday, 1 May, 2017"); Task p3 = helper.generateTaskWithStartDateTime("2 July, 2017"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, p2, p3); TaskBoss expectedTB = helper.generateTaskBoss(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, p1); helper.addToModel(model, fourTasks); assertCommandSuccess("find sd/Mar", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedTB, expectedList); } @Test public void execute_findEndDatetime_matchesOnlyIfKeywordPresentInOrder() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithEndDateTime("Monday, 13 March, 2017"); Task p1 = helper.generateTaskWithEndDateTime("16 March, 2017"); Task p2 = helper.generateTaskWithEndDateTime("Monday, 1 May, 2017"); Task p3 = helper.generateTaskWithEndDateTime("2 July, 2017"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, p2, p3); TaskBoss expectedAB = helper.generateTaskBoss(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, p1); helper.addToModel(model, fourTasks); assertCommandSuccess("find ed/Mar", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } /** * A utility class to generate test data. */ class TestDataHelper { Task adam() throws Exception { Name name = new Name("Adam Brown"); PriorityLevel privatePriorityLevel = new PriorityLevel("High priority"); DateTime startDateTime = new DateTime("today 5pm"); DateTime endDateTime = new DateTime("tomorrow 8pm"); Information privateInformation = new Information("111, alpha street"); Category category1 = new Category("category1"); Category category2 = new Category("longercategory2"); UniqueCategoryList categories = new UniqueCategoryList(category1, category2); return new Task(name, privatePriorityLevel, startDateTime, endDateTime, privateInformation, categories); } /** * Generates a valid task using the given seed. Running this function * with the same parameter values guarantees the returned task will have * the same state. Each unique seed will generate a unique Task object. * * @param seed * used to generate the task data field values */ Task generateTask(int seed) throws Exception { return new Task( new Name("Task " + seed), new PriorityLevel("Yes"), new DateTime("Feb 19 10am 2017"), new DateTime("Feb 20 10am 2017"), new Information("House of " + seed), new UniqueCategoryList(new Category("category" + Math.abs(seed)), new Category("category" + Math.abs(seed + 1))) ); } private String generateAddCommand(Task p) throws IllegalValueException { StringBuffer cmd = new StringBuffer(); cmd.append("add "); cmd.append(" n/").append(p.getName().toString()); cmd.append(" p/").append(p.getPriorityLevel()); cmd.append(" sd/").append(p.getStartDateTime().toString()); cmd.append(" ed/").append(p.getEndDateTime().toString()); cmd.append(" i/").append(p.getInformation()); UniqueCategoryList categories = p.getCategories(); for (Category t : categories) { cmd.append(" c/").append(t.categoryName); } return cmd.toString(); } /** * Generates an TaskBoss with auto-generated tasks. */ TaskBoss generateTaskBoss(int numGenerated) throws Exception { TaskBoss taskBoss = new TaskBoss(); addToTaskBoss(taskBoss, numGenerated); return taskBoss; } /** * Generates TaskBoss based on the list of Tasks given. */ TaskBoss generateTaskBoss(List<Task> tasks) throws Exception { TaskBoss taskBoss = new TaskBoss(); addToTaskBoss(taskBoss, tasks); return taskBoss; } /** * Adds auto-generated Task objects to the given TaskBoss * * @param taskBoss * The TaskBoss to which the Tasks will be added */ void addToTaskBoss(TaskBoss taskBoss, int numGenerated) throws Exception { addToTaskBoss(taskBoss, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given TaskBoss */ void addToTaskBoss(TaskBoss taskBoss, List<Task> tasksToAdd) throws Exception { for (Task t : tasksToAdd) { taskBoss.addTask(t); } } /** * Adds auto-generated Task objects to the given model * * @param model * The model to which the Tasks will be added */ void addToModel(Model model, int numGenerated) throws Exception { addToModel(model, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given model */ void addToModel(Model model, List<Task> tasksToAdd) throws Exception { for (Task t : tasksToAdd) { model.addTask(t); } } /** * Generates a list of Tasks based on the flags. */ List<Task> generateTaskList(int numGenerated) throws Exception { List<Task> tasks = new ArrayList<>(); for (int i = 1; i <= numGenerated; i++) { tasks.add(generateTask(i)); } return tasks; } List<Task> generateTaskList(Task... tasks) { return Arrays.asList(tasks); } /** * Generates a Task object with given name. Other fields will have some * dummy values. */ Task generateTaskWithName(String name) throws Exception { return new Task( new Name(name), new PriorityLevel("Yes"), new DateTime("Feb 19 10am 2017"), new DateTime("Feb 20 10am 2017"), new Information("House of 1"), new UniqueCategoryList(new Category("category")) ); } /** * Generates a Task object with given startDatetime. Other fields will have some * dummy values. */ Task generateTaskWithStartDateTime(String startDatetime) throws Exception { return new Task( new Name("testTask"), new PriorityLevel("Yes"), new DateTime(startDatetime), new DateTime("Feb 20 10am 2018"), new Information("House of 1"), new UniqueCategoryList(new Category("category")) ); } /** * Generates a Task object with given endDatetime. Other fields will have some * dummy values. */ Task generateTaskWithEndDateTime(String endDatetime) throws Exception { return new Task( new Name("testTask"), new PriorityLevel("Yes"), new DateTime("Feb 20 10am 2017"), new DateTime(endDatetime), new Information("House of 1"), new UniqueCategoryList(new Category("category")) ); } } }
package seedu.unburden.logic; import com.google.common.eventbus.Subscribe; import seedu.unburden.commons.core.EventsCenter; import seedu.unburden.commons.core.Messages; import seedu.unburden.commons.events.model.ListOfTaskChangedEvent; import seedu.unburden.commons.events.ui.JumpToListRequestEvent; import seedu.unburden.commons.events.ui.ShowHelpRequestEvent; import seedu.unburden.logic.Logic; import seedu.unburden.logic.LogicManager; import seedu.unburden.logic.commands.*; import seedu.unburden.model.ListOfTask; import seedu.unburden.model.Model; import seedu.unburden.model.ModelManager; import seedu.unburden.model.ReadOnlyListOfTask; import seedu.unburden.model.tag.Tag; import seedu.unburden.model.tag.UniqueTagList; import seedu.unburden.model.task.*; import seedu.unburden.storage.StorageManager; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static seedu.unburden.commons.core.Messages.*; public class LogicManagerTest { @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; // These are for checking the correctness of the events raised private ReadOnlyListOfTask latestSavedAddressBook; private boolean helpShown; private int targetedJumpIndex; @Subscribe private void handleLocalModelChangedEvent(ListOfTaskChangedEvent abce) { latestSavedAddressBook = new ListOfTask(abce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setup() { model = new ModelManager(); String tempTaskListFile = saveFolder.getRoot().getPath() + "TempTaskList.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempTaskListFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedAddressBook = new ListOfTask(model.getListOfTask()); // last // saved // assumed // to be // up to // date // before. helpShown = false; targetedJumpIndex = -1; // non yet } @After public void teardown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() throws Exception { String invalidCommand = " "; assertCommandBehavior(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } /** * Executes the command and confirms that the result message is correct. * Both the 'address book' and the 'last shown list' are expected to be * empty. * * @see #assertCommandBehavior(String, String, ReadOnlyListOfTask, List) */ private void assertCommandBehavior(String inputCommand, String expectedMessage) throws Exception { assertCommandBehavior(inputCommand, expectedMessage, new ListOfTask(), Collections.emptyList()); } /** * Executes the command and confirms that the result message is correct and * also confirms that the following three parts of the LogicManager object's * state are as expected:<br> * - the internal address book data are same as those in the * {@code expectedAddressBook} <br> * - the backing list shown by UI max5ches the {@code shownList} <br> * - {@code expectedAddressBook} was saved to the storage file. <br> */ private void assertCommandBehavior(String inputCommand, String expectedMessage, ReadOnlyListOfTask expectedAddressBook, List<? extends ReadOnlyTask> expectedShownList) throws Exception { // Execute the command CommandResult result = logic.execute(inputCommand); // Confirm the ui display elements should contain the right data assertEquals(expectedMessage, result.feedbackToUser); assertEquals(expectedShownList, model.getFilteredTaskList()); // Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedAddressBook, model.getListOfTask()); assertEquals(expectedAddressBook, latestSavedAddressBook); } @Test public void execute_unknownCommandWord() throws Exception { String unknownCommand = "uicfhmowqewca"; assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() throws Exception { assertCommandBehavior("help", HelpCommand.HELP_MESSAGE_HELP); assertTrue(helpShown); } @Test public void execute_exit() throws Exception { assertCommandBehavior("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generateTask(1)); model.addTask(helper.generateTask(2)); model.addTask(helper.generateTask(3)); assertCommandBehavior("clear", ClearCommand.MESSAGE_SUCCESS, new ListOfTask(), Collections.emptyList()); } @Test public void execute_add_invalidArgsFormat() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); assertCommandBehavior("add Valid Name 12-12-2010 s/2300 e/2359", expectedMessage); assertCommandBehavior("add Valid Name d/12-12-2010 s/2300 2359", expectedMessage); } @Test public void execute_add_invalidTaskData() throws Exception { // TODO : add test case to check if start time later than end time assertCommandBehavior("add []\\[;] i/Valid Task Description d/12-12-2016 s/2300 e/2359", Name.MESSAGE_NAME_CONSTRAINTS); assertCommandBehavior("add Valid Name i/[]\\[;] d/12-12-2016 s/2300 e/2359", TaskDescription.MESSAGE_TASK_CONSTRAINTS); assertCommandBehavior("add Valid Name i/Valid Task Description d/12-12-2010 s/2300 e/2359", Date.MESSAGE_DATE_CONSTRAINTS); assertCommandBehavior("add Valid Name i/Valid Task Description d/12-12-2016 s/2300 e/2400", Time.MESSAGE_TIME_CONSTRAINTS); assertCommandBehavior("add Valid Name i/Valid Task Description d/12-12-2016 s/2400 e/2359", Time.MESSAGE_TIME_CONSTRAINTS); assertCommandBehavior("add Valid Name i/Valid Task Description d/12-12-2010 s/2300 e/2359 t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); } // @@author A0139678J @Test public void execute_add_deadline() throws Exception { TestDataHelper helper = new TestDataHelper(); Task t1 = helper.generateDeadlineTask("Hi hi", "bye bye", "11-10-2016", "bored"); ListOfTask expected = new ListOfTask(); expected.addTask(t1); assertCommandBehavior("add Hi hi i/bye bye d/11-10-2016 t/bored", String.format(AddCommand.MESSAGE_SUCCESS, t1), expected, expected.getTaskList()); } // @@author A0139678J @Test public void execute_add_floatingTask() throws Exception { TestDataHelper helper = new TestDataHelper(); Task t1 = helper.generateFloatingTask("I'm so tired", "I haven't sleep", "sleep"); ListOfTask expected = new ListOfTask(); expected.addTask(t1); assertCommandBehavior("Add I'm so tired i/I haven't sleep t/sleep", String.format(AddCommand.MESSAGE_SUCCESS, t1), expected, expected.getTaskList()); } @Test public void execute_add_floating_task_without_tags() throws Exception { TestDataHelper helper = new TestDataHelper(); Task task = helper.generateFloatingTaskWithoutTag("Hello", "It's me"); ListOfTask expected = new ListOfTask(); expected.addTask(task); assertCommandBehavior("add Hello i/It's me", String.format(AddCommand.MESSAGE_SUCCESS, task), expected, expected.getTaskList()); } @Test public void execute_add_event_task_without_tags() throws Exception { TestDataHelper helper = new TestDataHelper(); Task task = helper.generateEventTaskWithAllWithoutTag("Hi", "there", "12-12-2016", "1400", "1500"); ListOfTask expected = new ListOfTask(); expected.addTask(task); assertCommandBehavior("add Hi i/there d/12-12-2016 s/1400 e/1500", String.format(AddCommand.MESSAGE_SUCCESS, task), expected, expected.getTaskList()); } @Test public void execute_add_floating_task_without_description() throws Exception { TestDataHelper helper = new TestDataHelper(); Task task = helper.generateFloatingTaskWithoutTaskDescription("Joey", "Tribbiani"); ListOfTask expected = new ListOfTask(); expected.addTask(task); assertCommandBehavior("add Joey t/Tribbiani", String.format(AddCommand.MESSAGE_SUCCESS, task), expected, expected.getTaskList()); } @Test public void execute_add_deadline_without_description_and_tags() throws Exception { TestDataHelper helper = new TestDataHelper(); Task task = helper.generateDeadlineTaskWithEndTimeWithoutTaskDescriptionWithoutTag("Monica", "13-11-2017", "0137"); ListOfTask expected = new ListOfTask(); expected.addTask(task); assertCommandBehavior("add Monica d/13-11-2017 e/0137", String.format(AddCommand.MESSAGE_SUCCESS, task), expected, expected.getTaskList()); } @Test public void execute_add_deadline_without_description() throws Exception { TestDataHelper helper = new TestDataHelper(); Task task = helper.generateDeadlineTaskWithoutTaskDescription("Chandler", "22-12-2018", "Friends"); ListOfTask expected = new ListOfTask(); expected.addTask(task); assertCommandBehavior("Add Chandler d/22-12-2018 t/Friends", String.format(AddCommand.MESSAGE_SUCCESS, task), expected, expected.getTaskList()); } @Test public void execute_add_deadline_without_tags() throws Exception { TestDataHelper helper = new TestDataHelper(); Task task = helper.generateDeadlineTask("Chandler", "Bing", "13-12-2017"); ListOfTask expected = new ListOfTask(); expected.addTask(task); assertCommandBehavior("add Chandler i/Bing d/13-12-2017", String.format(AddCommand.MESSAGE_SUCCESS, task), expected, expected.getTaskList()); } @Test public void execute_add_deadline_with_everything() throws Exception { TestDataHelper helper = new TestDataHelper(); Task task = helper.generateDeadlineTask("How you doin?", "Joey", "14-11-2100", "Friends"); ListOfTask expected = new ListOfTask(); expected.addTask(task); assertCommandBehavior("add How you doin? i/Joey d/14-11-2100 t/Friends", String.format(AddCommand.MESSAGE_SUCCESS, task), expected, expected.getTaskList()); } @Test public void execute_add_deadline_with_end_time() throws Exception { TestDataHelper helper = new TestDataHelper(); Task task = helper.generateDeadlineTaskWithEndTime("Chandler", "Bing", "14-12-2019", "1800", "Friends"); ListOfTask expected = new ListOfTask(); expected.addTask(task); assertCommandBehavior("add Chandler i/Bing d/14-12-2019 e/1800 t/Friends", String.format(AddCommand.MESSAGE_SUCCESS, task), expected, expected.getTaskList()); } @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); ListOfTask expectedAB = new ListOfTask(); expectedAB.addTask(toBeAdded); // execute command and verify result assertCommandBehavior(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); ListOfTask expectedAB = new ListOfTask(); expectedAB.addTask(toBeAdded); // setup starting state model.addTask(toBeAdded); // person already in internal address book // execute command and verify result assertCommandBehavior(helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK, expectedAB, expectedAB.getTaskList()); } @Test public void execute_list_showsAllPersons() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); ListOfTask expectedAB = helper.generateListOfTask(2); List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList(); // prepare address book state helper.addToModel(model, 2); assertCommandBehavior("list all", ListCommand.MESSAGE_SUCCESS, expectedAB, expectedList); } /** * Confirms the 'invalid argument index number behaviour' for the given * command targeting a single person in the shown list, using visible index. * * @param commandWord * to test assuming it targets a single person in the last shown * list based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandBehavior(commandWord, expectedMessage); // index missing assertCommandBehavior(commandWord + " +1", expectedMessage); // index // should // unsigned assertCommandBehavior(commandWord + " -1", expectedMessage); // index // should // unsigned assertCommandBehavior(commandWord + " 0", expectedMessage); // index // cannot be assertCommandBehavior(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given * command targeting a single person in the shown list, using visible index. * * @param commandWord * to test assuming it targets a single person in the last shown * list based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<Task> taskList = helper.generateTaskList(2); // set AB state to 2 persons model.resetData(new ListOfTask()); for (Task p : taskList) { model.addTask(p); } if (commandWord.equals(EditCommand.COMMAND_WORD)) { assertCommandBehavior(commandWord + " 3 e/2359", expectedMessage, model.getListOfTask(), taskList); } else { assertCommandBehavior(commandWord + " 3", expectedMessage, model.getListOfTask(), taskList); } } @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } @Test public void execute_select_jumpsToCorrectPerson() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); ListOfTask expectedAB = helper.generateListOfTask(threeTasks); helper.addToModel(model, threeTasks); assertCommandBehavior("select 2", String.format(SelectCommand.MESSAGE_SELECT_PERSON_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1)); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); } @Test public void execute_delete_removesCorrectPerson() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); ListOfTask expectedAB = helper.generateListOfTask(threeTasks); expectedAB.removeTask(threeTasks.get(1)); helper.addToModel(model, threeTasks); assertCommandBehavior("delete 2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeTasks.get(1)), expectedAB, expectedAB.getTaskList()); } // @@author A0139714B @Test public void execute_editIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("edit"); } // @@author A0139714B @Test public void execute_edit_validDate() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateEventTaskWithAll("bla bla KEY bla", "blah blah blah", "11-10-2016", "1500", "1800", "tag"); Task p2 = helper.generateEventTaskWithAll("bla KEY bla bceofeia", "hello world", "12-10-2016", "1500", "1800", "blah"); Task p3 = helper.generateEventTaskWithAll("KE Y", "say goodbye", "13-10-2016", "1500", "1800", "hi"); Task p4 = helper.generateEventTaskWithAll("keyKEY sduauo", "move", "14-10-2016", "1500", "1800", "bye"); Task p5 = helper.generateEventTaskWithAll("K EY sduauo", "high kneel", "15-10-2016", "1500", "1800", "yo"); Task toEdit = helper.generateEventTaskWithAll("", "", "16-10-2016", "", "", "yo"); Task updatedTask = helper.generateEventTaskWithAll("K EY sduauo", "high kneel", "16-10-2016", "1500", "1800", "yo"); List<Task> fiveTasks = helper.generateTaskList(p1, p2, p3, p4, p5); ListOfTask expectedAB = helper.generateListOfTask(fiveTasks); List<Task> expectedList = helper.generateTaskList(p1, p2, p3, p4, updatedTask); model.resetData(new ListOfTask()); for (Task t : fiveTasks) { model.addTask(t); } expectedAB.editTask((ReadOnlyTask) fiveTasks.get(4), toEdit); assertCommandBehavior("edit 5 d/16-10-2016", String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, updatedTask), expectedAB, expectedList); } // @@author A0139714B @Test public void execute_edit_validStartTime() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateEventTaskWithAll("bla bla KEY bla", "blah blah blah", "11-10-2016", "1500", "1800", "tag"); Task p2 = helper.generateEventTaskWithAll("bla KEY bla bceofeia", "hello world", "12-10-2016", "1500", "1800", "blah"); Task p3 = helper.generateEventTaskWithAll("KE Y", "say goodbye", "13-10-2016", "1500", "1800", "hi"); Task p4 = helper.generateEventTaskWithAll("keyKEY sduauo", "move", "14-10-2016", "1500", "1800", "bye"); Task p5 = helper.generateEventTaskWithAll("K EY sduauo", "high kneel", "15-10-2016", "1500", "1800", "yo"); Task toEdit = helper.generateEventTaskWithAll("", "", "", "1200", "", "blah"); Task updatedTask = helper.generateEventTaskWithAll("bla KEY bla bceofeia", "hello world", "12-10-2016", "1200", "1800", "blah"); List<Task> fiveTasks = helper.generateTaskList(p1, p2, p3, p4, p5); ListOfTask expectedAB = helper.generateListOfTask(fiveTasks); List<Task> expectedList = helper.generateTaskList(p1, updatedTask, p3, p4, p5); model.resetData(new ListOfTask()); for (Task t : fiveTasks) { model.addTask(t); } expectedAB.editTask((ReadOnlyTask) fiveTasks.get(2), toEdit); assertCommandBehavior("edit 2 s/1200", String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, updatedTask), expectedAB, expectedList); } // @@author A0139714B @Test public void execute_edit_validEndTime() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateEventTaskWithAll("bla bla KEY bla", "blah blah blah", "11-10-2016", "1500", "1800", "tag"); Task p2 = helper.generateEventTaskWithAll("bla KEY bla bceofeia", "hello world", "12-10-2016", "1500", "1800", "blah"); Task p3 = helper.generateEventTaskWithAll("KE Y", "say goodbye", "13-10-2016", "1500", "1800", "hi"); Task p4 = helper.generateEventTaskWithAll("keyKEY sduauo", "move", "14-10-2016", "1500", "1800", "bye"); Task p5 = helper.generateEventTaskWithAll("K EY sduauo", "high kneel", "15-10-2016", "1500", "1800", "yo"); Task toEdit = helper.generateEventTaskWithAll("", "", "", "", "1900", "blah"); Task updatedTask = helper.generateEventTaskWithAll("bla KEY bla bceofeia", "hello world", "12-10-2016", "1500", "1900", "blah"); List<Task> fiveTasks = helper.generateTaskList(p1, p2, p3, p4, p5); ListOfTask expectedAB = helper.generateListOfTask(fiveTasks); List<Task> expectedList = helper.generateTaskList(p1, updatedTask, p3, p4, p5); model.resetData(new ListOfTask()); for (Task t : fiveTasks) { model.addTask(t); } expectedAB.editTask((ReadOnlyTask) fiveTasks.get(2), toEdit); assertCommandBehavior("edit 2 e/1900", String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, updatedTask), expectedAB, expectedList); } // @@author A0139714B @Test public void execute_edit_fail_addEndTimeToATaskWithNoDate() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateFloatingTask("bla bla KEY bla", "blah blah blah", "tag"); Task p2 = helper.generateFloatingTask("bla KEY bla bceofeia", "hello world", "blah"); Task p3 = helper.generateFloatingTask("KE Y", "say goodbye", "hi"); Task p4 = helper.generateFloatingTask("keyKEY sduauo", "move", "bye"); Task p5 = helper.generateFloatingTask("K EY sduauo", "high kneel", "yo"); Task updatedTask = helper.generateFloatingTask("K EY sduauo", "high kneel", "yo"); List<Task> fiveTasks = helper.generateTaskList(p1, p2, p3, p4, p5); ListOfTask expectedAB = helper.generateListOfTask(fiveTasks); List<Task> expectedList = helper.generateTaskList(p1, p2, p3, p4, updatedTask); model.resetData(new ListOfTask()); for (Task t : fiveTasks) { model.addTask(t); } assertCommandBehavior("edit 5 e/1900", String.format(Messages.MESSAGE_CANNOT_ADD_ENDTIME_WITH_NO_DATE), expectedAB, expectedList); } // @@author A0139714B @Test public void execute_edit_fail_addStartTimeToATaskWithoutEndTime() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateDeadlineTask("bla bla KEY bla", "blah blah blah", "11-10-2016", "tag"); Task p2 = helper.generateDeadlineTask("bla KEY bla bceofeia", "hello world", "12-10-2016", "blah"); Task p3 = helper.generateDeadlineTask("KE Y", "say goodbye", "13-10-2016", "hi"); Task p4 = helper.generateDeadlineTask("keyKEY sduauo", "move", "14-10-2016", "bye"); Task p5 = helper.generateDeadlineTask("K EY sduauo", "high kneel", "15-10-2016", "yo"); List<Task> fiveTasks = helper.generateTaskList(p1, p2, p3, p4, p5); ListOfTask expectedAB = helper.generateListOfTask(fiveTasks); List<Task> expectedList = helper.generateTaskList(p1, p2, p3, p4, p5); model.resetData(new ListOfTask()); for (Task t : fiveTasks) { model.addTask(t); } assertCommandBehavior("edit 5 s/1900", String.format(Messages.MESSAGE_CANNOT_ADD_STARTTIME_WITH_NO_ENDTIME), expectedAB, expectedList); } // @@author A0139714B @Test public void execute_edit_fail_startTimeAfterEndTime() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateEventTaskWithAll("bla bla KEY bla", "blah blah blah", "11-10-2016", "1500", "1800", "tag"); Task p2 = helper.generateEventTaskWithAll("bla KEY bla bceofeia", "hello world", "12-10-2016", "1500", "1800", "blah"); Task p3 = helper.generateEventTaskWithAll("KE Y", "say goodbye", "13-10-2016", "1500", "1800", "hi"); Task p4 = helper.generateEventTaskWithAll("keyKEY sduauo", "move", "14-10-2016", "1500", "1800", "bye"); Task p5 = helper.generateEventTaskWithAll("K EY sduauo", "high kneel", "15-10-2016", "1500", "1800", "yo"); List<Task> fiveTasks = helper.generateTaskList(p1, p2, p3, p4, p5); ListOfTask expectedAB = helper.generateListOfTask(fiveTasks); List<Task> expectedList = helper.generateTaskList(p1, p2, p3, p4, p5); model.resetData(new ListOfTask()); for (Task t : fiveTasks) { model.addTask(t); } assertCommandBehavior("edit 2 s/2000", String.format(MESSAGE_STARTTIME_AFTER_ENDTIME), expectedAB, expectedList); } // @@author A0139714B @Test public void execute_edit_removeDate() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateDeadlineTask("bla bla KEY bla", "blah blah blah", "11-10-2016", "tag"); Task p2 = helper.generateDeadlineTask("bla KEY bla bceofeia", "hello world", "12-10-2016", "blah"); Task p3 = helper.generateDeadlineTask("KE Y", "say goodbye", "13-10-2016", "hi"); Task p4 = helper.generateDeadlineTask("keyKEY sduauo", "move", "14-10-2016", "bye"); Task p5 = helper.generateDeadlineTask("K EY sduauo", "high kneel", "15-10-2016", "yo"); Task updatedTask = helper.generateFloatingTask("K EY sduauo", "high kneel", "yo"); List<Task> fiveTasks = helper.generateTaskList(p1, p2, p3, p4, p5); ListOfTask expectedAB = helper.generateListOfTask(fiveTasks); List<Task> expectedList = helper.generateTaskList(p1, p2, p3, p4, updatedTask); model.resetData(new ListOfTask()); for (Task t : fiveTasks) { model.addTask(t); } assertCommandBehavior("edit 5 d/rm", String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, updatedTask), expectedAB, expectedList); } // @@author A0139714B @Test public void execute_edit_removeEndTime() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateDeadlineTaskWithEndTime("bla bla KEY bla", "blah blah blah", "11-10-2016", "1900", "tag"); Task p2 = helper.generateDeadlineTaskWithEndTime("bla KEY bla bceofeia", "hello world", "12-10-2016", "1800", "blah"); Task p3 = helper.generateDeadlineTaskWithEndTime("KE Y", "say goodbye", "13-10-2016", "1900", "hi"); Task p4 = helper.generateDeadlineTaskWithEndTime("keyKEY sduauo", "move", "14-10-2016", "1900", "bye"); Task p5 = helper.generateDeadlineTaskWithEndTime("K EY sduauo", "high kneel", "15-10-2016", "1500", "yo"); Task updatedTask = helper.generateDeadlineTask("bla bla KEY bla", "blah blah blah", "11-10-2016", "tag"); List<Task> fiveTasks = helper.generateTaskList(p1, p2, p3, p4, p5); ListOfTask expectedAB = helper.generateListOfTask(fiveTasks); List<Task> expectedList = helper.generateTaskList(updatedTask, p2, p3, p4, p5); model.resetData(new ListOfTask()); for (Task t : fiveTasks) { model.addTask(t); } assertCommandBehavior("edit 1 e/rm", String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, updatedTask), expectedAB, expectedList); } // @@author A0139714B @Test public void execute_edit_removeTaskDescription() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateEventTaskWithAll("bla bla KEY bla", "blah blah blah", "11-10-2016", "1800", "1900", "tag"); Task p2 = helper.generateEventTaskWithAll("bla KEY bla bceofeia", "hello world", "12-10-2016", "1500", "1800", "blah"); Task p3 = helper.generateEventTaskWithAll("KE Y", "say goodbye", "13-10-2016", "1600", "1900", "hi"); Task p4 = helper.generateEventTaskWithAll("keyKEY sduauo", "move", "14-10-2016", "1500", "1900", "bye"); Task p5 = helper.generateEventTaskWithAll("K EY sduauo", "high kneel", "15-10-2016", "1000", "1500", "yo"); Task updatedTask = helper.generateEventTaskWithoutTaskDescription("bla bla KEY bla", "11-10-2016", "1800", "1900", "tag"); List<Task> fiveTasks = helper.generateTaskList(p1, p2, p3, p4, p5); ListOfTask expectedAB = helper.generateListOfTask(fiveTasks); List<Task> expectedList = helper.generateTaskList(updatedTask, p2, p3, p4, p5); model.resetData(new ListOfTask()); for (Task t : fiveTasks) { model.addTask(t); } assertCommandBehavior("edit 1 i/rm", String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, updatedTask), expectedAB, expectedList); } // @@author A0139714B @Test public void execute_edit_removeStartTime() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateEventTaskWithAll("bla bla KEY bla", "blah blah blah", "11-10-2016", "1800", "1900", "tag"); Task p2 = helper.generateEventTaskWithAll("bla KEY bla bceofeia", "hello world", "12-10-2016", "1500", "1800", "blah"); Task p3 = helper.generateEventTaskWithAll("KE Y", "say goodbye", "13-10-2016", "1600", "1900", "hi"); Task p4 = helper.generateEventTaskWithAll("keyKEY sduauo", "move", "14-10-2016", "1500", "1900", "bye"); Task p5 = helper.generateEventTaskWithAll("K EY sduauo", "high kneel", "15-10-2016", "1000", "1500", "yo"); Task updatedTask = helper.generateDeadlineTaskWithEndTime("bla bla KEY bla", "blah blah blah", "11-10-2016", "1900", "tag"); List<Task> fiveTasks = helper.generateTaskList(p1, p2, p3, p4, p5); ListOfTask expectedAB = helper.generateListOfTask(fiveTasks); List<Task> expectedList = helper.generateTaskList(updatedTask, p2, p3, p4, p5); model.resetData(new ListOfTask()); for (Task t : fiveTasks) { model.addTask(t); } assertCommandBehavior("edit 1 s/rm", String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, updatedTask), expectedAB, expectedList); } // @@author A0139714B @Test public void execute_edit_InvalidIndex() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateEventTaskWithAll("bla bla KEY bla", "blah blah blah", "11-10-2016", "1500", "1800", "tag"); Task p2 = helper.generateEventTaskWithAll("bla KEY bla bceofeia", "hello world", "12-10-2016", "1500", "1800", "blah"); Task p3 = helper.generateEventTaskWithAll("KE Y", "say goodbye", "13-10-2016", "1500", "1800", "hi"); Task p4 = helper.generateEventTaskWithAll("keyKEY sduauo", "move", "14-10-2016", "1500", "1800", "bye"); Task p5 = helper.generateEventTaskWithAll("K EY sduauo", "high kneel", "15-10-2016", "1500", "1800", "yo"); List<Task> fiveTasks = helper.generateTaskList(p1, p2, p3, p4, p5); ListOfTask expectedAB = helper.generateListOfTask(fiveTasks); List<Task> expectedList = helper.generateTaskList(p1, p2, p3, p4, p5); model.resetData(new ListOfTask()); for (Task t : fiveTasks) { model.addTask(t); } assertCommandBehavior("edit 7 e/1900", String.format(MESSAGE_INVALID_TASK_DISPLAYED_INDEX), expectedAB, expectedList); } @Test public void execute_find_invalidArgsFormat() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandBehavior("find ", expectedMessage); } @Test public void execute_find_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateEventTaskWithAll("bla bla KEY bla", "blah blah blah", "11-10-2016", "1500", "1800", "tag"); Task pTarget2 = helper.generateEventTaskWithAll("bla KEY bla bceofeia", "hello world", "11-10-2016", "1500", "1800", "blah"); Task p1 = helper.generateEventTaskWithAll("KE Y", "say goodbye", "11-10-2016", "1500", "1800", "hi"); Task pTarget3 = helper.generateEventTaskWithAll("keyKEY sduauo", "move", "11-10-2016", "1500", "1800", "bye"); Task p2 = helper.generateEventTaskWithAll("K EY sduauo", "high kneel", "11-10-2016", "1500", "1800", "yo"); List<Task> fiveTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2, pTarget3); ListOfTask expectedAB = helper.generateListOfTask(fiveTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fiveTasks); assertCommandBehavior("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateEventTaskWithAll("bla bla KEY bla", "blah blah blah", "11-10-2016", "1500", "1800", "tag"); Task p2 = helper.generateEventTaskWithAll("bla KEY bla bceofeia", "hello world", "06-12-2016", "1800", "1900", "blah"); Task p3 = helper.generateEventTaskWithAll("key key", "say goodbye", "03-10-2016", "1300", "1400", "hi"); Task p4 = helper.generateEventTaskWithAll("KEy sduauo", "move", "10-09-2016", "1200", "1800", "bye"); List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2); ListOfTask expectedAB = helper.generateListOfTask(fourTasks); List<Task> expectedList = fourTasks; helper.addToModel(model, fourTasks); assertCommandBehavior("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateEventTaskWithAll("bla bla KEY bla", "blah blah blah", "11-10-2016", "1500", "1800", "tag"); Task pTarget2 = helper.generateEventTaskWithAll("bla rAnDoM bla bceofeia", "hello world", "22-09-2016", "1100", "1800", "blah"); Task pTarget3 = helper.generateEventTaskWithAll("key key", "move around", "06-10-2017", "1100", "1200", "hi"); Task p1 = helper.generateEventTaskWithAll("sduauo", "jump", "02-03-2016", "1300", "1400", "bye"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3); ListOfTask expectedAB = helper.generateListOfTask(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourTasks); assertCommandBehavior("find key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } /** * A utility class to generate test data. */ class TestDataHelper { Task adam() throws Exception { Name name = new Name("Adam Brown"); Date date = new Date("23-06-2016"); Time startTime = new Time("1900"); Time endTime = new Time("2200"); Tag tag1 = new Tag("tag1"); Tag tag2 = new Tag("tag2"); UniqueTagList tags = new UniqueTagList(tag1, tag2); return new Task(name, date, startTime, endTime, tags); } /** * Generates a valid task using the given seed. Running this function * with the same parameter values guarantees the returned task will have * the same state. Each unique seed will generate a unique Task object. * * @param seed * used to generate the task data field values */ Task generateTask(int seed) throws Exception { return new Task(new Name("Task " + seed), new Date((seed % 2 == 1) ? "1" + seed + "-12-2" + seed + "22" : "1" + seed + "-12-212" + seed), new Time("0" + seed + "00"), new Time("0" + seed + "0" + seed), new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1)))); } /** Generates the correct add command based on the person given */ String generateAddCommand(Task p) { StringBuffer cmd = new StringBuffer(); cmd.append("add "); cmd.append(p.getName().toString()); cmd.append(" d/").append(p.getDate().toString()); cmd.append(" s/").append(p.getStartTime().toString()); cmd.append(" e/").append(p.getEndTime().toString()); UniqueTagList tags = p.getTags(); for (Tag t : tags) { cmd.append(" t/").append(t.tagName); } return cmd.toString(); } /** * Generates an ListOfTask with auto-generated persons. */ ListOfTask generateListOfTask(int numGenerated) throws Exception { ListOfTask listOfTask = new ListOfTask(); addToListOfTask(listOfTask, numGenerated); return listOfTask; } /** * Generates an ListOfTask based on the list of Persons given. */ ListOfTask generateListOfTask(List<Task> tasks) throws Exception { ListOfTask listOfTask = new ListOfTask(); addToListOfTask(listOfTask, tasks); return listOfTask; } /** * Adds auto-generated Task objects to the given ListOfTask * * @param listOfTask * The ListOfTask to which the Persons will be added */ void addToListOfTask(ListOfTask listOfTask, int numGenerated) throws Exception { addToListOfTask(listOfTask, generateTaskList(numGenerated)); } /** * Adds the given list of Persons to the given ListOfTask */ void addToListOfTask(ListOfTask listOfTask, List<Task> tasksToAdd) throws Exception { for (Task p : tasksToAdd) { listOfTask.addTask(p); } } /** * Adds auto-generated Task objects to the given model * * @param model * The model to which the Persons will be added */ void addToModel(Model model, int numGenerated) throws Exception { addToModel(model, generateTaskList(numGenerated)); } /** * Adds the given list of Persons to the given model */ void addToModel(Model model, List<Task> tasksToAdd) throws Exception { for (Task p : tasksToAdd) { model.addTask(p); } } /** * Generates a list of Persons based on the flags. */ List<Task> generateTaskList(int numGenerated) throws Exception { List<Task> tasks = new ArrayList<>(); for (int i = 1; i <= numGenerated; i++) { tasks.add(generateTask(i)); } return tasks; } List<Task> generateTaskList(Task... persons) { return Arrays.asList(persons); } /** * Generates a Task object with given name. Other fields will have some * dummy values. */ Task generateEventTaskWithAll(String name, String taskDescription, String date, String startTime, String endTime, String tag) throws Exception { return new Task(new Name(name), new TaskDescription(taskDescription), new Date(date), new Time(startTime), new Time(endTime), new UniqueTagList(new Tag(tag))); } Task generateEventTaskWithAllWithoutTag(String name, String taskDescription, String date, String startTime, String endTime) throws Exception { return new Task(new Name(name), new TaskDescription(taskDescription), new Date(date), new Time(startTime), new Time(endTime), new UniqueTagList()); } Task generateEventTaskWithoutTaskDescription(String name, String date, String startTime, String endTime, String tag) throws Exception { return new Task(new Name(name), new Date(date), new Time(startTime), new Time(endTime), new UniqueTagList(new Tag(tag))); } Task generateEventTaskWithoutTaskDescriptionWithoutTag(String name, String date, String startTime, String endTime) throws Exception { return new Task(new Name(name), new Date(date), new Time(startTime), new Time(endTime), new UniqueTagList()); } Task generateDeadlineTaskWithEndTime(String name, String taskDescription, String date, String endTime, String tag) throws Exception { return new Task(new Name(name), new TaskDescription(taskDescription), new Date(date), new Time(endTime), new UniqueTagList(new Tag(tag))); } Task generateDeadlineTaskWithEndTimeWithoutTag(String name, String taskDescription, String date, String endTime, String tag) throws Exception { return new Task(new Name(name), new TaskDescription(taskDescription), new Date(date), new Time(endTime), new UniqueTagList(new Tag(tag))); } Task generateDeadlineTaskWithEndTimeWithoutTaskDescription(String name, String date, String endTime, String tag) throws Exception { return new Task(new Name(name), new Date(date), new Time(endTime), new UniqueTagList(new Tag(tag))); } Task generateDeadlineTaskWithEndTimeWithoutTaskDescriptionWithoutTag(String name, String date, String endTime) throws Exception { return new Task(new Name(name), new Date(date), new Time(endTime), new UniqueTagList()); } Task generateDeadlineTask(String name, String taskDescription, String date, String tag) throws Exception { return new Task(new Name(name), new TaskDescription(taskDescription), new Date(date), new UniqueTagList(new Tag(tag))); } Task generateDeadlineTask(String name, String taskDescription, String date) throws Exception { return new Task(new Name(name), new TaskDescription(taskDescription), new Date(date), new UniqueTagList()); } Task generateDeadlineTaskWithoutTaskDescription(String name, String date, String tag) throws Exception { return new Task(new Name(name), new Date(date), new UniqueTagList(new Tag(tag))); } Task generateDeadlineTaskWithoutTaskDescriptionWithoutTag(String name, String date) throws Exception { return new Task(new Name(name), new Date(date), new UniqueTagList()); } Task generateFloatingTask(String name, String taskDescription, String tag) throws Exception { return new Task(new Name(name), new TaskDescription(taskDescription), new UniqueTagList(new Tag(tag))); } Task generateFloatingTaskWithoutTag(String name, String taskDescription) throws Exception { return new Task(new Name(name), new TaskDescription(taskDescription), new UniqueTagList()); } Task generateFloatingTaskWithoutTaskDescription(String name, String tag) throws Exception { return new Task(new Name(name), new UniqueTagList(new Tag(tag))); } Task generateFloatingTaskWithoutTaskDescriptionWithoutTag(String name) throws Exception { return new Task(new Name(name), new UniqueTagList()); } } }
package org.jdesktop.swingx; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.SwingUtilities; import org.jdesktop.swingx.JXLoginPane.JXLoginFrame; import org.jdesktop.swingx.JXLoginPane.SaveMode; import org.jdesktop.swingx.auth.LoginService; import org.jdesktop.swingx.auth.SimpleLoginService; import org.jdesktop.swingx.graphics.GraphicsUtilities; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.plaf.basic.BasicLoginPaneUI; /** * Simple tests to ensure that the {@code JXLoginPane} can be instantiated and * displayed. * * @author Karl Schaefer */ public class JXLoginPaneVisualCheck extends InteractiveTestCase { public JXLoginPaneVisualCheck() { super("JXLoginPane Test"); } public static void main(String[] args) throws Exception { // setSystemLF(true); JXLoginPaneVisualCheck test = new JXLoginPaneVisualCheck(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #538-swingx Failure to set locale at runtime * */ public void interactiveDisplay() { JComponent.setDefaultLocale(Locale.FRANCE); JXLoginPane panel = new JXLoginPane(); JFrame frame = JXLoginPane.showLoginFrame(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(createAndFillMenuBar(panel)); panel.setSaveMode(SaveMode.BOTH); frame.pack(); frame.setVisible(true); } /** * Issue #538-swingx Failure to set locale at runtime * */ public void interactiveDisplayFixedUser() { JComponent.setDefaultLocale(Locale.FRANCE); JXLoginPane panel = new JXLoginPane(); JFrame frame = JXLoginPane.showLoginFrame(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(createAndFillMenuBar(panel)); panel.setSaveMode(SaveMode.BOTH); panel.setUserName("aGuy"); panel.setUserNameEnabled(false); frame.pack(); frame.setVisible(true); } /** * Issue #538-swingx Failure to set locale at runtime * */ public void interactiveSetBackground() { JXLoginPane panel = new JXLoginPane(); panel.setBackgroundPainter(new MattePainter<Object>(Color.RED, true)); JFrame frame = JXLoginPane.showLoginFrame(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(createAndFillMenuBar(panel)); panel.setSaveMode(SaveMode.BOTH); frame.pack(); frame.setVisible(true); } /** * Issue #777-swingx Custom banner not picked up due to double updateUI() call * */ public void interactiveCustomBannerDisplay() { JXLoginPane panel = new JXLoginPane(); panel.setUI(new DummyLoginPaneUI(panel)); JFrame frame = JXLoginPane.showLoginFrame(panel); frame.setJMenuBar(createAndFillMenuBar(panel)); panel.setSaveMode(SaveMode.BOTH); frame.pack(); frame.setVisible(true); } /** * Issue #636-swingx Unexpected resize on long exception message. * */ public void interactiveError() { JComponent.setDefaultLocale(Locale.FRANCE); final JXLoginPane panel = new JXLoginPane(new LoginService() { public boolean authenticate(String name, char[] password, String server) throws Exception { if (true) { throw new Exception("Ex."); } return false; }}); final JXLoginFrame frame = JXLoginPane.showLoginFrame(panel); // if uncomented dialog will disappear immediatelly dou to invocation of login action //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(createAndFillMenuBar(panel)); panel.setErrorMessage("TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO Unexpected resize on long exception message. Unexpected resize on long exception message."); panel.setSaveMode(SaveMode.BOTH); frame.pack(); frame.setVisible(true); SwingUtilities.invokeLater(new Runnable() { public void run() { evaluateChildren(frame.getContentPane().getComponents()); }}); } /** * Issue #636-swingx Unexpected resize on long exception message. * */ public void interactiveBackground() { JComponent.setDefaultLocale(Locale.FRANCE); final JXLoginPane panel = new JXLoginPane(new LoginService() { public boolean authenticate(String name, char[] password, String server) throws Exception { if (true) { throw new Exception("Ex."); } return false; }}); final JXLoginFrame frame = JXLoginPane.showLoginFrame(panel); // if uncomented dialog will disappear immediatelly dou to invocation of login action //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(createAndFillMenuBar(panel)); panel.setErrorMessage("TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO Unexpected resize on long exception message. Unexpected resize on long exception message."); panel.setSaveMode(SaveMode.BOTH); frame.getContentPane().setBackgroundPainter(new MattePainter<Object>( new GradientPaint(0, 0, Color.BLUE, 1, 0, Color.YELLOW), true)); frame.pack(); frame.setVisible(true); SwingUtilities.invokeLater(new Runnable() { public void run() { evaluateChildren(frame.getContentPane().getComponents()); }}); } /** * Progress message test. */ public void interactiveProgress() { final JXLoginPane panel = new JXLoginPane(); final JFrame frame = JXLoginPane.showLoginFrame(panel); panel.setLoginService(new LoginService() { public boolean authenticate(String name, char[] password, String server) throws Exception { panel.startLogin(); Thread.sleep(5000); return true; }}); frame.setJMenuBar(createAndFillMenuBar(panel)); panel.setSaveMode(SaveMode.BOTH); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); SwingUtilities.invokeLater(new Runnable() { public void run() { evaluateChildren(frame.getContentPane().getComponents()); }}); } private boolean evaluateChildren(Component[] components) { for (Component c: components) { if (c instanceof JButton && "login".equals(((JButton) c).getActionCommand())) { ((JButton) c).doClick(); return true; } else if (c instanceof Container) { if (evaluateChildren(((Container) c).getComponents()) ){ return true; } } } return false; } public class DummyLoginPaneUI extends BasicLoginPaneUI { public DummyLoginPaneUI(JXLoginPane dlg) { super(dlg); // TODO Auto-generated constructor stub } @Override public Image getBanner() { Image banner = super.getBanner(); BufferedImage im = GraphicsUtilities.createCompatibleTranslucentImage(banner.getWidth(null), banner.getHeight(null)); Graphics2D g = im.createGraphics(); g.setComposite(AlphaComposite.Src); g.drawImage(banner, 0, 0, 100, 100, null); g.dispose(); return im; } } @Override protected void createAndAddMenus(JMenuBar menuBar, final JComponent component) { super.createAndAddMenus(menuBar, component); JMenu menu = new JMenu("Locales"); menu.add(new AbstractAction("Change Locale") { public void actionPerformed(ActionEvent e) { if (component.getLocale() == Locale.FRANCE) { component.setLocale(Locale.ENGLISH); } else { component.setLocale(Locale.FRANCE); } }}); menuBar.add(menu); } /** * swingx-917 * TODO: this test works only when not run together with the others * @throws Exception */ public void interactiveBrokenLayoutAfterFailedLogin() throws Exception { sun.awt.AppContext.getAppContext().put("JComponent.defaultLocale", Locale.FRANCE); Map<String, char[]> aMap = new HashMap<String, char[]>(); aMap.put("asdf", "asdf".toCharArray()); JXLoginPane panel = new JXLoginPane(new SimpleLoginService(aMap)); panel.setSaveMode(JXLoginPane.SaveMode.BOTH); panel.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange( PropertyChangeEvent thePropertyChangeEvent) { System.err.println(thePropertyChangeEvent.getPropertyName() + " " + thePropertyChangeEvent.getOldValue() + " -> " + thePropertyChangeEvent.getNewValue()); } }); JFrame frame = JXLoginPane.showLoginFrame(panel); frame.pack(); frame.setVisible(true); } /** * Do nothing, make the test runner happy * (would output a warning without a test fixture). * */ public void testDummy() { } }
package it.dfa.unict; import it.dfa.unict.pojo.AppInput; import it.dfa.unict.pojo.InputFile; import it.dfa.unict.pojo.Link; import it.dfa.unict.pojo.Task; import it.dfa.unict.util.Constants; import it.dfa.unict.util.Utils; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletConfig; import javax.portlet.PortletException; import javax.portlet.PortletPreferences; import javax.portlet.ProcessAction; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.portlet.LiferayPortletConfig; import com.liferay.portal.kernel.servlet.SessionErrors; import com.liferay.portal.kernel.servlet.SessionMessages; import com.liferay.portal.kernel.upload.UploadPortletRequest; import com.liferay.portal.kernel.util.FileUtil; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.JavaConstants; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.portal.model.User; import com.liferay.portal.theme.ThemeDisplay; import com.liferay.portal.util.PortalUtil; import com.liferay.util.bridges.mvc.MVCPortlet; import com.sun.jersey.api.client.UniformInterfaceException; public class WJ48Portlet extends MVCPortlet { private final Log _log = LogFactoryUtil.getLog(WJ48Portlet.class); public static String pilotScript; /** * Initializes portlet's configuration with pilot-script file path. * * @see com.liferay.util.bridges.mvc.MVCPortlet#init() */ @Override public void init() throws PortletException { super.init(); pilotScript = getPortletContext().getRealPath(Constants.FILE_SEPARATOR) + "WEB-INF/job/" + getInitParameter("pilot-script"); } @ProcessAction(name = "uploadFile") public void uploadFile(ActionRequest actionRequest, ActionResponse actionResponse) { ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest .getAttribute(WebKeys.THEME_DISPLAY); User user = themeDisplay.getUser(); String username = user.getScreenName(); UploadPortletRequest uploadRequest = PortalUtil .getUploadPortletRequest(actionRequest); SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.TS_FORMAT); String timestamp = dateFormat.format(Calendar.getInstance().getTime()); try { File uploadedFile = processInputFile(uploadRequest, username, timestamp); if (uploadedFile != null && uploadedFile.length() == 0) { SessionErrors.add(actionRequest, "empty-file"); } else { InputFile inputFile = new InputFile(); inputFile.setName(uploadedFile.getName()); // Path to the uploaded file in the Liferay server String filePath = uploadedFile.getAbsolutePath(); _log.debug("PATH: " + filePath); PortalUtil.copyRequestParameters(actionRequest, actionResponse); actionResponse.setRenderParameter("filePath", filePath); actionResponse.setRenderParameter("filter", ParamUtil.getString(uploadRequest, "filters")); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Hide default Liferay success/error messages PortletConfig portletConfig = (PortletConfig) actionRequest .getAttribute(JavaConstants.JAVAX_PORTLET_CONFIG); LiferayPortletConfig liferayPortletConfig = (LiferayPortletConfig) portletConfig; SessionMessages.add(actionRequest, liferayPortletConfig.getPortletId() + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE); } @ProcessAction(name = "submit") public void submit(ActionRequest actionRequest, ActionResponse actionResponse) { PortletPreferences preferences = actionRequest.getPreferences(); String JSONAppPrefs = GetterUtil.getString(preferences.getValue( Constants.APP_PREFERENCES, null)); _log.info(JSONAppPrefs); AppPreferences appPrefs = Utils.getAppPreferences(JSONAppPrefs); _log.debug(appPrefs); if (appPrefs.getApplicationId() <= 0) { SessionErrors.add(actionRequest, "wrong-app-id"); } else if (Validator.isIPAddress(appPrefs.getFgHost()) || Validator.isHostName(appPrefs.getFgHost())) { AppInput appInput = new AppInput(); appInput.setApplication(appPrefs.getApplicationId()); // Just a description of the job, could passed from the JSP maybe. appInput.setDescription("WEKA Application"); String[] inputSandbox = null; String inputFilePath = ParamUtil.getString(actionRequest, "fileName"); File inputARFF = new File(inputFilePath); List<InputFile> inputFiles = new ArrayList<InputFile>(); InputFile inputFile = new InputFile(); inputFile.setName(inputARFF.getName()); inputFiles.add(inputFile); inputSandbox = new String[] { inputFilePath }; appInput.setInputFiles(inputFiles); String filter = ParamUtil.getString(actionRequest, "filter", null); if (filter != null && !filter.isEmpty()) { appInput.getArguments().add("-f " + filter); } String folds = ParamUtil.getString(actionRequest, "folds", null); if (folds != null && !folds.isEmpty()) { appInput.getArguments().add(" -x " + folds); } appInput.getArguments().add(inputARFF.getName()); String classifier = ParamUtil .getString(actionRequest, "classifier"); appInput.getArguments().add(classifier); _log.info(appInput); FutureGatewayClient client = new FutureGatewayClient( appPrefs.getFgHost(), appPrefs.getFgPort(), appPrefs.getFgAPIVersion()); ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest .getAttribute(WebKeys.THEME_DISPLAY); User user = themeDisplay.getUser(); String username = user.getScreenName(); // 1. Create FG task try { Task t = client.createTask(appInput, username); _log.info(t); if (t.getStatus().equals("WAITING") && inputSandbox != null) { // 2. upload input file String uploadPath = ""; List<Link> links = t.getLinks(); for (Link link : links) { if (link.getRel().equals("input")) { uploadPath = link.getHref(); break; } } String t2 = client.uploadFile(uploadPath, inputSandbox); _log.info(t2); // TODO Check the FG response to see if the file was // correctly uploaded --> "gestatus": "triggered" in the // respose notify user that task was correctly submitted and // he can check status on my-jobs page } else { // TODO Manage this condition } } catch (UniformInterfaceException | IOException e) { _log.error(e.getMessage()); SessionErrors.add(actionRequest, "error"); actionResponse.setRenderParameter("jspPage", "/jsps/view.jsp"); } actionResponse.setRenderParameter("jspPage", "/jsps/submit.jsp"); } else { SessionErrors.add(actionRequest, "wrong-fg-host"); } // Hide default Liferay success/error messages PortletConfig portletConfig = (PortletConfig) actionRequest .getAttribute(JavaConstants.JAVAX_PORTLET_CONFIG); LiferayPortletConfig liferayPortletConfig = (LiferayPortletConfig) portletConfig; SessionMessages.add(actionRequest, liferayPortletConfig.getPortletId() + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE); } * _log.info(t2); // // /* // * TODO Check the FG * response to see if the file was correctly // * * uploaded --> "gestatus": "triggered" in the respose * notify // * user that task was correctly submitted * and he can check // * status on my-jobs page // // } * else { // // TODO Manage this condition // } * * } } else { SessionErrors.add(actionRequest, * "wrong-fg-host"); } * * // Hide default Liferay success/error messages * PortletConfig portletConfig = (PortletConfig) * actionRequest * .getAttribute(JavaConstants.JAVAX_PORTLET_CONFIG); * LiferayPortletConfig liferayPortletConfig = * (LiferayPortletConfig) portletConfig; * SessionMessages.add(actionRequest, * liferayPortletConfig.getPortletId() + * SessionMessages. * KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE); } */ /** * @param uploadRequest * @param username * @param timestamp * @return * @throws IOException */ private File processInputFile(UploadPortletRequest uploadRequest, String username, String timestamp) throws IOException { File file = null; String fileInputName = "fileupload"; String sourceFileName = uploadRequest.getFileName(fileInputName); if (Validator.isNotNull(sourceFileName)) { _log.debug("Uploading file: " + sourceFileName + " ..."); String fileName = FileUtil.stripExtension(sourceFileName); _log.debug(fileName); String extension = FileUtil.getExtension(sourceFileName); _log.debug(extension); // Get the uploaded file as a file. File uploadedFile = uploadRequest.getFile(fileInputName, true); File folder = new File(Constants.ROOT_FOLDER_NAME); // This is our final file path. file = new File(folder.getAbsolutePath() + Constants.FILE_SEPARATOR + username + "_" + timestamp + "_" + fileName + ((!extension.isEmpty()) ? "." + extension : "")); FileUtil.move(uploadedFile, file); } return file; } }
package cgeo.geocaching; import cgeo.geocaching.activity.AbstractActivity; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.geopoint.DistanceParser; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.GeopointFormatter; import cgeo.geocaching.geopoint.GeopointParser; import org.apache.commons.lang3.StringUtils; import android.app.ProgressDialog; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Html; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import java.util.ArrayList; import java.util.List; public class cgeowaypointadd extends AbstractActivity { private String geocode = null; private int id = -1; private cgGeo geo = null; private UpdateLocationCallback geoUpdate = new update(); private ProgressDialog waitDialog = null; private cgWaypoint waypoint = null; private WaypointType type = WaypointType.OWN; private String prefix = "OWN"; private String lookup = " /** * number of waypoints that the corresponding cache has until now */ private int wpCount = 0; private Handler loadWaypointHandler = new Handler() { @Override public void handleMessage(Message msg) { try { if (waypoint == null) { if (waitDialog != null) { waitDialog.dismiss(); waitDialog = null; } id = -1; } else { geocode = waypoint.getGeocode(); type = waypoint.getWaypointType(); prefix = waypoint.getPrefix(); lookup = waypoint.getLookup(); app.setAction(geocode); if (waypoint.getCoords() != null) { ((Button) findViewById(R.id.buttonLatitude)).setText(waypoint.getCoords().format(GeopointFormatter.Format.LAT_DECMINUTE)); ((Button) findViewById(R.id.buttonLongitude)).setText(waypoint.getCoords().format(GeopointFormatter.Format.LON_DECMINUTE)); } ((EditText) findViewById(R.id.name)).setText(Html.fromHtml(StringUtils.trimToEmpty(waypoint.getName())).toString()); ((EditText) findViewById(R.id.note)).setText(Html.fromHtml(StringUtils.trimToEmpty(waypoint.getNote())).toString()); if (waitDialog != null) { waitDialog.dismiss(); waitDialog = null; } } } catch (Exception e) { if (waitDialog != null) { waitDialog.dismiss(); waitDialog = null; } Log.e(Settings.tag, "cgeowaypointadd.loadWaypointHandler: " + e.toString()); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(); setContentView(R.layout.waypoint_new); setTitle("waypoint"); if (geo == null) { geo = app.startGeo(geoUpdate); } // get parameters Bundle extras = getIntent().getExtras(); if (extras != null) { geocode = extras.getString("geocode"); wpCount = extras.getInt("count", 0); id = extras.getInt("waypoint"); } if (StringUtils.isBlank(geocode) && id <= 0) { showToast(res.getString(R.string.err_waypoint_cache_unknown)); finish(); return; } if (id <= 0) { setTitle(res.getString(R.string.waypoint_add_title)); } else { setTitle(res.getString(R.string.waypoint_edit_title)); } if (geocode != null) { app.setAction(geocode); } Button buttonLat = (Button) findViewById(R.id.buttonLatitude); buttonLat.setOnClickListener(new coordDialogListener()); Button buttonLon = (Button) findViewById(R.id.buttonLongitude); buttonLon.setOnClickListener(new coordDialogListener()); Button addWaypoint = (Button) findViewById(R.id.add_waypoint); addWaypoint.setOnClickListener(new coordsListener()); List<String> wayPointNames = new ArrayList<String>(cgBase.waypointTypes.values()); AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.name); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, wayPointNames); textView.setAdapter(adapter); if (id > 0) { waitDialog = ProgressDialog.show(this, null, res.getString(R.string.waypoint_loading), true); waitDialog.setCancelable(true); (new loadWaypoint()).start(); } disableSuggestions((EditText) findViewById(R.id.distance)); } @Override public void onResume() { super.onResume(); if (geo == null) { geo = app.startGeo(geoUpdate); } if (id > 0) { if (waitDialog == null) { waitDialog = ProgressDialog.show(this, null, res.getString(R.string.waypoint_loading), true); waitDialog.setCancelable(true); (new loadWaypoint()).start(); } } } @Override public void onDestroy() { if (geo != null) { geo = app.removeGeo(); } super.onDestroy(); } @Override public void onStop() { if (geo != null) { geo = app.removeGeo(); } super.onStop(); } @Override public void onPause() { if (geo != null) { geo = app.removeGeo(); } super.onPause(); } private class update implements UpdateLocationCallback { @Override public void updateLocation(cgGeo geo) { Log.d(Settings.tag, "cgeowaypointadd.updateLocation called"); if (geo == null || geo.coordsNow == null) { return; } try { Button bLat = (Button) findViewById(R.id.buttonLatitude); Button bLon = (Button) findViewById(R.id.buttonLongitude); bLat.setHint(geo.coordsNow.format(GeopointFormatter.Format.LAT_DECMINUTE_RAW)); bLon.setHint(geo.coordsNow.format(GeopointFormatter.Format.LON_DECMINUTE_RAW)); } catch (Exception e) { Log.w(Settings.tag, "Failed to update location."); } } } private class loadWaypoint extends Thread { @Override public void run() { try { waypoint = app.loadWaypoint(id); loadWaypointHandler.sendMessage(new Message()); } catch (Exception e) { Log.e(Settings.tag, "cgeowaypoint.loadWaypoint.run: " + e.toString()); } } } private class coordDialogListener implements View.OnClickListener { public void onClick(View arg0) { Geopoint gp = null; if (waypoint != null && waypoint.getCoords() != null) { gp = waypoint.getCoords(); } cgeocoords coordsDialog = new cgeocoords(cgeowaypointadd.this, gp, geo); coordsDialog.setCancelable(true); coordsDialog.setOnCoordinateUpdate(new cgeocoords.CoordinateUpdate() { @Override public void update(final Geopoint gp) { ((Button) findViewById(R.id.buttonLatitude)).setText(gp.format(GeopointFormatter.Format.LAT_DECMINUTE)); ((Button) findViewById(R.id.buttonLongitude)).setText(gp.format(GeopointFormatter.Format.LON_DECMINUTE)); if (waypoint != null) { waypoint.setCoords(gp); } } }); coordsDialog.show(); } } private class coordsListener implements View.OnClickListener { public void onClick(View arg0) { final String bearingText = ((EditText) findViewById(R.id.bearing)).getText().toString(); final String distanceText = ((EditText) findViewById(R.id.distance)).getText().toString(); final String latText = ((Button) findViewById(R.id.buttonLatitude)).getText().toString(); final String lonText = ((Button) findViewById(R.id.buttonLongitude)).getText().toString(); if (StringUtils.isBlank(bearingText) && StringUtils.isBlank(distanceText) && StringUtils.isBlank(latText) && StringUtils.isBlank(lonText)) { helpDialog(res.getString(R.string.err_point_no_position_given_title), res.getString(R.string.err_point_no_position_given)); return; } double latitude; double longitude; if (StringUtils.isNotBlank(latText) && StringUtils.isNotBlank(lonText)) { try { latitude = GeopointParser.parseLatitude(latText); longitude = GeopointParser.parseLongitude(lonText); } catch (GeopointParser.ParseException e) { showToast(res.getString(e.resource)); return; } } else { if (geo == null || geo.coordsNow == null) { showToast(res.getString(R.string.err_point_curr_position_unavailable)); return; } latitude = geo.coordsNow.getLatitude(); longitude = geo.coordsNow.getLongitude(); } Geopoint coords = null; if (StringUtils.isNotBlank(bearingText) && StringUtils.isNotBlank(distanceText)) { // bearing & distance double bearing = 0; try { bearing = Double.parseDouble(bearingText); } catch (NumberFormatException e) { helpDialog(res.getString(R.string.err_point_bear_and_dist_title), res.getString(R.string.err_point_bear_and_dist)); return; } double distance; try { distance = DistanceParser.parseDistance(distanceText, Settings.isUseMetricUnits()); } catch (NumberFormatException e) { showToast(res.getString(R.string.err_parse_dist)); return; } coords = new Geopoint(latitude, longitude).project(bearing, distance); } else { coords = new Geopoint(latitude, longitude); } String name = ((EditText) findViewById(R.id.name)).getText().toString().trim(); // if no name is given, just give the waypoint its number as name if (name.length() == 0) { name = res.getString(R.string.waypoint) + " " + String.valueOf(wpCount + 1); } final String note = ((EditText) findViewById(R.id.note)).getText().toString().trim(); final cgWaypoint waypoint = new cgWaypoint(name, type); waypoint.setGeocode(geocode); waypoint.setPrefix(prefix); waypoint.setLookup(lookup); waypoint.setCoords(coords); waypoint.setNote(note); waypoint.setId(id); if (app.saveOwnWaypoint(id, geocode, waypoint)) { StaticMapsProvider.removeWpStaticMaps(id, geocode); if (Settings.isStoreOfflineWpMaps()) { StaticMapsProvider.storeWaypointStaticMap(app.getCacheByGeocode(geocode), cgeowaypointadd.this, waypoint); } finish(); return; } else { showToast(res.getString(R.string.err_waypoint_add_failed)); } } } @Override public void goManual(View view) { if (id >= 0) { ActivityMixin.goManual(this, "c:geo-waypoint-edit"); } else { ActivityMixin.goManual(this, "c:geo-waypoint-new"); } } }
package sk.henrichg.phoneprofilesplus; import android.animation.LayoutTransition; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.PopupMenu; import android.widget.RelativeLayout; import android.widget.TextView; import com.getkeepsafe.taptargetview.TapTarget; import com.getkeepsafe.taptargetview.TapTargetSequence; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.AppCompatSpinner; import androidx.appcompat.widget.Toolbar; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class EditorEventListFragment extends Fragment implements OnStartDragItemListener { public DataWrapper activityDataWrapper; private RelativeLayout activatedProfileHeader; RecyclerView listView; private TextView activeProfileName; private ImageView activeProfileIcon; private Toolbar bottomToolbar; TextView textViewNoData; private LinearLayout progressBar; private AppCompatSpinner orderSpinner; private EditorEventListAdapter eventListAdapter; private ItemTouchHelper itemTouchHelper; private WeakReference<LoadEventListAsyncTask> asyncTaskContext; // private ValueAnimator hideAnimatorHeader; // private ValueAnimator showAnimatorHeader; // private int headerHeight; // private ValueAnimator hideAnimatorBottomBar; // private ValueAnimator showAnimatorBottomBar; // private int bottomBarHeight; private int orderSelectedItem = 0; static final int EDIT_MODE_UNDEFINED = 0; static final int EDIT_MODE_INSERT = 1; static final int EDIT_MODE_DUPLICATE = 2; private static final int EDIT_MODE_EDIT = 3; static final int EDIT_MODE_DELETE = 4; static final String FILTER_TYPE_ARGUMENT = "filter_type"; //static final String ORDER_TYPE_ARGUMENT = "order_type"; static final String START_TARGET_HELPS_ARGUMENT = "start_target_helps"; static final int FILTER_TYPE_ALL = 0; static final int FILTER_TYPE_RUNNING = 1; static final int FILTER_TYPE_PAUSED = 2; static final int FILTER_TYPE_STOPPED = 3; static final int FILTER_TYPE_START_ORDER = 4; private static final int ORDER_TYPE_START_ORDER = 0; private static final int ORDER_TYPE_EVENT_NAME = 1; private static final int ORDER_TYPE_PROFILE_NAME = 2; private static final int ORDER_TYPE_PRIORITY = 3; public boolean targetHelpsSequenceStarted; public static final String PREF_START_TARGET_HELPS = "editor_event_list_fragment_start_target_helps"; private int filterType = FILTER_TYPE_ALL; private int orderType = ORDER_TYPE_EVENT_NAME; static final String SP_EDITOR_ORDER_SELECTED_ITEM = "editor_order_selected_item"; /** * The fragment's current callback objects */ private OnStartEventPreferences onStartEventPreferencesCallback = sDummyOnStartEventPreferencesCallback; /** * A callback interface that all activities containing this fragment must * implement. This mechanism allows activities to be notified. */ // invoked when start profile preference fragment/activity needed interface OnStartEventPreferences { void onStartEventPreferences(Event event, int editMode, int predefinedEventIndex/*, boolean startTargetHelps*/); } /** * A dummy implementation of the Callbacks interface that does * nothing. Used only when this fragment is not attached to an activity. */ private static final OnStartEventPreferences sDummyOnStartEventPreferencesCallback = new OnStartEventPreferences() { public void onStartEventPreferences(Event event, int editMode, int predefinedEventIndex/*, boolean startTargetHelps*/) { } }; public EditorEventListFragment() { } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); onStartEventPreferencesCallback = (OnStartEventPreferences) getActivity(); } @Override public void onDetach() { super.onDetach(); // Reset the active callbacks interface to the dummy implementation. onStartEventPreferencesCallback = sDummyOnStartEventPreferencesCallback; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // this is really important in order to save the state across screen // configuration changes for example setRetainInstance(true); filterType = getArguments() != null ? getArguments().getInt(FILTER_TYPE_ARGUMENT, EditorEventListFragment.FILTER_TYPE_START_ORDER) : EditorEventListFragment.FILTER_TYPE_START_ORDER; // orderType = getArguments() != null ? // getArguments().getInt(ORDER_TYPE_ARGUMENT, EditorEventListFragment.ORDER_TYPE_START_ORDER) : // EditorEventListFragment.ORDER_TYPE_START_ORDER; orderType = getEventsOrderType(); //Log.d("EditorEventListFragment.onCreate","filterType="+filterType); //Log.d("EditorEventListFragment.onCreate","orderType="+orderType); //noinspection ConstantConditions activityDataWrapper = new DataWrapper(getActivity().getApplicationContext(), false, 0, false); getActivity().getIntent(); setHasOptionsMenu(true); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView; boolean applicationEditorPrefIndicator = ApplicationPreferences.applicationEditorPrefIndicator(activityDataWrapper.context); //boolean applicationEditorHeader = ApplicationPreferences.applicationEditorHeader(activityDataWrapper.context); //rootView = inflater.inflate(R.layout.editor_event_list, container, false); if (applicationEditorPrefIndicator/* && applicationEditorHeader*/) rootView = inflater.inflate(R.layout.editor_event_list, container, false); else //if (applicationEditorHeader) rootView = inflater.inflate(R.layout.editor_event_list_no_indicator, container, false); //else // rootView = inflater.inflate(R.layout.editor_event_list_no_header, container, false); return rootView; } @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); doOnViewCreated(view/*, savedInstanceState*/); boolean startTargetHelps = getArguments() != null && getArguments().getBoolean(START_TARGET_HELPS_ARGUMENT, false); if (startTargetHelps) showTargetHelps(); } @SuppressWarnings("ConstantConditions") private void doOnViewCreated(View view/*, Bundle savedInstanceState*/) { //super.onActivityCreated(savedInstanceState); activeProfileName = view.findViewById(R.id.activated_profile_name); activeProfileIcon = view.findViewById(R.id.activated_profile_icon); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity()); listView = view.findViewById(R.id.editor_events_list); //listView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL)); listView.setLayoutManager(layoutManager); listView.setHasFixedSize(true); activatedProfileHeader = view.findViewById(R.id.activated_profile_header); /*if (activatedProfileHeader != null) { Handler handler = new Handler(getActivity().getMainLooper()); handler.postDelayed(new Runnable() { @Override public void run() { if (getActivity() == null) return; headerHeight = activatedProfileHeader.getMeasuredHeight(); //Log.e("EditorProfileListFragment.doOnViewCreated", "headerHeight="+headerHeight); hideAnimatorHeader = ValueAnimator.ofInt(headerHeight / 4, 0); hideAnimatorHeader.setDuration(500); hideAnimatorHeader.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { int val = (Integer) valueAnimator.getAnimatedValue(); //Log.e("hideAnimator.onAnimationUpdate", "val="+val); ViewGroup.LayoutParams layoutParams = activatedProfileHeader.getLayoutParams(); layoutParams.height = val * 4; activatedProfileHeader.setLayoutParams(layoutParams); } }); showAnimatorHeader = ValueAnimator.ofInt(0, headerHeight / 4); showAnimatorHeader.setDuration(500); showAnimatorHeader.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { int val = (Integer) valueAnimator.getAnimatedValue(); //Log.e("showAnimator.onAnimationUpdate", "val="+val); ViewGroup.LayoutParams layoutParams = activatedProfileHeader.getLayoutParams(); layoutParams.height = val * 4; activatedProfileHeader.setLayoutParams(layoutParams); } }); bottomBarHeight = bottomToolbar.getMeasuredHeight(); //Log.e("EditorProfileListFragment.doOnViewCreated", "headerHeight="+headerHeight); hideAnimatorBottomBar = ValueAnimator.ofInt(bottomBarHeight / 4, 0); hideAnimatorBottomBar.setDuration(500); hideAnimatorBottomBar.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { int val = (Integer) valueAnimator.getAnimatedValue(); //Log.e("hideAnimator.onAnimationUpdate", "val="+val); ViewGroup.LayoutParams layoutParams = bottomToolbar.getLayoutParams(); layoutParams.height = val * 4; bottomToolbar.setLayoutParams(layoutParams); } }); showAnimatorBottomBar = ValueAnimator.ofInt(0, bottomBarHeight / 4); showAnimatorBottomBar.setDuration(500); showAnimatorBottomBar.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { int val = (Integer) valueAnimator.getAnimatedValue(); //Log.e("showAnimator.onAnimationUpdate", "val="+val); ViewGroup.LayoutParams layoutParams = bottomToolbar.getLayoutParams(); layoutParams.height = val * 4; bottomToolbar.setLayoutParams(layoutParams); } }); } }, 200); }*/ bottomToolbar = view.findViewById(R.id.editor_list_bottom_bar); final LayoutTransition layoutTransition = ((ViewGroup) view.findViewById(R.id.layout_events_list_fragment)) .getLayoutTransition(); layoutTransition.enableTransitionType(LayoutTransition.CHANGING); //layoutTransition.setDuration(500); listView.addOnScrollListener(new HidingRecyclerViewScrollListener() { @Override public void onHide() { //if ((activatedProfileHeader.getMeasuredHeight() >= headerHeight - 4) && // (activatedProfileHeader.getMeasuredHeight() <= headerHeight + 4)) // if (!hideAnimatorHeader.isRunning()) { // hideAnimatorHeader.start(); // if (!showAnimatorBottomBar.isRunning()) { // showAnimatorBottomBar.start(); if (!layoutTransition.isRunning()) { //final int firstVisibleItem = ((LinearLayoutManager) listView.getLayoutManager()).findFirstVisibleItemPosition(); //if (firstVisibleItem != 0) activatedProfileHeader.setVisibility(View.GONE); bottomToolbar.setVisibility(View.VISIBLE); } } @Override public void onShow() { //if (activatedProfileHeader.getMeasuredHeight() == 0) // if (!showAnimatorHeader.isRunning()) { // showAnimatorHeader.start(); // if (!hideAnimatorBottomBar.isRunning()) { // hideAnimatorBottomBar.start(); if (!layoutTransition.isRunning()) { //final int firstVisibleItem = ((LinearLayoutManager) listView.getLayoutManager()).findFirstVisibleItemPosition(); //if (firstVisibleItem == 0) activatedProfileHeader.setVisibility(View.VISIBLE); bottomToolbar.setVisibility(View.GONE); } } }); textViewNoData = view.findViewById(R.id.editor_events_list_empty); progressBar = view.findViewById(R.id.editor_events_list_linla_progress); /* View footerView = ((LayoutInflater)getActivity().getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)) .inflate(R.layout.editor_list_footer, null, false); listView.addFooterView(footerView, null, false); */ final EditorEventListFragment fragment = this; Menu menu = bottomToolbar.getMenu(); if (menu != null) menu.clear(); bottomToolbar.inflateMenu(R.menu.editor_events_bottom_bar); bottomToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.menu_add_event: if (eventListAdapter != null) { ((EditorProfilesActivity) getActivity()).addEventDialog = new AddEventDialog(getActivity(), fragment); ((EditorProfilesActivity) getActivity()).addEventDialog.show(); } return true; case R.id.menu_delete_all_events: deleteAllEvents(); return true; case R.id.menu_default_profile: Intent intent = new Intent(getActivity(), PhoneProfilesPrefsActivity.class); intent.putExtra(PhoneProfilesPrefsActivity.EXTRA_SCROLL_TO, "profileActivationCategoryRoot"); startActivity(intent); return true; } return false; } }); LinearLayout orderLayout = view.findViewById(R.id.editor_list_bottom_bar_order_root); if (filterType == EditorEventListFragment.FILTER_TYPE_START_ORDER) orderLayout.setVisibility(View.GONE); else orderLayout.setVisibility(View.VISIBLE); ApplicationPreferences.getSharedPreferences(getActivity()); orderSelectedItem = ApplicationPreferences.preferences.getInt(SP_EDITOR_ORDER_SELECTED_ITEM, 0); orderSpinner = view.findViewById(R.id.editor_list_bottom_bar_order); HighlightedSpinnerAdapter orderSpinnerAdapter = new HighlightedSpinnerAdapter( getActivity(), R.layout.editor_toolbar_spinner, getResources().getStringArray(R.array.orderEventsArray)); orderSpinnerAdapter.setDropDownViewResource(R.layout.editor_toolbar_spinner_dropdown); orderSpinner.setPopupBackgroundResource(R.drawable.popupmenu_background); orderSpinner.setSupportBackgroundTintList(ContextCompat.getColorStateList(getActivity().getBaseContext(), R.color.accent)); orderSpinner.setAdapter(orderSpinnerAdapter); orderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { ((HighlightedSpinnerAdapter)orderSpinner.getAdapter()).setSelection(position); if (position != orderSelectedItem) changeEventOrder(position); } public void onNothingSelected(AdapterView<?> parent) { } }); TextView orderLabel = view.findViewById(R.id.editor_list_bottom_bar_order_title); orderLabel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { orderSpinner.performClick(); } }); PPApplication.logE("EditorEventListFragment.doOnViewCreated", "orderSelectedItem="+orderSelectedItem); // first must be set eventsOrderType changeEventOrder(orderSelectedItem/*, savedInstanceState != null*/); } private static class LoadEventListAsyncTask extends AsyncTask<Void, Void, Void> { private final WeakReference<EditorEventListFragment> fragmentWeakRef; private final DataWrapper _dataWrapper; private final int _filterType; private final int _orderType; final boolean applicationEditorPrefIndicator; private LoadEventListAsyncTask (EditorEventListFragment fragment, int filterType, int orderType) { fragmentWeakRef = new WeakReference<>(fragment); _filterType = filterType; _orderType = orderType; //noinspection ConstantConditions _dataWrapper = new DataWrapper(fragment.getActivity().getApplicationContext(), false, 0, false); applicationEditorPrefIndicator = ApplicationPreferences.applicationEditorPrefIndicator(_dataWrapper.context); } @Override protected void onPreExecute() { super.onPreExecute(); EditorEventListFragment fragment = this.fragmentWeakRef.get(); if ((fragment != null) && (fragment.isAdded())) { fragment.textViewNoData.setVisibility(View.GONE); fragment.progressBar.setVisibility(View.VISIBLE); } } @Override protected Void doInBackground(Void... params) { _dataWrapper.fillProfileList(true, applicationEditorPrefIndicator); _dataWrapper.fillEventList(); //Log.d("EditorEventListFragment.LoadEventListAsyncTask","filterType="+filterType); if (_filterType == FILTER_TYPE_START_ORDER) EditorEventListFragment.sortList(_dataWrapper.eventList, ORDER_TYPE_START_ORDER, _dataWrapper); else EditorEventListFragment.sortList(_dataWrapper.eventList, _orderType, _dataWrapper); return null; } @Override protected void onPostExecute(Void response) { super.onPostExecute(response); EditorEventListFragment fragment = fragmentWeakRef.get(); if ((fragment != null) && (fragment.isAdded())) { fragment.progressBar.setVisibility(View.GONE); // get local profileList _dataWrapper.fillProfileList(true, applicationEditorPrefIndicator); // set local profile list into activity dataWrapper fragment.activityDataWrapper.copyProfileList(_dataWrapper); // get local eventList _dataWrapper.fillEventList(); // set local event list into activity dataWrapper fragment.activityDataWrapper.copyEventList(_dataWrapper); fragment.eventListAdapter = new EditorEventListAdapter(fragment, fragment.activityDataWrapper, _filterType, fragment); // added touch helper for drag and drop items ItemTouchHelper.Callback callback = new ItemTouchHelperCallback(fragment.eventListAdapter, false, false); fragment.itemTouchHelper = new ItemTouchHelper(callback); fragment.itemTouchHelper.attachToRecyclerView(fragment.listView); fragment.listView.setAdapter(fragment.eventListAdapter); Profile profile = fragment.activityDataWrapper.getActivatedProfileFromDB(true, applicationEditorPrefIndicator); fragment.updateHeader(profile); } } } boolean isAsyncTaskPendingOrRunning() { try { return this.asyncTaskContext != null && this.asyncTaskContext.get() != null && !this.asyncTaskContext.get().getStatus().equals(AsyncTask.Status.FINISHED); } catch (Exception e) { return false; } } void stopRunningAsyncTask() { this.asyncTaskContext.get().cancel(true); } @Override public void onDestroy() { if (isAsyncTaskPendingOrRunning()) { stopRunningAsyncTask(); } if (listView != null) listView.setAdapter(null); if (eventListAdapter != null) eventListAdapter.release(); if (activityDataWrapper != null) activityDataWrapper.invalidateDataWrapper(); activityDataWrapper = null; super.onDestroy(); } @Override public void onStartDrag(RecyclerView.ViewHolder viewHolder) { itemTouchHelper.startDrag(viewHolder); } void startEventPreferencesActivity(Event event, int predefinedEventIndex) { int editMode; if (event != null) { // edit event int eventPos = eventListAdapter.getItemPosition(event); /*int last = listView.getLastVisiblePosition(); int first = listView.getFirstVisiblePosition(); if ((eventPos <= first) || (eventPos >= last)) { listView.setSelection(eventPos); }*/ RecyclerView.LayoutManager lm = listView.getLayoutManager(); if (lm != null) lm.scrollToPosition(eventPos); boolean startTargetHelps = getArguments() != null && getArguments().getBoolean(START_TARGET_HELPS_ARGUMENT, false); if (startTargetHelps) showAdapterTargetHelps(); editMode = EDIT_MODE_EDIT; } else { // add new event editMode = EDIT_MODE_INSERT; } // Notify the active callbacks interface (the activity, if the // fragment is attached to one) one must start profile preferences onStartEventPreferencesCallback.onStartEventPreferences(event, editMode, predefinedEventIndex); } void runStopEvent(final Event event) { if (Event.getGlobalEventsRunning(activityDataWrapper.context)) { // events are not globally stopped List<EventTimeline> eventTimelineList = activityDataWrapper.getEventTimelineList(); if (event.getStatusFromDB(activityDataWrapper.context) == Event.ESTATUS_STOP) { // pause event // not needed to use handlerThread, profile is not activated (activateReturnProfile=false) event.pauseEvent(activityDataWrapper, eventTimelineList, false, false, false, /*false,*/ null, false, false); } else { // stop event // not needed to use handlerThread, profile is not activated (activateReturnProfile=false) event.stopEvent(activityDataWrapper, eventTimelineList, false, false, true/*, false*/); // activate return profile } // redraw event list updateListView(event, false, false, true, 0); // restart events PPApplication.logE("$$$ restartEvents","from EditorEventListFragment.runStopEvent"); activityDataWrapper.restartEvents(false, true, true, true, true); /*Intent serviceIntent = new Intent(activityDataWrapper.context, PhoneProfilesService.class); serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false); serviceIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_JOBS, true); PPApplication.startPPService(activityDataWrapper.context, serviceIntent);*/ Intent commandIntent = new Intent(PhoneProfilesService.ACTION_COMMAND); //commandIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false); commandIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_JOBS, true); PPApplication.runCommand(activityDataWrapper.context, commandIntent); } else { if (event.getStatusFromDB(activityDataWrapper.context) == Event.ESTATUS_STOP) { // pause event event.setStatus(Event.ESTATUS_PAUSE); } else { // stop event event.setStatus(Event.ESTATUS_STOP); } // update event in DB DatabaseHandler.getInstance(activityDataWrapper.context).updateEvent(event); // redraw event list updateListView(event, false, false, true, 0); } } private void duplicateEvent(Event origEvent) { /* Event newEvent = new Event( origEvent._name+"_d", origEvent._type, origEvent._fkProfile, origEvent._status ); newEvent.copyEventPreferences(origEvent); // add event into db and set id and order databaseHandler.addEvent(newEvent); // add event into listview eventListAdapter.addItem(newEvent, false); updateListView(newEvent, false); startEventPreferencesActivity(newEvent); */ int editMode; // duplicate event editMode = EDIT_MODE_DUPLICATE; // Notify the active callbacks interface (the activity, if the // fragment is attached to one) one must start profile preferences onStartEventPreferencesCallback.onStartEventPreferences(origEvent, editMode, 0); } private void deleteEvent(final Event event) { if (activityDataWrapper.getEventById(event._id) == null) // event not exists return; activityDataWrapper.addActivityLog(DatabaseHandler.ALTYPE_EVENTDELETED, event._name, null, null, 0); listView.getRecycledViewPool().clear(); eventListAdapter.deleteItemNoNotify(event); DatabaseHandler.getInstance(activityDataWrapper.context).deleteEvent(event); // restart events PPApplication.logE("$$$ restartEvents", "from EditorEventListFragment.deleteEvent"); activityDataWrapper.restartEvents(false, true, true, true, true); eventListAdapter.notifyDataSetChanged(); /*Intent serviceIntent = new Intent(getActivity().getApplicationContext(), PhoneProfilesService.class); serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false); serviceIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_JOBS, true); PPApplication.startPPService(getActivity(), serviceIntent);*/ Intent commandIntent = new Intent(PhoneProfilesService.ACTION_COMMAND); //commandIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false); commandIntent.putExtra(PhoneProfilesService.EXTRA_REREGISTER_RECEIVERS_AND_JOBS, true); PPApplication.runCommand(getActivity(), commandIntent); onStartEventPreferencesCallback.onStartEventPreferences(null, EDIT_MODE_DELETE, 0); } public void showEditMenu(View view) { //Context context = ((AppCompatActivity)getActivity()).getSupportActionBar().getThemedContext(); Context context = view.getContext(); PopupMenu popup; //if (android.os.Build.VERSION.SDK_INT >= 19) popup = new PopupMenu(context, view, Gravity.END); //else // popup = new PopupMenu(context, view); Menu menu = popup.getMenu(); //noinspection ConstantConditions getActivity().getMenuInflater().inflate(R.menu.event_list_item_edit, menu); final Event event = (Event)view.getTag(); MenuItem menuItem = menu.findItem(R.id.event_list_item_menu_run_stop); //if (PPApplication.getGlobalEventsRunning(dataWrapper.context)) //menuItem.setVisible(true); if (event.getStatusFromDB(activityDataWrapper.context) == Event.ESTATUS_STOP) { menuItem.setTitle(R.string.event_list_item_menu_run); } else { menuItem.setTitle(R.string.event_list_item_menu_stop); } //else // menuItem.setVisible(false); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(android.view.MenuItem item) { switch (item.getItemId()) { case R.id.event_list_item_menu_run_stop: runStopEvent(event); return true; case R.id.event_list_item_menu_duplicate: duplicateEvent(event); return true; case R.id.event_list_item_menu_delete: deleteEventWithAlert(event); return true; default: return false; } } }); popup.show(); } private void deleteEventWithAlert(Event event) { final Event _event = event; //noinspection ConstantConditions AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()); dialogBuilder.setTitle(getResources().getString(R.string.event_string_0) + ": " + event._name); dialogBuilder.setMessage(getResources().getString(R.string.delete_event_alert_message)); //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert); dialogBuilder.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { deleteEvent(_event); } }); dialogBuilder.setNegativeButton(R.string.alert_button_no, null); AlertDialog dialog = dialogBuilder.create(); /*dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE); if (positive != null) positive.setAllCaps(false); Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE); if (negative != null) negative.setAllCaps(false); } });*/ if (!getActivity().isFinishing()) dialog.show(); } private void deleteAllEvents() { if (eventListAdapter != null) { //noinspection ConstantConditions AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()); dialogBuilder.setTitle(getResources().getString(R.string.alert_title_delete_all_events)); dialogBuilder.setMessage(getResources().getString(R.string.alert_message_delete_all_events)); //dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert); dialogBuilder.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { activityDataWrapper.addActivityLog(DatabaseHandler.ALTYPE_ALLEVENTSDELETED, null, null, null, 0); listView.getRecycledViewPool().clear(); activityDataWrapper.stopAllEventsFromMainThread(true, false); eventListAdapter.clear(); // this is in eventListAdapter.clear() //eventListAdapter.notifyDataSetChanged(); if (getActivity() != null) { /*Intent serviceIntent = new Intent(getActivity().getApplicationContext(), PhoneProfilesService.class); serviceIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false); serviceIntent.putExtra(PhoneProfilesService.EXTRA_UNREGISTER_RECEIVERS_AND_JOBS, true); PPApplication.startPPService(getActivity(), serviceIntent);*/ Intent commandIntent = new Intent(PhoneProfilesService.ACTION_COMMAND); //commandIntent.putExtra(PhoneProfilesService.EXTRA_ONLY_START, false); commandIntent.putExtra(PhoneProfilesService.EXTRA_UNREGISTER_RECEIVERS_AND_JOBS, true); PPApplication.runCommand(getActivity(), commandIntent); } onStartEventPreferencesCallback.onStartEventPreferences(null, EDIT_MODE_DELETE, 0); } }); dialogBuilder.setNegativeButton(R.string.alert_button_no, null); AlertDialog dialog = dialogBuilder.create(); /*dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { Button positive = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE); if (positive != null) positive.setAllCaps(false); Button negative = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE); if (negative != null) negative.setAllCaps(false); } });*/ if (!getActivity().isFinishing()) dialog.show(); } } void updateHeader(Profile profile) { //if (!ApplicationPreferences.applicationEditorHeader(activityDataWrapper.context)) // return; if ((activeProfileName == null) || (activeProfileIcon == null)) return; String oldDisplayedText = (String)activatedProfileHeader.getTag(); if (profile == null) { activatedProfileHeader.setTag(getString(R.string.profiles_header_profile_name_no_activated)); activeProfileName.setText(getResources().getString(R.string.profiles_header_profile_name_no_activated)); activeProfileIcon.setImageResource(R.drawable.ic_profile_default); } else { activatedProfileHeader.setTag(DataWrapper.getProfileNameWithManualIndicatorAsString(profile, true, "", true, false, activityDataWrapper, true, activityDataWrapper.context)); activeProfileName.setText(DataWrapper.getProfileNameWithManualIndicator(profile, true, "", true, false, activityDataWrapper, true, activityDataWrapper.context)); if (profile.getIsIconResourceID()) { if (profile._iconBitmap != null) activeProfileIcon.setImageBitmap(profile._iconBitmap); else { //int res = getResources().getIdentifier(profile.getIconIdentifier(), "drawable", getActivity().getPackageName()); int res = Profile.getIconResource(profile.getIconIdentifier()); activeProfileIcon.setImageResource(res); // icon resource } } else { activeProfileIcon.setImageBitmap(profile._iconBitmap); } } if (ApplicationPreferences.applicationEditorPrefIndicator(activityDataWrapper.context)) { //noinspection ConstantConditions ImageView profilePrefIndicatorImageView = getActivity().findViewById(R.id.activated_profile_pref_indicator); if (profilePrefIndicatorImageView != null) { //profilePrefIndicatorImageView.setImageBitmap(ProfilePreferencesIndicator.paint(profile, getActivity().getBaseContext())); if (profile == null) profilePrefIndicatorImageView.setImageResource(R.drawable.ic_empty); else { if (profile._preferencesIndicator != null) profilePrefIndicatorImageView.setImageBitmap(profile._preferencesIndicator); else profilePrefIndicatorImageView.setImageResource(R.drawable.ic_empty); } } } String newDisplayedText = (String)activatedProfileHeader.getTag(); if (!newDisplayedText.equals(oldDisplayedText)) activatedProfileHeader.setVisibility(View.VISIBLE); } void updateListView(Event event, boolean newEvent, boolean refreshIcons, boolean setPosition, long loadEventId) { /*if (listView != null) listView.cancelDrag();*/ if (eventListAdapter != null) listView.getRecycledViewPool().clear(); if (eventListAdapter != null) { if ((newEvent) && (event != null)) // add event into listview eventListAdapter.addItem(event); } synchronized (activityDataWrapper.eventList) { if (activityDataWrapper.eventList != null) { // sort list sortList(activityDataWrapper.eventList, orderType, activityDataWrapper); } } if (eventListAdapter != null) { int eventPos = ListView.INVALID_POSITION; if (event != null) eventPos = eventListAdapter.getItemPosition(event); //else // eventPos = listView.getCheckedItemPosition(); if (loadEventId != 0) { if (getActivity() != null) { Event eventFromDB = DatabaseHandler.getInstance(getActivity().getApplicationContext()).getEvent(loadEventId); activityDataWrapper.updateEvent(eventFromDB); refreshIcons = true; } } eventListAdapter.notifyDataSetChanged(refreshIcons); if (setPosition || newEvent) { if (eventPos != ListView.INVALID_POSITION) { if (listView != null) { // set event visible in list //int last = listView.getLastVisiblePosition(); //int first = listView.getFirstVisiblePosition(); //if ((eventPos <= first) || (eventPos >= last)) { // listView.setSelection(eventPos); RecyclerView.LayoutManager lm = listView.getLayoutManager(); if (lm != null) lm.scrollToPosition(eventPos); } } } boolean startTargetHelps = getArguments() != null && getArguments().getBoolean(START_TARGET_HELPS_ARGUMENT, false); if (startTargetHelps) showAdapterTargetHelps(); } } /* public int getFilterType() { return filterType; } */ private void changeListOrder(int orderType) { if (isAsyncTaskPendingOrRunning()) { this.asyncTaskContext.get().cancel(true); } this.orderType = orderType; synchronized (activityDataWrapper.eventList) { if (!activityDataWrapper.eventListFilled) { LoadEventListAsyncTask asyncTask = new LoadEventListAsyncTask(this, filterType, orderType); this.asyncTaskContext = new WeakReference<>(asyncTask); asyncTask.execute(); } else { sortList(activityDataWrapper.eventList, orderType, activityDataWrapper); listView.setAdapter(eventListAdapter); synchronized (activityDataWrapper.profileList) { Profile profile = activityDataWrapper.getActivatedProfileFromDB(true, ApplicationPreferences.applicationEditorPrefIndicator(activityDataWrapper.context)); updateHeader(profile); } eventListAdapter.notifyDataSetChanged(); } } /*if (eventListAdapter != null) { listView.getRecycledViewPool().clear(); synchronized (activityDataWrapper.eventList) { sortList(activityDataWrapper.eventList, orderType, activityDataWrapper); } eventListAdapter.notifyDataSetChanged(); }*/ } private static void sortList(List<Event> eventList, int orderType, DataWrapper _dataWrapper) { final DataWrapper dataWrapper = _dataWrapper; class EventNameComparator implements Comparator<Event> { public int compare(Event lhs, Event rhs) { if (GlobalGUIRoutines.collator != null) return GlobalGUIRoutines.collator.compare(lhs._name, rhs._name); else return 0; } } class StartOrderComparator implements Comparator<Event> { public int compare(Event lhs, Event rhs) { return lhs._startOrder - rhs._startOrder; } } class ProfileNameComparator implements Comparator<Event> { public int compare(Event lhs, Event rhs) { if (GlobalGUIRoutines.collator != null) { Profile profileLhs = dataWrapper.getProfileById(lhs._fkProfileStart, false, false,false); Profile profileRhs = dataWrapper.getProfileById(rhs._fkProfileStart, false, false, false); String nameLhs = ""; if (profileLhs != null) nameLhs = profileLhs._name; String nameRhs = ""; if (profileRhs != null) nameRhs = profileRhs._name; return GlobalGUIRoutines.collator.compare(nameLhs, nameRhs); } else return 0; } } class PriorityComparator implements Comparator<Event> { public int compare(Event lhs, Event rhs) { //int res = lhs._priority - rhs._priority; return rhs._priority - lhs._priority; } } switch (orderType) { case ORDER_TYPE_EVENT_NAME: Collections.sort(eventList, new EventNameComparator()); break; case ORDER_TYPE_START_ORDER: Collections.sort(eventList, new StartOrderComparator()); break; case ORDER_TYPE_PROFILE_NAME: Collections.sort(eventList, new ProfileNameComparator()); break; case ORDER_TYPE_PRIORITY: if (ApplicationPreferences.applicationEventUsePriority(_dataWrapper.context)) Collections.sort(eventList, new PriorityComparator()); else Collections.sort(eventList, new StartOrderComparator()); break; } } void refreshGUI(boolean refresh, boolean refreshIcons, boolean setPosition, long eventId) { if (activityDataWrapper == null) return; Profile profileFromDB = DatabaseHandler.getInstance(activityDataWrapper.context).getActivatedProfile(); String pName; if (profileFromDB != null) pName = DataWrapper.getProfileNameWithManualIndicatorAsString(profileFromDB, true, "", true, false, activityDataWrapper, false, activityDataWrapper.context); else pName = getResources().getString(R.string.profiles_header_profile_name_no_activated); if (!refresh) { String pNameWidget = PPApplication.getActivityProfileName(activityDataWrapper.context, 3); if (pName.equals(pNameWidget)) { PPApplication.logE("EditorEventListFragment.refreshGUI", "activated profile NOT changed"); return; } } PPApplication.setActivityProfileName(activityDataWrapper.context, 3, pName); synchronized (activityDataWrapper.eventList) { if (!activityDataWrapper.eventListFilled) return; //noinspection ForLoopReplaceableByForEach for (Iterator<Event> it = activityDataWrapper.eventList.iterator(); it.hasNext(); ) { Event event = it.next(); int status = DatabaseHandler.getInstance(activityDataWrapper.context).getEventStatus(event); event.setStatus(status); event._isInDelayStart = DatabaseHandler.getInstance(activityDataWrapper.context).getEventInDelayStart(event); event._isInDelayEnd = DatabaseHandler.getInstance(activityDataWrapper.context).getEventInDelayEnd(event); DatabaseHandler.getInstance(activityDataWrapper.context).setEventCalendarTimes(event); DatabaseHandler.getInstance(activityDataWrapper.context).getSMSStartTime(event); //DatabaseHandler.getInstance(activityDataWrapper.context).getNotificationStartTime(event); DatabaseHandler.getInstance(activityDataWrapper.context).getNFCStartTime(event); DatabaseHandler.getInstance(activityDataWrapper.context).getCallStartTime(event); DatabaseHandler.getInstance(activityDataWrapper.context).getAlarmClockStartTime(event); } } if (profileFromDB != null) { PPApplication.logE("EditorEventListFragment.refreshGUI", "profile activated"); Profile profileFromDataWrapper = activityDataWrapper.getProfileById(profileFromDB._id, true, ApplicationPreferences.applicationEditorPrefIndicator(activityDataWrapper.context), false); if (profileFromDataWrapper != null) profileFromDataWrapper._checked = true; updateHeader(profileFromDataWrapper); } else { PPApplication.logE("EditorEventListFragment.refreshGUI", "profile not activated"); updateHeader(null); } updateListView(null, false, refreshIcons, setPosition, eventId); } void removeAdapter() { if (listView != null) listView.setAdapter(null); } void showTargetHelps() { /*if (Build.VERSION.SDK_INT <= 19) // TapTarget.forToolbarMenuItem FC :-( // Toolbar.findViewById() returns null return;*/ if (getActivity() == null) return; if (((EditorProfilesActivity)getActivity()).targetHelpsSequenceStarted) return; ApplicationPreferences.getSharedPreferences(getActivity()); boolean showTargetHelps = ApplicationPreferences.preferences.getBoolean(PREF_START_TARGET_HELPS, true); boolean showTargetHelpsDefaultProfile = ApplicationPreferences.preferences.getBoolean(EditorProfilesActivity.PREF_START_TARGET_HELPS_DEFAULT_PROFILE, true); if (showTargetHelps || showTargetHelpsDefaultProfile || ApplicationPreferences.preferences.getBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS, true) || ApplicationPreferences.preferences.getBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS_ORDER, true)) { //Log.d("EditorEventListFragment.showTargetHelps", "PREF_START_TARGET_HELPS_ORDER=true"); if (showTargetHelps || showTargetHelpsDefaultProfile) { //Log.d("EditorEventListFragment.showTargetHelps", "PREF_START_TARGET_HELPS=true"); SharedPreferences.Editor editor = ApplicationPreferences.preferences.edit(); editor.putBoolean(PREF_START_TARGET_HELPS, false); editor.putBoolean(EditorProfilesActivity.PREF_START_TARGET_HELPS_DEFAULT_PROFILE, false); editor.apply(); String appTheme = ApplicationPreferences.applicationTheme(getActivity(), true); int outerCircleColor = R.color.tabTargetHelpOuterCircleColor; // if (appTheme.equals("dark")) // outerCircleColor = R.color.tabTargetHelpOuterCircleColor_dark; int targetCircleColor = R.color.tabTargetHelpTargetCircleColor; // if (appTheme.equals("dark")) // targetCircleColor = R.color.tabTargetHelpTargetCircleColor_dark; int textColor = R.color.tabTargetHelpTextColor; // if (appTheme.equals("dark")) // textColor = R.color.tabTargetHelpTextColor_dark; boolean tintTarget = !appTheme.equals("white"); final TapTargetSequence sequence = new TapTargetSequence(getActivity()); List<TapTarget> targets = new ArrayList<>(); int id = 1; if (showTargetHelps) { try { targets.add( TapTarget.forToolbarMenuItem(bottomToolbar, R.id.menu_add_event, getString(R.string.editor_activity_targetHelps_newEventButton_title), getString(R.string.editor_activity_targetHelps_newEventButton_description)) .outerCircleColor(outerCircleColor) .targetCircleColor(targetCircleColor) .textColor(textColor) .tintTarget(tintTarget) .drawShadow(true) .id(id) ); ++id; } catch (Exception ignored) { } // not in action bar? try { targets.add( TapTarget.forToolbarMenuItem(bottomToolbar, R.id.menu_delete_all_events, getString(R.string.editor_activity_targetHelps_deleteAllEventsButton_title), getString(R.string.editor_activity_targetHelps_deleteAllEventsButton_description)) .outerCircleColor(outerCircleColor) .targetCircleColor(targetCircleColor) .textColor(textColor) .tintTarget(tintTarget) .drawShadow(true) .id(id) ); ++id; } catch (Exception ignored) { } // not in action bar? } if (showTargetHelpsDefaultProfile) { try { targets.add( TapTarget.forToolbarMenuItem(bottomToolbar, R.id.menu_default_profile, getString(R.string.editor_activity_targetHelps_backgroundProfileButton_title), getString(R.string.editor_activity_targetHelps_backgroundProfileButton_description)) .outerCircleColor(outerCircleColor) .targetCircleColor(targetCircleColor) .textColor(textColor) .tintTarget(tintTarget) .drawShadow(true) .id(id) ); ++id; } catch (Exception ignored) { } // not in action bar? } sequence.targets(targets) .listener(new TapTargetSequence.Listener() { // This listener will tell us when interesting(tm) events happen in regards // to the sequence @Override public void onSequenceFinish() { targetHelpsSequenceStarted = false; showAdapterTargetHelps(); } @Override public void onSequenceStep(TapTarget lastTarget, boolean targetClicked) { //Log.d("TapTargetView", "Clicked on " + lastTarget.id()); } @Override public void onSequenceCanceled(TapTarget lastTarget) { targetHelpsSequenceStarted = false; SharedPreferences.Editor editor = ApplicationPreferences.preferences.edit(); editor.putBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS, false); if (filterType == FILTER_TYPE_START_ORDER) editor.putBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS_ORDER, false); editor.apply(); } }); sequence.continueOnCancel(true) .considerOuterCircleCanceled(true); targetHelpsSequenceStarted = true; sequence.start(); } else { //Log.d("EditorEventListFragment.showTargetHelps", "PREF_START_TARGET_HELPS=false"); final Handler handler = new Handler(getActivity().getMainLooper()); handler.postDelayed(new Runnable() { @Override public void run() { showAdapterTargetHelps(); } }, 500); } } } private void showAdapterTargetHelps() { /*if (Build.VERSION.SDK_INT <= 19) // TapTarget.forToolbarMenuItem FC :-( // Toolbar.findViewById() returns null return;*/ if (getActivity() == null) return; View itemView; if (listView.getChildCount() > 1) itemView = listView.getChildAt(1); else itemView = listView.getChildAt(0); if ((eventListAdapter != null) && (itemView != null)) eventListAdapter.showTargetHelps(getActivity(), this, itemView); else { targetHelpsSequenceStarted = false; ApplicationPreferences.getSharedPreferences(getActivity()); SharedPreferences.Editor editor = ApplicationPreferences.preferences.edit(); editor.putBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS, false); if (filterType == FILTER_TYPE_START_ORDER) editor.putBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS_ORDER, false); editor.apply(); } } private void changeEventOrder(int position/*, boolean orientationChange*/) { orderSelectedItem = position; if (filterType != EditorEventListFragment.FILTER_TYPE_START_ORDER) { // save into shared preferences ApplicationPreferences.getSharedPreferences(getActivity()); SharedPreferences.Editor editor = ApplicationPreferences.preferences.edit(); editor.putInt(SP_EDITOR_ORDER_SELECTED_ITEM, orderSelectedItem); editor.apply(); } int _eventsOrderType = getEventsOrderType(); //setStatusBarTitle(); //PPApplication.logE("EditorProfilesActivity.changeEventOrder", "filterSelectedItem="+filterSelectedItem); PPApplication.logE("EditorProfilesActivity.changeEventOrder", "orderSelectedItem="+orderSelectedItem); PPApplication.logE("EditorProfilesActivity.changeEventOrder", "_eventsOrderType="+_eventsOrderType); changeListOrder(_eventsOrderType); orderSpinner.setSelection(orderSelectedItem); /* // Close drawer if (ApplicationPreferences.applicationEditorAutoCloseDrawer(getApplicationContext()) && (!orientationChange)) drawerLayout.closeDrawer(drawerRoot); */ } private int getEventsOrderType() { int _eventsOrderType; if (filterType == EditorEventListFragment.FILTER_TYPE_START_ORDER) { _eventsOrderType = EditorEventListFragment.ORDER_TYPE_START_ORDER; } else { _eventsOrderType = EditorEventListFragment.ORDER_TYPE_START_ORDER; switch (orderSelectedItem) { /*case 0: _eventsOrderType = EditorEventListFragment.ORDER_TYPE_START_ORDER; break;*/ case 1: _eventsOrderType = EditorEventListFragment.ORDER_TYPE_EVENT_NAME; break; case 2: _eventsOrderType = EditorEventListFragment.ORDER_TYPE_PROFILE_NAME; break; case 3: _eventsOrderType = EditorEventListFragment.ORDER_TYPE_PRIORITY; break; } } return _eventsOrderType; } class HighlightedSpinnerAdapter extends ArrayAdapter<String> { private int mSelectedIndex = -1; private final Context context; @SuppressWarnings("SameParameterValue") HighlightedSpinnerAdapter(Context context, int textViewResourceId, String[] objects) { super(context, textViewResourceId, objects); this.context = context; } @Override public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent){ View itemView = super.getDropDownView(position, convertView, parent); TextView itemText = itemView.findViewById(android.R.id.text1); if (itemText != null) { if (position == mSelectedIndex) { itemText.setTextColor(GlobalGUIRoutines.getThemeAccentColor(context)); } else { itemText.setTextColor(GlobalGUIRoutines.getThemeEditorSpinnerDropDownTextColor(context)); } } return itemView; } void setSelection(int position) { mSelectedIndex = position; notifyDataSetChanged(); } } }
package sk.henrichg.phoneprofilesplus; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import java.util.Calendar; public class PackageReplacedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler()); PPApplication.logE(" //int intentUid = intent.getExtras().getInt("android.intent.extra.UID"); //int myUid = android.os.Process.myUid(); //if (intentUid == myUid) // start delayed bootup broadcast PPApplication.startedOnBoot = true; AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Intent delayedBootUpIntent = new Intent(context, DelayedBootUpReceiver.class); PendingIntent alarmIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, delayedBootUpIntent, PendingIntent.FLAG_CANCEL_CURRENT); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND, 10); alarmMgr.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent); PPApplication.setShowRequestAccessNotificationPolicyPermission(context.getApplicationContext(), true); PPApplication.setShowRequestWriteSettingsPermission(context.getApplicationContext(), true); PPApplication.setShowEnableLocationNotification(context.getApplicationContext(), true); PPApplication.setScreenUnlocked(context.getApplicationContext(), true); int oldVersionCode = PPApplication.getSavedVersionCode(context.getApplicationContext()); PPApplication.logE("@@@ PackageReplacedReceiver.onReceive", "oldVersionCode="+oldVersionCode); int actualVersionCode; try { PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); actualVersionCode = pinfo.versionCode; PPApplication.logE("@@@ PackageReplacedReceiver.onReceive", "actualVersionCode=" + actualVersionCode); if (oldVersionCode < actualVersionCode) { if (actualVersionCode <= 2322) { // for old packages use Priority in events SharedPreferences preferences = context.getSharedPreferences(PPApplication.APPLICATION_PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); PPApplication.logE("@@@ PackageReplacedReceiver.onReceive", "applicationEventUsePriority=true"); editor.putBoolean(PPApplication.PREF_APPLICATION_EVENT_USE_PRIORITY, true); editor.commit(); PPApplication.loadPreferences(context); } if (actualVersionCode <= 2400) { PPApplication.logE("@@@ PackageReplacedReceiver.onReceive", "donation alarm restart"); PPApplication.setDaysAfterFirstStart(context, 0); AboutApplicationBroadcastReceiver.setAlarm(context); } if (actualVersionCode <= 2500) { // for old packages hide profile notification from status bar if notification is disabled SharedPreferences preferences = context.getSharedPreferences(PPApplication.APPLICATION_PREFS_NAME, Context.MODE_PRIVATE); if (!preferences.getBoolean(PPApplication.PREF_NOTIFICATION_STATUS_BAR, true)) { SharedPreferences.Editor editor = preferences.edit(); PPApplication.logE("@@@ PackageReplacedReceiver.onReceive", "notificationShowInStatusBar=false"); editor.putBoolean(PPApplication.PREF_NOTIFICATION_SHOW_IN_STATUS_BAR, false); editor.commit(); PPApplication.loadPreferences(context); } } if (actualVersionCode <= 2700) { SharedPreferences preferences = context.getSharedPreferences(PPApplication.APPLICATION_PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean(PPApplication.PREF_APPLICATION_EDITOR_SAVE_EDITOR_STATE, true); editor.putBoolean(ActivateProfileActivity.PREF_START_TARGET_HELPS, false); editor.putBoolean(ActivateProfileListFragment.PREF_START_TARGET_HELPS, false); editor.putBoolean(ActivateProfileListAdapter.PREF_START_TARGET_HELPS, false); editor.putBoolean(EditorProfilesActivity.PREF_START_TARGET_HELPS, false); editor.putBoolean(EditorProfileListFragment.PREF_START_TARGET_HELPS, false); editor.putBoolean(EditorProfileListAdapter.PREF_START_TARGET_HELPS, false); editor.putBoolean(EditorProfileListAdapter.PREF_START_TARGET_HELPS_ORDER, false); editor.putBoolean(EditorEventListFragment.PREF_START_TARGET_HELPS, false); editor.putBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS, false); editor.putBoolean(EditorEventListAdapter.PREF_START_TARGET_HELPS_ORDER, false); editor.putBoolean(ProfilePreferencesActivity.PREF_START_TARGET_HELPS, false); editor.putBoolean(EventPreferencesActivity.PREF_START_TARGET_HELPS, false); editor.commit(); } } } catch (PackageManager.NameNotFoundException e) { //e.printStackTrace(); } PPApplication.logE("PackageReplacedReceiver.onReceive","PhoneProfilesService.instance="+PhoneProfilesService.instance); if (PPApplication.getApplicationStarted(context, false)) { PPApplication.logE("@@@ PackageReplacedReceiver.onReceive", "start PhoneProfilesService"); if (PhoneProfilesService.instance != null) { // stop PhoneProfilesService context.stopService(new Intent(context.getApplicationContext(), PhoneProfilesService.class)); PPApplication.sleep(2000); } // must by false for avoiding starts/pause events before restart events PPApplication.setApplicationStarted(context, false); // start PhoneProfilesService Intent serviceIntent = new Intent(context.getApplicationContext(), PhoneProfilesService.class); serviceIntent.putExtra(PPApplication.EXTRA_ONLY_START, true); serviceIntent.putExtra(PPApplication.EXTRA_START_ON_BOOT, false); context.startService(serviceIntent); } } }
package org.jkiss.dbeaver.model.impl.jdbc.struct; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.core.CoreMessages; import org.jkiss.dbeaver.model.DBPDataSource; import org.jkiss.dbeaver.model.DBPSaveableObject; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.data.*; import org.jkiss.dbeaver.model.exec.*; import org.jkiss.dbeaver.model.impl.DBObjectNameCaseTransformer; import org.jkiss.dbeaver.model.impl.jdbc.cache.JDBCStructCache; import org.jkiss.dbeaver.model.impl.struct.AbstractTable; import org.jkiss.dbeaver.model.meta.Property; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSAttributeBase; import org.jkiss.dbeaver.model.struct.DBSDataManipulator; import org.jkiss.dbeaver.model.struct.DBSObjectContainer; import org.jkiss.utils.CommonUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * JDBC abstract table implementation */ public abstract class JDBCTable<DATASOURCE extends DBPDataSource, CONTAINER extends DBSObjectContainer> extends AbstractTable<DATASOURCE, CONTAINER> implements DBSDataManipulator, DBPSaveableObject { static final Log log = LogFactory.getLog(JDBCTable.class); private boolean persisted; protected JDBCTable(CONTAINER container, boolean persisted) { super(container); this.persisted = persisted; } protected JDBCTable(CONTAINER container, String tableName, boolean persisted) { super(container, tableName); this.persisted = persisted; } public abstract JDBCStructCache<CONTAINER, ? extends JDBCTable, ? extends JDBCTableColumn> getCache(); @Property(viewable = true, editable = true, valueTransformer = DBObjectNameCaseTransformer.class, order = 1) @Override public String getName() { return super.getName(); } @Override public boolean isPersisted() { return persisted; } @Override public void setPersisted(boolean persisted) { this.persisted = persisted; } @Override public int getSupportedFeatures() { return DATA_COUNT | DATA_INSERT | DATA_UPDATE | DATA_DELETE | DATA_FILTER; } @Override public DBCStatistics readData(DBCSession session, DBDDataReceiver dataReceiver, DBDDataFilter dataFilter, long firstRow, long maxRows) throws DBCException { DBCStatistics statistics = new DBCStatistics(); boolean hasLimits = firstRow >= 0 && maxRows > 0; DBRProgressMonitor monitor = session.getProgressMonitor(); try { readRequiredMeta(monitor); } catch (DBException e) { log.warn(e); } DBDPseudoAttribute rowIdAttribute = null; if (this instanceof DBDPseudoAttributeContainer) { try { rowIdAttribute = DBDPseudoAttribute.getAttribute( ((DBDPseudoAttributeContainer) this).getPseudoAttributes(), DBDPseudoAttributeType.ROWID); } catch (DBException e) { log.warn("Can't get pseudo attributes for '" + getName() + "'", e); } } String tableAlias = null; StringBuilder query = new StringBuilder(100); if (rowIdAttribute != null) { // If we have pseudo attributes then query gonna be more complex tableAlias = "x"; query.append("SELECT ").append(tableAlias).append(".*"); //$NON-NLS-1$ query.append(",").append(rowIdAttribute.getQueryExpression().replace("$alias", tableAlias)).append(" as ").append(rowIdAttribute.getAlias()); query.append(" FROM ").append(getFullQualifiedName()).append(" ").append(tableAlias); //$NON-NLS-1$ } else { query.append("SELECT * FROM ").append(getFullQualifiedName()); //$NON-NLS-1$ } appendQueryConditions(query, tableAlias, dataFilter); appendQueryOrder(query, tableAlias, dataFilter); monitor.subTask(CoreMessages.model_jdbc_fetch_table_data); DBCStatement dbStat = DBUtils.prepareStatement( session, DBCStatementType.SCRIPT, query.toString(), firstRow, maxRows); try { dbStat.setDataContainer(this); long startTime = System.currentTimeMillis(); boolean executeResult = dbStat.executeStatement(); statistics.setExecuteTime(System.currentTimeMillis() - startTime); if (executeResult) { DBCResultSet dbResult = dbStat.openResultSet(); if (dbResult != null) { try { if (rowIdAttribute != null) { // Annotate last attribute with row id List<DBCAttributeMetaData> metaAttributes = dbResult.getResultSetMetaData().getAttributes(); for (int i = metaAttributes.size(); i > 0; i DBCAttributeMetaData attr = metaAttributes.get(i - 1); if (rowIdAttribute.getAlias().equalsIgnoreCase(attr.getName())) { attr.setPseudoAttribute(rowIdAttribute); break; } } } dataReceiver.fetchStart(session, dbResult); try { startTime = System.currentTimeMillis(); long rowCount = 0; while (dbResult.nextRow()) { if (monitor.isCanceled() || (hasLimits && rowCount >= maxRows)) { // Fetch not more than max rows break; } dataReceiver.fetchRow(session, dbResult); rowCount++; if (rowCount % 100 == 0) { monitor.subTask(rowCount + CoreMessages.model_jdbc__rows_fetched); monitor.worked(100); } } statistics.setFetchTime(System.currentTimeMillis() - startTime); statistics.setRowsFetched(rowCount); } finally { try { dataReceiver.fetchEnd(session); } catch (DBCException e) { log.error("Error while finishing result set fetch", e); //$NON-NLS-1$ } } } finally { dbResult.close(); } } } return statistics; } finally { dbStat.close(); dataReceiver.close(); } } @Override public long countData(DBCSession session, DBDDataFilter dataFilter) throws DBCException { DBRProgressMonitor monitor = session.getProgressMonitor(); StringBuilder query = new StringBuilder("SELECT COUNT(*) FROM "); //$NON-NLS-1$ query.append(getFullQualifiedName()); appendQueryConditions(query, null, dataFilter); monitor.subTask(CoreMessages.model_jdbc_fetch_table_row_count); DBCStatement dbStat = session.prepareStatement( DBCStatementType.QUERY, query.toString(), false, false, false); try { dbStat.setDataContainer(this); if (!dbStat.executeStatement()) { return 0; } DBCResultSet dbResult = dbStat.openResultSet(); if (dbResult == null) { return 0; } try { if (dbResult.nextRow()) { Object result = dbResult.getColumnValue(1); if (result == null) { return 0; } else if (result instanceof Number) { return ((Number) result).longValue(); } else { return Long.parseLong(result.toString()); } } else { return 0; } } finally { dbResult.close(); } } finally { dbStat.close(); } } @Override public ExecuteBatch insertData(DBCSession session, DBSAttributeBase[] attributes, DBDDataReceiver keysReceiver) throws DBCException { readRequiredMeta(session.getProgressMonitor()); // Make query StringBuilder query = new StringBuilder(200); query.append("INSERT INTO ").append(getFullQualifiedName()).append(" ("); //$NON-NLS-1$ //$NON-NLS-2$ boolean hasKey = false; for (int i = 0; i < attributes.length; i++) { DBSAttributeBase attribute = attributes[i]; if (attribute.isPseudoAttribute() || attribute.isSequence()) { continue; } if (hasKey) query.append(","); //$NON-NLS-1$ hasKey = true; query.append(DBUtils.getQuotedIdentifier(getDataSource(), attribute.getName())); } query.append(") VALUES ("); //$NON-NLS-1$ hasKey = false; for (int i = 0; i < attributes.length; i++) { if (attributes[i].isPseudoAttribute() || attributes[i].isSequence()) { continue; } if (hasKey) query.append(","); //$NON-NLS-1$ hasKey = true; query.append("?"); //$NON-NLS-1$ } query.append(")"); //$NON-NLS-1$ // Execute DBCStatement dbStat = session.prepareStatement(DBCStatementType.QUERY, query.toString(), false, false, keysReceiver != null); dbStat.setDataContainer(this); return new BatchImpl(dbStat, attributes, keysReceiver, true); } @Override public ExecuteBatch updateData( DBCSession session, DBSAttributeBase[] updateAttributes, DBSAttributeBase[] keyAttributes, DBDDataReceiver keysReceiver) throws DBCException { readRequiredMeta(session.getProgressMonitor()); // Make query StringBuilder query = new StringBuilder(); query.append("UPDATE ").append(getFullQualifiedName()).append(" SET "); //$NON-NLS-1$ //$NON-NLS-2$ boolean hasKey = false; for (DBSAttributeBase attribute : updateAttributes) { if (hasKey) query.append(","); //$NON-NLS-1$ hasKey = true; query.append(DBUtils.getQuotedIdentifier(getDataSource(), attribute.getName())).append("=?"); //$NON-NLS-1$ } query.append(" WHERE "); //$NON-NLS-1$ hasKey = false; for (DBSAttributeBase attribute : keyAttributes) { if (hasKey) query.append(" AND "); //$NON-NLS-1$ hasKey = true; String attrName = getAttributeName(attribute); query.append(attrName).append("=?"); //$NON-NLS-1$ } // Execute DBCStatement dbStat = session.prepareStatement(DBCStatementType.QUERY, query.toString(), false, false, keysReceiver != null); dbStat.setDataContainer(this); DBSAttributeBase[] attributes = CommonUtils.concatArrays(updateAttributes, keyAttributes); return new BatchImpl(dbStat, attributes, keysReceiver, false); } @Override public ExecuteBatch deleteData(DBCSession session, DBSAttributeBase[] keyAttributes) throws DBCException { readRequiredMeta(session.getProgressMonitor()); // Make query StringBuilder query = new StringBuilder(); query.append("DELETE FROM ").append(getFullQualifiedName()).append(" WHERE "); //$NON-NLS-1$ //$NON-NLS-2$ boolean hasKey = false; for (DBSAttributeBase attribute : keyAttributes) { if (hasKey) query.append(" AND "); //$NON-NLS-1$ hasKey = true; query.append(getAttributeName(attribute)).append("=?"); //$NON-NLS-1$ } // Execute DBCStatement dbStat = session.prepareStatement(DBCStatementType.QUERY, query.toString(), false, false, false); dbStat.setDataContainer(this); return new BatchImpl(dbStat, keyAttributes, null, false); } private String getAttributeName(DBSAttributeBase attribute) { // Do not quote pseudo attribute name return attribute.isPseudoAttribute() ? attribute.getName() : DBUtils.getQuotedIdentifier(getDataSource(), attribute.getName()); } private void appendQueryConditions(StringBuilder query, String tableAlias, DBDDataFilter dataFilter) { if (dataFilter != null && dataFilter.hasConditions()) { query.append(" WHERE "); //$NON-NLS-1$ dataFilter.appendConditionString(getDataSource(), tableAlias, query); } } private void appendQueryOrder(StringBuilder query, String tableAlias, DBDDataFilter dataFilter) { if (dataFilter != null) { // Construct ORDER BY if (dataFilter.hasOrdering()) { query.append(" ORDER BY "); //$NON-NLS-1$ dataFilter.appendOrderString(getDataSource(), tableAlias, query); } } } private void readKeys(DBCSession session, DBCStatement dbStat, DBDDataReceiver keysReceiver) throws DBCException { DBCResultSet dbResult; try { dbResult = dbStat.openGeneratedKeysResultSet(); } catch (Throwable e) { log.debug("Error obtaining generated keys", e); //$NON-NLS-1$ return; } if (dbResult == null) { return; } try { keysReceiver.fetchStart(session, dbResult); try { while (dbResult.nextRow()) { keysReceiver.fetchRow(session, dbResult); } } finally { keysReceiver.fetchEnd(session); } } finally { dbResult.close(); keysReceiver.close(); } } /** * Reads and caches metadata which is required for data requests * @param monitor progress monitor * @throws DBException on error */ private void readRequiredMeta(DBRProgressMonitor monitor) throws DBCException { try { getAttributes(monitor); } catch (DBException e) { throw new DBCException("Could not cache table columns", e); } } private class BatchImpl implements ExecuteBatch { private DBCStatement statement; private final DBSAttributeBase[] attributes; private final List<Object[]> values = new ArrayList<Object[]>(); private final DBDDataReceiver keysReceiver; private final boolean skipSequences; private BatchImpl(DBCStatement statement, DBSAttributeBase[] attributes, DBDDataReceiver keysReceiver, boolean skipSequences) { this.statement = statement; this.attributes = attributes; this.keysReceiver = keysReceiver; this.skipSequences = skipSequences; } @Override public void add(Object[] attributeValues) throws DBCException { if (!CommonUtils.isEmpty(attributes) && CommonUtils.isEmpty(attributeValues)) { throw new DBCException("Bad attribute values: " + Arrays.toString(attributeValues)); } values.add(attributeValues); } @Override public DBCStatistics execute() throws DBCException { if (statement == null) { throw new DBCException("Execute batch closed"); } DBDValueHandler[] handlers = new DBDValueHandler[attributes.length]; for (int i = 0; i < attributes.length; i++) { handlers[i] = DBUtils.findValueHandler(statement.getContext(), attributes[i]); } boolean useBatch = statement.getContext().getDataSource().getInfo().supportsBatchUpdates(); if (values.size() <= 1) { useBatch = false; } DBCStatistics statistics = new DBCStatistics(); for (Object[] rowValues : values) { int paramIndex = 0; for (int k = 0; k < handlers.length; k++) { DBDValueHandler handler = handlers[k]; if (skipSequences && (attributes[k].isPseudoAttribute() || attributes[k].isSequence())) { continue; } handler.bindValueObject(statement.getContext(), statement, attributes[k], paramIndex++, rowValues[k]); } if (useBatch) { statement.addToBatch(); } else { // Execute each row separately long startTime = System.currentTimeMillis(); statement.executeStatement(); statistics.addExecuteTime(System.currentTimeMillis() - startTime); long rowCount = statement.getUpdateRowCount(); if (rowCount > 0) { statistics.addRowsUpdated(rowCount); } // Read keys if (keysReceiver != null) { readKeys(statement.getContext(), statement, keysReceiver); } } } values.clear(); if (useBatch) { // Process batch long startTime = System.currentTimeMillis(); int[] updatedRows = statement.executeStatementBatch(); statistics.addExecuteTime(System.currentTimeMillis() - startTime); if (!CommonUtils.isEmpty(updatedRows)) { for (int rows : updatedRows) { statistics.addRowsUpdated(rows); } } } return statistics; } @Override public void close() { statement.close(); statement = null; } } }
package org.xcolab.portlets.members; import java.text.ParseException; import java.util.Date; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.search.Document; import com.liferay.portlet.social.service.SocialActivityLocalServiceUtil; public class MemberListItemBean { private MemberCategory category; private String realName; private int activityCount; private Date joinDate; private Long userId; public MemberListItemBean(Document userDoc) throws SystemException, NumberFormatException, PortalException, ParseException { userId = Long.parseLong(userDoc.get("userId")); activityCount = SocialActivityLocalServiceUtil.getUserActivitiesCount(userId); realName = userDoc.get("realName"); String screenName = userDoc.get("screenName"); String firstName = userDoc.get("firstName"); String firstPart = realName.substring(0, realName.length() / 2).trim(); String secondPart = realName.substring(realName.length() / 2).trim(); if (firstPart.equals(secondPart)) { realName = firstPart; } joinDate = userDoc.getDate("joinDate"); if (userDoc.getValues("memberCategory").length > 0) { try { String[] categoriesStr = userDoc.getValues("memberCategory"); MemberCategory currentCat = MemberCategory.MEMBER; category = MemberCategory.MEMBER; for (String categoryStr: userDoc.getValues("memberCategory")) { currentCat = MemberCategory.valueOf(categoryStr); if (currentCat.ordinal() > category.ordinal()) { category = currentCat; } } if (category == MemberCategory.MODERATOR) category = MemberCategory.STAFF; } catch (java.lang.IllegalArgumentException e) { // ignore } } } public MemberListItemBean(Document userDoc, MemberCategory categoryFilter) throws NumberFormatException, SystemException, PortalException, ParseException { this(userDoc); category = categoryFilter; } public String getRealName() { return realName; } public int getActivityCount() throws SystemException { return activityCount; } public MemberCategory getCategory() { return category; } public Date getMemberSince() { return joinDate; } public Comparable getColumnVal(MembersListColumns column) { switch (column) { case ACTIVITY: return activityCount; case MEMBER_CATEGORY: return category; case MEMBER_SINCE: return joinDate; default: return realName; } } public Long getUserId() { return userId; } }
package org.micromanager.api; /** * The list of tags used by the Micro-manager */ public class MMTags { /** * Meta-tags referring to main sections of the metadata */ public class Root { public static final String SUMMARY = "Summary"; // key for the Summary metadata } /** * Summary tags */ public class Summary { public static final String PREFIX = "Prefix"; // Acquisition name public static final String WIDTH = "Width"; // image width public static final String HEIGHT = "Height"; // image height public static final String FRAMES = "Frames"; // number of frames public static final String CHANNELS = "Channels"; // number of channels public static final String POSITIONS = "Positions"; // number of positions public static final String PIXSIZE = "PixelSize_um"; public static final String PIX_TYPE = "PixelType"; public static final String IJ_TYPE = "IJType"; public static final String PIXEL_ASPECT = "PixelAspect"; public static final String SOURCE = "Source"; public static final String SLICES = "Slices"; public static final String COLORS = "ChColors"; public static final String CHANNEL_MINS = "ChMins"; public static final String CHANNEL_MAXES = "ChMaxes"; public static final String NAMES = "ChNames"; public static final String BIT_DEPTH = "BitDepth"; public static final String OBJECTIVE_LABEL = "Objective-Label"; public static final String ELAPSED_TIME = "ElapsedTime-ms"; public static final String SLICES_FIRST = "SlicesFirst"; public static final String TIME_FIRST = "TimeFirst"; } public class Image { public static final String WIDTH = "Width"; // image width public static final String HEIGHT = "Height"; // image height public static final String CHANNEL = "Channel"; public static final String FRAME = "Frame"; public static final String SLICE = "Slice"; public static final String CHANNEL_INDEX = "ChannelIndex"; public static final String SLICE_INDEX = "SliceIndex"; public static final String FRAME_INDEX = "FrameIndex"; public static final String CHANNEL_NAME = "Channel"; public static final String POS_NAME = "PositionName"; public static final String POS_INDEX = "PositionIndex"; public static final String XUM = "XPositionUm"; public static final String YUM = "YPositionUm"; public static final String ZUM = "ZPositionUm"; public static final String IJ_TYPE = "IJType"; public static final String TIME = "Time"; public static final String PIX_TYPE = "PixelType"; } public class Values { public static final String PIX_TYPE_GRAY_16 = "GRAY16"; public static final String PIX_TYPE_GRAY_8 = "GRAY8"; } }
//Standard Java classes import java.util.*; import java.io.*; import java.lang.ref.*; import java.net.URI; // Imported TraX classes import javax.xml.transform.*; import javax.xml.transform.stream.*; import org.xml.sax.*; import org.xml.sax.helpers.*; //StarOffice Interfaces and UNO import com.sun.star.uno.*; import com.sun.star.lang.*; import com.sun.star.comp.loader.FactoryHelper; import com.sun.star.registry.XRegistryKey; import com.sun.star.io.*; import com.sun.star.ucb.*; import com.sun.star.beans.*; //Uno to java Adaptor import com.sun.star.lib.uno.adapter.*; /** This outer class provides an inner class to implement the service * description, a method to instantiate the * component on demand (__getServiceFactory()), and a method to give * information about the component (__writeRegistryServiceInfo()). */ public class XSLTransformer implements XTypeProvider, XServiceName, XServiceInfo, XActiveDataSink, XActiveDataSource, XActiveDataControl, XInitialization, URIResolver { /** * This component provides java based XSL transformations * A SAX based interface is not feasible when crossing language bordes * since too much time would be wasted by bridging the events between environments * example: 190 pages document, 82000 events 8seconds transform 40(!) sec. bridging * */ private XInputStream xistream; private XOutputStream xostream; private BufferedOutputStream ostream; // private static HashMap templatecache; private static final int STREAM_BUFFER_SIZE = 4000; private static final String STATSPROP = "XSLTransformer.statsfile"; private static PrintStream statsp; private String stylesheeturl; private String targeturl; private String targetbaseurl; private String sourceurl; private String sourcebaseurl; private String pubtype = new String(); private String systype = new String(); // processing thread private Thread t; // listeners private Vector listeners = new Vector(); private XMultiServiceFactory svcfactory; // cache for transformations by stylesheet private static Hashtable transformers = new Hashtable(); // struct for cached stylesheets private static class Transformation { public Transformer transformer; public long lastmod; } // Resolve URIs to an empty source public Source resolve(String href, String base) { return new StreamSource(new StringReader("")); } public XSLTransformer(XMultiServiceFactory msf) { svcfactory = msf; } public void initialize(Object[] values) throws com.sun.star.uno.Exception { NamedValue nv = null; for (int i=0; i<values.length; i++) { nv = (NamedValue)AnyConverter.toObject(new Type(NamedValue.class), values[i]); if (nv.Name.equals("StylesheetURL")) stylesheeturl = (String)AnyConverter.toObject( new Type(String.class), nv.Value); else if (nv.Name.equals("SourceURL")) sourceurl = (String)AnyConverter.toObject( new Type(String.class), nv.Value); else if (nv.Name.equals("TargetURL")) targeturl = (String)AnyConverter.toObject( new Type(String.class), nv.Value); else if (nv.Name.equals("SourceBaseURL")) sourcebaseurl = (String)AnyConverter.toObject( new Type(String.class), nv.Value); else if (nv.Name.equals("TargetBaseURL")) targetbaseurl = (String)AnyConverter.toObject( new Type(String.class), nv.Value); else if (nv.Name.equals("SystemType")) systype = (String)AnyConverter.toObject( new Type(String.class), nv.Value); else if (nv.Name.equals("PublicType")) pubtype = (String)AnyConverter.toObject( new Type(String.class), nv.Value); } // some configurable debugging String statsfilepath = null; if ((statsfilepath = System.getProperty(STATSPROP)) != null) { try { File statsfile = new File(statsfilepath); statsp = new PrintStream(new FileOutputStream(statsfile.getPath(), false)); } catch (java.lang.Exception e) { System.err.println("XSLTransformer: could not open statsfile'"+statsfilepath+"'"); System.err.println(" "+e.getClass().getName()+": "+e.getMessage()); System.err.println(" output disabled"); } } } public void setInputStream(XInputStream aStream) { xistream = aStream; } public com.sun.star.io.XInputStream getInputStream() { return xistream; } public void setOutputStream(XOutputStream aStream) { xostream = aStream; ostream = new BufferedOutputStream( new XOutputStreamToOutputStreamAdapter(xostream), STREAM_BUFFER_SIZE); } public com.sun.star.io.XOutputStream getOutputStream() { return xostream; } public void addListener(XStreamListener aListener) { if (aListener != null && !listeners.contains(aListener)) { listeners.add(aListener); } } public void removeListener(XStreamListener aListener) { if (aListener != null ) { listeners.removeElement(aListener); } } public void start() { // notify listeners t = new Thread(){ public void run() { try { if (statsp != null) statsp.println("starting transformation..."); for (Enumeration e = listeners.elements(); e.hasMoreElements();) { XStreamListener l = (XStreamListener)e.nextElement(); l.started(); } // buffer input and modify doctype declaration // remove any dtd references but keep localy defined // entities // ByteArrayOutputStream bufstream = new ByteArrayOutputStream(); // File buffile = File.createTempFile("xsltfilter",".tmp"); // buffile.deleteOnExit(); // OutputStream bufstream = new FileOutputStream(buffile); // final int bsize = 4000; // int rbytes = 0; // byte[][] byteBuffer = new byte[1][bsize]; XSeekable xseek = (XSeekable)UnoRuntime.queryInterface(XSeekable.class, xistream); if (xseek != null) { xseek.seek(0); } InputStream xmlinput = new BufferedInputStream( new XInputStreamToInputStreamAdapter(xistream)); StreamSource xmlsource = new StreamSource(xmlinput); BufferedOutputStream output = new BufferedOutputStream( new XOutputStreamToOutputStreamAdapter(xostream)); StreamResult xmlresult = new StreamResult(output); // in order to help performance and to remedy a a possible memory // leak in xalan, where it seems, that Transformer instances cannot // be reclaimed though they are no longer referenced here, we use // a cache of weak references to transformers created for specific // style sheet URLs see also #i48384# Transformer transformer = null; Transformation transformation = null; File stylefile = new File(new URI(stylesheeturl)); synchronized(transformers) { java.lang.ref.WeakReference ref = null; // try to get the transformer reference from the cache if ((ref = (java.lang.ref.WeakReference)transformers.get(stylesheeturl)) == null || (transformation = ((Transformation)ref.get())) == null || ((Transformation)ref.get()).lastmod < stylefile.lastModified() ) { // we cannot find a valid reference for this stylesheet // or the stylsheet was updated if (ref != null) { transformers.remove(stylesheeturl); } // create new transformer for this stylesheet TransformerFactory tfactory = TransformerFactory.newInstance(); transformer = tfactory.newTransformer(new StreamSource(stylefile)); transformer.setOutputProperty("encoding", "UTF-8"); transformer.setURIResolver(XSLTransformer.this); // store the transformation into the cache transformation = new Transformation(); transformation.lastmod = stylefile.lastModified(); transformation.transformer = transformer; ref = new java.lang.ref.WeakReference(transformation); transformers.put(stylesheeturl, ref); } } transformer = transformation.transformer; // invalid to set 'null' as parameter as 'null' is not a valid Java object if(sourceurl != null) transformer.setParameter("sourceURL", sourceurl); if(sourcebaseurl != null) transformer.setParameter("sourceBaseURL", sourcebaseurl); if(targeturl != null) transformer.setParameter("targetURL", targeturl); if(targetbaseurl != null) transformer.setParameter("targetBaseURL", targetbaseurl); if(pubtype != null) transformer.setParameter("publicType", pubtype); if(systype != null) transformer.setParameter("systemType", systype); if(svcfactory != null) transformer.setParameter("XMultiServiceFactory",svcfactory); long tstart = System.currentTimeMillis(); // StringWriter sw = new StringWriter(); // StreamResult sr = new StreamResult(sw); StreamResult sr = new StreamResult(output); transformer.transform(xmlsource, sr); // String s = sw.toString(); // OutputStreamWriter ow = new OutputStreamWriter(output, "UTF-8"); // ow.write(s); // ow.close(); long time = System.currentTimeMillis() - tstart; if (statsp != null) { statsp.println("finished transformation in "+time+"ms"); } // dereference input buffer xmlsource = null; output.close(); xostream.closeOutput(); // try to release reference asap... xostream = null; // notify any listeners about close for (Enumeration e = listeners.elements(); e.hasMoreElements();) { XStreamListener l = (XStreamListener)e.nextElement(); l.closed(); } } catch (java.lang.Throwable ex) { // notify any listeners about close for (Enumeration e = listeners.elements(); e.hasMoreElements();) { XStreamListener l = (XStreamListener)e.nextElement(); l.error(new com.sun.star.uno.Exception(ex.getClass().getName()+": "+ex.getMessage())); } if (statsp != null) { statsp.println(ex.getClass().getName()+": "+ex.getMessage()); ex.printStackTrace(statsp); } } } }; t.start(); } public void terminate() { try { if (statsp != null){ statsp.println("terminate called"); } if(t.isAlive()){ t.interrupt(); for (Enumeration e = listeners.elements(); e.hasMoreElements();) { XStreamListener l = (XStreamListener)e.nextElement(); l.terminated(); } } } catch (java.lang.Exception ex) { if (statsp != null){ statsp.println(ex.getClass().getName()+": "+ex.getMessage()); ex.printStackTrace(statsp); } } } private final static String _serviceName = "com.sun.star.comp.JAXTHelper"; // Implement methods from interface XTypeProvider public byte[] getImplementationId() { byte[] byteReturn = {}; byteReturn = new String( "" + this.hashCode() ).getBytes(); return( byteReturn ); } public com.sun.star.uno.Type[] getTypes() { Type[] typeReturn = {}; try { typeReturn = new Type[] { new Type( XTypeProvider.class ), new Type( XServiceName.class ), new Type( XServiceInfo.class ), new Type( XActiveDataSource.class ), new Type( XActiveDataSink.class ), new Type( XActiveDataControl.class ), new Type( XInitialization.class ) }; } catch( java.lang.Exception exception ) { } return( typeReturn ); } public String getServiceName() { return( _serviceName ); } public boolean supportsService(String stringServiceName) { return( stringServiceName.equals(_serviceName)); } public String getImplementationName() { return( XSLTransformer.class.getName()); } public String[] getSupportedServiceNames() { String[] stringSupportedServiceNames = { _serviceName }; return stringSupportedServiceNames; } public static XSingleServiceFactory __getServiceFactory( String implName, XMultiServiceFactory multiFactory, XRegistryKey regKey) { XSingleServiceFactory xSingleServiceFactory = null; if (implName.equals(XSLTransformer.class.getName()) ) { xSingleServiceFactory = FactoryHelper.getServiceFactory(XSLTransformer.class, _serviceName, multiFactory, regKey); } return xSingleServiceFactory; } public static boolean __writeRegistryServiceInfo(XRegistryKey regKey) { return FactoryHelper.writeRegistryServiceInfo(XSLTransformer.class.getName(), _serviceName, regKey); } }
package com.jetbrains.python.codeInsight.imports; import com.google.common.collect.Ordering; import com.intellij.application.options.CodeStyle; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.lang.ImportOptimizer; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.impl.DirectoryIndex; import com.intellij.openapi.roots.impl.DirectoryInfo; import com.intellij.openapi.util.Couple; import com.intellij.openapi.util.EmptyRunnable; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiComment; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiWhiteSpace; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.QualifiedName; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import com.jetbrains.python.codeInsight.imports.AddImportHelper.ImportPriority; import com.jetbrains.python.formatter.PyCodeStyleSettings; import com.jetbrains.python.inspections.unresolvedReference.PyUnresolvedReferencesVisitor; import com.jetbrains.python.inspections.unresolvedReference.SimplePyUnresolvedReferencesInspection; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyPsiUtils; import one.util.streamex.StreamEx; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.model.java.JavaResourceRootType; import org.jetbrains.jps.model.module.JpsModuleSourceRootType; import java.util.*; import static com.jetbrains.python.psi.PyUtil.as; /** * @author yole */ public class PyImportOptimizer implements ImportOptimizer { private static final Logger LOG = Logger.getInstance(PyImportOptimizer.class); private boolean mySortImports = true; @NotNull public static PyImportOptimizer onlyRemoveUnused() { final PyImportOptimizer optimizer = new PyImportOptimizer(); optimizer.mySortImports = false; return optimizer; } @Override public boolean supports(@NotNull PsiFile file) { return true; } @Override @NotNull public Runnable processFile(@NotNull final PsiFile file) { if (isInsideTestResourceRoot(file)) { return EmptyRunnable.INSTANCE; } final LocalInspectionToolSession session = new LocalInspectionToolSession(file, 0, file.getTextLength()); final PyUnresolvedReferencesVisitor visitor = new SimplePyUnresolvedReferencesInspection.Visitor(null, session); session.putUserData(PyUnresolvedReferencesVisitor.INSPECTION, new SimplePyUnresolvedReferencesInspection()); file.accept(new PyRecursiveElementVisitor() { @Override public void visitElement(@NotNull PsiElement node) { super.visitElement(node); node.accept(visitor); } }); return () -> { LOG.debug(String.format(" visitor.optimizeImports(); if (mySortImports && file instanceof PyFile) { new ImportSorter((PyFile)file).run(); } LOG.debug(" }; } private static boolean isInsideTestResourceRoot(@NotNull PsiFile file) { final DirectoryIndex directoryIndex = DirectoryIndex.getInstance(file.getProject()); final DirectoryInfo directoryInfo = directoryIndex.getInfoForFile(file.getVirtualFile()); final JpsModuleSourceRootType<?> sourceRootType = directoryIndex.getSourceRootType(directoryInfo); return JavaResourceRootType.TEST_RESOURCE.equals(sourceRootType); } private static final class ImportSorter { private final PyFile myFile; private final PyCodeStyleSettings myPySettings; private final List<PyImportStatementBase> myImportBlock; private final Map<ImportPriority, List<PyImportStatementBase>> myGroups; private final MultiMap<PyImportStatementBase, PsiComment> myOldImportToLineComments = MultiMap.create(); private final MultiMap<PyImportStatementBase, PsiComment> myOldImportToInnerComments = MultiMap.create(); private final MultiMap<String, PyFromImportStatement> myOldFromImportBySources = MultiMap.create(); private final MultiMap<PyImportStatementBase, PsiComment> myNewImportToLineComments = MultiMap.create(); // Contains trailing and nested comments of modified (split and joined) imports private final MultiMap<PyImportStatementBase, PsiComment> myNewImportToInnerComments = MultiMap.create(); private final List<PsiComment> myDanglingComments = new ArrayList<>(); private final PyElementGenerator myGenerator; private final LanguageLevel myLangLevel; private ImportSorter(@NotNull PyFile file) { myFile = file; myPySettings = CodeStyle.getCustomSettings(myFile, PyCodeStyleSettings.class); myImportBlock = myFile.getImportBlock(); myGroups = new EnumMap<>(ImportPriority.class); for (ImportPriority priority : ImportPriority.values()) { myGroups.put(priority, new ArrayList<>()); } myGenerator = PyElementGenerator.getInstance(myFile.getProject()); myLangLevel = LanguageLevel.forElement(myFile); } @NotNull private Comparator<PyImportElement> getFromNamesComparator() { final Comparator<String> stringComparator = AddImportHelper.getImportTextComparator(myFile); final Comparator<QualifiedName> qNamesComparator = Comparator.comparing(QualifiedName::toString, stringComparator); return Comparator .comparing(PyImportElement::getImportedQName, Comparator.nullsFirst(qNamesComparator)) .thenComparing(PyImportElement::getAsName, Comparator.nullsFirst(stringComparator)); } public void run() { if (myImportBlock.isEmpty()) { return; } analyzeImports(myImportBlock); for (PyImportStatementBase importStatement : myImportBlock) { final AddImportHelper.ImportPriorityChoice choice = AddImportHelper.getImportPriorityWithReason(importStatement); LOG.debug(String.format("Import group for '%s' is %s: %s", importStatement.getText(), choice.getPriority(), choice.getDescription())); myGroups.get(choice.getPriority()).add(importStatement); } boolean hasTransformedImports = false; for (ImportPriority priority : ImportPriority.values()) { final List<PyImportStatementBase> original = myGroups.get(priority); final List<PyImportStatementBase> transformed = transformImportsInGroup(original); hasTransformedImports |= !original.equals(transformed); myGroups.put(priority, transformed); } if (hasTransformedImports || needBlankLinesBetweenGroups() || groupsNotSorted()) { applyResults(); } } private void analyzeImports(@NotNull List<PyImportStatementBase> imports) { for (PyImportStatementBase statement : imports) { final PyFromImportStatement fromImport = as(statement, PyFromImportStatement.class); if (fromImport != null && !fromImport.isStarImport()) { myOldFromImportBySources.putValue(getNormalizedFromImportSource(fromImport), fromImport); } final Couple<List<PsiComment>> boundAndOthers = collectPrecedingLineComments(statement); myOldImportToLineComments.putValues(statement, boundAndOthers.getFirst()); if (statement != myImportBlock.get(0)) { myDanglingComments.addAll(boundAndOthers.getSecond()); } myOldImportToInnerComments.putValues(statement, PsiTreeUtil.collectElementsOfType(statement, PsiComment.class)); } } @NotNull private List<PyImportStatementBase> transformImportsInGroup(@NotNull List<PyImportStatementBase> imports) { final List<PyImportStatementBase> result = new ArrayList<>(); for (PyImportStatementBase statement : imports) { if (statement instanceof PyImportStatement) { transformPlainImport(result, (PyImportStatement)statement); } else if (statement instanceof PyFromImportStatement) { transformFromImport(result, (PyFromImportStatement)statement); } } return result; } private void transformPlainImport(@NotNull List<PyImportStatementBase> result, @NotNull PyImportStatement importStatement) { final PyImportElement[] importElements = importStatement.getImportElements(); // Split combined imports like "import foo, bar as b" if (importElements.length > 1) { final List<PyImportStatement> newImports = ContainerUtil.map(importElements, e -> myGenerator.createImportStatement(myLangLevel, e.getText(), null)); replaceOneImportWithSeveral(result, importStatement, newImports); } else { addImportAsIs(result, importStatement); } } private void transformFromImport(@NotNull List<PyImportStatementBase> result, @NotNull PyFromImportStatement fromImport) { // We can neither sort, nor combine star imports if (fromImport.isStarImport()) { addImportAsIs(result, fromImport); return; } final String source = getNormalizedFromImportSource(fromImport); final PyImportElement[] importedFromNames = fromImport.getImportElements(); final List<PyImportElement> newFromImportNames = new ArrayList<>(); final Comparator<PyImportElement> fromNamesComparator = getFromNamesComparator(); final Collection<PyFromImportStatement> sameSourceImports = myOldFromImportBySources.get(source); if (sameSourceImports.isEmpty()) { return; } // Keep existing parentheses if we only re-order names inside the import boolean forceParentheses = sameSourceImports.size() == 1 && fromImport.getLeftParen() != null; // Join multiple "from" imports with the same source, like "from module import foo; from module import bar as b" final boolean shouldJoinImports = myPySettings.OPTIMIZE_IMPORTS_JOIN_FROM_IMPORTS_WITH_SAME_SOURCE && sameSourceImports.size() > 1; final boolean shouldSplitImport = myPySettings.OPTIMIZE_IMPORTS_ALWAYS_SPLIT_FROM_IMPORTS && importedFromNames.length > 1; if (shouldJoinImports) { for (PyFromImportStatement sameSourceImport : sameSourceImports) { ContainerUtil.addAll(newFromImportNames, sameSourceImport.getImportElements()); } // Remember that we have checked imports with this source already myOldFromImportBySources.remove(source); } else if (!shouldSplitImport && myPySettings.OPTIMIZE_IMPORTS_SORT_NAMES_IN_FROM_IMPORTS) { if (!Ordering.from(fromNamesComparator).isOrdered(Arrays.asList(importedFromNames))) { ContainerUtil.addAll(newFromImportNames, importedFromNames); } } final boolean shouldGenerateNewFromImport = !newFromImportNames.isEmpty(); if (shouldGenerateNewFromImport) { if (myPySettings.OPTIMIZE_IMPORTS_SORT_NAMES_IN_FROM_IMPORTS) { newFromImportNames.sort(fromNamesComparator); } String importedNames = StringUtil.join(newFromImportNames, ImportSorter::getNormalizedImportElementText, ", "); if (forceParentheses) { importedNames = "(" + importedNames + ")"; } final PyFromImportStatement combinedImport = myGenerator.createFromImportStatement(myLangLevel, source, importedNames, null); final Set<PyImportStatementBase> oldImports = ContainerUtil.map2LinkedSet(newFromImportNames, e -> (PyImportStatementBase)e.getParent()); replaceSeveralImportsWithOne(result, oldImports, combinedImport); } else if (shouldSplitImport) { final List<PyFromImportStatement> newFromImports = ContainerUtil.map(importedFromNames, importElem -> { final String name = Objects.toString(importElem.getImportedQName(), ""); final String alias = importElem.getAsName(); return myGenerator.createFromImportStatement(myLangLevel, source, name, alias); }); replaceOneImportWithSeveral(result, fromImport, newFromImports); } else { addImportAsIs(result, fromImport); } } private void replaceSeveralImportsWithOne(@NotNull List<PyImportStatementBase> result, @NotNull Collection<? extends PyImportStatementBase> oldImports, @NotNull PyFromImportStatement newImport) { for (PyImportStatementBase replaced : oldImports) { myNewImportToLineComments.putValues(newImport, myOldImportToLineComments.get(replaced)); myNewImportToInnerComments.putValues(newImport, myOldImportToInnerComments.get(replaced)); } result.add(newImport); } private void replaceOneImportWithSeveral(@NotNull List<PyImportStatementBase> result, @NotNull PyImportStatementBase oldImport, @NotNull Collection<? extends PyImportStatementBase> newImports) { final PyImportStatementBase topmostImport; if (myPySettings.OPTIMIZE_IMPORTS_SORT_IMPORTS) { topmostImport = Collections.min(newImports, AddImportHelper.getSameGroupImportsComparator(myFile)); } else { topmostImport = ContainerUtil.getFirstItem(newImports); } myNewImportToLineComments.putValues(topmostImport, myOldImportToLineComments.get(oldImport)); myNewImportToInnerComments.putValues(topmostImport, myOldImportToInnerComments.get(oldImport)); result.addAll(newImports); } private void addImportAsIs(@NotNull List<PyImportStatementBase> result, @NotNull PyImportStatementBase oldImport) { myNewImportToLineComments.putValues(oldImport, myOldImportToLineComments.get(oldImport)); result.add(oldImport); } @NotNull private static String getNormalizedImportElementText(@NotNull PyImportElement element) { // Remove comments, line feeds and backslashes return element.getText().replaceAll("#.*", "").replaceAll("[\\s\\\\]+", " "); } @NotNull private static Couple<List<PsiComment>> collectPrecedingLineComments(@NotNull PyImportStatementBase statement) { final List<PsiComment> boundComments = PyPsiUtils.getPrecedingComments(statement, true); final PsiComment firstComment = ContainerUtil.getFirstItem(boundComments); if (firstComment != null && isFirstInFile(firstComment)) { return Couple.of(Collections.emptyList(), boundComments); } final List<PsiComment> remainingComments = PyPsiUtils.getPrecedingComments(ObjectUtils.notNull(firstComment, statement), false); return Couple.of(boundComments, remainingComments); } private static boolean isFirstInFile(@NotNull PsiElement element) { if (element.getTextRange().getStartOffset() == 0) return true; final PsiWhiteSpace prevWhitespace = as(PsiTreeUtil.prevLeaf(element), PsiWhiteSpace.class); return prevWhitespace != null && prevWhitespace.getTextRange().getStartOffset() == 0; } @NotNull public static String getNormalizedFromImportSource(@NotNull PyFromImportStatement statement) { return StringUtil.repeatSymbol('.', statement.getRelativeLevel()) + Objects.toString(statement.getImportSourceQName(), ""); } private boolean groupsNotSorted() { if (!myPySettings.OPTIMIZE_IMPORTS_SORT_IMPORTS) { return false; } final Ordering<PyImportStatementBase> importOrdering = Ordering.from(AddImportHelper.getSameGroupImportsComparator(myFile)); return ContainerUtil.exists(myGroups.values(), imports -> !importOrdering.isOrdered(imports)); } private boolean needBlankLinesBetweenGroups() { return StreamEx.of(myGroups.values()).remove(List::isEmpty).count() > 1; } private void applyResults() { if (myPySettings.OPTIMIZE_IMPORTS_SORT_IMPORTS) { for (ImportPriority priority : myGroups.keySet()) { final List<PyImportStatementBase> imports = myGroups.get(priority); imports.sort(AddImportHelper.getSameGroupImportsComparator(myFile)); myGroups.put(priority, imports); } } final PyImportStatementBase firstImport = myImportBlock.get(0); final List<PsiComment> boundComments = collectPrecedingLineComments(firstImport).getFirst(); final PsiElement firstElementToRemove = boundComments.isEmpty() ? firstImport : boundComments.get(0); final PyImportStatementBase lastImport = ContainerUtil.getLastItem(myImportBlock); assert lastImport != null; addImportsAfter(lastImport); deleteRangeThroughDocument(firstElementToRemove, PyPsiUtils.getNextNonWhitespaceSibling(lastImport).getPrevSibling()); } private void addImportsAfter(@NotNull PsiElement anchor) { final StringBuilder content = new StringBuilder(); for (List<PyImportStatementBase> imports : myGroups.values()) { if (content.length() > 0 && !imports.isEmpty()) { // one extra blank line between import groups according to PEP 8 content.append("\n"); } for (PyImportStatementBase statement : imports) { for (PsiComment comment : myNewImportToLineComments.get(statement)) { content.append(comment.getText()).append("\n"); } content.append(statement.getText()); final Collection<PsiComment> innerComments = myNewImportToInnerComments.get(statement); if (!innerComments.isEmpty()) { content.append(" // Join several comments for the same import statement by ";" as isort does final String combinedComment = StringUtil.join(innerComments, comment -> comment.getText().substring(1).trim(), "; "); content.append(combinedComment).append("\n"); } else { content.append("\n"); } } } if (!myDanglingComments.isEmpty()) { content.append("\n"); for (PsiComment comment : myDanglingComments) { content.append(comment.getText()).append("\n"); } } final Project project = anchor.getProject(); final PyFile file = (PyFile)myGenerator.createDummyFile(myLangLevel, content.toString()); final PyFile reformattedFile = (PyFile)CodeStyleManager.getInstance(project).reformat(file); final List<PyImportStatementBase> newImportBlock = reformattedFile.getImportBlock(); assert newImportBlock != null; myFile.addRangeAfter(reformattedFile.getFirstChild(), reformattedFile.getLastChild(), anchor); } private static void deleteRangeThroughDocument(@NotNull PsiElement first, @NotNull PsiElement last) { PyUtil.updateDocumentUnblockedAndCommitted(first, document -> { document.deleteString(first.getTextRange().getStartOffset(), last.getTextRange().getEndOffset()); }); } } }
package org.rabix.engine.service.impl; import com.google.inject.Inject; import org.apache.commons.configuration.Configuration; import org.rabix.engine.service.GarbageCollectionService; import org.rabix.engine.store.model.JobRecord; import org.rabix.engine.store.model.LinkRecord; import org.rabix.engine.store.repository.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; public class GarbageCollectionServiceImpl implements GarbageCollectionService { private final static Logger logger = LoggerFactory.getLogger(GarbageCollectionServiceImpl.class); private final TransactionHelper transactionService; private final JobRepository jobRepository; private final JobRecordRepository jobRecordRepository; private final JobStatsRecordRepository jobStatsRecordRepository; private final EventRepository eventRepository; private final VariableRecordRepository variableRecordRepository; private final LinkRecordRepository linkRecordRepository; private final DAGRepository dagRepository; private final ExecutorService executorService = Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "GarbageCollectionService")); private final boolean enabled; @Inject public GarbageCollectionServiceImpl(JobRepository jobRepository, JobRecordRepository jobRecordRepository, JobStatsRecordRepository jobStatsRecordRepository, EventRepository eventRepository, VariableRecordRepository variableRecordRepository, LinkRecordRepository linkRecordRepository, DAGRepository dagRepository, TransactionHelper transactionService, Configuration configuration) { this.jobRepository = jobRepository; this.jobRecordRepository = jobRecordRepository; this.jobStatsRecordRepository = jobStatsRecordRepository; this.transactionService = transactionService; this.eventRepository = eventRepository; this.variableRecordRepository = variableRecordRepository; this.linkRecordRepository = linkRecordRepository; this.dagRepository = dagRepository; this.enabled = configuration.getBoolean("gc.enabled", true); } public void gc(UUID rootId) { if (!enabled) return; executorService.submit(() -> { try { transactionService.doInTransaction((TransactionHelper.TransactionCallback<Void>) () -> { doGc(rootId); return null; }); } catch (Exception e) { logger.warn("Could not perform garbage collection.", e); } }); } private void doGc(UUID rootId) { List<JobRecord> jobRecords = jobRecordRepository .get(rootId, terminalStates()) .stream() .filter(jobRecord -> !jobRecord.isScattered()) .collect(Collectors.toList()); jobRecords.stream().filter(this::isGarbage).forEach(this::collect); } private void collect(JobRecord jobRecord) { logger.info("Collecting garbage of {} with id {}", jobRecord.getId(), jobRecord.getExternalId()); UUID rootId = jobRecord.getRootId(); if (jobRecord.isRoot()) { dagRepository.delete(rootId); linkRecordRepository.deleteByRootId(rootId); jobStatsRecordRepository.delete(rootId); eventRepository.deleteByRootId(rootId); List<JobRecord> all = jobRecordRepository.get(rootId); flush(all); } List<JobRecord> garbage = new ArrayList<>(); garbage.add(jobRecord); if (jobRecord.isScatterWrapper()) { List<JobRecord> scattered = jobRecordRepository.getByParent(jobRecord.getExternalId(), rootId); garbage.addAll(scattered); } flush(garbage); } private void flush(List<JobRecord> garbage) { garbage.forEach(record -> { variableRecordRepository.delete(record.getId(), record.getRootId()); eventRepository.deleteGroup(record.getExternalId()); jobRecordRepository.delete(record.getExternalId(), record.getRootId()); jobRepository.delete(record.getRootId(), new HashSet<>(Collections.singletonList(record.getExternalId()))); }); } private boolean isGarbage(JobRecord jobRecord) { if (jobRecord.isRoot() && jobRecord.isCompleted()) { return true; } List<LinkRecord> outputLink = linkRecordRepository.getBySource(jobRecord.getId(), jobRecord.getRootId()); List<JobRecord> outputJobRecords = outputLink .stream() .map(link -> jobRecordRepository.get(link.getDestinationJobId(), link.getRootId())) .filter(Objects::nonNull) .collect(Collectors.toList()); return outputJobRecords.isEmpty() || outputJobRecords.stream().allMatch(outputRecord -> { if (outputRecord.isScatterWrapper()) { return isGarbage(outputRecord); } return outputRecord.isCompleted(); }); } private Set<JobRecord.JobState> terminalStates() { return new HashSet<>( Arrays.asList(JobRecord.JobState.COMPLETED, JobRecord.JobState.ABORTED, JobRecord.JobState.FAILED)); } }
package integration.forms; import com.sun.star.uno.UnoRuntime; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.util.XCloseable; import integration.forms.DocumentHelper; public class TestSkeleton extends complexlib.ComplexTestCase { private DocumentHelper m_document; private FormLayer m_formLayer; private XMultiServiceFactory m_orb; /** Creates a new instance of ValueBinding */ public TestSkeleton() { } public String[] getTestMethodNames() { return new String[] { "checkSomething" }; } public String getTestObjectName() { return "Form Control Spreadsheet Cell Binding Test"; } public void before() throws com.sun.star.uno.Exception, java.lang.Exception { m_orb = (XMultiServiceFactory)param.getMSF(); m_document = DocumentHelper.blankTextDocument( m_orb ); m_formLayer = new FormLayer( m_document ); } public void after() throws com.sun.star.uno.Exception, java.lang.Exception { // close our document if ( m_document != null ) { XCloseable closeDoc = (XCloseable)UnoRuntime.queryInterface( XCloseable.class, m_document.getDocument() ); closeDoc.close( true ); } } public void checkSomething() throws com.sun.star.uno.Exception, java.lang.Exception { } }
package net.runelite.client.plugins.cluescrolls.clues; import com.google.common.collect.ImmutableSet; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Polygon; import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Nullable; import lombok.Getter; import net.runelite.api.Client; import static net.runelite.api.EquipmentInventorySlot.*; import static net.runelite.api.EquipmentInventorySlot.LEGS; import net.runelite.api.Item; import net.runelite.api.ItemID; import static net.runelite.api.ItemID.*; import net.runelite.api.Perspective; import net.runelite.api.ScriptID; import net.runelite.api.Varbits; import net.runelite.api.coords.LocalPoint; import net.runelite.api.coords.WorldPoint; import static net.runelite.client.plugins.cluescrolls.ClueScrollOverlay.TITLED_CONTENT_COLOR; import net.runelite.client.plugins.cluescrolls.ClueScrollPlugin; import net.runelite.client.plugins.cluescrolls.clues.emote.Emote; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.*; import static net.runelite.client.plugins.cluescrolls.clues.emote.Emote.BULL_ROARER; import net.runelite.client.plugins.cluescrolls.clues.emote.STASHUnit; import static net.runelite.client.plugins.cluescrolls.clues.emote.STASHUnit.*; import static net.runelite.client.plugins.cluescrolls.clues.emote.STASHUnit.SHANTAY_PASS; import net.runelite.client.plugins.cluescrolls.clues.item.ItemRequirement; import static net.runelite.client.plugins.cluescrolls.clues.item.ItemRequirements.*; import static net.runelite.client.plugins.cluescrolls.clues.Enemy.*; import net.runelite.client.ui.overlay.OverlayUtil; import net.runelite.client.ui.overlay.components.LineComponent; import net.runelite.client.ui.overlay.components.PanelComponent; import net.runelite.client.ui.overlay.components.TitleComponent; @Getter public class EmoteClue extends ClueScroll implements TextClueScroll, LocationClueScroll { private static final Set<EmoteClue> CLUES = ImmutableSet.of( new EmoteClue("Beckon on the east coast of the Kharazi Jungle. Beware of double agents! Equip any vestment stole and a heraldic rune shield.", "Kharazi Jungle", NORTHEAST_CORNER_OF_THE_KHARAZI_JUNGLE, new WorldPoint(2954, 2933, 0), DOUBLE_AGENT_108, BECKON, any("Any stole", item(GUTHIX_STOLE), item(SARADOMIN_STOLE), item(ZAMORAK_STOLE), item(ARMADYL_STOLE), item(BANDOS_STOLE), item(ANCIENT_STOLE)), any("Any heraldic rune shield", item(RUNE_SHIELD_H1), item(RUNE_SHIELD_H2), item(RUNE_SHIELD_H3), item(RUNE_SHIELD_H4), item(RUNE_SHIELD_H5))), new EmoteClue("Cheer in the Barbarian Agility Arena. Headbang before you talk to me. Equip a steel platebody, maple shortbow and a Wilderness cape.", "Barbarian Outpost", BARBARIAN_OUTPOST_OBSTACLE_COURSE, new WorldPoint(2552, 3556, 0), CHEER, HEADBANG, item(STEEL_PLATEBODY), item(MAPLE_SHORTBOW), range("Any team cape", TEAM1_CAPE, TEAM50_CAPE)), new EmoteClue("Bow upstairs in the Edgeville Monastery. Equip a completed prayer book.", "Edgeville Monastery", SOUTHEAST_CORNER_OF_THE_MONASTERY, new WorldPoint(3056, 3484, 1), BOW, any("Any god book", item(HOLY_BOOK), item(BOOK_OF_BALANCE), item(UNHOLY_BOOK), item(BOOK_OF_LAW), item(BOOK_OF_WAR), item(BOOK_OF_DARKNESS))), new EmoteClue("Cheer in the Shadow dungeon. Equip a rune crossbow, climbing boots and any mitre.", "Shadow dungeon", ENTRANCE_OF_THE_CAVE_OF_DAMIS, new WorldPoint(2629, 5071, 0), CHEER, any("Any mitre", item(GUTHIX_MITRE), item(SARADOMIN_MITRE), item(ZAMORAK_MITRE), item(ANCIENT_MITRE), item(BANDOS_MITRE), item(ARMADYL_MITRE)), item(RUNE_CROSSBOW), item(CLIMBING_BOOTS), item(RING_OF_VISIBILITY)), new EmoteClue("Cheer at the top of the agility pyramid. Beware of double agents! Equip a blue mystic robe top, and any rune heraldic shield.", "Agility Pyramid", AGILITY_PYRAMID, new WorldPoint(3043, 4697, 3), DOUBLE_AGENT_108, CHEER, item(MYSTIC_ROBE_TOP), any("Any rune heraldic shield", item(RUNE_SHIELD_H1), item(RUNE_SHIELD_H2), item(RUNE_SHIELD_H3), item(RUNE_SHIELD_H4), item(RUNE_SHIELD_H5))), new EmoteClue("Dance in Iban's temple. Beware of double agents! Equip Iban's staff, a black mystic top and a black mystic bottom.", "Iban's temple", WELL_OF_VOYAGE, new WorldPoint(2011, 4712, 0), DOUBLE_AGENT_141, DANCE, any("Any iban's staff", item(IBANS_STAFF), item(IBANS_STAFF_U)), item(MYSTIC_ROBE_TOP_DARK), item(MYSTIC_ROBE_BOTTOM_DARK)), new EmoteClue("Dance on the Fishing Platform. Equip barrows gloves, an amulet of glory and a dragon med helm.", "Fishing Platform", SOUTHEAST_CORNER_OF_THE_FISHING_PLATFORM, new WorldPoint(2782, 3273, 0), DANCE, any("Any amulet of glory", item(AMULET_OF_GLORY), item(AMULET_OF_GLORY1), item(AMULET_OF_GLORY2), item(AMULET_OF_GLORY3), item(AMULET_OF_GLORY4), item(AMULET_OF_GLORY5), item(AMULET_OF_GLORY6)), item(BARROWS_GLOVES), item(DRAGON_MED_HELM)), new EmoteClue("Flap at the death altar. Beware of double agents! Equip a death tiara, a legend's cape and any ring of wealth.", "Death altar", DEATH_ALTAR, new WorldPoint(2205, 4838, 0), DOUBLE_AGENT_141, FLAP, any("Any ring of wealth", item(RING_OF_WEALTH), item(RING_OF_WEALTH_1), item(RING_OF_WEALTH_2), item(RING_OF_WEALTH_3), item(RING_OF_WEALTH_4), item(RING_OF_WEALTH_5), item(RING_OF_WEALTH_I), item(RING_OF_WEALTH_I1), item(RING_OF_WEALTH_I2), item(RING_OF_WEALTH_I3), item(RING_OF_WEALTH_I4), item(RING_OF_WEALTH_I5)), item(DEATH_TIARA), item(CAPE_OF_LEGENDS)), new EmoteClue("Headbang in the Fight Arena pub. Equip a pirate bandana, a dragonstone necklace and and a magic longbow.", "Fight Arena pub", OUTSIDE_THE_BAR_BY_THE_FIGHT_ARENA, new WorldPoint(2568, 3149, 0), HEADBANG, any("Any pirate bandana", item(PIRATE_BANDANA), item(PIRATE_BANDANA_7124), item(PIRATE_BANDANA_7130), item(PIRATE_BANDANA_7136)), item(DRAGON_NECKLACE), item(MAGIC_LONGBOW)), new EmoteClue("Do a jig at the barrows chest. Beware of double agents! Equip any full barrows set.", "Barrows chest", BARROWS_CHEST, new WorldPoint(3551, 9694, 0), DOUBLE_AGENT_141, JIG, any("Any full barrows set", all(any("Ahrim's hood", item(AHRIMS_HOOD), range(AHRIMS_HOOD_100, AHRIMS_HOOD_0)), any("Ahrim's staff", item(AHRIMS_STAFF), range(AHRIMS_STAFF_100, AHRIMS_STAFF_0)), any("Ahrim's robetop", item(AHRIMS_ROBETOP), range(AHRIMS_ROBETOP_100, AHRIMS_ROBETOP_0)), any("Ahrim's robeskirt", item(AHRIMS_ROBESKIRT), range(AHRIMS_ROBESKIRT_100, AHRIMS_ROBESKIRT_0))), all(any("Dharok's helm", item(DHAROKS_HELM), range(DHAROKS_HELM_100, DHAROKS_HELM_0)), any("Dharok's greataxe", item(DHAROKS_GREATAXE), range(DHAROKS_GREATAXE_100, DHAROKS_GREATAXE_0)), any("Dharok's platebody", item(DHAROKS_PLATEBODY), range(DHAROKS_PLATEBODY_100, DHAROKS_PLATEBODY_0)), any("Dharok's platelegs", item(DHAROKS_PLATELEGS), range(DHAROKS_PLATELEGS_100, DHAROKS_PLATELEGS_0))), all(any("Guthan's helm", item(GUTHANS_HELM), range(GUTHANS_HELM_100, GUTHANS_HELM_0)), any("Guthan's warspear", item(GUTHANS_WARSPEAR), range(GUTHANS_WARSPEAR_100, GUTHANS_WARSPEAR_0)), any("Guthan's platebody", item(GUTHANS_PLATEBODY), range(GUTHANS_PLATEBODY_100, GUTHANS_PLATEBODY_0)), any("Guthan's chainskirt", item(GUTHANS_CHAINSKIRT), range(GUTHANS_CHAINSKIRT_100, GUTHANS_CHAINSKIRT_0))), all(any("Karil's coif", item(KARILS_COIF), range(KARILS_COIF_100, KARILS_COIF_0)), any("Karil's crossbow", item(KARILS_CROSSBOW), range(KARILS_CROSSBOW_100, KARILS_CROSSBOW_0)), any("Karil's leathertop", item(KARILS_LEATHERTOP), range(KARILS_LEATHERTOP_100, KARILS_LEATHERTOP_0)), any("Karil's leatherskirt", item(KARILS_LEATHERSKIRT), range(KARILS_LEATHERSKIRT_100, KARILS_LEATHERSKIRT_0))), all(any("Torag's helm", item(TORAGS_HELM), range(TORAGS_HELM_100, TORAGS_HELM_0)), any("Torag's hammers", item(TORAGS_HAMMERS), range(TORAGS_HAMMERS_100, TORAGS_HAMMERS_0)), any("Torag's platebody", item(TORAGS_PLATEBODY), range(TORAGS_PLATEBODY_100, TORAGS_PLATEBODY_0)), any("Torag's platelegs", item(TORAGS_PLATELEGS), range(TORAGS_PLATELEGS_100, TORAGS_PLATELEGS_0))), all(any("Verac's helm", item(VERACS_HELM), range(VERACS_HELM_100, VERACS_HELM_0)), any("Verac's flail", item(VERACS_FLAIL), range(VERACS_FLAIL_100, VERACS_FLAIL_0)), any("Verac's brassard", item(VERACS_BRASSARD), range(VERACS_BRASSARD_100, VERACS_BRASSARD_0)), any("Verac's plateskirt", item(VERACS_PLATESKIRT), range(VERACS_PLATESKIRT_100, VERACS_PLATESKIRT_0))))), new EmoteClue("Jig at Jiggig. Beware of double agents! Equip a Rune spear, rune platelegs and any rune heraldic helm.", "Jiggig", IN_THE_MIDDLE_OF_JIGGIG, new WorldPoint(2477, 3047, 0), DOUBLE_AGENT_108, JIG, range("Any rune heraldic helm", RUNE_HELM_H1, RUNE_HELM_H5), item(RUNE_SPEAR), item(RUNE_PLATELEGS)), new EmoteClue("Cheer at the games room. Have nothing equipped at all when you do.", "Games room", null, new WorldPoint(2207, 4952, 0), CHEER, emptySlot("Nothing at all", HEAD, CAPE, AMULET, WEAPON, BODY, SHIELD, LEGS, GLOVES, BOOTS, RING, AMMO)), new EmoteClue("Panic on the pier where you catch the Fishing trawler. Have nothing equipped at all when you do.", "Fishing trawler", null, new WorldPoint(2676, 3169, 0), PANIC, emptySlot("Nothing at all", HEAD, CAPE, AMULET, WEAPON, BODY, SHIELD, LEGS, GLOVES, BOOTS, RING, AMMO)), new EmoteClue("Panic in the heart of the Haunted Woods. Beware of double agents! Have no items equipped when you do.", "Haunted Woods", null, new WorldPoint(3611, 3492, 0), DOUBLE_AGENT_108, PANIC, emptySlot("Nothing at all", HEAD, CAPE, AMULET, WEAPON, BODY, SHIELD, LEGS, GLOVES, BOOTS, RING, AMMO)), new EmoteClue("Show your anger towards the Statue of Saradomin in Ellamaria's garden. Beware of double agents! Equip a zamorak godsword.", "Varrock Castle", BY_THE_BEAR_CAGE_IN_VARROCK_PALACE_GARDENS, new WorldPoint(3230, 3478, 0), DOUBLE_AGENT_141, ANGRY, any("Zamorak godsword", item(ZAMORAK_GODSWORD), item(ZAMORAK_GODSWORD_OR))), new EmoteClue("Show your anger at the Wise old man. Beware of double agents! Equip an abyssal whip, a legend's cape and some spined chaps.", "Draynor Village", BEHIND_MISS_SCHISM_IN_DRAYNOR_VILLAGE, new WorldPoint(3088, 3254, 0), DOUBLE_AGENT_141, ANGRY, any("Abyssal whip", item(ABYSSAL_WHIP), item(VOLCANIC_ABYSSAL_WHIP), item(FROZEN_ABYSSAL_WHIP)), item(CAPE_OF_LEGENDS), item(SPINED_CHAPS)), new EmoteClue("Beckon by a collection of crystalline maple trees. Beware of double agents! Equip Bryophyta's staff and a nature tiara.", "North of Prifddinas", CRYSTALLINE_MAPLE_TREES, new WorldPoint(2211, 3427, 0), DOUBLE_AGENT_141, BECKON, range("Bryophyta's staff", BRYOPHYTAS_STAFF_UNCHARGED, BRYOPHYTAS_STAFF), item(NATURE_TIARA)), new EmoteClue("Beckon in the Digsite, near the eastern winch. Bow before you talk to me. Equip a green gnome hat, snakeskin boots and an iron pickaxe.", "Digsite", DIGSITE, new WorldPoint(3370, 3425, 0), BECKON, BOW, item(GREEN_HAT), item(SNAKESKIN_BOOTS), item(IRON_PICKAXE)), new EmoteClue("Beckon in Tai Bwo Wannai. Clap before you talk to me. Equip green dragonhide chaps, a ring of dueling and a mithril medium helmet.", "Tai Bwo Wannai", SOUTH_OF_THE_SHRINE_IN_TAI_BWO_WANNAI_VILLAGE, new WorldPoint(2803, 3073, 0), BECKON, CLAP, item(GREEN_DHIDE_CHAPS), any("Ring of dueling", item(RING_OF_DUELING1), item(RING_OF_DUELING2), item(RING_OF_DUELING3), item(RING_OF_DUELING4), item(RING_OF_DUELING5), item(RING_OF_DUELING6), item(RING_OF_DUELING7), item(RING_OF_DUELING8)), item(MITHRIL_MED_HELM)), new EmoteClue("Beckon in the combat ring of Shayzien. Show your anger before you talk to me. Equip an adamant platebody, adamant full helm and adamant platelegs.", "Shayzien combat ring", WEST_OF_THE_SHAYZIEN_COMBAT_RING, new WorldPoint(1545, 3594, 0), BECKON, ANGRY, item(ADAMANT_PLATELEGS), item(ADAMANT_PLATEBODY), item(ADAMANT_FULL_HELM)), new EmoteClue("Bow near Lord Iorwerth. Beware of double agents! Equip a charged crystal bow.", "Lord Iorwerth's camp", TENT_IN_LORD_IORWERTHS_ENCAMPMENT, new WorldPoint(2205, 3252, 0), DOUBLE_AGENT_141, BOW, any("Crystal Bow", item(CRYSTAL_BOW), item(CRYSTAL_BOW_24123))), new EmoteClue("Bow in the Iorwerth Camp. Beware of double agents! Equip a charged crystal bow.", "Lord Iorwerth's camp", TENT_IN_LORD_IORWERTHS_ENCAMPMENT, new WorldPoint(2205, 3252, 0), DOUBLE_AGENT_141, BOW, any("Crystal Bow", item(CRYSTAL_BOW), item(CRYSTAL_BOW_24123))), new EmoteClue("Bow outside the entrance to the Legends' Guild. Equip iron platelegs, an emerald amulet and an oak longbow.", "Legend's Guild", OUTSIDE_THE_LEGENDS_GUILD_GATES, new WorldPoint(2729, 3349, 0), BOW, item(IRON_PLATELEGS), item(OAK_LONGBOW), item(EMERALD_AMULET)), new EmoteClue("Bow on the ground floor of the Legend's guild. Equip Legend's cape, a dragon battleaxe and an amulet of glory.", "Legend's Guild", OUTSIDE_THE_LEGENDS_GUILD_DOOR, new WorldPoint(2728, 3377, 0), BOW, item(CAPE_OF_LEGENDS), item(DRAGON_BATTLEAXE), any("Any amulet of glory", item(AMULET_OF_GLORY), item(AMULET_OF_GLORY1), item(AMULET_OF_GLORY2), item(AMULET_OF_GLORY3), item(AMULET_OF_GLORY4), item(AMULET_OF_GLORY5), item(AMULET_OF_GLORY6))), new EmoteClue("Bow in the ticket office of the Duel Arena. Equip an iron chain body, leather chaps and coif.", "Duel Arena", MUBARIZS_ROOM_AT_THE_DUEL_ARENA, new WorldPoint(3314, 3241, 0), BOW, item(IRON_CHAINBODY), item(LEATHER_CHAPS), item(COIF)), new EmoteClue("Bow at the top of the lighthouse. Beware of double agents! Equip a blue dragonhide body, blue dragonhide vambraces and no jewelry.", "Lighthouse", TOP_FLOOR_OF_THE_LIGHTHOUSE, new WorldPoint(2511, 3641, 2), DOUBLE_AGENT_108, BOW, item(BLUE_DHIDE_BODY), item(BLUE_DHIDE_VAMBRACES), emptySlot("No jewellery", AMULET, RING)), new EmoteClue("Blow a kiss between the tables in Shilo Village bank. Beware of double agents! Equip a blue mystic hat, bone spear and rune platebody.", "Shilo Village", SHILO_VILLAGE_BANK, new WorldPoint(2851, 2954, 0), DOUBLE_AGENT_108, BLOW_KISS, item(MYSTIC_HAT), item(BONE_SPEAR), item(RUNE_PLATEBODY)), new EmoteClue("Blow a kiss in the heart of the lava maze. Equip black dragonhide chaps, a spotted cape and a rolling pin.", "Lava maze", NEAR_A_LADDER_IN_THE_WILDERNESS_LAVA_MAZE, new WorldPoint(3069, 3861, 0), BLOW_KISS, item(BLACK_DHIDE_CHAPS), any("Spotted cape", item(SPOTTED_CAPE), item(SPOTTED_CAPE_10073)), item(ROLLING_PIN)), new EmoteClue("Blow a kiss outside K'ril Tsutsaroth's chamber. Beware of double agents! Equip a zamorak full helm and the shadow sword.", "K'ril's chamber", OUTSIDE_KRIL_TSUTSAROTHS_ROOM, new WorldPoint(2925, 5333, 0), DOUBLE_AGENT_141, BLOW_KISS, item(ZAMORAK_FULL_HELM), item(SHADOW_SWORD)), new EmoteClue("Cheer at the Druids' Circle. Equip a blue wizard hat, a bronze two-handed sword and HAM boots.", "Taverley stone circle", TAVERLEY_STONE_CIRCLE, new WorldPoint(2924, 3478, 0), CHEER, item(BLUE_WIZARD_HAT), item(BRONZE_2H_SWORD), item(HAM_BOOTS)), new EmoteClue("Cheer in the Edgeville general store. Dance before you talk to me. Equip a brown apron, leather boots and leather gloves.", "Edgeville", NORTH_OF_EVIL_DAVES_HOUSE_IN_EDGEVILLE, new WorldPoint(3080, 3509, 0), CHEER, DANCE, item(BROWN_APRON), item(LEATHER_BOOTS), item(LEATHER_GLOVES)), new EmoteClue("Cheer in the Ogre Pen in the Training Camp. Show you are angry before you talk to me. Equip a green dragonhide body and chaps and a steel square shield.", "King Lathas' camp", OGRE_CAGE_IN_KING_LATHAS_TRAINING_CAMP, new WorldPoint(2527, 3375, 0), CHEER, ANGRY, item(GREEN_DHIDE_BODY), item(GREEN_DHIDE_CHAPS), item(STEEL_SQ_SHIELD)), new EmoteClue("Cheer in the Entrana church. Beware of double agents! Equip a full set of black dragonhide armour.", "Entrana church", ENTRANA_CHAPEL, new WorldPoint(2852, 3349, 0), DOUBLE_AGENT_141, CHEER, item(BLACK_DHIDE_VAMBRACES), item(BLACK_DHIDE_CHAPS), item(BLACK_DHIDE_BODY)), new EmoteClue("Cheer for the monks at Port Sarim. Equip a coif, steel plateskirt and a sapphire necklace.", "Port Sarim", NEAR_THE_ENTRANA_FERRY_IN_PORT_SARIM, new WorldPoint(3047, 3237, 0), CHEER, item(COIF), item(STEEL_PLATESKIRT), item(SAPPHIRE_NECKLACE)), new EmoteClue("Clap in the main exam room in the Exam Centre. Equip a white apron, green gnome boots and leather gloves.", "Exam Centre", OUTSIDE_THE_DIGSITE_EXAM_CENTRE, new WorldPoint(3361, 3339, 0), CLAP, item(WHITE_APRON), item(GREEN_BOOTS), item(LEATHER_GLOVES)), new EmoteClue("Clap on the causeway to the Wizards' Tower. Equip an iron medium helmet, emerald ring and a white apron.", "Wizards' Tower", ON_THE_BRIDGE_TO_THE_MISTHALIN_WIZARDS_TOWER, new WorldPoint(3113, 3196, 0), CLAP, item(IRON_MED_HELM), item(EMERALD_RING), item(WHITE_APRON)), new EmoteClue("Clap on the top level of the mill, north of East Ardougne. Equip a blue gnome robe top, HAM robe bottom and an unenchanted tiara.", "East Ardougne", UPSTAIRS_IN_THE_ARDOUGNE_WINDMILL, new WorldPoint(2635, 3385, 3), CLAP, item(BLUE_ROBE_TOP), item(HAM_ROBE), item(TIARA)), new EmoteClue("Clap in Seers court house. Spin before you talk to me. Equip an adamant halberd, blue mystic robe bottom and a diamond ring.", "Seers Village", OUTSIDE_THE_SEERS_VILLAGE_COURTHOUSE, new WorldPoint(2735, 3469, 0), CLAP, SPIN, item(ADAMANT_HALBERD), item(MYSTIC_ROBE_BOTTOM), item(DIAMOND_RING)), new EmoteClue("Clap in the magic axe hut. Beware of double agents! Equip only some flared trousers.", "Magic axe hut", OUTSIDE_THE_WILDERNESS_AXE_HUT, new WorldPoint(3191, 3960, 0), DOUBLE_AGENT_141, CLAP, item(FLARED_TROUSERS), item(LOCKPICK), emptySlot("Nothing else", HEAD, CAPE, AMULET, WEAPON, BODY, SHIELD, GLOVES, BOOTS, RING, AMMO)), new EmoteClue("Clap your hands north of Mount Karuulm Spin before you talk to me. Equip an adamant warhammer, a ring of life and a pair of mithril boots.", "Mount Karuulm", NORTH_OF_MOUNT_KARUULM, new WorldPoint(1306, 3839, 0), CLAP, SPIN, item(ADAMANT_WARHAMMER), item(RING_OF_LIFE), item(MITHRIL_BOOTS)), new EmoteClue("Cry in the Catherby Ranging shop. Bow before you talk to me. Equip blue gnome boots, a hard leather body and an unblessed silver sickle.", "Catherby", HICKTONS_ARCHERY_EMPORIUM, new WorldPoint(2823, 3443, 0), CRY, BOW, item(BLUE_BOOTS), item(HARDLEATHER_BODY), item(SILVER_SICKLE)), new EmoteClue("Cry on the shore of Catherby beach. Laugh before you talk to me, equip an adamant sq shield, a bone dagger and mithril platebody.", "Catherby", OUTSIDE_HARRYS_FISHING_SHOP_IN_CATHERBY, new WorldPoint(2852, 3429, 0), CRY, LAUGH, item(ADAMANT_SQ_SHIELD), item(BONE_DAGGER), item(MITHRIL_PLATEBODY)), new EmoteClue("Cry on top of the western tree in the Gnome Agility Arena. Indicate 'no' before you talk to me. Equip a steel kiteshield, ring of forging and green dragonhide chaps.", "Gnome Stronghold", GNOME_STRONGHOLD_BALANCING_ROPE, new WorldPoint(2473, 3420, 2), CRY, NO, item(STEEL_KITESHIELD), item(RING_OF_FORGING), item(GREEN_DHIDE_CHAPS)), new EmoteClue("Cry in the TzHaar gem store. Beware of double agents! Equip a fire cape and TokTz-Xil-Ul.", "Tzhaar gem store", TZHAAR_GEM_STORE, new WorldPoint(2463, 5149, 0), DOUBLE_AGENT_141, CRY, any("Fire cape", item(FIRE_CAPE), item(FIRE_MAX_CAPE), item(INFERNAL_CAPE), item(INFERNAL_MAX_CAPE)), item(TOKTZXILUL)), new EmoteClue("Cry in the Draynor Village jail. Jump for joy before you talk to me. Equip an adamant sword, a sapphire amulet and an adamant plateskirt.", "Draynor Village jail", OUTSIDE_DRAYNOR_VILLAGE_JAIL, new WorldPoint(3128, 3245, 0), CRY, JUMP_FOR_JOY, item(ADAMANT_SWORD), item(SAPPHIRE_AMULET), item(ADAMANT_PLATESKIRT)), new EmoteClue("Dance at the crossroads north of Draynor. Equip an iron chain body, a sapphire ring and a longbow.", "Draynor Village", CROSSROADS_NORTH_OF_DRAYNOR_VILLAGE, new WorldPoint(3109, 3294, 0), DANCE, item(IRON_CHAINBODY), item(SAPPHIRE_RING), item(LONGBOW)), new EmoteClue("Dance in the Party Room. Equip a steel full helmet, steel platebody and an iron plateskirt.", "Falador Party Room", OUTSIDE_THE_FALADOR_PARTY_ROOM, new WorldPoint(3045, 3376, 0), DANCE, item(STEEL_FULL_HELM), item(STEEL_PLATEBODY), item(IRON_PLATESKIRT)), new EmoteClue("Dance in the shack in Lumbridge Swamp. Equip a bronze dagger, iron full helmet and a gold ring.", "Lumbridge swamp", NEAR_A_SHED_IN_LUMBRIDGE_SWAMP, new WorldPoint(3203, 3169, 0), DANCE, item(BRONZE_DAGGER), item(IRON_FULL_HELM), item(GOLD_RING)), new EmoteClue("Dance in the dark caves beneath Lumbridge Swamp. Blow a kiss before you talk to me. Equip an air staff, Bronze full helm and an amulet of power.", "Lumbridge swamp caves", LUMBRIDGE_SWAMP_CAVES, new WorldPoint(3168, 9571, 0), DANCE, BLOW_KISS, Varbits.FIRE_PIT_LUMBRIDGE_SWAMP, item(STAFF_OF_AIR), item(BRONZE_FULL_HELM), item(AMULET_OF_POWER)), new EmoteClue("Dance at the cat-doored pyramid in Sophanem. Beware of double agents! Equip a ring of life, an uncharged amulet of glory and an adamant two-handed sword.", "Pyramid Of Sophanem", OUTSIDE_THE_GREAT_PYRAMID_OF_SOPHANEM, new WorldPoint(3294, 2781, 0), DOUBLE_AGENT_108, DANCE, item(RING_OF_LIFE), item(AMULET_OF_GLORY), item(ADAMANT_2H_SWORD)), new EmoteClue("Dance in the centre of Canifis. Bow before you talk to me. Equip a green gnome robe top, mithril plate legs and an iron two-handed sword.", "Canifis", CENTRE_OF_CANIFIS, new WorldPoint(3492, 3488, 0), DANCE, BOW, item(GREEN_ROBE_TOP), item(MITHRIL_PLATELEGS), item(IRON_2H_SWORD)), new EmoteClue("Dance in the King Black Dragon's lair. Beware of double agents! Equip a black dragonhide body, black dragonhide vambraces and a black dragon mask.", "King black dragon's lair", KING_BLACK_DRAGONS_LAIR, new WorldPoint(2271, 4680, 0), DOUBLE_AGENT_141, DANCE, item(BLACK_DHIDE_BODY), item(BLACK_DHIDE_VAMBRACES), item(BLACK_DRAGON_MASK)), new EmoteClue("Dance at the entrance to the Grand Exchange. Equip a pink skirt, pink robe top and a body tiara.", "Grand Exchange", SOUTH_OF_THE_GRAND_EXCHANGE, new WorldPoint(3165, 3467, 0), DANCE, item(PINK_SKIRT), item(PINK_ROBE_TOP), item(BODY_TIARA)), new EmoteClue("Goblin Salute in the Goblin Village. Beware of double agents! Equip a bandos godsword, a bandos cloak and a bandos platebody.", "Goblin Village", OUTSIDE_MUDKNUCKLES_HUT, new WorldPoint(2956, 3505, 0), DOUBLE_AGENT_141, GOBLIN_SALUTE, item(BANDOS_PLATEBODY), item(BANDOS_CLOAK), any("Bandos godsword", item(BANDOS_GODSWORD), item(BANDOS_GODSWORD_OR))), new EmoteClue("Headbang in the mine north of Al Kharid. Equip a desert shirt, leather gloves and leather boots.", "Al Kharid mine", AL_KHARID_SCORPION_MINE, new WorldPoint(3299, 3289, 0), HEADBANG, item(DESERT_SHIRT), item(LEATHER_GLOVES), item(LEATHER_BOOTS)), new EmoteClue("Headbang at the exam centre. Beware of double agents! Equip a mystic fire staff, a diamond bracelet and rune boots.", "Exam Centre", INSIDE_THE_DIGSITE_EXAM_CENTRE, new WorldPoint(3362, 3340, 0), DOUBLE_AGENT_108, HEADBANG, item(MYSTIC_FIRE_STAFF), item(DIAMOND_BRACELET), item(RUNE_BOOTS)), new EmoteClue("Headbang at the top of Slayer Tower. Equip a seercull, a combat bracelet and helm of Neitiznot.", "Slayer Tower", OUTSIDE_THE_SLAYER_TOWER_GARGOYLE_ROOM, new WorldPoint(3421, 3537, 2), HEADBANG, item(SEERCULL), range("Combat bracelet", COMBAT_BRACELET4, COMBAT_BRACELET), item(HELM_OF_NEITIZNOT)), new EmoteClue("Dance a jig by the entrance to the Fishing Guild. Equip an emerald ring, a sapphire amulet, and a bronze chain body.", "Fishing Guild", OUTSIDE_THE_FISHING_GUILD, new WorldPoint(2610, 3391, 0), JIG, item(EMERALD_RING), item(SAPPHIRE_AMULET), item(BRONZE_CHAINBODY)), new EmoteClue("Dance a jig under Shantay's Awning. Bow before you talk to me. Equip a pointed blue snail helmet, an air staff and a bronze square shield.", "Shantay Pass", SHANTAY_PASS, new WorldPoint(3304, 3124, 0), JIG, BOW, any("Bruise blue snelm (pointed)", item(BRUISE_BLUE_SNELM_3343)), item(STAFF_OF_AIR), item(BRONZE_SQ_SHIELD)), new EmoteClue("Do a jig in Varrock's rune store. Equip an air tiara and a staff of water.", "Varrock rune store", AUBURYS_SHOP_IN_VARROCK, new WorldPoint(3253, 3401, 0), JIG, item(AIR_TIARA), item(STAFF_OF_WATER)), new EmoteClue("Jump for joy at the beehives. Equip a desert shirt, green gnome robe bottoms and a steel axe.", "Catherby", CATHERBY_BEEHIVE_FIELD, new WorldPoint(2759, 3445, 0), JUMP_FOR_JOY, item(DESERT_SHIRT), item(GREEN_ROBE_BOTTOMS), item(STEEL_AXE)), new EmoteClue("Jump for joy in Yanille bank. Dance a jig before you talk to me. Equip a brown apron, adamantite medium helmet and snakeskin chaps.", "Yanille", OUTSIDE_YANILLE_BANK, new WorldPoint(2610, 3092, 0), JUMP_FOR_JOY, JIG, item(BROWN_APRON), item(ADAMANT_MED_HELM), item(SNAKESKIN_CHAPS)), new EmoteClue("Jump for joy in the TzHaar sword shop. Shrug before you talk to me. Equip a Steel longsword, Blue D'hide body and blue mystic gloves.", "Tzhaar weapon store", TZHAAR_WEAPONS_STORE, new WorldPoint(2477, 5146, 0), JUMP_FOR_JOY, SHRUG, item(STEEL_LONGSWORD), item(BLUE_DHIDE_BODY), item(MYSTIC_GLOVES)), new EmoteClue("Jump for joy in the Ancient Cavern. Equip a granite shield, splitbark body and any rune heraldic helm.", "Ancient cavern", ENTRANCE_OF_THE_CAVERN_UNDER_THE_WHIRLPOOL, new WorldPoint(1768, 5366, 1), JUMP_FOR_JOY, item(GRANITE_SHIELD), item(SPLITBARK_BODY), range("Any rune heraldic helm", RUNE_HELM_H1, RUNE_HELM_H5)), new EmoteClue("Jump for joy at the Neitiznot rune rock. Equip Rune boots, a proselyte hauberk and a dragonstone ring.", "Fremennik Isles", NEAR_A_RUNITE_ROCK_IN_THE_FREMENNIK_ISLES, new WorldPoint(2375, 3850, 0), JUMP_FOR_JOY, item(RUNE_BOOTS), item(PROSELYTE_HAUBERK), item(DRAGONSTONE_RING)), new EmoteClue("Jump for joy in the centre of Zul-Andra. Beware of double agents! Equip a dragon 2h sword, bandos boots and an obsidian cape.", "Zul-Andra", NEAR_THE_PIER_IN_ZULANDRA, new WorldPoint(2199, 3056, 0), DOUBLE_AGENT_141, JUMP_FOR_JOY, item(DRAGON_2H_SWORD), item(BANDOS_BOOTS), item(OBSIDIAN_CAPE)), new EmoteClue("Laugh by the fountain of heroes. Equip splitbark legs, dragon boots and a Rune longsword.", "Fountain of heroes", FOUNTAIN_OF_HEROES, new WorldPoint(2920, 9893, 0), LAUGH, item(SPLITBARK_LEGS), any("Dragon boots", item(DRAGON_BOOTS), item(DRAGON_BOOTS_G)), item(RUNE_LONGSWORD)), new EmoteClue("Laugh in Jokul's tent in the Mountain Camp. Beware of double agents! Equip a rune full helmet, blue dragonhide chaps and a fire battlestaff.", "Mountain Camp", MOUNTAIN_CAMP_GOAT_ENCLOSURE, new WorldPoint(2812, 3681, 0), DOUBLE_AGENT_108, LAUGH, item(RUNE_FULL_HELM), item(BLUE_DHIDE_CHAPS), item(FIRE_BATTLESTAFF)), new EmoteClue("Laugh at the crossroads south of the Sinclair Mansion. Equip a cowl, a blue wizard robe top and an iron scimitar.", "Sinclair Mansion", ROAD_JUNCTION_SOUTH_OF_SINCLAIR_MANSION, new WorldPoint(2741, 3536, 0), LAUGH, item(LEATHER_COWL), item(BLUE_WIZARD_ROBE), item(IRON_SCIMITAR)), new EmoteClue("Laugh in front of the gem store in Ardougne market. Equip a Castlewars bracelet, a dragonstone amulet and a ring of forging.", "Ardougne", NEAR_THE_GEM_STALL_IN_ARDOUGNE_MARKET, new WorldPoint(2666, 3304, 0), LAUGH, any("Castle wars bracelet", range(CASTLE_WARS_BRACELET3, CASTLE_WARS_BRACELET1)), item(DRAGONSTONE_AMULET), item(RING_OF_FORGING)), new EmoteClue("Panic in the Limestone Mine. Equip bronze platelegs, a steel pickaxe and a steel medium helmet.", "Limestone Mine", LIMESTONE_MINE, new WorldPoint(3372, 3498, 0), PANIC, item(BRONZE_PLATELEGS), item(STEEL_PICKAXE), item(STEEL_MED_HELM)), new EmoteClue("Panic by the mausoleum in Morytania. Wave before you speak to me. Equip a mithril plate skirt, a maple longbow and no boots.", "Morytania mausoleum, access via the experiments cave", MAUSOLEUM_OFF_THE_MORYTANIA_COAST, new WorldPoint(3504, 3576, 0), PANIC, WAVE, item(MITHRIL_PLATESKIRT), item(MAPLE_LONGBOW), emptySlot("No boots", BOOTS)), new EmoteClue("Panic on the Wilderness volcano bridge. Beware of double agents! Equip any headband and crozier.", "Wilderness volcano", VOLCANO_IN_THE_NORTHEASTERN_WILDERNESS, new WorldPoint(3368, 3935, 0), DOUBLE_AGENT_65, PANIC, any("Any headband", range(RED_HEADBAND, BROWN_HEADBAND), range(WHITE_HEADBAND, GREEN_HEADBAND)), any("Any crozier", item(ANCIENT_CROZIER), item(ARMADYL_CROZIER), item(BANDOS_CROZIER), range(SARADOMIN_CROZIER, ZAMORAK_CROZIER))), new EmoteClue("Panic by the pilot on White Wolf Mountain. Beware of double agents! Equip mithril platelegs, a ring of life and a rune axe.", "White Wolf Mountain", GNOME_GLIDER_ON_WHITE_WOLF_MOUNTAIN, new WorldPoint(2847, 3499, 0), DOUBLE_AGENT_108, PANIC, item(MITHRIL_PLATELEGS), item(RING_OF_LIFE), item(RUNE_AXE)), new EmoteClue("Panic by the big egg where no one dare goes and the ground is burnt. Beware of double agents! Equip a dragon med helm, a TokTz-Ket-Xil, a brine sabre, rune platebody and an uncharged amulet of glory.", "Lava dragon isle", SOUTHEAST_CORNER_OF_LAVA_DRAGON_ISLE, new WorldPoint(3227, 3831, 0), DOUBLE_AGENT_141, PANIC, item(DRAGON_MED_HELM), item(TOKTZKETXIL), item(BRINE_SABRE), item(RUNE_PLATEBODY), any("Uncharged Amulet of glory", item(AMULET_OF_GLORY))), new EmoteClue("Panic at the area flowers meet snow. Equip Blue D'hide vambraces, a dragon spear and a rune plateskirt.", "Trollweiss mountain", HALFWAY_DOWN_TROLLWEISS_MOUNTAIN, new WorldPoint(2776, 3781, 0), PANIC, item(BLUE_DHIDE_VAMBRACES), item(DRAGON_SPEAR), item(RUNE_PLATESKIRT), item(SLED_4084)), new EmoteClue("Do a push up at the bank of the Warrior's guild. Beware of double agents! Equip a dragon battleaxe, a dragon defender and a slayer helm of any kind.", "Warriors' guild", WARRIORS_GUILD_BANK_29047, new WorldPoint(2843, 3543, 0), DOUBLE_AGENT_141, PUSH_UP, item(DRAGON_BATTLEAXE), any("Dragon defender", item(DRAGON_DEFENDER), item(DRAGON_DEFENDER_T)), any("Any slayer helmet", item(SLAYER_HELMET), item(BLACK_SLAYER_HELMET), item(GREEN_SLAYER_HELMET), item(PURPLE_SLAYER_HELMET), item(RED_SLAYER_HELMET), item(TURQUOISE_SLAYER_HELMET), item(SLAYER_HELMET_I), item(BLACK_SLAYER_HELMET_I), item(GREEN_SLAYER_HELMET_I), item(PURPLE_SLAYER_HELMET_I), item(RED_SLAYER_HELMET_I), item(TURQUOISE_SLAYER_HELMET_I), item(HYDRA_SLAYER_HELMET), item(HYDRA_SLAYER_HELMET_I), item(TWISTED_SLAYER_HELMET), item(TWISTED_SLAYER_HELMET_I))), new EmoteClue("Blow a raspberry in the bank of the Warriors' Guild. Beware of double agents! Equip a dragon battleaxe, a slayer helm of any kind and a dragon defender or avernic defender.", "Warriors' guild", WARRIORS_GUILD_BANK_29047, new WorldPoint(2843, 3543, 0), DOUBLE_AGENT_141, RASPBERRY, item(DRAGON_BATTLEAXE), any("Dragon defender or Avernic defender", item(DRAGON_DEFENDER), item(DRAGON_DEFENDER_T), item(AVERNIC_DEFENDER)), any("Any slayer helmet", item(SLAYER_HELMET), item(BLACK_SLAYER_HELMET), item(GREEN_SLAYER_HELMET), item(PURPLE_SLAYER_HELMET), item(RED_SLAYER_HELMET), item(TURQUOISE_SLAYER_HELMET), item(SLAYER_HELMET_I), item(BLACK_SLAYER_HELMET_I), item(GREEN_SLAYER_HELMET_I), item(PURPLE_SLAYER_HELMET_I), item(RED_SLAYER_HELMET_I), item(TURQUOISE_SLAYER_HELMET_I), item(HYDRA_SLAYER_HELMET), item(HYDRA_SLAYER_HELMET_I), item(TWISTED_SLAYER_HELMET), item(TWISTED_SLAYER_HELMET_I))), new EmoteClue("Blow a raspberry at the monkey cage in Ardougne Zoo. Equip a studded leather body, bronze platelegs and a normal staff with no orb.", "Ardougne Zoo", NEAR_THE_PARROTS_IN_ARDOUGNE_ZOO, new WorldPoint(2607, 3282, 0), RASPBERRY, item(STUDDED_BODY), item(BRONZE_PLATELEGS), item(STAFF)), new EmoteClue("Blow raspberries outside the entrance to Keep Le Faye. Equip a coif, an iron platebody and leather gloves.", "Keep Le Faye", OUTSIDE_KEEP_LE_FAYE, new WorldPoint(2757, 3401, 0), RASPBERRY, item(COIF), item(IRON_PLATEBODY), item(LEATHER_GLOVES)), new EmoteClue("Blow a raspberry in the Fishing Guild bank. Beware of double agents! Equip an elemental shield, blue dragonhide chaps and a rune warhammer.", "Fishing Guild", FISHING_GUILD_BANK, new WorldPoint(2588, 3419, 0), DOUBLE_AGENT_108, RASPBERRY, item(ELEMENTAL_SHIELD), item(BLUE_DHIDE_CHAPS), item(RUNE_WARHAMMER)), new EmoteClue("Salute in the banana plantation. Beware of double agents! Equip a diamond ring, amulet of power, and nothing on your chest and legs.", "Karamja", WEST_SIDE_OF_THE_KARAMJA_BANANA_PLANTATION, new WorldPoint(2914, 3168, 0), DOUBLE_AGENT_108, SALUTE, item(DIAMOND_RING), item(AMULET_OF_POWER), emptySlot("Nothing on chest & legs", BODY, LEGS)), new EmoteClue("Salute in the Warriors' guild bank. Equip only a black salamander.", "Warriors' guild", WARRIORS_GUILD_BANK, new WorldPoint(2844, 3542, 0), SALUTE, item(BLACK_SALAMANDER), emptySlot("Nothing else", HEAD, CAPE, AMULET, BODY, SHIELD, LEGS, GLOVES, BOOTS, RING, AMMO)), new EmoteClue("Salute in the centre of the mess hall. Beware of double agents! Equip a rune halberd rune platebody, and an amulet of strength.", "Hosidius mess hall", HOSIDIUS_MESS, new WorldPoint(1646, 3631, 0), DOUBLE_AGENT_108, SALUTE, item(RUNE_HALBERD), item(RUNE_PLATEBODY), item(AMULET_OF_STRENGTH)), new EmoteClue("Shrug in the mine near Rimmington. Equip a gold necklace, a gold ring and a bronze spear.", "Rimmington mine", RIMMINGTON_MINE, new WorldPoint(2976, 3238, 0), SHRUG, item(GOLD_NECKLACE), item(GOLD_RING), item(BRONZE_SPEAR)), new EmoteClue("Shrug in Catherby bank. Yawn before you talk to me. Equip a maple longbow, green d'hide chaps and an iron med helm.", "Catherby", OUTSIDE_CATHERBY_BANK, new WorldPoint(2808, 3440, 0), SHRUG, YAWN, item(MAPLE_LONGBOW), item(GREEN_DHIDE_CHAPS), item(IRON_MED_HELM)), new EmoteClue("Shrug in the Zamorak temple found in the Eastern Wilderness. Beware of double agents! Equip rune platelegs, an iron platebody and blue dragonhide vambraces.", "Chaos temple", CHAOS_TEMPLE_IN_THE_SOUTHEASTERN_WILDERNESS, new WorldPoint(3239, 3611, 0), DOUBLE_AGENT_65, SHRUG, item(RUNE_PLATELEGS), item(IRON_PLATEBODY), item(BLUE_DHIDE_VAMBRACES)), new EmoteClue("Shrug in the Shayzien command tent. Equip a blue mystic robe bottom, a rune kiteshield and any bob shirt.", "Shayzien command tent", SHAYZIEN_WAR_TENT, new WorldPoint(1555, 3537, 0), SHRUG, item(MYSTIC_ROBE_BOTTOM), item(RUNE_KITESHIELD), range("Any bob shirt", BOBS_RED_SHIRT, BOBS_PURPLE_SHIRT)), new EmoteClue("Slap your head in the centre of the Kourend catacombs. Beware of double agents! Equip the arclight and the amulet of the damned.", "Kourend catacombs", CENTRE_OF_THE_CATACOMBS_OF_KOUREND, new WorldPoint(1663, 10045, 0), DOUBLE_AGENT_141, SLAP_HEAD, item(ARCLIGHT), any("Amulet of the damned", item(AMULET_OF_THE_DAMNED), item(AMULET_OF_THE_DAMNED_FULL))), new EmoteClue("Spin at the crossroads north of Rimmington. Equip a green gnome hat, cream gnome top and leather chaps.", "Rimmington", ROAD_JUNCTION_NORTH_OF_RIMMINGTON, new WorldPoint(2981, 3276, 0), SPIN, item(GREEN_HAT), item(CREAM_ROBE_TOP), item(LEATHER_CHAPS)), new EmoteClue("Spin in Draynor Manor by the fountain. Equip an iron platebody, studded leather chaps and a bronze full helmet.", "Draynor Manor", DRAYNOR_MANOR_BY_THE_FOUNTAIN, new WorldPoint(3088, 3336, 0), SPIN, item(IRON_PLATEBODY), item(STUDDED_CHAPS), item(BRONZE_FULL_HELM)), new EmoteClue("Spin in front of the Soul altar. Beware of double agents! Equip a dragon pickaxe, helm of neitiznot and a pair of rune boots.", "Soul altar", SOUL_ALTAR, new WorldPoint(1815, 3856, 0), DOUBLE_AGENT_141, SPIN, any("Dragon or Crystal pickaxe", item(DRAGON_PICKAXE), item(DRAGON_PICKAXE_12797), item(INFERNAL_PICKAXE), item(INFERNAL_PICKAXE_UNCHARGED), item(DRAGON_PICKAXEOR), item(CRYSTAL_PICKAXE), item(CRYSTAL_PICKAXE_INACTIVE)), item(HELM_OF_NEITIZNOT), item(RUNE_BOOTS)), new EmoteClue("Spin in the Varrock Castle courtyard. Equip a black axe, a coif and a ruby ring.", "Varrock Castle", OUTSIDE_VARROCK_PALACE_COURTYARD, new WorldPoint(3213, 3463, 0), SPIN, item(BLACK_AXE), item(COIF), item(RUBY_RING)), new EmoteClue("Spin in West Ardougne Church. Equip a dragon spear and red dragonhide chaps.", "West Ardougne Church", CHAPEL_IN_WEST_ARDOUGNE, new WorldPoint(2530, 3290, 0), SPIN, item(DRAGON_SPEAR), item(RED_DHIDE_CHAPS)), new EmoteClue("Spin on the bridge by the Barbarian Village. Salute before you talk to me. Equip purple gloves, a steel kiteshield and a mithril full helmet.", "Barbarian Village", EAST_OF_THE_BARBARIAN_VILLAGE_BRIDGE, new WorldPoint(3105, 3420, 0), SPIN, SALUTE, item(PURPLE_GLOVES), item(STEEL_KITESHIELD), item(MITHRIL_FULL_HELM)), new EmoteClue("Stamp in the Enchanted valley west of the waterfall. Beware of double agents! Equip a dragon axe.", "Enchanted Valley", NORTHWESTERN_CORNER_OF_THE_ENCHANTED_VALLEY, new WorldPoint(3030, 4522, 0), DOUBLE_AGENT_141, STAMP, any("Dragon or Crystal axe", item(DRAGON_AXE), item(CRYSTAL_AXE), item(CRYSTAL_AXE_INACTIVE), item(INFERNAL_AXE), item(INFERNAL_AXE_UNCHARGED))), new EmoteClue("Think in middle of the wheat field by the Lumbridge mill. Equip a blue gnome robetop, a turquoise gnome robe bottom and an oak shortbow.", "Lumbridge mill", WHEAT_FIELD_NEAR_THE_LUMBRIDGE_WINDMILL, new WorldPoint(3159, 3298, 0), THINK, item(BLUE_ROBE_TOP), item(TURQUOISE_ROBE_BOTTOMS), item(OAK_SHORTBOW)), new EmoteClue("Think in the centre of the Observatory. Spin before you talk to me. Equip a mithril chain body, green dragonhide chaps and a ruby amulet.", "Observatory", OBSERVATORY, new WorldPoint(2439, 3161, 0), THINK, SPIN, item(MITHRIL_CHAINBODY), item(GREEN_DHIDE_CHAPS), item(RUBY_AMULET)), new EmoteClue("Wave along the south fence of the Lumber Yard. Equip a hard leather body, leather chaps and a bronze axe.", "Lumber Yard", NEAR_THE_SAWMILL_OPERATORS_BOOTH, new WorldPoint(3307, 3491, 0), WAVE, item(HARDLEATHER_BODY), item(LEATHER_CHAPS), item(BRONZE_AXE)), new EmoteClue("Wave in the Falador gem store. Equip a Mithril pickaxe, Black platebody and an Iron Kiteshield.", "Falador", NEAR_HERQUINS_SHOP_IN_FALADOR, new WorldPoint(2945, 3335, 0), WAVE, item(MITHRIL_PICKAXE), item(BLACK_PLATEBODY), item(IRON_KITESHIELD)), new EmoteClue("Wave on Mudskipper Point. Equip a black cape, leather chaps and a steel mace.", "Mudskipper Point", MUDSKIPPER_POINT, new WorldPoint(2989, 3110, 0), WAVE, item(BLACK_CAPE), item(LEATHER_CHAPS), item(STEEL_MACE)), new EmoteClue("Wave on the northern wall of Castle Drakan. Beware of double agents! Wear a dragon sq shield, splitbark body and any boater.", "Castle Drakan", NORTHERN_WALL_OF_CASTLE_DRAKAN, new WorldPoint(3562, 3379, 0), DOUBLE_AGENT_141, WAVE, any("Dragon sq shield", item(DRAGON_SQ_SHIELD), item(DRAGON_SQ_SHIELD_G)), item(SPLITBARK_BODY), any("Any boater", item(RED_BOATER), item(ORANGE_BOATER), item(GREEN_BOATER), item(BLUE_BOATER), item(BLACK_BOATER), item(PINK_BOATER), item(PURPLE_BOATER), item(WHITE_BOATER))), new EmoteClue("Yawn in the 7th room of Pyramid Plunder. Beware of double agents! Equip a pharaoh sceptre and a full set of menaphite robes.", "Pyramid Plunder", _7TH_CHAMBER_OF_JALSAVRAH, new WorldPoint(1944, 4427, 0), DOUBLE_AGENT_141, YAWN, any("Pharaoh's sceptre", item(PHARAOHS_SCEPTRE), item(PHARAOHS_SCEPTRE_1), item(PHARAOHS_SCEPTRE_2), item(PHARAOHS_SCEPTRE_3), item(PHARAOHS_SCEPTRE_4), item(PHARAOHS_SCEPTRE_5), item(PHARAOHS_SCEPTRE_6), item(PHARAOHS_SCEPTRE_7), item(PHARAOHS_SCEPTRE_8)), any("Full set of menaphite robes", all(item(MENAPHITE_PURPLE_HAT), item(MENAPHITE_PURPLE_TOP), range(MENAPHITE_PURPLE_ROBE, MENAPHITE_PURPLE_KILT)), all(item(MENAPHITE_RED_HAT), item(MENAPHITE_RED_TOP), range(MENAPHITE_RED_ROBE, MENAPHITE_RED_KILT)))), new EmoteClue("Yawn in the Varrock library. Equip a green gnome robe top, HAM robe bottom and an iron warhammer.", "Varrock Castle", VARROCK_PALACE_LIBRARY, new WorldPoint(3209, 3492, 0), YAWN, item(GREEN_ROBE_TOP), item(HAM_ROBE), item(IRON_WARHAMMER)), new EmoteClue("Yawn in Draynor Marketplace. Equip studded leather chaps, an iron kiteshield and a steel longsword.", "Draynor", DRAYNOR_VILLAGE_MARKET, new WorldPoint(3083, 3253, 0), YAWN, item(STUDDED_CHAPS), item(IRON_KITESHIELD), item(STEEL_LONGSWORD)), new EmoteClue("Yawn in the Castle Wars lobby. Shrug before you talk to me. Equip a ruby amulet, a mithril scimitar and a Wilderness cape.", "Castle Wars", CASTLE_WARS_BANK, new WorldPoint(2440, 3092, 0), YAWN, SHRUG, item(RUBY_AMULET), item(MITHRIL_SCIMITAR), range("Any team cape", TEAM1_CAPE, TEAM50_CAPE)), new EmoteClue("Yawn in the rogues' general store. Beware of double agents! Equip an adamant square shield, blue dragon vambraces and a rune pickaxe.", "Rogues general store", NOTERAZZOS_SHOP_IN_THE_WILDERNESS, new WorldPoint(3026, 3701, 0), DOUBLE_AGENT_65, YAWN, item(ADAMANT_SQ_SHIELD), item(BLUE_DHIDE_VAMBRACES), item(RUNE_PICKAXE)), new EmoteClue("Yawn at the top of Trollheim. Equip a lava battlestaff, black dragonhide vambraces and a mind shield.", "Trollheim Mountain", ON_TOP_OF_TROLLHEIM_MOUNTAIN, new WorldPoint(2887, 3676, 0), YAWN, any("Lava battlestaff", item(LAVA_BATTLESTAFF), item(LAVA_BATTLESTAFF_21198)), item(BLACK_DHIDE_VAMBRACES), item(MIND_SHIELD)), new EmoteClue("Yawn in the centre of Arceuus library. Nod your head before you talk to me. Equip blue dragonhide vambraces, adamant boots and an adamant dagger.", "Arceuus library", ENTRANCE_OF_THE_ARCEUUS_LIBRARY, new WorldPoint(1632, 3807, 0), YAWN, YES, item(BLUE_DHIDE_VAMBRACES), item(ADAMANT_BOOTS), item(ADAMANT_DAGGER)), new EmoteClue("Swing a bullroarer at the top of the watchtower. Beware of double agents! Equip a dragon plateskirt, climbing boots and a dragon chainbody.", "Yanille watchtower", TOP_FLOOR_OF_THE_YANILLE_WATCHTOWER, new WorldPoint(2932, 4712, 0), DOUBLE_AGENT_141, BULL_ROARER, any("Dragon plateskirt", item(DRAGON_PLATESKIRT), item(DRAGON_PLATESKIRT_G)), item(CLIMBING_BOOTS), any("Dragon chainbody", item(DRAGON_CHAINBODY_3140), item(DRAGON_CHAINBODY_G)), item(ItemID.BULL_ROARER)), new EmoteClue("Blow a raspberry at Gypsy Aris in her tent. Equip a gold ring and a gold necklace.", "Varrock", GYPSY_TENT_ENTRANCE, new WorldPoint(3203, 3424, 0), RASPBERRY, item(GOLD_RING), item(GOLD_NECKLACE)), new EmoteClue("Bow to Brugsen Bursen at the Grand Exchange.", "Grand Exchange", null, new WorldPoint(3164, 3477, 0), BOW), new EmoteClue("Cheer at Iffie Nitter. Equip a chef hat and a red cape.", "Varrock", FINE_CLOTHES_ENTRANCE, new WorldPoint(3205, 3416, 0), CHEER, item(CHEFS_HAT), item(RED_CAPE)), new EmoteClue("Clap at Bob's Brilliant Axes. Equip a bronze axe and leather boots.", "Lumbridge", BOB_AXES_ENTRANCE, new WorldPoint(3231, 3203, 0), CLAP, item(BRONZE_AXE), item(LEATHER_BOOTS)), new EmoteClue("Panic at Al Kharid mine.", "Al Kharid mine", null, new WorldPoint(3300, 3314, 0), PANIC), new EmoteClue("Spin at Flynn's Mace Shop.", "Falador", null, new WorldPoint(2950, 3387, 0), SPIN)); private static final String UNICODE_CHECK_MARK = "\u2713"; private static final String UNICODE_BALLOT_X = "\u2717"; private final String text; private final String locationName; @Nullable private final STASHUnit stashUnit; private final WorldPoint location; private final Emote firstEmote; private final Emote secondEmote; private final ItemRequirement[] itemRequirements; private EmoteClue(String text, String locationName, STASHUnit stashUnit, WorldPoint location, Emote firstEmote, @Nonnull ItemRequirement... itemRequirements) { this(text, locationName, stashUnit, location, firstEmote, null, itemRequirements); } private EmoteClue(String text, String locationName, STASHUnit stashUnit, WorldPoint location, Enemy enemy, Emote firstEmote, @Nonnull ItemRequirement... itemRequirements) { this(text, locationName, stashUnit, location, firstEmote, null, itemRequirements); setEnemy(enemy); } private EmoteClue(String text, String locationName, STASHUnit stashUnit, WorldPoint location, Emote firstEmote, Emote secondEmote, @Nonnull ItemRequirement... itemRequirements) { this.text = text; this.locationName = locationName; this.stashUnit = stashUnit; this.location = location; this.firstEmote = firstEmote; this.secondEmote = secondEmote; this.itemRequirements = itemRequirements; } private EmoteClue(String text, String locationName, @Nullable STASHUnit stashUnit, WorldPoint location, Emote firstEmote, Emote secondEmote, @Nonnull Varbits firePit, @Nonnull ItemRequirement... itemRequirements) { this(text, locationName, stashUnit, location, firstEmote, secondEmote, itemRequirements); setRequiresLight(true); setHasFirePit(firePit); } @Override public void makeOverlayHint(PanelComponent panelComponent, ClueScrollPlugin plugin) { panelComponent.getChildren().add(TitleComponent.builder().text("Emote Clue").build()); panelComponent.getChildren().add(LineComponent.builder().left("Emotes:").build()); panelComponent.getChildren().add(LineComponent.builder() .left(getFirstEmote().getName()) .leftColor(TITLED_CONTENT_COLOR) .build()); if (getSecondEmote() != null) { panelComponent.getChildren().add(LineComponent.builder() .left(getSecondEmote().getName()) .leftColor(TITLED_CONTENT_COLOR) .build()); } panelComponent.getChildren().add(LineComponent.builder().left("Location:").build()); panelComponent.getChildren().add(LineComponent.builder() .left(getLocationName()) .leftColor(TITLED_CONTENT_COLOR) .build()); if (itemRequirements.length > 0) { Client client = plugin.getClient(); if (stashUnit != null) { client.runScript(ScriptID.WATSON_STASH_UNIT_CHECK, stashUnit.getObjectId(), 0, 0, 0); int[] intStack = client.getIntStack(); boolean stashUnitBuilt = intStack[0] == 1; panelComponent.getChildren().add(LineComponent.builder() .left("STASH Unit:") .right(stashUnitBuilt ? UNICODE_CHECK_MARK : UNICODE_BALLOT_X) .rightColor(stashUnitBuilt ? Color.GREEN : Color.RED) .build()); } panelComponent.getChildren().add(LineComponent.builder().left("Equip:").build()); Item[] equipment = plugin.getEquippedItems(); Item[] inventory = plugin.getInventoryItems(); // If equipment is null, the player is wearing nothing if (equipment == null) { equipment = new Item[0]; } // If inventory is null, the player has nothing in their inventory if (inventory == null) { inventory = new Item[0]; } Item[] combined = new Item[equipment.length + inventory.length]; System.arraycopy(equipment, 0, combined, 0, equipment.length); System.arraycopy(inventory, 0, combined, equipment.length, inventory.length); for (ItemRequirement requirement : itemRequirements) { boolean equipmentFulfilled = requirement.fulfilledBy(equipment); boolean combinedFulfilled = requirement.fulfilledBy(combined); panelComponent.getChildren().add(LineComponent.builder() .left(requirement.getCollectiveName(client)) .leftColor(TITLED_CONTENT_COLOR) .right(combinedFulfilled ? UNICODE_CHECK_MARK : UNICODE_BALLOT_X) .rightColor(equipmentFulfilled ? Color.GREEN : (combinedFulfilled ? Color.ORANGE : Color.RED)) .build()); } } } @Override public void makeWorldOverlayHint(Graphics2D graphics, ClueScrollPlugin plugin) { LocalPoint localPoint = LocalPoint.fromWorld(plugin.getClient(), getLocation()); if (localPoint != null) { OverlayUtil.renderTileOverlay(plugin.getClient(), graphics, localPoint, plugin.getEmoteImage(), Color.ORANGE); } if (stashUnit != null) { final WorldPoint[] worldPoints = stashUnit.getWorldPoints(); for (final WorldPoint worldPoint : worldPoints) { final LocalPoint stashUnitLocalPoint = LocalPoint.fromWorld(plugin.getClient(), worldPoint); if (stashUnitLocalPoint != null) { final Polygon poly = Perspective.getCanvasTilePoly(plugin.getClient(), stashUnitLocalPoint); if (poly != null) { OverlayUtil.renderPolygon(graphics, poly, Color.RED); } } } } } public static EmoteClue forText(String text) { for (EmoteClue clue : CLUES) { if (clue.getText().equalsIgnoreCase(text)) { return clue; } } return null; } }
package com.vip.saturn.job.console.service; import com.vip.saturn.job.console.mybatis.entity.SaturnStatistics; import java.util.Map; /** * @author chembo.huang * */ public interface DashboardService { void refreshStatistics2DB(boolean force); int executorInDockerCount(String zkList); int executorNotInDockerCount(String zkList); int jobCount(String zkList); /** * top10 */ SaturnStatistics top10FailureDomain(String zklist); /** * top10 */ SaturnStatistics top10FailureJob(String zklist); SaturnStatistics top10AactiveJob(String zklist); /** * top10Executor */ SaturnStatistics top10LoadExecutor(String zklist); /** * top10 */ SaturnStatistics top10LoadJob(String zklist); /** * top10 */ SaturnStatistics top10UnstableDomain(String zklist); SaturnStatistics allProcessAndErrorCountOfTheDay(String zklist); /** * ()<br> * $Jobs/xx/config/cronrunning */ SaturnStatistics allUnnormalJob(String zklist); SaturnStatistics allTimeout4AlarmJob(String currentZkAddr); /** * * ExecutorExecutorExecutor */ SaturnStatistics allUnableFailoverJob(String currentZkAddr); SaturnStatistics top10FailureExecutor(String currentZkAddr); /** * /$SaturnExecutors/sharding/count * @param nns */ void cleanShardingCount(String nns) throws Exception; void cleanOneJobAnalyse(String jobName, String nns) throws Exception; void cleanAllJobAnalyse(String nns) throws Exception; void cleanAllJobExecutorCount(String nns) throws Exception; void cleanOneJobExecutorCount(String jobName, String nns) throws Exception; Map<String, Integer> loadDomainRankDistribution(String key); Map<Integer, Integer> loadJobRankDistribution(String key); SaturnStatistics abnormalContainer(String currentZkAddr); Map<String, Long> versionDomainNumber(String currentZkAddr); Map<String, Long> versionExecutorNumber(String currentZkAddr); }
package org.zpid.se4ojs.textStructure.bo; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.zpid.se4ojs.textStructure.SectionType; public class BOSection extends StructureElement { public static final int ARBITRARY_TITLE_LENGTH = 30; public static final String CHAR_NOT_ALLOWED = "[^A-Za-z0-9]"; private List<SectionType> types = new ArrayList<>(); private List<String> externalLinks = new ArrayList<>(); // private StringBuilder ancestorUri; FIXME private List<String> lists = new ArrayList<>(); private List<StructureElement> childStructures = new ArrayList<>(); private String title; public BOSection(String uriTitle) { this(uriTitle, null); } public BOSection(String uriTitle, List<SectionType> types) { this(null, uriTitle, types, null); } public BOSection(String title, String uriTitle, List<SectionType> types, String language) { super(uriTitle, language); this.title = title; if (types == null) { this.types.add(SectionType.OTHER); } else { this.types = types; } } public static String createUriTitle(String titleTagValue, List<SectionType> types, int idx, String parentTitle) { String uriTitle = null; if (!StringUtils.isEmpty(titleTagValue)) { uriTitle = titleTagValue.replaceAll(CHAR_NOT_ALLOWED, "-"); uriTitle = uriTitle.replaceAll("[-]+", "-"); } if (!StringUtils.isEmpty(uriTitle) && uriTitle.length() > ARBITRARY_TITLE_LENGTH) { uriTitle = uriTitle.substring(0, ARBITRARY_TITLE_LENGTH - 1); } StringBuilder strBuilder = new StringBuilder(); if (!StringUtils.isEmpty(parentTitle)) { strBuilder.append(parentTitle); strBuilder.append("_"); } if (!StringUtils.isEmpty(uriTitle)) { return strBuilder.append(uriTitle).toString(); } if (!types.isEmpty() && !types.get(0).equals(SectionType.OTHER)) { return strBuilder.append(types.get(0).getLabel()).toString(); } return strBuilder.append("sec_untitled_").append(idx).toString(); } // FIXME. Create ancestor uri from parent not from BOSection // private StringBuilder createAncestorUri(BOSection sectionBO, StringBuilder titleInUrl) { // if (parent != null) { // StringBuilder title = new StringBuilder(parent.getTitle()).append("_"); // titleInUrl.insert(0, title.toString()); // createAncestorUri(parent, titleInUrl); // return titleInUrl; public List<String> getExternalLinks() { return externalLinks; } public void setExternalLinks(List<String> extLinks) { this.externalLinks = extLinks; } // FIXME // public StringBuilder getAncestorUri() { // if (ancestorUri == null) { // return createAncestorUri(this, new StringBuilder()); // return ancestorUri; public List<String> getLists() { return lists; } public List<SectionType> getTypes() { return types; } public void addChildStructure(StructureElement childStructure) { childStructures.add(childStructure); } public List<StructureElement> getChildStructures() { return childStructures; } public String getTitle() { return title; } }
package org.quattor.pan.dml.functions; import org.quattor.pan.dml.Operation; import org.quattor.pan.dml.data.*; import org.quattor.pan.exceptions.EvaluationException; import org.quattor.pan.exceptions.SyntaxException; import org.quattor.pan.template.Context; import org.quattor.pan.template.SourceRange; import java.util.ArrayList; import static org.quattor.pan.utils.MessageUtils.MSG_SECOND_ARG_LIST_OR_VARIABLE_REF; import static org.quattor.pan.utils.MessageUtils.MSG_VALUE_CANNOT_BE_NULL; import static org.quattor.pan.utils.MessageUtils.MSG_FIRST_STRING_ARG_REQ; import static org.quattor.pan.utils.MessageUtils.MSG_TWO_OR_MORE_ARG_REQ; final public class Join extends BuiltInFunction { protected Join(SourceRange sourceRange, Operation... operations) { super("join", sourceRange, operations); } public static Operation getInstance(SourceRange sourceRange, Operation... operations) throws SyntaxException { if (operations.length < 2) { throw SyntaxException.create(sourceRange, MSG_TWO_OR_MORE_ARG_REQ, "join"); } // The first argument can't be null. if (operations[0] instanceof Null) { throw SyntaxException.create(sourceRange, MSG_VALUE_CANNOT_BE_NULL, "join"); } // If there are only two arguments, the second argument can't be null and needs to be a list. if (operations.length == 2) { if (operations[1] instanceof Null) { throw SyntaxException.create(sourceRange, MSG_VALUE_CANNOT_BE_NULL, "join"); } if (operations[1] instanceof Element) { if (!(operations[1] instanceof ListResource)) { throw SyntaxException.create(sourceRange, MSG_SECOND_ARG_LIST_OR_VARIABLE_REF, "join"); } } } return new Join(sourceRange, operations); } @Override public Element execute(Context context) throws EvaluationException { assert (ops.length != 1); // Extract the first argument. This must be a string value. String delimeter = null; try { delimeter = ((StringProperty) ops[0].execute(context)).getValue(); } catch (ClassCastException cce) { throw new EvaluationException("first argument in join() must be a string", getSourceRange(), context); } // Create a list containing all elements we need to join. ArrayList<String> result = new ArrayList<String>(); // If the second argument is a ListResource, add the strings to the result-list. if (ops.length == 2) { // Double check whether the second argument is actually a list. Element list = ops[1].execute(context); if (list instanceof ListResource) { // Loop over the list items and convert them to strings. Resource.Iterator it = ((ListResource) list).iterator(); while (it.hasNext()) { Element e = it.next().getValue(); if (e instanceof Resource) { throw new EvaluationException( "join() doesn't accept nested elements in the passed list", getSourceRange(), context); } if (!(e instanceof StringProperty)) { throw new EvaluationException( "join() only accepts strings or a list of strings as input arguments", getSourceRange(), context); } result.add(((StringProperty) e).getValue()); } } else { throw new EvaluationException( "join() only accepts strings or a list of strings as input arguments", getSourceRange(), context); } // If all arguments are passed individually, add them to a list. } else { int length = ops.length; for (int i = 1; i < length; i++) { Element e = ops[i].execute(context); if (e instanceof ListResource) { throw new EvaluationException( "join() only accepts a single list as an argument or all the arguments individually", getSourceRange(), context); } else if (!(e instanceof StringProperty)) { throw new EvaluationException( "join() only accepts strings or a list of strings as input arguments", getSourceRange(), context); } result.add(((StringProperty) e).getValue()); } } return StringProperty.getInstance(String.join(delimeter, result)); } }
package org.jetbrains.yaml.parser; import com.intellij.lang.ASTNode; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiParser; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.yaml.YAMLElementTypes; import org.jetbrains.yaml.YAMLTokenTypes; /** * @author oleg */ public class YAMLParser implements PsiParser, YAMLTokenTypes { private PsiBuilder myBuilder; private boolean eolSeen = false; private int myIndent; private PsiBuilder.Marker myAfterLastEolMarker; @NotNull public ASTNode parse(@NotNull final IElementType root, @NotNull final PsiBuilder builder) { myBuilder = builder; final PsiBuilder.Marker fileMarker = mark(); parseFile(); assert myBuilder.eof() : "Not all tokens were passed."; fileMarker.done(root); return builder.getTreeBuilt(); } private void parseFile() { passJunk(); parseDocument(); passJunk(); while (!myBuilder.eof()) { parseDocument(); passJunk(); } dropEolMarker(); } private void parseDocument() { final PsiBuilder.Marker marker = mark(); if (myBuilder.getTokenType() == DOCUMENT_MARKER){ advanceLexer(); } parseStatements(0); dropEolMarker(); marker.done(YAMLElementTypes.DOCUMENT); } private void parseStatements(int indent) { final boolean sequencesOnTheSameIndent = isSequenceStart(indent); while (!eof() && (isJunk() || !eolSeen || myIndent > indent || myIndent == indent && (!sequencesOnTheSameIndent || isSequenceStart(indent)))) { parseSingleStatement(indent); } } private boolean isSequenceStart(final int indent) { return myIndent == indent && getTokenType() == SEQUENCE_MARKER; } private void parseSingleStatement(int indent) { if (eof()){ return; } final IElementType tokenType = getTokenType(); if (tokenType == LBRACE){ parseHash(); } else if (tokenType == LBRACKET){ parseArray(); } else if (tokenType == SEQUENCE_MARKER){ parseSequence(); } else if (tokenType == SCALAR_KEY) { parseScalarKeyValue(indent); } else if (YAMLElementTypes.SCALAR_VALUES.contains(getTokenType())){ parseScalarValue(); } else { advanceLexer(); } } private void parseScalarValue() { final IElementType tokenType = getTokenType(); assert YAMLElementTypes.SCALAR_VALUES.contains(tokenType) : "Scalar value expected!"; if (tokenType == SCALAR_LIST || tokenType == SCALAR_TEXT){ parseMultiLineScalar(tokenType); } else { advanceLexer(); } } private void parseMultiLineScalar(final IElementType tokenType) { final PsiBuilder.Marker marker = mark(); IElementType type = getTokenType(); while (type == tokenType || type == INDENT || type == EOL){ advanceLexer(); type = getTokenType(); } rollBackToEol(); marker.done(tokenType == SCALAR_LIST ? YAMLElementTypes.SCALAR_LIST_VALUE : YAMLElementTypes.SCALAR_TEXT_VALUE); } private void parseScalarKeyValue(int indent) { final PsiBuilder.Marker marker = mark(); assert getTokenType() == SCALAR_KEY : "Expected scalar key"; eolSeen = false; advanceLexer(); passJunk(); if (YAMLElementTypes.SCALAR_VALUES.contains(getTokenType())){ parseScalarValue(); } else { final PsiBuilder.Marker valueMarker = mark(); if (!eolSeen) { parseSingleStatement(myIndent); } else { while (!eof() && (isJunk() || (myIndent > indent) || isSequenceStart(indent))) { parseStatements(myIndent); } } rollBackToEol(); valueMarker.done(YAMLElementTypes.COMPOUND_VALUE); } marker.done(YAMLElementTypes.KEY_VALUE_PAIR); } private void parseSequence() { final int indent = myIndent + 2; final PsiBuilder.Marker sequenceMarker = mark(); advanceLexer(); eolSeen = false; passJunk(); parseStatements(indent); rollBackToEol(); sequenceMarker.done(YAMLElementTypes.SEQUENCE); } private void parseHash() { final PsiBuilder.Marker marker = mark(); advanceLexer(); while (!eof()){ if (getTokenType() == RBRACE){ break; } parseSingleStatement(0); } dropEolMarker(); marker.done(YAMLElementTypes.HASH); } private void parseArray() { final PsiBuilder.Marker marker = mark(); advanceLexer(); while (!eof()){ if (getTokenType() == RBRACKET){ break; } parseSingleStatement(0); } dropEolMarker(); marker.done(YAMLElementTypes.ARRAY); } private boolean eof() { return myBuilder.eof() || myBuilder.getTokenType() == DOCUMENT_MARKER; } @Nullable private IElementType getTokenType() { return eof() ? null : myBuilder.getTokenType(); } private void dropEolMarker(){ if (myAfterLastEolMarker != null){ myAfterLastEolMarker.drop(); myAfterLastEolMarker = null; } } private void rollBackToEol() { if (eolSeen && myAfterLastEolMarker != null){ eolSeen = false; myAfterLastEolMarker.rollbackTo(); myAfterLastEolMarker = null; } } private PsiBuilder.Marker mark(){ dropEolMarker(); return myBuilder.mark(); } private void advanceLexer() { if (myBuilder.eof()){ return; } final IElementType type = myBuilder.getTokenType(); eolSeen = eolSeen || type == EOL; if (type == EOL){ // Drop and create new eolMarker myAfterLastEolMarker = mark(); myIndent = 0; } else if (type == INDENT){ myIndent = myBuilder.getTokenText().length(); } else { // Drop Eol Marker if other token seen dropEolMarker(); } myBuilder.advanceLexer(); } private void passJunk() { while (!eof() && isJunk()){ advanceLexer(); } } private boolean isJunk(){ final IElementType type = getTokenType(); return type == INDENT || type == EOL; } }
package com.rultor.web; import com.jcabi.aspects.Loggable; import com.jcabi.aspects.Timeable; import com.jcabi.manifests.Manifests; import com.jcabi.urn.URN; import com.rexsl.page.BasePage; import com.rexsl.page.BaseResource; import com.rexsl.page.Inset; import com.rexsl.page.JaxbBundle; import com.rexsl.page.Link; import com.rexsl.page.Resource; import com.rexsl.page.auth.AuthInset; import com.rexsl.page.auth.Facebook; import com.rexsl.page.auth.Github; import com.rexsl.page.auth.Google; import com.rexsl.page.auth.HttpBasic; import com.rexsl.page.auth.Identity; import com.rexsl.page.auth.Provider; import com.rexsl.page.inset.FlashInset; import com.rexsl.page.inset.LinksInset; import com.rexsl.page.inset.VersionInset; import com.rultor.spi.Repo; import com.rultor.spi.Spec; import com.rultor.spi.User; import com.rultor.spi.Users; import com.rultor.spi.Work; import com.rultor.tools.Time; import java.io.IOException; import java.net.URI; import java.util.logging.Level; import javax.validation.constraints.NotNull; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * Abstract RESTful resource. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 1.0 * @checkstyle ClassDataAbstractionCoupling (500 lines) */ @Resource.Forwarded @Loggable(Loggable.DEBUG) @Inset.Default(LinksInset.class) @SuppressWarnings({ "PMD.TooManyMethods", "PMD.ExcessiveImports" }) public class BaseRs extends BaseResource { /** * Authentication keys. */ private static final AuthKeys KEYS = new AuthKeys(); /** * Flash. * @return The inset with flash */ @Inset.Runtime @NotNull(message = "flash can never be NULL") public final FlashInset flash() { return new FlashInset(this); } /** * Inset with a version of the product. * @return The inset */ @Inset.Runtime @NotNull(message = "version can never be NULL") public final Inset insetVersion() { return new VersionInset( Manifests.read("Rultor-Version"), // @checkstyle MultipleStringLiterals (1 line) Manifests.read("Rultor-Revision"), Manifests.read("Rultor-Date") ); } /** * Supplementary inset. * @return The inset */ @Inset.Runtime @NotNull(message = "supplementary inset can never be NULL") public final Inset insetSupplementary() { return new Inset() { @Override public void render(final BasePage<?, ?> page, final Response.ResponseBuilder builder) { builder.type(MediaType.TEXT_XML); builder.header(HttpHeaders.VARY, "Cookie"); builder.header( "X-Rultor-Revision", Manifests.read("Rultor-Revision") ); } }; } /** * User financial stats. * @return The inset */ @Inset.Runtime @NotNull(message = "finance inset can never be NULL") public final Inset insetFinances() { // @checkstyle AnonInnerLength (50 lines) return new Inset() { @Override @Timeable public void render(final BasePage<?, ?> page, final Response.ResponseBuilder builder) { if (!BaseRs.this.auth().identity().equals(Identity.ANONYMOUS)) { page.link( new Link( "account", BaseRs.this.uriInfo().getBaseUriBuilder() .clone() .path(AccountRs.class) .build() ) ); page.append( new JaxbBundle( "balance", BaseRs.this.user().account().balance().toString() ) ); } } }; } /** * Nagivation links. * @return The inset */ @Inset.Runtime @NotNull(message = "navigation inset can never be NULL") public final Inset insetNavigation() { // @checkstyle AnonInnerLength (50 lines) return new Inset() { @Override public void render(final BasePage<?, ?> page, final Response.ResponseBuilder builder) { if (!BaseRs.this.auth().identity().equals(Identity.ANONYMOUS)) { page.link( new Link( "stands", BaseRs.this.uriInfo().getBaseUriBuilder() .clone() .path(StandsRs.class) .build() ) ); page.link( new Link( "units", BaseRs.this.uriInfo().getBaseUriBuilder() .clone() .path(UnitsRs.class) .build() ) ); } } }; } /** * Authentication key inset. * @return The inset */ @Inset.Runtime @NotNull(message = "auth key inset can never be NULL") public final Inset insetAuthKey() { return new Inset() { @Override public void render(final BasePage<?, ?> page, final Response.ResponseBuilder builder) { final Identity identity = BaseRs.this.auth().identity(); if (!identity.equals(Identity.ANONYMOUS)) { page.append( new JaxbBundle("api-key", BaseRs.KEYS.make(identity)) ); } } }; } /** * Authentication inset. * @return The inset */ @Inset.Runtime @NotNull(message = "auth inset can never be NULL") public final AuthInset auth() { // @checkstyle LineLength (4 lines) return new AuthInset(this, Manifests.read("Rultor-SecurityKey")) .with(new Facebook(this, Manifests.read("Rultor-FbId"), Manifests.read("Rultor-FbSecret"))) .with(new Github(this, Manifests.read("Rultor-GithubId"), Manifests.read("Rultor-GithubSecret"))) .with(new Google(this, Manifests.read("Rultor-GoogleId"), Manifests.read("Rultor-GoogleSecret"))) .with( new Provider() { @Override public Identity identity() throws IOException { Identity identity; if ("12345".equals(Manifests.read("Rultor-Revision"))) { identity = new Identity.Simple( URN.create("urn:facebook:1"), "Local Host", URI.create("http://img.rultor.com/none.png") ); } else { identity = Identity.ANONYMOUS; } return identity; } } ) .with(new HttpBasic(this, BaseRs.KEYS)); } /** * Get currently logged in user. * @return The user */ @NotNull(message = "User can't be NULL") protected final User user() { final Identity self = this.auth().identity(); if (self.equals(Identity.ANONYMOUS)) { throw this.flash().redirect( this.uriInfo().getBaseUri(), "please login first", Level.WARNING ); } return this.users().get(self.urn()); } /** * Get all users. * @return The users */ @NotNull(message = "USERS is not injected into servlet context") protected final Users users() { return Users.class.cast( this.servletContext().getAttribute(Users.class.getName()) ); } /** * Get repo. * @return Repo */ @NotNull(message = "REPO is not injected into servlet context") protected final Repo repo() { return Repo.class.cast( this.servletContext().getAttribute(Repo.class.getName()) ); } /** * The work we're in (while rendering). * @param unit Unit being rendered * @param spec Its spec * @return The work */ protected final Work work(final String unit, final Spec spec) { // @checkstyle AnonInnerLength (50 lines) return new Work() { @Override public Time scheduled() { return new Time(); } @Override public URN owner() { return BaseRs.this.user().urn(); } @Override public String unit() { return unit; } @Override public Spec spec() { return spec; } @Override public URI stdout() { throw new UnsupportedOperationException(); } }; } }
package com.exedio.cope.util; import java.io.IOException; import java.io.PrintStream; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.exedio.cope.Cope; import com.exedio.cope.Feature; import com.exedio.cope.IntegerField; import com.exedio.cope.Item; import com.exedio.cope.Model; import com.exedio.cope.NoSuchIDException; import com.exedio.cope.StringField; import com.exedio.cope.pattern.History; import com.exedio.cope.pattern.MapField; import com.exedio.cope.pattern.Media; import com.exedio.cope.pattern.MediaFilter; import com.exedio.cops.Cop; import com.exedio.cops.CopsServlet; public abstract class Editor implements Filter { private final Model model; /** * Subclasses must define a public no-args constructor * providing the model. */ protected Editor(final Model model) { if(model==null) throw new NullPointerException("model was null in " + getClass().getName()); this.model = model; } private ConnectToken connectToken = null; public final void init(final FilterConfig config) { connectToken = ServletUtil.connect(model, config, getClass().getName()); } public final void destroy() { connectToken.returnIt(); connectToken = null; } /** * If you want persistent http sessions, * make implementions of this interface serializable. */ public interface Login { String getName(); } protected abstract Login login(String user, String password); @SuppressWarnings("unused") protected String getBorderButtonURL(HttpServletRequest request, HttpServletResponse response, boolean bordersEnabled) { return null; } @SuppressWarnings("unused") protected String getCloseButtonURL(HttpServletRequest request, HttpServletResponse response) { return null; } @SuppressWarnings("unused") protected String getPreviousPositionButtonURL(HttpServletRequest request, HttpServletResponse response) { return null; } public final void doFilter( final ServletRequest servletRequest, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if(!(servletRequest instanceof HttpServletRequest)) { chain.doFilter(servletRequest, response); return; } final HttpServletRequest request = (HttpServletRequest)servletRequest; if(LOGIN_URL_PATH_INFO.equals(request.getPathInfo())) { servletRequest.setCharacterEncoding(CopsServlet.ENCODING); final HttpServletResponse httpResponse = (HttpServletResponse)response; final HttpSession httpSession = request.getSession(true); final Object session = httpSession.getAttribute(SESSION); if(session==null) doLogin(request, httpSession, httpResponse); else doBar(request, httpSession, httpResponse, (Session)session); return; } final HttpSession httpSession = request.getSession(false); if(httpSession!=null) { final Object session = httpSession.getAttribute(SESSION); if(session!=null) { try { tls.set(new TL(this, request, (HttpServletResponse)response, (Session)session)); chain.doFilter(request, response); } finally { tls.remove(); } } else chain.doFilter(request, response); } else { chain.doFilter(request, response); } } private static final void redirectHome( final HttpServletRequest request, final HttpServletResponse response) throws IOException { response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + request.getServletPath() + '/')); } static final String AVOID_COLLISION = "contentEditorBar823658617"; static final String REFERER = "referer"; private static final String BORDERS_ON = "bordersOn"; private static final String BORDERS_OFF = "bordersOff"; static final String CLOSE = "close"; static final String SAVE_FEATURE = "feature"; static final String SAVE_ITEM = "item"; static final String SAVE_TEXT = "text"; static final String SAVE_FILE = "file"; static final String SAVE_ITEM_FROM = "itemPrevious"; static final String PREVIEW = "preview"; private static final String CLOSE_IMAGE = CLOSE + ".x"; private static final String BORDERS_ON_IMAGE = BORDERS_ON + ".x"; private static final String BORDERS_OFF_IMAGE = BORDERS_OFF + ".x"; @SuppressWarnings("deprecation") private static final boolean isMultipartContent(final HttpServletRequest request) { return ServletFileUpload.isMultipartContent(request); } private final void doBar( final HttpServletRequest request, final HttpSession httpSession, final HttpServletResponse response, final Session session) throws IOException { if(!Cop.isPost(request)) { redirectHome(request, response); return; } final String referer; if(isMultipartContent(request)) { final HashMap<String, String> fields = new HashMap<String, String>(); final HashMap<String, FileItem> files = new HashMap<String, FileItem>(); final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(CopsServlet.ENCODING); try { for(Iterator<?> i = upload.parseRequest(request).iterator(); i.hasNext(); ) { final FileItem item = (FileItem)i.next(); if(item.isFormField()) fields.put(item.getFieldName(), item.getString(CopsServlet.ENCODING)); else files.put(item.getFieldName(), item); } } catch(FileUploadException e) { throw new RuntimeException(e); } final String featureID = fields.get(SAVE_FEATURE); if(featureID==null) throw new NullPointerException(); final Media feature = (Media)model.getFeature(featureID); if(feature==null) throw new NullPointerException(featureID); final String itemID = fields.get(SAVE_ITEM); if(itemID==null) throw new NullPointerException(); final FileItem file = files.get(SAVE_FILE); try { model.startTransaction(getClass().getName() + "#saveFile(" + featureID + ',' + itemID + ')'); final Item item = model.getItem(itemID); for(final History history : History.getHistories(item.getCopeType())) { final History.Event event = history.createEvent(item, session.loginName, false); event.createFeature( feature, feature.getName(), feature.isNull(item) ? null : ("file type=" + feature.getContentType(item) + " size=" + feature.getLength(item)), "file name=" + file.getName() + " type=" + file.getContentType() + " size=" + file.getSize()); } // TODO use more efficient setter with File or byte[] feature.set(item, file.getInputStream(), file.getContentType()); model.commit(); } catch(NoSuchIDException e) { throw new RuntimeException(e); } finally { model.rollbackIfNotCommitted(); } referer = fields.get(REFERER); } else // isMultipartContent { if(request.getParameter(BORDERS_ON)!=null || request.getParameter(BORDERS_ON_IMAGE)!=null) { session.borders = true; } else if(request.getParameter(BORDERS_OFF)!=null || request.getParameter(BORDERS_OFF_IMAGE)!=null) { session.borders = false; } else if(request.getParameter(CLOSE)!=null || request.getParameter(CLOSE_IMAGE)!=null) { httpSession.removeAttribute(SESSION); } else { final String featureID = request.getParameter(SAVE_FEATURE); if(featureID==null) throw new NullPointerException(); final Feature featureO = model.getFeature(featureID); if(featureO==null) throw new NullPointerException(featureID); final String itemID = request.getParameter(SAVE_ITEM); if(itemID==null) throw new NullPointerException(); if(featureO instanceof StringField) { final StringField feature = (StringField)featureO; final String value = request.getParameter(SAVE_TEXT); try { model.startTransaction(getClass().getName() + "#saveText(" + featureID + ',' + itemID + ')'); final Item item = model.getItem(itemID); if(request.getParameter(PREVIEW)!=null) { session.setPreview(value, feature, item); } else { String v = value; if("".equals(v)) v = null; for(final History history : History.getHistories(item.getCopeType())) { final History.Event event = history.createEvent(item, session.loginName, false); event.createFeature(feature, feature.getName(), feature.get(item), v); } feature.set(item, v); session.notifySaved(feature, item); } model.commit(); } catch(NoSuchIDException e) { throw new RuntimeException(e); } finally { model.rollbackIfNotCommitted(); } } else { final IntegerField feature = (IntegerField)featureO; final String itemIDFrom = request.getParameter(SAVE_ITEM_FROM); if(itemIDFrom==null) throw new NullPointerException(); try { model.startTransaction(getClass().getName() + "#savePosition(" + featureID + ',' + itemIDFrom + + ',' + itemID + ')'); final Item itemFrom = model.getItem(itemIDFrom); final Item itemTo = model.getItem(itemID); final Integer positionFrom = feature.get(itemFrom); final Integer positionTo = feature.get(itemTo); feature.set(itemFrom, feature.getMinimum()); feature.set(itemTo, positionFrom); feature.set(itemFrom, positionTo); for(final History history : History.getHistories(itemFrom.getCopeType())) { final History.Event event = history.createEvent(itemFrom, session.loginName, false); event.createFeature(feature, feature.getName(), positionFrom, positionTo); } for(final History history : History.getHistories(itemTo.getCopeType())) { final History.Event event = history.createEvent(itemTo, session.loginName, false); event.createFeature(feature, feature.getName(), positionTo, positionFrom); } model.commit(); } catch(NoSuchIDException e) { throw new RuntimeException(e); } finally { model.rollbackIfNotCommitted(); } } } referer = request.getParameter(REFERER); } if(referer!=null) response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + request.getServletPath() + referer)); } static final String LOGIN_URL = "contentEditorLogin.html"; private static final String LOGIN_URL_PATH_INFO = '/' + LOGIN_URL; static final String LOGIN = "login"; static final String LOGIN_USER = "user"; static final String LOGIN_PASSWORD = "password"; private final void doLogin( final HttpServletRequest request, final HttpSession httpSession, final HttpServletResponse response) throws IOException { assert httpSession!=null; PrintStream out = null; try { response.setContentType("text/html; charset="+CopsServlet.ENCODING); if(Cop.isPost(request) && request.getParameter(LOGIN)!=null) { final String user = request.getParameter(LOGIN_USER); final String password = request.getParameter(LOGIN_PASSWORD); try { model.startTransaction(getClass().getName() + "#login"); final Login login = login(user, password); if(login!=null) { final String name = login.getName(); httpSession.setAttribute(SESSION, new Session(login, name)); redirectHome(request, response); } else { out = new PrintStream(response.getOutputStream(), false, CopsServlet.ENCODING); Editor_Jspm.writeLogin(out, response, user); } model.commit(); } finally { model.rollbackIfNotCommitted(); } } else { out = new PrintStream(response.getOutputStream(), false, CopsServlet.ENCODING); Editor_Jspm.writeLogin(out, response, null); } } finally { if(out!=null) out.close(); } } private static final String SESSION = Session.class.getCanonicalName(); static final class Session implements Serializable // for session persistence { private static final long serialVersionUID = 1l; final Login login; final String loginName; boolean borders = false; final HashMap<Preview, String> previews = new HashMap<Preview, String>(); Session(final Login login, final String loginName) { this.login = login; this.loginName = loginName; assert login!=null; } private static final class Preview implements Serializable // for session persistence { private static final long serialVersionUID = 1l; final String feature; final Item item; Preview(final StringField feature, final Item item) { this.feature = feature.getID(); // id is serializable this.item = item; assert feature!=null; assert item!=null; } @Override public int hashCode() { return feature.hashCode() ^ item.hashCode(); } @Override public boolean equals(final Object other) { if(!(other instanceof Preview)) return false; final Preview o = (Preview)other; return feature.equals(o.feature) && item.equals(o.item); } } int getPreviewNumber() { return previews.size(); } String getPreview(final StringField feature, final Item item) { if(previews.isEmpty()) // shortcut return null; return previews.get(new Preview(feature, item)); } void setPreview(final String content, final StringField feature, final Item item) { previews.put(new Preview(feature, item), content); } void notifySaved(final StringField feature, final Item item) { previews.remove(new Preview(feature, item)); } @Override public String toString() { final StringBuilder bf = new StringBuilder(); // must not call login#getName() here, // because this may require a transaction, // which may not be present, // especially when this method is called by lamdba probe. if(loginName!=null) bf.append('"').append(loginName).append('"'); else bf.append(login.getClass().getName()); if(borders) bf.append(" bordered"); final int previewNumber = previews.size(); if(previewNumber>0) { bf.append(" *"); if(previewNumber>1) bf.append(previewNumber); } return bf.toString(); } } private static final class TL { final Editor filter; final HttpServletRequest request; final HttpServletResponse response; final Session session; private HashMap<IntegerField, Item> positionItems = null; TL( final Editor filter, final HttpServletRequest request, final HttpServletResponse response, final Session session) { this.filter = filter; this.request = request; this.response = response; this.session = session; assert filter!=null; assert request!=null; assert response!=null; assert session!=null; } Item registerPositionItem(final IntegerField feature, final Item item) { final Integer next = feature.get(item); if(next==null) return null; if(positionItems==null) positionItems = new HashMap<IntegerField, Item>(); final Item result = positionItems.put(feature, item); if(result==null) return null; final Integer previous = feature.get(result); return (previous!=null && previous.intValue()<next.intValue()) ? result : null; } } private static final ThreadLocal<TL> tls = new ThreadLocal<TL>(); public static final boolean isLoggedIn() { return tls.get()!=null; } public static final Login getLogin() { final TL tl = tls.get(); return tl!=null ? tl.session.login : null; } @SuppressWarnings("cast") // OK: for eclipse because of the javac bug private static final <K> Item getItem(final MapField<K, String> feature, final K key, final Item item) { return (Item)feature.getRelationType().searchSingletonStrict( // cast is needed because of a bug in javac feature.getKey().equal(key).and( Cope.equalAndCast(feature.getParent(item.getCopeType().getJavaClass()), item))); } public static final <K> String edit(final String content, final MapField<K, String> feature, final Item item, final K key) { final TL tl = tls.get(); if(tl==null) return content; checkEdit(feature, item); return edit( tl, content, (StringField)feature.getValue(), getItem(feature, key, item)); } public static final String edit(final String content, final StringField feature, final Item item) { final TL tl = tls.get(); if(tl==null) return content; return edit(tl, content, feature, item); } static final String EDIT_METHOD_LINE = AVOID_COLLISION + "line"; static final String EDIT_METHOD_FILE = AVOID_COLLISION + "file"; static final String EDIT_METHOD_AREA = AVOID_COLLISION + "area"; private static final String edit(final TL tl, final String content, final StringField feature, final Item item) { checkEdit(feature, item); if(feature.isFinal()) throw new IllegalArgumentException("feature " + feature.getID() + " must not be final"); if(!tl.session.borders) { final String preview = tl.session.getPreview(feature, item); return (preview!=null) ? preview : content; } final boolean block = feature.getMaximumLength()>StringField.DEFAULT_LENGTH; final String savedContent = feature.get(item); final String pageContent; final String editorContent; final boolean previewAllowed; if(content!=null ? content.equals(savedContent) : (savedContent==null)) { previewAllowed = true; final String preview = tl.session.getPreview(feature, item); if(preview!=null) pageContent = editorContent = preview; else pageContent = editorContent = savedContent; // equals content anyway } else { previewAllowed = false; pageContent = content; editorContent = savedContent; } final String tag = block ? "div" : "span"; final String editorContentEncoded = Cop.encodeXml(editorContent); final StringBuilder bf = new StringBuilder(); bf.append('<'). append(tag). append( " class=\"contentEditorLink\"" + " onclick=\"" + "return " + (block ? EDIT_METHOD_AREA : EDIT_METHOD_LINE) + "(this,'"). append(feature.getID()). append("','"). append(item.getCopeID()). append("','"). append(block ? editorContentEncoded.replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r") : editorContentEncoded). append("'," + previewAllowed + ");\""). append('>'). append(pageContent). append("</"). append(tag). append('>'); return bf.toString(); } public static final String edit(final Media feature, final Item item) { final TL tl = tls.get(); if(tl==null || !tl.session.borders) return ""; checkEdit(feature, item); if(feature.isFinal()) throw new IllegalArgumentException("feature " + feature.getID() + " must not be final"); final StringBuilder bf = new StringBuilder(); bf.append( " class=\"contentEditorLink\"" + " onclick=\"" + "return " + EDIT_METHOD_FILE + "(this,'"). append(feature.getID()). append("','"). append(item.getCopeID()). append("','"). append(Cop.encodeXml(feature.getURL(item))). append("');\""); return bf.toString(); } public static final String edit(final MediaFilter feature, final Item item) { final TL tl = tls.get(); if(tl==null || !tl.session.borders) return ""; checkEdit(feature, item); return edit(feature.getSource(), item); } public static final String edit(final IntegerField feature, final Item item) { final TL tl = tls.get(); if(tl==null || !tl.session.borders) return ""; checkEdit(feature, item); if(feature.isFinal()) throw new IllegalArgumentException("feature " + feature.getID() + " must not be final"); final Item previousItem = tl.registerPositionItem(feature, item); if(previousItem==null) return ""; final HttpServletRequest request = tl.request; final String previousPositionButtonURL = tl.filter.getPreviousPositionButtonURL(request, tl.response); return "<form action=\"" + action(request, tl.response) + "\" method=\"POST\" class=\"contentEditorPosition\">" + "<input type=\"hidden\" name=\"" + REFERER + "\" value=\"" + referer(request) + "\">" + "<input type=\"hidden\" name=\"" + SAVE_FEATURE + "\" value=\"" + feature.getID() + "\">" + "<input type=\"hidden\" name=\"" + SAVE_ITEM_FROM + "\" value=\"" + previousItem.getCopeID() + "\">" + "<input type=\"hidden\" name=\"" + SAVE_ITEM + "\" value=\"" + item.getCopeID() + "\">" + (previousPositionButtonURL!=null ? ("<input type=\"image\" src=\"" + previousPositionButtonURL + "\" alt=\"Swap with previous item\">") : ("<input type=\"submit\" value=\"Up" /*+ " " + feature.get(previousItem) + '/' + feature.get(item)*/ + "\">") ) + "</form>"; } private static final void checkEdit(final Feature feature, final Item item) { if(feature==null) throw new NullPointerException("feature must not be null"); if(item==null) throw new NullPointerException("item must not be null"); if(!feature.getType().isAssignableFrom(item.getCopeType())) throw new IllegalArgumentException("item " + item.getCopeID() + " does not belong to type of feature " + feature.getID()); } interface Out { void print(String s); void print(int i); } public static final void writeBar(final PrintStream out) { final TL tl = tls.get(); if(tl==null) return; writeBar(tl, new Out(){ public void print(final String s) { out.print(s); } public void print(final int i) { out.print(i); } }); } public static final void writeBar(final StringBuilder out) { final TL tl = tls.get(); if(tl==null) return; writeBar(tl, new Out(){ public void print(final String s) { out.append(s); } public void print(final int i) { out.append(i); } }); } private static final void writeBar(final TL tl, final Out out) { final HttpServletRequest request = tl.request; Editor_Jspm.writeBar(out, action(request, tl.response), referer(request), tl.session.borders, tl.session.borders ? BORDERS_OFF : BORDERS_ON, tl.filter.getBorderButtonURL(request, tl.response, tl.session.borders), tl.filter.getCloseButtonURL(request, tl.response), tl.session.getPreviewNumber(), tl.session.login.getName()); } private static final String action(final HttpServletRequest request, final HttpServletResponse response) { return response.encodeURL(request.getContextPath() + request.getServletPath() + LOGIN_URL_PATH_INFO); } private static final String referer(final HttpServletRequest request) { final String queryString = request.getQueryString(); return queryString!=null ? (request.getPathInfo() + '?' + request.getQueryString()) : request.getPathInfo(); } /** * @deprecated Use {@link #isLoggedIn()} instead */ @Deprecated public static final boolean isActive() { return isLoggedIn(); } /** * @deprecated use {@link #edit(String, MapField, Item, Object)} instead. */ @Deprecated public static final <K> String editBlock(final String content, final MapField<K, String> feature, final Item item, final K key) { return edit(content, feature, item, key); } }
package org.dazeend.harmonium.music; import java.awt.Image; import java.util.Timer; import java.util.TimerTask; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.roarsoftware.lastfm.Track; import org.dazeend.harmonium.Harmonium; import org.dazeend.harmonium.ImageHelper; import org.dazeend.harmonium.LastFm; public class StreamTrackData { private final Harmonium _app; private String _tagParsedStreamTitle; private String _tagParsedStreamUrl; private static final Pattern TAG_PARSE_TITLE_PATTERN = Pattern.compile("(.+?)\\b\\s*-\\s*(.+)\\b"); private static final Pattern TAG_PARSE_TITLE_WITH_PARENS_PATTERN = Pattern.compile("(.+?)\\b\\s*-\\s*(.*)(?:\\s+\\(.*\\))"); private static final int NEXT_TAG_DELAY = 500; private final Timer _timer = new Timer("WaitForNextTagEvent", true); private Runner _runner = null; private boolean _waitingForTag = false; public StreamTrackData(Harmonium app) { _app = app; } private synchronized void waitYourTurn() { if (_runner != null) { // If the runner's already running, let it finish. while (_runner.isRunning()) { try { Thread.sleep(100); } catch (InterruptedException e) { // do nothing } } _runner.cancel(); } _runner = new Runner(); if (!_waitingForTag) { _tagParsedStreamTitle = null; _tagParsedStreamUrl = null; } _waitingForTag = !_waitingForTag; _timer.schedule(_runner, NEXT_TAG_DELAY); } public synchronized void setTagParsedStreamTitle(String streamTitle) { String fixed = streamTitle.replace('`', '\''); waitYourTurn(); _tagParsedStreamTitle = fixed; } public synchronized void setTagParsedStreamUrl(String streamUrl) { waitYourTurn(); _tagParsedStreamUrl = streamUrl; } private class Runner extends TimerTask { private boolean _running = false; private Image _img; private String _artHashKey; private String _tagParsedArtist; private String _tagParsedTrackName; public boolean isRunning() { return _running; } @Override public void run() { _running = true; try { realRun(); } finally { _running = false; } } private void realRun() { Track track = null; getArtFromUrl(); if (_tagParsedStreamTitle != null) { Matcher m = TAG_PARSE_TITLE_WITH_PARENS_PATTERN.matcher(_tagParsedStreamTitle); track = parseArtistAndTrack(m); if (track == null) { m = TAG_PARSE_TITLE_PATTERN.matcher(_tagParsedStreamTitle); track = parseArtistAndTrack(m); } if (_app.isInDebugMode()) { if (track == null) System.out.println("Failed to retrieve last.fm info for stream: " + _tagParsedStreamTitle); else { System.out.println("Successfully retrieved last.fm info for stream: " + _tagParsedStreamTitle); } } } BasicArtSource art = null; if (_img != null) art = new BasicArtSource(_img, _artHashKey); else art = new BasicArtSource(null, null); if (track != null) _app.getDiscJockey().streamTrackDataChanged(art, track.getArtist(), _tagParsedArtist, track.getAlbum(), _tagParsedTrackName, 0); else _app.getDiscJockey().streamTrackDataChanged(art, _tagParsedArtist, _tagParsedArtist, null, _tagParsedTrackName, 0); _app.flush(); } private Track parseArtistAndTrack(Matcher m) { if (_tagParsedStreamTitle == null || _tagParsedStreamTitle.isEmpty()) return null; if (m.lookingAt()) { if (_app.isInDebugMode()) { System.out.println("Parsed Artist: [" + m.group(1) + "]"); System.out.println(" Parsed Track: [" + m.group(2) + "]"); } Track lastFmTrack = LastFm.fetchTrackInfo(m.group(1), m.group(2)); if (lastFmTrack != null) { _tagParsedArtist = m.group(1); _tagParsedTrackName = m.group(2); if (_img == null) { _img = LastFm.fetchArtForTrack(lastFmTrack); if (ImageHelper.imageIsValid(_img)) _artHashKey = _tagParsedStreamTitle; else _img = null; } return lastFmTrack; } } return null; } private void getArtFromUrl() { if (_tagParsedStreamUrl == null || _tagParsedStreamUrl.isEmpty()) return; _img = ImageHelper.getImageFromUrl(_app, _tagParsedStreamUrl); if (_img != null) _artHashKey = _tagParsedStreamUrl; } } }
package org.myrobotlab.framework; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.net.URI; import java.net.URISyntaxException; import org.junit.Test; public class EncoderTest { @Test public void testEncoderDecodeURI() { Encoder e = new Encoder(); try { // create and start a service named foo, decode a url for that service. org.myrobotlab.service.Test testService = new org.myrobotlab.service.Test("foo"); testService.startService(); Message m = e.decodeURI(new URI("http: assertNotNull(m); assertEquals("foo",m.getName()); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }
package osmTileMachine; import java.io.File; import java.lang.System; import java.util.ArrayList; public class MainClass { public static void main(String[] args) throws Exception { ActionList mainActionList = new ActionList(); Configuration sessionConfiguration = new Configuration(); sessionConfiguration.parseInputArguments(args); ActionList deleteDownlodedFileActionList = new ActionList(); ActionList deleteUpdatedFileActionList = new ActionList(); if (sessionConfiguration.getSourceType() == sessionConfiguration.SOURCETYPE_DOWNLOAD) { String newSourceFileName = sessionConfiguration.getWorkingDirectory() + File.separator + "datasource.pbf"; mainActionList.addItem(new DownloadAction(newSourceFileName, OpenStreetMapProject.getSourceFileMirrors(sessionConfiguration, sessionConfiguration.getSource()))); sessionConfiguration.setSource(newSourceFileName); DeleteFileSetAction delFileSetAction = new DeleteFileSetAction(); delFileSetAction.addFileName(newSourceFileName); deleteDownlodedFileActionList.addItem(delFileSetAction); } else if (sessionConfiguration.getSourceType() == sessionConfiguration.SOURCETYPE_URL) { String newSourceFileName = sessionConfiguration.getWorkingDirectory() + File.separator + "datasource.pbf"; ArrayList<String> addressList = new ArrayList<String>(); addressList.add(sessionConfiguration.getSource()); mainActionList.addItem(new DownloadAction(newSourceFileName,addressList)); sessionConfiguration.setSource(newSourceFileName); DeleteFileSetAction delFileSetAction = new DeleteFileSetAction(); delFileSetAction.addFileName(newSourceFileName); deleteDownlodedFileActionList.addItem(delFileSetAction); } if (sessionConfiguration.getUpdate()) { String newSourceFileName = sessionConfiguration.getWorkingDirectory() + File.separator + "datasource_updated.pbf"; mainActionList.addItem(new DataUpdateAction(sessionConfiguration.getSource(), newSourceFileName)); if (!sessionConfiguration.getKeepDownload()) { mainActionList.append(deleteDownlodedFileActionList); } sessionConfiguration.setSource(newSourceFileName); DeleteFileSetAction delFileSetAction = new DeleteFileSetAction(); delFileSetAction.addFileName(newSourceFileName); deleteUpdatedFileActionList.addItem(delFileSetAction); } //Merge the two actionlist to one common "remove source action list" ActionList deleteSourceFilesActionList = new ActionList(); deleteSourceFilesActionList.append (deleteDownlodedFileActionList); deleteSourceFilesActionList.append (deleteUpdatedFileActionList); if (sessionConfiguration.getRender()) { TileSet ts = new TileSet(); ts.addSet(Geography.getTileSetForRegion(sessionConfiguration.getRequestedArea())); ActionList splitAndRenderActionList = SplitAndRenderStrategy.CreateActionList(sessionConfiguration, ts, sessionConfiguration.getSource(), deleteSourceFilesActionList); mainActionList.append(splitAndRenderActionList); } mainActionList.PrintListInHumanReadableFormat(sessionConfiguration); System.out.println("Executing actionlist..."); int i = 0; while (mainActionList.actionsLeft()){ System.out.print("(" + (i+1) + "/"+ mainActionList.originalSize() +") "); if (i < (sessionConfiguration.getFirstAction()-1) ) { mainActionList.getNextAction(); //Debug ability to skip early actions, or for resuming aborted operations System.out.println("Skipped"); } else { Action a = mainActionList.getNextAction(); System.out.println(" " + a.getActionInHumanReadableFormat()); a.runAction(sessionConfiguration); } i++; } System.out.println("OSMTileMachine completed."); System.exit(0); } }
package org.myrobotlab.framework; import static org.junit.Assert.*; import java.util.Arrays; import java.util.concurrent.BlockingQueue; import org.junit.BeforeClass; import org.junit.Test; import org.myrobotlab.logging.Appender; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.Runtime; import org.myrobotlab.service.TestCatcher; import org.myrobotlab.service.TestThrower; import org.myrobotlab.service.interfaces.CommunicationInterface; import org.slf4j.Logger; public class MessageTest { public final static Logger log = LoggerFactory.getLogger(MessageTest.class); static TestCatcher catcher; static TestThrower thrower; @BeforeClass public static void setUpBeforeClass() throws Exception { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.INFO); catcher = (TestCatcher)Runtime.start("catcher", "TestCatcher"); thrower = (TestThrower)Runtime.start("thrower", "TestThrower"); } @Test public void simpleSubscribeAndThrow() throws Exception { catcher.clear(); catcher.subscribe("thrower", "pitch"); // ROUTE MUST STABALIZE - BEFORE MSGS - otherwise they will be missed Service.sleep(100); thrower.pitchInt(1000); BlockingQueue<Message> balls = catcher.waitForMsgs(1000); log.warn(String.format("caught %d balls", balls.size())); log.warn(String.format("left balls %d ", catcher.msgs.size())); } @Test public void broadcastMessage() throws Exception { catcher.clear(); catcher.subscribe("thrower", "pitch"); Message msg = thrower.createMessage(null, "getServiceNames", null); CommunicationInterface comm = thrower.getComm(); comm.send(msg); String[] ret = (String[])thrower.invoke(msg); log.info(String.format("got %s", Arrays.toString(ret))); assertNotNull(ret); } /** * test to verify we can remove all message routes * @throws Exception */ @Test public final void clearRoutes() throws Exception { catcher.clear(); catcher.subscribe("thrower", "pitch"); // "long" pause to make sure our message route is in Service.sleep(100); thrower.pitchInt(1000); BlockingQueue<Message> balls = catcher.waitForMsgs(1000); log.warn(String.format("caught %d balls", balls.size())); log.warn(String.format("left balls %d ", catcher.msgs.size())); Runtime.removeAllSubscriptions(); Message msg = thrower.createMessage(null, "getServiceNames", null); CommunicationInterface comm = thrower.getComm(); comm.send(msg); String[] ret = (String[])thrower.invoke(msg); log.info(String.format("got %s", Arrays.toString(ret))); assertNotNull(ret); catcher.clear(); // "long" pause to make sure our message route is in Service.sleep(100); thrower.pitchInt(1000); Service.sleep(100); assertEquals(0, catcher.msgs.size()); } @Test final public void badNameTest() throws Exception { catcher.clear(); TestCatcher catcher2 = null; try { Runtime.start("myName/isGeorge", "TestCatcher"); } catch (Exception e){ // Logging.logError(e); log.info("good bad name threw"); } assertNull(catcher2); } @Test final public void invokeStringNotation() throws Exception { catcher.clear(); // FIXME - implement // catcher.subscribe("thrower/pitch"); catcher.clear(); catcher.subscribe("thrower", "pitch"); Service.sleep(100); thrower.pitchInt(1000); BlockingQueue<Message> balls = catcher.waitForMsgs(1000); assertEquals(1000, balls.size()); /* Runtime runtime = Runtime.getInstance(); Message msg = thrower.createMessage(null, "getServiceNames", null); CommunicationInterface comm = thrower.getComm(); comm.send(msg); String[] ret = (String[])thrower.invoke(msg); log.info(String.format("got %s", Arrays.toString(ret))); assertNotNull(ret); */ } /** * test to excercise * @throws Exception */ @Test final public void RuntimeTests() throws Exception { catcher.clear(); // FIXME - implement // catcher.subscribe("thrower/pitch"); catcher.clear(); catcher.subscribe("thrower", "pitch"); Service.sleep(100); thrower.pitchInt(1000); BlockingQueue<Message> balls = catcher.waitForMsgs(1000); Runtime runtime = Runtime.getInstance(); Message msg = thrower.createMessage(null, "getServiceNames", null); CommunicationInterface comm = thrower.getComm(); comm.send(msg); String[] ret = (String[])thrower.invoke(msg); log.info(String.format("got %s", Arrays.toString(ret))); assertNotNull(ret); } public static void main(String[] args) { try { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.DEBUG); Logging logging = LoggingFactory.getInstance(); logging.addAppender(Appender.FILE); setUpBeforeClass(); //clearRoutes(); // badNameTest(); // invokeStringNotation(); } catch(Exception e){ Logging.logError(e); } System.exit(0); } }
package org.sagebionetworks.bridge; import static org.sagebionetworks.bridge.TestConstants.TEST_BASE_URL; import java.util.Map; import java.util.concurrent.Callable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import play.libs.WS; import play.libs.WS.WSRequestHolder; public class TestUtils { private static Logger logger = LoggerFactory.getLogger(TestUtils.class); public abstract static class FailableRunnable implements Runnable { public abstract void testCode() throws Exception; @Override public void run() { try { testCode(); } catch (Exception e) { throw new RuntimeException(e); } } } public static WSRequestHolder getURL(String sessionToken, String path) { return getURL(sessionToken, path, null); } public static WSRequestHolder getURL(String sessionToken, String path, Map<String,String> queryMap) { WSRequestHolder request = WS.url(TEST_BASE_URL + path).setHeader(BridgeConstants.SESSION_TOKEN_HEADER, sessionToken); if (queryMap != null) { for (Map.Entry<String,String> entry : queryMap.entrySet()) { request.setQueryParameter(entry.getKey(), entry.getValue()); } } return request; } // Waiting for that eventual consistency to ensure the test passes every time. // 3x with the correct answer is assumed to be propagated. public static void waitFor(Callable<Boolean> callable) throws Exception { int delay = 400; int loopLimit = 40; int successesLimit = 3; int loops = 0; int successes = 0; while (successes < successesLimit && loops < loopLimit) { if (callable.call()) { successes++; } else { successes = 0; } loops++; String msg = String.format("waitFor sleeping %sms (%s/%s successes after loop %s/%s)", delay, successes, successesLimit, loops, loopLimit); logger.info(msg); System.out.println(msg); Thread.sleep(delay); } } /* This waited for one right answer, then slept, then continued, it was pretty reliable * but not 100% reliable. public static void waitForOriginal(Callable<Boolean> callable) throws Exception { int countdown = 20; boolean processing = true; while(countdown-- > 0 && processing) { Thread.sleep(200); processing = !callable.call(); } // And then, it seems there's an issue with eventual consistency, even after // the system returns at least one desired state change. Possible with DynamoDB? System.out.println("Waiting 2s after condition was true for eventual consistency(?)"); Thread.sleep(2000); }*/ }
package org.broad.igv.tools; import org.broad.igv.AbstractHeadlessTest; import org.broad.igv.data.Dataset; import org.broad.igv.data.WiggleDataset; import org.broad.igv.data.WiggleParser; import org.broad.igv.data.expression.ExpressionFileParser; import org.broad.igv.feature.LocusScore; import org.broad.igv.feature.genome.FastaIndex; import org.broad.igv.feature.genome.Genome; import org.broad.igv.feature.tribble.CodecFactory; import org.broad.igv.sam.Alignment; import org.broad.igv.sam.reader.AlignmentReader; import org.broad.igv.sam.reader.AlignmentReaderFactory; import org.broad.igv.sam.reader.FeatureIndex; import org.broad.igv.sam.reader.SamUtils; import org.broad.igv.tdf.TDFDataSource; import org.broad.igv.tdf.TDFDataset; import org.broad.igv.tdf.TDFReader; import org.broad.igv.tdf.TDFTile; import org.broad.igv.tools.sort.SorterTest; import org.broad.igv.track.WindowFunction; import org.broad.igv.util.FileUtils; import org.broad.igv.util.ResourceLocator; import org.broad.igv.util.TestUtils; import org.broad.tribble.AbstractFeatureReader; import org.broad.tribble.Feature; import org.broad.tribble.FeatureCodec; import org.broad.tribble.index.Block; import org.broad.tribble.index.Index; import org.broad.tribble.index.IndexFactory; import org.broadinstitute.sting.utils.codecs.vcf.VCF3Codec; import org.broadinstitute.sting.utils.codecs.vcf.VCFCodec; import org.broadinstitute.sting.utils.variantcontext.VariantContext; import org.junit.*; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import java.io.*; import java.util.*; import static junit.framework.Assert.*; public class IGVToolsTest extends AbstractHeadlessTest { IgvTools igvTools; private static final String hg18id = TestUtils.DATA_DIR + "genomes/hg18.unittest.genome"; private static final int MAX_LINES_CHECK = 200; @Rule public TestRule testTimeout = new Timeout((int) 1e3 * 60 * 20); @Before public void setUp() throws Exception { super.setUp(); igvTools = new IgvTools(); } @After public void tearDown() throws Exception { super.tearDown(); igvTools = null; } private String doStandardIndex(String inputFile, String expectedExtension) throws IOException { String indDir = TestUtils.TMP_OUTPUT_DIR; TestUtils.clearOutputDir(); String indPath = igvTools.doIndex(inputFile, indDir, IgvTools.LINEAR_INDEX, IgvTools.LINEAR_BIN_SIZE); File indFile = new File(indPath); //Check that only the index file we intended exists assertTrue(indFile.exists()); assertTrue(indPath.endsWith(expectedExtension)); final Set<String> exts = new HashSet<String>(); for (String ext : new String[]{".idx", ".sai", ".bai", ".fai"}) { exts.add(ext); } File[] files = (new File(indDir)).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return exts.contains((Preprocessor.getExtension(name))); } }); assertEquals("Extra files in output directory", 1, files.length); return indFile.getAbsolutePath(); } @Test public void testIndexSam() throws Exception { String samFile = TestUtils.DATA_DIR + "sam/NA12878.muc1.test2.sam"; String samFileIdx = doStandardIndex(samFile, "sai"); FeatureIndex idx = SamUtils.getIndexFor(samFile); assertTrue(idx.containsChromosome("chr1")); assertEquals(1, idx.getIndexedChromosomes().size()); } @Test public void testIndexFasta() throws Exception { String inFile = TestUtils.DATA_DIR + "fasta/ecoli_out.padded2.fasta"; String indPath = doStandardIndex(inFile, "fai"); FastaIndex index = new FastaIndex(indPath); assertEquals(1, index.getSequenceNames().size()); assertNotNull(index.getIndexEntry("NC_000913_bb")); } @Test public void testLinearIndex() throws IOException { String bedFile = TestUtils.DATA_DIR + "bed/test.bed"; String idxPath = doStandardIndex(bedFile, "idx"); Index idx = IndexFactory.loadIndex(idxPath); List<Block> blocks = idx.getBlocks("chr1", 100, 200); Block block = blocks.get(0); assertEquals("Unexpected start position ", 0, block.getStartPosition()); } @Test public void testIntervalIndex33() throws Exception { String testFile = TestUtils.LARGE_DATA_DIR + "CEU.SRP000032.2010_03_v3.3.genotypes.head.vcf"; FeatureCodec codec = new VCF3Codec(); tstIntervalIndex(testFile, codec); } @Test public void testIntervalIndex40() throws Exception { String testFile = TestUtils.LARGE_DATA_DIR + "CEU.SRP000032.2010_03_v4.0.genotypes.head.vcf"; FeatureCodec codec = new VCFCodec(); tstIntervalIndex(testFile, codec); } private void tstIntervalIndex(String testFile, FeatureCodec codec) throws IOException { // Create an interval tree index with 5 features per interval File indexFile = new File(testFile + ".idx"); if (indexFile.exists()) { indexFile.delete(); } igvTools.doIndex(testFile, null, 2, 5); indexFile.deleteOnExit(); // Now use the index String chr = "1"; int start = 1718546; int end = 1748915; int[] expectedStarts = {1718547, 1718829, 1723079, 1724830, 1731376, 1733967, 1735586, 1736016, 1738594, 1739272, 1741124, 1742815, 1743224, 1748886, 1748914}; AbstractFeatureReader bfr = AbstractFeatureReader.getFeatureReader(testFile, codec); Iterator<VariantContext> iter = bfr.query(chr, start, end); int count = 0; while (iter.hasNext()) { VariantContext feat = iter.next(); int expStart = expectedStarts[count]; assertEquals(expStart, feat.getStart()); count++; } Assert.assertEquals(15, count); } @Test public void testVersion() throws IOException { String[] args = {"version"}; //IgvTools.main(args); igvTools.run(args); } @Test public void testTileWigFile() throws IOException { String inputFile = TestUtils.LARGE_DATA_DIR + "phastCons_chr1.wig"; testTile(inputFile, 0, 0); } @Test public void testTileCNFile() throws IOException { String inputFile = TestUtils.DATA_DIR + "cn/HindForGISTIC.hg16.cn"; testTile(inputFile, 5000000, 5500000); } @Test public void testTileGCT() throws IOException { String inputFile = TestUtils.DATA_DIR + "gct/OV.transcriptome__agilentg4502.data.txt"; String outFilePath = TestUtils.DATA_DIR + "out/testTileGCT.wig"; String genome = TestUtils.DATA_DIR + "genomes/hg18.unittest.genome"; String[] args = {"tile", "-z", "1", "--fileType", "mage-tab", inputFile, outFilePath, hg18id}; igvTools.run(args); inputFile = TestUtils.DATA_DIR + "gct/GBM.methylation__sampled.data.txt"; args = new String[]{"tile", "-z", "1", "--fileType", "mage-tab", inputFile, outFilePath, hg18id}; igvTools.run(args); } private void testTile(String inputFile, int start, int end) throws IOException { String file1 = TestUtils.DATA_DIR + "out/file1.tdf"; String file2 = TestUtils.DATA_DIR + "out/file2.tdf"; //todo Compare 2 outputs more meaningfully String[] args = {"toTDF", "-z", "1", "--windowFunctions", "min", inputFile, file1, hg18id}; igvTools.run(args); args = new String[]{"toTDF", "-z", "2", "--windowFunctions", "max", inputFile, file2, hg18id}; (new IgvTools()).run(args); String dsName = "/chr1/raw"; TDFDataset ds1 = TDFReader.getReader(file1).getDataset(dsName); TDFDataset ds2 = TDFReader.getReader(file2).getDataset(dsName); TDFTile t1 = ds1.getTiles(start, end).get(0); TDFTile t2 = ds2.getTiles(start, end).get(0); int nPts = t1.getSize(); assertEquals(nPts, t2.getSize()); for (int i = 0; i < nPts; i++) { assertTrue(t1.getStartPosition(i) < t1.getEndPosition(i)); assertEquals(t1.getStartPosition(i), t2.getStartPosition(i)); assertTrue(t1.getValue(0, i) <= t2.getValue(0, i)); if (i < nPts - 1) { assertTrue(t1.getStartPosition(i) < t1.getStartPosition(i + 1)); } } (new File(file1)).delete(); (new File(file2)).delete(); } @Test public void testCountTDF() throws Exception { String inputFile = TestUtils.DATA_DIR + "bed/Unigene.sample.sorted.bed"; tstCountStrandOpts(inputFile, "testtdf", "tdf", null, -1, -1); } @Test public void testCountWIG() throws Exception { String inputFile = TestUtils.DATA_DIR + "bed/Unigene.sample.sorted.bed"; tstCountStrandOpts(inputFile, "testwig", "wig", null, -1, -1); tstCountStrandOpts(inputFile, "testwig", "wig", "chr2", 178709699, 179008373); tstCountStrandMapOpts(inputFile, "testwig", "wig", null, -1, -1); tstCountStrandMapOpts(inputFile, "testwig", "wig", "chr2", 178709699, 179008373); } @Test public void testCountSAM() throws Exception { String inputFile = TestUtils.DATA_DIR + "sam/test_2.sam"; tstCountStrandOpts(inputFile, "testwig", "wig", null, -1, -1); } @Test public void testCountBAM() throws Exception { String inputFile = TestUtils.DATA_DIR + "bam/NA12878.SLX.sample.bam"; tstCountStrandOpts(inputFile, "testwig", "wig", null, -1, -1); tstCountStrandMapOpts(inputFile, "testwig", "wig", null, -1, -1); } public void tstCountStrandOpts(String inputFile, String outputBase, String outputExt, String chr, int start, int end) throws Exception { String[] opts = new String[]{"--bases", "--strands=read", "--strands=first", "--strands=read --bases"}; tstCountOptsGen(inputFile, outputBase, outputExt, chr, start, end, "", opts); } public void tstCountStrandMapOpts(String inputFile, String outputBase, String outputExt, String chr, int start, int end) throws Exception { String refOpt = "--minMapQuality 1"; String[] opts = new String[]{"--strands=read " + refOpt, "--bases " + refOpt}; tstCountOptsGen(inputFile, outputBase, outputExt, chr, start, end, refOpt, opts); } /** * Compare the output of count with the various options against the output of {@code refOpt}. That is, * we assume the row total for each will be equal. * * @param inputFile * @param outputBase * @param outputExt * @param chr * @param start * @param end * @param opts */ public void tstCountOptsGen(String inputFile, String outputBase, String outputExt, String chr, int start, int end, String refOpt, String[] opts) throws Exception { boolean query = chr != null && start >= 0 && end >= start + 1; String outputFile = TestUtils.TMP_OUTPUT_DIR + outputBase + "_"; Map<String, float[]> rowTotals = new HashMap<String, float[]>(opts.length + 1); String[] allOpts = new String[opts.length + 1]; allOpts[0] = refOpt; System.arraycopy(opts, 0, allOpts, 1, opts.length); for (int ind = 0; ind < allOpts.length; ind++) { String opt = allOpts[ind]; int winsize = 5; if (query) { opt += " --windowSize " + winsize + " --query " + chr + ":" + start + "-" + end; } //In case me modify the option for querying as above if (ind == 0) refOpt = opt; String fullout = outputFile + ind + "." + outputExt; String input = "count " + opt + " " + inputFile + " " + fullout + " " + hg18id; String[] args = input.split("\\s+"); igvTools.run(args); if (outputExt.equals("tdf")) { TDFReader reader = TDFReader.getReader(fullout); assertTrue(reader.getDatasetNames().size() > 0); if (query) { for (String name : reader.getDatasetNames()) { TDFDataset ds = reader.getDataset(name); List<TDFTile> tiles = ds.getTiles(); for (TDFTile tile : tiles) { assertTrue(tile.getTileStart() >= start); assertTrue(tile.getTileStart() < end); } } } } else { File outFile = new File(fullout); assertTrue(outFile.exists()); assertTrue(outFile.canRead()); ResourceLocator locator = new ResourceLocator(fullout); WiggleDataset ds = (new WiggleParser(locator, IgvTools.loadGenome(hg18id, true))).parse(); //We miss a few alignments with this option sometimes, //so it doesn't total up the same if (!opt.contains("strands=first")) { float[] linetotals = getLineTotals(fullout); rowTotals.put(opt, linetotals); } if (query) { assertEquals(1, ds.getChromosomes().length); assertEquals(chr, ds.getChromosomes()[0]); int[] starts = ds.getStartLocations(chr); for (Integer act_start : starts) { assertTrue(act_start + " is outside range", act_start >= start - winsize && act_start < end + winsize); } } } } //Compare row totals //They should all add up the same float[] refTotals = rowTotals.get(refOpt); for (String opt : rowTotals.keySet()) { if (opt.equals(refOpt)) { continue; } float[] testTotals = rowTotals.get(opt); assertEquals(refTotals.length, testTotals.length); for (int rw = 0; rw < refTotals.length; rw++) { float diff = refTotals[rw] - testTotals[rw]; String msg = "Difference between " + refTotals[rw] + " and " + testTotals[rw] + " too high. "; msg += "Row " + rw + ". Test option " + opt; //This can get pretty high, we only use 2 digits of precision //Also test this in CoverageCounterTest assertTrue(msg, Math.abs(diff) <= 0.1); } } } /** * Calculates the sum of each row, excluding the first column. * Skips non-numeric rows * * @param filename * @return */ private float[] getLineTotals(String filename) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(filename)); String line = ""; float tmpsum; List<Float> sums = new ArrayList<Float>(); while ((line = reader.readLine()) != null && sums.size() < MAX_LINES_CHECK) { try { String[] tokens = line.split("\\t"); tmpsum = 0; for (int ii = 1; ii < tokens.length; ii++) { tmpsum += Float.parseFloat(tokens[ii]); } sums.add(tmpsum); } catch (NumberFormatException e) { continue; } } reader.close(); float[] toret = new float[sums.size()]; for (int ii = 0; ii < sums.size(); ii++) { toret[ii] = sums.get(ii); } return toret; } public static String[] generateRepLargebamsList(String listPath, String bamFiName, int reps) throws IOException { return generateRepLargebamsList(listPath, bamFiName, reps, false); } /* Generate a bam.list file, with rep entries, all having the same content bamPath. If makeAbsolute is true and bamPath not absolute, the listPath parent directory is prepended. The file is saved to listPath */ public static String[] generateRepLargebamsList(String listPath, String bamPath, int reps, boolean makeAbsolute) throws IOException { File listFile = new File(listPath); listFile.delete(); listFile.deleteOnExit(); File f = new File(bamPath); String eachPath = null; if (makeAbsolute && !f.isAbsolute()) { eachPath = FileUtils.getAbsolutePath(bamPath, listPath); } else { eachPath = f.getPath(); } //We generate the file on each test, because largedata dir can change List<String> largebams = new ArrayList<String>(reps); for (int ii = 0; ii < reps; ii++) { largebams.add(eachPath); } FileWriter writer = new FileWriter(listFile); for (String s : largebams) { writer.write(s + "\n"); } writer.close(); return largebams.toArray(new String[0]); } /** * Test counting from a BAM.list file. Note that if the paths * in the bam.list are relative, they are interpreted as relative to * the location of the bam.list file, rather than the working directory. * <p/> * If paths are entered on the command line (option to be deprecated shortly) * via comma separated list, they are interpreted relative to the current working directory. * * @throws Exception */ @Test public void testCountBAMList() throws Exception { String listPath = TestUtils.DATA_DIR + "bam/test.unindexed.bam.list"; tstCountBamList(listPath); } /** * Test iterating through a merged bam file(actually a list with the same file duplicated). Each record * should appear twice (since the list contains the same file twice), and in coordinate sort order. * * @throws Exception */ @Test public void testMergedBam() throws Exception { String listPath = TestUtils.DATA_DIR + "bam/test.unindexed.bam.list"; AlignmentReader reader = AlignmentReaderFactory.getReader(new ResourceLocator(listPath), false); Set<String> visitedChromosomes = new HashSet(); String lastChr = null; int lastStart = -1; Iterator<Alignment> iter = reader.iterator(); while (iter.hasNext()) { Alignment a1 = iter.next(); Alignment a2 = iter.next(); assertEquals(a1.getReadName(), a2.getReadName()); assertEquals(a1.getChr(), a2.getChr()); assertEquals(a1.getStart(), a2.getStart()); assertEquals(a2.getEnd(), a2.getEnd()); String chr = a1.getChr(); int start = a1.getAlignmentStart(); if (lastChr != null && chr.equals(lastChr)) { assertTrue(a1.getReadName(), start >= lastStart); } else { assertFalse(visitedChromosomes.contains(chr)); lastChr = chr; visitedChromosomes.add(chr); } lastStart = start; } } private void tstCountBamList(String listArg) throws Exception { String outputFile = TestUtils.DATA_DIR + "out/file_"; String[] opts = new String[]{"--strands=read", "--strands=first", ""}; for (int ind = 0; ind < opts.length; ind++) { String opt = opts[ind]; String fullout = outputFile + ind + ".tdf"; String input = "count " + opt + " " + listArg + " " + fullout + " " + hg18id; String[] args = input.split("\\s+"); igvTools.run(args); TDFReader reader = TDFReader.getReader(fullout); assertTrue(reader.getDatasetNames().size() > 0); } } @Test public void testSort() throws Exception { String inputFiname = "Unigene.unsorted.bed"; String inputFile = TestUtils.DATA_DIR + "bed/" + inputFiname; String outputFile = TestUtils.TMP_OUTPUT_DIR + inputFiname + ".sorted"; File oFile = new File(outputFile); oFile.deleteOnExit(); String input = "sort --tmpDir=./ --maxRecords=50 " + inputFile + " " + outputFile; igvTools.run(input.split("\\s+")); int numlines = SorterTest.checkFileSorted(oFile, 0, 1); assertEquals(71, numlines); } /** * This test could stand to be improved, but it's difficult to test math. * So we just check that file is about the right size (and well formed). * * @throws Exception */ @Test public void testFormatexp() throws Exception { String inputFiname = "igv_test2"; String ext = ".gct"; String inputFile = TestUtils.DATA_DIR + "gct/" + inputFiname + ext; String outputFile = TestUtils.TMP_OUTPUT_DIR + inputFiname + "_formatted" + ext; File oFile = new File(outputFile); oFile.deleteOnExit(); String input = "formatexp " + inputFile + " " + outputFile; igvTools.run(input.split("\\s+")); Genome genome = TestUtils.loadGenome(); ExpressionFileParser parser = new ExpressionFileParser(new ResourceLocator(outputFile), null, genome); Dataset ds = parser.createDataset(); assertEquals(10, ds.getChromosomes().length); } @Test public void testCountDups() throws Exception { String inputFiname = "test_5duplicates"; String ext = ".sam"; String inputFile = TestUtils.DATA_DIR + "sam/" + inputFiname + ext; String outputFileND = TestUtils.TMP_OUTPUT_DIR + inputFiname + "_nodups" + ".tdf"; String outputFileWithDup = TestUtils.TMP_OUTPUT_DIR + inputFiname + "_withdups" + ".tdf"; String queryChr = "1"; int pos = 9718611; String queryStr = queryChr + ":" + (pos - 100) + "-" + (pos + 100) + " "; String cmd_nodups = "count --windowSize 1 -z 7 --query " + queryStr + inputFile + " " + outputFileND + " " + hg18id; igvTools.run(cmd_nodups.split("\\s+")); String cmd_withdups = "count --includeDuplicates -z 7 --windowSize 1 --query " + queryStr + inputFile + " " + outputFileWithDup + " " + hg18id; igvTools.run(cmd_withdups.split("\\s+")); assertTrue((new File(outputFileND).exists())); assertTrue((new File(outputFileWithDup).exists())); Genome genome = TestUtils.loadGenome(); //Have to read back in using aliased chromosome names String readChr = genome.getChromosomeAlias(queryChr); int noDupCount = (int) getCount(outputFileND, readChr, 23, pos, genome); int dupCount = (int) getCount(outputFileWithDup, readChr, 23, pos, genome); assertEquals(noDupCount + 4, dupCount); //No dups at this location pos += 80; noDupCount = (int) getCount(outputFileND, readChr, 23, pos, genome); dupCount = (int) getCount(outputFileWithDup, readChr, 23, pos, genome); assertEquals(noDupCount, dupCount); } private float getCount(String filename, String chr, int zoom, int pos, Genome genome) { TDFReader reader = TDFReader.getReader(filename); TDFDataset ds = reader.getDataset(chr, zoom, WindowFunction.mean); TDFDataSource dataSource = new TDFDataSource(reader, 0, "test", genome); List<LocusScore> scores = dataSource.getSummaryScoresForRange(chr, pos - 1, pos + 1, zoom); return scores.get(0).getScore(); } @Test public void testCountAliasedForward() throws Exception { String genfile = TestUtils.DATA_DIR + "genomes/hg18_truncated_aliased.genome"; tstCountAliased(TestUtils.DATA_DIR + "sam/NA12878.muc1.test.sam", TestUtils.DATA_DIR + "sam/NA12878.muc1.test_modchr.sam", genfile); } @Test public void testCountAliasedReversed() throws Exception { String genfile = TestUtils.DATA_DIR + "genomes/hg18_truncated_aliased_reversed.genome"; tstCountAliased(TestUtils.DATA_DIR + "sam/NA12878.muc1.test.sam", TestUtils.DATA_DIR + "sam/NA12878.muc1.test_modchr.sam", genfile); } /** * Test count when using a custom alias file. * Should supply a file using normal chromosome names, and aliases * which are defined in the genome file. */ public void tstCountAliased(String normfile, String aliasedfile, String genfile) throws Exception { String outfile = TestUtils.DATA_DIR + "out/tmpcount1.wig"; File outFi = new File(outfile); outFi.delete(); outFi.deleteOnExit(); //Count aliased file String command = "count " + normfile + " " + outfile + " " + genfile; igvTools.run(command.split("\\s+")); //Count non-aliased file String outfile2 = TestUtils.DATA_DIR + "out/tmpcount2.wig"; File outFi2 = new File(outfile2); outFi2.delete(); //Count aliased file command = "count " + aliasedfile + " " + outfile2 + " " + genfile; igvTools = new IgvTools(); igvTools.run(command.split("\\s+")); BufferedReader reader1 = new BufferedReader(new FileReader(outfile)); BufferedReader reader2 = new BufferedReader(new FileReader(outfile2)); String line1, line2; line1 = reader1.readLine(); line2 = reader2.readLine(); while ((line1 = reader1.readLine()) != null) { line2 = reader2.readLine(); //Header lines don't need to match if (line1.startsWith("#") || line1.startsWith("variableStep") || line1.startsWith("fixedStep")) { continue; } assertEquals(line1, line2); } reader1.close(); reader2.close(); } @Test public void testCountIndexedFasta() throws Exception { String fasta_file = TestUtils.DATA_DIR + "fasta/ecoli_out.padded.fasta"; String infile = TestUtils.DATA_DIR + "bed/ecoli_out.test.bed"; String outfile = TestUtils.DATA_DIR + "out/findextest.wig"; String end_command = infile + " " + outfile + " " + fasta_file; String count_command = "count " + end_command; igvTools.run(count_command.split("\\s")); File outFi = new File(outfile); assertTrue(outFi.exists()); outFi.delete(); igvTools = new IgvTools(); String index_command = "index " + end_command; igvTools.run(index_command.split("\\s")); String indexFile = infile + ".idx"; File idxFi = new File(indexFile); assertTrue(idxFi.exists()); idxFi.deleteOnExit(); Genome genome = IgvTools.loadGenome(fasta_file, true); FeatureCodec codec = CodecFactory.getCodec(infile, genome); AbstractFeatureReader<Feature> reader = AbstractFeatureReader.getFeatureReader(infile, codec, true); String chr = "NC_000913_bb"; Iterator<Feature> features = reader.query(chr, 5085, 5091); int count = 0; while (features.hasNext() && count < 100) { assertEquals(chr, features.next().getChr()); count++; } assertEquals(3, count); } @Test public void testCountAllWF() throws Exception { String[] exclude = {"none", "density", "stddev", "count"}; List<WindowFunction> wfList = new ArrayList<WindowFunction>(); wfList.addAll(Arrays.asList(WindowFunction.values())); for (String s : exclude) { wfList.remove(WindowFunction.valueOf(s)); } String inputFile = TestUtils.DATA_DIR + "bam/NA12878.SLX.sample.bam"; tstCountWindowFunctions(inputFile, "All", wfList); } private void tstCountWindowFunctions(String inputFile, String chr, Iterable<WindowFunction> windowFunctions) throws Exception { String outputFile = TestUtils.DATA_DIR + "out/testCountWindowFunctions.tdf"; String wfs = ""; for (WindowFunction wf : windowFunctions) { wfs += wf.name() + ","; } wfs = wfs.substring(0, wfs.lastIndexOf(",")); String[] cmd = {"count", "--windowFunctions", wfs, inputFile, outputFile, hg18id}; igvTools.run(cmd); TDFReader reader = new TDFReader(new ResourceLocator(outputFile)); for (WindowFunction wf : windowFunctions) { TDFDataset ds = reader.getDataset(chr, 0, wf); assertNotNull(ds); } } @Test //tile -z 1 --fileType mage-tab public void testTileMageTab() throws Exception { String mageTabFile = TestUtils.DATA_DIR + "mage-tab/test.data.txt"; String outputFile = TestUtils.DATA_DIR + "mage-tab/test.data.tdf"; String genfile = TestUtils.DATA_DIR + "genomes/hg18_truncated_aliased.genome"; String command = "tile -z 1 --fileType mage-tab " + mageTabFile + " " + outputFile + " " + genfile; igvTools.run(command.split("\\s+")); } }
/* * $Id: MockLockssDaemon.java,v 1.76 2014-12-27 03:42:40 tlipkis Exp $ */ package org.lockss.test; import java.util.List; import org.apache.commons.collections.map.LinkedMap; import org.lockss.alert.AlertManager; import org.lockss.account.AccountManager; import org.lockss.app.*; import org.lockss.config.*; import org.lockss.crawler.CrawlManager; import org.lockss.daemon.*; import org.lockss.daemon.status.StatusService; import org.lockss.db.DbManager; import org.lockss.exporter.counter.CounterReportsManager; import org.lockss.hasher.HashService; import org.lockss.mail.MailService; import org.lockss.metadata.MetadataManager; import org.lockss.plugin.*; import org.lockss.truezip.*; import org.lockss.poller.PollManager; import org.lockss.protocol.*; import org.lockss.protocol.psm.*; import org.lockss.proxy.ProxyManager; import org.lockss.proxy.icp.IcpManager; import org.lockss.remote.RemoteApi; import org.lockss.repository.*; import org.lockss.scheduler.SchedService; import org.lockss.servlet.*; import org.lockss.state.*; import org.lockss.subscription.SubscriptionManager; import org.lockss.util.*; import org.lockss.clockss.*; public class MockLockssDaemon extends LockssDaemon { private static Logger log = Logger.getLogger("MockLockssDaemon"); ResourceManager resourceManager = null; WatchdogService wdogService = null; MailService mailService = null; AlertManager alertManager = null; AccountManager accountManager = null; RandomManager randomManager = null; LockssKeyStoreManager keystoreManager = null; HashService hashService = null; SchedService schedService = null; SystemMetrics systemMetrics = null; PollManager pollManager = null; PsmManager psmManager = null; LcapDatagramComm commManager = null; LcapStreamComm scommManager = null; LcapDatagramRouter datagramRouterManager = null; LcapRouter routerManager = null; ProxyManager proxyManager = null; ServletManager servletManager = null; CrawlManager crawlManager = null; RepositoryManager repositoryManager = null; NodeManagerManager nodeManagerManager = null; PluginManager pluginManager = null; MetadataManager metadataManager = null; IdentityManager identityManager = null; TrueZipManager tzipManager = null; StatusService statusService = null; RemoteApi remoteApi = null; IcpManager icpManager = null; ClockssParams clockssParams = null; DbManager dbManager = null; CounterReportsManager counterReportsManager = null; SubscriptionManager subscriptionManager = null; Cron cron = null; private boolean suppressStartAuManagers = true; /** Unit tests that need a MockLockssDaemon should use {@link * LockssTestCase#getMockLockssDaemon()} rather than calling this * directly. Some utilities (not descended from LockssTestCase) also * need one, so this constructor is protected to allow them to directly * create an instance (of their own subclass). */ protected MockLockssDaemon() { this(null); } private MockLockssDaemon(List<String> urls) { super(urls); ConfigManager mgr = ConfigManager.getConfigManager(); mgr.registerConfigurationCallback(new Configuration.Callback() { public void configurationChanged(Configuration newConfig, Configuration prevConfig, Configuration.Differences changedKeys) { setConfig(newConfig, prevConfig, changedKeys); } }); } protected void setConfig(Configuration config, Configuration prevConfig, Configuration.Differences changedKeys) { super.setConfig(config, prevConfig, changedKeys); } /** Does nothing */ public void startDaemon() throws Exception { } public void stopDaemon() { auManagerMaps.clear(); wdogService = null; hashService = null; schedService = null; pollManager = null; psmManager = null; commManager = null; scommManager = null; proxyManager = null; crawlManager = null; pluginManager = null; metadataManager = null; identityManager = null; statusService = null; icpManager = null; dbManager = null; counterReportsManager = null; subscriptionManager = null; cron = null; //super.stopDaemon(); } /** Set the testing mode. (Normally done through config and daemon * startup.) */ public void setTestingMode(String mode) { testingMode = mode; } ManagerDesc findManagerDesc(String key) { return findDesc(managerDescs, key); } ManagerDesc findAuManagerDesc(String key) { return findDesc(getAuManagerDescs(), key); } ManagerDesc findDesc(ManagerDesc[] descs, String key) { for(int i=0; i< descs.length; i++) { ManagerDesc desc = descs[i]; if (key.equals(desc.getKey())) { return desc; } } return null; } /** Create a manager instance, mimicking what LockssDaemon does */ LockssManager newManager(String key) { log.debug2("Loading manager: " + key); ManagerDesc desc = findManagerDesc(key); if (desc == null) { throw new LockssAppException("No ManagerDesc for: " + key); } if (log.isDebug2()) { log.debug2("Manager class: " + getManagerClassName(desc)); } try { return initManager(desc); } catch (Exception e) { log.error("Error creating manager", e); throw new LockssAppException("Can't load manager: " + e.toString()); } } /** * return the watchdog service instance * @return the WatchdogService */ public WatchdogService getWatchdogService() { if (wdogService == null) { wdogService = (WatchdogService)newManager(LockssDaemon.WATCHDOG_SERVICE); managerMap.put(LockssDaemon.WATCHDOG_SERVICE, wdogService); } return wdogService; } /** * return the mail manager instance * @return the MailService */ public MailService getMailService() { if (mailService == null) { mailService = new NullMailService(); managerMap.put(LockssDaemon.MAIL_SERVICE, mailService); } return mailService; } /** * return the resource manager instance * @return the ResourceManager */ public ResourceManager getResourceManager() { if (resourceManager == null) { resourceManager = (ResourceManager)newManager(RESOURCE_MANAGER); managerMap.put(RESOURCE_MANAGER, resourceManager); } return resourceManager; } /** * return the alert manager instance * @return the AlertManager */ public AlertManager getAlertManager() { if (alertManager == null) { alertManager = new NullAlertManager(); managerMap.put(LockssDaemon.ALERT_MANAGER, alertManager); } return alertManager; } /** * return the account manager instance * @return the AccountManager */ public AccountManager getAccountManager() { if (accountManager == null) { accountManager = (AccountManager)newManager(ACCOUNT_MANAGER); managerMap.put(LockssDaemon.ACCOUNT_MANAGER, accountManager); } return accountManager; } /** * return the random manager instance * @return the RandomManager */ public RandomManager getRandomManager() { if (randomManager == null) { randomManager = (RandomManager)newManager(RANDOM_MANAGER); managerMap.put(LockssDaemon.RANDOM_MANAGER, randomManager); } return randomManager; } /** * return the keystore manager instance * @return the KeystoreManager */ public LockssKeyStoreManager getKeystoreManager() { if (keystoreManager == null) { keystoreManager = (LockssKeyStoreManager)newManager(KEYSTORE_MANAGER); managerMap.put(LockssDaemon.KEYSTORE_MANAGER, keystoreManager); } return keystoreManager; } /** * return the hash service instance * @return the HashService */ public HashService getHashService() { if (hashService == null) { hashService = (HashService)newManager(LockssDaemon.HASH_SERVICE); managerMap.put(LockssDaemon.HASH_SERVICE, hashService); } return hashService; } /** * return the sched service instance * @return the SchedService */ public SchedService getSchedService() { if (schedService == null) { schedService = (SchedService)newManager(LockssDaemon.SCHED_SERVICE); managerMap.put(LockssDaemon.SCHED_SERVICE, schedService); } return schedService; } /** * return the SystemMetrics instance * @return the SystemMetrics */ public SystemMetrics getSystemMetrics() { if (systemMetrics == null) { systemMetrics = (SystemMetrics)newManager(LockssDaemon.SYSTEM_METRICS); managerMap.put(LockssDaemon.SYSTEM_METRICS, systemMetrics); } return systemMetrics; } /** * return the poll manager instance * @return the PollManager */ public PollManager getPollManager() { if (pollManager == null) { pollManager = (PollManager)newManager(LockssDaemon.POLL_MANAGER); managerMap.put(LockssDaemon.POLL_MANAGER, pollManager); } return pollManager; } /** * return the psm manager instance * @return the PsmManager */ public PsmManager getPsmManager() { if (psmManager == null) { psmManager = (PsmManager)newManager(LockssDaemon.PSM_MANAGER); managerMap.put(LockssDaemon.PSM_MANAGER, psmManager); } return psmManager; } /** * return the datagram communication manager instance * @return the LcapDatagramComm */ public LcapDatagramComm getDatagramCommManager() { if (commManager == null) { commManager = (LcapDatagramComm)newManager(LockssDaemon.DATAGRAM_COMM_MANAGER); managerMap.put(LockssDaemon.DATAGRAM_COMM_MANAGER, commManager); } return commManager; } /** * return the stream communication manager instance * @return the LcapStreamComm */ public LcapStreamComm getStreamCommManager() { if (scommManager == null) { scommManager = (LcapStreamComm)newManager(LockssDaemon.STREAM_COMM_MANAGER); managerMap.put(LockssDaemon.STREAM_COMM_MANAGER, scommManager); } return scommManager; } /** * return the datagram router manager instance * @return the LcapDatagramRouter */ public LcapDatagramRouter getDatagramRouterManager() { if (datagramRouterManager == null) { datagramRouterManager = (LcapDatagramRouter)newManager(LockssDaemon.DATAGRAM_ROUTER_MANAGER); managerMap.put(LockssDaemon.DATAGRAM_ROUTER_MANAGER, datagramRouterManager); } return datagramRouterManager; } /** * return the router manager instance * @return the LcapRouter */ public LcapRouter getRouterManager() { if (routerManager == null) { routerManager = (LcapRouter)newManager(LockssDaemon.ROUTER_MANAGER); managerMap.put(LockssDaemon.ROUTER_MANAGER, routerManager); } return routerManager; } /** * return the proxy manager instance * @return the ProxyManager */ public ProxyManager getProxyManager() { if (proxyManager == null) { proxyManager = (ProxyManager)newManager(LockssDaemon.PROXY_MANAGER); managerMap.put(LockssDaemon.PROXY_MANAGER, proxyManager); } return proxyManager; } /** * return the servlet manager instance * @return the ServletManager */ public ServletManager getServletManager() { if (servletManager == null) { servletManager = (ServletManager)newManager(LockssDaemon.SERVLET_MANAGER); managerMap.put(LockssDaemon.SERVLET_MANAGER, servletManager); } return servletManager; } /** * return the TrueZip manager instance * @return the TrueZipManager */ public TrueZipManager getTrueZipManager() { if (tzipManager == null) { tzipManager = (TrueZipManager)newManager(LockssDaemon.TRUEZIP_MANAGER); managerMap.put(LockssDaemon.TRUEZIP_MANAGER, tzipManager); } return tzipManager; } /** * return the crawl manager instance * @return the CrawlManager */ public CrawlManager getCrawlManager() { if (crawlManager == null) { crawlManager = (CrawlManager)newManager(LockssDaemon.CRAWL_MANAGER); managerMap.put(LockssDaemon.CRAWL_MANAGER, crawlManager); } return crawlManager; } /** * return the node manager status instance * @return the TreewalkManager */ public NodeManagerManager getNodeManagerManager() { if (nodeManagerManager == null) { nodeManagerManager = (NodeManagerManager)newManager(LockssDaemon.NODE_MANAGER_MANAGER); managerMap.put(LockssDaemon.NODE_MANAGER_MANAGER, nodeManagerManager); } return nodeManagerManager; } /** * return the repository manager instance * @return the RepositoryManager */ public RepositoryManager getRepositoryManager() { if (repositoryManager == null) { repositoryManager = (RepositoryManager)newManager(LockssDaemon.REPOSITORY_MANAGER); managerMap.put(LockssDaemon.REPOSITORY_MANAGER, repositoryManager); } return repositoryManager; } /** * return the plugin manager instance * @return the PluginManager */ public PluginManager getPluginManager() { if (pluginManager == null) { pluginManager = (PluginManager)newManager(LockssDaemon.PLUGIN_MANAGER); managerMap.put(LockssDaemon.PLUGIN_MANAGER, pluginManager); } return pluginManager; } /** * return the metadata manager instance * @return the MetadataManager */ public MetadataManager getMetadataManager() { if (metadataManager == null) { metadataManager = (MetadataManager)newManager(LockssDaemon.METADATA_MANAGER); managerMap.put(LockssDaemon.METADATA_MANAGER, metadataManager); } return metadataManager; } /** * return the Identity Manager * @return IdentityManager */ public IdentityManager getIdentityManager() { if (identityManager == null) { identityManager = (IdentityManager)newManager(LockssDaemon.IDENTITY_MANAGER); managerMap.put(LockssDaemon.IDENTITY_MANAGER, identityManager); } return identityManager; } public boolean hasIdentityManager() { return identityManager != null; } /** * return the database manager instance * @return the DbManager */ public DbManager getDbManager() { if (dbManager == null) { dbManager = (DbManager)newManager(LockssDaemon.DB_MANAGER); managerMap.put(LockssDaemon.DB_MANAGER, dbManager); } return dbManager; } /** * return the COUNTER reports manager instance * @return the CounterReportsManager */ public CounterReportsManager getCounterReportsManager() { if (counterReportsManager == null) { counterReportsManager = (CounterReportsManager)newManager(LockssDaemon.COUNTER_REPORTS_MANAGER); managerMap.put(LockssDaemon.COUNTER_REPORTS_MANAGER, counterReportsManager); } return counterReportsManager; } /** * return the subscription manager instance * @return the SusbcriptionManager */ public SubscriptionManager getSusbcriptionManager() { if (subscriptionManager == null) { subscriptionManager = (SubscriptionManager)newManager(LockssDaemon.SUBSCRIPTION_MANAGER); managerMap.put(LockssDaemon.SUBSCRIPTION_MANAGER, subscriptionManager); } return subscriptionManager; } /** * return the cron instance * @return the Cron */ public Cron getCron() { if (cron == null) { cron = (Cron)newManager(LockssDaemon.CRON); managerMap.put(LockssDaemon.CRON, cron); } return cron; } public StatusService getStatusService() { if (statusService == null) { statusService = (StatusService)newManager(LockssDaemon.STATUS_SERVICE); managerMap.put(LockssDaemon.STATUS_SERVICE, statusService); } return statusService; } /** * return the RemoteApi instance * @return the RemoteApi */ public RemoteApi getRemoteApi() { if (remoteApi == null) { remoteApi = (RemoteApi)newManager(LockssDaemon.REMOTE_API); managerMap.put(LockssDaemon.REMOTE_API, remoteApi); } return remoteApi; } /** * return the ClockssParams instance * @return the ClockssParams */ public ClockssParams getClockssParams() { if (clockssParams == null) { clockssParams = (ClockssParams)newManager(LockssDaemon.CLOCKSS_PARAMS); managerMap.put(LockssDaemon.CLOCKSS_PARAMS, clockssParams); } return clockssParams; } private boolean forceIsClockss = false; public void setClockss(boolean val) { forceIsClockss = val; } public boolean isClockss() { return forceIsClockss || super.isClockss(); } /** * Set the datagram CommManager * @param commMan the new manager */ public void setDatagramCommManager(LcapDatagramComm commMan) { commManager = commMan; managerMap.put(LockssDaemon.DATAGRAM_COMM_MANAGER, commManager); } /** * Set the stream CommManager * @param scommMan the new manager */ public void setStreamCommManager(LcapStreamComm scommMan) { scommManager = scommMan; managerMap.put(LockssDaemon.STREAM_COMM_MANAGER, scommManager); } /** * Set the DatagramRouterManager * @param datagramRouterMan the new manager */ public void setDatagramRouterManager(LcapDatagramRouter datagramRouterMan) { datagramRouterManager = datagramRouterMan; managerMap.put(LockssDaemon.DATAGRAM_ROUTER_MANAGER, datagramRouterManager); } /** * Set the RouterManager * @param routerMan the new manager */ public void setRouterManager(LcapRouter routerMan) { routerManager = routerMan; managerMap.put(LockssDaemon.ROUTER_MANAGER, routerManager); } /** * Set the CrawlManager * @param crawlMan the new manager */ public void setCrawlManager(CrawlManager crawlMan) { crawlManager = crawlMan; managerMap.put(LockssDaemon.CRAWL_MANAGER, crawlManager); } /** * Set the RepositoryManager * @param repositoryMan the new manager */ public void setRepositoryManager(RepositoryManager repositoryMan) { repositoryManager = repositoryMan; managerMap.put(LockssDaemon.REPOSITORY_MANAGER, repositoryManager); } /** * Set the NodeManagerManager * @param nodeManMan the new manager */ public void setNodeManagerManager(NodeManagerManager nodeManMan) { nodeManagerManager = nodeManMan; managerMap.put(LockssDaemon.NODE_MANAGER_MANAGER, nodeManMan); } /** * Set the WatchdogService * @param wdogService the new service */ public void setWatchdogService(WatchdogService wdogService) { this.wdogService = wdogService; managerMap.put(LockssDaemon.WATCHDOG_SERVICE, wdogService); } /** * Set the MailService * @param mailMan the new manager */ public void setMailService(MailService mailMan) { mailService = mailMan; managerMap.put(LockssDaemon.MAIL_SERVICE, mailService); } /** * Set the AlertManager * @param alertMan the new manager */ public void setAlertManager(AlertManager alertMan) { alertManager = alertMan; managerMap.put(LockssDaemon.ALERT_MANAGER, alertManager); } /** * Set the AccountManager * @param accountMan the new manager */ public void setAccountManager(AccountManager accountMan) { accountManager = accountMan; managerMap.put(LockssDaemon.ACCOUNT_MANAGER, accountManager); } /** * Set the RandomManager * @param randomMan the new manager */ public void setRandomManager(RandomManager randomMan) { randomManager = randomMan; managerMap.put(LockssDaemon.RANDOM_MANAGER, randomManager); } /** * Set the KeystoreManager * @param keystoreMan the new manager */ public void setKeystoreManager(LockssKeyStoreManager keystoreMan) { keystoreManager = keystoreMan; managerMap.put(LockssDaemon.KEYSTORE_MANAGER, keystoreManager); } /** * Set the HashService * @param hashServ the new service */ public void setHashService(HashService hashServ) { hashService = hashServ; managerMap.put(LockssDaemon.HASH_SERVICE, hashService); } /** * Set the SchedService * @param schedServ the new service */ public void setSchedService(SchedService schedServ) { schedService = schedServ; managerMap.put(LockssDaemon.SCHED_SERVICE, schedService); } /** * Set the IdentityManager * @param idMan the new manager */ public void setIdentityManager(IdentityManager idMan) { identityManager = idMan; managerMap.put(LockssDaemon.IDENTITY_MANAGER, identityManager); } /** * Set the MetadataManager * @param metadataMan the new manager */ public void setMetadataManager(MetadataManager metadataMan) { metadataManager = metadataMan; managerMap.put(LockssDaemon.METADATA_MANAGER, metadataManager); } /** * Set the PluginManager * @param pluginMan the new manager */ public void setPluginManager(PluginManager pluginMan) { pluginManager = pluginMan; managerMap.put(LockssDaemon.PLUGIN_MANAGER, pluginManager); } /** * Set the PollManager * @param pollMan the new manager */ public void setPollManager(PollManager pollMan) { pollManager = pollMan; managerMap.put(LockssDaemon.POLL_MANAGER, pollManager); } /** * Set the ProxyManager * @param proxyMgr the new manager */ public void setProxyManager(ProxyManager proxyMgr) { proxyManager = proxyMgr; managerMap.put(LockssDaemon.PROXY_MANAGER, proxyManager); } /** * Set the ServletManager * @param servletMgr the new manager */ public void setServletManager(ServletManager servletMgr) { servletManager = servletMgr; managerMap.put(LockssDaemon.SERVLET_MANAGER, servletManager); } /** * Set the TrueZipManager * @param tzMgr the new manager */ public void setTrueZipManager(TrueZipManager tzMgr) { tzipManager = tzMgr; managerMap.put(LockssDaemon.TRUEZIP_MANAGER, tzipManager); } /** * Set the DbManager * @param dbMan the new manager */ public void setDbManager(DbManager dbMan) { dbManager = dbMan; managerMap.put(LockssDaemon.DB_MANAGER, dbManager); } /** * Set the CounterReportsManager * @param counterReportsMan the new manager */ public void setCounterReportsManager(CounterReportsManager counterReportsMan) { counterReportsManager = counterReportsMan; managerMap.put(LockssDaemon.COUNTER_REPORTS_MANAGER, counterReportsManager); } /** * Set the SubscriptionManager * @param subscriptionMan the new manager */ public void setSubscriptionManager(SubscriptionManager subscriptionMan) { subscriptionManager = subscriptionMan; managerMap.put(LockssDaemon.SUBSCRIPTION_MANAGER, subscriptionManager); } /** * Set the SystemMetrics * @param sysMetrics the new metrics */ public void setSystemMetrics(SystemMetrics sysMetrics) { systemMetrics = sysMetrics; managerMap.put(LockssDaemon.SYSTEM_METRICS, sysMetrics); } /** * Set the RemoteApi * @param sysMetrics the new metrics */ public void setRemoteApi(RemoteApi sysMetrics) { remoteApi = sysMetrics; managerMap.put(LockssDaemon.REMOTE_API, sysMetrics); } /** * Set the Cron * @param cron the new cron */ public void setCron(Cron cron) { this.cron = cron; managerMap.put(LockssDaemon.CRON, cron); } // AU managers /** Create an AU manager instance, mimicking what LockssDaemon does */ public LockssAuManager newAuManager(String key, ArchivalUnit au) { ManagerDesc desc = findAuManagerDesc(key); if (desc == null) { throw new LockssAppException("No AU ManagerDesc for: " + key); } log.debug2("Loading manager: " + desc.getKey() + " for " + au); try { LockssAuManager mgr = initAuManager(desc, au); setAuManager(desc, au, mgr); return mgr; } catch (Exception e) { log.error("Error starting au manager", e); throw new LockssAppException("Can't load au manager: " + e.toString()); } } public void setAuManager(String key, ArchivalUnit au, LockssAuManager mgr) { setAuManager(findAuManagerDesc(key), au, mgr); } void setAuManager(ManagerDesc desc, ArchivalUnit au, LockssAuManager mgr) { LinkedMap auMgrMap = (LinkedMap)auManagerMaps.get(au); if (auMgrMap == null) { auMgrMap = new LinkedMap(); auManagerMaps.put(au, auMgrMap); } auMgrMap.put(desc.getKey(), mgr); } /** AU managers are normally not started on AU creation. Call this with * false to cause them to be started. */ public void suppressStartAuManagers(boolean val) { suppressStartAuManagers = val; } /** Overridden to prevent managers from being started. See {@link * #suppressStartAuManagers(boolean)} to cause them to be started. */ public void startOrReconfigureAuManagers(ArchivalUnit au, Configuration auConfig) throws Exception { if (!suppressStartAuManagers) { super.startOrReconfigureAuManagers(au, auConfig); } } /** For tests that override startOrReconfigureAuManagers and want to * conditionally start them. */ public void reallyStartOrReconfigureAuManagers(ArchivalUnit au, Configuration auConfig) throws Exception { super.startOrReconfigureAuManagers(au, auConfig); } /** Return ActivityRegulator for AU */ public ActivityRegulator getActivityRegulator(ArchivalUnit au) { try { return super.getActivityRegulator(au); } catch (IllegalArgumentException e) { return (ActivityRegulator)newAuManager(LockssDaemon.ACTIVITY_REGULATOR, au); } } /** Return LockssRepository for AU */ public LockssRepository getLockssRepository(ArchivalUnit au) { try { return super.getLockssRepository(au); } catch (IllegalArgumentException e) { return (LockssRepository)newAuManager(LockssDaemon.LOCKSS_REPOSITORY, au); } } /** Return NodeManager for AU */ public NodeManager getNodeManager(ArchivalUnit au) { try { return super.getNodeManager(au); } catch (IllegalArgumentException e) { return (NodeManager)newAuManager(LockssDaemon.NODE_MANAGER, au); } } /** Return HistoryRepository for AU */ public HistoryRepository getHistoryRepository(ArchivalUnit au) { try { return super.getHistoryRepository(au); } catch (IllegalArgumentException e) { return (HistoryRepository)newAuManager(LockssDaemon.HISTORY_REPOSITORY, au); } } /** * Set the ActivityRegulator for a given AU. * @param actReg the new regulator * @param au the ArchivalUnit */ public void setActivityRegulator(ActivityRegulator actReg, ArchivalUnit au) { setAuManager(ACTIVITY_REGULATOR, au, actReg); } /** * Set the LockssRepository for a given AU. * @param repo the new repository * @param au the ArchivalUnit */ public void setLockssRepository(LockssRepository repo, ArchivalUnit au) { setAuManager(LOCKSS_REPOSITORY, au, repo); } /** * Set the NodeManager for a given AU. * @param nodeMan the new manager * @param au the ArchivalUnit */ public void setNodeManager(NodeManager nodeMan, ArchivalUnit au) { setAuManager(NODE_MANAGER, au, nodeMan); } /** * Set the HistoryRepository for a given AU. * @param histRepo the new repository * @param au the ArchivalUnit */ public void setHistoryRepository(HistoryRepository histRepo, ArchivalUnit au) { setAuManager(HISTORY_REPOSITORY, au, histRepo); } /** * <p>Forcibly sets the ICP manager to a new value.</p> * @param icpManager A new ICP manager to use. */ public void setIcpManager(IcpManager icpManager) { this.icpManager = icpManager; managerMap.put(LockssDaemon.ICP_MANAGER, icpManager); } private boolean daemonInited = false; private boolean daemonRunning = false; /** * @return true iff all managers have been inited */ public boolean isDaemonInited() { return daemonInited; } // need to override this one too, inherited from LockssApp public boolean isAppInited() { return isDaemonInited(); } /** * @return true iff all managers have been started */ public boolean isDaemonRunning() { return daemonRunning; } // need to override this one too, inherited from LockssApp public boolean isAppRunning() { return isDaemonRunning(); } /** set daemonInited * @param val true if inited */ public void setDaemonInited(boolean val) { daemonInited = val; } /** set daemonRunning * @param val true if running */ public void setDaemonRunning(boolean val) { daemonRunning = val; } public void setAusStarted(boolean val) { if (val) { ausStarted.fill(); } else { ausStarted = new OneShotSemaphore(); } } }
/* * $Id: TestMetadataUtil.java,v 1.12 2013-12-10 00:04:03 etenbrink Exp $ */ package org.lockss.util; import java.util.*; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import org.apache.commons.lang.LocaleUtils; import org.lockss.test.*; public class TestMetadataUtil extends LockssTestCase { void assertLocale(String lang, Locale l) { assertEquals("Language", lang, l.getLanguage()); } void assertLocale(String lang, String country, Locale l) { assertEquals("Language", lang, l.getLanguage()); assertEquals("Country", country, l.getCountry()); } void assertLocale(String lang, String country, String variant, Locale l) { assertEquals("Language", lang, l.getLanguage()); assertEquals("Country", country, l.getCountry()); assertEquals("Variant", variant, l.getVariant()); } static Set<Locale> testLocales = SetUtil.set( new Locale("aa"), new Locale("bb"), new Locale("bb", "XX"), new Locale("cc"), new Locale("cc", "XX"), new Locale("cc", "YY"), new Locale("cc", "XX", "V1"), new Locale("dd", "WW"), new Locale("ee", "WW", "V3") ); String findClosestLocale(String str) { Locale l = MetadataUtil.findClosestLocale(LocaleUtils.toLocale(str), testLocales); return l != null ? l.toString() : null; } String findClosestAvailableLocale(String str) { Locale l = MetadataUtil.findClosestAvailableLocale(LocaleUtils.toLocale(str)); return l != null ? l.toString() : null; } public void testFindClosestLocale() { assertEquals("aa", findClosestLocale("aa")); assertEquals("aa", findClosestLocale("aa_XX")); assertEquals("aa", findClosestLocale("aa_XX_V1")); assertEquals("bb", findClosestLocale("bb")); assertEquals("bb_XX", findClosestLocale("bb_XX")); assertEquals("bb_XX", findClosestLocale("bb_XX_V1")); assertEquals("bb", findClosestLocale("bb_YY")); assertEquals("bb", findClosestLocale("bb_YY_V1")); assertEquals("cc", findClosestLocale("cc")); assertEquals("cc_XX", findClosestLocale("cc_XX")); assertEquals("cc_XX_V1", findClosestLocale("cc_XX_V1")); assertEquals("cc_XX", findClosestLocale("cc_XX_V2")); assertEquals("cc", findClosestLocale("cc_ZZ")); assertEquals("cc_YY", findClosestLocale("cc_YY")); assertEquals("cc_YY", findClosestLocale("cc_YY_V1")); assertEquals("cc_YY", findClosestLocale("cc_YY_V2")); assertEquals(null, findClosestLocale("xx")); assertEquals(null, findClosestLocale("xx_XX")); assertEquals(null, findClosestLocale("xx_XX_V1")); assertEquals("dd_WW", findClosestLocale("dd_WW")); assertEquals(null, findClosestLocale("dd_VV")); assertEquals("ee_WW_V3", findClosestLocale("ee_WW_V3")); assertEquals(null, findClosestLocale("ee_WW_V4")); assertEquals(null, findClosestLocale("ee_VV")); } // Java spec says Locale.US must exist; still not sure this will succeed // in all environments public void testFindClosestAvailableLocale() { assertEquals("en", findClosestAvailableLocale("en")); assertEquals("en", findClosestAvailableLocale("en_ZF")); assertEquals("en_US", findClosestAvailableLocale("en_US")); } static Locale DEF_LOC = MetadataUtil.DEFAULT_DEFAULT_LOCALE; public void testConfigDefaultLocale() { assertEquals(DEF_LOC, MetadataUtil.getDefaultLocale()); ConfigurationUtil.setFromArgs(MetadataUtil.PARAM_DEFAULT_LOCALE, "fr_CA"); assertLocale("fr", "CA", MetadataUtil.getDefaultLocale()); ConfigurationUtil.setFromArgs(MetadataUtil.PARAM_DEFAULT_LOCALE, ""); assertEquals(DEF_LOC, MetadataUtil.getDefaultLocale()); } private String validISBN10s [] = { "99921-58-10-7", "9971-5-0210-0", "80-902734-1-6", "85-359-0277-5", "1-84356-028-3", "0-684-84328-5", "0-8044-2957-X", "0-85131-041-9", "0-943396-04-2" }; private String invalidISBN10s[] = { "99921-48-10-7", "9971-5-0110-0", "80-902735-1-6", "85-359-0278-5", "1-84356-028-2", "0-684-83328-5", "0-8044-2757-X", "0-85131-042-9", "0-943396-14-2" }; private String validISBN13s [] = { "978-99921-58-10-4", "978-9971-5-0210-2", "978-80-902734-1-2", "978-85-359-0277-8", "978-1-84356-028-9", "978-0-684-84328-5", "978-0-8044-2957-3", "978-0-85131-041-1", "978-0-943396-04-0" }; private String invalidISBN13s[] = { "978-99931-58-10-4", "978-9971-5-0200-2", "978-80-901734-1-2", "978-85-359-1277-8", "978-1-84356-128-9", "978-0-682-84328-5", "978-0-8043-2957-3", "978-0-85130-041-1", "978-0-942396-04-0" }; private String malformedISBNs[] = { "X78-99931-58-10-4", "X9921-48-10-7", "0-8044-2957-Z", "1234-5678", }; private String validISSNS [] = { "1144-875X", "1543-8120", "1508-1109", "1733-5329", "0740-2783", "0097-4463", "1402-2001", "1523-0430", "1938-4246", "0006-3363" }; private String invalidISSNS [] = { "1144-175X", "1144-8753", "1543-8122", "1541-8120", "1508-1409", "2740-2783" }; private String malformedISSNS [] = { "140-42001", "15236-430", "1402-200", "1938/4246", "1402", "1402-", "-4246" }; private String validDOIS [] = { "10.1095/biolreprod.106.054056", "10.2992/007.078.0301", "10.1206/606.1", "10.1640/0002-8444-99.2.61", "10.1663/0006-8101(2007)73[267:TPOSRI]2.0.CO;2", "10.1663/0006-8101(2007)73[267%3ATPOSRI]2.0.CO%3B2", "10.1640/0002-8444/99.2.61", "10.1635a/006-8101", "10.166356/006-8101" }; private String invalidDOIS [] = { "12.1095/biolreprod.106.054056", "10.2992-007.078.0301", "10.1206", "/0002-8444-99.2.61", "-0002-8444-99.2.61", "10.2992007/078.0301", null }; public void testISBN() { // valid with checksum calculations for(int i=0; i<validISBN10s.length;i++) { assertTrue(MetadataUtil.isIsbn(validISBN10s[i], true)); } // malformed ISBN for(int i=0; i<malformedISBNs.length;i++){ assertFalse(MetadataUtil.isIsbn(malformedISBNs[i], false)); } // invalid with checksum calculations for(int i=0; i<invalidISBN10s.length;i++){ assertFalse(MetadataUtil.isIsbn(invalidISBN10s[i], true)); } // valid ignoring checksum calculations for(int i=0; i<invalidISBN10s.length;i++){ assertTrue(MetadataUtil.isIsbn(invalidISBN10s[i], false)); } // valid with checksum calculations for(int i=0; i<validISBN13s.length;i++){ assertTrue(MetadataUtil.isIsbn(validISBN13s[i], true)); } // invalid with checksum calculations for(int i=0; i<invalidISBN13s.length;i++){ assertFalse(MetadataUtil.isIsbn(invalidISBN13s[i], true)); } // valid ignoring checksum calculation for(int i=0; i<invalidISBN13s.length;i++){ assertTrue(MetadataUtil.isIsbn(invalidISBN13s[i], false)); } // Knuth vol 4A 1st edition // test ISBN conversions with correct check digit assertEquals("0201038048", MetadataUtil.toIsbn10("978-0-201-03804-0")); assertEquals("0201038048", MetadataUtil.toIsbn10("9780201038040")); assertEquals("0201038048", MetadataUtil.toIsbn10("0-201-03804-8")); assertEquals("0201038048", MetadataUtil.toIsbn10("0201038048")); assertEquals("9780201038040", MetadataUtil.toIsbn13("978-0-201-03804-0")); assertEquals("9780201038040", MetadataUtil.toIsbn13("9780201038040")); assertEquals("9780201038040", MetadataUtil.toIsbn13("0-201-03804-8")); assertEquals("9780201038040", MetadataUtil.toIsbn13("0201038048")); // test ISBN conversions with incorrect check digit assertEquals("0201038048", MetadataUtil.toIsbn10("978-0-201-03804-7")); assertEquals("0201038048", MetadataUtil.toIsbn10("9780201038047")); assertEquals("0201038048", MetadataUtil.toIsbn10("0-201-03804-X")); assertEquals("0201038048", MetadataUtil.toIsbn10("020103804X")); assertEquals("9780201038040", MetadataUtil.toIsbn13("978-0-201-03804-7")); assertEquals("9780201038040", MetadataUtil.toIsbn13("9780201038047")); assertEquals("9780201038040", MetadataUtil.toIsbn13("0-201-03804-X")); assertEquals("9780201038040", MetadataUtil.toIsbn13("020103804X")); // test ISBN conversions with invalid check digit assertNull(MetadataUtil.toIsbn10("978-0-201-03804-X")); assertNull(MetadataUtil.toIsbn10("978020103804X")); assertNull(MetadataUtil.toIsbn10("0-201-03804-Z")); assertNull(MetadataUtil.toIsbn10("020103804Z")); assertNull(MetadataUtil.toIsbn13("978-0-201-03804-X")); assertNull(MetadataUtil.toIsbn13("978020103804X")); assertNull(MetadataUtil.toIsbn13("0-201-03804-Z")); assertNull(MetadataUtil.toIsbn13("020103804Z")); // test ISBN conversions with invalid input issn assertNull(MetadataUtil.toIsbn10("978-X-201-03804-0")); assertNull(MetadataUtil.toIsbn10("9780X01038040")); assertNull(MetadataUtil.toIsbn10("0-2X1-03804-8")); assertNull(MetadataUtil.toIsbn10("02X1038048")); assertNull(MetadataUtil.toIsbn10("xyzzy")); assertNull(MetadataUtil.toIsbn13("978-X-201-03804-0")); assertNull(MetadataUtil.toIsbn13("9780X01038040")); assertNull(MetadataUtil.toIsbn13("0-2X1-03804-8")); assertNull(MetadataUtil.toIsbn13("02X1038048")); assertNull(MetadataUtil.toIsbn13("xyzzy")); // test ISBN formatting assertEquals("978-0-201-03804-0", MetadataUtil.formatIsbn("9780201038040")); assertEquals("0-201-03804-8", MetadataUtil.formatIsbn("0201038048")); assertEquals("xyzzy", MetadataUtil.formatIsbn("xyzzy")); } public void testISSN() { for(int i=0; i<validISSNS.length;i++){ String validIssn = validISSNS[i]; assertTrue(MetadataUtil.isIssn(validIssn)); assertEquals(validIssn, MetadataUtil.validateIssn(validIssn)); } for(int j=0; j<malformedISSNS.length;j++){ String malformedIssn = malformedISSNS[j]; assertFalse(MetadataUtil.isIssn(malformedIssn)); assertEquals(null, MetadataUtil.validateIssn(malformedIssn)); } // invalid with checksum calculations for(int j=0; j<invalidISSNS.length;j++){ String invalidIssn = invalidISSNS[j]; assertFalse(MetadataUtil.isIssn(invalidISSNS[j], true)); assertEquals(null, MetadataUtil.validateIssn(invalidIssn, true)); } // valid ignoring checksum calculations for(int j=0; j<invalidISSNS.length;j++){ String invalidIssn = invalidISSNS[j]; assertTrue(MetadataUtil.isIssn(invalidIssn, false)); assertEquals(invalidIssn, MetadataUtil.validateIssn(invalidIssn, false)); } // test ISSN formatting functions assertEquals("1234-5678", MetadataUtil.formatIssn("12345678")); assertEquals("xyzzy", MetadataUtil.formatIssn("xyzzy")); } public void testDOI() throws UnsupportedEncodingException { for(int i=0; i<validDOIS.length;i++){ assertTrue(MetadataUtil.isDoi(URLDecoder.decode(validDOIS[i], Constants.ENCODING_UTF_8))); } for(int j=0; j<invalidDOIS.length;j++){ assertFalse(MetadataUtil.isDoi(invalidDOIS[j])); } } }
package com.google.sps.utils; // Imports the Google Cloud client library import com.google.cloud.dialogflow.v2.QueryInput; import com.google.cloud.dialogflow.v2.QueryResult; import com.google.gson.Gson; import com.google.protobuf.ByteString; import com.google.protobuf.Struct; import com.google.protobuf.Value; import com.google.sps.utils.TextUtils; import com.google.sps.utils.SpeechUtils; import com.google.sps.data.Location; import com.google.sps.data.Output; import com.google.sps.agents.*; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Map; import java.util.stream.Collectors; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; /** * Identifies agent from Dialogflow API Query result and creates Output object */ public class AgentUtils { public static Output getOutput(QueryResult queryResult, String languageCode) { String fulfillment = null; String display = null; String redirect = null; byte[] byteStringToByteArray = null; Agent object = null; String detectedIntent = queryResult.getIntent().getDisplayName(); String agentName = getAgentName(detectedIntent); String intentName = getIntentName(detectedIntent); // Retrieve detected input from DialogFlow result. String inputDetected = queryResult.getQueryText(); inputDetected = inputDetected.equals("") ? " (null) " : inputDetected; Map<String, Value> parameterMap = getParameterMap(queryResult); object = getAgent(agentName, intentName, parameterMap); if (object != null) { fulfillment = object.getOutput(); fulfillment = fulfillment == null ? queryResult.getFulfillmentText() : fulfillment; display = object.getDisplay(); redirect = object.getRedirect(); } else { fulfillment = queryResult.getFulfillmentText(); } fulfillment = fulfillment.equals("") ? "Can you repeat that?" : fulfillment; byteStringToByteArray = getByteStringToByteArray(fulfillment, languageCode); Output output = new Output(inputDetected, fulfillment, byteStringToByteArray, display, redirect); return output; } private static Agent getAgent(String agentName, String intentName, Map<String, Value> parameterMap) { switch(agentName) { case "calculator": return new Tip(intentName, parameterMap); case "currency": return new Currency(intentName, parameterMap); case "language": return new Language(intentName, parameterMap); case "name": return new Name(intentName, parameterMap); case "reminders": return new Reminders(intentName, parameterMap); case "time": return new Time(intentName, parameterMap); case "translate": return new TranslateAgent(intentName, parameterMap); case "units": return new UnitConverter(intentName, parameterMap); case "weather": return new Weather(intentName, parameterMap); case "web": return new WebSearch(intentName, parameterMap); default: return null; } } private static String getAgentName(String detectedIntent) { String[] intentList = detectedIntent.split("\\.", 2); return intentList[0]; } private static String getIntentName(String detectedIntent) { String[] intentList = detectedIntent.split("\\.", 2); String intentName = detectedIntent; if (intentList.length > 1) { intentName = intentList[1]; } return intentName; } public static Map<String, Value> getParameterMap(QueryResult queryResult) { Struct paramStruct = queryResult.getParameters(); Map<String, Value> parameters = paramStruct.getFieldsMap(); return parameters; } public static byte[] getByteStringToByteArray(String fulfillment, String languageCode){ byte[] byteArray = null; try { ByteString audioResponse = SpeechUtils.synthesizeText(fulfillment, languageCode); byteArray = audioResponse.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return byteArray; } public static String getLanguageCode(String language) { if (language == null) { return "en-US"; } switch(language) { case "Chinese": return "zh-CN"; case "English": return "en-US"; case "French": return "fr"; case "German": return "de"; case "Hindi": return "hi"; case "Italian": return "it"; case "Japanese": return "ja"; case "Korean": return "ko"; case "Portuguese": return "pt"; case "Russian": return "ru"; case "Spanish": return "es"; case "Swedish": return "sv"; default: return null; } } }
package com.facebook.presto.cli; import com.facebook.presto.execution.FailureInfo; import com.facebook.presto.execution.QueryInfo; import com.facebook.presto.execution.StageInfo; import com.facebook.presto.execution.TaskInfo; import com.facebook.presto.operator.Operator; import com.facebook.presto.operator.OutputProcessor; import com.facebook.presto.server.HttpQueryClient; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import sun.misc.Signal; import sun.misc.SignalHandler; import java.io.Closeable; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.util.List; import java.util.Set; import static com.facebook.presto.operator.OutputProcessor.OutputHandler; import static com.facebook.presto.operator.OutputProcessor.OutputStats; import static com.google.common.base.Preconditions.checkNotNull; public class Query implements Closeable { private static final Signal SIGINT = new Signal("INT"); private final HttpQueryClient queryClient; public Query(HttpQueryClient queryClient) { this.queryClient = checkNotNull(queryClient, "queryClient is null"); } public void renderOutput(PrintStream out) { SignalHandler oldHandler = Signal.handle(SIGINT, new SignalHandler() { @Override public void handle(Signal signal) { cancelLeafStage(); } }); try { renderQueryOutput(out); } finally { Signal.handle(SIGINT, oldHandler); } } private void renderQueryOutput(PrintStream out) { StatusPrinter statusPrinter = new StatusPrinter(queryClient, out); statusPrinter.printInitialStatusUpdates(); QueryInfo queryInfo = queryClient.getQueryInfo(false); if (queryInfo == null) { out.println("Query is gone (server restarted?)"); return; } if (queryInfo.getState().isDone()) { switch (queryInfo.getState()) { case CANCELED: out.printf("Query %s was canceled\n", queryInfo.getQueryId()); return; case FAILED: renderFailure(queryInfo, out); return; } } Operator operator = queryClient.getResultsOperator(); List<String> fieldNames = queryInfo.getFieldNames(); OutputStats stats = pageOutput(Pager.LESS, operator, fieldNames); // print final info after the user exits from the pager statusPrinter.printFinalInfo(stats); } private static OutputStats pageOutput(List<String> pagerCommand, Operator operator, List<String> fieldNames) { try (Pager pager = Pager.create(pagerCommand)) { @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") OutputStreamWriter writer = new OutputStreamWriter(pager, Charsets.UTF_8); OutputHandler outputHandler = new AlignedTuplePrinter(fieldNames, writer); OutputProcessor processor = new OutputProcessor(operator, outputHandler); return processor.process(); } } public void cancelLeafStage() { queryClient.cancelLeafStage(); } @Override public void close() { queryClient.destroy(); } public void renderFailure(QueryInfo queryInfo, PrintStream out) { if (queryClient.isDebug()) { out.printf("Query %s failed:\n", queryInfo.getQueryId()); renderStacks(queryInfo, out); return; } Set<String> failureMessages = ImmutableSet.copyOf(getFailureMessages(queryInfo)); if (failureMessages.isEmpty()) { out.printf("Query %s failed for an unknown reason\n", queryInfo.getQueryId()); } else if (failureMessages.size() == 1) { out.printf("Query %s failed: %s\n", queryInfo.getQueryId(), Iterables.getOnlyElement(failureMessages)); } else { out.printf("Query %s failed:\n", queryInfo.getQueryId()); for (String failureMessage : failureMessages) { out.println(" " + failureMessage); } } } private static void renderStacks(QueryInfo queryInfo, PrintStream out) { for (FailureInfo failureInfo : queryInfo.getFailures()) { failureInfo.toException().printStackTrace(out); } if (queryInfo.getOutputStage() != null) { renderStacks(queryInfo.getOutputStage(), out); } } private static void renderStacks(StageInfo stageInfo, PrintStream out) { if (!stageInfo.getFailures().isEmpty()) { out.printf("Stage %s failed:\n", stageInfo.getStageId()); for (FailureInfo failureInfo : stageInfo.getFailures()) { failureInfo.toException().printStackTrace(out); } } for (TaskInfo taskInfo : stageInfo.getTasks()) { renderStacks(taskInfo, out); } for (StageInfo subStageInfo : stageInfo.getSubStages()) { renderStacks(subStageInfo, out); } } private static void renderStacks(TaskInfo taskInfo, PrintStream out) { if (!taskInfo.getFailures().isEmpty()) { out.printf("Task %s failed:\n", taskInfo.getTaskId()); for (FailureInfo failureInfo : taskInfo.getFailures()) { failureInfo.toException().printStackTrace(out); } } } public static List<String> getFailureMessages(QueryInfo queryInfo) { ImmutableList.Builder<String> builder = ImmutableList.builder(); for (FailureInfo failureInfo : queryInfo.getFailures()) { builder.add(failureInfo.getMessage()); } if (queryInfo.getOutputStage() != null) { builder.addAll(getFailureMessages(queryInfo.getOutputStage())); } return builder.build(); } public static List<String> getFailureMessages(StageInfo stageInfo) { ImmutableList.Builder<String> builder = ImmutableList.builder(); for (FailureInfo failureInfo : stageInfo.getFailures()) { builder.add(failureInfo.getMessage()); } for (TaskInfo taskInfo : stageInfo.getTasks()) { builder.addAll(getFailureMessages(taskInfo)); } for (StageInfo subStageInfo : stageInfo.getSubStages()) { builder.addAll(getFailureMessages(subStageInfo)); } return builder.build(); } private static List<String> getFailureMessages(TaskInfo taskInfo) { ImmutableList.Builder<String> builder = ImmutableList.builder(); for (FailureInfo failureInfo : taskInfo.getFailures()) { builder.add(failureInfo.getMessage()); } return builder.build(); } }
package org.jgroups.tests; import junit.framework.TestCase; import org.jgroups.*; import org.jgroups.stack.IpAddress; import java.util.HashMap; import java.util.Map; /** * * @author Bela Ban * @version $Id: AddDataTest.java,v 1.9 2007/03/06 09:07:27 belaban Exp $ */ public class AddDataTest extends TestCase { JChannel ch1, ch2; String properties="udp.xml"; String bundlingProperties="UDP(mcast_addr=228.1.2.3;mcast_port=45566;ip_ttl=32;" + "enable_bundling=true;max_bundle_size=3000;max_bundle_timeout=500):" + "PING(timeout=2000;num_initial_members=2):" + "pbcast.NAKACK(gc_lag=10;retransmit_timeout=600,1200,2400,4800):" + "UNICAST(timeout=600,1200,2400,4800):" + "pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;" + "shun=true;print_local_addr=true)"; public AddDataTest(String name) { super(name); } protected void tearDown() throws Exception { super.tearDown(); if(ch2 != null) ch2.close(); if(ch1 != null) ch1.close(); } /** * Uncomment to test shunning/reconnecting (using CTRL-Z and fg) */ // public void testAdditionalDataWithShun() { // try { // JChannel c=new JChannel(props); // Map m=new HashMap(); // m.put("additional_data", new byte[]{'b', 'e', 'l', 'a'}); // c.down(new Event(Event.CONFIG, m)); // c.setOpt(Channel.AUTO_RECONNECT, Boolean.TRUE); // c.setChannelListener(new ChannelListener() { // public void channelDisconnected(Channel channel) { // System.out.println("channel disconnected"); // public void channelShunned() { // System.out.println("channel shunned"); // public void channelReconnected(Address addr) { // System.out.println("channel reconnected"); // public void channelConnected(Channel channel) { // System.out.println("channel connected"); // public void channelClosed(Channel channel) { // System.out.println("channel closed"); // System.out.println("CONNECTING"); // c.connect("bla"); // System.out.println("CONNECTING: done"); // IpAddress addr=(IpAddress)c.getLocalAddress(); // System.out.println("address is " + addr); // assertNotNull(addr.getAdditionalData()); // assertEquals(addr.getAdditionalData()[0], 'b'); // Util.sleep(600000); // c.close(); // catch(ChannelException e) { // e.printStackTrace(); // fail(e.toString()); public void testAdditionalData() { try { for(int i=1; i <= 5; i++) { System.out.println("-- attempt # " + i + "/10"); JChannel c=new JChannel(properties); Map m=new HashMap(); m.put("additional_data", new byte[]{'b', 'e', 'l', 'a'}); c.down(new Event(Event.CONFIG, m)); c.connect("bla"); IpAddress addr=(IpAddress)c.getLocalAddress(); System.out.println("address is " + addr); assertNotNull(addr.getAdditionalData()); assertEquals('b', addr.getAdditionalData()[0]); c.close(); } } catch(ChannelException e) { e.printStackTrace(); fail(e.toString()); } } public void testBetweenTwoChannelsMcast() throws Exception { _testWithProps(this.properties, true); } public void testBetweenTwoChannelsUnicast() throws Exception { _testWithProps(this.properties, false); } public void testBetweenTwoChannelsWithBundlingMcast() throws Exception { _testWithProps(this.bundlingProperties, true); } public void testBetweenTwoChannelsWithBundlingUnicast() throws Exception { _testWithProps(this.bundlingProperties, false); } private void _testWithProps(String props, boolean mcast) throws Exception { Map m=new HashMap(); m.put("additional_data", new byte[]{'b', 'e', 'l', 'a'}); byte[] buf=new byte[1000]; ch1=new JChannel(props); ch1.down(new Event(Event.CONFIG, m)); ch2=new JChannel(props); ch2.down(new Event(Event.CONFIG, m)); ch1.connect("group"); ch2.connect("group"); while(ch2.peek(10) != null) { System.out.println("-- received " + ch2.receive(100)); } if(mcast) ch1.send(new Message(null, null, buf)); else { Address dest=ch2.getLocalAddress(); ch1.send(new Message(dest, null, buf)); } Message msg=(Message)ch2.receive(10000); System.out.println("received " + msg); IpAddress src=(IpAddress)msg.getSrc(); System.out.println("src=" + src); // Thread.sleep(600000); // todo: remove assertNotNull(src); assertNotNull(src.getAdditionalData()); assertEquals(4, src.getAdditionalData().length); } public static void main(String[] args) { String[] testCaseName={AddDataTest.class.getName()}; junit.textui.TestRunner.main(testCaseName); } }
package org.jgroups.tests; import org.jgroups.*; import org.jgroups.util.Util; import org.testng.annotations.Test; import java.util.LinkedList; import java.util.List; /** * Tests various methods in JChannel * @author Bela Ban * @version $Id: ChannelTest.java,v 1.23 2008/10/13 14:20:37 vlada Exp $ */ @Test(groups=Global.STACK_DEPENDENT,sequential=false) public class ChannelTest extends ChannelTestBase { @Test public void testBasicOperations() throws Exception { JChannel c1 = createChannel(true,1); JChannel c2=null; try { c1.connect("testBasicOperations"); assert c1.isOpen(); assert c1.isConnected(); assert c1.getLocalAddress() != null; assert c1.getView() != null; assert c1.getView().getMembers().contains(c1.getLocalAddress()); c1.connect("testBasicOperations"); c1.disconnect(); assert c1.isConnected() == false; assert c1.isOpen(); assert c1.getLocalAddress() == null; assert c1.getView() == null; assert c1.getClusterName() == null; c1.connect("testBasicOperations"); c1.close(); try { c1.connect("testBasicOperations"); throw new IllegalStateException("Should generated exception, and it has NOT"); } catch (Exception e) { assert e instanceof ChannelClosedException; } assert c1.isConnected() == false; assert c1.isOpen() == false; assert c1.getLocalAddress() == null; assert c1.getView() == null; assert c1.getClusterName() == null; c1 = createChannel(true,2); c1.connect("testBasicOperations"); c2 = createChannel(c1); c2.connect("testBasicOperations"); Util.sleep(1000); assert c1.isOpen(); assert c1.isConnected(); assert c1.getLocalAddress() != null; assert c1.getView() != null; assert c1.getView().getMembers().contains(c1.getLocalAddress()); assert c1.getView().getMembers().contains(c2.getLocalAddress()); assert c2.isOpen(); assert c2.isConnected(); assert c2.getLocalAddress() != null; assert c2.getView() != null; assert c2.getView().getMembers().contains(c2.getLocalAddress()); assert c2.getView().getMembers().contains(c1.getLocalAddress()); c2.close(); Util.sleep(1000); assert c2.isOpen() == false; assert c2.isConnected() == false; assert c2.getLocalAddress() == null; assert c2.getView() == null; assert c1.isOpen(); assert c1.isConnected(); assert c1.getLocalAddress() != null; assert c1.getView() != null; assert c1.getView().getMembers().contains(c1.getLocalAddress()); assert c1.getView().getMembers().contains(c2.getLocalAddress()) == false; } finally { Util.close(c1,c2); } } @Test public void testViewChange() throws Exception { JChannel ch1 = createChannel(true,2); ViewChecker checker=new ViewChecker(ch1); ch1.setReceiver(checker); ch1.connect("testViewChange"); Channel ch2=createChannel(ch1); try { ch2.connect("testViewChange"); assertTrue(checker.getReason(), checker.isSuccess()); ch2.close(); assertTrue(checker.getReason(), checker.isSuccess()); } finally { Util.close(ch1,ch2); } } @Test public void testIsConnectedOnFirstViewChange() throws Exception { JChannel ch1 = createChannel(true,2); Channel ch2=createChannel(ch1); ConnectedChecker tmp=new ConnectedChecker(ch2); ch2.setReceiver(tmp); try { ch1.connect("testIsConnectedOnFirstViewChange"); ch2.connect("testIsConnectedOnFirstViewChange"); assertFalse(tmp.isConnected()); } finally { Util.close(ch1,ch2); } } @Test public void testNoViewIsReceivedAferDisconnect() throws Exception { JChannel ch1 = createChannel(true,2); Channel ch2=createChannel(ch1); MyViewChecker ra = new MyViewChecker(ch2); ch2.setReceiver(ra); try { ch1.connect("testNoViewIsReceivedAferDisconnect"); ch2.connect("testNoViewIsReceivedAferDisconnect"); Util.sleep(500); ch2.disconnect(); Util.sleep(1000); assert !ra.receivedViewWhenDisconnected : "Received view where not member"; } finally { Util.close(ch1,ch2); } } @Test public void testNoViewIsReceivedAferClose() throws Exception { JChannel ch1 = createChannel(true,2); Channel ch2=createChannel(ch1); MyViewChecker ra = new MyViewChecker(ch2); ch2.setReceiver(ra); try { ch1.connect("testNoViewIsReceivedAferClose"); ch2.connect("testNoViewIsReceivedAferClose"); Util.sleep(200); ch2.close(); Util.sleep(1000); assert !ra.receivedViewWhenDisconnected : "Received view where not member"; } finally { Util.close(ch1,ch2); } } @Test(expectedExceptions=TimeoutException.class) public void testReceiveTimeout() throws Exception, TimeoutException { JChannel ch1 = createChannel(true,2); try{ ch1.connect("testReceiveTimeout"); ch1.receive(1000); // this one works, because we're expecting a View ch1.receive(2000);// .. but this one doesn't (no msg available) - needs to throw a TimeoutException } finally{ Util.close(ch1); } } @Test(expectedExceptions={NullPointerException.class}) public void testNullMessage() throws Exception { JChannel ch1 = createChannel(true,2); try{ ch1.connect("testNullMessage"); ch1.send(null); } finally{ Util.close(ch1); } } @Test public void testOrdering() throws Exception { final int NUM=100; JChannel ch=createChannel(true, 2); MyReceiver receiver=new MyReceiver(NUM); ch.setReceiver(receiver); try { ch.connect("testOrdering"); for(int i=1;i <= NUM;i++) { ch.send(new Message(null, null, new Integer(i))); // System.out.println("-- sent " + i); } receiver.waitForCompletion(); List<Integer> nums=receiver.getNums(); checkMonotonicallyIncreasingNumbers(nums); } finally { Util.close(ch); } } private static void checkMonotonicallyIncreasingNumbers(List<Integer> nums) { int current=-1; for(int num: nums) { if(current < 0) { current=num; } else { assert ++current == num : "list is " + nums; } } } private static class MyReceiver extends ReceiverAdapter { final List<Integer> nums=new LinkedList<Integer>(); final int expected; public MyReceiver(int expected) { this.expected=expected; } public List<Integer> getNums() { return nums; } public void waitForCompletion() throws InterruptedException { synchronized(nums) { while(nums.size() < expected) { nums.wait(); } } } public void receive(Message msg) { Integer num=(Integer)msg.getObject(); synchronized(nums) { nums.add(num); if(nums.size() >= expected) { nums.notifyAll(); } } } } private static class ConnectedChecker extends ReceiverAdapter { boolean connected=false; public ConnectedChecker(Channel channel) { this.channel=channel; } final Channel channel; public boolean isConnected() { return connected; } public void viewAccepted(View new_view) { connected=channel.isConnected(); // System.out.println("ConnectedChecker: channel.isConnected()=" + connected + ", view=" + new_view); } } private static class ViewChecker extends ReceiverAdapter { final Channel channel; boolean success=true; String reason=""; public ViewChecker(Channel channel) { this.channel=channel; } public String getReason() { return reason; } public boolean isSuccess() { return success; } public void viewAccepted(View new_view) { View view=channel.getView(); String str="viewAccepted(): channel's view=" + view + "\nreceived view=" + new_view; // System.out.println(str); if(view!= null && !view.equals(new_view)) { success=false; reason+=str + "\n"; } } } private static class MyViewChecker extends ReceiverAdapter { private boolean receivedViewWhenDisconnected; private final Channel ch; public MyViewChecker(Channel ch) { this.ch=ch; } public void viewAccepted(View new_view) { receivedViewWhenDisconnected = !new_view.containsMember(ch.getLocalAddress()); } } }
// $Id: UnicastTest.java,v 1.15 2010/01/08 13:25:28 belaban Exp $ package org.jgroups.tests; import org.jgroups.*; import org.jgroups.jmx.JmxConfigurator; import org.jgroups.protocols.UNICAST; import org.jgroups.util.Util; import org.jgroups.util.Streamable; import javax.management.MBeanServer; import java.io.*; import java.util.Vector; /** * Tests the UNICAST by sending unicast messages between a sender and a receiver * * @author Bela Ban */ public class UnicastTest extends ReceiverAdapter { private JChannel channel; private final MyReceiver receiver=new MyReceiver(); static final String groupname="UnicastTest-Group"; private long sleep_time=0; private boolean exit_on_end=false, busy_sleep=false; public void init(String props, long sleep_time, boolean exit_on_end, boolean busy_sleep) throws Exception { this.sleep_time=sleep_time; this.exit_on_end=exit_on_end; this.busy_sleep=busy_sleep; channel=new JChannel(props); channel.connect(groupname); channel.setReceiver(receiver); try { MBeanServer server=Util.getMBeanServer(); JmxConfigurator.registerChannel(channel, server, "jgroups", channel.getClusterName(), true); } catch(Throwable ex) { System.err.println("registering the channel in JMX failed: " + ex); } } public void eventLoop() throws Exception { int c; while(true) { System.out.print("[1] Send msgs [2] Print view [3] Print connections " + "[4] Trash connection [5] Trash all connections [q] Quit "); System.out.flush(); c=System.in.read(); switch(c) { case -1: break; case '1': sendMessages(); break; case '2': printView(); break; case '3': printConnections(); break; case '4': removeConnection(); break; case '5': removeAllConnections(); break; case '6': break; case 'q': channel.close(); return; default: break; } } } private void printConnections() { UNICAST unicast=(UNICAST)channel.getProtocolStack().findProtocol(UNICAST.class); System.out.println("connections:\n" + unicast.printConnections()); } private void removeConnection() { Address member=getReceiver(); if(member != null) { UNICAST unicast=(UNICAST)channel.getProtocolStack().findProtocol(UNICAST.class); unicast.removeConnection(member); } } private void removeAllConnections() { UNICAST unicast=(UNICAST)channel.getProtocolStack().findProtocol(UNICAST.class); unicast.removeAllConnections(); } void sendMessages() throws Exception { long num_msgs=Util.readLongFromStdin("Number of messages: "); int msg_size=Util.readIntFromStdin("Message size: "); Address destination=getReceiver(); Message msg; if(destination == null) { System.err.println("UnicastTest.sendMessages(): receiver is null, cannot send messages"); return; } System.out.println("sending " + num_msgs + " messages to " + destination); byte[] buf=Util.objectToByteBuffer(new StartData(num_msgs)); msg=new Message(destination, null, buf); channel.send(msg); int print=(int)(num_msgs / 10); for(int i=1; i <= num_msgs; i++) { Value val=new Value(i, msg_size); buf=Util.objectToByteBuffer(val); msg=new Message(destination, null, buf); if(i % print == 0) System.out.println("-- sent " + i); channel.send(msg); if(sleep_time > 0) Util.sleep(sleep_time, busy_sleep); } System.out.println("done sending " + num_msgs + " to " + destination); } void printView() { System.out.println("\n-- view: " + channel.getView() + '\n'); try { System.in.skip(System.in.available()); } catch(Exception e) { } } private Address getReceiver() { Vector mbrs=null; int index; BufferedReader reader; String tmp; try { mbrs=channel.getView().getMembers(); System.out.println("pick receiver from the following members:"); for(int i=0; i < mbrs.size(); i++) { if(mbrs.elementAt(i).equals(channel.getAddress())) System.out.println("[" + i + "]: " + mbrs.elementAt(i) + " (self)"); else System.out.println("[" + i + "]: " + mbrs.elementAt(i)); } System.out.flush(); System.in.skip(System.in.available()); reader=new BufferedReader(new InputStreamReader(System.in)); tmp=reader.readLine().trim(); index=Integer.parseInt(tmp); return (Address)mbrs.elementAt(index); // index out of bounds caught below } catch(Exception e) { System.err.println("UnicastTest.getReceiver(): " + e); return null; } } public static void main(String[] args) { long sleep_time=0; boolean exit_on_end=false; boolean busy_sleep=false; String props=null; for(int i=0; i < args.length; i++) { if("-props".equals(args[i])) { props=args[++i]; continue; } if("-sleep".equals(args[i])) { sleep_time=Long.parseLong(args[++i]); continue; } if("-exit_on_end".equals(args[i])) { exit_on_end=true; continue; } if("-busy_sleep".equals(args[i])) { busy_sleep=true; continue; } help(); return; } try { UnicastTest test=new UnicastTest(); test.init(props, sleep_time, exit_on_end, busy_sleep); test.eventLoop(); } catch(Exception ex) { System.err.println(ex); } } static void help() { System.out.println("UnicastTest [-help] [-props <props>] [-sleep <time in ms between msg sends] " + "[-exit_on_end] [-busy-sleep]"); } public abstract static class Data implements Streamable { } public static class StartData extends Data { long num_values=0; public StartData() {} StartData(long num_values) { this.num_values=num_values; } public void writeTo(DataOutputStream out) throws IOException { out.writeLong(num_values); } public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { num_values=in.readLong(); } } public static class Value extends Data { long value=0; byte[] buf=null; public Value() { } Value(long value, int len) { this.value=value; if(len > 0) this.buf=new byte[len]; } public void writeTo(DataOutputStream out) throws IOException { out.writeLong(value); if(buf != null) { out.writeInt(buf.length); out.write(buf, 0, buf.length); } else { out.writeInt(0); } } public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { value=in.readLong(); int len=in.readInt(); if(len > 0) { buf=new byte[len]; in.read(buf, 0, len); } } } private class MyReceiver extends ReceiverAdapter { private Data data; private boolean started=false; private long start=0, stop=0; private long current_value=0, tmp=0, num_values=0; private long total_time=0, msgs_per_sec; public void receive(Message msg) { try { data=(Data)Util.objectFromByteBuffer(msg.getRawBuffer(), msg.getOffset(), msg.getLength()); } catch(Exception e) { e.printStackTrace(); return; } if(data instanceof StartData) { if(started) { System.err.println("UnicastTest.run(): received START data, but am already processing data"); } else { started=true; current_value=0; // first value to be received tmp=0; num_values=((StartData)data).num_values; start=System.currentTimeMillis(); } } else if(data instanceof Value) { tmp=((Value)data).value; if(current_value + 1 != tmp) { System.err.println("-- message received (" + tmp + ") is not 1 greater than " + current_value); } else { current_value++; if(current_value % (num_values / 10) == 0) System.out.println("received " + current_value); if(current_value >= num_values) { stop=System.currentTimeMillis(); total_time=stop - start; msgs_per_sec=(long)(num_values / (total_time / 1000.0)); System.out.println("-- received " + num_values + " messages in " + total_time + " ms (" + msgs_per_sec + " messages/sec)"); started=false; if(exit_on_end) System.exit(0); } } } } public void viewAccepted(View new_view) { System.out.println("** view: " + new_view); } } }
import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; /** * * @author Hyun Choi, Ted Pyne, Patrick Forelli */ public class CheckersGUI extends javax.swing.JFrame { //keeps track of a Board, a 2d array of JLabels to represent each tile, and JPanel to store the tiles public Board board; private JLabel[][] GUIboard; //JPanel entireGUI for the enclosure of both the board and the text private JPanel entireGUI; //outer JPanel panel for the outer board panel, boardGUI for the inner board panel private JPanel panel; private JPanel boardGUI; //JPanel for textual info; JLabels/JButton for information and toggling private JPanel text; GridBagConstraints c; private JLabel victoryStatus; private JLabel turnStatus; private JButton aiToggle; private JLabel aiDifficulty; private JButton newGame; //AI implementation private MoveAI ai; private boolean aiActive; private JSlider difficulty; private boolean selected = false; //if a piece is selected or not private int[][] currentSelected; //coordinates of the selected piece and the target area private final int MULTIPLIER = 62; //width of one tile /** * Creates new form CheckersGUI */ public CheckersGUI() { board = new Board(); GUIboard = new JLabel[8][8]; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { //if(board.getPiece(i,j) != null) GUIboard[i][j] = new JLabel(); } } entireGUI = new JPanel(); //outer JPanel to store the boardGUI and the textual information entireGUI.setLayout(new BoxLayout(entireGUI, BoxLayout.X_AXIS)); aiActive = false; //by default, AI is inactive text = new JPanel(); //inner JPanel to hold textual information text.setLayout(new GridBagLayout()); c = new GridBagConstraints(); initializeBoardGUI(); //initalizes board side of gui initializeText(); //initializes text side of gui currentSelected = new int[2][2]; panel = new JPanel(); //enclose GridLayout within JPanel on the JFrame panel.add(boardGUI); renderBoard(); //render board on the GUI } public void renderBoard() //method to arrange images to form the board { boolean previousColorIsWhite = false; //for arrangement for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (board.getPiece(i,j) != null) //Get the piece at that space in the board { if (board.getPiece(i,j).getIsWhite())//if the piece is white { if (board.getPiece(i,j).getIsKing()) GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithwhiteking.png"))); else GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithwhite.png"))); } else //so that means it's a red { if (board.getPiece(i,j).getIsKing()) GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithredking.png"))); else GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithred.png"))); } previousColorIsWhite=true; } else //if no piece, then blank tile (white or green) { if (previousColorIsWhite) GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/greentile.png"))); else GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitetile.png"))); previousColorIsWhite = !previousColorIsWhite; } boardGUI.add(GUIboard[i][j]); } previousColorIsWhite=!previousColorIsWhite; } refreshText(); //update the text fields //combine the two components of the GUI entireGUI.add(panel); entireGUI.add(text); setResizable(false); //window cannot be resized //make it visible pack(); this.setContentPane(entireGUI); setVisible(true); } public void initializeBoard() { board = new Board(); GUIboard = new JLabel[8][8]; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { //if(board.getPiece(i,j) != null) GUIboard[i][j] = new JLabel(); } } initializeBoardGUI(); entireGUI.remove(panel); panel = new JPanel(); panel.add(boardGUI); renderBoard(); } public void initializeBoardGUI() { boardGUI = new JPanel(); boardGUI.setLayout(new GridLayout(8,8)); //tiles in a GridLayout of 8x8 boardGUI.addMouseListener(new MouseAdapter() { //essence of the GUI's click detection int selected =0; public void mouseClicked(MouseEvent e) { if (selected==0) //if nothing is selected { currentSelected[0]=arrayCoord(pressed(e)); //store coordinates of the press in array selected++; //if invalid selection, revert if(!board.isValidSelection(currentSelected[0][1], currentSelected[0][0])){ currentSelected = new int[2][2]; selected=0; } else { //If a valid selection has been made, highlight the piece to the user int i = currentSelected[0][1]; int j = currentSelected[0][0]; if (board.getPiece(i,j).getIsWhite())//if the piece is white { if (board.getPiece(i,j).getIsKing()) GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithwhitekingselected.png"))); else GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithwhiteselected.png"))); } else //so that means it's a red { if (board.getPiece(i,j).getIsKing()) GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithredkingselected.png"))); else GUIboard[i][j].setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/whitewithredselected.png"))); } } } else if (selected ==1) //Target tile { //using the coordinates, make a move and render the board on the GUI currentSelected[1]=arrayCoord(pressed(e)); TurnProcessor turnProc = new TurnProcessor(currentSelected[0][1], currentSelected[0][0], currentSelected[1][1], currentSelected[1][0], board); if(currentSelected[1][1]==currentSelected[0][1] && currentSelected[0][0] == currentSelected[1][0]){ //If the player clicked on their first selection, deselect it currentSelected = new int[2][2]; selected=0; renderBoard(); } else if(!turnProc.isValidTurn()){ //If the selection is invalid, wait for a valid one selected = 1; } else{ //If a valid selection, do the move move(currentSelected); renderBoard(); //revert to original state currentSelected = new int[2][2]; selected=0; } makeAllAIMoves(); } } }); } private void makeAllAIMoves(){ if(ai!=null) while(!board.isWhiteTurn() && board.gameIsWon()==null){ ai.makeMove(); renderBoard(); } } private void initializeText() { c.ipady=80; final JLabel VICTORY = new JLabel ("VICTORY"); //victory text c.gridx=0; c.gridy=0; text.add(VICTORY, c); victoryStatus = new JLabel(); //victory status c.gridx=1; c.gridy=0; text.add(victoryStatus, c); final JLabel TURN = new JLabel ("TURN"); c.gridx=0; c.gridy=1; text.add(TURN, c); turnStatus = new JLabel(); c.gridx=1; c.gridy=1; text.add(turnStatus, c); final JLabel AI = new JLabel ("AI STATUS"); c.gridx=0; c.gridy=2; text.add(AI, c); aiToggle = new JButton("AI INACTIVE"); FontMetrics fm = aiToggle.getFontMetrics(aiToggle.getFont()); int w = fm.stringWidth("AI INACTIVE "); int h = fm.getHeight(); Dimension size = new Dimension (w,h); aiToggle.setMinimumSize(size); aiToggle.setPreferredSize(size); c.gridx=1; c.gridy=2; c.ipady=40; c.ipadx=40; text.add(aiToggle, c); aiToggle.addActionListener(new ActionListener() { //button for toggling AI activation status public void actionPerformed(ActionEvent e) { aiActive = !aiActive; if (aiActive) { ai = new AI2(board); aiToggle.setText("AI ACTIVE "); difficultyToggle(); makeAllAIMoves(); } else { aiToggle.setText("AI INACTIVE"); ai = null; difficultyToggle(); } } }); newGame = new JButton ("PLAY NEW GAME"); c.gridx=0; c.gridy=4; c.gridwidth=2; c.fill = GridBagConstraints.HORIZONTAL; newGame.addActionListener(new ActionListener() { //button to reset game public void actionPerformed(ActionEvent e) { initializeBoard(); } }); text.add(newGame,c); final JLabel name = new JLabel ("PCCheckers"); name.setFont(new Font("Courier New", Font.ITALIC, 16)); c.gridx=0; c.gridy=5; c.gridwidth=2; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.CENTER; c.ipady=0; text.add(name,c); final JLabel copyright = new JLabel ("\u00a9" + "PC Software Solutions"); copyright.setFont(new Font("Courier New", Font.ITALIC, 16)); c.gridx=0; c.gridy=6; c.gridwidth=2; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.CENTER; text.add(copyright,c); } private void difficultyToggle() { if (aiActive) { aiDifficulty = new JLabel ("AI DIFFICULTY"); c.gridx=0; c.gridy=3; text.add(aiDifficulty, c); difficulty = new JSlider(JSlider.HORIZONTAL, 25, 200, 150); //slider for AI aggression level difficulty.setMajorTickSpacing(25); difficulty.setPaintTicks(true);//ticks difficulty.setPaintLabels(true);//numbers at ticks difficulty.addChangeListener(new ChangeListener(){ public void stateChanged(ChangeEvent e){ JSlider source = (JSlider) e.getSource(); if (!source.getValueIsAdjusting()) { double newValue = (double)source.getValue()/100; AI2.setAggression(newValue); System.out.println(newValue); } } }); c.gridx=1; c.gridy=3; text.add(difficulty, c); } else { text.remove(aiDifficulty); text.remove(difficulty); } } private void refreshText() { if (board.gameIsWon()!=null) //set victor if there is one { if (board.gameIsWon().getIsWhite()) { victoryStatus.setText("WHITE"); } else { victoryStatus.setText("RED"); } } else { victoryStatus.setText("???"); } if (board.isWhiteTurn()) //display turn turnStatus.setText("WHITE"); else turnStatus.setText("RED"); } private int[] pressed(MouseEvent e) //returns pixel coordinates where clicked { Component c = boardGUI.findComponentAt(e.getX(), e.getY()); int[] coordinates = new int[2]; coordinates[0] = e.getX(); coordinates[1] = e.getY(); return coordinates; } private int[] arrayCoord(int[] pixelCoord) //returns coordinates within the checkerboard, limited to [0,0] to [7,7] { for (int i=0; i<2; i++) pixelCoord[i] /= MULTIPLIER; //Divide the pixel by the width of each piece return pixelCoord; } private void move(int[][] currentSelected) //moves the pieces in the Board variable { board.makeMove(currentSelected[0][1],currentSelected[0][0],currentSelected[1][1],currentSelected[1][0]); } public static void main (String[] args) //Run the game! { CheckersGUI gui = new CheckersGUI(); gui.renderBoard(); } }
//FILE: OughtaFocus.java //PROJECT: Micro-Manager //SUBSYSTEM: Autofocusing plug-in for mciro-manager and ImageJ // This file is distributed in the hope that it will be useful, // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. //CVS: $Id: MetadataDlg.java 1275 2008-06-03 21:31:24Z nenad $ import ij.process.ImageProcessor; import ij.process.ImageStatistics; import java.awt.Rectangle; import java.text.ParseException; import java.util.logging.Level; import java.util.logging.Logger; import mmcorej.CMMCore; import mmcorej.Configuration; import org.apache.commons.math.FunctionEvaluationException; import org.apache.commons.math.analysis.UnivariateRealFunction; import org.apache.commons.math.optimization.GoalType; import org.apache.commons.math.optimization.univariate.BrentOptimizer; import org.micromanager.MMStudioMainFrame; import org.micromanager.metadata.AcquisitionData; import org.micromanager.utils.AutofocusBase; import org.micromanager.utils.ImageUtils; import org.micromanager.utils.MMException; import org.micromanager.utils.NumberUtils; import org.micromanager.utils.ReportingUtils; public class OughtaFocus extends AutofocusBase implements org.micromanager.api.Autofocus { private CMMCore core_; private final MMStudioMainFrame gui_; private static final String AF_DEVICE_NAME = "OughtaFocus"; private static final String SEARCH_RANGE = "SearchRange_um"; private static final String TOLERANCE = "Tolerance_um"; private static final String CROP_FACTOR = "CropFactor"; private static final String CHANNEL = "Channel"; private static final String EXPOSURE = "Exposure"; private static final String SHOW = "ShowImages"; private double searchRange = 10; private double tolerance = 1; private double cropFactor = 1; private String channel = ""; private double exposure = 100; private int show = 0; public OughtaFocus() { super(); gui_ = MMStudioPlugin.getMMStudioMainFrameInstance(); createProperty(SEARCH_RANGE, NumberUtils.doubleToDisplayString(searchRange)); createProperty(TOLERANCE, NumberUtils.doubleToDisplayString(tolerance)); createProperty(CROP_FACTOR, NumberUtils.doubleToDisplayString(cropFactor)); createProperty(EXPOSURE, NumberUtils.doubleToDisplayString(exposure)); createProperty(SHOW, NumberUtils.intToDisplayString(show)); } public void applySettings() { try { searchRange = NumberUtils.displayStringToDouble(getPropertyValue(SEARCH_RANGE)); tolerance = NumberUtils.displayStringToDouble(getPropertyValue(TOLERANCE)); cropFactor = NumberUtils.displayStringToDouble(getPropertyValue(CROP_FACTOR)); channel = getPropertyValue(CHANNEL); exposure = NumberUtils.displayStringToDouble(getPropertyValue(EXPOSURE)); show = NumberUtils.displayStringToInt(getPropertyValue(SHOW)); } catch (MMException ex) { ReportingUtils.logError(ex); } catch (ParseException ex) { ReportingUtils.logError(ex); } } public void setMMCore(CMMCore core) { core_ = core; String chanGroup = core_.getChannelGroup(); String curChan; try { curChan = core_.getCurrentConfig(chanGroup); createProperty(CHANNEL, curChan, core_.getAvailableConfigs(core_.getChannelGroup()).toArray()); } catch (Exception ex) { ReportingUtils.logError(ex); } super.loadSettings(); } public String getDeviceName() { return AF_DEVICE_NAME; } public double fullFocus() throws MMException { Thread th = new Thread() { public void run() { applySettings(); try { Rectangle oldROI = gui_.getROI(); Rectangle newROI = new Rectangle(); newROI.width = (int) (oldROI.width * cropFactor); newROI.height = (int) (oldROI.height * cropFactor); newROI.x = oldROI.x + newROI.width / 2; newROI.y = oldROI.y + newROI.height / 2; String chanGroup = core_.getChannelGroup(); Configuration oldState = core_.getConfigGroupState(chanGroup); core_.setConfig(chanGroup, channel); gui_.setROI(newROI); double oldExposure = core_.getExposure(); core_.setExposure(exposure); runAutofocusAlgorithm(); gui_.setROI(oldROI); core_.setSystemState(oldState); core_.setExposure(exposure); } catch (Exception ex) { ReportingUtils.logError(ex); } } }; th.start(); if (show == 0) { try { th.join(); } catch (InterruptedException ex) { ReportingUtils.showError(ex); } } return 0; } private void runAutofocusAlgorithm() { UnivariateRealFunction scoreFun = new UnivariateRealFunction() { public double value(double d) throws FunctionEvaluationException { return measureFocusScore(d); } }; BrentOptimizer brentOptimizer = new BrentOptimizer(); brentOptimizer.setAbsoluteAccuracy(tolerance); try { double z = core_.getPosition(core_.getFocusDevice()); brentOptimizer.optimize(scoreFun, GoalType.MAXIMIZE, z - searchRange / 2, z + searchRange / 2); } catch (Exception ex) { ReportingUtils.logError(ex); } } private void setZPosition(double z) { try { String focusDevice = core_.getFocusDevice(); core_.setPosition(focusDevice, z); core_.waitForDevice(focusDevice); } catch (Exception ex) { ReportingUtils.logError(ex); } } public double measureFocusScore(double z) { try { System.out.println(z); setZPosition(z); core_.snapImage(); Object img = core_.getImage(); if (show == 1) { gui_.displayImage(img); } ImageProcessor proc = ImageUtils.makeProcessor(core_, img); ImageStatistics stats = proc.getStatistics(); return stats.stdDev / stats.mean; } catch (Exception ex) { ReportingUtils.logError(ex); return 0; } } public double incrementalFocus() throws MMException { throw new UnsupportedOperationException("Not supported yet."); } public int getNumberOfImages() { throw new UnsupportedOperationException("Not supported yet."); } public AcquisitionData getFocusingSequence() throws MMException { throw new UnsupportedOperationException("Not supported yet."); } public String getVerboseStatus() { throw new UnsupportedOperationException("Not supported yet."); } public double getCurrentFocusScore() { throw new UnsupportedOperationException("Not supported yet."); } public void focus(double coarseStep, int numCoarse, double fineStep, int numFine) throws MMException { throw new UnsupportedOperationException("Not supported yet."); } }
package org.postgresql.core.v3; import java.io.InputStream; import java.io.IOException; import java.sql.SQLException; import java.util.Arrays; import org.postgresql.core.*; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import org.postgresql.util.StreamWrapper; import org.postgresql.util.GT; /** * Parameter list for a single-statement V3 query. * * @author Oliver Jowett (oliver@opencloud.com) */ class SimpleParameterList implements V3ParameterList { private final static int IN = 1; private final static int OUT = 2; private final static int INOUT = IN|OUT; SimpleParameterList(int paramCount) { this.paramValues = new Object[paramCount]; this.paramTypes = new int[paramCount]; this.encoded = new byte[paramCount][]; this.direction = new int[paramCount]; } public void registerOutParameter( int index, int sqlType ) throws SQLException { if (index < 1 || index > paramValues.length) throw new PSQLException(GT.tr("The column index is out of range: {0}, number of columns: {1}.", new Object[]{new Integer(index), new Integer(paramValues.length)}), PSQLState.INVALID_PARAMETER_VALUE ); direction[index-1] |= OUT; } private void bind(int index, Object value, int oid) throws SQLException { if (index < 1 || index > paramValues.length) throw new PSQLException(GT.tr("The column index is out of range: {0}, number of columns: {1}.", new Object[]{new Integer(index), new Integer(paramValues.length)}), PSQLState.INVALID_PARAMETER_VALUE ); --index; encoded[index] = null; paramValues[index] = value ; direction[index] |= IN; // If we are setting something to an UNSPECIFIED NULL, don't overwrite // our existing type for it. We don't need the correct type info to // send this value, and we don't want to overwrite and require a // reparse. if (oid == Oid.UNSPECIFIED && paramTypes[index] != Oid.UNSPECIFIED && value == NULL_OBJECT) return; paramTypes[index] = oid; } public int getParameterCount() { return paramValues.length; } public int getOutParameterCount() { int count=0; for( int i=paramTypes.length; --i >= 0;) { if ((direction[i] & OUT) == OUT ) { count++; } } // Every function has at least one output. if (count == 0) count = 1; return count; } public int getInParameterCount() { int count=0; for( int i=0; i< paramTypes.length;i++) { if (direction[i] != OUT ) { count++; } } return count; } public void setIntParameter(int index, int value) throws SQLException { byte[] data = new byte[4]; data[3] = (byte)value; data[2] = (byte)(value >> 8); data[1] = (byte)(value >> 16); data[0] = (byte)(value >> 24); bind(index, data, Oid.INT4); } public void setLiteralParameter(int index, String value, int oid) throws SQLException { bind(index, value, oid); } public void setStringParameter(int index, String value, int oid) throws SQLException { bind(index, value, oid); } public void setBytea(int index, byte[] data, int offset, int length) throws SQLException { bind(index, new StreamWrapper(data, offset, length), Oid.BYTEA); } public void setBytea(int index, InputStream stream, int length) throws SQLException { bind(index, new StreamWrapper(stream, length), Oid.BYTEA); } public void setNull(int index, int oid) throws SQLException { bind(index, NULL_OBJECT, oid); } public String toString(int index) { --index; if (paramValues[index] == null) return "?"; else if (paramValues[index] == NULL_OBJECT) return "NULL"; else return paramValues[index].toString(); } public void checkAllParametersSet() throws SQLException { for (int i = 0; i < paramTypes.length; ++i) { if (direction[i] != OUT && paramValues[i] == null) throw new PSQLException(GT.tr("No value specified for parameter {0}.", new Integer(i + 1)), PSQLState.INVALID_PARAMETER_VALUE); } } // bytea helper private static void streamBytea(PGStream pgStream, StreamWrapper wrapper) throws IOException { byte[] rawData = wrapper.getBytes(); if (rawData != null) { pgStream.Send(rawData, wrapper.getOffset(), wrapper.getLength()); return ; } pgStream.SendStream(wrapper.getStream(), wrapper.getLength()); } public int[] getTypeOIDs() { return paramTypes; } // Package-private V3 accessors int getTypeOID(int index) { if (direction[index-1] == OUT) { paramTypes[index-1] = Oid.VOID; paramValues[index-1] = "null"; } return paramTypes[index-1]; } boolean hasUnresolvedTypes() { for (int i=0; i< paramTypes.length; i++) { if (paramTypes[i] == Oid.UNSPECIFIED) return true; } return false; } void setResolvedType(int index, int oid) { // only allow overwriting an unknown value if (paramTypes[index-1] == Oid.UNSPECIFIED) { paramTypes[index-1] = oid; } else if (paramTypes[index-1] != oid) { throw new IllegalArgumentException("Can't change resolved type for param: " + index + " from " + paramTypes[index-1] + " to " + oid); } } boolean isNull(int index) { return (paramValues[index-1] == NULL_OBJECT); } boolean isBinary(int index) { // Currently, only StreamWrapper uses the binary parameter form. return (paramValues[index-1] instanceof StreamWrapper); } int getV3Length(int index) { --index; // Null? if (paramValues[index] == NULL_OBJECT) throw new IllegalArgumentException("can't getV3Length() on a null parameter"); // Directly encoded? if (paramValues[index] instanceof byte[]) return ((byte[])paramValues[index]).length; // Binary-format bytea? if (paramValues[index] instanceof StreamWrapper) return ((StreamWrapper)paramValues[index]).getLength(); // Already encoded? if (encoded[index] == null) { // Encode value and compute actual length using UTF-8. encoded[index] = Utils.encodeUTF8(paramValues[index].toString()); } return encoded[index].length; } void writeV3Value(int index, PGStream pgStream) throws IOException { --index; // Null? if (paramValues[index] == NULL_OBJECT) throw new IllegalArgumentException("can't writeV3Value() on a null parameter"); // Directly encoded? if (paramValues[index] instanceof byte[]) { pgStream.Send((byte[])paramValues[index]); return ; } // Binary-format bytea? if (paramValues[index] instanceof StreamWrapper) { streamBytea(pgStream, (StreamWrapper)paramValues[index]); return ; } // Encoded string. if (encoded[index] == null) encoded[index] = Utils.encodeUTF8((String)paramValues[index]); pgStream.Send(encoded[index]); } public ParameterList copy() { SimpleParameterList newCopy = new SimpleParameterList(paramValues.length); System.arraycopy(paramValues, 0, newCopy.paramValues, 0, paramValues.length); System.arraycopy(paramTypes, 0, newCopy.paramTypes, 0, paramTypes.length); System.arraycopy(direction, 0, newCopy.direction, 0, direction.length); return newCopy; } public void clear() { Arrays.fill(paramValues, null); Arrays.fill(paramTypes, 0); Arrays.fill(encoded, null); Arrays.fill(direction, 0); } public SimpleParameterList[] getSubparams() { return null; } private final Object[] paramValues; private final int[] paramTypes; private final int[] direction; private final byte[][] encoded; /** * Marker object representing NULL; this distinguishes * "parameter never set" from "parameter set to null". */ private final static Object NULL_OBJECT = new Object(); }
package com.vaadin.tests; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.terminal.StreamResource; import com.vaadin.ui.AbstractField; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.CheckBox; import com.vaadin.ui.CustomComponent; import com.vaadin.ui.Label; import com.vaadin.ui.Layout; import com.vaadin.ui.Link; import com.vaadin.ui.Panel; import com.vaadin.ui.ProgressIndicator; import com.vaadin.ui.Select; import com.vaadin.ui.TextField; import com.vaadin.ui.Upload; import com.vaadin.ui.Upload.FinishedEvent; import com.vaadin.ui.Upload.StartedEvent; import com.vaadin.ui.Upload.StartedListener; import com.vaadin.ui.VerticalLayout; public class TestForUpload extends CustomComponent implements Upload.ProgressListener { private static final long serialVersionUID = -3400119871764256575L; Layout main = new VerticalLayout(); Buffer buffer = new MemoryBuffer(); Panel status = new Panel("Uploaded file:"); private final Upload up; private final Label l; private final ProgressIndicator pi = new ProgressIndicator(); private final ProgressIndicator pi2 = new ProgressIndicator(); private final Label memoryStatus; private final Select uploadBufferSelector; private TextField textField; private Label textFieldValue; private CheckBox beSluggish = new CheckBox("Be sluggish"); private CheckBox throwExecption = new CheckBox( "Throw exception in receiver"); private Button interrupt = new Button("Interrupt upload"); public TestForUpload() { setCompositionRoot(main); main.addComponent(new Label( "This is a simple test for upload application. " + "Upload should work with big files and concurrent " + "requests should not be blocked. Button 'b' reads " + "current state into label below it. Memory receiver " + "streams upload contents into memory. You may track" + "consumption." + "tempfile receiver writes upload to file and " + "should have low memory consumption.")); main.addComponent(new Label( "Clicking on button b updates information about upload components status or same with garbage collector.")); textField = new TextField("Test field"); textFieldValue = new Label(); main.addComponent(textField); main.addComponent(textFieldValue); up = new Upload("Upload", buffer); up.setImmediate(true); up.addListener(new Listener() { private static final long serialVersionUID = -8319074730512324303L; public void componentEvent(Event event) { // print out all events fired by upload for debug purposes System.out.println("Upload fired event | " + event); } }); up.addListener(new StartedListener() { private static final long serialVersionUID = 5508883803861085154L; public void uploadStarted(StartedEvent event) { pi.setVisible(true); pi2.setVisible(true); l.setValue("Started uploading file " + event.getFilename()); textFieldValue .setValue(" TestFields value at the upload start is:" + textField.getValue()); } }); up.addListener(new Upload.FinishedListener() { private static final long serialVersionUID = -3773034195991947371L; public void uploadFinished(FinishedEvent event) { pi.setVisible(false); pi2.setVisible(false); if (event instanceof Upload.FailedEvent) { Exception reason = ((Upload.FailedEvent) event).getReason(); l.setValue("Finished with failure ( " + reason + " ), idle"); } else if (event instanceof Upload.SucceededEvent) { l.setValue("Finished with succes, idle"); } else { l.setValue("Finished with unknow event"); } status.removeAllComponents(); final InputStream stream = buffer.getStream(); if (stream == null) { status.addComponent(new Label( "Upload finished, but output buffer is null")); } else { status.addComponent(new Label("<b>Name:</b> " + event.getFilename(), Label.CONTENT_XHTML)); status.addComponent(new Label("<b>Mimetype:</b> " + event.getMIMEType(), Label.CONTENT_XHTML)); status.addComponent(new Label("<b>Size:</b> " + event.getLength() + " bytes.", Label.CONTENT_XHTML)); status.addComponent(new Link("Download " + buffer.getFileName(), new StreamResource(buffer, buffer.getFileName(), getApplication()))); status.setVisible(true); } setBuffer(); } }); up.addListener(new Upload.ProgressListener() { public void updateProgress(long readBytes, long contentLenght) { pi2.setValue(new Float(readBytes / (float) contentLenght)); refreshMemUsage(); } }); final Button b = new Button("Reed state from upload", this, "readState"); final Button c = new Button("Force GC", this, "gc"); main.addComponent(b); main.addComponent(c); main.addComponent(beSluggish); main.addComponent(throwExecption); main.addComponent(interrupt); interrupt.addListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { up.interruptUpload(); } }); uploadBufferSelector = new Select("StreamVariable type"); uploadBufferSelector.setImmediate(true); uploadBufferSelector.addItem("memory"); uploadBufferSelector.setValue("memory"); uploadBufferSelector.addItem("tempfile"); uploadBufferSelector .addListener(new AbstractField.ValueChangeListener() { public void valueChange(ValueChangeEvent event) { setBuffer(); } }); main.addComponent(uploadBufferSelector); main.addComponent(up); l = new Label("Idle"); main.addComponent(l); pi.setVisible(false); pi.setPollingInterval(1000); main.addComponent(pi); pi2.setVisible(false); pi2.setPollingInterval(1000); main.addComponent(pi2); memoryStatus = new Label(); main.addComponent(memoryStatus); status.setVisible(false); main.addComponent(status); final Button restart = new Button("R"); restart.addListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { getApplication().close(); } }); main.addComponent(restart); } private void setBuffer() { final String id = (String) uploadBufferSelector.getValue(); if ("memory".equals(id)) { buffer = new MemoryBuffer(); } else if ("tempfile".equals(id)) { buffer = new TmpFileBuffer(); } up.setReceiver(buffer); } public void gc() { Runtime.getRuntime().gc(); } public void readState() { final StringBuffer sb = new StringBuffer(); if (up.isUploading()) { sb.append("Uploading..."); sb.append(up.getBytesRead()); sb.append("/"); sb.append(up.getUploadSize()); sb.append(" "); sb.append(Math.round(100 * up.getBytesRead() / (double) up.getUploadSize())); sb.append("%"); } else { sb.append("Idle"); } l.setValue(sb.toString()); refreshMemUsage(); } public interface Buffer extends StreamResource.StreamSource, Upload.Receiver { String getFileName(); } public class MemoryBuffer implements Buffer { ByteArrayOutputStream outputBuffer = null; String mimeType; String fileName; public MemoryBuffer() { } public InputStream getStream() { if (outputBuffer == null) { return null; } return new ByteArrayInputStream(outputBuffer.toByteArray()); } /** * @see com.vaadin.ui.Upload.Receiver#receiveUpload(String, String) */ public OutputStream receiveUpload(String filename, String MIMEType) { fileName = filename; mimeType = MIMEType; outputBuffer = new ByteArrayOutputStream() { @Override public synchronized void write(byte[] b, int off, int len) { beSluggish(); throwExecption(); super.write(b, off, len); } }; return outputBuffer; } /** * Returns the fileName. * * @return String */ public String getFileName() { return fileName; } /** * Returns the mimeType. * * @return String */ public String getMimeType() { return mimeType; } } public class TmpFileBuffer implements Buffer { String mimeType; String fileName; private File file; public TmpFileBuffer() { final String tempFileName = "upload_tmpfile_" + System.currentTimeMillis(); try { file = File.createTempFile(tempFileName, null); } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public InputStream getStream() { if (file == null) { return null; } try { return new FileInputStream(file); } catch (final FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * @see com.vaadin.ui.Upload.Receiver#receiveUpload(String, String) */ public OutputStream receiveUpload(String filename, String MIMEType) { fileName = filename; mimeType = MIMEType; try { return new FileOutputStream(file) { @Override public void write(byte[] b, int off, int len) throws IOException { beSluggish(); throwExecption(); super.write(b, off, len); } }; } catch (final FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * Returns the fileName. * * @return String */ public String getFileName() { return fileName; } /** * Returns the mimeType. * * @return String */ public String getMimeType() { return mimeType; } } public void updateProgress(long readBytes, long contentLenght) { pi.setValue(new Float(readBytes / (float) contentLenght)); refreshMemUsage(); } private void refreshMemUsage() { memoryStatus.setValue("Not available in Java 1.4"); StringBuffer mem = new StringBuffer(); MemoryMXBean mmBean = ManagementFactory.getMemoryMXBean(); mem.append("Heap (M):"); mem.append(mmBean.getHeapMemoryUsage().getUsed() / 1048576); mem.append(" | Non-Heap (M):"); mem.append(mmBean.getNonHeapMemoryUsage().getUsed() / 1048576); memoryStatus.setValue(mem.toString()); } private void beSluggish() { if (beSluggish.booleanValue()) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void throwExecption() { if (throwExecption.booleanValue()) { throwExecption.setValue(false); throw new RuntimeException("Test execption in receiver."); } } }
public class Main { public static void main(String[] args) { System.out.println("Timme") } }
package gov.nih.nci.cananolab.restful.sample; import gov.nih.nci.cananolab.domain.common.File; import gov.nih.nci.cananolab.domain.common.Keyword; import gov.nih.nci.cananolab.dto.common.ColumnHeader; import gov.nih.nci.cananolab.dto.common.ExperimentConfigBean; import gov.nih.nci.cananolab.dto.common.FileBean; import gov.nih.nci.cananolab.dto.common.FindingBean; import gov.nih.nci.cananolab.dto.common.Row; import gov.nih.nci.cananolab.dto.common.TableCell; import gov.nih.nci.cananolab.dto.particle.SampleBean; import gov.nih.nci.cananolab.dto.particle.characterization.CharacterizationBean; import gov.nih.nci.cananolab.dto.particle.characterization.CharacterizationSummaryViewBean; import gov.nih.nci.cananolab.exception.SecurityException; import gov.nih.nci.cananolab.restful.core.BaseAnnotationBO; import gov.nih.nci.cananolab.restful.protocol.InitProtocolSetup; import gov.nih.nci.cananolab.restful.util.PropertyUtil; import gov.nih.nci.cananolab.restful.view.SimpleCharacterizationsByTypeBean; import gov.nih.nci.cananolab.restful.view.edit.SimpleCell; import gov.nih.nci.cananolab.restful.view.edit.SimpleCharacterizationEditBean; import gov.nih.nci.cananolab.restful.view.edit.SimpleCharacterizationSummaryEditBean; import gov.nih.nci.cananolab.restful.view.edit.SimpleExperimentBean; import gov.nih.nci.cananolab.restful.view.edit.SimpleFileBean; import gov.nih.nci.cananolab.restful.view.edit.SimpleFindingBean; import gov.nih.nci.cananolab.restful.view.edit.SimpleRowBean; import gov.nih.nci.cananolab.service.protocol.ProtocolService; import gov.nih.nci.cananolab.service.protocol.impl.ProtocolServiceLocalImpl; import gov.nih.nci.cananolab.service.sample.CharacterizationService; import gov.nih.nci.cananolab.service.sample.SampleService; import gov.nih.nci.cananolab.service.sample.impl.CharacterizationExporter; import gov.nih.nci.cananolab.service.sample.impl.CharacterizationServiceLocalImpl; import gov.nih.nci.cananolab.service.sample.impl.SampleServiceLocalImpl; import gov.nih.nci.cananolab.service.security.SecurityService; import gov.nih.nci.cananolab.service.security.UserBean; import gov.nih.nci.cananolab.util.Constants; import gov.nih.nci.cananolab.util.DateUtils; import gov.nih.nci.cananolab.util.ExportUtils; import gov.nih.nci.cananolab.util.StringUtils; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; /** * Base action for characterization actions * * @author pansu */ public class CharacterizationBO extends BaseAnnotationBO { private Logger logger = Logger.getLogger(CharacterizationBO.class); /** * Add or update a characterization to database * * Upon success, go back to characterizaiton summary edit page * * @param request * @param simpleEdit * @return * @throws Exception */ public SimpleCharacterizationSummaryEditBean submitOrUpdate(HttpServletRequest request, SimpleCharacterizationEditBean simpleEdit) throws Exception { CharacterizationBean charBean = (CharacterizationBean)request.getSession().getAttribute("theChar"); simpleEdit.getErrors().clear(); simpleEdit.getMessages().clear(); charBean = simpleEdit.transferToCharacterizationBean(charBean); if (simpleEdit.getCharId() == 0) simpleEdit.setSubmitNewChar(true); this.setServicesInSession(request); List<String> errs = new ArrayList<String>(); if (!validateInputs(request, charBean, errs)) { SimpleCharacterizationSummaryEditBean emptyView = new SimpleCharacterizationSummaryEditBean(); emptyView.setErrors(errs); return emptyView; } this.saveCharacterization(request, charBean, simpleEdit); simpleEdit.getMessages().add(PropertyUtil.getPropertyReplacingToken("sample", "message.addCharacterization", "0", charBean.getCharacterizationName())); InitCharacterizationSetup.getInstance() //save "others" to db .persistCharacterizationDropdowns(request, charBean); SimpleCharacterizationSummaryEditBean success = new SimpleCharacterizationSummaryEditBean(); success.getMessages().add("The characterization has been saved successfully"); return success; } // public ActionForward input(ActionMapping mapping, ActionForm form, // HttpServletRequest request, HttpServletResponse response) // throws Exception { // DynaValidatorForm theForm = (DynaValidatorForm) form; // CharacterizationBean charBean = (CharacterizationBean) theForm // .get("achar"); // charBean.updateEmptyFieldsToNull(); // this.checkOpenForms(charBean, theForm, request); // // Save uploaded data in session to avoid asking user to upload again. // FileBean theFile = charBean.getTheFinding().getTheFile(); // escapeXmlForFileUri(theFile); // String charName = StringUtils.getOneWordLowerCaseFirstLetter(charBean // .getCharacterizationName()); // preserveUploadedFile(request, theFile, charName); // return mapping.findForward("inputForm"); /** * Set up the input form for adding new characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public SimpleCharacterizationEditBean setupNew(HttpServletRequest request, String sampleId, String charType) throws Exception { if (StringUtils.isEmpty(sampleId)) throw new Exception("Sample id is empty"); if (StringUtils.isEmpty(charType)) throw new Exception("Characterization type is empty"); setServicesInSession(request); //This method sets tons of lookups. Need to see what's needed and what's not //setupInputForm(request, sampleId, charType); CharacterizationBean charBean = new CharacterizationBean(); charBean.setCharacterizationType(charType); //this.checkOpenForms(charBean, theForm, request); // clear copy to otherSamples // clearCopy(theForm); // return mapping.findForward("inputForm"); SimpleCharacterizationEditBean editBean = new SimpleCharacterizationEditBean(); editBean.transferFromCharacterizationBean(request, charBean, sampleId); request.getSession().setAttribute("theEditChar", editBean); request.getSession().setAttribute("theChar", charBean); return editBean; } /** * Set up drop-downs need for the input form * * @param request * @param theForm * @throws Exception */ private void setupInputForm(HttpServletRequest request, String sampleId, String charType) throws Exception { if (StringUtils.isEmpty(sampleId)) throw new Exception("Sample id is invalid"); if (!StringUtils.isEmpty(charType)) InitProtocolSetup.getInstance().getProtocolsByChar(request, charType); InitCharacterizationSetup.getInstance().setPOCDropdown(request, sampleId); // InitCharacterizationSetup.getInstance().setCharacterizationDropdowns( // request); // set up other samples with the same primary point of contact InitSampleSetup.getInstance().getOtherSampleNames(request, sampleId); } /** * Set up the input form for editing existing characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public SimpleCharacterizationEditBean setupUpdate(HttpServletRequest request, String sampleId, String charId, String charClassName, String charType) throws Exception { CharacterizationService charService = this.setServicesInSession(request); charId = super.validateCharId(charId); CharacterizationBean charBean = charService .findCharacterizationById(charId); // // TODO: Find out usage of "charNameDatumNames", not used in any JSPs. // InitCharacterizationSetup.getInstance().getDatumNamesByCharName( // request, charBean.getCharacterizationType(), // charBean.getCharacterizationName(), charBean.getAssayType()); //SY: new request.getSession().setAttribute("theChar", charBean); logger.debug("Setting theChar in session: " + request.getSession().getId());; SimpleCharacterizationEditBean editBean = new SimpleCharacterizationEditBean(); editBean.transferFromCharacterizationBean(request, charBean, sampleId); request.getSession().setAttribute("theEditChar", editBean); return editBean; } // private void clearCopy(DynaValidatorForm theForm) { // theForm.set("otherSamples", new String[0]); // theForm.set("copyData", false); /** * Setup, prepare and save characterization. * * @param request * @param theForm * @param charBean * @throws Exception */ private void saveCharacterization(HttpServletRequest request, CharacterizationBean charBean, SimpleCharacterizationEditBean simpleEdit) throws Exception { SampleBean sampleBean = setupSampleById(String.valueOf(simpleEdit.getParentSampleId()), request); UserBean user = (UserBean) request.getSession().getAttribute("user"); charBean.setupDomain(user.getLoginName()); if (charBean.getDomainChar().getDate() == null && simpleEdit.getCharacterizationDate() != null) charBean.getDomainChar().setDate(simpleEdit.getCharacterizationDate()); Boolean newChar = true; if (charBean.getDomainChar().getId() != null) { newChar = false; } logger.debug("Saving new char? " + newChar); // reuse the existing char service CharacterizationService charService = (CharacterizationService) request .getSession().getAttribute("characterizationService"); charService.saveCharacterization(sampleBean, charBean); // retract from public if updating an existing public record and not // curator if (!newChar && !user.isCurator() && sampleBean.getPublicStatus()) { retractFromPublic(String.valueOf(simpleEdit.getParentSampleId()), request, sampleBean.getDomain().getId() .toString(), sampleBean.getDomain().getName(), "sample"); simpleEdit.getErrors().add(PropertyUtil.getProperty("sample", "message.updateSample.retractFromPublic")); } // save to other samples (only when user click [Submit] button.) if (simpleEdit.isSubmitNewChar()) { SampleBean[] otherSampleBeans = prepareCopy(request, simpleEdit.getSelectedOtherSampleNames(), sampleBean); if (otherSampleBeans != null) { charService.copyAndSaveCharacterization(charBean, sampleBean, otherSampleBeans, simpleEdit.isCopyToOtherSamples()); //field should be renamed to copyDeepData } simpleEdit.setSubmitNewChar(false); } sampleBean = setupSampleById(String.valueOf(simpleEdit.getParentSampleId()), request); request.setAttribute("sampleId", sampleBean.getDomain().getId() .toString()); logger.debug("Done saving characterization: " + charBean.getDomainChar().getId()); } private void deleteCharacterization(HttpServletRequest request, CharacterizationBean charBean, String createdBy) throws Exception { charBean.setupDomain(createdBy); CharacterizationService service = this.setServicesInSession(request); service.deleteCharacterization(charBean.getDomainChar()); service.removeAccesses(charBean.getDomainChar()); } public SimpleCharacterizationSummaryEditBean delete(HttpServletRequest request, SimpleCharacterizationEditBean editBean) throws Exception { CharacterizationBean charBean = (CharacterizationBean)request.getSession().getAttribute("theChar"); if (charBean == null) throw new Exception("No characterization bean in session. Unable to proceed with delete"); Long charId = charBean.getDomainChar().getId(); if (charId == null) throw new Exception("Characterization bean in session has null id. Unable to proceed with delete"); if (charId.longValue() != editBean.getCharId()) throw new Exception("Characterization id in session doesn't match input char id. Unable to proceed with delete"); UserBean user = (UserBean) request.getSession().getAttribute("user"); deleteCharacterization(request, charBean, user.getLoginName()); SimpleCharacterizationSummaryEditBean summaryEdit = new SimpleCharacterizationSummaryEditBean(); summaryEdit.getMessages().add(PropertyUtil.getProperty("sample", "message.deleteCharacterization")); return this.summaryEdit(String.valueOf(editBean.getParentSampleId()), request, summaryEdit); } /** * summaryEdit() handles Edit request for Characterization Summary view. * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public SimpleCharacterizationSummaryEditBean summaryEdit(String sampleId, HttpServletRequest request, SimpleCharacterizationSummaryEditBean editBean) throws Exception { // Prepare data. CharacterizationSummaryViewBean sumBean = this.prepareSummary(sampleId, request); if (editBean == null) editBean = new SimpleCharacterizationSummaryEditBean(); List<SimpleCharacterizationsByTypeBean> finalBeans = editBean.transferData(request, sumBean, sampleId); return editBean; } /** * summaryView() handles View request for Characterization Summary report. * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception * if error occurred. */ public CharacterizationSummaryViewBean summaryView(String sampleId, HttpServletRequest request) throws Exception { if (sampleId == null || sampleId.length() == 0) throw new Exception("sampleId can't be null or empty"); CharacterizationSummaryViewBean viewBean = prepareSummary(sampleId, request); List<String> charTypes = prepareCharacterizationTypes(request); //setSummaryTab(request, charTypes.size()); return viewBean; } // public ActionForward setupView(ActionMapping mapping, ActionForm form, // HttpServletRequest request, HttpServletResponse response) // throws Exception { //TODO // DynaValidatorForm theForm = (DynaValidatorForm) form; // CharacterizationService service = this.setServicesInSession(request); // String charId = super.validateId(request, "charId"); // setupSample(theForm, request); // CharacterizationBean charBean = service // .findCharacterizationById(charId); // request.setAttribute("charBean", charBean); // return mapping.findForward("singleSummaryView"); /** * Shared function for summaryView(), summaryPrint() and summaryEdit(). * Prepare CharacterizationBean based on Sample Id. * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ private CharacterizationSummaryViewBean prepareSummary(String sampleId, HttpServletRequest request) throws Exception { // Remove previous result from session. request.getSession().removeAttribute("characterizationSummaryView"); CharacterizationService service = this.setServicesInSession(request); List<CharacterizationBean> charBeans = service .findCharacterizationsBySampleId(sampleId); CharacterizationSummaryViewBean summaryView = new CharacterizationSummaryViewBean( charBeans); request.getSession().setAttribute("characterizationSummaryView", summaryView); return summaryView; } /** * Shared function for summaryView() and summaryPrint(). Keep submitted * characterization types in the correct display order. Should be called * after calling prepareSummary(), to avoid session timeout issue. * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ private List<String> prepareCharacterizationTypes(HttpServletRequest request) throws Exception { CharacterizationSummaryViewBean summaryView = (CharacterizationSummaryViewBean) request .getSession().getAttribute("characterizationSummaryView"); // Keep submitted characterization types in the correct display order // prepare characterization tabs and forward to appropriate tab List<String> allCharacterizationTypes = InitCharacterizationSetup .getInstance().getCharacterizationTypes(request); Set<String> foundTypes = summaryView.getCharacterizationTypes(); List<String> characterizationTypes = new ArrayList<String>(); for (String charType : allCharacterizationTypes) { if (foundTypes.contains(charType) && !characterizationTypes.contains(charType)) { characterizationTypes.add(charType); } } // other types that are not in allCharacterizationTypes, e.g. other // types from grid search for (String type : foundTypes) { if (!characterizationTypes.contains(type)) { characterizationTypes.add(type); } } request.setAttribute("characterizationTypes", characterizationTypes); return characterizationTypes; } /** * summaryPrint() handles Print request for Characterization Summary report. * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public CharacterizationSummaryViewBean summaryPrint(String sampleId, HttpServletRequest request, HttpServletResponse response) throws Exception { CharacterizationSummaryViewBean charSummaryBean = (CharacterizationSummaryViewBean) request .getSession().getAttribute("characterizationSummaryView"); if (charSummaryBean == null) { // Retrieve data again when session timeout. this.prepareSummary(sampleId, request); charSummaryBean = (CharacterizationSummaryViewBean) request .getSession().getAttribute("characterizationSummaryView"); } //TODO: w List<String> charTypes = prepareCharacterizationTypes(request); this.filterType(request, "all", charTypes); // Filter out un-selected types. // Marker that indicates page is for printing only, hide tabs/links. request.setAttribute("printView", Boolean.TRUE); //return mapping.findForward("summaryPrintView"); return charSummaryBean; } /** * Export Characterization Summary report. * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public String summaryExport(String sampleId, String type, HttpServletRequest request, HttpServletResponse response) throws Exception { if (sampleId == null || sampleId.length() == 0) return "Sample Id can't be null or empty"; if (type == null) type = "all"; SampleBean sampleBean = (SampleBean) request.getSession().getAttribute( "theSample"); CharacterizationSummaryViewBean charSummaryBean = (CharacterizationSummaryViewBean) request .getSession().getAttribute("characterizationSummaryView"); if (sampleBean == null || charSummaryBean == null) { // Prepare data. this.prepareSummary(sampleId, request); sampleBean = (SampleBean) request.getSession().getAttribute( "theSample"); charSummaryBean = (CharacterizationSummaryViewBean) request .getSession().getAttribute("characterizationSummaryView"); } List<String> charTypes = prepareCharacterizationTypes(request); List<String> filteredCharTypes = this.filterType(request, type, charTypes); //String type = "all"; //request.getParameter("type"); // per app scan if (!StringUtils.xssValidate(type)) { type = ""; } String sampleName = sampleBean.getDomain().getName(); String fileName = ExportUtils.getExportFileName(sampleName, "CharacterizationSummaryView", type); ExportUtils.prepareReponseForExcel(response, fileName); StringBuilder sb = getDownloadUrl(request); CharacterizationExporter.exportSummary(filteredCharTypes, charSummaryBean, sb.toString(), response.getOutputStream()); return "success"; } public SimpleCharacterizationEditBean saveExperimentConfig(HttpServletRequest request, SimpleCharacterizationEditBean charEditBean) throws Exception { logger.debug("Start saving experiment confg"); //editBean's charId could be null, indicating new char CharacterizationBean achar = (CharacterizationBean) request.getSession().getAttribute("theChar"); // SimpleCharacterizationEditBean editBean = // (SimpleCharacterizationEditBean) request.getSession().getAttribute("theEditChar"); SimpleExperimentBean simpleExpConfig = charEditBean.getDirtyExperimentBean(); ExperimentConfigBean configBean = this.findMatchExperimentConfig(achar, simpleExpConfig); simpleExpConfig.transferToExperimentConfigBean(configBean); // ///duck tapping // if (achar.getCharacterizationName() == null || achar.getCharacterizationName().length() == 0) // achar.setCharacterizationName(simpleExpConfig.getParentCharName()); // if (achar.getCharacterizationType() == null || achar.getCharacterizationType().length() == 0) // achar.setCharacterizationType(simpleExpConfig.getParentCharType()); // ///duck tapping UserBean user = (UserBean) request.getSession().getAttribute("user"); configBean.setupDomain(user.getLoginName()); CharacterizationService service = this.setServicesInSession(request); logger.debug("Call saveExperimentConfig"); service.saveExperimentConfig(configBean); logger.debug("Save exp config complete"); achar.addExperimentConfig(configBean); //transfer other data fields of the char achar = charEditBean.transferToCharacterizationBean(achar); // This is to validate characterization data fields if (!validateInputs(request, achar, charEditBean.getMessages())) { return charEditBean; } this.saveCharacterization(request, achar, charEditBean); logger.debug("Save char complete"); service.assignAccesses(achar.getDomainChar(), configBean.getDomain()); //TODO: //this.checkOpenForms(achar, theForm, request); InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, achar); // return to setupUpdate to retrieve the data matrix in the correct // form from database // after saving to database. request.setAttribute("charId", achar.getDomainChar().getId().toString()); request.setAttribute("charType", achar.getCharacterizationType()); return setupUpdate(request, String.valueOf(charEditBean.getParentSampleId()), achar.getDomainChar().getId().toString(), achar.getClassName(), achar.getCharacterizationType()); } // public ActionForward getFinding(ActionMapping mapping, ActionForm form, // HttpServletRequest request, HttpServletResponse response) // throws Exception { // DynaValidatorForm theForm = (DynaValidatorForm) form; // String theFindingId = request.getParameter("findingId"); // CharacterizationService service = this.setServicesInSession(request); // FindingBean findingBean = service.findFindingById(theFindingId); // CharacterizationBean achar = (CharacterizationBean) theForm // .get("achar"); // achar.setTheFinding(findingBean); // request.setAttribute("anchor", "submitFinding"); // this.checkOpenForms(achar, theForm, request); // // Feature request [26487] Deeper Edit Links. // if (findingBean.getFiles().size() == 1) { // request.setAttribute("onloadJavascript", "setTheFile(0)"); // request.setAttribute("disableOuterButtons", true); // // remove columnHeaders stored in the session; // request.getSession().removeAttribute("columnHeaders"); // return mapping.findForward("inputForm"); // public ActionForward resetFinding(ActionMapping mapping, ActionForm form, // HttpServletRequest request, HttpServletResponse response) // throws Exception { // DynaValidatorForm theForm = (DynaValidatorForm) form; // FindingBean theFinding = new FindingBean(); // // theFinding.setNumberOfColumns(1); // // theFinding.setNumberOfRows(1); // // theFinding.updateMatrix(theFinding.getNumberOfColumns(), theFinding // // .getNumberOfRows()); // CharacterizationBean achar = (CharacterizationBean) theForm // .get("achar"); // achar.setTheFinding(theFinding); // request.setAttribute("anchor", "submitFinding"); // this.checkOpenForms(achar, theForm, request); // request.setAttribute("disableOuterButtons", true); // request.getSession().removeAttribute("columnHeaders"); // return mapping.findForward("inputForm"); // return null; public SimpleCharacterizationEditBean saveFinding(HttpServletRequest request, SimpleCharacterizationEditBean editBean /*SimpleFindingBean simpleFinding*/) throws Exception { CharacterizationBean achar = (CharacterizationBean) request.getSession().getAttribute("theChar"); // SimpleCharacterizationEditBean editBean = // (SimpleCharacterizationEditBean) request.getSession().getAttribute("theEditChar"); SimpleFindingBean simpleFinding = editBean.getDirtyFindingBean(); if (simpleFinding == null) throw new Exception("Can't find dirty finding object"); //temp FindingBean findingBean = this.findMatchFindingBean(achar, simpleFinding); CharacterizationService service = this.setServicesInSession(request); //FindingBean findingBean = achar.getTheFinding(); String theFindingId = String.valueOf(simpleFinding.getFindingId()); UserBean user = (UserBean) request.getSession().getAttribute("user"); simpleFinding.transferToFindingBean(findingBean, user); if (!validateEmptyFinding(request, findingBean, editBean.getErrors())) { return editBean; } // setup domainFile uri for fileBeans SampleBean sampleBean = (SampleBean) request.getSession().getAttribute("theSample"); String internalUriPath = Constants.FOLDER_PARTICLE + '/' + sampleBean.getDomain().getName() + '/' + StringUtils.getOneWordLowerCaseFirstLetter(achar .getCharacterizationName()); findingBean.setupDomain(internalUriPath, user.getLoginName()); service.saveFinding(findingBean); achar.addFinding(findingBean); //transfer other data fields of the char editBean.transferToCharacterizationBean(achar); // also save characterization if (!validateInputs(request, achar, editBean.getMessages())) { return editBean; } this.saveCharacterization(request, achar, editBean); service.assignAccesses(achar.getDomainChar(), findingBean.getDomain()); //this.checkOpenForms(achar, theForm, request); InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, achar); request.setAttribute("anchor", "result"); // return to setupUpdate to retrieve the data matrix in the correct // form from database // after saving to database. request.setAttribute("charId", achar.getDomainChar().getId().toString()); request.setAttribute("charType", achar.getCharacterizationType()); return setupUpdate(request, String.valueOf(editBean.getParentSampleId()), achar.getDomainChar().getId().toString(), achar.getClassName(), achar.getCharacterizationType()); } public SimpleFindingBean saveFile(HttpServletRequest request, SimpleFindingBean simpleFinding) throws Exception { CharacterizationBean achar = (CharacterizationBean) request.getSession().getAttribute("theChar"); SimpleCharacterizationEditBean editBean = (SimpleCharacterizationEditBean) request.getSession().getAttribute("theEditChar"); SampleBean currentSample = (SampleBean) request.getSession().getAttribute("theSample"); request.getSession().setAttribute("sampleId", String.valueOf(editBean.getParentSampleId())); //FindingBean findingBean = this.findMatchFindingBean(achar, simpleFinding); FindingBean findingBean = this.transferSimpleFinding(simpleFinding); int theFileIndex = simpleFinding.getTheFileIndex(); FileBean theFile = simpleFinding.transferToNewFileBean(); simpleFinding.getErrors().clear(); this.setServicesInSession(request); // create a new copy before adding to finding FileBean newFile = theFile.copy(); if (currentSample == null) //should not be currentSample = setupSampleById(String.valueOf(editBean.getParentSampleId()), request); // setup domainFile uri for fileBeans String internalUriPath = Constants.FOLDER_PARTICLE + '/' + currentSample.getDomain().getName() + '/' + StringUtils.getOneWordLowerCaseFirstLetter(achar .getCharacterizationName()); UserBean user = (UserBean) request.getSession().getAttribute("user"); newFile.setupDomainFile(internalUriPath, user.getLoginName()); String timestamp = DateUtils.convertDateToString(new Date(), "yyyyMMdd_HH-mm-ss-SSS"); byte[] newFileData = (byte[]) request.getSession().getAttribute("newFileData"); if(!theFile.getDomainFile().getUriExternal()){ if(newFileData!=null){ newFile.setNewFileData((byte[]) request.getSession().getAttribute("newFileData")); // newFile.getDomainFile().setUri(internalUriPath + "/" + timestamp + "_" // + newFile.getDomainFile().getName()); logger.debug("File path: " + newFile.getDomainFile().getUri()); } else if(theFile.getDomainFile().getId()!=null){ theFile.getDomainFile().setUri(theFile.getDomainFile().getName()); }else { newFile.getDomainFile().setUri(null); } } this.validateFileBean(request, simpleFinding.getErrors(), theFile); if (simpleFinding.getErrors().size() > 0) return simpleFinding; findingBean.addFile(newFile, theFileIndex); achar.addFinding(findingBean); simpleFinding.transferFromFindingBean(request, findingBean); request.setAttribute("anchor", "submitFinding"); // this.checkOpenForms(achar, theForm, request); InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, achar); request.getSession().removeAttribute("newFileData"); request.getSession().setAttribute("theChar", achar); /// save char to session return simpleFinding; } private FindingBean transferSimpleFinding(SimpleFindingBean simpleFinding) { FindingBean finding = new FindingBean(); finding.setColumnHeaders(simpleFinding.getColumnHeaders()); FileBean theFile = new FileBean(); File file = new File(); file.setCreatedBy(simpleFinding.getTheFile().getCreatedBy()); file.setCreatedDate(simpleFinding.getTheFile().getCreatedDate()); file.setId(simpleFinding.getTheFile().getId()); file.setTitle(simpleFinding.getTheFile().getTitle()); file.setType(simpleFinding.getTheFile().getType()); theFile.setKeywordsStr(simpleFinding.getTheFile().getKeywordsStr()); theFile.setDomainFile(file); finding.setTheFile(theFile); finding.setNumberOfColumns(simpleFinding.getNumberOfColumns()); finding.setNumberOfRows(simpleFinding.getNumberOfRows()); finding.setTheFileIndex(simpleFinding.getTheFileIndex()); List<Row> rowList = new ArrayList<Row>(); for(SimpleRowBean rowBean : simpleFinding.getRows()){ Row row = new Row(); List<TableCell> cellList = new ArrayList<TableCell>(); for(SimpleCell cell : rowBean.getCells()){ TableCell tbCell = new TableCell(); tbCell.setColumnOrder(cell.getColumnOrder()); tbCell.setDatumOrCondition(cell.getDatumOrCondition()); tbCell.setCreatedDate(cell.getCreatedDate()); tbCell.setValue(cell.getValue()); cellList.add(tbCell); } row.setCells(cellList); rowList.add(row); } finding.setRows(rowList); List<FileBean> fileList = new ArrayList<FileBean>(); for(SimpleFileBean fileBean : simpleFinding.getFiles()){ file = new File(); theFile = new FileBean(); file.setCreatedBy(fileBean.getCreatedBy()); file.setCreatedDate(fileBean.getCreatedDate()); file.setId(fileBean.getId()); file.setTitle(fileBean.getTitle()); file.setUriExternal(fileBean.getUriExternal()); file.setUri(fileBean.getUri()); file.setType(fileBean.getType()); theFile.setKeywordsStr(fileBean.getKeywordsStr()); theFile.setExternalUrl(fileBean.getExternalUrl()); theFile.setDomainFile(file); fileList.add(theFile); } finding.setFiles(fileList); return finding; } public SimpleFindingBean removeFile(HttpServletRequest request, SimpleFindingBean simpleFinding) throws Exception { CharacterizationBean achar = (CharacterizationBean) request.getSession().getAttribute("theChar"); SimpleCharacterizationEditBean editBean = (SimpleCharacterizationEditBean) request.getSession().getAttribute("theEditChar"); FindingBean findingBean = this.findMatchFindingBean(achar, simpleFinding); int theFileIndex = simpleFinding.getTheFileIndex(); findingBean.removeFile(theFileIndex); findingBean.setTheFile(new FileBean()); request.setAttribute("anchor", "submitFinding"); simpleFinding.transferFilesFromFindingBean(request, findingBean.getFiles()); //this.checkOpenForms(achar, theForm, request); //return mapping.findForward("inputForm"); return simpleFinding; } /** * * @param request * @param simpleFinding * @return * @throws Exception */ public SimpleFindingBean drawMatrix(HttpServletRequest request, SimpleFindingBean simpleFinding) throws Exception { CharacterizationBean achar = (CharacterizationBean) request.getSession().getAttribute("theChar"); SimpleCharacterizationEditBean editBean = (SimpleCharacterizationEditBean) request.getSession().getAttribute("theEditChar"); request.setAttribute("anchor", "result"); FindingBean findingBean = this.findMatchFindingBean(achar, simpleFinding); simpleFinding.transferTableNumbersToFindingBean(findingBean); // if (request.getParameter("removeColumn") != null) { // int columnToRemove = Integer.parseInt(request // .getParameter("removeColumn")); // findingBean.removeColumn(columnToRemove); // this.checkOpenForms(achar, theForm, request); // return mapping.findForward("inputForm"); // } else if (request.getParameter("removeRow") != null) { // int rowToRemove = Integer.parseInt(request // .getParameter("removeRow")); // findingBean.removeRow(rowToRemove); // this.checkOpenForms(achar, theForm, request); // return mapping.findForward("inputForm"); int existingNumberOfColumns = findingBean.getColumnHeaders().size(); int existingNumberOfRows = findingBean.getRows().size(); if (existingNumberOfColumns > findingBean.getNumberOfColumns()) { // ActionMessages msgs = new ActionMessages(); // ActionMessage msg = new ActionMessage( // "message.addCharacterization.removeMatrixColumn"); // msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); // saveMessages(request, msgs); // findingBean.setNumberOfColumns(existingNumberOfColumns); // //this.checkOpenForms(achar, theForm, request); // return mapping.getInputForward(); } if (existingNumberOfRows > findingBean.getNumberOfRows()) { // ActionMessages msgs = new ActionMessages(); // ActionMessage msg = new ActionMessage( // "message.addCharacterization.removeMatrixRow"); // msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); // saveMessages(request, msgs); // findingBean.setNumberOfRows(existingNumberOfRows); // this.checkOpenForms(achar, theForm, request); // return mapping.getInputForward(); } findingBean.updateMatrix(findingBean.getNumberOfColumns(), findingBean.getNumberOfRows()); InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, achar); simpleFinding.transferFromFindingBean(request, findingBean); simpleFinding.setColumnHeaders(findingBean.getColumnHeaders()); simpleFinding.setDefaultValuesForNullHeaders(); request.setAttribute("anchor", "submitFinding"); //this.checkOpenForms(achar, theForm, request); // set columnHeaders in the session so jsp can check duplicate columns request.getSession().setAttribute("columnHeaders", findingBean.getColumnHeaders()); //return mapping.findForward("inputForm"); return simpleFinding; } public SimpleCharacterizationEditBean deleteFinding(HttpServletRequest request, SimpleFindingBean simpleFinding) throws Exception { CharacterizationBean achar = (CharacterizationBean) request.getSession().getAttribute("theChar"); SimpleCharacterizationEditBean editBean = (SimpleCharacterizationEditBean) request.getSession().getAttribute("theEditChar"); FindingBean dataSetBean = this.findMatchFindingBean(achar, simpleFinding); CharacterizationService service = this.setServicesInSession(request); service.deleteFinding(dataSetBean.getDomain()); service.removeAccesses(achar.getDomainChar(), dataSetBean.getDomain()); achar.removeFinding(dataSetBean); request.setAttribute("anchor", "result"); //this.checkOpenForms(achar, theForm, request); InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, achar); return setupUpdate(request, String.valueOf(editBean.getParentSampleId()), achar.getDomainChar().getId().toString(), achar.getClassName(), achar.getCharacterizationType()); } public SimpleCharacterizationEditBean deleteExperimentConfig(HttpServletRequest request, SimpleExperimentBean simpleExpConfig) throws Exception { CharacterizationBean achar = (CharacterizationBean) request.getSession().getAttribute("theChar"); SimpleCharacterizationEditBean editBean = (SimpleCharacterizationEditBean) request.getSession().getAttribute("theEditChar"); editBean.getErrors().clear(); editBean.getMessages().clear(); ExperimentConfigBean configBean = achar.getTheExperimentConfig(); simpleExpConfig.transferToExperimentConfigBean(configBean); CharacterizationService service = this.setServicesInSession(request); service.deleteExperimentConfig(configBean.getDomain()); logger.debug("Experiment config deleted"); achar.removeExperimentConfig(configBean); if (validateInputs(request, achar, editBean.getMessages())) { logger.debug("char validated"); this.saveCharacterization(request, achar, editBean); logger.debug("Char saved"); } service.removeAccesses(achar.getDomainChar(), configBean.getDomain()); logger.debug("Access removed"); //this.checkOpenForms(achar, theForm, request); InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, achar); return setupUpdate(request, String.valueOf(editBean.getParentSampleId()), achar.getDomainChar().getId().toString(), achar.getClassName(), achar.getCharacterizationType()); } /** * Method to support setColumnOrder rest service * @param request * @param simpleFinding * @return * @throws Exception */ public SimpleFindingBean updateColumnOrder(HttpServletRequest request, SimpleFindingBean simpleFinding) throws Exception { CharacterizationBean achar = (CharacterizationBean) request.getSession().getAttribute("theChar"); // SimpleCharacterizationEditBean editBean = // (SimpleCharacterizationEditBean) request.getSession().getAttribute("theEditChar"); FindingBean findingBean = findMatchFindingBean(achar, simpleFinding); simpleFinding.transferColumnOrderToFindingBean(findingBean); findingBean.updateColumnOrder(); simpleFinding.transferFromFindingBean(request, findingBean); request.setAttribute("anchor", "submitFinding"); //this.checkOpenForms(achar, theForm, request); InitCharacterizationSetup.getInstance() .persistCharacterizationDropdowns(request, achar); return simpleFinding; } protected FindingBean findMatchFindingBean(CharacterizationBean achar, SimpleFindingBean simpleFinding) throws Exception { List<FindingBean> findingBeans = achar.getFindings(); if (findingBeans == null) throw new Exception("Current characterization has no finding matching input finding id: " + simpleFinding.getFindingId()); for (FindingBean finding : findingBeans) { if (finding.getDomain() != null) { Long id = finding.getDomain().getId(); if (id == null && simpleFinding.getFindingId() == 0 || //could be a new finding bean added when saving a file id != null && id.longValue() == simpleFinding.getFindingId()) { achar.setTheFinding(finding); return finding; } } } if (simpleFinding.getFindingId() <= 0) {//new finding FindingBean newBean = new FindingBean(); achar.setTheFinding(newBean); return newBean; } throw new Exception("Current characterization has no finding matching input finding id: " + simpleFinding.getFindingId()); } protected ExperimentConfigBean findMatchExperimentConfig(CharacterizationBean achar, SimpleExperimentBean simpleExp) throws Exception { long expId = simpleExp.getId(); if (expId <= 0) return achar.getTheExperimentConfig(); List<ExperimentConfigBean> expConfigs = achar.getExperimentConfigs(); if (expConfigs == null) throw new Exception("Current characterization has null experiment config list. This should not happen"); for (ExperimentConfigBean expConfig : expConfigs) { if (expConfig.getDomain() != null && expConfig.getDomain().getId() != null) { if (expId == expConfig.getDomain().getId().longValue()) return expConfig; } } throw new Exception("Current characterization has no Experiment config matching input experiment id: " + expId); } // private void checkOpenForms(CharacterizationBean achar, // DynaValidatorForm theForm, HttpServletRequest request) // throws Exception { // achar.updateEmptyFieldsToNull(); // String dispatch = request.getParameter("dispatch"); // String browserDispatch = getBrowserDispatch(request); // HttpSession session = request.getSession(); // Boolean openFile = false, openExperimentConfig = false, openFinding = false; // if (dispatch.equals("input") && browserDispatch.equals("addFile")) { // openFile = true; // session.setAttribute("openFile", openFile); // if (dispatch.equals("input") // && browserDispatch.equals("saveExperimentConfig")) { // openExperimentConfig = true; // session.setAttribute("openExperimentConfig", openExperimentConfig); // if (dispatch.equals("input") // && (browserDispatch.equals("saveFinding") || browserDispatch // .equals("addFile")) || dispatch.equals("addFile") // || dispatch.equals("removeFile") // || dispatch.equals("drawMatrix") // || dispatch.equals("getFinding") // || dispatch.equals("resetFinding") // || dispatch.equals("updateColumnOrder")) { // openFinding = true; // session.setAttribute("openFinding", openFinding); // InitCharacterizationSetup.getInstance() // .persistCharacterizationDropdowns(request, achar); // /** // * If user entered customized Char Type/Name, Assay Type by selecting // * [other], we should show and highlight the value on the edit page. // */ // String currentCharType = achar.getCharacterizationType(); // setOtherValueOption(request, currentCharType, "characterizationTypes"); // String currentCharName = achar.getCharacterizationName(); // setOtherValueOption(request, currentCharName, "charTypeChars"); // String currentAssayType = achar.getAssayType(); // setOtherValueOption(request, currentAssayType, "charNameAssays"); // // setup detail page // if (achar.isWithProperties()) { // String detailPage = null; // if (!StringUtils.isEmpty(achar.getCharacterizationType()) // && !StringUtils.isEmpty(achar.getCharacterizationName())) { // detailPage = InitCharacterizationSetup.getInstance() // .getDetailPage(achar.getCharacterizationType(), // achar.getCharacterizationName()); // request.setAttribute("characterizationDetailPage", detailPage); // // if finding contains more than one column, set disableSetColumnOrder // // false // if (achar.getTheFinding().getNumberOfColumns() > 1 // && dataMatrixSaved(achar.getTheFinding())) { // request.setAttribute("setColumnOrder", true); // } else { // request.setAttribute("setColumnOrder", false); private Boolean dataMatrixSaved(FindingBean theFinding) { if (theFinding.getColumnHeaders() != null) { for (ColumnHeader header : theFinding.getColumnHeaders()) { if (header.getCreatedDate() == null) { return false; } } } return true; } /** * Shared function for summaryExport() and summaryPrint(). Filter out * unselected types when user selected one type for print/export. * * @param request * @param compBean */ private List<String> filterType(HttpServletRequest request, String type, List<String> charTypes) { //String type = request.getParameter("type"); List<String> filteredTypes = new ArrayList<String>(); if( !StringUtils.isEmpty(type) && type.equals("all")) { filteredTypes = charTypes; } else if (!StringUtils.isEmpty(type) && charTypes.contains(type)) { filteredTypes.add(type); } request.setAttribute("characterizationTypes", filteredTypes); return filteredTypes; } private boolean validateCharacterization(HttpServletRequest request, CharacterizationBean achar, List<String> errors) { String charName = achar.getCharacterizationName(); String charType = achar.getCharacterizationType(); if (charType == null || charType.length() == 0) { errors.add("Characterization type can't be empty."); return false; } if (charName == null || charName.length() == 0) { errors.add("Characterization name can't be empty."); return false; } boolean status = true; if (charName.equalsIgnoreCase("shape")) { if (achar.getShape().getType() != null && !StringUtils.xssValidate(achar.getShape().getType())) { errors.add(PropertyUtil.getProperty("sample", "achar.shape.type.invalid")); status = false; } if (achar.getShape().getMaxDimensionUnit() != null && !achar.getShape().getMaxDimensionUnit() .matches(Constants.UNIT_PATTERN)) { errors.add(PropertyUtil.getProperty("sample", "achar.shape.maxDimensionUnit.invalid")); status = false; } if (achar.getShape().getMinDimensionUnit() != null && !achar.getShape().getMinDimensionUnit() .matches(Constants.UNIT_PATTERN)) { errors.add(PropertyUtil.getProperty("sample", "achar.shape.minDimensionUnit.invalid")); status = false; } } else if (charName.equalsIgnoreCase( "physical state")) { if (achar.getPhysicalState().getType() != null && !StringUtils.xssValidate(achar.getPhysicalState() .getType())) { errors.add(PropertyUtil.getProperty("sample", "achar.physicalState.type.invalid")); status = false; } } else if (charName.equalsIgnoreCase( "solubility")) { if (achar.getSolubility().getSolvent() != null && !StringUtils.xssValidate(achar.getSolubility() .getSolvent())) { errors.add(PropertyUtil.getProperty("sample", "achar.solubility.solvent.invalid")); status = false; } if (achar.getSolubility().getCriticalConcentrationUnit() != null && !achar.getSolubility().getCriticalConcentrationUnit() .matches(Constants.UNIT_PATTERN)) { errors.add(PropertyUtil.getProperty("sample", "achar.solubility.criticalConcentrationUnit.invalid")); status = false; } } else if (charName.equalsIgnoreCase( "enzyme induction")) { if (achar.getEnzymeInduction().getEnzyme() != null && !StringUtils.xssValidate(achar.getEnzymeInduction().getEnzyme())) { errors.add(PropertyUtil.getProperty("sample", "achar.enzymeInduction.enzyme.invalid")); status = false; } } return status; } private Boolean validateInputs(HttpServletRequest request, CharacterizationBean achar, List<String> errors) { if (!validateCharacterization(request, achar, errors)) { return false; } return true; } private boolean validateEmptyFinding(HttpServletRequest request, FindingBean finding, List<String> errors) { if (finding.getFiles().isEmpty() && finding.getColumnHeaders().isEmpty()) { errors.add(PropertyUtil.getProperty("sample", "achar.theFinding.emptyFinding")); return false; } else { return true; } } /** * Copy "isSoluble" property from achar to Solubility entity. * * @param achar */ private void copyIsSoluble(CharacterizationBean achar) { Boolean soluble = null; String isSoluble = achar.getIsSoluble(); if (!StringUtils.isEmpty(isSoluble)) { soluble = Boolean.valueOf(isSoluble); } if ("Solubility".equals(achar.getClassName())) { achar.getSolubility().setIsSoluble(soluble); } } public Boolean canUserExecutePrivateDispatch(UserBean user) throws SecurityException { if (user == null) { return false; } return true; } private CharacterizationService setServicesInSession( HttpServletRequest request) throws Exception { SecurityService securityService = super .getSecurityServiceFromSession(request); CharacterizationService charService = new CharacterizationServiceLocalImpl( securityService); request.getSession().setAttribute("characterizationService", charService); ProtocolService protocolService = new ProtocolServiceLocalImpl( securityService); request.getSession().setAttribute("protocolService", protocolService); SampleService sampleService = new SampleServiceLocalImpl( securityService); request.getSession().setAttribute("sampleService", sampleService); return charService; } public java.io.File download(String fileId, HttpServletRequest request) throws Exception { CharacterizationService service = setServicesInSession(request); return downloadImage(service, fileId, request); } public String download(String fileId, HttpServletRequest request, HttpServletResponse response) throws Exception { CharacterizationService service = setServicesInSession(request); return downloadFile(service, fileId, request, response); } protected boolean validCharTypeAndName(String charType, String charName, List<String> errors) { boolean valid = true; if (charType == null || charType.length() == 0) { errors.add("Characterization type can't be empty"); valid = false; } if (charName == null || charName.length() == 0) { errors.add("Characterization name can't be empty"); valid = false; } return valid; } }
package ucar.nc2.grib.grib1; import ucar.nc2.grib.GdsHorizCoordSys; import ucar.nc2.grib.GribNumbers; import ucar.nc2.grib.QuasiRegular; import ucar.nc2.util.Misc; import ucar.unidata.geoloc.*; import ucar.unidata.geoloc.projection.LatLonProjection; import ucar.unidata.geoloc.projection.Stereographic; import javax.annotation.concurrent.Immutable; import java.util.Arrays; import java.util.Formatter; @Immutable public abstract class Grib1Gds { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Grib1Gds.class); static final double maxReletiveErrorPos = .01; // reletive error in position - GRIB numbers sometime miscoded public static Grib1Gds factory(int template, byte[] data) { switch (template) { case 0: return new LatLon(data, 0); case 1: return new Mercator(data, 1); case 3: return new LambertConformal(data, 3); case 4: return new GaussianLatLon(data, 4); case 5: return new PolarStereographic(data, 5); case 10: return new RotatedLatLon(data, 10); case 50: return new SphericalHarmonicCoefficients(data, 50); default: return new UnknownGds(data, template); } } private static final float scale3 = (float) 1.0e-3; // private static final float scale6 = (float) 1.0e-6; protected final byte[] data; protected int[] nptsInLine; // thin grids, else null public final int template; protected int nx, ny; public int scanMode, resolution; protected int lastOctet; protected Grib1Gds(int template) { this.template = template; this.data = null; } public Grib1Gds(byte[] data, int template) { this.data = data; this.template = template; nx = getOctet2(7); ny = getOctet2(9); } public byte[] getRawBytes() { return data; } public int getNpts() { if (nptsInLine != null) { int npts = 0; for (int pts : nptsInLine) { npts += pts; } return npts; } else { return nx * ny; } } public int[] getNptsInLine() { return nptsInLine; } void setNptsInLine(int[] nptsInLine) { this.nptsInLine = nptsInLine; } protected int getOctet(int index) { if (index > data.length) { return GribNumbers.UNDEFINED; } return data[index - 1] & 0xff; } // signed protected int getOctet2(int start) { return GribNumbers.int2(getOctet(start), getOctet(start + 1)); } // signed protected int getOctet3(int start) { return GribNumbers.int3(getOctet(start), getOctet(start + 1), getOctet(start + 2)); } // signed protected int getOctet4(int start) { return GribNumbers.int4(getOctet(start), getOctet(start + 1), getOctet(start + 2), getOctet(start + 3)); } private static boolean getDirectionIncrementsGiven(int resolution) { return GribNumbers.testGribBitIsSet(resolution, 1); } private static boolean getEarthShapeIsSpherical(int resolution) { return !GribNumbers.testGribBitIsSet(resolution, 2); } private static boolean getUVisReletiveToEastNorth(int resolution) { return !GribNumbers.testGribBitIsSet(resolution, 5); } protected Earth getEarth() { if (getEarthShapeIsSpherical(resolution)) { return new Earth(6367470.0); } else { return EarthEllipsoid.IAU; } } public int getEarthShape() { return getEarthShapeIsSpherical(resolution) ? 0 : 1; } public boolean getUVisReletiveToEastNorth() { return getUVisReletiveToEastNorth(resolution); } public int getResolution() { return resolution; } public boolean isLatLon() { return false; } public int getScanMode() { return scanMode; } public int getNxRaw() { return nx; } public int getNyRaw() { return ny; } ///////// thin grid crapola // number of points along nx, adjusted for thin grid public int getNx() { if (nptsInLine == null || nx > 0) { return nx; } return QuasiRegular.getMax(nptsInLine); } // number of points along ny, adjusted for thin grid public int getNy() { if (nptsInLine == null || ny > 0) { return ny; } return QuasiRegular.getMax(nptsInLine); } // delta in x direction public float getDx() { return getDxRaw(); } // delta in y direction public float getDy() { return getDyRaw(); } public abstract float getDxRaw(); public abstract float getDyRaw(); public abstract GdsHorizCoordSys makeHorizCoordSys(); public abstract void testHorizCoordSys(Formatter f); public String getNameShort() { String className = getClass().getName(); int pos = className.lastIndexOf("$"); return className.substring(pos + 1); } @Override public String toString() { StringBuilder sb = new StringBuilder("Grib1Gds{"); sb.append(" template=").append(template); sb.append(", nx=").append(nx); sb.append(", ny=").append(ny); sb.append(", scanMode=").append(scanMode); sb.append(", resolution=").append(resolution); sb.append(", lastOctet=").append(lastOctet); if (nptsInLine == null) { sb.append(", nptsInLine=null"); } else { sb.append(", nptsInLine (").append(nptsInLine.length); sb.append(")=").append(Arrays.toString(nptsInLine)); } sb.append('}'); return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Grib1Gds Grib1Gds = (Grib1Gds) o; if (nx != Grib1Gds.nx) { return false; } if (ny != Grib1Gds.ny) { return false; } return template == Grib1Gds.template; } @Override public int hashCode() { int result = template; result = 31 * result + nx; result = 31 * result + ny; return result; } protected int hashCode; public static class LatLon extends Grib1Gds { protected float la1, lo1, la2, lo2, deltaLon, deltaLat; protected LatLon(int template) { super(template); } LatLon(byte[] data, int template) { super(data, template); la1 = getOctet3(11) * scale3; lo1 = getOctet3(14) * scale3; resolution = getOctet(17); // Resolution and component flags (see Code table 7) la2 = getOctet3(18) * scale3; lo2 = getOctet3(21) * scale3; if (lo2 < lo1) { lo2 += 360.0F; } deltaLon = getOctet2(24); float calcDelta = (lo2 - lo1) / (nx - 1); // more accurate - deltaLon may have roundoff if (deltaLon != GribNumbers.UNDEFINED) { deltaLon *= scale3; // undefined for thin grids } else { deltaLon = calcDelta; } // If calcDelta is a finite number (isn't the case when we only have one lat/lon // point in the GDS, which can lead to NaN or +/-Inf), can compare deltaLon // against a calculated delta, which appears to be more accurate in some cases. if (Float.isFinite(calcDelta) && !Misc.nearlyEquals(deltaLon, calcDelta)) { log.debug("deltaLon != calcDeltaLon"); deltaLon = calcDelta; } deltaLat = getOctet2(26); calcDelta = (la2 - la1) / (ny - 1); // more accurate - deltaLon may have roundoff if (deltaLat != GribNumbers.UNDEFINED) { deltaLat *= scale3; // undefined for thin grids if (la2 < la1) { deltaLat *= -1.0; } } else { deltaLat = calcDelta; } /* * thanks to johann.sorel@geomatys.com 11/1/2012. withdrawn for now 11/2/2012 * if (deltaLat != GribNumbers.UNDEFINED) { * deltaLat *= scale3; // undefined for thin grids * if (la2 < la1) { * //flip declaration order * float latemp = la1; * la1 = la2; * la2 = latemp; * calcDelta *= -1.0; * * //we must also consider the cell corner, since we flipped the order * //we should specify that the true value is at the BOTTOM-LEFT corner * //but we can't show this information so we make a one cell displacement * //to move the value on a TOP-LEFT corner. * la1 -= calcDelta; * la2 -= calcDelta; * } * } else { * deltaLat = calcDelta; * } */ // If calcDelta is a finite number (isn't the case when we only have one lat/lon // point in the GDS, which can lead to NaN or +/-Inf), can compare deltaLon // against a calculated delta, which appears to be more accurate in some cases. if (Float.isFinite(calcDelta) && !Misc.nearlyEquals(deltaLat, calcDelta)) { log.debug("deltaLat != calcDeltaLat"); deltaLat = calcDelta; } scanMode = (byte) getOctet(28); lastOctet = 28; } @Override public void setNptsInLine(int[] nptsInLine) { super.setNptsInLine(nptsInLine); // now that we know this, we may have to recalc some stuff int n = QuasiRegular.getMax(nptsInLine); if (nx < 0) { deltaLon = (lo2 - lo1) / (n - 1); } if (ny < 0) { deltaLat = (la2 - la1) / (n - 1); } } @Override public boolean isLatLon() { return true; } @Override public float getDx() { if (nptsInLine == null || deltaLon != GribNumbers.UNDEFINED) { return deltaLon; } return (lo2 - lo1) / (getNx() - 1); } @Override public float getDy() { if (nptsInLine == null || deltaLat != GribNumbers.UNDEFINED) { return deltaLat; } return (la2 - la1) / (getNy() - 1); } @Override public float getDxRaw() { return deltaLon; } @Override public float getDyRaw() { return deltaLat; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } LatLon other = (LatLon) o; if (!Misc.nearlyEqualsAbs(la1, other.la1, maxReletiveErrorPos * deltaLat)) { return false; // allow some slop, reletive to grid size } if (!Misc.nearlyEqualsAbs(lo1, other.lo1, maxReletiveErrorPos * deltaLon)) { return false; } if (!Misc.nearlyEquals(deltaLat, other.deltaLat)) { return false; } return Misc.nearlyEquals(deltaLon, other.deltaLon); } @Override public int hashCode() { if (hashCode == 0) { int useLat = (int) (la1 / (maxReletiveErrorPos * deltaLat)); // Two equal objects must have the same hashCode() // value int useLon = (int) (lo1 / (maxReletiveErrorPos * deltaLon)); int useDeltaLon = (int) (deltaLon / Misc.defaultMaxRelativeDiffFloat); int useDeltaLat = (int) (deltaLat / Misc.defaultMaxRelativeDiffFloat); int result = super.hashCode(); result = 31 * result + useLat; result = 31 * result + useLon; result = 31 * result + useDeltaLon; result = 31 * result + useDeltaLat; hashCode = result; } return hashCode; } @Override public String toString() { return "LatLon{" + "la1=" + la1 + ", lo1=" + lo1 + ", la2=" + la2 + ", lo2=" + lo2 + ", deltaLon=" + deltaLon + ", deltaLat=" + deltaLat + "} " + super.toString(); } @Override public GdsHorizCoordSys makeHorizCoordSys() { LatLonProjection proj = new LatLonProjection(getEarth()); // ProjectionPoint startP = proj.latLonToProj(LatLonPoint.create(la1, lo1)); double startx = lo1; // startP.getX(); double starty = la1; // startP.getY(); return new GdsHorizCoordSys(getNameShort(), template, 0, scanMode, proj, startx, getDx(), starty, getDy(), getNx(), getNy(), null); } public void testHorizCoordSys(Formatter f) { GdsHorizCoordSys cs = makeHorizCoordSys(); double Lo2 = lo2; if (Lo2 < lo1) { Lo2 += 360; } LatLonPoint startLL = LatLonPoint.create(la1, lo1); LatLonPoint endLL = LatLonPoint.create(la2, Lo2); f.format("%s testProjection%n", getClass().getName()); f.format(" start at latlon= %s%n", startLL); f.format(" end at latlon= %s%n", endLL); ProjectionPoint endPP = cs.proj.latLonToProj(endLL); f.format(" start at proj coord= %s%n", ProjectionPoint.create(cs.startx, cs.starty)); f.format(" end at proj coord= %s%n", endPP); double endx = cs.startx + (getNx() - 1) * cs.dx; double endy = cs.starty + (getNy() - 1) * cs.dy; f.format(" should end at x= (%f,%f)%n", endx, endy); } } public static class GaussianLatLon extends LatLon { final int nparellels; public float latSouthPole, lonSouthPole, rotAngle, latPole, lonPole, stretchFactor; GaussianLatLon(byte[] data, int template) { super(data, template); nparellels = getOctet2(26); if (data.length > 32) { latSouthPole = getOctet3(33) * scale3; lonSouthPole = getOctet3(36) * scale3; rotAngle = getOctet4(39) * scale3; latPole = getOctet3(43) * scale3; lonPole = getOctet3(46) * scale3; stretchFactor = getOctet4(49) * scale3; } lastOctet = 52; } @Override public GdsHorizCoordSys makeHorizCoordSys() { GdsHorizCoordSys hc = super.makeHorizCoordSys(); hc.setGaussianLats(nparellels, la1, la2); return hc; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } GaussianLatLon that = (GaussianLatLon) o; return nparellels == that.nparellels; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + nparellels; return result; } @Override public String toString() { return "GaussianLatLon{" + "nparellels=" + nparellels + ", latSouthPole=" + latSouthPole + ", lonSouthPole=" + lonSouthPole + ", rotAngle=" + rotAngle + ", latPole=" + latPole + ", lonPole=" + lonPole + ", stretchFactor=" + stretchFactor + "} " + super.toString(); } } public static class PolarStereographic extends Grib1Gds { protected float la1, lo1, lov, dX, dY; protected int projCenterFlag; private final float lad = (float) 60.0; // LOOK protected PolarStereographic(int template) { super(template); } PolarStereographic(byte[] data, int template) { super(data, template); la1 = getOctet3(11) * scale3; lo1 = getOctet3(14) * scale3; resolution = getOctet(17); // Resolution and component flags (see Code table 7) lov = getOctet3(18) * scale3; dX = getOctet3(21) * scale3; dY = getOctet3(24) * scale3; projCenterFlag = getOctet(27); scanMode = getOctet(28); lastOctet = 28; } @Override public String toString() { return "PolarStereographic{" + "la1=" + la1 + ", lo1=" + lo1 + ", lov=" + lov + ", dX=" + dX + ", dY=" + dY + ", projCenterFlag=" + projCenterFlag + ", lad=" + lad + "} " + super.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } PolarStereographic that = (PolarStereographic) o; if (!Misc.nearlyEqualsAbs(la1, that.la1, maxReletiveErrorPos * dY)) { return false; // allow some slop, reletive to grid size } if (!Misc.nearlyEqualsAbs(lo1, that.lo1, maxReletiveErrorPos * dX)) { return false; } if (!Misc.nearlyEquals(lov, that.lov)) { return false; } if (!Misc.nearlyEquals(dY, that.dY)) { return false; } if (!Misc.nearlyEquals(dX, that.dX)) { return false; } return projCenterFlag == that.projCenterFlag; } @Override public int hashCode() { if (hashCode == 0) { int useLat = (int) (la1 / (maxReletiveErrorPos * dY)); // Two equal objects must have the same hashCode() value int useLon = (int) (lo1 / (maxReletiveErrorPos * dX)); int useLov = (int) (lov / Misc.defaultMaxRelativeDiffFloat); int useDeltaLon = (int) (dX / Misc.defaultMaxRelativeDiffFloat); int useDeltaLat = (int) (dY / Misc.defaultMaxRelativeDiffFloat); int result = super.hashCode(); result = 31 * result + useLat; result = 31 * result + useLon; result = 31 * result + useLov; result = 31 * result + useDeltaLon; result = 31 * result + useDeltaLat; result = 31 * result + projCenterFlag; hashCode = result; } return hashCode; } @Override public float getDxRaw() { return dX; } @Override public float getDyRaw() { return dY; } public GdsHorizCoordSys makeHorizCoordSys() { boolean northPole = (projCenterFlag & 128) == 0; double latOrigin = northPole ? 90.0 : -90.0; // Why the scale factor?. according to GRIB docs: // "Grid lengths are in units of meters, at the 60 degree latitude circle nearest to the pole" // since the scale factor at 60 degrees = k = 2*k0/(1+sin(60)) [Snyder,Working Manual p157] // then to make scale = 1 at 60 degrees, k0 = (1+sin(60))/2 = .933 double scale; if (Double.isNaN(lad)) { // LOOK ?? scale = 0.9330127018922193; } else { scale = (1.0 + Math.sin(Math.toRadians(Math.abs(lad)))) / 2; } ProjectionImpl proj; Earth earth = getEarth(); if (earth.isSpherical()) { proj = new Stereographic(latOrigin, lov, scale); } else { proj = new ucar.unidata.geoloc.projection.proj4.StereographicAzimuthalProjection(latOrigin, lov, scale, lad, 0.0, 0.0, earth); } ProjectionPointImpl start = (ProjectionPointImpl) proj.latLonToProj(LatLonPoint.create(la1, lo1)); return new GdsHorizCoordSys(getNameShort(), template, 0, scanMode, proj, start.getX(), getDx(), start.getY(), getDy(), getNx(), getNy(), null); } public void testHorizCoordSys(Formatter f) { GdsHorizCoordSys cs = makeHorizCoordSys(); f.format("%s testProjection %s%n", getClass().getName(), cs.proj.getClass().getName()); double endx = cs.startx + (getNx() - 1) * cs.dx; double endy = cs.starty + (getNy() - 1) * cs.dy; ProjectionPoint endPP = ProjectionPoint.create(endx, endy); f.format(" start at proj coord= %s%n", ProjectionPoint.create(cs.startx, cs.starty)); f.format(" end at proj coord= %s%n", endPP); LatLonPoint startLL = LatLonPoint.create(la1, lo1); LatLonPoint endLL = cs.proj.projToLatLon(endPP); f.format(" start at latlon= %s%n", startLL); f.format(" end at latlon= %s%n", endLL); } } public static class LambertConformal extends Grib1Gds { protected final float la1; protected final float lo1; protected final float lov; protected float lad; protected final float dX; protected final float dY; protected final float latin1; protected final float latin2; protected final float latSouthPole; protected final float lonSouthPole; protected final int projCenterFlag; // private int hla1, hlo1, hlov, hlad, hdX, hdY, hlatin1, hlatin2; // hasheesh LambertConformal(byte[] data, int template) { super(data, template); la1 = getOctet3(11) * scale3; lo1 = getOctet3(14) * scale3; resolution = getOctet(17); // Resolution and component flags (see Code table 7) lov = getOctet3(18) * scale3; dX = getOctet3(21) * scale3; dY = getOctet3(24) * scale3; projCenterFlag = getOctet(27); scanMode = getOctet(28); latin1 = getOctet3(29) * scale3; latin2 = getOctet3(32) * scale3; latSouthPole = getOctet3(35) * scale3; lonSouthPole = getOctet3(38) * scale3; lastOctet = 42; } @Override public float getDxRaw() { return dX; } @Override public float getDyRaw() { return dY; } @Override public String toString() { return "LambertConformal{" + "la1=" + la1 + ", lo1=" + lo1 + ", lov=" + lov + ", lad=" + lad + ", dX=" + dX + ", dY=" + dY + ", latin1=" + latin1 + ", latin2=" + latin2 + ", latSouthPole=" + latSouthPole + ", lonSouthPole=" + lonSouthPole + ", projCenterFlag=" + projCenterFlag + "} " + super.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } LambertConformal that = (LambertConformal) o; if (!Misc.nearlyEqualsAbs(la1, that.la1, maxReletiveErrorPos * dY)) { return false; // allow some slop, relative to grid size } if (!Misc.nearlyEqualsAbs(lo1, that.lo1, maxReletiveErrorPos * dX)) { return false; } if (!Misc.nearlyEquals(lad, that.lad)) { return false; } if (!Misc.nearlyEquals(lov, that.lov)) { return false; } if (!Misc.nearlyEquals(dY, that.dY)) { return false; } if (!Misc.nearlyEquals(dX, that.dX)) { return false; } if (!Misc.nearlyEquals(latin1, that.latin1)) { return false; } return Misc.nearlyEquals(latin2, that.latin2); } @Override public int hashCode() { if (hashCode == 0) { int useLat = (int) (la1 / (maxReletiveErrorPos * dY)); // Two equal objects must have the same hashCode() value int useLon = (int) (lo1 / (maxReletiveErrorPos * dX)); int useLad = (int) (lad / Misc.defaultMaxRelativeDiffFloat); int useLov = (int) (lov / Misc.defaultMaxRelativeDiffFloat); int useDeltaLon = (int) (dX / Misc.defaultMaxRelativeDiffFloat); int useDeltaLat = (int) (dY / Misc.defaultMaxRelativeDiffFloat); int useLatin1 = (int) (latin1 / Misc.defaultMaxRelativeDiffFloat); int useLatin2 = (int) (latin2 / Misc.defaultMaxRelativeDiffFloat); int result = super.hashCode(); result = 31 * result + useLat; result = 31 * result + useLon; result = 31 * result + useLad; result = 31 * result + useLov; result = 31 * result + useDeltaLon; result = 31 * result + useDeltaLat; result = 31 * result + useLatin1; result = 31 * result + useLatin2; result = 31 * result + projCenterFlag; hashCode = result; } return hashCode; } public GdsHorizCoordSys makeHorizCoordSys() { ProjectionImpl proj; Earth earth = getEarth(); if (earth.isSpherical()) { proj = new ucar.unidata.geoloc.projection.LambertConformal(latin1, lov, latin1, latin2, 0.0, 0.0, earth.getEquatorRadius() * .001); } else { proj = new ucar.unidata.geoloc.projection.proj4.LambertConformalConicEllipse(latin1, lov, latin1, latin2, 0.0, 0.0, earth); } LatLonPoint startLL = LatLonPoint.create(la1, lo1); ProjectionPointImpl start = (ProjectionPointImpl) proj.latLonToProj(startLL); return new GdsHorizCoordSys(getNameShort(), template, 0, scanMode, proj, start.getX(), getDx(), start.getY(), getDy(), getNx(), getNy(), null); } public void testHorizCoordSys(Formatter f) { GdsHorizCoordSys cs = makeHorizCoordSys(); f.format("%s testProjection %s%n", getClass().getName(), cs.proj.getClass().getName()); double endx = cs.startx + (getNx() - 1) * cs.dx; double endy = cs.starty + (getNy() - 1) * cs.dy; ProjectionPoint endPP = ProjectionPoint.create(endx, endy); f.format(" start at proj coord= %s%n", ProjectionPoint.create(cs.startx, cs.starty)); f.format(" end at proj coord= %s%n", endPP); LatLonPoint startLL = LatLonPoint.create(la1, lo1); LatLonPoint endLL = cs.proj.projToLatLon(endPP); f.format(" start at latlon= %s%n", startLL); f.format(" end at latlon= %s%n", endLL); } } public static class Mercator extends Grib1Gds { protected final float la1; protected final float lo1; protected final float la2; protected final float lo2; protected final float latin; protected final float dX; protected final float dY; Mercator(byte[] data, int template) { super(data, template); la1 = getOctet3(11) * scale3; lo1 = getOctet3(14) * scale3; resolution = getOctet(17); // Resolution and component flags (see Code table 7) la2 = getOctet3(18) * scale3; lo2 = getOctet3(21) * scale3; latin = getOctet3(24) * scale3; scanMode = getOctet(28); dX = getOctet3(29) * scale3; dY = getOctet3(32) * scale3; lastOctet = 42; } @Override public float getDxRaw() { return dX; } @Override public float getDyRaw() { return dY; } @Override public String toString() { return "Mercator{" + "la1=" + la1 + ", lo1=" + lo1 + ", la2=" + la2 + ", lo2=" + lo2 + ", latin=" + latin + ", dX=" + dX + ", dY=" + dY + "} " + super.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } Mercator that = (Mercator) o; if (!Misc.nearlyEqualsAbs(la1, that.la1, maxReletiveErrorPos * dY)) { return false; // allow some slop, reletive to grid size } if (!Misc.nearlyEqualsAbs(lo1, that.lo1, maxReletiveErrorPos * dX)) { return false; } if (!Misc.nearlyEquals(latin, that.latin)) { return false; } if (!Misc.nearlyEquals(dY, that.dY)) { return false; } return Misc.nearlyEquals(dX, that.dX); } @Override public int hashCode() { if (hashCode == 0) { int useLat = (int) (la1 / (maxReletiveErrorPos * dY)); // Two equal objects must have the same hashCode() value int useLon = (int) (lo1 / (maxReletiveErrorPos * dX)); int useLad = (int) (latin / Misc.defaultMaxRelativeDiffFloat); int useDeltaLon = (int) (dX / Misc.defaultMaxRelativeDiffFloat); int useDeltaLat = (int) (dY / Misc.defaultMaxRelativeDiffFloat); int result = super.hashCode(); result = 31 * result + useLat; result = 31 * result + useLon; result = 31 * result + useLad; result = 31 * result + useDeltaLon; result = 31 * result + useDeltaLat; hashCode = result; } return hashCode; } public GdsHorizCoordSys makeHorizCoordSys() { // put longitude origin at first point - doesnt actually matter // param par standard parallel (degrees). cylinder cuts earth at this latitude. // LOOK dont have an elipsoidal Mercator projection Earth earth = getEarth(); ucar.unidata.geoloc.projection.Mercator proj = new ucar.unidata.geoloc.projection.Mercator(lo1, latin, 0, 0, earth.getEquatorRadius() * .001); // find out where things start ProjectionPoint startP = proj.latLonToProj(LatLonPoint.create(la1, lo1)); double startx = startP.getX(); double starty = startP.getY(); return new GdsHorizCoordSys(getNameShort(), template, 0, scanMode, proj, startx, getDx(), starty, getDy(), getNx(), getNy(), null); } public void testHorizCoordSys(Formatter f) { GdsHorizCoordSys cs = makeHorizCoordSys(); double Lo2 = lo2; if (Lo2 < lo1) { Lo2 += 360; } LatLonPoint startLL = LatLonPoint.create(la1, lo1); LatLonPoint endLL = LatLonPoint.create(la2, Lo2); f.format("%s testProjection%n", getClass().getName()); f.format(" start at latlon= %s%n", startLL); f.format(" end at latlon= %s%n", endLL); ProjectionPoint endPP = cs.proj.latLonToProj(endLL); f.format(" start at proj coord= %s%n", ProjectionPoint.create(cs.startx, cs.starty)); f.format(" end at proj coord= %s%n", endPP); double endx = cs.startx + (getNx() - 1) * cs.dx; double endy = cs.starty + (getNy() - 1) * cs.dy; f.format(" should end at x= (%f,%f)%n", endx, endy); } } public static class RotatedLatLon extends LatLon { protected final float angleRotation; // Angle of rotation (represented in the same way as the reference value) protected final float latSouthPole; // Latitude of pole of stretching in millidegrees (integer) protected final float lonSouthPole; // Longitude of pole of stretching in millidegrees (integer) RotatedLatLon(byte[] data, int template) { super(data, template); latSouthPole = getOctet3(33) * scale3; lonSouthPole = getOctet3(36) * scale3; angleRotation = getOctet4(39) * scale3; lastOctet = 43; } public String getName() { return "Rotated latitude/longitude"; } @Override public String toString() { return "RotatedLatLon{" + "angleRotation=" + angleRotation + ", latSouthPole=" + latSouthPole + ", lonSouthPole=" + lonSouthPole + "} " + super.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } RotatedLatLon other = (RotatedLatLon) o; return Misc.nearlyEquals(angleRotation, other.angleRotation); } @Override public int hashCode() { if (hashCode == 0) { int result = super.hashCode(); result = 31 * result + (angleRotation != +0.0f ? Float.floatToIntBits(angleRotation) : 0); hashCode = result; } return hashCode; } public GdsHorizCoordSys makeHorizCoordSys() { ucar.unidata.geoloc.projection.RotatedLatLon proj = new ucar.unidata.geoloc.projection.RotatedLatLon(latSouthPole, lonSouthPole, angleRotation); // LOOK dont transform - works for grib1 Q:/cdmUnitTest/transforms/HIRLAMhybrid.grib // LatLonPoint startLL = proj.projToLatLon(ProjectionPoint.create(lo1, la1)); // double startx = startLL.getLongitude(); // double starty = startLL.getLatitude(); return new GdsHorizCoordSys(getNameShort(), template, 0, scanMode, proj, lo1, deltaLon, la1, deltaLat, nx, ny, null); } public void testHorizCoordSys(Formatter f) { GdsHorizCoordSys cs = makeHorizCoordSys(); LatLonPoint startLL = cs.proj.projToLatLon(ProjectionPoint.create(lo1, la1)); LatLonPoint endLL = cs.proj.projToLatLon(ProjectionPoint.create(lo2, la2)); f.format("%s testProjection%n", getClass().getName()); f.format(" start at latlon= %s%n", startLL); f.format(" end at latlon= %s%n", endLL); ProjectionPoint endPP = cs.proj.latLonToProj(endLL); f.format(" start at proj coord= %s%n", ProjectionPoint.create(cs.startx, cs.starty)); f.format(" end at proj coord= %s%n", endPP); double endx = cs.startx + (nx - 1) * cs.dx; double endy = cs.starty + (ny - 1) * cs.dy; f.format(" should end at x= (%f,%f)%n", endx, endy); } } public static class SphericalHarmonicCoefficients extends Grib1Gds { final int j; final int k; final int m; final int type; final int mode; SphericalHarmonicCoefficients(byte[] data, int template) { super(data, template); j = getOctet2(7); k = getOctet2(9); m = getOctet2(11); type = getOctet(13); // code table 9 mode = getOctet(14); // code table 10 } @Override public float getDxRaw() { return 0; } @Override public float getDyRaw() { return 0; } @Override public GdsHorizCoordSys makeHorizCoordSys() { return null; // LOOK not done yet } @Override public void testHorizCoordSys(Formatter f) {} @Override public String toString() { return "SphericalHarmonicCoefficients{" + "j=" + j + ", k=" + k + ", m=" + m + ", type=" + type + ", mode=" + mode + "} " + super.toString(); } } public static class UnknownGds extends Grib1Gds { UnknownGds(byte[] data, int template) { super(data, template); } @Override public float getDxRaw() { return 0; } @Override public float getDyRaw() { return 0; } @Override public GdsHorizCoordSys makeHorizCoordSys() { return null; // LOOK } @Override public void testHorizCoordSys(Formatter f) { } @Override public String toString() { return "UnknownGds{} " + super.toString(); } } }
package cn.cerc.db.mysql; import cn.cerc.core.IHandle; import cn.cerc.core.Record; import cn.cerc.core.TDateTime; import cn.cerc.core.Utils; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import static cn.cerc.core.Utils.safeString; /** * select * * @author */ public class BuildQuery { public static final String vbCrLf = "\r\n"; private SqlQuery dataSet; private List<String> sqlWhere = new ArrayList<>(); private List<String> sqlText = new ArrayList<>(); private String orderText; private String sql; private IHandle handle; public BuildQuery(IHandle handle) { super(); this.handle = handle; } /** * * * @param param * @return */ public BuildQuery byParam(String param) { if (!"".equals(param)) { sqlWhere.add("(" + param + ")"); } return this; } /** * * <p> * List * <p> * SQL * <p> * and ( * CusCode_ like '%05559255%' * or SalesCode_ like '%05559255%' * or AppUser_ like '%05559255%' * or UpdateUser_ like '%05559255%' * or Address_ like '%05559255%' * or Mobile_ like '%$i8OknluCnFsW$%' * ) * * @param items * @return */ public BuildQuery byLink(Map<String, List<String>> items) { if (items == null) { return this; } StringBuilder builder = new StringBuilder(); for (String k : items.keySet()) { List<String> fields = items.get(k); String text = "%" + safeString(k).replaceAll("\\*", "") + "%"; for (String field : fields) { builder.append(String.format("%s like '%s'", field, text)); builder.append(" or "); } } String str = builder.toString(); str = str.substring(0, str.length() - 3); sqlWhere.add("(" + str + ")"); return this; } public BuildQuery byLink(String[] fields, String value) { if (value == null || "".equals(value)) { return this; } String str = ""; String s1 = "%" + safeString(value).replaceAll("\\*", "") + "%"; for (String sql : fields) { str = str + String.format("%s like '%s'", sql, s1); str = str + " or "; } str = str.substring(0, str.length() - 3); sqlWhere.add("(" + str + ")"); return this; } public BuildQuery byNull(String field, boolean value) { String s = value ? "not null" : "null"; sqlWhere.add(String.format("%s is %s", field, s)); return this; } public BuildQuery byField(String field, String text) { String value = safeString(text); if ("".equals(value)) { return this; } if ("*".equals(value)) { return this; } if (value.contains("*")) { sqlWhere.add(String.format("%s like '%s'", field, value.replace("*", "%"))); return this; } if ("``".equals(value)) { sqlWhere.add(String.format("%s='%s'", field, "`")); return this; } if ("`is null".equals(value)) { sqlWhere.add(String.format("(%s is null or %s='')", field, field)); return this; } if (!value.startsWith("`")) { sqlWhere.add(String.format("%s='%s'", field, value)); return this; } if ("`=".equals(value.substring(0, 2))) { sqlWhere.add(String.format("%s=%s", field, value.substring(2))); return this; } if ("`!=".equals(value.substring(0, 3)) || "`<>".equals(value.substring(0, 3))) { sqlWhere.add(String.format("%s<>%s", field, value.substring(3))); return this; } return this; } public BuildQuery byField(String field, int value) { sqlWhere.add(String.format("%s=%s", field, value)); return this; } public BuildQuery byField(String field, double value) { sqlWhere.add(String.format("%s=%s", field, value)); return this; } public BuildQuery byField(String field, TDateTime value) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sqlWhere.add(String.format("%s='%s'", field, sdf.format(value.getData()))); return this; } public BuildQuery byField(String field, boolean value) { int s = value ? 1 : 0; sqlWhere.add(String.format("%s=%s", field, s)); return this; } public BuildQuery byBetween(String field, String value1, String value2) { sqlWhere.add(String.format("%s between '%s' and '%s'", field, safeString(value1), safeString(value2))); return this; } public BuildQuery byBetween(String field, int value1, int value2) { sqlWhere.add(String.format("%s between %s and %s", field, value1, value2)); return this; } public BuildQuery byBetween(String field, double value1, double value2) { sqlWhere.add(String.format("%s between %s and %s", field, value1, value2)); return this; } public BuildQuery byBetween(String field, TDateTime value1, TDateTime value2) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sqlWhere.add(String.format(" %s between '%s' and '%s' ", field, sdf.format(value1.getData()), sdf.format(value2.getData()))); return this; } public BuildQuery byRange(String field, String... values) { // where code_ in ("aa","Bb") if (values.length > 0) { String s = field + " in ("; for (String val : values) { s = s + "'" + safeString(val) + "',"; } s = s.substring(0, s.length() - 1) + ")"; sqlWhere.add(s); } return this; } public BuildQuery byRange(String field, int[] values) { if (values.length > 0) { String s = field + " in ("; for (int sql : values) { s = s + sql + ","; } s = s.substring(0, s.length() - 1) + ")"; sqlWhere.add(s); } return this; } public BuildQuery byRange(String field, double[] values) { if (values.length > 0) { String s = field + " in ("; for (double sql : values) { s = s + sql + ","; } s = s.substring(0, s.length() - 1) + ")"; sqlWhere.add(s); } return this; } public BuildQuery add(String text) { String regex = "((\\bselect)|(\\bSelect)|(\\s*select)|(\\s*Select))\\s*(distinct)*\\s+%s"; if (text.matches(regex)) { text = text.replaceFirst("%s", ""); } sqlText.add(text); return this; } public BuildQuery add(String fmtText, Object... args) { ArrayList<Object> items = new ArrayList<>(); for (Object arg : args) { if (arg instanceof String) { items.add(Utils.safeString((String) arg)); } else { items.add(arg); } } sqlText.add(String.format(fmtText, items.toArray())); return this; } public SqlQuery getDataSet() { if (this.dataSet == null) { this.dataSet = new SqlQuery(handle); } return this.dataSet; } public void setDataSet(SqlQuery dataSet) { this.dataSet = dataSet; } protected String getSelectCommand() { if (this.sql != null) { sql = sql.replaceFirst("%s", ""); return this.sql; } StringBuffer str = new StringBuffer(); for (String sql : sqlText) { if (str.length() > 0) { str.append(vbCrLf); } str.append(sql); } if (sqlWhere.size() > 0) { if (str.length() > 0) { str.append(vbCrLf); } str.append("where "); for (String sql : sqlWhere) { str.append(sql).append(" and "); } str.setLength(str.length() - 5); } if (orderText != null) { str.append(vbCrLf).append(orderText); } String sqls = str.toString().trim(); sqls = sqls.replaceAll(" %s ", " "); return sqls; } public String getCommandText() { String sql = getSelectCommand(); if ("".equals(sql)) { return sql; } if (getDataSet().getSqlText().getMaximum() > -1) { return sql + " limit " + getDataSet().getSqlText().getMaximum(); } else { return sql; } } public SqlQuery open() { SqlQuery ds = getDataSet(); ds.getSqlText().clear(); ds.add(this.getSelectCommand()); ds.open(); return ds; } public SqlQuery openReadonly() { SqlQuery ds = getDataSet(); ds.getSqlText().clear(); ds.add(this.getSelectCommand()); ds.openReadonly(); return ds; } public SqlQuery open(Record head, Record foot) { SqlQuery ds = getDataSet(); if (!head.exists("__offset__")) { } else { this.setOffset(head.getInt("__offset__")); } ds.getSqlText().clear(); ds.add(this.getSelectCommand()); ds.open(); if (foot == null) { return ds; } foot.setField("__finish__", ds.getFetchFinish()); return ds; } public SqlQuery openReadonly(Record head, Record foot) { SqlQuery ds = getDataSet(); if (head.exists("__offset__")) { this.setOffset(head.getInt("__offset__")); } ds.getSqlText().clear(); ds.add(this.getSelectCommand()); ds.openReadonly(); if (foot != null) { foot.setField("__finish__", ds.getFetchFinish()); } return ds; } // @Override public void close() { sql = null; sqlText.clear(); sqlWhere.clear(); orderText = null; if (this.dataSet != null) { this.dataSet.close(); } } public int getOffset() { return getDataSet().getSqlText().getOffset(); } public BuildQuery setOffset(int offset) { getDataSet().getSqlText().setOffset(offset); return this; } public int getMaximum() { return getDataSet().getSqlText().getMaximum(); } public BuildQuery setMaximum(int maximum) { getDataSet().getSqlText().setMaximum(maximum); return this; } public String getOrderText() { return this.orderText; } public void setOrderText(String orderText) { this.orderText = orderText; } }
package org.objectweb.proactive.core.component.group; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.util.Map; import java.util.Vector; import org.objectweb.fractal.api.Component; import org.objectweb.fractal.api.Interface; import org.objectweb.proactive.Body; import org.objectweb.proactive.ProActive; import org.objectweb.proactive.core.ProActiveRuntimeException; import org.objectweb.proactive.core.component.collectiveitfs.MulticastHelper; import org.objectweb.proactive.core.component.exceptions.ParameterDispatchException; import org.objectweb.proactive.core.component.identity.ProActiveComponent; import org.objectweb.proactive.core.component.type.ProActiveInterfaceType; import org.objectweb.proactive.core.component.type.ProActiveInterfaceTypeImpl; import org.objectweb.proactive.core.group.ExceptionListException; import org.objectweb.proactive.core.group.ProActiveComponentGroup; import org.objectweb.proactive.core.group.ProcessForAsyncCall; import org.objectweb.proactive.core.group.ProcessForOneWayCall; import org.objectweb.proactive.core.group.ProxyForGroup; import org.objectweb.proactive.core.mop.ClassNotReifiableException; import org.objectweb.proactive.core.mop.ConstructionOfReifiedObjectFailedException; import org.objectweb.proactive.core.mop.ConstructorCall; import org.objectweb.proactive.core.mop.MOP; import org.objectweb.proactive.core.mop.MethodCall; import org.objectweb.proactive.core.mop.StubObject; /** * An extension of the standard group proxy for handling groups of component interfaces. * * @author Matthieu Morel * */ public class ProxyForComponentInterfaceGroup extends ProxyForGroup { protected ProActiveInterfaceType interfaceType; protected Class itfSignatureClass = null; protected ProActiveComponent owner; protected ProxyForComponentInterfaceGroup delegatee = null; public ProxyForComponentInterfaceGroup() throws ConstructionOfReifiedObjectFailedException { super(); className = Interface.class.getName(); } public ProxyForComponentInterfaceGroup(ConstructorCall c, Object[] p) throws ConstructionOfReifiedObjectFailedException { super(c, p); className = Interface.class.getName(); } public ProxyForComponentInterfaceGroup(String nameOfClass) throws ConstructionOfReifiedObjectFailedException { this(); className = Interface.class.getName(); } /** * @return Returns the interfaceType. */ public ProActiveInterfaceType getInterfaceType() { return interfaceType; } /* * @see org.objectweb.proactive.core.group.ProxyForGroup#reify(org.objectweb.proactive.core.mop.MethodCall) */ @Override public synchronized Object reify(MethodCall mc) throws InvocationTargetException { if (delegatee != null) { // check if (itfSignatureClass.equals(mc.getReifiedMethod() .getDeclaringClass())) { // nothing to do } else if (mc.getReifiedMethod().getDeclaringClass() .isAssignableFrom(itfSignatureClass)) { // need to adapt method call Method adaptedMethod; try { // TODO optimize (avoid reflective calls!) adaptedMethod = itfSignatureClass.getMethod(mc.getReifiedMethod() .getName(), mc.getReifiedMethod().getParameterTypes()); } catch (SecurityException e) { throw new InvocationTargetException(e, "could not adapt client interface to multicast server interface " + interfaceType.getFcItfName()); } catch (NoSuchMethodException e) { throw new InvocationTargetException(e, "could not adapt client interface to multicast server interface " + interfaceType.getFcItfName()); } mc = MethodCall.getComponentMethodCall(adaptedMethod, mc.getEffectiveArguments(), mc.getGenericTypesMapping(), mc.getComponentMetadata().getComponentInterfaceName(), mc.getComponentMetadata().getSenderItfID(), mc.getComponentMetadata().getPriority()); } else { throw new InvocationTargetException(null, "method " + mc.getName() + " defined in " + mc.getReifiedMethod().getDeclaringClass() + " cannot be invoked on " + itfSignatureClass.getName()); } } return super.reify(mc); } /* * @see org.objectweb.proactive.core.group.Group#getGroupByType() */ @Override public Object getGroupByType() { try { Interface result = ProActiveComponentGroup.newComponentInterfaceGroup(interfaceType, owner); ProxyForComponentInterfaceGroup proxy = (ProxyForComponentInterfaceGroup) ((StubObject) result).getProxy(); proxy.memberList = this.memberList; proxy.className = this.className; proxy.interfaceType = this.interfaceType; proxy.owner = this.owner; proxy.proxyForGroupID = this.proxyForGroupID; proxy.waited = this.waited; return result; } catch (ClassNotReifiableException e) { e.printStackTrace(); return null; } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } } /* * @see org.objectweb.proactive.core.group.ProxyForGroup#asynchronousCallOnGroup(org.objectweb.proactive.core.mop.MethodCall) */ @Override protected Object asynchronousCallOnGroup(MethodCall mc) throws InvocationTargetException { if (((ProActiveInterfaceTypeImpl) interfaceType).isFcCollective()) { if (delegatee != null) { Object result; Body body = ProActive.getBodyOnThis(); // Creates a stub + ProxyForGroup for representing the result try { Object[] paramProxy = new Object[0]; // create a result group of the type of the adapted mc if (!(mc.getReifiedMethod().getGenericReturnType() instanceof ParameterizedType)) { throw new ProActiveRuntimeException( "all methods in multicast interfaces must return parameterized lists, " + "which is not the case for method " + mc.getReifiedMethod().toString()); } Class returnTypeForGroup = (Class) ((ParameterizedType) mc.getReifiedMethod() .getGenericReturnType()).getActualTypeArguments()[0]; result = MOP.newInstance(returnTypeForGroup.getName(), null, null, ProxyForGroup.class.getName(), paramProxy); ((ProxyForGroup) ((StubObject) result).getProxy()).setClassName(returnTypeForGroup.getName()); } catch (Exception e) { e.printStackTrace(); return null; } Map<MethodCall, Integer> generatedMethodCalls; try { generatedMethodCalls = MulticastHelper.generateMethodCallsForMulticastDelegatee(owner, mc, delegatee); } catch (ParameterDispatchException e) { throw new InvocationTargetException(e, "cannot dispatch invocation parameters for method " + mc.getReifiedMethod().toString() + " from collective interface " + interfaceType.getFcItfName()); } // Init the lists of result with null value to permit the "set(index)" operation Vector memberListOfResultGroup = ((ProxyForGroup) ((StubObject) result).getProxy()).getMemberList(); // there are as many results expected as there are method invocations for (int i = 0; i < generatedMethodCalls.size(); i++) { memberListOfResultGroup.add(null); } for (MethodCall currentMc : generatedMethodCalls.keySet()) { // delegate invocations this.threadpool.addAJob(new ProcessForAsyncCall(delegatee, delegatee.memberList, memberListOfResultGroup, generatedMethodCalls.get(currentMc), currentMc, body)); } // LocalBodyStore.getInstance().setCurrentThreadBody(body); return result; } else { Thread.dumpStack(); return null; } } else { return super.asynchronousCallOnGroup(mc); } } /* * @see org.objectweb.proactive.core.group.ProxyForGroup#oneWayCallOnGroup(org.objectweb.proactive.core.mop.MethodCall, org.objectweb.proactive.core.group.ExceptionListException) */ @Override protected void oneWayCallOnGroup(MethodCall mc, ExceptionListException exceptionList) throws InvocationTargetException { if (((ProActiveInterfaceTypeImpl) interfaceType).isFcCollective() && (delegatee != null)) { // 2. generate adapted method calls depending on nb members and parameters distribution // each method call is assigned a given member index Body body = ProActive.getBodyOnThis(); Map<MethodCall, Integer> generatedMethodCalls; try { generatedMethodCalls = MulticastHelper.generateMethodCallsForMulticastDelegatee(owner, mc, delegatee); } catch (ParameterDispatchException e) { throw new InvocationTargetException(e, "cannot dispatch invocation parameters for method " + mc.getReifiedMethod().toString() + " from collective interface " + interfaceType.getFcItfName()); } for (MethodCall currentMc : generatedMethodCalls.keySet()) { // delegate invocations this.threadpool.addAJob(new ProcessForOneWayCall(delegatee, delegatee.memberList, generatedMethodCalls.get(currentMc), currentMc, body, exceptionList)); } // LocalBodyStore.getInstance().setCurrentThreadBody(body); } super.oneWayCallOnGroup(mc, exceptionList); } /** * The delegatee introduces an indirection which can be used for altering the reified invocation * */ public void setDelegatee(ProxyForComponentInterfaceGroup delegatee) { this.delegatee = delegatee; } /** * The delegatee introduces an indirection which can be used for altering the reified invocation * */ public ProxyForComponentInterfaceGroup getDelegatee() { return delegatee; } /* * @see org.objectweb.proactive.core.group.ProxyForGroup#size() */ @Override public int size() { if (getDelegatee() != null) { return getDelegatee().size(); } return super.size(); } /** * @return Returns the owner. */ public Component getOwner() { return owner; } /** * @param owner The owner to set. */ public void setOwner(Component owner) { this.owner = (ProActiveComponent) owner; } /** * @param interfaceType The interfaceType to set. */ public void setInterfaceType(ProActiveInterfaceType interfaceType) { this.interfaceType = interfaceType; try { itfSignatureClass = Class.forName(interfaceType.getFcItfSignature()); } catch (ClassNotFoundException e) { throw new ProActiveRuntimeException("cannot find Java interface " + interfaceType.getFcItfSignature() + " defined in interface named " + interfaceType.getFcItfName(), e); } } }
package fini.main.model; import fini.main.MainApp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalTime; import java.util.Date; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class Task { public static enum TaskType { FLOATING, DEADLINE, EVENT }; private StringProperty title; private SimpleObjectProperty<LocalDate> date; private SimpleStringProperty startTime; private SimpleStringProperty endTime; private StringProperty priority; private StringProperty id; private SimpleStringProperty recurringDay; private TaskType type; DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); private SimpleStringProperty deadline; /** * Default constructor. */ public Task() { this(null); } /** * Constructor with some initial data. * @param title */ public Task(String title) { this.title = new SimpleStringProperty(title); // Some initial dummy data, just for convenient testing. //this.date = new SimpleObjectProperty<LocalDate>(LocalDate.of(2015, 9, 14)); this.priority = new SimpleStringProperty("Normal"); setTaskId(); } public void setTaskId() { int taskId = MainApp.getTaskData().size() + 1; this.id = new SimpleStringProperty(Integer.toString(taskId)); } public void setTaskId(int newIndex) { this.id = new SimpleStringProperty(Integer.toString(newIndex)); } public Task(String title, String taskDetails) { this.title = new SimpleStringProperty(title); int indexOfPriority = checkIfPriorityExists(taskDetails); int indexOfStartTime = checkIfStartTimeExists(taskDetails); int indexOfEndTime = checkIfEndTimeExists(taskDetails); int indexOfDeadline = checkIfOnlyDeadlineExists(taskDetails); int indexOfRecurringTask = checkIfRecurringDeadlineExists(taskDetails); if(indexOfRecurringTask >= 0) { System.out.println("ENTERED"); String dateDetails = taskDetails; System.out.println(dateDetails); if(indexOfPriority > 0) { dateDetails = taskDetails.substring(indexOfRecurringTask, indexOfPriority); } int indexOfTime = dateDetails.indexOf("at "); String timeDetails = dateDetails.substring(indexOfTime); timeDetails = timeDetails.replace("at ", ""); this.startTime = new SimpleStringProperty(timeDetails); dateDetails = dateDetails.substring(0, indexOfTime-1); dateDetails = dateDetails.replace("every ", ""); dateDetails = dateDetails.toUpperCase(); String storeRecurringDay = ""; System.out.println(dateDetails); if (dateDetails.equals("MONDAY")) { storeRecurringDay = "Mon"; } else if (dateDetails.equals("TUESDAY")) { storeRecurringDay = "Tue"; } else if (dateDetails.equals("WEDNESDAY")) { storeRecurringDay = "Wed"; } else if (dateDetails.equals("THURSDAY")) { storeRecurringDay = "Thu"; } else if (dateDetails.equals("FRIDAY")) { storeRecurringDay = "Fri"; } else if (dateDetails.equals("SATURDAY")) { storeRecurringDay = "Sat"; } else if (dateDetails.equals("SUNDAY")) { storeRecurringDay = "Sun"; } System.out.println(storeRecurringDay + "HELLO"); this.recurringDay = new SimpleStringProperty(storeRecurringDay); } else if(indexOfDeadline > 0) { String date = taskDetails.substring(0, indexOfDeadline-1); setDate(date); if(indexOfPriority > 0) { String deadlineDetails = taskDetails.substring(indexOfDeadline, indexOfPriority-1); deadlineDetails = deadlineDetails.replace("at ", ""); String priorityDetails = taskDetails.substring(indexOfPriority); this.startTime = new SimpleStringProperty(deadlineDetails); priorityDetails = priorityDetails.replace("with priority", ""); this.priority = new SimpleStringProperty(priorityDetails.toUpperCase()); } } if(indexOfPriority > 0) { String priorityDetails = taskDetails.substring(indexOfPriority); priorityDetails = priorityDetails.replace("with priority", ""); this.priority = new SimpleStringProperty(priorityDetails.toUpperCase()); } if((indexOfStartTime > 0) && (indexOfEndTime > 0)) { String dateDetails = taskDetails.substring(0, indexOfStartTime - 1); setDate(dateDetails); String startTimeDetails = taskDetails.substring(indexOfStartTime, indexOfEndTime-1); startTimeDetails = startTimeDetails.replace("from ", ""); this.startTime = new SimpleStringProperty(startTimeDetails); if (indexOfPriority > 0) { String endTimeDetails = taskDetails.substring(indexOfEndTime, indexOfPriority - 1); this.endTime = new SimpleStringProperty(endTimeDetails.replace("to ", "")); String priorityDetails = taskDetails.substring(indexOfPriority); priorityDetails = priorityDetails.replace("with priority", ""); this.priority = new SimpleStringProperty(priorityDetails.toUpperCase()); } else { String endTimeDetails = taskDetails.substring(indexOfEndTime); this.endTime = new SimpleStringProperty(endTimeDetails.replace("to ", "")); } } // if(indexOfPriority > 0) { // setDate(taskDetails, indexOfPriority); // String priorityDetails = taskDetails.substring(indexOfPriority); // priorityDetails = priorityDetails.replace("with priority", ""); // this.priority = new SimpleStringProperty(priorityDetails.toUpperCase()); // } else { // setDate(taskDetails); // this.priority = new SimpleStringProperty("Normal"); setTaskId(); } private int checkIfRecurringDeadlineExists(String taskDetails) { return taskDetails.indexOf("every"); } private int checkIfOnlyDeadlineExists(String taskDetails) { return taskDetails.indexOf("at"); } private int checkIfStartTimeExists(String taskDetails) { return taskDetails.indexOf("from"); } private int checkIfEndTimeExists(String taskDetails) { return taskDetails.indexOf("to"); } private int checkIfPriorityExists(String taskDetails) { return taskDetails.indexOf("with priority"); } private void setDate(String taskDetails) { String[] dateArray = taskDetails.split("/"); int day = Integer.parseInt(dateArray[0]); int month = Integer.parseInt(dateArray[1]); int year = Integer.parseInt(dateArray[2]); this.date = new SimpleObjectProperty<LocalDate>(LocalDate.of(year, month, day)); } private void setDate(String taskDetails, int indexOfPriorityDetails) { taskDetails = taskDetails.substring(0, indexOfPriorityDetails-1); String[] dateArray = taskDetails.split("/"); int day = Integer.parseInt(dateArray[0]); int month = Integer.parseInt(dateArray[1]); int year = Integer.parseInt(dateArray[2]); this.date = new SimpleObjectProperty<LocalDate>(LocalDate.of(year, month, day)); } public String getTitle() { return title.get(); } public void setTitle(String title) { this.title.set(title); } public StringProperty getTitleProperty() { return title; } public StringProperty getIdProperty() { return id; } public LocalDate getDate() { return date.get(); } public void setDate(LocalDate date) { this.date.set(date); } public String getPriority() { return priority.get(); } public void setPriority(String priority) { this.priority.set(priority); } public StringProperty getPriorityProperty() { return priority; } public SimpleObjectProperty<LocalDate> getDateProperty() { return date; } public SimpleStringProperty getStartTimeProperty() { return startTime; } public SimpleStringProperty getEndTimeProperty() { return endTime; } public SimpleStringProperty getRecurringProperty() { return recurringDay; } }
package foam.dao; import foam.core.*; import foam.dao.*; import foam.mlang.*; import foam.mlang.predicate.*; import foam.mlang.order.*; public abstract class AbstractDAO extends ContextAwareSupport implements DAO { public final static long MAX_SAFE_INTEGER = 9007199254740991l; protected ClassInfo of_ = null; protected PropertyInfo primaryKey_ = null; public DAO where(Predicate predicate) { return new FilteredDAO(predicate, this); } public DAO orderBy(Comparator comparator) { return new OrderedDAO(comparator, this); } public DAO skip(long count) { return new SkipDAO(count, this); } public DAO limit(long count) { return new LimitedDAO(count, this); } public void pipe_(X x, foam.dao.Sink sink) { throw new UnsupportedOperationException(); } protected Sink decorateSink_(Sink sink, long skip, long limit, Comparator order, Predicate predicate) { if ( limit < this.MAX_SAFE_INTEGER ) { sink = new LimitedSink(limit, 0, sink); } if ( skip > 0 ) { sink = new SkipSink(skip, 0, sink); } if ( order != null ) { sink = new OrderedSink(order, null, sink); } if ( predicate != null ) { sink = new PredicatedSink(predicate, sink); } return sink; } public ClassInfo getOf() { return of_; } public AbstractDAO setOf(ClassInfo of) { of_ = of; primaryKey_ = (PropertyInfo)of.getAxiomByName("id"); return this; } public PropertyInfo getPrimaryKey() { return primaryKey_; } protected Object getPK(FObject obj) { return getPrimaryKey().get(obj); } public void listen() { this.listen_(this.getX()); } public void listen_(X x) { // TODO } public FObject put(FObject obj) { return this.put_(this.getX(), obj); } public FObject remove(FObject obj) { return this.remove_(this.getX(), obj); } public void removeAll() { this.removeAll_(this.getX(), 0, this.MAX_SAFE_INTEGER, null, null); } public void removeAll_(X x, Sink sink, long skip, long limit, Comparator order, Predicate predicate) { this.select_(x, new RemoveSink(this), skip, limit, order, predicate); } public Sink select(Sink sink) { return this.select_(this.getX(), sink, 0, this.MAX_SAFE_INTEGER, null, null); } public FObject find(Object id) { return this.find_(this.getX(), id); } public void pipe(Sink sink) { this.pipe_(this.getX(), sink); } public DAO inX(X x) { ProxyDAO dao = new ProxyDAO(this); dao.setX(x); return dao; } public Object cmd_(X x, Object obj) { // TODO return null; } public Object cmd(Object obj) { return this.cmd_(this.getX(), obj); } }
package org.smoothbuild.builtin.file.match.testing; import static com.google.common.truth.Truth.assertThat; import static org.smoothbuild.builtin.file.match.testing.NamePatternGenerator.generatePatternsImpl; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; public class NamePatternGeneratorTest { @Test public void all_possible_patterns_are_generated() { final List<String> generatedPatterns = new ArrayList<>(); generatePatternsImpl(3, generatedPatterns::add); assertThat(generatedPatterns) .containsExactly("aaa", "aab", "aa*", "aba", "abb", "abc", "ab*", "a*a", "a*b", "*aa", "*ab", "*a*"); } }
package com.health.visuals; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.swing.JFrame; import com.health.Column; import com.health.Record; import com.health.Table; import com.health.ValueType; import com.xeiam.xchart.Chart; import com.xeiam.xchart.ChartBuilder; import com.xeiam.xchart.StyleManager.ChartType; import com.xeiam.xchart.StyleManager.LegendPosition; import com.xeiam.xchart.SwingWrapper; import de.erichseifert.vectorgraphics2d.PDFGraphics2D; import de.erichseifert.vectorgraphics2d.VectorGraphics2D; /** * Generates a Frequency Bar Diagram based on a Table object. * * @author Bjorn van der Laan &amp; Lizzy Scholten * */ public final class FreqBar { /** * Private constructor to prevent instantiation. */ private FreqBar() { // Nothing happens } /** * Generates a Frequency bar diagram. This variant has no column specified. * It chooses the last date column and last frequency column in the Table * object. * * @param table * Table to use */ public static JFrame frequencyBar(final Table table) { // Check if the Table contains a frequency and a date column Column freqColumn = null; Column dateColumn = null; for (Column c : table.getColumns()) { if (c.isFrequencyColumn()) { freqColumn = c; } else if (c.getType() == ValueType.Date) { dateColumn = c; } } // If both exist, format the frequency map based on these columns. if (freqColumn != null && dateColumn != null) { Map<String, Integer> freqMap = formatFrequencyMap(table, freqColumn.getName(), dateColumn.getName()); return makeBarChart(freqMap, dateColumn.getName()); } else { // Not good. throw new RuntimeException("Table contains either no frequency column or no date column."); } } /** * Generates a Frequency Bar diagram. * * @param table * Table to use * @param column * Column to display frequency of */ public static JFrame frequencyBar(final Table table, final String column) { // Check if the Table contains a frequency column Column freqColumn = null; for (Column c : table.getColumns()) { if (c.isFrequencyColumn()) { freqColumn = c; } } // If the Table contains a frequency column, use it to format the // frequency map // Else if no frequency column exists, count occurrences of values in // the specified column if (freqColumn != null) { Map<String, Integer> freqMap = formatFrequencyMap(table, freqColumn.getName(), column); return makeBarChart(freqMap, column); } else { Map<String, Integer> freqMap = createFrequencyMap(table, column); return makeBarChart(freqMap, column); } } /** * Creates a frequency map from the input Table to serve as input for * makeBarChart. * * @param table * Table to use * @param freqColumn * the frequency column * @param column * the column * @return frequency map */ private static Map<String, Integer> formatFrequencyMap(final Table table, final String freqColumn, final String column) { // Create map to save frequencies Map<String, Integer> freqMap = new HashMap<String, Integer>(); for (Record r : table) { String value = r.getValue(column).toString(); double frequency = (Double) r.getValue(freqColumn); freqMap.put(value, (int) frequency); } return freqMap; } /** * Counts the occurrences of each value of column and creates a frequency * map. Used when no the table contains no frequency column * * @param table * Table to use * @param column * Column to count * @return frequency map */ private static Map<String, Integer> createFrequencyMap(final Table table, final String column) { // Create map to save frequencies Map<String, Integer> freqMap = new HashMap<String, Integer>(); for (Record r : table) { // Get value of record String value = r.getValue(column).toString(); if (!freqMap.containsKey(value)) { freqMap.put(value, 1); } else { int currentFrequency = freqMap.get(value); freqMap.replace(value, ++currentFrequency); } } return freqMap; } /** * Creates a frequency bar diagram based on the frequency map. * * @param freqMap * frequency map */ private static JFrame makeBarChart(final Map<String, Integer> freqMap, final String seriesName) { final int frameWidth = 800; final int frameHeight = 600; // Convert input data for processing ArrayList<String> labels = new ArrayList<String>(freqMap.keySet()); ArrayList<Integer> frequency = new ArrayList<Integer>(freqMap.values()); // Create Chart Chart chart = new ChartBuilder().chartType(ChartType.Bar) .width(frameWidth).height(frameHeight).title("Score Histogram") .xAxisTitle(seriesName).yAxisTitle("Frequency").build(); chart.addSeries(seriesName, new ArrayList<String>(labels), new ArrayList<Integer>(frequency)); // Customize Chart chart.getStyleManager().setLegendPosition(LegendPosition.InsideNW); return new SwingWrapper(chart).displayChart(); } public static void saveGraph(Chart chart, String fileName) throws IOException{ VectorGraphics2D g = new PDFGraphics2D(0.0, 0.0, chart.getWidth(), chart.getHeight()); chart.paint(g, chart.getWidth(), chart.getHeight()); // Write the vector graphic output to a file FileOutputStream file = new FileOutputStream(fileName + ".pdf"); try { file.write(g.getBytes()); } finally { file.close(); } } }
package foam.nanos.boot; import foam.core.*; import foam.dao.AbstractSink; import foam.dao.ArraySink; import foam.dao.DAO; import foam.dao.ProxyDAO; import foam.dao.java.JDAO; import foam.nanos.auth.Group; import foam.nanos.auth.User; import foam.nanos.logger.Logger; import foam.nanos.logger.ProxyLogger; import foam.nanos.logger.StdoutLogger; import foam.nanos.pm.NullPM; import foam.nanos.pm.PM; import foam.nanos.script.Script; import foam.nanos.session.Session; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import static foam.mlang.MLang.EQ; public class Boot { // Context key used to store the top-level root context in the context. public final static String ROOT = "_ROOT_"; public static PM nullPM_ = new NullPM(); protected DAO serviceDAO_; protected X root_ = new ProxyX(); protected Map<String, NSpecFactory> factories_ = new HashMap<>(); public Boot() { this(""); } public Boot(String datadir) { Logger logger = new ProxyLogger(new StdoutLogger()); root_.put("logger", logger); if ( datadir == null || datadir == "" ) { datadir = System.getProperty("JOURNAL_HOME"); } root_.put(foam.nanos.fs.Storage.class, new foam.nanos.fs.FileSystemStorage(datadir)); // Used for all the services that will be required when Booting serviceDAO_ = new foam.nanos.auth.PermissionedPropertyDAO(root_, new JDAO(((foam.core.ProxyX) root_).getX(), NSpec.getOwnClassInfo(), "services")); installSystemUser(); // Just adding services in order will create an un-ordered tree, // so add so that we get a balanced Context tree. ArraySink arr = (ArraySink) serviceDAO_.select(new ArraySink()); List l = perfectList(arr.getArray()); for ( int i = 0 ; i < l.size() ; i++ ) { NSpec sp = (NSpec) l.get(i); NSpecFactory factory = new NSpecFactory((ProxyX) root_, sp); factories_.put(sp.getName(), factory); logger.info("Registering:", sp.getName()); root_.putFactory(sp.getName(), factory); } serviceDAO_.listen(new AbstractSink() { @Override public void put(Object obj, Detachable sub) { NSpec sp = (NSpec) obj; logger.info("Reload service:", sp.getName()); factories_.get(sp.getName()).invalidate(sp); } }, null); // PM factory, only return a real PM 1% of the time root_ = root_.putFactory("PM", new XFactory() { public Object create(X x) { return ThreadLocalRandom.current().nextInt(0, 100) == 0 ? new PM() : nullPM_ ; } }); // Use an XFactory so that the root context can contain itself. root_ = root_.putFactory(ROOT, new XFactory() { public Object create(X x) { return Boot.this.getX(); } }); // Revert root_ to non ProxyX to avoid letting children add new bindings. root_ = ((ProxyX) root_).getX(); // Export the ServiceDAO ((ProxyDAO) root_.get("nSpecDAO")).setDelegate( new foam.nanos.auth.AuthorizationDAO(getX(), serviceDAO_, new foam.nanos.auth.GlobalReadAuthorizer("service"))); // 'read' authenticated version - for dig and docs ((ProxyDAO) root_.get("AuthenticatedNSpecDAO")).setDelegate( new foam.dao.PMDAO(root_, new foam.nanos.auth.AuthorizationDAO(getX(), (DAO) root_.get("nSpecDAO"), new foam.nanos.auth.StandardAuthorizer("service")))); serviceDAO_.where(EQ(NSpec.LAZY, false)).select(new AbstractSink() { @Override public void put(Object obj, Detachable sub) { NSpec sp = (NSpec) obj; logger.info("Starting:", sp.getName()); root_.get(sp.getName()); } }); String startScript = System.getProperty("foam.main", "main"); if ( startScript != null ) { DAO scriptDAO = (DAO) root_.get("scriptDAO"); Script script = (Script) scriptDAO.find(startScript); if ( script != null ) { script.runScript(root_); } } } protected List perfectList(List src) { List dst = new ArrayList(src.size()); perfectList(src, dst, 0, src.size()-1); return dst; } protected void perfectList(List src, List dst, int start, int end) { if ( start == end ) { dst.add(src.get(start)); } else if ( end > start ) { int pivot = ( start + end ) / 2; perfectList(src, dst, pivot, pivot); perfectList(src, dst, start, pivot-1); perfectList(src, dst, pivot+1, end); } } protected void installSystemUser() { User user = new User(); user.setId(User.SYSTEM_USER_ID); user.setFirstName("system"); user.setGroup("system"); user.setLoginEnabled(false); Session session = new Session(); session.setUserId(user.getId()); session.setContext(root_); root_.put("user", user); root_.put(Session.class, session); Group group = new Group(); group.setId("system"); root_.put("group", group); } public X getX() { return root_; } public static void main (String[] args) throws java.lang.Exception { System.out.println("Starting Nanos Server"); boolean datadirFlag = false; String datadir = ""; for ( int i = 0 ; i < args.length ; i++ ) { String arg = args[i]; if ( datadirFlag ) { datadir = arg; datadirFlag = false; } else if ( arg.equals("--datadir") ) { datadirFlag = true; } else { System.err.println("Unknown argument " + arg); System.exit(1); } } System.out.println("Datadir is " + datadir); new Boot(datadir); } }
package com.hokolinks.model; import android.content.Context; import com.hokolinks.deeplinking.listeners.MetadataRequestListener; import com.hokolinks.utils.Utils; import com.hokolinks.utils.log.HokoLog; import com.hokolinks.utils.networking.Networking; import com.hokolinks.utils.networking.async.HttpRequest; import com.hokolinks.utils.networking.async.HttpRequestCallback; import com.hokolinks.utils.networking.async.NetworkAsyncTask; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import java.util.HashMap; import java.util.List; /** * Deeplink is the model which represents an inbound or outbound deeplink object. * It contains a route format string, the route parameters, the query parameters and an optional * url scheme. */ public class Deeplink { // Key values from incoming deeplinks private static final String SMARTLINK_CLICK_IDENTIFIER_KEY = "_hk_cid"; private static final String SMARTLINK_IDENTIFIER_KEY = "_hk_sid"; private static final String METADATA_KEY = "_hk_md"; private static final String METADATA_PATH = "smartlinks/metadata"; private String mRoute; private HashMap<String, String> mRouteParameters; private HashMap<String, String> mQueryParameters; private JSONObject mMetadata; private String mURLScheme; private HashMap<String, JSONObject> mURLs; private String mDeeplinkURL; private boolean mIsDeferred; private boolean mWasOpened; private boolean mIsUnique; /** * The constructor for Deeplink objects. * * @param urlScheme Optional url scheme. * @param route A route in route format. * @param routeParameters A HashMap where the keys are the route components and the values are * the route parameters. * @param queryParameters A HashMap where the keys are the query components and the values are * the query parameters. * @param metadata A JSONObject containing metadata to be passed to whoever opens the deeplink. * @param deeplinkURL The actual deeplink url opened by the app. * @param isDeferred true in case the deeplink came from a deferred deeplink, false otherwise. * @param isUnique true in case the deeplink should be unique, false otherwise. */ public Deeplink(String urlScheme, String route, HashMap<String, String> routeParameters, HashMap<String, String> queryParameters, JSONObject metadata, String deeplinkURL, boolean isDeferred, boolean isUnique) { if (urlScheme == null) mURLScheme = ""; else mURLScheme = urlScheme; mRoute = route; mMetadata = metadata; mRouteParameters = routeParameters != null ? routeParameters : new HashMap<String, String>(); mQueryParameters = queryParameters != null ? queryParameters : new HashMap<String, String>(); mURLs = new HashMap<>(); mDeeplinkURL = deeplinkURL; mIsDeferred = isDeferred; mIsUnique = isUnique; } /** * An easy to use static function for the developer to generate their own deeplinks to * generate Smartlinks afterwards. * * @return The generated Deeplink. */ public static Deeplink deeplink() { return deeplink(null); } /** * An easy to use static function for the developer to generate their own deeplinks to * generate Smartlinks afterwards. * * @param route A route in route format. * @return The generated Deeplink. */ public static Deeplink deeplink(String route) { return deeplink(route, null); } /** * An easy to use static function for the developer to generate their own deeplinks to * generate Smartlinks afterwards. * * @param route A route in route format. * @param routeParameters A HashMap where the keys are the route components and the values are * the route parameters. * @return The generated Deeplink. */ public static Deeplink deeplink(String route, HashMap<String, String> routeParameters) { return deeplink(route, routeParameters, null); } /** * An easy to use static function for the developer to generate their own deeplinks to * generate Smartlinks afterwards. * * @param route A route in route format. * @param routeParameters A HashMap where the keys are the route components and the values are * the route parameters. * @param queryParameters A HashMap where the keys are the query components and the values are * the query parameters. * @return The generated Deeplink. */ public static Deeplink deeplink(String route, HashMap<String, String> routeParameters, HashMap<String, String> queryParameters) { return deeplink(route, routeParameters, queryParameters, null); } /** * An easy to use static function for the developer to generate their own deeplinks to * generate Smartlinks afterwards. * * @param route A route in route format. * @param routeParameters A HashMap where the keys are the route components and the values are * the route parameters. * @param queryParameters A HashMap where the keys are the query components and the values are * the query parameters. * @param metadata A JSONObject containing metadata to be passed to whoever opens the deeplink. * @return The generated Deeplink. */ public static Deeplink deeplink(String route, HashMap<String, String> routeParameters, HashMap<String, String> queryParameters, JSONObject metadata) { return deeplink(route, routeParameters, queryParameters, metadata, false); } /** * An easy to use static function for the developer to generate their own deeplinks to * generate Smartlinks afterwards. * * @param route A route in route format. * @param routeParameters A HashMap where the keys are the route components and the values are * the route parameters. * @param queryParameters A HashMap where the keys are the query components and the values are * the query parameters. * @param metadata A JSONObject containing metadata to be passed to whoever opens the deeplink. * @param isUnique true in case the deeplink should be unique, false otherwise. * @return The generated Deeplink. */ public static Deeplink deeplink(String route, HashMap<String, String> routeParameters, HashMap<String, String> queryParameters, JSONObject metadata, boolean isUnique) { Deeplink deeplink = new Deeplink(null, Utils.sanitizeRoute(route), routeParameters, queryParameters, metadata, null, false, isUnique); if (matchRoute(deeplink.getRoute(), deeplink.getRouteParameters()) || (route == null && routeParameters == null && queryParameters == null && metadata == null)) { return deeplink; } return null; } public static boolean matchRoute(String route, HashMap<String, String> routeParameters) { List<String> routeComponents = Arrays.asList(route.split("/")); for (int index = 0; index < routeComponents.size(); index++) { String routeComponent = routeComponents.get(index); if (routeComponent.startsWith(":") && routeComponent.length() > 2) { String token = routeComponent.substring(1); if (!routeParameters.containsKey(token)) { return false; } } } return true; } /** * Allows the developer to add a custom deeplink for a given platform. * * @param url The deeplink URL to be used on the platform. * @param platform The platform (from the DeeplinkPlatform enum). */ public void addURL(String url, DeeplinkPlatform platform) { try { JSONObject urlJSON = new JSONObject(); urlJSON.put("link", url); mURLs.put(stringForPlatform(platform), urlJSON); } catch (JSONException e) { HokoLog.e(e); } } /** * Logic behind the deeplink needing to request the server for metadata. * * @return true if the server should get metadata and doesn't have it already, false otherwise. */ public boolean needsMetadata() { return hasMetadataKey() && mMetadata == null; } private String stringForPlatform(DeeplinkPlatform platform) { switch (platform) { case IPHONE: return "iphone"; case IPAD: return "ipad"; case IOS_UNIVERSAL: return "universal"; case ANDROID: return "android"; case WEB: return "web"; default: return null; } } public boolean hasURLs() { return mURLs.size() > 0; } /** * This function serves the purpose of communicating to the Hoko backend service that a given * inbound deeplink object was opened either through the notification id or through the * deeplink id. * * @param token The Hoko API Token. */ public void post(String token, Context context) { if (isSmartlink()) { Networking.getNetworking().addRequest( new HttpRequest(HttpRequest.HokoNetworkOperationType.POST, "smartlinks/open", token, smartlinkJSON(context).toString())); } } /** * Requests metadata for the Deeplink object from the HOKO server. * Will call the listener after the request is complete. * @param token The HOKO SDK token. * @param metadataRequestListener A listener to know when the task completes. */ public void requestMetadata(String token, final MetadataRequestListener metadataRequestListener) { if (needsMetadata()) { new NetworkAsyncTask(new HttpRequest(HttpRequest.HokoNetworkOperationType.GET, HttpRequest.getURLFromPath(METADATA_PATH), token, metadataJSON().toString()) .toRunnable(new HttpRequestCallback() { @Override public void onSuccess(JSONObject jsonObject) { Deeplink.this.mMetadata = jsonObject; if (metadataRequestListener != null) { metadataRequestListener.completion(); } } @Override public void onFailure(Exception e) { if (metadataRequestListener != null) { metadataRequestListener.completion(); } } })).execute(); } } public String getURL() { String url = this.getRoute(); if (this.getRouteParameters() != null) { for (String routeParameterKey : this.getRouteParameters().keySet()) { url = url.replace(":" + routeParameterKey, this.getRouteParameters() .get(routeParameterKey)); } } if (this.getRouteParameters() != null && this.getQueryParameters().size() > 0) { url = url + "?"; for (String queryParameterKey : this.getQueryParameters().keySet()) { url = url + queryParameterKey + "=" + this.getQueryParameters() .get(queryParameterKey) + "&"; } url = url.substring(0, url.length() - 1); } return url; } /** * Serves the purpose of returning a Deeplink in JSON form (useful for PhoneGap SDK) * * @return Deeplink in JSON form. */ public JSONObject toJSON() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("route", getRoute()); jsonObject.put("routeParameters", new JSONObject(mRouteParameters)); jsonObject.put("queryParameters", new JSONObject(mQueryParameters)); jsonObject.putOpt("metadata", getMetadata()); } catch (JSONException e) { HokoLog.e(e); } return jsonObject; } /** * Converts all the Deeplink information into a JSONObject to be sent to the Hoko backend * service. * * @return The JSONObject representation of Deeplink. */ public JSONObject json() { try { JSONObject root = new JSONObject(); root.putOpt("uri", getURL()); root.putOpt("metadata", getMetadata()); root.putOpt("unique", isUnique()); if (hasURLs()) root.putOpt("routes", new JSONObject(mURLs)); return root; } catch (JSONException e) { return null; } } /** * Converts the Deeplink into a JSONObject referring the Smartlink that was opened. * * @return The JSONObject representation of the Smartlink. */ private JSONObject smartlinkJSON(Context context) { JSONObject root = new JSONObject(); try { root.put("deeplink", mDeeplinkURL); root.put("uid", Device.getDeviceID(context)); } catch (JSONException e) { HokoLog.e(e); } return root; } private JSONObject metadataJSON() { try { if (getSmartlinkClickIdentifier() != null) { return new JSONObject().put(SMARTLINK_CLICK_IDENTIFIER_KEY, getSmartlinkClickIdentifier()); } else { return new JSONObject().put(SMARTLINK_IDENTIFIER_KEY, getSmartlinkIdentifier()); } } catch (JSONException e) { HokoLog.e(e); } return null; } public String toString() { String urlScheme = mURLScheme != null ? mURLScheme : ""; String route = mRoute != null ? mRoute : ""; String routeParameters = mRouteParameters != null ? mRouteParameters.toString() : ""; String queryParameters = mQueryParameters != null ? mQueryParameters.toString() : ""; String metadata = mMetadata != null ? mMetadata.toString() : ""; return "<Deeplink> URLScheme='" + urlScheme + "' route ='" + route + "' routeParameters='" + routeParameters + "' queryParameters='" + queryParameters + "' metadata='" + metadata + "'"; } public String getURLScheme() { return mURLScheme; } public HashMap<String, String> getRouteParameters() { return mRouteParameters; } public HashMap<String, String> getQueryParameters() { return mQueryParameters; } public JSONObject getMetadata() { return mMetadata; } public void setMetadata(JSONObject metadata) { mMetadata = metadata; } public String getRoute() { return mRoute; } private String getSmartlinkClickIdentifier() { return mQueryParameters.get(SMARTLINK_CLICK_IDENTIFIER_KEY); } private String getSmartlinkIdentifier() { return mQueryParameters.get(SMARTLINK_IDENTIFIER_KEY); } private boolean hasMetadataKey() { return mQueryParameters.containsKey(METADATA_KEY); } private boolean isSmartlink() { return getSmartlinkClickIdentifier() != null; } public boolean wasOpened() { return mWasOpened; } public void setWasOpened(boolean wasOpened) { mWasOpened = wasOpened; } public boolean isDeferred() { return mIsDeferred; } public boolean isUnique() { return mIsUnique; } }
package com.intersystems.iknow.languagemodel.slavic; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableSet; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * @author Andrey Shcheglov (mailto:andrey.shcheglov@intersystems.com) */ public final class MorphologicalAnalysisResult implements Serializable { private static final long serialVersionUID = 3598477807346909697L; @Nonnull private final String language; @Nonnull private final String stem; @Nullable private final PartOfSpeech partOfSpeech; @Nonnull private final Set<GrammaticalCategory> categories = new HashSet<>(); public MorphologicalAnalysisResult(@Nonnull final String language, @Nonnull final String stem) { this(language, stem, null); } /** * @param language lowercase 2 to 8 language code. * @param stem * @param partOfSpeech * @param categories */ public MorphologicalAnalysisResult(@Nonnull final String language, @Nonnull final String stem, @Nullable final PartOfSpeech partOfSpeech, @Nonnull final GrammaticalCategory ... categories) { this(language, stem, partOfSpeech, asList(categories)); } /** * @param language lowercase 2 to 8 language code. * @param stem * @param partOfSpeech * @param categories */ public MorphologicalAnalysisResult(@Nonnull final String language, @Nonnull final String stem, @Nullable final PartOfSpeech partOfSpeech, @Nonnull final Collection<GrammaticalCategory> categories) { if (language == null || language.length() == 0) { throw new IllegalArgumentException("Language is empty"); } if (stem == null || stem.length() == 0) { throw new IllegalArgumentException("Stem is empty"); } this.language = language; this.stem = stem; this.partOfSpeech = partOfSpeech; this.categories.addAll(categories); } public String getLanguage() { return this.language; } public String getStem() { return this.stem; } public PartOfSpeech getPartOfSpeech() { return this.partOfSpeech; } public Set<? extends GrammaticalCategory> getCategories() { return unmodifiableSet(this.categories); } /** * @see Object#toString() */ @Override public String toString() { return String.format("{:language %s :stem %s :partOfSpeech %s :categories %s}", this.language, this.stem, this.partOfSpeech, this.categories); } /** * @see Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.categories.hashCode(); result = prime * result + this.language.hashCode(); result = prime * result + (this.partOfSpeech == null ? 0 : this.partOfSpeech.hashCode()); result = prime * result + this.stem.hashCode(); return result; } /** * @see Object#equals(Object) */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof MorphologicalAnalysisResult) { final MorphologicalAnalysisResult that = (MorphologicalAnalysisResult) obj; return this.language.equals(that.language) && this.stem.equals(that.stem) && this.partOfSpeech == that.partOfSpeech && this.categories.equals(that.categories); } return false; } }
package de.pbauerochse.youtrack.connector.createreport.request; import de.pbauerochse.youtrack.util.FormattingUtil; import java.time.LocalDate; import java.time.ZoneId; import java.time.ZonedDateTime; /** * @author Patrick Bauerochse * @since 07.07.15 */ public class FixedReportRange implements CreateReportRange { private long from; private long to; private transient String name; public FixedReportRange() {} public FixedReportRange(LocalDate startDate, LocalDate endDate) { ZoneId defaultZone = ZoneId.systemDefault(); ZonedDateTime zonedStartDateTime = startDate.atStartOfDay(defaultZone); ZonedDateTime zonedEndDateTime = endDate.atStartOfDay(defaultZone); from = zonedStartDateTime.toInstant().toEpochMilli(); to = zonedEndDateTime.toInstant().toEpochMilli(); name = FormattingUtil.formatDate(startDate) + " - " + FormattingUtil.formatDate(endDate); } public long getFrom() { return from; } public void setFrom(long from) { this.from = from; } public long getTo() { return to; } public void setTo(long to) { this.to = to; } @Override public String toString() { return name; } }
package io.github.jevaengine.builder.animationbuilder.ui; import io.github.jevaengine.IDisposable; import io.github.jevaengine.builder.animationbuilder.ui.SelectSpriteAnimationQueryFactory.ISelectSpriteAnimationQueryObserver; import io.github.jevaengine.builder.animationbuilder.ui.SelectSpriteAnimationQueryFactory.SelectSpriteAnimationQuery; import io.github.jevaengine.builder.ui.FileInputQueryFactory; import io.github.jevaengine.builder.ui.FileInputQueryFactory.FileInputQuery; import io.github.jevaengine.builder.ui.FileInputQueryFactory.FileInputQueryMode; import io.github.jevaengine.builder.ui.FileInputQueryFactory.IFileInputQueryObserver; import io.github.jevaengine.builder.ui.MessageBoxFactory; import io.github.jevaengine.builder.ui.MessageBoxFactory.IMessageBoxObserver; import io.github.jevaengine.builder.ui.MessageBoxFactory.MessageBox; import io.github.jevaengine.graphics.ISpriteFactory; import io.github.jevaengine.graphics.ISpriteFactory.SpriteConstructionException; import io.github.jevaengine.graphics.Sprite; import io.github.jevaengine.math.Vector2D; import io.github.jevaengine.ui.Button; import io.github.jevaengine.ui.Button.IButtonPressObserver; import io.github.jevaengine.ui.IWindowFactory; import io.github.jevaengine.ui.IWindowFactory.WindowConstructionException; import io.github.jevaengine.ui.NoSuchControlException; import io.github.jevaengine.ui.Window; import io.github.jevaengine.ui.WindowBehaviourInjector; import io.github.jevaengine.ui.WindowManager; import java.net.URI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class FloatingToolbarFactory { private static final URI WINDOW_LAYOUT = URI.create("local:///ui/windows/toolbar.jwl"); private final WindowManager m_windowManager; private final IWindowFactory m_windowFactory; private final ISpriteFactory m_spriteFactory; private final URI m_baseDirectory; public FloatingToolbarFactory(WindowManager windowManager, IWindowFactory windowFactory, ISpriteFactory spriteFactory, URI baseDirectory) { m_windowManager = windowManager; m_windowFactory = windowFactory; m_spriteFactory = spriteFactory; m_baseDirectory = baseDirectory; } public FloatingToolbar create() throws WindowConstructionException { Window window = m_windowFactory.create(WINDOW_LAYOUT, new FloatingToolbarBehaviourInjector()); m_windowManager.addWindow(window); return new FloatingToolbar(window); } public static class FloatingToolbar implements IDisposable { private Window m_window; private FloatingToolbar(Window window) { m_window = window; } @Override public void dispose() { m_window.dispose(); } public void setVisible(boolean isVisible) { m_window.setVisible(isVisible); } public void setLocation(Vector2D location) { m_window.setLocation(location); } public void center() { m_window.center(); } } private class FloatingToolbarBehaviourInjector extends WindowBehaviourInjector { private Logger m_logger = LoggerFactory.getLogger(FloatingToolbarBehaviourInjector.class); private void displayMessage(String message) { try { final MessageBox msgBox = new MessageBoxFactory(m_windowManager, m_windowFactory).create(message); msgBox.getObservers().add(new IMessageBoxObserver() { @Override public void okay() { msgBox.dispose(); } }); } catch(WindowConstructionException e) { m_logger.error("Unable to construct message box", e); } } private void createSpritePreview(Sprite sprite) { try { final SelectSpriteAnimationQuery spritePreview = new SelectSpriteAnimationQueryFactory(m_windowManager, m_windowFactory).create(sprite); spritePreview.getObservers().add(new ISelectSpriteAnimationQueryObserver() { @Override public void okay(String animation) { spritePreview.dispose(); } @Override public void cancel() { spritePreview.dispose(); } }); } catch (WindowConstructionException e) { m_logger.error("Unable to construct sprite preview window", e); } } @Override protected void doInject() throws NoSuchControlException { getControl(Button.class, "btnPreviewSprite").getObservers().add(new IButtonPressObserver() { @Override public void onPress() { try { final FileInputQuery query = new FileInputQueryFactory(m_windowManager, m_windowFactory, m_baseDirectory).create(FileInputQueryMode.OpenFile, "Select a sprite file to preview:", m_baseDirectory); query.getObservers().add(new IFileInputQueryObserver() { @Override public void okay(URI file) { try { createSpritePreview(m_spriteFactory.create(file)); } catch (SpriteConstructionException e) { m_logger.error("Error occured constructing sprite.", e); displayMessage("Error constructing sprite. View stacktrace for more details."); } query.dispose(); } @Override public void cancel() { query.dispose(); } }); } catch(WindowConstructionException e) { m_logger.error("Unable to construct world selection dialogue", e); } } }); } } }
package org.mtransit.parser.us_everett_transit_bus; import static org.mtransit.commons.CleanUtils.SPACE; import static org.mtransit.commons.StringUtils.EMPTY; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mtransit.commons.CleanUtils; import org.mtransit.parser.ColorUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.mt.data.MAgency; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; public class EverettTransitBusAgencyTools extends DefaultAgencyTools { public static void main(@NotNull String[] args) { new EverettTransitBusAgencyTools().start(args); } @Nullable @Override public List<Locale> getSupportedLanguages() { return LANG_EN; } @Override public boolean defaultExcludeEnabled() { return true; } @NotNull public String getAgencyName() { return "Everett Transit"; } @NotNull @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_BUS; } @Override public boolean defaultRouteIdEnabled() { return true; } @Override public boolean useRouteShortNameForRouteId() { return true; } @Override public boolean defaultRouteLongNameEnabled() { return true; } @Override public boolean defaultAgencyColorEnabled() { return true; } private static final String AGENCY_COLOR_RED = "C92E36"; // RED (from web site CSS) private static final String AGENCY_COLOR = AGENCY_COLOR_RED; @NotNull @Override public String getAgencyColor() { return AGENCY_COLOR; } @Nullable @Override public String fixColor(@Nullable String color) { if (ColorUtils.BLACK.equalsIgnoreCase(color)) { return null; } return super.fixColor(color); } @Override public boolean directionFinderEnabled() { return true; } private static final Pattern ENDS_WITH_BAY_ = Pattern.compile("((^|\\W)(b:\\w+)(\\W|$))", Pattern.CASE_INSENSITIVE); private static final String ENDS_WITH_BAY_REPLACEMENT = "$2" + "$4"; private static final Pattern ENDS_WITH_D_ = Pattern.compile("((^|\\W)(d\\w+)(\\W|$))", Pattern.CASE_INSENSITIVE); private static final String ENDS_WITH_D_REPLACEMENT = "$2" + "$4"; private static final Pattern ENDS_WITH_I_ = Pattern.compile("((\\s*-\\s*)?(i\\d+)(?=(\\W|$)))", Pattern.CASE_INSENSITIVE); private static final String ENDS_WITH_I_REPLACEMENT = EMPTY; private static final Pattern ENDS_WITH_BOUNDS_ = Pattern.compile("((^|\\W)(nb|sb|eb|wb)(\\W|$))", Pattern.CASE_INSENSITIVE); private static final String ENDS_WITH_BOUNDS_REPLACEMENT = "$2" + "$4"; @NotNull @Override public String cleanDirectionHeadsign(boolean fromStopName, @NotNull String directionHeadSign) { directionHeadSign = super.cleanDirectionHeadsign(fromStopName, directionHeadSign); directionHeadSign = ENDS_WITH_BAY_.matcher(directionHeadSign).replaceAll(ENDS_WITH_BAY_REPLACEMENT); directionHeadSign = ENDS_WITH_D_.matcher(directionHeadSign).replaceAll(ENDS_WITH_D_REPLACEMENT); directionHeadSign = ENDS_WITH_I_.matcher(directionHeadSign).replaceAll(ENDS_WITH_I_REPLACEMENT); directionHeadSign = ENDS_WITH_BOUNDS_.matcher(directionHeadSign).replaceAll(ENDS_WITH_BOUNDS_REPLACEMENT); return CleanUtils.cleanLabel(directionHeadSign); } @NotNull @Override public String cleanTripHeadsign(@NotNull String tripHeadsign) { tripHeadsign = CleanUtils.cleanSlashes(tripHeadsign); tripHeadsign = CleanUtils.CLEAN_AT.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT); tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } private String[] getIgnoredWords() { return new String[]{ "SB", "NB", "WB", "EB", }; } private static final Pattern _DASH_ = Pattern.compile("( - )", Pattern.CASE_INSENSITIVE); @NotNull @Override public String cleanStopName(@NotNull String gStopName) { gStopName = _DASH_.matcher(gStopName).replaceAll(SPACE); gStopName = CleanUtils.toLowerCaseUpperCaseWords(getFirstLanguageNN(), gStopName, getIgnoredWords()); gStopName = CleanUtils.SAINT.matcher(gStopName).replaceAll(CleanUtils.SAINT_REPLACEMENT); gStopName = CleanUtils.CLEAN_AND.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT); gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); gStopName = CleanUtils.cleanSlashes(gStopName); gStopName = CleanUtils.cleanStreetTypes(gStopName); return CleanUtils.cleanLabel(gStopName); } @Override public int getStopId(@NotNull GStop gStop) { return Integer.parseInt(gStop.getStopCode()); // using stop code as stop ID } }
package com.opengamma.id; import java.io.Serializable; import javax.time.CalendricalException; import javax.time.Instant; import javax.time.InstantProvider; import javax.time.calendar.OffsetDateTime; import org.apache.commons.lang.ObjectUtils; import com.google.common.base.Objects; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.CompareUtils; import com.opengamma.util.PublicAPI; /** * An immutable version-correction combination. * <p> * History can be stored in two dimensions and the version-correction provides the key. * The first historic dimension is the classic series of versions. * Each new version is stored in such a manor that previous versions can be accessed. * The second historic dimension is corrections. * A correction occurs when it is realized that the original data stored was incorrect. * <p> * A fully versioned object in an OpenGamma installation will have a single state for * any combination of version and correction. This state is assigned a version string * which is used as the third component in a {@link UniqueId}, where all versions * share the same {@link ObjectId}. * <p> * This class represents a single version-correction combination suitable for identifying * a single state. It is typically used to obtain an object, while the version string is * used in the response. * <p> * This class is immutable and thread-safe. */ @PublicAPI public final class VersionCorrection implements Comparable<VersionCorrection>, Serializable { /** Serialization version. */ private static final long serialVersionUID = 1L; /** * Version-correction instance representing the latest version and correction. */ public static final VersionCorrection LATEST = new VersionCorrection(null, null); /** * The version instant. */ private final Instant _versionAsOf; /** * The correction instant. */ private final Instant _correctedTo; /** * Obtains a {@code VersionCorrection} from another version-correction, * defaulting the LATEST constant for null. * * @param versionCorrection the version-correction to check, null for latest * @return the version-correction combination, not null */ public static VersionCorrection of(VersionCorrection versionCorrection) { return Objects.firstNonNull(versionCorrection, VersionCorrection.LATEST); } /** * Obtains a {@code VersionCorrection} from a version and correction instant. * * @param versionAsOf the version as of instant, null for latest * @param correctedTo the corrected to instant, null for latest * @return the version-correction combination, not null */ public static VersionCorrection of(InstantProvider versionAsOf, InstantProvider correctedTo) { if (versionAsOf == null && correctedTo == null) { return LATEST; } Instant v = (versionAsOf != null ? Instant.of(versionAsOf) : null); Instant c = (correctedTo != null ? Instant.of(correctedTo) : null); return new VersionCorrection(v, c); } /** * Obtains a {@code VersionCorrection} from a version instant and the latest * correction. * * @param versionAsOf the version as of instant, null for latest * @return the version-correction combination, not null */ public static VersionCorrection ofVersionAsOf(InstantProvider versionAsOf) { return of(versionAsOf, null); } /** * Obtains a {@code VersionCorrection} from a correction instant and the latest * version. * * @param correctedTo the corrected to instant, null for latest * @return the version-correction combination, not null */ public static VersionCorrection ofCorrectedTo(InstantProvider correctedTo) { return of(null, correctedTo); } public static VersionCorrection parse(String str) { ArgumentChecker.notEmpty(str, "str"); int posC = str.indexOf(".C"); if (str.charAt(0) != 'V' || posC < 0) { throw new IllegalArgumentException("Invalid identifier format: " + str); } String verStr = str.substring(1, posC); String corrStr = str.substring(posC + 2); Instant versionAsOf = parseInstantString(verStr); Instant correctedTo = parseInstantString(corrStr); return of(versionAsOf, correctedTo); } public static VersionCorrection parse(String versionAsOfString, String correctedToString) { ArgumentChecker.notEmpty(versionAsOfString, "versionAsOfString"); ArgumentChecker.notEmpty(correctedToString, "correctedToString"); Instant versionAsOf = parseInstantString(versionAsOfString); Instant correctedTo = parseInstantString(correctedToString); return of(versionAsOf, correctedTo); } /** * Parses a version-correction {@code Instant} from a standard string representation. * <p> * The string representation must be either {@code LATEST} for null, or the ISO-8601 * representation of the desired {@code Instant}. * * @param instantStr the instant string, not null * @return the instant, not null */ private static Instant parseInstantString(String instantStr) { if (instantStr.equals("LATEST")) { return null; } else { try { return OffsetDateTime.parse(instantStr).toInstant(); // TODO: JSR-310 should be Instant.parse() } catch (CalendricalException ex) { throw new IllegalArgumentException(ex); } } } /** * Creates a version-correction combination. * * @param versionAsOf the version as of instant, null for latest * @param correctedTo the corrected to instant, null for latest */ private VersionCorrection(Instant versionAsOf, Instant correctedTo) { _versionAsOf = versionAsOf; _correctedTo = correctedTo; } /** * Gets the version as of instant. * <p> * This will locate the version that was active at this instant. * * @return the version as of instant, null for latest */ public Instant getVersionAsOf() { return _versionAsOf; } /** * Gets the corrected to instant. * <p> * This will locate the correction that was active at this instant. * * @return the corrected to instant, null for latest */ public Instant getCorrectedTo() { return _correctedTo; } /** * Returns a copy of this object with the specified version as of instant. * <p> * This instance is immutable and unaffected by this method call. * * @param versionAsOf the version instant, null for latest * @return a version-correction based on this one with the version as of instant altered, not null */ public VersionCorrection withVersionAsOf(InstantProvider versionAsOf) { Instant v = (versionAsOf != null ? Instant.of(versionAsOf) : null); if (ObjectUtils.equals(_versionAsOf, v)) { return this; } return new VersionCorrection(v, _correctedTo); } /** * Returns a copy of this object with the specified corrected to instant. * <p> * This instance is immutable and unaffected by this method call. * * @param correctedTo the corrected to instant, null for latest * @return a version-correction based on this one with the corrected to instant altered, not null */ public VersionCorrection withCorrectedTo(InstantProvider correctedTo) { Instant c = (correctedTo != null ? Instant.of(correctedTo) : null); if (ObjectUtils.equals(_correctedTo, c)) { return this; } return new VersionCorrection(_versionAsOf, c); } /** * Checks whether this object has either the version or correction instant * set to 'latest'. * * @return true if either instant is 'latest' */ public boolean containsLatest() { return (_versionAsOf == null || _correctedTo == null); } /** * Returns a copy of this object with any latest instant fixed to the specified instant. * <p> * This instance is immutable and unaffected by this method call. * * @param now the current instant, not null * @return a version-correction based on this one with the correction altered, not null */ public VersionCorrection withLatestFixed(Instant now) { ArgumentChecker.notNull(now, "Now must not be null"); if (containsLatest()) { return new VersionCorrection(Objects.firstNonNull(_versionAsOf, now), Objects.firstNonNull(_correctedTo, now)); } return this; } /** * Gets a string representation of the version as of instant. * <p> * This is either the ISO-8601 representation of the version as of instant, such as * {@code 2011-02-01T12:30:40Z}, or {@code LATEST} for null. * * @return the string version as of, not null */ public String getVersionAsOfString() { return ObjectUtils.defaultIfNull(_versionAsOf, "LATEST").toString(); } /** * Gets a string representation of the corrected to instant. * <p> * This is either the ISO-8601 representation of the corrected to instant, such as * {@code 2011-02-01T12:30:40Z}, or {@code LATEST} for null. * * @return the string corrected to, not null */ public String getCorrectedToString() { return ObjectUtils.defaultIfNull(_correctedTo, "LATEST").toString(); } /** * Compares the version-corrections, sorting by version followed by correction. * * @param other the other identifier, not null * @return negative if this is less, zero if equal, positive if greater */ @Override public int compareTo(VersionCorrection other) { int cmp = CompareUtils.compareWithNullHigh(_versionAsOf, other._versionAsOf); if (cmp != 0) { return cmp; } return CompareUtils.compareWithNullHigh(_correctedTo, other._correctedTo); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof VersionCorrection) { VersionCorrection other = (VersionCorrection) obj; return Objects.equal(_versionAsOf, other._versionAsOf) && Objects.equal(_correctedTo, other._correctedTo); } return false; } @Override public int hashCode() { return Objects.hashCode(_versionAsOf, _correctedTo); } /** * Returns the version-correction instants. * <p> * This is a standard format that can be parsed. * It consists of 'V' followed by the version, a dot, then 'C' followed by the correction, * such as {@code V2011-02-01T12:30:40Z.C2011-02-01T12:30:40Z}. * The text 'LATEST' is used in place of the instant for a latest version or correction. * * @return the string version-correction, not null */ @Override public String toString() { return "V" + getVersionAsOfString() + ".C" + getCorrectedToString(); } }
package org.pentaho.agilebi.spoon.visualizations.analyzer; import mondrian.rolap.agg.AggregationManager; import org.pentaho.agilebi.modeler.util.ISpoonModelerSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.eclipse.swt.SWTError; import org.eclipse.swt.widgets.Composite; import org.pentaho.agilebi.modeler.ModelerException; import org.pentaho.agilebi.modeler.ModelerWorkspace; import org.pentaho.agilebi.spoon.ModelerHelper; import org.pentaho.agilebi.spoon.perspective.AgileBiModelerPerspective; import org.pentaho.agilebi.spoon.publish.PublisherHelper; import org.pentaho.agilebi.spoon.visualizations.AbstractVisualization; import org.pentaho.agilebi.spoon.visualizations.IVisualization; import org.pentaho.agilebi.spoon.visualizations.PropertyPanelController; import org.pentaho.di.core.EngineMetaInterface; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.gui.SpoonFactory; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.ui.spoon.FileListener; import org.pentaho.di.ui.spoon.Spoon; import org.pentaho.metadata.model.Domain; import org.pentaho.metadata.model.IPhysicalModel; import org.pentaho.metadata.model.IPhysicalTable; import org.pentaho.platform.api.repository.ISolutionRepository; import org.pentaho.ui.xul.XulException; import org.pentaho.ui.xul.binding.Binding; import org.pentaho.ui.xul.binding.Binding.Type; import org.pentaho.ui.xul.binding.BindingFactory; import org.pentaho.ui.xul.binding.DefaultBindingFactory; import org.pentaho.ui.xul.components.XulBrowser; import org.pentaho.ui.xul.components.XulMessageBox; import org.pentaho.ui.xul.containers.XulEditpanel; import org.pentaho.ui.xul.impl.AbstractXulEventHandler; import org.w3c.dom.Node; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import java.util.Locale; public class AnalyzerVisualizationController extends AbstractXulEventHandler implements FileListener, PropertyPanelController { public static final String XUL_FILE_ANALYZER_TOOLBAR_PROPERTIES = "plugins/spoon/agile-bi/ui/analyzer-toolbar.properties"; //$NON-NLS-1$ private String xmiFileLocation = null; private String modelId = null; private AnalyzerVisualization visualization; private AnalyzerVisualizationMeta meta; private String visFileLocation = null; private XulBrowser browser; private Spoon spoon; private String location; private BindingFactory bf; private Binding modelNameBinding; private Binding factTableNameBinding; private String factTableName; private XulEditpanel propPanel; private ModelerWorkspace workspace; private boolean dirty = true; private static Logger logger = LoggerFactory.getLogger(AnalyzerVisualizationController.class); private String fileName; public AnalyzerVisualizationController(Composite parent, final AnalyzerVisualization visualization, String xmiFileLocation, String modelId, String aVisFileLocaiton, String fileName) throws SWTError { this.visualization = visualization; this.xmiFileLocation = xmiFileLocation; this.modelId = modelId; this.visFileLocation = aVisFileLocaiton; this.meta = new AnalyzerVisualizationMeta(this); this.spoon = ((Spoon) SpoonFactory.getInstance()); this.location = visualization.generateNewUrl(xmiFileLocation, modelId); this.bf = new DefaultBindingFactory(); this.fileName = fileName; } public void init() { this.browser = (XulBrowser) this.document.getElementById("web_visualization_browser"); this.propPanel = (XulEditpanel) document.getElementById("propPanel"); this.browser.setSrc(this.location); this.bf.setDocument(super.document); this.bf.setBindingType(Type.ONE_WAY); this.modelNameBinding = this.bf.createBinding(this, "modelId", "modelName", "value"); this.factTableNameBinding = this.bf.createBinding(this, "factTableName", "factTableName", "value"); this.bf.setBindingType(Type.BI_DIRECTIONAL); bf.createBinding(this.propPanel, "visible", this, "propVisible"); fireBindings(); } public void openReport(String aReport) { String theLocation = this.location.substring(0, this.location.indexOf("?")); try { aReport = URLEncoder.encode(aReport, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } theLocation = theLocation + "?command=open&solution=&path=&action=" + aReport + "&edit=true&showFieldList=true"; this.browser.setSrc(theLocation); } private String processFactTableName() { String theName = null; Domain theDomain = ModelerHelper.getInstance().loadDomain(this.xmiFileLocation); List<IPhysicalModel> theModels = theDomain.getPhysicalModels(); if (theModels != null && theModels.size() > 0) { IPhysicalModel theModel = theModels.get(0); List theTables = theModel.getPhysicalTables(); if (theTables != null && theTables.size() > 0) { IPhysicalTable theTable = (IPhysicalTable) theTables.get(0); theName = theTable.getName(Locale.getDefault().toString()); } } return theName; } private void fireBindings() { try { this.modelNameBinding.fireSourceChanged(); this.factTableNameBinding.fireSourceChanged(); } catch (Exception e) { logger.info("Error firing bindings", e); } } public String getFactTableName() { if (this.factTableName == null) { this.factTableName = processFactTableName(); } return this.factTableName; } public void setFactTableName(String aFactTableName) { this.factTableName = aFactTableName; } public AnalyzerVisualization getVisualization() { return visualization; } public String getVisFileLocation() { return visFileLocation; } public void save(String filename) { visFileLocation = filename; browser.execute(visualization.generateSaveJavascript(filename)); } public void save() { try { spoon.saveToFile(meta); setDirty(false); } catch (KettleException e) { logger.error("error saving", e); showErrorDialog(BaseMessages.getString(IVisualization.class,"error_saving")); } } public void saveAs() { try{ spoon.saveFileAs(meta); setDirty(false); } catch (KettleException e) { logger.error("error saving", e); showErrorDialog(BaseMessages.getString(IVisualization.class,"error_saving")); } } private void showErrorDialog(String msg){ XulMessageBox dlg; try { dlg = (XulMessageBox) document.createElement("messagebox"); dlg.setTitle(BaseMessages.getString(IVisualization.class,"error_title")); dlg.setMessage(msg); dlg.open(); } catch (XulException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void editModel() { AgileBiModelerPerspective.getInstance().open(null, xmiFileLocation, false); } public void refreshData() { // first clear the server cache AggregationManager.instance().getCacheControl(null).flushSchemaCache(); browser.execute(visualization.generateRefreshDataJavascript(xmiFileLocation, modelId)); } public void refreshModel() { // first save the view // if (true) throw new UnsupportedOperationException(); // TODO: can we do this without requiring a "remote save"? AggregationManager.instance().getCacheControl(null).flushSchemaCache(); browser.execute(visualization.generateRefreshModelJavascript(xmiFileLocation, modelId)); // "gCtrlr.repositoryBrowserController.remoteSave('"+modelId+"','tmp', '', 'xanalyzer', true)" } public String getModelId() { return modelId; } public void setModelId(String modelId) { this.modelId = modelId; } public AnalyzerVisualizationMeta getMeta() { return meta; } public boolean canHandleSave() { return true; } public boolean setFocus() { return true; } public boolean open(Node arg0, String arg1, boolean arg2) { // TODO Auto-generated method stub return false; } public boolean save(EngineMetaInterface arg0, String arg1, boolean arg2) { // TODO Auto-generated method stub return false; } public void syncMetaName(EngineMetaInterface arg0, String arg1) { // TODO Auto-generated method stub } public void setXmiFileLocation(String xmiFileLocation) { this.xmiFileLocation = xmiFileLocation; } public void setVisFileLocation(String visFileLocation) { this.visFileLocation = visFileLocation; } // FileListener methods public boolean accepts(String fileName) { if (fileName == null || fileName.indexOf('.') == -1) { return false; } String extension = fileName.substring(fileName.lastIndexOf('.') + 1); return extension.equals("xanalyzer"); } public boolean acceptsXml(String nodeName) { return nodeName.equals("reportRecord"); } public String[] getFileTypeDisplayNames(Locale locale) { return new String[] { "Models" }; } public String getRootNodeName() { return null; } public String[] getSupportedExtensions() { return new String[] { "xmi" }; } public String getName() { return "analyzerVis"; } public String getFileName(){ return fileName; } public String getFileLocation() { return this.xmiFileLocation; } private boolean showFields = true; private boolean showFilters = false; private boolean showFieldLayout = false; public void toggleFieldList(){ showFields = !showFields; browser.execute("window.cv.rptEditor._toggleReportPane(window.cv.rptEditor.fieldList, "+showFields+", false, true)"); } public void toggleFilters(){ showFilters = !showFilters; browser.execute("window.cv.rptEditor._toggleReportPane(window.cv.rptEditor.report.nodeFilter,"+showFilters+",true,true)"); } public void toggleFieldLayout(){ showFieldLayout = !showFieldLayout; browser.execute("window.cv.rptEditor._toggleReportPane(window.cv.rptEditor.report.nodeLayout,"+showFieldLayout+",true,true)"); } public void undo(){ browser.execute("window.cv.rptEditor.report.history.undo()"); } public void redo(){ browser.execute("window.cv.rptEditor.report.history.redo()"); } public void reset(){ browser.execute("window.cv.rptEditor.report.onReset()"); } public void getReportPDF(){ browser.execute("window.cv.io.getReportInFormat(window.cv.rptEditor.report.getReportXml(), \"PDF\", null, null, window.cv.rptEditor.report.isDirty())"); } public void showReportOptions(){ browser.execute("window.cv.rptEditor.report.rptDlg.showReportOptions()"); } public void togglePropertiesPanel(){ setPropVisible(! isPropVisible()); } private boolean propVisible = true; public boolean isPropVisible(){ return propVisible; } public void setPropVisible(boolean vis){ boolean prevVal = propVisible; this.propVisible = vis; this.firePropertyChange("propVisible", prevVal, vis); } public void publish() throws ModelerException{ if(isDirty()){ XulMessageBox msg; try { msg = (XulMessageBox) document.createElement("messagebox"); msg.setTitle(BaseMessages.getString(AbstractVisualization.class, "Publish.UnsavedChangesWarning.Title")); msg.setMessage(BaseMessages.getString(AbstractVisualization.class, "Publish.UnsavedChangesWarning.Message")); msg.open(); } catch (XulException e) { throw new ModelerException(e); } return; } EngineMetaInterface engineMeta = spoon.getActiveMeta(); String publishingFile = engineMeta.getFilename(); int treeDepth = 100; DatabaseMeta databaseMeta = ((ISpoonModelerSource)workspace.getModelSource()).getDatabaseMeta(); boolean checkDatasources = true; boolean showServerSelection = true; boolean showFolders = true; boolean showCurrentFolder = true; String serverPathTemplate = "{path}" + ISolutionRepository.SEPARATOR + //$NON-NLS-1$ "resources" + ISolutionRepository.SEPARATOR + "metadata"; //$NON-NLS-1$ //$NON-NLS-2$ String databaseName = PublisherHelper.getBiServerCompatibleDatabaseName(workspace.getDatabaseName()); String extension = ".xanalyzer"; //$NON-NLS-1$ String filename = new File(publishingFile).getName(); String newName = PublisherHelper.publishAnalysis(workspace, filename, treeDepth, databaseMeta, publishingFile, checkDatasources, true, showFolders, showCurrentFolder, serverPathTemplate, extension, databaseName); this.setName(newName ); } public void setModel(ModelerWorkspace aWorkspace) { this.workspace = aWorkspace; } public ModelerWorkspace getModel() { return this.workspace; } public boolean isDirty() { return dirty; } public void setDirty(boolean dirty) { this.dirty = dirty; } }
package com.opengamma.util; import java.io.Closeable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.springframework.beans.factory.DisposableBean; import org.springframework.util.ClassUtils; import com.opengamma.OpenGammaRuntimeException; /** * Utility to provide reflection helpers. * <p> * This is a thread-safe static utility class. */ public final class ReflectionUtils { /** * Restricted constructor. */ private ReflectionUtils() { } /** * Loads a Class from a full class name. * <p> * This uses Spring's {@link ClassUtils#forName(String, ClassLoader)} passing null * for the class loader. * * @param <T> the auto-cast class * @param className the class name, not null * @return the class, not null * @throws RuntimeException if the class cannot be loaded */ @SuppressWarnings("unchecked") public static <T> Class<T> loadClass(final String className) { try { return (Class<T>) ClassUtils.forName(className, null); } catch (ClassNotFoundException ex) { throw new OpenGammaRuntimeException(ex.getMessage(), ex); } } /** * Loads a Class from a full class name with a fallback class loader. * <p> * This uses Spring's {@link ClassUtils#forName(String, ClassLoader)} passing null * for the class loader. If that fails, it calls the same method with the class loader * * @param <T> the auto-cast class * @param className the class name, not null * @param fallbackClassLoader a suitable class loader, may be null * @return the class, not null * @throws RuntimeException if the class cannot be loaded */ @SuppressWarnings("unchecked") public static <T> Class<T> loadClassWithFallbackLoader(final String className, final ClassLoader fallbackClassLoader) { try { return (Class<T>) ClassUtils.forName(className, null); } catch (ClassNotFoundException ex) { try { return (Class<T>) ClassUtils.forName(className, fallbackClassLoader); } catch (ClassNotFoundException ex2) { throw new OpenGammaRuntimeException(ex.getMessage(), ex2); } } } /** * Finds a constructor from a Class. * * @param <T> the type * @param type the type to create, not null * @param arguments the arguments, not null * @return the constructor, not null * @throws RuntimeException if the class cannot be loaded */ @SuppressWarnings("unchecked") public static <T> Constructor<T> findConstructorByArguments(final Class<T> type, final Object... arguments) { Class<?>[] paramTypes = new Class<?>[arguments.length]; for (int i = 0; i < arguments.length; i++) { paramTypes[i] = (arguments[i] != null ? arguments[i].getClass() : null); } List<Constructor<?>> constructors = Arrays.asList(type.getConstructors()); for (Iterator<Constructor<?>> it = constructors.iterator(); it.hasNext(); ) { Constructor<?> constructor = (Constructor<?>) it.next(); if (org.apache.commons.lang.ClassUtils.isAssignable(paramTypes, constructor.getParameterTypes()) == false) { it.remove(); } } if (constructors.size() != 1) { throw new OpenGammaRuntimeException("Unable to match single constructor: " + type); } return (Constructor<T>) constructors.get(0); } /** * Finds a constructor from a Class. * * @param <T> the type * @param type the type to create, not null * @param paramTypes the parameter types, not null * @return the constructor, not null * @throws RuntimeException if the class cannot be loaded */ public static <T> Constructor<T> findConstructor(final Class<T> type, final Class<?>... paramTypes) { try { return type.getConstructor(paramTypes); } catch (NoSuchMethodException ex) { throw new OpenGammaRuntimeException(ex.getMessage(), ex); } } /** * Creates an instance of a class from a constructor. * * @param <T> the type * @param constructor the constructor to call, not null * @param args the arguments, not null * @return the constructor, not null * @throws RuntimeException if the class cannot be loaded */ public static <T> T newInstance(final Constructor<T> constructor, final Object... args) { try { return constructor.newInstance(args); } catch (InstantiationException ex) { throw new OpenGammaRuntimeException(ex.getMessage(), ex); } catch (IllegalAccessException ex) { throw new OpenGammaRuntimeException(ex.getMessage(), ex); } catch (InvocationTargetException ex) { if (ex.getCause() instanceof RuntimeException) { throw (RuntimeException) ex.getCause(); } throw new OpenGammaRuntimeException(ex.getMessage(), ex); } } /** * Checks if the class is closeable. * <p> * This invokes the close method if it is present. * * @param type the type, not null * @return true if closeable */ public static boolean isCloseable(final Class<?> type) { if (Closeable.class.isAssignableFrom(type)) { return true; } else if (DisposableBean.class.isAssignableFrom(type)) { return true; } try { if (Modifier.isPublic(type.getMethod("close").getModifiers())) { return true; } } catch (Exception ex) { try { if (Modifier.isPublic(type.getMethod("stop").getModifiers())) { return true; } } catch (Exception ex2) { try { if (Modifier.isPublic(type.getMethod("shutdown").getModifiers())) { return true; } } catch (Exception ex3) { // ignored } } } return false; } /** * Tries to "close" an object. * <p> * This invokes the close method if it is present. * * @param obj the object, null ignored */ public static void close(final Object obj) { if (obj != null) { try { if (obj instanceof Closeable) { ((Closeable) obj).close(); } else if (obj instanceof DisposableBean) { ((DisposableBean) obj).destroy(); } else { invokeNoArgsNoException(obj, "close"); invokeNoArgsNoException(obj, "stop"); invokeNoArgsNoException(obj, "shutdown"); } } catch (Exception ex) { // ignored } } } /** * Invokes a no-args method on an object, throwing no errors. * * @param obj the object, null ignored * @param methodName the method name, not null */ public static void invokeNoArgsNoException(final Object obj, final String methodName) { if (obj != null) { try { obj.getClass().getMethod(methodName).invoke(obj); } catch (Exception ex2) { // ignored } } } }
// $Id: Config.java,v 1.20 2003/01/15 00:45:22 mdb Exp $ // samskivert library - useful routines for java programs // 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.util; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Properties; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import com.samskivert.Log; /** * The config class provides a unified interaface to application * configuration information. It takes care of loading properties files * (done via the classpath) and allows for overriding and inheriting of * properties values (see {@link ConfigUtil#loadInheritedProperties}). * * <p> A common pattern is to create, for each package that shares * configuration information, a singleton class containing a config object * that is configured to load its data from a single configuration * file. For example: * * <pre> * public class FooConfig * { * public static final String FIDDLES = "fiddles"; * * public static Config config = new Config("com/fribitz/foo"); * } * </pre> * * which would look for <code>com/fribitz/foo.properties</code> in the * classpath and serve up those configuration values when requests were * made from <code>FooConfig.config</code>. For example: * * <pre> * int fiddles = FooConfig.config.getValue(FooConfig.FIDDLES, 0); * for (int ii = 0; ii < fiddles; ii++) { * fiddle(); * } * </pre> * * An even better approach involves creating accessors for all defined * configuration properties: * * <pre> * public class FooConfig * { * public static final String FIDDLES = "fiddles"; * * public static Config config = new Config("com/fribitz/foo"); * * public static int getFiddles () * { * return config.getValue(FIDDLES, FIDDLES_DEFAULT); * } * * protected static final int FIDDLES_DEFAULT = 0; * } * </pre> * * This allows the default value for <code>fiddles</code> to be specified * in one place and simplifies life for the caller who can now simply * request <code>FooConfig.getFiddles()</code>. * * <p> The config class allows one to override configuration values * persistently, using the standard Java {@link Preferences} facilities to * maintain the overridden values. If a property is {@link #setValue}d in * a configuration object, it will remain overridden in between * invocations of the application (leveraging the benefits of the * pluggable preferences backends provided by the standard Java * preferences facilities). */ public class Config { /** * Constructs a new config object which will obtain configuration * information from the specified properties bundle. */ public Config (String path) { // first load up our default prefs _props = new Properties(); try { // append the file suffix onto the path String ppath = path + PROPS_SUFFIX; // load the properties file ConfigUtil.loadInheritedProperties(ppath, _props); } catch (FileNotFoundException fnfe) { Log.debug("No properties file found to back config " + "[path=" + path + "]."); } catch (IOException ioe) { Log.warning("Unable to load configuration [path=" + path + ", ioe=" + ioe + "]."); } // get a handle on the preferences instance that we'll use to // override values in the properties file _prefs = Preferences.userRoot().node(path); } /** * Fetches and returns the value for the specified configuration * property. If the value is not specified in the associated * properties file, the supplied default value is returned instead. If * the property specified in the file is poorly formatted (not and * integer, not in proper array specification), a warning message will * be logged and the default value will be returned. * * @param name name of the property. * @param defval the value to return if the property is not specified * in the config file. * * @return the value of the requested property. */ public int getValue (String name, int defval) { return _prefs.getInt(name, getDefValue(name, defval)); } /** * Returns the value specified in the properties override file. */ protected int getDefValue (String name, int defval) { String val = _props.getProperty(name); if (val != null) { try { defval = Integer.parseInt(val); } catch (NumberFormatException nfe) { Log.warning("Malformed integer property [name=" + name + ", value=" + val + "]."); } } return defval; } /** * Sets the value of the specified preference, overriding the value * defined in the configuration files shipped with the application. */ public void setValue (String name, int value) { Integer oldValue = null; if (_prefs.get(name, null) != null || _props.getProperty(name) != null) { oldValue = new Integer(_prefs.getInt(name, getDefValue(name, 0))); } _prefs.putInt(name, value); _propsup.firePropertyChange(name, oldValue, new Integer(value)); } /** * Fetches and returns the value for the specified configuration * property. If the value is not specified in the associated * properties file, the supplied default value is returned instead. If * the property specified in the file is poorly formatted (not and * integer, not in proper array specification), a warning message will * be logged and the default value will be returned. * * @param name name of the property. * @param defval the value to return if the property is not specified * in the config file. * * @return the value of the requested property. */ public long getValue (String name, long defval) { return _prefs.getLong(name, getDefValue(name, defval)); } /** * Returns the value specified in the properties override file. */ protected long getDefValue (String name, long defval) { String val = _props.getProperty(name); if (val != null) { try { defval = Long.parseLong(val); } catch (NumberFormatException nfe) { Log.warning("Malformed long integer property [name=" + name + ", value=" + val + "]."); } } return defval; } /** * Sets the value of the specified preference, overriding the value * defined in the configuration files shipped with the application. */ public void setValue (String name, long value) { Long oldValue = null; if (_prefs.get(name, null) != null || _props.getProperty(name) != null) { oldValue = new Long(_prefs.getLong(name, getDefValue(name, 0L))); } _prefs.putLong(name, value); _propsup.firePropertyChange(name, oldValue, new Long(value)); } /** * Fetches and returns the value for the specified configuration * property. If the value is not specified in the associated * properties file, the supplied default value is returned instead. If * the property specified in the file is poorly formatted (not and * integer, not in proper array specification), a warning message will * be logged and the default value will be returned. * * @param name name of the property. * @param defval the value to return if the property is not specified * in the config file. * * @return the value of the requested property. */ public float getValue (String name, float defval) { return _prefs.getFloat(name, getDefValue(name, defval)); } /** * Returns the value specified in the properties override file. */ protected float getDefValue (String name, float defval) { String val = _props.getProperty(name); if (val != null) { try { defval = Float.parseFloat(val); } catch (NumberFormatException nfe) { Log.warning("Malformed float property [name=" + name + ", value=" + val + "]."); } } return defval; } /** * Sets the value of the specified preference, overriding the value * defined in the configuration files shipped with the application. */ public void setValue (String name, float value) { Float oldValue = null; if (_prefs.get(name, null) != null || _props.getProperty(name) != null) { oldValue = new Float(_prefs.getFloat(name, getDefValue(name, 0f))); } _prefs.putFloat(name, value); _propsup.firePropertyChange(name, oldValue, new Float(value)); } /** * Fetches and returns the value for the specified configuration * property. If the value is not specified in the associated * properties file, the supplied default value is returned instead. * * @param name the name of the property to be fetched. * @param defval the value to return if the property is not specified * in the config file. * * @return the value of the requested property. */ public String getValue (String name, String defval) { // if there is a value, parse it into an integer String val = _props.getProperty(name); if (val != null) { defval = val; } // finally look for an overridden value return _prefs.get(name, defval); } /** * Sets the value of the specified preference, overriding the value * defined in the configuration files shipped with the application. */ public void setValue (String name, String value) { String oldValue = getValue(name, (String)null); _prefs.put(name, value); _propsup.firePropertyChange(name, oldValue, value); } /** * Fetches and returns the value for the specified configuration * property. If the value is not specified in the associated * properties file, the supplied default value is returned * instead. The returned value will be <code>false</code> if the * config value is <code>"false"</code> (case-insensitive), else * the return value will be true. * * @param name the name of the property to be fetched. * @param defval the value to return if the property is not specified * in the config file. * * @return the value of the requested property. */ public boolean getValue (String name, boolean defval) { return _prefs.getBoolean(name, getDefValue(name, defval)); } /** * Returns the value specified in the properties override file. */ protected boolean getDefValue (String name, boolean defval) { String val = _props.getProperty(name); if (val != null) { defval = !val.equalsIgnoreCase("false"); } return defval; } /** * Sets the value of the specified preference, overriding the value * defined in the configuration files shipped with the application. */ public void setValue (String name, boolean value) { Boolean oldValue = null; if (_prefs.get(name, null) != null || _props.getProperty(name) != null) { oldValue = new Boolean( _prefs.getBoolean(name, getDefValue(name, false))); } _prefs.putBoolean(name, value); _propsup.firePropertyChange(name, oldValue, new Boolean(value)); } /** * Fetches and returns the value for the specified configuration * property. If the value is not specified in the associated * properties file, the supplied default value is returned instead. If * the property specified in the file is poorly formatted (not and * integer, not in proper array specification), a warning message will * be logged and the default value will be returned. * * @param name the name of the property to be fetched. * @param defval the value to return if the property is not specified * in the config file. * * @return the value of the requested property. */ public int[] getValue (String name, int[] defval) { // look up the value in the configuration file and use that to // look up any overridden value String val = _prefs.get(name, _props.getProperty(name)); int[] result = defval; // parse it into an array of ints if (val != null) { result = StringUtil.parseIntArray(val); if (result == null) { Log.warning("Malformed int array property [name=" + name + ", value=" + val + "]."); return defval; } } return result; } /** * Sets the value of the specified preference, overriding the value * defined in the configuration files shipped with the application. */ public void setValue (String name, int[] value) { int[] oldValue = getValue(name, (int[])null); _prefs.put(name, StringUtil.toString(value, "", "")); _propsup.firePropertyChange(name, oldValue, value); } /** * Fetches and returns the value for the specified configuration * property. If the value is not specified in the associated * properties file, the supplied default value is returned instead. If * the property specified in the file is poorly formatted (not and * integer, not in proper array specification), a warning message will * be logged and the default value will be returned. * * @param name the name of the property to be fetched. * @param defval the value to return if the property is not specified * in the config file. * * @return the value of the requested property. */ public String[] getValue (String name, String[] defval) { // look up the value in the configuration file and use that to // look up any overridden value String val = _prefs.get(name, _props.getProperty(name)); String[] result = defval; // parse it into an array of ints if (val != null) { result = StringUtil.parseStringArray(val); if (result == null) { Log.warning("Malformed string array property [name=" + name + ", value=" + val + "]."); return defval; } } return result; } /** * Sets the value of the specified preference, overriding the value * defined in the configuration files shipped with the application. */ public void setValue (String name, String[] value) { String[] oldValue = getValue(name, (String[])null); _prefs.put(name, StringUtil.joinEscaped(value)); _propsup.firePropertyChange(name, oldValue, value); } /** * Adds a listener that will be notified whenever any configuration * properties are changed by a call to one of the <code>set</code> * methods. */ public void addPropertyChangeListener (PropertyChangeListener listener) { _propsup.addPropertyChangeListener(listener); } /** * Removes a property change listener previously added via a call to * {@link #addPropertyChangeListener}. */ public void removePropertyChangeListener (PropertyChangeListener listener) { _propsup.removePropertyChangeListener(listener); } /** * Adds a listener that will be notified whenever the specified * configuration property is changed by a call to the appropriate * <code>set</code> method. */ public void addPropertyChangeListener ( String name, PropertyChangeListener listener) { _propsup.addPropertyChangeListener(name, listener); } /** * Removes a property change listener previously added via a call to * {@link #addPropertyChangeListener(String,PropertyChangeListener)}. */ public void removePropertyChangeListener ( String name, PropertyChangeListener listener) { _propsup.removePropertyChangeListener(name, listener); } /** * Looks up the specified string-valued configuration entry, loads the * class with that name and instantiates a new instance of that class, * which is returned. * * @param name the name of the property to be fetched. * @param defcname the class name to use if the property is not * specified in the config file. * * @exception Exception thrown if any error occurs while loading or * instantiating the class. */ public Object instantiateValue (String name, String defcname) throws Exception { return Class.forName(getValue(name, defcname)).newInstance(); } /** * Returns a properties object containing all configuration values * that start with the supplied prefix (plus a trailing "." which will * be added if it doesn't already exist). The keys in the * sub-properties will have had the prefix stripped off. */ public Properties getSubProperties (String prefix) { Properties props = new Properties(); getSubProperties(prefix, props); return props; } /** * Fills into the supplied properties object all configuration values * that start with the supplied prefix (plus a trailing "." which will * be added if it doesn't already exist). The keys in the * sub-properties will have had the prefix stripped off. */ public void getSubProperties (String prefix, Properties target) { // slap a trailing dot on if necessary if (!prefix.endsWith(".")) { prefix = prefix + "."; } // build the sub-properties Iterator iter = keys(); while (iter.hasNext()) { String key = (String)iter.next(); if (!key.startsWith(prefix)) { continue; } String value = getValue(key, (String)null); if (value == null) { continue; } target.put(key.substring(prefix.length()), value); } } /** * Returns an iterator that returns all of the configuration keys in * this config object. */ public Iterator keys () { // what with all the complicated business, we just need to take // the brute force approach and enumerate everything up front HashSet matches = new HashSet(); // add the keys provided in the config files Enumeration defkeys = _props.propertyNames(); while (defkeys.hasMoreElements()) { matches.add(defkeys.nextElement()); } // then add the overridden keys try { String[] keys = _prefs.keys(); for (int i = 0; i < keys.length; i++) { matches.add(keys[i]); } } catch (BackingStoreException bse) { Log.warning("Unable to enumerate preferences keys " + "[error=" + bse + "]."); } return matches.iterator(); } /** Contains the default configuration information. */ protected Properties _props; /** Used to maintain configuration overrides. */ protected Preferences _prefs; /** Used to support our property change mechanism. */ protected PropertyChangeSupport _propsup = new PropertyChangeSupport(this); /** The file extension used for configuration files. */ protected static final String PROPS_SUFFIX = ".properties"; }
package ucar.nc2.write; import static com.google.common.truth.Truth.assertThat; import org.junit.*; import org.junit.rules.TemporaryFolder; import org.junit.runners.MethodSorters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ucar.ma2.*; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.List; import ucar.nc2.Attribute; import ucar.nc2.Dimension; import ucar.nc2.NetcdfFile; import ucar.nc2.NetcdfFiles; import ucar.nc2.Variable; import ucar.nc2.constants.CDM; /** Test NetcdfFormatWriter */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestWrite { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @ClassRule public static TemporaryFolder tempFolder = new TemporaryFolder(); private static String writerLocation; @BeforeClass public static void setupClass() throws IOException { writerLocation = tempFolder.newFile().getAbsolutePath(); NetcdfFormatWriter.Builder writerb = NetcdfFormatWriter.createNewNetcdf3(writerLocation); // add dimensions Dimension latDim = writerb.addDimension("lat", 64); Dimension lonDim = writerb.addDimension("lon", 128); // add Variable double temperature(lat,lon) List<Dimension> dims = new ArrayList<>(); dims.add(latDim); dims.add(lonDim); writerb.addVariable("temperature", DataType.DOUBLE, dims).addAttribute(new Attribute("units", "K")) // add a 1D // attribute of // length 3 .addAttribute(new Attribute("scale", Array.factory(DataType.INT, new int[] {3}, new int[] {1, 2, 3}))); // add a string-valued variable: char svar(80) Dimension svar_len = writerb.addDimension("svar_len", 80); writerb.addVariable("svar", DataType.CHAR, "svar_len"); writerb.addVariable("svar2", DataType.CHAR, "svar_len"); // add a 2D string-valued variable: char names(names, 80) Dimension names = writerb.addDimension("names", 3); writerb.addVariable("names", DataType.CHAR, "names svar_len"); writerb.addVariable("names2", DataType.CHAR, "names svar_len"); // add a scalar variable writerb.addVariable("scalar", DataType.DOUBLE, new ArrayList<>()); // signed byte writerb.addVariable("bvar", DataType.BYTE, "lat"); // add global attributes writerb.addAttribute(new Attribute("yo", "face")); writerb.addAttribute(new Attribute("versionD", 1.2)); writerb.addAttribute(new Attribute("versionF", (float) 1.2)); writerb.addAttribute(new Attribute("versionI", 1)); writerb.addAttribute(new Attribute("versionS", (short) 2)); writerb.addAttribute(new Attribute("versionB", (byte) 3)); writerb.addAttribute(new Attribute(CDM.NCPROPERTIES, "test internal attribute is removed when writing")); // test some errors try { Array bad = Array.makeObjectArray(DataType.OBJECT, ArrayList.class, new int[] {1}, null); writerb.addAttribute(new Attribute("versionB", bad)); assert (false); } catch (IllegalArgumentException e) { assert (true); } try (NetcdfFormatWriter writer = writerb.build()) { // write some data ArrayDouble A = new ArrayDouble.D2(latDim.getLength(), lonDim.getLength()); int i, j; Index ima = A.getIndex(); // write for (i = 0; i < latDim.getLength(); i++) { for (j = 0; j < lonDim.getLength(); j++) { A.setDouble(ima.set(i, j), (i * 1000000 + j * 1000)); } } int[] origin = new int[2]; Variable v = writer.findVariable("temperature"); try { writer.write(v, origin, A); } catch (IOException e) { System.err.println("ERROR writing file"); assert (false); } catch (InvalidRangeException e) { e.printStackTrace(); assert (false); } // write char variable int[] origin1 = new int[1]; ArrayChar ac = new ArrayChar.D1(svar_len.getLength()); ima = ac.getIndex(); String val = "Testing 1-2-3"; for (j = 0; j < val.length(); j++) { ac.setChar(ima.set(j), val.charAt(j)); } v = writer.findVariable("svar"); try { writer.write(v, origin1, ac); } catch (IOException e) { System.err.println("ERROR writing Achar"); assert (false); } catch (InvalidRangeException e) { e.printStackTrace(); assert (false); } // write char variable ArrayByte.D1 barray = new ArrayByte.D1(latDim.getLength(), false); int start = -latDim.getLength() / 2; for (j = 0; j < latDim.getLength(); j++) { barray.setByte(j, (byte) (start + j)); } v = writer.findVariable("bvar"); try { writer.write(v, barray); } catch (IOException e) { System.err.println("ERROR writing bvar"); assert (false); } catch (InvalidRangeException e) { e.printStackTrace(); assert (false); } // write char variable as String try { ArrayChar ac2 = new ArrayChar.D1(svar_len.getLength()); ac2.setString("Two pairs of ladies stockings!"); v = writer.findVariable("svar2"); writer.write(v, origin1, ac2); } catch (IOException e) { System.err.println("ERROR writing Achar2"); assert (false); } catch (InvalidRangeException e) { e.printStackTrace(); assert (false); } // write String array try { ArrayChar ac2 = new ArrayChar.D2(names.getLength(), svar_len.getLength()); ima = ac2.getIndex(); ac2.setString(ima.set(0), "No pairs of ladies stockings!"); ac2.setString(ima.set(1), "One pair of ladies stockings!"); ac2.setString(ima.set(2), "Two pairs of ladies stockings!"); v = writer.findVariable("names"); writer.write(v, origin, ac2); } catch (IOException e) { System.err.println("ERROR writing Achar3"); assert (false); } catch (InvalidRangeException e) { e.printStackTrace(); assert (false); } // write String array try { ArrayChar ac2 = new ArrayChar.D2(names.getLength(), svar_len.getLength()); ac2.setString(0, "0 pairs of ladies stockings!"); ac2.setString(1, "1 pair of ladies stockings!"); ac2.setString(2, "2 pairs of ladies stockings!"); v = writer.findVariable("names2"); writer.write(v, origin, ac2); } catch (IOException e) { System.err.println("ERROR writing Achar4"); assert (false); } catch (InvalidRangeException e) { e.printStackTrace(); assert (false); } // write scalar data // write String array try { ArrayDouble.D0 datas = new ArrayDouble.D0(); datas.set(222.333); v = writer.findVariable("scalar"); writer.write(v, datas); } catch (IOException e) { System.err.println("ERROR writing scalar"); assert (false); } catch (InvalidRangeException e) { e.printStackTrace(); assert (false); } } } @Test public void shouldRemoveInternalAttribute() throws IOException { try (NetcdfFile netcdfFile = NetcdfFiles.open(writerLocation)) { assertThat(netcdfFile.findGlobalAttributeIgnoreCase(CDM.NCPROPERTIES)).isNull(); } } @Test public void testReadBack() throws IOException { try (NetcdfFile ncfile = NetcdfFiles.open(writerLocation)) { // read entire array Variable temp = ncfile.findVariable("temperature"); assert (null != temp); Array tA = temp.read(); assert (tA.getRank() == 2); Index ima = tA.getIndex(); int[] shape = tA.getShape(); for (int i = 0; i < shape[0]; i++) { for (int j = 0; j < shape[1]; j++) { assert (tA.getDouble(ima.set(i, j)) == (double) (i * 1000000 + j * 1000)); } } // read part of array int[] origin2 = new int[2]; int[] shape2 = new int[2]; shape2[0] = 1; shape2[1] = temp.getShape()[1]; try { tA = temp.read(origin2, shape2); } catch (InvalidRangeException e) { System.err.println("ERROR reading file " + e); assert (false); return; } catch (IOException e) { System.err.println("ERROR reading file"); assert (false); return; } assert (tA.getRank() == 2); for (int j = 0; j < shape2[1]; j++) { assert (tA.getDouble(ima.set(0, j)) == (double) (j * 1000)); } // rank reduction Array Areduce = tA.reduce(); Index ima2 = Areduce.getIndex(); assert (Areduce.getRank() == 1); for (int j = 0; j < shape2[1]; j++) { assert (Areduce.getDouble(ima2.set(j)) == (double) (j * 1000)); } // read char variable Variable c = ncfile.findVariable("svar"); Assert.assertNotNull(c); try { tA = c.read(); } catch (IOException e) { assert (false); } assert (tA instanceof ArrayChar); ArrayChar achar = (ArrayChar) tA; String sval = achar.getString(achar.getIndex()); assert sval.equals("Testing 1-2-3") : sval; // System.out.println( "val = "+ val); // read char variable 2 Variable c2 = ncfile.findVariable("svar2"); Assert.assertNotNull(c2); try { tA = c2.read(); } catch (IOException e) { assert (false); } assert (tA instanceof ArrayChar); ArrayChar ac2 = (ArrayChar) tA; Assert.assertEquals("Two pairs of ladies stockings!", ac2.getString()); // read String Array Variable c3 = ncfile.findVariable("names"); Assert.assertNotNull(c3); try { tA = c3.read(); } catch (IOException e) { assert (false); } assert (tA instanceof ArrayChar); ArrayChar ac3 = (ArrayChar) tA; ima = ac3.getIndex(); assert (ac3.getString(ima.set(0)).equals("No pairs of ladies stockings!")); assert (ac3.getString(ima.set(1)).equals("One pair of ladies stockings!")); assert (ac3.getString(ima.set(2)).equals("Two pairs of ladies stockings!")); // read String Array - 2 Variable c4 = ncfile.findVariable("names2"); Assert.assertNotNull(c4); try { tA = c4.read(); } catch (IOException e) { assert (false); } assert (tA instanceof ArrayChar); ArrayChar ac4 = (ArrayChar) tA; assert (ac4.getString(0).equals("0 pairs of ladies stockings!")); assert (ac4.getString(1).equals("1 pair of ladies stockings!")); assert (ac4.getString(2).equals("2 pairs of ladies stockings!")); } } @Test public void testNC3WriteExisting() throws IOException, InvalidRangeException { try (NetcdfFormatWriter writer = NetcdfFormatWriter.openExisting(writerLocation).build()) { Variable v = writer.findVariable("temperature"); Assert.assertNotNull(v); int[] shape = v.getShape(); ArrayDouble A = new ArrayDouble.D2(shape[0], shape[1]); int i, j; Index ima = A.getIndex(); for (i = 0; i < shape[0]; i++) { for (j = 0; j < shape[1]; j++) { A.setDouble(ima.set(i, j), i * 1000000 + j * 1000); } } int[] origin = new int[2]; try { writer.write(v, origin, A); } catch (IOException e) { System.err.println("ERROR writing file"); assert (false); } catch (InvalidRangeException e) { e.printStackTrace(); assert (false); } // write char variable v = writer.findVariable("svar"); Assert.assertNotNull(v); shape = v.getShape(); int[] origin1 = new int[1]; ArrayChar ac = new ArrayChar.D1(shape[0]); ima = ac.getIndex(); String val = "Testing 1-2-3"; for (j = 0; j < val.length(); j++) { ac.setChar(ima.set(j), val.charAt(j)); } try { writer.write(v, origin1, ac); } catch (IOException e) { System.err.println("ERROR writing Achar"); assert (false); } catch (InvalidRangeException e) { e.printStackTrace(); assert (false); } // write char variable v = writer.findVariable("bvar"); Assert.assertNotNull(v); shape = v.getShape(); int len = shape[0]; ArrayByte.D1 barray = new ArrayByte.D1(len, false); int start = -len / 2; for (j = 0; j < len; j++) { barray.setByte(j, (byte) (start + j)); } try { writer.write("bvar", barray); } catch (IOException e) { System.err.println("ERROR writing bvar"); assert (false); } catch (InvalidRangeException e) { e.printStackTrace(); assert (false); } // write char variable as String v = writer.findVariable("svar2"); Assert.assertNotNull(v); shape = v.getShape(); len = shape[0]; try { ArrayChar ac2 = new ArrayChar.D1(len); ac2.setString("Two pairs of ladies stockings!"); writer.write(v, ac2); } catch (IOException e) { System.err.println("ERROR writing Achar2"); assert (false); } catch (InvalidRangeException e) { e.printStackTrace(); assert (false); } // write char variable using writeStringDataToChar v = writer.findVariable("names"); Assert.assertNotNull(v); shape = new int[] {v.getDimension(0).getLength()}; Array data = Array.factory(DataType.STRING, shape); ima = data.getIndex(); data.setObject(ima.set(0), "No pairs of ladies stockings!"); data.setObject(ima.set(1), "One pair of ladies stockings!"); data.setObject(ima.set(2), "Two pairs of ladies stockings!"); writer.writeStringDataToChar(v, origin, data); // write another String array v = writer.findVariable("names2"); Assert.assertNotNull(v); shape = v.getShape(); ArrayChar ac2 = new ArrayChar.D2(shape[0], shape[1]); ac2.setString(0, "0 pairs of ladies stockings!"); ac2.setString(1, "1 pair of ladies stockings!"); ac2.setString(2, "2 pairs of ladies stockings!"); writer.write(v, origin, ac2); // write scalar data try { ArrayDouble.D0 datas = new ArrayDouble.D0(); datas.set(222.333); v = writer.findVariable("scalar"); Assert.assertNotNull(v); writer.write(v, datas); } catch (IOException e) { System.err.println("ERROR writing scalar"); assert (false); } catch (InvalidRangeException e) { e.printStackTrace(); assert (false); } } } // test reading after closing the file @Test public void testNC3ReadExisting() throws IOException { try (NetcdfFile ncfile = NetcdfFiles.open(writerLocation)) { // read entire array Variable temp = ncfile.findVariable("temperature"); assert (null != temp); Array tA = temp.read(); assert (tA.getRank() == 2); Index ima = tA.getIndex(); int[] shape = tA.getShape(); for (int i = 0; i < shape[0]; i++) { for (int j = 0; j < shape[1]; j++) { assert (tA.getDouble(ima.set(i, j)) == (double) (i * 1000000 + j * 1000)); } } // read part of array int[] origin2 = new int[2]; int[] shape2 = new int[2]; shape2[0] = 1; shape2[1] = temp.getShape()[1]; try { tA = temp.read(origin2, shape2); } catch (InvalidRangeException e) { System.err.println("ERROR reading file " + e); assert (false); return; } catch (IOException e) { System.err.println("ERROR reading file"); assert (false); return; } assert (tA.getRank() == 2); for (int j = 0; j < shape2[1]; j++) { assert (tA.getDouble(ima.set(0, j)) == (double) (j * 1000)); } // rank reduction Array Areduce = tA.reduce(); Index ima2 = Areduce.getIndex(); assert (Areduce.getRank() == 1); for (int j = 0; j < shape2[1]; j++) { assert (Areduce.getDouble(ima2.set(j)) == (double) (j * 1000)); } // read char variable Variable c = ncfile.findVariable("svar"); Assert.assertNotNull(c); try { tA = c.read(); } catch (IOException e) { assert (false); } assert (tA instanceof ArrayChar); ArrayChar achar = (ArrayChar) tA; String sval = achar.getString(achar.getIndex()); assert sval.equals("Testing 1-2-3") : sval; // System.out.println( "val = "+ val); // read char variable 2 Variable c2 = ncfile.findVariable("svar2"); Assert.assertNotNull(c2); try { tA = c2.read(); } catch (IOException e) { assert (false); } assert (tA instanceof ArrayChar); ArrayChar ac2 = (ArrayChar) tA; assert (ac2.getString().equals("Two pairs of ladies stockings!")); // read String Array Variable c3 = ncfile.findVariable("names"); Assert.assertNotNull(c3); try { tA = c3.read(); } catch (IOException e) { assert (false); } assert (tA instanceof ArrayChar); ArrayChar ac3 = (ArrayChar) tA; ima = ac3.getIndex(); assert (ac3.getString(ima.set(0)).equals("No pairs of ladies stockings!")); assert (ac3.getString(ima.set(1)).equals("One pair of ladies stockings!")); assert (ac3.getString(ima.set(2)).equals("Two pairs of ladies stockings!")); // read String Array - 2 Variable c4 = ncfile.findVariable("names2"); Assert.assertNotNull(c4); try { tA = c4.read(); } catch (IOException e) { assert (false); } assert (tA instanceof ArrayChar); ArrayChar ac4 = (ArrayChar) tA; assert (ac4.getString(0).equals("0 pairs of ladies stockings!")); assert (ac4.getString(1).equals("1 pair of ladies stockings!")); assert (ac4.getString(2).equals("2 pairs of ladies stockings!")); } } @Test public void testWriteRecordOneAtaTime() throws IOException, InvalidRangeException { String filename = tempFolder.newFile().getAbsolutePath(); NetcdfFormatWriter.Builder writerb = NetcdfFormatWriter.createNewNetcdf3(filename); // define dimensions, including unlimited Dimension latDim = writerb.addDimension("lat", 3); Dimension lonDim = writerb.addDimension("lon", 4); writerb.addDimension(Dimension.builder().setName("time").setIsUnlimited(true).build()); // define Variables writerb.addVariable("lat", DataType.FLOAT, "lat").addAttribute(new Attribute("units", "degrees_north")); writerb.addVariable("lon", DataType.FLOAT, "lon").addAttribute(new Attribute("units", "degrees_east")); writerb.addVariable("rh", DataType.INT, "time lat lon") .addAttribute(new Attribute("long_name", "relative humidity")).addAttribute(new Attribute("units", "percent")); writerb.addVariable("T", DataType.DOUBLE, "time lat lon") .addAttribute(new Attribute("long_name", "surface temperature")).addAttribute(new Attribute("units", "degC")); writerb.addVariable("time", DataType.INT, "time").addAttribute(new Attribute("units", "hours since 1990-01-01")); try (NetcdfFormatWriter writer = writerb.build()) { // write out the non-record variables writer.write("lat", Array.makeFromJavaArray(new float[] {41, 40, 39}, false)); writer.write("lon", Array.makeFromJavaArray(new float[] {-109, -107, -105, -103}, false)); //// heres where we write the record variables // different ways to create the data arrays. // Note the outer dimension has shape 1, since we will write one record at a time ArrayInt rhData = new ArrayInt.D3(1, latDim.getLength(), lonDim.getLength(), false); ArrayDouble.D3 tempData = new ArrayDouble.D3(1, latDim.getLength(), lonDim.getLength()); Array timeData = Array.factory(DataType.INT, new int[] {1}); Index ima = rhData.getIndex(); int[] origin = new int[] {0, 0, 0}; int[] time_origin = new int[] {0}; // loop over each record for (int timeIdx = 0; timeIdx < 10; timeIdx++) { // make up some data for this record, using different ways to fill the data arrays. timeData.setInt(timeData.getIndex(), timeIdx * 12); for (int latIdx = 0; latIdx < latDim.getLength(); latIdx++) { for (int lonIdx = 0; lonIdx < lonDim.getLength(); lonIdx++) { rhData.setInt(ima.set(0, latIdx, lonIdx), timeIdx * latIdx * lonIdx); tempData.set(0, latIdx, lonIdx, timeIdx * latIdx * lonIdx / 3.14159); } } // write the data out for one record // set the origin here time_origin[0] = timeIdx; origin[0] = timeIdx; writer.write("rh", origin, rhData); writer.write("T", origin, tempData); writer.write("time", time_origin, timeData); } // loop over record } } // fix for bug introduced 2/9/10, reported by Christian Ward-Garrison cwardgar@usgs.gov @Test public void testRecordSizeBug() throws IOException, InvalidRangeException { String filename = tempFolder.newFile().getAbsolutePath(); int size = 10; Array timeDataAll = Array.factory(DataType.INT, new int[] {size}); NetcdfFormatWriter.Builder writerb = NetcdfFormatWriter.createNewNetcdf3(filename).setFill(false); writerb.addDimension(Dimension.builder().setName("time").setIsUnlimited(true).build()); writerb.addVariable("time", DataType.INT, "time").addAttribute(new Attribute("units", "hours since 1990-01-01")); try (NetcdfFormatWriter writer = writerb.build()) { IndexIterator iter = timeDataAll.getIndexIterator(); Array timeData = Array.factory(DataType.INT, new int[] {1}); int[] time_origin = new int[] {0}; for (int time = 0; time < size; time++) { int val = time * 12; iter.setIntNext(val); timeData.setInt(timeData.getIndex(), val); time_origin[0] = time; writer.write("time", time_origin, timeData); } } try (NetcdfFile ncFile = NetcdfFiles.open(filename)) { Array result = ncFile.readSection("time"); Assert.assertEquals("0 12 24 36 48 60 72 84 96 108", result.toString().trim()); } } }
// $Id: XMLUtil.java,v 1.3 2001/08/13 14:33:52 shaper Exp $ // samskivert library - useful routines for java programs // 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.xml; import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; import java.io.*; import javax.xml.parsers.*; /** * The XMLUtil class provides a simplified interface for XML parsing. * * <p> Classes wishing to parse XML data should extend the * <code>org.xml.sax.helpers.DefaultHandler</code> class, override the * desired SAX event handler methods, and call * <code>XMLUtil.parse()</code>. */ public class XMLUtil { /** * Parse the XML data in the given input stream, using the * specified handler object as both the content and error handler. * * @param handler the SAX event handler * @param in the input stream containing the XML to be parsed */ public static void parse (DefaultHandler handler, InputStream in) throws IOException, ParserConfigurationException, SAXException { XMLReader xr = _pfactory.newSAXParser().getXMLReader(); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.parse(new InputSource(in)); } /** The factory from whence we obtain XMLReader objects */ protected static SAXParserFactory _pfactory; static { _pfactory = SAXParserFactory.newInstance(); _pfactory.setValidating(false); } }
package ca.corefacility.bioinformatics.irida.ria.integration.pages; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p> * Page Object to represent the projects page. * </p> * */ public class ProjectsPage extends AbstractPage { private static final Logger logger = LoggerFactory.getLogger(ProjectsPage.class); public static final String RELATIVE_URL = "projects"; public static final String ADMIN_URL = RELATIVE_URL + "/all"; public ProjectsPage(WebDriver driver) { super(driver); } public void toUserProjectsPage() { loadPage(RELATIVE_URL); } public void toAdminProjectsPage() { loadPage(ADMIN_URL); } private void loadPage(String url) { get(driver, url); waitForTime(100); waitForElementVisible(By.cssSelector("#projects tbody tr")); } public int projectsTableSize() { logger.trace("Getting table size"); List<WebElement> projectList = driver.findElements(By.cssSelector("#projects tbody tr")); int size = projectList.size(); // exclude the "no projects" row if it's empty if (size == 1) { WebElement next = projectList.iterator().next(); if (next.findElement(By.cssSelector("td")).getAttribute("class").contains("dataTables_empty")) { logger.trace("Removing no projects found row"); size } } return size; } public void gotoProjectPage(int row) { submitAndWait(driver.findElements(By.cssSelector("#projects .item-link")).get(row)); } public List<WebElement> getProjectColumn() { return driver.findElements(By.cssSelector("#projects tbody td:nth-child(2)")); } public void clickProjectNameHeader() { // Sorting row is the second one WebElement th = driver.findElement(By.cssSelector("[data-data='name']")); final String originalSortOrder = th.getAttribute("class"); th.click(); new WebDriverWait(driver, TIME_OUT_IN_SECONDS).until( (org.openqa.selenium.support.ui.ExpectedCondition<Boolean>) input -> { final String ariaSort = th.getAttribute("class"); return ariaSort!= null && !ariaSort.equals(originalSortOrder); }); } public void filterByName(String name) { openFilters(); WebElement input = waitForElementVisible(By.id("nameFilter")); input.sendKeys(name); submitFilter("nameFilterClear"); } public void filterByOrganism(String organism) { openFilters(); WebElement input = driver.findElement(By.id("organismFilter")); input.sendKeys(organism); submitFilter("organismFilterClear"); } private void openFilters() { WebElement btn = waitForElementVisible(By.id("openFilterModal")); btn.click(); } private void submitFilter(String filterClearerId) { driver.findElement(By.id("filterProjectsBtn")).click(); waitForElementInvisible(By.className("modal-header")); } public void doSearch(String term) { driver.findElement(By.cssSelector("#projects_filter input")).sendKeys(term); waitForElementInvisible(By.className("projects_processing")); } public void clickLinkToProject(int row) { List<WebElement> links = (List<WebElement>) waitForElementsVisible(By.className("item-link")); submitAndWait(links.get(row)); } }
package fi.otavanopisto.kuntaapi.test.server.integration.management; import static com.jayway.restassured.RestAssured.given; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.StringContains.containsString; import static org.junit.Assert.assertEquals; import java.time.ZoneId; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.jayway.restassured.http.ContentType; import fi.otavanopisto.kuntaapi.server.integrations.management.ManagementConsts; import fi.otavanopisto.kuntaapi.server.integrations.ptv.PtvConsts; import fi.otavanopisto.kuntaapi.test.AbstractIntegrationTest; @SuppressWarnings ("squid:S1192") public class PostTestsIT extends AbstractIntegrationTest { private static final ZoneId TIMEZONE_ID = ZoneId.systemDefault(); private static final String IMAGE_JPEG = "image/jpeg"; private static final String IMAGE_PNG = "image/png"; /** * Starts WireMock */ @Rule public WireMockRule wireMockRule = new WireMockRule(getWireMockPort()); @Before public void beforeTest() throws InterruptedException { createPtvSettings(); getRestfulPtvOrganizationMocker() .mockOrganizations("0de268cf-1ea1-4719-8a6e-1150933b6b9e"); getManagementCategoryMocker() .mockCategories(9001, 9002, 9003); getManagementPostMocker() .mockPosts(789, 890, 901); getManagementMediaMocker() .mockMedias(3001, 3002); startMocks(); waitApiListCount("/organizations", 1); createManagementSettings(getOrganizationId(0)); waitApiListCount(String.format("/organizations/%s/news", getOrganizationId(0)), 3); } @After public void afterClass() { String organizationId = getOrganizationId(0); deletePtvSettings(); deleteManagementSettings(organizationId); getPtvMocker().endMock(); getManagementMocker().endMock(); } @Test public void testFindPosts() { String organizationId = getOrganizationId(0); given() .baseUri(getApiBasePath()) .contentType(ContentType.JSON) .get("/organizations/{organizationId}/news/{newsArticleId}", organizationId, getNewsArticleId(organizationId, 0)) .then() .assertThat() .statusCode(200) .body("id", notNullValue()) .body("title", is("Lorem ipsum dolor sit amet")) .body("slug", is("lorem-ipsum-dolor-sit-amet")) .body("abstract", containsString("Consectetur adipiscing elit")) .body("contents", containsString("Aenean a pellentesque erat")) .body("published", sameInstant(getInstant(2017, 01, 12, 13, 38, TIMEZONE_ID))); } @Test public void testMoreLink() { String organizationId = getOrganizationId(0); given() .baseUri(getApiBasePath()) .contentType(ContentType.JSON) .get("/organizations/{organizationId}/news/{newsArticleId}", organizationId, getNewsArticleId(organizationId, 0)) .then() .assertThat() .statusCode(200) .body("abstract", containsString("Consectetur adipiscing elit")) .body("abstract", not(containsString("more-link"))); } @Test public void testListPosts() { // Zeus shoud be listed before abraham and bertha because it's menu_order is set to -100 String organizationId = getOrganizationId(0); given() .baseUri(getApiBasePath()) .contentType(ContentType.JSON) .get("/organizations/{organizationId}/news", organizationId) .then() .assertThat() .statusCode(200) .body("slug[0]", is("lorem-ipsum-dolor-sit-amet")) .body("slug[1]", is("test-2")) .body("slug[2]", is("test-3")); } @Test public void testListPostsByPath() { given() .baseUri(getApiBasePath()) .contentType(ContentType.JSON) .get("/organizations/{organizationId}/news?slug=test-3", getOrganizationId(0)) .then() .assertThat() .statusCode(200) .body("id.size()", is(1)) .body("id[0]", notNullValue()) .body("slug[0]", is("test-3")); given() .baseUri(getApiBasePath()) .contentType(ContentType.JSON) .get("/organizations/{organizationId}/news?slug=non-existing", getOrganizationId(0)) .then() .assertThat() .statusCode(200) .body("id.size()", is(0)); } @Test public void testListPostsByTag() { given() .baseUri(getApiBasePath()) .contentType(ContentType.JSON) .get("/organizations/{organizationId}/news?tag=test tag 1", getOrganizationId(0)) .then() .assertThat() .statusCode(200) .body("id.size()", is(1)) .body("id[0]", notNullValue()) .body("slug[0]", is("lorem-ipsum-dolor-sit-amet")) .body("tags[0].size()", is(3)) .body("tags[0][0]", is("Yleinen")) .body("tags[0][1]", is("test tag 1")) .body("tags[0][2]", is("test tag 2")); given() .baseUri(getApiBasePath()) .contentType(ContentType.JSON) .get("/organizations/{organizationId}/news?tag=test tag 2", getOrganizationId(0)) .then() .assertThat() .statusCode(200) .body("id.size()", is(2)) .body("slug[0]", is("lorem-ipsum-dolor-sit-amet")) .body("slug[1]", is("test-2")) .body("tags[1].size()", is(2)) .body("tags[1][0]", is("Precious")) .body("tags[1][1]", is("test tag 2")); given() .baseUri(getApiBasePath()) .contentType(ContentType.JSON) .get("/organizations/{organizationId}/news?tag=non-existing", getOrganizationId(0)) .then() .assertThat() .statusCode(200) .body("id.size()", is(0)); } @Test public void testOrganizationPostsNotFound() throws InterruptedException { String organizationId = getOrganizationId(0); String incorrectOrganizationId = getOrganizationId(1); String organizationNewsArticleId = getNewsArticleId(organizationId, 0); String[] malformedIds = new String[] {"evil", "*", "/", "1", "-1", "~"}; assertFound(String.format("/organizations/%s/news/%s", organizationId, organizationNewsArticleId)); assertEquals(3, countApiList(String.format("/organizations/%s/news", organizationId))); for (String malformedId : malformedIds) { assertNotFound(String.format("/organizations/%s/news/%s", organizationId, malformedId)); } assertNotFound(String.format("/organizations/%s/news/%s", incorrectOrganizationId, organizationNewsArticleId)); assertEquals(0, countApiList(String.format("/organizations/%s/news", incorrectOrganizationId))); } @Test public void testNewsArticleImage() { String organizationId = getOrganizationId(0); String newsArticleId = getNewsArticleId(organizationId, 0); String imageId = getNewsArticleImageId(organizationId, newsArticleId, 0); given() .baseUri(getApiBasePath()) .contentType(ContentType.JSON) .get("/organizations/{ORGANIZATIONID}/news/{NEWSARTICLEID}/images/{IMAGEID}", organizationId, newsArticleId, imageId) .then() .assertThat() .statusCode(200) .body("id", is(imageId)) .body("contentType", is(IMAGE_JPEG)); } @Test public void testNewsArticleImageNotFound() { String organizationId = getOrganizationId(0); String newsArticleId = getNewsArticleId(organizationId, 0); String incorrectNewsArticleId = getNewsArticleId(organizationId, 2); String imageId = getNewsArticleImageId(organizationId, newsArticleId, 0); String[] malformedIds = new String[] {"evil", "*", "/", "1", "-1", "~"}; assertFound(String.format("/organizations/%s/news/%s/images/%s", organizationId, newsArticleId, imageId)); assertEquals(1, countApiList(String.format("/organizations/%s/news/%s/images", organizationId, newsArticleId))); for (String malformedId : malformedIds) { assertNotFound(String.format("/organizations/%s/news/%s/images/%s", organizationId, newsArticleId, malformedId)); } assertNotFound(String.format("/organizations/%s/news/%s/images/%s", organizationId, incorrectNewsArticleId, imageId)); assertEquals(0, countApiList(String.format("/organizations/%s/news/%s/images", organizationId, incorrectNewsArticleId))); } @Test public void testNewsArticleImageData() { String organizationId = getOrganizationId(0); String newsArticleId = getNewsArticleId(organizationId, 0); String imageId = getNewsArticleImageId(organizationId, newsArticleId, 0); given() .baseUri(getApiBasePath()) .contentType(ContentType.JSON) .get("/organizations/{ORGANIZATIONID}/news/{NEWSARTICLEID}/images/{IMAGEID}/data", organizationId, newsArticleId, imageId) .then() .assertThat() .statusCode(200) .header("Content-Length", "21621") .header("Content-Type", IMAGE_JPEG); } @Test public void testNewsArticleImageDataScaled() { String organizationId = getOrganizationId(0); String newsArticleId = getNewsArticleId(organizationId, 0); String imageId = getNewsArticleImageId(organizationId, newsArticleId, 0); given() .baseUri(getApiBasePath()) .contentType(ContentType.JSON) .get("/organizations/{ORGANIZATIONID}/news/{EVENTID}/images/{IMAGEID}/data?size=100", organizationId, newsArticleId, imageId) .then() .assertThat() .statusCode(200) .header("Content-Length", "13701") .header("Content-Type", IMAGE_PNG); } private void createPtvSettings() { insertSystemSetting(PtvConsts.SYSTEM_SETTING_BASEURL, String.format("%s%s", getWireMockBasePath(), BASE_URL)); flushCache(); } private void deletePtvSettings() { deleteSystemSetting(PtvConsts.SYSTEM_SETTING_BASEURL); } private void createManagementSettings(String organizationId) { insertOrganizationSetting(organizationId, ManagementConsts.ORGANIZATION_SETTING_BASEURL, String.format("%s/wp-json", getWireMockBasePath(), BASE_URL)); flushCache(); } private void deleteManagementSettings(String organizationId) { deleteOrganizationSetting(organizationId, ManagementConsts.ORGANIZATION_SETTING_BASEURL); } }
package plugins.CENO.Bridge; import java.math.BigInteger; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.params.RSAKeyParameters; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import plugins.CENO.CENOException; import plugins.CENO.CENOL10n; import plugins.CENO.Configuration; import plugins.CENO.Version; import plugins.CENO.Bridge.Signaling.ChannelMaker; import plugins.CENO.Bridge.Signaling.Crypto; import plugins.CENO.FreenetInterface.HighLevelSimpleClientInterface; import plugins.CENO.FreenetInterface.NodeInterface; import freenet.keys.FreenetURI; import freenet.pluginmanager.FredPlugin; import freenet.pluginmanager.FredPluginRealVersioned; import freenet.pluginmanager.FredPluginVersioned; import freenet.pluginmanager.PluginRespirator; import freenet.support.Logger; public class CENOBridge implements FredPlugin, FredPluginVersioned, FredPluginRealVersioned { private PluginRespirator pluginRespirator; public static final Integer cacheLookupPort = 3091; public static final Integer requestReceiverPort = 3093; public static final Integer bundleServerPort = 3094; public static final Integer bundleInserterPort = 3095; /** The HTTP Server to handle requests from other agents */ private Server cenoHttpServer; // Interface objects with fred private HighLevelSimpleClientInterface client; public static NodeInterface nodeInterface; private RequestReceiver reqReceiver; ChannelMaker channelMaker; // Plugin-specific configuration public static final String PLUGIN_URI = "/plugins/plugins.CENO.CENOBridge"; public static final String PLUGIN_NAME = "CENOBridge"; public static Configuration initConfig; private static final Version VERSION = new Version(Version.PluginType.BRIDGE); private static final String CONFIGPATH = ".CENO/bridge.properties"; public static final String BRIDGE_FREEMAIL = "DEFLECTBridge@ih5ixq57yetjdbrspbtskdp6fjake4rdacziriiefnjkwlvhgw3a.freemail"; public static final String CLIENT_FREEMAIL = "CENO@54u2ko3lssqgalpvfqbq44gwfquqrejm3itl4rxj5nt7v6mjy22q.freemail"; public static final String CLIENT_IDENTITY_REQUEST_URI = "USK@7ymlO2uUoGAt9SwDDnDWLCkIkSzaJr5G6etn~vmJxrU,WMeRYMzx2tQHM~O8UWglUmBnjIhp~bh8xue-6g2pmps,AQACAAE/WebOfTrust/0"; public static final String BACKBONE_IDENTITY_REQUEST_URI = "USK@M9UhahTX81i-bB7N8rmWwY5LKKEPfPWgoewNLNkLMmg,IqlCA047XPFoBhxb4gU7YbHWEUV-9iz9mJblXO~w9Zk,AQACAAE/WebOfTrust/0"; public static final String BACKBONE_FREEMAIL = "deflectbackbone@gpksc2qu27zvrp3md3g7fomwyghewkfbb56plifb5qgszwilgjua.freemail"; public static final String ANNOUNCER_PATH = "CENO-signaler"; public void runPlugin(PluginRespirator pr) { // Initialize interfaces with fred pluginRespirator = pr; client = new HighLevelSimpleClientInterface(pluginRespirator.getNode(), pluginRespirator.getHLSimpleClient()); nodeInterface = new NodeInterface(pluginRespirator.getNode(), pluginRespirator); nodeInterface.initFetchContexts(); new CENOL10n("CENOLANG"); // Read properties of the configuration file initConfig = new Configuration(CONFIGPATH); initConfig.readProperties(); // If CENO has no private key for inserting freesites, // generate a new key pair and store it in the configuration file if (initConfig.getProperty("insertURI") == null) { Logger.warning(this, "CENOBridge will generate a new public key for inserting bundles"); FreenetURI[] keyPair = nodeInterface.generateKeyPair(); initConfig.setProperty("insertURI", keyPair[0].toString()); initConfig.setProperty("requestURI", keyPair[1].toString()); initConfig.storeProperties(); } AsymmetricCipherKeyPair asymKeyPair; if (initConfig.getProperty("asymkey.privexponent") == null || initConfig.getProperty("asymkey.modulus") == null || initConfig.getProperty("asymkey.pubexponent") == null) { Logger.warning(this, "CENOBridge will generate a new RSA key pair for the decentralized signaling. This might take a while"); asymKeyPair = Crypto.generateAsymKey(); initConfig.setProperty("asymkey.privexponent", ((RSAKeyParameters) asymKeyPair.getPrivate()).getExponent().toString(23)); initConfig.setProperty("asymkey.modulus", ((RSAKeyParameters) asymKeyPair.getPublic()).getModulus().toString(32)); initConfig.setProperty("asymkey.pubexponent", ((RSAKeyParameters) asymKeyPair.getPublic()).getExponent().toString(32)); initConfig.storeProperties(); } else { asymKeyPair = new AsymmetricCipherKeyPair(new RSAKeyParameters(false, new BigInteger(initConfig.getProperty("asymkey.modulus"),32), new BigInteger(initConfig.getProperty("asymkey.pubexponent"), 32)), new RSAKeyParameters(true, new BigInteger(initConfig.getProperty("asymkey.modulus"), 32), new BigInteger(initConfig.getProperty("asymkey.privexponent"), 32))); } nodeInterface.clearOutboxLog(BRIDGE_FREEMAIL, CLIENT_FREEMAIL); // Initialize RequestReceiver reqReceiver = new RequestReceiver(new String[]{BRIDGE_FREEMAIL}); // Start a thread for polling for new freemails reqReceiver.loopFreemailBoxes(); try { channelMaker = new ChannelMaker(initConfig.getProperty("insertURI"),asymKeyPair); } catch (CENOException e) { Logger.error(this, "Could not start decentralized signaling channel maker"); terminate(); } // Configure CENO's jetty embedded server cenoHttpServer = new Server(); configHttpServer(cenoHttpServer); // Start server and wait until it gets interrupted try { cenoHttpServer.start(); cenoHttpServer.join(); } catch (InterruptedException interruptedEx) { Logger.normal(this, "HTTP Server interrupted. Terminating plugin..."); terminate(); return; } catch (Exception ex) { Logger.error(this, "HTTP Server terminated abnormally"); Logger.error(this, ex.getMessage()); terminate(); return; } } /** * Configure CENO's embedded server * * @param cenoHttpServer the jetty server to be configured */ private void configHttpServer(Server cenoHttpServer) { // Create a collection of ContextHandlers for the server ContextHandlerCollection handlers = new ContextHandlerCollection(); cenoHttpServer.setHandler(handlers); // Add a ServerConnector for the BundlerInserter agent ServerConnector bundleInserterConnector = new ServerConnector(cenoHttpServer); bundleInserterConnector.setName("bundleInserter"); bundleInserterConnector.setHost("localhost"); bundleInserterConnector.setPort(bundleInserterPort); // Add the connector to the server cenoHttpServer.addConnector(bundleInserterConnector); // Configure ContextHandlers to listen to a specific port // and upon request call the appropriate CENOJettyHandler subclass ContextHandler cacheInsertCtxHandler = new ContextHandler(); cacheInsertCtxHandler.setHandler(new BundleInserterHandler()); cacheInsertCtxHandler.setVirtualHosts(new String[]{"@cacheInsert"}); // Add the configured ContextHandler to the server handlers.addHandler(cacheInsertCtxHandler); /* * Uncomment the following block if you need a lookup handler in the bridge side */ /* ServerConnector httpConnector = new ServerConnector(cenoHttpServer); httpConnector.setName("cacheLookup"); httpConnector.setPort(cacheLookupPort); cenoHttpServer.addConnector(httpConnector); ContextHandler cacheLookupCtxHandler = new ContextHandler(); cacheLookupCtxHandler.setHandler(new CacheLookupHandler()); cacheLookupCtxHandler.setVirtualHosts(new String[]{"@cacheLookup"}); handlers.addHandler(cacheLookupCtxHandler); */ } public String getVersion() { return VERSION.getVersion(); } public long getRealVersion() { return VERSION.getRealVersion(); } /** * Method called before termination of the CENO bridge plugin * Terminates ceNoHttpServer and releases resources */ public void terminate() { // Stop the thread that is polling for freemails reqReceiver.stopLooping(); nodeInterface.clearOutboxLog(BRIDGE_FREEMAIL, CLIENT_FREEMAIL); channelMaker.stopListener(); // Stop cenoHttpServer and unbind ports if (cenoHttpServer != null) { try { cenoHttpServer.stop(); } catch (Exception e) { Logger.error(this, "Exception while terminating HTTP server."); Logger.error(this, e.getMessage()); } } Logger.normal(this, PLUGIN_NAME + " terminated."); } }
import org.apache.commons.lang.StringEscapeUtils; import java.sql.ResultSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class Issue_DBWrapper extends DBWrapper { private Issue issue; public Issue_DBWrapper() { this.setTableName("issues"); } // Accessors /** * getIssues() * Returns a list of all issues in database * * @return Issue[] */ public Issue[] getIssues() { List<Object> data = this.getAll(); return (Issue[]) data.toArray(new Issue[data.size()]); } /** * getIssuesbyUserId() * Returns a list of all issues in database * @param userId int * @return Issue[] */ public Issue[] getIssuesbyUserId(int userId) { List<Object> data = this.getManyBy("userId", userId); return (Issue[]) data.toArray(new Issue[data.size()]); } /** * getById() * Returns the status with a matching id * * @param id int * @return Issue */ public Issue getIssueById(int id) { return Issue.class.cast(this.getOneBy("id", id)); } /** * getIssuesByCategory() * Returns the issues with a matching category * * @param category String * @return Issue[] */ public Issue[] getIssuesByCategory(int category) { List<Object> data = this.getManyBy("category", category); return (Issue[]) data.toArray(new Issue[data.size()]); } /** * getIssuesByStatus() * Returns the issues with a matching status * * @param status String * @return Issue[] */ public Issue[] getIssuesByStatus(String status) { List<Object> data = this.getManyBy("status", status); return (Issue[]) data.toArray(new Issue[data.size()]); } // Mutators /** * Create a new issue * @param issue * @return */ public boolean createNewIssue(Issue issue) { this.issue = issue; return this.insertRow(); } /** * Update and existing issue * @param issue * @return */ public boolean updateIssue(Issue issue) { this.issue = issue; return this.updateRow(issue.getIssueId()); } /** * Delete an issue by id * @param id * @return */ public boolean deleteIssue(int id) { return this.delete(id); } /** * runQuery() * Returns the queried results * * @return Issue[] */ public Issue[] runQuery() { List<Object> data = this.run(); return (Issue[]) data.toArray(new Issue[data.size()]); } /** * mapRowToObject() * Maps a row to a Issue * * @param rs ResultSet * @return Issue */ protected Issue mapRowToObject(ResultSet rs) { try { return new Issue( rs.getInt("id"), rs.getString("title"), rs.getString("description"), rs.getString("resolution"), rs.getInt("category"), rs.getInt("userId"), rs.getInt("status"), rs.getTimestamp("created"), rs.getTimestamp("resolved") ); } catch (Exception ex) { System.out.println(ex.toString()); return null; } } /** * Maps an Issue to an SQL update statement * @return */ @Override protected Map<String, String> mapObjectToUpdateValues() { Map<String, String> values = new HashMap<>(); values.put("values", "title='" + StringEscapeUtils.escapeSql(this.issue.getTitle()) + "', " + "description='" + StringEscapeUtils.escapeSql(this.issue.getDescription()) + "', " + "resolution='" + StringEscapeUtils.escapeSql(this.issue.getResolution()) + "', " + "category=" + this.issue.getCategory().getId() + ", " + "userId=" + this.issue.getUserId() + ", " + "status=" + this.issue.getStatus().getId() + ", " + "created='" + this.issue.getCreated() + "', " + "resolved='" + this.issue.getResolved() + "'"); return values; } /** * Maps an Issue to an SQL insert statement * This is where a new issue is created * @return */ @Override protected Map<String, String> mapObjectToInsertValues() { Map<String, String> values = new HashMap<>(); values.put("columns", "title, description, resolution, category, userId, status, created, resolved"); values.put("values", "'" + StringEscapeUtils.escapeSql(this.issue.getTitle()) + "', " + "'" + StringEscapeUtils.escapeSql(this.issue.getDescription()) + "', " + "'" + this.issue.getResolution() + "', " + this.issue.getCategoryId() + ", " + this.issue.getUserId() + ", " + this.issue.getStatusId() + ", " + "'" + this.issue.getCreated() + "', " + "'" + this.issue.getResolved() + "'"); return values; } // @Override // protected Map<String, String> mapObjectToInsertValues() { // Map<String, String> values = new HashMap<>(); // values.put("columns", "title, description, resolution, category, userId, status, created, resolved"); // values.put("values", "'" + this.issue.getTitle() + "', " + // "'" + this.issue.getDescription() + "', " + // "'" + this.issue.getResolution() + "', " + // this.issue.getCategory() + ", " + // this.issue.getUserId() + ", " + // this.issue.getStatus() + ", " + // "'" + this.issue.getCreated() + "', " + // "'" + this.issue.getResolved() + "'"); // return values; }
package org.fiware.apps.repository.it.collectionService; import org.fiware.apps.repository.it.IntegrationTestHelper; import com.fasterxml.jackson.core.JsonProcessingException; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.message.BasicHeader; import org.fiware.apps.repository.model.Resource; import org.fiware.apps.repository.model.ResourceCollection; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; public class CollectionServiceITTest { private IntegrationTestHelper client; private static String rdfxmlExample; private static String rdfjsonExample; public CollectionServiceITTest() { client = new IntegrationTestHelper(); } @BeforeClass public static void setUpClass() throws IOException { //Delete test collection. IntegrationTestHelper client = new IntegrationTestHelper(); List <Header> headers = new LinkedList<>(); client.deleteCollection("collectionTest1", headers); String auxString = ""; FileReader file = new FileReader("src/test/resources/rdf+xml.rdf"); BufferedReader buffer = new BufferedReader(file); while(buffer.ready()) { auxString = auxString.concat(buffer.readLine()); } buffer.close(); rdfxmlExample = auxString; auxString = ""; file = new FileReader("src/test/resources/rdf+json.rdf"); buffer = new BufferedReader(file); while(buffer.ready()) { auxString = auxString.concat(buffer.readLine()); } buffer.close(); rdfjsonExample = auxString; } @AfterClass public static void tearDownClass() throws IOException { //Delete test collection. IntegrationTestHelper client = new IntegrationTestHelper(); List <Header> headers = new LinkedList<>(); client.deleteCollection("collectionTest1", headers); } @Before public void setUp() { } @After public void tearDown() { } /* Test que crea un recurso */ @Test public void createResourceTest() throws JsonProcessingException, IOException { String collections = "collectionTest1"; String fileName = ""; String mimeType = ""; String contentUrl = "http://localhost:8080/contentUrl/resourceTest1"; String creator = "Me"; String name = "resourceTest1"; Resource resource = generateResource(null, fileName, mimeType, contentUrl, null, creator, null, null, name); //Create a resource List <Header> headers = new LinkedList<>(); headers.add(new BasicHeader("Content-Type", "application/json")); HttpResponse response = client.postResourceMeta(collections, client.resourceToJson(resource), headers); assertEquals(201, response.getStatusLine().getStatusCode()); } /* Test que crea un recurso, comprueba que existe y lo elimina */ @Test public void createAndDeleteResourceTest() throws JsonProcessingException, IOException { String collections = "collectionTest1"; String fileName = ""; String mimeType = ""; String contentUrl = "http://localhost:8080/contentUrl/resourceTest2"; String creator = ""; String name = "resourceTest2"; Resource resource = generateResource(null, fileName, mimeType, contentUrl, null, creator, null, null, name); //Create un resource in the repository List <Header> headers = new LinkedList<>(); headers.add(new BasicHeader("Content-Type", "application/json")); HttpResponse response = client.postResourceMeta(collections, client.resourceToJson(resource), headers); assertEquals(201, response.getStatusLine().getStatusCode()); //Get the resource meta headers = new LinkedList<>(); headers.add(new BasicHeader("Accept", "application/json")); response = client.getResourceMeta(collections+"/"+name, headers); assertEquals(200, response.getStatusLine().getStatusCode()); //Delete the resource response = client.deleteResource(collections+"/"+name, headers); assertEquals(204, response.getStatusLine().getStatusCode()); } /* Test que crea un recurso e inserta un contenido */ @Test public void createAndinsertResourceTest() throws JsonProcessingException, IOException { String collections = "collectionTest1"; String fileName = ""; String mimeType = ""; String contentUrl = "http://localhost:8080/contentUrl/resourceTest3"; String creator = ""; String name = "resourceTest3"; Resource resource = generateResource(null, fileName, mimeType, contentUrl, null, creator, null, null, name); //Create un resource in the repository List <Header> headers = new LinkedList<>(); headers.add(new BasicHeader("Content-Type", "application/json")); HttpResponse response = client.postResourceMeta(collections, client.resourceToJson(resource), headers); assertEquals(201, response.getStatusLine().getStatusCode()); //Get the resource meta headers = new LinkedList<>(); headers.add(new BasicHeader("Accept", "application/json")); response = client.getResourceMeta(collections+"/"+name, headers); assertEquals(200, response.getStatusLine().getStatusCode()); //Insert a RDF content in the repository headers = new LinkedList<>(); headers.add(new BasicHeader("Content-Type", "application/rdf+xml")); response = client.putResourceContent(collections+"/"+name, rdfxmlExample, headers); assertEquals(200, response.getStatusLine().getStatusCode()); } /* Test que crea un recurso y lo modifica */ @Test public void createAndEditResourceTest() throws IOException { String collections = "collectionTest1"; String fileName = ""; String mimeType = ""; String contentUrl = "http://localhost:8080/contentUrl/resourceTest4"; String creator = ""; String name = "resourceTest4"; Resource resource = generateResource(null, fileName, mimeType, contentUrl, null, creator, null, null, name); //Add a resource in the repository List <Header> headers = new LinkedList<>(); headers.add(new BasicHeader("Content-Type", "application/json")); HttpResponse response = client.postResourceMeta(collections, client.resourceToJson(resource), headers); assertEquals(201, response.getStatusLine().getStatusCode()); resource = generateResource(null, fileName, null, contentUrl, null, creator, null, null, name+".1"); //Modify the resource in the repository response = client.putResourceMeta(collections+"/"+name, client.resourceToJson(resource), headers); assertEquals(200, response.getStatusLine().getStatusCode()); //Check the old resource is not in the repository headers = new LinkedList<>(); headers.add(new BasicHeader("Accept", "application/json")); response = client.getResourceMeta(collections+"/"+name, headers); assertEquals(404, response.getStatusLine().getStatusCode()); //Check the new resource is in the repository response = client.getResourceMeta(collections+"/"+name+".1", headers); assertEquals(200, response.getStatusLine().getStatusCode()); } /* Test que crea un recurso inserta contenido y lo modifica */ @Test public void createInsertAndModifyResourceTest() throws IOException { String collections = "collectionTest1"; String fileName = ""; String mimeType = ""; String contentUrl = "http://localhost:8080/contentUrl/resourceTest5"; String creator = ""; String name = "resourceTest5"; Resource resource = generateResource(null, fileName, mimeType, contentUrl, null, creator, null, null, name); //Create a resource in the repository List <Header> headers = new LinkedList<>(); headers.add(new BasicHeader("Content-Type", "application/json")); HttpResponse response = client.postResourceMeta(collections, client.resourceToJson(resource), headers); assertEquals(201, response.getStatusLine().getStatusCode()); //Insert a RDF content in the repository headers = new LinkedList<>(); headers.add(new BasicHeader("Content-Type", "application/rdf+xml")); response = client.putResourceContent(collections+"/"+name, rdfxmlExample, headers); assertEquals(200, response.getStatusLine().getStatusCode()); //Get the resource content headers = new LinkedList<>(); headers.add(new BasicHeader("Accept", "application/rdf+xml")); response = client.getResourceContent(collections+"/"+name, headers); assertEquals(200, response.getStatusLine().getStatusCode()); //Update de the resource content headers = new LinkedList<>(); headers.add(new BasicHeader("Content-Type", "application/rdf+json")); response = client.putResourceContent(collections+"/"+name, rdfjsonExample, headers); assertEquals(200, response.getStatusLine().getStatusCode()); //Get the new resource content headers = new LinkedList<>(); headers.add(new BasicHeader("Accept", "application/rdf+xml")); response = client.getResourceContent(collections+"/"+name, headers); assertEquals(200, response.getStatusLine().getStatusCode()); } /* Test que crea un recurso lo elimina y lo vuelve a crear */ @Test public void createDeleteAndCreateResourceTest() throws IOException { String collections = "collectionTest1"; String fileName = ""; String mimeType = ""; String contentUrl = "http://localhost:8080/contentUrl/resourceTest6"; String creator = ""; String name = "resourceTest6"; Resource resource = generateResource(null, fileName, mimeType, contentUrl, null, creator, null, null, name); //Add a resource in the repository List <Header> headers = new LinkedList<>(); headers.add(new BasicHeader("Content-Type", "application/json")); HttpResponse response = client.postResourceMeta(collections, client.resourceToJson(resource), headers); assertEquals(201, response.getStatusLine().getStatusCode()); //Delete the resource in the repository response = client.deleteResource(collections+"/"+name, headers); assertEquals(204, response.getStatusLine().getStatusCode()); //Add the resource again in the repository response = client.postResourceMeta(collections, client.resourceToJson(resource), headers); assertEquals(201, response.getStatusLine().getStatusCode()); } @Test public void createResourceConflictTest() throws IOException { String collections = "collectionTest1"; String fileName = ""; String mimeType = ""; String contentUrl = "http://localhost:8080/contentUrl/resourceTestConflict"; String creator = "Me"; String name = "resourceTestConflict"; Resource resource = generateResource(null, fileName, mimeType, contentUrl, null, creator, null, null, name); //Create a resource List <Header> headers = new LinkedList<>(); headers.add(new BasicHeader("Content-Type", "application/json")); client.postResourceMeta(collections, client.resourceToJson(resource), headers); HttpResponse response = client.postResourceMeta(collections, client.resourceToJson(resource), headers); assertEquals(409, response.getStatusLine().getStatusCode()); } @Test public void createResourceFailTest() throws IOException { String collections = "collectionTest1"; String fileName = ""; String mimeType = ""; String contentUrl = "http://localhost:8080/contentUrl/badName"; String creator = "Me"; String name = "badname.meta"; Resource resource = generateResource(null, fileName, mimeType, contentUrl, null, creator, null, null, name); //Create a resource List <Header> headers = new LinkedList<>(); headers.add(new BasicHeader("Content-Type", "application/json")); client.postResourceMeta(collections, client.resourceToJson(resource), headers); HttpResponse response = client.postResourceMeta(collections, client.resourceToJson(resource), headers); assertEquals(400, response.getStatusLine().getStatusCode()); } @Test public void getResourceNotFoundTest() throws IOException { String collections = "collectionTest1"; String name = "notfound"; //Get a resource that not exist List <Header> headers = new LinkedList<>(); headers.add(new BasicHeader("Accept", "application/json")); client.getResourceMeta(collections, headers); HttpResponse response = client.getResourceMeta(collections+"/"+name, headers); assertEquals(404, response.getStatusLine().getStatusCode()); } private Resource generateResource(String content, String fileName, String mimeType, String contentUrl, Date creationDate, String creator, String id, Date modificationDate, String name) { Resource resource = new Resource(); if (content == null) { resource.setContent(null); } else { resource.setContent(content.getBytes()); } resource.setContentFileName(fileName); resource.setContentMimeType(mimeType); resource.setContentUrl(contentUrl); resource.setCreationDate(creationDate); resource.setCreator(creator); resource.setId(id); resource.setModificationDate(modificationDate); resource.setName(name); return resource; } private ResourceCollection generateResourceCollection(String string, Date date, boolean creationDate) { ResourceCollection collection = new ResourceCollection(); if (string == null) string = "string"; if (date == null) date = new Date(); if (creationDate) collection.setCreationDate(date); collection.setName(string); collection.setCreator(string + "Creator"); collection.setModificationDate(date); collection.setId(string + "Id"); return collection; } }
package com.alx.etx; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.xml.bind.annotation.XmlTransient; /** * The client representantion of the coordination. * * @author alemser */ public class Coordination implements Serializable { /** * Coordination was created but was not started yet. */ public static final int CREATED = 0; /** * Coordination was created and started. */ public static final int RUNNING = 1; /** * Coordination ended successfully (confirmed). */ public static final int ENDED = 2; /** * Coordination ended with timeout (error state) */ public static final int ENDED_TIMEOUT = 3; /** * Coordination ended because participant cancellation (error state) */ public static final int ENDED_CANCELLED = 4; /** * Coordination is in a inconsistent state (must be cancelled). */ public static final int INCONSISTENT = 5; private static final long serialVersionUID = 1L; private String id; private Date createTime; private Date startTime; private Date endTime; private int state; private List<Participant> participants; public Coordination() { this.createTime = new Date(); this.state = CREATED; } public Coordination(String id) { this(); this.id = id; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public int getState() { return state; } public void setState(int state) { this.state = state; } public List<Participant> getParticipants() { return participants; } public void setParticipants(List<Participant> participants) { this.participants = participants; } /** * Print the current coordination state and info. * @param out the outputstream the print the coordination info. */ public void print(OutputStream out) { StringBuilder sb = new StringBuilder(); sb.append("Coordination " + getId() + " is " + getStateDescription()); if( getStartTime() != null ) { sb.append(" and was started at " + getStartTime() + "."); } else { sb.append(" and is not started yet."); } sb.append("\n"); int psize = getParticipants().size(); if( psize == 0 ) { sb.append("There is no registered participants."); } else { sb.append("There " + (psize > 1 ? " are " : " is ") + psize + " registered participant" + (psize>1?"s" : "") + ".\n"); for (Participant p : getParticipants() ) { sb.append("=> Participant " + p.getId() + " state is " + p.getStateDescription()+ "\n"); } } try { out.write(sb.toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } } @XmlTransient public String getStateDescription() { return getStateDescription(getState()); } @XmlTransient public String getStateDescription(int state) { switch (state) { case CREATED: return "created"; case ENDED: return "ended"; case ENDED_CANCELLED: return "cancelled"; case ENDED_TIMEOUT: return "timeouted"; case RUNNING: return "running"; default: return "undefined"; } } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } private boolean allDesiredState(int desiredState) { boolean allIn = true; for (Participant p : this.participants ) { if( p.getState() != desiredState ) { allIn = false; break; } } return allIn; } }
/** *package for calculate task * *@author Natasha Panchina(panchinanata25@gmail.com) *@version $Id$ *@since 0.1 */ package ru.job4j;
package org.jboss.forge.addon.swarm.config; import org.junit.Assert; import org.junit.Test; /** * Test class for {@link WildflySwarmConfigurationBuilder} * * @author <a href="mailto:ggastald@redhat.com">George Gastaldi</a> */ public class WildflySwarmConfigurationBuilderTest { @Test public void testCreate() { WildflySwarmConfigurationBuilder builder = WildflySwarmConfigurationBuilder.create(); Assert.assertNotNull(builder); builder.contextPath("/context").httpPort(80).portOffset(100); Assert.assertEquals("/context", builder.getContextPath()); Assert.assertEquals(Integer.valueOf(80), builder.getHttpPort()); Assert.assertEquals(Integer.valueOf(100), builder.getPortOffset()); } }
package org.springframework.data.ebean.repository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.*; import org.springframework.data.ebean.sample.config.SampleConfig; import org.springframework.data.ebean.sample.domain.User; import org.springframework.data.ebean.sample.domain.UserRepository; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.hasItem; import static org.junit.Assert.*; /** * @author Xuegui Yuan */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SampleConfig.class) public class UserRepositoryIntegrationTest { @Autowired UserRepository userRepository; // Test fixture User user; @Before public void setUp() throws Exception { userRepository.deleteAll(); user = new User("Xuegui", "Yuan", "yuanxuegui@163.com"); user.setAge(29); user = userRepository.save(user); } @Test public void updateQuery() throws Exception { assertNotNull(userRepository.updateQuery()); } @Test public void sqlUpdateOf() throws Exception { assertNotNull(userRepository.sqlUpdateOf("update user set age = 30 where id = ?")); } @Test public void save() throws Exception { User u = new User("test", "test", "test@163.com"); u = userRepository.save(u); assertNotNull(u.getId()); } @Test public void saveAll() throws Exception { List<User> users = new ArrayList<>(3); for (int i = 0; i < 3; i++) { users.add(new User("test", "test" + i, "test" + i + "@163.com")); } userRepository.saveAll(users); for (User u : users) { assertNotNull(u.getId()); } } @Test public void update() throws Exception { User u = new User("update", "update", "update@163.com"); userRepository.save(u); User u1 = new User(); u1.setId(u.getId()); u1.setAge(31); userRepository.update(u1); u = userRepository.findById(u.getId()).get(); assertEquals(31, u.getAge()); } @Test public void updateAll() throws Exception { List<User> users = new ArrayList<>(3); for (int i = 0; i < 3; i++) { User u = new User(); u.setId(i + 1L); u.setAge(32); users.add(u); } userRepository.updateAll(users); users = userRepository.findAllById(Arrays.asList(1L, 2L, 3L)); for (User u : users) { assertEquals(32, u.getAge()); } } @Test public void deleteById() throws Exception { user = new User("Xuegui", "Yuan", "yuanxuegui@163.com"); userRepository.deleteById(1L); assertEquals(false, userRepository.findById(1L).isPresent()); user.changeEmail("yuanxuegui@126.com"); userRepository.save(user); User u = userRepository.findByProperty("emailAddress", "yuanxuegui@126.com").get(); assertNotNull(u); userRepository.deleteById(u.getId()); } @Test public void delete() throws Exception { User u = new User(); u.setId(1L); userRepository.delete(u); assertEquals(false, userRepository.findById(1L).isPresent()); } @Test public void deleteAll() throws Exception { userRepository.deleteAll(); assertEquals(0, userRepository.count()); } @Test public void deleteAll_entities() throws Exception { List<User> users = new ArrayList<>(3); for (int i = 0; i < 3; i++) { User u = new User(); u.setId(i + 1L); users.add(u); } userRepository.deleteAll(users); users = userRepository.findAllById(Arrays.asList(1L, 2L, 3L)); assertEquals(0, users.size()); } @Test public void findById() throws Exception { User u = new User("findById", "findById", "findById@163.com"); userRepository.save(u); assertEquals(true, userRepository.findById(u.getId()).isPresent()); } @Test public void findById_fetchPath() throws Exception { User u = new User("find", "find", "find@163.com"); userRepository.save(u); u = userRepository.findById("emailAddress", u.getId()).get(); assertEquals("find@163.com", u.getEmailAddress()); } @Test public void findByProperty() throws Exception { User u = new User("findOneByProperty", "findOneByProperty", "findOneByProperty@163.com"); userRepository.save(u); User u1 = userRepository.findByProperty("id", u.getId()).get(); assertEquals("findOneByProperty@163.com", u1.getEmailAddress()); } @Test public void findByProperty_fetchPath() throws Exception { User u = new User("findOneByProperty_fetchPath", "findOneByProperty_fetchPath", "findOneByProperty_fetchPath@163.com"); userRepository.save(u); User u1 = userRepository.findByProperty("id,emailAddress", "id", u.getId()).get(); assertEquals("findOneByProperty_fetchPath@163.com", u1.getEmailAddress()); } @Test public void findAllByProperty() throws Exception { User u = new User("findOneByProperty", "findOneByProperty", "findOneByProperty@163.com"); userRepository.save(u); List<User> users = userRepository.findAllByProperty("id", u.getId()); assertNotEquals(0, users.size()); } @Test public void findAllByProperty_fetchPath() throws Exception { User u = new User("findOneByProperty", "findOneByProperty", "findOneByProperty@163.com"); userRepository.save(u); List<User> users = userRepository.findAllByProperty("fullName(lastName)", "id", u.getId()); assertNotEquals(0, users.size()); } @Test public void findAllByProperty_fetchPath_sort() throws Exception { User u = new User("findAllByProperty_fetchPath_sort", "findAllByProperty_fetchPath_sort", "findAllByProperty_fetchPath_sort@163.com"); userRepository.save(u); List<User> users = userRepository.findAllByProperty("fullName(lastName)", "id", u.getId(), Sort.by(Sort.Direction.DESC, "id")); assertNotEquals(0, users.size()); } @Test public void findAllById() throws Exception { User u = new User("findAllById", "findAllById", "findAllById@163.com"); userRepository.save(u); List<User> users = userRepository.findAllById(Arrays.asList(u.getId())); assertEquals(1, users.size()); } @Test public void findAll() throws Exception { List<User> users = userRepository.findAll(); assertEquals(1, users.size()); } @Test public void findAll_sort() throws Exception { User u = new User("findAll_sort", "findAll_sort", "findAll_sort@163.com"); userRepository.save(u); List<User> result1 = userRepository.findAll(Sort.by(Sort.Direction.DESC, "id")); assertNotEquals(0, result1.size()); assertEquals("findAll_sort", result1.get(0).getFullName().getLastName()); } @Test public void findAll_fetchPath() throws Exception { User u = new User("findAll_fetchPath", "findAll_fetchPath", "findAll_fetchPath@163.com"); userRepository.save(u); List<User> result1 = userRepository.findAll("fullName(lastName)"); assertNotEquals(0, result1.size()); } @Test public void findAll_fetchPath_ids() throws Exception { User u = new User("findAll_fetchPath_ids", "findAll_fetchPath_ids", "findAll_fetchPath_ids@163.com"); userRepository.save(u); List<User> result1 = userRepository.findAll("fullName(lastName)", Arrays.asList(u.getId())); assertEquals(1, result1.size()); assertEquals("findAll_fetchPath_ids", result1.get(0).getFullName().getLastName()); } @Test public void findAll_fetchPath_sort() throws Exception { User u = new User("findAll_fetchPath_ids", "findAll_fetchPath_ids", "findAll_fetchPath_ids@163.com"); userRepository.save(u); List<User> result1 = userRepository.findAll("fullName(lastName)", Sort.by(Sort.Direction.DESC, "id")); assertNotEquals(1, result1.size()); } @Test public void findAll_fetchPath_pageable() throws Exception { User u = new User("findAll_fetchPath_pageable", "findAll_fetchPath_pageable", "findAll_fetchPath_pageable@163.com"); userRepository.save(u); Page<User> page = userRepository.findAll("fullName(lastName)", PageRequest.of(0, 20, Sort.Direction.DESC, "id")); assertNotNull(page); } @Test public void findAll_example() throws Exception { User u = new User("findOneByProperty", "findOneByProperty", "findOneByProperty@163.com"); userRepository.save(u); u.setEmailAddress("FINDOneByProperty"); List<User> result1 = userRepository.findAll(Example.of(u, ExampleMatcher.matchingAll() .withIgnoreCase(true) .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING))); assertEquals(1, result1.size()); assertEquals("findOneByProperty", result1.get(0).getFullName().getLastName()); } @Test public void findAll_fetchPath_example() throws Exception { User u = new User("findAll_fetchPath_example", "findAll_fetchPath_example", "findAll_fetchPath_example@163.com"); userRepository.save(u); u.setEmailAddress("FINDAll_fetchPath_example"); List<User> result1 = userRepository.findAll("fullName(lastName)", Example.of(u, ExampleMatcher.matchingAll() .withIgnoreCase(true) .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING))); assertEquals(1, result1.size()); assertEquals("findAll_fetchPath_example", result1.get(0).getFullName().getLastName()); } @Test public void findAll_fetchPath_example_sort() throws Exception { User u = new User("findAll_fetchPath_example_sort", "findAll_fetchPath_example_sort", "findAll_fetchPath_example_sort@163.com"); userRepository.save(u); u.setEmailAddress("FINDAll_fetchPath_example_sort"); List<User> result1 = userRepository.findAll("fullName(lastName)", Example.of(u, ExampleMatcher.matchingAll() .withIgnoreCase(true) .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)), Sort.by(Sort.Direction.DESC, "fullName.lastName") ); assertEquals(1, result1.size()); assertEquals("findAll_fetchPath_example_sort", result1.get(0).getFullName().getLastName()); } @Test public void findAll_example_sort() throws Exception { User u = new User("findAll_example_sort", "findAll_example_sort", "findAll_example_sort@163.com"); userRepository.save(u); u.setEmailAddress("findAll_example_sort"); List<User> result1 = userRepository.findAll(Example.of(u, ExampleMatcher.matchingAll() .withIgnoreCase(true) .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)), Sort.by(Sort.Direction.DESC, "id") ); assertEquals(1, result1.size()); assertEquals("findAll_example_sort", result1.get(0).getFullName().getLastName()); } @Test public void findAll_example_pageable() throws Exception { User userExample = new User("X", "Y", "y"); Page<User> page = userRepository.findAll(Example.of(userExample), PageRequest.of(0, 20, Sort.Direction.DESC, "id")); assertNotNull(page); } @Test public void findAll_fetchPath_example_pageable() throws Exception { User userExample = new User("X", "Y", "y"); Page<User> page = userRepository.findAll("fullName(lastName)", Example.of(userExample), PageRequest.of(0, 20, Sort.Direction.DESC, "id")); assertNotNull(page); } @Test public void findAll_pageable() { Page<User> page = userRepository.findAll(PageRequest.of(0, 20, Sort.Direction.DESC, "id")); assertNotNull(page); } @Test public void findOne_example() throws Exception { User u = new User("findOne_example", "findOne_example", "findOne_example@163.com"); userRepository.save(u); User userExample = new User("example", "example", "example"); assertEquals(true, userRepository.findOne(Example.of(userExample, ExampleMatcher.matchingAll() .withIgnoreCase(true) .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING))).isPresent()); } @Test public void count() throws Exception { User u = new User("findOne_example", "findOne_example", "findOne_example@163.com"); userRepository.save(u); User userExample = new User("example", "example", "example"); assertEquals(true, userRepository.findOne(Example.of(userExample, ExampleMatcher.matchingAll() .withIgnoreCase(true) .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING))).isPresent()); } @Test public void exists_example() throws Exception { User u = new User("exists_example", "exists_example", "exists_example@163.com"); userRepository.save(u); User userExample = new User("exists_example", "exists_example", "exists_example"); assertEquals(true, userRepository.exists(Example.of(userExample, ExampleMatcher.matchingAll() .withIgnoreCase(true) .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)))); } @Test public void existsById() throws Exception { User u = new User("existsById", "existsById", "existsById@163.com"); userRepository.save(u); User userExample = new User("existsById", "existsById", "existsById"); assertEquals(true, userRepository.existsById(u.getId())); } @Test public void count_example() throws Exception { User u = new User("count_example", "count_example", "count_example@163.com"); userRepository.save(u); User userExample = new User("count_example", "count_example", "count_example"); assertEquals(1, userRepository.count(Example.of(userExample, ExampleMatcher.matchingAll() .withIgnoreCase(true) .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)))); } @Test public void queryAndMethod() { // test find all orm query List<User> result1 = (List<User>) userRepository.findAll(); result1.forEach(it -> System.out.println(it)); assertEquals(1, result1.size()); assertEquals("Yuan", result1.get(0).getFullName().getLastName()); assertThat(result1, hasItem(user)); // test find list orm query List<User> result2 = userRepository.findByLastnameOql("Yuan"); assertEquals(1, result2.size()); assertEquals("Yuan", result2.get(0).getFullName().getLastName()); assertThat(result2, hasItem(user)); // test find list sql query List<User> result3 = userRepository.findUsersByLastNameEquals("Yuan"); assertEquals(1, result3.size()); assertEquals("Yuan", result3.get(0).getFullName().getLastName()); // test find one orm query User result4 = userRepository.findUserByEmailAddressEqualsOql("yuanxuegui@163.com"); assertEquals("yuanxuegui@163.com", result4.getEmailAddress()); // test find one sql query User result5 = userRepository.findUserByEmailAddressEquals("yuanxuegui@163.com"); assertEquals("yuanxuegui@163.com", result5.getEmailAddress()); // test update orm query int result6 = userRepository.changeUserEmailAddress("yuanxuegui@163.com", "yuanxuegui@126.com"); assertEquals(1, result6); // test find list orm query List<User> result7 = userRepository.findByLastnameOql("Yuan"); assertEquals("yuanxuegui@126.com", result7.get(0).getEmailAddress()); // test delete sql query int result8 = userRepository.deleteUserByEmailAddress("yuanxuegui@126.com"); assertEquals(1, result8); // test find one sql query User result9 = userRepository.findUserByEmailAddressEquals("yuanxuegui@126.com"); assertNull(result9); // test create user = new User("Xuegui", "Yuan", "yuanxuegui@163.com"); user.setAge(29); user = userRepository.save(user); // test find list named orm query List<User> result10 = userRepository.findByLastNameNamedOql("Yuan"); assertEquals(1, result10.size()); assertEquals("Yuan", result10.get(0).getFullName().getLastName()); // test find one orm query User result11 = userRepository.findUserByEmailAddressEquals("yuanxuegui@163.com"); assertNotNull(result11); // test delete orm update int result12 = userRepository.deleteUserByEmailAddressOql("yuanxuegui@163.com"); assertEquals(1, result12); // test find one sql query User result13 = userRepository.findUserByEmailAddressEquals("yuanxuegui@163.com"); assertNull(result13); } @Test public void testFindByMethodName() { List<User> result1 = userRepository.findAllByEmailAddressAndFullNameLastName("yuanxuegui@163.com", "Yuan"); assertEquals(1, result1.size()); assertEquals("Yuan", result1.get(0).getFullName().getLastName()); assertThat(result1, hasItem(user)); } @Test public void testAuditable() { User u = userRepository.findUserByEmailAddressEqualsOql("yuanxuegui@163.com"); assertEquals("test", u.getCreatedBy().orElse(null)); assertEquals("test", u.getLastModifiedBy().orElse(null)); } @Test public void testDomainEvent() { user.changeEmail("yuanxuegui@126.com"); userRepository.save(user); User u = userRepository.findByProperty("emailAddress", "yuanxuegui@126.com").get(); assertNotNull(u); assertEquals("yuanxuegui@126.com", u.getEmailAddress()); } @Test public void findUserByEmailAddressEqualsOql_pageable() { Page<User> page = userRepository.findUserByEmailAddressEqualsOql("yuanxuegui@163.com", PageRequest.of(0, 20, Sort.Direction.DESC, "id")); assertNotNull(page); } }