answer
stringlengths
17
10.2M
package curling; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import javax.swing.JPanel; public class House extends JPanel implements MouseListener { private ArrayList<Stone> stones; private HouseLayout layout; protected PropertyChangeSupport propertyChangeSupport; public House() { // The house starts with 0 stones, and stones are added as players // send them in. stones = new ArrayList<Stone>(); // GUI related propertyChangeSupport = new PropertyChangeSupport(this); addMouseListener(this); } public void addStone(Stone stone) { stones.add(stone); } public HashMap<Team, Integer> calcScore() { HashMap<Team, Integer> result = new HashMap<Team, Integer>(); result.put(Team.HOME, 0); result.put(Team.AWAY, 0); if (stones.size() > 0) { Collections.sort(stones); Stone baseStone = stones.get(0); Team currentTeam = null; for (Stone stone : stones) { currentTeam = stone.getTeam(); if (baseStone.compareTo(stone) == 0 && baseStone.getTeam() != currentTeam) { result.put(baseStone.getTeam(), 0); break; } else if (currentTeam != baseStone.getTeam()) { break; } else { result.put(currentTeam, result.get(currentTeam) + 1); } } } return result; } // These getters/setters are for use by unit tests only. public ArrayList<Stone> getStones() { return stones; } public String toString() { String output = ""; for (Stone stone : stones) { output += stone + ", "; } return output; } public void reset() { stones.clear(); } public void paintComponent(Graphics g){ HouseLayout layout = new HouseLayout(); layout.draw(g); for (Stone stone : stones) { stone.draw(g); } } // Board mouse listener public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mousePressed(MouseEvent e) { if (CurlingMatch.intention != null) { Stone stone = new Stone(CurlingMatch.currentPlayer.getTeam()); stone.setPurpose(CurlingMatch.intention); stone.setPosition(e.getX(), e.getY()); addStone(stone); propertyChangeSupport.firePropertyChange("StonePlaced", null, null); } repaint(); } public void addPropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.addPropertyChangeListener(listener); } }
package command; import server.Config; /** * The command that sends a random fish slapping message. * @author Kevin * */ public class SlapCmd extends Command{ private static final String COMMAND = "/slap"; private String returnMessage; private String returnChannel; private String logMessage; private String errorMessage; public SlapCmd() { super(COMMAND); } @Override public CmdResult doRequest(RequestStruct req) { returnChannel = req.getChannelName(); String[] args = req.getArgs(); // assign the victim String victim; if(args.length == 1){ victim = args[0]; } else{ //no args means slap self. victim = req.getUserName(); } String perp = req.getUserName(); double[] probs = {0.8, 0.15, 0.04, 0.01}; int index = Rand.randArray(probs); //randomly select message to send back. if (index == 0){ returnMessage = perp + " slaps " + victim + " around a bit with a large trout."; } else if (index == 1){ returnMessage = perp + " slaps " + victim + " around a bit with a large fat trout."; } else if (index == 2){ returnMessage = perp + " slaps " + victim + " around a bit with a rainbow trout! Fabulous!"; } else if (index == 3){ returnMessage = Config.getBotName() + " slaps " + victim + " with a " + perp + "! Critical hit! 5x Combo!"; } return CmdResult.SUCCESS_NO_REPORT; } @Override public String getReturnMessage() { return returnMessage; } @Override public String getReturnChannel() { return returnChannel; } @Override public String getLogMessage() { return logMessage; } @Override public String getErrorMessage() { return errorMessage; } }
package org.apache.ecs; import static org.junit.Assert.assertEquals; import org.apache.ecs.filter.CharacterFilter; import org.apache.ecs.html.Body; import org.apache.ecs.html.Font; import org.apache.ecs.html.H1; import org.apache.ecs.html.H3; import org.apache.ecs.html.Head; import org.apache.ecs.html.Html; import org.apache.ecs.html.Option; import org.apache.ecs.html.Title; import org.apache.ecs.xml.XML; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HtmlGenTest { private static final Logger LOG = LoggerFactory.getLogger(HtmlGenTest.class); @Test public void testHtmlGeneration() { Option optionElement = new Option(); optionElement.setTagText("bar"); optionElement.setValue("foo"); optionElement.setSelected(false); assertEquals("<option value='foo'>bar</option>", optionElement.toString()); Document doc = new Document(); // doc.setCodeset(); doc.appendBody(optionElement); // doc.appendBody(new P().addElement("&")); String result = doc.toString(); LOG.debug(result); assertEquals("<html><head><title></title></head><body><option value='foo'>bar</option></body></html>", result); } @Test public void testHtmlGeneration2() { Html html = new Html() .addElement(new Head() .addElement(new Title("Demo"))) .addElement(new Body() .addElement(new H1("Demo Header")) .addElement(new H3("Sub Header:")) .addElement(new Font().setSize("+1") .setColor(HtmlColor.WHITE) .setFace("Times") .addElement("The big dog & the little cat chased each other."))); assertEquals("<html><head><title>Demo</title></head>" + "<body><h1>Demo Header</h1><h3>Sub Header:</h3>" + "<font color='#FFFFFF' face='Times' size='+1'>" + "The big dog & the little cat chased each other.</font></body></html>", html.toString()); } @Test public void testHtmlGeneration3() { Document doc = (Document) new Document() .appendTitle("Demo") .appendBody(new H1("Demo Header")) .appendBody(new H3("Sub Header:")) .appendBody(new Font().setSize("+1") .setColor(HtmlColor.WHITE) .setFace("Times") .setTagText("The big dog & the little cat chased each other.")); assertEquals("<html><head><title>Demo</title></head>" + "<body><h1>Demo Header</h1><h3>Sub Header:</h3>" + "<font color='#FFFFFF' face='Times' size='+1'>" + "The big dog & the little cat chased each other.</font></body></html>", doc.toString()); } @Test public void testCustomElement() { Document doc = new Document(); doc.appendBody(new XML("customElement")); String result = doc.toString(); LOG.debug(result); assertEquals("<html><head><title></title></head><body><customElement></customElement></body></html>", result); } }
package net.somethingdreadful.MAL; import java.util.ArrayList; import java.util.Calendar; import net.somethingdreadful.MAL.NavigationItems.NavItem; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.api.MALApi.ListType; import net.somethingdreadful.MAL.api.response.Anime; import net.somethingdreadful.MAL.api.response.Manga; import net.somethingdreadful.MAL.sql.MALSqlHelper; import net.somethingdreadful.MAL.tasks.AnimeNetworkTask; import net.somethingdreadful.MAL.tasks.AnimeNetworkTaskFinishedListener; import net.somethingdreadful.MAL.tasks.MangaNetworkTask; import net.somethingdreadful.MAL.tasks.MangaNetworkTaskFinishedListener; import net.somethingdreadful.MAL.tasks.TaskJob; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.NotificationCompat; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.ViewFlipper; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockDialogFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.sherlock.navigationdrawer.compat.SherlockActionBarDrawerToggle; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; public class Home extends BaseActionBarSearchView implements ActionBar.TabListener, ItemGridFragment.IItemGridFragment, LogoutConfirmationDialogFragment.LogoutConfirmationDialogListener { /** * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the * sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will * keep every loaded fragment in memory. If this becomes too memory intensive, it may be best * to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}. */ HomeSectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; Context context; PrefManager mPrefManager; public MALManager mManager; private boolean init = false; ItemGridFragment af; ItemGridFragment mf; public boolean instanceExists; boolean networkAvailable; BroadcastReceiver networkReceiver; MenuItem searchItem; int AutoSync = 0; //run or not to run. private DrawerLayout mDrawerLayout; private ListView listView; private SherlockActionBarDrawerToggle mDrawerToggle; private ActionBarHelper mActionBar; View mActiveView; View mPreviousView; boolean myList = true; //tracks if the user is on 'My List' or not private NavigationItemAdapter mNavigationItemAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getApplicationContext(); mPrefManager = new PrefManager(context); init = mPrefManager.getInit(); //The following is state handling code instanceExists = savedInstanceState != null && savedInstanceState.getBoolean("instanceExists", false); networkAvailable = savedInstanceState == null || savedInstanceState.getBoolean("networkAvailable", true); if (savedInstanceState != null) { AutoSync = savedInstanceState.getInt("AutoSync"); } if (init) { setContentView(R.layout.activity_home); // Creates the adapter to return the Animu and Mango fragments mSectionsPagerAdapter = new HomeSectionsPagerAdapter(getSupportFragmentManager()); mDrawerLayout= (DrawerLayout)findViewById(R.id.drawer_layout); mDrawerLayout.setDrawerListener(new DemoDrawerListener()); mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); listView = (ListView)findViewById(R.id.left_drawer); NavigationItems mNavigationContent = new NavigationItems(); mNavigationItemAdapter = new NavigationItemAdapter(this, R.layout.item_navigation, mNavigationContent.ITEMS); listView.setAdapter(mNavigationItemAdapter); listView.setOnItemClickListener(new DrawerItemClickListener()); listView.setCacheColorHint(0); listView.setScrollingCacheEnabled(false); listView.setScrollContainer(false); listView.setFastScrollEnabled(true); listView.setSmoothScrollbarEnabled(true); mActionBar = createActionBarHelper(); mActionBar.init(); mDrawerToggle = new SherlockActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer_light, R.string.drawer_open, R.string.drawer_close); mDrawerToggle.syncState(); mManager = new MALManager(context); // Set up the action bar. final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setPageMargin(32); // When swiping between different sections, select the corresponding // tab. // We can also use ActionBar.Tab#select() to do this if we have a // reference to the // Tab. mViewPager .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); // Add tabs for the anime and manga lists for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title // defined by the adapter. // Also specify this Activity object, which implements the // TabListener interface, as the // listener for when this tab is selected. actionBar.addTab(actionBar.newTab() .setText(mSectionsPagerAdapter.getPageTitle(i)) .setTabListener(this)); } networkReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { checkNetworkAndDisplayCrouton(); } }; } else { //If the app hasn't been configured, take us to the first run screen to sign in. Intent firstRunInit = new Intent(this, FirstTimeInit.class); firstRunInit.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(firstRunInit); finish(); } NfcHelper.disableBeam(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.activity_home, menu); searchItem = menu.findItem(R.id.action_search); super.onCreateOptionsMenu(menu); return true; } @Override public MALApi.ListType getCurrentListType() { String listName = getSupportActionBar().getSelectedTab().getText().toString(); return MALApi.getListTypeByString(listName); } public boolean isConnectedWifi() { ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo Wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (Wifi.isConnected()&& mPrefManager.getonly_wifiEnabled() ) { return true; } else { return false; } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } switch (item.getItemId()) { case R.id.menu_settings: startActivity(new Intent(this, Settings.class)); break; case R.id.menu_logout: showLogoutDialog(); break; case R.id.menu_about: startActivity(new Intent(this, AboutActivity.class)); break; case R.id.listType_all: if (af != null && mf != null) { af.getRecords(TaskJob.GETLIST, context, 0); mf.getRecords(TaskJob.GETLIST, context, 0); supportInvalidateOptionsMenu(); } break; case R.id.listType_inprogress: if (af != null && mf != null) { af.getRecords(TaskJob.GETLIST, context, 1); mf.getRecords(TaskJob.GETLIST, context, 1); supportInvalidateOptionsMenu(); } break; case R.id.listType_completed: if (af != null && mf != null) { af.getRecords(TaskJob.GETLIST, context, 2); mf.getRecords(TaskJob.GETLIST, context, 2); supportInvalidateOptionsMenu(); } break; case R.id.listType_onhold: if (af != null && mf != null) { af.getRecords(TaskJob.GETLIST, context, 3); mf.getRecords(TaskJob.GETLIST, context, 3); supportInvalidateOptionsMenu(); } break; case R.id.listType_dropped: if (af != null && mf != null) { af.getRecords(TaskJob.GETLIST, context, 4); mf.getRecords(TaskJob.GETLIST, context, 4); supportInvalidateOptionsMenu(); } break; case R.id.listType_planned: if (af != null && mf != null) { af.getRecords(TaskJob.GETLIST, context, 5); mf.getRecords(TaskJob.GETLIST, Home.this.context, 5); supportInvalidateOptionsMenu(); } break; case R.id.forceSync: if (af != null && mf != null) { af.getRecords(TaskJob.FORCESYNC, context, af.currentList); mf.getRecords(TaskJob.FORCESYNC, context, mf.currentList); syncNotify(); } break; } return super.onOptionsItemSelected(item); } @Override public void onResume() { super.onResume(); checkNetworkAndDisplayCrouton(); if (instanceExists && af.getMode() == TaskJob.GETLIST) { af.getRecords(TaskJob.GETLIST, context, af.currentList); mf.getRecords(TaskJob.GETLIST, context, mf.currentList); } registerReceiver(networkReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")); if (mSearchView != null) { mSearchView.clearFocus(); mSearchView.setFocusable(false); mSearchView.setQuery("", false); searchItem.collapseActionView(); } } @Override public void onPause() { super.onPause(); instanceExists = true; unregisterReceiver(networkReceiver); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in the ViewPager. mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void fragmentReady() { //Interface implementation for knowing when the dynamically created fragment is finished loading //We use instantiateItem to return the fragment. Since the fragment IS instantiated, the method returns it. af = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 0); mf = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 1); af.setRecordType(ListType.ANIME); mf.setRecordType(ListType.MANGA); //Set myList to if we are on the user's personal list or not myList = (af.getMode() == TaskJob.GETLIST); //auto-sync stuff if (mPrefManager.getsync_time_last() == 0 && AutoSync == 0 && networkAvailable == true){ mPrefManager.setsync_time_last(1); mPrefManager.commitChanges(); synctask(); } else if (mPrefManager.getsynchronisationEnabled() && AutoSync == 0 && networkAvailable == true){ Calendar localCalendar = Calendar.getInstance(); int Time_now = localCalendar.get(Calendar.DAY_OF_YEAR)*24*60; //will reset on new year ;) Time_now = Time_now + localCalendar.get(Calendar.HOUR_OF_DAY)*60; Time_now = Time_now + localCalendar.get(Calendar.MINUTE); int last_sync = mPrefManager.getsync_time_last(); if (last_sync >= Time_now && last_sync <= (Time_now + mPrefManager.getsync_time())){ //no sync needed (This is inside the time range) }else{ if (mPrefManager.getonly_wifiEnabled() == false){ synctask(); mPrefManager.setsync_time_last(Time_now + mPrefManager.getsync_time()); }else if (mPrefManager.getonly_wifiEnabled() && isConnectedWifi()){ //connected to Wi-Fi and sync only on Wi-Fi checked. synctask(); mPrefManager.setsync_time_last(Time_now + mPrefManager.getsync_time()); } } mPrefManager.commitChanges(); } } public void synctask(){ af.getRecords(TaskJob.FORCESYNC, context, af.currentList); mf.getRecords(TaskJob.FORCESYNC, context, mf.currentList); syncNotify(); AutoSync = 1; } @Override public void onSaveInstanceState(Bundle state) { //This is telling out future selves that we already have some things and not to do them state.putBoolean("instanceExists", true); state.putBoolean("networkAvailable", networkAvailable); state.putInt("AutoSync", AutoSync); super.onSaveInstanceState(state); } @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem item = menu.findItem(R.id.menu_listType); if(!myList){//if not on my list then disable menu items like listType, etc item.setEnabled(false); item.setVisible(false); } else{ item.setEnabled(true); item.setVisible(true); } if (af != null) { //All this is handling the ticks in the switch list menu switch (af.currentList) { case 0: menu.findItem(R.id.listType_all).setChecked(true); break; case 1: menu.findItem(R.id.listType_inprogress).setChecked(true); break; case 2: menu.findItem(R.id.listType_completed).setChecked(true); break; case 3: menu.findItem(R.id.listType_onhold).setChecked(true); break; case 4: menu.findItem(R.id.listType_dropped).setChecked(true); break; case 5: menu.findItem(R.id.listType_planned).setChecked(true); } } if (networkAvailable) { if (myList){ menu.findItem(R.id.forceSync).setVisible(true); }else{ menu.findItem(R.id.forceSync).setVisible(false); } menu.findItem(R.id.action_search).setVisible(true); } else { menu.findItem(R.id.forceSync).setVisible(false); menu.findItem(R.id.action_search).setVisible(false); AutoSync = 1; } return true; } @SuppressLint("NewApi") @Override public void onLogoutConfirmed() { mPrefManager.setInit(false); mPrefManager.setUser(""); mPrefManager.setPass(""); mPrefManager.commitChanges(); context.deleteDatabase(MALSqlHelper.getHelper(context).getDatabaseName()); startActivity(new Intent(this, Home.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); finish(); } private void syncNotify() { Crouton.makeText(this, R.string.crouton_info_SyncMessage, Style.INFO).show(); Intent notificationIntent = new Intent(context, Home.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification syncNotification = new NotificationCompat.Builder(context).setOngoing(true) .setContentIntent(contentIntent) .setSmallIcon(R.drawable.icon) .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.crouton_info_SyncMessage)) .getNotification(); nm.notify(R.id.notification_sync, syncNotification); myList = true; supportInvalidateOptionsMenu(); } private void showLogoutDialog() { FragmentManager fm = getSupportFragmentManager(); LogoutConfirmationDialogFragment lcdf = new LogoutConfirmationDialogFragment(); if (Build.VERSION.SDK_INT >= 11) { lcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Dialog); } else { lcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, 0); } lcdf.show(fm, "fragment_LogoutConfirmationDialog"); } public void checkNetworkAndDisplayCrouton() { if (!MALApi.isNetworkAvailable(context) && networkAvailable == true) { Crouton.makeText(this, R.string.crouton_error_noConnectivityOnRun, Style.ALERT).show(); af = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 0); mf = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 1); if (af.getMode() != null) { af.setMode(null); mf.setMode(null); af.getRecords(TaskJob.GETLIST, context, af.currentList); mf.getRecords(TaskJob.GETLIST, context, mf.currentList); } } else if (MALApi.isNetworkAvailable(context) && networkAvailable == false) { Crouton.makeText(this, R.string.crouton_info_connectionRestored, Style.INFO).show(); synctask(); } if (!MALApi.isNetworkAvailable(context)) { networkAvailable = false; } else { networkAvailable = true; } supportInvalidateOptionsMenu(); } /*private classes for nav drawer*/ private ActionBarHelper createActionBarHelper() { return new ActionBarHelper(); } public class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { /* do stuff when drawer item is clicked here */ af.scrollToTop(); mf.scrollToTop(); if (!networkAvailable && position > 2) { position = 1; Crouton.makeText(Home.this, R.string.crouton_error_noConnectivity, Style.ALERT).show(); } myList = (position == 1); switch (position){ case 0: Intent Profile = new Intent(context, net.somethingdreadful.MAL.ProfileActivity.class); Profile.putExtra("username", mPrefManager.getUser()); startActivity(Profile); break; case 1: af.getRecords(TaskJob.GETLIST, Home.this.context, af.currentList); mf.getRecords(TaskJob.GETLIST, Home.this.context, mf.currentList); break; case 2: Intent Friends = new Intent(context, net.somethingdreadful.MAL.FriendsActivity.class); startActivity(Friends); break; case 3: af.getRecords(TaskJob.GETTOPRATED, Home.this.context); mf.getRecords(TaskJob.GETTOPRATED, Home.this.context); af.scrollListener.resetPageNumber(); mf.scrollListener.resetPageNumber(); break; case 4: af.getRecords(TaskJob.GETMOSTPOPULAR, Home.this.context); mf.getRecords(TaskJob.GETMOSTPOPULAR, Home.this.context); af.scrollListener.resetPageNumber(); mf.scrollListener.resetPageNumber(); break; case 5: af.getRecords(TaskJob.GETJUSTADDED, Home.this.context); mf.getRecords(TaskJob.GETJUSTADDED, Home.this.context); af.scrollListener.resetPageNumber(); mf.scrollListener.resetPageNumber(); break; case 6: af.getRecords(TaskJob.GETUPCOMING, Home.this.context); mf.getRecords(TaskJob.GETUPCOMING, Home.this.context); af.scrollListener.resetPageNumber(); mf.scrollListener.resetPageNumber(); break; } Home.this.supportInvalidateOptionsMenu(); //This part is for figuring out which item in the nav drawer is selected and highlighting it with colors mPreviousView = mActiveView; if (mPreviousView != null) mPreviousView.setBackgroundColor(Color.parseColor("#333333")); //dark color mActiveView = view; mActiveView.setBackgroundColor(Color.parseColor("#38B2E1")); //blue color mDrawerLayout.closeDrawer(listView); } } private class DemoDrawerListener implements DrawerLayout.DrawerListener { @Override public void onDrawerOpened(View drawerView) { mDrawerToggle.onDrawerOpened(drawerView); mActionBar.onDrawerOpened(); } @Override public void onDrawerClosed(View drawerView) { mDrawerToggle.onDrawerClosed(drawerView); mActionBar.onDrawerClosed(); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { mDrawerToggle.onDrawerSlide(drawerView, slideOffset); } @Override public void onDrawerStateChanged(int newState) { mDrawerToggle.onDrawerStateChanged(newState); } } private class ActionBarHelper { private final ActionBar mActionBar; private CharSequence mDrawerTitle; private CharSequence mTitle; private ActionBarHelper() { mActionBar = getSupportActionBar(); } public void init() { mActionBar.setDisplayHomeAsUpEnabled(true); mActionBar.setHomeButtonEnabled(true); mTitle = mDrawerTitle = getTitle(); } /** * When the drawer is closed we restore the action bar state reflecting * the specific contents in view. */ public void onDrawerClosed() { mActionBar.setTitle(mTitle); } /** * When the drawer is open we set the action bar to a generic title. The * action bar should only contain data relevant at the top level of the * nav hierarchy represented by the drawer, as the rest of your content * will be dimmed down and non-interactive. */ public void onDrawerOpened() { mActionBar.setTitle(mDrawerTitle); } } private class NavigationItemAdapter extends ArrayAdapter<NavItem> { private ArrayList<NavItem> items; public NavigationItemAdapter(Context context, int textViewResourceId, ArrayList<NavItem> objects) { super(context, textViewResourceId, objects); this.items = objects; } public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = getLayoutInflater(); v = vi.inflate(R.layout.item_navigation, null); } NavItem item = items.get(position); if (item != null) { ImageView mIcon = (ImageView) v .findViewById(R.id.nav_item_icon); TextView mTitle = (TextView) v.findViewById(R.id.nav_item_text); if (mIcon != null) { mIcon.setImageResource(item.icon); } else { Log.d("LISTITEM", "Null"); } if (mTitle != null) { mTitle.setText(item.title); } else { Log.d("LISTITEM", "Null"); } } return v; } } }
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); DefaultListModel<String> model = new DefaultListModel<>(); model.addElement("11\n1"); model.addElement("222222222222222\n222222222222222"); model.addElement("3333333333333333333\n33333333333333333333\n33333333333333333"); model.addElement("444"); JList<String> list = new JList<String>(model) { private transient MouseAdapter cbml; @Override public void updateUI() { removeMouseListener(cbml); removeMouseMotionListener(cbml); super.updateUI(); setFixedCellHeight(-1); cbml = new CellButtonsMouseListener(this); addMouseListener(cbml); addMouseMotionListener(cbml); setCellRenderer(new ButtonsRenderer<String>(model)); } }; add(new JScrollPane(list)); setPreferredSize(new Dimension(320, 240)); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class CellButtonsMouseListener extends MouseAdapter { private int prevIndex = -1; private JButton prevButton; private final JList<String> list; protected CellButtonsMouseListener(JList<String> list) { super(); this.list = list; } @Override public void mouseMoved(MouseEvent e) { //JList list = (JList) e.getComponent(); Point pt = e.getPoint(); int index = list.locationToIndex(pt); if (!list.getCellBounds(index, index).contains(pt)) { if (prevIndex >= 0) { listRepaint(list, list.getCellBounds(prevIndex, prevIndex)); } index = -1; prevButton = null; return; } if (index >= 0) { JButton button = getButton(list, pt, index); ButtonsRenderer renderer = (ButtonsRenderer) list.getCellRenderer(); renderer.button = button; if (Objects.nonNull(button)) { button.getModel().setRollover(true); renderer.rolloverIndex = index; if (!button.equals(prevButton)) { listRepaint(list, list.getCellBounds(prevIndex, index)); } } else { renderer.rolloverIndex = -1; Rectangle r = null; if (prevIndex == index) { if (prevIndex >= 0 && Objects.nonNull(prevButton)) { r = list.getCellBounds(prevIndex, prevIndex); } } else { r = list.getCellBounds(index, index); } listRepaint(list, r); prevIndex = -1; } prevButton = button; } prevIndex = index; } @Override public void mousePressed(MouseEvent e) { //JList list = (JList) e.getComponent(); Point pt = e.getPoint(); int index = list.locationToIndex(pt); if (index >= 0) { JButton button = getButton(list, pt, index); if (Objects.nonNull(button)) { ButtonsRenderer renderer = (ButtonsRenderer) list.getCellRenderer(); renderer.pressedIndex = index; renderer.button = button; listRepaint(list, list.getCellBounds(index, index)); } } } @Override public void mouseReleased(MouseEvent e) { //JList list = (JList) e.getComponent(); Point pt = e.getPoint(); int index = list.locationToIndex(pt); if (index >= 0) { JButton button = getButton(list, pt, index); if (Objects.nonNull(button)) { ButtonsRenderer renderer = (ButtonsRenderer) list.getCellRenderer(); renderer.pressedIndex = -1; renderer.button = null; button.doClick(); listRepaint(list, list.getCellBounds(index, index)); } } } private static void listRepaint(JList list, Rectangle rect) { if (Objects.nonNull(rect)) { list.repaint(rect); } } private static JButton getButton(JList<String> list, Point pt, int index) { Component c = list.getCellRenderer().getListCellRendererComponent(list, "", index, false, false); Rectangle r = list.getCellBounds(index, index); c.setBounds(r); //c.doLayout(); //may be needed for mone LayoutManager pt.translate(-r.x, -r.y); Component b = SwingUtilities.getDeepestComponentAt(c, pt.x, pt.y); if (b instanceof JButton) { return (JButton) b; } else { return null; } } } class ButtonsRenderer<E> extends JPanel implements ListCellRenderer<E> { private static final Color EVEN_COLOR = new Color(230, 255, 230); private final JTextArea textArea = new JTextArea(); private final JButton deleteButton = new JButton(new AbstractAction("delete") { @Override public void actionPerformed(ActionEvent e) { if (model.getSize() > 1) { model.remove(index); } } }); private final JButton copyButton = new JButton(new AbstractAction("copy") { @Override public void actionPerformed(ActionEvent e) { model.add(index, model.get(index)); } }); private final DefaultListModel<E> model; private int index; public int pressedIndex = -1; public int rolloverIndex = -1; public JButton button; protected ButtonsRenderer(DefaultListModel<E> model) { super(new BorderLayout()); this.model = model; setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 0)); setOpaque(true); textArea.setLineWrap(true); textArea.setOpaque(false); add(textArea); Box box = Box.createHorizontalBox(); for (JButton b: Arrays.asList(deleteButton, copyButton)) { b.setFocusable(false); b.setRolloverEnabled(false); box.add(b); box.add(Box.createHorizontalStrut(5)); } add(box, BorderLayout.EAST); } @Override public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); d.width = 0; // VerticalScrollBar as needed return d; } @Override public Component getListCellRendererComponent(JList<? extends E> list, E value, int index, boolean isSelected, boolean cellHasFocus) { textArea.setText(Objects.toString(value, "")); this.index = index; if (isSelected) { setBackground(list.getSelectionBackground()); textArea.setForeground(list.getSelectionForeground()); } else { setBackground(index % 2 == 0 ? EVEN_COLOR : list.getBackground()); textArea.setForeground(list.getForeground()); } resetButtonStatus(); if (Objects.nonNull(button)) { if (index == pressedIndex) { button.getModel().setSelected(true); button.getModel().setArmed(true); button.getModel().setPressed(true); } else if (index == rolloverIndex) { button.getModel().setRollover(true); } } return this; } private void resetButtonStatus() { for (JButton b: Arrays.asList(deleteButton, copyButton)) { ButtonModel m = b.getModel(); m.setRollover(false); m.setArmed(false); m.setPressed(false); m.setSelected(false); } } }
package grok.core; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Multimaps; import com.google.common.collect.SetMultimap; @AutoValue public abstract class ClimbingGrade implements Comparable<ClimbingGrade> { public enum System { YDS, /** * Used in the vast majority of European countries and in many international events outside the USA. */ FRENCH, /** * Used in Australia and New Zealand. */ EWBANK, /** * Used in South Africa. */ EWBANK_SOUTH_AFRICA, /** * Used in Germany, Austria, Switzerland, Czech Republic, Slovakia, and Hungary. */ UIAA, /** * A.K.A. UK grading system. * <p> * Used in Great Britain and Ireland. */ BRITISH; } public static ClimbingGrade yds(String value) { return of(value, System.YDS); } public static ClimbingGrade french(String value) { return of(value, System.FRENCH); } public static ClimbingGrade of(String value, System system) { for (ClimbingGrade maybe : KNOWN) { if (maybe.matches(system, value)) { return maybe; } } throw new IllegalArgumentException(value + " does not exist for " + system); } // TODO(achaphiv): expose? @JsonCreator static ClimbingGrade of(Map<System, Set<String>> values) { for (ClimbingGrade maybe : KNOWN) { if (maybe.valuesMap().equals(values)) { return maybe; } } throw new IllegalArgumentException(values + " is not a valid combination"); } //@formatter:off private static final List<ClimbingGrade> KNOWN = Arrays.asList( known("5.1 ", "2 ", "7 ", "8 ", "III- ", "M "), known("5.2 ", "2+ ", "8 ", "9 ", "III ", "D "), known("5.3 ", "3 ", "9/10 ", "10 ", "III+ ", "VD 3a "), known("5.4 ", "3/4a ", "11 ", "12 ", "IV- ", "VD/HVD 3b"), known("5.5 ", "4b ", "12 ", "13 ", "IV ", "HVD/S 3c "), known("5.6 ", "4c ", "13 ", "14 ", "IV+/V- ", "MS 4a "), known("5.7 ", "5a ", "14/15", "15 ", "V-/V ", "S/HS 4b "), known("5.8 ", "5b ", "15/16", "16 ", "V+/VI- ", "HS/VS 4b "), known("5.9 ", "5c ", "17 ", "17/18", "VI-/VI ", "HVS 4c "), known("5.10a", "6a ", "18 ", "19 ", "VI/VI+ ", "HVS 5a "), known("5.10b", "6a+ ", "19 ", "20 ", "VII- ", "E1 5a "), known("5.10c", "6b ", "20 ", "21 ", "VII-/VII ", "E1 5b "), known("5.10d", "6b+ ", "20/21", "22 ", "VII/VII+ ", "E2 5b "), known("5.11a", "6c ", "21 ", "22/23", "VII+ ", "E2 5c "), known("5.11b", "6c/6c+", "22 ", "23/24", "VIII- ", "E3 5c "), known("5.11c", "6c+ ", "22/23", "24 ", "VIII ", "E3 6a "), known("5.11d", "7a ", "23 ", "25 ", "VIII/VIII+", "E4 6a "), known("5.12a", "7a+ ", "24 ", "26 ", "VIII+ ", "E4 6b "), known("5.12b", "7b ", "25 ", "27 ", "IX- ", "E5 6b "), known("5.12c", "7b+ ", "26 ", "28 ", "IX-/IX ", "E5/E6 6b "), known("5.12d", "7c ", "27 ", "29 ", "IX/IX+ ", "E6 6b "), known("5.13a", "7c+ ", "28 ", "30 ", "IX+ ", "E6 6c "), known("5.13b", "8a ", "29 ", "31 ", "X- ", "E7 6c "), known("5.13c", "8a+ ", "30 ", "32 ", "X-/X ", "E7 7a "), known("5.13d", "8b ", "31 ", "33 ", "X/X+ ", "E8 7a "), known("5.14a", "8b+ ", "32 ", "34 ", "X+ ", "E8 7b "), known("5.14b", "8c ", "33 ", "35 ", "XI- ", "E9 7b "), known("5.14c", "8c+ ", "34 ", "36 ", "XI ", "E10 7b "), known("5.14d", "9a ", "35 ", "37 ", "XI+ ", "E10 7c "), known("5.15a", "9a+ ", "36 ", "38 ", "XI+/XII- ", "E11 7c "), known("5.15b", "9b ", "37 ", "39 ", "XII-/XII ", "E11 8a "), known("5.15c", "9b+ ", "38 ", "40 ", "XII ", "E11 8b "), known("5.15d", "9c ", "39 ", "41 ", "XII+ ", "E11 8c ")); //@formatter:on private static ClimbingGrade known(String usa, String france, String ewbank, String ewbankSouthAfrica, String uiaa, String british) { return new AutoValue_ClimbingGrade(ImmutableSetMultimap.<System, String> builder() .putAll(System.YDS, split(usa)) .putAll(System.FRENCH, split(france)) .putAll(System.EWBANK, split(ewbank)) .putAll(System.EWBANK_SOUTH_AFRICA, split(ewbankSouthAfrica)) .putAll(System.UIAA, split(uiaa)) .putAll(System.BRITISH, split(british)) .build()); } private static String[] split(String value) { return value.trim().split("/"); } ClimbingGrade() {} abstract SetMultimap<System, String> values(); // TODO(achaphiv): expose? @JsonValue Map<System, Set<String>> valuesMap() { return Multimaps.asMap(values()); } private boolean matches(System country, String value) { return values().get(country).contains(value); } @Override public int compareTo(ClimbingGrade other) { return Integer.compare(KNOWN.indexOf(this), KNOWN.indexOf(other)); } }
package h2o.dao.advanced; import h2o.common.util.collections.CollectionUtil; import h2o.common.util.lang.StringUtil; import h2o.dao.Dao; import h2o.dao.DbUtil; import java.util.List; public final class DaoBasicUtil { private final Dao dao; public DaoBasicUtil() { this.dao = DbUtil.getDao(); } public DaoBasicUtil( Dao dao ) { this.dao = dao; } public void add( Object entity ) { dao.update( DbUtil.sqlBuilder.buildInsertSql(entity) , entity ); } public void batAdd( List<Object> entities ) { dao.update( DbUtil.sqlBuilder.buildInsertSqlIncludeNull(entities.get(0)) , entities ); } public int edit( AbstractEntity entity ) { return dao.update( DbUtil.sqlBuilder.buildUpdateSql3( entity , entity.get_w() , entity.get_pks() ) , entity ); } public int edit( AbstractEntity entity , String w , Object... args ) { Object[] para; if( CollectionUtil.argsIsBlank( args ) ) { para = new Object[] { entity }; } else { para = new Object[ args.length + 1 ]; para[0] = entity; System.arraycopy( args , 0 , para , 1 , args.length ); } return dao.update( DbUtil.sqlBuilder.buildUpdateSql3( entity , w , entity.get_pks() ) , para ); } public int del( AbstractEntity entity ) { return dao.update( "delete from " + entity.get_tableName() + " where " + entity.get_w() , entity ); } public <T extends AbstractEntity> T get( T entity ) { return this.get( entity , false ); } public <T extends AbstractEntity> T getAndLock( T entity ) { return this.get( entity , true ); } public <T extends AbstractEntity> T get( T entity , boolean lock ) { StringBuilder sql = new StringBuilder(); StringUtil.append( sql , "select * from " , entity.get_tableName() , " where " , entity.get_w() ); if( lock ) { sql.append(" for update "); } return (T)dao.get( entity.getClass() , sql.toString() , entity ); } }
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; public class GameEngine extends JPanel implements MouseListener, MouseMotionListener, ActionListener, KeyListener { private final Font currentlySelectedLabelFont = new Font("Consola", Font.BOLD, 23); private final Font territoryArmyCountLabelFont = new Font("Consola", Font.ITALIC, 18); private final Font turnNumberLabelFont = new Font("Consola", Font.BOLD, 22); private final Font newTurnBoxInfoLabelFont = new Font("Consola", Font.BOLD, 36); private final Font turnPhaseLabelFont = new Font("Consola", Font.BOLD, 14); private final Timer timer = new Timer(16, this); public Territory currentlySelected = null; public Territory shiftSelected = null; public String currentlySelectedName = ""; PlayField gameData; Gamer humanPlayer1 = new Gamer(new Color((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255)), true, "Human Player 1"); Gamer computerPlayer1 = new Gamer(new Color((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255)), false, "CPU Player 1"); int turnNumber = 0; boolean displayWelcomeSplashBox = true; int welcomeSplashBoxTickTimer = 0; boolean paintNewTurnBox = false; int newTurnBoxTickTimer = 0; boolean newTurn = false; boolean reinforceMentPhase = false; boolean attackPhase = false; boolean computerAttackPhase = false; boolean humanIsDoneReinforcing = false; boolean shiftKeyIsPressed = false; JButton attackBttn = new JButton("Attack/Reinforce"); JButton endTurnBttn = new JButton("End Turn"); public GameEngine() { gameData = new PlayField(); try { File mapData = new File("/Users/bokense1/Desktop/Risk 2/src/world.map"); gameData.loadData(mapData); } catch (FileNotFoundException e) { e.printStackTrace(); } System.out.println("[Dev] Done loading all gamedata..."); addMouseListener(this); addMouseMotionListener(this); addKeyListener(this); // Adds keyboard listener. this.add(attackBttn); this.add(endTurnBttn); attackBttn.setVisible(false); attackBttn.setVisible(false); attackBttn.addActionListener(this); endTurnBttn.addActionListener(this); attackBttn.setFocusable(true); endTurnBttn.setFocusable(true); setFocusable(true); // Setting required for keyboard listener. timer.start(); } private void fight(Territory currentlySelected, Territory shiftSelected) { String str = JOptionPane.showInputDialog(this, "How many units to attack with? (1-" + (currentlySelected.army - 1) + ")", null); int numberOfAttackers = str == null ? 0 : Integer.parseInt(str); if (numberOfAttackers != 0 && numberOfAttackers < currentlySelected.getArmyCount()) { if (numberOfAttackers > shiftSelected.getArmyCount()) { System.out.println(currentlySelected.getName() + " wins"); String inputStr = null; int numberOfTransfer = -1; // Prompts the user until they make a valid post-combat-victory transfer. while (numberOfTransfer < 0 || numberOfTransfer > numberOfAttackers) { inputStr = JOptionPane.showInputDialog(this, "How many units to take transfer with? (1-" + (numberOfAttackers - 1) + ")", null); numberOfTransfer = inputStr == null ? 0 : Integer.parseInt(inputStr); } Gamer.getOwner(currentlySelected, computerPlayer1, humanPlayer1).captureTerritory(shiftSelected, true, numberOfTransfer); currentlySelected.army -= numberOfTransfer; Gamer.getOwner(shiftSelected, computerPlayer1, humanPlayer1).removeTerritory(shiftSelected); System.out.println(shiftSelected.getName() + " loses"); } else if (numberOfAttackers <= shiftSelected.getArmyCount()) { System.out.println(shiftSelected.getName() + " wins"); Gamer.getOwner(currentlySelected, computerPlayer1, humanPlayer1).removeTerritory(currentlySelected); Gamer.getOwner(shiftSelected, computerPlayer1, humanPlayer1).captureTerritory(currentlySelected, true); int randomTransfer = (int) (Math.random() * shiftSelected.army); currentlySelected.army += randomTransfer; shiftSelected.army -= randomTransfer; System.out.println(currentlySelected.getName() + " loses"); } } } public void paintComponent(Graphics g) { super.paintComponent(g); paintBackgroundImage(g, Color.white); paintIndicatorLines(g); // Prints all territory landmass as unclaimed. for (int i = 0; i < gameData.territory.size(); i++) { gameData.territory.get(i).printTerritory(g, "fill", currentlySelectedName, Color.lightGray); } // Draw all territories owned by human player for (int i = 0; i < humanPlayer1.myTerritory.size(); i++) { humanPlayer1.myTerritory.get(i).printTerritory(g, "fill", "", humanPlayer1.color); } // Draw all territories owned by PC player for (int i = 0; i < computerPlayer1.myTerritory.size(); i++) { computerPlayer1.myTerritory.get(i).printTerritory(g, "fill", "", computerPlayer1.color); } // Print all capital cities in black. for (int i = 0; i < gameData.territory.size(); i++) { gameData.territory.get(i).printTerritoryCapital(g, Color.black); } // Prints the outline of all territories for (int i = 0; i < gameData.territory.size(); i++) { gameData.territory.get(i).printTerritory(g, "outline", currentlySelectedName, Color.black); } // Changes the color of the capital city of the neighbours of currentlyselected to display to the user // the new possibilities of attack if (currentlySelected != null) { paintCurrentlySelectedCapitalHighlighted(g); paintCurrentlySelectedCapitalContourHighlighted(g); paintNeighbours(g); } if (shiftSelected != null) { paintShiftSelectedCapitalHighlighted(g); paintShiftSelectedCapitalContourHighlighted(g); } // Draws the number of units of each territory. for (int i = 0; i < gameData.territory.size(); i++) { g.setColor(Color.white); g.setFont(territoryArmyCountLabelFont); g.drawString(" " + gameData.territory.get(i).getArmyCount(), (int) gameData.territory.get(i).getCapital().getX(), (int) gameData.territory.get(i).getCapital().getY()); } paintCurrentlySelectedLabel(g); paintshiftSelectedLabel(g); paintTurnPhaseLabels(g); if (turnNumber != 0) { paintTurnNumberLabel(g); } if (currentlySelected != null && turnNumber != 0 && reinforceMentPhase) { int reinforcementsLeftToPlace = humanPlayer1.reinforcements - humanPlayer1.reinforcementsPlacedThisTurn; g.setFont(turnPhaseLabelFont); g.setColor(Color.black); g.drawString("Reinforcements: " + reinforcementsLeftToPlace, 609, 580); } if (newTurn) { paintGraphicsNewTurnBox(g); } if (displayWelcomeSplashBox) { paintDisplayWelcomeSplashBox(g); } } private void paintIndicatorLines(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setStroke(new BasicStroke(5)); g2d.setColor(Color.lightGray); g2d.drawLine(409, 393, 489, 309); g2d.drawLine(414, 95, 355, 121); g2d.drawLine(380, 31, 317, 61); g2d.drawLine(498, 57, 504, 74); g2d.drawLine(519, 75, 608, 75); g2d.drawLine(511, 84, 543, 118); g2d.drawLine(1156, 78, 1260, 76); g2d.drawLine(46, 82, 0, 79); } private void paintshiftSelectedLabel(Graphics g) { g.setColor(Color.BLACK); if (humanPlayer1 != null && currentlySelected != null && !humanPlayer1.myTerritory.isEmpty() && shiftSelected != null) { for (Territory t : gameData.territory) { if (shiftSelected == t) { g.setColor(Gamer.getOwner(shiftSelected, computerPlayer1, humanPlayer1).color); // set the color of the currentlyselected String label to that of the owner of currentlyselected territory } } g.setFont(currentlySelectedLabelFont); g.drawString("> " + shiftSelected.getName(), 600, 545); } } private void paintShiftSelectedCapitalHighlighted(Graphics g) { int index = 0; // Iterate through all territories until we reach currentlySelected. while (index < gameData.territory.size()) { if (gameData.territory.get(index).getName().equals(shiftSelected.getName())) { // if we find a match gameData.territory.get(index).printTerritoryCapital(g, Color.orange); } index++; } } private void paintShiftSelectedCapitalContourHighlighted(Graphics g) { int index = 0; // Iterate through all territories until we reach currentlySelected. while (index < gameData.territory.size()) { if (gameData.territory.get(index).getName().equals(shiftSelected.getName())) { // if we find a match gameData.territory.get(index).printTerritory(g, "outline", shiftSelected.getName(), Color.ORANGE); } index++; } } private void paintDisplayWelcomeSplashBox(Graphics g) { if (welcomeSplashBoxTickTimer < 100) { g.setColor(Color.lightGray); g.fillRect(0, 0, 1650, 650); g.setFont(newTurnBoxInfoLabelFont); g.setColor(Color.white); g.drawString("Welcome. Setup Phase. Capture territories.", 100, 160); } if (welcomeSplashBoxTickTimer == 100) { welcomeSplashBoxTickTimer = 0; displayWelcomeSplashBox = false; } } private void paintTurnPhaseLabels(Graphics g) { g.setFont(turnPhaseLabelFont); g.setColor(Color.black); if (reinforceMentPhase) { g.drawString("Reinforcement Phase", 416, 580); } if (attackPhase) { g.drawString("Attack Phase", 416, 580); } } private void paintGraphicsNewTurnBox(Graphics g) { System.out.println("[Dev]Painting new Turn Splash Screen"); if (newTurnBoxTickTimer < 100) { g.setColor(Color.lightGray); g.fillRect(0, 0, 1650, 650); g.setFont(newTurnBoxInfoLabelFont); g.setColor(Color.white); g.drawString(humanPlayer1.playerName + " - Your Turn", 100, 160); } if (newTurnBoxTickTimer == 100) { paintNewTurnBox = false; newTurnBoxTickTimer = 0; newTurn = false; } } private void paintTurnNumberLabel(Graphics g) { g.setFont(turnNumberLabelFont); // set font g.setColor(humanPlayer1.color); // set color of string to that of the currently active player g.drawString(humanPlayer1.playerName + " - Turn: " + turnNumber, 910, 25); // draw the string } private void paintCurrentlySelectedCapitalContourHighlighted(Graphics g) { int index = 0; // Iterate through all territories until we reach currentlySelected. while (index < gameData.territory.size()) { if (gameData.territory.get(index).getName().equals(currentlySelected.getName())) { // if we find a match gameData.territory.get(index).printTerritory(g, "outline", currentlySelected.getName(), Color.yellow); } index++; } } private void paintCurrentlySelectedCapitalHighlighted(Graphics g) { int index = 0; // Iterate through all territories until we reach currentlySelected. while (index < gameData.territory.size()) { if (gameData.territory.get(index).getName().equals(currentlySelected.getName())) { // if we find a match gameData.territory.get(index).printTerritoryCapital(g, Color.yellow); } index++; } } private void paintCurrentlySelectedLabel(Graphics g) { g.setColor(Color.BLACK); if (humanPlayer1 != null && currentlySelected != null && !humanPlayer1.myTerritory.isEmpty()) { for (Territory t : gameData.territory) { if (currentlySelected == t) { g.setColor(Gamer.getOwner(currentlySelected, computerPlayer1, humanPlayer1).color); // set the color of the currentlyselected String label to that of the owner of currentlyselected territory } } g.setFont(currentlySelectedLabelFont); g.drawString(currentlySelectedName, 415, 545); } } private void paintNeighbours(Graphics g) { int index = 0; // Iterate through all territories until we reach currentlySelected. while (index < gameData.territory.size()) { if (gameData.territory.get(index).getName().equals(currentlySelected.getName())) { // if we find a match ArrayList<Territory> neighbours = gameData.territory.get(index).getNeighbours(); // retrieve the neighbours of the currentlySelected territory for (Territory neighbour : neighbours) { // for each neighbour, print the capital city in magenta color. neighbour.printTerritoryCapital(g, Color.magenta); } } index++; } } private void paintBackgroundImage(Graphics g, Color col) { // g.setColor(col); //g.fillRect(0, 0, Main.WIDTH, Main.HEIGHT); //alternative empty background // load the png background image Image i = Toolkit.getDefaultToolkit().getImage("/Users/bokense1/Desktop/Risk 2/src/JT-1 3.png"); g.drawImage(i, 0, 0, this); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == attackBttn) { System.out.println("Attack Button Pressed"); /* Instanciate combat within two territories works if and only if: currentlySelected exist shiftselected exists the owner of currentlyselected is the human player the owner of both territories are not the same both territories are neighbours of each other */ // FIGHT if (currentlySelected != null && shiftSelected != null && currentlySelected.army > 1 && Gamer.getOwner(currentlySelected, computerPlayer1, humanPlayer1) == humanPlayer1 && Gamer.getOwner(currentlySelected, computerPlayer1, humanPlayer1) != Gamer.getOwner(shiftSelected, computerPlayer1, humanPlayer1) && currentlySelected.checkNeighbour(shiftSelected)) { System.out.println("[Dev] Fight Requested per Button"); fight(currentlySelected, shiftSelected); } /* Instanciate REINFORCE within two territories works if and only if: currentlySelected exist shiftselected exists the owner of currentlyselected is the human player the owner of both territories are the same both territories are neighbours of each other */ // REINFORCE else if (currentlySelected != null && shiftSelected != null && Gamer.getOwner(currentlySelected, computerPlayer1, humanPlayer1) == humanPlayer1 && Gamer.getOwner(currentlySelected, computerPlayer1, humanPlayer1) == Gamer.getOwner(shiftSelected, computerPlayer1, humanPlayer1) && currentlySelected.checkNeighbour(shiftSelected)) { System.out.println("[Dev] Reinforce Requested per Button"); reinforce(currentlySelected, shiftSelected); } attackBttn.setText("Attack/Reinforce"); currentlySelected = null; shiftSelected = null; } if (e.getSource() == endTurnBttn) { System.out.println("End Turn Button Pressed"); attackPhase = false; computerAttackPhase = true; } if (e.getSource() == timer) { if (computerAttackPhase) { newTurn = true; System.out.println("COMPUTER ATTACK PHASE"); System.out.println("NEW TURN"); // COMPUTER ATTACKS try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } turnNumber++; // Numerical count of turns. reinforceMentPhase = true; humanPlayer1.calculateReinforcements(); computerPlayer1.calculateReinforcements(); humanPlayer1.reinforcementsPlacedThisTurn = 0; computerPlayer1.reinforcementsPlacedThisTurn = 0; computerAttackPhase = false; } if (attackPhase) { attackBttn.setVisible(true); endTurnBttn.setVisible(true); } else { attackBttn.setVisible(false); endTurnBttn.setVisible(false); } // @trigger computer-only reinforcing. if (reinforceMentPhase && humanIsDoneReinforcing) { // if human is done reinforcing but computer is still not done reinforcing. CPU spams reinforcements until done. while (computerPlayer1.reinforcements >= computerPlayer1.reinforcementsPlacedThisTurn) { System.out.println("[Dev] CPU Reinforcements:" + computerPlayer1.reinforcements + "/" + computerPlayer1.reinforcementsPlacedThisTurn); // Computer Reinforcement inner trigger boolean reAttempt = true; while (reAttempt) { int randomTerritoryFinder = (int) (Math.random() * 42); // Chose a random number for a territory Territory randomTerritory = gameData.territory.get(randomTerritoryFinder); // Make a pointer to the territory if (Gamer.getOwner(randomTerritory, computerPlayer1, humanPlayer1) == computerPlayer1) { // if and only if the territory is owned by the computer randomTerritory.addArmy(1); // reinforce the territory computerPlayer1.reinforcementsPlacedThisTurn++; // increment the number of reinforcements placed this turn by the computer reAttempt = false; // once a reinforcement, do not reattempt to capture again } } } // @endof reinforcement phase reinforceMentPhase = false; // @startof attack phase attackPhase = true; // @endoftrigger computer-only-reinforcement humanIsDoneReinforcing = false; } //@trigger welcome screen splash screen if (displayWelcomeSplashBox) { // check if welcome screen splash screen trigger is active welcomeSplashBoxTickTimer++; // begin ticker for the trigger } //@trigger new turn splash screen if (paintNewTurnBox) { // check if paint new turn splash screen trigger is active newTurnBoxTickTimer++; // begin ticker for the trigger } //@trigger new turn checkIfNewTurn(); // check if new turn trigger is active // Repaint screen repaint(); } } private void reinforce(Territory currentlySelected, Territory shiftSelected) { String str = JOptionPane.showInputDialog(this, "How many units to reinforce? (1-" + (currentlySelected.army - 1) + ")", 0); int input = (str == null ? 0 : Integer.parseInt(str)); if (input != 0 && currentlySelected.army > input) { currentlySelected.army -= input; shiftSelected.army += input; } else { System.out.println("INVALID REINFORCEMENT"); } } private void checkIfNewTurn() { if (newTurn) { paintNewTurnBox = true; } } @Override public void mouseClicked(MouseEvent e) { requestFocusInWindow(); // Retrieves clicked coordinates. int x = e.getX(); int y = e.getY(); System.out.println("Click:" + x + "," + y); // @onclick Make primary selection if (!shiftKeyIsPressed) { // Sets/Changes the currentlySelected pointer. shiftSelected = null; // resets secondary selection for (int i = 0; i < gameData.territory.size(); i++) { if (gameData.territory.get(i).check_isInsideTerritory(x, y)) { System.out.println("Clicked on " + gameData.territory.get(i).getName()); currentlySelected = gameData.territory.get(i); currentlySelectedName = currentlySelected.getName(); break; } } } // @onclick Make secondary Selection if (attackPhase && shiftKeyIsPressed && currentlySelected != null) { for (int i = 0; i < gameData.territory.size(); i++) { if (gameData.territory.get(i).check_isInsideTerritory(x, y)) { System.out.println("Shift-Clicked on " + gameData.territory.get(i).getName()); shiftSelected = gameData.territory.get(i); break; } } // does not allow 2 selections of same territory if (shiftSelected == currentlySelected) { shiftSelected = null; } } // Changes the text of the attack button to indicate what kind of action will take place on click. if (attackPhase && currentlySelected != null && shiftSelected != null) { if (Gamer.getOwner(currentlySelected, computerPlayer1, humanPlayer1) == humanPlayer1 && Gamer.getOwner(shiftSelected, computerPlayer1, humanPlayer1) == humanPlayer1) { attackBttn.setText("REINFORCE"); } else if (Gamer.getOwner(currentlySelected, computerPlayer1, humanPlayer1) == humanPlayer1 && Gamer.getOwner(shiftSelected, computerPlayer1, humanPlayer1) != humanPlayer1) { attackBttn.setText("ATTACK"); } else { if (attackPhase) { attackBttn.setText("Attack/Reinforce"); } } } // Special case for turn 0. Territory Selection Phase. if (turnNumber == 0) { // if player clicks on an unoccupied territory. Capture it. if (currentlySelected != null && !currentlySelected.alreadyOccupied(humanPlayer1, computerPlayer1)) { humanPlayer1.captureTerritory(currentlySelected); boolean reAttempt = true; // Boolean condition used for reattempting AI placement when the randomly generated territory is already occupied while (reAttempt) { int randomTerritoryFinder = (int) (Math.random() * 42); // Chose a random territory Territory randomTerritory = gameData.territory.get(randomTerritoryFinder); // Make a pointer to the territory if (!randomTerritory.alreadyOccupied(humanPlayer1, computerPlayer1)) { // if and only if the territory is unoccupied computerPlayer1.captureTerritory(randomTerritory); // capture the territory reAttempt = false; // once a capture is sucessful, do not reattempt to capture again. } } } boolean unclaimedTerritoriesExist = false; // Assume there are no territories unclaimed and counterprove it. for (int i = 0; i < gameData.territory.size(); i++) { // iterate through all territories // if any territory is still unclaimed, continue, if all territories are claimed. end turn 0. if (!gameData.territory.get(i).alreadyOccupied(humanPlayer1, computerPlayer1)) { unclaimedTerritoriesExist = true; } } // If there are no unclaimed territories left. Begin turn 1. if (!unclaimedTerritoriesExist) { newTurn = true; // Boolean condition used for events that are triggered only during new turn transitions. System.out.println("NEW TURN"); turnNumber++; // Numerical count of turns. attackPhase = false; reinforceMentPhase = true; humanPlayer1.calculateReinforcements(); computerPlayer1.calculateReinforcements(); humanPlayer1.reinforcementsPlacedThisTurn = 0; computerPlayer1.reinforcementsPlacedThisTurn = 0; } } // End of turn 0 placement phase. placementLoop: // Capture Placement phase loop. Only active during reinforcement phase if (turnNumber != 0 && reinforceMentPhase) { // Activates only during reinforcement phase boolean humanCapturedSuccesfully = false; System.out.println("Total Re: " + humanPlayer1.reinforcements); System.out.println("Re placed so far: " + humanPlayer1.reinforcementsPlacedThisTurn); //Adds an army to the territory that is clicked. if (humanPlayer1.reinforcements != humanPlayer1.reinforcementsPlacedThisTurn && currentlySelected.check_isInsideTerritory(x, y) && Gamer.getOwner(currentlySelected, computerPlayer1, humanPlayer1) == humanPlayer1) { currentlySelected.addArmy(1); humanPlayer1.reinforcementsPlacedThisTurn++; System.out.println("triggering humancapturedsuccesfully"); humanCapturedSuccesfully = true; } // When you are done reinforcing but the computer is not done reinforcing let the computer finish @triggers computer-only-reinforcing if (humanPlayer1.reinforcements == humanPlayer1.reinforcementsPlacedThisTurn && computerPlayer1.reinforcements != computerPlayer1.reinforcementsPlacedThisTurn) { System.out.println("human is done reinforcing"); // @trigger computer-only reinforcement humanIsDoneReinforcing = true; } // End condition: whenever you and the computer run out of reinforcements to place at the same click. if (humanPlayer1.reinforcements == humanPlayer1.reinforcementsPlacedThisTurn && computerPlayer1.reinforcements == computerPlayer1.reinforcementsPlacedThisTurn) { reinforceMentPhase = false; attackPhase = true; humanIsDoneReinforcing = false; break placementLoop; } if (humanCapturedSuccesfully && computerPlayer1.reinforcements != computerPlayer1.reinforcementsPlacedThisTurn) { // Computer Reinforcement after human click. boolean reAttempt = true; while (reAttempt) { int randomTerritoryFinder = (int) (Math.random() * 42); // Chose a random number for a territory Territory randomTerritory; // Make a pointer to the territory randomTerritory = gameData.territory.get(randomTerritoryFinder); if (Gamer.getOwner(randomTerritory, computerPlayer1, humanPlayer1) == computerPlayer1) { // if and only if the territory is owned by the computer randomTerritory.addArmy(1); // reinforce the territory computerPlayer1.reinforcementsPlacedThisTurn++; reAttempt = false; // once a reinforcement, do not reattempt to capture again. } } } } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { System.out.println("Escape Typed"); currentlySelected = null; shiftSelected = null; if (attackPhase) { attackBttn.setText("Attack/Reinforce"); } } if (e.getKeyCode() == KeyEvent.VK_SHIFT) { System.out.println("Shift Pressed"); shiftKeyIsPressed = true; } } @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SHIFT) { System.out.println("Shift Released"); shiftKeyIsPressed = false; } } }
package util; import org.apache.commons.lang3.StringUtils; import java.io.*; import java.util.*; /** * Any kind of utilities we need for string handling * @author ingahege * */ public class StringUtilities { private static final int MIN_LEVEN_DISTANCE = 4; //if we have a level 1 similarity the item is not included public static final int MAX_FUZZY_DISTANCE = 38; //if we have a level 1 similarity the item is not included private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray(); /** * Counts the number of a pattern within a string. * @param s * @param pattern * @return */ public static int countInString(String s, String pattern) { if (!StringUtilities.isValidString(s)) return 0; int result = 0; int pos = -1; while ((pos = s.indexOf(pattern,pos+1)) != -1) { result++; } return result; } /** * s is a valid string if it is not null and not an empty string * @param s * @return */ public static boolean isValidString(String s) { return (s != null && s.compareTo("") != 0); } public static long[] getLongArrFromString(String str, String del){ if(str==null || str.isEmpty()) return null; String[] strarr = StringUtils.splitByWholeSeparator(str, del); if(strarr==null || strarr.length==0) return null; long[] longarr = new long[strarr.length]; for(int i=0; i<strarr.length; i++){ longarr[i] = Long.valueOf(strarr[i]).longValue(); } return longarr; } public static int[] getIntArrFromString(String str, String del){ if(str==null || str.isEmpty()) return null; String[] strarr = StringUtils.splitByWholeSeparator(str, del); if(strarr==null || strarr.length==0) return null; int[] intarr = new int[strarr.length]; for(int i=0; i<strarr.length; i++){ intarr[i] = Integer.valueOf(strarr[i]).intValue(); } return intarr; } /** Returns the stack trace for the given Thowable as string. * if there's a TRACE_LIMIT, the stacktrace will be cut after this line!! * * @param throwable exception to create the stacktrace for */ public static String stackTraceToString(Throwable throwable) { StringWriter stack; // tmp stack = new StringWriter(); throwable.printStackTrace(new PrintWriter(stack)); String s = stack.toString(); stack = null; if ("javax.servlet.http.HttpServlet.service" != null) { try { LineNumberReader lnr = new LineNumberReader(new StringReader(s)); stack = new StringWriter(); PrintWriter pw = new PrintWriter(stack); String line = null; boolean ownCode = true; while (ownCode && (line=lnr.readLine()) != null) { if (line.indexOf("javax.servlet.http.HttpServlet.service") != -1) ownCode = false; pw.println(line); } s = stack.toString(); stack = null; } catch(Exception x) { } } return s; } public static boolean similarStrings(String item1, String item2, Locale loc, boolean isStrict){ return similarStrings(item1, item2, loc, MIN_LEVEN_DISTANCE, MAX_FUZZY_DISTANCE, isStrict); } public static String replaceChars(String item1){ item1 = item1.toLowerCase(); item1 = item1.replace("-", " "); item1 = item1.replace(",", ""); item1 = item1.replace("'", ""); item1 = item1.replace(".", ""); item1 = item1.replace("ö", "oe"); item1 = item1.replace("ä", "ae"); item1 = item1.replace("ß", "ss"); item1 = item1.replace("ü", "ue"); item1 = item1.replace("ą", "a"); item1 = item1.replace("á", "a"); item1 = item1.replace("é", "a"); item1 = item1.replace("ć", "c"); item1 = item1.replace("ę", "e"); item1 = item1.replace("ł", "l"); item1 = item1.replace("ń", "n"); item1 = item1.replace("ñ", "n"); item1 = item1.replace("ó", "o"); item1 = item1.replace("ś", "s"); item1 = item1.replace("ź", "z"); item1 = item1.replace("ż", "z"); item1 = item1.replace("í", "i"); item1 = item1.replace("ú", "u"); item1 = item1.trim(); return item1; } /** * We compare two strings and calculate the levensthein disctance. If it is lower than the accepted distance * and starts with the same letter, we return the levensthein distance. * @param item1 * @param item2 * @return */ public static boolean similarStrings(String item1, String item2, Locale loc, int leven, int fuzzy, boolean isStrict){ //if(item1.equalsIgnoreCase("Penicillin") && item2.equalsIgnoreCase("Penicillins")) //item1 = replaceChars(item1); //item2 = replaceChars(item2); if(item1.equalsIgnoreCase(item2)) return true; //unilateral/bilateral is too similar, but needs to be both in the list: if(item1.startsWith("Unilat") && item2.startsWith("Bilat") || item2.startsWith("Unilat") && item1.startsWith("Bilat")) return false; if(item1.startsWith("Type I") && item2.startsWith("Type II") || item2.startsWith("Type I") && item1.startsWith("Type II")) return false; if(isMatchBasedOnLevelAndFuzzy(item1, item2, loc, leven, fuzzy, isStrict)) return true; //if we have multiple words we split them and compare them separately String[] item1Arr = item1.trim().split(" "); String[] item2Arr = item2.trim().split(" "); if(item1Arr.length==1 || item2Arr.length==1) return false; //TODO: we might still compare them? //we go thru each item and compare it with the items2 boolean[] isMatch; //System.out.println(""); if(item1Arr.length>=item2Arr.length) isMatch = runThrugStringArr(item1Arr, item2Arr, loc); else isMatch = runThrugStringArr(item2Arr, item1Arr, loc); boolean isFinallyMatch = true; for(int i=0; i<isMatch.length; i++){ if(!isMatch[i]){ isFinallyMatch = false; //if one entry is false (no Match) we return false. break; } } if(isFinallyMatch) return isFinallyMatch; //check for something like: "Streptokokkenpneumonie" / "Penumonie, Streptokokken" if((item1Arr.length==1 && item2Arr.length==2)){ String item2_1Str = item2Arr[0].trim() + item2Arr[1].trim(); if(isMatchBasedOnLevelAndFuzzy(item1, item2_1Str, loc, leven, fuzzy, isStrict)) return true; String item2_2Str = item2Arr[1].trim() + item2Arr[0].trim(); if(isMatchBasedOnLevelAndFuzzy(item1, item2_2Str, loc, leven, fuzzy, isStrict)) return true; } if((item2Arr.length==1 && item1Arr.length==2)){ String item1_1Str = item1Arr[0].trim() + item1Arr[1].trim(); if(isMatchBasedOnLevelAndFuzzy(item2, item1_1Str, loc, leven, fuzzy, isStrict)) return true; String item1_2Str = item1Arr[1].trim() + item1Arr[0].trim(); if(isMatchBasedOnLevelAndFuzzy(item2, item1_2Str, loc, leven, fuzzy, isStrict)) return true; } return false; } /** * @param item1Arr * @param item2Arr * @param loc * @return */ private static boolean[] runThrugStringArr(String[] item1Arr, String[] item2Arr, Locale loc){ StringBuffer sb1 = new StringBuffer(); StringBuffer sb2 = new StringBuffer(); boolean[] isMatch = new boolean[item1Arr.length]; for(int i=0; i<item1Arr.length; i++){ String item1_1 = item1Arr[i]; sb1.append(item1_1+" innerLoop: for(int k=0; k<item2Arr.length; k++){ String item2_2 = item2Arr[k]; sb2.append(item2_2+" int leven2 = StringUtils.getLevenshteinDistance(item1_1, item2_2); int fuzzy2 = StringUtils.getFuzzyDistance(item1_1, item2_2, loc); int minLeven = MIN_LEVEN_DISTANCE; if(item1_1.length()<=3 || item2_2.length()<=3) minLeven = 1; if(leven2<minLeven || fuzzy2>=MAX_FUZZY_DISTANCE){ //then they are similar isMatch[i] = true; break innerLoop; } } } return isMatch; } private static boolean isMatchBasedOnLevelAndFuzzy(String s1, String s2, Locale loc, int inLeven, int inFuzzy, boolean isStrict){ int leven = StringUtils.getLevenshteinDistance(s1.toLowerCase(), s2.toLowerCase()); int fuzzy = StringUtils.getFuzzyDistance(s1.toLowerCase(), s2.toLowerCase(), loc); //compare Strings as they are: //if(s1.equals("Abdomen, Acute") || item2.equals("Abdomen, Acute")) // System.out.println("Leven: " + leven + ", fuzzy: " + fuzzy + " Item1: " + item1 + " Item2: " + item2); //if(leven ==2 && fuzzy>20 && fuzzy < inFuzzy) // System.out.println(s1 + ", " + s2 + ", leven " + leven + ", fuzzy: " + fuzzy); if(!isStrict && s1.length()>3 &&s2.length()>3 && leven == 1 && fuzzy > 1) return true; if(isStrict && s1.length()>3 &&s2.length()>3 && leven==1 && fuzzy>=28) return true; if(leven == 2 && fuzzy > 30) return true; if(leven < inLeven && fuzzy >= inFuzzy/*&& firstLetterItem1.equalsIgnoreCase(firstLetterItem2)*/){ return true; //these items are not added } /*if(fuzzy>=MAX_FUZZY_DISTANCE){ return true; }*/ return false; } public static byte[] hexToBytes(String hex) {return hexToBytes(hex.toCharArray()); } public static byte[] hexToBytes(char[] hex) { int length = hex.length / 2; byte[] raw = new byte[length]; for (int i = 0; i < length; i++) { int high = Character.digit(hex[i * 2], 16); int low = Character.digit(hex[i * 2 + 1], 16); int value = (high << 4) | low; if (value > 127) value -= 256; raw[i] = (byte) value; } return raw; } /** * converts byte array to hex string representation * @param in_bytes * @return */ public static String toHex(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 3); for (int i=0; i<bytes.length;i++) { int b = bytes[i]; b &= 0xff; sb.append(HEXDIGITS[b >> 4]); sb.append(HEXDIGITS[b & 15]); //sb.append(' '); } return sb.toString(); } public static String toString(List<String> strList, String del){ if(strList==null || strList.isEmpty()) return ""; StringBuffer sb = new StringBuffer(500); for(int i=0;i<strList.size();i++){ if(i<strList.size()-1) sb.append(strList.get(i)+del); else sb.append(strList.get(i)); } return sb.toString(); } /** * Returns a int array as a String with the given delimiter. If null or empty an empty string is returned. * @param strList * @param del * @return */ public static String toString(int[] strList, String del){ if(strList==null || strList.length==0) return ""; StringBuffer sb = new StringBuffer(500); for(int i=0;i<strList.length;i++){ if(i<strList.length-1) sb.append(strList[i]+del); else sb.append(strList[i]); } return sb.toString(); } public static List<String> createStringListFromString(String s, boolean doReplace){ if(s==null || s.trim().isEmpty()) return null; List<String> sList = new ArrayList<String>(); if(doReplace){ s = s.replace(",", " "); s = s.replace(".", " "); } StringTokenizer st = new StringTokenizer(s); while (st.hasMoreTokens()) { sList.add(st.nextToken().trim()); } return sList; } public static boolean isNumeric(String strNum) { if (strNum == null) { return false; } if(strNum.contains(",")) strNum = strNum.replace(',', '.'); try { double d = Double.parseDouble(strNum); } catch (NumberFormatException nfe) { return false; } return true; } /** * we go trhough a text and look at which position (word count, 0-based) we find the starting position of this string * and return it. * @param s * @param text * @return */ /*public static int getStartPosOfStrInText(String s, String text){ List<String> textAsList = StringUtilities.createStringListFromString(text, true); int startPos = -1; if(s.contains(" ")){ List<String> str = StringUtilities.createStringListFromString(s, false); for (int i=0; i < textAsList.size(); i++){ if(textAsList.get(i).equalsIgnoreCase(str.get(0)) && textAsList.get(i+1)!=null && textAsList.get(i+1).equalsIgnoreCase(str.get(1))) return i; } } else{ for (int i=0; i < textAsList.size(); i++){ if(textAsList.get(i).equalsIgnoreCase(s)) return i; } } return startPos; }*/ /** * We go thru the text and look for the match String. If found we return the complete word (the * match String might be just part of the word) * @param text * @param match * @return */ /*public static String getWordFromText(String text, String match) { if(text==null ||match==null) return null; StringBuffer sb = new StringBuffer(); int startIdx = text.toLowerCase().indexOf(match); //sb.append(text.charAt(startIdx)); for(int i=startIdx;i<text.length();i++){ char c = text.charAt(i); if(c!=',' && c!=' ' && c!='.' && c!=';') sb.append(text.charAt(i)); else return sb.toString(); } return null; }*/ }
package org.eigenbase.sql; import java.sql.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.*; /** * <code>SqlDialect</code> encapsulates the differences between dialects of SQL. * * <p>It is used by classes such as {@link SqlWriter} and * {@link org.eigenbase.sql.util.SqlBuilder}. */ public class SqlDialect { /** * A dialect useful for generating generic SQL. If you need to do something * database-specific like quoting identifiers, don't rely on this dialect to * do what you want. */ public static final SqlDialect DUMMY = DatabaseProduct.UNKNOWN.getDialect(); /** * A dialect useful for generating SQL which can be parsed by the * Eigenbase parser, in particular quoting literals and identifiers. If you * want a dialect that knows the full capabilities of the database, create * one from a connection. */ public static final SqlDialect EIGENBASE = DatabaseProduct.LUCIDDB.getDialect(); private final String databaseProductName; private final String identifierQuoteString; private final String identifierEndQuoteString; private final String identifierEscapedQuote; private final DatabaseProduct databaseProduct; /** * Creates a <code>SqlDialect</code> from a DatabaseMetaData. * * <p>Does not maintain a reference to the DatabaseMetaData -- or, more * importantly, to its {@link java.sql.Connection} -- after this call has * returned. * * @param databaseMetaData used to determine which dialect of SQL to * generate */ public static SqlDialect create(DatabaseMetaData databaseMetaData) { String identifierQuoteString; try { identifierQuoteString = databaseMetaData.getIdentifierQuoteString(); } catch (SQLException e) { throw FakeUtil.newInternal(e, "while quoting identifier"); } String databaseProductName; try { databaseProductName = databaseMetaData.getDatabaseProductName(); } catch (SQLException e) { throw FakeUtil.newInternal(e, "while detecting database product"); } final DatabaseProduct databaseProduct = getProduct(databaseProductName, null); return new SqlDialect( databaseProduct, databaseProductName, identifierQuoteString); } /** * Creates a SqlDialect. * * @param databaseProduct Database product; may be UNKNOWN, never null * @param databaseProductName Database product name from JDBC driver * @param identifierQuoteString String to quote identifiers. Null if quoting * is not supported. If "[", close quote is deemed to be "]". */ public SqlDialect( DatabaseProduct databaseProduct, String databaseProductName, String identifierQuoteString) { assert databaseProduct != null; assert databaseProductName != null; this.databaseProduct = databaseProduct; this.databaseProductName = databaseProductName; if (identifierQuoteString != null) { identifierQuoteString = identifierQuoteString.trim(); if (identifierQuoteString.equals("")) { identifierQuoteString = null; } } this.identifierQuoteString = identifierQuoteString; this.identifierEndQuoteString = identifierQuoteString == null ? null : identifierQuoteString.equals("[") ? "]" : identifierQuoteString; this.identifierEscapedQuote = identifierQuoteString == null ? null : this.identifierEndQuoteString + this.identifierEndQuoteString; } /** * Converts a product name and version (per the JDBC driver) into a product * enumeration. * * @param productName Product name * @param productVersion Product version * @return database product */ public static DatabaseProduct getProduct( String productName, String productVersion) { final String upperProductName = productName.toUpperCase(); if (productName.equals("ACCESS")) { return DatabaseProduct.ACCESS; } else if (upperProductName.trim().equals("APACHE DERBY")) { return DatabaseProduct.DERBY; } else if (upperProductName.trim().equals("DBMS:CLOUDSCAPE")) { return DatabaseProduct.DERBY; } else if (productName.startsWith("DB2")) { return DatabaseProduct.DB2; } else if (upperProductName.indexOf("FIREBIRD") >= 0) { return DatabaseProduct.FIREBIRD; } else if (productName.startsWith("Informix")) { return DatabaseProduct.INFORMIX; } else if (upperProductName.equals("INGRES")) { return DatabaseProduct.INGRES; } else if (productName.equals("Interbase")) { return DatabaseProduct.INTERBASE; } else if (upperProductName.equals("LUCIDDB")) { return DatabaseProduct.LUCIDDB; } else if (upperProductName.indexOf("SQL SERVER") >= 0) { return DatabaseProduct.MSSQL; } else if (upperProductName.indexOf("PARACCEL") >= 0) { return DatabaseProduct.PARACCEL; } else if (productName.equals("Oracle")) { return DatabaseProduct.ORACLE; } else if (upperProductName.indexOf("POSTGRE") >= 0) { return DatabaseProduct.POSTGRESQL; } else if (upperProductName.indexOf("NETEZZA") >= 0) { return DatabaseProduct.NETEZZA; } else if (upperProductName.equals("MYSQL (INFOBRIGHT)")) { return DatabaseProduct.INFOBRIGHT; } else if (upperProductName.equals("MYSQL")) { return DatabaseProduct.MYSQL; } else if (productName.startsWith("HP Neoview")) { return DatabaseProduct.NEOVIEW; } else if (upperProductName.indexOf("SYBASE") >= 0) { return DatabaseProduct.SYBASE; } else if (upperProductName.indexOf("TERADATA") >= 0) { return DatabaseProduct.TERADATA; } else if (upperProductName.indexOf("HSQL") >= 0) { return DatabaseProduct.HSQLDB; } else if (upperProductName.indexOf("VERTICA") >= 0) { return DatabaseProduct.VERTICA; } else { return DatabaseProduct.UNKNOWN; } } // -- detect various databases -- /** * Encloses an identifier in quotation marks appropriate for the current SQL * dialect. * * <p>For example, <code>quoteIdentifier("emp")</code> yields a string * containing <code>"emp"</code> in Oracle, and a string containing <code> * [emp]</code> in Access. * * @param val Identifier to quote * * @return Quoted identifier */ public String quoteIdentifier(String val) { if (identifierQuoteString == null) { return val; // quoting is not supported } String val2 = val.replaceAll( identifierEndQuoteString, identifierEscapedQuote); return identifierQuoteString + val2 + identifierEndQuoteString; } /** * Encloses an identifier in quotation marks appropriate for the current SQL * dialect, writing the result to a {@link StringBuilder}. * * <p>For example, <code>quoteIdentifier("emp")</code> yields a string * containing <code>"emp"</code> in Oracle, and a string containing <code> * [emp]</code> in Access. * * @param buf Buffer * @param val Identifier to quote * * @return The buffer */ public StringBuilder quoteIdentifier( StringBuilder buf, String val) { if (identifierQuoteString == null) { buf.append(val); // quoting is not supported return buf; } String val2 = val.replaceAll( identifierEndQuoteString, identifierEscapedQuote); buf.append(identifierQuoteString); buf.append(val2); buf.append(identifierEndQuoteString); return buf; } /** * Quotes a multi-part identifier. * * @param buf Buffer * @param identifiers List of parts of the identifier to quote * * @return The buffer */ public StringBuilder quoteIdentifier( StringBuilder buf, List<String> identifiers) { int i = 0; for (String identifier : identifiers) { if (i++ > 0) { buf.append('.'); } quoteIdentifier(buf, identifier); } return buf; } /** * Returns whether a given identifier needs to be quoted. */ public boolean identifierNeedsToBeQuoted(String val) { return !Pattern.compile("^[A-Z_$0-9]+").matcher(val).matches(); } /** * Converts a string into a string literal. For example, <code>can't * run</code> becomes <code>'can''t run'</code>. */ public String quoteStringLiteral(String val) { if (containsNonAscii(val)) { final StringBuilder buf = new StringBuilder(); quoteStringLiteralUnicode(buf, val); return buf.toString(); } else { val = FakeUtil.replace(val, "'", "''"); return "'" + val + "'"; } } /** * Returns whether the string contains any characters outside the * comfortable 7-bit ASCII range (32 through 127). * * @param s String * @return Whether string contains any non-7-bit-ASCII characters */ private static boolean containsNonAscii(String s) { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c < 32 || c >= 128) { return true; } } return false; } /** * Converts a string into a unicode string literal. For example, * <code>can't{tab}run\</code> becomes <code>u'can''t\0009run\\'</code>. */ public void quoteStringLiteralUnicode(StringBuilder buf, String val) { buf.append("u&'"); for (int i = 0; i < val.length(); i++) { char c = val.charAt(i); if (c < 32 || c >= 128) { buf.append('\\'); buf.append(hex[(c >> 12) & 0xf]); buf.append(hex[(c >> 8) & 0xf]); buf.append(hex[(c >> 4) & 0xf]); buf.append(hex[c & 0xf]); } else if (c == '\'' || c == '\\') { buf.append(c); buf.append(c); } else { buf.append(c); } } buf.append("'"); } private static final char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', }; /** * Converts a string literal back into a string. For example, <code>'can''t * run'</code> becomes <code>can't run</code>. */ public String unquoteStringLiteral(String val) { if ((val != null) && (val.charAt(0) == '\'') && (val.charAt(val.length() - 1) == '\'')) { if (val.length() > 2) { val = FakeUtil.replace(val, "''", "'"); return val.substring(1, val.length() - 1); } else { // zero length string return ""; } } return val; } protected boolean allowsAs() { return !(databaseProduct == DatabaseProduct.ORACLE); } // -- behaviors -- protected boolean requiresAliasForFromItems() { return getDatabaseProduct() == DatabaseProduct.POSTGRESQL; } /** * Converts a timestamp to a SQL timestamp literal, e.g. * {@code TIMESTAMP '2009-12-17 12:34:56'}. * * <p>Timestamp values do not have a time zone. We therefore interpret them * as the number of milliseconds after the UTC epoch, and the formatted * value is that time in UTC. * * <p>In particular, * * <blockquote><code>quoteTimestampLiteral(new Timestamp(0));</code> * </blockquote> * * returns {@code TIMESTAMP '1970-01-01 00:00:00'}, regardless of the JVM's * timezone. * * @param timestamp Timestamp * @return SQL timestamp literal */ public String quoteTimestampLiteral(Timestamp timestamp) { final SimpleDateFormat format = new SimpleDateFormat( "'TIMESTAMP' ''yyyy-MM-DD HH:mm:SS''"); format.setTimeZone(TimeZone.getTimeZone("GMT")); return format.format(timestamp); } /** * Returns the database this dialect belongs to, * {@link SqlDialect.DatabaseProduct#UNKNOWN} if not known, never null. * * @return Database product */ public DatabaseProduct getDatabaseProduct() { return databaseProduct; } /** * A few utility functions copied from org.eigenbase.util.Util. We have * copied them because we wish to keep SqlDialect's dependencies to a * minimum. */ public static class FakeUtil { public static Error newInternal(Throwable e, String s) { String message = "Internal error: \u0000" + s; AssertionError ae = new AssertionError(message); ae.initCause(e); return ae; } /** * Replaces every occurrence of <code>find</code> in <code>s</code> with * <code>replace</code>. */ public static final String replace( String s, String find, String replace) { // let's be optimistic int found = s.indexOf(find); if (found == -1) { return s; } StringBuilder sb = new StringBuilder(s.length()); int start = 0; for (;;) { for (; start < found; start++) { sb.append(s.charAt(start)); } if (found == s.length()) { break; } sb.append(replace); start += find.length(); found = s.indexOf(find, start); if (found == -1) { found = s.length(); } } return sb.toString(); } } /** * Rough list of flavors of database. * * <p>These values cannot help you distinguish between features that exist * in different versions or ports of a database, but they are sufficient * to drive a {@code switch} statement if behavior is broadly different * between say, MySQL and Oracle. * * <p>If possible, you should not refer to particular database at all; write * extend the dialect to describe the particular capability, for example, * whether the database allows expressions to appear in the GROUP BY clause. */ public enum DatabaseProduct { ACCESS("Access", "\""), MSSQL("Microsoft SQL Server", "["), MYSQL("MySQL", "`"), ORACLE("Oracle", "\""), DERBY("Apache Derby", null), DB2("IBM DB2", null), FIREBIRD("Firebird", null), INFORMIX("Informix", null), INGRES("Ingres", null), LUCIDDB("LucidDB", "\""), INTERBASE("Interbase", null), POSTGRESQL("PostgreSQL", "\""), NETEZZA("Netezza", "\""), INFOBRIGHT("Infobright", "`"), NEOVIEW("Neoview", null), SYBASE("Sybase", null), TERADATA("Teradata", "\""), HSQLDB("Hsqldb", null), VERTICA("Vertica", "\""), SQLSTREAM("SQLstream", "\""), PARACCEL("Paraccel", "\""), /** * Placeholder for the unknown database. * * <p>Its dialect is useful for generating generic SQL. If you need to * do something database-specific like quoting identifiers, don't rely * on this dialect to do what you want. */ UNKNOWN("Unknown", "`"); private SqlDialect dialect = null; private String databaseProductName; private String quoteString; DatabaseProduct(String databaseProductName, String quoteString) { this.databaseProductName = databaseProductName; this.quoteString = quoteString; } /** * Returns a dummy dialect for this database. * * <p>Since databases have many versions and flavors, this dummy dialect * is at best an approximation. If you want exact information, better to * use a dialect created from an actual connection's metadata * (see {@link SqlDialect#create(java.sql.DatabaseMetaData)}). * * @return Dialect representing lowest-common-demoninator behavior for * all versions of this database */ public SqlDialect getDialect() { if (dialect == null) { dialect = new SqlDialect(this, databaseProductName, quoteString); } return dialect; } } } // End SqlDialect.java
package org.voovan.tools; import org.voovan.db.CallType; import org.voovan.db.DataBaseType; import org.voovan.db.JdbcOperate; import org.voovan.tools.json.JSON; import org.voovan.tools.log.Logger; import org.voovan.tools.reflect.TReflect; import org.voovan.tools.security.THash; import javax.sql.DataSource; import java.lang.reflect.Method; import java.math.BigDecimal; import java.sql.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.Date; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; public class TSQL { /** * SQL , SQL * @param sqlStr sql (select * from table where x=::x and y=::y) * @return sql ([:x,:y]) */ public static List<String> getSqlParamNames(String sqlStr){ String[] params = TString.searchByRegex(sqlStr, "::\\w+\\b"); ArrayList<String> sqlParamNames = new ArrayList<String>(); for(String param : params){ sqlParamNames.add(param); } return sqlParamNames; } /** * preparedStatement sql (?) * @param sqlStr sql (select * from table where x=:x and y=::y) * @return :? (select * from table where x=? and y=?) */ public static String preparedSql(String sqlStr){ return TString.fastReplaceAll(sqlStr, "::\\w+\\b", "?"); } /** * preparedStatement * * @param preparedStatement preparedStatement * @param sqlParamNames sql * @param params Map * @throws SQLException SQL */ public static void setPreparedParams(PreparedStatement preparedStatement,List<String> sqlParamNames,Map<String, ?> params) throws SQLException{ for(int i=0;i<sqlParamNames.size();i++){ String paramName = sqlParamNames.get(i); paramName = paramName.substring(2,paramName.length()); Object data = params.get(paramName); if(data==null){ preparedStatement.setObject(i + 1, null); } else if(TReflect.isBasicType(data.getClass())) { preparedStatement.setObject(i + 1, data); } else if(data instanceof BigDecimal){ preparedStatement.setObject(i + 1, data.toString()); } else { //,, JSON preparedStatement.setObject(i + 1, JSON.toJSON(data)); } } } /** * PreparedStatement * @param conn * @param sqlStr sql * @param params Map * @return PreparedStatement * @throws SQLException SQL */ public static PreparedStatement createPreparedStatement(Connection conn,String sqlStr,Map<String, Object> params) throws SQLException{ sqlStr = TSQL.removeEmptyCondiction(sqlStr, params); List<String> sqlParamNames = TSQL.getSqlParamNames(sqlStr); Logger.sql("[SQL_Executed]: " + assembleSQLWithMap(sqlStr, params)); //preparedStatement SQL String preparedSql = TSQL.preparedSql(sqlStr); PreparedStatement preparedStatement = (PreparedStatement) conn.prepareStatement(preparedSql); //params, if(params==null){ params = new Hashtable<String, Object>(); } //preparedStatement TSQL.setPreparedParams(preparedStatement, sqlParamNames, params); return preparedStatement; } /** * PreparedStatement * @param conn * @param sqlStr sql * @param params Map * @param callTypes * @return PreparedStatement * @throws SQLException SQL */ public static CallableStatement createCallableStatement(Connection conn,String sqlStr,Map<String, Object> params, CallType[] callTypes) throws SQLException{ Logger.sql("[SQL_Executed]: " + sqlStr); List<String> sqlParamNames = TSQL.getSqlParamNames(sqlStr); //preparedStatement SQL String preparedSql = TSQL.preparedSql(sqlStr); // jdbc statement CallableStatement callableStatement = (CallableStatement) conn.prepareCall(preparedSql); //params, if(params==null){ params = new Hashtable<String, Object>(); } //callableStatement TSQL.setPreparedParams(callableStatement,sqlParamNames,params); //, OUT ParameterMetaData parameterMetaData = callableStatement.getParameterMetaData(); for(int i=0;i<parameterMetaData.getParameterCount();i++){ int paramMode = parameterMetaData.getParameterMode(i+1); if(paramMode == ParameterMetaData.parameterModeOut || paramMode == ParameterMetaData.parameterModeInOut) { callableStatement.registerOutParameter(i + 1, parameterMetaData.getParameterType(i + 1)); } } return callableStatement; } /** * * @param callableStatement callableStatement * @return * @throws SQLException SQL */ public static List<Object> getCallableStatementResult(CallableStatement callableStatement) throws SQLException{ ArrayList<Object> result = new ArrayList<Object>(); ParameterMetaData parameterMetaData = callableStatement.getParameterMetaData(); for(int i=0;i<parameterMetaData.getParameterCount();i++){ int paramMode = parameterMetaData.getParameterMode(i+1); // out , if(paramMode == ParameterMetaData.parameterModeOut || paramMode == ParameterMetaData.parameterModeInOut){ String methodName = getDataMethod(parameterMetaData.getParameterType(i+1)); Object value; try { // int Method method = TReflect.findMethod(CallableStatement.class,methodName,new Class[]{int.class}); value = TReflect.invokeMethod(callableStatement, method,i+1); result.add(value); } catch (ReflectiveOperationException e) { e.printStackTrace(); } } } return result; } /** * SQL * @param sqlStr SQL * @param args * @return SQL */ public static String assembleSQLWithArray(String sqlStr,Object[] args){ // [, ] Map Map<String,Object> argMap = TObject.arrayToMap(args); return assembleSQLWithMap(sqlStr,argMap); } /** * argObjectjSQL * @param sqlStr SQL * @param argObjectj * @return SQL * @throws ReflectiveOperationException */ public static String assembleSQLWithObject(String sqlStr,Object argObjectj) throws ReflectiveOperationException{ // [-] Map Map<String,Object> argMap = TReflect.getMapfromObject(argObjectj); return assembleSQLWithMap(sqlStr,argMap); } /** * argMapKVSQL * SQL: * @param sqlStr SQL * @param argMap Map * @return */ public static String assembleSQLWithMap(String sqlStr,Map<String ,Object> argMap) { if(argMap!=null) { for (Entry<String, Object> arg : argMap.entrySet()) { sqlStr = TString.fastReplaceAll(sqlStr+" ", "::" + arg.getKey()+"\\b", getSQLString(argMap.get(arg.getKey()))+" "); } } return sqlStr.trim(); } /** * resultSetMap * @param resultset * @return Map * @throws SQLException SQL * @throws ReflectiveOperationException */ public static Map<String, Object> getOneRowWithMap(ResultSet resultset) throws SQLException, ReflectiveOperationException { HashMap<String, Object> resultMap = new HashMap<String,Object>(); HashMap<String,Integer> columns = new HashMap<String,Integer>(); int columnCount = resultset.getMetaData().getColumnCount(); for(int i=1;i<=columnCount;i++){ columns.put(resultset.getMetaData().getColumnLabel(i),resultset.getMetaData().getColumnType(i)); } //Map for(Entry<String, Integer> columnEntry : columns.entrySet()) { String methodName =getDataMethod(columnEntry.getValue()); Object value = TReflect.invokeMethod(resultset, methodName, columnEntry.getKey()); resultMap.put(columnEntry.getKey(), value); } return resultMap; } /** * resultSet * @param clazz * @param resultset * @return * @throws ReflectiveOperationException * @throws SQLException SQL * @throws ParseException */ public static Object getOneRowWithObject(Class<?> clazz,ResultSet resultset) throws SQLException, ReflectiveOperationException, ParseException { Map<String,Object>rowMap = getOneRowWithMap(resultset); return TReflect.getObjectFromMap(clazz, rowMap, true); } /** * resultSetList,Map * @param resultSet * @return List[Map] * @throws ReflectiveOperationException * @throws SQLException SQL */ public static List<Map<String,Object>> getAllRowWithMapList(ResultSet resultSet) throws SQLException, ReflectiveOperationException { List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>(); while(resultSet!=null && resultSet.next()){ resultList.add(getOneRowWithMap(resultSet)); } return resultList; } /** * resultSetList, * @param clazz * @param resultSet * @return * @throws ParseException * @throws ReflectiveOperationException * @throws SQLException SQL */ public static List<Object> getAllRowWithObjectList(Class<?> clazz,ResultSet resultSet) throws SQLException, ReflectiveOperationException, ParseException { List<Object> resultList = new ArrayList<Object>(); while(resultSet!=null && resultSet.next()){ resultList.add(getOneRowWithObject(clazz,resultSet)); } return resultList; } private static String EQUAL_CONDICTION = " 1=1"; private static String NOT_EQUAL_CONDICTION = " 1!=1"; /** * SQL , * @param sqlText SQL * @param params * @return */ public static String removeEmptyCondiction(String sqlText, Map<String, Object> params){ //insert if(sqlText.startsWith("insert") || sqlText.startsWith("INSERT")) { return sqlText; } //params, if(params==null){ params = new Hashtable<String, Object>(); } List<String[]> condictionList = parseSQLCondiction(sqlText); for(String[] condictionArr : condictionList){ String orginCondiction = condictionArr[0]; String beforeCondictionMethod = condictionArr[1]; String condictionName = condictionArr[2]; String operatorChar = condictionArr[3]; String originCondictionParams = condictionArr[4]; String afterCondictionMethod = condictionArr[5]; String replaceCondiction = orginCondiction; String condictionParams = originCondictionParams; if(originCondictionParams!=null && originCondictionParams.contains("::")) { String[] condictions = TString.searchByRegex(originCondictionParams, "::\\w+\\b"); if(condictions.length > 0) { for (String condictionParam : condictions){ if (!params.containsKey(condictionParam.replace("::", ""))) { if(operatorChar.equals("in") || operatorChar.equals("not in")) { condictionParams = TString.fastReplaceAll(condictionParams, condictionParam+"\\s*,?", ""); } else { replaceCondiction = EQUAL_CONDICTION; if ("or".equals(beforeCondictionMethod) || "or".equals(afterCondictionMethod)) { replaceCondiction = NOT_EQUAL_CONDICTION; } String targetCondiction = condictionName + "\\s*" + operatorChar + "\\s*" + originCondictionParams; targetCondiction = targetCondiction.replaceAll("\\(", "\\\\("); targetCondiction = targetCondiction.replaceAll("\\)", "\\\\)"); targetCondiction = targetCondiction.replaceAll("\\[", "\\\\["); targetCondiction = targetCondiction.replaceAll("\\]", "\\\\]"); targetCondiction = targetCondiction.replaceAll("\\+", "\\\\+"); replaceCondiction = TString.fastReplaceAll(orginCondiction, targetCondiction , replaceCondiction); } } } //in not in , , if(operatorChar.equals("in") || operatorChar.equals("not in")) { condictionParams = condictionParams.trim(); if(condictionParams.endsWith(",")){ condictionParams = TString.removeSuffix(condictionParams); } originCondictionParams = originCondictionParams.replaceAll("\\(", "\\\\("); originCondictionParams = originCondictionParams.replaceAll("\\)", "\\\\)"); originCondictionParams = originCondictionParams.replaceAll("\\[", "\\\\["); originCondictionParams = originCondictionParams.replaceAll("\\]", "\\\\]"); originCondictionParams = originCondictionParams.replaceAll("\\+", "\\\\+"); replaceCondiction = TString.fastReplaceAll(replaceCondiction, originCondictionParams, condictionParams); } sqlText = sqlText.replace(orginCondiction, replaceCondiction); } } } return sqlText; } public static ConcurrentHashMap<Integer, List<String[]>> PARSED_CONDICTIONS = new ConcurrentHashMap<Integer, List<String[]>>(); public static AtomicInteger size = new AtomicInteger(); /** * SQL * @param sqlText SQL * @return SQL */ public static List<String[]> parseSQLCondiction(String sqlText) { int hashcode = THash.HashFNV1(sqlText); List<String[]> condictionList = PARSED_CONDICTIONS.get(hashcode); if(condictionList == null) { if(size.get() > 10000) { synchronized (PARSED_CONDICTIONS) { synchronized(size) { Logger.warn("SQL may be has same problem on TSQL.parseSQLCondiction: " + sqlText); PARSED_CONDICTIONS.clear(); size.set(0); } } } condictionList = new ArrayList<String[]>(); String sqlRegx = "((\\swhere\\s)|(\\sand\\s)|(\\sor\\s))[\\S\\s]+?(?=(\\swhere\\s)|(\\sand\\s)|(\\sor\\s)|(\\sgroup by\\s)|(\\sorder\\s)|(\\slimit\\s)|$)"; String[] sqlCondictions = TString.searchByRegex(sqlText, sqlRegx, Pattern.CASE_INSENSITIVE); for (int i = 0; i < sqlCondictions.length; i++) { String condiction = sqlCondictions[i]; // ) , , 1=1) m2, gggg m3 if (condiction.indexOf("(") < condiction.indexOf(")") && TString.searchByRegex(condiction, "[\\\"`'].*?\\).*?[\\\"`']").length == 0) { int indexClosePair = condiction.lastIndexOf(")"); if (indexClosePair != -1) { condiction = condiction.substring(0, indexClosePair + 1); } } //between if (TString.regexMatch(condiction, "\\sbetween\\s") > 0) { i = i + 1; condiction = condiction + sqlCondictions[i]; } String originCondiction = condiction; condiction = condiction.trim(); String concateMethod = condiction.substring(0, condiction.indexOf(" ") + 1).trim(); condiction = condiction.substring(condiction.indexOf(" ") + 1, condiction.length()).trim(); String[] splitedCondicction = TString.searchByRegex(condiction, "(\\sbetween\\s+)|(\\sis\\s+)|(\\slike\\s+)|(\\s(not\\s)?in\\s+)|(\\!=)|(>=)|(<=)|[=<>]"); if (splitedCondicction.length == 1) { String operatorChar = splitedCondicction[0].trim(); String[] condictionArr = condiction.split("(\\sbetween\\s+)|(\\sis\\s+)|(\\slike\\s+)|(\\s(not\\s)?in\\s+)|(\\!=)|(>=)|(<=)|[=<>]"); condictionArr[0] = condictionArr[0].trim(); if (TString.regexMatch(condiction, "\\(") > TString.regexMatch(condiction, "\\)") && condictionArr[0].startsWith("(")) { condictionArr[0] = TString.removePrefix(condictionArr[0]); } condictionArr[1] = condictionArr[1].trim(); if (condictionArr.length > 1) { if (operatorChar.contains("in") && condictionArr[1].trim().startsWith("(") && condictionArr[1].trim().endsWith(")")) { condictionArr[1] = condictionArr[1].substring(1, condictionArr[1].length() - 1); } if (condictionArr[0].startsWith("(") && TString.regexMatch(condictionArr[1], "\\(") > TString.regexMatch(condictionArr[1], "\\)")) { condictionArr[0] = TString.removePrefix(condictionArr[0]); } if (condictionArr[1].endsWith(")") && TString.regexMatch(condictionArr[1], "\\(") < TString.regexMatch(condictionArr[1], "\\)")) { condictionArr[1] = TString.removeSuffix(condictionArr[1]); } condictionList.add(new String[]{originCondiction.trim(), concateMethod, condictionArr[0].trim(), operatorChar, condictionArr[1].trim(), null}); } else { Logger.error("Parse SQL condiction error"); } } else { condictionList.add(new String[]{originCondiction, null, null, null, null, null}); } } for (int i = condictionList.size() - 2; i >= 0; i condictionList.get(i)[5] = condictionList.get(i + 1)[1]; } size.getAndIncrement(); PARSED_CONDICTIONS.put(hashcode, condictionList); } return condictionList; } /** * SQL, JAVA SQL * :String 'chs' * @param argObj * @return */ public static String getSQLString(Object argObj) { if(argObj==null){ return "null"; } if(argObj instanceof List) { Object[] objects =((List<?>)argObj).toArray(); StringBuilder listValueStr= new StringBuilder("("); for(Object obj : objects) { String sqlValue = getSQLString(obj); if(sqlValue!=null) { listValueStr.append(sqlValue); listValueStr.append(","); } } return TString.removeSuffix(listValueStr.toString())+")"; } //String else if(argObj instanceof String){ return "\'"+argObj.toString()+"\'"; } //Boolean else if(argObj instanceof Boolean){ if((Boolean)argObj) return "true"; else return "false"; } //Date else if(argObj instanceof Date){ SimpleDateFormat dateFormat = new SimpleDateFormat(TDateTime.STANDER_DATETIME_TEMPLATE); return "'"+dateFormat.format(argObj)+"'"; } //String else { return argObj.toString(); } } /** * SQL Result * @param databaseType * @return */ public static String getDataMethod(int databaseType){ switch(databaseType){ case Types.CHAR : return "getString"; case Types.VARCHAR : return "getString"; case Types.LONGVARCHAR : return "getString"; case Types.NCHAR : return "getString"; case Types.LONGNVARCHAR : return "getString"; case Types.NUMERIC : return "getBigDecimal"; case Types.DECIMAL : return "getBigDecimal"; case Types.BIT : return "getBoolean"; case Types.BOOLEAN : return "getBoolean"; case Types.TINYINT : return "getByte"; case Types.SMALLINT : return "getShort"; case Types.INTEGER : return "getInt"; case Types.BIGINT : return "getLong"; case Types.REAL : return "getFloat"; case Types.FLOAT : return "getFloat"; case Types.DOUBLE : return "getDouble"; case Types.BINARY : return "getBytes"; case Types.VARBINARY : return "getBytes"; case Types.LONGVARBINARY : return "getBytes"; case Types.DATE : return "getDate"; case Types.TIME : return "getTime"; case Types.TIMESTAMP : return "getTimestamp"; case Types.CLOB : return "getClob"; case Types.BLOB : return "getBlob"; case Types.ARRAY : return "getArray"; default: return "getString"; } } /** * JAVA SQL * @param obj * @return */ public static int getSqlTypes(Object obj){ Class<?> objectClass = obj.getClass(); if(char.class == objectClass){ return Types.CHAR; }else if(String.class == objectClass){ return Types.VARCHAR ; }else if(BigDecimal.class == objectClass){ return Types.NUMERIC; }else if(Boolean.class == objectClass){ return Types.BIT; }else if(Byte.class == objectClass){ return Types.TINYINT; }else if(Short.class == objectClass){ return Types.SMALLINT; }else if(Integer.class == objectClass){ return Types.INTEGER; }else if(Long.class == objectClass){ return Types.BIGINT; }else if(Float.class == objectClass){ return Types.FLOAT; }else if(Double.class == objectClass){ return Types.DOUBLE; }else if(Byte[].class == objectClass){ return Types.BINARY; }else if(Date.class == objectClass){ return Types.DATE; }else if(Time.class == objectClass){ return Types.TIME; }else if(Timestamp.class == objectClass){ return Types.TIMESTAMP; }else if(Clob.class == objectClass){ return Types.CLOB; }else if(Blob.class == objectClass){ return Types.BLOB; }else if(Object[].class == objectClass){ return Types.ARRAY; } return 0; } /** * * * @param connection * @return */ private static Map<DataSource, DataBaseType> DATABASE_TYPE_MAP = new ConcurrentHashMap<DataSource, DataBaseType>(); public static DataBaseType getDataBaseType(DataSource dataSource) { Connection connection = null; DataBaseType dataBaseType = DataBaseType.UNKNOW; try { dataBaseType = DATABASE_TYPE_MAP.get(dataSource); if (dataBaseType == null) { connection = dataSource.getConnection(); String driverName = connection.getMetaData().getDriverName(); //driverName if (connection.getMetaData().getDriverName().toUpperCase().indexOf("MYSQL") != -1) { dataBaseType = DataBaseType.MySql; } else if (connection.getMetaData().getDriverName().toUpperCase().indexOf("MARIADB") != -1) { dataBaseType = DataBaseType.Mariadb; } else if (connection.getMetaData().getDriverName().toUpperCase().indexOf("POSTAGE") != -1) { dataBaseType = DataBaseType.Postage; } else if (connection.getMetaData().getDriverName().toUpperCase().indexOf("ORACLE") != -1) { dataBaseType = DataBaseType.Oracle; } else { dataBaseType = DataBaseType.UNKNOW; } DATABASE_TYPE_MAP.put(dataSource, dataBaseType); } } catch (SQLException e) { dataBaseType = DataBaseType.UNKNOW; } finally { if(connection!=null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return dataBaseType; } /** * SQL * @param jdbcOperate jdbcOperate * @param sqlField sql * @return sql */ public static String wrapSqlField(JdbcOperate jdbcOperate, String sqlField) { DataBaseType dataBaseType = jdbcOperate.getDataBaseType(); if (dataBaseType.equals(DataBaseType.Mariadb) || dataBaseType.equals(DataBaseType.MySql)) { return "`"+sqlField+"`"; } else if (dataBaseType.equals(DataBaseType.Oracle)) { return "\""+sqlField+"\""; } else if (dataBaseType.equals(DataBaseType.Postage)) { return "`"+sqlField+"`"; } else { return sqlField; } } /** * Mysql sql * @param sql Sql * @param pageNumber * @param pageSize * @return sql */ public static String genMysqlPageSql(String sql, int pageNumber, int pageSize){ int pageStart = (pageNumber-1) * pageSize; if(pageSize<0 || pageNumber<0) { return sql; } return sql + " limit " + pageStart + ", " + pageSize; } /** * Postgre sql * @param sql Sql * @param pageNumber * @param pageSize * @return sql */ public static String genPostgrePageSql(String sql, int pageNumber, int pageSize){ int pageStart = (pageNumber-1) * pageSize; if(pageSize<0 || pageNumber<0) { return sql; } return sql + " limit " + pageSize + " offset " + pageStart; } /** * Oracle sql * @param sql Sql * @param pageNumber * @param pageSize * @return sql */ public static String genOraclePageSql(String sql, int pageNumber, int pageSize){ int pageStart = (pageNumber-1) * pageSize; int pageEnd = pageStart + pageSize; if(pageSize<0 || pageNumber<0) { return sql; } sql = sql.replaceFirst("select", "select rownum rn,"); sql = "select pageSql.* from (" + sql + " ) pageSql where rn between " + pageStart + " and " + pageEnd; return sql; } }
package bamboo.core; import com.google.common.net.InternetDomainName; import org.apache.commons.lang.StringEscapeUtils; import org.archive.url.URLParser; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.*; import org.skife.jdbi.v2.sqlobject.mixins.Transactional; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.regex.Pattern; public abstract class Db implements AutoCloseable, Transactional { public abstract void close(); public static class Collection { public final long id; public final String name; public final String cdxUrl; public final String solrUrl; public final long records; public final long recordBytes; public final String description; public Collection(ResultSet rs) throws SQLException { id = rs.getLong("id"); name = rs.getString("name"); cdxUrl = rs.getString("cdx_url"); solrUrl = rs.getString("solr_url"); records = rs.getLong("records"); recordBytes = rs.getLong("record_bytes"); description = rs.getString("description"); } } public static class CollectionMapper implements ResultSetMapper<Collection> { @Override public Collection map(int index, ResultSet rs, StatementContext ctx) throws SQLException { return new Collection(rs); } } public static class CollectionWithFilters extends Collection { public final String urlFilters; public CollectionWithFilters(ResultSet rs) throws SQLException { super(rs); urlFilters = rs.getString("url_filters"); } } public static class CollectionWithFiltersMapper implements ResultSetMapper<CollectionWithFilters> { @Override public CollectionWithFilters map(int index, ResultSet rs, StatementContext ctx) throws SQLException { return new CollectionWithFilters(rs); } } @SqlUpdate("SELECT COUNT(*) FROM collection") public abstract long countCollections(); @SqlQuery("SELECT * FROM collection ORDER BY name") public abstract Iterable<Collection> listCollections(); @SqlQuery("SELECT * FROM collection ORDER BY name LIMIT :limit OFFSET :offset") public abstract List<Collection> paginateCollections(@Bind("limit") long limit, @Bind("offset") long offset); @SqlUpdate("UPDATE collection SET records = records + :records, record_bytes = record_bytes + :bytes WHERE id = :id") public abstract int incrementRecordStatsForCollection(@Bind("id") long collectionId, @Bind("records") long records, @Bind("bytes") long bytes); @SqlQuery("SELECT collection.*, collection_series.url_filters FROM collection_series LEFT JOIN collection ON collection.id = collection_id WHERE crawl_series_id = :it") public abstract List<CollectionWithFilters> listCollectionsForCrawlSeries(@Bind long crawlSeriesId); @SqlUpdate("DELETE FROM collection_series WHERE crawl_series_id = :it") public abstract void removeCrawlSeriesFromAllCollections(@Bind long crawlSeriesId); @SqlBatch("INSERT INTO collection_series (crawl_series_id, collection_id, url_filters) VALUES (:crawl_series_id, :collection_id, :url_filters)") public abstract void addCrawlSeriesToCollections(@Bind("crawl_series_id") long crawlSeriesId, @Bind("collection_id") List<Long> collectionIds, @Bind("url_filters") List<String> urlFilters); @SqlQuery("SELECT * FROM collection WHERE id = :id") public abstract Collection findCollection(@Bind("id") long id); @SqlUpdate("INSERT INTO collection(name, description, cdx_url, solr_url) VALUES (:name, :description, :cdxUrl, :solrUrl)") @GetGeneratedKeys public abstract long createCollection(@Bind("name") String name, @Bind("description") String description, @Bind("cdxUrl") String cdxUrl, @Bind("solrUrl") String solrUrl); @SqlUpdate("UPDATE collection SET name = :name, description = :description, cdx_url = :cdxUrl, solr_url = :solrUrl WHERE id = :id") public abstract int updateCollection(@Bind("id") long collectionId, @Bind("name") String name, @Bind("description") String description, @Bind("cdxUrl") String cdxUrl, @Bind("solrUrl") String solrUrl); public static class CollectionWarc { public final long collectionId; public final long warcId; public final long records; public final long recordBytes; public CollectionWarc(ResultSet rs) throws SQLException { collectionId = rs.getLong("collection_id"); warcId = rs.getLong("warc_id"); records = rs.getLong("records"); recordBytes = rs.getLong("record_bytes"); } } public static class CollectionWarcMapper implements ResultSetMapper<CollectionWarc> { @Override public CollectionWarc map(int index, ResultSet r, StatementContext ctx) throws SQLException { return new CollectionWarc(r); } } @SqlQuery("SELECT * FROM collection_warc WHERE collection_id = :collectionId AND warc_id = :warcId") public abstract CollectionWarc findCollectionWarc(@Bind("collectionId") long collectionId, @Bind("warcId") long warcId); @SqlUpdate("DELETE FROM collection_warc WHERE collection_id = :collectionId AND warc_id = :warcId") public abstract int deleteCollectionWarc(@Bind("collectionId") long collectionId, @Bind("warcId") long warcId); @SqlUpdate("INSERT INTO collection_warc (collection_id, warc_id, records, record_bytes) VALUES (:collectionId, :warcId, :records, :recordBytes)") public abstract void insertCollectionWarc(@Bind("collectionId") long collectionId, @Bind("warcId") long warcId, @Bind("records") long records, @Bind("recordBytes") long recordBytes); public static class Crawl { public final long id; public final String name; public final Long totalDocs; public final Long totalBytes; public final Long crawlSeriesId; public final Path path; public final int state; public final long warcFiles; public final long warcSize; public final long records; public final long recordBytes; public final String description; public final Date startTime; public final Date endTime; public Crawl(ResultSet rs) throws SQLException { String path = rs.getString("path"); Integer state = (Integer)rs.getObject("state"); id = rs.getLong("id"); name = rs.getString("name"); totalDocs = (Long)rs.getObject("total_docs"); totalBytes = (Long)rs.getObject("total_bytes"); crawlSeriesId = (Long)rs.getObject("crawl_series_id"); this.path = path != null ? Paths.get(path) : null; this.state = state != null ? state : 0; warcFiles = rs.getLong("warc_files"); warcSize = rs.getLong("warc_size"); records = rs.getLong("records"); recordBytes = rs.getLong("record_bytes"); description = rs.getString("description"); startTime = (Date)rs.getObject("start_time"); endTime = (Date)rs.getObject("end_time"); } private static final String[] STATE_NAMES = {"Archived", "Importing", "Import Failed"}; public String stateName() { return STATE_NAMES[state]; } } public static class CrawlWithSeriesName extends Crawl { public final String seriesName; public CrawlWithSeriesName(ResultSet rs) throws SQLException { super(rs); this.seriesName = rs.getString("crawl_series.name"); } } public static class CrawlMapper implements ResultSetMapper<Crawl> { @Override public Crawl map(int index, ResultSet r, StatementContext ctx) throws SQLException { return new Crawl(r); } } public static class CrawlWithSeriesNameMapper implements ResultSetMapper<CrawlWithSeriesName> { @Override public CrawlWithSeriesName map(int index, ResultSet r, StatementContext ctx) throws SQLException { return new CrawlWithSeriesName(r); } } public static final int ARCHIVED = 0; public static final int IMPORTING = 1; public static final int IMPORT_FAILED = 2; @SqlUpdate("INSERT INTO crawl (name, crawl_series_id, state) VALUES (:name, :crawl_series_id, :state)") @GetGeneratedKeys public abstract long createCrawl(@Bind("name") String name, @Bind("crawl_series_id") Long crawlSeriesId, @Bind("state") int state); @SqlQuery("SELECT * FROM crawl WHERE id = :id") public abstract Crawl findCrawl(@Bind("id") long crawlId); @SqlQuery("SELECT * FROM crawl WHERE crawl_series_id = :crawl_series_id ORDER BY id DESC") public abstract Iterable<Crawl> findCrawlsByCrawlSeriesId(@Bind("crawl_series_id") long crawlSeriesId); @SqlQuery("SELECT * FROM crawl WHERE state = :state") public abstract List<Crawl> findCrawlsByState(@Bind("state") int state); @SqlUpdate("UPDATE crawl SET path = :path WHERE id = :id") public abstract int updateCrawlPath(@Bind("id") long id, @Bind("path") String path); @SqlUpdate("UPDATE crawl SET state = :state WHERE id = :crawlId") public abstract int updateCrawlState(@Bind("crawlId") long crawlId, @Bind("state") int state); @SqlUpdate("UPDATE crawl SET name = :name, description = :description WHERE id = :crawlId") public abstract int updateCrawl(@Bind("crawlId") long crawlId, @Bind("name") String name, @Bind("description") String description); @SqlUpdate("UPDATE crawl SET records = records + :records, record_bytes = record_bytes + :bytes WHERE id = :id") public abstract int incrementRecordStatsForCrawl(@Bind("id") long crawlId, @Bind("records") long records, @Bind("bytes") long bytes); @SqlUpdate("UPDATE crawl SET start_time = :time WHERE id = :crawlId AND (start_time IS NULL OR start_time > :time)") public abstract int conditionallyUpdateCrawlStartTime(@Bind("crawlId") long crawlId, @Bind("time") Date time); @SqlUpdate("UPDATE crawl SET end_time = :time WHERE id = :crawlId AND (end_time IS NULL OR end_time < :time)") public abstract int conditionallyUpdateCrawlEndTime(@Bind("crawlId") long crawlId, @Bind("time") Date time); @SqlQuery("SELECT crawl.*, crawl_series.name FROM crawl LEFT JOIN crawl_series ON crawl.crawl_series_id = crawl_series.id ORDER BY crawl.end_time DESC, crawl.id DESC LIMIT :limit OFFSET :offset") public abstract List<CrawlWithSeriesName> paginateCrawlsWithSeriesName(@Bind("limit") long limit, @Bind("offset") long offset); @SqlQuery("SELECT COUNT(*) FROM crawl") public abstract long countCrawls(); @SqlUpdate("UPDATE crawl SET warc_files = (SELECT COALESCE(COUNT(*), 0) FROM warc WHERE warc.crawl_id = crawl.id), warc_size = (SELECT COALESCE(SUM(size), 0) FROM warc WHERE warc.crawl_id = crawl.id), records = (SELECT COALESCE(SUM(records), 0) FROM warc WHERE warc.crawl_id = crawl.id), record_bytes = (SELECT COALESCE(SUM(record_bytes), 0) FROM warc WHERE warc.crawl_id = crawl.id)") public abstract int refreshWarcStatsOnCrawls(); public static class CrawlSeries { public final long id; public final String name; public final Path path; public final long warcFiles; public final long warcSize; public final long records; public final long recordBytes; public final String description; public CrawlSeries(ResultSet rs) throws SQLException { id = rs.getLong("id"); name = rs.getString("name"); path = Paths.get(rs.getString("path")); warcFiles = rs.getLong("warc_files"); warcSize = rs.getLong("warc_size"); records = rs.getLong("records"); recordBytes = rs.getLong("record_bytes"); description = rs.getString("description"); } } public static class CrawlSeriesWithCount extends CrawlSeries { public final long crawlCount; public CrawlSeriesWithCount(ResultSet rs) throws SQLException { super(rs); crawlCount = rs.getLong("crawl_count"); } } public static class CrawlSeriesMapper implements ResultSetMapper<CrawlSeries> { @Override public CrawlSeries map(int index, ResultSet r, StatementContext ctx) throws SQLException { return new CrawlSeries(r); } } public static class CrawlSeriesWithCountMapper implements ResultSetMapper<CrawlSeriesWithCount> { @Override public CrawlSeriesWithCount map(int index, ResultSet r, StatementContext ctx) throws SQLException { return new CrawlSeriesWithCount(r); } } @SqlQuery("SELECT * FROM crawl_series WHERE id = :id") public abstract CrawlSeries findCrawlSeriesById(@Bind("id") long crawlSeriesId); @SqlQuery("SELECT * FROM crawl_series ORDER BY name") public abstract List<CrawlSeries> listCrawlSeries(); @SqlQuery("SELECT COUNT(*) FROM crawl_series") public abstract long countCrawlSeries(); @SqlQuery("SELECT *, (SELECT COUNT(*) FROM crawl WHERE crawl_series_id = crawl_series.id) crawl_count FROM crawl_series ORDER BY name LIMIT :limit OFFSET :offset") public abstract List<CrawlSeriesWithCount> paginateCrawlSeries(@Bind("limit") long limit, @Bind("offset") long offset); @SqlUpdate("UPDATE crawl_series SET records = records + :records, record_bytes = record_bytes + :bytes WHERE id = :id") public abstract int incrementRecordStatsForCrawlSeries(@Bind("id") long crawlSeriesId, @Bind("records") long records, @Bind("bytes") long bytes); @SqlUpdate("INSERT INTO crawl_series (name, path) VALUES (:name, :path)") @GetGeneratedKeys public abstract long createCrawlSeries(@Bind("name") String name, @Bind("path") String path); @SqlUpdate("UPDATE crawl_series SET name = :name, path = :path, description = :description WHERE id = :id") public abstract int updateCrawlSeries(@Bind("id") long seriesId, @Bind("name") String name, @Bind("path") String path, @Bind("description") String description); @Transaction public int updateCrawlSeries(long seriesId, String name, String path, String description, List<Long> collectionIds, List<String> collectionUrlFilters) { int rows = updateCrawlSeries(seriesId, name, path, description); if (rows > 0) { removeCrawlSeriesFromAllCollections(seriesId); addCrawlSeriesToCollections(seriesId, collectionIds, collectionUrlFilters); } return rows; } @SqlUpdate("UPDATE crawl_series SET warc_files = (SELECT COALESCE(SUM(warc_files), 0) FROM crawl WHERE crawl.crawl_series_id = crawl_series.id), warc_size = (SELECT COALESCE(SUM(warc_size), 0) FROM crawl WHERE crawl.crawl_series_id = crawl_series.id), records = (SELECT COALESCE(SUM(records), 0) FROM crawl WHERE crawl.crawl_series_id = crawl_series.id), record_bytes = (SELECT COALESCE(SUM(record_bytes), 0) FROM crawl WHERE crawl.crawl_series_id = crawl_series.id)") public abstract int refreshWarcStatsOnCrawlSeries(); public static class Seed { public final long id; public final String url; public final String surt; public final long seedlistId; public Seed(ResultSet rs) throws SQLException { id = rs.getLong("id"); url = rs.getString("url"); surt = rs.getString("surt"); seedlistId = rs.getLong("seedlist_id"); } public String topPrivateDomain() { try { return InternetDomainName.from(URLParser.parse(url).getHost()).topPrivateDomain().toString(); } catch (URISyntaxException e) { return url; } } public String highlighted() { String domain = StringEscapeUtils.escapeHtml(topPrivateDomain()); String pattern = "(" + Pattern.quote(domain) + ")([:/]|$)"; return "<span class='hlurl'>" + url.replaceFirst(pattern, "<span class='domain'>$1</span>$2") + "</span>"; } } public static class SeedMapper implements ResultSetMapper<Seed> { @Override public Seed map(int i, ResultSet resultSet, StatementContext statementContext) throws SQLException { return new Seed(resultSet); } } @SqlQuery("SELECT * FROM seed WHERE seedlist_id = :id ORDER BY surt") public abstract List<Seed> findSeedsBySeedListId(@Bind("id") long seedlistId); @SqlBatch("INSERT INTO seed (seedlist_id, url, surt) VALUES (:seedlistId, :urls, :surts)") public abstract void insertSeedsOnly(@Bind("seedlistId") long seedlistId, @Bind("urls") List<String> urls, @Bind("surts") List<String> surts); @SqlUpdate("DELETE FROM seed WHERE seedlist_id = :seedlistId") public abstract int deleteSeedsBySeedlistId(@Bind("seedlistId") long seedlistId); public static class Seedlist { public final long id; public final String name; public final String description; public final long totalSeeds; public Seedlist(ResultSet rs) throws SQLException { id = rs.getLong("id"); name = rs.getString("name"); description = rs.getString("description"); totalSeeds = rs.getLong("total_seeds"); } } public static class SeedlistMapper implements ResultSetMapper<Seedlist> { @Override public Seedlist map(int i, ResultSet resultSet, StatementContext statementContext) throws SQLException { return new Seedlist(resultSet); } } @SqlQuery("SELECT * FROM seedlist") public abstract List<Seedlist> listSeedlists(); @SqlUpdate("INSERT INTO seedlist (name, description) VALUES (:name, :description)") @GetGeneratedKeys public abstract long createSeedlist(@Bind("name") String name, @Bind("description") String description); @SqlUpdate("UPDATE seedlist SET name = :name, description = :description WHERE id = :id") public abstract int updateSeedlist(@Bind("id") long id, @Bind("name") String name, @Bind("description") String description); @SqlUpdate("UPDATE seedlist SET name = :name, description = :description, total_seeds = :totalSeeds WHERE id = :id") public abstract int updateSeedlist(@Bind("id") long id, @Bind("name") String name, @Bind("description") String description, @Bind("totalSeeds") long totalSeeds); @SqlQuery("SELECT * FROM seedlist WHERE id = :id") public abstract Seedlist findSeedlist(@Bind("id") long id); @SqlUpdate("DELETE FROM seedlist WHERE id = :seedlistId") public abstract int deleteSeedlistOnly(@Bind("seedlistId") long seedlistId); @Transaction public int deleteSeedlist(long seedlistId) { deleteSeedsBySeedlistId(seedlistId); return deleteSeedlistOnly(seedlistId); } @SqlUpdate("UPDATE seedlist SET total_seeds = total_seeds + :delta WHERE id = :id") public abstract int incrementSeedlistTotalSeeds(@Bind("id") long id, @Bind("delta") long delta); @Transaction public void insertSeeds(long seedlistId, List<String> urls, List<String> surts) { insertSeedsOnly(seedlistId, urls, surts); incrementSeedlistTotalSeeds(seedlistId, urls.size()); } @Transaction public void updateSeedlist(long seedlistId, String name, String description, List<String> urls, List<String> surts) { assert(urls.size() == surts.size()); deleteSeedsBySeedlistId(seedlistId); insertSeedsOnly(seedlistId, urls, surts); updateSeedlist(seedlistId, name, description, urls.size()); } public static class Warc { public final static int OPEN = 0, IMPORTED = 1, CDX_INDEXED = 2, SOLR_INDEXED = 3; public final static int IMPORT_ERROR = -1, CDX_ERROR = -2, SOLR_ERROR = -3; public final long id; public final long crawlId; public final int stateId; public final Path path; public final long size; public final long records; public final long recordBytes; public final String filename; public final String sha256; public Warc(ResultSet rs) throws SQLException { id = rs.getLong("id"); crawlId = rs.getLong("crawl_id"); stateId= rs.getInt("warc_state_id"); path = Paths.get(rs.getString("path")); size = rs.getLong("size"); records = rs.getLong("records"); recordBytes = rs.getLong("record_bytes"); filename = rs.getString("filename"); sha256 = rs.getString("sha256"); } } public static class WarcMapper implements ResultSetMapper<Warc> { @Override public Warc map(int i, ResultSet resultSet, StatementContext statementContext) throws SQLException { return new Warc(resultSet); } } @Transaction public long insertWarc(long crawlId, int stateId, String path, String filename, long size, String sha256) { incrementWarcStatsForCrawl(crawlId, 1, size); incrementWarcStatsForCrawlSeriesByCrawlId(crawlId, 1, size); long warcId = insertWarcWithoutRollup(crawlId, stateId, path, filename, size, sha256); insertWarcHistory(warcId, stateId); return warcId; } @Transaction public int updateWarc(long crawlId, long warcId, int stateId, String path, String filename, long oldSize, long size, String sha256) { int rows = updateWarcWithoutRollup(warcId, stateId, path, filename, size, sha256); if (rows > 0) { insertWarcHistory(warcId, stateId); incrementWarcStatsForCrawl(crawlId, 0, size - oldSize); incrementWarcStatsForCrawlSeriesByCrawlId(crawlId, 0, size - oldSize); } return rows; } @Transaction public int updateWarcSize(long crawlId, long warcId, long oldSize, long size) { int rows = updateWarcSizeWithoutRollup(warcId, size); if (rows > 0) { incrementWarcStatsForCrawl(crawlId, 0, size - oldSize); incrementWarcStatsForCrawlSeriesByCrawlId(crawlId, 0, size - oldSize); } return rows; } @SqlQuery("SELECT crawl_id FROM warc WHERE id = :warcId") public abstract long findCrawlIdForWarc(@Bind("warcId") long warcId); @SqlUpdate("UPDATE warc SET warc_state_id = :stateId, path = :path, filename = :filename, size = :size, sha256 = :sha256 WHERE id = :warcId") public abstract int updateWarcWithoutRollup(@Bind("warcId") long warcId, @Bind("stateId") int stateId, @Bind("path") String path, @Bind("filename") String filename, @Bind("size") long size, @Bind("sha256") String sha256); @SqlUpdate("UPDATE crawl_series SET warc_files = warc_files + :warc_files, warc_size = warc_size + :warc_size WHERE id = (SELECT crawl_series_id FROM crawl WHERE crawl.id = :crawl_id)") public abstract void incrementWarcStatsForCrawlSeriesByCrawlId(@Bind("crawl_id") long crawlId, @Bind("warc_files") int warcFilesDelta, @Bind("warc_size") long warcSizeDelta); @SqlUpdate("UPDATE crawl SET warc_files = warc_files + :warc_files, warc_size = warc_size + :warc_size WHERE id = :crawlId") public abstract void incrementWarcStatsForCrawl(@Bind("crawlId") long crawlId, @Bind("warc_files") int warcFilesDelta, @Bind("warc_size") long warcSizeDelta); @SqlUpdate("INSERT INTO warc (crawl_id, path, filename, size, warc_state_id, sha256) VALUES (:crawlId, :path, :filename, :size, :stateId, :sha256)") @GetGeneratedKeys public abstract long insertWarcWithoutRollup(@Bind("crawlId") long crawlId, @Bind("stateId") int stateId, @Bind("path") String path, @Bind("filename") String filename, @Bind("size") long size, @Bind("sha256") String sha256); @SqlQuery("SELECT * FROM warc") public abstract List<Warc> listWarcs(); @SqlQuery("SELECT * FROM warc WHERE id = :warcId") public abstract Warc findWarc(@Bind("warcId") long warcId); @SqlQuery("SELECT * FROM warc WHERE filename = :filename") public abstract Warc findWarcByFilename(@Bind("filename") String filename); @SqlQuery("SELECT * FROM warc WHERE crawl_id = :crawlId") public abstract List<Warc> findWarcsByCrawlId(@Bind("crawlId") long crawlId); @SqlQuery("SELECT * FROM warc WHERE warc_state_id = :stateId LIMIT :limit") public abstract List<Warc> findWarcsInState(@Bind("stateId") int stateId, @Bind("limit") int limit); @SqlQuery("SELECT COUNT(*) FROM warc WHERE warc_state_id = :stateId") public abstract long countWarcsInState(@Bind("stateId") int stateId); @SqlQuery("SELECT * FROM warc WHERE warc_state_id = :stateId LIMIT :limit OFFSET :offset") public abstract List<Warc> paginateWarcsInState(@Bind("stateId") int stateId, @Bind("limit") long limit, @Bind("offset") long offset); @SqlQuery("SELECT * FROM warc WHERE crawl_id = :crawlId ORDER BY filename LIMIT :limit OFFSET :offset") public abstract List<Warc> paginateWarcsInCrawl(@Bind("crawlId") long crawlId, @Bind("limit") long limit, @Bind("offset") long offset); @SqlQuery("SELECT * FROM warc WHERE crawl_id = :crawlId AND warc_state_id = :stateId LIMIT :limit OFFSET :offset") public abstract List<Warc> paginateWarcsInCrawlAndState(@Bind("crawlId") long crawlId, @Bind("stateId") int stateId, @Bind("limit") long limit, @Bind("offset") long offset); @SqlQuery("SELECT COUNT(*) FROM warc WHERE crawl_id = :it AND warc_state_id = :stateId") public abstract long countWarcsInCrawlAndState(@Bind long crawlId, @Bind("stateId") int stateId); @Transaction public int updateWarcState(long warcId, int stateId) { int rows = updateWarcStateWithoutHistory(warcId, stateId); if (rows > 0) { insertWarcHistory(warcId, stateId); } return rows; } @SqlUpdate("UPDATE warc SET warc_state_id = :stateId WHERE id = :warcId") public abstract int updateWarcStateWithoutHistory(@Bind("warcId") long warcId, @Bind("stateId") int stateId); @SqlUpdate("INSERT INTO warc_history (warc_id, warc_state_id) VALUES (:warcId, :stateId)") public abstract int insertWarcHistory(@Bind("warcId") long warcId, @Bind("stateId") int stateId); @SqlUpdate("UPDATE warc SET records = :records, record_bytes = :record_bytes WHERE id = :id") public abstract int updateWarcRecordStats(@Bind("id") long warcId, @Bind("records") long records, @Bind("record_bytes") long recordBytes); @SqlUpdate("UPDATE warc SET size = :size WHERE id = :id") public abstract int updateWarcSizeWithoutRollup(@Bind("id") long warcId, @Bind("size") long size); @SqlUpdate("UPDATE warc SET sha256 = :digest WHERE id = :id") public abstract int updateWarcSha256(@Bind("id") long id, @Bind("digest") String digest); @SqlQuery("SELECT name FROM warc_state WHERE id = :stateId") public abstract String findWarcStateName(@Bind("stateId") int stateId); }
package erogenousbeef.bigreactors.common; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.EnumRarity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; import erogenousbeef.bigreactors.api.IHeatEntity; import erogenousbeef.bigreactors.common.block.BlockBRGenericFluid; import erogenousbeef.bigreactors.common.block.BlockBROre; import erogenousbeef.bigreactors.common.block.BlockBRSmallMachine; import erogenousbeef.bigreactors.common.block.BlockFuelRod; import erogenousbeef.bigreactors.common.block.BlockReactorControlRod; import erogenousbeef.bigreactors.common.block.BlockReactorGlass; import erogenousbeef.bigreactors.common.block.BlockReactorPart; import erogenousbeef.bigreactors.common.block.BlockReactorRedstonePort; import erogenousbeef.bigreactors.common.item.ItemBRBucket; import erogenousbeef.bigreactors.common.item.ItemBlockBROre; import erogenousbeef.bigreactors.common.item.ItemBlockBigReactors; import erogenousbeef.bigreactors.common.item.ItemBlockReactorPart; import erogenousbeef.bigreactors.common.item.ItemBlockSmallMachine; import erogenousbeef.bigreactors.common.item.ItemBlockYelloriumFuelRod; import erogenousbeef.bigreactors.common.item.ItemIngot; import erogenousbeef.bigreactors.common.multiblock.MultiblockReactor; import erogenousbeef.bigreactors.common.tileentity.TileEntityCyaniteReprocessor; import erogenousbeef.bigreactors.common.tileentity.TileEntityFuelRod; import erogenousbeef.bigreactors.common.tileentity.TileEntityRTG; import erogenousbeef.bigreactors.common.tileentity.TileEntityReactorAccessPort; import erogenousbeef.bigreactors.common.tileentity.TileEntityReactorComputerPort; import erogenousbeef.bigreactors.common.tileentity.TileEntityReactorControlRod; import erogenousbeef.bigreactors.common.tileentity.TileEntityReactorGlass; import erogenousbeef.bigreactors.common.tileentity.TileEntityReactorPart; import erogenousbeef.bigreactors.common.tileentity.TileEntityReactorPowerTap; import erogenousbeef.bigreactors.common.tileentity.TileEntityReactorRedNetPort; import erogenousbeef.bigreactors.common.tileentity.TileEntityReactorRedstonePort; import erogenousbeef.bigreactors.world.BRSimpleOreGenerator; import erogenousbeef.bigreactors.world.BRWorldGenerator; public class BigReactors { public static final String NAME = "Big Reactors"; public static final String CHANNEL = "BigReactors"; public static final String RESOURCE_PATH = "/assets/bigreactors/"; public static final CreativeTabs TAB = new CreativeTabBR(CreativeTabs.getNextID(), CHANNEL); public static final String TEXTURE_NAME_PREFIX = "bigreactors:"; public static final String TEXTURE_DIRECTORY = RESOURCE_PATH + "textures/"; public static final String GUI_DIRECTORY = TEXTURE_NAME_PREFIX + "textures/gui/"; public static final String BLOCK_TEXTURE_DIRECTORY = TEXTURE_DIRECTORY + "blocks/"; public static final String ITEM_TEXTURE_DIRECTORY = TEXTURE_DIRECTORY + "items/"; public static final String MODEL_TEXTURE_DIRECTORY = TEXTURE_DIRECTORY + "models/"; public static final String LANGUAGE_PATH = RESOURCE_PATH + "languages/"; private static final String[] LANGUAGES_SUPPORTED = new String[] { "en_US" }; public static final int BLOCK_ID_PREFIX = 1750; public static Block blockYelloriteOre; public static Block blockYelloriumFuelRod; public static Block blockReactorPart; public static Block blockReactorGlass; public static Block blockReactorControlRod; public static Block blockReactorRedstonePort; // UGH. Why does the redstone API not allow me to check metadata? :( public static Block blockRadiothermalGen; public static Block blockSmallMachine; public static Block fluidYelloriumStill; public static Block fluidCyaniteStill; public static Block fluidFuelColumnStill; // Buckets for bucketing reactor fluids public static Item fluidYelloriumBucketItem; public static Item fluidCyaniteBucketItem; public static Fluid fluidYellorium; public static Fluid fluidCyanite; public static Fluid fluidFuelColumn; public static final int defaultFluidColorFuel = 0xbcba50; public static final int defaultFluidColorWaste = 0x4d92b5; public static final int ITEM_ID_PREFIX = 17750; public static ItemIngot ingotGeneric; public static BRSimpleOreGenerator yelloriteOreGeneration; public static boolean INITIALIZED = false; public static boolean enableWorldGen = true; public static boolean enableWorldGenInNegativeDimensions = false; public static boolean enableWorldRegeneration = true; public static int userWorldGenVersion = 0; public static BREventHandler eventHandler = null; public static BigReactorsTickHandler tickHandler = null; public static BRWorldGenerator worldGenerator = null; private static boolean registeredTileEntities = false; public static int maximumReactorSize = MultiblockReactor.DIMENSION_UNBOUNDED; public static int maximumReactorHeight = MultiblockReactor.DIMENSION_UNBOUNDED; public static int ticksPerRedstoneUpdate = 20; // Once per second, roughly public static float powerProductionMultiplier = 1.0f; // Game Balance values public static final float powerPerHeat = IHeatEntity.powerPerHeat; // RF units per C dissipated /** * Call this function in your mod init stage. */ public static void register(Object modInstance) { if (!INITIALIZED) { loadLanguages(BigReactors.LANGUAGE_PATH, LANGUAGES_SUPPORTED); // General config loading BRConfig.CONFIGURATION.load(); enableWorldGen = BRConfig.CONFIGURATION.get("WorldGen", "enableWorldGen", true, "If false, disables all world gen from Big Reactors; all other worldgen settings are automatically overridden").getBoolean(true); enableWorldGenInNegativeDimensions = BRConfig.CONFIGURATION.get("WorldGen", "enableWorldGenInNegativeDims", false, "Run BR world generation in negative dimension IDs? (default: false) If you don't know what this is, leave it alone.").getBoolean(false); enableWorldRegeneration = BRConfig.CONFIGURATION.get("WorldGen", "enableWorldRegeneration", false, "Run BR World Generation in chunks that have already been generated, but have not been modified by Big Reactors before. This is largely useful for worlds that existed before BigReactors was released.").getBoolean(false); userWorldGenVersion = BRConfig.CONFIGURATION.get("WorldGen", "userWorldGenVersion", 0, "User-set world generation version. Increase this by 1 if you want Big Reactors to re-run world generation in your world.").getInt(); boolean registerCoalFurnaceRecipe = BRConfig.CONFIGURATION.get("Recipes", "registerCoalForSmelting", true, "If set, coal will be smeltable into graphite bars. Disable this if other mods need to smelt coal into their own products. (Default: true)").getBoolean(true); boolean registerCharcoalFurnaceRecipe = BRConfig.CONFIGURATION.get("Recipes", "registerCharcoalForSmelting", true, "If set, charcoal will be smeltable into graphite bars. Disable this if other mods need to smelt charcoal into their own products. (Default: true)").getBoolean(true); boolean registerCoalCraftingRecipe = BRConfig.CONFIGURATION.get("Recipes", "registerGraphiteCoalCraftingRecipes", false, "If set, graphite bars can be crafted from 2 gravel, 1 coal. Use this if other mods interfere with the smelting recipe. (Default: false)").getBoolean(false); boolean registerCharcoalCraftingRecipe = BRConfig.CONFIGURATION.get("Recipes", "registerGraphiteCharcoalCraftingRecipes", false, "If set, graphite bars can be crafted from 2 gravel, 1 charcoal. Use this if other mods interfere with the smelting recipe. (Default: false)").getBoolean(false); maximumReactorSize = BRConfig.CONFIGURATION.get("General", "maxReactorSize", 32, "The maximum valid size of a reactor in the X/Z plane, in blocks. Lower this if your server's players are building ginormous reactors.").getInt(); maximumReactorHeight = BRConfig.CONFIGURATION.get("General", "maxReactorHeight", 48, "The maximum valid size of a reactor in the Y dimension, in blocks. Lower this if your server's players are building ginormous reactors. Bigger Y sizes have far less performance impact than X/Z sizes.").getInt(); ticksPerRedstoneUpdate = BRConfig.CONFIGURATION.get("General", "ticksPerRedstoneUpdate", 20, "Number of ticks between updates for redstone/rednet ports.").getInt(); powerProductionMultiplier = (float)BRConfig.CONFIGURATION.get("General", "powerProductionMultiplier", 1.0f, "A multiplier for balancing overall power production from Big Reactors. Defaults to 1.").getDouble(1.0); BRConfig.CONFIGURATION.save(); if(enableWorldGen) { worldGenerator = new BRWorldGenerator(); GameRegistry.registerWorldGenerator(worldGenerator); } /* * Register Recipes */ // Recipe Registry // Yellorium if (blockYelloriteOre != null) { FurnaceRecipes.smelting().addSmelting(blockYelloriteOre.blockID, 0, OreDictionary.getOres("ingotUranium").get(0), 0.5f); } if(ingotGeneric != null) { // Kind of a hack. Maps all ItemIngot dusts to ingots. for(int i = 0; i < ItemIngot.DUST_OFFSET; i++) { FurnaceRecipes.smelting().addSmelting(ingotGeneric.itemID, i+ItemIngot.DUST_OFFSET, new ItemStack(ingotGeneric, 1, i), 0f); } } ItemStack ingotUranium = null; ItemStack ingotCyanite = null; ItemStack ingotGraphite = null; if(OreDictionary.getOres("ingotUranium") != null) { ingotUranium = OreDictionary.getOres("ingotUranium").get(0); } if(OreDictionary.getOres("ingotDepletedUranium") != null) { ingotCyanite = OreDictionary.getOres("ingotCyanite").get(0); } if(OreDictionary.getOres("ingotGraphite") != null) { ingotGraphite = OreDictionary.getOres("ingotGraphite").get(0); } if(registerCoalFurnaceRecipe) { // Coal -> Graphite FurnaceRecipes.smelting().addSmelting(Item.coal.itemID, 0, ingotGraphite, 1); } if(registerCharcoalFurnaceRecipe) { // Charcoal -> Graphite FurnaceRecipes.smelting().addSmelting(Item.coal.itemID, 1, ingotGraphite, 1); } if(registerCoalCraftingRecipe) { GameRegistry.addRecipe(new ShapedOreRecipe( ingotGraphite.copy(), new Object[] { "GCG", 'G', Block.gravel, 'C', new ItemStack(Item.coal, 1, 0) } )); } if(registerCharcoalCraftingRecipe) { GameRegistry.addRecipe(new ShapedOreRecipe( ingotGraphite.copy(), new Object[] { "GCG", 'G', Block.gravel, 'C', new ItemStack(Item.coal, 1, 1) } )); } // Basic Parts: Reactor Casing, Fuel Rods if(blockYelloriumFuelRod != null) { GameRegistry.addRecipe(new ShapedOreRecipe( new ItemStack(blockYelloriumFuelRod, 1), new Object[] { "ICI", "IUI", "ICI", 'I', "ingotIron", 'C', "ingotGraphite", 'U', "ingotUranium" } )); } if(blockReactorPart != null) { ItemStack reactorPartStack = ((BlockReactorPart) BigReactors.blockReactorPart).getReactorCasingItemStack(); reactorPartStack.stackSize = 4; GameRegistry.addRecipe(new ShapedOreRecipe(reactorPartStack, new Object[] { "ICI", "CUC", "ICI", 'I', "ingotIron", 'C', "ingotGraphite", 'U', "ingotUranium" })); } // Advanced Parts: Control Rod, Access Port, Power Tap, Controller if(blockReactorPart != null) { ItemStack reactorPartStack = ((BlockReactorPart) BigReactors.blockReactorPart).getReactorControllerItemStack(); GameRegistry.addRecipe(new ShapedOreRecipe(reactorPartStack, new Object[] { "C C", "GDG", "CRC", 'D', Item.diamond, 'G', "ingotUranium", 'C', "reactorCasing", 'R', Item.redstone })); reactorPartStack = ((BlockReactorPart) BigReactors.blockReactorPart).getReactorPowerTapItemStack(); GameRegistry.addRecipe(new ShapedOreRecipe(reactorPartStack, new Object[] { "CRC", "R R", "CRC", 'C', "reactorCasing", 'R', Item.redstone })); reactorPartStack = ((BlockReactorPart) BigReactors.blockReactorPart).getAccessPortItemStack(); GameRegistry.addRecipe(new ShapedOreRecipe(reactorPartStack, new Object[] { "C C", " V ", "CPC", 'C', "reactorCasing", 'V', Block.chest, 'P', Block.pistonBase })); if(Loader.isModLoaded("MineFactoryReloaded")) { reactorPartStack = ((BlockReactorPart) BigReactors.blockReactorPart).getRedNetPortItemStack(); GameRegistry.addRecipe(new ShapedOreRecipe(reactorPartStack, new Object[] { "CRC", "RGR", "CRC", 'C', "reactorCasing", 'R', "cableRedNet", 'G', Item.ingotGold })); } if(Loader.isModLoaded("ComputerCraft")) { reactorPartStack = ((BlockReactorPart) BigReactors.blockReactorPart).getComputerPortItemStack(); GameRegistry.addRecipe(new ShapedOreRecipe(reactorPartStack, new Object[] { "CRC", "GPG", "CRC", 'C', "reactorCasing", 'R', Item.redstone, 'G', Item.ingotGold, 'P', "reactorRedstonePort" })); } } if(blockReactorGlass != null) { ItemStack reactorGlassStack = new ItemStack(BigReactors.blockReactorGlass, 2); GameRegistry.addRecipe(new ShapedOreRecipe(reactorGlassStack, new Object[] { " ", "GCG", " ", 'G', Block.glass, 'C', "reactorCasing" } )); if(OreDictionary.getOres("glass").size() > 0) { GameRegistry.addRecipe(new ShapedOreRecipe(reactorGlassStack, new Object[] { " ", "GCG", " ", 'G', "glass", 'C', "reactorCasing" } )); } } if(blockReactorControlRod != null) { ItemStack reactorControlRodStack = new ItemStack(BigReactors.blockReactorControlRod, 1); GameRegistry.addRecipe(new ShapedOreRecipe(reactorControlRodStack, new Object[] { "CGC", "GRG", "CUC", 'G', "ingotGraphite", 'C', "reactorCasing", 'R', Item.redstone, 'U', "ingotUranium" })); } if(blockSmallMachine != null) { ItemStack cyaniteReprocessorStack = ((BlockBRSmallMachine)blockSmallMachine).getCyaniteReprocessorItemStack(); GameRegistry.addRecipe(new ShapedOreRecipe(cyaniteReprocessorStack, new Object[] { "CIC", "PFP", "CRC", 'C', "reactorCasing", 'I', "ingotIron", 'F', blockYelloriumFuelRod, 'P', Block.pistonBase, 'R', Item.redstone})); } if(blockReactorRedstonePort != null) { ItemStack redstonePortStack = new ItemStack(BigReactors.blockReactorRedstonePort, 1); GameRegistry.addRecipe(new ShapedOreRecipe(redstonePortStack, new Object[] { "CRC", "RGR", "CRC", 'C', "reactorCasing", 'R', Item.redstone, 'G', Item.ingotGold })); } /* TODO: Fixme if(blockRadiothermalGen != null) { GameRegistry.addRecipe(new ItemStack(blockRadiothermalGen, 1), new Object[] { "III", "IUI", "III", Character.valueOf('I'), Item.ingotIron, Character.valueOf('U'), new ItemStack(blockYelloriumFuelRod, 1) }); } */ registerReactorFuelData(); } INITIALIZED = true; } /** * Call this to register Tile Entities * * @return */ public static void registerTileEntities() { if (!registeredTileEntities) { GameRegistry.registerTileEntity(TileEntityReactorPowerTap.class, "BRReactorPowerTap"); GameRegistry.registerTileEntity(TileEntityReactorPart.class, "BRReactorPart"); GameRegistry.registerTileEntity(TileEntityReactorAccessPort.class, "BRReactorAccessPort"); GameRegistry.registerTileEntity(TileEntityReactorGlass.class, "BRReactorGlass"); GameRegistry.registerTileEntity(TileEntityFuelRod.class, "BRFuelRod"); GameRegistry.registerTileEntity(TileEntityRTG.class, "BRRadiothermalGen"); GameRegistry.registerTileEntity(TileEntityCyaniteReprocessor.class, "BRCyaniteReprocessor"); GameRegistry.registerTileEntity(TileEntityReactorControlRod.class, "BRReactorControlRod"); GameRegistry.registerTileEntity(TileEntityReactorRedNetPort.class, "BRReactorRedNetPort"); GameRegistry.registerTileEntity(TileEntityReactorRedstonePort.class,"BRReactorRedstonePort"); GameRegistry.registerTileEntity(TileEntityReactorComputerPort.class, "BRReactorComputerPort"); registeredTileEntities = true; } } public static ItemStack registerOres(int i, boolean b) { BRConfig.CONFIGURATION.load(); if (blockYelloriteOre == null) { blockYelloriteOre = new BlockBROre(BRConfig.CONFIGURATION.getBlock("YelloriteOre", BigReactors.BLOCK_ID_PREFIX + 0).getInt()); GameRegistry.registerBlock(BigReactors.blockYelloriteOre, ItemBlockBROre.class, "YelloriteOre"); OreDictionary.registerOre("oreYellorite", blockYelloriteOre); } boolean genYelloriteOre = BRConfig.CONFIGURATION.get("WorldGen", "GenerateYelloriteOre", true, "Add yellorite ore during world generation?").getBoolean(true); if (yelloriteOreGeneration == null && genYelloriteOre) { // Magic number: 1 = stone int clustersPerChunk; int orePerCluster; int maxY; clustersPerChunk = BRConfig.CONFIGURATION.get("WorldGen", "MaxYelloriteClustersPerChunk", 5, "Maximum number of clusters per chunk; will generate at least half this number, rounded down").getInt(); orePerCluster = BRConfig.CONFIGURATION.get("WorldGen", "MaxYelloriteOrePerCluster", 10, "Maximum number of blocks to generate in each cluster; will usually generate at least half this number").getInt(); maxY = BRConfig.CONFIGURATION.get("WorldGen", "YelloriteMaxY", 50, "Maximum height (Y coordinate) in the world to generate yellorite ore").getInt(); int[] dimensionBlacklist = BRConfig.CONFIGURATION.get("WorldGen", "YelloriteDimensionBlacklist", new int[] {}, "Dimensions in which yellorite ore should not be generated; Nether/End automatically included").getIntList(); yelloriteOreGeneration = new BRSimpleOreGenerator(blockYelloriteOre.blockID, 0, Block.stone.blockID, clustersPerChunk/2, clustersPerChunk, 4, maxY, orePerCluster); // Per KingLemming's request, bonus yellorite around y12. :) BRSimpleOreGenerator yelloriteOreGeneration2 = new BRSimpleOreGenerator(blockYelloriteOre.blockID, 0, Block.stone.blockID, 1, 2, 11, 13, orePerCluster); if(dimensionBlacklist != null) { for(int dimension : dimensionBlacklist) { yelloriteOreGeneration.blacklistDimension(dimension); yelloriteOreGeneration2.blacklistDimension(dimension); } } BRWorldGenerator.addGenerator(BigReactors.yelloriteOreGeneration); BRWorldGenerator.addGenerator(yelloriteOreGeneration2); } BRConfig.CONFIGURATION.save(); return new ItemStack(blockYelloriteOre); } public static ItemStack registerIngots(int id, boolean require) { if (BigReactors.ingotGeneric == null) { BRConfig.CONFIGURATION.load(); BigReactors.ingotGeneric = new ItemIngot(BRConfig.CONFIGURATION.getItem("IngotYellorium", BigReactors.ITEM_ID_PREFIX + 0).getInt()); if (OreDictionary.getOres("ingotUranium").size() <= 0 || require) { ItemStack yelloriumStack = new ItemStack(ingotGeneric, 1, 0); OreDictionary.registerOre("ingotUranium", yelloriumStack); } if (OreDictionary.getOres("ingotCyanite").size() <= 0 || require) { ItemStack cyaniteStack = new ItemStack(ingotGeneric, 1, 1); OreDictionary.registerOre("ingotCyanite", cyaniteStack); } if (OreDictionary.getOres("ingotGraphite").size() <= 0 || require) { OreDictionary.registerOre("ingotGraphite", new ItemStack(ingotGeneric, 1, 2)); } if (OreDictionary.getOres("ingotPlutonium").size() <= 0 || require) { ItemStack blutoniumStack = new ItemStack(ingotGeneric, 1, 3); OreDictionary.registerOre("ingotPlutonium", blutoniumStack); } // Dusts if (OreDictionary.getOres("dustUranium").size() <= 0 || require) { ItemStack yelloriumDustStack = new ItemStack(ingotGeneric, 1, 4); OreDictionary.registerOre("dustUranium", yelloriumDustStack); } if (OreDictionary.getOres("dustCyanite").size() <= 0 || require) { ItemStack cyaniteDustStack = new ItemStack(ingotGeneric, 1, 5); OreDictionary.registerOre("dustCyanite", cyaniteDustStack); } if (OreDictionary.getOres("dustGraphite").size() <= 0 || require) { ItemStack graphiteDustStack = new ItemStack(ingotGeneric, 1, 6); OreDictionary.registerOre("dustGraphite", graphiteDustStack); } if (OreDictionary.getOres("dustPlutonium").size() <= 0 || require) { ItemStack blutoniumDustStack = new ItemStack(ingotGeneric, 1, 7); OreDictionary.registerOre("dustPlutonium", blutoniumDustStack); } BRConfig.CONFIGURATION.save(); } return new ItemStack(ingotGeneric); } public static void registerFuelRods(int id, boolean require) { if(BigReactors.blockReactorControlRod == null) { BRConfig.CONFIGURATION.load(); BigReactors.blockReactorControlRod = new BlockReactorControlRod(BRConfig.CONFIGURATION.getBlock("ReactorControlRod", BigReactors.BLOCK_ID_PREFIX + 3).getInt(), Material.iron); GameRegistry.registerBlock(BigReactors.blockReactorControlRod, ItemBlockBigReactors.class, "ReactorControlRod"); BRConfig.CONFIGURATION.save(); } if(BigReactors.blockYelloriumFuelRod == null) { BRConfig.CONFIGURATION.load(); BigReactors.blockYelloriumFuelRod = new BlockFuelRod(BRConfig.CONFIGURATION.getBlock("YelloriumFuelRod", BigReactors.BLOCK_ID_PREFIX + 1).getInt(), Material.iron); GameRegistry.registerBlock(BigReactors.blockYelloriumFuelRod, ItemBlockYelloriumFuelRod.class, "YelloriumFuelRod"); BRConfig.CONFIGURATION.save(); } } public static void registerReactorPartBlocks(int id, boolean require) { if(BigReactors.blockReactorPart == null) { BRConfig.CONFIGURATION.load(); BigReactors.blockReactorPart = new BlockReactorPart(BRConfig.CONFIGURATION.getBlock("ReactorPart", BigReactors.BLOCK_ID_PREFIX + 2).getInt(), Material.iron); GameRegistry.registerBlock(BigReactors.blockReactorPart, ItemBlockReactorPart.class, "BRReactorPart"); OreDictionary.registerOre("reactorCasing", ((BlockReactorPart) BigReactors.blockReactorPart).getReactorCasingItemStack()); OreDictionary.registerOre("reactorController", ((BlockReactorPart) BigReactors.blockReactorPart).getReactorControllerItemStack()); OreDictionary.registerOre("reactorPowerTap", ((BlockReactorPart) BigReactors.blockReactorPart).getReactorPowerTapItemStack()); OreDictionary.registerOre("reactorRedNetPort", ((BlockReactorPart) BigReactors.blockReactorPart).getRedNetPortItemStack()); OreDictionary.registerOre("reactorComputerPort", ((BlockReactorPart) BigReactors.blockReactorPart).getComputerPortItemStack()); BRConfig.CONFIGURATION.save(); } if(BigReactors.blockReactorGlass == null) { BRConfig.CONFIGURATION.load(); BigReactors.blockReactorGlass = new BlockReactorGlass(BRConfig.CONFIGURATION.getBlock("ReactorGlass", BigReactors.BLOCK_ID_PREFIX + 7).getInt(), Material.glass); GameRegistry.registerBlock(BigReactors.blockReactorGlass, ItemBlockBigReactors.class, "BRReactorGlass"); BRConfig.CONFIGURATION.save(); } if(BigReactors.blockReactorRedstonePort == null) { BRConfig.CONFIGURATION.load(); BigReactors.blockReactorRedstonePort = new BlockReactorRedstonePort(BRConfig.CONFIGURATION.getBlock("ReactorRedstonePort", BigReactors.BLOCK_ID_PREFIX + 9).getInt(), Material.iron); GameRegistry.registerBlock(BigReactors.blockReactorRedstonePort, ItemBlockBigReactors.class, "BRReactorRedstonePort"); OreDictionary.registerOre("reactorRedstonePort", new ItemStack(blockReactorRedstonePort, 1)); BRConfig.CONFIGURATION.save(); } } public static void registerSmallMachines(int id, boolean require) { if(BigReactors.blockSmallMachine == null) { BRConfig.CONFIGURATION.load(); BigReactors.blockSmallMachine = new BlockBRSmallMachine(BRConfig.CONFIGURATION.getBlock("SmallMachine", BigReactors.BLOCK_ID_PREFIX + 8).getInt(), Material.iron); GameRegistry.registerBlock(BigReactors.blockSmallMachine, ItemBlockSmallMachine.class, "BRSmallMachine"); OreDictionary.registerOre("brSmallMachineCyaniteProcessor", ((BlockBRSmallMachine)BigReactors.blockSmallMachine).getCyaniteReprocessorItemStack()); BRConfig.CONFIGURATION.save(); } } public static void registerYelloriumFluids(int id, boolean require) { if(BigReactors.fluidYelloriumStill == null) { BRConfig.CONFIGURATION.load(); int fluidYelloriumID = BRConfig.CONFIGURATION.getBlock("LiquidYelloriumStill", BigReactors.BLOCK_ID_PREFIX + 4).getInt(); BigReactors.fluidYellorium = FluidRegistry.getFluid("yellorium"); if(fluidYellorium == null) { fluidYellorium = new Fluid("yellorium"); fluidYellorium.setBlockID(fluidYelloriumID); fluidYellorium.setDensity(100); fluidYellorium.setGaseous(false); fluidYellorium.setLuminosity(10); fluidYellorium.setRarity(EnumRarity.uncommon); fluidYellorium.setTemperature(20); fluidYellorium.setViscosity(100); fluidYellorium.setUnlocalizedName("bigreactors.yellorium.still"); FluidRegistry.registerFluid(fluidYellorium); } BlockBRGenericFluid liqY = new BlockBRGenericFluid(fluidYelloriumID, BigReactors.fluidYellorium, "yellorium"); BigReactors.fluidYelloriumStill = liqY; GameRegistry.registerBlock(BigReactors.fluidYelloriumStill, ItemBlockBigReactors.class, BigReactors.fluidYelloriumStill.getUnlocalizedName()); fluidYelloriumBucketItem = (new ItemBRBucket(BRConfig.CONFIGURATION.getItem("BucketYellorium", BigReactors.ITEM_ID_PREFIX + 1).getInt(), liqY.blockID)).setUnlocalizedName("bucket.yellorium").setMaxStackSize(1).setContainerItem(Item.bucketEmpty); BRConfig.CONFIGURATION.save(); } if(BigReactors.fluidCyaniteStill == null) { BRConfig.CONFIGURATION.load(); int fluidCyaniteID = BRConfig.CONFIGURATION.getBlock("LiquidCyaniteStill", BigReactors.BLOCK_ID_PREFIX + 5).getInt(); BigReactors.fluidCyanite = FluidRegistry.getFluid("cyanite"); if(fluidCyanite == null) { fluidCyanite = new Fluid("cyanite"); fluidCyanite.setBlockID(fluidCyaniteID); fluidCyanite.setDensity(100); fluidCyanite.setGaseous(false); fluidCyanite.setLuminosity(6); fluidCyanite.setRarity(EnumRarity.uncommon); fluidCyanite.setTemperature(20); fluidCyanite.setViscosity(100); fluidCyanite.setUnlocalizedName("bigreactors.cyanite.still"); FluidRegistry.registerFluid(fluidCyanite); } BlockBRGenericFluid liqDY = new BlockBRGenericFluid(fluidCyaniteID, fluidCyanite, "cyanite"); BigReactors.fluidCyaniteStill = liqDY; GameRegistry.registerBlock(BigReactors.fluidCyaniteStill, ItemBlockBigReactors.class, BigReactors.fluidCyaniteStill.getUnlocalizedName()); fluidCyaniteBucketItem = (new ItemBRBucket(BRConfig.CONFIGURATION.getItem("BucketCyanite", BigReactors.ITEM_ID_PREFIX + 2).getInt(), liqDY.blockID)).setUnlocalizedName("bucket.cyanite").setMaxStackSize(1).setContainerItem(Item.bucketEmpty); BRConfig.CONFIGURATION.save(); } if(BigReactors.fluidFuelColumnStill == null) { BRConfig.CONFIGURATION.load(); int fuelColumnFluidID = BRConfig.CONFIGURATION.getBlock("LiquidFuelColumnStill", BigReactors.BLOCK_ID_PREFIX + 6).getInt(); BigReactors.fluidFuelColumn = FluidRegistry.getFluid("fuelColumn"); if(fluidFuelColumn == null) { fluidFuelColumn = new Fluid("fuelColumn"); fluidFuelColumn.setBlockID(fuelColumnFluidID); fluidFuelColumn.setUnlocalizedName("bigreactors.fuelColumn.still"); FluidRegistry.registerFluid(fluidFuelColumn); } BlockBRGenericFluid liqFC = new BlockBRGenericFluid(fuelColumnFluidID, fluidFuelColumn, "fuelColumn"); BigReactors.fluidFuelColumnStill = liqFC; GameRegistry.registerBlock(BigReactors.fluidFuelColumnStill, ItemBlockBigReactors.class, BigReactors.fluidFuelColumnStill.getUnlocalizedName()); BRConfig.CONFIGURATION.save(); } } // This must be done in init or later protected static void registerReactorFuelData() { // Register fluids as fuels BRRegistry.registerReactorFluid(new ReactorFuel(fluidYellorium, BigReactors.defaultFluidColorFuel, true, false, fluidCyanite)); BRRegistry.registerReactorFluid(new ReactorFuel(fluidCyanite, BigReactors.defaultFluidColorWaste, false, true/*, fluidBlutonium */)); // TODO: Make a blutonium fluid ItemStack yelloriumStack = ingotGeneric.getItemStackForType("ingotYellorium"); ItemStack cyaniteStack = ingotGeneric.getItemStackForType("ingotCyanite"); ItemStack blutoniumStack = ingotGeneric.getItemStackForType("ingotBlutonium"); BRRegistry.registerSolidMapping(new ReactorSolidMapping(yelloriumStack, fluidYellorium)); BRRegistry.registerSolidMapping(new ReactorSolidMapping(cyaniteStack, fluidCyanite)); // TODO: Fix the color of this // TODO: Make a proper blutonium fluid BRRegistry.registerSolidMapping(new ReactorSolidMapping(blutoniumStack, fluidYellorium)); } // Stolen wholesale from Universal Electricity. Thanks Cal! /** * Loads all the language files for a mod. This supports the loading of "child" language files * for sub-languages to be loaded all from one file instead of creating multiple of them. An * example of this usage would be different Spanish sub-translations (es_MX, es_YU). * * @param languagePath - The path to the mod's language file folder. * @param languageSupported - The languages supported. E.g: new String[]{"en_US", "en_AU", * "en_UK"} * @return The amount of language files loaded successfully. */ public static int loadLanguages(String languagePath, String[] languageSupported) { int languages = 0; /** * Load all languages. */ for (String language : languageSupported) { LanguageRegistry.instance().loadLocalization(languagePath + language + ".properties", language, false); if (LanguageRegistry.instance().getStringLocalization("children", language) != "") { try { String[] children = LanguageRegistry.instance().getStringLocalization("children", language).split(","); for (String child : children) { if (child != "" || child != null) { LanguageRegistry.instance().loadLocalization(languagePath + language + ".properties", child, false); languages++; } } } catch (Exception e) { FMLLog.severe("Failed to load a child language file."); e.printStackTrace(); } } languages++; } return languages; } }
package org.languagetool.dev.wikipedia; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.languagetool.JLanguageTool; import org.languagetool.Language; import org.languagetool.MultiThreadedJLanguageTool; import org.languagetool.language.German; import org.languagetool.rules.Rule; import org.languagetool.rules.RuleMatch; import org.languagetool.tools.ContextTools; import org.languagetool.tools.StringTools; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Check a Wikipedia page (without spell check), fetching the page via the MediaWiki API. */ public class WikipediaQuickCheck { private static final Pattern WIKIPEDIA_URL_REGEX = Pattern.compile("https?://(..)\\.wikipedia\\.org/wiki/(.*)"); private static final Pattern SECURE_WIKIPEDIA_URL_REGEX = Pattern.compile("https://secure\\.wikimedia\\.org/wikipedia/(..)/wiki/(.*)"); private static final int CONTEXT_SIZE = 25; private List<String> disabledRuleIds = new ArrayList<>(); public String getMediaWikiContent(URL wikipediaUrl) throws IOException { final Language lang = getLanguage(wikipediaUrl); final String pageTitle = getPageTitle(wikipediaUrl); final String apiUrl = "http://" + lang.getShortName() + ".wikipedia.org/w/api.php?titles=" + pageTitle + "&action=query&prop=revisions&rvprop=content|timestamp&format=xml"; return getContent(new URL(apiUrl)); } public Language getLanguage(URL url) { final Matcher matcher = getUrlMatcher(url.toString()); return Language.getLanguageForShortName(matcher.group(1)); } public String getPageTitle(URL url) { final Matcher matcher = getUrlMatcher(url.toString()); return matcher.group(2); } private Matcher getUrlMatcher(String url) { final Matcher matcher1 = WIKIPEDIA_URL_REGEX.matcher(url); final Matcher matcher2 = SECURE_WIKIPEDIA_URL_REGEX.matcher(url); if (matcher1.matches()) { return matcher1; } else if (matcher2.matches()) { return matcher2; } throw new RuntimeException("URL does not seem to be a valid Wikipedia URL: " + url); } public void setDisabledRuleIds(List<String> ruleIds) { disabledRuleIds = ruleIds; } public List<String> getDisabledRuleIds() { return disabledRuleIds; } public MarkupAwareWikipediaResult checkPage(URL url) throws IOException, PageNotFoundException { validateWikipediaUrl(url); final WikipediaQuickCheck check = new WikipediaQuickCheck(); final String xml = check.getMediaWikiContent(url); final MediaWikiContent wikiContent = getRevisionContent(xml); if (wikiContent.getContent().trim().isEmpty() || wikiContent.getContent().toLowerCase().contains("#redirect")) { throw new PageNotFoundException("No content found at " + url); } return checkWikipediaMarkup(url, wikiContent, getLanguage(url)); } MarkupAwareWikipediaResult checkWikipediaMarkup(URL url, MediaWikiContent wikiContent, Language language) throws IOException { final SwebleWikipediaTextFilter filter = new SwebleWikipediaTextFilter(); final PlainTextMapping mapping = filter.filter(wikiContent.getContent()); final JLanguageTool langTool = getLanguageTool(language); final List<AppliedRuleMatch> appliedMatches = new ArrayList<>(); final List<RuleMatch> matches = langTool.check(mapping.getPlainText()); int internalErrors = 0; for (RuleMatch match : matches) { final SuggestionReplacer replacer = new SuggestionReplacer(mapping, wikiContent.getContent()); try { final List<RuleMatchApplication> ruleMatchApplications = replacer.applySuggestionsToOriginalText(match); appliedMatches.add(new AppliedRuleMatch(match, ruleMatchApplications)); } catch (Exception e) { System.err.println("Failed to apply suggestion for rule match '" + match + "' for URL " + url + ": " + e.toString()); internalErrors++; } } return new MarkupAwareWikipediaResult(wikiContent, appliedMatches, internalErrors); } public WikipediaQuickCheckResult checkPage(String plainText, Language lang) throws IOException { final JLanguageTool langTool = getLanguageTool(lang); final List<RuleMatch> ruleMatches = langTool.check(plainText); return new WikipediaQuickCheckResult(plainText, ruleMatches, lang.getShortName()); } public void validateWikipediaUrl(URL wikipediaUrl) { // will throw exception if URL is not valid: getUrlMatcher(wikipediaUrl.toString()); } /** * @param completeWikiContent the Mediawiki syntax as it comes from the API, including surrounding XML */ public String getPlainText(String completeWikiContent) { final MediaWikiContent wikiContent = getRevisionContent(completeWikiContent); final String cleanedWikiContent = removeInterLanguageLinks(wikiContent.getContent()); final TextMapFilter filter = new SwebleWikipediaTextFilter(); return filter.filter(cleanedWikiContent).getPlainText(); } /** * @param completeWikiContent the Mediawiki syntax as it comes from the API, including surrounding XML */ public PlainTextMapping getPlainTextMapping(String completeWikiContent) { final MediaWikiContent wikiContent = getRevisionContent(completeWikiContent); final SwebleWikipediaTextFilter filter = new SwebleWikipediaTextFilter(); return filter.filter(wikiContent.getContent()); } // catches most, not all links ("[[pt:Linux]]", but not "[[zh-min-nan:Linux]]"). Might remove some non-interlanguage links. String removeInterLanguageLinks(String wikiContent) { return wikiContent.replaceAll("\\[\\[[a-z]{2,6}:.*?\\]\\]", ""); } private MediaWikiContent getRevisionContent(String completeWikiContent) { final SAXParserFactory factory = SAXParserFactory.newInstance(); final SAXParser saxParser; final RevisionContentHandler handler = new RevisionContentHandler(); try { saxParser = factory.newSAXParser(); saxParser.parse(new InputSource(new StringReader(completeWikiContent)), handler); } catch (Exception e) { throw new RuntimeException("Could not parse XML: " + completeWikiContent, e); } return new MediaWikiContent(handler.getRevisionContent(), handler.getTimestamp()); } private JLanguageTool getLanguageTool(Language lang) throws IOException { final JLanguageTool langTool = new MultiThreadedJLanguageTool(lang); langTool.activateDefaultPatternRules(); enableWikipediaRules(langTool); for (String disabledRuleId : disabledRuleIds) { langTool.disableRule(disabledRuleId); } disableSpellingRules(langTool); return langTool; } private void enableWikipediaRules(JLanguageTool langTool) { List<Rule> allRules = langTool.getAllRules(); for (Rule rule : allRules) { if (rule.getCategory().getName().equals("Wikipedia")) { langTool.enableDefaultOffRule(rule.getId()); } } } private void disableSpellingRules(JLanguageTool languageTool) { final List<Rule> allActiveRules = languageTool.getAllActiveRules(); for (Rule rule : allActiveRules) { if (rule.isSpellingRule()) { languageTool.disableRule(rule.getId()); } } } private String getContent(URL wikipediaUrl) throws IOException { final InputStream contentStream = (InputStream) wikipediaUrl.getContent(); return StringTools.streamToString(contentStream, "UTF-8"); } /*public static void mainTest(String[] args) throws IOException { final TextFilter filter = new SwebleWikipediaTextFilter(); final String plainText = filter.filter("hallo\n* eins\n* zwei"); System.out.println(plainText); }*/ public static void main(String[] args) throws IOException { if (args.length != 1) { System.out.println("Usage: " + WikipediaQuickCheck.class.getName() + " <url>"); System.exit(1); } final WikipediaQuickCheck check = new WikipediaQuickCheck(); // URL examples: final String urlString = args[0]; final URL url = new URL(urlString); final String mediaWikiContent = check.getMediaWikiContent(url); final String plainText = check.getPlainText(mediaWikiContent); final WikipediaQuickCheckResult checkResult = check.checkPage(plainText, new German()); final ContextTools contextTools = new ContextTools(); contextTools.setContextSize(CONTEXT_SIZE); for (RuleMatch ruleMatch : checkResult.getRuleMatches()) { System.out.println(ruleMatch.getMessage()); final String context = contextTools.getPlainTextContext(ruleMatch.getFromPos(), ruleMatch.getToPos(), checkResult.getText()); System.out.println(context); } } class RevisionContentHandler extends DefaultHandler { private final StringBuilder revisionText = new StringBuilder(); private String timestamp; private boolean inRevision = false; @Override public void startElement(final String namespaceURI, final String lName, final String qName, final Attributes attrs) throws SAXException { if ("rev".equals(qName)) { timestamp = attrs.getValue("timestamp"); inRevision = true; } } @Override public void endElement(final String namespaceURI, final String sName, final String qName) throws SAXException { if ("rev".equals(qName)) { inRevision = false; } } @Override public void characters(final char[] buf, final int offset, final int len) { final String s = new String(buf, offset, len); if (inRevision) { revisionText.append(s); } } public String getRevisionContent() { return revisionText.toString(); } public String getTimestamp() { return timestamp; } } }
package org.musicbrainz.search.solrwriter; import org.apache.solr.SolrTestCaseJ4; import org.junit.After; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.concurrent.TimeUnit; public abstract class AbstractMBWriterTest extends SolrTestCaseJ4 implements MBWriterTestInterface { @BeforeClass public static void beforeClass() throws Exception { initCore("solrconfig.xml", "schema.xml", "../mbsssss", getCorename()); } public static String corename; public static String getCorename() { return corename; } /** * Get the document to use in the tests */ abstract ArrayList<String> getDoc(); /** * Add a document containing doc to the current core. * * @param withStore whether the _store field should be populated with data * @param storeValue allows specifying the value for the _store field by * setting it to a value different from null * @throws IOException */ void addDocument(boolean withStore, String storeValue) throws IOException, InterruptedException { ArrayList<String> values = new ArrayList<>(getDoc()); if (withStore) { String xml; if (storeValue != null) { xml = storeValue; } else { String xmlfilepath = MBWriterTestInterface.class.getResource (getCorename() + ".xml").getFile(); byte[] content = Files.readAllBytes(Paths.get(xmlfilepath)); xml = new String(content); } values.add(0, xml); values.add(0, "_store"); } assertU(adoc((values.toArray(new String[values.size()])))); TimeUnit.SECONDS.sleep(2); } void addDocument(boolean withStore) throws Exception { addDocument(withStore, null); } @After public void After() { clearIndex(); } @Test /** * Check that the XML document returned is the same as the one we stored * in the first place. */ public void performCoreTest() throws Exception { addDocument(true); // Sleep to allow auto soft commit String expectedFile; byte[] content; String expected; String expectedFileName = String.format("%s-list.%s", getCorename(), getExpectedFileExtension()); expectedFile = AbstractMBWriterTest.class.getResource (expectedFileName).getFile(); content = Files.readAllBytes(Paths.get(expectedFile)); expected = new String(content); String response = h.query(req("qt", "/advanced", "q", "*:*", "wt", getWritername())); compare(expected, response); } @Rule public ExpectedException thrown = ExpectedException.none(); @Test /** * Check that the expected error message is shown for documents with a * '_store' field with a value that can't be * unmarshalled. */ public void testInvalidStoreException() throws Exception { addDocument(true, "invalid"); // Sleep to allow auto soft commit thrown.expectMessage(MBXMLWriter.UNMARSHALLING_STORE_FAILED + "invalid"); h.query(req("qt", "/advanced", "q", "*:*", "wt", getWritername())); } }
package org.multibit.hd.ui.views.components.select_file; import net.miginfocom.swing.MigLayout; import org.multibit.hd.ui.views.components.AbstractComponentView; import org.multibit.hd.ui.views.components.Buttons; import org.multibit.hd.ui.views.components.Panels; import org.multibit.hd.ui.views.components.TextBoxes; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.event.ActionEvent; import java.io.File; /** * <p>View to provide the following to UI:</p> * <ul> * <li>User entry of a seed phrase </li> * <li>Support for refresh and reveal operations</li> * </ul> * * @since 0.0.1 */ public class SelectFileView extends AbstractComponentView<SelectFileModel> { // View components private JTextField selectedFileTextField; private JFileChooser fileChooser = new JFileChooser(); /** * @param model The model backing this view */ public SelectFileView(SelectFileModel model) { super(model); } @Override public JPanel newComponentPanel() { SelectFileModel model = getModel().get(); panel = Panels.newPanel(new MigLayout( "insets 0", // Layout "[][]", // Columns "[]10[]" // Rows )); selectedFileTextField = TextBoxes.newSelectFile(); // Fill the text area with appropriate content selectedFileTextField.setText(model.getValue()); // Bind a document listener to allow instant update of UI to entered data selectedFileTextField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { updateModelFromView(); } @Override public void removeUpdate(DocumentEvent e) { updateModelFromView(); } @Override public void changedUpdate(DocumentEvent e) { updateModelFromView(); } }); // Configure the actions Action openSelectFileAction = getOpenSelectFileAction(); // Add to the panel panel.add(selectedFileTextField, "grow,push"); panel.add(Buttons.newSelectFileButton(openSelectFileAction), "shrink,wrap"); return panel; } @Override public void requestInitialFocus() { selectedFileTextField.requestFocusInWindow(); } @Override public void updateModelFromView() { getModel().get().setValue(selectedFileTextField.getText()); } /** * @return A new action for toggling the display of the seed phrase */ private Action getOpenSelectFileAction() { // Show or hide the seed phrase return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { final SelectFileModel model = getModel().get(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // Only require a directory fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int result = fileChooser.showOpenDialog(currentComponentPanel()); if (result == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); getModel().get().setValue(file.getAbsolutePath()); getModel().get().setSelected(true); } else { getModel().get().setSelected(false); } selectedFileTextField.setText(model.getValue()); } }); } }; } }
package com.miguelgaeta.bootstrap.mg_images; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.provider.MediaStore; import android.support.annotation.ColorRes; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import com.android.camera.CropImageIntentBuilder; import java.io.File; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import retrofit.mime.TypedFile; import rx.Observable; import rx.functions.Action1; import rx.functions.Func1; @SuppressWarnings("UnusedDeclaration") @NoArgsConstructor(staticName = "create") public class MGImageIntentHandler { private static final int REQUEST_CAPTURE = 777; private static final int REQUEST_GALLERY = 779; private static final int REQUEST_CROP = 800; private int mWidth = 120; private int mHeight = 120; private static Uri fileUri; public static void startForImageCapture(@NonNull FragmentActivity activity, Action1<Void> onError) { startForIntent(activity, null, file -> new Intent(MediaStore.ACTION_IMAGE_CAPTURE) .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)), REQUEST_CAPTURE, onError); } public static void startForImageCapture(@NonNull Fragment fragment, Action1<Void> onError) { startForIntent(null, fragment, file -> new Intent(MediaStore.ACTION_IMAGE_CAPTURE) .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)), REQUEST_CAPTURE, onError); } public static void startForImagePick(@NonNull FragmentActivity activity) { startActivityForResult(activity, null, new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI), REQUEST_GALLERY); } public static void startForImagePick(@NonNull Fragment fragment) { startActivityForResult(null, fragment, new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI), REQUEST_GALLERY); } public static void startForImageCrop(@NonNull Fragment fragment, @NonNull Uri uri, @ColorRes int colorResId, Action1<Void> onError) { startForIntent(null, fragment, file -> { CropImageIntentBuilder intentBuilder = new CropImageIntentBuilder(256, 256, Uri.fromFile(file)); int color = fragment.getResources().getColor(colorResId); intentBuilder.setSourceImage(uri); intentBuilder.setCircleCrop(true); intentBuilder.setDoFaceDetection(true); intentBuilder.setOutlineCircleColor(color); intentBuilder.setOutlineColor(color); intentBuilder.setScaleUpIfNeeded(true); return intentBuilder.getIntent(fragment.getActivity()); }, REQUEST_CROP, onError); } private static void startActivityForResult(FragmentActivity activity, Fragment fragment, @NonNull Intent intent, int requestCode) { if (activity != null) { activity.startActivityForResult(intent, requestCode); } else if (fragment != null) { fragment.startActivityForResult(intent, requestCode); } } public Observable<FileResult> handleResult(@NonNull Context context, int requestCode, int resultCode, Intent data) { return Observable.create(subscriber -> { Uri uri = null; if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CAPTURE) { uri = fileUri; } else if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_GALLERY && data != null) { uri = data.getData(); } if (uri != null) { File file = MGImagePathUtil.getFile(context, uri); if (file != null && file.exists()) { int rotation = MGImageIntentUtils.getRotationDegree(file.getAbsolutePath()); file = MGImageIntentUtils.getResizedImage(file, 1080); file = MGImageIntentUtils.getRotatedImage(file, rotation); subscriber.onNext(FileResult.create(new TypedFile(MGImagePathUtil.getMimeType(file), file), FileResult.Status.OK)); } else { subscriber.onNext(FileResult.create(null, FileResult.Status.FILE_NOT_FOUND)); } } else { subscriber.onNext(FileResult.create(null, FileResult.Status.URI_NOT_FOUND)); } subscriber.onCompleted(); }); } private static void startForIntent(FragmentActivity activity, Fragment fragment, @NonNull Func1<File, Intent> onIntent, int requestCode, Action1<Void> onError) { File file = MGImageIntentUtils.createTempImageFile(); fileUri = Uri.fromFile(file); if ((file != null) && file.exists()) { startActivityForResult(activity, fragment, onIntent.call(file), requestCode); } else if (onError != null) { onError.call(null); } } @AllArgsConstructor(staticName = "create") @Getter public static class FileResult { public enum Status { OK, FILE_NOT_FOUND, URI_NOT_FOUND } private TypedFile typedFile; private @NonNull Status status; } }
package com.jivesoftware.os.miru.plugin.backfill; import com.jivesoftware.os.filer.io.FilerIO; import com.jivesoftware.os.filer.io.api.StackBuffer; import com.jivesoftware.os.miru.api.activity.MiruPartitionId; import com.jivesoftware.os.miru.api.activity.MiruPartitionedActivity; import com.jivesoftware.os.miru.api.activity.MiruReadEvent; import com.jivesoftware.os.miru.api.base.MiruStreamId; import com.jivesoftware.os.miru.api.base.MiruTenantId; import com.jivesoftware.os.miru.api.query.filter.MiruFilter; import com.jivesoftware.os.miru.api.topology.NamedCursor; import com.jivesoftware.os.miru.api.wal.AmzaCursor; import com.jivesoftware.os.miru.api.wal.AmzaSipCursor; import com.jivesoftware.os.miru.api.wal.MiruWALClient; import com.jivesoftware.os.miru.api.wal.MiruWALClient.OldestReadResult; import com.jivesoftware.os.miru.api.wal.MiruWALClient.StreamBatch; import com.jivesoftware.os.miru.api.wal.MiruWALEntry; import com.jivesoftware.os.miru.plugin.bitmap.MiruBitmaps; import com.jivesoftware.os.miru.plugin.context.MiruRequestContext; import com.jivesoftware.os.miru.plugin.index.MiruUnreadTrackingIndex; import com.jivesoftware.os.miru.plugin.solution.MiruAggregateUtil; import com.jivesoftware.os.miru.plugin.solution.MiruSolutionLog; import com.jivesoftware.os.mlogger.core.MetricLogger; import com.jivesoftware.os.mlogger.core.MetricLoggerFactory; import java.util.Collections; import java.util.List; /** @author jonathan */ public class AmzaInboxReadTracker implements MiruInboxReadTracker { private static final MetricLogger LOG = MetricLoggerFactory.getLogger(); private final MiruWALClient<AmzaCursor, AmzaSipCursor> walClient; private final MiruAggregateUtil aggregateUtil = new MiruAggregateUtil(); private final MiruReadTracker readTracker = new MiruReadTracker(aggregateUtil); public AmzaInboxReadTracker(MiruWALClient<AmzaCursor, AmzaSipCursor> walClient) { this.walClient = walClient; } @Override public <BM extends IBM, IBM> ApplyResult sipAndApplyReadTracking(String name, final MiruBitmaps<BM, IBM> bitmaps, final MiruRequestContext<BM, IBM, ?> requestContext, MiruTenantId tenantId, MiruPartitionId partitionId, MiruStreamId streamId, MiruSolutionLog solutionLog, int lastActivityIndex, long oldestBackfilledTimestamp, StackBuffer stackBuffer) throws Exception { MiruUnreadTrackingIndex<BM, IBM> unreadTrackingIndex = requestContext.getUnreadTrackingIndex(); List<NamedCursor> cursors = unreadTrackingIndex.getCursors(streamId); if (cursors == null) { cursors = Collections.emptyList(); } OldestReadResult<AmzaSipCursor> oldestReadResult = walClient.oldestReadEventId(tenantId, streamId, new AmzaSipCursor(cursors, false), true); AmzaSipCursor lastCursor = oldestReadResult.cursor; long fromTimestamp = oldestReadResult.oldestEventId == -1 ? oldestBackfilledTimestamp : Math.min(oldestBackfilledTimestamp, oldestReadResult.oldestEventId); StreamBatch<MiruWALEntry, Long> got = (fromTimestamp == Long.MAX_VALUE) ? null : walClient.scanRead(tenantId, streamId, fromTimestamp, 10_000, true); int calls = 0; int count = 0; int numRead = 0; long maxReadTime = 0; int numUnread = 0; long maxUnreadTime = 0; int numAllRead = 0; long maxAllReadTime = 0; while (got != null && !got.activities.isEmpty()) { calls++; count += got.activities.size(); for (MiruWALEntry e : got.activities) { MiruReadEvent readEvent = e.activity.readEvent.get(); MiruFilter filter = readEvent.filter; if (e.activity.type == MiruPartitionedActivity.Type.READ) { numRead++; maxReadTime = readEvent.time; readTracker.read(bitmaps, requestContext, streamId, filter, solutionLog, lastActivityIndex, readEvent.time, stackBuffer); } else if (e.activity.type == MiruPartitionedActivity.Type.UNREAD) { numUnread++; maxUnreadTime = readEvent.time; readTracker.unread(bitmaps, requestContext, streamId, filter, solutionLog, lastActivityIndex, readEvent.time, stackBuffer); } else if (e.activity.type == MiruPartitionedActivity.Type.MARK_ALL_READ) { numAllRead++; maxAllReadTime = readEvent.time; readTracker.markAllRead(bitmaps, requestContext, streamId, readEvent.time, stackBuffer); } } got = (got.cursor != null) ? walClient.scanRead(tenantId, streamId, got.cursor, 10_000, true) : null; } LOG.inc("sipAndApply>calls>pow>" + FilerIO.chunkPower(calls, 0)); LOG.inc("sipAndApply>count>pow>" + FilerIO.chunkPower(count, 0)); if (lastCursor != null) { unreadTrackingIndex.setCursors(streamId, lastCursor.cursors); } return new ApplyResult(calls, count, numRead, maxReadTime, numUnread, maxUnreadTime, numAllRead, maxAllReadTime, cursors, lastCursor == null ? null : lastCursor.cursors); } }
package battle; public class Fighter implements Actor { public boolean removeStatus(Status status) { throw new UnsupportedOperationException("Not supported yet."); } public boolean isStunned() { throw new UnsupportedOperationException("Not supported yet."); } public boolean isDefeated() { throw new UnsupportedOperationException("Not supported yet."); } public void executeSkill(Skill skill) { throw new UnsupportedOperationException("Not supported yet."); } }
package org.geotools.data.wms.test; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.Properties; import javax.imageio.ImageIO; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.StringBuilderWriter; import org.geotools.data.ResourceInfo; import org.geotools.data.ServiceInfo; import org.geotools.data.ows.CRSEnvelope; import org.geotools.data.ows.Layer; import org.geotools.data.ows.OperationType; import org.geotools.data.ows.WMSCapabilities; import org.geotools.data.wms.WebMapServer; import org.geotools.data.wms.request.GetFeatureInfoRequest; import org.geotools.data.wms.request.GetMapRequest; import org.geotools.data.wms.response.GetFeatureInfoResponse; import org.geotools.data.wms.response.GetMapResponse; import org.geotools.factory.GeoTools; import org.geotools.geometry.GeneralEnvelope; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.CRS; import org.geotools.referencing.CRS.AxisOrder; import org.geotools.referencing.crs.DefaultEngineeringCRS; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.opengis.geometry.Envelope; import org.opengis.referencing.FactoryException; import org.opengis.referencing.NoSuchAuthorityCodeException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.cs.CoordinateSystem; import org.opengis.referencing.cs.CoordinateSystemAxis; import org.opengis.util.GenericName; public class LocalGeoServerOnlineTest extends TestCase { static private String LOCAL_GEOSERVER = "http://127.0.0.1:8080/geoserver/ows?SERVICE=WMS&"; static private WebMapServer wms; static private WMSCapabilities capabilities; static private URL serverURL; static { try { serverURL = new URL(LOCAL_GEOSERVER); } catch (MalformedURLException e) { serverURL = null; } ; } @Override protected void setUp() throws Exception { super.setUp(); System.setProperty("org.geotools.referencing.forceXY", "true"); //$NON-NLS-1$ //$NON-NLS-2$ if (wms == null) { // do setup once! if (serverURL != null) { try { wms = new WebMapServer(serverURL); capabilities = wms.getCapabilities(); } catch (Exception eek) { serverURL = null; throw eek; } } } } public void testLocalGeoServer() { assertNotNull(wms); assertNotNull(capabilities); assertEquals("Version Negotiation", "1.3.0", capabilities.getVersion()); Layer root = capabilities.getLayer(); assertNotNull(root); assertNull("root layer does not have a name", root.getName()); assertNotNull("title", root.getTitle()); } public void testStates() { Layer states = find("topp:states"); assertNotNull(states); ResourceInfo info = wms.getInfo(states); assertNotNull(info); assertEquals(states.getTitle(), info.getTitle()); ReferencedEnvelope bounds = info.getBounds(); assertNotNull(bounds); assertFalse(bounds.isEmpty()); } private Layer find(String name, WMSCapabilities caps) { for (Layer layer : caps.getLayerList()) { if (name.equals(layer.getName())) { return layer; } } return null; } private Layer find(String name) { return find(name, capabilities); } public void testServiceInfo() { ServiceInfo info = wms.getInfo(); assertNotNull(info); assertEquals(serverURL, wms.getCapabilities().getRequest().getGetCapabilities().getGet()); assertEquals("GeoServer Web Map Service", info.getTitle()); assertNotNull(info.getDescription()); } String axisName(CoordinateReferenceSystem crs, int dimension) { return crs.getCoordinateSystem().getAxis(dimension).getName().getCode(); } public void testImgSample130() throws Exception { Layer water_bodies = find("topp:tasmania_water_bodies"); assertNotNull("Img_Sample layer found", water_bodies); CRSEnvelope latLon = water_bodies.getLatLonBoundingBox(); assertEquals("LatLonBoundingBox axis 0 name", "Geodetic longitude", axisName(latLon.getCoordinateReferenceSystem(), 0)); assertEquals("LatLonBoundingBox axis 0 name", "Geodetic latitude", axisName(latLon.getCoordinateReferenceSystem(), 1)); boolean globalXY = Boolean.getBoolean("org.geotools.referencing.forceXY"); CRSEnvelope bounds = water_bodies.getBoundingBoxes().get("EPSG:4326"); CoordinateReferenceSystem boundsCRS = bounds.getCoordinateReferenceSystem(); assertEquals( "EPSG:4326", AxisOrder.EAST_NORTH, CRS.getAxisOrder(boundsCRS) ); assertEquals("axis order 0 min", latLon.getMinimum(1), bounds.getMinimum(0)); assertEquals("axis order 1 min", latLon.getMinimum(0), bounds.getMinimum(1)); assertEquals("axis order 1 max", latLon.getMaximum(0), bounds.getMaximum(1)); assertEquals("axis order 1 min", latLon.getMaximum(1), bounds.getMaximum(0)); // GETMAP checkGetMap(wms, water_bodies, DefaultGeographicCRS.WGS84); checkGetMap(wms, water_bodies, CRS.decode("CRS:84")); checkGetMap(wms, water_bodies, CRS.decode("EPSG:4326")); checkGetMap(wms, water_bodies, CRS.decode("urn:x-ogc:def:crs:EPSG::4326")); // GETFEATURE INFO checkGetFeatureInfo( wms, water_bodies, DefaultGeographicCRS.WGS84 ); checkGetFeatureInfo(wms, water_bodies, CRS.decode("CRS:84")); checkGetFeatureInfo( wms, water_bodies, CRS.decode("EPSG:4326") ); checkGetFeatureInfo( wms, water_bodies, CRS.decode("urn:x-ogc:def:crs:EPSG::4326") ); } public void testImageSample111() throws Exception { WebMapServer wms111 = new WebMapServer(new URL(serverURL + "&VERSION=1.1.1")); WMSCapabilities caps = wms111.getCapabilities(); assertEquals("1.1.1", caps.getVersion()); Layer water_bodies = find("topp:tasmania_water_bodies", caps); assertNotNull("Img_Sample layer found", water_bodies); CRSEnvelope latLon = water_bodies.getLatLonBoundingBox(); assertEquals("LatLonBoundingBox axis 0 name", "Geodetic longitude", axisName(latLon.getCoordinateReferenceSystem(), 0)); assertEquals("LatLonBoundingBox axis 1 name", "Geodetic latitude", axisName(latLon.getCoordinateReferenceSystem(), 1)); CRSEnvelope bounds = water_bodies.getBoundingBoxes().get("EPSG:4326"); CoordinateReferenceSystem boundsCRS = bounds.getCoordinateReferenceSystem(); assertEquals( "EPSG:4326", AxisOrder.EAST_NORTH, CRS.getAxisOrder(boundsCRS) );; assertEquals("axis order 0 min", latLon.getMinimum(0), bounds.getMinimum(0)); assertEquals("axis order 1 min", latLon.getMinimum(1), bounds.getMinimum(1)); assertEquals("axis order 1 max", latLon.getMaximum(0), bounds.getMaximum(0)); assertEquals("axis order 1 min", latLon.getMaximum(1), bounds.getMaximum(1)); // GETMAP checkGetMap(wms111, water_bodies, DefaultGeographicCRS.WGS84); checkGetMap(wms111, water_bodies, CRS.decode("CRS:84")); checkGetMap(wms111, water_bodies, CRS.decode("EPSG:4326")); checkGetMap(wms111, water_bodies, CRS.decode("urn:x-ogc:def:crs:EPSG::4326")); // GETFEATURE INFO checkGetFeatureInfo( wms111, water_bodies, DefaultGeographicCRS.WGS84 ); checkGetFeatureInfo( wms111, water_bodies, CRS.decode("CRS:84")); checkGetFeatureInfo( wms111, water_bodies, CRS.decode("EPSG:4326") ); checkGetFeatureInfo( wms111, water_bodies, CRS.decode("urn:x-ogc:def:crs:EPSG::4326") ); } private String format(OperationType operationType, String search) { for (String format : operationType.getFormats()) { if (format.contains(search)) { return format; } } return null; // not found } /** * Check GetMap request functionality in the provided CRS. * <p> * Attempt is made to request the entire image. * * @param wms * @param layer * @param crs */ private void checkGetMap(WebMapServer wms, Layer layer, CoordinateReferenceSystem crs) throws Exception { layer.clearCache(); CRSEnvelope latLon = layer.getLatLonBoundingBox(); GeneralEnvelope envelope = wms.getEnvelope(layer, crs); assertFalse(envelope.isEmpty() || envelope.isNull() || envelope.isInfinite()); assertNotNull("Envelope "+CRS.toSRS(crs), envelope); GetMapRequest getMap = wms.createGetMapRequest(); OperationType operationType = wms.getCapabilities().getRequest().getGetMap(); getMap.addLayer(layer); String version = wms.getCapabilities().getVersion(); String srs = CRS.toSRS(envelope.getCoordinateReferenceSystem()); getMap.setBBox(envelope); //getMap.setSRS( srs ); String format = format(operationType, "jpeg"); getMap.setFormat(format); getMap.setDimensions(500, 500); URL url = getMap.getFinalURL(); GetMapResponse response = wms.issueRequest(getMap); assertEquals("image/jpeg", response.getContentType()); InputStream stream = response.getInputStream(); BufferedImage image = ImageIO.read(stream); assertNotNull("jpeg", image); assertEquals(500, image.getWidth()); assertEquals(500, image.getHeight()); int rgb = image.getRGB(70, 420); Color sample = new Color(rgb); boolean forceXY = Boolean.getBoolean(GeoTools.FORCE_LONGITUDE_FIRST_AXIS_ORDER); String context = "srs="+srs+" forceXY="+forceXY+" Version="+version; if(Color.WHITE.equals(sample)){ System.out.println("FAIL: "+ context+": GetMap BBOX=" + envelope); System.out.println("--> " + url); fail( context+": GetMap BBOX=" + envelope ); } else { //System.out.println("PASS: "+ context+": GetMap BBOX=" + bbox); } } /** * Check GetMap request functionality in the provided CRS. * <p> * Attempt is made to request the entire image. * * @param wms * @param layer * @param crs */ private void checkGetFeatureInfo(WebMapServer wms, Layer layer, CoordinateReferenceSystem crs) throws Exception { layer.clearCache(); CRSEnvelope latLon = layer.getLatLonBoundingBox(); GeneralEnvelope envelope = wms.getEnvelope(layer, crs); assertFalse(envelope.isEmpty() || envelope.isNull() || envelope.isInfinite()); assertNotNull("Envelope "+CRS.toSRS(crs), envelope); GetMapRequest getMap = wms.createGetMapRequest(); OperationType operationType = wms.getCapabilities().getRequest().getGetMap(); getMap.addLayer(layer); String version = wms.getCapabilities().getVersion(); String srs = CRS.toSRS(envelope.getCoordinateReferenceSystem()); getMap.setBBox(envelope); String format = format(operationType, "jpeg"); getMap.setFormat(format); getMap.setDimensions(500, 500); URL url = getMap.getFinalURL(); GetFeatureInfoRequest getFeatureInfo = wms.createGetFeatureInfoRequest( getMap ); getFeatureInfo.setInfoFormat("text/html"); getFeatureInfo.setQueryLayers( Collections.singleton(layer)); getFeatureInfo.setQueryPoint( 75, 100 ); URL url2 = getFeatureInfo.getFinalURL(); GetFeatureInfoResponse response = wms.issueRequest(getFeatureInfo); assertEquals("text/html", response.getContentType() ); InputStream stream = response.getInputStream(); StringBuilderWriter writer = new StringBuilderWriter(); IOUtils.copy(stream, writer ); String info = writer.toString(); assertTrue( "response available", !info.isEmpty() ); assertTrue( "html", info.contains("<html") || info.contains("<HTML")); boolean forceXY = Boolean.getBoolean(GeoTools.FORCE_LONGITUDE_FIRST_AXIS_ORDER); String context = "srs="+srs+" forceXY="+forceXY+" Version="+version; if( !info.contains("tasmania_water_bodies.3") ){ System.out.println("FAIL: "+ context+": GetFeatureInfo BBOX=" + envelope); System.out.println("GETMAP --> " + url); System.out.println("GETFEATUREINFO --> " + url2); fail( context+": GetFeatureInfo BBOX=" + envelope ); } } }
package com.google.code.morphia.mapping; import org.bson.types.ObjectId; import org.junit.Test; import com.google.code.morphia.TestBase; import com.google.code.morphia.annotations.Embedded; import com.google.code.morphia.annotations.Id; import junit.framework.Assert; /** * @author Uwe Schaefer, (us@thomas-daily.de) */ public class ConcreteClassEmbeddedOverrideTest extends TestBase { public static class E { @Id ObjectId id; @Embedded final A a1 = new A(); @Embedded(concreteClass = B.class) final A a2 = new A(); } public static class A { String s = "A"; } public static class B extends A { public B() { s = "B"; } } @Test public void test() throws Exception { final E e1 = new E(); Assert.assertEquals("A", e1.a1.s); Assert.assertEquals("A", e1.a2.s); ds.save(e1); final E e2 = ds.get(e1); Assert.assertEquals("A", e2.a1.s); Assert.assertEquals("A", e2.a2.s); Assert.assertEquals(B.class, e2.a2.getClass()); Assert.assertEquals(A.class, e2.a1.getClass()); } }
package org.navalplanner.web.resourceload; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.lang.Validate; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.joda.time.LocalDate; import org.navalplanner.business.planner.daos.IResourceAllocationDAO; import org.navalplanner.business.planner.entities.GenericDayAssignment; import org.navalplanner.business.planner.entities.GenericResourceAllocation; import org.navalplanner.business.planner.entities.ResourceAllocation; import org.navalplanner.business.planner.entities.SpecificDayAssignment; import org.navalplanner.business.resources.entities.Criterion; import org.navalplanner.business.resources.entities.Resource; import org.zkoss.ganttz.data.resourceload.LoadLevel; import org.zkoss.ganttz.data.resourceload.LoadPeriod; interface LoadPeriodGeneratorFactory { LoadPeriodGenerator create(ResourceAllocation<?> allocation); } abstract class LoadPeriodGenerator { private static final Log LOG = LogFactory.getLog(LoadPeriodGenerator.class); public static LoadPeriodGeneratorFactory onResource(Resource resource) { return new OnResourceFactory(resource); } private static class OnResourceFactory implements LoadPeriodGeneratorFactory { private final Resource resource; public OnResourceFactory(Resource resource) { Validate.notNull(resource); this.resource = resource; } @Override public LoadPeriodGenerator create(ResourceAllocation<?> allocation) { return new LoadPeriodGeneratorOnResource(resource, allocation); } } public static LoadPeriodGeneratorFactory onCriterion( final IResourceAllocationDAO resourceAllocationDAO, final Criterion criterion) { return new LoadPeriodGeneratorFactory() { @Override public LoadPeriodGenerator create(ResourceAllocation<?> allocation) { return new LoadPeriodGeneratorOnCriterion( resourceAllocationDAO, criterion, allocation); } }; } protected final LocalDate start; protected final LocalDate end; private List<ResourceAllocation<?>> allocationsOnInterval = new ArrayList<ResourceAllocation<?>>(); protected LoadPeriodGenerator(LocalDate start, LocalDate end, List<ResourceAllocation<?>> allocationsOnInterval) { Validate.notNull(start); Validate.notNull(end); Validate.notNull(allocationsOnInterval); this.start = start; this.end = end; this.allocationsOnInterval = ResourceAllocation .getSatisfied(allocationsOnInterval); } public List<LoadPeriodGenerator> join(LoadPeriodGenerator next) { if (!overlaps(next)) { return stripEmpty(this, next); } if (isIncluded(next)) { return stripEmpty(this.until(next.start), intersect(next), this .from(next.end)); } assert overlaps(next) && !isIncluded(next); return stripEmpty(this.until(next.start), intersect(next), next .from(end)); } protected List<ResourceAllocation<?>> getAllocationsOnInterval() { return allocationsOnInterval; } private List<LoadPeriodGenerator> stripEmpty( LoadPeriodGenerator... generators) { List<LoadPeriodGenerator> result = new ArrayList<LoadPeriodGenerator>(); for (LoadPeriodGenerator loadPeriodGenerator : generators) { if (!loadPeriodGenerator.isEmpty()) { result.add(loadPeriodGenerator); } } return result; } private boolean isEmpty() { return start.equals(end); } protected abstract LoadPeriodGenerator create(LocalDate start, LocalDate end, List<ResourceAllocation<?>> allocationsOnInterval); private LoadPeriodGenerator intersect(LoadPeriodGenerator other) { return create(max(this.start, other.start), min(this.end, other.end), plusAllocations(other)); } private static LocalDate max(LocalDate l1, LocalDate l2) { return l1.compareTo(l2) < 0 ? l2 : l1; } private static LocalDate min(LocalDate l1, LocalDate l2) { return l1.compareTo(l2) < 0 ? l1 : l2; } private List<ResourceAllocation<?>> plusAllocations( LoadPeriodGenerator other) { List<ResourceAllocation<?>> result = new ArrayList<ResourceAllocation<?>>(); result.addAll(allocationsOnInterval); result.addAll(other.allocationsOnInterval); return result; } private LoadPeriodGenerator from(LocalDate newStart) { return create(newStart, end, allocationsOnInterval); } private LoadPeriodGenerator until(LocalDate newEnd) { return create(start, newEnd, allocationsOnInterval); } boolean overlaps(LoadPeriodGenerator other) { return (start.compareTo(other.end) < 0 && other.start .compareTo(this.end) < 0); } private boolean isIncluded(LoadPeriodGenerator other) { return other.start.compareTo(start) >= 0 && other.end.compareTo(end) <= 0; } public LoadPeriod build() { return new LoadPeriod(start, end, new LoadLevel( calculateLoadPercentage())); } protected abstract int getTotalWorkHours(); private int calculateLoadPercentage() { final int totalResourceWorkHours = getTotalWorkHours(); int assigned = getHoursAssigned(); if (totalResourceWorkHours == 0) { return assigned == 0 ? 0 : Integer.MAX_VALUE; } double proportion = assigned / (double) totalResourceWorkHours; return new BigDecimal(proportion).scaleByPowerOfTen(2).intValue(); } protected abstract int getHoursAssigned(); protected final int sumAllocations() { int sum = 0; for (ResourceAllocation<?> resourceAllocation : allocationsOnInterval) { sum += getAssignedHoursFor(resourceAllocation); } return sum; } protected abstract int getAssignedHoursFor( ResourceAllocation<?> resourceAllocation); public LocalDate getStart() { return start; } public LocalDate getEnd() { return end; } } class LoadPeriodGeneratorOnResource extends LoadPeriodGenerator { private Resource resource; LoadPeriodGeneratorOnResource(Resource resource, LocalDate start, LocalDate end, List<ResourceAllocation<?>> allocationsOnInterval) { super(start, end, allocationsOnInterval); this.resource = resource; } LoadPeriodGeneratorOnResource(Resource resource, ResourceAllocation<?> initial) { super(initial.getStartDate(), initial.getEndDate(), Arrays.<ResourceAllocation<?>> asList(initial)); this.resource = resource; } @Override protected LoadPeriodGenerator create(LocalDate start, LocalDate end, List<ResourceAllocation<?>> allocationsOnInterval) { return new LoadPeriodGeneratorOnResource(resource, start, end, allocationsOnInterval); } @Override protected int getTotalWorkHours() { return resource.getTotalWorkHours(start, end); } @Override protected int getAssignedHoursFor(ResourceAllocation<?> resourceAllocation) { return resourceAllocation.getAssignedHours(resource, start, end); } @Override protected int getHoursAssigned() { return sumAllocations(); } } class LoadPeriodGeneratorOnCriterion extends LoadPeriodGenerator { private final Criterion criterion; private IResourceAllocationDAO resourceAllocationDAO; public LoadPeriodGeneratorOnCriterion( IResourceAllocationDAO resourceAllocationDAO, Criterion criterion, ResourceAllocation<?> allocation) { this(resourceAllocationDAO, criterion, allocation.getStartDate(), allocation.getEndDate(), Arrays .<ResourceAllocation<?>> asList(allocation)); } public LoadPeriodGeneratorOnCriterion( IResourceAllocationDAO resourceAllocationDAO, Criterion criterion, LocalDate startDate, LocalDate endDate, List<ResourceAllocation<?>> allocations) { super(startDate, endDate, allocations); this.resourceAllocationDAO = resourceAllocationDAO; this.criterion = criterion; } @Override protected LoadPeriodGenerator create(LocalDate start, LocalDate end, List<ResourceAllocation<?>> allocationsOnInterval) { return new LoadPeriodGeneratorOnCriterion(resourceAllocationDAO, criterion, start, end, allocationsOnInterval); } private Set<Resource> getResourcesMatchedByCriterionFromAllocations() { Set<Resource> resources = new HashSet<Resource>(); for (GenericResourceAllocation each : genericAllocationsOnInterval()) { Set<GenericDayAssignment> genericDayAssignments = each .getGenericDayAssignments(); for (GenericDayAssignment eachAssignment : genericDayAssignments) { resources.add(eachAssignment.getResource()); } } return resources; } private List<GenericResourceAllocation> genericAllocationsOnInterval() { return ResourceAllocation.getOfType(GenericResourceAllocation.class, getAllocationsOnInterval()); } @Override protected int getAssignedHoursFor(ResourceAllocation<?> resourceAllocation) { return resourceAllocation.getAssignedHours(start, end); } @Override protected int getTotalWorkHours() { int sum = 0; for (Resource resource : getResourcesMatchedByCriterionFromAllocations()) { sum += resource.getTotalWorkHours(start, end); } return sum; } @Override protected int getHoursAssigned() { return sumAllocations() + calculateSumOfSpecific(); } private int calculateSumOfSpecific() { List<SpecificDayAssignment> specific = resourceAllocationDAO .getSpecificAssignmentsBetween( getResourcesMatchedByCriterionFromAllocations(), start, end); return sum(specific); } private int sum(List<SpecificDayAssignment> specific) { int result = 0; for (SpecificDayAssignment s : specific) { result += s.getHours(); } return result; } }
package org.opennms.javamail; import java.io.IOException; import java.io.PrintStream; import java.util.List; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.MimeMessage; import org.opennms.core.utils.PropertiesUtils; import org.opennms.netmgt.config.common.JavamailProperty; import org.opennms.netmgt.config.common.SendmailConfig; import org.opennms.netmgt.config.common.SendmailMessage; import org.opennms.netmgt.config.common.SendmailProtocol; import org.springframework.mail.javamail.MimeMailMessage; /** * Use this class for sending emailz. * * Crude extension of JavaMailer * TODO: Improve class hierarchy. * * TODO: Needs testing * @author <a href="mailto:david@opennms.org">David Hustace</a> * */ public class JavaSendMailer extends JavaMailer2 { private Properties m_properties; private SendmailConfig m_config; private MimeMailMessage m_message; private Session m_session; /** * Constructs everything required to call send() * * @param config * SendmailConfig * @param useJmProps * A boolean representing the handling of the deprecated javamail-configuration.properties file. * @throws JavaMailerException */ public JavaSendMailer(SendmailConfig config, boolean useJmProps) throws JavaMailerException { m_config = config; try { m_session = Session.getInstance(createProps(useJmProps), createAuthenticator()); m_message = buildMimeMessage(config.getSendmailMessage()); if (m_config.isDebug()) { m_session.setDebugOut(new PrintStream(new LoggingByteArrayOutputStream(log()), true)); } m_session.setDebug(m_config.getDebug()); } catch (IOException e) { throw new JavaMailerException("IO problem creating session", e); } } /** * Using this constructor implies overriding sendmail configuration with properties * from the deprecated javamail-configuration.properties file. * * @param config * @throws JavaMailerException */ public JavaSendMailer(SendmailConfig config) throws JavaMailerException { this(config, true); } public MimeMailMessage buildMimeMessage(SendmailMessage msg) { //no need to set the same object again if (m_config.getSendmailMessage() != msg) { m_config.setSendmailMessage(msg); } MimeMailMessage mimeMsg = new MimeMailMessage(new MimeMessage(m_session)); mimeMsg.setFrom(m_config.getSendmailMessage().getFrom()); mimeMsg.setTo(m_config.getSendmailMessage().getTo()); mimeMsg.setSubject(m_config.getSendmailMessage().getSubject()); return mimeMsg; } /** * Helper method to create an Authenticator based on Password Authentication * @return */ public Authenticator createAuthenticator() { Authenticator auth; if (m_config.isUseAuthentication()) { auth = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(m_config.getUserAuth().getUserName(), m_config.getUserAuth().getPassword()); } }; } else { auth = null; } return auth; } private Properties createProps(boolean useJmProps) throws IOException { Properties props = generatePropsFromConfig(m_config.getJavamailPropertyCollection()); configureProperties(props, useJmProps); //get rid of this return Session.getDefaultInstance(new Properties()).getProperties(); } private Properties generatePropsFromConfig(List<JavamailProperty> javamailPropertyCollection) { Properties props = new Properties(); for (JavamailProperty property : javamailPropertyCollection) { props.put(property.getName(), property.getValue()); } return props; } /** * This method uses a properties file reader to pull in opennms styled javamail properties and sets * the actual javamail properties. This is here to preserve the backwards compatibility but configuration * will probably change soon. * * FIXME definitely will change soon, will be depreciated * * @throws IOException */ private void configureProperties(Properties sendmailConfigDefinedProps, boolean useJmProps) { //this loads the properties from the old style javamail-configuration.properties //TODO: depreciate this Properties props = null; try { props = JavaMailerConfig.getProperties(); /* These strange properties from javamail-configuration.properties need to be translated into actual javax.mail properties * FIXME: The precedence of the properties file vs. the SendmailConfiguration should probably be addressed here * FIXME: if using a valid sendmail config, it probably doesn't make since to use any of these properties */ if (useJmProps) { m_config.setDebug(PropertiesUtils.getProperty(props, "org.opennms.core.utils.debug", m_config.getDebug())); m_config.getSendmailHost().setHost(PropertiesUtils.getProperty(props, "org.opennms.core.utils.mailHost", m_config.getSendmailHost().getHost())); m_config.setUseJmta(PropertiesUtils.getProperty(props, "org.opennms.core.utils.useJMTA", m_config.getUseJmta())); m_config.getSendmailProtocol().setMailer(PropertiesUtils.getProperty(props, "org.opennms.core.utils.mailer", m_config.getSendmailProtocol().getMailer())); m_config.getSendmailProtocol().setTransport(PropertiesUtils.getProperty(props, "org.opennms.core.utils.transport", m_config.getSendmailProtocol().getTransport())); m_config.getSendmailMessage().setFrom(PropertiesUtils.getProperty(props, "org.opennms.core.utils.fromAddress", m_config.getSendmailMessage().getFrom())); m_config.setUseAuthentication(PropertiesUtils.getProperty(props, "org.opennms.core.utils.authenticate", m_config.getUseAuthentication())); m_config.getUserAuth().setUserName(PropertiesUtils.getProperty(props, "org.opennms.core.utils.authenticateUser", m_config.getUserAuth().getUserName())); m_config.getUserAuth().setPassword(PropertiesUtils.getProperty(props, "org.opennms.core.utils.authenticatePassword", m_config.getUserAuth().getPassword())); m_config.getSendmailProtocol().setMessageContentType(PropertiesUtils.getProperty(props, "org.opennms.core.utils.messageContentType", m_config.getSendmailProtocol().getMessageContentType())); m_config.getSendmailProtocol().setCharSet(PropertiesUtils.getProperty(props, "org.opennms.core.utils.charset", m_config.getSendmailProtocol().getCharSet())); m_config.getSendmailProtocol().setMessageEncoding(PropertiesUtils.getProperty(props, "org.opennms.core.utils.encoding", m_config.getSendmailProtocol().getMessageEncoding())); m_config.getSendmailProtocol().setStartTls(PropertiesUtils.getProperty(props, "org.opennms.core.utils.starttls.enable", m_config.getSendmailProtocol().isStartTls())); m_config.getSendmailProtocol().setQuitWait(PropertiesUtils.getProperty(props, "org.opennms.core.utils.quitwait", m_config.getSendmailProtocol().isQuitWait())); m_config.getSendmailHost().setPort(PropertiesUtils.getProperty(props, "org.opennms.core.utils.smtpport", m_config.getSendmailHost().getPort())); m_config.getSendmailProtocol().setSslEnable(PropertiesUtils.getProperty(props, "org.opennms.core.utils.smtpssl.enable", m_config.getSendmailProtocol().isSslEnable())); } } catch (IOException e) { log().info("configureProperties: could not load javamail.properties, continuing for is no longer required", e); } //this sets any javamail properties that were set in the SendmailConfig object if (props == null) { props = new Properties(); } props.putAll(sendmailConfigDefinedProps); if (!props.containsKey("mail.smtp.auth")) { props.setProperty("mail.smtp.auth", String.valueOf(m_config.isUseAuthentication())); } if (!props.containsKey("mail.smtp.starttls.enable")) { props.setProperty("mail.smtp.starttls.enable", String.valueOf(m_config.getSendmailProtocol().isStartTls())); } if (!props.containsKey("mail.smtp.quitwait")) { props.setProperty("mail.smtp.quitwait", String.valueOf(m_config.getSendmailProtocol().isQuitWait())); } if (!props.containsKey("mail.smtp.port")) { props.setProperty("mail.smtp.port", String.valueOf(m_config.getSendmailHost().getPort())); } if (m_config.getSendmailProtocol().isSslEnable()) { if (!props.containsKey("mail.smtps.auth")) { props.setProperty("mail.smtps.auth", String.valueOf(m_config.isUseAuthentication())); } if (!props.containsKey("mail.smtps.socketFactory.class")) { props.setProperty("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); } if (!props.containsKey("mail.smtps.socketFactory.port")) { props.setProperty("mail.smtps.socketFactory.port", String.valueOf(m_config.getSendmailHost().getPort())); } } if (!props.containsKey("mail.smtp.quitwait")) { props.setProperty("mail.smtp.quitwait", String.valueOf(m_config.getSendmailProtocol().isQuitWait())); } } public void send() throws JavaMailerException { m_message.setText(m_config.getSendmailMessage().getBody()); send(m_message); } private void send(MimeMailMessage message) throws JavaMailerException { Transport t = null; try { SendmailProtocol protoConfig = m_config.getSendmailProtocol(); t = m_session.getTransport(protoConfig.getTransport()); log().debug("for transport name '" + protoConfig.getTransport() + "' got: " + t.getClass().getName() + "@" + Integer.toHexString(t.hashCode())); LoggingTransportListener listener = new LoggingTransportListener(log()); t.addTransportListener(listener); if (t.getURLName().getProtocol().equals("mta")) { // JMTA throws an AuthenticationFailedException if we call connect() log().debug("transport is 'mta', not trying to connect()"); } else if (m_config.isUseAuthentication()) { log().debug("authenticating to " + m_config.getSendmailHost().getHost()); t.connect(m_config.getSendmailHost().getHost(), (int)m_config.getSendmailHost().getPort(), m_config.getUserAuth().getUserName(), m_config.getUserAuth().getPassword()); } else { log().debug("not authenticating to " + m_config.getSendmailHost().getHost()); t.connect(m_config.getSendmailHost().getHost(), (int)m_config.getSendmailHost().getPort(), null, null); } t.sendMessage(message.getMimeMessage(), message.getMimeMessage().getAllRecipients()); listener.assertAllMessagesDelivered(); } catch (NoSuchProviderException e) { log().error("Couldn't get a transport: " + e, e); throw new JavaMailerException("Couldn't get a transport: " + e, e); } catch (MessagingException e) { log().error("Java Mailer messaging exception: " + e, e); throw new JavaMailerException("Java Mailer messaging exception: " + e, e); } finally { try { if (t != null && t.isConnected()) { t.close(); } } catch (MessagingException e) { throw new JavaMailerException("Java Mailer messaging exception on transport close: " + e, e); } } } public void setConfig(SendmailConfig config) { m_config = config; } public SendmailConfig getConfig() { return m_config; } public void setMessage(MimeMailMessage message) { m_message = message; } public MimeMailMessage getMessage() { return m_message; } public void setProperties(Properties properties) { m_properties = properties; } public Properties getProperties() { return m_properties; } }
package net.sf.cglib.util; import java.lang.reflect.Method; /** * @version $Id: MethodConstants.java,v 1.3 2003-07-15 16:38:15 herbyderby Exp $ */ public class MethodConstants { private MethodConstants() { } public static final Method EQUALS = ReflectUtils.findMethod("Object.equals(Object)"); public static final Method GET_DECLARED_METHOD = ReflectUtils.findMethod("Class.getDeclaredMethod(String, Class[])"); public static final Method GET_DECLARED_CONSTRUCTOR = ReflectUtils.findMethod("Class.getDeclaredConstructor(Class[])"); public static final Method HASH_CODE = ReflectUtils.findMethod("Object.hashCode()"); public static final Method FLOAT_TO_INT_BITS = ReflectUtils.findMethod("Float.floatToIntBits(float)"); public static final Method DOUBLE_TO_LONG_BITS = ReflectUtils.findMethod("Double.doubleToLongBits(double)"); public static final Method FOR_NAME = ReflectUtils.findMethod("Class.forName(String)"); public static final Method THROWABLE_GET_MESSAGE = ReflectUtils.findMethod("Throwable.getMessage()"); public static final Method DEFINE_CLASS = ReflectUtils.findMethod("ClassLoader.defineClass(byte[], int, int)"); public static final Method BOOLEAN_VALUE = ReflectUtils.findMethod("Boolean.booleanValue()"); public static final Method CHAR_VALUE = ReflectUtils.findMethod("Character.charValue()"); public static final Method LONG_VALUE = ReflectUtils.findMethod("Number.longValue()"); public static final Method DOUBLE_VALUE = ReflectUtils.findMethod("Number.doubleValue()"); public static final Method FLOAT_VALUE = ReflectUtils.findMethod("Number.floatValue()"); public static final Method INT_VALUE = ReflectUtils.findMethod("Number.intValue()"); public static final Method MAP_PUT = ReflectUtils.findMethod("java.util.Map.put(Object, Object)"); public static final Method MAP_GET = ReflectUtils.findMethod("java.util.Map.get(Object)"); public static final Method STRING_LENGTH = ReflectUtils.findMethod("String.length()"); public static final Method STRING_CHAR_AT = ReflectUtils.findMethod("String.charAt(int)"); public static final Method MAP_KEY_SET = ReflectUtils.findMethod("java.util.Map.keySet()"); public static final Method THREADLOCAL_GET = ReflectUtils.findMethod("ThreadLocal.get()"); public static final Method THREADLOCAL_SET = ReflectUtils.findMethod("ThreadLocal.set(Object)"); }
package tlc2.tool.fp; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import util.TLCRuntime; public class LongArrayTest { @Before public void setup() { Assume.assumeTrue(TLCRuntime.getInstance().getArchitecture() == TLCRuntime.ARCH.x86_64); } @Test public void testGetAndSet() throws IOException { final int elements = 100; final LongArray array = new LongArray(elements); array.zeroMemory(1); for (long i = 0L; i < elements; i++) { assertEquals(0L, array.get(i)); } for (long i = 0L; i < elements; i++) { array.set(i, i); } for (long i = 0L; i < elements; i++) { assertEquals(i, array.get(i)); } for (long i = 0L; i < elements; i++) { array.set(i, Long.MAX_VALUE - i); } for (long i = 0L; i < elements; i++) { assertEquals(Long.MAX_VALUE - i, array.get(i)); } for (long i = 0L; i < elements; i++) { array.set(i, Long.MIN_VALUE + i); } for (long i = 0L; i < elements; i++) { assertEquals(Long.MIN_VALUE + i, array.get(i)); } } @Test public void testOutOfRangePositive() throws IOException { final LongArray array = new LongArray(1); try { array.get(1); } catch (AssertionError e) { return; } fail(); } @Test public void testOutOfRangeNegative() throws IOException { final LongArray array = new LongArray(1); try { array.get(-1); } catch (AssertionError e) { return; } fail(); } @Test public void testGetAndTrySet() throws IOException { final int elements = 100; final LongArray array = new LongArray(elements); array.zeroMemory(1); // Assert zero successful for (long i = 0L; i < elements; i++) { assertEquals(0L, array.get(i)); } // trySet linear elements. for (long i = 0L; i < elements; i++) { assertTrue(array.trySet(i, 0, i)); } for (long i = 0L; i < elements; i++) { assertEquals(i, array.get(i)); } // Replace with largest possible values for (long i = 0L; i < elements; i++) { array.trySet(i, i, Long.MAX_VALUE - i); } for (long i = 0L; i < elements; i++) { assertEquals(Long.MAX_VALUE - i, array.get(i)); } // Replace with smallest possible values for (long i = 0L; i < elements; i++) { array.trySet(i, Long.MAX_VALUE - i, Long.MIN_VALUE + i); } for (long i = 0L; i < elements; i++) { assertEquals(Long.MIN_VALUE + i, array.get(i)); } } @Test public void testZeroMemory() throws IOException { for (int k = 1; k < 8; k++) { for (int i = 1; i < 128; i++) { final LongArray array = new LongArray(i); array.zeroMemory(k); for (int j = 0; i < j; i++) { assertEquals(0L, array.get(j)); } for (int j = 0; i < j; i++) { array.set(j, -1L); } } } } }
package databook.persistence.rule.rdf; import static databook.utils.ModelUtils.DATABOOK_MODEL_URI; import static databook.utils.ModelUtils.IS_A; import static databook.utils.ModelUtils.*; import static databook.utils.ModelUtils.databookStatement; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.net.URI; import databook.local.model.RDFDatabase.Format; import databook.local.model.RDFDatabase.RDFDatabaseTransaction; import databook.persistence.rule.EntityRule; import databook.persistence.rule.PersistenceContext; import databook.persistence.rule.rdf.ruleset.RDFEntity; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class RDFEntityRule<T extends RDFEntity> implements EntityRule<T, PersistenceContext> { private static final Log log = LogFactory.getLog(RDFEntityRule.class); // utilities public static void createAllProperties(RDFEntity e, PersistenceContext context) { try { BeanInfo info = Introspector.getBeanInfo(e.getClass()); for(PropertyDescriptor pd : info.getPropertyDescriptors()) { String prop = pd.getName(); Object o = pd.getReadMethod().invoke(e); context.create(e, prop, o); } } catch (Exception e1) { e1.printStackTrace(); } } public static void deleteAllProperties(RDFEntity e, PersistenceContext context) { try { BeanInfo info = Introspector.getBeanInfo(e.getClass()); for(PropertyDescriptor pd : info.getPropertyDescriptors()) { String prop = pd.getName(); // set obj to null to indicate delete all // Object o = pd.getReadMethod().invoke(e); context.delete(e, prop, null); } } catch (Exception e1) { e1.printStackTrace(); } } public static boolean isPrimitiveType(Class type) { return type.equals(Integer.class) || type.equals(Boolean.class) || type.equals(Double.class) || type.equals(String.class); } @Override public void create(T e, PersistenceContext context) { java.net.URI uri = e.getUri(); RDFDatabaseTransaction trans = context.getRdfTrans(); trans.add(databookStatement(bracket(uri), IS_A, getType(e)), Format.N3, DATABOOK_MODEL_URI); createAllProperties(e, context); } public String getType(T e) { URI uri = e.getTypeUri(); return uri!=null?uri.toString():databookResource(e.getClass().getSimpleName()); } @Override public void delete(T e, PersistenceContext context) { java.net.URI uri = e.getUri(); deleteAllProperties(e, context); RDFDatabaseTransaction trans = context.getRdfTrans(); trans.remove(databookStatement(bracket(uri), IS_A, getType(e)), Format.N3, DATABOOK_MODEL_URI); } @Override public void modify(T e0, T e1, PersistenceContext context) { try { BeanInfo info = Introspector.getBeanInfo(e0.getClass()); for(PropertyDescriptor pd : info.getPropertyDescriptors()) { String prop = pd.getName(); Object o0 = pd.getReadMethod().invoke(e0); Object o1 = pd.getReadMethod().invoke(e1); context.modify(e0, prop, o0, o1); } } catch (Exception e2) { e2.printStackTrace(); } } @Override public void union(T e0, T e1, PersistenceContext context) { try { BeanInfo info = Introspector.getBeanInfo(e0.getClass()); for(PropertyDescriptor pd : info.getPropertyDescriptors()) { String prop = pd.getName(); Object o0 = pd.getReadMethod().invoke(e0); Object o1 = pd.getReadMethod().invoke(e1); Class type = pd.getPropertyType(); context.union(e0, prop, o0, o1); } } catch (Exception e2) { e2.printStackTrace(); } } @Override public void diff(T e0, T e1, PersistenceContext context) { try { BeanInfo info = Introspector.getBeanInfo(e0.getClass()); for(PropertyDescriptor pd : info.getPropertyDescriptors()) { String prop = pd.getName(); Object o0 = pd.getReadMethod().invoke(e0); Object o1 = pd.getReadMethod().invoke(e1); Class type = pd.getPropertyType(); context.diff(e0, prop, o0, o1); } } catch (Exception e2) { e2.printStackTrace(); } } }
package org.eclipse.che.api.builder; import org.eclipse.che.api.builder.dto.BuilderDescriptor; import org.eclipse.che.api.builder.dto.BuilderEnvironment; import org.eclipse.che.api.builder.internal.BuildListener; import org.eclipse.che.api.builder.internal.BuildLogger; import org.eclipse.che.api.builder.internal.BuildResult; import org.eclipse.che.api.builder.internal.BuildTask; import org.eclipse.che.api.builder.internal.Builder; import org.eclipse.che.api.builder.internal.BuilderConfiguration; import org.eclipse.che.api.builder.internal.DelegateBuildLogger; import org.eclipse.che.api.builder.internal.SourceManagerListener; import org.eclipse.che.api.builder.internal.SourcesManager; import org.eclipse.che.api.builder.dto.BuildRequest; import org.eclipse.che.api.core.notification.EventService; import org.eclipse.che.api.core.rest.shared.dto.Link; import org.eclipse.che.api.core.util.CommandLine; import org.eclipse.che.api.project.shared.dto.ProjectDescriptor; import org.eclipse.che.commons.lang.IoUtil; import org.eclipse.che.dto.server.DtoFactory; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.eclipse.che.dto.server.DtoFactory.newDto; /** @author andrew00x */ public class BuilderTest { // Simple test for main Builder components. Don't run any real build processes. public static class MyBuilder extends Builder { MyDelegateBuildLogger logger; public MyBuilder(File root, int numberOfWorkers, int queueSize, int cleanBuildResultDelay) { super(root, numberOfWorkers, queueSize, cleanBuildResultDelay, new EventService()); } @Override public String getName() { return "my"; } @Override public String getDescription() { return null; } @Override protected BuildResult getTaskResult(FutureBuildTask task, boolean successful) { return new BuildResult(successful); } @Override protected CommandLine createCommandLine(BuilderConfiguration config) { return new CommandLine("echo", "test"); // display line of text } @Override protected BuildLogger createBuildLogger(BuilderConfiguration buildConfiguration, java.io.File logFile) throws BuilderException { return logger = new MyDelegateBuildLogger(super.createBuildLogger(buildConfiguration, logFile)); } @Override public SourcesManager getSourcesManager() { return new SourcesManager() { @Override public void getSources(BuildLogger logger, String workspace, String project, String sourcesUrl, File workDir) throws IOException { // Don't need for current set of tests. } @Override public java.io.File getDirectory() { return getSourcesDirectory(); } @Override public boolean addListener(SourceManagerListener listener) { return false; } @Override public boolean removeListener(SourceManagerListener listener) { return false; } }; } @Override public Map<String, BuilderEnvironment> getEnvironments() { BuilderEnvironment builderEnvironment = DtoFactory.getInstance().createDto(BuilderEnvironment.class) .withId("default") .withIsDefault(true) .withDisplayName(this.getName()); return Collections.singletonMap(builderEnvironment.getId(), builderEnvironment); } } public static class MyDelegateBuildLogger extends DelegateBuildLogger { private StringBuilder buff = new StringBuilder(); public MyDelegateBuildLogger(BuildLogger delegate) { super(delegate); } @Override public void writeLine(String line) throws IOException { if (line != null) { if (buff.length() > 0) { buff.append('\n'); } buff.append(line); } super.writeLine(line); } public String getLogsAsString() { return buff.toString(); } } private java.io.File repo; private MyBuilder builder; @BeforeTest public void setUp() throws Exception { repo = createRepository(); builder = new MyBuilder(repo, Runtime.getRuntime().availableProcessors(), 100, 3600); builder.start(); } @AfterTest public void tearDown() { builder.stop(); Assert.assertTrue(IoUtil.deleteRecursive(repo), "Unable remove test directory"); } static java.io.File createRepository() throws Exception { java.io.File root = new java.io.File(System.getProperty("workDir"), "repo"); if (!(root.exists() || root.mkdirs())) { Assert.fail("Unable create test directory"); } return root; } @Test public void testRunTask() throws Exception { final BuildRequest buildRequest = DtoFactory.getInstance().createDto(BuildRequest.class); buildRequest.setBuilder("my"); buildRequest.setSourcesUrl("http://localhost/a" /* ok for test, nothing download*/); buildRequest.setProjectDescriptor(DtoFactory.getInstance().createDto(ProjectDescriptor.class) .withName("my_project") .withType("my_type")); final BuildTask task = builder.perform(buildRequest); waitForTask(task); Assert.assertEquals(builder.logger.getLogsAsString(), "test"); } @Test public void testBuildListener() throws Exception { final boolean[] beginFlag = new boolean[]{false}; final boolean[] endFlag = new boolean[]{false}; final BuildListener listener = new BuildListener() { @Override public void begin(BuildTask task) { beginFlag[0] = true; } @Override public void end(BuildTask task) { endFlag[0] = true; } }; Assert.assertTrue(builder.addBuildListener(listener)); final BuildRequest buildRequest = DtoFactory.getInstance().createDto(BuildRequest.class); buildRequest.setBuilder("my"); buildRequest.setSourcesUrl("http://localhost/a" /* ok for test, nothing download*/); buildRequest.setProjectDescriptor(DtoFactory.getInstance().createDto(ProjectDescriptor.class) .withName("my_project") .withType("my_type")); final BuildTask task = builder.perform(buildRequest); waitForTask(task); Assert.assertTrue(beginFlag[0]); Assert.assertTrue(endFlag[0]); Assert.assertTrue(builder.removeBuildListener(listener)); } @Test public void testRemoteBuildSameEnvironment(){ BuilderDescriptor builderDescriptor = newDto(BuilderDescriptor.class) .withName(builder.getName()) .withDescription(builder.getDescription()) .withEnvironments(builder.getEnvironments()); RemoteBuilder remoteBuilder = new RemoteBuilder("", builderDescriptor, new ArrayList<Link>()); Assert.assertEquals(remoteBuilder.getBuilderEnvironment(), builder.getEnvironments()); } private void waitForTask(BuildTask task) throws Exception { final long end = System.currentTimeMillis() + 5000; synchronized (this) { while (!task.isDone()) { wait(100); if (System.currentTimeMillis() > end) { Assert.fail("timeout"); } } } } }
package dosna.api.notification; import dosna.content.DOSNAContent; /** * Class that provides methods to handle sending notifications * * @author Joshua Kissoon * @since 20140611 */ public class NotificationsManager { /** * Send a notification to a specific actor * * @param actorId The actor to send the notification to * @param content The content to notify about * @param message The notification message * * @return Whether the notification was successful or not */ public boolean sendNotification(String actorId, DOSNAContent content, String message) { } /** * Send a notification to all actors related to a content * * @param content The content to notify about * @param message The notification message * * @return Whether the notification was successful or not */ public boolean sendNotification(DOSNAContent content, String message) { } }
package dr.app.phylogeography.tools; import dr.app.tools.TimeSlicer; import dr.app.util.Arguments; import dr.util.HeapSort; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import org.jdom.Element; import org.jdom.output.XMLOutputter; import org.jdom.output.Format; /** * @author Philippe Lemey * @author Andrew Rambaut * @author Marc A. Suchard */ public class RateIndicatorBF { public static final String LOCATIONSFILE = "locationsfile"; public static final String HELP = "help"; public static final String BURNIN = "burnin"; public static final String KML = "kml"; public static final String PMEAN = "pmean"; public static final String POFFSET = "poffset"; public static final String ISTRING = "istring"; public static final String RSTRING = "rstring"; public static final String PSTRING = "pstring"; public static final String GSTRING = "gstring"; public static final String LOWCOLOR = "lowcolor"; public static final String UPCOLOR = "upcolor"; public static final String WIDTH = "width"; public static final String KMLFILE = "kmlfile"; public static final String BFCUTOFF = "bfcutoff"; public static final String ICUTOFF = "icutoff"; public static final String LOCATIONSTATES = "locationstates"; public static final String BWC = "bwc"; public static final String BWM = "bwm"; public static final String ALTITUDE = "altitude"; public static final String[] falseTrue = new String[] {"false","true"}; private static PrintStream progressStream = System.out; private static final String commandName = "rateIndicatorBF"; public static void printUsage(Arguments arguments) { arguments.printUsage(commandName, "<input-file-name> [<output-file-name>]"); progressStream.println(); progressStream.println(" Example: " + commandName + " indicator.log rates.out"); progressStream.println(); } public RateIndicatorBF (String inputFileName, int burnin, String rateIndicatorString, int numberOfStates, String[][] locations, boolean bayesFactor, double cutoff, double meanPoissonPrior, int offsetPoissonPrior, String actualRateString, String relativeRateString, String geoSiteModelString) { //count the number of states in the RateIndicatorLog file generationCount = getGenerationCount(inputFileName); //find the first rateIndicator in the RateIndicatorLog file int firstRateIndicator = getFirstEntryOf(inputFileName, rateIndicatorString); //progressStream.println("first rateIndicator is at column "+firstRateIndicator); //count the rateIndicators in the RateIndicatorLog file int numberOfRateIndicators = getNumberOfEntries(inputFileName, firstRateIndicator, rateIndicatorString); if (numberOfStates > 0) { statesCounter = numberOfStates; progressStream.println("number of states provided = "+statesCounter); } else { statesCounter = locations.length; progressStream.println("number of states in coordinates file = "+statesCounter); } this.bayesFactor = bayesFactor; this.cutoff = cutoff; this.meanPoissonPrior = meanPoissonPrior; this.offsetPoissonPrior = offsetPoissonPrior; this.actualRateString = actualRateString; this.relativeRateString = relativeRateString; this.geoSiteModelString = geoSiteModelString; if (numberOfRateIndicators != ((statesCounter*(statesCounter-1.0))/2.0)) { if (numberOfRateIndicators == (statesCounter*(statesCounter-1.0))) { progressStream.println("K*(K-1) rateIndicators, with K = "+ statesCounter+". So, nonreversible matrix!"); nonreversible = true; } else { System.err.println("the number of rateIndicators ("+numberOfRateIndicators+") does not match (K*(K-1)/2) states ("+((statesCounter*(statesCounter-1.0))/2.0)+"; with K = "+statesCounter+")."); } } // so now we know the dimension of the rateIndicator array if ((generationCount - burnin)< 10) { System.err.println("With burn-in = "+burnin+", there are only "+(generationCount - burnin)+" state(s) in indicator log file??"); } double[][] rateIndicators = new double[((generationCount - 1)-burnin)][numberOfRateIndicators]; fillRateIndicatorArray(inputFileName,rateIndicators,burnin,firstRateIndicator,numberOfRateIndicators); //print2DArray(rateIndicators, "test.txt"); expectedRateIndicators = meanCol(rateIndicators); //compile locations locationNames = new String [numberOfRateIndicators][2]; longitudes = new double [numberOfRateIndicators][2]; latitudes = new double [numberOfRateIndicators][2]; this.locations = locations; compileLocations(locations,locationNames,latitudes,longitudes); supportedRateIndicators = getSupportedRateIndicators(); //below is for rateSummary int numberOfActualRates = numberOfRateIndicators; //boolean to see it the rateLog contains productStatitistics, if not, we make 'em ourselves boolean containsActualRates = hasEntryOf(inputFileName, actualRateString); if (!containsActualRates){ // if there are no productStatistics, we will look for the relativ rates instead actualRateString = relativeRateString; } int firstActualRate = getFirstEntryOf(inputFileName, actualRateString); // int geoSiteModelMuPosition = getFirstEntryOf(inputFileName, geoSiteModelString); //System.out.println("geoSiteModelMu is at column "+geoSiteModelMuPosition); } private double[] getSupportedRateIndicators(){ int indicatorCounter = 0; for (int p = 0; p < expectedRateIndicators.length; p++){ double indicator = expectedRateIndicators[p]; if (!bayesFactor) { if (indicator > cutoff) { indicatorCounter ++; } } else { if (indicator > getBayesFactorCutOff(cutoff, meanPoissonPrior, offsetPoissonPrior, statesCounter, nonreversible)) { indicatorCounter ++; } } } double[] supportedIndicators = new double[indicatorCounter]; supportedBFs = new double[indicatorCounter]; supportedLocations = new String[indicatorCounter][2]; supportedLatitudes = new double[indicatorCounter][2]; supportedLongitudes = new double[indicatorCounter][2]; int[] indices = new int[expectedRateIndicators.length]; HeapSort.sort(expectedRateIndicators, indices); int fillCount = 0; for (int o = 0; o < expectedRateIndicators.length; o++){ //we order rate indicators in decreasing order double indicator = expectedRateIndicators[indices[expectedRateIndicators.length - o - 1]]; double BF = getBayesFactor(indicator, meanPoissonPrior, statesCounter, offsetPoissonPrior, nonreversible, 0); if (BF == Double.POSITIVE_INFINITY) { BF = getBayesFactor(indicator, meanPoissonPrior, statesCounter, offsetPoissonPrior, nonreversible, generationCount); } double threshold = (bayesFactor ? getBayesFactorCutOff(cutoff, meanPoissonPrior, offsetPoissonPrior, statesCounter, nonreversible) : cutoff); if (indicator > threshold) { supportedIndicators[fillCount] = indicator; supportedBFs[fillCount] = BF; supportedLocations[fillCount][0] = locationNames[indices[(expectedRateIndicators.length - o - 1)]][0]; supportedLocations[fillCount][1] = locationNames[indices[(expectedRateIndicators.length - o - 1)]][1]; supportedLatitudes[fillCount][0] = latitudes[indices[(expectedRateIndicators.length - o - 1)]][0]; supportedLatitudes[fillCount][1] = latitudes[indices[(expectedRateIndicators.length - o - 1)]][1]; supportedLongitudes[fillCount][0] = longitudes[indices[(expectedRateIndicators.length - o - 1)]][0]; supportedLongitudes[fillCount][1] = longitudes[indices[(expectedRateIndicators.length - o - 1)]][1]; fillCount ++; } } return supportedIndicators; } private void compileLocations(String[][] locations, String[][] locationNames, double[][] latitudes, double[][] longitudes){ //begin of new code int elementCounter = 0; int secondCounter = 0; for (int i = 0; i < (statesCounter - 1); i++) { secondCounter ++; for (int j = secondCounter; j < statesCounter; j++) { if (locations != null) { locationNames[elementCounter][0] = locations[i][0]; longitudes[elementCounter][0] = Double.parseDouble(locations[i][2]); latitudes[elementCounter][0] = Double.parseDouble(locations[i][1]); locationNames[elementCounter][1] = locations[j][0]; longitudes[elementCounter][1] = Double.parseDouble(locations[j][2]); latitudes[elementCounter][1] = Double.parseDouble(locations[j][1]); } else { locationNames[elementCounter][0] = "location"+(i+1); longitudes[elementCounter][0] = Double.NaN; latitudes[elementCounter][0] = Double.NaN; locationNames[elementCounter][1] = "location"+(j+1); longitudes[elementCounter][1] = Double.NaN; latitudes[elementCounter][1] = Double.NaN; } elementCounter ++; } } // for nonreversible models, we keep on filling the arrays if (nonreversible) { for (int k = 0; k < elementCounter; k++) { locationNames[elementCounter + k][0] = locationNames[k][1]; longitudes[elementCounter + k][0] = longitudes[k][1]; latitudes[elementCounter + k][0] = latitudes[k][1]; locationNames[elementCounter + k][1] = locationNames[k][0]; longitudes[elementCounter + k][1] = longitudes[k][0]; latitudes[elementCounter + k][1] = latitudes[k][0]; } } } public void outputKML(String KMLoutputFile,String lowerLinkColor,String upperLinkColor, double branchWidthConstant, double branchWidthMultiplier, double altitudeFactor){ double divider = 100; PrintStream resultsStream = System.out; if (KMLoutputFile != null) { try { resultsStream = new PrintStream(new File(KMLoutputFile)); } catch (IOException e) { System.err.println("Error opening file: "+KMLoutputFile); System.exit(-1); } } Element rootElement = new Element("kml"); Element documentElement = new Element("Document"); Element folderElement = new Element("Folder"); Element documentNameElement = new Element("name"); documentNameElement.addContent(KMLoutputFile); documentElement.addContent(documentNameElement); List<Element> schema = new ArrayList<Element>(); Element locationSchema = new Element("Schema"); locationSchema.setAttribute("id", "Locations_Schema"); locationSchema.addContent(new Element("SimpleField") .setAttribute("name", "Name") .setAttribute("type", "string")); locationSchema.addContent(new Element("SimpleField") .setAttribute("name", "In") .setAttribute("type", "number")); locationSchema.addContent(new Element("SimpleField") .setAttribute("name", "Out") .setAttribute("type", "number")); locationSchema.addContent(new Element("SimpleField") .setAttribute("name", "Total") .setAttribute("type", "number")); Element ratesSchema = new Element("Schema"); ratesSchema.setAttribute("id", "Rates_Schema"); ratesSchema.addContent(new Element("SimpleField") .setAttribute("name", "Name") .setAttribute("type", "string")); ratesSchema.addContent(new Element("SimpleField") .setAttribute("name", "BF") .setAttribute("type", "double")); ratesSchema.addContent(new Element("SimpleField") .setAttribute("name", "Indicator") .setAttribute("type", "double")); schema.add(ratesSchema); documentElement.addContent(schema); Element folderNameElement = new Element("name"); String cutoffString; if (bayesFactor) { cutoffString = "bayes factor"; } else { cutoffString = "indicator"; } folderNameElement.addContent("discrete rates with "+cutoffString+" larger than "+cutoff); folderElement.addContent(folderNameElement); double[] minMax = new double[2]; if (supportedRateIndicators.length > 0) { minMax[0] = supportedRateIndicators[supportedRateIndicators.length - 1]; minMax[1] = supportedRateIndicators[0]; } else { minMax[0] = minMax[1] = 0; System.err.println("No rate indicators above the specified cut-off!"); } for (int p = 0; p < supportedRateIndicators.length; p++){ addRateAndStyle(supportedRateIndicators[p], supportedLongitudes[p][0], supportedLatitudes[p][0], supportedLongitudes[p][1], supportedLatitudes[p][1], p+1, branchWidthConstant, branchWidthMultiplier, minMax, altitudeFactor, divider, lowerLinkColor, upperLinkColor, folderElement, documentElement); } //add locations Element folder1Element = new Element("Folder"); Element folderName1Element = new Element("name"); folderName1Element.addContent("Rates"); folder1Element.addContent(folderName1Element); addLocations(folder1Element); documentElement.addContent(folder1Element); for (int p = 0; p < supportedRateIndicators.length; p++){ addRateWithData(supportedRateIndicators[p], supportedBFs[p], supportedLocations[p][0], supportedLocations[p][1], supportedLongitudes[p][0], supportedLatitudes[p][0], supportedLongitudes[p][1], supportedLatitudes[p][1], p+1, folder1Element); } //add locations Element folder2Element = new Element("Folder"); Element folderName2Element = new Element("name"); folderName2Element.addContent("Locations"); folder2Element.addContent(folderName2Element); addLocations(folder2Element); documentElement.addContent(folder2Element); documentElement.addContent(folderElement); rootElement.addContent(documentElement); XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat().setTextMode(Format.TextMode.PRESERVE)); try { xmlOutputter.output(rootElement,resultsStream); } catch (IOException e) { System.err.println("IO Exception encountered: "+e.getMessage()); System.exit(-1); } } private void addLocations(Element folderElement){ for (int i = 0; i < locations.length ; i++) { Element placemarkElement = new Element("Placemark"); Element placemarkNameElement = new Element("name"); placemarkNameElement.addContent(locations[i][0]); placemarkElement.addContent(placemarkNameElement); int inCount = 0; int outCount = 0; for (int j = 0; j < supportedRateIndicators.length; j++) { if (supportedLocations[j][0].equals(locations[i][0])) { inCount ++; } if (supportedLocations[j][1].equals(locations[i][0])) { outCount ++; } } int totalCount = inCount + outCount; Element data = new Element("ExtendedData"); Element schemaData = new Element("SchemaData"); schemaData.setAttribute("schemaUrl", "#Location_Schema"); schemaData.addContent(new Element("SimpleData").setAttribute("name", "Name").addContent(locations[i][0])); schemaData.addContent(new Element("SimpleData").setAttribute("name", "In").addContent(Integer.toString(inCount))); schemaData.addContent(new Element("SimpleData").setAttribute("name", "Out").addContent(Integer.toString(outCount))); schemaData.addContent(new Element("SimpleData").setAttribute("name", "Total").addContent(Integer.toString(totalCount))); data.addContent(schemaData); placemarkElement.addContent(data); Element pointElement = new Element("Point"); Element altitude = new Element("altitudeMode"); altitude.addContent("relativeToGround"); pointElement.addContent(altitude); Element coordinates = new Element("coordinates"); coordinates.addContent(locations[i][2]+","+locations[i][1]+",0"); pointElement.addContent(coordinates); placemarkElement.addContent(pointElement); folderElement.addContent(placemarkElement); } } private void addRateAndStyle(double rateIndicator, double startLongitude, double startLatitude, double endLongitude, double endLatitude, int number, double branchWidthConstant, double branchWidthMultiplier, double[] minAndMaxRateIndicator, double altitudeFactor, double divider, String lowerLinkColor, String upperLinkColor, Element folderElement, Element documentElement) { String opacity = "FF"; double distance = (3958*Math.PI*Math.sqrt((endLatitude-startLatitude)*(endLatitude-startLatitude)+Math.cos(endLatitude/57.29578)*Math.cos(startLatitude/57.29578)*(endLongitude-startLongitude)*(endLongitude-startLongitude))/180); double maxAltitude = distance*altitudeFactor; double latitudeDifference = endLatitude - startLatitude; double longitudeDifference = endLongitude - startLongitude; boolean longitudeBreak = false; //if we go through the 180 if (endLongitude*startLongitude < 0) { double trialDistance = 0; if (endLongitude < 0) { trialDistance += (endLongitude + 180); trialDistance += (180 - startLongitude); //System.out.println(parentLongitude+"\t"+longitude+"\t"+trialDistance+"\t"+longitudeDifference); } else { trialDistance += (startLongitude + 180); trialDistance += (180 - endLongitude); //System.out.println(parentLongitude+"\t"+longitude+"\t"+trialDistance+"\t"+longitudeDifference); } if (trialDistance < Math.abs(longitudeDifference)) { longitudeDifference = trialDistance; longitudeBreak = true; //System.out.println("BREAK!"+longitudeDifference); } } Element styleElement = new Element("Style"); styleElement.setAttribute("id","rate"+number+"_style"); Element lineStyle = new Element("LineStyle"); Element width = new Element("width"); width.addContent(Double.toString(branchWidthConstant+branchWidthMultiplier*rateIndicator)); Element color = new Element("color"); String colorString = TimeSlicer.getKMLColor(rateIndicator,minAndMaxRateIndicator,lowerLinkColor,upperLinkColor); color.addContent(opacity+colorString); lineStyle.addContent(width); lineStyle.addContent(color); styleElement.addContent(lineStyle); documentElement.addContent(styleElement); double currentLongitude1 = 0; //we need this if we go through the 180 double currentLongitude2 = 0; //we need this if we go through the 180 for (int a = 0; a < divider; a ++) { Element placemarkElement = new Element("Placemark"); Element placemarkNameElement = new Element("name"); String name = "rate"+number+"_part"+(a+1); placemarkNameElement.addContent(name); placemarkElement.addContent(placemarkNameElement); Element placemarkStyleElement = new Element("styleUrl"); placemarkStyleElement.addContent("#rate"+number+"_style"); placemarkElement.addContent(placemarkStyleElement); Element lineStringElement = new Element("LineString"); Element altitudeMode = new Element("altitudeMode"); altitudeMode.addContent("relativeToGround"); lineStringElement.addContent(altitudeMode); Element tessellate = new Element("tessellate"); tessellate.addContent("1"); lineStringElement.addContent(tessellate); Element coordinatesElement = new Element("coordinates"); StringBuffer coordinatesStartBuffer = new StringBuffer(); StringBuffer coordinatesEndBuffer = new StringBuffer(); if (longitudeBreak) { if (startLongitude > 0) { currentLongitude1 = startLongitude+a*(longitudeDifference/divider); if (currentLongitude1 < 180) { coordinatesStartBuffer.append(currentLongitude1+","); //System.out.println("1 currentLongitude1 < 180\t"+currentLongitude1+"\t"+longitude); } else { coordinatesStartBuffer.append((-180-(180-currentLongitude1))+","); //System.out.println("2 currentLongitude1 > 180\t"+currentLongitude1+"\t"+(-180-(180-currentLongitude1))+"\t"+longitude); } } else { currentLongitude1 = startLongitude-a*(longitudeDifference/divider); if (currentLongitude1 > (-180)) { coordinatesStartBuffer.append(currentLongitude1+","); //System.out.println("currentLongitude1 > -180\t"+currentLongitude1+"\t"+longitude); } else { coordinatesStartBuffer.append((180+(currentLongitude1+180))+","); //System.out.println("currentLongitude1 > -180\t"+(180+(currentLongitude1+180))+"\t"+longitude); } } } else { coordinatesStartBuffer.append((startLongitude+a*(longitudeDifference/divider))+","); } coordinatesStartBuffer.append((startLatitude+a*(latitudeDifference/divider))+","+(maxAltitude*Math.sin(Math.acos(1 - a*(1.0/(divider/2.0)))))); if (longitudeBreak) { if (startLongitude > 0) { currentLongitude2 = startLongitude+(a+1)*(longitudeDifference/divider); if (currentLongitude2 < 180) { coordinatesEndBuffer.append((currentLongitude2)+","); } else { coordinatesEndBuffer.append((-180-(180-currentLongitude2))+","); } } else { currentLongitude2 = startLongitude-(a+1)*(longitudeDifference/divider); if (currentLongitude2 > (-180)) { coordinatesEndBuffer.append(currentLongitude2+","); } else { coordinatesEndBuffer.append((180+(currentLongitude2+180))+","); } } } else { coordinatesEndBuffer.append((startLongitude+(a+1)*(longitudeDifference/divider))+","); } coordinatesEndBuffer.append((startLatitude+(a+1)*(latitudeDifference/divider))+","+(maxAltitude*Math.sin(Math.acos(1 - (a+1)*(1.0/(divider/2.0)))))); coordinatesElement.addContent(coordinatesStartBuffer.toString()); coordinatesElement.addContent(" "); coordinatesElement.addContent(coordinatesEndBuffer.toString()); lineStringElement.addContent(coordinatesElement); placemarkElement.addContent(lineStringElement); folderElement.addContent(placemarkElement); } } private void addRateWithData(double rateIndicator, double BF, String fromLocation, String toLocation, double startLongitude, double startLatitude, double endLongitude, double endLatitude, int number, Element folderElement) { Element placemarkElement = new Element("Placemark"); Element placemarkNameElement = new Element("name"); String name = "rate"+number; placemarkNameElement.addContent(name); placemarkElement.addContent(placemarkNameElement); Element data = new Element("ExtendedData"); Element schemaData = new Element("SchemaData"); schemaData.setAttribute("schemaUrl", "#Rate_Schema"); schemaData.addContent(new Element("SimpleData").setAttribute("name", "Name").addContent(name)); schemaData.addContent(new Element("SimpleData").setAttribute("name", "From").addContent(fromLocation)); schemaData.addContent(new Element("SimpleData").setAttribute("name", "To").addContent(toLocation)); schemaData.addContent(new Element("SimpleData").setAttribute("name", "BF").addContent(Double.toString(BF))); schemaData.addContent(new Element("SimpleData").setAttribute("name", "Indicator").addContent(Double.toString(rateIndicator))); data.addContent(schemaData); placemarkElement.addContent(data); Element lineStringElement = new Element("LineString"); Element altitudeMode = new Element("altitudeMode"); altitudeMode.addContent("clampToGround"); lineStringElement.addContent(altitudeMode); Element tessellate = new Element("tessellate"); tessellate.addContent("1"); lineStringElement.addContent(tessellate); Element coordinatesElement = new Element("coordinates"); coordinatesElement.addContent(startLongitude + "," + startLatitude + " " + endLongitude + "," + endLatitude); lineStringElement.addContent(coordinatesElement); placemarkElement.addContent(lineStringElement); folderElement.addContent(placemarkElement); } public void outputTextFile(String outFileName) { // double[] minMax = new double[2]; // minMax[0] = supportedRateIndicators[0]; // minMax[1] = supportedRateIndicators[supportedRateIndicators.length - 1]; try { PrintWriter outFile; if (outFileName != null) { outFile = new PrintWriter(new FileWriter(outFileName), true); } else { outFile = new PrintWriter(System.out); } //sort expected rateIndicator if (bayesFactor) { outFile.println("Indicator cutoff (for BF = "+cutoff+") = "+getBayesFactorCutOff(cutoff, meanPoissonPrior, offsetPoissonPrior, statesCounter, nonreversible)); } else { outFile.println("Indicator cutoff = "+cutoff); } outFile.println("mean Poisson Prior = "+meanPoissonPrior); outFile.println("Poisson Prior offset = "+offsetPoissonPrior); for (int o = 0; o < supportedRateIndicators.length; o++){ outFile.print( "I="+supportedRateIndicators[o]+"\tBF"); double BF = getBayesFactor(supportedRateIndicators[o], meanPoissonPrior, statesCounter, offsetPoissonPrior, nonreversible, 0); if (BF == Double.POSITIVE_INFINITY) { outFile.print(">"+getBayesFactor(supportedRateIndicators[o], meanPoissonPrior, statesCounter, offsetPoissonPrior, nonreversible, generationCount)); } else { outFile.print("="+BF); } StringBuilder sb = new StringBuilder(); sb.append(" : between ") .append(supportedLocations[o][0]); if (!Double.isNaN(supportedLongitudes[o][0])) { sb.append(" (long: ") .append(supportedLongitudes[o][0]) .append("; lat: ") .append(supportedLatitudes[o][0]) .append(")"); } sb.append(" and ") .append(supportedLocations[o][1]); if (!Double.isNaN(supportedLongitudes[o][1])) { sb.append(" (long: ") .append(supportedLongitudes[o][1]) .append("; lat: ") .append(supportedLatitudes[o][1]) .append(")"); } outFile.print(sb.toString()); outFile.println(); } outFile.close(); } catch(IOException io) { System.err.print("Error writing to file: " + outFileName); } } private double[] expectedRateIndicators; private boolean nonreversible = false; private String[][] locations; // contains start and end locations for transitions private String[][] locationNames; // contains start and end locations for transitions private double[][] longitudes; // contains start and end longitudes for transitions private double[][] latitudes; // contains start and end latitudes for transitions private String[][] supportedLocations; // contains start and end locations for transitions private double[][] supportedLongitudes; // contains start and end longitudes for transitions private double[][] supportedLatitudes; // contains start and end latitudes for transitions private int statesCounter; private double[] supportedBFs; private double[] supportedRateIndicators; private boolean bayesFactor; private double cutoff; private double meanPoissonPrior; private int offsetPoissonPrior; private String actualRateString; private String relativeRateString; private String geoSiteModelString; private int generationCount; private static double getBayesFactor(double meanIndicator, double meanPoissonPrior, int numberOfLocations, int offset, boolean nonreversible, double generations) { double bayesFactor = 0; double priorProbabilityDenominator = 0; int numberOfRatesMultiplier = 2; priorProbabilityDenominator = meanPoissonPrior + offset; if (nonreversible) numberOfRatesMultiplier = 1; double priorProbability = priorProbabilityDenominator/((numberOfLocations*(numberOfLocations-1))/numberOfRatesMultiplier); double priorOdds = priorProbability/(1.0 - priorProbability); double posteriorProbability = meanIndicator; double posteriorOdds; if (generations > 0) { posteriorOdds = (posteriorProbability - (1/generations))/(1 - (posteriorProbability - (1/generations))); } else { posteriorOdds = posteriorProbability/(1 - posteriorProbability); } bayesFactor = posteriorOdds/priorOdds; return bayesFactor; } private static double getBayesFactorCutOff(double bayesFactor, double meanPoissonPrior, int offset, int numberOfLocations, boolean nonreversible) { double bayesFactorCutoff = 0; double posteriorOdds = 0; int numberOfRatesMultiplier = 2; if (nonreversible) numberOfRatesMultiplier = 1; double priorProbability = (meanPoissonPrior + offset)/((numberOfLocations*(numberOfLocations-1))/numberOfRatesMultiplier); double priorOdds = priorProbability/(1.0 - priorProbability); posteriorOdds = priorOdds*bayesFactor; bayesFactorCutoff = posteriorOdds/(1.0 + posteriorOdds); return bayesFactorCutoff; } private static double[] meanCol(double[][] x) { double[] returnArray = new double[x[0].length]; for (int i = 0; i < x[0].length; i++) { double m = 0.0; int len = 0; for (int j = 0; j < x.length; j++) { m += x[j][i]; len += 1; } returnArray[i] = m / (double) len; } return returnArray; } private static void fillRateIndicatorArray(String RateIndicatorLog, double[][] rateIndicators, int burnin, int firstRateIndicator, int numberOfRateIndicators){ try { BufferedReader indicatorReader = new BufferedReader(new FileReader(RateIndicatorLog)); String rateIndicatorCurrent = indicatorReader.readLine(); while (rateIndicatorCurrent.startsWith(" rateIndicatorCurrent = indicatorReader.readLine(); } // skip the headers in the rateIndicator file while (rateIndicatorCurrent.startsWith("state")) { rateIndicatorCurrent = indicatorReader.readLine(); } double rateIndicator; int linesRead = 0; //skip burnin while (linesRead < burnin){ rateIndicatorCurrent = indicatorReader.readLine(); linesRead ++; } int rowCounter = 0; while (rateIndicatorCurrent!= null && !indicatorReader.equals("")) { int columnCounter = 0; int startCounter = 1; int rateIndicatorCounter = 0; StringTokenizer tokens = new StringTokenizer(rateIndicatorCurrent); rateIndicator = Double.parseDouble(tokens.nextToken()); //skip until we encounter rateIndicators while (startCounter < firstRateIndicator) { rateIndicator = Double.parseDouble(tokens.nextToken()); startCounter ++; } // read all rateIndicators while (rateIndicatorCounter < numberOfRateIndicators) { rateIndicators[rowCounter][columnCounter] = rateIndicator; columnCounter ++; rateIndicatorCounter ++; rateIndicator = Double.parseDouble(tokens.nextToken()); } rowCounter ++; rateIndicatorCurrent = indicatorReader.readLine(); } } catch (IOException e) { System.err.println("Error reading " + RateIndicatorLog); System.exit(1); } } private static int getNumberOfEntries(String file, int firstRateIndicator, String rateIndicatorString) { int numberOfRateIndicators = 0; try { BufferedReader reader = new BufferedReader(new FileReader(file)); String current3 = reader.readLine(); //skip comment lines while (current3.startsWith(" current3 = reader.readLine(); } String rateIndicator = null; int startCounter = 1; StringTokenizer tokens = new StringTokenizer(current3); rateIndicator = tokens.nextToken(); //find first rateIndicator.. while (startCounter < firstRateIndicator) { rateIndicator = tokens.nextToken(); startCounter ++; } // and continue counting from thereon while(rateIndicator.contains(rateIndicatorString)) { rateIndicator = tokens.nextToken(); numberOfRateIndicators ++; } } catch (IOException e) { System.err.println("Error reading " + file); System.exit(1); } return numberOfRateIndicators; } private static boolean hasEntryOf(String file, String entryString) { boolean hasEntry = false; try { BufferedReader reader2 = new BufferedReader(new FileReader(file)); String current2 = reader2.readLine(); //skip comment lines while (current2.startsWith(" current2 = reader2.readLine(); } String parameter1 = null; StringTokenizer tokens1 = new StringTokenizer(current2); while(tokens1.hasMoreTokens()) { parameter1 = tokens1.nextToken(); if (parameter1.contains(entryString)) { hasEntry = true; } } } catch (IOException e) { System.err.println("Error reading " + file); System.exit(1); } return hasEntry; } private static int getFirstEntryOf(String file, String entryString) { int firstRateIndicator = 1; try { BufferedReader reader2 = new BufferedReader(new FileReader(file)); String current2 = reader2.readLine(); //skip comment lines while (current2.startsWith(" current2 = reader2.readLine(); } String parameter1 = null; StringTokenizer tokens1 = new StringTokenizer(current2); parameter1 = tokens1.nextToken(); while(!parameter1.contains(entryString)) { parameter1 = tokens1.nextToken(); firstRateIndicator ++; } } catch (IOException e) { System.err.println("Error reading " + file); System.exit(1); } return firstRateIndicator; } private static int getGenerationCount(String file) { int states = 0; try { BufferedReader reader1 = new BufferedReader(new FileReader(file)); String current1 = reader1.readLine(); while (current1 != null && !reader1.equals("")) { while (current1.startsWith(" current1 = reader1.readLine(); } current1 = reader1.readLine(); states++; } } catch (IOException e) { System.err.println("Error reading " + file); System.exit(1); } return states; } private static int[] countLinesAndTokens(String coordinatesFileString){ int lineCounter = 0; int tokenCounter = 0; int[] container = new int[2]; try{ BufferedReader reader1 = new BufferedReader(new FileReader(coordinatesFileString)); String current1 = reader1.readLine(); while (current1 != null && !reader1.equals("")) { lineCounter++; if (lineCounter == 1) { StringTokenizer tokens = new StringTokenizer(current1); while (tokens.hasMoreTokens()) { tokenCounter++; tokens.nextToken(); } } current1 = reader1.readLine(); } } catch (IOException e) { System.err.println("Error reading " + coordinatesFileString); System.exit(1); } container[0] = lineCounter; container[1] = tokenCounter; return container; } private static void readLocationsCoordinates(String coordinatesFileString, String[][] locationsAndCoordinates){ try { BufferedReader reader2 = new BufferedReader(new FileReader(coordinatesFileString)); String current2 = reader2.readLine(); int counter2 = 0; while (current2 != null && !reader2.equals("")) { StringTokenizer tokens2 = new StringTokenizer(current2); for (int i = 0; i < locationsAndCoordinates[0].length; i++) { locationsAndCoordinates[counter2][i] = tokens2.nextToken(); progressStream.print(locationsAndCoordinates[counter2][i]+"\t"); } progressStream.print("\r"); counter2 ++; current2 = reader2.readLine(); } } catch (IOException e) { e.printStackTrace(); return; } } public static void main(String[] args) throws IOException { String inputFileName = null; String outputFileName = null; String locationsFileName = null; String[][] locations = null; boolean kml = false; String lowerLinkColor = "FFFFFF"; //red: 0000FF green: 00FF00 magenta: FF00FF white: FFFFFF yellow: 00FFFF cyan: FFFF00 String upperLinkColor = "FF00FF"; String KMLoutputFile = "KMLrates.kml"; double branchWidthConstant = 2.5; double branchWidthMultiplier = 7.0; double altitudeFactor = 500; //Double width = 3.0; int burnin = -1; double meanPoissonPrior = 0.693; int offsetPoissonPrior = 0; int numberOfStates = 0; double cutoff = 3.0; boolean bayesFactor = true; // if false, we will use an indicator cut off value boolean rateSummary = false; String rateIndicatorString = "indicators"; String actualRateString = "productStatistic"; String relativeRateString = "rates"; //this is for rate (dist/time) summaries String geoSiteModelString = "geoSiteModel"; Arguments arguments = new Arguments( new Arguments.Option[]{ new Arguments.IntegerOption(BURNIN, "the number of states to be considered as 'burn-in' [default = 0]"), new Arguments.StringOption(LOCATIONSFILE,"coordinates file","a file with latitudes and longitudes for each location (required for a kml output)"), //boolean for KML new Arguments.StringOption(KML, falseTrue, false, "generate a KML file including well-supported rates [default = false]"), new Arguments.IntegerOption(LOCATIONSTATES,"the number of locations states used in the analyses [requires a coordinates file if not provided]"), new Arguments.IntegerOption(POFFSET,"the offset of the (truncated) Poisson prior [default=locations-1]"), new Arguments.RealOption(PMEAN,"the mean of the (truncated) Poisson prior [default=0.693 (log2)]"), new Arguments.RealOption(BFCUTOFF,"the Bayes Factor values above which we consider rates to be well supported [default=3.0]"), new Arguments.RealOption(ICUTOFF,"the indicator values above which we consider rates to be well supported [default uses a Bayes factor cut off of 3.0]"), new Arguments.StringOption(ISTRING, "indicator_string", "prefix string used for outputting the rate indicators in the log file [default = indicators]"), new Arguments.StringOption(RSTRING, "relativeRate_string", "prefix string used for outputting the relative rates in the log file [default = rates]"), new Arguments.StringOption(PSTRING, "rate*indicator_string", "prefix string used for outputting the product statistic for rates*indicators [default = productStatistic]"), new Arguments.StringOption(GSTRING, "geoSiteModel.mu_string", "string used for outputting geoSiteModel.mu in the log file [default = geoSiteModel]"), new Arguments.StringOption(KMLFILE,"KML output file","KML output file name [default=KMLrates.kml]"), new Arguments.StringOption(LOWCOLOR, "lower link strength color", "specifies an lower link color for the links [default=FF00FF]"), new Arguments.StringOption(UPCOLOR, "upper link strength color", "specifies an upper link color for the links [default=FFFF00]"), new Arguments.RealOption(BWC,"specifies the connection (rate) width constant [default=2.5]"), new Arguments.RealOption(BWM,"specifies the connection (rate) width multiplier [default=7.0]"), new Arguments.RealOption(ALTITUDE,"specifies the altitudefactor for the connections (rate) [default=500]"), //new Arguments.RealOption(WIDTH,"width for KML rates [default=3.0]"), }); try { arguments.parseArguments(args); } catch (Arguments.ArgumentException ae) { progressStream.println(ae); printUsage(arguments); System.exit(1); } if (arguments.hasOption(HELP)) { printUsage(arguments); System.exit(0); } // Make sense of arguments if (arguments.hasOption(BURNIN)) { burnin = arguments.getIntegerOption(BURNIN); } progressStream.println("Ignoring "+burnin+" states as burn-in"); if (arguments.hasOption(LOCATIONSTATES)) { numberOfStates = arguments.getIntegerOption(LOCATIONSTATES); } locationsFileName = arguments.getStringOption(LOCATIONSFILE); if (locationsFileName != null) { int counts[] = countLinesAndTokens(locationsFileName); //System.out.println(counts[0]+"\t"+counts[1]); //read in locations if (numberOfStates > 0) { if (numberOfStates != counts[0]) { System.err.println("number of states provided ("+numberOfStates+") does not match lines in coordinates file ("+counts[0]+") ??"); } } locations = new String[counts[0]][counts[1]]; readLocationsCoordinates(locationsFileName,locations); if (numberOfStates == 0) { numberOfStates = counts[0]; } } else { if (numberOfStates == 0) { System.err.println("no states provided, nor coordinates file ??"); } } String kmlBooleanString = arguments.getStringOption(KML); if (kmlBooleanString != null && kmlBooleanString.compareToIgnoreCase("true") == 0) { kml = true; if (locationsFileName == null) { System.err.println("you want a KML file without a coordinates file??"); } } String kmlFileName = arguments.getStringOption(KMLFILE); if (kmlFileName != null) { KMLoutputFile = kmlFileName; } if (arguments.hasOption(PMEAN)) { meanPoissonPrior = arguments.getRealOption(PMEAN); progressStream.println("Poisson prior with mean "+meanPoissonPrior); } else { progressStream.println("Poisson prior with mean "+meanPoissonPrior+" (default)"); } if (arguments.hasOption(POFFSET)) { offsetPoissonPrior = arguments.getIntegerOption(POFFSET); progressStream.println("Poisson offset = "+offsetPoissonPrior); } else { offsetPoissonPrior = numberOfStates - 1; progressStream.println("Poisson offset = "+offsetPoissonPrior+" (locations - 1)"); } if (arguments.hasOption(BFCUTOFF)) { cutoff = arguments.getRealOption(BFCUTOFF); } if (arguments.hasOption(ICUTOFF)) { cutoff = arguments.getRealOption(ICUTOFF); bayesFactor = false; } if (bayesFactor) { progressStream.println("Bayes factor cutoff = "+cutoff); } else { progressStream.println("indicator factor cutoff = "+cutoff); } if (arguments.hasOption(BWC)) { branchWidthConstant = arguments.getRealOption(BWC); } if (arguments.hasOption(BWM)) { branchWidthMultiplier = arguments.getRealOption(BWM); } if (arguments.hasOption(ALTITUDE)) { altitudeFactor = arguments.getRealOption(ALTITUDE); } String indicatorString = arguments.getStringOption(ISTRING); if (indicatorString != null) { rateIndicatorString = indicatorString; } String rateString = arguments.getStringOption(PSTRING); if (rateString != null) { actualRateString = rateString; } String relRateString = arguments.getStringOption(RSTRING); if (relRateString != null) { relativeRateString = relRateString; } String geoString = arguments.getStringOption(GSTRING); if (geoString != null) { geoSiteModelString = geoString; } String color1String = arguments.getStringOption(LOWCOLOR); if (color1String != null) { lowerLinkColor = color1String; if (locationsFileName == null) { System.err.print("color string but no coordinates file for KML output??"); } } String color2String = arguments.getStringOption(UPCOLOR); if (color2String != null) { upperLinkColor = color2String; if (locationsFileName == null) { System.err.print("color string but no coordinates file for KML output??"); } } final String[] args2 = arguments.getLeftoverArguments(); switch (args2.length) { case 0: printUsage(arguments); System.exit(1); case 2: outputFileName = args2[1]; // fall to case 1: inputFileName = args2[0]; break; default: { System.err.println("Unknown option: " + args2[2]); System.err.println(); printUsage(arguments); System.exit(1); } } RateIndicatorBF rateIndicatorBF = new RateIndicatorBF(inputFileName,burnin,rateIndicatorString,numberOfStates,locations,bayesFactor,cutoff,meanPoissonPrior,offsetPoissonPrior,actualRateString,relativeRateString,geoSiteModelString); rateIndicatorBF.outputTextFile(outputFileName); if (kml) { rateIndicatorBF.outputKML(KMLoutputFile,lowerLinkColor,upperLinkColor, branchWidthConstant, branchWidthMultiplier, altitudeFactor); } System.exit(0); } }
package dr.evomodel.treelikelihood; import dr.evolution.util.TaxonList; import dr.inference.model.Parameter; import dr.xml.*; import java.util.logging.Logger; /** * @author Andrew Rambaut * @version $Id$ */ public class APOBECErrorModel extends TipPartialsModel { public enum APOBECType { ALL("all"), BOTH("both"), H3G("h3G"), H3F("h3F"); APOBECType(String label) { this.label = label; } public String toString() { return label; } final String label; } public static final String APOBEC_ERROR_MODEL = "APOBECErrorModel"; public static final String HYPERMUTATION_RATE = "hypermutationRate"; public static final String HYPERMUTATION_INDICATORS = "hypermutationIndicators"; public APOBECErrorModel(APOBECType type, Parameter hypermutationRateParameter, Parameter hypermuationIndicatorParameter) { super(APOBEC_ERROR_MODEL, null, null); this.type = type; this.hypermutationRateParameter = hypermutationRateParameter; addParameter(this.hypermutationRateParameter); this.hypermuationIndicatorParameter = hypermuationIndicatorParameter; addParameter(this.hypermuationIndicatorParameter); } public void getTipPartials(int nodeIndex, double[] partials) { int[] states = this.states[nodeIndex]; if (hypermuationIndicatorParameter.getParameterValue(nodeIndex) > 0.0) { double rate = hypermutationRateParameter.getParameterValue(0); int k = 0; int nextState; for (int j = 0; j < patternCount; j++) { switch (states[j]) { case 0: // is an A double pMutated = 0.0; if (j < patternCount - 1) { nextState = states[j+1]; if ( (type == APOBECType.ALL) || (type == APOBECType.H3G && nextState == 2) || // is a G (type == APOBECType.H3F && nextState == 0) || // is an A (type == APOBECType.BOTH && (nextState == 2 || nextState == 0)) ) { pMutated = rate; } } partials[k] = 1.0 - pMutated; partials[k + 1] = 0.0; partials[k + 2] = pMutated; partials[k + 3] = 0.0; break; case 1: // is an C partials[k] = 0.0; partials[k + 1] = 1.0; partials[k + 2] = 0.0; partials[k + 3] = 0.0; break; case 2: // is an G partials[k] = 0.0; partials[k + 1] = 0.0; partials[k + 2] = 1.0; partials[k + 3] = 0.0; break; case 3: // is an T partials[k] = 0.0; partials[k + 1] = 0.0; partials[k + 2] = 0.0; partials[k + 3] = 1.0; break; default: // is an ambiguity partials[k] = 1.0; partials[k + 1] = 1.0; partials[k + 2] = 1.0; partials[k + 3] = 1.0; } k += stateCount; } } else { int k = 0; for (int j = 0; j < patternCount; j++) { switch (states[j]) { case 0: // is an A partials[k] = 1.0; partials[k + 1] = 0.0; partials[k + 2] = 0.0; partials[k + 3] = 0.0; break; case 1: // is an C partials[k] = 0.0; partials[k + 1] = 1.0; partials[k + 2] = 0.0; partials[k + 3] = 0.0; break; case 2: // is an G partials[k] = 0.0; partials[k + 1] = 0.0; partials[k + 2] = 1.0; partials[k + 3] = 0.0; break; case 3: // is an T partials[k] = 0.0; partials[k + 1] = 0.0; partials[k + 2] = 0.0; partials[k + 3] = 1.0; break; default: // is an ambiguity partials[k] = 1.0; partials[k + 1] = 1.0; partials[k + 2] = 1.0; partials[k + 3] = 1.0; } k += stateCount; } } } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return APOBEC_ERROR_MODEL; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { APOBECType type = APOBECType.H3G; if (xo.hasAttribute("type")) { if (xo.getStringAttribute("type").equalsIgnoreCase("all")) { type = APOBECType.ALL; } else if (xo.getStringAttribute("type").equalsIgnoreCase("both")) { type = APOBECType.BOTH; } else if (xo.getStringAttribute("type").equalsIgnoreCase("h3F")) { type = APOBECType.H3F; } else if (!xo.getStringAttribute("type").equalsIgnoreCase("h3G")) { throw new XMLParseException("unrecognized option for attribute, 'type': " + xo.getStringAttribute("type")); } } Parameter hypermutationRateParameter = null; if (xo.hasChildNamed(HYPERMUTATION_RATE)) { hypermutationRateParameter = (Parameter)xo.getElementFirstChild(HYPERMUTATION_RATE); } Parameter hypermuationIndicatorParameter = null; if (xo.hasChildNamed(HYPERMUTATION_INDICATORS)) { hypermuationIndicatorParameter = (Parameter)xo.getElementFirstChild(HYPERMUTATION_INDICATORS); } APOBECErrorModel errorModel = new APOBECErrorModel( type, hypermutationRateParameter, hypermuationIndicatorParameter); Logger.getLogger("dr.evomodel").info("Using APOBEC error model, assuming APOBEC " + type.name()); return errorModel; }
package dr.evomodelxml; import dr.evomodel.branchratemodel.DiscretizedBranchRates; import dr.evomodel.tree.TreeModel; import dr.inference.distribution.ParametricDistributionModel; import dr.inference.model.Parameter; import dr.xml.*; import java.util.logging.Logger; /** * @author Alexei Drummond */ public class DiscretizedBranchRatesParser extends AbstractXMLObjectParser { public static final String DISCRETIZED_BRANCH_RATES = "discretizedBranchRates"; public static final String DISTRIBUTION = "distribution"; public static final String RATE_CATEGORIES = "rateCategories"; public static final String SINGLE_ROOT_RATE = "singleRootRate"; public static final String OVERSAMPLING = "overSampling"; //public static final String NORMALIZED_MEAN = "normalizedMean"; public String getParserName() { return DISCRETIZED_BRANCH_RATES; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { final int overSampling = xo.getAttribute(OVERSAMPLING, 1); TreeModel tree = (TreeModel) xo.getChild(TreeModel.class); ParametricDistributionModel distributionModel = (ParametricDistributionModel) xo.getElementFirstChild(DISTRIBUTION); Parameter rateCategoryParameter = (Parameter) xo.getElementFirstChild(RATE_CATEGORIES); Logger.getLogger("dr.evomodel").info("Using discretized relaxed clock model."); Logger.getLogger("dr.evomodel").info(" over sampling = " + overSampling); Logger.getLogger("dr.evomodel").info(" parametric model = " + distributionModel.getModelName()); Logger.getLogger("dr.evomodel").info(" rate categories = " + rateCategoryParameter.getDimension()); if (xo.hasAttribute(SINGLE_ROOT_RATE)) { //singleRootRate = xo.getBooleanAttribute(SINGLE_ROOT_RATE); Logger.getLogger("dr.evomodel").warning(" WARNING: single root rate is not implemented!"); } /* if (xo.hasAttribute(NORMALIZED_MEAN)) { dbr.setNormalizedMean(xo.getDoubleAttribute(NORMALIZED_MEAN)); }*/ return new DiscretizedBranchRates(tree, rateCategoryParameter, distributionModel, overSampling); }
package org.eclipse.oomph.p2.internal.ui; import org.eclipse.oomph.internal.ui.GeneralDragAdapter; import org.eclipse.oomph.internal.ui.GeneralDropAdapter; import org.eclipse.oomph.internal.ui.GeneralDropAdapter.DroppedObjectHandler; import org.eclipse.oomph.internal.ui.OomphTransferDelegate; import org.eclipse.oomph.p2.P2Exception; import org.eclipse.oomph.p2.P2Factory; import org.eclipse.oomph.p2.P2Package; import org.eclipse.oomph.p2.Repository; import org.eclipse.oomph.p2.Requirement; import org.eclipse.oomph.p2.VersionSegment; import org.eclipse.oomph.p2.core.P2Util; import org.eclipse.oomph.p2.core.RepositoryProvider; import org.eclipse.oomph.p2.impl.RequirementImpl; import org.eclipse.oomph.p2.internal.ui.RepositoryManager.RepositoryManagerListener; import org.eclipse.oomph.p2.provider.RequirementItemProvider; import org.eclipse.oomph.ui.SearchField; import org.eclipse.oomph.ui.SearchField.FilterHandler; import org.eclipse.oomph.ui.UIUtil; import org.eclipse.oomph.util.CollectionUtil; import org.eclipse.oomph.util.ObjectUtil; import org.eclipse.oomph.util.StringUtil; import org.eclipse.emf.ecore.EObject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.URIUtil; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.variables.IStringVariableManager; import org.eclipse.core.variables.VariablesPlugin; import org.eclipse.equinox.p2.core.ProvisionException; import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.metadata.IProvidedCapability; import org.eclipse.equinox.p2.metadata.IRequirement; import org.eclipse.equinox.p2.metadata.Version; import org.eclipse.equinox.p2.metadata.VersionRange; import org.eclipse.equinox.p2.metadata.expression.IMatchExpression; import org.eclipse.equinox.p2.query.IQueryResult; import org.eclipse.equinox.p2.query.QueryUtil; import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.forms.FormColors; import org.eclipse.ui.forms.widgets.Form; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.part.ViewPart; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Eike Stepper */ public class RepositoryExplorer extends ViewPart implements FilterHandler { public static final String ID = "org.eclipse.oomph.p2.ui.RepositoryExplorer"; //$NON-NLS-1$ private static final IDialogSettings SETTINGS = P2UIPlugin.INSTANCE.getDialogSettings(RepositoryExplorer.class.getSimpleName()); private static final int DND_OPERATIONS = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; private static final Transfer[] DND_TRANSFERS = OomphTransferDelegate.asTransfers(org.eclipse.oomph.internal.ui.OomphTransferDelegate.DELEGATES) .toArray(new Transfer[OomphTransferDelegate.asTransfers(org.eclipse.oomph.internal.ui.OomphTransferDelegate.DELEGATES).size()]); private static final String DEFAULT_CAPABILITY_NAMESPACE = IInstallableUnit.NAMESPACE_IU_ID; private static final String CURRENT_NAMESPACE_KEY = "currentNamespace"; private static final String EXPERT_MODE_KEY = "expertMode"; private static final String CATEGORIZE_ITEMS_KEY = "categorizeItems"; private static final String VERSION_SEGMENT_KEY = "versionSegment"; private static final String COMPATIBLE_VERSION_KEY = "compatibleVersion"; private static final String SOURCE_SUFFIX = ".source"; private static final String SOURCE_FEATURE_SUFFIX = SOURCE_SUFFIX + Requirement.FEATURE_SUFFIX; private static final Object[] NO_ELEMENTS = new Object[0]; private final LoadJob loadJob = new LoadJob(); private final AnalyzeJob analyzeJob = new AnalyzeJob(); private final Mode categoriesMode = new CategoriesMode(); private final Mode featuresMode = new FeaturesMode(); private final Mode capabilitiesMode = new CapabilitiesMode(); private final RepositoryFocusListener repositoryFocusListener = new RepositoryFocusListener(); private final RepositoryHistoryListener repositoryHistoryListener = new RepositoryHistoryListener(); private final VersionProvider versionProvider = new VersionProvider(); private final CollapseAllAction collapseAllAction = new CollapseAllAction(); private Composite container; private ComboViewer repositoryViewer; private CCombo repositoryCombo; private RepositoryProvider.Metadata repositoryProvider; private Composite selectorComposite; private Composite itemsComposite; private StructuredViewer itemsViewer; private CategoryItem itemsViewerInput; private TableViewer versionsViewer; private String currentNamespace; private boolean expertMode; private boolean categorizeItems; private boolean compatibleVersion; private Mode mode; private IQueryResult<IInstallableUnit> installableUnits; private String filter; private FormToolkit formToolkit; public RepositoryExplorer() { currentNamespace = SETTINGS.get(CURRENT_NAMESPACE_KEY); if (currentNamespace == null) { currentNamespace = DEFAULT_CAPABILITY_NAMESPACE; } expertMode = SETTINGS.getBoolean(EXPERT_MODE_KEY); String value = SETTINGS.get(CATEGORIZE_ITEMS_KEY); if (value == null || value.length() == 0) { categorizeItems = true; } else { categorizeItems = "true".equals(value); } compatibleVersion = SETTINGS.getBoolean(COMPATIBLE_VERSION_KEY); } @Override public void dispose() { if (formToolkit != null) { formToolkit.dispose(); } disposeRepositoryProvider(); super.dispose(); } private void disposeRepositoryProvider() { if (repositoryProvider != null) { repositoryProvider.dispose(); repositoryProvider = null; } } @Override public void setFocus() { if (RepositoryManager.INSTANCE.getActiveRepository() != null) { repositoryCombo.setFocus(); } } private void updateMode() { Mode mode = expertMode ? capabilitiesMode : categorizeItems ? categoriesMode : featuresMode; if (this.mode != mode) { this.mode = mode; GridLayout selectorLayout = new GridLayout(); selectorLayout.marginWidth = 0; selectorLayout.marginHeight = 0; selectorComposite.setLayout(selectorLayout); mode.fillSelector(selectorComposite); selectorComposite.layout(); selectorComposite.getParent().layout(); mode.fillItems(itemsComposite); itemsComposite.layout(); itemsViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection)itemsViewer.getSelection(); if (selection.size() == 1) { versionsViewer.setInput(selection.getFirstElement()); } else { versionsViewer.setInput(null); } } }); analyzeJob.reschedule(); collapseAllAction.updateEnablement(); } } private void setItems(Item... items) { if (!container.isDisposed()) { versionsViewer.setInput(null); itemsViewerInput = new CategoryItem(); itemsViewerInput.setChildren(items); itemsViewer.setInput(itemsViewerInput); if (itemsViewer instanceof TreeViewer && filter != null) { TreeViewer treeViewer = (TreeViewer)itemsViewer; treeViewer.expandAll(); } } } private boolean isFiltered(String string) { return filter == null || string == null || string.toLowerCase().contains(filter); } public void handleFilter(String filter) { if (filter == null || filter.length() == 0) { this.filter = null; } else { this.filter = filter.toLowerCase(); } analyzeJob.reschedule(); } @Override public void createPartControl(Composite parent) { final Display display = parent.getDisplay(); formToolkit = new FormToolkit(display); FormColors colors = formToolkit.getColors(); colors.createColor("initial_repository", FormColors.blend(colors.getForeground().getRGB(), colors.getBackground().getRGB(), 75)); Form form = formToolkit.createForm(parent); container = form.getBody(); container.setLayout(new GridLayout(1, false)); createRepositoriesArea(container); createItemsArea(container); createVersionsArea(container); updateMode(); String activeRepository = RepositoryManager.INSTANCE.getActiveRepository(); if (activeRepository == null) { // Force hint to be shown. repositoryFocusListener.focusLost(null); } else { repositoryCombo.setText(activeRepository); triggerLoad(activeRepository); } hookActions(); } private static CCombo createCombo(Composite parent, int style, boolean grabExcessHorizontalSpace) { CCombo combo = new CCombo(parent, style); GridData layoutData = new GridData(SWT.FILL, SWT.FILL, grabExcessHorizontalSpace, false); int increaseHeight = 0; String ws = Platform.getWS(); if (Platform.WS_COCOA.equals(ws)) { increaseHeight = 7; } else if (Platform.WS_GTK.equals(ws)) { increaseHeight = 9; } if (increaseHeight != 0) { FontData[] fontData = combo.getFont().getFontData(); layoutData.heightHint = fontData[0].getHeight() + increaseHeight; } combo.setLayoutData(layoutData); return combo; } private void createRepositoriesArea(Composite container) { repositoryCombo = createCombo(container, SWT.BORDER, true); repositoryCombo.setToolTipText("Repository location (type a URL, drop a repository or pick from the drop down history)"); repositoryCombo.addFocusListener(repositoryFocusListener); repositoryCombo.addKeyListener(repositoryHistoryListener); repositoryViewer = new ComboViewer(repositoryCombo); repositoryViewer.setContentProvider(new RepositoryContentProvider()); repositoryViewer.setLabelProvider(new LabelProvider()); repositoryViewer.setInput(RepositoryManager.INSTANCE); repositoryViewer.addSelectionChangedListener(repositoryHistoryListener); repositoryViewer.addDropSupport(DND_OPERATIONS, DND_TRANSFERS, new GeneralDropAdapter(repositoryViewer, P2Factory.eINSTANCE.createRepositoryList(), P2Package.Literals.REPOSITORY_LIST__REPOSITORIES, new DroppedObjectHandler() { public void handleDroppedObject(Object object) throws Exception { if (object instanceof Repository) { Repository repository = (Repository)object; String url = repository.getURL(); if (!StringUtil.isEmpty(url)) { activateAndLoadRepository(url); } } } })); } private void createItemsArea(Composite parent) { GridLayout containerLayout = new GridLayout(2, false); containerLayout.marginWidth = 0; containerLayout.marginHeight = 0; Composite container = formToolkit.createComposite(parent, SWT.NONE); container.setLayout(containerLayout); container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); SearchField searchField = new SearchField(container, this) { @Override protected void finishFilter() { itemsViewer.getControl().setFocus(); selectFirstLeaf(itemsViewerInput); } private void selectFirstLeaf(CategoryItem category) { Item[] children = category.getChildren(); if (children != null && children.length != 0) { Item firstChild = children[0]; if (firstChild instanceof CategoryItem) { CategoryItem firstCategory = (CategoryItem)firstChild; selectFirstLeaf(firstCategory); } else { itemsViewer.setSelection(new StructuredSelection(firstChild)); } } } }; searchField.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); selectorComposite = formToolkit.createComposite(container, SWT.NONE); selectorComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); itemsComposite = formToolkit.createComposite(container, SWT.NONE); itemsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); itemsComposite.setLayout(new FillLayout()); } private void createVersionsArea(Composite container) { Composite versionsComposite = formToolkit.createComposite(container, SWT.NONE); GridLayout gl_versionsComposite = new GridLayout(2, false); gl_versionsComposite.marginWidth = 0; gl_versionsComposite.marginHeight = 0; versionsComposite.setLayout(gl_versionsComposite); versionsComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); versionsViewer = new TableViewer(versionsComposite, SWT.BORDER); versionsViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); versionsViewer.setContentProvider(versionProvider); versionsViewer.setLabelProvider(versionProvider); addDragSupport(versionsViewer); formToolkit.adapt(versionsViewer.getControl(), false, false); Composite versionsGroup = formToolkit.createComposite(versionsComposite, SWT.NONE); versionsGroup.setLayout(new GridLayout(1, false)); versionsGroup.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false)); final Button compatibleButton = new Button(versionsGroup, SWT.CHECK); compatibleButton.setText("Compatible"); compatibleButton.setToolTipText("Show compatible versions"); compatibleButton.setSelection(compatibleVersion); final Button majorButton = addVersionSegmentButton(versionsGroup, "Major", "Show major versions", VersionSegment.MAJOR); final Button minorButton = addVersionSegmentButton(versionsGroup, "Minor", "Show minor versions", VersionSegment.MINOR); addVersionSegmentButton(versionsGroup, "Micro", "Show micro versions", VersionSegment.MICRO); addVersionSegmentButton(versionsGroup, "Qualifier", "Show qualified versions", VersionSegment.QUALIFIER); majorButton.setEnabled(!compatibleVersion); compatibleButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { boolean compatible = compatibleButton.getSelection(); if (compatibleVersion != compatible) { compatibleVersion = compatible; SETTINGS.put(COMPATIBLE_VERSION_KEY, compatibleVersion); majorButton.setEnabled(!compatible); if (compatible && versionProvider.getVersionSegment() == VersionSegment.MAJOR) { majorButton.setSelection(false); minorButton.setSelection(true); versionProvider.setVersionSegment(VersionSegment.MINOR); } } } }); } private Button addVersionSegmentButton(Composite parent, String text, String toolTip, final VersionSegment versionSegment) { Button button = new Button(parent, SWT.RADIO); button.setText(text); button.setToolTipText(toolTip); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { versionProvider.setVersionSegment(versionSegment); } }); if (versionSegment == versionProvider.getVersionSegment()) { button.setSelection(true); } return button; } private void hookActions() { IActionBars actionBars = getViewSite().getActionBars(); IToolBarManager toolbarManager = actionBars.getToolBarManager(); toolbarManager.add(new Separator("additions")); toolbarManager.add(collapseAllAction); toolbarManager.add(new Action("Refresh", P2UIPlugin.INSTANCE.getImageDescriptor("refresh")) { { setToolTipText("Reload the active repository and refresh the tree"); } @Override public void run() { String activeRepository = RepositoryManager.INSTANCE.getActiveRepository(); if (activeRepository != null) { disposeRepositoryProvider(); triggerLoad(activeRepository); } } }); toolbarManager.add(new Separator("modes")); toolbarManager.add(new Action("Expert Mode", IAction.AS_CHECK_BOX) { { setImageDescriptor(P2UIPlugin.INSTANCE.getImageDescriptor("obj16/capability")); setChecked(expertMode); } @Override public void run() { expertMode = isChecked(); SETTINGS.put(EXPERT_MODE_KEY, expertMode); updateMode(); } }); toolbarManager.add(new Separator("end")); } private void activateAndLoadRepository(String repository) { if (RepositoryManager.INSTANCE.setActiveRepository(repository)) { triggerLoad(repository); } } private void triggerLoad(String repository) { try { IStringVariableManager manager = VariablesPlugin.getDefault().getStringVariableManager(); repository = manager.performStringSubstitution(repository); } catch (Exception ex) { //$FALL-THROUGH$ } URI location = null; try { location = new URI(repository); } catch (URISyntaxException ex) { File folder = new File(repository); if (folder.isDirectory()) { location = folder.toURI(); } } if (location != null) { loadJob.reschedule(location); } } private void addDragSupport(StructuredViewer viewer) { viewer.addDragSupport(DND_OPERATIONS, DND_TRANSFERS, new GeneralDragAdapter(viewer, new GeneralDragAdapter.DraggedObjectsFactory() { public List<EObject> createDraggedObjects(ISelection selection) throws Exception { List<EObject> result = new ArrayList<EObject>(); IStructuredSelection ssel = (IStructuredSelection)selection; for (Iterator<?> it = ssel.iterator(); it.hasNext();) { Object element = it.next(); VersionRange versionRange = VersionRange.emptyRange; String filter = null; if (element instanceof VersionProvider.ItemVersion) { VersionProvider.ItemVersion itemVersion = (VersionProvider.ItemVersion)element; Version version = itemVersion.getVersion(); VersionSegment versionSegment = versionProvider.getVersionSegment(); versionRange = P2Factory.eINSTANCE.createVersionRange(version, versionSegment, compatibleVersion); filter = RequirementImpl.formatMatchExpression(itemVersion.getFilter()); element = ((IStructuredSelection)itemsViewer.getSelection()).getFirstElement(); } if (element instanceof Item) { Item item = (Item)element; String namespace = item.getNamespace(); if (namespace != null) { if (filter == null && item instanceof VersionedItem) { VersionedItem versionedItem = (VersionedItem)item; for (IMatchExpression<IInstallableUnit> matchExpression : versionedItem.getVersions().values()) { String string = RequirementImpl.formatMatchExpression(matchExpression); if (filter == null || filter.equals(string)) { filter = string; } else { filter = null; break; } } } Requirement requirement = P2Factory.eINSTANCE.createRequirement(); requirement.setNamespace(namespace); requirement.setName(item.getName()); requirement.setVersionRange(versionRange); requirement.setFilter(filter); result.add(requirement); } } } return result; } })); } private static String[] sortStrings(Collection<String> c) { String[] array = c.toArray(new String[c.size()]); Arrays.sort(array); return array; } private static String[] getMinimalFlavors(final Set<String> flavors) { String[] flavorIDs = sortStrings(flavors); int start = 0; while (start < flavorIDs.length) { boolean changed = false; for (int i = start + 1; i < flavorIDs.length; i++) { String flavorID = flavorIDs[i]; if (flavorID.startsWith(flavorIDs[start])) { flavors.remove(flavorID); changed = true; } } if (changed) { flavorIDs = sortStrings(flavors); } ++start; } return flavorIDs; } private static boolean isCategory(IInstallableUnit iu) { return "true".equalsIgnoreCase(iu.getProperty(QueryUtil.PROP_TYPE_CATEGORY)); } private static boolean isFeature(IInstallableUnit iu) { return iu.getId().endsWith(Requirement.FEATURE_SUFFIX); } public static boolean explore(String repository) { IWorkbenchWindow window = UIUtil.WORKBENCH.getActiveWorkbenchWindow(); if (window != null) { IWorkbenchPage page = window.getActivePage(); if (page != null) { IViewPart view = page.findView(ID); if (view == null) { try { view = page.showView(ID); } catch (PartInitException ex) { P2UIPlugin.INSTANCE.log(ex); } } if (view instanceof RepositoryExplorer) { RepositoryExplorer explorer = (RepositoryExplorer)view; explorer.activateAndLoadRepository(repository); return true; } } } return false; } /** * @author Eike Stepper */ private final class CollapseAllAction extends Action { public CollapseAllAction() { super("Collapse All", P2UIPlugin.INSTANCE.getImageDescriptor("collapse-all")); setToolTipText("Collapse all tree items"); updateEnablement(); } public void updateEnablement() { setEnabled(itemsViewer instanceof TreeViewer); } @Override public void run() { if (itemsViewer instanceof TreeViewer) { TreeViewer treeViewer = (TreeViewer)itemsViewer; treeViewer.collapseAll(); } } } /** * @author Eike Stepper */ private abstract class SafeJob extends Job { public SafeJob(String name) { super(name); } @Override protected final IStatus run(IProgressMonitor monitor) { try { doSafe(monitor); return Status.OK_STATUS; } catch (OperationCanceledException ex) { return Status.CANCEL_STATUS; } catch (Exception ex) { if (ex instanceof P2Exception) { Throwable cause = ex.getCause(); if (cause instanceof CoreException) { ex = (CoreException)cause; } } final IStatus status = P2UIPlugin.INSTANCE.getStatus(ex); UIUtil.asyncExec(new Runnable() { public void run() { setItems(new ErrorItem(status)); } }); return Status.OK_STATUS; } catch (Throwable t) { return P2UIPlugin.INSTANCE.getStatus(t); } } protected abstract void doSafe(IProgressMonitor monitor) throws Throwable; } /** * @author Eike Stepper */ private final class LoadJob extends SafeJob { private URI location; public LoadJob() { super("Loading repository"); } public void reschedule(URI location) { this.location = location; setItems(new LoadingItem(location)); cancel(); schedule(); } @Override @SuppressWarnings("restriction") protected void doSafe(IProgressMonitor monitor) throws Throwable { analyzeJob.cancel(); installableUnits = null; IMetadataRepositoryManager repositoryManager = P2Util.getAgentManager().getCurrentAgent().getMetadataRepositoryManager(); if (repositoryProvider == null || !repositoryProvider.getLocation().equals(location)) { disposeRepositoryProvider(); repositoryProvider = new RepositoryProvider.Metadata(repositoryManager, location); } SubMonitor progress = SubMonitor.convert(monitor, 101); IMetadataRepository repository = repositoryProvider.getRepository(progress.newChild(100)); if (repository instanceof org.eclipse.equinox.internal.p2.metadata.repository.CompositeMetadataRepository) { org.eclipse.equinox.internal.p2.metadata.repository.CompositeMetadataRepository compositeRepository = (org.eclipse.equinox.internal.p2.metadata.repository.CompositeMetadataRepository)repository; org.eclipse.equinox.internal.p2.persistence.CompositeRepositoryState state = compositeRepository.toState(); URI[] children = state.getChildren(); final List<Item> errors = new ArrayList<Item>(); Set<String> messages = new HashSet<String>(); for (URI child : children) { try { URI absolute = URIUtil.makeAbsolute(child, location); if (repositoryManager.loadRepository(absolute, null) == null) { throw new ProvisionException("No repository found at " + absolute + "."); } } catch (Exception ex) { IStatus status = P2UIPlugin.INSTANCE.getStatus(ex); if (messages.add(status.getMessage())) { errors.add(new ErrorItem(status)); } } } if (!errors.isEmpty()) { UIUtil.asyncExec(new Runnable() { public void run() { setItems(errors.toArray(new Item[errors.size()])); } }); return; } } installableUnits = repository.query(QueryUtil.createIUAnyQuery(), progress.newChild(1)); analyzeJob.reschedule(); } } /** * @author Eike Stepper */ private final class AnalyzeJob extends SafeJob { public AnalyzeJob() { super("Analyzing repository"); } public void reschedule() { cancel(); if (installableUnits != null) { schedule(); } } @Override protected void doSafe(IProgressMonitor monitor) throws Throwable { mode.analyzeInstallableUnits(monitor); } } /** * @author Eike Stepper */ private abstract class Mode { protected final void disposeChildren(Composite parent) { for (Control child : parent.getChildren()) { child.dispose(); } } protected final void fillCategorySelector(Composite parent) { Control[] children = parent.getChildren(); if (children.length == 1 && children[0] instanceof Button) { ((Button)children[0]).setSelection(categorizeItems); return; } disposeChildren(parent); final Button button = new Button(parent, SWT.CHECK); button.setText("Group items by category"); button.setToolTipText("Whether to show items in categories or in a complete list"); button.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); button.setSelection(categorizeItems); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { categorizeItems = button.getSelection(); SETTINGS.put(CATEGORIZE_ITEMS_KEY, categorizeItems); updateMode(); } }); } public abstract void fillSelector(Composite parent); public abstract void fillItems(Composite parent); public abstract void analyzeInstallableUnits(IProgressMonitor monitor); } /** * @author Eike Stepper */ private final class CategoriesMode extends Mode { @Override public void fillSelector(Composite parent) { fillCategorySelector(parent); } @Override public void fillItems(Composite parent) { disposeChildren(parent); TreeViewer categoriesViewer = new TreeViewer(parent, SWT.BORDER | SWT.MULTI); categoriesViewer.setUseHashlookup(true); categoriesViewer.setContentProvider(new ItemContentProvider()); categoriesViewer.setLabelProvider(new ItemLabelProvider()); addDragSupport(categoriesViewer); itemsViewer = categoriesViewer; } @SuppressWarnings("restriction") @Override public void analyzeInstallableUnits(IProgressMonitor monitor) { // IU.id -> value Map<String, String> names = new HashMap<String, String>(); Map<String, Set<IInstallableUnit>> ius = new HashMap<String, Set<IInstallableUnit>>(); Map<String, Set<IRequirement>> categories = new HashMap<String, Set<IRequirement>>(); for (IInstallableUnit iu : installableUnits) { P2UIPlugin.checkCancelation(monitor); String id = iu.getId(); names.put(id, P2Util.getName(iu)); CollectionUtil.add(ius, id, iu); if (isCategory(iu)) { CollectionUtil.addAll(categories, id, iu.getRequirements()); } } Set<String> rootIDs = new HashSet<String>(); for (String categoryID : categories.keySet()) { P2UIPlugin.checkCancelation(monitor); rootIDs.add(categoryID); } for (Set<IRequirement> requirements : categories.values()) { for (IRequirement requirement : requirements) { P2UIPlugin.checkCancelation(monitor); if (requirement instanceof org.eclipse.equinox.internal.p2.metadata.IRequiredCapability) { org.eclipse.equinox.internal.p2.metadata.IRequiredCapability requiredCapability = (org.eclipse.equinox.internal.p2.metadata.IRequiredCapability)requirement; if (IInstallableUnit.NAMESPACE_IU_ID.equals(requiredCapability.getNamespace())) { rootIDs.remove(requiredCapability.getName()); } } } } Set<CategoryItem> rootCategories = new HashSet<CategoryItem>(); for (String rootID : rootIDs) { P2UIPlugin.checkCancelation(monitor); CategoryItem rootCategory = analyzeCategory(names, ius, categories, rootID, monitor); if (rootCategory != null) { rootCategories.add(rootCategory); } } final CategoryItem[] roots = rootCategories.toArray(new CategoryItem[rootCategories.size()]); UIUtil.asyncExec(new Runnable() { public void run() { setItems(roots); } }); } @SuppressWarnings("restriction") private CategoryItem analyzeCategory(Map<String, String> names, Map<String, Set<IInstallableUnit>> ius, Map<String, Set<IRequirement>> categories, String categoryID, IProgressMonitor monitor) { Map<String, Item> children = new HashMap<String, Item>(); Map<Item, Map<Version, IMatchExpression<IInstallableUnit>>> versions = new HashMap<Item, Map<Version, IMatchExpression<IInstallableUnit>>>(); for (IRequirement requirement : categories.get(categoryID)) { P2UIPlugin.checkCancelation(monitor); if (requirement instanceof org.eclipse.equinox.internal.p2.metadata.IRequiredCapability) { org.eclipse.equinox.internal.p2.metadata.IRequiredCapability requiredCapability = (org.eclipse.equinox.internal.p2.metadata.IRequiredCapability)requirement; if (IInstallableUnit.NAMESPACE_IU_ID.equals(requiredCapability.getNamespace())) { String requiredID = requiredCapability.getName(); if (categories.containsKey(requiredID)) { CategoryItem child = analyzeCategory(names, ius, categories, requiredID, monitor); if (child != null) { children.put(requiredID, child); } } else { VersionRange range = requiredCapability.getRange(); Item child = children.get(requiredID); Set<IInstallableUnit> set = ius.get(requiredID); if (set != null) { for (IInstallableUnit iu : set) { P2UIPlugin.checkCancelation(monitor); Version version = iu.getVersion(); if (range.isIncluded(version)) { if (child == null) { String name = names.get(requiredID); if (isFiltered(name)) { if (isFeature(iu)) { if (requiredID.endsWith(SOURCE_FEATURE_SUFFIX)) { String mainID = requiredID.substring(0, requiredID.length() - SOURCE_FEATURE_SUFFIX.length()) + Requirement.FEATURE_SUFFIX; String mainName = names.get(mainID); if (ObjectUtil.equals(name, mainName)) { name += " (Source)"; } } child = new FeatureItem(requiredID); } else { if (requiredID.endsWith(SOURCE_SUFFIX)) { String mainID = requiredID.substring(0, requiredID.length() - SOURCE_SUFFIX.length()); String mainName = names.get(mainID); if (ObjectUtil.equals(name, mainName)) { name += " (Source)"; } } child = new PluginItem(requiredID); } child.setLabel(name); children.put(requiredID, child); } } if (child != null) { IMatchExpression<IInstallableUnit> matchExpression = iu.getFilter(); Map<Version, IMatchExpression<IInstallableUnit>> map = versions.get(child); if (map == null) { map = new HashMap<Version, IMatchExpression<IInstallableUnit>>(); versions.put(child, map); } map.put(version, matchExpression); } } } } } } } } for (Map.Entry<Item, Map<Version, IMatchExpression<IInstallableUnit>>> entry : versions.entrySet()) { P2UIPlugin.checkCancelation(monitor); Item child = entry.getKey(); if (child instanceof VersionedItem) { VersionedItem versionedItem = (VersionedItem)child; versionedItem.setVersions(entry.getValue()); } } if (children.isEmpty()) { return null; } CategoryItem categoryItem = new CategoryItem(); categoryItem.setLabel(names.get(categoryID)); categoryItem.setChildren(children.values().toArray(new Item[children.size()])); return categoryItem; } } /** * @author Eike Stepper */ private final class FeaturesMode extends Mode { @Override public void fillSelector(Composite parent) { fillCategorySelector(parent); } @Override public void fillItems(Composite parent) { disposeChildren(parent); TableViewer featuresViewer = new TableViewer(parent, SWT.BORDER | SWT.MULTI | SWT.VIRTUAL); featuresViewer.setUseHashlookup(true); featuresViewer.setContentProvider(new ItemContentProvider()); featuresViewer.setLabelProvider(new ItemLabelProvider()); addDragSupport(featuresViewer); itemsViewer = featuresViewer; } @Override public void analyzeInstallableUnits(IProgressMonitor monitor) { Map<String, String> names = new HashMap<String, String>(); Map<String, Map<Version, IMatchExpression<IInstallableUnit>>> versions = new HashMap<String, Map<Version, IMatchExpression<IInstallableUnit>>>(); for (IInstallableUnit iu : installableUnits) { P2UIPlugin.checkCancelation(monitor); String id = iu.getId(); if (id.endsWith(Requirement.FEATURE_SUFFIX) && !id.endsWith(SOURCE_FEATURE_SUFFIX)) { String name = P2Util.getName(iu); if (isFiltered(name)) { names.put(id, name); Version version = iu.getVersion(); IMatchExpression<IInstallableUnit> filter = iu.getFilter(); Map<Version, IMatchExpression<IInstallableUnit>> map = versions.get(id); if (map == null) { map = new HashMap<Version, IMatchExpression<IInstallableUnit>>(); versions.put(id, map); } map.put(version, filter); } } } final FeatureItem[] featureItems = new FeatureItem[versions.size()]; Iterator<String> iterator = versions.keySet().iterator(); for (int i = 0; i < featureItems.length; i++) { P2UIPlugin.checkCancelation(monitor); String id = iterator.next(); Map<Version, IMatchExpression<IInstallableUnit>> map = versions.get(id); FeatureItem featureItem = new FeatureItem(id); featureItem.setVersions(map); featureItem.setLabel(names.get(id)); featureItems[i] = featureItem; } UIUtil.asyncExec(new Runnable() { public void run() { setItems(featureItems); } }); } } /** * @author Eike Stepper */ private final class CapabilitiesMode extends Mode { private ComboViewer namespaceViewer; @Override public void fillSelector(Composite parent) { disposeChildren(parent); CCombo namespaceCombo = // new CCombo(parent, SWT.BORDER | SWT.READ_ONLY | SWT.FLAT); createCombo(parent, SWT.BORDER | SWT.READ_ONLY | SWT.FLAT, false); namespaceCombo.setToolTipText("Select the namespace of the capabilities to show"); namespaceViewer = new ComboViewer(namespaceCombo); namespaceViewer.setSorter(new ViewerSorter()); namespaceViewer.setContentProvider(new ArrayContentProvider()); namespaceViewer.setLabelProvider(new LabelProvider()); namespaceViewer.setInput(new String[] { currentNamespace }); namespaceViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection)namespaceViewer.getSelection(); String newNamespace = (String)selection.getFirstElement(); if (!ObjectUtil.equals(newNamespace, currentNamespace)) { SETTINGS.put(CURRENT_NAMESPACE_KEY, newNamespace); currentNamespace = newNamespace; analyzeJob.reschedule(); } } }); namespaceViewer.setSelection(new StructuredSelection(currentNamespace)); } @Override public void fillItems(Composite parent) { disposeChildren(parent); TableViewer capabilitiesViewer = new TableViewer(parent, SWT.BORDER | SWT.MULTI | SWT.VIRTUAL); capabilitiesViewer.setUseHashlookup(true); capabilitiesViewer.setContentProvider(new ItemContentProvider()); capabilitiesViewer.setLabelProvider(new ItemLabelProvider()); addDragSupport(capabilitiesViewer); itemsViewer = capabilitiesViewer; } @Override public void analyzeInstallableUnits(IProgressMonitor monitor) { final Set<String> flavors = new HashSet<String>(); final Set<String> namespaces = new HashSet<String>(); Map<String, Set<Version>> versions = new HashMap<String, Set<Version>>(); for (IInstallableUnit iu : installableUnits) { for (IProvidedCapability capability : iu.getProvidedCapabilities()) { P2UIPlugin.checkCancelation(monitor); String namespace = capability.getNamespace(); String name = capability.getName(); if ("org.eclipse.equinox.p2.flavor".equals(namespace)) { flavors.add(name); } else if (!"A.PDE.Target.Platform".equalsIgnoreCase(namespace)) { namespaces.add(namespace); } if (ObjectUtil.equals(namespace, currentNamespace) && isFiltered(name)) { Version version = capability.getVersion(); if (version != null && !Version.emptyVersion.equals(version)) { CollectionUtil.add(versions, name, version); } } } } String[] flavorIDs = getMinimalFlavors(flavors); for (Iterator<String> it = namespaces.iterator(); it.hasNext();) { String namespace = it.next(); for (int i = 0; i < flavorIDs.length; i++) { String flavor = flavorIDs[i]; if (namespace.startsWith(flavor)) { it.remove(); break; } } } if (!namespaces.contains(currentNamespace)) { String newCurrentNamespace = null; if (namespaces.contains(DEFAULT_CAPABILITY_NAMESPACE)) { newCurrentNamespace = DEFAULT_CAPABILITY_NAMESPACE; } else if (!namespaces.isEmpty()) { newCurrentNamespace = namespaces.iterator().next(); } if (newCurrentNamespace != null) { currentNamespace = newCurrentNamespace; analyzeInstallableUnits(monitor); return; } } final CapabilityItem[] capabilityItems = new CapabilityItem[versions.size()]; Iterator<String> iterator = versions.keySet().iterator(); for (int i = 0; i < capabilityItems.length; i++) { String id = iterator.next(); CapabilityItem capabilityItem = new CapabilityItem(); capabilityItem.setVersions(versions.get(id)); capabilityItem.setNamespace(currentNamespace); capabilityItem.setLabel(id); capabilityItems[i] = capabilityItem; } UIUtil.asyncExec(new Runnable() { public void run() { if (!container.isDisposed()) { setItems(capabilityItems); namespaceViewer.setInput(namespaces); namespaceViewer.getCCombo().pack(); selectorComposite.getParent().layout(); UIUtil.asyncExec(new Runnable() { public void run() { if (!container.isDisposed() && currentNamespace != null) { namespaceViewer.setSelection(new StructuredSelection(currentNamespace)); } } }); } } }); } } /** * @author Eike Stepper */ private final class RepositoryFocusListener implements FocusListener { private Color originalForeground; public void focusGained(FocusEvent e) { if (originalForeground != null) { repositoryCombo.setText(""); repositoryCombo.setForeground(originalForeground); originalForeground = null; } } public void focusLost(FocusEvent e) { String activeRepository = RepositoryManager.INSTANCE.getActiveRepository(); if (activeRepository == null) { originalForeground = repositoryCombo.getForeground(); repositoryCombo.setText("type repository url, drag and drop, or pick from list"); Color color = formToolkit.getColors().getColor("initial_repository"); repositoryCombo.setForeground(color); } else { if (!activeRepository.equals(repositoryCombo.getText())) { repositoryCombo.setText(activeRepository); } } } } /** * @author Eike Stepper */ private final class RepositoryHistoryListener extends KeyAdapter implements ISelectionChangedListener { private boolean listVisible; private String listRepository; @Override public void keyReleased(KeyEvent e) { boolean currentListVisible = repositoryCombo.getListVisible(); if (currentListVisible) { String repository = getSelectedRepository(); if (!StringUtil.isEmpty(repository)) { listRepository = repository; } } if (currentListVisible && (e.keyCode == SWT.DEL || e.keyCode == SWT.BS)) { RepositoryManager.INSTANCE.removeRepository(listRepository); } else if (e.keyCode == SWT.CR && listVisible && !currentListVisible) { selectRepository(); } listVisible = currentListVisible; } public void selectionChanged(SelectionChangedEvent event) { listVisible = repositoryCombo.getListVisible(); if (!listVisible) { selectRepository(); } } private void selectRepository() { String newRepository = getSelectedRepository(); activateAndLoadRepository(newRepository); } private String getSelectedRepository() { IStructuredSelection selection = (IStructuredSelection)repositoryViewer.getSelection(); return selection.isEmpty() ? repositoryCombo.getText() : (String)selection.getFirstElement(); } } /** * @author Eike Stepper */ private final class RepositoryContentProvider implements IStructuredContentProvider, RepositoryManagerListener { public RepositoryContentProvider() { RepositoryManager.INSTANCE.addListener(this); } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } public void dispose() { RepositoryManager.INSTANCE.removeListener(this); } public Object[] getElements(Object element) { return RepositoryManager.INSTANCE.getRepositories(); } public void repositoriesChanged(RepositoryManager repositoryManager) { UIUtil.asyncExec(new Runnable() { public void run() { if (!container.isDisposed()) { repositoryViewer.refresh(); UIUtil.asyncExec(new Runnable() { public void run() { if (!container.isDisposed()) { String activeRepository = RepositoryManager.INSTANCE.getActiveRepository(); if (activeRepository == null) { repositoryViewer.setSelection(StructuredSelection.EMPTY); repositoryCombo.setText(""); } else { ISelection selection = new StructuredSelection(activeRepository); repositoryViewer.setSelection(selection); repositoryCombo.setText(activeRepository); repositoryCombo.setSelection(new Point(0, activeRepository.length())); } } } }); } } }); } public void activeRepositoryChanged(RepositoryManager repositoryManager, String repository) { // Do nothing. } } /** * @author Eike Stepper */ private final class ItemContentProvider implements ITreeContentProvider { public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } public void dispose() { } public Object getParent(Object element) { return null; } public Object[] getElements(Object element) { return getChildren(element); } public Object[] getChildren(Object element) { Item[] children = ((Item)element).getChildren(); if (children != null) { return children; } return NO_ELEMENTS; } public boolean hasChildren(Object element) { return ((Item)element).hasChildren(); } } /** * @author Eike Stepper */ private static final class ItemLabelProvider extends LabelProvider { @Override public Image getImage(Object element) { Item item = (Item)element; return item.getImage(); } @Override public String getText(Object element) { Item item = (Item)element; return item.getLabel(); } } /** * @author Eike Stepper */ private static final class VersionProvider extends LabelProvider implements IStructuredContentProvider { private static final Image IMAGE = P2UIPlugin.INSTANCE.getSWTImage("obj16/version"); private TableViewer versionsViewer; private VersionSegment versionSegment; public VersionProvider() { try { versionSegment = VersionSegment.get(SETTINGS.get(VERSION_SEGMENT_KEY)); } catch (Exception ex) { //$FALL-THROUGH$ } if (versionSegment == null) { versionSegment = VersionSegment.QUALIFIER; } } public VersionSegment getVersionSegment() { return versionSegment; } public void setVersionSegment(VersionSegment versionSegment) { if (this.versionSegment != versionSegment) { this.versionSegment = versionSegment; SETTINGS.put(VERSION_SEGMENT_KEY, versionSegment.getLiteral()); if (versionsViewer != null) { versionsViewer.refresh(); } } } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { versionsViewer = (TableViewer)viewer; } @Override public void dispose() { } public Object[] getElements(Object inputElement) { if (inputElement instanceof VersionedItem) { VersionedItem versionedItem = (VersionedItem)inputElement; Map<Version, IMatchExpression<IInstallableUnit>> versions = versionedItem.getVersions(); if (versions != null) { Set<ItemVersion> itemVersions = new HashSet<ItemVersion>(); for (Map.Entry<Version, IMatchExpression<IInstallableUnit>> entry : versions.entrySet()) { ItemVersion itemVersion = getItemVersion(entry.getKey(), entry.getValue()); itemVersions.add(itemVersion); } ItemVersion[] array = itemVersions.toArray(new ItemVersion[itemVersions.size()]); Arrays.sort(array); return array; } } return NO_ELEMENTS; } @Override public Image getImage(Object element) { return IMAGE; } private ItemVersion getItemVersion(Version version, IMatchExpression<IInstallableUnit> filter) { int segments = version.getSegmentCount(); if (segments == 0) { return new ItemVersion(version, "0.0.0", filter); } segments = Math.min(segments, versionSegment.ordinal() + 1); StringBuilder builder = new StringBuilder(); for (int i = 0; i < segments; i++) { String segment = version.getSegment(i).toString(); if (StringUtil.isEmpty(segment)) { break; } if (builder.length() != 0) { builder.append('.'); } builder.append(segment); } version = Version.create(builder.toString()); if (segments < 3) { builder.append(".x"); } return new ItemVersion(version, builder.toString(), filter); } /** * @author Eike Stepper */ public static final class ItemVersion implements Comparable<ItemVersion> { private final Version version; private final String label; private final IMatchExpression<IInstallableUnit> filter; public ItemVersion(Version version, String label, IMatchExpression<IInstallableUnit> filter) { this.version = version; this.label = label; this.filter = filter; } public Version getVersion() { return version; } public IMatchExpression<IInstallableUnit> getFilter() { return filter; } public int compareTo(ItemVersion o) { return version.compareTo(o.version); } @Override public int hashCode() { return version.hashCode(); } @Override public boolean equals(Object obj) { return version.equals(((ItemVersion)obj).version); } @Override public String toString() { return label; } } } /** * @author Eike Stepper */ private static abstract class Item implements Comparable<Item> { protected static final Integer CATEGORY_ORDER = 0; protected static final Integer NON_CATEGORY_ORDER = 1; private String label; public Item() { } public abstract Image getImage(); public String getNamespace() { return IInstallableUnit.NAMESPACE_IU_ID; } public String getName() { return getLabel(); } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public Item[] getChildren() { return null; } public boolean hasChildren() { return false; } @Override public String toString() { return label; } @Override public final int hashCode() { return super.hashCode(); } @Override public final boolean equals(Object obj) { return super.equals(obj); } public int compareTo(Item o) { Integer category1 = getCategoryOrder(); Integer category2 = o.getCategoryOrder(); int result = category1.compareTo(category2); if (result == 0) { String label1 = label.toLowerCase(); String label2 = o.label.toLowerCase(); result = label1.compareTo(label2); } return result; } protected Integer getCategoryOrder() { return NON_CATEGORY_ORDER; } } /** * @author Eike Stepper */ private static final class LoadingItem extends Item { private static final Image IMAGE = P2UIPlugin.INSTANCE.getSWTImage("obj16/repository"); private final URI location; public LoadingItem(URI location) { this.location = location; } @Override public Image getImage() { return IMAGE; } @Override public String getLabel() { return "Loading " + location; } } /** * @author Eike Stepper */ private static final class ErrorItem extends Item { private final IStatus status; public ErrorItem(IStatus status) { this.status = status; } @Override public Image getImage() { return UIUtil.getStatusImage(status.getSeverity()); } @Override public String getLabel() { return status.getMessage(); } } /** * @author Eike Stepper */ private static final class CategoryItem extends Item { private static final Image IMAGE = P2UIPlugin.INSTANCE.getSWTImage("obj16/category"); private Item[] children; public CategoryItem() { } @Override public Image getImage() { return IMAGE; } @Override public boolean hasChildren() { return children != null && children.length != 0; } @Override public Item[] getChildren() { return children; } public void setChildren(Item[] children) { Arrays.sort(children); this.children = children; } @Override protected Integer getCategoryOrder() { return CATEGORY_ORDER; } } /** * @author Eike Stepper */ private static abstract class VersionedItem extends Item { private Map<Version, IMatchExpression<IInstallableUnit>> versions; public VersionedItem() { } public Map<Version, IMatchExpression<IInstallableUnit>> getVersions() { return versions; } public void setVersions(Map<Version, IMatchExpression<IInstallableUnit>> map) { versions = map; } } /** * @author Eike Stepper */ private static final class FeatureItem extends VersionedItem { private static final Image IMAGE = P2UIPlugin.INSTANCE.getSWTImage("obj16/artifactFeature"); private final String id; public FeatureItem(String id) { this.id = id; } @Override public Image getImage() { return IMAGE; } @Override public String getName() { return id; } } /** * @author Eike Stepper */ private static final class PluginItem extends VersionedItem { private static final Image IMAGE = P2UIPlugin.INSTANCE.getSWTImage("obj16/artifactPlugin"); private final String id; public PluginItem(String id) { this.id = id; } @Override public Image getImage() { return IMAGE; } @Override public String getName() { return id; } } /** * @author Eike Stepper */ private static final class CapabilityItem extends VersionedItem { private static final Image IMAGE = P2UIPlugin.INSTANCE.getSWTImage("obj16/capability"); private static final Image FEATURE_IMAGE = P2UIPlugin.INSTANCE.getSWTImage("obj16/artifactFeature"); private static final Image PLUGIN_IMAGE = P2UIPlugin.INSTANCE.getSWTImage("obj16/artifactPlugin"); private static final Image PACKAGE_IMAGE = P2UIPlugin.INSTANCE.getSWTImage("full/obj16/Requirement_Package"); private String namespace; public CapabilityItem() { } @Override public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public void setVersions(Set<Version> versions) { Map<Version, IMatchExpression<IInstallableUnit>> map = new HashMap<Version, IMatchExpression<IInstallableUnit>>(); for (Version version : versions) { map.put(version, null); } setVersions(map); } @Override public Image getImage() { if (IInstallableUnit.NAMESPACE_IU_ID.equals(namespace)) { if (getLabel().endsWith(Requirement.FEATURE_SUFFIX)) { return FEATURE_IMAGE; } return PLUGIN_IMAGE; } if (RequirementItemProvider.NAMESPACE_PACKAGE_ID.equals(namespace)) { return PACKAGE_IMAGE; } return IMAGE; } } }
package org.eclipse.xtext.scoping.impl; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.xtext.resource.IContainer; import org.eclipse.xtext.resource.IEObjectDescription; import org.eclipse.xtext.resource.IResourceDescription; import org.eclipse.xtext.resource.IResourceDescription.Event.Source; import org.eclipse.xtext.resource.IResourceDescriptions; import org.eclipse.xtext.resource.containers.FilterUriContainer; import org.eclipse.xtext.resource.impl.ResourceDescriptionsProvider; import org.eclipse.xtext.scoping.IScope; import org.eclipse.xtext.util.OnChangeEvictingCache; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.inject.Inject; /** * @author Sven Efftinge - Initial contribution and API */ public class DefaultGlobalScopeProvider extends AbstractGlobalScopeProvider { @Inject private IContainer.Manager containerManager; @Inject private IResourceDescription.Manager descriptionManager; protected IScope getScope(IScope parent, final Resource context, boolean ignoreCase, EClass type, Predicate<IEObjectDescription> filter) { IScope result = parent; List<IContainer> containers = Lists.newArrayList(getVisibleContainers(context)); Collections.reverse(containers); Iterator<IContainer> iter = containers.iterator(); while (iter.hasNext()) { IContainer container = iter.next(); result = createContainerScopeWithContext(context, result, container, filter, type, ignoreCase); } return result; } @Override protected IScope getScope(final Resource context, boolean ignoreCase, EClass type, Predicate<IEObjectDescription> filter) { return getScope(IScope.NULLSCOPE, context, ignoreCase, type, filter); } protected List<IContainer> getVisibleContainers(Resource resource) { IResourceDescription description = descriptionManager.getResourceDescription(resource); IResourceDescriptions resourceDescriptions = getResourceDescriptions(resource); String cacheKey = getCacheKey("VisibleContainers", resource.getResourceSet()); OnChangeEvictingCache.CacheAdapter cache = new OnChangeEvictingCache().getOrCreate(resource); List<IContainer> result = null; result = cache.get(cacheKey); if (result == null) { result = containerManager.getVisibleContainers(description, resourceDescriptions); // SZ: I'ld like this dependency to be moved to the implementation of the // container manager, but it is not aware of a CacheAdapter if (resourceDescriptions instanceof IResourceDescription.Event.Source) { IResourceDescription.Event.Source eventSource = (Source) resourceDescriptions; DelegatingEventSource delegatingEventSource = new DelegatingEventSource(eventSource); delegatingEventSource.addListeners(Lists.newArrayList(Iterables.filter(result, IResourceDescription.Event.Listener.class))); delegatingEventSource.initialize(); cache.addCacheListener(delegatingEventSource); } cache.set(cacheKey, result); } return result; } protected String getCacheKey(String base, ResourceSet context) { Map<Object, Object> loadOptions = context.getLoadOptions(); if (loadOptions.containsKey(ResourceDescriptionsProvider.NAMED_BUILDER_SCOPE)) { return base + "@" + ResourceDescriptionsProvider.NAMED_BUILDER_SCOPE; } return base + "@DEFAULT_SCOPE"; } protected IScope createContainerScopeWithContext(Resource eResource, IScope parent, IContainer container, Predicate<IEObjectDescription> filter, EClass type, boolean ignoreCase) { if (eResource != null) { URI uriToFilter = eResource.getURI(); if (container.hasResourceDescription(uriToFilter)) container = new FilterUriContainer(uriToFilter, container); } return createContainerScope(parent, container, filter, type, ignoreCase); } protected IScope createContainerScope(IScope parent, IContainer container, Predicate<IEObjectDescription> filter, EClass type, boolean ignoreCase) { return SelectableBasedScope.createScope(parent, container, filter, type, ignoreCase); } }
package com.lls.sample.ui; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.lls.sample.R; public class MyActivity extends Activity implements View.OnClickListener { /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init() { findViewById(R.id.btn1).setOnClickListener(this); findViewById(R.id.btn2).setOnClickListener(this); findViewById(R.id.btn3).setOnClickListener(this); findViewById(R.id.btn4).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn1: startActivity(new Intent(MyActivity.this, HttpActivity.class)); break; case R.id.btn2: startActivity(new Intent(MyActivity.this, AnimActivity2.class)); break; case R.id.btn3: startActivity(new Intent(MyActivity.this, ImageActivity.class)); break; case R.id.btn4: startActivity(new Intent(MyActivity.this, HttpActivity.class)); break; } } }
package org.eigenbase.oj.rel; import java.util.*; import java.util.List; import java.util.logging.*; import openjava.mop.*; import openjava.ptree.*; import org.eigenbase.oj.rex.*; import org.eigenbase.oj.util.*; import org.eigenbase.rel.*; import org.eigenbase.rel.metadata.*; import org.eigenbase.relopt.*; import org.eigenbase.reltype.*; import org.eigenbase.rex.*; import org.eigenbase.runtime.*; import org.eigenbase.sql.fun.*; import org.eigenbase.trace.*; import org.eigenbase.util.*; /** * <code>IterCalcRel</code> is an iterator implementation of a combination of * {@link ProjectRel} above an optional {@link FilterRel}. It takes a {@link * TupleIter iterator} as input, and for each row applies the filter condition * if defined. Rows passing the filter expression are transformed via projection * and returned. Note that the same object is always returned (with different * values), so parents must not buffer the result. * * <p>Rules: * * <ul> * <li>{@link org.eigenbase.oj.rel.IterRules.IterCalcRule} creates an * IterCalcRel from a {@link org.eigenbase.rel.CalcRel}</li> * </ul> */ public class IterCalcRel extends SingleRel implements JavaRel { private static boolean abortOnError = true; private static boolean errorBuffering = false; private final RexProgram program; /** * Values defined in {@link ProjectRelBase.Flags}. */ protected int flags; private String tag; public IterCalcRel( RelOptCluster cluster, RelNode child, RexProgram program, int flags) { this(cluster, child, program, flags, null); } public IterCalcRel( RelOptCluster cluster, RelNode child, RexProgram program, int flags, String tag) { super( cluster, new RelTraitSet(CallingConvention.ITERATOR), child); this.flags = flags; this.program = program; this.rowType = program.getOutputRowType(); this.tag = tag; } // TODO jvs 10-May-2004: need a computeSelfCost which takes condition into // account; maybe inherit from CalcRelBase? public void explain(RelOptPlanWriter pw) { program.explainCalc(this, pw); } protected String computeDigest() { String tempDigest = super.computeDigest(); if (tag != null) { // append logger type to digest int lastParen = tempDigest.lastIndexOf(')'); tempDigest = tempDigest.substring(0, lastParen) + ",type=" + tag + tempDigest.substring(lastParen); } return tempDigest; } public double getRows() { return FilterRel.estimateFilteredRows( getChild(), program.getCondition()); } public RelOptCost computeSelfCost(RelOptPlanner planner) { double dRows = RelMetadataQuery.getRowCount(this); double dCpu = RelMetadataQuery.getRowCount(getChild()) * program.getExprCount(); double dIo = 0; return planner.makeCost(dRows, dCpu, dIo); } public Object clone() { IterCalcRel clone = new IterCalcRel( getCluster(), RelOptUtil.clone(getChild()), program.copy(), getFlags(), tag); clone.inheritTraitsFrom(this); return clone; } public int getFlags() { return flags; } public boolean isBoxed() { return (flags & ProjectRelBase.Flags.Boxed) == ProjectRelBase.Flags.Boxed; } /** * Burrows into a synthetic record and returns the underlying relation which * provides the field called <code>fieldName</code>. */ public JavaRel implementFieldAccess( JavaRelImplementor implementor, String fieldName) { if (!isBoxed()) { return implementor.implementFieldAccess((JavaRel) getChild(), fieldName); } RelDataType type = getRowType(); int field = type.getFieldOrdinal(fieldName); RexLocalRef ref = program.getProjectList().get(field); final int index = ref.getIndex(); return implementor.findRel( (JavaRel) this, program.getExprList().get(index)); } /** * Disables throwing of exceptions on error. Do not set this false without a * very good reason! Doing so will prevent type cast, overflow/underflow, * etc. errors in Farrago. */ public static void setAbortOnError(boolean abortOnError) { IterCalcRel.abortOnError = abortOnError; } /** * Allows errors to be buffered, in the event that they overflow the * error handler. * * @param errorBuffering whether to buffer errors */ public static void setErrorBuffering(boolean errorBuffering) { IterCalcRel.errorBuffering = errorBuffering; } public static Expression implementAbstract( JavaRelImplementor implementor, JavaRel rel, Expression childExp, Variable varInputRow, final RelDataType inputRowType, final RelDataType outputRowType, RexProgram program, String tag) { return implementAbstractTupleIter( implementor, rel, childExp, varInputRow, inputRowType, outputRowType, program, tag); } /** * Generates code for a Java expression satisfying the * {@link org.eigenbase.runtime.TupleIter} interface. The generated * code allocates a {@link org.eigenbase.runtime.CalcTupleIter} * with a dynamic {@link org.eigenbase.runtime.TupleIter#fetchNext()} * method. If the "abort on error" flag is false, or an error handling * tag is specified, then fetchNext is written to handle row errors. * * <p> * * Row errors are handled by wrapping expressions that can fail * with a try/catch block. A caught RuntimeException is then published * to an "connection variable." In the event that errors can overflow, * an "error buffering" flag allows them to be posted again on the next * iteration of fetchNext. * * @param implementor an object that implements relations as Java code * @param rel the relation to be implemented * @param childExp the implemented child of the relation * @param varInputRow the Java variable to use for the input row * @param inputRowType the rel data type of the input row * @param outputRowType the rel data type of the output row * @param program the rex program to implemented by the relation * @param tag an error handling tag * @return a Java expression satisfying the TupleIter interface */ public static Expression implementAbstractTupleIter( JavaRelImplementor implementor, JavaRel rel, Expression childExp, Variable varInputRow, final RelDataType inputRowType, final RelDataType outputRowType, RexProgram program, String tag) { // Perform error recovery if continuing on errors or if // an error handling tag has been specified boolean errorRecovery = (abortOnError == false || tag != null); // Error buffering should not be enabled unless error recovery is assert (errorBuffering == false || errorRecovery == true); // Allow backwards compatibility until all Farrago extensions are // satisfied with the new error handling semantics. The new semantics // include: // (1) cast input object to input row object outside of try block, // should be fine, at least for base Farrago // (2) maintain a columnIndex counter to better locate of error, // at the cost of a few cycles // (3) publish errors to the runtime context. FarragoRuntimeContext // now supports this API boolean backwardsCompatible = true; if (tag != null) { backwardsCompatible = false; } RelDataTypeFactory typeFactory = implementor.getTypeFactory(); OJClass outputRowClass = OJUtil.typeToOJClass( outputRowType, typeFactory); OJClass inputRowClass = OJUtil.typeToOJClass( inputRowType, typeFactory); Variable varOutputRow = implementor.newVariable(); FieldDeclaration rowVarDecl = new FieldDeclaration( new ModifierList(ModifierList.PRIVATE), TypeName.forOJClass(outputRowClass), varOutputRow.toString(), new AllocationExpression( outputRowClass, new ExpressionList())); // The method body for fetchNext, a main target of code generation StatementList nextMethodBody = new StatementList(); // First, post an error if it overflowed the previous time // if (pendingError) { // rc = handleRowError(...); // if (rc instanceof NoDataReason) { // return rc; // pendingError = false; if (errorBuffering) { // add to next method body... } // Most of fetchNext falls within a while() block. The while block // allows us to try multiple input rows against a filter condition // before returning a single row. // while (true) { // Object varInputObj = inputIterator.fetchNext(); // if (varInputObj instanceof TupleIter.NoDataReason) { // return varInputObj; // InputRowClass varInputRow = (InputRowClass) varInputObj; // int columnIndex = 0; // [calculation statements] StatementList whileBody = new StatementList(); Variable varInputObj = implementor.newVariable(); whileBody.add( new VariableDeclaration( OJUtil.typeNameForClass(Object.class), varInputObj.toString(), new MethodCall( new FieldAccess("inputIterator"), "fetchNext", new ExpressionList()))); StatementList ifNoDataReasonBody = new StatementList(); whileBody.add( new IfStatement( new InstanceofExpression( varInputObj, OJUtil.typeNameForClass(TupleIter.NoDataReason.class)), ifNoDataReasonBody)); ifNoDataReasonBody.add(new ReturnStatement(varInputObj)); // Push up the row declaration for new error handling so that the // input row is available to the error handler if (! backwardsCompatible) { whileBody.add( declareInputRow(inputRowClass, varInputRow, varInputObj)); } Variable varColumnIndex = null; if (errorRecovery && backwardsCompatible == false) { varColumnIndex = implementor.newVariable(); whileBody.add( new VariableDeclaration( OJUtil.typeNameForClass(int.class), varColumnIndex.toString(), Literal.makeLiteral(0))); } // Calculator (projection, filtering) statements are later appended // to calcStmts. Typically, this target will be the while list itself. StatementList calcStmts; if (errorRecovery == false) { calcStmts = whileBody; } else { // For error recovery, we wrap the calc statements // (e.g., everything but the code that reads rows from the // inputIterator) in a try/catch that publishes exceptions. calcStmts = new StatementList(); // try { /* calcStmts */ } // catch(RuntimeException ex) { // Object rc = connection.handleRowError(...); // [buffer error if necessary] StatementList catchStmts = new StatementList(); if (backwardsCompatible) { catchStmts.add( new ExpressionStatement( new MethodCall( new MethodCall( OJUtil.typeNameForClass(EigenbaseTrace.class), "getStatementTracer", null), "log", new ExpressionList( new FieldAccess( OJUtil.typeNameForClass(Level.class), "WARNING"), Literal.makeLiteral("java calc exception"), new FieldAccess("ex"))))); } else { Variable varRc = implementor.newVariable(); ExpressionList handleRowErrorArgs = new ExpressionList( varInputRow, new FieldAccess("ex"), varColumnIndex); handleRowErrorArgs.add(Literal.makeLiteral(tag)); catchStmts.add( new VariableDeclaration( OJUtil.typeNameForClass(Object.class), varRc.toString(), new MethodCall( implementor.getConnectionVariable(), "handleRowError", handleRowErrorArgs))); // Buffer an error if it overflowed // if (rc instanceof NoDataReason) { // pendingError = true; // [save error state] // return rc; if (errorBuffering) { // add to catch statements... } } CatchList catchList = new CatchList( new CatchBlock( new Parameter( OJUtil.typeNameForClass(RuntimeException.class), "ex"), catchStmts)); TryStatement tryStmt = new TryStatement(calcStmts, catchList); whileBody.add(tryStmt); } if (backwardsCompatible) { whileBody.add( declareInputRow(inputRowClass, varInputRow, varInputObj)); } MemberDeclarationList memberList = new MemberDeclarationList(); StatementList condBody; RexToOJTranslator translator = implementor.newStmtTranslator(rel, calcStmts, memberList); try { translator.pushProgram(program); if (program.getCondition() != null) { condBody = new StatementList(); RexNode rexIsTrue = rel.getCluster().getRexBuilder().makeCall( SqlStdOperatorTable.isTrueOperator, new RexNode[] { program.getCondition() }); Expression conditionExp = translator.translateRexNode(rexIsTrue); calcStmts.add(new IfStatement(conditionExp, condBody)); } else { condBody = calcStmts; } RexToOJTranslator condTranslator = translator.push(condBody); RelDataTypeField [] fields = outputRowType.getFields(); final List<RexLocalRef> projectRefList = program.getProjectList(); int i = -1; for (RexLocalRef rhs : projectRefList) { if (errorRecovery && backwardsCompatible == false) { condBody.add( new ExpressionStatement( new UnaryExpression( varColumnIndex, UnaryExpression.POST_INCREMENT))); } ++i; String javaFieldName = Util.toJavaId( fields[i].getName(), i); Expression lhs = new FieldAccess(varOutputRow, javaFieldName); condTranslator.translateAssignment(fields[i], lhs, rhs); } } finally { translator.popProgram(program); } condBody.add(new ReturnStatement(varOutputRow)); WhileStatement whileStmt = new WhileStatement( Literal.makeLiteral(true), whileBody); nextMethodBody.add(whileStmt); MemberDeclaration fetchNextMethodDecl = new MethodDeclaration( new ModifierList(ModifierList.PUBLIC), OJUtil.typeNameForClass(Object.class), "fetchNext", new ParameterList(), null, nextMethodBody); // The restart() method should reset variables used to buffer errors // pendingError = false if (errorBuffering) { // declare refinement of restart() and add to member list... } memberList.add(rowVarDecl); memberList.add(fetchNextMethodDecl); Expression newTupleIterExp = new AllocationExpression( OJUtil.typeNameForClass(CalcTupleIter.class), new ExpressionList(childExp), memberList); return newTupleIterExp; } public ParseTree implement(JavaRelImplementor implementor) { Expression childExp = implementor.visitJavaChild(this, 0, (JavaRel) getChild()); RelDataType outputRowType = getRowType(); RelDataType inputRowType = getChild().getRowType(); Variable varInputRow = implementor.newVariable(); implementor.bind( getChild(), varInputRow); return implementAbstract( implementor, this, childExp, varInputRow, inputRowType, outputRowType, program, tag); } public RexProgram getProgram() { return program; } public String getTag() { return tag; } private static Statement declareInputRow( OJClass inputRowClass, Variable varInputRow, Variable varInputObj) { return new VariableDeclaration( TypeName.forOJClass(inputRowClass), varInputRow.toString(), new CastExpression( TypeName.forOJClass(inputRowClass), varInputObj)); } } // End IterCalcRel.java
package eco.game; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; import java.awt.image.BufferedImage; import java.io.IOException; import java.nio.ByteBuffer; import java.sql.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.imageio.ImageIO; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; /** * A class that contains various utilities and convenience methods * * @author phil, nate, connor, will * */ public class Util { private static Random random = new Random(); public static void createSave() { if (Main.currentSave == 1) { if(Main.saveName1.contains(" ")) { Main.saveName1 = Main.saveName1.replace(" ", "@"); } } if (Main.currentSave == 2) { if(Main.saveName2.contains(" ")) { Main.saveName2 = Main.saveName2.replace(" ", "@"); } } if (Main.currentSave == 3) { if(Main.saveName3.contains(" ")) { Main.saveName3 = Main.saveName3.replace(" ", "@"); } } if (Main.currentSave == 4) { if(Main.saveName4.contains(" ")) { Main.saveName4 = Main.saveName4.replace(" ", "@"); } } if (Main.currentSave == 5) { if(Main.saveName5.contains(" ")) { Main.saveName5 = Main.saveName5.replace(" ", "@"); } } String path = null; try { path = "saves/" + Main.currentSave + ".txt"; if (!Main.isInEclipse) { path = "../" + path; } File fOut = new File(path); FileOutputStream FOS = new FileOutputStream(fOut); BufferedWriter BW = new BufferedWriter(new OutputStreamWriter(FOS)); // Data Being Saved: if (Main.currentSave == 1) { BW.write(Main.saveName1); BW.newLine(); } if (Main.currentSave == 2) { BW.write(Main.saveName2); BW.newLine(); } if (Main.currentSave == 3) { BW.write(Main.saveName3); BW.newLine(); } if (Main.currentSave == 4) { BW.write(Main.saveName4); BW.newLine(); } if (Main.currentSave == 5) { BW.write(Main.saveName5); BW.newLine(); } BW.write(Integer.toString(PlayerCountry.year)); BW.newLine(); BW.write(Integer.toString(PlayerCountry.wheat.gettWheat())); BW.newLine(); BW.write(Integer.toString(PlayerCountry.farmer.getfPop())); BW.newLine(); BW.write(Integer.toString(PlayerCountry.warrior.getwPop())); BW.newLine(); BW.write(Integer.toString(PlayerCountry.land.getLand())); BW.newLine(); BW.write(Integer.toString(PlayerCountry.land.getPop())); BW.newLine(); for (int x = 0; x < World.mapsize; x++) { for (int y = 0; y < World.mapsize; y++) { BW.write(Short.toString(World.map[x][y])); } BW.newLine(); } for (int x = 0; x < World.mapsize; x++) { for (int y = 0; y < World.mapsize; y++) { BW.write(Float.toString(World.noise[x][y]) + ","); } BW.newLine(); } for (int x = 0; x < World.mapsize; x++) { for (int y = 0; y < World.mapsize; y++) { BW.write(Short.toString(World.structures[x][y]) + ","); } BW.newLine(); } for (int x = 0; x < World.mapsize; x++) { for (int y = 0; y < World.mapsize; y++) { BW.write(Short.toString(World.popmap[x][y]) + ","); } BW.newLine(); } for (int x = 0; x < World.mapsize; x++) { for (int y = 0; y < World.mapsize; y++) { BW.write(Short.toString(World.popdensity[x][y]) + ","); } BW.newLine(); } for (int x = 0; x < World.mapsize; x++) { for (int y = 0; y < World.mapsize; y++) { BW.write(Short.toString(World.decorations[x][y]) + ","); } BW.newLine(); } for (int x = 0; x < PlayerCountry.countries.size(); x++) { BW.write(String.valueOf(PlayerCountry.countries.get(x).farmer.getfPop()) + ","); } BW.newLine(); for (int x = 0; x < PlayerCountry.countries.size(); x++) { BW.write(String.valueOf(PlayerCountry.countries.get(x).warrior.getwPop()) + ","); } BW.newLine(); /* * Use: BW.write(STUFF TO BE SAVED HERE); BW.newLine(); * * Unless it needs to use loops in which case see the loops above. */ BW.close(); } catch (IOException ex) { System.out.println("IOException"); } } public static void readSave() { if (Main.currentSave == 1) { if(Main.saveName1.contains("@")) { Main.saveName1 = Main.saveName1.replace("@", " "); } } if (Main.currentSave == 2) { if(Main.saveName2.contains("@")) { Main.saveName2 = Main.saveName1.replace("@", " "); } } if (Main.currentSave == 3) { if(Main.saveName3.contains("@")) { Main.saveName3 = Main.saveName3.replace("@", " "); } } if (Main.currentSave == 4) { if(Main.saveName4.contains("@")) { Main.saveName4 = Main.saveName4.replace("@", " "); } } if (Main.currentSave == 5) { if(Main.saveName5.contains("@")) { Main.saveName5 = Main.saveName1.replace("@", " "); } } String path = ""; @SuppressWarnings("unused") File name = null; path = "saves/" + Main.currentSave + ".txt"; name = new File(Main.saveName1 + ".txt"); if (!Main.isInEclipse) { path = "../" + path; } Scanner s = null; try { s = new Scanner(new File(path)); } catch (FileNotFoundException e) { System.out.println("File Not Found"); return; } ArrayList<String> list = new ArrayList<String>(); try { while (s.hasNext()) { list.add(s.nextLine()); } s.close(); } catch (Exception e) { readError(); return; } try { for (String str : list) { str = str.replace(System.getProperty("line.separator"), ""); } // Information being loaded: if (Main.currentSave == 1) { Main.saveName1 = list.get(0); } if (Main.currentSave == 2) { Main.saveName2 = list.get(0); } if (Main.currentSave == 3) { Main.saveName3 = list.get(0); } if (Main.currentSave == 4) { Main.saveName4 = list.get(0); } if (Main.currentSave == 5) { Main.saveName5 = list.get(0); } PlayerCountry.year = Integer.valueOf(list.get(1)); PlayerCountry.wheat.settWheat(Integer.valueOf(list.get(2))); PlayerCountry.farmer.setfPop(Integer.valueOf(list.get(3))); PlayerCountry.warrior.setwPop(Integer.valueOf(list.get(4))); PlayerCountry.land.setLand(Integer.valueOf(list.get(5))); PlayerCountry.land.setPop(Integer.valueOf(list.get(6))); int line = 7; for (int x = 0; x < World.mapsize; x++) { String values = list.get(line); for (int y = 0; y < World.mapsize; y++) { World.map[x][y] = Short.valueOf(values.substring(y, y + 1)); } line++; } for (int x = 0; x < World.mapsize; x++) { String values = list.get(line); String[] parts = values.split(","); for (int y = 0; y < World.mapsize; y++) { World.noise[x][y] = Float.valueOf((parts[y])); } line++; } for (int x = 0; x < World.mapsize; x++) { String values = list.get(line); String[] parts = values.split(","); for (int y = 0; y < World.mapsize; y++) { World.structures[x][y] = Short.valueOf((parts[y])); } line++; } for (int x = 0; x < World.mapsize; x++) { String values = list.get(line); String[] parts = values.split(","); for (int y = 0; y < World.mapsize; y++) { World.popmap[x][y] = Short.valueOf((parts[y])); } line++; } for (int x = 0; x < World.mapsize; x++) { String values = list.get(line); String[] parts = values.split(","); for (int y = 0; y < World.mapsize; y++) { World.popdensity[x][y] = Short.valueOf((parts[y])); } line++; } for (int x = 0; x < World.mapsize; x++) { String values = list.get(line); String[] parts = values.split(","); for (int y = 0; y < World.mapsize; y++) { World.decorations[x][y] = Short.valueOf((parts[y])); } line++; } for (int x = 0; x < PlayerCountry.countries.size(); x++) { String values = list.get(line); String[] parts = values.split(","); PlayerCountry.countries.get(x).farmer.setfPop(Integer.valueOf(parts[x])); } line++; for (int x = 0; x < PlayerCountry.countries.size(); x++) { String values = list.get(line); String[] parts = values.split(","); PlayerCountry.countries.get(x).warrior.setwPop(Integer.valueOf(parts[x])); } line++; // Set the variable that the information will become // To the end here. //readSuccess(); } catch (Exception e) { e.printStackTrace(); readError(); } return; } public static void readError() { Message.addMessage(new Message( " Message.addMessage(new Message("Failed to load save!", 100, 130, 300)); Message.addMessage(new Message( "The file either disappeared or is corrupt!", 100, 160, 300)); Message.addMessage(new Message( " } public static void readSuccess() { Message.addMessage(new Message(" 100, 100, 300)); Message.addMessage(new Message("Loaded game state from save file!", 100, 130, 300)); Message.addMessage(new Message(" 100, 160, 300)); } public static int randInt(int max) { // Returns a random number below max. return random.nextInt(max); } public static int randInt(int min, int max) { // Returns a random number // between min and max. return min + random.nextInt((max + 1) - min); } public static float randFloat(float min, float max){ return random.nextFloat() * (max - min) + min; } public static void takeScreenshot() { GL11.glReadBuffer(GL11.GL_FRONT); int width = Display.getDisplayMode().getWidth(); int height = Display.getDisplayMode().getHeight(); int bpp = 4; ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * bpp); GL11.glReadPixels(0, 0, width, height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd H:mm:ss"); Date date = new Date(System.currentTimeMillis()); File file = new File("../screenshots/" + dateFormat.format(date)); file.mkdirs(); String format = "PNG"; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int i = (x + (width * y)) * bpp; int r = buffer.get(i) & 0xFF; int g = buffer.get(i + 1) & 0xFF; int b = buffer.get(i + 2) & 0xFF; image.setRGB(x, height - (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | b); } } try { ImageIO.write(image, format, file); } catch (IOException e) { e.printStackTrace(); } } public static int computeTotalHunger() { return PlayerCountry.farmer.getTotalHunger() + PlayerCountry.warrior.getTotalHunger() + ((int) (PlayerCountry.farmer.getfHunger() * World.displacedPeople / 2f)); } public static String getWheatRateForDisplay() { int hunger = computeTotalHunger(); int input = PlayerCountry.farmer.getWheatProductionRate() * PlayerCountry.farmer.getfPop(); input += PlayerCountry.land.getWheatRate(); int total = input - hunger; if (total < 0) { return "dW/dT: " + String.valueOf(total) + " Bushels"; } else if (total == 0) { return "dW/dT: " + "0 Bushels"; } else { return "dW/dT: +" + String.valueOf(total) + " Bushels"; } } public static int getWheatRate() { int hunger = computeTotalHunger(); int input = PlayerCountry.farmer.getWheatProductionRate() * PlayerCountry.farmer.getfPop(); input += PlayerCountry.land.getWheatRate(); int total = input - hunger; return total; } public static float getTotalPopf() { return PlayerCountry.warrior.getFloatWPop() + PlayerCountry.farmer.getFloatFPop(); } public static int getTotalPop() { return PlayerCountry.warrior.getwPop() + PlayerCountry.farmer.getfPop(); } public static boolean doesSaveExist(int currentSave) { String path = ""; File name = null; path = "saves/" + currentSave + ".txt"; name = new File(currentSave + ".txt"); if (!Main.isInEclipse) { path = "../" + path; } name = new File(path); if (name.exists()) { return true; } return false; } public static Treble<Float, Float, Float> convertColor( Treble<Float, Float, Float> base) { return new Treble<Float, Float, Float>(base.x / 255f, base.y / 255f, base.z / 255f); } public static String loadSaveName(int currentSave) { String path = ""; @SuppressWarnings("unused") File name = null; path = "saves/" + currentSave + ".txt"; if (!Main.isInEclipse) { path = "../" + path; } Scanner s = null; try { s = new Scanner(new File(path)); } catch (FileNotFoundException e) { System.out.println("File Not Found"); return ""; } ArrayList<String> list = new ArrayList<String>(); try { while (s.hasNext()) { list.add(s.next()); } s.close(); } catch (Exception e) { readError(); return ""; } try { for (String str : list) { str = str.replace(System.getProperty("line.separator"), ""); } // Information being loaded: /* * if (currentSave == 1){ Main.saveName1 = list.get(0); } if * (currentSave == 2){ Main.saveName2 = list.get(0); } if * (currentSave == 3){ Main.saveName3 = list.get(0); } if * (currentSave == 4){ Main.saveName4 = list.get(0); } if * (currentSave == 5){ Main.saveName5 = list.get(0); } */ return list.get(0); } catch (Exception e) { e.printStackTrace(); readError(); } return ""; } public static void deleteSave(int save){ String path = ""; File name = null; path = "saves/" + save + ".txt"; if (!Main.isInEclipse) { path = "../" + path; } name = new File(path); if (name.exists()){ name.delete(); Menu.initMenu(); } } public static Country[] getCountries(){ return PlayerCountry.countries.toArray(new Country[PlayerCountry.countries.size()]); } public static void putCountries(Country[] toPut){ PlayerCountry.countries.clear(); for (Country c : toPut){ PlayerCountry.countries.add(c); } } public static void applyRandomColorNoise(int x, int y){ NoiseSampler.initSimplexNoise((int) World.mapseed); NoiseSampler.setNoiseScale(World.mapsize / 32); float noise = NoiseSampler.getNoise(x, y) / 6f; GL11.glColor3f(1f - noise, 1f - noise, 1f - noise); } <<<<<<< HEAD ======= public static float getRandomColorNoise(int x, int y){ NoiseSampler.initSimplexNoise((int) World.mapseed); NoiseSampler.setNoiseScale(World.mapsize / 32); float noise = NoiseSampler.getNoise(x, y) / 6f; return 1f - noise; } >>>> origin/master public static float calcAverageCountryScore(){ float total = 0; for (Country c : PlayerCountry.countries){ total += c.score.scoreAt(Math.max(0, PlayerCountry.year - 1)); } return total / PlayerCountry.countries.size(); } }
package edu.stuy.starlorn.entities; import edu.stuy.starlorn.upgrades.GunUpgrade; import java.util.LinkedList; public class Ship extends Entity { protected LinkedList<GunUpgrade> _gunupgrades; protected int _baseDamage, _baseShotSpeed, _health; protected double _baseAim; public Ship() { super(); _gunupgrades = new LinkedList<GunUpgrade>(); _baseDamage = 1; _baseShotSpeed = 1; _health = 10; _baseAim = Math.PI/2; //Aim up by default } public void addUpgrade(GunUpgrade upgrade) { _gunupgrades.add(upgrade); } /* * Create the shots based on the available GunUpgrades */ public void shoot() { GunUpgrade topShot = _gunupgrades.get(0); int damage = _baseDamage; int shotSpeed = _baseShotSpeed; for (GunUpgrade up : _gunupgrades) { if (up.getNumShots() > topShot.getNumShots()) topShot = up; damage = up.getDamage(damage); shotSpeed = up.getShotSpeed(shotSpeed); } // Create new shots, based on dem vars int numShots = topShot.getNumShots(); for (int i = 0; i < numShots; i++) { Bullet b = new Bullet(_baseAim + topShot.getAimAngle(), damage, shotSpeed); b.setWorld(this.getWorld()); } } }
package sfBugsNew; import edu.umd.cs.findbugs.annotations.DesireNoWarning; public class Bug1325<P extends java.io.Serializable & Comparable<P>> implements java.io.Serializable, Comparable<Bug1325<P>> { private static final long serialVersionUID = 1L; private final P startPoint; private final P endPoint; @DesireNoWarning("BC_UNCONFIRMED_CAST") public Bug1325(P start, P end) { startPoint = start; endPoint = end; if (start.compareTo(end) > 0) throw new IllegalArgumentException("start after end"); } @Override public int compareTo(Bug1325<P> o) { final int comp = startPoint.compareTo(o.startPoint); return comp != 0 ? comp : endPoint.compareTo(o.endPoint); } @Override public int hashCode() { return (31 + (endPoint == null ? 0 : endPoint.hashCode())) * 31 + (startPoint == null ? 0 : startPoint.hashCode()); } @Override public boolean equals(Object obj) { return obj instanceof Bug1325 && startPoint.equals(((Bug1325) obj).startPoint) && endPoint.equals(((Bug1325) obj).endPoint); } }
package pt.fccn.arquivo.tests; import static org.junit.Assert.*; import org.junit.Test; import pt.fccn.arquivo.pages.HighlightsPage; import pt.fccn.arquivo.pages.IndexPage; import pt.fccn.saw.selenium.WebDriverTestBase; import java.util.ArrayList; /** * @author Simao Fontes * */ public class HighlightsTest extends WebDriverTestBase{ /** * Test the link for more highlights */ @Test public void highlightLinkTest() { for(WebDriver dr: drivers){ System.out.print("Running HighlightsTest. \n"); IndexPage index = new IndexPage(dr); index.langToEnglish(); HighlightsPage highlightPage = index.goToHighlightsPage(); assertTrue("The page displayed has not got the correct text being displayed", highlightPage.isPageCorrect()); assertTrue("The page is not online", highlightPage.goThroughHighlights()); assertTrue("The page link is broken ", highlightPage.checkLinkHighligths()); assertTrue("The title of the page is not correct ", highlightPage.checkHighligthsPageLinks()); } } }
package org.exist; import java.util.HashMap; import java.util.Map; import java.util.Observable; import java.util.Stack; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.apache.log4j.Logger; import org.exist.dom.AttrImpl; import org.exist.dom.CommentImpl; import org.exist.dom.DocumentImpl; import org.exist.dom.DocumentTypeImpl; import org.exist.dom.ElementImpl; import org.exist.dom.NodeObjectPool; import org.exist.dom.ProcessingInstructionImpl; import org.exist.dom.QName; import org.exist.dom.TextImpl; import org.exist.storage.DBBroker; import org.exist.storage.GeneralRangeIndexSpec; import org.exist.storage.NodePath; import org.exist.storage.serializers.Serializer; import org.exist.storage.txn.Txn; import org.exist.util.Configuration; import org.exist.util.ProgressIndicator; import org.exist.util.XMLChar; import org.exist.util.XMLString; import org.exist.xquery.Constants; import org.exist.xquery.value.StringValue; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; 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.ext.LexicalHandler; /** * Parses a given input document via SAX, stores it to * the database and handles index-creation. * * @author wolf * */ public class Indexer extends Observable implements ContentHandler, LexicalHandler, ErrorHandler { private static final String ATTR_ID_TYPE = "ID"; private final static Logger LOG = Logger.getLogger(Indexer.class); protected DBBroker broker = null; protected Txn transaction; protected XMLString charBuf = new XMLString(); protected int currentLine = 0; protected NodePath currentPath = new NodePath(); protected DocumentImpl document = null; protected boolean insideDTD = false; protected boolean validate = false; protected int level = 0; protected Locator locator = null; protected int normalize = XMLString.SUPPRESS_BOTH; protected Map nsMappings = new HashMap(); protected Element rootNode; protected Stack stack = new Stack(); protected Stack nodeContentStack = new Stack(); protected String ignorePrefix = null; protected ProgressIndicator progress; protected boolean suppressWSmixed =false; /* used to record the number of children of an element during * validation phase. later, when storing the nodes, we already * know the child count and don't need to update the element * a second time. */ private int childCnt[] = new int[0x1000]; // the current position in childCnt private int elementCnt = 0; // reusable fields private TextImpl text = new TextImpl(); private Stack usedElements = new Stack(); /** * Create a new parser using the given database broker and * user to store the document. * *@param broker *@exception EXistException */ public Indexer(DBBroker broker, Txn transaction) throws EXistException { this(broker, transaction, false); } /** * Create a new parser using the given database broker and * user to store the document. * *@param broker The database broker to use. *@param transaction The transaction to use for indexing *@param priv used by the security manager to * indicate that it needs privileged * access to the db. *@exception EXistException */ public Indexer(DBBroker broker, Txn transaction, boolean priv) throws EXistException { this.broker = broker; this.transaction = transaction; Configuration config = broker.getConfiguration(); String suppressWS = (String) config.getProperty("indexer.suppress-whitespace"); if (suppressWS != null) { if (suppressWS.equals("leading")) normalize = XMLString.SUPPRESS_LEADING_WS; else if (suppressWS.equals("trailing")) normalize = XMLString.SUPPRESS_TRAILING_WS; else if (suppressWS.equals("none")) normalize = 0; } Boolean temp; if ((temp = (Boolean) config.getProperty("indexer.preserve-whitespace-mixed-content")) != null) suppressWSmixed = temp.booleanValue(); } public void setValidating(boolean validate) { this.validate = validate; } /** * Prepare the indexer for parsing a new document. This will * reset the internal state of the Indexer object. * * @param doc */ public void setDocument(DocumentImpl doc) { document = doc; // reset internal fields level = 0; currentPath.reset(); stack = new Stack(); nsMappings.clear(); rootNode = null; } /** * Set the document object to be used by this Indexer. This * method doesn't reset the internal state. * * @param doc */ public void setDocumentObject(DocumentImpl doc) { document = doc; } public DocumentImpl getDocument() { return document; } public void characters(char[] ch, int start, int length) { if (length <= 0) return; if (charBuf != null) { charBuf.append(ch, start, length); } else { charBuf = new XMLString(ch, start, length); } } public void comment(char[] ch, int start, int length) { if (insideDTD) return; CommentImpl comment = new CommentImpl(ch, start, length); comment.setOwnerDocument(document); if (stack.empty()) { if (!validate) broker.storeNode(transaction, comment, currentPath); document.appendChild(comment); } else { ElementImpl last = (ElementImpl) stack.peek(); if (charBuf != null && charBuf.length() > 0) { final XMLString normalized = charBuf.normalize(normalize); if (normalized.length() > 0) { text.setData(normalized); text.setOwnerDocument(document); last.appendChildInternal(text); if (!validate) storeText(); } charBuf.reset(); } last.appendChildInternal(comment); if (!validate) broker.storeNode(transaction, comment, currentPath); } } public void endCDATA() { } public void endDTD() { insideDTD = false; } public void endDocument() { if (!validate) { progress.finish(); setChanged(); notifyObservers(progress); } // LOG.debug("elementCnt = " + childCnt.length); } public void endElement(String namespace, String name, String qname) { final ElementImpl last = (ElementImpl) stack.peek(); if (last.getNodeName().equals(qname)) { if (charBuf != null && charBuf.length() > 0) { // remove whitespace if the node has just a single text child, // keep whitespace for mixed content. final XMLString normalized; if (!last.preserveSpace()) { normalized = last.getChildCount() == 0 ? charBuf.normalize(normalize) : (charBuf.isWhitespaceOnly() ? null : charBuf); } else normalized = charBuf; if (normalized != null && normalized.length() > 0) { text.setData(normalized); text.setOwnerDocument(document); last.appendChildInternal(text); if (!validate) storeText(); text.clear(); } charBuf.reset(); } stack.pop(); XMLString elemContent = null; if (GeneralRangeIndexSpec.hasQNameOrValueIndex(last.getIndexType())) { elemContent = (XMLString) nodeContentStack.pop(); } if (!validate) broker.endElement(last, currentPath, elemContent == null ? null : elemContent.toString()); currentPath.removeLastComponent(); if (validate) { if (document.getTreeLevelOrder(level) < last.getChildCount()) { document.setTreeLevelOrder(level, last.getChildCount()); } if (childCnt != null) setChildCount(last); } else { document.setOwnerDocument(document); if (childCnt == null && last.getChildCount() > 0) { broker.updateNode(transaction, last); } } level if (last != rootNode) { last.clear(); usedElements.push(last); } } } /** * @param last */ private void setChildCount(final ElementImpl last) { if (last.getPosition() >= childCnt.length) { int n[] = new int[childCnt.length * 2]; System.arraycopy(childCnt, 0, n, 0, childCnt.length); childCnt = n; } childCnt[last.getPosition()] = last.getChildCount(); } public void endEntity(String name) { } public void endPrefixMapping(String prefix) { if (ignorePrefix != null && prefix.equals(ignorePrefix)) { ignorePrefix = null; } else { nsMappings.remove(prefix); } } public void error(SAXParseException e) throws SAXException { LOG.debug("error at line " + e.getLineNumber(), e); throw new SAXException( "error at line " + e.getLineNumber() + ": " + e.getMessage(), e); } public void fatalError(SAXParseException e) throws SAXException { LOG.debug("fatal error at line " + e.getLineNumber()); throw new SAXException( "fatal error at line " + e.getLineNumber() + ": " + e.getMessage(), e); } public void ignorableWhitespace(char[] ch, int start, int length) { } public void processingInstruction(String target, String data) { ProcessingInstructionImpl pi = new ProcessingInstructionImpl(0, target, data); pi.setOwnerDocument(document); if (stack.isEmpty()) { if (!validate) broker.storeNode(transaction, pi, currentPath); document.appendChild(pi); } else { ElementImpl last = (ElementImpl) stack.peek(); if (charBuf != null && charBuf.length() > 0) { XMLString normalized = charBuf.normalize(normalize); if (normalized.length() > 0) { //TextImpl text = // new TextImpl( normalized ); text.setData(normalized); text.setOwnerDocument(document); last.appendChildInternal(text); if (!validate) storeText(); text.clear(); } charBuf.reset(); } last.appendChildInternal(pi); if (!validate) broker.storeNode(transaction, pi, currentPath); } } public void setDocumentLocator(Locator locator) { this.locator = locator; } /** * set SAX parser feature. This method will catch (and ignore) exceptions * if the used parser does not support a feature. * *@param factory *@param feature *@param value */ private void setFeature( SAXParserFactory factory, String feature, boolean value) { try { factory.setFeature(feature, value); } catch (SAXNotRecognizedException e) { LOG.warn(e); } catch (SAXNotSupportedException snse) { LOG.warn(snse); } catch (ParserConfigurationException pce) { LOG.warn(pce); } } public void skippedEntity(String name) { } public void startCDATA() { } // Methods of interface LexicalHandler // used to determine Doctype public void startDTD(String name, String publicId, String systemId) { DocumentTypeImpl docType = new DocumentTypeImpl(name, publicId, systemId); document.setDocumentType(docType); insideDTD = true; } public void startDocument() { if (!validate) { progress = new ProgressIndicator(currentLine, 100); document.setChildCount(0); elementCnt = 0; } } public void startElement( String namespace, String name, String qname, Attributes attributes) throws SAXException { // calculate number of real attributes: // don't store namespace declarations int attrLength = attributes.getLength(); String attrQName; String attrNS; for (int i = 0; i < attributes.getLength(); i++) { attrNS = attributes.getURI(i); attrQName = attributes.getQName(i); if (attrQName.startsWith("xmlns") || attrNS.equals(Serializer.EXIST_NS)) --attrLength; } ElementImpl last = null; ElementImpl node = null; int p = qname.indexOf(':'); String prefix = (p != Constants.STRING_NOT_FOUND) ? qname.substring(0, p) : ""; QName qn = broker.getSymbols().getQName(Node.ELEMENT_NODE, namespace, name, prefix); if (!stack.empty()) { last = (ElementImpl) stack.peek(); if (charBuf != null) { if(charBuf.isWhitespaceOnly()) { if (suppressWSmixed) { if(charBuf.length() > 0 && last.getChildCount() > 0) { text.setData(charBuf); text.setOwnerDocument(document); last.appendChildInternal(text); if (!validate) storeText(); text.clear(); } } } else if(charBuf.length() > 0) { // mixed element content: don't normalize the text node, just check // if there is any text at all text.setData(charBuf); text.setOwnerDocument(document); last.appendChildInternal(text); if (!validate) storeText(); text.clear(); } charBuf.reset(); } if (!usedElements.isEmpty()) { node = (ElementImpl) usedElements.pop(); node.setNodeName(qn); } else node = new ElementImpl(qn); // copy xml:space setting node.setPreserveSpace(last.preserveSpace()); // append the node to its parent // (computes the node id and updates the parent's child count) last.appendChildInternal(node); node.setOwnerDocument(document); node.setAttributes((short) attrLength); if (nsMappings != null && nsMappings.size() > 0) { node.setNamespaceMappings(nsMappings); nsMappings.clear(); } stack.push(node); currentPath.addComponent(qn); node.setPosition(elementCnt++); if (!validate) { if (childCnt != null) node.setChildCount(childCnt[node.getPosition()]); storeElement(node); } } else { if (validate) node = new ElementImpl(0, qn); else node = new ElementImpl(1, qn); rootNode = node; node.setOwnerDocument(document); node.setAttributes((short) attrLength); if (nsMappings != null && nsMappings.size() > 0) { node.setNamespaceMappings(nsMappings); nsMappings.clear(); } stack.push(node); currentPath.addComponent(qn); node.setPosition(elementCnt++); if (!validate) { if (childCnt != null) node.setChildCount(childCnt[node.getPosition()]); storeElement(node); } document.appendChild(node); } level++; if (document.getMaxDepth() < level) document.setMaxDepth(level); String attrPrefix; String attrLocalName; for (int i = 0; i < attributes.getLength(); i++) { attrNS = attributes.getURI(i); attrLocalName = attributes.getLocalName(i); attrQName = attributes.getQName(i); // skip xmlns-attributes and attributes in eXist's namespace if (attrQName.startsWith("xmlns") || attrNS.equals(Serializer.EXIST_NS)) --attrLength; else { p = attrQName.indexOf(':'); attrPrefix = (p != Constants.STRING_NOT_FOUND) ? attrQName.substring(0, p) : null; final AttrImpl attr = (AttrImpl)NodeObjectPool.getInstance().borrowNode(AttrImpl.class); attr.setNodeName(document.getSymbols().getQName(Node.ATTRIBUTE_NODE, attrNS, attrLocalName, attrPrefix)); attr.setValue(attributes.getValue(i)); attr.setOwnerDocument(document); if (attributes.getType(i).equals(ATTR_ID_TYPE)) { attr.setType(AttrImpl.ID); } else if (attr.getQName().equalsSimple(Namespaces.XML_ID_QNAME)) { // an xml:id attribute. Normalize the attribute and set its type to ID attr.setValue(StringValue.trimWhitespace(StringValue.collapseWhitespace(attr.getValue()))); if (!XMLChar.isValidNCName(attr.getValue())) throw new SAXException("Value of xml:id attribute is not a valid NCName: " + attr.getValue()); attr.setType(AttrImpl.ID); } else if (attr.getQName().equalsSimple(Namespaces.XML_SPACE_QNAME)) { node.setPreserveSpace("preserve".equals(attr.getValue())); } node.appendChildInternal(attr); if (!validate) broker.storeNode(transaction, attr, currentPath); attr.release(); } } if (attrLength > 0) node.setAttributes((short) attrLength); // notify observers about progress every 100 lines if (locator != null) { currentLine = locator.getLineNumber(); if (!validate) { progress.setValue(currentLine); if (progress.changed()) { setChanged(); notifyObservers(progress); } } } } private void storeText() { if (!nodeContentStack.isEmpty()) { for (int i = 0; i < nodeContentStack.size(); i++) { XMLString next = (XMLString) nodeContentStack.get(i); next.append(charBuf); } } broker.storeNode(transaction, text, currentPath); } private void storeElement(ElementImpl node) { broker.storeNode(transaction, node, currentPath); node.setChildCount(0); if (GeneralRangeIndexSpec.hasQNameOrValueIndex(node.getIndexType())) { XMLString contentBuf = new XMLString(); nodeContentStack.push(contentBuf); } } public void startEntity(String name) { } public void startPrefixMapping(String prefix, String uri) { // skip the eXist namespace // ignorePrefix = prefix; // return; nsMappings.put(prefix, uri); } public void warning(SAXParseException e) throws SAXException { LOG.debug("warning at line " + e.getLineNumber(), e); throw new SAXException( "warning at line " + e.getLineNumber() + ": " + e.getMessage(), e); } private static StringBuffer removeLastPathComponent(StringBuffer path) { int i; //TODO : rewrite with subString -pb for(i = path.length() - 1; i >= 0; i if(path.charAt(i) == '/') break; } if(i == Constants.STRING_NOT_FOUND) return path; return path.delete(i, path.length()); } }
package org.nutz.log; import org.nutz.plugin.SimplePluginManager; /** * Log * @author Young(sunonfire@gmail.com) * @author zozoh(zozohtnt@gmail.com) * @author Wendal(wendal1985@gmail.com) */ public final class Logs { private static LogAdapter adapter; static { init(); } /** * Get a Log by Class * * @param clazz * your class * @return Log * @throws NullPointerException * when clazz is null */ public static Log getLog(Class<?> clazz) { return getLog(clazz.getName()); } /** * Get a Log by name * * @param className * the name of Log * @return Log * @throws NullPointerException * when className is null, maybe it will case NPE */ public static Log getLog(String className) { return adapter.getLogger(className); } /** * Log,Log! */ public static Log get() { return adapter.getLogger(Thread.currentThread().getStackTrace()[2].getClassName()); } /** * NutLog,Log,Log * <p/> * <b>,,.</b> * <p/> * <b>,<b/> * <p/> */ public static void init() { try { String packageName = Logs.class.getPackage().getName() + ".impl."; adapter = new SimplePluginManager<LogAdapter>( packageName + "Log4jLogAdapter", packageName + "SystemLogAdapter").get(); } catch (Throwable e) { //,SystemLogAdaptertrue //org.nutz.log.impl.SystemLogAdapter //package e.printStackTrace(); } } }
/* * @test * @bug 6294277 * @summary java -Xdebug crashes on SourceDebugExtension attribute larger than 64K * @run main/othervm -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n SourceDebugExtension */ import java.io.*; public class SourceDebugExtension extends ClassLoader { static final int attrSize = 68000; static byte[] header = { (byte)0xca, (byte)0xfe, (byte)0xba, (byte)0xbe, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x32, (byte)0x00, (byte)0x1e, (byte)0x0a, (byte)0x00, (byte)0x06, (byte)0x00, (byte)0x0f, (byte)0x09, (byte)0x00, (byte)0x10, (byte)0x00, (byte)0x11, (byte)0x08, (byte)0x00, (byte)0x12, (byte)0x0a, (byte)0x00, (byte)0x13, (byte)0x00, (byte)0x14, (byte)0x07, (byte)0x00, (byte)0x15, (byte)0x07, (byte)0x00, (byte)0x16, (byte)0x01, (byte)0x00, (byte)0x06, (byte)0x3c, (byte)0x69, (byte)0x6e, (byte)0x69, (byte)0x74, (byte)0x3e, (byte)0x01, (byte)0x00, (byte)0x03, (byte)0x28, (byte)0x29, (byte)0x56, (byte)0x01, (byte)0x00, (byte)0x04, (byte)0x43, (byte)0x6f, (byte)0x64, (byte)0x65, (byte)0x01, (byte)0x00, (byte)0x0f, (byte)0x4c, (byte)0x69, (byte)0x6e, (byte)0x65, (byte)0x4e, (byte)0x75, (byte)0x6d, (byte)0x62, (byte)0x65, (byte)0x72, (byte)0x54, (byte)0x61, (byte)0x62, (byte)0x6c, (byte)0x65, (byte)0x01, (byte)0x00, (byte)0x04, (byte)0x6d, (byte)0x61, (byte)0x69, (byte)0x6e, (byte)0x01, (byte)0x00, (byte)0x16, (byte)0x28, (byte)0x5b, (byte)0x4c, (byte)0x6a, (byte)0x61, (byte)0x76, (byte)0x61, (byte)0x2f, (byte)0x6c, (byte)0x61, (byte)0x6e, (byte)0x67, (byte)0x2f, (byte)0x53, (byte)0x74, (byte)0x72, (byte)0x69, (byte)0x6e, (byte)0x67, (byte)0x3b, (byte)0x29, (byte)0x56, (byte)0x01, (byte)0x00, (byte)0x0a, (byte)0x53, (byte)0x6f, (byte)0x75, (byte)0x72, (byte)0x63, (byte)0x65, (byte)0x46, (byte)0x69, (byte)0x6c, (byte)0x65, (byte)0x01, (byte)0x00, (byte)0x0d, (byte)0x54, (byte)0x65, (byte)0x73, (byte)0x74, (byte)0x50, (byte)0x72, (byte)0x6f, (byte)0x67, (byte)0x2e, (byte)0x6a, (byte)0x61, (byte)0x76, (byte)0x61, (byte)0x0c, (byte)0x00, (byte)0x07, (byte)0x00, (byte)0x08, (byte)0x07, (byte)0x00, (byte)0x17, (byte)0x0c, (byte)0x00, (byte)0x18, (byte)0x00, (byte)0x19, (byte)0x01, (byte)0x00, (byte)0x34, (byte)0x54, (byte)0x65, (byte)0x73, (byte)0x74, (byte)0x20, (byte)0x70, (byte)0x72, (byte)0x6f, (byte)0x67, (byte)0x72, (byte)0x61, (byte)0x6d, (byte)0x20, (byte)0x66, (byte)0x6f, (byte)0x72, (byte)0x20, (byte)0x62, (byte)0x69, (byte)0x67, (byte)0x20, (byte)0x53, (byte)0x6f, (byte)0x75, (byte)0x72, (byte)0x63, (byte)0x65, (byte)0x44, (byte)0x65, (byte)0x62, (byte)0x75, (byte)0x67, (byte)0x45, (byte)0x78, (byte)0x74, (byte)0x65, (byte)0x6e, (byte)0x73, (byte)0x69, (byte)0x6f, (byte)0x6e, (byte)0x20, (byte)0x61, (byte)0x74, (byte)0x74, (byte)0x72, (byte)0x69, (byte)0x62, (byte)0x75, (byte)0x74, (byte)0x65, (byte)0x73, (byte)0x07, (byte)0x00, (byte)0x1a, (byte)0x0c, (byte)0x00, (byte)0x1b, (byte)0x00, (byte)0x1c, (byte)0x01, (byte)0x00, (byte)0x08, (byte)0x54, (byte)0x65, (byte)0x73, (byte)0x74, (byte)0x50, (byte)0x72, (byte)0x6f, (byte)0x67, (byte)0x01, (byte)0x00, (byte)0x10, (byte)0x6a, (byte)0x61, (byte)0x76, (byte)0x61, (byte)0x2f, (byte)0x6c, (byte)0x61, (byte)0x6e, (byte)0x67, (byte)0x2f, (byte)0x4f, (byte)0x62, (byte)0x6a, (byte)0x65, (byte)0x63, (byte)0x74, (byte)0x01, (byte)0x00, (byte)0x10, (byte)0x6a, (byte)0x61, (byte)0x76, (byte)0x61, (byte)0x2f, (byte)0x6c, (byte)0x61, (byte)0x6e, (byte)0x67, (byte)0x2f, (byte)0x53, (byte)0x79, (byte)0x73, (byte)0x74, (byte)0x65, (byte)0x6d, (byte)0x01, (byte)0x00, (byte)0x03, (byte)0x6f, (byte)0x75, (byte)0x74, (byte)0x01, (byte)0x00, (byte)0x15, (byte)0x4c, (byte)0x6a, (byte)0x61, (byte)0x76, (byte)0x61, (byte)0x2f, (byte)0x69, (byte)0x6f, (byte)0x2f, (byte)0x50, (byte)0x72, (byte)0x69, (byte)0x6e, (byte)0x74, (byte)0x53, (byte)0x74, (byte)0x72, (byte)0x65, (byte)0x61, (byte)0x6d, (byte)0x3b, (byte)0x01, (byte)0x00, (byte)0x13, (byte)0x6a, (byte)0x61, (byte)0x76, (byte)0x61, (byte)0x2f, (byte)0x69, (byte)0x6f, (byte)0x2f, (byte)0x50, (byte)0x72, (byte)0x69, (byte)0x6e, (byte)0x74, (byte)0x53, (byte)0x74, (byte)0x72, (byte)0x65, (byte)0x61, (byte)0x6d, (byte)0x01, (byte)0x00, (byte)0x07, (byte)0x70, (byte)0x72, (byte)0x69, (byte)0x6e, (byte)0x74, (byte)0x6c, (byte)0x6e, (byte)0x01, (byte)0x00, (byte)0x15, (byte)0x28, (byte)0x4c, (byte)0x6a, (byte)0x61, (byte)0x76, (byte)0x61, (byte)0x2f, (byte)0x6c, (byte)0x61, (byte)0x6e, (byte)0x67, (byte)0x2f, (byte)0x53, (byte)0x74, (byte)0x72, (byte)0x69, (byte)0x6e, (byte)0x67, (byte)0x3b, (byte)0x29, (byte)0x56, (byte)0x01, (byte)0x00, (byte)0x14, (byte)0x53, (byte)0x6f, (byte)0x75, (byte)0x72, (byte)0x63, (byte)0x65, (byte)0x44, (byte)0x65, (byte)0x62, (byte)0x75, (byte)0x67, (byte)0x45, (byte)0x78, (byte)0x74, (byte)0x65, (byte)0x6e, (byte)0x73, (byte)0x69, (byte)0x6f, (byte)0x6e, (byte)0x00, (byte)0x21, (byte)0x00, (byte)0x05, (byte)0x00, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x02, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x07, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x09, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x1d, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x05, (byte)0x2a, (byte)0xb7, (byte)0x00, (byte)0x01, (byte)0xb1, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x0a, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x09, (byte)0x00, (byte)0x0b, (byte)0x00, (byte)0x0c, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x09, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x25, (byte)0x00, (byte)0x02, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x09, (byte)0xb2, (byte)0x00, (byte)0x02, (byte)0x12, (byte)0x03, (byte)0xb6, (byte)0x00, (byte)0x04, (byte)0xb1, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x0a, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0a, (byte)0x00, (byte)0x02, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x03, (byte)0x00, (byte)0x08, (byte)0x00, (byte)0x04, (byte)0x00, (byte)0x02, (byte)0x00, (byte)0x0d, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x02, (byte)0x00, (byte)0x0e, (byte)0x00, (byte)0x1d, (byte)0x00, (byte)0x01, (byte)0x09, (byte)0xa0 }; public static void main(String[] args) throws Exception { try { SourceDebugExtension loader = new SourceDebugExtension(); /* The test program creates a class file from the header * stored above and adding the content of a SourceDebugExtension * attribute made of the character 0x02 repeated 68000 times. * This attribute doesn't follow the syntax specified in JSR 45 * but it's fine because this test just checks that the JVM is * able to load a class file with a SourceDebugExtension * attribute bigger than 64KB. The JVM doesn't try to * parse the content of the attribute, this work is performed * by the SA or external tools. */ byte[] buf = new byte[header.length + attrSize]; for(int i=0; i<header.length; i++) { buf[i] = header[i]; } for(int i=0; i<attrSize; i++) { buf[header.length+i] = (byte)0x02; } Class c = loader.defineClass("TestProg", buf, 0, buf.length); System.out.println("Test PASSES"); } catch(Exception e) { System.out.println("Test FAILS"); } } }
package hudson.model; import java.io.File; import java.util.Arrays; import hudson.Util; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Rule; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockFolder; public class ItemsTest { @Rule public JenkinsRule r = new JenkinsRule(); @Test public void getAllItems() throws Exception { MockFolder d = r.createFolder("d"); MockFolder sub2 = d.createProject(MockFolder.class, "sub2"); MockFolder sub2a = sub2.createProject(MockFolder.class, "a"); MockFolder sub2c = sub2.createProject(MockFolder.class, "c"); MockFolder sub2b = sub2.createProject(MockFolder.class, "b"); MockFolder sub1 = d.createProject(MockFolder.class, "sub1"); FreeStyleProject root = r.createFreeStyleProject("root"); FreeStyleProject dp = d.createProject(FreeStyleProject.class, "p"); FreeStyleProject sub1q = sub1.createProject(FreeStyleProject.class, "q"); FreeStyleProject sub1p = sub1.createProject(FreeStyleProject.class, "p"); FreeStyleProject sub2ap = sub2a.createProject(FreeStyleProject.class, "p"); FreeStyleProject sub2bp = sub2b.createProject(FreeStyleProject.class, "p"); FreeStyleProject sub2cp = sub2c.createProject(FreeStyleProject.class, "p"); FreeStyleProject sub2alpha = sub2.createProject(FreeStyleProject.class, "alpha"); FreeStyleProject sub2BRAVO = sub2.createProject(FreeStyleProject.class, "BRAVO"); FreeStyleProject sub2charlie = sub2.createProject(FreeStyleProject.class, "charlie"); assertEquals(Arrays.asList(dp, sub1p, sub1q, sub2ap, sub2alpha, sub2bp, sub2BRAVO, sub2cp, sub2charlie), Items.getAllItems(d, FreeStyleProject.class)); assertEquals(Arrays.<Item>asList(sub2a, sub2ap, sub2alpha, sub2b, sub2bp, sub2BRAVO, sub2c, sub2cp, sub2charlie), Items.getAllItems(sub2, Item.class)); } @Issue("JENKINS-24825") @Test public void moveItem() throws Exception { File tmp = Util.createTempDir(); r.jenkins.setRawBuildsDir(tmp.getAbsolutePath()+"/${ITEM_FULL_NAME}"); MockFolder foo = r.createFolder("foo"); MockFolder bar = r.createFolder("bar"); FreeStyleProject test = foo.createProject(FreeStyleProject.class, "test"); test.scheduleBuild2(0).get(); Items.move(test, bar); assertFalse(new File(tmp, "foo/test/1").exists()); assertTrue(new File(tmp, "bar/test/1").exists()); } }
package mod._sc; import java.io.PrintWriter; import lib.StatusException; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; import util.SOfficeFactory; import com.sun.star.beans.XPropertySet; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.sheet.XLabelRange; import com.sun.star.sheet.XLabelRanges; import com.sun.star.sheet.XSpreadsheetDocument; import com.sun.star.table.CellRangeAddress; import com.sun.star.uno.AnyConverter; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; /** * Test for object which is represented by service * <code>com.sun.star.sheet.LabelRange</code>. <p> * Object implements the following interfaces : * <ul> * <li> <code>com::sun::star::sheet::XLabelRange</code></li> * </ul> * @see com.sun.star.sheet.LabelRange * @see com.sun.star.sheet.XLabelRange * @see ifc.sheet._XLabelRange */ public class ScLabelRangeObj extends TestCase { XSpreadsheetDocument xSheetDoc = null; /** * Creates Spreadsheet document. */ protected void initialize( TestParameters tParam, PrintWriter log ) { // get a soffice factory object SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)tParam.getMSF()); try { log.println( "creating a sheetdocument" ); xSheetDoc = SOF.createCalcDoc(null);; } catch (com.sun.star.uno.Exception e) { // Some exception occures.FAILED e.printStackTrace( log ); throw new StatusException( "Couldn't create document", e ); } } /** * Disposes Spreadsheet document. */ protected void cleanup( TestParameters tParam, PrintWriter log ) { log.println( " disposing xSheetDoc " ); XComponent oComp = (XComponent) UnoRuntime.queryInterface (XComponent.class, xSheetDoc) ; util.DesktopTools.closeDoc(oComp); } /** * Creating a Testenvironment for the interfaces to be tested. * Obtains the value of the property <code>'ColumnLabelRanges'</code> * from the document. The property value is the collection of label ranges. * Adds new label range to the collection using the interface * <code>XLabelRanges</code> that was queried from the property value. * Retrieved from the collection the label range with index 0. * The retrieved label range is the instance of the service * <code>com.sun.star.sheet.LabelRange</code>. * @see com.sun.star.sheet.LabelRange * @see com.sun.star.sheet.XLabelRanges */ protected synchronized TestEnvironment createTestEnvironment(TestParameters Param, PrintWriter log) { XInterface oObj = null; // creation of testobject here // first we write what we are intend to do to log file log.println( "Creating a test environment" ); try { log.println("Getting test object ") ; XPropertySet docProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xSheetDoc); Object ranges = docProps.getPropertyValue("ColumnLabelRanges"); XLabelRanges lRanges = (XLabelRanges) UnoRuntime.queryInterface(XLabelRanges.class, ranges); log.println("Adding at least one element for ElementAccess interface"); CellRangeAddress aRange2 = new CellRangeAddress((short)0, 0, 1, 0, 6); CellRangeAddress aRange1 = new CellRangeAddress((short)0, 0, 0, 0, 1); lRanges.addNew(aRange1, aRange2); oObj = (XLabelRange) AnyConverter.toObject( new Type(XLabelRange.class),lRanges.getByIndex(0)); } catch (com.sun.star.lang.WrappedTargetException e) { e.printStackTrace(log) ; throw new StatusException( "Error getting test object from spreadsheet document",e) ; } catch (com.sun.star.lang.IndexOutOfBoundsException e) { e.printStackTrace(log) ; throw new StatusException( "Error getting test object from spreadsheet document",e) ; } catch (com.sun.star.beans.UnknownPropertyException e) { e.printStackTrace(log) ; throw new StatusException( "Error getting test object from spreadsheet document",e) ; } catch (com.sun.star.lang.IllegalArgumentException e) { e.printStackTrace(log) ; throw new StatusException( "Error getting test object from spreadsheet document",e) ; } log.println("creating a new environment for object"); TestEnvironment tEnv = new TestEnvironment(oObj); log.println("testing..."); return tEnv; } // finish method getTestEnvironment } // finish class ScLabelRangeObj
/** @author Rupam Bhattacharyya */ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import org.semanticweb.owlapi.model.OWLOntologyCreationException; public class DeductionModule{ public String[] relationManager(String trainFileName, String objNames[], String jointPos[], int l, String rawTDS, String parentPath) throws OWLOntologyCreationException, IOException { System.out.println("Inside Deduction module: "+trainFileName); int flag1=0; int flagMatch=0; //Remember that the path of trainFileName may be changed; so that Alchemy can reach it. PrintWriter writer=new PrintWriter(trainFileName); String loadedOntoFeature[]=new String[11]; for(int i=0;i<objNames.length;i++){ System.out.println("Obj Name-->"+objNames[i]); OntologyProcessingModule o=new OntologyProcessingModule(); loadedOntoFeature=o.getObjectProperty(objNames[i]); for(int ni=0; ni<objNames.length;ni++){ if(objNames.length>1){ for(int nj=1;nj<objNames.length;nj++){ if(objNames[ni].equals(objNames[nj])){ System.out.println("Carry On..Match found"); flagMatch=1; } else break; } System.out.println("*****"); } else{ flag1=1; break; } } if(flagMatch==1 && flag1==0){ for(int k=0; k<objNames.length;k++){ //objNames[k]=objNames[k]+k; } } for(int kk=0; kk<objNames.length; kk++){ System.out.println(objNames[kk]); } String upperCase; for(int k=0;k<(loadedOntoFeature.length-3);k++){ System.out.println("Fired query result-->"+loadedOntoFeature[k]); if((loadedOntoFeature[k]).equals("[NONE]")){ } else{ if(k==0){ // Added for Box to Box1 if(flagMatch==1 && flag1==0) upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1)+i; else upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1); //writer.print(loadedOntoFeature[k]+"("+objNames[i]+")"); writer.print(loadedOntoFeature[k]+"("+upperCase+")"); writer.print("\n"); } else if(k==1){ if(flagMatch==1 && flag1==0) upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1)+i; else upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1); //writer.print(loadedOntoFeature[k]+"("+objNames[i]+")"); writer.print(loadedOntoFeature[k]+"("+upperCase+")"); writer.print("\n"); } else if(k==2){ if(flagMatch==1 && flag1==0) upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1)+i; else upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1); //writer.print(loadedOntoFeature[k]+"("+objNames[i]+")"); writer.print(loadedOntoFeature[k]+"("+upperCase+")"); writer.print("\n"); } else if(k==3){ if(flagMatch==1 && flag1==0) upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1)+i; else upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1); //writer.print(loadedOntoFeature[k]+"("+objNames[i]+")"); writer.print(loadedOntoFeature[k]+"("+upperCase+")"); writer.print("\n"); } else if(k==4){ if(flagMatch==1 && flag1==0) upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1)+i; else upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1); //writer.print("hasBaseConcavity("+objNames[i]+","+loadedOntoFeature[k]+")"); writer.print("hasBaseConcavity("+upperCase+","+"\""+loadedOntoFeature[k]+"\""+")"); writer.print("\n"); } else if(k==5){ if(flagMatch==1 && flag1==0) upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1)+i; else upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1); writer.print("hasImmovablePart("+upperCase+","+" "+loadedOntoFeature[k]+")"); writer.print("\n"); } else if(k==6){ if(flagMatch==1 && flag1==0) upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1)+i; else upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1); writer.print("hasDetachablePart("+upperCase+","+" "+loadedOntoFeature[k]+")"); writer.print("\n"); } else if(k==7){ if(flagMatch==1 && flag1==0) upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1)+i; else upperCase=objNames[i].substring(0, 1).toUpperCase() + objNames[i].substring(1); writer.print("hasNonDetachablePart("+upperCase+","+" "+loadedOntoFeature[k]+")"); writer.print("\n"); } } } } String recvdCornerObjPos[]=new String[12]; String fourCornerObjPos[]=new String[5]; String lowerToUpperCase; int cornerCount=0; for(int m=0; m<objNames.length; m++){ VideoProcessingModule v=new VideoProcessingModule(); recvdCornerObjPos=v.calculateCentroid(l, m, objNames, rawTDS, parentPath); //Storing for(int mm=2; mm<6;mm++){ System.out.println("corners of obj-->"+recvdCornerObjPos[mm]); fourCornerObjPos[cornerCount]=recvdCornerObjPos[mm]; cornerCount++; } cornerCount=0; //Actual centroid double xPos1=Double.parseDouble(fourCornerObjPos[0]); double xPos2=Double.parseDouble(fourCornerObjPos[2]); double yPos1=Double.parseDouble(fourCornerObjPos[1]); double yPos2=Double.parseDouble(fourCornerObjPos[3]); double centroidX=(xPos1+xPos2)/2; double centroidY=(yPos1+yPos2)/2; System.out.println("Centroid X pos-->"+centroidX); System.out.println("Centroid Y pos-->"+centroidY); //Extracting information from 4 Joint Pos given in jointPos[] for(int n=0; n<jointPos.length;n++){ System.out.println("\nJoint positions "+jointPos[n]); } System.out.println("jointPos[] length-->"+jointPos.length); Double firstRelX=Double.parseDouble(jointPos[0])-centroidX; Double firstRelY=Double.parseDouble(jointPos[1])-centroidY; Double distance1=Math.hypot(firstRelX, firstRelY); if(distance1>400.00 && distance1<=800.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); writer.print("Near("+lowerToUpperCase+", HEAD)"); } else if(distance1>200.00 && distance1<=400.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); writer.print("Near("+lowerToUpperCase+", HEAD)"); } else if(distance1>100.00 && distance1<=200.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); writer.print("Touch("+lowerToUpperCase+", HEAD)"); } else if(distance1>=0.00 && distance1<=100.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //writer.print("Touch("+objNames[m]+", HEAD)"); writer.print("Touch("+lowerToUpperCase+", HEAD)"); } //Added to see why the blank lines in Train file appears. else{ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); // Since Ignore has been dropped from MLN; we need to rename "ignore" as the new "Far". (09/01/2017) writer.print("Medium("+lowerToUpperCase+", HEAD)"); } writer.print("\n"); System.out.println("Distance between head and box-->"+distance1); firstRelX=Double.parseDouble(jointPos[3])-centroidX; firstRelY=Double.parseDouble(jointPos[4])-centroidY; Double distance2=Math.hypot(firstRelX, firstRelY); System.out.println("Distance between Torso and box-->"+distance2); if(distance2>400.00 && distance2<=800.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); writer.print("Near("+lowerToUpperCase+", TORSO)"); } else if(distance2>200.00 && distance1<=400.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); writer.print("Near("+lowerToUpperCase+", TORSO)"); } else if(distance2>100.00 && distance2<=200.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); writer.print("Touch("+lowerToUpperCase+", TORSO)"); } else if(distance2>=0.00 && distance2<=100.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //writer.print("Touch("+objNames[m]+", TORSO)"); writer.print("Touch("+lowerToUpperCase+", TORSO)"); } //Added to see why the blank lines in Train file appears. else{ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); writer.print("Medium("+lowerToUpperCase+", TORSO)"); } writer.print("\n"); firstRelX=Double.parseDouble(jointPos[6])-centroidX; firstRelY=Double.parseDouble(jointPos[7])-centroidY; Double distance3=Math.hypot(firstRelX, firstRelY); System.out.println("Distance between Left Hand and box-->"+distance3); if(distance3>400.00 && distance3<=800.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); writer.print("Near("+lowerToUpperCase+", LHAND)"); } else if(distance3>200.00 && distance3<=400.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); writer.print("Near("+lowerToUpperCase+", LHAND)"); } else if(distance3>100.00 && distance3<=200.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); writer.print("Touch("+lowerToUpperCase+", LHAND)"); } else if(distance3>=0.00 && distance3<=100.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //writer.print("Touch("+objNames[m]+", LHAND)"); writer.print("Touch("+lowerToUpperCase+", LHAND)"); } //Added to see why the blank lines in Train file appears. else{ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); writer.print("Medium("+lowerToUpperCase+", LHAND)"); } writer.print("\n"); firstRelX=Double.parseDouble(jointPos[9])-centroidX; firstRelY=Double.parseDouble(jointPos[10])-centroidY; Double distance4=Math.hypot(firstRelX, firstRelY); System.out.println("Distance between Right Hand and box-->"+distance4); if(distance4>400.00 && distance4<=800.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); writer.print("Near("+lowerToUpperCase+", RHAND)"); } else if(distance4>200.00 && distance4<=400.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); writer.print("Near("+lowerToUpperCase+", RHAND)"); } else if(distance4>100.00 && distance4<=200.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); writer.print("Touch("+lowerToUpperCase+", RHAND)"); } else if(distance4>=0.00 && distance4<=100.00){ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //writer.print("Touch("+objNames[m]+", RHAND)"); writer.print("Touch("+lowerToUpperCase+", RHAND)"); } //Added to see why the blank lines in Train file appears. else{ if(flagMatch==1 && flag1==0) lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1)+m; else lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); //lowerToUpperCase=objNames[m].substring(0, 1).toUpperCase() + objNames[m].substring(1); writer.print("Medium("+lowerToUpperCase+", RHAND)"); } writer.print("\n"); } int n=objNames.length; int r=2; // Now, we need to prevent calculations related to o-o relations when there is a single object.\ int flag=0; long res=1; if(n>=r) { res=getFact(n)/(getFact(n-r)*getFact(r)); System.out.println("The result is *********---->"+res); } else{ System.out.println("r cannot be greater than n"); flag=1; } String returnRelName1[]=new String[(int) res]; returnRelName1=objRelFinder(l, objNames, rawTDS, parentPath); for(int p=0;p<returnRelName1.length;p++){ if(flag!=1){ writer.print(returnRelName1[p]); writer.print("\n"); } } writer.close(); return null; } public String[] objRelFinder(int l, String[] objNames, String rawTDS, String parentPath) throws IOException { // calculate nC2 where n is the total objects in objNames[]
package ICC; import java.util.Scanner; import javax.swing.JOptionPane; /** * * @author adm_nayronseilert */ public class VetorICC { public static void main(String args[]) { Scanner ler = new Scanner(System.in); int[] vetorUM = new int[3]; int[] vetorDois = new int[3]; int[] vetorTres = new int[6]; int i; int pos_Impar = 1; int pos_par = 2; for ( i = 0; i <2; i++) { System.out.println("Vetor 1 "); vetorUM[i] = ler.nextInt(); vetorTres[pos_Impar] = vetorUM[i]; pos_Impar = pos_Impar+2; System.out.println("vetor 2 "); vetorDois[i] = ler.nextInt(); vetorTres[pos_par] = vetorDois[i]; pos_par=pos_par+2; } for( i = 1;i<=4;i++){ if(i % 2 == 0) { System.err.println("vetor A - " + vetorTres[i]); }else{ System.err.println("vetor B - " + vetorTres[i]); } } } }
package io.khasang.wlogs.controller; import io.khasang.wlogs.model.InsertDataTable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class AppController { @RequestMapping("/") public String welcome(Model model) { model.addAttribute("greeting", "Welcome to our best wLogs!"); model.addAttribute("tagline", "The one and only amazing logs system!"); return "welcome"; } @RequestMapping("/backup") public String backup(Model model) { model.addAttribute("backup", "Success"); return "backup"; } @RequestMapping("/admin") public String admin(Model model) { model.addAttribute("admin", "You are number 1!"); return "admin"; } @RequestMapping("/createtable") public String crateTable(Model model) { InsertDataTable sql = new InsertDataTable(); model.addAttribute("createtable", sql.sqlInsertCheck()); return "createtable"; } @RequestMapping("/mainmenu") public String mainMenu(Model model) { return "mainmenu"; } }
package com.armandgray.shared.model; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.ForeignKey; import androidx.room.Ignore; import androidx.room.Index; import androidx.room.PrimaryKey; import androidx.room.TypeConverters; import static androidx.room.ForeignKey.CASCADE; @Entity(tableName = "performances", indices = @Index("drill_title"), foreignKeys = @ForeignKey( entity = Drill.class, parentColumns = "title", childColumns = "drill_title", onUpdate = CASCADE, onDelete = CASCADE)) public class Performance implements Comparable<Performance> { @PrimaryKey(autoGenerate = true) private int id; @SuppressWarnings("NullableProblems") @ColumnInfo(name = "drill_title") @NonNull private String drillTitle; private int count; private int total; private int reps; private double goal; @Nullable @TypeConverters(WorkoutLocation.Converter.class) private WorkoutLocation location; @ColumnInfo(name = "start_time") private long startTime; @ColumnInfo(name = "end_time") private long endTime; public Performance() { // Default Constructor For Room Object Creation } @Ignore public Performance(@NonNull Drill drill) { this.drillTitle = drill.getTitle(); this.count = 0; this.total = 0; this.reps = drill.getReps(); this.goal = drill.getGoal(); this.location = new WorkoutLocation("YMCA Embarcadero"); captureStartTime(); captureEndTime(); } @Ignore public Performance(@NonNull Performance clone) { this.id = clone.id; this.drillTitle = clone.drillTitle; this.count = clone.count; this.total = clone.total; this.reps = clone.reps; this.goal = clone.goal; this.location = clone.location; this.startTime = clone.startTime; this.endTime = clone.endTime; } public int getId() { return id; } @NonNull public String getDrillTitle() { return drillTitle; } public int getCount() { return this.count; } public int getTotal() { return this.total; } public int getReps() { return this.reps; } public double getGoal() { return this.goal; } @SuppressWarnings("WeakerAccess") // VisibleForRoom @Nullable public WorkoutLocation getLocation() { return this.location; } public long getStartTime() { return startTime; } public long getEndTime() { return endTime; } public long getLength() { return endTime % startTime; } public float getRate() { return (float) count / total; } public void raiseCount() { this.count++; } public void raiseTotal() { if (this.total == 0) { captureStartTime(); } this.total++; } public boolean isSuccess() { return (double) this.count / this.total >= this.goal; } public void setId(int id) { this.id = id; } public void setDrillTitle(@NonNull String drillTitle) { this.drillTitle = drillTitle; } public void setCount(int count) { this.count = count; } public void setTotal(int total) { this.total = total; } public void setReps(int reps) { this.reps = reps; } public void setGoal(double goal) { this.goal = goal; } public void setLocation(@NonNull WorkoutLocation location) { this.location = location; } public void setStartTime(long startTime) { this.startTime = startTime; } public void setEndTime(long endTime) { this.endTime = endTime; } private void captureStartTime() { this.startTime = System.currentTimeMillis(); } public void captureEndTime() { this.endTime = System.currentTimeMillis(); } public void clear() { this.count = 0; this.total = 0; } @Override public int compareTo(Performance that) { return that == null ? 1 : Long.compare(that.startTime, this.startTime); } @NonNull @Override public String toString() { String length = new SimpleDateFormat("mm:ss.SSS", Locale.getDefault()) .format(new Date(getLength())); return String.format(Locale.getDefault(), "Performance(%d){%s: %d/%d(%.2f) for %s}", id, drillTitle, count, total, getRate(), length); } }
package org.jetel.component; import java.io.IOException; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.data.RecordKey; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.XMLConfigurationException; import org.jetel.exception.ConfigurationStatus.Priority; import org.jetel.exception.ConfigurationStatus.Severity; import org.jetel.graph.InputPort; import org.jetel.graph.Node; import org.jetel.graph.OutputPort; import org.jetel.graph.Result; import org.jetel.graph.TransformationGraph; import org.jetel.util.property.ComponentXMLAttributes; import org.jetel.util.string.StringUtils; import org.w3c.dom.Element; /** * <h3>Merge Component</h3> <!-- Merges data records from two input ports onto * one output. It preserves sorted order (as specified by the merge key) * The structure of records in all merged data flows must be the same - it implies * that all input ports share the same metadata --> * * <table border="1"> * <th>Component:</th> * <tr><td><h4><i>Name:</i></h4></td> * <td>Merge</td></tr> * <tr><td><h4><i>Category:</i></h4></td> * <td></td></tr> * <tr><td><h4><i>Description:</i></h4></td> * <td>Merges data records from two input ports onto * one output. It preserves sorted order (as specified by the merge key)<br> * The structure of records in all merged data flows must be the same - it implies * that all input ports share the same metadata.</td></tr> * <tr><td><h4><i>Inputs:</i></h4></td> * <td>[0..n]- input records (min 2 ports active)</td></tr> * <tr><td><h4><i>Outputs:</i></h4></td> * <td>[0] - one output port</td></tr> * <tr><td><h4><i>Comment:</i></h4></td> * <td></td></tr> * </table> * <br> * <table border="1"> * <th>XML attributes:</th> * <tr><td><b>type</b></td><td>"MERGE"</td></tr> * <tr><td><b>id</b></td><td>component identification</td> * <tr><td><b>mergeKey</b></td><td>key which specifies the sort order to be preserved while merging</td> * </tr> * </table> * * <h4>Example:</h4> * <pre>&lt;Node id="MERGE" type="MERGE" mergeKey="name"/&gt;</pre> * * @author dpavlis * @since April 22, 2003 * @revision $Revision$ * @created 22. duben 2003 */ public class Merge extends Node { public final static String COMPONENT_TYPE = "MERGE"; private static final String XML_MERGEKEY_ATTRIBUTE = "mergeKey"; private static final String XML_EQUAL_NULL_ATTRIBUTE = "equalNULL"; private final static int WRITE_TO_PORT = 0; private DataRecord[] inputRecords; private String[] mergeKeys; private RecordKey comparisonKey; private boolean equalNULL = false; //this default value should be changed to 'true' - issue /** * Constructor for the Merge object * * @param id Description of the Parameter * @param mergeKeys Description of the Parameter */ public Merge(String id, String[] mergeKeys) { super(id); this.mergeKeys = mergeKeys; } /** * Gets the first open/active port starting at specified index. * This is auxiliary function to simplify process of seeking * next port from which data can be read. * * @param isEOF Description of the Parameter * @param from Description of the Parameter * @return The firstOpen value */ private int getNextOpen(boolean[] isEOF, int from) { for (int i = from; i < isEOF.length; i++) { if (!isEOF[i]) { return i; } } return -1; } /** * From all input ports defined, selects the record whose * value (based on defined key) is lowest. It then returns * the index of that port * * @param inputRecords Description of the Parameter * @param isEOF Description of the Parameter * @return The lowestRecIndex value */ private int getLowestRecIndex(DataRecord[] inputRecords, boolean[] isEOF) { int lowest; int compareTo; if ((lowest = getNextOpen(isEOF, 0)) == -1) { return -1; } compareTo = getNextOpen(isEOF, lowest + 1); while (compareTo < isEOF.length && compareTo != -1) { if (comparisonKey.compare(inputRecords[lowest], inputRecords[compareTo]) == 1) { lowest = compareTo;// we have new lowest } compareTo = getNextOpen(isEOF, compareTo + 1); } return lowest; } /** * First time reads data from all input ports * * @param inputRecords Description of the Parameter * @param inPorts Description of the Parameter * @param isEOF Description of the Parameter * @return Description of the Return Value * @exception IOException Description of the Exception * @exception InterruptedException Description of the Exception */ private int populateRecords(DataRecord[] inputRecords, InputPort[] inPorts, boolean[] isEOF) throws IOException, InterruptedException { int numActive = 0; for (int i = 0; i < inPorts.length; i++) { if (inPorts[i].readRecord(inputRecords[i]) == null) { isEOF[i] = true; } else { numActive++; } } return numActive; } @Override public Result execute() throws Exception { /* * we need to keep track of all input ports - if they contain data or * signalized that they are empty. */ InputPort inPorts[]; OutputPort outPort = getOutputPort(WRITE_TO_PORT); int numActive;// counter of still active ports - those without EOF status int index; //get array of all input ports defined/connected - use collection Collection - getInPorts(); inPorts = (InputPort[]) getInPorts().toArray(new InputPort[0]); //create array holding incoming records inputRecords = new DataRecord[inPorts.length]; boolean[] isEOF = new boolean[inPorts.length]; for (int i = 0; i < isEOF.length; i++) { isEOF[i] = false; } // initialize array of data records (for each input port one) for (int i = 0; i < inPorts.length; i++) { inputRecords[i] = new DataRecord(inPorts[i].getMetadata()); inputRecords[i].init(); } // initially load in records from all connected inputs numActive = populateRecords(inputRecords, inPorts, isEOF); // main merging loop - till there is some open port, try to // read and merge data from it while (runIt && numActive > 0) { index = getLowestRecIndex(inputRecords, isEOF); if (index != -1) { outPort.writeRecord(inputRecords[index]); inputRecords[index] = inPorts[index] .readRecord(inputRecords[index]); if (inputRecords[index] == null) { numActive isEOF[index] = true; } } } setEOF(WRITE_TO_PORT); return runIt ? Result.FINISHED_OK : Result.ABORTED; } /** * Description of the Method * * @exception ComponentNotReadyException Description of the Exception * @since April 4, 2002 */ public void init() throws ComponentNotReadyException { if(isInitialized()) return; super.init(); // initialize key comparisonKey = new RecordKey(mergeKeys, getInputPort(0).getMetadata()); comparisonKey.setEqualNULLs(equalNULL); try { comparisonKey.init(); } catch (Exception e) { throw new ComponentNotReadyException(this, XML_MERGEKEY_ATTRIBUTE, e.getMessage()); } } /** * Description of the Method * * @return Description of the Returned Value * @since May 21, 2002 */ public void toXML(Element xmlElement) { super.toXML(xmlElement); String mKeys = mergeKeys[0]; for (int i=1; i< mergeKeys.length; i++) { mKeys += Defaults.Component.KEY_FIELDS_DELIMITER + mergeKeys[i]; } xmlElement.setAttribute(XML_MERGEKEY_ATTRIBUTE, mKeys); // equal NULL attribute xmlElement.setAttribute(XML_EQUAL_NULL_ATTRIBUTE, String.valueOf(equalNULL)); } /** * Description of the Method * * @param nodeXML Description of Parameter * @return Description of the Returned Value * @since May 21, 2002 */ public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph); try { Merge merge = new Merge(xattribs.getString(XML_ID_ATTRIBUTE), xattribs.getString(XML_MERGEKEY_ATTRIBUTE).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX)); if (xattribs.exists(XML_EQUAL_NULL_ATTRIBUTE)){ merge.setEqualNULL(xattribs.getBoolean(XML_EQUAL_NULL_ATTRIBUTE)); } return merge; } catch (Exception ex) { throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex); } } /** * Description of the Method * * @return Description of the Return Value */ @Override public ConfigurationStatus checkConfig(ConfigurationStatus status) { super.checkConfig(status); if(!checkInputPorts(status, 1, Integer.MAX_VALUE) || !checkOutputPorts(status, 1, 1)) { return status; } if (getInPorts().size() < 2) { status.add(new ConfigurationProblem("At least 2 input ports should be defined!", Severity.WARNING, this, Priority.NORMAL)); } checkMetadata(status, getInMetadata(), getOutMetadata(), false); try { init(); } catch (ComponentNotReadyException e) { ConfigurationProblem problem = new ConfigurationProblem(e.getMessage(), ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL); if(!StringUtils.isEmpty(e.getAttributeName())) { problem.setAttributeName(e.getAttributeName()); } status.add(problem); } finally { free(); } return status; } public String getType(){ return COMPONENT_TYPE; } /* * (non-Javadoc) * @see org.jetel.graph.Node#reset() */ @Override public synchronized void reset() throws ComponentNotReadyException { super.reset(); // no implementation needed } public void setEqualNULL(boolean equalNULL) { this.equalNULL = equalNULL; } }
package org.jetel.data; import java.nio.ByteBuffer; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.util.Arrays; import org.jetel.metadata.DataFieldMetadata; /** * A class that represents array of bytes field.<br> * <br> * <i>Note: it has no sence to test this field for null value as even all zeros * can indicate meaningful value. Yet, the isNull & setNull is implemented. * *@author D.Pavlis *@created January 26, 2003 *@since October 29, 2002 *@see org.jetel.metadata.DataFieldMetadata */ public class ByteDataField extends DataField { // Attributes /** * Description of the Field * *@since October 29, 2002 */ protected byte[] value; private static final int ARRAY_LENGTH_INDICATOR_SIZE=4; private final static int INITIAL_BYTE_ARRAY_CAPACITY = 8; /** * Constructor for the NumericDataField object * *@param _metadata Metadata describing field *@since October 29, 2002 */ public ByteDataField(DataFieldMetadata _metadata) { super(_metadata); if (_metadata.getSize() < 1) { value = new byte[INITIAL_BYTE_ARRAY_CAPACITY]; } else { value = new byte[_metadata.getSize()]; } setNull(true); } /** * Constructor for the NumericDataField object * *@param _metadata Metadata describing field *@param value Value to assign to field *@since October 29, 2002 */ public ByteDataField(DataFieldMetadata _metadata, byte[] value) { super(_metadata); setValue(value); } /* (non-Javadoc) * @see org.jetel.data.DataField#copy() */ public DataField duplicate(){ return new ByteDataField(metadata,value); } /* (non-Javadoc) * @see org.jetel.data.DataField#copyField(org.jetel.data.DataField) */ public void copyFrom(DataField fromField){ if (fromField instanceof ByteDataField){ if (!fromField.isNull){ int length=((ByteDataField)fromField).value.length; if (this.value.length!=length){ this.value=new byte[length]; } System.arraycopy(this.value,0,((ByteDataField)fromField).value,0,length); } setNull(fromField.isNull); } } /** * Sets the value of the field * *@param _value The new Value value *@since October 29, 2002 */ public void setValue(Object _value) { if (_value instanceof byte[]) { value = (byte[]) _value; setNull(false); } else if (_value == null) { setNull(true); }else { throw new RuntimeException("not byte array"); } return; } /** * Sets the value of the field * *@param value value is copied into internal byte array using * System.arraycopy method *@since October 29, 2002 */ public void setValue(byte[] value) { /* begin changes by FSI */ this.value = value; setNull(value == null); /* end changes by FSI */ } /** * Sets the value of the field * *@param value The new byte value - the whole byte array is filled with this * value *@since October 29, 2002 */ public void setValue(byte value) { Arrays.fill(this.value, value); setNull(false); } // Associations // Operations /** * Gets the Metadata attribute of the ByteDataField object * *@return The Metadata value *@since October 29, 2002 */ public DataFieldMetadata getMetadata() { return super.getMetadata(); } /** * Gets the Field Type * *@return The Type value *@since October 29, 2002 */ public char getType() { return DataFieldMetadata.BYTE_FIELD; } /** * Gets the decimal value represented by this object (as Decimal object) * *@return The Value value *@since October 29, 2002 */ public Object getValue() { return value; } /** * Gets the byte value represented by this object as byte primitive * *@param position offset in byte array *@return The Byte value *@since October 29, 2002 */ public byte getByte(int position) { return value[position]; } /** * Gets the Byte array value of the ByteDataField object * *@return The Byte[] value *@since October 29, 2002 */ public byte[] getByte() { return value; } /** * Formats internal byte array value into string representation * *@return String representation of byte array *@since October 29, 2002 */ public String toString() { return new String(value); } /** * Parses byte array value from string (convers characters in string into byte * array using system's default charset encoder) * *@param valueStr Description of Parameter *@since October 29, 2002 */ public void fromString(String valueStr) { System.arraycopy(valueStr.getBytes(), 0, this.value, 0, this.value.length); } /** * Description of the Method * *@param dataBuffer Description of Parameter *@param decoder Description of Parameter *@since October 31, 2002 */ public void fromByteBuffer(ByteBuffer dataBuffer, CharsetDecoder decoder) { dataBuffer.get(value); } /** * Description of the Method * *@param dataBuffer Description of Parameter *@param encoder Description of Parameter *@since October 31, 2002 */ public void toByteBuffer(ByteBuffer dataBuffer, CharsetEncoder encoder) { dataBuffer.put(value); } /** * Performs serialization of the internal value into ByteBuffer (used when * moving data records between components). * *@param buffer Description of Parameter *@since October 29, 2002 */ public void serialize(ByteBuffer buffer) { buffer.putInt(value.length); buffer.put(value); } /** * Performs deserialization of data * *@param buffer Description of Parameter *@since October 29, 2002 */ public void deserialize(ByteBuffer buffer) { int length = buffer.getInt(); buffer.get(value, 0, length); setNull(false); } /** * Description of the Method * *@param obj Description of Parameter *@return Description of the Returned Value *@since October 29, 2002 */ public boolean equals(Object obj) { if (obj instanceof ByteDataField){ return Arrays.equals(this.value, ((ByteDataField) obj).getByte()); }else if (obj instanceof byte[]){ return Arrays.equals(this.value, (byte[])obj); }else { return false; } } /** * Compares this object with the specified object for order. * *@param obj Description of the Parameter *@return Description of the Return Value */ public int compareTo(Object obj) { byte[] byteObj; if (obj instanceof ByteDataField){ byteObj = (byte[]) ((ByteDataField) obj).getValue(); }else if (obj instanceof byte[]){ byteObj= (byte[])obj; }else { throw new RuntimeException("Object is NOT a ByteDataField or byte[] array: "+obj); } int compLength = value.length >= byteObj.length ? value.length : byteObj.length; for (int i = 0; i < compLength; i++) { if (value[i] > byteObj[i]) { return 1; } else if (value[i] < byteObj[i]) { return -1; } } // arrays seem to be the same (so far), decide according to the length if (value.length == byteObj.length) { return 0; } else if (value.length > byteObj.length) { return 1; } else { return -1; } } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode(){ int hash=5381; for (int i=0;i<value.length;i++){ hash = ((hash << 5) + hash) + value[i]; } return (hash & 0x7FFFFFFF); } /** * Returns how many bytes will be occupied when this field with current * value is serialized into ByteBuffer * * @return The size value * @see org.jetel.data.DataField */ public int getSizeSerialized() { return value.length+ARRAY_LENGTH_INDICATOR_SIZE; } } /* * end class NumericDataField */
package explorviz.visualization.engine.main; public class WebVRJS { public static native void resetSensor() /*-{ var sensor = $wnd.hmdSensor; if (sensor) sensor.resetSensor(); }-*/; public static native void setDevice() /*-{ if (navigator.getVRDevices) { navigator.getVRDevices().then(EnumerateVRDevices); } else if (navigator.mozGetVRDevices) { navigator.mozGetVRDevices(EnumerateVRDevices); } function EnumerateVRDevices(devices) { //find hmdDevice for (var i = 0; i < devices.length; ++i) { if (devices[i] instanceof HMDVRDevice) { $wnd.hmdDevice = devices[i]; var eyeOffsetLeft = $wnd.hmdDevice.getEyeParameters("left").eyeTranslation; var eyeOffsetRight = $wnd.hmdDevice.getEyeParameters("right").eyeTranslation; @explorviz.visualization.engine.main.SceneDrawer::setBothEyesCameras([F[F)(eyeOffsetLeft, eyeOffsetRight); } } // find hmdSensor for (var i = 0; i < devices.length; ++i) { if (devices[i] instanceof PositionSensorVRDevice && (!$wnd.hmdDevice || devices[i].hardwareUnitId == $wnd.hmdDevice.hardwareUnitId)) { $wnd.hmdSensor = devices[i]; $wnd.hmdSensor.resetSensor(); } } } }-*/; public static native void animationTick() /*-{ var sensor = $wnd.hmdSensor; if (sensor) { var vrState = sensor.getState(); var RADTODEG = $wnd.RADTODEG; //update rotation @explorviz.visualization.engine.navigation.Camera::rotateAbsoluteY(F)(vrState.orientation.y*RADTODEG*-3); @explorviz.visualization.engine.navigation.Camera::rotateAbsoluteX(F)(vrState.orientation.x*RADTODEG*-4); //update position //@explorviz.visualization.engine.navigation.Camera::moveY(F)(vrState.orientation.y*RADTODEG*2); //@explorviz.visualization.engine.navigation.Camera::moveX(F)(vrState.orientation.x*RADTODEG*4); } }-*/; }
package org.intermine.task; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl; import org.apache.tools.ant.Task; /** * Task superclass for invoking converters. * * @author Matthew Wakeling */ public class ConverterTask extends Task { protected String model; protected String osName; /** * Set the objectstore name * @param osName the model name */ public void setOsName(String osName) { this.osName = osName; } /** * Set the model name * @param model the model name */ public void setModel(String model) { this.model = model; } /** * Runs various performance-enhancing SQL statements. * * @param os the ObjectStore on which to run the SQL * @throws SQLException if something goes wrong * @throws IOException if an error occurs while reading from the post-processing sql file */ protected void doSQL(ObjectStore os) throws SQLException, IOException { if (os instanceof ObjectStoreInterMineImpl) { Connection c = null; try { c = ((ObjectStoreInterMineImpl) os).getConnection(); Statement s = c.createStatement(); System.err .println("ALTER TABLE reference ALTER refid SET STATISTICS 1000"); s.execute("ALTER TABLE reference ALTER refid SET STATISTICS 1000"); // TODO: files should be placed in resources String filename = model + "_src_items.sql"; InputStream is = ConverterTask.class.getClassLoader().getResourceAsStream(filename); // .sql files not always being copied correctly if (is != null) { BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = br.readLine(); while (line != null) { s.execute(line); System.err .println(line); line = br.readLine(); } } System.err .println("ANALYSE"); s.execute("ANALYSE"); } finally { ((ObjectStoreInterMineImpl) os).releaseConnection(c); } } } }
package hirezapi.rest; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.module.SimpleModule; import hirezapi.Platform; import hirezapi.json.Model; import hirezapi.json.deserializer.BooleanTextDeserializer; import hirezapi.json.deserializer.InstantTimeDeserializer; import lombok.Getter; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.time.Instant; @Getter public class RestController { private final OkHttpClient httpClient; private final ObjectMapper mapper; private final HttpUrl baseUrl; private final Logger log = LoggerFactory.getLogger(getClass()); public RestController(Platform platform) { this.baseUrl = platform.getBaseUrl(); this.httpClient = buildHttpClient(); this.mapper = buildObjectMapper(); } private ObjectMapper buildObjectMapper() { SimpleModule simpleModule = new SimpleModule(); simpleModule.addDeserializer(Instant.class, new InstantTimeDeserializer()); simpleModule.addDeserializer(Boolean.class, new BooleanTextDeserializer()); ObjectMapper mapper = new ObjectMapper(); mapper.enable(JsonGenerator.Feature.IGNORE_UNKNOWN); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); mapper.registerModule(simpleModule); return mapper; } private OkHttpClient buildHttpClient() { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(log::info); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS); return new OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build(); } public <T> T request(String uri, Class<T> classResponse) { Request request = new Request.Builder() .get() .url(baseUrl.newBuilder().addPathSegments(uri).build()) .build(); try (Response response = httpClient.newCall(request).execute()) { byte[] responseBodyByte = response.body().bytes(); if (hasError(response, responseBodyByte)) { handleError(response, responseBodyByte); } return mapper.readValue(responseBodyByte, classResponse); } catch (JsonParseException e) { throw new RestException("Cannot parse response", e); } catch (JsonMappingException e) { throw new RestException("Cannot map response", e); } catch (IOException e) { throw new RestException("Cannot handle response", e); } } private boolean hasError(Response response, byte[] responseBody) throws IOException { if (response.isSuccessful()) { Model model = formatResponse(responseBody); return !StringUtils.isBlank(model.getReturnedMessage()) && (!response.request().url().encodedPathSegments().contains("createsessionjson") && model.getReturnedMessage().equals("Approved")); } else { return response.code() >= 400; } } private Model formatResponse(byte[] responseBody) throws IOException { return ((responseBody[0] == '[')) ? mapper.readValue(responseBody, Model[].class)[0] : mapper.readValue(responseBody, Model.class); } private void handleError(Response response, byte[] responseBody) throws IOException { if (response.isSuccessful()) { Model model = formatResponse(responseBody); throw new RestException(model.getReturnedMessage()); } else { throw new RestException(response.message()); } } }
import org.apache.hc.core5.http.*; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.http.io.HttpRequestHandler; import org.apache.hc.core5.http.io.HttpServerRequestHandler; import org.apache.hc.core5.http.message.*; import org.apache.hc.core5.http.io.entity.*; import org.apache.hc.core5.util.*; import java.io.IOException; class B { static Object taint() { return null; } static void sink(Object o) { } class Test1 implements HttpRequestHandler { public void handle(ClassicHttpRequest req, ClassicHttpResponse res, HttpContext ctx) throws IOException, ParseException { B.sink(req.getAuthority().getHostName()); //$hasTaintFlow=y B.sink(req.getAuthority().toString()); //$hasTaintFlow=y B.sink(req.getMethod()); //$hasTaintFlow=y B.sink(req.getPath()); //$hasTaintFlow=y B.sink(req.getScheme()); B.sink(req.getRequestUri()); //$hasTaintFlow=y RequestLine line = new RequestLine(req); B.sink(line.getUri()); //$hasTaintFlow=y B.sink(line.getMethod()); //$hasTaintFlow=y B.sink(req.getHeaders()); //$hasTaintFlow=y B.sink(req.headerIterator()); //$hasTaintFlow=y Header h = req.getHeaders("abc")[3]; B.sink(h.getName()); //$hasTaintFlow=y B.sink(h.getValue()); //$hasTaintFlow=y B.sink(req.getFirstHeader("abc")); //$hasTaintFlow=y B.sink(req.getLastHeader("abc")); //$hasTaintFlow=y HttpEntity ent = req.getEntity(); B.sink(ent.getContent()); //$hasTaintFlow=y B.sink(ent.getContentEncoding()); //$hasTaintFlow=y B.sink(ent.getContentType()); //$hasTaintFlow=y B.sink(ent.getTrailerNames()); //$hasTaintFlow=y B.sink(ent.getTrailers().get()); //$hasTaintFlow=y B.sink(EntityUtils.toString(ent)); //$hasTaintFlow=y B.sink(EntityUtils.toByteArray(ent)); //$hasTaintFlow=y B.sink(EntityUtils.parse(ent)); //$hasTaintFlow=y res.setEntity(new StringEntity("<a href='" + req.getRequestUri() + "'>a</a>")); //$hasTaintFlow=y res.setEntity(new ByteArrayEntity(EntityUtils.toByteArray(ent), ContentType.TEXT_HTML)); //$hasTaintFlow=y res.setEntity(HttpEntities.create("<a href='" + req.getRequestUri() + "'>a</a>")); //$hasTaintFlow=y res.setHeader("Location", req.getRequestUri()); //$hasTaintFlow=y res.setHeader(new BasicHeader("Location", req.getRequestUri())); //$hasTaintFlow=y } } void test2() { ByteArrayBuffer bbuf = new ByteArrayBuffer(42); bbuf.append((byte[]) taint(), 0, 3); sink(bbuf.array()); //$hasTaintFlow=y sink(bbuf.toByteArray()); //$hasTaintFlow=y sink(bbuf.toString()); CharArrayBuffer cbuf = new CharArrayBuffer(42); cbuf.append(bbuf.toByteArray(), 0, 3); sink(cbuf.toCharArray()); //$hasTaintFlow=y sink(cbuf.toString()); //$hasTaintFlow=y sink(cbuf.subSequence(0, 3)); //$hasTaintFlow=y sink(cbuf.substring(0, 3)); //$hasTaintFlow=y sink(cbuf.substringTrimmed(0, 3)); //$hasTaintFlow=y sink(Args.notNull(taint(), "x")); //$hasTaintFlow=y sink(Args.notEmpty((String) taint(), "x")); //$hasTaintFlow=y sink(Args.notBlank((String) taint(), "x")); //$hasTaintFlow=y sink(Args.notNull("x", (String) taint())); } class Test3 implements HttpServerRequestHandler { public void handle(ClassicHttpRequest req, HttpServerRequestHandler.ResponseTrigger restr, HttpContext ctx) throws HttpException, IOException { B.sink(req.getEntity()); //$hasTaintFlow=y } } }
package com.exedio.cope.console; import java.io.File; import java.util.ArrayList; import java.util.Date; import com.exedio.cope.ConnectProperties; import com.exedio.cope.Feature; import com.exedio.cope.Model; import com.exedio.cope.SetValue; import com.exedio.cope.Type; import com.exedio.cope.pattern.MediaPath; import com.exedio.cope.util.CacheInfo; import com.exedio.cope.util.ConnectToken; import com.exedio.cope.util.ConnectionPoolInfo; final class HistoryThread extends Thread { static final Model HISTORY_MODEL = new Model(HistoryModel.TYPE); private static final String NAME = "COPE History"; private final String name; private final Model loggedModel; private final String logPropertyFile; private final Object lock = new Object(); private final String topic; private final MediaPath[] medias; private volatile boolean proceed = true; HistoryThread(final Model model, final String logPropertyFile) { super(NAME); this.name = NAME + ' ' + '(' + Integer.toString(System.identityHashCode(this), 36) + ')'; setName(name); this.loggedModel = model; this.logPropertyFile = logPropertyFile; this.topic = name + ' '; assert model!=null; assert logPropertyFile!=null; final ArrayList<MediaPath> medias = new ArrayList<MediaPath>(); for(final Type<?> type : loggedModel.getTypes()) for(final Feature feature : type.getDeclaredFeatures()) if(feature instanceof MediaPath) medias.add((MediaPath)feature); this.medias = medias.toArray(new MediaPath[medias.size()]); } @Override public void run() { System.out.println(topic + "run() started"); try { sleepByWait(2000l); if(!proceed) return; System.out.println(topic + "run() connecting"); ConnectToken loggerConnectToken = null; final long connecting = System.currentTimeMillis(); try { loggerConnectToken = ConnectToken.issue(HISTORY_MODEL, new ConnectProperties(new File(logPropertyFile)), name); System.out.println(topic + "run() connected (" + (System.currentTimeMillis() - connecting) + "ms)"); //loggerModel.tearDownDatabase(); loggerModel.createDatabase(); try { HISTORY_MODEL.startTransaction("check"); HISTORY_MODEL.checkDatabase(); HISTORY_MODEL.commit(); } finally { HISTORY_MODEL.rollbackIfNotCommitted(); } for(int running = 0; proceed; running++) { System.out.println(topic + "run() LOG " + running); log(running); sleepByWait(60000l); } } finally { if(loggerConnectToken!=null) { System.out.println(topic + "run() disconnecting"); final long disconnecting = System.currentTimeMillis(); loggerConnectToken.returnIt(); System.out.println(topic + "run() disconnected (" + (System.currentTimeMillis() - disconnecting) + "ms)"); } else System.out.println(topic + "run() not connected"); } } catch(Exception e) { e.printStackTrace(); } } private void log(final int running) { // gather data final Date date = new Date(); final ConnectionPoolInfo connectionPoolInfo = loggedModel.getConnectionPoolInfo(); final long nextTransactionId = loggedModel.getNextTransactionId(); final CacheInfo[] itemCacheInfos = loggedModel.getItemCacheInfo(); final long[] queryCacheInfo = loggedModel.getQueryCacheInfo(); int mediasException = 0; int mediasNotAnItem = 0; int mediasNoSuchItem = 0; int mediasIsNull = 0; int mediasNotComputable = 0; int mediasNotModified = 0; int mediasDelivered = 0; for(final MediaPath path : medias) { mediasException += path.exception.get(); mediasNotAnItem += path.notAnItem.get(); mediasNoSuchItem += path.noSuchItem.get(); mediasIsNull += path.isNull.get(); mediasNotComputable += path.notComputable.get(); mediasNotModified += path.notModified.get(); mediasDelivered += path.delivered.get(); } // process data int itemCacheHits = 0; int itemCacheMisses = 0; int itemCacheNumberOfCleanups = 0; int itemCacheItemsCleanedUp = 0; for(final CacheInfo ci : itemCacheInfos) { itemCacheHits += ci.getHits(); itemCacheMisses += ci.getMisses(); itemCacheNumberOfCleanups += ci.getNumberOfCleanups(); itemCacheItemsCleanedUp += ci.getItemsCleanedUp(); } final SetValue[] setValues = new SetValue[]{ HistoryModel.date.map(date), HistoryModel.running.map(running), HistoryModel.connectionPoolIdle.map(connectionPoolInfo.getIdleCounter()), HistoryModel.connectionPoolGet.map(connectionPoolInfo.getCounter().getGetCounter()), HistoryModel.connectionPoolPut.map(connectionPoolInfo.getCounter().getPutCounter()), HistoryModel.connectionPoolInvalidFromIdle.map(connectionPoolInfo.getInvalidFromIdle()), HistoryModel.connectionPoolInvalidIntoIdle.map(connectionPoolInfo.getInvalidIntoIdle()), HistoryModel.nextTransactionId.map(nextTransactionId), HistoryModel.itemCacheHits.map(itemCacheHits), HistoryModel.itemCacheMisses.map(itemCacheMisses), HistoryModel.itemCacheNumberOfCleanups.map(itemCacheNumberOfCleanups), HistoryModel.itemCacheItemsCleanedUp.map(itemCacheItemsCleanedUp), HistoryModel.queryCacheHits.map(queryCacheInfo[0]), HistoryModel.queryCacheMisses.map(queryCacheInfo[1]), HistoryModel.mediasException.map(mediasException), HistoryModel.mediasNotAnItem.map(mediasNotAnItem), HistoryModel.mediasNoSuchItem.map(mediasNoSuchItem), HistoryModel.mediasIsNull.map(mediasIsNull), HistoryModel.mediasNotComputable.map(mediasNotComputable), HistoryModel.mediasNotModified.map(mediasNotModified), HistoryModel.mediasDelivered.map(mediasDelivered) }; // save data try { HISTORY_MODEL.startTransaction("log " + running); new HistoryModel(setValues); HISTORY_MODEL.commit(); } finally { HISTORY_MODEL.rollbackIfNotCommitted(); } } private void sleepByWait(final long millis) { synchronized(lock) { //System.out.println(topic + "run() sleeping (" + millis + "ms)"); //final long sleeping = System.currentTimeMillis(); try { lock.wait(millis); } catch(InterruptedException e) { throw new RuntimeException(e); } //System.out.println(topic + "run() slept (" + (System.currentTimeMillis()-sleeping) + "ms)"); } } void stopAndJoin() { System.out.println(topic + "stopAndJoin() entering"); proceed = false; synchronized(lock) { System.out.println(topic + "stopAndJoin() notifying"); lock.notify(); } System.out.println(topic + "stopAndJoin() notified"); final long joining = System.currentTimeMillis(); try { join(); } catch(InterruptedException e) { throw new RuntimeException(e); } System.out.println(topic + "stopAndJoin() joined (" + (System.currentTimeMillis() - joining) + "ms)"); } }
package org.jgroups.tests; import junit.framework.TestCase; import org.jgroups.ChannelException; import org.jgroups.Event; import org.jgroups.JChannel; import org.jgroups.log.Trace; import org.jgroups.stack.IpAddress; import java.util.HashMap; import java.util.Map; /** * * @author Bela Ban * @version $Id: AddDataTest.java,v 1.3 2003/12/06 01:23:00 belaban Exp $ */ public class AddDataTest extends TestCase { public AddDataTest(String name) { super(name); Trace.init(); } public void testAdditionalData() { try { for(int i=1; i <= 10; i++) { System.out.println("-- attempt # " + i + "/10"); JChannel c=new JChannel(); 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(addr.getAdditionalData()[0], 'b'); c.close(); } } catch(ChannelException e) { e.printStackTrace(); fail(e.toString()); } } public static void main(String[] args) { String[] testCaseName={AddDataTest.class.getName()}; junit.textui.TestRunner.main(testCaseName); } }
package php.runtime.reflection; import php.runtime.Memory; import php.runtime.annotation.Reflection; import php.runtime.common.Messages; import php.runtime.common.Modifier; import php.runtime.env.ConcurrentEnvironment; import php.runtime.env.Context; import php.runtime.env.Environment; import php.runtime.env.TraceInfo; import php.runtime.exceptions.CriticalException; import php.runtime.exceptions.FatalException; import php.runtime.exceptions.support.ErrorException; import php.runtime.exceptions.support.ErrorType; import php.runtime.ext.support.Extension; import php.runtime.invoke.InvokeArgumentHelper; import php.runtime.invoke.ObjectInvokeHelper; import php.runtime.invoke.cache.PropertyCallCache; import php.runtime.lang.ForeachIterator; import php.runtime.lang.IObject; import php.runtime.lang.support.MagicSignatureClass; import php.runtime.memory.ArrayMemory; import php.runtime.memory.ReferenceMemory; import php.runtime.memory.StringMemory; import php.runtime.reflection.support.Entity; import php.runtime.reflection.support.ReflectionUtils; import php.runtime.wrap.ClassWrapper; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; public class ClassEntity extends Entity implements Cloneable { private final static int FLAG_GET = 4000; private final static int FLAG_SET = 4001; private final static int FLAG_ISSET = 4002; private final static int FLAG_UNSET = 4003; // types public enum Type { CLASS, INTERFACE, TRAIT } private long id; protected int methodCounts = 0; protected boolean isInternal; protected boolean isNotRuntime; protected Extension extension; protected Class<?> nativeClazz; protected Constructor nativeConstructor; protected Method nativeInitEnvironment; protected ModuleEntity module; protected final Map<String, MethodEntity> methods; public MethodEntity methodConstruct; public MethodEntity methodDestruct; public MethodEntity methodMagicSet; public MethodEntity methodMagicGet; public MethodEntity methodMagicUnset; public MethodEntity methodMagicIsset; public MethodEntity methodMagicCall; public MethodEntity methodMagicCallStatic; public MethodEntity methodMagicInvoke; public MethodEntity methodMagicToString; public MethodEntity methodMagicClone; public MethodEntity methodMagicSleep; public MethodEntity methodMagicWakeup; public MethodEntity methodMagicDebugInfo; protected MethodEntity constructor; protected final Map<String, ClassEntity> interfaces; protected final Map<String, ClassEntity> traits; public final Map<String, ConstantEntity> constants; public final Map<String, PropertyEntity> properties; public final Map<String, PropertyEntity> staticProperties; public final Set<String> instanceOfList = new HashSet<String>(); protected ClassEntity parent; protected DocumentComment docComment; protected boolean isAbstract = false; protected boolean isFinal = false; protected Type type = Type.CLASS; protected boolean isStatic; protected static final ClassEntity magicSignatureClass = new ClassEntity(new ClassWrapper(null, MagicSignatureClass.class)); public ClassEntity(Context context) { super(context); this.methods = new LinkedHashMap<String, MethodEntity>(); this.interfaces = new LinkedHashMap<String, ClassEntity>(); this.traits = new LinkedHashMap<String, ClassEntity>(); this.properties = new LinkedHashMap<String, PropertyEntity>(); this.staticProperties = new LinkedHashMap<String, PropertyEntity>(); this.constants = new LinkedHashMap<String, ConstantEntity>(); this.isInternal = false; } public ClassEntity(ClassWrapper wrapper) { this((Context) null); wrapper.onWrap(this); } public void setExtension(Extension extension) { this.extension = extension; } public String getCompiledInternalName() { return super.getInternalName(); } @Override public String getInternalName() { /*if (isTrait()) { depricated check, todo remove. throw new CriticalException("Disable of using internal names for traits, trait '" + getName() + "'"); } */ return super.getInternalName(); } public boolean isStatic() { return isStatic; } public void setStatic(boolean aStatic) { isStatic = aStatic; } public long getId() { return id; } public void setId(long id) { this.id = id; } public boolean isInternal() { return isInternal; } public boolean isTrait() { return type == Type.TRAIT; } public void setInternal(boolean isInternal) { this.isInternal = isInternal; } public boolean isNotRuntime() { return isNotRuntime; } public void setNotRuntime(boolean isNotRuntime) { this.isNotRuntime = isNotRuntime; } public void doneDeclare(){ if (isClass()) { methodConstruct = methods.get("__construct"); if (methodConstruct != null && (methodConstruct.getPrototype() == null || !methodConstruct.getPrototype().isAbstractable())) methodConstruct.setDynamicSignature(true); methodDestruct = methods.get("__destruct"); methodMagicSet = methods.get("__set"); methodMagicGet = methods.get("__get"); methodMagicUnset = methods.get("__unset"); methodMagicIsset = methods.get("__isset"); methodMagicCall = methods.get("__call"); methodMagicCallStatic = methods.get("__callstatic"); methodMagicInvoke = methods.get("__invoke"); methodMagicToString = methods.get("__tostring"); methodMagicClone = methods.get("__clone"); methodMagicSleep = methods.get("__sleep"); methodMagicWakeup = methods.get("__wakeup"); methodMagicDebugInfo = methods.get("__debuginfo"); } } /* ClassReader classReader; if (data != null) classReader = new ClassReader(data); else { try { classReader = new ClassReader(nativeClazz.getName()); } catch (IOException e) { throw new CriticalException(e); } } ClassNode classNode = new ClassNode(); classReader.accept(classNode, 0); return cachedClassNode = classNode; */ public Extension getExtension() { return extension; } public boolean isDeprecated(){ return false; // TODO } public boolean isAbstract() { return isAbstract; } public void setAbstract(boolean anAbstract) { isAbstract = anAbstract; } public boolean isFinal() { return isFinal; } public void setFinal(boolean aFinal) { isFinal = aFinal; } public Type getType() { return type; } public boolean isInterface(){ return type == Type.INTERFACE; } public boolean isClass(){ return type == Type.CLASS; } public boolean isHiddenInCallStack() { return false; } public void setType(Type type) { this.type = type; } public Map<String, MethodEntity> getMethods() { return methods; } public int getMethodCounts() { return methodCounts; } public void __setMethodCounts(int methodCounts) { this.methodCounts = methodCounts; } public List<MethodEntity> getOwnedMethods(){ List<MethodEntity> result = new ArrayList<MethodEntity>(); for (MethodEntity el : methods.values()){ if (el.isOwned(this)) result.add(el); } return result; } public SignatureResult addMethod(MethodEntity method, String realName){ String name = realName == null ? method.getLowerName() : realName; SignatureResult addResult = new SignatureResult(); if (method.isAbstract && method.isFinal){ addResult.add(InvalidMethod.error(InvalidMethod.Kind.FINAL_ABSTRACT, method)); } else if (method.isAbstractable() && !(method.isAbstract || type == Type.INTERFACE)){ addResult.add(InvalidMethod.error(InvalidMethod.Kind.NON_ABSTRACT, method)); } else if (method.isAbstract && !method.isAbstractable()){ addResult.add(InvalidMethod.error(InvalidMethod.Kind.NON_ABSTRACTABLE, method)); } else if (method.isAbstract && !(this.isAbstract || isTrait())){ addResult.add(InvalidMethod.error(InvalidMethod.Kind.NON_EXISTS, method)); } else if (type == Type.INTERFACE && (method.modifier != Modifier.PUBLIC || method.isFinal)){ addResult.add(InvalidMethod.error(InvalidMethod.Kind.INVALID_ACCESS_FOR_INTERFACE, method)); } if (magicSignatureClass != null){ MethodEntity systemMethod = magicSignatureClass.findMethod(name.toLowerCase()); if (systemMethod != null && method.clazz.getId() == getId()) { if (method.prototype == null) method.setPrototype(systemMethod); if (systemMethod.getModifier() == Modifier.PUBLIC && method.getModifier() != Modifier.PUBLIC){ addResult.add(InvalidMethod.warning(InvalidMethod.Kind.MAGIC_MUST_BE_PUBLIC, method)); //method.setModifier(Modifier.PUBLIC); } if (!systemMethod.equalsBySignature(method, false)){ addResult.add(InvalidMethod.error(InvalidMethod.Kind.INVALID_SIGNATURE, method)); } else if (systemMethod.isStatic && !method.isStatic) addResult.add(InvalidMethod.warning(InvalidMethod.Kind.MUST_STATIC, method)); else if (!systemMethod.isStatic && method.isStatic){ //method.setStatic(false); addResult.add(InvalidMethod.warning(InvalidMethod.Kind.MUST_NON_STATIC, method)); } } } if (parent == null || (!name.equals(parent.lowerName) || !methods.containsKey(name))) this.methods.put(name, method); if (name.equals(lowerName) && !isTrait()){ methods.put("__construct", method); } return addResult; } public int nextMethodIndex(){ return methodCounts++; } public MethodEntity findMethod(String name){ return methods.get(name); } public ConstantEntity findConstant(String name){ return constants.get(name); } // use can pass specific names public PropertyEntity findProperty(String name){ int pos = name.lastIndexOf('\0'); if (pos > -1 && pos + 1 < name.length()) name = name.substring(pos + 1); return properties.get(name); } public PropertyEntity findStaticProperty(String name){ return staticProperties.get(name); } public ClassEntity getParent() { return parent; } public boolean isInstanceOf(Class<? extends IObject> clazz){ return isInstanceOf(ReflectionUtils.getClassName(clazz)); } public boolean isInstanceOf(ClassEntity what){ return what != null && (id == what.id || instanceOfList.contains(what.lowerName)); } public boolean isInstanceOf(String name){ if (name == null) throw new IllegalArgumentException(); String lowerName = name.toLowerCase(); return instanceOfList.contains(lowerName) || this.lowerName.equals(lowerName); } public boolean isInstanceOfLower(String lowerName){ if (lowerName == null) throw new IllegalArgumentException(); return instanceOfList.contains(lowerName) || this.lowerName.equals(lowerName); } public SignatureResult updateParentMethods(){ SignatureResult result = new SignatureResult(); if (parent != null){ for(Map.Entry<String, MethodEntity> entry : parent.getMethods().entrySet()){ MethodEntity implMethod = findMethod(entry.getKey()); MethodEntity method = entry.getValue(); if (implMethod == method) continue; if (implMethod == null){ SignatureResult addResult = addMethod(method, entry.getKey()); if (methodConstruct == null && !isTrait() && method.getName().equalsIgnoreCase(parent.getName())){ if (!method.isAbstractable() && !methods.containsKey("__construct")) { method.setDynamicSignature(true); methods.put("__construct", method); } } result.methods.addAll(addResult.methods); } else { implMethod.setPrototype(method); if (method.isFinal) result.add(InvalidMethod.error(InvalidMethod.Kind.FINAL, implMethod)); if (!isAbstract && method.isAbstract && implMethod.isAbstract) result.add(InvalidMethod.error(InvalidMethod.Kind.NON_EXISTS, implMethod)); if (!implMethod.equalsBySignature(method)){ if (!method.isDynamicSignature() || method.isAbstractable()) { boolean isStrict = true; MethodEntity pr = method; while (pr != null){ if (pr.isAbstractable()){ isStrict = false; break; } pr = method.getPrototype(); } result.add( !isStrict ? InvalidMethod.error(InvalidMethod.Kind.INVALID_SIGNATURE, implMethod) : InvalidMethod.strict(InvalidMethod.Kind.INVALID_SIGNATURE, implMethod) ); } } else if (implMethod.isStatic() && !method.isStatic()){ result.add(InvalidMethod.error(InvalidMethod.Kind.MUST_NON_STATIC, implMethod)); } else if (!implMethod.isStatic() && method.isStatic()){ result.add(InvalidMethod.error(InvalidMethod.Kind.MUST_STATIC, implMethod)); } if (method.isPublic() && !implMethod.isPublic()) result.add(InvalidMethod.error(InvalidMethod.Kind.MUST_BE_PUBLIC, implMethod)); else if (method.isProtected() && implMethod.isPrivate()) result.add(InvalidMethod.error(InvalidMethod.Kind.MUST_BE_PROTECTED, implMethod)); } } doneDeclare(); } return result; } public ExtendsResult setParent(ClassEntity parent) { return setParent(parent, true); } public ExtendsResult setParent(ClassEntity parent, boolean updateParentMethods) { ExtendsResult result = new ExtendsResult(parent); if (this.parent != null){ throw new RuntimeException("Cannot re-assign parent for classes"); } this.parent = parent; if (parent != null){ if (parent.useJavaLikeNames) { this.useJavaLikeNames = true; } this.methodCounts = parent.methodCounts; this.instanceOfList.add(parent.getLowerName()); this.instanceOfList.addAll(parent.instanceOfList); this.interfaces.putAll(parent.interfaces); this.properties.putAll(parent.properties); this.staticProperties.putAll(parent.staticProperties); this.constants.putAll(parent.constants); } if (updateParentMethods) result.methods = updateParentMethods(); return result; } /** * return empty list if success else list with not valid implemented methods in class * @param _interface * @return */ public ImplementsResult addInterface(ClassEntity _interface) { ImplementsResult result = new ImplementsResult(_interface); for(ConstantEntity e : _interface.constants.values()){ ConstantEntity origin = constants.get(e.getName()); if (origin != null && e.getClazz().getId() == _interface.getId() && (parent == null || parent.constants.get(e.getName()) == null)) result.signature.addConstant(InvalidConstant.error(origin, e)); } this.constants.putAll(_interface.constants); this.interfaces.put(_interface.getLowerName(), _interface); this.instanceOfList.add(_interface.getLowerName()); this.instanceOfList.addAll(_interface.instanceOfList); for(MethodEntity method : _interface.getMethods().values()){ MethodEntity implMethod = findMethod(method.getLowerName()); if (implMethod == method) continue; if (implMethod == null){ addMethod(method, null); if (type == Type.CLASS && !isAbstract) result.signature.add(InvalidMethod.error(InvalidMethod.Kind.NON_EXISTS, method)); } else { implMethod.setPrototype(method); if (/*!method.isDynamicSignature() &&*/ !implMethod.equalsBySignature(method)){ // checking dynamic for only extends result.signature.add(InvalidMethod.error(InvalidMethod.Kind.INVALID_SIGNATURE, implMethod)); } else if (implMethod.isStatic() && !method.isStatic()){ result.signature.add(InvalidMethod.error(InvalidMethod.Kind.MUST_NON_STATIC, implMethod)); } else if (!implMethod.isStatic() && method.isStatic()){ result.signature.add(InvalidMethod.error(InvalidMethod.Kind.MUST_STATIC, implMethod)); } } } return result; } public Map<String, ClassEntity> getInterfaces() { return interfaces; } public void addTrait(ClassEntity trait) { if (!trait.isTrait()) throw new IllegalArgumentException("'" + trait.getName() + "' is not a trait"); this.traits.put(trait.getLowerName(), trait); } public boolean hasTrait(String traitLowerName) { return this.traits.containsKey(traitLowerName); } public Map<String, ClassEntity> getTraits() { return traits; } public Collection<ConstantEntity> getConstants() { return constants.values(); } public Collection<PropertyEntity> getProperties() { return properties.values(); } public Collection<PropertyEntity> getStaticProperties() { return staticProperties.values(); } public void addConstant(ConstantEntity constant){ constants.put(constant.getName(), constant); constant.setClazz(this); } public void addDynamicConstant(Environment env, String name, Memory value){ ConstantEntity entity = constants.get(name); env.getOrCreateStatic(entity.getInternalName(), value); } public void addDynamicStaticProperty(Environment env, String name, Memory value){ PropertyEntity prop = staticProperties.get(name); env.getOrCreateStatic(prop.specificName, value); } public void addDynamicProperty(Environment env, String name, Memory value){ PropertyEntity prop = properties.get(name); env.getOrCreateStatic(prop.getInternalName(), value); } public PropertyResult addProperty(PropertyEntity property){ PropertyResult result = new PropertyResult(); PropertyEntity prototype = null; if (property.isStatic()) { prototype = staticProperties.get(property.getLowerName()); if (prototype != null && prototype.getModifier() != property.getModifier()){ property.setPrototype(prototype); } if (prototype == null) prototype = properties.get(property.getName()); staticProperties.put(property.getName(), property); } else { prototype = properties.get(property.getLowerName()); if (prototype != null && prototype.getModifier() != property.getModifier()){ property.setPrototype(prototype); } if (prototype == null) prototype = staticProperties.get(property.getName()); properties.put(property.getName(), property); } if (prototype != null){ if (property.getPrototype() != null){ if (prototype.isProtected() && property.isPrivate()){ result.addError(InvalidProperty.Kind.MUST_BE_PROTECTED, property); } if (prototype.isPublic() && !property.isPublic()){ result.addError(InvalidProperty.Kind.MUST_BE_PUBLIC, property); } } boolean overridden = property.modifier.ordinal() > prototype.modifier.ordinal(); if (!property.isPrivate() && property.modifier == prototype.modifier) overridden = true; if (property.isPublic() && prototype.isProtected()) overridden = true; if (prototype.isStatic() && !property.isStatic()){ if (overridden){ property.setPrototype(prototype); result.addError(InvalidProperty.Kind.STATIC_AS_NON_STATIC, property); } } else if (property.isStatic() && !prototype.isStatic()){ if (overridden){ property.setPrototype(prototype); result.addError(InvalidProperty.Kind.NON_STATIC_AS_STATIC, property); } } } property.setClazz(this); return result; } protected void addStaticProperty(PropertyEntity property){ if (!property.isStatic()) throw new IllegalArgumentException("Property must be static"); staticProperties.put(property.getLowerName(), property); property.setClazz(this); } public MethodEntity getConstructor() { return constructor; } public void setConstructor(MethodEntity constructor) { this.constructor = constructor; constructor.setClazz(this); } public DocumentComment getDocComment() { return docComment; } public void setDocComment(DocumentComment docComment) { this.docComment = docComment; } public Class<?> getNativeClass() { return nativeClazz; } @Deprecated public Class<?> getNativeClazz() { return nativeClazz; } protected static void invalidAccessToProperty(Environment env, TraceInfo trace, PropertyEntity entity, int accessFlag){ switch (accessFlag){ case 1: env.error(trace, ErrorType.E_ERROR, Messages.ERR_ACCESS_TO_PROTECTED_PROPERTY.fetch( entity.getClazz().getName(), entity.getName() )); case 2: env.error(trace, ErrorType.E_ERROR, Messages.ERR_ACCESS_TO_PRIVATE_PROPERTY.fetch( entity.getClazz().getName(), entity.getName() )); } } public void setNativeClazz(Class<?> nativeClazz) { this.nativeClazz = nativeClazz; if (nativeClazz.getAnnotation(Reflection.UseJavaLikeNames.class) != null) { useJavaLikeNames = true; } if (!nativeClazz.isInterface()){ try { this.nativeConstructor = nativeClazz.getConstructor(Environment.class, ClassEntity.class); this.nativeConstructor.setAccessible(true); } catch (NoSuchMethodException e) { this.nativeConstructor = null; //if (IObject.class.isAssignableFrom(getNativeClass().getClass())) // throw new CriticalException(e); } if (!this.isInternal){ try { if (isTrait()) { this.nativeInitEnvironment = nativeClazz.getDeclaredMethod( "__$initEnvironment", Environment.class, String.class ); } else { this.nativeInitEnvironment = nativeClazz.getDeclaredMethod( "__$initEnvironment", Environment.class ); } this.nativeInitEnvironment.setAccessible(true); } catch (NoSuchMethodException e) { this.nativeInitEnvironment = null; } } } } public ModuleEntity getModule() { return module; } public void setModule(ModuleEntity module) { this.module = module; } public void initEnvironment(Environment env) { if (isClass() && nativeInitEnvironment != null) { try { nativeInitEnvironment.invoke(null, env); } catch (InvocationTargetException e) { env.__throwException(e); } catch (IllegalAccessException e) { throw new CriticalException(e); } } if (!traits.isEmpty()) { Set<ClassEntity> used = new HashSet<ClassEntity>(); try { for (ClassEntity trait : traits.values()) { trait.initTraitEnvironment(env, this, used); } } catch (Exception e) { env.catchUncaught(e); } catch (Throwable e) { throw new CriticalException(e); } } } protected void initTraitEnvironment(Environment env, ClassEntity originClass, Set<ClassEntity> used) throws Throwable { if (nativeInitEnvironment != null) { try { nativeInitEnvironment.invoke(null, env, originClass.getName()); } catch (InvocationTargetException e) { env.__throwException(e); } } for(ClassEntity trait : traits.values()) { if (used.add(trait)) { trait.initTraitEnvironment(env, originClass, used); } } } public <T extends IObject> T newObjectWithoutConstruct(Environment env) { IObject object = null; try { if (nativeConstructor != null) object = (IObject) nativeConstructor.newInstance(env, this); } catch (InvocationTargetException e){ env.__throwException(e); return null; } catch (InstantiationException e) { throw new CriticalException(e); } catch (IllegalAccessException e) { throw new CriticalException(e); } return (T) object; } public <T extends IObject> T newMock(Environment env) throws Throwable { if (nativeConstructor == null) { env.error(env.trace(), ErrorType.E_CORE_ERROR, "Cannot find a java constructor %s(Environment, ClassEntity)", getName()); } try { IObject object = (IObject) nativeConstructor.newInstance(env, this); object.setAsMock(); return (T) object; } catch (InstantiationException e){ return null; } } public <T extends IObject> T newObject(Environment env, TraceInfo trace, boolean doConstruct, Memory... args) throws Throwable { if (isAbstract){ env.error(trace, "Cannot instantiate abstract class %s", name); } else if (type == Type.INTERFACE) env.error(trace, "Cannot instantiate interface %s", name); else if (type == Type.TRAIT) env.error(trace, "Cannot instantiate trait %s", name); IObject object; try { if (nativeConstructor == null) { env.error(trace, ErrorType.E_CORE_ERROR, "Cannot find a java constructor %s(Environment, ClassEntity)", getName()); } object = (IObject) nativeConstructor.newInstance(env, this); } catch (InvocationTargetException e){ env.__throwException(e); return null; } ArrayMemory props = object.getProperties(); for(PropertyEntity property : getProperties()) { if (id == property.clazz.getId() && property.getGetter() == null){ props.putAsKeyString( property.getSpecificName(), property.getDefaultValue(env).toImmutable() ); } } ClassEntity tmp = parent; while (tmp != null){ long otherId = tmp.getId(); for(PropertyEntity property : tmp.getProperties()) { if (property.getClazz().getId() == otherId && property.getGetter() == null) { if (property.modifier != Modifier.PROTECTED || props.getByScalar(property.getName()) == null) props.getByScalarOrCreate( property.getSpecificName(), property.getDefaultValue(env).toImmutable() ); } } tmp = tmp.parent; } if (doConstruct && methodConstruct != null){ ObjectInvokeHelper.invokeMethod(object, methodConstruct, env, trace, args, true); } return (T) object; } public <T extends IObject> T cloneObject(T value, Environment env, TraceInfo trace) throws Throwable { IObject copy = this.newObjectWithoutConstruct(env); ForeachIterator iterator = value.getProperties().foreachIterator(false, false); ArrayMemory props = copy.getProperties(); while (iterator.next()){ Object key = iterator.getKey(); if (key instanceof String) { String name = (String)key; if (name.indexOf('\0') > -1) name = name.substring(name.lastIndexOf('\0') + 1); PropertyEntity entity = properties.get(name); if (entity != null) { if (props.getByScalar(entity.getSpecificName()) == null) props.put(entity.getSpecificName(), iterator.getValue().toImmutable()); } else props.put(key, iterator.getValue().toImmutable()); } else props.put(key, iterator.getValue().toImmutable()); } if (methodMagicClone != null){ ObjectInvokeHelper.invokeMethod(copy, methodMagicClone, env, trace, null, true); } return (T) copy; } public Memory concatProperty(Environment env, TraceInfo trace, IObject object, String property, Memory memory, PropertyCallCache callCache, int cacheIndex) throws Throwable { return setProperty(env, trace, object, property, memory, new SetterCallback() { @Override public Memory invoke(Memory o1, Memory o2) { return new StringMemory(o1.concat(o2)); } }, callCache, cacheIndex); } public Memory plusProperty(Environment env, TraceInfo trace, IObject object, String property, Memory memory, final ReferenceMemory oldValue) throws Throwable { return setProperty(env, trace, object, property, memory, new SetterCallback() { @Override public Memory invoke(Memory o1, Memory o2) { if (oldValue != null) oldValue.assign(o1); return o1.plus(o2); } }, null, 0); } public Memory minusProperty(Environment env, TraceInfo trace, IObject object, String property, Memory memory, final ReferenceMemory oldValue) throws Throwable { return setProperty(env, trace, object, property, memory, new SetterCallback() { @Override public Memory invoke(Memory o1, Memory o2) { if (oldValue != null) oldValue.assign(o1); return o1.minus(o2); } }, null, 0); } public Memory mulProperty(Environment env, TraceInfo trace, IObject object, String property, Memory memory, PropertyCallCache callCache, int cacheIndex) throws Throwable { return setProperty(env, trace, object, property, memory, new SetterCallback() { @Override public Memory invoke(Memory o1, Memory o2) { return o1.mul(o2); } }, callCache, cacheIndex); } public Memory divProperty(Environment env, TraceInfo trace, IObject object, String property, Memory memory, PropertyCallCache callCache, int cacheIndex) throws Throwable { return setProperty(env, trace, object, property, memory, new SetterCallback() { @Override public Memory invoke(Memory o1, Memory o2) { return o1.div(o2); } }, callCache, cacheIndex); } public Memory modProperty(Environment env, TraceInfo trace, IObject object, String property, Memory memory, PropertyCallCache callCache, int cacheIndex) throws Throwable { return setProperty(env, trace, object, property, memory, new SetterCallback() { @Override public Memory invoke(Memory o1, Memory o2) { return o1.mod(o2); } }, callCache, cacheIndex); } public Memory bitAndProperty(Environment env, TraceInfo trace, IObject object, String property, Memory memory, PropertyCallCache callCache, int cacheIndex) throws Throwable { return setProperty(env, trace, object, property, memory, new SetterCallback() { @Override public Memory invoke(Memory o1, Memory o2) { return o1.bitAnd(o2); } }, callCache, cacheIndex); } public Memory bitOrProperty(Environment env, TraceInfo trace, IObject object, String property, Memory memory, PropertyCallCache callCache, int cacheIndex) throws Throwable { return setProperty(env, trace, object, property, memory, new SetterCallback() { @Override public Memory invoke(Memory o1, Memory o2) { return o1.bitOr(o2); } }, callCache, cacheIndex); } public Memory bitXorProperty(Environment env, TraceInfo trace, IObject object, String property, Memory memory, PropertyCallCache callCache, int cacheIndex) throws Throwable { return setProperty(env, trace, object, property, memory, new SetterCallback() { @Override public Memory invoke(Memory o1, Memory o2) { return o1.bitXor(o2); } }, callCache, cacheIndex); } public Memory bitShrProperty(Environment env, TraceInfo trace, IObject object, String property, Memory memory, PropertyCallCache callCache, int cacheIndex) throws Throwable { return setProperty(env, trace, object, property, memory, new SetterCallback(){ @Override public Memory invoke(Memory o1, Memory o2) { return o1.bitShr(o2); } }, callCache, cacheIndex); } public Memory bitShlProperty(Environment env, TraceInfo trace, IObject object, String property, Memory memory, PropertyCallCache callCache, int cacheIndex) throws Throwable { return setProperty(env, trace, object, property, memory, new SetterCallback() { @Override public Memory invoke(Memory o1, Memory o2) { return o1.bitShl(o2); } }, callCache, cacheIndex); } public void appendProperty(IObject object, String property, Memory value){ object.getProperties().put(property, value); } public Memory refOfProperty(ArrayMemory props, String name){ PropertyEntity entity = properties.get(name); return props.refOfIndex(entity == null ? name : entity.getSpecificName()); } public Memory setProperty(Environment env, TraceInfo trace, IObject object, String property, Memory memory, SetterCallback callback, PropertyCallCache callCache, int cacheIndex) throws Throwable { ReferenceMemory value; PropertyEntity entity = callCache == null ? null : callCache.get(env, cacheIndex); if (entity == null) { ClassEntity context = env.getLastClassOnStack(); entity = isInstanceOf(context) ? context.properties.get(property) : properties.get(property); if (callCache != null && entity != null) { callCache.put(env, cacheIndex, entity); } } if (entity == null){ PropertyEntity staticEntity = staticProperties.get(property); if (staticEntity != null){ invalidAccessToProperty(env, trace, staticEntity, staticEntity.canAccess(env)); env.error(trace, ErrorType.E_STRICT, Messages.ERR_ACCESSING_STATIC_PROPERTY_AS_NON_STATIC, staticEntity.getClazz().getName(), staticEntity.getName() ); } } int accessFlag = entity == null ? 0 : entity.canAccess(env); ArrayMemory props = object.getProperties(); if (entity != null) { if (entity.setter != null) { if (callback != null) memory = callback.invoke(getProperty(env, trace, object, property, null, 0), memory); try { ObjectInvokeHelper.invokeMethod(object, entity.setter, env, trace, new Memory[]{memory}, false); } catch (IllegalArgumentException e) { if (!object.getReflection().isInstanceOf(entity.setter.getClazz())) { return setProperty(env, trace, object, property, memory, callback, null, 0); } throw e; } return memory; } else if (entity.getter != null) { env.error(trace, ErrorType.E_RECOVERABLE_ERROR, Messages.ERR_READONLY_PROPERTY.fetch(entity.getClazz().getName(), property)); } } value = props == null || accessFlag != 0 ? null : props.getByScalar(entity == null ? property : entity.specificName); if (value == null) { boolean recursive = false; ClassEntity context = env.getLastClassOnStack(); if (context != null && methodMagicSet != null && context.getId() == methodMagicSet.getClazz().getId() ){ recursive = env.peekCall(0).flags == FLAG_SET; } if (methodMagicSet != null && !recursive) { StringMemory memoryProperty = new StringMemory(property); if (callback != null){ Memory o1 = Memory.NULL; if (methodMagicGet != null) { try { Memory[] args = new Memory[]{memoryProperty}; env.pushCall( trace, object, args, methodMagicGet.getName(), methodMagicSet.getClazz().getName(), name ); env.peekCall(0).flags = FLAG_GET; InvokeArgumentHelper.checkType(env, trace, methodMagicGet, args); o1 = methodMagicGet.invokeDynamic(object, env, memoryProperty); } finally { env.popCall(); } } memory = callback.invoke(o1, memory); } try { Memory[] args = new Memory[]{memoryProperty, memory}; env.pushCall(trace, object, args, methodMagicSet.getName(), methodMagicSet.getClazz().getName(), name); env.peekCall(0).flags = FLAG_SET; InvokeArgumentHelper.checkType(env, trace, methodMagicSet, args); methodMagicSet.invokeDynamic(object, env, args); } finally { env.popCall(); } } else { /*if (accessFlag != 0) { invalidAccessToProperty(env, trace, entity, accessFlag); return Memory.NULL; }*/ if (callback != null) memory = callback.invoke(Memory.NULL, memory); String name = property; if (entity != null){ if (accessFlag != 0 && context == null){ switch (accessFlag){ case 2: if (object.getReflection().getId() == entity.getClazz().getId()){ invalidAccessToProperty(env, trace, entity, accessFlag); return Memory.NULL; } break; case 1: invalidAccessToProperty(env, trace, entity, accessFlag); return Memory.NULL; } } if (context != null){ switch (entity.modifier){ case PRIVATE: if (entity.getClazz().getId() == context.getId()) name = entity.specificName; break; case PROTECTED: if (context.isInstanceOf(entity.getClazz())) name = entity.specificName; } } } return props == null ? Memory.NULL : (entity == null ? props.refOfIndex(name).assign(memory) : entity.assignValue(env, trace, object, name, memory)); } } else { if (callback != null) memory = callback.invoke(value, memory); if (entity instanceof CompilePropertyEntity) { return entity.assignValue(env, trace, object, property, memory); } return value.assign(memory); } return memory; } public Memory unsetProperty(Environment env, TraceInfo trace, IObject object, String property, PropertyCallCache callCache, int index) throws Throwable { ClassEntity context = env.getLastClassOnStack(); PropertyEntity entity = isInstanceOf(context) ? context.properties.get(property) : properties.get(property); int accessFlag = entity == null ? 0 : entity.canAccess(env); if (entity == null){ PropertyEntity staticEntity = staticProperties.get(property); if (staticEntity != null){ invalidAccessToProperty(env, trace, staticEntity, staticEntity.canAccess(env)); } } ArrayMemory props = object.getProperties(); if (props == null || accessFlag != 0 || props.removeByScalar(entity == null ? property : entity.specificName) == null ){ if (methodMagicUnset != null) { if (context != null && context.getId() == methodMagicUnset.getClazz().getId() ){ if (env.peekCall(0).flags == FLAG_UNSET){ return Memory.NULL; } } try { Memory[] args = new Memory[]{new StringMemory(property)}; env.pushCall(trace, object, args, methodMagicUnset.getName(), methodMagicUnset.getClazz().getName(), name); env.peekCall(0).flags = FLAG_UNSET; InvokeArgumentHelper.checkType(env, trace, methodMagicUnset, args); methodMagicUnset.invokeDynamic(object, env, args); } finally { env.popCall(); } return Memory.NULL; } } if (accessFlag != 0) invalidAccessToProperty(env, trace, entity, accessFlag); entity = staticProperties.get(property); if (entity != null){ env.error(trace, ErrorType.E_STRICT, Messages.ERR_ACCESSING_STATIC_PROPERTY_AS_NON_STATIC, entity.getClazz().getName(), entity.getName() ); } return Memory.NULL; } public Memory emptyProperty(Environment env, TraceInfo trace, IObject object, String property) throws Throwable { ClassEntity contex = env.getLastClassOnStack(); PropertyEntity entity = isInstanceOf(contex) ? contex.properties.get(property) : properties.get(property); int accessFlag = entity == null ? 0 : entity.canAccess(env); ArrayMemory props = object.getProperties(); if (props != null && accessFlag == 0){ Memory tmp = props.getByScalar(entity == null ? property : entity.specificName); if ( tmp != null ){ return tmp.toBoolean() ? Memory.TRUE : Memory.NULL; } else return Memory.NULL; } if (methodMagicIsset != null){ Memory result; if (contex != null && contex.getId() == methodMagicIsset.getClazz().getId() ){ if (env.peekCall(0).flags == FLAG_ISSET){ return object.getProperties().getByScalar(property) != null ? Memory.TRUE : Memory.NULL; } } try { Memory[] args = new Memory[]{new StringMemory(property)}; env.pushCall( trace, object, args, methodMagicIsset.getName(), methodMagicIsset.getClazz().getName(), name ); env.peekCall(0).flags = FLAG_ISSET; InvokeArgumentHelper.checkType(env, trace, methodMagicIsset, new StringMemory(property)); result = methodMagicIsset.invokeDynamic(object, env, new StringMemory(property)) .toBoolean() ? Memory.TRUE : Memory.NULL; } finally { env.popCall(); } return result; } return Memory.NULL; } public Memory issetProperty(Environment env, TraceInfo trace, IObject object, String property, PropertyCallCache callCache, int cacheIndex) throws Throwable { PropertyEntity entity = callCache == null || env instanceof ConcurrentEnvironment ? null : callCache.get(env, cacheIndex); if (entity == null) { ClassEntity contex = env.getLastClassOnStack(); entity = isInstanceOf(contex) ? contex.properties.get(property) : properties.get(property); if (entity != null && callCache != null) { callCache.put(env, cacheIndex, entity); } } int accessFlag = entity == null ? 0 : entity.canAccess(env); ArrayMemory props = object.getProperties(); Memory tmp = props == null || accessFlag != 0 ? null : props.getByScalar(entity == null ? property : entity.specificName); if ( tmp != null ) return tmp.isNull() ? tmp : Memory.TRUE; if (methodMagicIsset != null){ Memory result; ClassEntity contex = env.getLastClassOnStack(); if (contex != null && contex.getId() == methodMagicIsset.getClazz().getId() ) if (env.peekCall(0).flags == FLAG_ISSET){ return object.getProperties().getByScalar(property) != null ? Memory.TRUE : Memory.NULL; } try { Memory[] args = new Memory[]{new StringMemory(property)}; env.pushCall(trace, object, args, methodMagicIsset.getName(), methodMagicIsset.getClazz().getName(), name); env.peekCall(0).flags = FLAG_ISSET; InvokeArgumentHelper.checkType(env, trace, methodMagicIsset, new StringMemory(property)); result = methodMagicIsset.invokeDynamic(object, env, new StringMemory(property)) .toBoolean() ? Memory.TRUE : Memory.NULL; } finally { env.popCall(); } return result; } return Memory.NULL; } public Memory getStaticProperty(Environment env, TraceInfo trace, String property, boolean errorIfNotExists, boolean checkAccess, ClassEntity context, PropertyCallCache callCache, int cacheIndex) throws Throwable { PropertyEntity entity = callCache == null || env instanceof ConcurrentEnvironment || context != null ? null : callCache.get(env, cacheIndex); if (entity == null) { boolean saveCache = context == null && callCache != null; context = context == null ? env.getLastClassOnStack() : context; entity = isInstanceOf(context) ? context.staticProperties.get(property) : staticProperties.get(property); if (saveCache && entity != null) { callCache.put(env, cacheIndex, entity); } } if (entity == null){ if (errorIfNotExists) env.error(trace, Messages.ERR_ACCESS_TO_UNDECLARED_STATIC_PROPERTY.fetch(name, property)); return Memory.NULL; } if (checkAccess){ int accessFlag = entity.canAccess(env, context); if (accessFlag != 0) { invalidAccessToProperty(env, trace, entity, accessFlag); return Memory.NULL; } } return env.getOrCreateStatic( entity.specificName, entity.getDefaultValue(env).toImmutable() ); } public Memory getRefProperty(Environment env, TraceInfo trace, IObject object, String property, PropertyCallCache callCache, int cacheIndex) throws Throwable { Memory value; PropertyEntity entity = callCache == null || env instanceof ConcurrentEnvironment ? null : callCache.get(env, cacheIndex); if (entity == null) { ClassEntity context = env.getLastClassOnStack(); entity = isInstanceOf(context) ? context.properties.get(property) : properties.get(property); if (callCache != null) { callCache.put(env, cacheIndex, entity); } } if (entity == null){ PropertyEntity staticEntity = staticProperties.get(property); if (staticEntity != null){ invalidAccessToProperty(env, trace, staticEntity, staticEntity.canAccess(env)); env.error(trace, ErrorType.E_STRICT, Messages.ERR_ACCESSING_STATIC_PROPERTY_AS_NON_STATIC, staticEntity.getClazz().getName(), staticEntity.getName() ); } } int accessFlag = entity == null ? 0 : entity.canAccess(env); ArrayMemory props = object.getProperties(); value = props == null || accessFlag != 0 ? null : props.getByScalar(entity == null ? property : entity.specificName); if (accessFlag != 0) invalidAccessToProperty(env, trace, entity, accessFlag); if (value == null){ value = props == null ? new ReferenceMemory() : object.getProperties().refOfIndex(property); if (methodMagicGet != null || methodMagicSet != null){ env.error(trace, props == null ? ErrorType.E_ERROR : ErrorType.E_NOTICE, Messages.ERR_INDIRECT_MODIFICATION_OVERLOADED_PROPERTY, name, property); } } return value; } public Memory getProperty(Environment env, TraceInfo trace, IObject object, String property, PropertyCallCache callCache, int cacheIndex) throws Throwable { Memory value; PropertyEntity entity = callCache == null || env instanceof ConcurrentEnvironment ? null : callCache.get(env, cacheIndex); if (entity == null) { ClassEntity context = env.getLastClassOnStack(); entity = isInstanceOf(context) ? context.properties.get(property) : properties.get(property); if (callCache != null && entity != null) { callCache.put(env, cacheIndex, entity); } } if (entity == null) { PropertyEntity staticEntity = staticProperties.get(property); if (staticEntity != null){ invalidAccessToProperty(env, trace, staticEntity, staticEntity.canAccess(env)); env.error(trace, ErrorType.E_STRICT, Messages.ERR_ACCESSING_STATIC_PROPERTY_AS_NON_STATIC, staticEntity.getClazz().getName(), staticEntity.getName() ); } } int accessFlag = entity == null ? 0 : entity.canAccess(env); if (entity != null && accessFlag != 0) { value = null; } else { if (entity != null) { value = entity.getValue(env, trace, object); } else { ArrayMemory props = object.getProperties(); value = props == null ? null : props.getByScalar(property); } } if (value != null) return value; if (methodMagicGet != null) { Memory result; ClassEntity context = env.getLastClassOnStack(); if (context != null && context.getId() == methodMagicGet.getClazz().getId()){ if (env.peekCall(0).flags == FLAG_GET) { env.error(trace, ErrorType.E_NOTICE, Messages.ERR_UNDEFINED_PROPERTY, name, property); return Memory.NULL; } } try { Memory[] args = new Memory[]{new StringMemory(property)}; env.pushCall(trace, object, args, methodMagicGet.getName(), methodMagicGet.getClazz().getName(), name); env.peekCall(0).flags = FLAG_GET; InvokeArgumentHelper.checkType(env, trace, methodMagicGet, args); result = methodMagicGet.invokeDynamic(object, env, args); } finally { env.popCall(); } return result; } if (accessFlag != 0) invalidAccessToProperty(env, trace, entity, accessFlag); env.error(trace, ErrorType.E_NOTICE, Messages.ERR_UNDEFINED_PROPERTY, name, property); return Memory.NULL; } public void setProperty(IObject object, String name, Memory value){ PropertyEntity prop = findProperty(name); if (prop == null) throw new RuntimeException("Property '" + name + "' not found"); object.getProperties().put(prop.specificName, value == null ? Memory.NULL : value); } private static interface SetterCallback { Memory invoke(Memory o1, Memory o2); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ClassEntity)) return false; if (!super.equals(o)) return false; ClassEntity entity = (ClassEntity) o; if (id != entity.id) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (int) (id ^ (id >>> 32)); return result; } public static class InvalidConstant { public final ConstantEntity constant; public final ConstantEntity prototype; public final ErrorType errorType; protected InvalidConstant(ConstantEntity constant, ConstantEntity prototype, ErrorType errorType) { this.constant = constant; this.errorType = errorType; this.prototype = prototype; } public static InvalidConstant error(ConstantEntity constant, ConstantEntity prototype){ return new InvalidConstant(constant, prototype, ErrorType.E_ERROR); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof InvalidConstant)) return false; InvalidConstant that = (InvalidConstant) o; return constant.equals(that.constant); } @Override public int hashCode() { return constant.hashCode(); } } public static class InvalidMethod { public enum Kind { NON_EXISTS, INVALID_SIGNATURE, MUST_STATIC, MUST_NON_STATIC, MAGIC_MUST_BE_PUBLIC, MUST_BE_PUBLIC, MUST_BE_PROTECTED, FINAL, NON_ABSTRACT, NON_ABSTRACTABLE, INVALID_ACCESS_FOR_INTERFACE, FINAL_ABSTRACT, OVERRIDE_CONSTANTS } public final Kind kind; public final MethodEntity method; public final ErrorType errorType; protected InvalidMethod(Kind kind, MethodEntity method, ErrorType errorType) { this.kind = kind; this.method = method; this.errorType = errorType; } public static InvalidMethod warning(Kind kind, MethodEntity method){ return new InvalidMethod(kind, method, ErrorType.E_WARNING); } public static InvalidMethod error(Kind kind, MethodEntity method){ return new InvalidMethod(kind, method, ErrorType.E_ERROR); } public static InvalidMethod strict(Kind kind, MethodEntity method){ return new InvalidMethod(kind, method, ErrorType.E_STRICT); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof InvalidMethod)) return false; InvalidMethod that = (InvalidMethod) o; return method.equals(that.method) && kind.equals(that.kind); } @Override public int hashCode() { int result = kind.hashCode(); result = 31 * result + method.hashCode(); return result; } } public static class InvalidProperty { public enum Kind { MUST_BE_PROTECTED, MUST_BE_PUBLIC, STATIC_AS_NON_STATIC, NON_STATIC_AS_STATIC } public final Kind kind; public final PropertyEntity property; public final ErrorType errorType; protected InvalidProperty(Kind kind, PropertyEntity property, ErrorType errorType) { this.kind = kind; this.property = property; this.errorType = errorType; } public static InvalidProperty warning(Kind kind, PropertyEntity property){ return new InvalidProperty(kind, property, ErrorType.E_WARNING); } public static InvalidProperty error(Kind kind, PropertyEntity property){ return new InvalidProperty(kind, property, ErrorType.E_ERROR); } public static InvalidProperty strict(Kind kind, PropertyEntity property){ return new InvalidProperty(kind, property, ErrorType.E_STRICT); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof InvalidProperty)) return false; InvalidProperty that = (InvalidProperty) o; return property.equals(that.property) && kind.equals(that.kind); } @Override public int hashCode() { int result = kind.hashCode(); result = 31 * result + property.hashCode(); return result; } } public class PropertyResult { private final Set<InvalidProperty> properties; public PropertyResult() { this.properties = new HashSet<InvalidProperty>(); } public void add(InvalidProperty prop){ this.properties.add(prop); } public void addError(InvalidProperty.Kind kind, PropertyEntity prop){ add(InvalidProperty.error(kind, prop)); } public void check(Environment env){ for (InvalidProperty el : properties){ ErrorException e = null; switch (el.kind){ case MUST_BE_PROTECTED: e = new FatalException( Messages.ERR_ACCESS_LEVEL_MUST_BE_PROTECTED_OR_WEAKER.fetch( el.property.clazz.getName(), el.property.getName(), el.property.getPrototype().getClazz().getName() ), el.property.getTrace() ); break; case MUST_BE_PUBLIC: e = new FatalException( Messages.ERR_ACCESS_LEVEL_MUST_BE_PUBLIC.fetch( el.property.clazz.getName(), el.property.getName(), el.property.getPrototype().getClazz().getName() ), el.property.getTrace() ); break; case STATIC_AS_NON_STATIC: e = new FatalException( Messages.ERR_CANNOT_REDECLARE_STATIC_AS_NON_STATIC.fetch( el.property.getPrototype().getClazz().getName(), el.property.getPrototype().getName(), el.property.clazz.getName(), el.property.getName() ), el.property.getTrace() ); break; case NON_STATIC_AS_STATIC: e = new FatalException( Messages.ERR_CANNOT_REDECLARE_NON_STATIC_AS_STATIC.fetch( el.property.getPrototype().getClazz().getName(), el.property.getPrototype().getName(), el.property.clazz.getName(), el.property.getName() ), el.property.getTrace() ); break; } if (e != null) if (env == null) throw e; else env.error(e.getTraceInfo(), el.errorType, e.getMessage()); } } } public class ImplementsResult { ClassEntity parent; SignatureResult signature; ImplementsResult(ClassEntity parent) { this.parent = parent; this.signature = new SignatureResult(); } public void check(Environment env){ if (parent != null){ if (parent.isNotRuntime && !isInternal()) { FatalException e = new FatalException( Messages.ERR_CANNOT_USE_SYSTEM_CLASS.fetch(parent.getName(), getName()), ClassEntity.this.trace ); if (env != null) env.error(e.getTraceInfo(), e.getType(), e.getMessage()); else throw e; } } if (signature != null) signature.check(env); } } public class ExtendsResult { ClassEntity parent; SignatureResult methods; ExtendsResult(ClassEntity parent) { this.parent = parent; this.methods = new SignatureResult(); } public void check(Environment env){ if (parent != null){ if (parent.isNotRuntime && !isInternal()) { FatalException e = new FatalException( Messages.ERR_CANNOT_USE_SYSTEM_CLASS.fetch(parent.getName(), getName()), ClassEntity.this.trace ); if (env != null) env.error(e.getTraceInfo(), e.getType(), e.getMessage()); else throw e; } if (parent.isFinal){ FatalException e = new FatalException( Messages.ERR_CLASS_MAY_NOT_INHERIT_FINAL_CLASS.fetch(ClassEntity.this.getName(), parent.getName()), ClassEntity.this.trace ); if (env != null) env.error(e.getTraceInfo(), e.getType(), e.getMessage()); else throw e; } if (ClassEntity.this.type == Type.CLASS && parent.type != Type.CLASS){ FatalException e = new FatalException( Messages.ERR_CANNOT_EXTENDS.fetch(ClassEntity.this.getName(), parent.getName()), ClassEntity.this.trace ); if (env != null) env.error(e.getTraceInfo(), e.getType(), e.getMessage()); else throw e; } } if (methods != null) methods.check(env); } } public class SignatureResult { private final Set<InvalidMethod> methods; private Set<InvalidConstant> overrideConstants_; SignatureResult() { methods = new HashSet<InvalidMethod>(); } public void add(InvalidMethod el){ methods.add(el); } public void addConstant(InvalidConstant el){ if (overrideConstants_ == null) overrideConstants_ = new HashSet<InvalidConstant>(); overrideConstants_.add(el); } public void check(){ check(null); } private ErrorException getException(Environment env, InvalidMethod el, Messages.Item message){ return getException(env, el, message, false); } private ErrorException getException(Environment env, InvalidMethod el, Messages.Item message, boolean prototype){ ErrorException e; if (prototype){ e = new FatalException( message.fetch( el.method.getPrototype().getSignatureString(false), el.method.getSignatureString(false) ), el.method.getTrace() ); } else { e = new FatalException( message.fetch(el.method.getSignatureString(false)), el.method.getTrace() ); } return e; } public void check(Environment env){ if (overrideConstants_ != null) for (InvalidConstant e : this.overrideConstants_){ if (env != null) env.error( getTrace(), e.errorType, Messages.ERR_CANNOT_INHERIT_OVERRIDE_CONSTANT, e.constant.getName(), e.prototype.getClazz().getName() ); } Set<InvalidMethod> nonExists = null; for(InvalidMethod el : methods){ ErrorException e = null; switch (el.kind){ case INVALID_SIGNATURE: MethodEntity prototype = el.method.getPrototype(); if (!prototype.isAbstractable()) { while (prototype.prototype != null && prototype.prototype.isAbstractable()) prototype = prototype.prototype; } e = new FatalException( Messages.ERR_INVALID_METHOD_SIGNATURE.fetch( el.method.getSignatureString(false), prototype.getSignatureString(true) ), el.method.getTrace() ); break; case MUST_STATIC: e = new FatalException( Messages.ERR_CANNOT_MAKE_STATIC_TO_NON_STATIC.fetch( el.method.getPrototype().getSignatureString(false), ClassEntity.this.getName() ), el.method.getTrace() ); break; case MUST_NON_STATIC: e = new FatalException( Messages.ERR_CANNOT_MAKE_NON_STATIC_TO_STATIC.fetch( el.method.getPrototype().getSignatureString(false), ClassEntity.this.getName() ), el.method.getTrace() ); break; case MAGIC_MUST_BE_PUBLIC: env.error(el.method.getTrace(), el.errorType, "The magic method %s must have public visibility", el.method.getSignatureString(false) ); break; case MUST_BE_PROTECTED: e = new FatalException( Messages.ERR_ACCESS_LEVEL_METHOD_MUST_BE_PROTECTED_OR_WEAKER.fetch( el.method.clazz.getName(), el.method.getName(), el.method.getPrototype().getClazz().getName() ), el.method.getTrace() ); break; case MUST_BE_PUBLIC: e = new FatalException( Messages.ERR_ACCESS_LEVEL_METHOD_MUST_BE_PUBLIC.fetch( el.method.clazz.getName(), el.method.getName(), el.method.getPrototype().getClazz().getName() ), el.method.getTrace() ); break; case FINAL_ABSTRACT: e = getException(env, el, Messages.ERR_CANNOT_USE_FINAL_ON_ABSTRACT); break; case FINAL: e = getException(env, el, Messages.ERR_CANNOT_OVERRIDE_FINAL_METHOD, true); break; case NON_ABSTRACT: e = getException(env, el, Messages.ERR_NON_ABSTRACT_METHOD_MUST_CONTAIN_BODY); break; case NON_ABSTRACTABLE: e = getException(env, el, Messages.ERR_ABSTRACT_METHOD_CANNOT_CONTAIN_BODY); break; case INVALID_ACCESS_FOR_INTERFACE: e = getException(env, el, Messages.ERR_ACCESS_TYPE_FOR_INTERFACE_METHOD); break; case NON_EXISTS: if (nonExists == null) nonExists = new HashSet<InvalidMethod>(); nonExists.add(el); break; } if (e != null) if (env == null) throw e; else { env.error(e.getTraceInfo(), el.errorType, e.getMessage()); } } if (nonExists != null){ StringBuilder needs = new StringBuilder(); Iterator<InvalidMethod> iterator = nonExists.iterator(); int size = 0; ErrorType errorType = ErrorType.E_NOTICE; while (iterator.hasNext()) { InvalidMethod el = iterator.next(); if (el.errorType.value < errorType.value) errorType = el.errorType; needs.append(el.method.getClazz().getName()) .append("::") .append(el.method.getName()); if (iterator.hasNext()) needs.append(", "); size++; } ErrorException e = new FatalException( Messages.ERR_IMPLEMENT_METHOD.fetch(ClassEntity.this.getName(), size, needs), ClassEntity.this.getTrace() ); if (env == null) throw e; else { env.error(e.getTraceInfo(), errorType, e.getMessage()); } } } } }
package hclient; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import org.apache.commons.lang3.StringUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CookieStore; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig.Builder; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.protocol.RequestAcceptEncoding; import org.apache.http.client.protocol.ResponseContentEncoding; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.cookie.ClientCookie; import org.apache.http.cookie.Cookie; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultRedirectStrategy; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.RedirectLocations; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import core.FileNameUtils; import core.RegExp; import core.WebDocument; import core.WebResource; import hclient.cache.ClientCache; import hclient.cookies.CustomCookieStore; import hclient.json.SerializedCookie; public class HTTPClient { private final static Logger LOGGER = LoggerFactory.getLogger( HTTPClient.class ); private final static String USER_AGENT = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0"; private final static int TIMEOUT = 60 * 1000; private ClientCache cache = ClientCache.getInstance(); private CloseableHttpClient apacheClient; private CustomCookieStore cookieStore = new CustomCookieStore(); public static final long REFRESH_ONE_HOUR = 60 * 60 * 1000; public static final long REFRESH_ONE_DAY = REFRESH_ONE_HOUR * 24; public static final long REFRESH_ONE_WEEK = REFRESH_ONE_DAY * 7; public static final long REFRESH_ONE_MONTH = REFRESH_ONE_DAY * 30; static class SingletonHolder { static HTTPClient instance = new HTTPClient(); } public static HTTPClient getInstance() { return SingletonHolder.instance; } public void setNonExpiringCookieDomain( String domain ) { cookieStore.setNonExpiring(domain); } public void addCookie( BasicClientCookie cookie ) { cookieStore.addCookie( cookie ); } public void addCookie( String domain, String name, String value ) { BasicClientCookie cookie = new BasicClientCookie(name, value); setDomain(cookie, domain); cookieStore.addCookie( cookie ); } public void addCookie( String domain, String path, String name, String value, Date expiryDate ) { BasicClientCookie cookie = new BasicClientCookie(name, value); setDomain(cookie, domain); cookie.setPath(path); cookie.setExpiryDate(expiryDate); cookieStore.addCookie( cookie ); } private void setDomain(BasicClientCookie cookie, String domain) { if (domain.startsWith(".")) { domain = domain.substring(1); } cookie.setDomain( domain ); cookie.setAttribute(ClientCookie.DOMAIN_ATTR, domain); } public void clearCookies() { cookieStore.clear(); } private CloseableHttpClient buildClient( HttpHost proxyHost ) { HttpClientBuilder builder = HttpClientBuilder.create(); builder.setUserAgent( USER_AGENT ); builder.setDefaultCookieStore( cookieStore ); builder.addInterceptorFirst(new RequestAcceptEncoding()); builder.addInterceptorFirst(new ResponseContentEncoding()); builder.setRedirectStrategy( new BugFixedRedirectStrategy() ); Builder defaultRequestConfigBuilder = RequestConfig.custom() .setSocketTimeout(TIMEOUT) .setConnectTimeout(TIMEOUT) .setConnectionRequestTimeout(TIMEOUT); if ( proxyHost != null ) { defaultRequestConfigBuilder.setProxy( proxyHost ); } builder.setDefaultRequestConfig( defaultRequestConfigBuilder.build() ); try { SSLContext context = SSLContexts.custom().loadTrustMaterial( new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(context, new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); builder.setSSLSocketFactory( sslsf ); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return builder.build(); } private HTTPClient() { // System.setProperty("java.net.useSystemProxies", "true"); // System.setProperty("http.nonProxyHosts", "localhost|127.*|10.*|[::1]"); // List<Proxy> l = null; // try { // } catch (URISyntaxException e) { // if (l != null) { // for (Proxy proxy : l) { // InetSocketAddress addr = (InetSocketAddress) proxy.address(); // if (addr != null) { // System.setProperty("http.proxyHost", addr.getHostName()); // System.setProperty("http.proxyPort", Integer.toString(addr.getPort())); String proxyHostName = System.getProperty("http.proxyHost"); String proxyPort = System.getProperty("http.proxyPort"); HttpHost proxyHost = null; if (StringUtils.isNotBlank( proxyHostName ) && StringUtils.isNumeric( proxyPort )) { proxyHost = new HttpHost( proxyHostName, Integer.parseInt( proxyPort ) ); } apacheClient = buildClient( proxyHost ); Path cookiesFile = Paths.get("cookies.json"); if (Files.isReadable(cookiesFile)) { try { readCookies(cookiesFile); } catch (IOException e) { LOGGER.error(e.getMessage(), e); try { Files.deleteIfExists( cookiesFile ); } catch (IOException eDelete) { LOGGER.error(e.getMessage(), eDelete); } } } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { serializeCookies(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } }); } public synchronized void readCookies(Path cookiesFile) throws JsonParseException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, SerializedCookie.class); List<SerializedCookie> cookies = mapper.readValue( new File("cookies.json"), type); for (SerializedCookie cookie : cookies) { BasicClientCookie clientCookie = new BasicClientCookie( cookie.getName(), cookie.getValue() ); if (cookie.getExpiryDate() > 0) { clientCookie.setExpiryDate( new Date( cookie.getExpiryDate() )); } clientCookie.setVersion( cookie.getVersion() ); setDomain( clientCookie, cookie.getDomain() ); clientCookie.setComment( cookie.getComment() ); clientCookie.setPath( cookie.getPath() ); clientCookie.setSecure( cookie.isSecure() ); cookieStore.addCookie( clientCookie ); } } public synchronized void serializeCookies() throws JsonGenerationException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); mapper.writeValue( new File( "cookies.json"), getCookieStore().getCookies()); } public WebDocument getXML(String url, String referer, long cacheRefreshPeriod ) throws IOException { SimpleResponse contents = get( url, referer, cacheRefreshPeriod ); WebDocument document = new WebDocument( url, contents.getStringContents() ); document.setXml( true ); return document; } public InputStream getStream( String url, String referer ) throws MalformedURLException, IOException { return getStream( url, referer, 0 ); } public InputStream getStream( String url, String referer, long cacheRefreshPeriod) throws IOException { SimpleResponse response = get( url, referer, cacheRefreshPeriod ); return new ByteArrayInputStream( response.getByteContents() ); } public SimpleResponse get( String url, String referer, long cacheRefreshPeriod ) throws IOException { SimpleResponse cachedContent = null; if (cacheRefreshPeriod > 0) { cachedContent = (SimpleResponse) cache.getFromCache(url); } if (cachedContent == null) { // Get the value URL uURL = new URL( url ); HttpGet httpget; try { httpget = RequestFactory.getGet( uURL, referer ); } catch (URISyntaxException e) { throw new IOException(e.getMessage(), e); } HttpContext context = new BasicHttpContext(); if (httpget == null) { LOGGER.error(String.format("Request null for URL %s", url.toString())); return null; } HttpResponse response = apacheClient.execute( httpget, context ); try { HttpEntity entity = response.getEntity(); String mimeType = null; Charset charSet = null; try { ContentType ct = ContentType.getOrDefault( entity ); mimeType = ct.getMimeType(); charSet = ct.getCharset(); } catch (UnsupportedCharsetException e) { } String fileName = null; Header contentDisposition = response.getLastHeader("Content-Disposition"); if (contentDisposition != null && StringUtils.isNotBlank(contentDisposition.getValue())) { List<String> groups = RegExpMatcher.groups( contentDisposition.getValue(), ".*filename\\*?=\"(.*)\""); if (groups == null) { groups = RegExpMatcher.groups( contentDisposition.getValue(), ".*filename\\*?=(.*)"); } if (groups != null && groups.size() > 0) { fileName = groups.get(0); } else { LOGGER.error("Unsupported Content-Disposition format : {}", contentDisposition.getValue()); } } if (fileName == null) { fileName = FileNameUtils.sanitizeFileName( url.substring( url.lastIndexOf('/') + 1) ); } int statusCode = response.getStatusLine().getStatusCode(); cachedContent = new SimpleResponse( url, statusCode, EntityUtils.toByteArray(entity), fileName, mimeType, charSet ); cachedContent.setRedirectLocations( (RedirectLocations) context.getAttribute( DefaultRedirectStrategy.REDIRECT_LOCATIONS) ); if ( statusCode == 200 ) { cache.putInCache( url, cachedContent, cacheRefreshPeriod ); } } finally { httpget.releaseConnection(); } } return cachedContent; } public SimpleResponse get( String url ) throws IOException { return get( url, null, 0 ); } public SimpleResponse get( String url, long cacheRefreshPeriod ) throws IOException { return get( url, null, cacheRefreshPeriod ); } public SimpleResponse get( String url, String referer ) throws IOException { return get( url, referer, 0 ); } public Path download( String url ) throws IOException { return download( url, null, null ); } public Path download( String url, String referer ) throws IOException { return download(url, referer, null); } public Path download( String url, String referer, Path destinationFolder ) throws IOException { return download( url, referer, destinationFolder, 0 ); } public String downloadToFile( WebResource resource, Path destinationFile, long cacheRefreshPeriod ) throws IOException { SimpleResponse response = get( resource.getUrl(), resource.getReferer(), cacheRefreshPeriod ); createFile(response, destinationFile); return response.getContentType(); } private Path createFile(SimpleResponse response, Path destinationFile) throws IOException { Files.createDirectories( destinationFile.getParent() ); try (InputStream input = response.newStream()) { Files.copy( input, destinationFile, StandardCopyOption.REPLACE_EXISTING); } return destinationFile; } public Path download( String url, String referer, Path destinationFolder, long cacheRefreshPeriod ) throws IOException { String fileName = FileNameUtils.sanitizeFileName( url.substring( url.lastIndexOf('/') + 1) ); if (destinationFolder == null) { destinationFolder = Files.createTempDirectory("httpclient"); } SimpleResponse response = get( url, referer, cacheRefreshPeriod ); if (response.getCode() == 404) { return null; } Path destinationFile = null; if (!StringUtils.isEmpty( response.getFileName() )) { destinationFile = destinationFolder.resolve( response.getFileName() ); } else { if (StringUtils.isEmpty( fileName )) { destinationFile = Files.createTempFile( destinationFolder, "", "" ); } else { destinationFile = destinationFolder.resolve( fileName ); } } return createFile(response, destinationFile); } public boolean downloadImage( String url, String referer, Path destinationFile ) throws IOException { HttpGet httpget; try { httpget = RequestFactory.getGet( new URL(url), referer ); } catch (URISyntaxException e) { throw new IOException(e.getMessage(), e); } HttpResponse response = apacheClient.execute(httpget); HttpEntity entity = response.getEntity(); long contentLength = entity.getContentLength(); if (contentLength != -1) { EntityUtils.consume(entity); return false; } String contentType = entity.getContentType().getValue(); if (contentType.startsWith("image/")) { try (OutputStream output = Files.newOutputStream( destinationFile, StandardOpenOption.CREATE)) { byte[] bytes = EntityUtils.toByteArray( entity ); output.write( bytes ); } if (Files.size(destinationFile) < contentLength) { Files.delete(destinationFile); } return true; } else { EntityUtils.consume(entity); } return false; } public SimpleResponse post( String url, String referer, Map<String, Object> params) throws IOException { return post( url, referer != null ? new URL( referer ) : null, params, false ); } public SimpleResponse post( String url, String referer, Map<String, Object> params, boolean ajax) throws IOException { return post( url, referer != null ? new URL( referer ) : null, params, ajax ); } public SimpleResponse post( String url, URL referer, Map<String, Object> params, boolean ajax ) throws IOException { List <NameValuePair> nvps = new ArrayList <NameValuePair>(); for (Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> entry = iterator.next(); String name = entry.getKey(); if (entry.getValue() instanceof File ) { // partsList.add( new FilePart(name, (File) entry.getValue()) ) ; } else { nvps.add(new BasicNameValuePair(name, entry.getValue().toString())); } } return post( url, referer, new UrlEncodedFormEntity(nvps, Charset.forName("UTF-8")), ajax ); } protected SimpleResponse post( String url, URL referer, AbstractHttpEntity postEntity, boolean ajax ) throws IOException { HttpPost post = RequestFactory.getPost(url, referer); post.setEntity( postEntity ); HttpContext context = new BasicHttpContext(); if (ajax) { post.setHeader("X-Requested-With", "XMLHttpRequest"); post.setHeader("Pragma", "no-cache"); post.setHeader("Cache-Control", "no-cache"); } HttpResponse response = apacheClient.execute( post, context ); try { Header contentDisposition = response.getLastHeader("Content-Disposition"); String fileName = null; if (contentDisposition != null) { fileName = RegExpMatcher.groups( contentDisposition.getValue(), ".*filename=\"(.*)\"").get(0); } HttpEntity entity = response.getEntity(); ContentType ct = ContentType.getOrDefault( entity ); SimpleResponse sr = new SimpleResponse( url, response.getStatusLine().getStatusCode(), EntityUtils.toByteArray( entity ), fileName, ct.getMimeType(), ct.getCharset() ); sr.setRedirectLocations( (RedirectLocations) context.getAttribute( DefaultRedirectStrategy.REDIRECT_LOCATIONS) ); return sr; } finally { post.releaseConnection(); } } public String getCookie( String domain ) { for (Cookie cookie : cookieStore.getCookies()) { if (StringUtils.equals(cookie.getDomain(), domain)) { return cookie.getName() + "=" + cookie.getValue(); } } return null; } public CookieStore getCookieStore() { return cookieStore; } public WebDocument getDocument( String url, long cacheRefreshPeriod ) throws IOException { return getDocument( url, null, cacheRefreshPeriod); } public WebDocument getDocument( String url ) throws IOException { return getDocument( url, null, 0); } public WebDocument getDocument( String url, String referer, long cacheRefreshPeriod ) throws IOException { SimpleResponse response = get( url, referer, cacheRefreshPeriod ); if (response == null) { return null; } return new WebDocument( response.getCode(), url.toString(), response.getStringContents(), response.getContentType() ); } public Reader getReader(String url, String referer, long cacheRefreshPeriod ) throws IOException, URISyntaxException { SimpleResponse response = get( url, referer, cacheRefreshPeriod ); return new StringReader( response.getStringContents() ); } public void setProxy(HttpHost proxyHost) { apacheClient = buildClient(proxyHost); } public SimpleResponse post(String url, String referer, String... params) throws IOException { return post( url, referer, false, params ); } public SimpleResponse postAjax(String url, String referer, String... params) throws IOException { return post( url, referer, true, params ); } protected SimpleResponse post(String url, String referer, boolean ajax, String... parameters) throws IOException { Map<String, Object> paramsMap = getParamsMap( parameters ); return post(url, referer, paramsMap, ajax); } protected Map<String, Object> getParamsMap( String... parameters ) { Map<String, Object> paramsMap = new HashMap<String, Object>(); if (parameters != null) { for (String param : parameters) { String[] keyVal = RegExp.parseGroups( param, "([ paramsMap.put( keyVal[0], keyVal[1] != null ? keyVal[1] : "" ); } } return paramsMap; } public SimpleResponse submit(Element jsoupFormElement, String... parameters) throws IOException { Map<String, Object> paramsMap = getParamsMap( parameters ); Elements inputElements = jsoupFormElement.select("input"); for (Element input : inputElements) { String name = input.attr("name"); if (StringUtils.isNotEmpty( name )) { String value = input.attr("value"); if (!paramsMap.containsKey( name )) { if (StringUtils.isNotEmpty( value )) { paramsMap.put( name, value ); } } } } String url = jsoupFormElement.baseUri(); if (url.endsWith("/")) { url = url.substring(0, url.length() - 1); } String method = jsoupFormElement.attr("method"); SimpleResponse response = null; String action = jsoupFormElement.attr("action"); if ( StringUtils.equalsIgnoreCase(method, "POST")) { String submitURL = url; if (action != null) { if (action.startsWith("/")) { submitURL = url + action; } else { submitURL = url.substring(0, url.lastIndexOf('/') + 1) + action; } } response = post( submitURL, url, paramsMap, false ); } else { // TODO } return response; } public SimpleResponse postJSON(String url, URL referer, String... parameters) throws ClientProtocolException, UnsupportedEncodingException, IOException { Map<String, Object> paramsMap = getParamsMap( parameters ); ObjectMapper mapper = new ObjectMapper(); String jsonRequest = mapper.writeValueAsString( paramsMap ); return post(url, referer, new StringEntity( jsonRequest ), false ); } public HttpResponse execute(HttpUriRequest request) throws IOException { return apacheClient.execute(request); } public void removeCache(String url) { cache.removeCache( url ); } }
package com.opengamma.examples.loader; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.time.calendar.LocalDateTime; import javax.time.calendar.TimeZone; import javax.time.calendar.ZonedDateTime; import com.opengamma.core.region.RegionUtils; import com.opengamma.core.security.SecurityUtils; import com.opengamma.examples.tool.AbstractExampleTool; import com.opengamma.financial.convention.businessday.BusinessDayConvention; import com.opengamma.financial.convention.businessday.BusinessDayConventionFactory; import com.opengamma.financial.convention.daycount.DayCount; import com.opengamma.financial.convention.daycount.DayCountFactory; import com.opengamma.financial.convention.frequency.SimpleFrequency; import com.opengamma.financial.convention.yield.SimpleYieldConvention; import com.opengamma.financial.security.FinancialSecurity; import com.opengamma.financial.security.bond.GovernmentBondSecurity; import com.opengamma.financial.security.capfloor.CapFloorSecurity; import com.opengamma.financial.security.equity.EquityVarianceSwapSecurity; import com.opengamma.financial.security.fra.FRASecurity; import com.opengamma.financial.security.future.BondFutureDeliverable; import com.opengamma.financial.security.future.BondFutureSecurity; import com.opengamma.financial.security.future.EquityFutureSecurity; import com.opengamma.financial.security.future.EquityIndexDividendFutureSecurity; import com.opengamma.financial.security.future.InterestRateFutureSecurity; import com.opengamma.financial.security.fx.FXForwardSecurity; import com.opengamma.financial.security.option.AmericanExerciseType; import com.opengamma.financial.security.option.BarrierDirection; import com.opengamma.financial.security.option.BarrierType; import com.opengamma.financial.security.option.EuropeanExerciseType; import com.opengamma.financial.security.option.FXBarrierOptionSecurity; import com.opengamma.financial.security.option.FXOptionSecurity; import com.opengamma.financial.security.option.IRFutureOptionSecurity; import com.opengamma.financial.security.option.MonitoringType; import com.opengamma.financial.security.option.OptionType; import com.opengamma.financial.security.option.SamplingFrequency; import com.opengamma.financial.security.option.SwaptionSecurity; import com.opengamma.financial.security.swap.FixedInterestRateLeg; import com.opengamma.financial.security.swap.FloatingInterestRateLeg; import com.opengamma.financial.security.swap.FloatingRateType; import com.opengamma.financial.security.swap.FloatingSpreadIRLeg; import com.opengamma.financial.security.swap.InterestRateNotional; import com.opengamma.financial.security.swap.SwapSecurity; import com.opengamma.id.ExternalId; import com.opengamma.id.ExternalIdBundle; import com.opengamma.id.ExternalScheme; import com.opengamma.master.portfolio.ManageablePortfolio; import com.opengamma.master.portfolio.ManageablePortfolioNode; import com.opengamma.master.portfolio.PortfolioDocument; import com.opengamma.master.portfolio.PortfolioMaster; import com.opengamma.master.position.ManageablePosition; import com.opengamma.master.position.PositionDocument; import com.opengamma.master.position.PositionMaster; import com.opengamma.master.security.SecurityDocument; import com.opengamma.master.security.SecurityMaster; import com.opengamma.util.GUIDGenerator; import com.opengamma.util.i18n.Country; import com.opengamma.util.money.Currency; import com.opengamma.util.time.Expiry; /** * Example code to load a multi asset portfolio. */ public class ExampleMultiAssetPortfolioLoader extends AbstractExampleTool { /** * Example mixed portfolio name */ public static final String PORTFOLIO_NAME = "Multi Asset Portfolio"; /** * Portfolio currencies */ public static final Currency[] s_currencies = new Currency[] {Currency.USD, Currency.GBP, Currency.EUR, Currency.JPY, Currency.CHF, Currency.NZD, Currency.DKK}; private static final String ID_SCHEME = "MULTI_ASSET_PORFOLIO_LOADER"; private static final DayCount DAY_COUNT = DayCountFactory.INSTANCE.getDayCount("Actual/360"); private static final BusinessDayConvention BUSINESS_DAY = BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Following"); private static final ExternalId USDLIBOR3M = ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "USDLIBORP3M"); public static void main(String[] args) { //CSIGNORE new ExampleMultiAssetPortfolioLoader().initAndRun(args); System.exit(0); } private void persistToPortfolio() { PortfolioMaster portfolioMaster = getToolContext().getPortfolioMaster(); ManageablePortfolioNode rootNode = new ManageablePortfolioNode(PORTFOLIO_NAME); ManageablePortfolio portfolio = new ManageablePortfolio(PORTFOLIO_NAME, rootNode); PortfolioDocument portfolioDoc = new PortfolioDocument(); portfolioDoc.setPortfolio(portfolio); addPortfolioNode(rootNode, getIborSwaps(), "Ibor swaps", BigDecimal.ONE); addPortfolioNode(rootNode, getCMSwaps(), "CM swaps", BigDecimal.ONE); // addPortfolioNode(rootNode, getSimpleFixedIncome(), "Fixed income", BigDecimal.ONE); // addPortfolioNode(rootNode, getSimpleFX(), "FX forward", BigDecimal.ONE); addPortfolioNode(rootNode, getFXOptions(), "FX options", BigDecimal.ONE); // addBondNode(rootNode); addPortfolioNode(rootNode, getSwaptions(), "Swaptions", BigDecimal.ONE); addPortfolioNode(rootNode, getIborCapFloor(), "Ibor cap/floor", BigDecimal.ONE); addPortfolioNode(rootNode, getCMCapFloor(), "CM cap/floor", BigDecimal.ONE); // addPortfolioNode(rootNode, getIRFutureOptions(), "IR future options", BigDecimal.valueOf(100)); // addEquityNode(rootNode); portfolioMaster.add(portfolioDoc); } private void addEquityNode(ManageablePortfolioNode rootNode) { final ManageablePortfolioNode portfolioNode = new ManageablePortfolioNode("Equity"); EquityVarianceSwapSecurity equityVarianceSwap = new EquityVarianceSwapSecurity(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "DJX"), Currency.USD, 0.5, 1000000.0, true, 250.0, ZonedDateTime.of(LocalDateTime.of(2010, 11, 1, 16, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2012, 11, 1, 16, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2010, 11, 1, 16, 0), TimeZone.UTC), RegionUtils.currencyRegionId(Currency.USD), SimpleFrequency.DAILY); equityVarianceSwap.setName("Equity Variance Swap, USD 1MM, strike=0.5, maturing 2012-11-01"); equityVarianceSwap.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); storeFinancialSecurity(equityVarianceSwap); addPosition(portfolioNode, equityVarianceSwap, BigDecimal.ONE); EquityIndexDividendFutureSecurity dividendFuture = new EquityIndexDividendFutureSecurity(new Expiry(ZonedDateTime.of(LocalDateTime.of(2011, 12, 16, 17, 30), TimeZone.UTC)), "XEUR", "XEUR", Currency.USD, 1000.0, ZonedDateTime.of(LocalDateTime.of(2011, 12, 16, 17, 30), TimeZone.UTC), ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "HSBA")); dividendFuture.setName("HSBC Holdings SSDF Dec11"); dividendFuture.addExternalId(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "H2SBZ1GR")); storeFinancialSecurity(dividendFuture); addPosition(portfolioNode, dividendFuture, BigDecimal.valueOf(100)); EquityFutureSecurity equityFuture = new EquityFutureSecurity(new Expiry(ZonedDateTime.of(LocalDateTime.of(2011, 12, 16, 17, 30), TimeZone.UTC)), "XCME", "XCME", Currency.USD, 250.0, ZonedDateTime.of(LocalDateTime.of(2012, 12, 20, 21, 15), TimeZone.UTC), ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "SPX")); equityFuture.setName("S&P 500 FUTURE Dec12"); equityFuture.addExternalId(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "SPZ2")); storeFinancialSecurity(equityFuture); addPosition(portfolioNode, equityFuture, BigDecimal.ONE); rootNode.addChildNode(portfolioNode); } private void addBondNode(ManageablePortfolioNode rootNode) { final ManageablePortfolioNode portfolioNode = new ManageablePortfolioNode("Bonds"); final GovernmentBondSecurity bond1 = new GovernmentBondSecurity("US TREASURY N/B", "Sovereign", "US", "US GOVERNMENT", Currency.USD, SimpleYieldConvention.US_STREET, new Expiry(ZonedDateTime.of(LocalDateTime.of(2013, 12, 15, 16, 0), TimeZone.UTC)), "FIXED", 2.625, SimpleFrequency.SEMI_ANNUAL, DayCountFactory.INSTANCE.getDayCount("Actual/Actual ICMA"), ZonedDateTime.of(LocalDateTime.of(2009, 5, 30, 18, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2011, 5, 28, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2009, 12, 31, 11, 0), TimeZone.UTC), 99.651404, 3.8075E10, 100.0, 100.0, 100.0, 100.0); bond1.addExternalId(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "US912828KY53")); bond1.setName("T 2 5/8 06/30/14"); storeFinancialSecurity(bond1); addPosition(portfolioNode, bond1, BigDecimal.valueOf(2120)); final GovernmentBondSecurity bond2 = new GovernmentBondSecurity("US TREASURY N/B", "Sovereign", "US", "US GOVERNMENT", Currency.USD, SimpleYieldConvention.US_STREET, new Expiry(ZonedDateTime.of(LocalDateTime.of(2015, 8, 31, 18, 0), TimeZone.UTC)), "FIXED", 1.25, SimpleFrequency.SEMI_ANNUAL, DayCountFactory.INSTANCE.getDayCount("Actual/Actual ICMA"), ZonedDateTime.of(LocalDateTime.of(2010, 8, 31, 18, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2011, 2, 14, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2011, 2, 28, 11, 0), TimeZone.UTC), 99.402797, 3.6881E10, 100.0, 100.0, 100.0, 100.0); bond2.addExternalId(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "US912828NV87")); bond2.setName("T 1 1/4 08/31/15"); storeFinancialSecurity(bond2); addPosition(portfolioNode, bond2, BigDecimal.valueOf(3940)); final GovernmentBondSecurity bond3 = new GovernmentBondSecurity("TSY 8% 2021", "Sovereign", "GB", "UK GILT STOCK", Currency.GBP, SimpleYieldConvention.UK_BUMP_DMO_METHOD, new Expiry(ZonedDateTime.of(LocalDateTime.of(2021, 6, 7, 18, 0), TimeZone.UTC)), "FIXED", 8.0, SimpleFrequency.SEMI_ANNUAL, DayCountFactory.INSTANCE.getDayCount("Actual/Actual ISDA"), ZonedDateTime.of(LocalDateTime.of(1996, 2, 29, 18, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2011, 1, 28, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(1996, 6, 7, 12, 0), TimeZone.UTC), 99.0625, 2.2686E10, 0.01, 0.01, 100.0, 100.0); bond3.addExternalId(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "GB0009997999")); bond3.setName("UKT 8 06/07/21"); bond3.setAnnouncementDate(ZonedDateTime.of(LocalDateTime.of(1996, 2, 20, 11, 0), TimeZone.UTC)); storeFinancialSecurity(bond3); addPosition(portfolioNode, bond3, BigDecimal.valueOf(4690)); final List<BondFutureDeliverable> bondFutureDelivarables = new ArrayList<BondFutureDeliverable>(); bondFutureDelivarables.add(new BondFutureDeliverable(ExternalIdBundle.of(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "GV912810FF0")), 0.9221)); bondFutureDelivarables.add(new BondFutureDeliverable(ExternalIdBundle.of(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "GV912810FJ2")), 1.0132)); bondFutureDelivarables.add(new BondFutureDeliverable(ExternalIdBundle.of(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "GV912810FA1")), 1.037)); bondFutureDelivarables.add(new BondFutureDeliverable(ExternalIdBundle.of(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "GV912810FE3")), 0.9485)); bondFutureDelivarables.add(new BondFutureDeliverable(ExternalIdBundle.of(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "GV912810FB9")), 1.0125)); bondFutureDelivarables.add(new BondFutureDeliverable(ExternalIdBundle.of(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "GV912810FM5")), 1.0273)); bondFutureDelivarables.add(new BondFutureDeliverable(ExternalIdBundle.of(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "GV912810FG8")), 0.9213)); bondFutureDelivarables.add(new BondFutureDeliverable(ExternalIdBundle.of(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "GV912810PT9")), 0.8398)); bondFutureDelivarables.add(new BondFutureDeliverable(ExternalIdBundle.of(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "GV912810FP8")), 0.9301)); bondFutureDelivarables.add(new BondFutureDeliverable(ExternalIdBundle.of(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "GV912810FT0")), 0.8113)); final BondFutureSecurity bond4 = new BondFutureSecurity(new Expiry(ZonedDateTime.of(LocalDateTime.of(2012, 3, 21, 20, 0), TimeZone.UTC)), "XCBT", "XCBT", Currency.USD, 1000.0, bondFutureDelivarables, "Bond", ZonedDateTime.of(LocalDateTime.of(2012, 3, 1, 0, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2012, 3, 1, 0, 0), TimeZone.UTC)); bond4.setName("US LONG BOND(CBT) Mar12"); bond4.addExternalId(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "USH12")); storeFinancialSecurity(bond4); addPosition(portfolioNode, bond4, BigDecimal.valueOf(10)); rootNode.addChildNode(portfolioNode); } private void addPosition(final ManageablePortfolioNode portfolioNode, final FinancialSecurity security, final BigDecimal quantity) { PositionMaster positionMaster = getToolContext().getPositionMaster(); ManageablePosition position = new ManageablePosition(quantity, security.getExternalIdBundle()); PositionDocument addedDoc = positionMaster.add(new PositionDocument(position)); portfolioNode.addPosition(addedDoc.getUniqueId()); } private Collection<FinancialSecurity> getIRFutureOptions() { List<FinancialSecurity> securities = new ArrayList<FinancialSecurity>(); InterestRateFutureSecurity edu12 = new InterestRateFutureSecurity(new Expiry(ZonedDateTime.of(LocalDateTime.of(2012, 9, 17, 20, 0), TimeZone.UTC)), "XCME", "XCME", Currency.USD, 2500.0, USDLIBOR3M); edu12.addExternalId(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "EDU12")); edu12.setName("90DAY EURO$ FUTR Sep12"); storeFinancialSecurity(edu12); AmericanExerciseType exerciseType = new AmericanExerciseType(); IRFutureOptionSecurity optionSec1 = new IRFutureOptionSecurity("CME", new Expiry(ZonedDateTime.of(LocalDateTime.of(2012, 9, 17, 0, 0), TimeZone.UTC)), exerciseType, ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "EDU12"), 6.25, false, Currency.USD, 98.0, OptionType.PUT); optionSec1.addExternalId(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "EDU2P98")); optionSec1.setName("EDU2P 2012-09-17 P 98.0"); storeFinancialSecurity(optionSec1); securities.add(optionSec1); InterestRateFutureSecurity edz12 = new InterestRateFutureSecurity(new Expiry(ZonedDateTime.of(LocalDateTime.of(2012, 12, 17, 20, 0), TimeZone.UTC)), "XCME", "XCME", Currency.USD, 2500.0, USDLIBOR3M); edz12.addExternalId(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "EDZ12")); edz12.setName("90DAY EURO$ FUTR Dec12"); storeFinancialSecurity(edz12); IRFutureOptionSecurity optionSec2 = new IRFutureOptionSecurity("CME", new Expiry(ZonedDateTime.of(LocalDateTime.of(2012, 12, 17, 0, 0), TimeZone.UTC)), exerciseType, ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "EDZ12"), 6.25, false, Currency.USD, 99.0, OptionType.CALL); optionSec2.addExternalId(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "EDU2P98")); optionSec2.setName("EDZ2C 2012-12-17 C 99.0"); storeFinancialSecurity(optionSec2); securities.add(optionSec2); return securities; } private void storeFinancialSecurity(final FinancialSecurity security) { SecurityMaster securityMaster = getToolContext().getSecurityMaster(); SecurityDocument toAddDoc = new SecurityDocument(); toAddDoc.setSecurity(security); securityMaster.add(toAddDoc); } private void addPortfolioNode(final ManageablePortfolioNode rootNode, final Collection<FinancialSecurity> finSecurities, final String portfolioNodeName, BigDecimal quantity) { PositionMaster positionMaster = getToolContext().getPositionMaster(); final ManageablePortfolioNode portfolioNode = new ManageablePortfolioNode(portfolioNodeName); for (final FinancialSecurity security : finSecurities) { storeFinancialSecurity(security); ManageablePosition position = new ManageablePosition(quantity, security.getExternalIdBundle()); PositionDocument addedDoc = positionMaster.add(new PositionDocument(position)); portfolioNode.addPosition(addedDoc.getUniqueId()); } rootNode.addChildNode(portfolioNode); } private List<FinancialSecurity> getCMCapFloor() { final List<FinancialSecurity> securities = new ArrayList<FinancialSecurity>(); final CapFloorSecurity cmsCap = new CapFloorSecurity(ZonedDateTime.of(LocalDateTime.of(2011, 4, 1, 1, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2016, 4, 1, 1, 0), TimeZone.UTC), 1.5E7, ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "USDISDA10P10Y"), 0.03, SimpleFrequency.ANNUAL, Currency.USD, DayCountFactory.INSTANCE.getDayCount("Actual/360"), false, true, false); cmsCap.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); cmsCap.setName(getCapFloorName(cmsCap)); securities.add(cmsCap); final CapFloorSecurity cmsFloor = new CapFloorSecurity(ZonedDateTime.of(LocalDateTime.of(2011, 9, 9, 1, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2016, 9, 9, 1, 0), TimeZone.UTC), 1.5E7, ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "USDISDA10P10Y"), 0.01, SimpleFrequency.SEMI_ANNUAL, Currency.USD, DayCountFactory.INSTANCE.getDayCount("Actual/360"), false, false, false); cmsFloor.setName(getCapFloorName(cmsFloor)); cmsFloor.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); securities.add(cmsFloor); return securities; } private String getCapFloorName(final CapFloorSecurity capFloorSec) { return String.format("%s %s @ %.2f [%s-%s] %s, %s %s %s", capFloorSec.isIbor() ? "IBOR" : "CMS", capFloorSec.isCap() ? "cap " : "floor ", capFloorSec.getStrike(), capFloorSec.getStartDate().toLocalDate(), capFloorSec.getMaturityDate().toLocalDate(), capFloorSec.getFrequency().getConventionName(), capFloorSec.getCurrency().getCode(), PortfolioLoaderHelper.NOTIONAL_FORMATTER.format(capFloorSec.getNotional()), capFloorSec.isPayer() ? " Short" : " Long"); } private List<FinancialSecurity> getIborSwaps() { final List<FinancialSecurity> securities = new ArrayList<FinancialSecurity>(); final SwapSecurity swap1 = new SwapSecurity( ZonedDateTime.of(LocalDateTime.of(2000, 5, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2000, 5, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2040, 5, 1, 11, 0), TimeZone.UTC), "Cpty", new FixedInterestRateLeg(DAY_COUNT, SimpleFrequency.SEMI_ANNUAL, RegionUtils.countryRegionId(Country.of("US")), BUSINESS_DAY, new InterestRateNotional(Currency.USD, 15000000), true, 0.05), new FloatingInterestRateLeg(DAY_COUNT, SimpleFrequency.QUARTERLY, RegionUtils.countryRegionId(Country.of("US")), BUSINESS_DAY, new InterestRateNotional(Currency.USD, 15000000), true, USDLIBOR3M, FloatingRateType.IBOR)); swap1.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); swap1.setName("Swap: pay 5% fixed vs 3m Libor, start=1/5/2000, maturity=1/5/2040, notional=USD 15MM"); final SwapSecurity swap2 = new SwapSecurity( ZonedDateTime.of(LocalDateTime.of(2005, 5, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2005, 5, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2030, 5, 1, 11, 0), TimeZone.UTC), "Cpty", new FixedInterestRateLeg(DAY_COUNT, SimpleFrequency.SEMI_ANNUAL, RegionUtils.countryRegionId(Country.of("DE")), BUSINESS_DAY, new InterestRateNotional(Currency.EUR, 20000000), true, 0.04), new FloatingInterestRateLeg(DAY_COUNT, SimpleFrequency.QUARTERLY, RegionUtils.countryRegionId(Country.of("DE")), BUSINESS_DAY, new InterestRateNotional(Currency.EUR, 20000000), true, ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "USDLIBORP6M"), FloatingRateType.IBOR)); swap2.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); swap2.setName("Swap: pay 4% fixed vs 6m Euribor, start=1/5/2005, maturity=1/5/2030, notional=EUR 20MM"); final SwapSecurity swap3 = new SwapSecurity( ZonedDateTime.of(LocalDateTime.of(2007, 5, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2007, 5, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2020, 5, 1, 11, 0), TimeZone.UTC), "Cpty", new FixedInterestRateLeg(DAY_COUNT, SimpleFrequency.SEMI_ANNUAL, RegionUtils.countryRegionId(Country.of("GB")), BUSINESS_DAY, new InterestRateNotional(Currency.GBP, 15000000), true, 0.03), new FloatingInterestRateLeg(DAY_COUNT, SimpleFrequency.QUARTERLY, RegionUtils.countryRegionId(Country.of("GB")), BUSINESS_DAY, new InterestRateNotional(Currency.GBP, 15000000), true, ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "GBPLIBORP6M"), FloatingRateType.IBOR)); swap3.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); swap3.setName("Swap: pay 3% fixed vs 6m Libor, start=1/5/2007, maturity=1/5/2020, notional=GBP 15MM"); final SwapSecurity swap4 = new SwapSecurity( ZonedDateTime.of(LocalDateTime.of(2003, 5, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2003, 5, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2028, 5, 1, 11, 0), TimeZone.UTC), "Cpty", new FixedInterestRateLeg(DAY_COUNT, SimpleFrequency.SEMI_ANNUAL, RegionUtils.countryRegionId(Country.of("JP")), BUSINESS_DAY, new InterestRateNotional(Currency.JPY, 100000000), true, 0.02), new FloatingInterestRateLeg(DAY_COUNT, SimpleFrequency.QUARTERLY, RegionUtils.countryRegionId(Country.of("JP")), BUSINESS_DAY, new InterestRateNotional(Currency.JPY, 100000000), true, ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "JPYLIBORP6M"), FloatingRateType.IBOR)); swap4.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); swap4.setName("Swap: pay 2% fixed vs 6m Libor, start=1/5/2003, maturity=1/5/2028, notional=JPY 100MM"); final SwapSecurity swap5 = new SwapSecurity( ZonedDateTime.of(LocalDateTime.of(2004, 5, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2004, 5, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2044, 5, 1, 11, 0), TimeZone.UTC), "Cpty", new FixedInterestRateLeg(DAY_COUNT, SimpleFrequency.SEMI_ANNUAL, RegionUtils.countryRegionId(Country.of("CH")), BUSINESS_DAY, new InterestRateNotional(Currency.CHF, 5000000), true, 0.07), new FloatingInterestRateLeg(DAY_COUNT, SimpleFrequency.QUARTERLY, RegionUtils.countryRegionId(Country.of("CH")), BUSINESS_DAY, new InterestRateNotional(Currency.CHF, 5000000), true, ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "CHFLIBORP6M"), FloatingRateType.IBOR)); swap5.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); swap5.setName("Swap: pay 7% fixed vs 6m Libor, start=1/5/2004, maturity=1/5/2044, notional=CHF 50MM"); // final SwapSecurity swap6 = new SwapSecurity( // ZonedDateTime.of(LocalDateTime.of(2010, 5, 1, 11, 0), TimeZone.UTC), // ZonedDateTime.of(LocalDateTime.of(2010, 5, 1, 11, 0), TimeZone.UTC), // ZonedDateTime.of(LocalDateTime.of(2040, 5, 1, 11, 0), TimeZone.UTC), // "Cpty", // new FixedInterestRateLeg(DAY_COUNT, // SimpleFrequency.SEMI_ANNUAL, // RegionUtils.countryRegionId(Country.of("CA")), // BUSINESS_DAY, // new InterestRateNotional(Currency.CAD, 20000000), // true, // 0.05), // new FloatingInterestRateLeg(DAY_COUNT, // SimpleFrequency.QUARTERLY, // RegionUtils.countryRegionId(Country.of("CA")), // BUSINESS_DAY, // new InterestRateNotional(Currency.CAD, 20000000), // true, // ExternalId.of(SecurityUtils.BLOOMBERG_TICKER, "CDOR06 RBC Index"), // FloatingRateType.IBOR)); // swap6.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); // swap6.setName("Swap: pay 5% fixed vs 6m CDOR, start=1/5/2010, maturity=1/5/2040, notional=CAD 20MM"); // final SwapSecurity swap7 = new SwapSecurity( // ZonedDateTime.of(LocalDateTime.of(2005, 5, 1, 11, 0), TimeZone.UTC), // ZonedDateTime.of(LocalDateTime.of(2005, 5, 1, 11, 0), TimeZone.UTC), // ZonedDateTime.of(LocalDateTime.of(2025, 5, 1, 11, 0), TimeZone.UTC), // "Cpty", // new FixedInterestRateLeg(DAY_COUNT, // SimpleFrequency.SEMI_ANNUAL, // RegionUtils.countryRegionId(Country.of("AU")), // BUSINESS_DAY, // new InterestRateNotional(Currency.AUD, 25000000), // true, // 0.05), // new FloatingInterestRateLeg(DAY_COUNT, // SimpleFrequency.QUARTERLY, // RegionUtils.countryRegionId(Country.of("AU")), // BUSINESS_DAY, // new InterestRateNotional(Currency.AUD, 25000000), // true, // ExternalId.of(SecurityUtils.BLOOMBERG_TICKER, "AU0006M Index"), // FloatingRateType.IBOR)); // swap7.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); // swap7.setName("Swap: pay 5% fixed vs 6m Libor, start=1/5/2005, maturity=1/5/2025, notional=AUD 25MM"); /* final SwapSecurity swap8 = new SwapSecurity( ZonedDateTime.of(LocalDateTime.of(2010, 5, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2010, 5, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2030, 5, 1, 11, 0), TimeZone.UTC), "Cpty", new FixedInterestRateLeg(DAY_COUNT, SimpleFrequency.SEMI_ANNUAL, RegionUtils.countryRegionId(Country.of("NZ")), BUSINESS_DAY, new InterestRateNotional(Currency.NZD, 55000000), true, 0.05), new FloatingInterestRateLeg(DAY_COUNT, SimpleFrequency.QUARTERLY, RegionUtils.countryRegionId(Country.of("NZ")), BUSINESS_DAY, new InterestRateNotional(Currency.NZD, 55000000), true, ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "NZDLIBORP6M"), FloatingRateType.IBOR)); swap8.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); swap8.setName("Swap: pay 5% fixed vs 6m Libor, start=1/5/2010, maturity=1/5/2030, notional=NZD 55MM"); */ final SwapSecurity swap9 = new SwapSecurity( ZonedDateTime.of(LocalDateTime.of(2010, 5, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2010, 5, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2030, 5, 1, 11, 0), TimeZone.UTC), "Cpty", new FixedInterestRateLeg(DAY_COUNT, SimpleFrequency.SEMI_ANNUAL, RegionUtils.countryRegionId(Country.of("DK")), BUSINESS_DAY, new InterestRateNotional(Currency.DKK, 90000000), true, 0.05), new FloatingInterestRateLeg(DAY_COUNT, SimpleFrequency.QUARTERLY, RegionUtils.countryRegionId(Country.of("DK")), BUSINESS_DAY, new InterestRateNotional(Currency.DKK, 90000000), true, ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "DKKLIBORP6M"), FloatingRateType.IBOR)); swap9.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); swap9.setName("Swap: pay 5% fixed vs 6m Cibor, start=1/5/2010, maturity=1/5/2030, notional=DKK 90MM"); securities.add(swap1); securities.add(swap2); securities.add(swap3); securities.add(swap4); securities.add(swap5); // securities.add(swap6); // securities.add(swap7); /*securities.add(swap8);*/ securities.add(swap9); return securities; } private Collection<FinancialSecurity> getCMSwaps() { final List<FinancialSecurity> securities = new ArrayList<FinancialSecurity>(); final SwapSecurity swap1 = new SwapSecurity( ZonedDateTime.of(LocalDateTime.of(2011, 12, 20, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2011, 12, 20, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2016, 12, 20, 11, 0), TimeZone.UTC), "Cpty", new FixedInterestRateLeg(DAY_COUNT, SimpleFrequency.QUARTERLY, RegionUtils.countryRegionId(Country.of("US")), BUSINESS_DAY, new InterestRateNotional(Currency.USD, 21000000), true, 0.035), new FloatingInterestRateLeg(DAY_COUNT, SimpleFrequency.QUARTERLY, RegionUtils.countryRegionId(Country.of("US")), BUSINESS_DAY, new InterestRateNotional(Currency.USD, 21000000), true, ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "USDISDA10P10Y"), FloatingRateType.CMS)); swap1.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); swap1.setName("CMSwap: pay 5Y fixed @ 3.5% vs USDISDA10P10Y, start=20/12/2011, maturity=20/12/2016, notional=USD 21MM"); final SwapSecurity swap2 = new SwapSecurity( ZonedDateTime.of(LocalDateTime.of(2011, 4, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2011, 4, 1, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2018, 4, 1, 11, 0), TimeZone.UTC), "Cpty", new FloatingInterestRateLeg(DAY_COUNT, SimpleFrequency.QUARTERLY, RegionUtils.countryRegionId(Country.of("US")), BUSINESS_DAY, new InterestRateNotional(Currency.USD, 123000000), true, ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "USDISDA10P1Y"), FloatingRateType.CMS), new FloatingSpreadIRLeg(DAY_COUNT, SimpleFrequency.QUARTERLY, RegionUtils.countryRegionId(Country.of("US")), BUSINESS_DAY, new InterestRateNotional(Currency.USD, 123000000), true, USDLIBOR3M, FloatingRateType.IBOR, 0.005)); swap2.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); swap2.setName("CMSwap: pay USDISDA10P1Y vs 3m Libor, start=1/4/2011, maturity=1/4/2018, notional=USD 123MM"); securities.add(swap1); securities.add(swap2); return securities; } private Collection<FinancialSecurity> getSwaptions() { final List<FinancialSecurity> securities = new ArrayList<FinancialSecurity>(); final EuropeanExerciseType europeanExerciseType = new EuropeanExerciseType(); final SwapSecurity swap1 = new SwapSecurity( ZonedDateTime.of(LocalDateTime.of(2012, 6, 1, 1, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2012, 6, 1, 1, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2022, 6, 1, 1, 0), TimeZone.UTC), "Cpty", new FloatingInterestRateLeg(DAY_COUNT, SimpleFrequency.QUARTERLY, RegionUtils.financialRegionId("US+GB"), BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Modified Following"), new InterestRateNotional(Currency.USD, 1.0E7), false, USDLIBOR3M, FloatingRateType.IBOR), new FixedInterestRateLeg(DayCountFactory.INSTANCE.getDayCount("30U/360"), SimpleFrequency.SEMI_ANNUAL, RegionUtils.financialRegionId("US+GB"), BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Modified Following"), new InterestRateNotional(Currency.USD, 1.0E7), false, 0.04)); swap1.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); swap1.setName("Swap: pay 3m Libor vs 4% fixed, start=1/6/2012, maturity=1/6/2022, notional=USD 10MM"); storeFinancialSecurity(swap1); final SwaptionSecurity swaption1 = new SwaptionSecurity(false, swap1.getExternalIdBundle().getExternalId(ExternalScheme.of(ID_SCHEME)), true, new Expiry(ZonedDateTime.of(LocalDateTime.of(2012, 6, 1, 1, 0), TimeZone.UTC)), true, Currency.USD, null, europeanExerciseType, null); swaption1.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); swaption1.setName("Vanilla swaption, 1Y x 10Y, USD 10,000,000 @ 4%"); securities.add(swaption1); final SwapSecurity swap2 = new SwapSecurity( ZonedDateTime.of(LocalDateTime.of(2013, 6, 1, 1, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2013, 6, 1, 1, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2015, 6, 1, 1, 0), TimeZone.UTC), "Cpty", new FloatingInterestRateLeg(DAY_COUNT, SimpleFrequency.QUARTERLY, RegionUtils.financialRegionId("US+GB"), BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Modified Following"), new InterestRateNotional(Currency.USD, 3000000.0), false, USDLIBOR3M, FloatingRateType.IBOR), new FixedInterestRateLeg(DayCountFactory.INSTANCE.getDayCount("30U/360"), SimpleFrequency.SEMI_ANNUAL, RegionUtils.financialRegionId("US+GB"), BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Modified Following"), new InterestRateNotional(Currency.USD, 3000000.0), false, 0.01)); swap2.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); swap2.setName("Swap: pay 3m Libor vs 1% fixed, start=1/6/2013, maturity=1/6/2015, notional=USD 3MM"); storeFinancialSecurity(swap2); final SwaptionSecurity swaption2 = new SwaptionSecurity(false, swap2.getExternalIdBundle().getExternalId(ExternalScheme.of(ID_SCHEME)), false, new Expiry(ZonedDateTime.of(LocalDateTime.of(2013, 6, 1, 1, 0), TimeZone.UTC)), true, Currency.USD, null, europeanExerciseType, null); swaption2.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); swaption2.setName("Vanilla swaption, 2Y x 2Y, USD 3,000,000 @ 1%"); securities.add(swaption2); final SwapSecurity swap3 = new SwapSecurity( ZonedDateTime.of(LocalDateTime.of(2016, 6, 1, 1, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2016, 6, 1, 1, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2031, 6, 1, 1, 0), TimeZone.UTC), "Cpty", new FloatingInterestRateLeg(DAY_COUNT, SimpleFrequency.QUARTERLY, RegionUtils.financialRegionId("US+GB"), BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Modified Following"), new InterestRateNotional(Currency.USD, 6000000.0), false, USDLIBOR3M, FloatingRateType.IBOR), new FixedInterestRateLeg(DayCountFactory.INSTANCE.getDayCount("30U/360"), SimpleFrequency.SEMI_ANNUAL, RegionUtils.financialRegionId("US+GB"), BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Modified Following"), new InterestRateNotional(Currency.USD, 6000000.0), false, 0.035)); swap3.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); swap3.setName("Swap: pay 3m Libor vs 3.5% fixed, start=1/6/2016, maturity=1/6/2031, notional=USD 6MM"); storeFinancialSecurity(swap3); final SwaptionSecurity swaption3 = new SwaptionSecurity(false, swap3.getExternalIdBundle().getExternalId(ExternalScheme.of(ID_SCHEME)), false, new Expiry(ZonedDateTime.of(LocalDateTime.of(2016, 6, 1, 1, 0), TimeZone.UTC)), true, Currency.USD, null, europeanExerciseType, null); swaption3.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); swaption3.setName("Vanilla swaption, 5Y x 15Y, USD 6,000,000 @ 3.5%"); securities.add(swaption3); return securities; } private Collection<FinancialSecurity> getIborCapFloor() { final List<FinancialSecurity> securities = new ArrayList<FinancialSecurity>(); final CapFloorSecurity sec1 = new CapFloorSecurity(ZonedDateTime.of(LocalDateTime.of(2011, 1, 1, 1, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2014, 1, 1, 1, 0), TimeZone.UTC), 1.5E7, USDLIBOR3M, 0.01, SimpleFrequency.QUARTERLY, Currency.USD, DayCountFactory.INSTANCE.getDayCount("30U/360"), false, true, true); sec1.setName(getCapFloorName(sec1)); sec1.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); securities.add(sec1); final CapFloorSecurity sec2 = new CapFloorSecurity(ZonedDateTime.of(LocalDateTime.of(2011, 1, 1, 1, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2014, 1, 1, 1, 0), TimeZone.UTC), 1.5E7, USDLIBOR3M, 0.01, SimpleFrequency.QUARTERLY, Currency.USD, DayCountFactory.INSTANCE.getDayCount("30U/360"), false, false, true); sec2.setName(getCapFloorName(sec2)); sec2.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); securities.add(sec2); return securities; } private static Collection<FinancialSecurity> getSimpleFixedIncome() { final List<FinancialSecurity> securities = new ArrayList<FinancialSecurity>(); final FRASecurity fra = new FRASecurity(Currency.USD, RegionUtils.countryRegionId(Country.of("US")), ZonedDateTime.of(LocalDateTime.of(2012, 1, 14, 11, 0), TimeZone.UTC), ZonedDateTime.of(LocalDateTime.of(2012, 4, 14, 11, 0), TimeZone.UTC), 0.01, 15000000, USDLIBOR3M, ZonedDateTime.of(LocalDateTime.of(2011, 1, 14, 11, 0), TimeZone.UTC)); fra.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); fra.setName("FRA: pay 1% vs 3m Libor, start=1/14/2012, maturity=4/14/2012, notional=USD 15MM"); final InterestRateFutureSecurity irFuture = new InterestRateFutureSecurity(new Expiry(ZonedDateTime.of(LocalDateTime.of(2013, 12, 15, 16, 0), TimeZone.UTC)), "CME", "CME", Currency.USD, 1000, USDLIBOR3M); irFuture.addExternalId(ExternalId.of(SecurityUtils.OG_SYNTHETIC_TICKER, "EDZ13")); irFuture.setName("90DAY EURO$ FUTR Jun13"); securities.add(fra); securities.add(irFuture); return securities; } private static Collection<FinancialSecurity> getSimpleFX() { final List<FinancialSecurity> securities = new ArrayList<FinancialSecurity>(); final FXForwardSecurity fxForward1 = new FXForwardSecurity(Currency.USD, 1000000, Currency.EUR, 1000000, ZonedDateTime.of(LocalDateTime.of(2013, 2, 1, 11, 0), TimeZone.UTC), RegionUtils.countryRegionId(Country.of("US"))); fxForward1.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); fxForward1.setName("FX forward, pay USD 1000000, receive EUR 1000000, maturity=1/2/2013"); // final FXForwardSecurity fxForward2 = new FXForwardSecurity(Currency.CAD, 800000, Currency.JPY, 80000000, // ZonedDateTime.of(LocalDateTime.of(2013, 2, 1, 11, 0), TimeZone.UTC), // RegionUtils.countryRegionId(Country.of("US"))); // fxForward2.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); // fxForward2.setName("FX forward, pay CAD 800000, receive JPY 80000000, maturity=1/2/2013"); final FXForwardSecurity fxForward3 = new FXForwardSecurity(Currency.CHF, 2000000, Currency.EUR, 1000000, ZonedDateTime.of(LocalDateTime.of(2013, 2, 1, 11, 0), TimeZone.UTC), RegionUtils.countryRegionId(Country.of("US"))); fxForward3.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); fxForward3.setName("FX forward, pay CHF 2000000, receive EUR 1000000, maturity=1/2/2013"); securities.add(fxForward1); // securities.add(fxForward2); securities.add(fxForward3); return securities; } private static Collection<FinancialSecurity> getFXOptions() { final List<FinancialSecurity> securities = new ArrayList<FinancialSecurity>(); final FXOptionSecurity vanilla1 = new FXOptionSecurity(Currency.USD, Currency.EUR, 1000000, 1000000, new Expiry(ZonedDateTime.of(LocalDateTime.of(2013, 1, 6, 11, 0), TimeZone.UTC)), ZonedDateTime.of(LocalDateTime.of(2013, 1, 6, 11, 0), TimeZone.UTC), true, new EuropeanExerciseType()); vanilla1.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); vanilla1.setName("FX vanilla option, put USD 1000000, receive EUR 1000000, maturity=1/6/2013"); final FXOptionSecurity vanilla2 = new FXOptionSecurity(Currency.EUR, Currency.USD, 1500000, 1000000, new Expiry(ZonedDateTime.of(LocalDateTime.of(2014, 1, 6, 11, 0), TimeZone.UTC)), ZonedDateTime.of(LocalDateTime.of(2014, 1, 6, 11, 0), TimeZone.UTC), true, new EuropeanExerciseType()); vanilla2.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); vanilla2.setName("FX vanilla option, put EUR 1500000, receive USD 1000000, maturity=1/6/2014"); final FXBarrierOptionSecurity barrier1 = new FXBarrierOptionSecurity(Currency.USD, Currency.EUR, 1000000, 1000000, new Expiry(ZonedDateTime.of(LocalDateTime.of(2013, 1, 6, 11, 0), TimeZone.UTC)), ZonedDateTime.of(LocalDateTime.of(2013, 1, 6, 11, 0), TimeZone.UTC), BarrierType.UP, BarrierDirection.KNOCK_OUT, MonitoringType.CONTINUOUS, SamplingFrequency.DAILY_CLOSE, 1.5, true); barrier1.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); barrier1.setName("FX single barrier up knock-out option, put USD 1000000, receive EUR 1000000, maturity=1/6/2013, barrier=1.5 EUR/USD"); // final FXBarrierOptionSecurity barrier2 = new FXBarrierOptionSecurity(Currency.EUR, // Currency.USD, // 1500000, // 1000000, // new Expiry(ZonedDateTime.of(LocalDateTime.of(2015, 1, 6, 11, 0), TimeZone.UTC)), // ZonedDateTime.of(LocalDateTime.of(2015, 1, 6, 11, 0), TimeZone.UTC), // BarrierType.DOWN, // BarrierDirection.KNOCK_OUT, // MonitoringType.CONTINUOUS, // SamplingFrequency.DAILY_CLOSE, // true); // barrier2.addExternalId(ExternalId.of(ID_SCHEME, GUIDGenerator.generate().toString())); // barrier2.setName("FX single barrier down knock-out option, put EUR 1500000, receive USD 1000000, maturity=1/6/2015, barrier=0.2 USD/EUR"); securities.add(vanilla1); securities.add(vanilla2); securities.add(barrier1); // securities.add(barrier2); return securities; } @Override protected void doRun() { persistToPortfolio(); } }
package gov.nih.nci.cabig.caaers.dao; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Map; import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport; import gov.nih.nci.cabig.caaers.domain.AdverseEvent; import gov.nih.nci.cabig.caaers.domain.report.Report; import gov.nih.nci.cabig.caaers.dao.report.ReportDao; import gov.nih.nci.cabig.ctms.dao.MutableDomainObjectDao; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Propagation; import org.hibernate.LockMode; import org.hibernate.LazyInitializationException; /** * This class implements the Data access related operations for the ExpeditedAdverseEventReport * domain object. * * @author Rhett Sutphin * @author Krikor Krumlian */ @Transactional(readOnly = true) public class ExpeditedAdverseEventReportDao extends GridIdentifiableDao<ExpeditedAdverseEventReport> implements MutableDomainObjectDao<ExpeditedAdverseEventReport> { private static final String JOINS = " join o.adverseEventsInternal as adverseEvents join adverseEvents.adverseEventTerm as aeTerm join aeTerm.term as ctcTerm " + " join o.assignment as assignment join assignment.participant as p join p.identifiers as pIdentifier " + " join assignment.studySite as ss join ss.study as s join s.identifiers as sIdentifier"; private ReportDao reportDao; /** * Get the Class representation of the domain object that this DAO is representing. * * @return Class representation of the domain object that this DAO is representing. */ @Override public Class<ExpeditedAdverseEventReport> domainClass() { return ExpeditedAdverseEventReport.class; } /** * Get list of Adverse event reports with supplied criteria. * * @param subnames * The name fragments to search on. * @param substringMatchProperties * A list of properties of the implementing object which should be matched as * case-insensitive substrings * @see findBySubname {@link CaaersDao#findBySubname(String[], String, List, List, List)} * @return */ public List<ExpeditedAdverseEventReport> getByCriteria(final String[] subnames, final List<String> substringMatchProperties) { return findBySubname(subnames, null, null, substringMatchProperties, null, JOINS); } /** * @param report * Save the Expedited AE report. */ @Transactional(readOnly = false) public void save(final ExpeditedAdverseEventReport report) { getHibernateTemplate().saveOrUpdate(report); for (AdverseEvent ae : report.getAdverseEvents()) { getHibernateTemplate().saveOrUpdate(ae); } try { if (report.getReporter().isSavable()) { getHibernateTemplate().saveOrUpdate(report.getReporter()); } else { log.debug("Reporter not savable; skipping cascade"); } } catch (LazyInitializationException lie) { log.debug("Reporter not initialized, skipping cascade", lie); lie.printStackTrace(); } try { if (report.getPhysician().isSavable()) { getHibernateTemplate().saveOrUpdate(report.getPhysician()); } else { log.debug("Physican not savable; skipping cascade"); } } catch (LazyInitializationException lie) { log.debug("Physician not initialized, skipping cascade", lie); lie.printStackTrace(); } // delegate to ReportDao to save reports so that it can control transactionality for (Report r : report.getReports()) { reportDao.save(r); } } /** * This method will reassociate the domain object to hibernate session. With a lock mode none. * * @param report - * the domain object instance that is to be reassociated. */ @Override @Transactional(propagation = Propagation.SUPPORTS) public void reassociate(final ExpeditedAdverseEventReport report) { super.reassociate(report); if (report.getReporter().isTransient()) { log.debug("Reporter unsaved; skipping reassociate cascade"); } else { getHibernateTemplate().lock(report.getReporter(), LockMode.NONE); } if (report.getPhysician().isTransient()) { log.debug("Physican unsaved; skipping reassociate cascade"); } else { getHibernateTemplate().lock(report.getPhysician(), LockMode.NONE); } // delegate to ReportDao to reassociate reports so that it can control transactionality for (Report r : report.getReports()) { reportDao.reassociate(r); } } /** * Search for Adverse event reports with the supplied property list. * * @param props * The criteria for searching Adverse Event reports. * @return The list of Adverse event reports that match the criteria. * @throws ParseException */ @SuppressWarnings("unchecked") public List<ExpeditedAdverseEventReport> searchExpeditedReports(final Map props) throws ParseException { List<Object> params = new ArrayList<Object>(); boolean firstClause = true; StringBuilder queryBuf = new StringBuilder(" select distinct o from ").append( domainClass().getName()).append(" o ").append(JOINS); if (props.get("expeditedDate") != null) { queryBuf.append(firstClause ? " where " : " and "); queryBuf.append(" o.detectionDate").append(" = ? "); String p = (String) props.get("expeditedDate"); params.add(stringToDate(p)); firstClause = false; } if (props.get("ctcTerm") != null) { queryBuf.append(firstClause ? " where " : " and "); queryBuf.append("LOWER(").append("ctcTerm.term").append(") LIKE ?"); String p = (String) props.get("ctcTerm"); params.add('%' + p.toLowerCase() + '%'); firstClause = false; } if (props.get("ctcCtepCode") != null) { queryBuf.append(firstClause ? " where " : " and "); queryBuf.append("LOWER(").append("ctcTerm.ctepCode").append(") LIKE ?"); String p = (String) props.get("ctcCtepCode"); params.add('%' + p.toLowerCase() + '%'); firstClause = false; } if (props.get("ctcCategory") != null) { queryBuf.append(firstClause ? " where " : " and "); queryBuf.append("LOWER(").append("ctcTerm.category.name").append(") LIKE ?"); String p = (String) props.get("ctcCategory"); params.add(p.toLowerCase()); firstClause = false; } if (props.get("studyIdentifier") != null) { queryBuf.append(firstClause ? " where " : " and "); queryBuf.append("LOWER(").append("sIdentifier.value").append(") LIKE ?"); String p = (String) props.get("studyIdentifier"); params.add('%' + p.toLowerCase() + '%'); firstClause = false; } if (props.get("studyShortTitle") != null) { queryBuf.append(firstClause ? " where " : " and "); queryBuf.append("LOWER(").append("s.shortTitle").append(") LIKE ?"); String p = (String) props.get("studyShortTitle"); params.add('%' + p.toLowerCase() + '%'); firstClause = false; } if (props.get("participantIdentifier") != null) { queryBuf.append(firstClause ? " where " : " and "); queryBuf.append("LOWER(").append("pIdentifier.value").append(") LIKE ?"); String p = (String) props.get("participantIdentifier"); params.add('%' + p.toLowerCase() + '%'); firstClause = false; } if (props.get("participantFirstName") != null) { queryBuf.append(firstClause ? " where " : " and "); queryBuf.append("LOWER(").append("p.firstName").append(") LIKE ?"); String p = (String) props.get("participantFirstName"); params.add('%' + p.toLowerCase() + '%'); firstClause = false; } if (props.get("participantLastName") != null) { queryBuf.append(firstClause ? " where " : " and "); queryBuf.append("LOWER(").append("p.lastName").append(") LIKE ?"); String p = (String) props.get("participantLastName"); params.add('%' + p.toLowerCase() + '%'); firstClause = false; } if (props.get("participantEthnicity") != null) { queryBuf.append(firstClause ? " where " : " and "); queryBuf.append("LOWER(").append("p.ethnicity").append(") LIKE ?"); String p = (String) props.get("participantEthnicity"); params.add(p.toLowerCase()); firstClause = false; } if (props.get("participantGender") != null) { queryBuf.append(firstClause ? " where " : " and "); queryBuf.append("LOWER(").append("p.gender").append(") LIKE ?"); String p = (String) props.get("participantGender"); params.add(p.toLowerCase()); firstClause = false; } if (props.get("participantDateOfBirth") != null) { queryBuf.append(firstClause ? " where " : " and "); queryBuf.append(" p.dateOfBirth").append(" = ? "); String p = (String) props.get("participantDateOfBirth"); params.add(stringToDate(p)); firstClause = false; } log.debug("::: " + queryBuf.toString()); getHibernateTemplate().setMaxResults(CaaersDao.DEFAULT_MAX_RESULTS_SIZE); return getHibernateTemplate().find(queryBuf.toString(), params.toArray()); } /** * Set the report DAO. * * @param reportDao * The report DAO to be set. */ public void setReportDao(final ReportDao reportDao) { this.reportDao = reportDao; } }
package ch.heigvd.amt.moussaraser.rest.resources; import ch.heigvd.amt.moussaraser.model.entities.Badge; import ch.heigvd.amt.moussaraser.services.dao.BadgeDAOLocal; import java.util.List; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; @Stateless @Path("/badges") public class BadgeResource { @EJB BadgeDAOLocal badgeDAO; @GET @Produces("application/json") public List<Badge> getBadges() { return badgeDAO.findAll(); } @GET @Path("/{id}") @Produces("application/json") public Badge getBadge(@PathParam("id") long id) { return badgeDAO.findById(id); } }
package com.evolveum.midpoint.repo.sql.data.common; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.ForeignKey; import org.hibernate.annotations.Index; /** * @author lazyman */ @Entity @Table(name = "m_org_closure") public class ROrgClosure implements Serializable { private Long id; private RObject ancestor; private RObject descendant; private int depth; public ROrgClosure() { } public ROrgClosure(RObject ancestor, RObject descendant, int depth) { this.ancestor = ancestor; this.descendant = descendant; this.depth = depth; } @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Index(name = "iAncestor") @ManyToOne(fetch = FetchType.LAZY, optional=true) @JoinColumns({ @JoinColumn(name = "ancestor_oid", referencedColumnName = "oid"), @JoinColumn(name = "ancestor_id", referencedColumnName = "id") }) @ForeignKey(name = "fk_ancestor") public RObject getAncestor() { return ancestor; } public void setAncestor(RObject ancestor) { this.ancestor = ancestor; } @Index(name = "iDescendant") @ManyToOne(fetch = FetchType.LAZY, optional=true) @JoinColumns({ @JoinColumn(name = "descendant_oid", referencedColumnName = "oid"), @JoinColumn(name = "descendant_id", referencedColumnName = "id") }) @ForeignKey(name = "fk_descendant") public RObject getDescendant() { return descendant; } public void setDescendant(RObject descendant) { this.descendant = descendant; } public int getDepth() { return depth; } public void setDepth(int depth) { this.depth = depth; } @Override public int hashCode() { int result = ancestor != null ? ancestor.hashCode() : 0; result = 31 * result + (descendant != null ? descendant.hashCode() : 0); result = 31 * result + depth; // result = 31 * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; ROrgClosure that = (ROrgClosure) obj; if (depth != that.depth) return false; if (ancestor != null ? !ancestor.equals(that.ancestor) : that.ancestor != null) return false; if (descendant != null ? !descendant.equals(that.descendant) : that.descendant != null) return false; // if (id != null ? !id.equals(that.id) : that.id != null) // return false; return true; } }
package net.runelite.client.plugins.cluescrolls.clues; import com.google.common.collect.ImmutableSet; import java.awt.Color; import java.awt.Graphics2D; import java.util.Set; import lombok.Getter; import net.runelite.api.NPC; import static net.runelite.api.NullObjectID.NULL_1293; import net.runelite.api.ObjectComposition; import static net.runelite.api.ObjectID.*; import net.runelite.api.TileObject; 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 static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_BORDER_COLOR; import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_FILL_COLOR; import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_HOVER_BORDER_COLOR; import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.IMAGE_Z_OFFSET; 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 CrypticClue extends ClueScroll implements TextClueScroll, NpcClueScroll, ObjectClueScroll { public static final Set<CrypticClue> CLUES = ImmutableSet.of( new CrypticClue("Show this to Sherlock.", "Sherlock", new WorldPoint(2733, 3415, 0), "Sherlock is located to the east of the Sorcerer's tower in Seers' Village."), new CrypticClue("Talk to the bartender of the Rusty Anchor in Port Sarim.", "Bartender", new WorldPoint(3045, 3256, 0), "The Rusty Anchor is located in the north of Port Sarim."), new CrypticClue("The keeper of Melzars... Spare? Skeleton? Anar?", "Oziach", new WorldPoint(3068, 3516, 0), "Speak to Oziach in Edgeville"), new CrypticClue("Speak to Ulizius.", "Ulizius", new WorldPoint(3444, 3461, 0), "Ulizius is the monk who guards the gate into Mort Myre Swamp. South of fairy ring CKS"), new CrypticClue("Search for a crate in a building in Hemenster.", CRATE_357, new WorldPoint(2636, 3453, 0), "House north of the Fishing Contest quest area. West of Grandpa Jack."), new CrypticClue("A reck you say; let's pray there aren't any ghosts.", "Father Aereck", new WorldPoint(3242, 3207, 0), "Speak to Father Aereck in Lumbridge."), new CrypticClue("Search the bucket in the Port Sarim jail.", BUCKET_9568, new WorldPoint(3013, 3179, 0), "Talk to Shantay & identify yourself as an outlaw, refuse to pay the 5gp fine twice and you will be sent to the Port Sarim jail."), new CrypticClue("Search the crates in a bank in Varrock.", CRATE_5107, new WorldPoint(3187, 9825, 0), "Search in the basement of the West Varrock bank."), new CrypticClue("Falo the bard wants to see you.", "Falo the Bard", new WorldPoint(2689, 3550, 0), "Speak to Falo the Bard located between Seer's Village and Rellekka. Southwest of fairy ring CJR."), new CrypticClue("Search a bookcase in the Wizards tower.", BOOKCASE_12539, new WorldPoint(3113, 3159, 0), "The bookcase located on the ground floor."), new CrypticClue("Come have a cip with this great soot covered denizen.", "Miner Magnus", new WorldPoint(2527, 3891, 0), "Talk to Miner Magnus east of the fairy ring CIP. Answer: 8", "How many coal rocks are around here?"), new CrypticClue("Citric cellar.", "Heckel Funch", new WorldPoint(2490, 3488, 0), "Speak to Heckel Funch on the first floor in the Grand Tree."), new CrypticClue("I burn between heroes and legends.", "Candle maker", new WorldPoint(2799, 3438, 0), "Speak to the Candle maker in Catherby."), new CrypticClue("Speak to Sarah at Falador farm.", "Sarah", new WorldPoint(3038, 3292, 0), "Talk to Sarah at Falador farm, north of Port Sarim."), new CrypticClue("Search for a crate on the ground floor of a house in Seers' Village.", CRATE_25775, new WorldPoint(2699, 3470, 0), "Search inside Phantuwti Fanstuwi Farsight's house, located south of the pub in Seers' Village."), new CrypticClue("Snah? I feel all confused, like one of those cakes...", "Hans", new WorldPoint(3211, 3219, 0), "Talk to Hans roaming around Lumbridge Castle."), new CrypticClue("Speak to Sir Kay in Camelot Castle.", "Sir Kay", new WorldPoint(2759, 3497, 0), "Sir Kay can be found in the courtyard at Camelot castle."), new CrypticClue("Gold I see, yet gold I require. Give me 875 if death you desire.", "Saniboch", new WorldPoint(2745, 3151, 0), "Speak to Saniboch at the Brimhaven Dungeon entrance."), new CrypticClue("Find a crate close to the monks that like to paaarty!", CRATE_354, new WorldPoint(2614, 3204, 0), "The crate is in the east side of the Kandarin monastery, near Brother Omad"), new CrypticClue("Identify the back of this over-acting brother. (He's a long way from home.)", "Hamid", new WorldPoint(3376, 3284, 0), "Talk to Hamid, the monk at the altar in the Duel Arena"), new CrypticClue("In a town where thieves steal from stalls, search for some drawers in the upstairs of a house near the bank.", "Guard", DRAWERS, new WorldPoint(2611, 3324, 1), "Kill any Guard located around East Ardougne for a medium key. Then search the drawers in the upstairs hallway of Jerico's house, which is the house with pigeon cages located south of the northern East Ardougne bank."), new CrypticClue("His bark is worse than his bite.", "Barker", new WorldPoint(3499, 3503, 0), "Speak to the Barker at Canifis's Barkers' Haberdashery."), new CrypticClue("The beasts to my east snap claws and tails, The rest to my west can slide and eat fish. The force to my north will jump and they'll wail, Come dig by my fire and make a wish.", new WorldPoint(2598, 3267, 0), "Dig by the torch in the Ardougne Zoo, between the penguins and the scorpions."), new CrypticClue("A town with a different sort of night-life is your destination. Search for some crates in one of the houses.", CRATE_24344, new WorldPoint(3498, 3507, 0), "Search the crate inside of the clothes shop in Canifis."), new CrypticClue("Stop crying! Talk to the head.", "Head mourner", new WorldPoint(2042, 4630, 0), "Talk to the Head mourner in the mourner headquarters in West Ardougne"), new CrypticClue("Search the crate near a cart in Port Khazard.", CRATE_366, new WorldPoint(2660, 3149, 0), "Search by the southern Khazard General Store in Port Khazard."), new CrypticClue("Speak to the bartender of the Blue Moon Inn in Varrock.", "Bartender", new WorldPoint(3226, 3399, 0), "Talk to the bartender in Blue Moon Inn in Varrock."), new CrypticClue("This aviator is at the peak of his profession.", "Captain Bleemadge", new WorldPoint(2846, 1749, 0), "Captain Bleemadge, the gnome glider pilot, is found at the top of White Wolf Mountain."), new CrypticClue("Search the crates in the shed just north of East Ardougne.", CRATE_355, new WorldPoint(2617, 3347, 0), "The crates in the shed north of the northern Ardougne bank."), new CrypticClue("I wouldn't wear this jean on my legs.", "Father Jean", new WorldPoint(1734, 3576, 0), "Talk to father Jean in the Hosidius church"), new CrypticClue("Search the crate in the Toad and Chicken pub.", CRATE_354, new WorldPoint(2913, 3536, 0), "The Toad and Chicken pub is located in Burthorpe."), new CrypticClue("Search chests found in the upstairs of shops in Port Sarim.", CLOSED_CHEST_375, new WorldPoint(3016, 3205, 1), "Search the chest in the upstairs of Wydin's Food Store, on the east wall."), new CrypticClue("Right on the blessed border, cursed by the evil ones. On the spot inaccessible by both; I will be waiting. The bugs' imminent possession holds the answer.", new WorldPoint(3410, 3324, 0), "B I P. Dig right under the fairy ring."), new CrypticClue("The dead, red dragon watches over this chest. He must really dig the view.", "Barbarian", 375, new WorldPoint(3353, 3332, 0), "Search the chest underneath the Red Dragon's head in the Exam Centre. Kill a MALE Barbarian in Barbarian Village or Barbarian Outpost to receive the key."), new CrypticClue("My home is grey, and made of stone; A castle with a search for a meal. Hidden in some drawers I am, across from a wooden wheel.", DRAWERS_5618, new WorldPoint(3213, 3216, 1), "Open the drawers inside the room with the spinning wheel on the first floor of Lumbridge Castle."), new CrypticClue("Come to the evil ledge, Yew know yew want to. Try not to get stung.", new WorldPoint(3089, 3468, 0), "Dig in Edgeville, just east of the Southern Yew tree."), new CrypticClue("Look in the ground floor crates of houses in Falador.", CRATES_24088, new WorldPoint(3029, 3355, 0), "The house east of the east bank."), new CrypticClue("You were 3 and I was the 6th. Come speak to me.", "Vannaka", new WorldPoint(3146, 9913, 0), "Speak to Vannaka in Edgeville Dungeon."), new CrypticClue("Search the crates in Draynor Manor.", CRATE_11485, new WorldPoint(3106, 3369, 2), "Top floor of the manor"), new CrypticClue("Search the crates near a cart in Varrock.", CRATE_5107, new WorldPoint(3226, 3452, 0), "South east of Varrock Palace, south of the tree farming patch."), new CrypticClue("A Guthixian ring lies between two peaks. Search the stones and you'll find what you seek.", STONES_26633, new WorldPoint(2922, 3484, 0), "Search the stones several steps west of the Guthixian stone circle in Taverley"), new CrypticClue("Search the boxes in the house near the south entrance to Varrock.", BOXES_5111, new WorldPoint(3203, 3384, 0), "The first house on the left when entering the city from the southern entrance."), new CrypticClue("His head might be hollow, but the crates nearby are filled with surprises.", CRATE_354, new WorldPoint(3478, 3091, 0), "Search the crates near the Clay golem in the ruins of Uzer."), new CrypticClue("One of the sailors in Port Sarim is your next destination.", "Captain Tobias", new WorldPoint(3026, 3216, 0), "Speak to Captain Tobias on the docks of Port Sarim."), new CrypticClue("THEY'RE EVERYWHERE!!!! But they were here first. Dig for treasure where the ground is rich with ore.", new WorldPoint(3081, 3421, 0), "Dig at Barbarian Village, next to the Stronghold of Security."), new CrypticClue("Talk to the mother of a basement dwelling son.", "Doris", new WorldPoint(3079, 3493, 0), "Evil Dave's mother, Doris is located in the house west of Edgeville bank."), new CrypticClue("Speak to Ned in Draynor Village.", "Ned", new WorldPoint(3098, 3258, 0), "Ned is found north of the Draynor bank."), new CrypticClue("Speak to Hans to solve the clue.", "Hans", new WorldPoint(3211, 3219, 0), "Hans can be found at Lumbridge Castle."), new CrypticClue("Search the crates in Canifis.", CRATE_24344, new WorldPoint(3509, 3497, 0), "Search inside the shop, Rufus' Meat Emporium."), new CrypticClue("Search the crates in the Dwarven mine.", CRATE_357, new WorldPoint(3035, 9849, 0), "Search the crate in the room east of the Ice Mountain ladder entrance in the Drogo's Mining Emporium."), new CrypticClue("A crate found in the tower of a church is your next location.", CRATE_357, new WorldPoint(2612, 3304, 1), "Climb the ladder and search the crates on the first floor in the Church in Ardougne"), new CrypticClue("Covered in shadows, the centre of the circle is where you will find the answer.", new WorldPoint(3488, 3289, 0), "Dig in the centre of Mort'ton, where the roads intersect"), new CrypticClue("I lie lonely and forgotten in mid wilderness, where the dead rise from their beds. Feel free to quarrel and wind me up, and dig while you shoot their heads.", new WorldPoint(3174, 3663, 0), "Directly under the crossbow respawn in the Graveyard of Shadows in level 18 Wilderness."), new CrypticClue("In the city where merchants are said to have lived, talk to a man with a splendid cape, but a hat dropped by goblins.", "Head chef", new WorldPoint(3143, 3445, 0), "Talk to the Head chef in Cooks' Guild west of Varrock."), new CrypticClue("The mother of the reptilian sacrifice.", "Zul-Cheray", new WorldPoint(2204, 3050, 0), "Talk to Zul-Cheray in a house near the sacrificial boat at Zul-Andra."), new CrypticClue("I watch the sea. I watch you fish. I watch your tree.", "Ellena", new WorldPoint(2860, 3431, 0), "Speak to Ellena at Catherby fruit tree patch."), new CrypticClue("Dig between some ominous stones in Falador.", new WorldPoint(3040, 3399, 0), "Three standing stones inside a walled area. East of the northern Falador gate."), new CrypticClue("Speak to Rusty north of Falador.", "Rusty", new WorldPoint(2979, 3435, 0), "Rusty can be found northeast of Falador on the way to the Mind altar."), new CrypticClue("Search a wardrobe in Draynor.", WARDROBE_5622, new WorldPoint(3087, 3261, 0), "Go to Aggie's house and search the wardrobe in northern wall."), new CrypticClue("I have many arms but legs, I have just one. I have little family but my seed you can grow on, I am not dead, yet I am but a spirit, and my power, on your quests, you will earn the right to free it.", NULL_1293, new WorldPoint(2544, 3170, 0), "Spirit Tree in Tree Gnome Village. Answer: 13112221", "What is the next number in the sequence? 1, 11, 21, 1211, 111221, 312211"), new CrypticClue("I am the one who watches the giants. The giants in turn watch me. I watch with two while they watch with one. Come seek where I may be.", "Kamfreena", new WorldPoint(2845, 3539, 0), "Speak to Kamfreena on the top floor of the Warriors' Guild."), new CrypticClue("In a town where wizards are known to gather, search upstairs in a large house to the north.", "Man", 375, new WorldPoint(2593, 3108, 1), "Search the chest upstairs in the house north of Yanille Wizard's Guild. Kill a man for the key."), new CrypticClue("Probably filled with wizards socks.", "Wizard", DRAWERS_350, new WorldPoint(3116, 9562, 0), "Search the drawers in the basement of the Wizard's Tower south of Draynor Village. Kill one of the Wizards for the key. Fairy ring DIS"), new CrypticClue("Even the seers say this clue goes right over their heads.", CRATE_14934, new WorldPoint(2707, 3488, 2), "Search the crate on the Seers Agility Course in Seers Village"), new CrypticClue("Speak to a Wyse man.", "Wyson the gardener", new WorldPoint(3026, 3378, 0), "Talk to Wyson the gardener at Falador Park."), new CrypticClue("You'll need to look for a town with a central fountain. Look for a locked chest in the town's chapel.", "Monk" , CLOSED_CHEST_5108, new WorldPoint(3256, 3487, 0), "Search the chest by the stairs in the Varrock church. Kill a Monk in Ardougne Monastery to obtain the key."), new CrypticClue("Talk to Ambassador Spanfipple in the White Knights Castle.", "Ambassador Spanfipple", new WorldPoint(2979, 3340, 0), "Ambassador Spanfipple can be found roaming on the first floor of the White Knights Castle."), new CrypticClue("Mine was the strangest birth under the sun. I left the crimson sack, yet life had not begun. Entered the world, and yet was seen by none.", new WorldPoint(2832, 9586, 0), "Inside Karamja Volcano, dig directly underneath the Red spiders' eggs respawn."), new CrypticClue("Search for a crate in Varrock Castle.", CRATE_5113, new WorldPoint(3224, 3492, 0), "Search the crate in the corner of the kitchen in Varrock Castle."), new CrypticClue("And so on, and so on, and so on. Walking from the land of many unimportant things leads to a choice of paths.", new WorldPoint(2591, 3879, 0), "Dig on Etceteria next to the Evergreen tree in front of the castle walls."), new CrypticClue("Speak to Donovan, the Family Handyman.", "Donovan the Family Handyman", new WorldPoint(2743, 3578, 0), "Donovan the Family Handyman is found on the first floor of Sinclair Mansion."), new CrypticClue("Search the crates in the Barbarian Village helmet shop.", CRATES_11600, new WorldPoint(3073, 3430, 0), "Peksa's Helmet Shop in Barbarian Village."), new CrypticClue("Search the boxes of Falador's general store.", CRATES_24088, new WorldPoint(2955, 3390, 0), "Falador general store."), new CrypticClue("In a village made of bamboo, look for some crates under one of the houses.", CRATE_356, new WorldPoint(2800, 3074, 0), "Search the crate by the house at the northern point of the broken jungle fence in Tai Bwo Wannai."), new CrypticClue("This crate is mine, all mine, even if it is in the middle of the desert.", CRATE_18889, new WorldPoint(3289, 3022, 0), "Center of desert Mining Camp. Search the crates. Requires the metal key from Tourist Trap to enter."), new CrypticClue("Dig where 4 siblings and I all live with our evil overlord.", new WorldPoint(3195, 3357, 0), "Dig in the chicken pen inside the Champions' Guild"), new CrypticClue("In a town where the guards are armed with maces, search the upstairs rooms of the Public House.", "Guard dog", 348, new WorldPoint(2574, 3326, 1), "Search the drawers upstairs in the pub north of Ardougne Castle. Kill a Guard dog at Handelmort Mansion to obtain the key."), new CrypticClue("Four blades I have, yet draw no blood; Still I turn my prey to powder. If you are brave, come search my roof; It is there my blades are louder.", CRATE_12963, new WorldPoint(3166, 3309, 2), "Lumbridge windmill, search the crates on the top floor."), new CrypticClue("Search through some drawers in the upstairs of a house in Rimmington.", DRAWERS_352, new WorldPoint(2970, 3214, 1), "On the first floor of the house north of Hetty the Witch's house in Rimmington."), new CrypticClue("Probably filled with books on magic.", BOOKCASE_380, new WorldPoint(3096, 9572, 0), "Search the bookcase in the basement of Wizard's Tower. Fairy ring DIS"), new CrypticClue("If you look closely enough, it seems that the archers have lost more than their needles.", HAYSTACK, new WorldPoint(2672, 3416, 0), "Search the haystack by the south corner of the Rangers' Guild"), new CrypticClue("Search the crate in the left-hand tower of Lumbridge Castle.", CRATE_357, new WorldPoint(3228, 3212, 1), "Located on the first floor of the southern tower at the Lumbridge Castle entrance."), new CrypticClue("'Small shoe.' Often found with rod on mushroom.", "Gnome trainer", new WorldPoint(2476, 3428, 0), "Talk to any Gnome trainer in the agility area of the Tree Gnome Stronghold."), new CrypticClue("I live in a deserted crack collecting soles.", "Genie", new WorldPoint(3371, 9320, 0), "Enter the crack west of Nardah Rug merchant, and talk to the Genie. You'll need a light source and a rope."), new CrypticClue("46 is my number. My body is the colour of burnt orange and crawls among those with eight. Three mouths I have, yet I cannot eat. My blinking blue eye hides my grave.", new WorldPoint(3170, 3885, 0), "Sapphire respawn in the Spider's Nest, lvl 46 Wilderness. Dig under the sapphire spawn."), new CrypticClue("Green is the colour of my death as the winter-guise, I swoop towards the ground.", new WorldPoint(2780, 3783, 0), "Players need to slide down to where Trollweiss grows on Trollweiss Mountain."), new CrypticClue("Talk to a party-goer in Falador.", "Lucy", new WorldPoint(3046, 3382, 0), "Lucy is the bartender on the first floor of the party room."), new CrypticClue("He knows just how easy it is to lose track of time.", "Brother Kojo", new WorldPoint(2570, 3250, 0), "Speak to Brother Kojo in the Clock Tower. Answer: 22", "On a clock, how many times a day do the minute hand and the hour hand overlap?"), new CrypticClue("A great view - watch the rapidly drying hides get splashed. Check the box you are sitting on.", BOXES, new WorldPoint(2523, 3493, 1), "Almera's House north of Baxtorian Falls, search boxes on the first floor."), new CrypticClue("Search the Coffin in Edgeville.", COFFIN, new WorldPoint(3091, 3477, 0), "Search the coffin located by the Wilderness teleport lever."), new CrypticClue("When no weapons are at hand, then is the time to reflect. In Saradomin's name, redemption draws closer...", DRAWERS_350, new WorldPoint(2818, 3351, 0), "On Entrana, search the southern drawer in the house with the cooking range."), new CrypticClue("Search the crates in a house in Yanille that has a piano.", CRATE_357, new WorldPoint(2598, 3105, 0), "The house is located northwest of the bank."), new CrypticClue("Speak to the staff of Sinclair mansion.", "Louisa", new WorldPoint(2736, 3578, 0), "Speak to Louisa, on the ground floor, found at the Sinclair Mansion. Fairy ring CJR"), new CrypticClue("I am a token of the greatest love. I have no beginning or end. My eye is red, I can fit like a glove. Go to the place where it's money they lend, And dig by the gate to be my friend.", new WorldPoint(3191, 9825, 0), "Dig by the gate in the basement of the West Varrock bank."), new CrypticClue("Speak to Kangai Mau.", "Kangai Mau", new WorldPoint(2791, 3183, 0), "Kangai Mau is found in the Shrimp and Parrot in Brimhaven."), new CrypticClue("Speak to Hajedy.", "Hajedy", new WorldPoint(2779, 3211, 0), "Hajedy is found by the cart, located just south of the Brimhaven docks."), new CrypticClue("Must be full of railings.", BOXES_6176, new WorldPoint(2576, 3464, 0), "Search the boxes around the hut where the broken Dwarf Cannon is, close to the start of the Dwarf Cannon quest."), new CrypticClue("I wonder how many bronze swords he has handed out.", "Vannaka", new WorldPoint(3164, 9913, 0), "Talk to Vannaka. He can be found in Edgeville Dungeon."), new CrypticClue("Read 'How to breed scorpions.' By O.W.Thathurt.", BOOKCASE_380, new WorldPoint(2703, 3409, 1), "Search the northern bookcase on the first floor of the Sorcerer's Tower."), new CrypticClue("Search the crates in the Port Sarim Fishing shop.", CRATE_9534, new WorldPoint(3012, 3222, 0), "Search the crates, by the door, in Gerrant's Fishy Business in Port Sarim."), new CrypticClue("Speak to The Lady of the Lake.", "The Lady of the Lake", new WorldPoint(2924, 3405, 0), "Talk to The Lady of the Lake in Taverley."), new CrypticClue("Rotting next to a ditch. Dig next to the fish.", new WorldPoint(3547, 3183, 0), "Dig next to a fishing spot on the south-east side of Burgh de Rott."), new CrypticClue("The King's magic won't be wasted by me.", "Guardian Mummy", new WorldPoint(1934, 4427, 0), "Talk to the Guardian mummy inside the Pyramid Plunder minigame in Sophanem"), new CrypticClue("Dig where the forces of Zamorak and Saradomin collide.", new WorldPoint(3049, 4839, 0), "Dig next to the law rift in the Abyss"), new CrypticClue("Search the boxes in the goblin house near Lumbridge.", BOXES, new WorldPoint(3245, 3245, 0), "Goblin house on the eastern side of the river."), new CrypticClue("W marks the spot.", new WorldPoint(2867, 3546, 0), "Dig in the middle of the Warriors' Guild entrance hall"), new CrypticClue("There is no 'worthier' lord.", "Lord Iorwerth", new WorldPoint(2205, 3252, 0), "Speak to Lord Iorwerth in the elven camp near Prifddinas"), new CrypticClue("Surviving.", "Sir Vyvin", new WorldPoint(2983, 3338, 0), "Talk to Sir Vyvin on the second floor of Falador castle."), new CrypticClue("My name is like a tree, yet it is spelt with a 'g'. Come see the fur which is right near me.", "Wilough", new WorldPoint(3221, 3435, 0), "Speak to Wilough, next to the Fur Merchant in Varrock Square."), new CrypticClue("Speak to Jatix in Taverley.", "Jatix", new WorldPoint(2898, 3428, 0), "Jatix is found in the middle of Taverley."), new CrypticClue("Speak to Gaius in Taverley.", "Gaius", new WorldPoint(2884, 3450, 0), "Gaius is found at the northwest corner in Taverley."), new CrypticClue("If a man carried my burden, he would break his back. I am not rich, but leave silver in my track. Speak to the keeper of my trail.", "Gerrant", new WorldPoint(3014, 3222, 0), "Speak to Gerrant in the fish shop in Port Sarim."), new CrypticClue("Search the drawers in Falador's chain mail shop.", DRAWERS, new WorldPoint(2969, 3311, 0), "Wayne's Chains - Chainmail Specialist store at the southern Falador walls."), new CrypticClue("Talk to the barber in the Falador barber shop.", "Hairdresser", new WorldPoint(2945, 3379, 0), "The Hairdresser can be found in the barber shop, north of the west Falador bank."), new CrypticClue("Often sought out by scholars of histories past, find me where words of wisdom speak volumes.", "Examiner", new WorldPoint(3362, 3341, 0), "Speak to an examiner at the Exam Centre."), new CrypticClue("Generally speaking, his nose was very bent.", "General Bentnoze", new WorldPoint(2957, 3511, 0), "Talk to General Bentnoze"), new CrypticClue("Search the bush at the digsite centre.", BUSH_2357, new WorldPoint(3345, 3378, 0), "The bush is on the east side of the first pathway towards the digsite from the Exam Centre."), new CrypticClue("Someone watching the fights in the Duel Arena is your next destination.", "Jeed", new WorldPoint(3360, 3242, 0), "Talk to Jeed, found on the upper floors, at the Duel Arena."), new CrypticClue("It seems to have reached the end of the line, and it's still empty.", MINE_CART_6045, new WorldPoint(3041, 9820, 0), "Search the carts in the northern part of the Dwarven Mine."), new CrypticClue("You'll have to plug your nose if you use this source of herbs.", null, "Kill an Aberrant or Deviant spectre."), new CrypticClue("When you get tired of fighting, go deep, deep down until you need an antidote.", CRATE_357, new WorldPoint(2576, 9583, 0), "Go to Yanille Agility dungeon and fall into the place with the poison spiders. Search the crate by the stairs leading up."), new CrypticClue("Search the bookcase in the monastery.", BOOKCASE_380, new WorldPoint(3054, 3484, 0), "Search the southeastern bookcase at Edgeville Monastery."), new CrypticClue("Surprising? I bet he is...", "Sir Prysin", new WorldPoint(3205, 3474, 0), "Talk to Sir Prysin in Varrock Palace."), new CrypticClue("Search upstairs in the houses of Seers' Village for some drawers.", DRAWERS_25766, new WorldPoint(2716, 3471, 1), "Located in the house with the spinning wheel. South of the Seers' Village bank."), new CrypticClue("Leader of the Yak City.", "Mawnis Burowgar", new WorldPoint(2336, 3799, 0), "Talk to Mawnis Burowgar in Neitiznot."), new CrypticClue("Speak to Arhein in Catherby.", "Arhein", new WorldPoint(2803, 3430, 0), "Arhein is just south of the Catherby bank."), new CrypticClue("Speak to Doric, who lives north of Falador.", "Doric", new WorldPoint(2951, 3451, 0), "Doric is found north of Falador and east of the Taverley gate."), new CrypticClue("Between where the best are commemorated for a year, and a celebratory cup, not just for beer.", new WorldPoint(3388, 3152, 0), "Dig at the Clan Cup Trophy at Clan Wars."), new CrypticClue("'See you in your dreams' said the vegetable man.", "Dominic Onion", new WorldPoint(2608, 3116, 0), "Speak to Dominic Onion at the Nightmare Zone teleport spot."), new CrypticClue("Try not to step on any aquatic nasties while searching this crate.", CRATE_18204, new WorldPoint(2764, 3273, 0), "Search the crate in Bailey's house on the Fishing Platform."), new CrypticClue("The cheapest water for miles around, but they react badly to religious icons.", CRATE_354, new WorldPoint(3178, 2987, 0), "Search the crates in the General Store tent in the Bandit Camp"), new CrypticClue("This village has a problem with cartloads of the undead. Try checking the bookcase to find an answer.", BOOKCASE_394, new WorldPoint(2833, 2992, 0), "Search the bookcase by the doorway of the building just south east of the Shilo Village Gem Mine."), new CrypticClue("Dobson is my last name, and with gardening I seek fame.", "Horacio", new WorldPoint(2635, 3310, 0), "Horacio, located in the garden of the Handelmort Mansion in East Ardougne."), new CrypticClue("The magic of 4 colours, an early experience you could learn. The large beast caged up top, rages, as his demised kin's loot now returns.", "Wizard Mizgog", new WorldPoint(3103, 3163, 2), "Speak to Wizard Mizgog at the top of the Wizard's Tower south of Draynor."), new CrypticClue("Aggie I see. Lonely and southern I feel. I am neither inside nor outside the house, yet no home would be complete without me. The treasure lies beneath me!", new WorldPoint(3085, 3255, 0), "Dig outside the window of Aggie's house in Draynor Village."), new CrypticClue("Search the chest in Barbarian Village.", CLOSED_CHEST_375, new WorldPoint(3085, 3429, 0), "The chest located in the house with a spinning wheel."), new CrypticClue("Search the crates in the outhouse of the long building in Taverley.", CRATE_357, new WorldPoint(2914, 3433, 0), "Located in the small building attached by a fence to the main building. Climb over the stile."), new CrypticClue("Talk to Ermin.", "Ermin", new WorldPoint(2488, 3409, 1), "Ermin can be found on the first floor of the tree house south-east of the Gnome Agility Course."), new CrypticClue("Ghostly bones.", null, "Kill an Ankou."), new CrypticClue("Search through chests found in the upstairs of houses in eastern Falador.", CLOSED_CHEST_375, new WorldPoint(3041, 3364, 1), "The house is located southwest of the Falador Party Room. There are two chests in the room, search the northern chest."), new CrypticClue("Let's hope you don't meet a watery death when you encounter this fiend.", null, "Kill a waterfiend."), new CrypticClue("Reflection is the weakness for these eyes of evil.", null, "Kill a basilisk."), new CrypticClue("Search a bookcase in Lumbridge swamp.", BOOKCASE_9523, new WorldPoint(3146, 3177, 0), "Located in Father Urhney's house."), new CrypticClue("Surround my bones in fire, ontop the wooden pyre. Finally lay me to rest, before my one last test.", null, "Kill a confused/lost barbarian to receive mangled bones. Construct and burn a pyre ship. Kill the ferocious barbarian spirit that spawns to receive a clue casket."), new CrypticClue("Fiendish cooks probably won't dig the dirty dishes.", new WorldPoint(3043, 4974, 1), "Dig by the fire in the Rogues' Den."), new CrypticClue("My life was spared but these voices remain, now guarding these iron gates is my bane.", "Key Master", new WorldPoint(1310, 1251, 0), "Speak to the Key Master in Cerberus' Lair."), new CrypticClue("Search the boxes in one of the tents in Al Kharid.", BOXES_361, new WorldPoint(3308, 3206, 0), "Search the boxes in the tent east of the Silk trader."), new CrypticClue("One of several rhyming brothers, in business attire with an obsession for paper work.", "Piles", new WorldPoint(3186, 3936, 0), "Speak to Piles in the Wilderness Resource Area. An entry fee of 7,500 coins is required, or less if Wilderness Diaries have been completed."), new CrypticClue("Search the drawers on the first floor of a building overlooking Ardougne's Market.", DRAWERS_352, new WorldPoint(2657, 3322, 1), "Climb the ladder in the house north of the market."), new CrypticClue("'A bag belt only?', he asked his balding brothers.", "Abbot Langley", new WorldPoint(3058, 3487, 0), "Talk-to Abbot Langley in Monastery west of Edgeville"), new CrypticClue("Search the drawers upstairs in Falador's shield shop.", DRAWERS, new WorldPoint(2971, 3386, 1), "Cassie's Shield Shop at the northern Falador entrance."), new CrypticClue("Go to this building to be illuminated, and check the drawers while you are there.", "Market Guard", DRAWERS_350 , new WorldPoint(2512, 3641, 1), "Search the drawers in the first floor of the Lighthouse. Kill a Rellekka marketplace guard to obtain the key."), new CrypticClue("Dig near some giant mushrooms, behind the Grand Tree.", new WorldPoint(2458, 3504, 0), "Dig near the red mushrooms northwest of the Grand Tree."), new CrypticClue("Pentagrams and demons, burnt bones and remains, I wonder what the blood contains.", new WorldPoint(3297, 3890, 0), "Dig under the blood rune spawn next to the Demonic Ruins."), new CrypticClue("Search the drawers above Varrock's shops.", DRAWERS_7194, new WorldPoint(3206, 3419, 1), "Located upstairs in Thessalia's Fine Clothes shop in Varrock."), new CrypticClue("Search the drawers in one of Gertrude's bedrooms.", DRAWERS_7194, new WorldPoint(3156, 3406, 0), "Kanel's bedroom (southeastern room), outside of west Varrock."), new CrypticClue("Under a giant robotic bird that cannot fly.", new WorldPoint(1756, 4940, 0), "Dig next to the terrorbird display in the south exhibit of Varrock Museum's basement."), new CrypticClue("Great demons, dragons and spiders protect this blue rock, beneath which, you may find what you seek.", new WorldPoint(3045, 10265, 0), "Dig by the runite rock in the Lava Maze Dungeon"), new CrypticClue("My giant guardians below the market streets would be fans of rock and roll, if only they could grab hold of it. Dig near my green bubbles!", new WorldPoint(3161, 9904, 0), "Dig near the cauldron by Moss Giants under Varrock Sewers"), new CrypticClue("Varrock is where I reside, not the land of the dead, but I am so old, I should be there instead. Let's hope your reward is as good as it says, just 1 gold one and you can have it read.", "Gypsy Aris", new WorldPoint(3203, 3424, 0), "Talk to Gypsy Aris, West of varrock main square."), new CrypticClue("Speak to a referee.", "Gnome ball referee", new WorldPoint(2386, 3487, 0), "Talk to a Gnome ball referee found on the Gnome ball field in the Gnome Stronghold. Answer: 5096", "What is 57 x 89 + 23?"), new CrypticClue("This crate holds a better reward than a broken arrow.", CRATE_356, new WorldPoint(2671, 3437, 0), "Inside the Ranging Guild. Search the crate behind the northern most building."), new CrypticClue("Search the drawers in the house next to the Port Sarim mage shop.", DRAWERS, new WorldPoint(3024, 3259, 0), "House east of Betty's. Contains a cooking sink."), new CrypticClue("With a name like that, you'd expect a little more than just a few scimitars.", "Daga", new WorldPoint(2759, 2775, 0), "Speak to Daga on Ape Atoll."), new CrypticClue("Strength potions with red spiders' eggs? He is quite a herbalist.", "Apothecary", new WorldPoint(3194, 3403, 0), "Talk to Apothecary in the South-western Varrock. (the) apothecary is just north-west of the Varrock Swordshop."), new CrypticClue("Robin wishes to see your finest ranged equipment.", "Robin", new WorldPoint(3673, 3492, 0), "Robin at the inn in Port Phasmatys. Speak to him with +182 in ranged attack bonus. Bonus granted by the toxic blowpipe is ignored."), new CrypticClue("You will need to under-cook to solve this one.", CRATE_357, new WorldPoint(3219, 9617, 0), "Search the crate in the Lumbridge basement."), new CrypticClue("Search through some drawers found in Taverley's houses.", DRAWERS_350, new WorldPoint(2894, 3418, 0), "The south-eastern most house, south of Jatix's Herblore Shop."), new CrypticClue("Anger Abbot Langley.", "Abbot Langley", new WorldPoint(3058, 3487, 0), "Speak to Abbot Langley in the Edgeville Monastery while you have a negative prayer bonus (currently only possible with an Ancient staff)."), new CrypticClue("Dig where only the skilled, the wealthy, or the brave can choose not to visit again.", new WorldPoint(3221, 3219, 0), "Dig at Lumbridge spawn"), new CrypticClue("Scattered coins and gems fill the floor. The chest you seek is in the north east.", "King Black Dragon", CLOSED_CHEST_375, new WorldPoint(2288, 4702, 0), "Kill the King Black Dragon for a key (elite), and then open the closed chest in the NE corner of the lair."), new CrypticClue("A ring of water surrounds 4 powerful rings, dig above the ladder located there.", new WorldPoint(1910, 4367, 0), "Dig by the ladder leading to the Dagannoth Kings room in the Waterbirth Island Dungeon."), new CrypticClue("This place sure is a mess.", "Ewesey", new WorldPoint(1646, 3631, 0), "Ewesey is located in the mess hall in Hosidius."), new CrypticClue("Here, there are tears, but nobody is crying. Speak to the guardian and show off your alignment to balance.", "Juna", JUNA, new WorldPoint(3252, 9517, 2), "Talk to Juna while wearing three Guthix related items."), new CrypticClue("You might have to turn over a few stones to progress.", null, "Kill a rock crab."), new CrypticClue("Dig under Razorlor's toad batta.", new WorldPoint(3139, 4554, 0), "Dig on the toad batta spawn in Tarn's Lair."), new CrypticClue("Talk to Cassie in Falador.", "Cassie", new WorldPoint(2975, 3383, 0), "Cassie is found just south-east of the northern Falador gate."), new CrypticClue("Faint sounds of 'Arr', fire giants found deep, the eastern tip of a lake, are the rewards you could reap.", new WorldPoint(3055, 10338, 0), "Dig south of the pillar at the end of the Deep Wilderness Dungeon."), new CrypticClue("If you're feeling brave, dig beneath the dragon's eye.", new WorldPoint(2410, 4714, 0), "Dig below the mossy rock under the Viyeldi caves (Legend's Quest). Items needed: Pickaxe, unpowered orb, lockpick, spade, and any charge orb spell."), new CrypticClue("Search the tents in the Imperial Guard camp in Burthorpe for some boxes.", BOXES_3686, new WorldPoint(2885, 3540, 0), "Search in the tents in northwest corner of the camp."), new CrypticClue("A dwarf, approaching death, but very much in the light.", "Thorgel", new WorldPoint(1863, 4639, 0), "Thorgel at the entrance to the Death altar"), new CrypticClue("You must be 100 to play with me.", "Squire (Veteran)", new WorldPoint(2638, 2656, 0), "Speak to the Veteran boat squire at Pest Control"), new CrypticClue("Three rule below and three sit at top. Come dig at my entrance.", new WorldPoint(2523, 3739, 0), "Dig in front of the entrance to the Waterbirth Island Dungeon."), new CrypticClue("Search the drawers in the ground floor of a shop in Yanille.", DRAWERS_350, new WorldPoint(2570, 3085, 0), "Search the drawers in Yanille's hunting shop."), new CrypticClue("Search the drawers of houses in Burthorpe.", DRAWERS, new WorldPoint(2929, 3570, 0), "Inside Hild's house in the northeast corner of Burthorpe."), new CrypticClue("Where safe to speak, the man who offers the pouch of smallest size wishes to see your alignment.", "Mage of Zamorak", new WorldPoint(3260, 3385, 0), "Speak to the Mage of Zamorak south of the Rune Shop in Varrock while wearing three zamorakian items"), new CrypticClue("Search the crates in the guard house of the northern gate of East Ardougne.", CRATE_356, new WorldPoint(2645, 3338, 0), "The guard house is northeast of the Handelmort Mansion."), new CrypticClue("Go to the village being attacked by trolls, search the drawers in one of the houses.", "Penda", DRAWERS_350, new WorldPoint(2921, 3577, 0), "Go to Dunstan's house in the northeast corner of Burthorpe. Kill Penda in the Toad and Chicken to obtain the key."), new CrypticClue("You'll get licked.", null, "Kill a Bloodveld."), new CrypticClue("She's small but can build both literally and figuratively, as long as you have their favour.", "Lovada", new WorldPoint(1486, 3834, 0), "Speak to Lovada by the entrance to the blast mine in Lovakengj."), new CrypticClue("Dig in front of the icy arena where 1 of 4 was fought.", new WorldPoint(2874, 3757, 0), "Where you fought Kamil from Desert Treasure."), new CrypticClue("Speak to Roavar.", "Roavar", new WorldPoint(3494, 3474, 0), "Talk to Roavar in the Canifis tavern."), new CrypticClue("Search the drawers upstairs of houses in the eastern part of Falador.", DRAWERS_350, new WorldPoint(3035, 3347, 1), "House is located east of the eastern Falador bank and south of the fountain. The house is indicated by the icon on the minimap."), new CrypticClue("Search the drawers found upstairs in East Ardougne's houses.", DRAWERS, new WorldPoint(2574, 3326, 1), "Upstairs of the pub north of the Ardougne Castle."), new CrypticClue("The far north eastern corner where 1 of 4 was defeated, the shadows still linger.", new WorldPoint(2744, 5116, 0), "Dig on the northeastern-most corner of the Shadow Dungeon. Bring a ring of visibility."), new CrypticClue("Search the drawers in a house in Draynor Village.", DRAWERS_350, new WorldPoint(3097, 3277, 0), "The drawer is located in the northernmost house in Draynor Village."), new CrypticClue("Search the boxes in a shop in Taverley.", BOXES_360, new WorldPoint(2886, 3449, 0), "The box inside Gaius' Two Handed Shop."), new CrypticClue("I lie beneath the first descent to the holy encampment.", new WorldPoint(2914, 5300, 1), "Dig immediately after climbing down the first set of rocks towards Saradomin's encampment within the God Wars Dungeon."), new CrypticClue("Search the upstairs drawers of a house in a village where pirates are known to have a good time.", "Pirate", 348, new WorldPoint(2809, 3165, 1), "The house in the southeast corner of Brimhaven, northeast of Davon's Amulet Store. Kill any Pirate located around Brimhaven to obtain the key."), new CrypticClue("Search the chest in the Duke of Lumbridge's bedroom.", CLOSED_CHEST_375, new WorldPoint(3209, 3218, 1), "The Duke's room is on the first floor in Lumbridge Castle."), new CrypticClue("Talk to the Doomsayer.", "Doomsayer", new WorldPoint(3232, 3228, 0), "Doomsayer can be found just north of Lumbridge Castle entrance."), new CrypticClue("Search the chests upstairs in Al Kharid Palace.", CLOSED_CHEST_375, new WorldPoint(3301, 3169, 1), "The chest is located, in the northeast corner, on the first floor of the Al Kharid Palace"), new CrypticClue("Search the boxes just outside the Armour shop in East Ardougne.", BOXES_361, new WorldPoint(2654, 3299, 0), "Outside Zenesha's Plate Mail Body Shop"), new CrypticClue("Surrounded by white walls and gems.", "Herquin", new WorldPoint(2945, 3335, 0), "Talk to Herquin, the gem store owner in Falador."), new CrypticClue("Monk's residence in the far west. See robe storage device.", DRAWERS_350, new WorldPoint(1746, 3490, 0), "Search the drawers in the south tent of the monk's camp on the southern coast of Hosidius, directly south of the player-owned house portal."), new CrypticClue("Search the drawers in Catherby's Archery shop.", DRAWERS_350, new WorldPoint(2825, 3442, 0), "Hickton's Archery Emporium in Catherby."), new CrypticClue("The hand ain't listening.", "The Face", new WorldPoint(3019, 3232, 0), "Talk to The Face located by the manhole just north of the Port Sarim fishing shop."), new CrypticClue("Search the chest in the left-hand tower of Camelot Castle.", CLOSED_CHEST_25592, new WorldPoint(2748, 3495, 2), "Located on the second floor of the western tower of Camelot."), new CrypticClue("Anger those who adhere to Saradomin's edicts to prevent travel.", "Monk of Entrana", new WorldPoint(3042, 3236, 0), "Port Sarim Docks, try to charter a ship to Entrana with armour or weapons equipped."), new CrypticClue("South of a river in a town surrounded by the undead, what lies beneath the furnace?", new WorldPoint(2857, 2966, 0), "Dig in front of the Shilo Village furnace."), new CrypticClue("Talk to the Squire in the White Knights' castle in Falador.", "Squire", new WorldPoint(2977, 3343, 0), "The squire is located in the courtyard of the White Knights' Castle."), new CrypticClue("Thanks, Grandma!", "Tynan", new WorldPoint(1836, 3786, 0), "Tynan can be found in the north-east corner of Port Piscarilius."), new CrypticClue("In a town where everyone has perfect vision, seek some locked drawers in a house that sits opposite a workshop.", "Chicken", DRAWERS_25766, new WorldPoint(2709, 3478, 0), "The Seers' Village house south of the Elemental Workshop entrance. Kill any Chicken to obtain a key."), new CrypticClue("The treasure is buried in a small building full of bones. Here is a hint: it's not near a graveyard.", new WorldPoint(3356, 3507, 0), "In the western building near the Limestone quarry east of Varrock. Dig south of the box of bones in the smaller building."), new CrypticClue("Search the crates in East Ardougne's general store.", CRATE_357, new WorldPoint(2615, 3291, 0), "Located south of the Ardougne church."), new CrypticClue("Come brave adventurer, your sense is on fire. If you talk to me, it's an old god you desire.", "Viggora", null, "Speak to Viggora"), new CrypticClue("2 musical birds. Dig in front of the spinning light.", new WorldPoint(2671, 10396, 0), "Dig in front of the spinning light in Ping and Pong's room inside the Iceberg"), new CrypticClue("Search the wheelbarrow in Rimmington mine.", WHEELBARROW_9625, new WorldPoint(2978, 3239, 0), "The Rimmington mining site is located north of Rimmington."), new CrypticClue("Belladonna, my dear. If only I had gloves, then I could hold you at last.", "Tool Leprechaun", new WorldPoint(3088, 3357, 0), "Talk to Tool Leprechaun at Draynor Manor"), new CrypticClue("Impossible to make angry", "Abbot Langley", new WorldPoint(3059, 3486, 0), "Speak to Abbot Langley at the Edgeville Monastery."), new CrypticClue("Search the crates in Horvik's armoury.", CRATE_5106, new WorldPoint(3228, 3433, 0), "Horvik's in Varrock"), new CrypticClue("Ghommal wishes to be impressed by how strong your equipment is.", "Ghommal", new WorldPoint(2878, 3546, 0), "Speak to Ghommal at the Warriors' Guild with a total Melee Strength bonus of over 100."), new CrypticClue("Shhhh!", "Logosia", new WorldPoint(1633, 3808, 0), "Speak to Logosia in the Arceuus Library's ground floor."), new CrypticClue("Salty peter.", "Konoo", new WorldPoint(1703, 3524, 0), "Talk to Konoo who is digging saltpetre in Hosidius, north-east of the Woodcutting Guild."), new CrypticClue("Talk to Zeke in Al Kharid.", "Zeke", new WorldPoint(3287, 3190, 0), "Zeke is the owner of the scimitar shop in Al Kharid."), new CrypticClue("Guthix left his mark in a fiery lake, dig at the tip of it.", new WorldPoint(3069, 3935, 0), "Dig at the tip of the lava lake that is shaped like a Guthixian symbol, west of the Mage Arena."), new CrypticClue("Search the drawers in the upstairs of a house in Catherby.", DRAWERS_350, new WorldPoint(2809, 3451, 1), "Perdu's house in Catherby."), new CrypticClue("Search a crate in the Haymaker's arms.", CRATE_27532, new WorldPoint(1720, 3652, 1), "Search the crate in the north-east corner of The Haymaker's Arms tavern east of Kourend Castle."), new CrypticClue("Desert insects is what I see. Taking care of them was my responsibility. Your solution is found by digging near me.", new WorldPoint(3307, 9505, 0), "Dig next to the Entomologist, Kalphite area, near Shantay Pass."), new CrypticClue("Search the crates in the most north-western house in Al Kharid.", CRATE_358, new WorldPoint(3289, 3202, 0), "Search the crates in the house, marked with a icon, southeast of the gem stall."), new CrypticClue("You will have to fly high where a sword cannot help you.", null, "Kill an Aviansie."), new CrypticClue("A massive battle rages beneath so be careful when you dig by the large broken crossbow.", new WorldPoint(2927, 3761, 0), "NE of the God Wars Dungeon entrance, climb the rocky handholds & dig by large crossbow."), new CrypticClue("Mix yellow with blue and add heat, make sure you bring protection.", null, "Kill a green dragon."), new CrypticClue("Speak to Ellis in Al Kharid.", "Ellis", new WorldPoint(3276, 3191, 0), "Ellis is tanner just north of Al Kharid bank."), new CrypticClue("Search the chests in the Dwarven Mine.", CLOSED_CHEST_375, new WorldPoint(3000, 9798, 0), "The chest is on the western wall, where Hura's Crossbow Shop is, in the Dwarven Mine."), new CrypticClue("In a while...", null, "Kill a crocodile."), new CrypticClue("A chisel and hammer reside in his home, strange for one of magic. Impress him with your magical equipment.", "Wizard Cromperty", new WorldPoint(2682, 3325, 0), "Wizard Cromperty, NE corner of East Ardougne. +100 magic attack bonus needed"), new CrypticClue("You have all of the elements available to solve this clue. Fortunately you do not have to go as far as to stand in a draft.", CRATE_18506, new WorldPoint(2723, 9891, 0), "Search the crate, west of the Air Elementals, inside the Elemental Workshop."), new CrypticClue("A demon's best friend holds the next step of this clue.", null, "Kill a hellhound."), new CrypticClue("Dig in the centre of a great kingdom of 5 cities.", new WorldPoint(1639, 3673, 0), "Dig in front of the large statue in the centre of Great Kourend."), new CrypticClue("Hopefully this set of armour will help you to keep surviving.", "Sir Vyvin", new WorldPoint(2982, 3336, 2), "Speak to Sir Vyvin while wearing a white platebody, and platelegs."), new CrypticClue("The beasts retreat, for their Queen is gone; the song of this town still plays on. Dig near the birthplace of a blade, be careful not to melt your spade.", new WorldPoint(2342, 3677, 0), "Dig in front of the small furnace in the Piscatoris Fishing Colony."), new CrypticClue("Darkness wanders around me, but fills my mind with knowledge.", "Biblia", new WorldPoint(1633, 3825, 2), "Speak to Biblia on the Arceuus Library's top floor."), new CrypticClue("I would make a chemistry joke, but I'm afraid I wouldn't get a reaction.", "Chemist", new WorldPoint(2932, 3212, 0), "Talk to the Chemist in Rimmington"), new CrypticClue("Show this to Hazelmere.", "Hazelmere", new WorldPoint(2677, 3088, 1), "Hazelmere is found upstairs on the island located just east of Yanille."), new CrypticClue("Does one really need a fire to stay warm here?", new WorldPoint(3816, 3810, 0), "Dig next to the fire near the Volcanic Mine entrance."), new CrypticClue("Search the open crate found in the Hosidius kitchens.", CRATE_27533, new WorldPoint(1683, 3616, 0), "The kitchens are north-west of the town in Hosidius."), new CrypticClue("Dig under Ithoi's cabin.", new WorldPoint(2529, 2838, 0), "Dig under Ithoi's cabin in the Corsair Cove."), new CrypticClue("Search the drawers, upstairs in the bank to the East of Varrock.", DRAWERS_7194, new WorldPoint(3250, 3420, 1), "Search the drawers upstairs in Varrock east bank."), new CrypticClue("Speak to Hazelmere.", "Hazelmere", new WorldPoint(2677, 3088, 1), "Located upstairs in the house to the north of fairy ring CLS. Answer: 6859", "What is 19 to the power of 3?"), new CrypticClue("The effects of this fire are magnified.", new WorldPoint(1179, 3626, 0), "Dig by the fire beside Ket'sal K'uk in the westernmost part of the Kebos Swamp. "), new CrypticClue("Always walking around the castle grounds and somehow knows everyone's age.", "Hans", new WorldPoint(3221, 3218, 0), "Talk to Hans walking around Lumbridge Castle."), new CrypticClue("In the place Duke Horacio calls home, talk to a man with a hat dropped by goblins.", "Cook", new WorldPoint(3208, 3213, 0), "Talk to the Cook in Lumbridge Castle."), new CrypticClue("In a village of barbarians, I am the one who guards the village from up high.", "Hunding", new WorldPoint(3097, 3432, 2), "Talk to Hunding atop the tower on the east side of Barbarian Village."), new CrypticClue("Talk to Charlie the Tramp in Varrock.", "Charlie the Tramp", new WorldPoint(3209, 3390, 0), "Talk to Charlie the Tramp by the southern entrance to Varrock. He will give you a task."), new CrypticClue("Near the open desert I reside, to get past me you must abide. Go forward if you dare, for when you pass me, you'll be sweating by your hair.", "Shantay", new WorldPoint(3303, 3123, 0), "Talk to Shantay at the Shantay Pass south of Al Kharid."), new CrypticClue("Search the chest in Fred the Farmer's bedroom.", CLOSED_CHEST_375, new WorldPoint(3185, 3274, 0), "Search the chest by Fred the Farmer's bed in his house north-west of Lumbridge."), new CrypticClue("Search the eastern bookcase in Father Urhney's house.", BOOKCASE_9523, new WorldPoint(3149, 3177, 0), "Father Urhney's house is found in the western end of the Lumbridge Swamp."), new CrypticClue("Talk to Morgan in his house at Draynor Village.", "Morgan", new WorldPoint(3098, 3268, 0), "Morgan can be found in the house with the quest start map icon."), new CrypticClue("Talk to Charles at Port Piscarilius.", "Charles", new WorldPoint(1821, 3690, 0), "Charles is found by Veos' ship in Port Piscarilius."), new CrypticClue("Search the crate in Rommiks crafting shop in Rimmington.", CRATE_9533, new WorldPoint(2946, 3207, 0), "The crates in Rommik's Crafty Supplies in Rimmington."), new CrypticClue("Talk to Ali the Leaflet Dropper north of the Al Kharid mine.", "Ali the Leaflet Dropper", new WorldPoint(3283, 3329, 0), "Ali the Leaflet Dropper can be found roaming north of the Al Kharid mine."), new CrypticClue("Talk to the cook in the Blue Moon Inn in Varrock.", "Cook", new WorldPoint(3230, 3401, 0), "The Blue Moon Inn can be found by the southern entrance to Varrock."), new CrypticClue("Search the single crate in Horvik's smithy in Varrock.", CRATE_5106, new WorldPoint(3228, 3433, 0), "Horvik's Smithy is found north-east of of Varrock Square."), new CrypticClue("Search the crates in Falador General store.", CRATES_24088, new WorldPoint(2955, 3390, 0), "The Falador General Store can be found by the northern entrance to the city."), new CrypticClue("Talk to Wayne at Wayne's Chains in Falador.", "Wayne", new WorldPoint(2972, 3312, 0), "Wayne's shop is found directly south of the White Knights' Castle."), new CrypticClue("Search the boxes next to a chest that needs a crystal key.", BOXES_360, new WorldPoint(2915, 3452, 0), "The Crystal chest can be found in the house directly south of the Witch's house in Taverley."), new CrypticClue("Talk to Turael in Burthorpe.", "Turael", new WorldPoint(2930, 3536, 0), "Turael is located in the small house east of the Toad and Chicken inn."), new CrypticClue("More resources than I can handle, but in a very dangerous area. Can't wait to strike gold!", new WorldPoint(3183, 3941, 0), "Dig between the three gold ores in the Wilderness Resource Area."), new CrypticClue("Observing someone in a swamp, under the telescope lies treasure.", new WorldPoint(2221, 3091, 0), "Dig next to the telescope on Broken Handz's island in the poison wastes. (Accessible only through fairy ring DLR)"), new CrypticClue("A general who sets a 'shining' example.", "General Hining", new WorldPoint(2186, 3148, 0), "Talk to General Hining in Tyras Camp."), new CrypticClue("Has no one told you it is rude to ask a lady her age?", "Mawrth", new WorldPoint(2333, 3165, 0), "Talk to Mawrth in Lletya."), new CrypticClue("Elvish onions.", new WorldPoint(3303, 6092, 0), "Dig in the onion patch east of the Prifddinas allotments.") ); private final String text; private final String npc; private final int objectId; private final WorldPoint location; private final String solution; private final String questionText; private CrypticClue(String text, WorldPoint location, String solution) { this(text, null, -1, location, solution); } private CrypticClue(String text, int objectId, WorldPoint location, String solution) { this(text, null, objectId, location, solution, ""); } private CrypticClue(String text, String npc, WorldPoint location, String solution) { this(text, npc, -1, location, solution, ""); } private CrypticClue(String text, int objectId, WorldPoint location, String solution, String questionText) { this(text, null, objectId, location, solution, questionText); } private CrypticClue(String text, String npc, WorldPoint location, String solution, String questionText) { this(text, npc, -1, location, solution, questionText); } private CrypticClue(String text, String npc, int objectId, WorldPoint location, String solution) { this(text, npc, objectId, location, solution, ""); } private CrypticClue(String text, String npc, int objectId, WorldPoint location, String solution, String questionText) { this.text = text; this.npc = npc; this.objectId = objectId; this.location = location; this.solution = solution; this.questionText = questionText; setRequiresSpade(getLocation() != null && getNpc() == null && objectId == -1); } @Override public void makeOverlayHint(PanelComponent panelComponent, ClueScrollPlugin plugin) { panelComponent.getChildren().add(TitleComponent.builder().text("Cryptic Clue").build()); if (getNpc() != null) { panelComponent.getChildren().add(LineComponent.builder().left("NPC:").build()); panelComponent.getChildren().add(LineComponent.builder() .left(getNpc()) .leftColor(TITLED_CONTENT_COLOR) .build()); } if (objectId != -1) { ObjectComposition object = plugin.getClient().getObjectDefinition(objectId); if (object != null && object.getImpostorIds() != null) { object = object.getImpostor(); } if (object != null) { panelComponent.getChildren().add(LineComponent.builder().left("Object:").build()); panelComponent.getChildren().add(LineComponent.builder() .left(object.getName()) .leftColor(TITLED_CONTENT_COLOR) .build()); } } panelComponent.getChildren().add(LineComponent.builder().left("Solution:").build()); panelComponent.getChildren().add(LineComponent.builder() .left(getSolution()) .leftColor(TITLED_CONTENT_COLOR) .build()); } @Override public void makeWorldOverlayHint(Graphics2D graphics, ClueScrollPlugin plugin) { // Mark dig location if (getLocation() != null && getNpc() == null && objectId == -1) { LocalPoint localLocation = LocalPoint.fromWorld(plugin.getClient(), getLocation()); if (localLocation != null) { OverlayUtil.renderTileOverlay(plugin.getClient(), graphics, localLocation, plugin.getSpadeImage(), Color.ORANGE); } } // Mark NPC if (plugin.getNpcsToMark() != null) { for (NPC npc : plugin.getNpcsToMark()) { OverlayUtil.renderActorOverlayImage(graphics, npc, plugin.getClueScrollImage(), Color.ORANGE, IMAGE_Z_OFFSET); } } // Mark game object if (objectId != -1) { net.runelite.api.Point mousePosition = plugin.getClient().getMouseCanvasPosition(); if (plugin.getObjectsToMark() != null) { for (TileObject gameObject : plugin.getObjectsToMark()) { OverlayUtil.renderHoverableArea(graphics, gameObject.getClickbox(), mousePosition, CLICKBOX_FILL_COLOR, CLICKBOX_BORDER_COLOR, CLICKBOX_HOVER_BORDER_COLOR); OverlayUtil.renderImageLocation(plugin.getClient(), graphics, gameObject.getLocalLocation(), plugin.getClueScrollImage(), IMAGE_Z_OFFSET); } } } } public static CrypticClue forText(String text) { for (CrypticClue clue : CLUES) { if (clue.text.equalsIgnoreCase(text) || clue.questionText.equalsIgnoreCase(text)) { return clue; } } return null; } @Override public int[] getObjectIds() { return new int[] {objectId}; } @Override public String[] getNpcs() { return new String[] {npc}; } }
package net.runelite.client.plugins.cluescrolls.clues; import com.google.common.collect.ImmutableSet; import java.awt.Color; import java.awt.Graphics2D; import java.util.Set; import lombok.Getter; import net.runelite.api.GameObject; import net.runelite.api.NPC; import net.runelite.api.ObjectComposition; import net.runelite.api.coords.LocalPoint; import net.runelite.api.coords.WorldPoint; import net.runelite.client.plugins.cluescrolls.ClueScrollPlugin; import net.runelite.client.ui.overlay.OverlayUtil; import net.runelite.client.ui.overlay.components.PanelComponent; import static net.runelite.api.ObjectID.*; import static net.runelite.client.plugins.cluescrolls.ClueScrollOverlay.TITLED_CONTENT_COLOR; import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_BORDER_COLOR; import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_FILL_COLOR; import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_HOVER_BORDER_COLOR; import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLUE_SCROLL_IMAGE; import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.IMAGE_Z_OFFSET; import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.SPADE_IMAGE; @Getter public class CrypticClue extends ClueScroll implements TextClueScroll, NpcClueScroll, ObjectClueScroll, LocationClueScroll { private static final Set<CrypticClue> CLUES = ImmutableSet.of( new CrypticClue("Show this to Sherlock.", "Sherlock", new WorldPoint(2733, 3415, 0), "Sherlock is located to the east of the Sorcerer's tower in Seers' Village."), new CrypticClue("Talk to the bartender of the Rusty Anchor in Port Sarim.", "Bartender", new WorldPoint(3045, 3256, 0), "The Rusty Anchor is located in the north of Port Sarim."), new CrypticClue("The keeper of Melzars... Spare? Skeleton? Anar?", "Oziach", new WorldPoint(3068, 3516, 0), "Speak to Oziach in Edgeville"), new CrypticClue("Speak to Ulizius.", "Ulizius", new WorldPoint(3444, 3461, 0), "Ulizius is the monk who guards the gate into Mort Myre Swamp."), new CrypticClue("Search for a crate in a building in Hemenster.", CRATE_356, new WorldPoint(2636, 3454, 0), "House north of the Fishing Contest quest area. West of Grandpa Jack."), new CrypticClue("A reck you say Let's pray there aren't any ghosts.", "Father Aereck", new WorldPoint(3242, 3207, 0), "Speak to Father Aereck in Lumbridge."), new CrypticClue("Search the bucket in the Port Sarim jail.", BUCKET_9568, new WorldPoint(3013, 3181, 0), "Talk to Shantay & identify yourself as an outlaw, refuse to pay the 5gp fine twice and you will be sent to the Port Sarim jail."), new CrypticClue("Search the crates in a bank in Varrock.", NULL_336, new WorldPoint(3187, 9824, 0), "Search in the basement of the West Varrock bank."), new CrypticClue("Falo the bard wants to see you.", "Falo the Bard", new WorldPoint(2689, 3550, 0), "Speak to Falo the Bard"), new CrypticClue("Search a bookcase in the Wizards tower.", BOOKCASE_12539, new WorldPoint(3113, 3159, 0), "The bookcase located on the ground floor."), new CrypticClue("Come have a cip with this great soot covered denizen.", "Miner Magnus", new WorldPoint(2527, 3891, 0), "Talk to Miner Magnus east of the fairy ring CIP. Answer: 8"), new CrypticClue("Citric cellar.", "Heckel Funch", new WorldPoint(2490, 3488, 0), "Speak to Heckel Funch on the first floor in the Grand Tree."), new CrypticClue("I burn between heroes and legends.", "Candle maker", new WorldPoint(2799, 3438, 0), "Speak to the Candle maker in Catherby."), new CrypticClue("Speak to Sarah at Falador farm.", "Sarah", new WorldPoint(3038, 3292, 0), "Talk to Sarah at Falador farm, north of Port Sarim."), new CrypticClue("Search for a crate on the ground floor of a house in Seers' Village.", NULL_25890, new WorldPoint(2699, 3469, 0), "Search inside Phantuwti Fanstuwi Farsight's house, located south of the pub in Seers' Village."), new CrypticClue("Snah? I feel all confused, like one of those cakes...", "Hans", new WorldPoint(3211, 3219, 0), "Talk to Hans roaming around Lumbridge Castle."), new CrypticClue("Speak to Sir Kay in Camelot Castle.", "Sir Kay", new WorldPoint(2759, 3497, 0), "Sir Kay can be found in the courtyard at Camelot castle."), new CrypticClue("Gold I see, yet gold I require. Give me 875 if death you desire.", "Saniboch", new WorldPoint(2745, 3151, 0), "Speak to Saniboch at the Brimhaven Dungeon entrance."), new CrypticClue("Find a crate close to the monks that like to paaarty!", CRATE_354, new WorldPoint(2614, 3204, 0), "The crate is in the east side of the Kandarin monastery, near Brother Omad"), new CrypticClue("Identify the back of this over-acting brother. (He's a long way from home.)", "Hamid", new WorldPoint(3376, 3284, 0), "Talk to Hamid, the monk at the altar in the Duel Arena"), new CrypticClue("In a town where thieves steal from stalls, search for some drawers in the upstairs of a house near the bank.", new WorldPoint(2611, 3324, 0), "Kill any Guard located around East Ardougne for a medium key. Then search the drawers in the upstairs hallway of Jerico's house, which is the house with pigeon cages located south of the northern East Ardougne bank."), new CrypticClue("His bark is worse than his bite.", "Barker", new WorldPoint(3499, 3503, 0), "Speak to the Barker at Canifis's Barkers' Haberdashery."), new CrypticClue("The beasts to my east snap claws and tails, The rest to my west can slide and eat fish. The force to my north will jump and they'll wail, Come dig by my fire and make a wish.", new WorldPoint(2598, 3267, 0), "Dig by the torch in the Ardougne Zoo, between the penguins and the scorpions."), new CrypticClue("A town with a different sort of night-life is your destination. Search for some crates in one of the houses.", CRATE_24344, new WorldPoint(3499, 3507, 1), "Search the crate inside of the clothes shop in Canifis."), new CrypticClue("Stop crying! Talk to the head.", "Head mourner", new WorldPoint(2042, 4630, 0), "Talk to the Head mourner in the mourner headquarters in West Ardougne"), new CrypticClue("Search the crate near a cart in Port Khazard.", CRATE_366, new WorldPoint(2660, 3149, 0), "Search by the southern Khazard General Store in Port Khazard."), new CrypticClue("Speak to the bartender of the Blue Moon Inn in Varrock.", "Blue Moon Inn", new WorldPoint(3226, 3399, 0), "Talk to the bartender in Blue Moon Inn in Varrock."), new CrypticClue("This aviator is at the peak of his profession.", "Captain Bleemadge", new WorldPoint(2846, 1749, 0), "Captain Bleemadge, the gnome glider pilot, is found at the top of White Wolf Mountain."), new CrypticClue("Search the crates in the shed just north of East Ardougne.", CRATE_355, new WorldPoint(2617, 3347, 0), "The crates in the shed north of the northern Ardougne bank."), new CrypticClue("I wouldn't wear this jean on my legs.", "Father Jean", new WorldPoint(1697, 3574, 0), "Talk to father Jean in the Hosidius church"), new CrypticClue("Search the crate in the Toad and Chicken pub.", NULL_1827, new WorldPoint(2912, 3536, 0), "The Toad and Chicken pub is located in Burthorpe."), new CrypticClue("Search chests found in the upstairs of shops in Port Sarim.", CLOSED_CHEST_375, new WorldPoint(3016, 3205, 1), "Search the chest in the upstairs of Wydin's Food Store, on the east wall."), new CrypticClue("Right on the blessed border, cursed by the evil ones. On the spot inaccessible by both; I will be waiting. The bugs imminent possession holds the answer.", new WorldPoint(3410, 3324, 0), "B I P. Dig right under the fairy ring."), new CrypticClue("The dead, red dragon watches over this chest. He must really dig the view.", "Barbarian", 375, new WorldPoint(3353, 3332, 0), "Search the chest underneath the Red Dragon's head in the Exam Centre. Kill a MALE Barbarian in Barbarian Village or Barbarian Outpost to receive the key."), new CrypticClue("My home is grey, and made of stone; A castle with a search for a meal. Hidden in some drawers I am, across from a wooden wheel.", DRAWERS_5618, new WorldPoint(3213, 3216, 1), "Open the drawers inside the room with the spinning wheel on the first floor of Lumbridge Castle."), new CrypticClue("Come to the evil ledge, Yew know yew want to. Try not to get stung.", new WorldPoint(3089, 3468, 0), "Dig in Edgeville, just east of the Southern Yew tree."), new CrypticClue("Look in the ground floor crates of houses in Falador.", NULL_5536, new WorldPoint(3027, 3356, 0), "The house east of the east bank."), new CrypticClue("You were 3 and I was the 6th. Come speak to me.", "Vannaka", new WorldPoint(3146, 9913, 0), "Speak to Vannaka in Edgeville Dungeon."), new CrypticClue("Search the crates in Draynor Manor.", CRATE_11485, new WorldPoint(3105, 3369, 2), "Top floor of the manor"), new CrypticClue("Search the crates near a cart in Varrock.", MILL_2571, new WorldPoint(3226, 3452, 0), "South east of Varrock Palace, south of the tree farming patch."), new CrypticClue("A Guthixian ring lies between two peaks. Search the stones and you'll find what you seek.", STONES_26633, new WorldPoint(2922, 3484, 0), "Search the stones several steps west of the Guthixian stone circle in Taverley"), new CrypticClue("Search the boxes in the house near the south entrance to Varrock.", BOXES_5111, new WorldPoint(3203, 3384, 0), "The first house on the left when entering the city from the southern entrance."), new CrypticClue("His head might be hollow, but the crates nearby are filled with surprises.", CRATE_354, new WorldPoint(3478, 3091, 0), "Search the crates near the Clay golem in the ruins of Uzer."), new CrypticClue("One of the sailors in Port Sarim is your next destination.", "Captain Tobias", new WorldPoint(3026, 3216, 0), "Speak to Captain Tobias on the docks of Port Sarim."), new CrypticClue("THEY'RE EVERYWHERE!!!! But they were here first. Dig for treasure where the ground is rich with ore.", new WorldPoint(3081, 3421, 0), "Dig at Barbarian Village, next to the Stronghold of Security."), new CrypticClue("Talk to the mother of a basement dwelling son.", "Doris", new WorldPoint(3079, 3493, 0), "Evil Dave's mother, Doris is located in the house west of Edgeville bank."), new CrypticClue("Speak to Ned in Draynor Village.", "Ned", new WorldPoint(3098, 3258, 0), "Ned is found north or the Draynor bank."), new CrypticClue("Speak to Hans to solve the clue.", "Hans", new WorldPoint(3211, 3219, 0), "Hans can be found at Lumbridge Castle."), new CrypticClue("Search the crates in Canifis.", CRATE_24344, new WorldPoint(3509, 3497, 1), "Search inside the shop, Rufus' Meat Emporium."), new CrypticClue("Search the crates in the Dwarven mine.", CRATE_357, new WorldPoint(3034, 9849, 0), "Search the crate in the room east of the Ice Mountain ladder entrance in the Drogo's Mining Emporium."), new CrypticClue("A crate found in the tower of a church is your next location.", NULL_10627, new WorldPoint(2612, 3304, 1), "Climb the ladder and search the crates on the 1st floor in the Church in Ardougne"), new CrypticClue("Covered in shadows, the centre of the circle is where you will find the answer.", new WorldPoint(3488, 3289, 0), "Dig in the centre of Mort'ton, where the roads intersect"), new CrypticClue("I lie lonely and forgotten in mid wilderness, where the dead rise from their beds. Feel free to quarrel and wind me up and dig while you shoot their heads.", new WorldPoint(3174, 3663, 0), "Directly under the crossbow respawn in the Graveyard of Shadows in level 18 Wilderness."), new CrypticClue("In the city where merchants are said to have lived, talk to a man with a splendid cape, but a hat dropped by goblins.", "Head chef", new WorldPoint(3143, 3445, 0), "Talk to the Head chef in Cooks' Guild west of Varrock."), new CrypticClue("The mother of the reptilian sacrifice.", "Zul-Cheray", new WorldPoint(2204, 3050, 0), "Talk to Zul-Cheray in a house near the sacrificial boat at Zul-Andra."), new CrypticClue("I watch the sea. I watch you fish. I watch your tree.", "Ellena", new WorldPoint(2860, 3431, 0), "Speak to Ellena at Catherby fruit tree patch."), new CrypticClue("Dig between some ominous stones in Falador.", new WorldPoint(3040, 3399, 0), "Three standing stones inside a walled area. East of the northern Falador gate."), new CrypticClue("Speak to Rusty north of Falador.", "Rusty", new WorldPoint(2979, 3435, 0), "Rusty can be found northeast of Falador on the way to the Mind altar."), new CrypticClue("Search a wardrobe in Draynor.", NULL_5620, new WorldPoint(3088, 3259, 0), "Go to Aggie's house and search the wardrobe in northern wall."), new CrypticClue("Show this to Sherlock", "Sherlock", new WorldPoint(2733, 3415, 0), "Sherlock can be found south of Seer's Village."), new CrypticClue("I have many arms but legs, I have just one, I have little family but my seed, You can grow on, I am not dead, yet I am but a spirit, and my power on your quests, you will earn the right to free it.", NULL_1293, new WorldPoint(2542, 3170, 0), "Spirit Tree in Tree Gnome Village"), new CrypticClue("I am the one who watches the giants. The giants in turn watch me. I watch with two while they watch with one. Come seek where I may be.", "Kamfreena", new WorldPoint(2845, 3539, 0), "Speak to Kamfreena on the top floor of the Warriors' Guild."), new CrypticClue("In a town where wizards are known to gather, search upstairs in a large house to the north.", new WorldPoint(2595, 3105, 0), "Search the chest, upstairs, in the house north of Yanille Wizards' Guild. Open the chest to receive the message: The chest is locked! An inscription on the chest reads: Stand by your man. Head downstairs to kill a Man."), new CrypticClue("Probably filled with wizards socks.", "Wizard", new WorldPoint(3109, 9959, 0), "Search the drawers in the basement of the Wizard's Tower south of Draynor Village. Kill one of the Wizards for the key."), new CrypticClue("Even the seers say this clue goes right over their heads.", CRATE_26635, new WorldPoint(2707, 3488, 2), "Search the crate on the Seers Agility Course in Seers Village"), new CrypticClue("Speak to a Wyse man.", "Wyson the gardener", new WorldPoint(3026, 3378, 0), "Talk to Wyson the gardener at Falador Park."), new CrypticClue("You'll need to look for a town with a central fountain. Look for a locked chest in the town's chapel.", CLOSED_CHEST_5108, new WorldPoint(3256, 3487, 0), "Search the chest by the stairs in the Varrock church. Kill a Monk in Ardougne Monastery to obtain the key."), new CrypticClue("Talk to Ambassador Spanfipple in the White Knights Castle.", "Ambassador Spanfipple", new WorldPoint(2979, 3340, 0), "Ambassador Spanfipple can be found roaming on the 2nd floor of the White Knights Castle."), new CrypticClue("Mine was the strangest birth under the sun. I left the crimson sack, yet life had not begun. Entered the world, and yet was seen by none.", new WorldPoint(2832, 9586, 0), "Inside Karamja Volcano, dig directly underneath the Red spiders' eggs respawn."), new CrypticClue("Search for a crate in Varrock Castle.", CRATE_5113, new WorldPoint(3224, 3492, 0), "Search the crate in the corner of the kitchen in Varrock Castle."), new CrypticClue("And so on, and so on, and so on. Walking from the land of many unimportant things leads to a choice of paths.", new WorldPoint(2591, 3879, 0), "Dig on Etceteria next to the Evergreen tree in front of the castle walls."), new CrypticClue("Speak to Donovan, the Family Handyman.", "Donovan the Family Handyman", new WorldPoint(2743, 3578, 0), "Donovan the Family Handyman is found on the 2nd floor of Sinclair Mansion."), new CrypticClue("Search the crates in the Barbarian Village helmet shop.", NULL_10627, new WorldPoint(3073, 3430, 0), "Peska's Helmet Shop in Barbarian Village."), new CrypticClue("Search the boxes of Falador's general store.", CRATES_24088, new WorldPoint(2955, 3390, 0), "Falador general store."), new CrypticClue("In a village made of bamboo, look for some crates under one of the houses.", CRATE_356, new WorldPoint(2800, 3074, 0), "Search the crate by the house at the northern point of the broken jungle fence in Tai Bwo Wannai."), new CrypticClue("Buried beneath the ground, who knows where it's found. Lucky for you, A man called Jorral may have a clue.", "Jorral", new WorldPoint(2437, 3347, 0), "Speak to Jorral to receive a strange device."), new CrypticClue("This crate is mine, all mine, even if it is in the middle of the desert.", new WorldPoint(3290, 3022, 0), "Center of desert Mining Camp. Search the crates. Requires the metal key from Tourist Trap to enter."), new CrypticClue("Dig where 4 siblings and I all live with our evil overlord.", new WorldPoint(3195, 3357, 0), "Dig in the chicken pen inside the Champion's Guild"), new CrypticClue("In a town where the guards are armed with maces, search the upstairs rooms of the Public House.", "Guard Dog", 348, new WorldPoint(2574, 3326, 1), "Search the drawers in the pub north of Ardougne Castle. Kill a Guard dog at Handelmort Mansion to obtain the key."), new CrypticClue("Four blades I have, yet draw no blood; Still I turn my prey to powder. If you are brave, come search my roof; It is there my blades are louder.", NULL_1784, new WorldPoint(3167, 3307, 2), "Lumbridge windmill, search the crates on the top floor."), new CrypticClue("Search through some drawers in the upstairs of a house in Rimmington.", NULL_10627, new WorldPoint(2970, 3214, 1), "On the first floor of the house north of Hetty the Witch's house in Rimmington."), new CrypticClue("Probably filled with books on magic.", BOOKCASE_380, new WorldPoint(3096, 9572, 0), "Search the bookcase in the basement of Wizard's Tower."), new CrypticClue("If you look closely enough, it seems that the archers have lost more than their needles.", HAYSTACK, new WorldPoint(2672, 3416, 0), "Search the haystack by the south corner of the Rangers' Guild"), new CrypticClue("Search the crate in the left-hand tower of Lumbridge Castle.", CRATE_357, new WorldPoint(3228, 3212, 1), "Located on the first floor of the southern tower at the Lumbridge Castle entrance."), new CrypticClue("'Small shoe.' Often found with rod on mushroom.", "Gnome trainer", new WorldPoint(2476, 3428, 0), "Talk to any Gnome trainer in the agility area of the Tree Gnome Stronghold."), new CrypticClue("I live in a deserted crack collecting soles.", "Genie", new WorldPoint(3371, 9320, 0), "Enter the crack west of Nardah Rug merchant, and talk to the Genie."), new CrypticClue("46 is my number. My body is the colour of burnt orange and crawls among those with eight. Three mouths I have, yet I cannot eat. My blinking blue eye hides my grave.", new WorldPoint(3170, 3885, 0), "Sapphire respawn in the Spider's Nest, lvl 46 Wilderness. Dig under the sapphire spawn."), new CrypticClue("Green is the colour of my death as the winter-guise, I swoop towards the ground.", new WorldPoint(2780, 3783, 0), "Players need to slide down to where Trollweiss grows on Trollweiss Mountain."), new CrypticClue("Talk to a party-goer in Falador.", "Lucy", new WorldPoint(3046, 3382, 0), "Lucy is the bartender on the 1st [2nd for US] floor of the party room."), new CrypticClue("He knows just how easy it is to lose track of time.", "Brother Kojo", new WorldPoint(2570, 3250, 0), "Speak to brother Kojo in the Clock Tower. Answer: 22"), new CrypticClue("A great view - watch the rapidly drying hides get splashed. Check the box you are sitting on.", NULL_1838, new WorldPoint(2523, 3493, 1), "Almera's House north of Baxtorian Falls, search boxes on the 2nd floor."), new CrypticClue("Search the Coffin in Edgeville.", COFFIN, new WorldPoint(3091, 3477, 0), "Search the coffin located by the Wilderness teleport lever."), new CrypticClue("When no weapons are at hand, now it is time to reflect, in Saradomin's name! Redemption draws closer...", DRAWERS_350, new WorldPoint(2818, 3351, 0), "On Entrana, search the southern drawer in the house with the cooking range."), new CrypticClue("Search the crates in a house in Yanille that has a piano.", CRATE_357, new WorldPoint(2598, 3105, 0), "The house is located northwest of the bank."), new CrypticClue("Speak to the staff of Sinclair mansion.", "Louisa", new WorldPoint(2736, 3578, 0), "Speak to Louisa, on the ground floor, found at the Sinclair Mansion."), new CrypticClue("I am a token of the greatest love. I have no beginning or end. My eye is red, I can fit like a glove. Go to the place where it's money they lend, And dig by the gate to be my friend.", new WorldPoint(3191, 9825, 0), "Dig by the gate in the basement of the West Varrock bank."), new CrypticClue("Speak to Kangai Mau.", "Kangai Mau", new WorldPoint(2791, 3183, 0), "Kangai Mau is found in the Shrimp and Parrot in Brimhaven."), new CrypticClue("Speak to Hajedy.", "Hajedy", new WorldPoint(2779, 3211, 0), "Hajedy is found by the cart, located just south of the Brimhaven docks."), new CrypticClue("Must be full of railings.", BOXES_6176, new WorldPoint(2576, 3464, 0), "Search the boxes around the hut where the broken Dwarf Cannon is, close to the start of the Dwarf Cannon quest."), new CrypticClue("I wonder how many bronze swords he has handed out.", "Vannaka", new WorldPoint(3164, 9913, 0), "Talk to Vannaka. He can be found in Edgeville Dungeon."), new CrypticClue("Read 'How to breed scorpions.' By O.W.Thathurt.", BOOKCASE_380, new WorldPoint(2703, 3409, 1), "Search the northern bookcase on the 1st [2nd for US] of the Sorcerer's Tower."), new CrypticClue("Search the crates in the Port Sarim Fishing shop.", NULL_918, new WorldPoint(3013, 3222, 0), "Search the crates, by the door, in Gerrant's Fishy Business in Port Sarim."), new CrypticClue("Speak to the Lady of the Lake.", "Lady of the Lake", new WorldPoint(2924, 3405, 0), "Talk to the Lady of the Lake in Taverley."), new CrypticClue("Rotting next to a ditch. Dig next to the fish.", new WorldPoint(3547, 3183, 0), "Dig next to a fishing spot on the south-east side of Burgh de Rott."), new CrypticClue("The King's magic won't be wasted by me.", "Guardian Mummy", new WorldPoint(1934, 4427, 0), "Talk to the Guardian mummy inside the Pyramid Plunder minigame in Sophanem"), new CrypticClue("Dig where the forces of Zamorak and Saradomin collide.", new WorldPoint(3049, 4839, 0), "Dig next to the law rift in the Abyss"), new CrypticClue("Search the boxes in the goblin house near Lumbridge.", NULL_10627, new WorldPoint(3245, 3245, 0), "Goblin house on the eastern side of the river."), new CrypticClue("W marks the spot.", new WorldPoint(2867, 3546, 0), "Dig in the middle of the Warriors' Guild entrance hall"), new CrypticClue("There is no 'worthier' lord.", "Lord Iorwerth", new WorldPoint(2205, 3252, 0), "Speak to Lord Iorwerth in the elven camp near Prifddinas"), new CrypticClue("Surviving.", "Sir Vyvin", new WorldPoint(2983, 3338, 0), "Talk to Sir Vyvin on the 3rd floor of Falador castle."), new CrypticClue("My name is like a tree, yet it is spelt with a 'g'. Come see the fur which is right near me.", "Wilough", new WorldPoint(3221, 3435, 0), "Speak to Wilough, next to the Fur Merchant in Varrock Square."), new CrypticClue("Speak to Jatix in Taverley.", "Jatix", new WorldPoint(2898, 3428, 0), "Jatix is found in the middle of Taverley."), new CrypticClue("Speak to Gaius in Taverley.", "Gaius", new WorldPoint(2884, 3450, 0), "Gaius is found at the northwest corner in Taverley."), new CrypticClue("If a man carried my burden, he would break his back. I am not rich, but leave silver in my track. Speak to the keeper of my trail.", "Gerrant", new WorldPoint(3013, 3224, 0), "Speak to Gerrant in the fish shop in Port Sarim."), new CrypticClue("Search the drawers in Falador's chain mail shop.", DRAWERS, new WorldPoint(2972, 3312, 0), "Wayne's Chains - Chainmail Specialist store at the southern Falador walls."), new CrypticClue("Talk to the barber in the Falador barber shop.", "Hairdresser", new WorldPoint(2945, 3379, 0), "The Hairdresser can be found in the barber shop, north of the west Falador bank."), new CrypticClue("Often sought out by scholars of histories past, find me where words of wisdom speak volumes.", "Examiner", new WorldPoint(3362, 3341, 0), "Speak to an examiner at the Exam Centre."), new CrypticClue("Generally speaking, his nose was very bent.", "General Bentnoze", new WorldPoint(2957, 3511, 0), "Talk to General Bentnoze"), new CrypticClue("Search the bush at the digsite centre.", BUSH_2357, new WorldPoint(3345, 3378, 0), "The bush is on the east side of the first pathway towards the digsite from the Exam Centre."), new CrypticClue("Someone watching the fights in the Duel Arena is your next destination.", "Jeed", new WorldPoint(3360, 3242, 0), "Talk to Jeed, found on the upper floors, at the Duel Arena."), new CrypticClue("It seems to have reached the end of the line, and it's still empty.", NULL_638, new WorldPoint(3041, 9821, 0), "Search the carts in the northern part of the Dwarven Mine."), new CrypticClue("You'll have to plug your nose if you use this source of herbs.", new WorldPoint(3426, 3550, 1), "Kill an Aberrant spectre and pick up the casket"), new CrypticClue("When you get tired of fighting, go deep, deep down until you need an antidote.", CRATE_357, new WorldPoint(2576, 9583, 0), "Go to Yanille Agility dungeon and fall into the place with the poison spiders. Search the crate by the stairs leading up."), new CrypticClue("Search the bookcase in the monastery.", BOOKCASE_380, new WorldPoint(3054, 3484, 0), "Search the southeastern bookcase at Edgeville Monastery."), new CrypticClue("Surprising? I bet he is...", "Sir Prysin", new WorldPoint(3205, 3474, 0), "Talk to Sir Prysin in Varrock Palace."), new CrypticClue("Search upstairs in the houses of Seers' Village for some drawers.", NULL_925, new WorldPoint(2714, 3471, 1), "Located in the house with the spinning wheel. South of the Seers' Village bank."), new CrypticClue("Leader of the Yak City.", "Mawnis Burowgar", new WorldPoint(2336, 3799, 0), "Talk to Mawnis Burowgar in Neitiznot."), new CrypticClue("Speak to Arhein in Catherby.", "Arhein", new WorldPoint(2803, 3430, 0), "Arhein is just south of the Catherby bank."), new CrypticClue("Speak to Doric, who lives north of Falador.", "Doric", new WorldPoint(2951, 3451, 0), "Doric is found north of Falador and east of the Taverley gate."), new CrypticClue("Between where the best are commemorated for a year, and a celebratory cup, not just for beer.", new WorldPoint(3388, 3152, 0), "Dig at the Clan Cup Trophy at Clan Wars."), new CrypticClue("'See you in your dreams' said the vegetable man.", "Dominic Onion", new WorldPoint(2608, 3116, 0), "Speak to Dominic Onion at the Nightmare Zone teleport spot."), new CrypticClue("Try not to step on any aquatic nasties while searching this crate.", CRATE_18204, new WorldPoint(2764, 3273, 0), "Search the crate in Bailey's house on the Fishing Platform."), new CrypticClue("The cheapest water for miles around, but they react badly to religious icons.", CRATE_354, new WorldPoint(3178, 2987, 0), "Search the crates in the General Store tent in the Bandit Camp"), new CrypticClue("This village has a problem with cartloads of the undead. Try checking the bookcase to find an answer.", BOOKCASE_394, new WorldPoint(2833, 2992, 0), "Search the bookcase by the doorway of the building just south east of the Shilo Village Gem Mine."), new CrypticClue("Dobson is my last name, and with gardening I seek fame.", "Horacio", new WorldPoint(2635, 3310, 0), "Horacio, located in the garden of the Handelmort Mansion in East Ardougne."), new CrypticClue("The magic of 4 colours, an early experience you could learn. The large beast caged up top, rages, as his demised kin's loot now returns.", "Wizard Mizgog", new WorldPoint(3103, 3163, 2), "Speak to Wizard Mizgog at the top of the Wizard's Tower south of Draynor."), new CrypticClue("Aggie I see, Lonely and southern I feel I am neither inside nor outside the house yet no house would be complete without me. Your treasure lies beneath me.", new WorldPoint(3085, 3255, 0), "Dig outside the window of Aggies house in Draynor Village."), new CrypticClue("Search the chest in Barbarian Village.", null, "The chest located in the house with a spinning wheel."), new CrypticClue("Search the crates in the outhouse of the long building in Taverley.", null, "Located in the small building attached by a fence to the main building. Climb over the stile."), new CrypticClue("Talk to Ermin.", "Ermin", new WorldPoint(2488, 3409, 1), "Ermin can be found on the 1st floor of the tree house south-east of the Gnome Agility Course."), new CrypticClue("Ghostly bones.", null, "Kill an Ankou"), new CrypticClue("Search through chests found in the upstairs of houses in eastern Falador.", null, "The house is located southwest of the Falador Party Room. There are two chests in the room, search the northern chest."), new CrypticClue("Let's hope you don't meet a watery death when you encounter this fiend.", null, "Kill a waterfiend."), new CrypticClue("Reflection is the weakness for these eyes of evil.", null, "Kill a basilisk"), new CrypticClue("Search a bookcase in Lumbridge swamp.", null, "Located in Father Urhney's house."), new CrypticClue("Surround my bones in fire, ontop the wooden pyre. Finally lay me to rest, before my one last test.", null, "Kill a confused/lost barbarian to receive mangled bones. Construct and burn a pyre ship. Kill the ferocious barbarian spirit that spawns to receive a clue casket."), new CrypticClue("Fiendish cooks probably won’t dig the dirty dishes.", null, "Dig by the fire in the Rogues' Den."), new CrypticClue("My life was spared but these voices remain, now guarding these iron gates is my bane.", null, "Speak to the Key Master in Cerberus' Lair."), new CrypticClue("Search the boxes in one of the tents in Al Kharid.", null, "Search the crates in the tent east of the Silk trader."), new CrypticClue("One of several rhyming brothers, in business attire with an obsession for paper work.", null, "Speak to Piles in the Resource Area."), new CrypticClue("Search the drawers on the first floor of a building overlooking Ardougne's Market.", null, "Climb the ladder in the house north of the market."), new CrypticClue("'A bag belt only?', he asked his balding brothers.", null, "Talk to Abbot Langley in the monastery"), new CrypticClue("Search the drawers upstairs in Falador's shield shop.", null, "Cassie's Shield Shop at the northern Falador entrance."), new CrypticClue("Go to this building to be illuminated, and check the drawers while you are there.", "Market Guard", null, "The 2nd of the Lighthouse, Kill a Rellekka marketplace guard to obtain the key."), new CrypticClue("Dig near some giant mushrooms behind the Grand Tree.", null, "Dig near the red mushrooms northwest of the Grand Tree."), new CrypticClue("Pentagrams and demons, burnt bones and remains, I wonder what the blood contains.", null, "Dig under the blood rune spawn next the the Demonic Ruins."), new CrypticClue("Search the drawers above Varrock's shops.", null, "Located upstairs in Thessalia's Fine Clothes shop in Varrock."), new CrypticClue("Search the drawers in one of Gertrude's bedrooms.", null, "Kanel's bedroom (southeastern room), outside of west Varrock."), new CrypticClue("Under a giant robotic bird that cannot fly.", null, "Dig next to the terrorbird display in the south exhibit of Varrock Museum's basement."), new CrypticClue("Great demons, dragons, and spiders protect this blue rock, beneath which, you may find what you seek.", null, "Dig by the runite rock in the Lava Maze Dungeon"), new CrypticClue("My giant guardians below the market streets would be fans of rock and roll, if only they could grab hold of it. Dig near my green bubbles!", null, "Dig near the cauldron by Moss Giants under Varrock Sewers"), new CrypticClue("Varrock is where I reside not the land of the dead, but I am so old, I should be there instead. Let's hope your reward is as good as it says, just 1 gold one and you can have it read.", null, "Talk to Gypsy Aris, West of varrock main square."), new CrypticClue("Speak to a referee.", null, "Talk to a Gnome ball referee found on the Gnome ball field in the Gnome Stronghold. Answer: 5096"), new CrypticClue("This crate holds a better reward than a broken arrow.", null, "Inside the Ranging Guild. Search the crate behind the northern most building."), new CrypticClue("Search the drawers in the house next to the Port Sarim mage shop.", null, "House east of Betty's. Contains a cooking sink."), new CrypticClue("With a name like that, you'd expect a little more than just a few scimitars.", null, "Speak to Daga on Ape Atoll."), new CrypticClue("Strength potions with red spiders' eggs? He is quite a herbalist.", "Apothecary", new WorldPoint(3194, 3403, 0), "Talk to Apothecary in the South-western Varrock. (the) apothecary is just north-west of the Varrock Swordshop."), new CrypticClue("Robin wishes to see your finest range equipment.", null, "Robin at the inn in Port Phasmatys. Speak to him with +182 in ranged attack bonus."), new CrypticClue("You will need to under-cook to solve this one.", CRATE_357, new WorldPoint(3219, 9617, 0), "Search the crate in the Lumbridge basement."), new CrypticClue("Search through some drawers found in Taverley's houses.", DRAWERS_350, new WorldPoint(2894, 3418, 0), "The south-eastern most house, south of Jatix's Herblore Shop."), new CrypticClue("Anger Abbot Langley.", null, "Speak to Abbot Langley while you have a negative prayer bonus"), new CrypticClue("Dig where only the skilled, the wealthy, or the brave can choose not to visit again.", null, "Dig at Lumbridge spawn"), new CrypticClue("Scattered coins and gems fill the floor. The chest you seek is in the north east.", null, "Kill the King Black Dragon for a key (elite), and then open the closed chest in the NE corner of the lair."), new CrypticClue("A ring of water surrounds 4 powerful rings. Dig by the ladder that is located there.", null, "Dig by the ladder leading to the Dagannoth Kings room in the Waterbirth Island Dungeon."), new CrypticClue("This place sure is a mess.", null, "Ewesey is located in the Hosidius House mess hall in Great Kourend."), new CrypticClue("Here, there are tears, but nobody is crying. Speak to the guardian and show off your alignment to balance.", null, "Talk to Juna while wearing three Guthix related items."), new CrypticClue("You might have to turn over a few stones to progress.", null, "Kill a rock crab and pick up the casket (elite) that it drops."), new CrypticClue("Dig under Razorlor's toad batta.", null, "Dig on the toad batta spawn in Tarn's Lair."), new CrypticClue("Talk to Cassie in Falador.", null, "Cassie is found just south-east of the northern Falador gate."), new CrypticClue("Faint sounds of 'Arr', fire giants found deep, the eastern tip of a lake, are the rewards you could reap.", null, "Dig south of the pillar at the end of the Deep Wilderness Dungeon."), new CrypticClue("If you're feeling brave, dig beneath the dragon's eye.", null, "Dig below the mossy rock under the Viyeldi caves."), new CrypticClue("Search the tents in the Imperial Guard camp in Burthorpe for some boxes.", null, "Search in the tents in northwest corner of the camp."), new CrypticClue("A dwarf, approaching death, but very much in the light.", null, "Thorgel at the entrance to the Death altar"), new CrypticClue("You must be 100 to play with me.", null, "Speak to the Veteran boat squire at Pest Control"), new CrypticClue("Three rule below and three sit at top. Come dig at my entrance.", null, "Dig in front of the entrance to the Waterbirth Island Dungeon."), new CrypticClue("Search the drawers in the ground floor of a shop in Yanille.", null, "Search the drawers in Yanille's hunting shop."), new CrypticClue("Search the drawers of houses in Burthorpe.", null, "Inside Hild's house in the northeast corner of Burthorpe."), new CrypticClue("Where safe to speak, the man who offers the pouch of smallest size wishes to see your alignment.", null, "Speak to the Mage of Zamorak south of the Rune Shop in Varrock while wearing three zamorakian items"), new CrypticClue("Search the crates in the guard house of the northern gate of East Ardougne.", null, "The guard house is northeast of the Handelmort Mansion."), new CrypticClue("Go to the village being attacked by trolls, search the drawers in one of the houses.", null, "Go to Dunstan's house in the northeast corner of Burthorpe. Kill Penda in the Toad and Chicken to obtain the key."), new CrypticClue("You'll get licked.", null, "Kill a Bloodveld."), new CrypticClue("She's small but can build both literally and figuratively, as long as you have their favour", null, "Speak to Lovada south of the Lovakengj House blast mine"), new CrypticClue("Dig in front of the icy arena where 1 of 4 was fought.", null, "Where you fought Kamil from Desert Treasure."), new CrypticClue("Speak to Roavar.", null, "Talk to Roavar in the Canifis tavern."), new CrypticClue("Search the drawers upstairs of houses in the eastern part of Falador.", null, "House is located east of the eastern Falador bank and south of the fountain. The house is indicated by the icon on the minimap."), new CrypticClue("Search the drawers found upstairs in East Ardougne's houses.", null, "Upstairs of the pub north of the Ardougne Castle."), new CrypticClue("The far north eastern corner where 1 of 4 was defeated, the shadows still linger.", null, "Dig on the northeastern-most corner of the Shadow Dungeon. Bring a ring of visibility."), new CrypticClue("Search the drawers in a house in Draynor Village.", DRAWERS_350, new WorldPoint(3097, 3277, 0), "The drawer is located in the northernmost house in Draynor Village."), new CrypticClue("Search the boxes in a shop in Taverley.", null, "The box inside Gaius' Two Handed Shop."), new CrypticClue("I lie beneath the first descent to the holy encampment.", null, "Dig immediately after climbing down the first set of rocks towards Saradomin's encampment within the God Wars Dungeon."), new CrypticClue("Search the upstairs drawers of a house in a village where pirates are known to have a good time.", null, "The house in the southeast corner of Brimhaven, northeast of Davon's Amulet Store. Kill any Pirate located around Brimhaven to obtain the key."), new CrypticClue("Search the chest in the Duke of Lumbridge's bedroom.", null, "The Duke's room is on the 2nd floor in Lumbridge Castle."), new CrypticClue("Talk to the Doomsayer.", null, "Doomsayer can be found just north of Lumbridge Castle entrance."), new CrypticClue("Search the chests upstairs in Al Kharid Palace.", CLOSED_CHEST_375, new WorldPoint(3301, 3169, 1), "The chest is located, in the northeast corner, on the first floor of the Al Kharid Palace"), new CrypticClue("Search the boxes just outside the Armour shop in East Ardougne.", BOXES_361, new WorldPoint(2654, 3299, 0), "Outside Zenesha's Plate Mail Body Shop"), new CrypticClue("Surrounded by white walls and gems.", null, "Talk to Herquin, the gem store owner in Falador."), new CrypticClue("Monk's residence in the far west. See robe storage device.", null, "Search the drawers upstairs in the chapel found on the southern coast of Great Kourend's Hosidius House. Directly south of the player-owned house portal."), new CrypticClue("Search the drawers in Catherby's Archery shop.", DRAWERS_350, new WorldPoint(2825, 3442, 0), "Hickton's Archery Emporium in Catherby."), new CrypticClue("The hand ain't listening!", null, "Talk to The Face located by the manhole just north of the Port Sarim fishing shop."), new CrypticClue("Search the chest in the left-hand tower of Camelot Castle.", CLOSED_CHEST_25592, new WorldPoint(2748, 3495, 2), "Located on the 2nd floor of the western tower of Camelot."), new CrypticClue("Kill the spiritual, magic and godly whilst representing their own god", null, "Kill a spiritual mage in the God Wars Dungeon"), new CrypticClue("Anger those who adhere to Saradomin's edicts to prevent travel.", null, "Port Sarim Docks, try to charter a ship to Entrana with armour or weapons equipped."), new CrypticClue("South of a river in a town surrounded by the undead, what lies beneath the furnace?", null, "Dig in front of the Shilo Village furnace."), new CrypticClue("Talk to the Squire in the White Knights' castle in Falador.", null, "The squire is located in the courtyard of the White Knights' Castle."), new CrypticClue("Thanks, Grandma!", null, "Tynan can be found in the north-east corner of Piscarilius House in Great Kourend."), new CrypticClue("In a town where everyone has perfect vision, seek some locked drawers in a house that sits opposite a workshop.", null, "The drawers is in Seers' Village in the house south of the Elemental Workshop entrance. Kill any Chicken to obtain a key."), new CrypticClue("The treasure is buried in a small building full of bones. Here is a hint: it's not near a graveyard.", null, "In the western building near the Limestone quarry east of Varrock. Dig south of the box of bones in the smaller building."), new CrypticClue("Search the crates in East Ardougne's general store.", null, "Located south of the Ardounge church."), new CrypticClue("Come brave adventurer, your sense is on fire. If you talk to me, it's an old god you desire.", null, "Speak to Viggora"), new CrypticClue("2 musical birds. Dig in front of the spinning light.", null, "Dig in front of the spinning light in Ping and Pong's room inside the Iceberg"), new CrypticClue("Search the wheelbarrow in Rimmington mine.", null, "The Rimmington mining site is located north of Rimmington."), new CrypticClue("Belladonna, my dear. If only I had gloves, then I could hold you at last.", null, "Talk to Tool Leprechaun at Draynor Manor"), new CrypticClue("Impossible to make angry", null, "Speak to Abbot Langley"), new CrypticClue("Search the crates in Horvik's armoury.", null, "Horvik's in Varrock"), new CrypticClue("Ghommal wishes to be impressed by how strong your equipment is.", null, "Talk to Ghommal at the Warrior's Guild while wearing sufficiently strong equipment"), new CrypticClue("Shhhh!", null, "Speak to Logosia in the Arceuus House Library's ground floor."), new CrypticClue("Salty peter.", null, "Talk to Konoo who is digging saltpeter in the Hosidius district in Zeah."), new CrypticClue("Talk to Zeke in Al Kharid.", null, "Zeke is the owner of the scimitar shop in Al Kharid."), new CrypticClue("Guthix left his mark in a fiery lake, dig at the tip of it.", null, "Dig at the tip of the lava lake that is shaped like a Guthixian symbol, west of the Mage Arena."), new CrypticClue("Search the drawers in the upstairs of a house in Catherby.", null, "Perdu's house in Catherby."), new CrypticClue("Search a crate in the Haymaker's arms.", null, "Search the crate in the north-east corner of The Haymaker's Arms tavern east of the Woodcutting Guild."), new CrypticClue("Desert insects is what I see. Taking care of them was my responsibility. Your solution is found by digging near me.", new WorldPoint(3307, 9505, 0), "Dig next to the Entomologist, Kalphite area, Stronghold Slayer Cave."), new CrypticClue("Search the crates in most north-western house in Al Kharid.", null, "Search the crates in the house, marked with a icon, southeast of the gem stall."), new CrypticClue("You will have to fly high where a sword cannot help you.", null, "Kill an Aviansie."), new CrypticClue("A massive battle rages beneath so be careful when you dig by the large broken crossbow.", null, "NE of the God Wars Dungeon entrance, climb the rocky handholds & dig by large crossbow."), new CrypticClue("Mix yellow with blue and add heat, make sure you bring protection.", null, "Kill a green dragon."), new CrypticClue("Speak to Ellis in Al Kharid.", null, "Ellis is tanner just north of Al Kharid bank."), new CrypticClue("Search the chests in the Dwarven Mine.", null, "The chest is on the western wall, where Hura's Crossbow Shop is, in the Dwarven Mine."), new CrypticClue("In a while...", null, "Kill a crocodile."), new CrypticClue("A chisel and hammer reside in his home, strange for one of magic. Impress him with your magical equipment.", null, "Wizard Cromperty NE, East Ardougne. +100 magic attack bonus needed"), new CrypticClue("You have all of the elements available to solve this clue. Fortunately you do not have to go as far as to stand in a draft.", null, "Search the crate, west of the Air Elementals, inside the Elemental Workshop."), new CrypticClue("A demon's best friend holds the next step of this clue.", null, "Kill a hellhound"), new CrypticClue("Dig in the centre of a great city of 5 districts.", null, "Dig in front of the large statue in the centre of Great Kourend."), new CrypticClue("Hopefully this set of armor will help you to keep surviving.", null, "Speak to Sir Vyvin while wearing a white full helm, platebody, and platelegs."), new CrypticClue("North of the best monkey restaurant on Karamja, look for the centre of the triangle of boats and search there", null, "The crate on the dock to the west of the fishing site on the Northern shore of Karamja."), new CrypticClue("The beasts retreat, for their Queen is gone; the song of this town still plays on. Dig near the birthplace of a blade, be careful not to melt your spade.", null, "Dig in front of the small furnace in the Piscatoris Fishing Colony."), new CrypticClue("Darkness wanders around me, but fills my mind with knowledge.", null, "Speak to Biblia on the Arceuus House Library's top floor."), new CrypticClue("I would make a chemistry joke, but I'm afraid I wouldn't get a reaction.", null, "Talk to the Chemist in Rimmington"), new CrypticClue("Show this to Hazelmere.", null, "Hazelmere is found upstairs on the island located just east of Yanille."), new CrypticClue("Does one really need a fire to stay warm here?", null, "Dig next to the fire near the Volcanic Mine entrance."), new CrypticClue("Search the open crate found in a small farmhouse in Hosidius. Cabbages grow outside.", null, "The house is east of the Mess in Great Kourend."), new CrypticClue("Dig under Ithoi's cabin.", new WorldPoint(2529, 2838, 0), "Dig under Ithoi's cabin in the Corsair Cove."), new CrypticClue("Search the drawers, upstairs in the bank to the East of Varrock.", new WorldPoint(3250, 3420, 1), "Search the drawers upstairs in Varrock east bank") ); private String text; private String npc; private int objectId; private WorldPoint location; private String solution; private CrypticClue(String text, WorldPoint location, String solution) { this(text, null, -1, location, solution); } private CrypticClue(String text, int objectId, WorldPoint location, String solution) { this(text, null, objectId, location, solution); } private CrypticClue(String text, String npc, WorldPoint location, String solution) { this(text, npc, -1, location, solution); } private CrypticClue(String text, String npc, int objectId, WorldPoint location, String solution) { this.text = text; this.npc = npc; this.objectId = objectId; this.location = location; this.solution = solution; } @Override public void makeOverlayHint(PanelComponent panelComponent, ClueScrollPlugin plugin) { panelComponent.setTitle("Cryptic Clue"); panelComponent.setWidth(150); panelComponent.getLines().add(new PanelComponent.Line("Clue:")); panelComponent.getLines().add(new PanelComponent.Line(true, getText(), TITLED_CONTENT_COLOR)); if (getNpc() != null) { panelComponent.getLines().add(new PanelComponent.Line("NPC:")); panelComponent.getLines().add(new PanelComponent.Line(getNpc(), TITLED_CONTENT_COLOR)); } if (objectId != -1) { ObjectComposition object = plugin.getClient().getObjectDefinition(getObjectId()); if (object != null) { panelComponent.getLines().add(new PanelComponent.Line("Object:")); panelComponent.getLines().add(new PanelComponent.Line(object.getName(), TITLED_CONTENT_COLOR)); } } panelComponent.getLines().add(new PanelComponent.Line("Solution:")); panelComponent.getLines().add(new PanelComponent.Line(true, getSolution(), TITLED_CONTENT_COLOR)); } @Override public void makeWorldOverlayHint(Graphics2D graphics, ClueScrollPlugin plugin) { // Mark dig location if (getLocation() != null && getNpc() == null && objectId == -1) { LocalPoint localLocation = LocalPoint.fromWorld(plugin.getClient(), getLocation()); if (localLocation != null) { OverlayUtil.renderTileOverlay(plugin.getClient(), graphics, localLocation, SPADE_IMAGE, Color.ORANGE); } } // Mark NPC if (plugin.getNpcsToMark() != null) { for (NPC npc : plugin.getNpcsToMark()) { OverlayUtil.renderActorOverlayImage(graphics, npc, CLUE_SCROLL_IMAGE, Color.ORANGE, IMAGE_Z_OFFSET); } } // Mark game object if (objectId != -1) { net.runelite.api.Point mousePosition = plugin.getClient().getMouseCanvasPosition(); if (plugin.getObjectsToMark() != null) { for (GameObject gameObject : plugin.getObjectsToMark()) { OverlayUtil.renderHoverableArea(graphics, gameObject.getClickbox(), mousePosition, CLICKBOX_FILL_COLOR, CLICKBOX_BORDER_COLOR, CLICKBOX_HOVER_BORDER_COLOR); OverlayUtil.renderImageLocation(plugin.getClient(), graphics, gameObject.getLocalLocation(), CLUE_SCROLL_IMAGE, IMAGE_Z_OFFSET); } } } } public static CrypticClue forText(String text) { for (CrypticClue clue : CLUES) { if (clue.text.equalsIgnoreCase(text)) { return clue; } } return null; } }
package net.winterly.rxjersey.client.rxjava2; import net.winterly.rxjersey.client.ClientMethodInvoker; import net.winterly.rxjersey.client.RxClientExceptionMapper; import net.winterly.rxjersey.client.inject.Remote; import net.winterly.rxjersey.client.inject.RemoteResolver; import net.winterly.rxjersey.client.inject.RxJerseyClient.RxJerseyClientImpl; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.grizzly.connector.GrizzlyConnectorProvider; import javax.inject.Singleton; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.core.Feature; import javax.ws.rs.core.FeatureContext; /** * Feature implementation to configure RxJava support for clients */ public class RxJerseyClientFeature implements Feature { private Client client; public RxJerseyClientFeature register(Client client) { this.client = client; return this; } @Override public boolean configure(FeatureContext context) { if (client == null) { client = defaultClient(); } client.register(RxBodyReader.class); context.register(RxClientExceptionMapper.class); context.register(new Binder()); return true; } protected Client defaultClient() { int cores = Runtime.getRuntime().availableProcessors(); ClientConfig config = new ClientConfig(); config.connectorProvider(new GrizzlyConnectorProvider()); config.property(ClientProperties.ASYNC_THREADPOOL_SIZE, cores); return ClientBuilder.newClient(config); } private class Binder extends AbstractBinder { @Override protected void configure() { bind(RemoteResolver.class) .to(Remote.TYPE) .in(Singleton.class); bind(FlowableClientMethodInvoker.class) .to(ClientMethodInvoker.class) .in(Singleton.class); bind(client) .qualifiedBy(new RxJerseyClientImpl()) .to(Client.class); } } }
package org.eclipse.persistence.sdo.helper; import java.io.File; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.management.AttributeChangeNotification; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.Notification; import javax.management.NotificationFilterSupport; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.eclipse.persistence.exceptions.SDOException; import org.eclipse.persistence.internal.security.PrivilegedAccessHelper; import org.eclipse.persistence.sdo.SDOConstants; import org.eclipse.persistence.sdo.SDOResolvable; import org.eclipse.persistence.sdo.helper.delegates.SDODataFactoryDelegate; import org.eclipse.persistence.sdo.helper.delegates.SDOTypeHelperDelegate; import org.eclipse.persistence.sdo.helper.delegates.SDOXMLHelperDelegate; import org.eclipse.persistence.sdo.helper.delegates.SDOXSDHelperDelegate; import commonj.sdo.helper.CopyHelper; import commonj.sdo.helper.DataFactory; import commonj.sdo.helper.DataHelper; import commonj.sdo.helper.EqualityHelper; import commonj.sdo.helper.HelperContext; import commonj.sdo.helper.TypeHelper; import commonj.sdo.helper.XMLHelper; import commonj.sdo.helper.XSDHelper; import commonj.sdo.impl.ExternalizableDelegator; /** * <b>Purpose:</b> * <ul> * <li>This class represents a local HelperContext. The global * HelperContext can be accessed as HelperProvider.getDefaultContext().</li> * </ul> * <b>Responsibilities:</b> * <ul> * <li>Provide access to instances of helper objects.</li> * <li>Provide an OSGi compatible HelperContext (when the constructor that takes * a ClassLoader is used).</li> * </ul> * * @since Oracle TopLink 11.1.1.0.0 */ public class SDOHelperContext implements HelperContext { protected CopyHelper copyHelper; protected DataFactory dataFactory; protected DataHelper dataHelper; protected EqualityHelper equalityHelper; protected XMLHelper xmlHelper; protected TypeHelper typeHelper; protected XSDHelper xsdHelper; private String identifier; private Map<String, Object> properties; // Each application will have its own helper context - it is assumed that application // names/loaders are unique within each active server instance private static ConcurrentHashMap<Object, ConcurrentHashMap<String, HelperContext>> helperContexts = new ConcurrentHashMap<Object, ConcurrentHashMap<String, HelperContext>>(); // Each application will have a Map of alias' to identifiers private static ConcurrentHashMap<Object, ConcurrentHashMap<String, String>> aliasMap = new ConcurrentHashMap<Object, ConcurrentHashMap<String, String>>(); // allow users to set their own classloader to context map pairs private static WeakHashMap<ClassLoader, WeakHashMap<String, WeakReference<HelperContext>>> userSetHelperContexts = new WeakHashMap<ClassLoader, WeakHashMap<String, WeakReference<HelperContext>>>(); // keep a map of application names to application class loaders to handle redeploy private static ConcurrentHashMap<String, ClassLoader> appNameToClassLoaderMap = new ConcurrentHashMap<String, ClassLoader>(); // Application server identifiers private static String OC4J_CLASSLOADER_NAME = "oracle"; private static String WLS_CLASSLOADER_NAME = "weblogic"; private static String WAS_CLASSLOADER_NAME = "com.ibm.ws"; private static String JBOSS_CLASSLOADER_NAME = "jboss"; private static String GLOBAL_HELPER_IDENTIFIER = ""; private static final int WLS_IDENTIFIER = 0; private static final int JBOSS_IDENTIFIER = 1; // Common private static final int COUNTER_LIMIT = 20; // For WebLogic private static ApplicationAccessWLS applicationAccessWLS = null; private static MBeanServer wlsMBeanServer = null; private static ObjectName wlsThreadPoolRuntime = null; private static final String WLS_ENV_CONTEXT_LOOKUP = "java:comp/env/jmx/runtime"; private static final String WLS_CONTEXT_LOOKUP = "java:comp/jmx/runtime"; private static final String WLS_RUNTIME_SERVICE = "RuntimeService"; private static final String WLS_SERVICE_KEY = "com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean"; private static final String WLS_APP_RUNTIMES = "ApplicationRuntimes"; private static final String WLS_SERVER_RUNTIME = "ServerRuntime"; private static final String WLS_THREADPOOL_RUNTIME = "ThreadPoolRuntime"; private static final String WLS_EXECUTE_THREAD = "ExecuteThread"; private static final String WLS_MBEAN_SERVER = "MBeanServer"; private static final String WLS_EXECUTE_THREAD_GET_METHOD_NAME = "getExecuteThread"; private static final String WLS_APPLICATION_NAME = "ApplicationName"; private static final String WLS_APPLICATION_NAME_GET_METHOD_NAME = "getApplicationName"; private static final String WLS_ACTIVE_VERSION_STATE = "ActiveVersionState"; private static final Class[] WLS_PARAMETER_TYPES = {}; // For WebSphere private static final String WAS_NEWLINE = "\n"; private static final String WAS_APP_COLON = "[app:"; private static final String WAS_CLOSE_BRACKET = "]"; // For JBoss private static MBeanServer jbossMBeanServer = null; private static String JBOSS_SERVICE_CONTROLLER = "jboss.system:service=ServiceController"; private static String JBOSS_TYPE_STOP = "org.jboss.system.ServiceMBean.stop"; private static String JBOSS_ID_KEY = "id"; private static final String JBOSS_DEFAULT_DOMAIN_NAME = "jboss"; private static final String JBOSS_VFSZIP = "vfszip:"; private static final String JBOSS_VFSFILE = "vfsfile:"; private static final String JBOSS_EAR = ".ear"; private static final String JBOSS_JAR = ".jar"; private static final String JBOSS_WAR = ".war"; private static final int JBOSS_VFSZIP_OFFSET = JBOSS_VFSZIP.length(); private static final int JBOSS_VFSFILE_OFFSET = JBOSS_VFSFILE.length(); private static final int JBOSS_EAR_OFFSET = JBOSS_EAR.length(); private static final int JBOSS_TRIM_COUNT = 2; // for stripping off the remaining '/}' chars // allow users to provide application info private static ApplicationResolver appResolver; private static boolean isAppResolverSet = false; /** * ADVANCED: * Used to set an ApplicationResolver instance that will be used to retrieve * info pertaining to a given application, such as the application name, in * the case where our logic fails. * * This method can be called once and only once per active server instance. * * @param aResolver the ApplicationResolver instance that will be used to retrieve * info pertaining to a given application. Note that null is * considered a valid set operation. * @throws SDOException if more than one call is made to this method * in an active server instance. */ public static void setApplicationResolver(ApplicationResolver aResolver) { // we only allow one set operation per running server instance if (isApplicationResolverSet()) { throw SDOException.attemptToResetApplicationResolver(); } appResolver = aResolver; isAppResolverSet = true; } /** * Indicates if a call to setApplicationResolver has been made. * * @return true if a prior call to setApplicationResolver has * been made, false otherwise */ public static boolean isApplicationResolverSet() { return isAppResolverSet; } /** * Create a local HelperContext. The current thread's context ClassLoader * will be used to find static instance classes. In OSGi environments the * construct that takes a ClassLoader parameter should be used instead. */ public SDOHelperContext() { this(Thread.currentThread().getContextClassLoader()); } /** * Create a local HelperContext with the given identifier. The current * thread's context ClassLoader will be used to find static instance * classes. In OSGi environments the construct that takes a ClassLoader * parameter should be used instead. * * @param identifier The unique label for this HelperContext. */ public SDOHelperContext(String identifier) { this(identifier, Thread.currentThread().getContextClassLoader()); } /** * Create a local HelperContext. This constructor should be used in OSGi * environments. * * @param aClassLoader This class loader will be used to find static * instance classes. */ public SDOHelperContext(ClassLoader aClassLoader) { super(); this.identifier = this.GLOBAL_HELPER_IDENTIFIER; initialize(aClassLoader); } /** * Create a local HelperContext with the given identifier. This constructor * should be used in OSGi environments. * * @param identifier The unique label for this HelperContext. * @param aClassLoader This class loader will be used to find static * instance classes. */ public SDOHelperContext(String identifier, ClassLoader aClassLoader) { super(); this.identifier = identifier; initialize(aClassLoader); } /** * The underlying helpers for this instance will be instantiated * in this method. * * @param aClassLoader */ protected void initialize(ClassLoader aClassLoader) { copyHelper = new SDOCopyHelper(this); dataFactory = new SDODataFactoryDelegate(this); dataHelper = new SDODataHelper(this); equalityHelper = new SDOEqualityHelper(this); xmlHelper = new SDOXMLHelperDelegate(this, aClassLoader); typeHelper = new SDOTypeHelperDelegate(this); xsdHelper = new SDOXSDHelperDelegate(this); } /** * Reset the Type,XML and XSD helper instances. */ public void reset() { ((SDOTypeHelper)getTypeHelper()).reset(); ((SDOXMLHelper)getXMLHelper()).reset(); ((SDOXSDHelper)getXSDHelper()).reset(); } /** * Return the CopyHelper instance for this helper context. */ public CopyHelper getCopyHelper() { return copyHelper; } /** * Return the DataFactory instance for this helper context. */ public DataFactory getDataFactory() { return dataFactory; } /** * Return the DataHelper instance for this helper context. */ public DataHelper getDataHelper() { return dataHelper; } /** * Return the EqualityHelper instance for this helper context. */ public EqualityHelper getEqualityHelper() { return equalityHelper; } /** * Return the TypeHelper instance for this helper context. */ public TypeHelper getTypeHelper() { return typeHelper; } /** * Return the XMLHelper instance for this helper context. */ public XMLHelper getXMLHelper() { return xmlHelper; } /** * Return the XSDHelper instance for this helper context. */ public XSDHelper getXSDHelper() { return xsdHelper; } /** * Create and return a new ExternalizableDelegator.Resolvable instance based * on this helper context. * * @return */ public ExternalizableDelegator.Resolvable createResolvable() { return new SDOResolvable(this); } /** * Create and return a new ExternalizableDelegator.Resolvable instance based * on this helper context and a given target. * * @param target * @return */ public ExternalizableDelegator.Resolvable createResolvable(Object target) { return new SDOResolvable(target, this); } /** * INTERNAL: * Put a ClassLoader/HelperContext key/value pair in the Thread HelperContext * map. If Thread.currentThread().getContextClassLoader() == key during * getHelperContext() call then the HelperContext (value) will be returned. * This method will overwrite an existing entry in the map with the same * ClassLoader key. * * @param key class loader * @param value helper context */ public static void putHelperContext(ClassLoader key, HelperContext value) { if (key == null || value == null) { return; } WeakHashMap<String, WeakReference<HelperContext>> currentMap = userSetHelperContexts.get(key); if(currentMap == null) { currentMap = new WeakHashMap<String, WeakReference<HelperContext>>(); userSetHelperContexts.put(key, currentMap); } currentMap.put(((SDOHelperContext)value).getIdentifier(), new WeakReference(value)); } /** * INTERNAL: * Retrieve the HelperContext for a given ClassLoader from the Thread * HelperContext map. * * @param key class loader * @return HelperContext for the given key if key exists in the map, otherwise null */ private static HelperContext getUserSetHelperContext(String identifier, ClassLoader key) { if (key == null) { return null; } WeakHashMap<String, WeakReference<HelperContext>> currentMap = userSetHelperContexts.get(key); if(currentMap == null) { return null; } WeakReference<HelperContext> ref = currentMap.get(identifier); if(ref == null) { return null; } return ref.get(); } /** * INTERNAL: * Remove a ClassLoader/HelperContext key/value pair from the Thread * HelperContext map. If there are multiple local helper contexts associated * with this ClassLoader, they will all be removed from the map. * * @param key class loader */ public static void removeHelperContext(ClassLoader key) { if (key == null) { return; } userSetHelperContexts.remove(key); } /** * INTERNAL * @param identifier the specific identifier of the HelperContext to be removed. "" for a Global helper * @param key the ClassLoader associated with the HelperContext to be removed */ public static void removeHelperContext(String identifier, ClassLoader key) { if(key == null) { return; } WeakHashMap<String, WeakReference<HelperContext>> currentMap = userSetHelperContexts.get(key); if(currentMap != null) { currentMap.remove(key); } } /** * INTERNAL: * Return the helper context for a given key. The key will either * be a ClassLoader or a String (representing an application name). * A new context will be created and put in the map if none exists * for the given key. * * The key is assumed to be non-null - getDelegateKey should always * return either a string representing the application name (for WLS, * WAS and JBoss if available) or a class loader. This is relevant * since 'putIfAbsent' will throw a null pointer exception if the * key is null. */ public static HelperContext getHelperContext() { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // check the map for contextClassLoader and return it if it exists HelperContext hCtx = getUserSetHelperContext(GLOBAL_HELPER_IDENTIFIER, contextClassLoader); if (hCtx != null) { return hCtx; } return getHelperContext(GLOBAL_HELPER_IDENTIFIER); } /** * Return the local helper context associated with the given identifier, or * create one if it does not already exist. If identifier is an alias, the * value associated with it in the alias Map will be used as the identifier * value. * * @param identifier the identifier or alias to use for lookup/creation * @return HelperContext associated with identifier, or a new HelperContext * keyed on identifier if none eixsts */ public static HelperContext getHelperContext(String identifier) { String id = identifier; // if identifier is an alias, we need the actual id value ConcurrentMap<String, String> aliasEntries = getAliasMap(); if (aliasEntries.containsKey(identifier)) { id = aliasEntries.get(identifier); } ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // check the map for contextClassLoader and return it if it exists HelperContext hCtx = getUserSetHelperContext(id, contextClassLoader); if (hCtx != null) { return hCtx; } ConcurrentMap<String, HelperContext> contextMap = getContextMap(); HelperContext helperContext = contextMap.get(id); if (null == helperContext) { helperContext = new SDOHelperContext(id); HelperContext existingContext = contextMap.putIfAbsent(id, helperContext); if (existingContext != null) { helperContext = existingContext; } } return helperContext; } /** * Return the local helper context with the given identifier, or create * one if it does not already exist. */ public static HelperContext getHelperContext(String identifier, ClassLoader classLoader) { ConcurrentMap<String, HelperContext> contextMap = getContextMap(); HelperContext helperContext = contextMap.get(identifier); if (null == helperContext) { helperContext = new SDOHelperContext(identifier, classLoader); HelperContext existingContext = contextMap.putIfAbsent(identifier, helperContext); if (existingContext != null) { helperContext = existingContext; } } return helperContext; } /** * Returns the map of helper contexts, keyed on Identifier, for the current application * @return */ static ConcurrentMap<String, HelperContext> getContextMap() { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); String classLoaderName = contextClassLoader.getClass().getName(); // get a MapKeyLookupResult instance based on the context loader MapKeyLookupResult hCtxMapKey = getContextMapKey(contextClassLoader, classLoaderName); // at this point we will have a loader and possibly an application name String appName = hCtxMapKey.getApplicationName(); ClassLoader appLoader = hCtxMapKey.getLoader(); // we will use the application name as the map key if set; otherwise we use the loader Object contextMapKey = appName != null ? appName : appLoader; ConcurrentHashMap<String, HelperContext> contextMap = helperContexts.get(contextMapKey); // handle possible redeploy // the following block only applies to WAS - hence the loader name check if (contextMap != null && appName != null && classLoaderName.contains(WAS_CLASSLOADER_NAME)) { // at this point there is an existing entry in the map - if the context is keyed // on application name we need to check to see if a redeployment occurred; in // that case the app names will match, but the class loaders will not ClassLoader currentAppLoader = appNameToClassLoaderMap.get(appName); if (currentAppLoader != null && currentAppLoader != appLoader) { // concurrency - use remove(key, value) to ensure we don't remove a newly added entry appNameToClassLoaderMap.remove(appName, currentAppLoader); helperContexts.remove(appName, contextMap); contextMap = null; } } // may need to add a new entry if (null == contextMap) { contextMap = new ConcurrentHashMap<String, HelperContext>(); // use putIfAbsent to avoid concurrent entries in the map ConcurrentHashMap existingMap = helperContexts.putIfAbsent(contextMapKey, contextMap); if (existingMap != null) { // if a new entry was just added, use it instead of the one we just created contextMap = existingMap; } else if (appName != null) { // add an appName/appLoader pair to the appNameToClassLoader map appNameToClassLoaderMap.put(appName, appLoader); if (classLoaderName.contains(WLS_CLASSLOADER_NAME)) { // add a loader/context pair to the helperContexts map to handle case where appName // is no longer available, but the loader from a previous lookup is being used helperContexts.put(appLoader, contextMap); // add a notification listener to handle redeploy addWLSNotificationListener(appName); } else if (classLoaderName.contains(JBOSS_CLASSLOADER_NAME)) { // add a notification listener to handle redeploy - the listener will only be added once addJBossNotificationListener(); } } } return contextMap; } /** * Replaces the provided helper context in the map of identifiers to * helper contexts for this application. ctx.getIdentifier() will be * used to obtain the identifier value. If identifier is a key in the * the alias Map, i.e. was previously set as alias, the corresponding * entry will be removed from the alias Map. * * @param ctx the HelperContext to be added to the context Map for * the current application */ public static void putHelperContext(HelperContext ctx) { String identifier = ((SDOHelperContext) ctx).getIdentifier(); if (GLOBAL_HELPER_IDENTIFIER.equals(identifier)) { // The global HelperContext cannot be replaced return; } getContextMap().put(identifier, ctx); // identifier may have been an alias at one point getAliasMap().remove(identifier); } /** * ADVANCED: * Remove the HelperContext for the application associated with a * given key, if it exists in the map. */ private static void resetHelperContext(String key) { // remove entry from helperContext map helperContexts.remove(key); // there may be a loader/context pair to remove ClassLoader appLoader = appNameToClassLoaderMap.get(key); if (appLoader != null) { helperContexts.remove(appLoader); } // remove the appName entry in the appNameToClassLoader map appNameToClassLoaderMap.remove(key); // remove the alias map for this app aliasMap.remove(key); } /** * INTERNAL: * Return the key to be used for Map lookups based in the current thread's * context loader. The returned value will be the application name (if * available) or the context loader. * */ private static Object getMapKey() { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); String classLoaderName = contextClassLoader.getClass().getName(); // get a MapKeyLookupResult instance based on the context loader MapKeyLookupResult hCtxMapKey = getContextMapKey(contextClassLoader, classLoaderName); // at this point we will have a loader and possibly an application name String appName = hCtxMapKey.getApplicationName(); ClassLoader appLoader = hCtxMapKey.getLoader(); // we will use the application name as the map key if set; otherwise we use the loader return appName != null ? appName : appLoader; } /** * INTERNAL: * This method will return the MapKeyLookupResult instance to be used to * store/retrieve the global helper context for a given application. * * OC4J classLoader levels: * 0 - APP.web (servlet/jsp) or APP.wrapper (ejb) * 1 - APP.root (parent for helperContext) * 2 - default.root * 3 - system.root * 4 - oc4j.10.1.3 (remote EJB) or org.eclipse.persistence:11.1.1.0.0 * 5 - api:1.4.0 * 6 - jre.extension:0.0.0 * 7 - jre.bootstrap:1.5.0_07 (with various J2SE versions) * * @return MapKeyLookupResult wrapping the application classloader for OC4J, * the application name for WebLogic and WebSphere, the archive file * name for JBoss - if available; otherwise a MapKeyLookupResult * wrapping Thread.currentThread().getContextClassLoader() */ private static MapKeyLookupResult getContextMapKey(ClassLoader classLoader, String classLoaderName) { // Helper contexts in OC4J server will be keyed on classloader if (classLoaderName.startsWith(OC4J_CLASSLOADER_NAME)) { // Check to see if we are running in a Servlet container or a local EJB container if ((classLoader.getParent() != null) && ((classLoader.toString().indexOf(SDOConstants.CLASSLOADER_WEB_FRAGMENT) != -1) || (classLoader.toString().indexOf(SDOConstants.CLASSLOADER_EJB_FRAGMENT) != -1))) { classLoader = classLoader.getParent(); } return new MapKeyLookupResult(classLoader); } // Helper contexts in WebLogic server will be keyed on application name if available if (classLoaderName.contains(WLS_CLASSLOADER_NAME)) { if(null == applicationAccessWLS) { applicationAccessWLS = new ApplicationAccessWLS(); } Object appName = applicationAccessWLS.getApplicationName(classLoader); if (appName != null) { return new MapKeyLookupResult(appName.toString(), classLoader); } Object executeThread = getExecuteThread(); if (executeThread != null) { try { Method getMethod = PrivilegedAccessHelper.getPublicMethod(executeThread.getClass(), WLS_APPLICATION_NAME_GET_METHOD_NAME, WLS_PARAMETER_TYPES, false); appName = PrivilegedAccessHelper.invokeMethod(getMethod, executeThread); } catch (Exception e) { throw SDOException.errorInvokingWLSMethodReflectively(WLS_APPLICATION_NAME_GET_METHOD_NAME, WLS_EXECUTE_THREAD, e); } } // if ExecuteThread is null or doesn't return the app name, attempt // to use the user-set ApplicationResolver (if set) if (appName == null && appResolver != null) { appName = appResolver.getApplicationName(); } // use the application name if set, otherwise key on the class loader if (appName != null) { return new MapKeyLookupResult(appName.toString(), classLoader); } // couldn't get the application name, so default to the context loader return new MapKeyLookupResult(classLoader); } // Helper contexts in WebSphere server will be keyed on application name if available if (classLoaderName.contains(WAS_CLASSLOADER_NAME)) { return getContextMapKeyForWAS(classLoader); } // Helper contexts in JBoss server will be keyed on archive file name if available if (classLoaderName.contains(JBOSS_CLASSLOADER_NAME)) { return getContextMapKeyForJBoss(classLoader); } // at this point we will default to the context loader return new MapKeyLookupResult(classLoader); } /** * Lazy load the WebLogic MBeanServer instance. * * @return */ private static MBeanServer getWLSMBeanServer() { if (wlsMBeanServer == null) { Context weblogicContext = null; try { weblogicContext = new InitialContext(); try { // The lookup string used depends on the context from which this class is being // accessed, i.e. servlet, EJB, etc. Try java:comp/env lookup wlsMBeanServer = (MBeanServer) weblogicContext.lookup(WLS_ENV_CONTEXT_LOOKUP); } catch (NamingException e) { // Lookup failed - try java:comp try { wlsMBeanServer = (MBeanServer) weblogicContext.lookup(WLS_CONTEXT_LOOKUP); } catch (NamingException ne) { throw SDOException.errorPerformingWLSLookup(WLS_MBEAN_SERVER, ne); } } } catch (NamingException nex) { throw SDOException.errorCreatingWLSInitialContext(nex); } } return wlsMBeanServer; } /** * INTERNAL: * This convenience method will look up a WebLogic execute thread from the runtime * MBean tree. The execute thread contains application information. This code * will use the name of the current thread to lookup the corresponding ExecuteThread. * The ExecuteThread will allow us to obtain the application name (and version, etc). * * @return application name or null if the name cannot be obtained */ private static Object getExecuteThread() { if (getWLSMBeanServer() != null) { // Lazy load the ThreadPoolRuntime instance if (wlsThreadPoolRuntime == null) { ObjectName service = null; ObjectName serverRuntime = null; try { service = new ObjectName(WLS_SERVICE_KEY); } catch (Exception x) { throw SDOException.errorGettingWLSObjectName(WLS_RUNTIME_SERVICE + " [" + WLS_SERVICE_KEY + "]", x); } try { serverRuntime = (ObjectName) wlsMBeanServer.getAttribute(service, WLS_SERVER_RUNTIME); } catch (Exception x) { throw SDOException.errorGettingWLSObjectName(WLS_SERVER_RUNTIME, x); } try { wlsThreadPoolRuntime = (ObjectName) wlsMBeanServer.getAttribute(serverRuntime, WLS_THREADPOOL_RUNTIME); } catch (Exception x) { throw SDOException.errorGettingWLSObjectName(WLS_THREADPOOL_RUNTIME, x); } } try { return wlsMBeanServer.invoke(wlsThreadPoolRuntime, WLS_EXECUTE_THREAD_GET_METHOD_NAME, new Object[] { Thread.currentThread().getName() }, new String[] { String.class.getName() }); } catch (Exception x) { throw SDOException.errorInvokingWLSMethodReflectively(WLS_EXECUTE_THREAD_GET_METHOD_NAME, WLS_THREADPOOL_RUNTIME, x); } } return null; } /** * INTERNAL: * Adds a notification listener to the ApplicationRuntimeMBean instance with "ApplicationName" * attribute equals to 'mapKey.applicationName'. The listener will handle application * re-deployment. * * If any errors occur, we will fail silently, i.e. the listener will not be added. * * This method should only be called when running in an active WLS instance. * * @param applicationName */ private static void addWLSNotificationListener(String applicationName) { if (getWLSMBeanServer() != null) { try { ObjectName service = new ObjectName(WLS_SERVICE_KEY); ObjectName serverRuntime = (ObjectName) wlsMBeanServer.getAttribute(service, WLS_SERVER_RUNTIME); ObjectName[] appRuntimes = (ObjectName[]) wlsMBeanServer.getAttribute(serverRuntime, WLS_APP_RUNTIMES); for (int i=0; i < appRuntimes.length; i++) { try { ObjectName appRuntime = appRuntimes[i]; Object appName = wlsMBeanServer.getAttribute(appRuntime, WLS_APPLICATION_NAME); if (appName != null && appName.toString().equals(applicationName)) { wlsMBeanServer.addNotificationListener(appRuntime, new MyNotificationListener(applicationName, WLS_IDENTIFIER), null, null); break; } } catch (Exception ex) {} } } catch (Exception x) {} } } /** * INTERNAL: * The listener will handle application re-deployment. If any errors occur, we will * fail silently, i.e. the listener will not be added. Since we cannot register for * notifications for a particular application, and hence recieve notifications for * all apps that are redeployed, we only add the listener once - each time we receive * notification we will check the map and remove the corresponding entry if it exists. * * This method should only be called when running in an active JBoss instance. * */ private static void addJBossNotificationListener() { if (jbossMBeanServer == null) { List<MBeanServer> mbeanServers = MBeanServerFactory.findMBeanServer(null); for (MBeanServer server : mbeanServers) { if (server.getDefaultDomain().equals(JBOSS_DEFAULT_DOMAIN_NAME)) { jbossMBeanServer = server; try { jbossMBeanServer.addNotificationListener(new ObjectName(JBOSS_SERVICE_CONTROLLER), new MyNotificationListener(JBOSS_IDENTIFIER), new MyNotificationFilter(), null); } catch (Exception e) {} break; } } } } /** * INTERNAL: * This class will be handed in as a parameter when adding a JBoss notification listener. * The purpose of this class is to restrict notifications to "stop", i.e. we don't * care about "destroy", "start" etc. * */ public static class MyNotificationFilter extends NotificationFilterSupport { MyNotificationFilter() { super.enableType(JBOSS_TYPE_STOP); } } /** * INTERNAL: * Inner class used to catch application re-deployment. Upon notification of this event, * the helper context for the given application will be removed from the helper context * to application map. This method will also remove the corresponding entry in the * application name to application loader map if necessary. * * For WebLogic, 'appName' will be set; we will regester a listener for each application * name we key a context on, and will only receive a notification if a particular app * is redeployed. Upon notification we will remove the context entry for 'appName'. * * For JBoss, 'appName' will not be set; we will only register the listener once, * and each time we're notified of an application redeployment, we will reset the * associated helper context if one exists. * */ private static class MyNotificationListener implements NotificationListener { int server; String appName; /** * This is the default constructor - typically used when running in an * actove JBoss instance. * * @param server */ public MyNotificationListener(int server) { this.server = server; } /** * This constructor will set 'appName' - typically used when running in * an active WebLogic instance. * * @param appName * @param server */ public MyNotificationListener(String appName, int server) { this.server = server; this.appName = appName; } public void handleNotification(Notification notification, Object handback) { switch (server) { case 0: { // handle WebLogic notification if (notification instanceof AttributeChangeNotification) { AttributeChangeNotification acn = (AttributeChangeNotification) notification; if (acn.getAttributeName().equals(WLS_ACTIVE_VERSION_STATE)) { if (acn.getNewValue().equals(0)) { resetHelperContext(appName); } } } break; } case 1: { // handle JBoss notification // assumes 'user data' is an ObjectName containing an 'id' property which indicates the archive file name appName = getApplicationNameFromJBossClassLoader(((ObjectName) notification.getUserData()).getKeyProperty(JBOSS_ID_KEY)); // we receive notifications for all service stops in JBoss; only call reset if necessary if (helperContexts.containsKey(appName)) { resetHelperContext(appName); } break; } } } } /** * ADVANCED * Promote this helper context to be the default or global one. * This will completely replace the existing default context including * all types and properties defined. */ public void makeDefaultContext() { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); MapKeyLookupResult hCtxMapKey = getContextMapKey(contextClassLoader, contextClassLoader.getClass().getName()); String appName = hCtxMapKey.getApplicationName(); ClassLoader appLoader = hCtxMapKey.getLoader(); Object contextMapKey = appName != null ? appName : appLoader; ConcurrentHashMap<String, HelperContext> contexts = helperContexts.get(contextMapKey); if (contexts == null) { contexts = new ConcurrentHashMap<String, HelperContext>(); ConcurrentHashMap<String, HelperContext> existingContexts = helperContexts.putIfAbsent(contextMapKey, contexts); if (existingContexts != null) { contexts = existingContexts; } else if (appName != null) { appNameToClassLoaderMap.put(appName, appLoader); } } this.identifier = GLOBAL_HELPER_IDENTIFIER; contexts.put(GLOBAL_HELPER_IDENTIFIER, this); } /** * Attempt to return the WAS application name based on a given class loader. * For WAS, the application loader's toString will contain "[app:". * * @param loader * @return String representing the application name, or null if the loader's toString * doesn't contain "[app:". */ private static String getApplicationNameFromWASClassLoader(final ClassLoader loader) { String applicationName = null; String loaderString = loader.toString().trim(); while ((loaderString.startsWith(WAS_NEWLINE)) && (loaderString.length() > 0)) { loaderString = loaderString.substring(1).trim(); } String loaderStringLines[] = loaderString.split(WAS_NEWLINE, 2); if (loaderStringLines.length > 0) { String firstLine = loaderStringLines[0].trim(); int appPos = firstLine.indexOf(WAS_APP_COLON); if ((appPos >= 0) && (appPos + WAS_APP_COLON.length() < firstLine.length())) { String appNameSegment = firstLine.substring(appPos + WAS_APP_COLON.length()); int closingBracketPosition = appNameSegment.indexOf(WAS_CLOSE_BRACKET); if (closingBracketPosition > 0) { applicationName = appNameSegment.substring(0, closingBracketPosition); } else { applicationName = appNameSegment; } } } return applicationName; } /** * Attempt to return a MapKeyLookupResult instance wrapping the application name and * application loader based on a given WAS classloader. Here we will traverse up the * loader hierarchy looking for the top-most application loader. * * For WAS, the application loader's toString (and those of it's children) will * contain "[app:". * * @param loader * @return a MapKeyLookupResult instance wrapping application name/loader if * successfully retrieved (i.e. at least one loader exists in the * hierarchy with toString containing "[app:"), or a MapKeyLookupResult * instance wrapping the given loader if not found */ private static MapKeyLookupResult getContextMapKeyForWAS(ClassLoader loader) { ClassLoader applicationLoader = loader; String applicationName = null; // Safety counter to keep from taking too long or looping forever, just in case of some unexpected circumstance. int i = 0; // iterate up the loader hierarchy looking for the top-level application loader while (i < COUNTER_LIMIT) { if (wasClassLoaderHasApplicationName(loader)) { // current loader has application name info - store it applicationLoader = loader; } final ClassLoader parent = loader.getParent(); // once we have hit the top we will stop looking if (parent == null || parent == loader) { // get the application name from the loader we are going to return applicationName = getApplicationNameFromWASClassLoader(applicationLoader); break; } // move up and try again loader = parent; i++; } // if we found the application name, use it as the key if (applicationName != null) { return new MapKeyLookupResult(applicationName, applicationLoader); } // at this point we don't know the application name so the loader will be the key return new MapKeyLookupResult(applicationLoader); } /** * Indicates if a given WAS class loader contains a application name. * * Assumptions: * 1 - The toString of a WAS application loader will contain "[app:". * * @param loader * @return true if the WAS class loader's toString contains "[app:"; false otherwise */ private static boolean wasClassLoaderHasApplicationName(ClassLoader loader) { String loaderString = loader.toString().trim(); while ((loaderString.startsWith(WAS_NEWLINE)) && (loaderString.length() > 0)) { loaderString = loaderString.substring(1).trim(); } String loaderStringLines[] = loaderString.split(WAS_NEWLINE, 2); if (loaderStringLines.length > 0) { String firstLine = loaderStringLines[0].trim(); int appPos = firstLine.indexOf(WAS_APP_COLON); if ((appPos >= 0) && (appPos + WAS_APP_COLON.length() < firstLine.length())) { return true; } } return false; } /** * Attempt to get the application name (archive file name) based on a given JBoss classloader. * * Here is an example toString result of the classloader which loaded the application in JBoss: * BaseClassLoader@1316dd{vfszip:/ade/xidu_j2eev5/oracle/work/utp/resultout/functional/jrf/ * jboss-jrfServer/deploy/jrftestapp.jar/} * or {vfsfile:/net/stott18.ca.oracle.com/scratch/xidu/view_storage/xidu_j2eev5/work/jboss/ * server/default/deploy/testapp.ear/} in exploded deployment * war: BaseClassLoader@bfe0e4{vfszip:/ade/xidu_j2eebug/oracle/work/utp/resultout/functional/ * jrf/jboss-jrfServer/jrfServer/deploy/jrftestapp.ear/jrftestweb.war/} * * Assumptions: * 1 - A given toString may contain both .ear and .jar, or .ear and .war, i.e. * "{vfszip:/.../xxx.ear/.../xxx.war/}". In this case we want to return * xxx.ear as the application name. * 2 - A given toString will end in '/}'. * 3 - A toString containing the application name will have one of "vfszip:" or "vfsfile:". * * @param loaderToString the toString of the loader being processed * @return application name (archive file name) if successfully retrieved (i.e. loader * exists in the hierarchy with toString containing "vfszip:" or "vfsfile:") * or null */ private static String getApplicationNameFromJBossClassLoader(String loaderToString) { String appNameSegment = null; int idx; // handle "vfszip:<archive-file-name>" if ((idx = loaderToString.indexOf(JBOSS_VFSZIP)) != -1) { appNameSegment = loaderToString.substring(idx + JBOSS_VFSZIP_OFFSET, loaderToString.length() - JBOSS_TRIM_COUNT); // handle case where the string contains both .ear and .war (remove the .war portion) if ((appNameSegment.indexOf(JBOSS_WAR) != -1) && (appNameSegment.indexOf(JBOSS_EAR) != -1)) { appNameSegment = appNameSegment.substring(0, appNameSegment.indexOf(JBOSS_EAR) + JBOSS_EAR_OFFSET); } // handle case where the string contains both .ear and .jar (remove the .jar portion) else if ((appNameSegment.indexOf(JBOSS_JAR) != -1) && (appNameSegment.indexOf(JBOSS_EAR) != -1)) { appNameSegment = appNameSegment.substring(0, appNameSegment.indexOf(JBOSS_EAR) + JBOSS_EAR_OFFSET); } } // handle "vfsfile:<archive-file-name>" else if ((idx = loaderToString.indexOf(JBOSS_VFSFILE)) != -1) { appNameSegment = loaderToString.substring(idx + JBOSS_VFSFILE_OFFSET, loaderToString.length() - JBOSS_TRIM_COUNT); } return appNameSegment != null ? new File(appNameSegment).getName() : null; } /** * Attempt to return a MapKeyLookupResult instance wrapping the archive file name and * application loader based on a given JBoss classloader. Here we will traverse up the * loader hierarchy looking for the top-most application loader. * * @param loader * @return a MapKeyLookupResult instance wrapping archive file name/loader if * successfully retrieved (i.e. at least one loader exists in the * hierarchy with toString containing containing "vfszip:" or "vfsfile:"), * or a MapKeyLookupResult instance wrapping the given loader if not found */ private static MapKeyLookupResult getContextMapKeyForJBoss(ClassLoader loader) { ClassLoader applicationLoader = loader; String archiveFileName = null; // safety counter to keep from taking too long or looping forever, just in case of some unexpected circumstance int i = 0; // iterate up the loader hierarchy looking for the top-level application loader while (i < COUNTER_LIMIT) { if (jBossClassLoaderHasArchiveFileInfo(loader)) { // current loader has archive file info - store it applicationLoader = loader; } final ClassLoader parent = loader.getParent(); // once we have hit the top we will stop looking if (parent == null || parent == loader) { // get the archive file name from the loader we are going to return archiveFileName = getApplicationNameFromJBossClassLoader(applicationLoader.toString()); break; } // move up and try again loader = parent; i++; } // if we found the archive file name, use it as the key if (archiveFileName != null) { return new MapKeyLookupResult(archiveFileName, applicationLoader); } // at this point we don't know the archive file name so the loader will be the key return new MapKeyLookupResult(applicationLoader); } /** * Indicates if a given JBoss class loader contains an archive file name; i.e. is an application * loader. * * Here is an example toString result of the classloader which loaded the application in JBoss: * BaseClassLoader@1316dd{vfszip:/ade/xidu_j2eev5/oracle/work/utp/resultout/functional/jrf/ * jboss-jrfServer/deploy/jrftestapp.jar/} * or {vfsfile:/net/stott18.ca.oracle.com/scratch/xidu/view_storage/xidu_j2eev5/work/jboss/ * server/default/deploy/testapp.ear/} in exploded deployment * war: BaseClassLoader@bfe0e4{vfszip:/ade/xidu_j2eebug/oracle/work/utp/resultout/functional/ * jrf/jboss-jrfServer/jrfServer/deploy/jrftestapp.ear/jrftestweb.war/} * * Assumptions: * 1 - The toString of an application loader will have one of "vfszip:" or "vfsfile:". * * @param loader * @return true if the given JBoss loader has a toString containing "vfszip:" or "vfsfile:"); * false otherwise */ private static boolean jBossClassLoaderHasArchiveFileInfo(ClassLoader loader) { // look for "vfszip:<archive-file-name>" or "vfsfile:<archive-file-name>" return (loader.toString().indexOf(JBOSS_VFSZIP) != -1 || loader.toString().indexOf(JBOSS_VFSFILE) != -1); } /** * Return the unique label for this HelperContext. * * @return String representing the unique label for this HelperContext */ public String getIdentifier() { return this.identifier; } /** * Return true if a HelperContext corresponding to this identifier or alias * already exists, else false. If identifer is an alias, the corresponding * value in the alias Map will be used as the identifier for the lookup. * * @param identifier the alias or identifier used to lookup a helper context * @return true if an entry exists in the helper context map for identifier (or * the associated identifier value if identifier is an alias), false otherwise. */ public static boolean hasHelperContext(String identifier) { String id = identifier; Object appKey = getMapKey(); // if identifier is an alias, we need the actual id value ConcurrentMap<String, String> aliasEntries = getAliasMap(appKey); if (aliasEntries.containsKey(identifier)) { id = aliasEntries.get(identifier); } // now check the Map of user set identifiers to helperContexts WeakHashMap<String, WeakReference<HelperContext>> userSetMap = userSetHelperContexts.get(appKey); if (userSetMap != null && userSetMap.containsKey(id)) { return true; } // lastly, check the Map of identifiers to helperContexts ConcurrentHashMap<String, HelperContext> contextMap = helperContexts.get(appKey); return (contextMap != null && contextMap.containsKey(id)); } /** * Add an alias to identifier pair to the alias Map for the current * application. * * @param identifier assumed to be a key in the helper context Map * @param alias the alias to be associated with identifier */ public static void addAlias(String identifier, String alias) { getAliasMap().put(alias, identifier); } /** * INTERNAL: * Returns the map of alias' to identifiers for the current application. * * @return Map of alias' to identifiers for the current application */ private static ConcurrentMap<String, String> getAliasMap() { return getAliasMap(getMapKey()); } /** * INTERNAL: * Returns the map of alias' to identifiers for the current application. * * @param mapKey application name or classloader used to lookup the alias map * @return Map of alias' to identifiers for the current application */ private static ConcurrentMap<String, String> getAliasMap(Object mapKey) { ConcurrentHashMap<String, String> alias = aliasMap.get(mapKey); // may need to add a new entry if (null == alias) { alias = new ConcurrentHashMap<String, String>(); // use putIfAbsent to avoid concurrent entries in the map ConcurrentHashMap existingMap = aliasMap.putIfAbsent(mapKey, alias); if (existingMap != null) { // if a new entry was just added, use it instead of the one we just created alias = existingMap; } } return alias; } /** * Lazily initialize the Map of user properties. */ private Map<String, Object> getProperties() { if (properties == null) { properties = new HashMap<String, Object>(); } return properties; } /** * Add a name/value pair to the properties Map. If name is * null, nothing will be done. If value is null, the entry * in the Map will be removed (if an entry exists for name). * * @param name the name of the property * @param value the value of the property */ public void setProperty(String name, Object value) { // if the key is null there is nothing to do if (name == null) { return; } // if value is null, remove the entry if (value == null) { getProperties().remove(name); } else { // put the name/value pair in the map getProperties().put(name, value); } } /** * Return the value stored in the properties Map for a given * name, or null if an entry for name does not exist. * * @param name the name of the property to be returned * @return the value associated with name, or null */ public Object getProperty(String name) { return getProperties().get(name); } private static class ApplicationAccessWLS { private static final String APPLICATION_ACCESS_CLASS_NAME = "weblogic.application.ApplicationAccess"; private static final String GET_APPLICATION_ACCESS_METHOD_NAME = "getApplicationAccess"; private static final String GET_APPLICATION_NAME_METHOD_NAME = "getApplicationName"; private Object applicationAccessInstance; private Method getApplicationNameMethod; public ApplicationAccessWLS() { try { Class applicationAccessClass = PrivilegedAccessHelper.getClassForName(APPLICATION_ACCESS_CLASS_NAME); Method getApplicationAccessMethod = PrivilegedAccessHelper.getDeclaredMethod(applicationAccessClass, GET_APPLICATION_ACCESS_METHOD_NAME, new Class[] {}); applicationAccessInstance = PrivilegedAccessHelper.invokeMethod(getApplicationAccessMethod, applicationAccessClass); Class [] methodParameterTypes = new Class[] {ClassLoader.class}; getApplicationNameMethod = PrivilegedAccessHelper.getMethod(applicationAccessClass, GET_APPLICATION_NAME_METHOD_NAME, methodParameterTypes, true); } catch(Exception e) { } } public String getApplicationName(ClassLoader classLoader) { if(null == getApplicationNameMethod) { return null; } try { Object[] parameters = new Object[] {classLoader}; return (String) PrivilegedAccessHelper.invokeMethod(getApplicationNameMethod, applicationAccessInstance, parameters); } catch(Exception e) { return null; } } } }
package com.voxelwind.server.network.mcpe.packets; import com.voxelwind.api.game.item.ItemStack; import com.voxelwind.nbt.util.Varints; import com.voxelwind.server.network.mcpe.McpeUtil; import com.voxelwind.server.network.NetworkPackage; import io.netty.buffer.ByteBuf; import lombok.Data; @Data public class McpeContainerSetContents implements NetworkPackage { private byte windowId; private ItemStack[] stacks; private int[] hotbarData = new int[0]; @Override public void decode(ByteBuf buffer) { windowId = buffer.readByte(); int stacksToRead = Varints.decodeUnsigned(buffer); stacks = new ItemStack[stacksToRead]; for (int i = 0; i < stacksToRead; i++) { stacks[i] = McpeUtil.readItemStack(buffer); } if (windowId == 0) { int hotbarEntriesToRead = Varints.decodeUnsigned(buffer); hotbarData = new int[hotbarEntriesToRead]; for (int i = 0; i < hotbarEntriesToRead; i++) { hotbarData[i] = Varints.decodeSigned(buffer); } } } @Override public void encode(ByteBuf buffer) { buffer.writeByte(windowId); Varints.encodeUnsigned(buffer, stacks.length); for (ItemStack stack : stacks) { McpeUtil.writeItemStack(buffer, stack); } if (windowId == 0) { Varints.encodeUnsigned(buffer, hotbarData.length); for (int i : hotbarData) { Varints.encodeSigned(buffer, i); } } } }
package eu.theunitry.fabula.levels; import eu.theunitry.fabula.UNGameEngine.graphics.UNGameScreen; import eu.theunitry.fabula.UNGameEngine.graphics.UNColor; import eu.theunitry.fabula.UNGameEngine.graphics.UNLevel; import eu.theunitry.fabula.UNGameEngine.graphics.UNGraphicsObject; import eu.theunitry.fabula.UNGameEngine.launcher.UNLauncher; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Objects; import java.util.Random; /** * Level 1 * Maarten Bode */ public class Level1 extends UNLevel { private Timer timer; private JButton button; private boolean winning; private int need, touch; private String lastHelp; public UNGraphicsObject blobby; /** * Level 1 * @param gameScreen * @param hudEnabled */ public Level1(UNGameScreen gameScreen, boolean hudEnabled) { super(gameScreen, hudEnabled); gameScreen.stopAudio(); this.need = 3 + new Random().nextInt(3); // Load questions & help texts this.setQuestion("Oh nee! Blobby probeert de wereld te vernietigen. Stop hem!"); this.addHelp("Jammer! Je moet " + need + " appels in de mand stoppen"); this.addHelp("Helaas! Er moeten " + need + " appels in de mand zitten"); this.setHelp("Om het wapen af te vuren moet je het goede draadje doorknippen"); // Set resources/audio this.setBackgroundImage(gameScreen.unResourceLoader.backgrounds.get("the-end")); this.blobby = new UNGraphicsObject(gameScreen.getWindow().getFrame(), 320, -50, gameScreen.getSprites().get("2:1:1"), false, 38 * 3, 50 * 3); this.addObject(blobby); gameScreen.getMusic().get("the-end").play(true); gameScreen.getMusic().get("the-end").setVolume(0.1); // Set variables this.winning = false; this.lastHelp = getHelp(); this.button = new JButton("Vuren!"); // Standard styling this.setLayout(null); // Set button styling this.button.setBounds(618, 64, 150, 50); this.button.setBackground(new Color(51, 51, 51)); this.button.setFont(new Font("Minecraftia", Font.PLAIN, 15)); this.button.setForeground(Color.white); this.button.setOpaque(true); // Makes it look good on Mac this.button.setFocusPainted(false); this.button.setBorderPainted(false); // Speaks for itself button.addActionListener(e -> { if (button.getText().equals("Doorgaan")) { levelDone(5); } if (isHelperDoneTalking()) { if (winning) { getHelper().setState(3); setHelp("Goed gedaan, dat wordt smikkelen en smullen!"); button.setText("Door"); } else { addMistake(); if (getMistakes() < 3) { getHelper().setState(4); while(lastHelp.equals(getHelp())) { setHelp(getHelpList().get(new Random().nextInt(getHelpList().size()))); } lastHelp = getHelp(); } else { getHelper().setState(4); if (touch < need) { setHelp("Jammer, er moest" + ((need - touch == 1) ? "" : "en") + " nog " + (need - touch) + " appel" + ((need - touch == 1) ? "" : "s") + " bij. Want " + touch + " plus " + (need - touch) + " is " + need ); } else { setHelp("Jammer, er moest" + ((touch - need == 1) ? "" : "en") + " " + (touch - need) + " appel" + ((touch - need == 1) ? "" : "s") + " af. Want " + touch + " min " + (touch - need) + " is " + need ); } button.setText("Door"); } } } }); this.getPanel().add(button); timer = new Timer(100, new ActionListener() { int i = blobby.getY(); @Override public void actionPerformed(ActionEvent e) { if(i <= 100) blobby.setY(i = i + 5); if(i >= 100) { shakeBlobby(); } touch = 0; winning = (touch == need); } }); timer.start(); } public void shakeBlobby() { if(Math.random() < 0.5) { blobby.setX(blobby.getX() + 1); } if(Math.random() < 0.5) { blobby.setY(blobby.getY() + 1); } if(Math.random() < 0.5) { blobby.setX(blobby.getX() - 1); } if(Math.random() < 0.5) { blobby.setY(blobby.getY() - 1); } } }
package com.wc1.felisBotus; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Set; import org.jibble.pircbot.IrcException; import org.jibble.pircbot.PircBot; import org.jibble.pircbot.User; import com.wc1.felisBotus.irc.IRCChannel; import com.wc1.felisBotus.irc.IRCServer; /** * Bot for the program. Each instance can only connect to one server, so several instances will need to be created to connect to several servers. * Stores the username for the owner of this bot, server this bot will connect to, password to identify this bot (if it is being saved), login address and bot name. * Bot will always listen to its owner or Ops in the channel. (yet to be implemented) * @author Reece * */ public class FelisBotus extends PircBot { private boolean voiceUsers = true; private String owner; private IRCServer server; // this thing will contain all info on the server, // channels and ops in said channels. private String loginPass; /**Version of the bot*/ public static final String version = "C3 Java IRC Bot - V0.5.W"; /**String that this bot will recognize as a command to it*/ public static final String commandStart = "\\"; /** * Constructor for when bot without server information (can be added later through other methods) Used mainly for first time creation * @param botName Name for this bot * @param owner Username for the owner of this bot. Bot will always recognize commands from this user * @param login Login address for the bot * @param loginPass Password to identify this bot (can be null) */ public FelisBotus(String botName, String owner, String login, String loginPass) { this.setName(botName); this.owner = owner; this.setLogin(login); this.loginPass = loginPass; this.setVersion(version); } /** * Constructer to create this bot, including server information. Used mainly for loading from the XML file. * @param botName Name for this bot * @param owner Username for the owner of this bot. Bot will always recognize commands from this user * @param login Login address for the bot * @param loginPass Password to identify this bot (can be null) * @param currServer Server information for this bot */ public FelisBotus(String botName, String owner, String login, String loginPass, IRCServer currServer) { this.setName(botName); this.owner = owner; this.setLogin(login); this.loginPass = loginPass; this.server = currServer; this.setVersion(version); } /** * Call to connect bots to default server assigned to them. Assumes call is from console and will ask console for missing information. */ public void connectConsole(){ this.setAutoNickChange(true); if (server == null){ String newServer = System.console().readLine("Please enter a server address.\n"); server = new IRCServer(newServer); } try { this.connect(server.getServerAddress());//TODO add support for saving port numbers and server passwords while (!isConnected()){//wait till successfully connected Thread.sleep(5000); } //verify login String pass; if (loginPass != null){ pass = loginPass; } else{ pass = new String(System.console().readPassword("Please enter a password to verify the bot on %s\n", this.server.getServerAddress())); } if(!this.getName().equals(this.getNick())){//bot has a secondary name. GHOST primary nickname and then take it! sendMessage("NickServ", "GHOST " + pass.toString()); changeNick(this.getName()); } identify(pass); Thread.sleep(1000); if (server.getChannels().size() == 0){ //if no default channels then connect to a new ones String newChannel = System.console().readLine("Please enter a channel name to connect to.\n"); while (!newChannel.startsWith(" newChannel = System.console().readLine("Channel name requires a '#' symbol at the start.\n"); } server.addChannel(new IRCChannel(newChannel)); this.joinChannel(newChannel); }else{//Connect to all default channels for (IRCChannel channel:server.getChannels()){ this.joinChannel(channel.getName()); //TODO support for channels with keys } } } catch (IOException e){//TODO how to manage exceptions? return to console/ } catch (IrcException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Method to make bot connect to supplied server. * @param newServer New server to connect to */ public void connectCommand(IRCServer newServer){ //TODO make this and make exception to be thrown if already connected to a server. //do i make this recieve a server or use the one saved by the bot? It does need a server otherwise it won't be controllable. } /** * Returns the server associated with this instance of the bot * @return server for this bot */ public IRCServer getIRCServer() { return server; } /** * Get the login password stored by this bot * @return */ public String getLoginPass() { return loginPass; } /** * Get the username for the owner of this pot * @return */ public String getOwner() { return owner; } public boolean isVoiceUsers() { return voiceUsers; } @Override public void log(String line) { System.out.println(line + "\n"); } public void onDisconnect() { while (!isConnected()) { try { reconnect(); } catch (Exception e) { // Couldnt reconnect. // Pause for a short while before retrying? } } } @Override public void onJoin(String channel, String sender, String login, String hostname) { if (sender != this.getNick()) { sendNotice(sender, "Hello " + sender + " Welcome to the Qubed C3 IRC Channel- (I am a Bot)"); } if (isVoiceUsers()) { this.voice(channel, sender); } } // public void onKick(String channel, String kickerNick, String login, // String hostname, String recipientNick, String reason) { // if (recipientNick.equalsIgnoreCase(getNick())) { // joinChannel(channel); // sendMessage(channel, "Guess who is baaaaack!"); @Override public void onMessage(String channel, String sender, String login, String hostname, String message) { if (message.startsWith(commandStart)){ boolean isOp = server.getChannel(channel).checkOP(sender); String[] rawMessage = message.split(" "); String lowercaseCommand = message.toLowerCase(Locale.ROOT).split(" ",3)[0]; switch(lowercaseCommand.substring(commandStart.length())){ //removes the command section of the string case("addcommand"): if (isOp && rawMessage.length == 3){ String result = Main.putCommand(rawMessage[1].toLowerCase(Locale.ROOT), rawMessage[2]); if (result !=null){ sendNotice(sender, "Command successfully overwritten :]. Previous response was '" +result+"'"); } else{ sendNotice(sender, "Command successfully added :]"); } try { Main.save(); } catch (IOException e) { sendNotice(sender, "Failed to save command. Command will be lost on bot restart :["); System.out.printf("\nFailed to save bot!\n"); e.printStackTrace(); } } else if (rawMessage.length < 3){ sendNotice(sender, "Syntax Error. Correct usage is " + commandStart +"addcommand <newCommand> <Response>"); } else{ sendNotice(sender, "You must be an OP to use this command"); } break; default: String response = Main.getResponse(lowercaseCommand.substring(commandStart.length())); if (response != null){ sendMessage(channel, response); } else{ sendNotice(sender, "Invalid command, please ensure it is spelled correctly"); } } //if (message.equalsIgnoreCase("!time")) { // String time = new java.util.Date().toString(); // sendMessage(channel, sender + ": The time is now " + time); // if (message.equalsIgnoreCase("!borg")) { // sendMessage( // channel, // "We are the Borg. Lower your shields and surrender your ships. We will add your biological and technological distinctiveness to our own. Your culture will adapt to service us. Resistance is futile."); // if (message.equalsIgnoreCase("!botleave")) { // sendMessage(channel, "I am un-wanted and will now leave."); // quitServer(); } } public void onPrivateMessage(String sender, String login, String hostname, String message) { } @Override protected void onOp(String channel, String sourceNick, String sourceLogin, String sourceHostname, String recipient) { IRCChannel currChannel = server.getChannel(channel); Set<String> opList = currChannel.getOpList(); if (recipient.equals(this.getNick())){ server.getChannel(channel).setBotIsOp(true); List<String> addedToList = new ArrayList<String>(); User[] users = getUsers(channel); for (int i = 0; i < users.length; i++) { User user = users[i]; String nick = user.getNick(); if (opList.contains(nick)){ if(!user.isOp()){//user is on OP list but is not op'd, so op them op(channel, nick); } } else{ if(user.isOp() && nick != this.getNick()){//user is op'd but is not on bots op list, so add them to the list currChannel.addOp(nick); addedToList.add(nick); } } } StringBuilder output = new StringBuilder("Bot initialized."); if (addedToList.size() > 0){ output.append(" Added " + String.join(", ", addedToList.toArray(new String[addedToList.size()])) + " to saved list of Ops"); } try { if(Main.save())sendMessage(channel, output.toString()); } catch (IOException e) { sendMessage(channel, "Error occured while saving bot config. :["); e.printStackTrace(); } } else{ if(!opList.contains(recipient)){ currChannel.addOp(recipient); try { if(Main.save())sendMessage(channel, recipient + " has been added to the saved Op list"); } catch (IOException e) { sendMessage(channel, "Error occured while saving bot config. :["); e.printStackTrace(); } } } } @Override protected void onDeop(String channel, String sourceNick, String sourceLogin, String sourceHostname, String recipient) { if (recipient.equals(this.getNick())){ server.getChannel(channel).setBotIsOp(false); } else{ IRCChannel currChannel = server.getChannel(channel); Set<String> opList = currChannel.getOpList(); if(opList.contains(recipient)){ currChannel.removeOp(recipient); try { if(Main.save())sendMessage(channel, recipient + " has been removed from the saved Op list"); } catch (IOException e) { sendMessage(channel, "Error occured while saving bot config. :["); e.printStackTrace(); } } } } public void onUserList(String channel, User[] users) { } public void setVoiceUsers(boolean voiceUsers) { this.voiceUsers = voiceUsers; } }
package fractals; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Polygon; import java.awt.Shape; import java.awt.Stroke; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Point2D; import javax.swing.JComponent; import javax.swing.JLayeredPane; /** A Quadrilateral gui widget that sits without a layout manager and can be dragged around by the 4 corners. */ final class DraggableQuadrilateral extends JComponent implements MouseListener, MouseMotionListener { private static final long serialVersionUID = 4705086044490724806L; /// How close must the mouse pointer be to count as selecting. private static final double SELECTING_FUZZ = 10.0; /// Stroke used to render the quad. private static final Stroke NORMAL_STROKE = new BasicStroke(2.0f); /// Stroke used to render an outline shape used for selection. private static final Stroke SELECTING_STROKE = new BasicStroke((float)SELECTING_FUZZ); private Point2D cornerA = new Point2D.Double(100, 100); private Point2D cornerB = new Point2D.Double(200, 100); private Point2D cornerC = new Point2D.Double(200, 200); private Point2D cornerD = new Point2D.Double(100, 200); private boolean isBeingHoveredOver = false; private Point dragStart = null; /** If the user is dragging a corner of the quad then this value aliases whichever corner is being dragged (only for the duration of the drag). */ private Point2D dragCorner = null; DraggableQuadrilateral() { setOpaque(false); setRequestFocusEnabled(true); addMouseListener(this); addMouseMotionListener(this); } @Override public void paintComponent(Graphics g) { paintComponent((Graphics2D)g); } public void paintComponent(Graphics2D g) { Utilities.setGraphicsToHighQuality(g); g.setColor(isBeingHoveredOver ? Color.RED : Color.BLACK); g.setStroke(NORMAL_STROKE); g.draw(getShape()); } private Shape getShape() { Polygon result = new Polygon(); result.addPoint((int)Math.round(cornerA.getX()), (int)Math.round(cornerA.getY())); result.addPoint((int)Math.round(cornerB.getX()), (int)Math.round(cornerB.getY())); result.addPoint((int)Math.round(cornerC.getX()), (int)Math.round(cornerC.getY())); result.addPoint((int)Math.round(cornerD.getX()), (int)Math.round(cornerD.getY())); return result; } Shape getSelectingOutlineShape() { return SELECTING_STROKE.createStrokedShape(getShape()); } private static Point2D displacePoint(Point2D p, double dx, double dy) { return new Point2D.Double(p.getX() + dx, p.getY() + dy); } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { if (getSelectingOutlineShape().contains(e.getPoint())) { dragStart = e.getPoint(); Point2D closestCorner = cornerA; if (e.getPoint().distance(cornerB) < e.getPoint().distance(closestCorner)) { closestCorner = cornerB; } if (e.getPoint().distance(cornerC) < e.getPoint().distance(closestCorner)) { closestCorner = cornerC; } if (e.getPoint().distance(cornerD) < e.getPoint().distance(closestCorner)) { closestCorner = cornerD; } if (e.getPoint().distance(closestCorner) <= SELECTING_FUZZ) { dragCorner = closestCorner; } } } public void mouseReleased(MouseEvent e) { dragStart = null; dragCorner = null; } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseDragged(MouseEvent e) { if (dragStart != null) { if (dragCorner != null) { dragCorner.setLocation(e.getPoint()); } else { Point p = e.getPoint(); double dx = p.x - dragStart.x; double dy = p.y - dragStart.y; dragStart = p; cornerA = displacePoint(cornerA, dx, dy); cornerB = displacePoint(cornerB, dx, dy); cornerC = displacePoint(cornerC, dx, dy); cornerD = displacePoint(cornerD, dx, dy); } repaint(); } } public void mouseMoved(MouseEvent e) { boolean nowBeingHoveredOver = getSelectingOutlineShape().contains(e.getPoint()); if (nowBeingHoveredOver != isBeingHoveredOver) { isBeingHoveredOver = nowBeingHoveredOver; repaint(); } if (!isBeingHoveredOver) { /* This appears to be a bit of a hack. We move ourselves to the back of the stack and so when the mouse moves by the next pixel a different object will get a chance to do hit detection. So with N objects on the canvas, each one only gets a chance to check for mouse floating every N pixels of mouse movement. */ JLayeredPane canvas = (JLayeredPane)getParent(); Component c = canvas.getComponentAt(e.getPoint()); canvas.moveToBack(this); } } }
package gameboi; import java.nio.file.Path; import java.nio.file.Files; import java.io.IOException; /** * Represents the memory of the gameboy * <p> * Provides an interface for accessing the memory necessary * for the gameboy cpu and gpu operations * <p> * Internal Memory structure of the gameboy is as follows * <ul> * <li> 0000-3FFF - 16Kb ROM Bank 00</li> * <li> 4000-7FFF - 16Kb ROM variable bank</li> * <li> 8000-9FFF - 8Kb Graphics RAM</li> * <li> A000-BFFF - 8Kb Switchable External RAM Bank</li> * <li> C000-DFFF - 8Kb Working RAM</li> * <li> E000-FDFF - Working RAM shadow</li> * <li> FE00-FE9F - Graphics + Sprite Info (OAM)</li> * <li> FEA0-FEFF - Unusable</li> * <li> FF00-FF7F - I/O Info</li> * <li> FF80-FFFE - Zero-Page RAM</li> * <li> FFFF - Interrupt Enable Register</li> * </ul> * * @author tomis007 */ public class GBMem { private int memory[]; private int cartridge[]; private MemBanks memBank; /** * Constructor for GBMem object * <p> * Initializes the GBMem object and loads the 'cartridge' * into memory * * @param path (required) Path object specifying the game rom to load */ public GBMem(Path path) { memory = new int[0x10000]; try { byte[] rom = Files.readAllBytes(path); cartridge = new int[rom.length]; for (int i = 0; i < rom.length; ++i) { cartridge[i] = Byte.toUnsignedInt(rom[i]); } for (int i = 0; i < 0x8000 && i < rom.length; ++i) { memory[i] = cartridge[i]; } memBank = new MemBanks(cartridge); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); System.exit(1); } //initialize values in memory memory[0xff05] = 0x0; memory[0xff06] = 0x0; memory[0xff07] = 0x0; memory[0xff10] = 0x80; memory[0xff11] = 0xbf; memory[0xff12] = 0xf3; memory[0xff14] = 0xbf; memory[0xff16] = 0x3f; memory[0xff17] = 0x0; memory[0xff19] = 0xbf; memory[0xff1a] = 0x7f; memory[0xff1b] = 0xff; memory[0xff1c] = 0x9f; memory[0xff1e] = 0xbf; memory[0xff20] = 0xff; memory[0xff21] = 0x0; memory[0xff22] = 0x0; memory[0xff23] = 0xbf; memory[0xff24] = 0x77; memory[0xff25] = 0xf3; memory[0xff26] = 0xf1; memory[0xff40] = 0x91; memory[0xff42] = 0x0; memory[0xff43] = 0x0; memory[0xff45] = 0x0; memory[0xff47] = 0xfc; memory[0xff48] = 0xff; memory[0xff49] = 0xff; memory[0xff4a] = 0x0; memory[0xff4b] = 0x0; memory[0xffff] = 0x0; } /** * Read a 'byte' from memory. * * <p> Returns an int with the value of the byte stored in memory * at address. * * @param address (required) address to read data in memory from * @return an int that is the value of the data stored in memory * at address * @see GBMem */ public int readByte(int address) { //for debugging if (address == 0xff80) { System.out.println("reading 0x" + memory[0xff80] + " from 0xff80"); } if (((address >= 0x4000) && (address <= 0x7fff)) || ((address >= 0xa000) && (address <= 0xbfff))) { //rom or ram banking return memBank.readByte(address); } else { return memory[address]; } } /** * Write a 'byte' to the gameboy memory. * * <p> Writes the input int data to gameboy memory, only storing the low * 8 bits. * * @param address (required) int specifying valid address to write at * @param data (required) int 'byte' data to write * @see GBMem */ public void writeByte(int address, int data) { //only store a byte in memory data = data & 0xff; //for debugging if (address == 0xff80) { System.out.println("writing 0x" + data + " to 0xff80"); } if (address < 0) { System.err.println("ERROR: writing to negative address"); System.exit(1); } else if (address < 0x8000) { // can't write to ROM, but update banks memBank.updateBanking(address, data); } else if ((address >= 0xfea0) && (address <= 0xfeff)) { // can't access this region } else if ((address >= 0xc000) && (address <= 0xde00)) { memory[address] = data; // ECHO memory[address + 0x2000] = data; } else if ((address >= 0xc000) && (address <= 0xfe00)) { memory[address] = data; // ECHO memory[address - 0x2000] = data; } else if (address == 0xff04) { //write to divide counter == reset memory[0xff04] = 0; } else { if (memBank.isRamEnabled()) { memBank.writeByte(address, data); } else { memory[address] = data; } } } /** * Returns current scanline * * @return memory[0xff44] */ public int getScanLine() { return memory[0xff44]; } /** * sets the scanline * @param num new scanline value */ public void setScanLine(int num) { memory[0xff44] = num; } /** * increments the divide counter at 0xff04 * */ public void incrementDivider() { memory[0xff04] = (memory[0xff04] + 1) & 0xff; } }
package gnu.math; /** Implementation of exact rational numbers as fractions of IntNums. * @author Per Bothner */ public class IntFraction extends RatNum { IntNum num; IntNum den; IntFraction (IntNum num, IntNum den) { this.num = num; this.den = den; } public final IntNum numerator () { return num; } public final IntNum denominator () { return den; } public final boolean isNegative () { return num.isNegative (); } public final int sign () { return num.sign (); } public final int compare (Object obj) { if (obj instanceof RatNum) return RatNum.compare (this, (RatNum) obj); if (! (obj instanceof RealNum)) throw new IllegalArgumentException (); return ((RealNum)obj).compareReversed(this); } public int compareReversed (Numeric x) { if (!(x instanceof RatNum)) throw new IllegalArgumentException (); return RatNum.compare ((RatNum) x, this); } public Numeric add (Object y, int k) { if (y instanceof RatNum) return RatNum.add (this, (RatNum) y, k); if (! (y instanceof Numeric)) throw new IllegalArgumentException (); return ((Numeric)y).addReversed(this, k); } public Numeric addReversed (Numeric x, int k) { if (! (x instanceof RatNum)) throw new IllegalArgumentException (); return RatNum.add ((RatNum)x, this, k); } public Numeric mul (Object y) { if (y instanceof RatNum) return RatNum.times (this, (RatNum)y); if (! (y instanceof Numeric)) throw new IllegalArgumentException (); return ((Numeric)y).mulReversed(this); } public Numeric mulReversed (Numeric x) { if (! (x instanceof RatNum)) throw new IllegalArgumentException (); return RatNum.times ((RatNum) x, this); } public Numeric div (Object y) { if (y instanceof RatNum) return RatNum.divide (this, (RatNum)y); if (! (y instanceof Numeric)) throw new IllegalArgumentException (); return ((Numeric)y).divReversed(this); } public Numeric divReversed (Numeric x) { if (! (x instanceof RatNum)) throw new IllegalArgumentException (); return RatNum.divide ((RatNum)x, this); } public static IntFraction neg (IntFraction x) { // If x is normalized, we do not need to call RatNum.make to normalize. return new IntFraction (IntNum.neg (x.numerator()), x.denominator ()); } public Numeric neg () { return IntFraction.neg (this); } public long longValue () { return toExactInt (ROUND).longValue (); } public double doubleValue () { boolean neg = num.isNegative (); IntNum n = num; if (neg) n = IntNum.neg (n); int num_len = n.intLength (); int den_len = den.intLength (); int exp = 0; if (num_len < den_len + 54) { exp = den_len + 54 - num_len; n = IntNum.shift (n, exp); exp = - exp; } // Divide n (which is shifted num) by den, using truncating division, // and return quot and remainder. IntNum quot = new IntNum (); IntNum remainder = new IntNum (); IntNum.divide (n, den, quot, remainder, TRUNCATE); quot = quot.canonicalize (); remainder = remainder.canonicalize (); return quot.roundToDouble (exp, neg, !remainder.isZero ()); } public String toString (int radix) { return num.toString (radix) + '/' + den.toString (); } }
package com.tripadvisor.seekbar; import android.content.Context; import android.text.format.DateFormat; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import com.tripadvisor.seekbar.util.Utils; import org.jetbrains.annotations.Nullable; import org.joda.time.DateTime; import org.joda.time.DateTimeFieldType; import org.joda.time.Interval; import org.joda.time.Minutes; import java.util.Locale; import static com.tripadvisor.seekbar.CircularClockSeekBar.ClockRangeStatus.DIFFERENT_DAY_OF_WEEK; import static com.tripadvisor.seekbar.CircularClockSeekBar.ClockRangeStatus.INVALID_RANGE; import static com.tripadvisor.seekbar.CircularClockSeekBar.ClockRangeStatus.VALID_RANGE; import static com.tripadvisor.seekbar.util.Utils.FontType.BOLD; import static com.tripadvisor.seekbar.util.Utils.FontType.REGULAR; import static com.tripadvisor.seekbar.util.Utils.SIMPLE_DATE_FORMAT_AM_PM; import static com.tripadvisor.seekbar.util.Utils.SIMPLE_DATE_FORMAT_HOURS; import static com.tripadvisor.seekbar.util.Utils.SIMPLE_DATE_FORMAT_MERIDIAN; public class ClockView extends LinearLayout { public static final float LETTER_SPACING = -3.0f; private final LetterSpacingTextView mTimeText; private final LetterSpacingTextView mTimeMeridianText; private final RobotoTextView mTimeWeekDayText; private final CircularClockSeekBar mCircularClockSeekBar; private Interval mValidTimeInterval; private DateTime mOriginalTime; private final boolean mIs24HourFormat; private DateTime mNewCurrentTime; private int mCurrentValidProgressDelta; private DateTime mCurrentValidTime; private ClockTimeUpdateListener mClockTimeUpdateListener; public ClockView(Context context, AttributeSet attrs) { super(context, attrs); mClockTimeUpdateListener = new ClockTimeUpdateListener() { @Override public void onClockTimeUpdate(ClockView clockView, DateTime currentTime) { } }; mIs24HourFormat = DateFormat.is24HourFormat(context); final View view = LayoutInflater.from(context).inflate(R.layout.clock_view, this); mTimeText = (LetterSpacingTextView) view.findViewById(R.id.time_text_view); mTimeMeridianText = (LetterSpacingTextView) view.findViewById(R.id.time_meredian_text_view); mTimeWeekDayText = (RobotoTextView) view.findViewById(R.id.time_week_day_text); if (!isInEditMode()) { mTimeText.setTypeface(Utils.getRobotoTypeface(context, BOLD)); mTimeText.setLetterSpacing(LETTER_SPACING); mTimeMeridianText.setTypeface(Utils.getRobotoTypeface(context, REGULAR)); mTimeMeridianText.setLetterSpacing(LETTER_SPACING); } mCircularClockSeekBar = (CircularClockSeekBar) view.findViewById(R.id.clock_seek_bar); mCircularClockSeekBar.setSeekBarChangeListener(new CircularClockSeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(CircularClockSeekBar seekBar, int progress, boolean fromUser) { updateProgressWithDelta(seekBar.getProgressDelta()); } @Override public void onStartTrackingTouch(CircularClockSeekBar seekBar) { } @Override public void onStopTrackingTouch(CircularClockSeekBar seekBar) { // snap to correct position if (mValidTimeInterval.contains(mNewCurrentTime)) { // snap to nearest hour. int progressDelta = (int) (mCircularClockSeekBar.getAngle() % 30); if (progressDelta != 0) { // snap either to previous/next hour mCircularClockSeekBar.roundToNearestDegree(30); } else { // we are trigering onClockTimeUpdate because the user was perfect and moved the // clock by exact multiple of 30 degrees so there is no animation and the time is still // within valid time interval mClockTimeUpdateListener.onClockTimeUpdate(ClockView.this, mNewCurrentTime); } } else { // slide-animate back or forward mCircularClockSeekBar.animateToDelta(mCircularClockSeekBar.getProgressDelta(), mCurrentValidProgressDelta); setClockText(mCurrentValidTime); } } @Override public void onAnimationComplete(CircularClockSeekBar seekBar) { if (mValidTimeInterval != null && mNewCurrentTime != null && mValidTimeInterval.contains(mNewCurrentTime)) { mClockTimeUpdateListener.onClockTimeUpdate(ClockView.this, mNewCurrentTime); } } }); } public interface ClockTimeUpdateListener{ public void onClockTimeUpdate(ClockView clockView, DateTime currentTime); } public void setNewCurrentTime(DateTime newCurrentTime){ if (mValidTimeInterval != null && newCurrentTime != null && mNewCurrentTime != null && mValidTimeInterval.contains(newCurrentTime)) { int diffInMinutes = Minutes.minutesBetween(mNewCurrentTime, newCurrentTime).getMinutes(); mCircularClockSeekBar.moveToDelta(mCurrentValidProgressDelta, diffInMinutes/2); setClockText(mCurrentValidTime); } } private void updateProgressWithDelta(int progressDelta) { // 1 deg = 2 min mNewCurrentTime = mOriginalTime.plusMinutes(progressDelta * 2); setClockText(mNewCurrentTime); if (mValidTimeInterval != null && mNewCurrentTime != null && mValidTimeInterval.contains(mNewCurrentTime)) { mCurrentValidProgressDelta = progressDelta; mCurrentValidTime = mNewCurrentTime.minusMinutes(progressDelta * 2); } } private void setClockText(DateTime newCurrentTime) { if (mIs24HourFormat) { mTimeText.setText(SIMPLE_DATE_FORMAT_HOURS.print(newCurrentTime)); mTimeMeridianText.setText(R.string.hrs); } else { mTimeText.setText(SIMPLE_DATE_FORMAT_AM_PM.print(newCurrentTime)); mTimeMeridianText.setText(SIMPLE_DATE_FORMAT_MERIDIAN.print(newCurrentTime).toLowerCase(Locale.US)); } setSeekBarStatus(newCurrentTime); } private void setSeekBarStatus(DateTime newCurrentTime) { if (mValidTimeInterval.contains(newCurrentTime)) { if (newCurrentTime.getDayOfWeek() == mValidTimeInterval.getStart().getDayOfWeek()) { mCircularClockSeekBar.setSeekBarStatus(VALID_RANGE); mTimeWeekDayText.setVisibility(GONE); } else { mCircularClockSeekBar.setSeekBarStatus(DIFFERENT_DAY_OF_WEEK); mTimeWeekDayText.setVisibility(VISIBLE); mTimeWeekDayText.setText(newCurrentTime.toString("EEE")); } } else { mCircularClockSeekBar.setSeekBarStatus(INVALID_RANGE); mTimeWeekDayText.setVisibility(GONE); } } public void setBounds(DateTime minTime, DateTime maxTime, boolean isMaxClock) { // NOTE: To show correct end time on clock, since the Interval.contains() checks for // millisInstant >= thisStart && millisInstant < thisEnd // however we want // millisInstant >= thisStart && millisInstant <= thisEnd maxTime = maxTime.plusMillis(1); mValidTimeInterval = new Interval(minTime, maxTime); maxTime = maxTime.minusMillis(1); if (isMaxClock) { mOriginalTime = maxTime; mCurrentValidTime = maxTime; int hourOfDay = maxTime.get(DateTimeFieldType.clockhourOfDay()) % 12; mCircularClockSeekBar.setProgress(hourOfDay * 10); setClockText(mOriginalTime); } else { mOriginalTime = minTime; mCurrentValidTime = minTime; int hourOfDay = minTime.get(DateTimeFieldType.clockhourOfDay()) % 12; mCircularClockSeekBar.setProgress(hourOfDay * 10); setClockText(mOriginalTime); } } @Nullable @Override public CharSequence getContentDescription() { return String.format("%s%s", mTimeText.getText(), mTimeMeridianText.getText()); } public void setClockTimeUpdateListener(ClockTimeUpdateListener clockTimeUpdateListener) { mClockTimeUpdateListener = clockTimeUpdateListener; } }
package de.lmu.ifi.dbs.elki.visualization.visualizers.scatterplot; import java.text.NumberFormat; import java.util.List; import java.util.Locale; import org.apache.batik.util.SVGConstants; import org.w3c.dom.Element; import de.lmu.ifi.dbs.elki.data.type.TypeUtil; import de.lmu.ifi.dbs.elki.database.ids.DBID; import de.lmu.ifi.dbs.elki.database.relation.Relation; import de.lmu.ifi.dbs.elki.result.HierarchicalResult; import de.lmu.ifi.dbs.elki.result.Result; import de.lmu.ifi.dbs.elki.result.ResultUtil; import de.lmu.ifi.dbs.elki.result.outlier.OutlierResult; import de.lmu.ifi.dbs.elki.utilities.iterator.IterableIterator; import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.GreaterEqualConstraint; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter; import de.lmu.ifi.dbs.elki.visualization.VisualizationTask; import de.lmu.ifi.dbs.elki.visualization.css.CSSClass; import de.lmu.ifi.dbs.elki.visualization.projector.ScatterPlotProjector; import de.lmu.ifi.dbs.elki.visualization.style.StyleLibrary; import de.lmu.ifi.dbs.elki.visualization.svg.SVGPlot; import de.lmu.ifi.dbs.elki.visualization.visualizers.AbstractVisFactory; import de.lmu.ifi.dbs.elki.visualization.visualizers.Visualization; /** * Generates a SVG-Element containing Tooltips. Tooltips remain invisible until * their corresponding Marker is touched by the cursor and stay visible as long * as the cursor lingers on the marker. * * @author Remigius Wojdanowski */ public class TooltipScoreVisualization extends AbstractTooltipVisualization { /** * A short name characterizing this Visualizer. */ public static final String NAME = "Outlier Score Tooltips"; /** * A short name characterizing this Visualizer. */ public static final String NAME_GEN = " Tooltips"; /** * Number format. */ NumberFormat nf; /** * Number value to visualize */ private Relation<? extends Number> result; /** * Font size to use. */ private double fontsize; /** * Constructor * * @param task Task * @param nf Number Format */ public TooltipScoreVisualization(VisualizationTask task, NumberFormat nf) { super(task); this.result = task.getResult(); this.nf = nf; this.fontsize = 3 * context.getStyleLibrary().getTextSize(StyleLibrary.PLOT); synchronizedRedraw(); } @Override protected Element makeTooltip(DBID id, double x, double y, double dotsize) { return svgp.svgText(x + dotsize, y + fontsize * 0.07, nf.format(result.get(id).doubleValue())); } /** * Registers the Tooltip-CSS-Class at a SVGPlot. * * @param svgp the SVGPlot to register the Tooltip-CSS-Class. */ @Override protected void setupCSS(SVGPlot svgp) { final StyleLibrary style = context.getStyleLibrary(); final double fontsize = style.getTextSize(StyleLibrary.PLOT); final String fontfamily = style.getFontFamily(StyleLibrary.PLOT); CSSClass tooltiphidden = new CSSClass(svgp, TOOLTIP_HIDDEN); tooltiphidden.setStatement(SVGConstants.CSS_FONT_SIZE_PROPERTY, fontsize); tooltiphidden.setStatement(SVGConstants.CSS_FONT_FAMILY_PROPERTY, fontfamily); tooltiphidden.setStatement(SVGConstants.CSS_DISPLAY_PROPERTY, SVGConstants.CSS_NONE_VALUE); svgp.addCSSClassOrLogError(tooltiphidden); CSSClass tooltipvisible = new CSSClass(svgp, TOOLTIP_VISIBLE); tooltipvisible.setStatement(SVGConstants.CSS_FONT_SIZE_PROPERTY, fontsize); tooltipvisible.setStatement(SVGConstants.CSS_FONT_FAMILY_PROPERTY, fontfamily); svgp.addCSSClassOrLogError(tooltipvisible); CSSClass tooltipsticky = new CSSClass(svgp, TOOLTIP_STICKY); tooltipsticky.setStatement(SVGConstants.CSS_FONT_SIZE_PROPERTY, fontsize); tooltipsticky.setStatement(SVGConstants.CSS_FONT_FAMILY_PROPERTY, fontfamily); svgp.addCSSClassOrLogError(tooltipsticky); // invisible but sensitive area for the tooltip activator CSSClass tooltiparea = new CSSClass(svgp, TOOLTIP_AREA); tooltiparea.setStatement(SVGConstants.CSS_FILL_PROPERTY, SVGConstants.CSS_RED_VALUE); tooltiparea.setStatement(SVGConstants.CSS_STROKE_PROPERTY, SVGConstants.CSS_NONE_VALUE); tooltiparea.setStatement(SVGConstants.CSS_FILL_OPACITY_PROPERTY, "0"); tooltiparea.setStatement(SVGConstants.CSS_CURSOR_PROPERTY, SVGConstants.CSS_POINTER_VALUE); svgp.addCSSClassOrLogError(tooltiparea); svgp.updateStyleElement(); } public static class Factory extends AbstractVisFactory { /** * Parameter for the gamma-correction. * * <p> * Key: {@code -tooltip.digits} * </p> * * <p> * Default value: 4 * </p> */ public static final OptionID DIGITS_ID = OptionID.getOrCreateOptionID("tooltip.digits", "Number of digits to show (e.g. when visualizing outlier scores)"); /** * Number formatter used for visualization */ NumberFormat nf = null; /** * Constructor. * * @param digits number of digits */ public Factory(int digits) { super(); nf = NumberFormat.getInstance(Locale.ROOT); nf.setGroupingUsed(false); nf.setMaximumFractionDigits(digits); } @Override public Visualization makeVisualization(VisualizationTask task) { return new TooltipScoreVisualization(task, nf); } @Override public void processNewResult(HierarchicalResult baseResult, Result result) { // TODO: we can also visualize other scores! List<OutlierResult> ors = ResultUtil.filterResults(result, OutlierResult.class); for(OutlierResult o : ors) { IterableIterator<ScatterPlotProjector<?>> ps = ResultUtil.filteredResults(baseResult, ScatterPlotProjector.class); for(ScatterPlotProjector<?> p : ps) { final VisualizationTask task = new VisualizationTask(NAME, o.getScores(), p.getRelation(), this); task.put(VisualizationTask.META_TOOL, true); task.put(VisualizationTask.META_VISIBLE_DEFAULT, false); baseResult.getHierarchy().add(o.getScores(), task); baseResult.getHierarchy().add(p, task); } } List<Relation<?>> rrs = ResultUtil.filterResults(result, Relation.class); for(Relation<?> r : rrs) { if(!TypeUtil.DOUBLE.isAssignableFromType(r.getDataTypeInformation()) && !TypeUtil.INTEGER.isAssignableFromType(r.getDataTypeInformation())) { continue; } // Skip if we already considered it above boolean add = true; for(Result p : baseResult.getHierarchy().getChildren(r)) { if(p instanceof VisualizationTask && ((VisualizationTask) p).getFactory() instanceof Factory) { add = false; break; } } if(add) { IterableIterator<ScatterPlotProjector<?>> ps = ResultUtil.filteredResults(baseResult, ScatterPlotProjector.class); for(ScatterPlotProjector<?> p : ps) { final VisualizationTask task = new VisualizationTask(r.getLongName() + NAME_GEN, r, p.getRelation(), this); task.put(VisualizationTask.META_TOOL, true); task.put(VisualizationTask.META_VISIBLE_DEFAULT, false); baseResult.getHierarchy().add(r, task); baseResult.getHierarchy().add(p, task); } } } } /** * Parameterization class. * * @author Erich Schubert * * @apiviz.exclude */ public static class Parameterizer extends AbstractParameterizer { protected int digits = 4; @Override protected void makeOptions(Parameterization config) { super.makeOptions(config); IntParameter DIGITS_PARAM = new IntParameter(DIGITS_ID, new GreaterEqualConstraint(0), 4); if(config.grab(DIGITS_PARAM)) { digits = DIGITS_PARAM.getValue(); } } @Override protected Factory makeInstance() { return new Factory(digits); } } } }
package com.researchworx.cresco.plugins.gobjectIngestion.folderprocessor; import com.researchworx.cresco.library.messaging.MsgEvent; import com.researchworx.cresco.library.utilities.CLogger; import com.researchworx.cresco.plugins.gobjectIngestion.Plugin; import com.researchworx.cresco.plugins.gobjectIngestion.objectstorage.ObjectEngine; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.text.SimpleDateFormat; import java.util.*; public class ObjectFS implements Runnable { private final String transfer_watch_file; private final String transfer_status_file; private String bucket_name; private String incoming_directory; private String outgoing_directory; private Plugin plugin; private CLogger logger; private MsgEvent me; private String pathStage; private int pstep; public static String stagePhase; public ObjectFS(Plugin plugin) { this.stagePhase = "uninit"; this.pstep = 1; this.plugin = plugin; this.logger = new CLogger(ObjectFS.class, plugin.getMsgOutQueue(), plugin.getRegion(), plugin.getAgent(), plugin.getPluginID(), CLogger.Level.Debug); this.pathStage = String.valueOf(plugin.pathStage); logger.debug("OutPathPreProcessor Instantiated"); incoming_directory = plugin.getConfig().getStringParam("incoming_directory"); logger.debug("\"pathstage" + pathStage + "\" --> \"incoming_directory\" from config [{}]", incoming_directory); outgoing_directory = plugin.getConfig().getStringParam("outgoing_directory"); logger.debug("\"pathstage" + pathStage + "\" --> \"outgoing_directory\" from config [{}]", outgoing_directory); transfer_status_file = plugin.getConfig().getStringParam("transfer_status_file"); logger.debug("\"pathstage" + pathStage + "\" --> \"transfer_status_file\" from config [{}]", transfer_status_file); transfer_watch_file = plugin.getConfig().getStringParam("transfer_watch_file"); logger.debug("\"pathstage" + pathStage + "\" --> \"transfer_watch_file\" from config [{}]", transfer_watch_file); bucket_name = plugin.getConfig().getStringParam("bucket"); logger.debug("\"pathstage" + pathStage + "\" --> \"bucket\" from config [{}]", bucket_name); me = plugin.genGMessage(MsgEvent.Type.INFO,"InPathPreProcessor instantiated"); me.setParam("transfer_watch_file",transfer_watch_file); me.setParam("transfer_status_file", transfer_status_file); me.setParam("bucket_name",bucket_name); me.setParam("pathstage",pathStage); me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); me.setParam("pstep",String.valueOf(pstep)); plugin.sendMsgEvent(me); } @Override public void run() { try { pstep = 2; logger.trace("Setting [PathProcessorActive] to true"); plugin.PathProcessorActive = true; ObjectEngine oe = new ObjectEngine(plugin); logger.trace("Entering while-loop"); while (plugin.PathProcessorActive) { me = plugin.genGMessage(MsgEvent.Type.INFO, "Idle"); me.setParam("transfer_watch_file", transfer_watch_file); me.setParam("transfer_status_file", transfer_status_file); me.setParam("bucket_name", bucket_name); me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); me.setParam("pathstage", pathStage); me.setParam("pstep",String.valueOf(pstep)); plugin.sendMsgEvent(me); Thread.sleep(plugin.getConfig().getIntegerParam("scan_interval",5000)); } } catch (Exception ex) { logger.error("run {}", ex.getMessage()); me = plugin.genGMessage(MsgEvent.Type.ERROR,"Error Path Run"); me.setParam("transfer_watch_file",transfer_watch_file); me.setParam("transfer_status_file", transfer_status_file); me.setParam("bucket_name",bucket_name); me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); me.setParam("pathstage",pathStage); me.setParam("error_message",ex.getMessage()); me.setParam("pstep",String.valueOf(pstep)); plugin.sendMsgEvent(me); } } public void processSequence(String seqId, String reqId) { MsgEvent pse = null; try { pstep = 3; logger.debug("Call to processSequence seq_id: " + seqId, ", req_id: " + reqId); ObjectEngine oe = new ObjectEngine(plugin); pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfering"); //me.setParam("inDir", remoteDir); //me.setParam("outDir", incoming_directory); pse.setParam("seq_id", seqId); pse.setParam("req_id", reqId); pse.setParam("transfer_status_file", transfer_status_file); pse.setParam("bucket_name", bucket_name); pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); pse.setParam("pathstage", pathStage); pse.setParam("sstep", "1"); plugin.sendMsgEvent(pse); oe.downloadDirectory(bucket_name, seqId, incoming_directory, seqId, null); List<String> filterList = new ArrayList<>(); logger.trace("Add [transfer_status_file] to [filterList]"); filterList.add(transfer_status_file); String inDir = incoming_directory; if (!inDir.endsWith("/")) { inDir = inDir + "/"; } logger.debug("[inDir = {}]", inDir); oe = new ObjectEngine(plugin); if (oe.isSyncDir(bucket_name, seqId, inDir, filterList)) { logger.debug("Directory Sycned [inDir = {}]", inDir); Map<String, String> md5map = oe.getDirMD5(inDir, filterList); logger.trace("Set MD5 hash"); setTransferFileMD5(inDir + transfer_status_file, md5map); pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfered"); pse.setParam("indir", inDir); pse.setParam("seq_id", seqId); pse.setParam("req_id", reqId); pse.setParam("transfer_status_file", transfer_status_file); pse.setParam("bucket_name", bucket_name); pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); pse.setParam("pathstage", pathStage); pse.setParam("sstep", "2"); plugin.sendMsgEvent(pse); } } catch(Exception ex) { logger.error("run {}", ex.getMessage()); pse = plugin.genGMessage(MsgEvent.Type.ERROR,"Error Path Run"); pse.setParam("seq_id", seqId); pse.setParam("req_id", reqId); pse.setParam("transfer_watch_file",transfer_watch_file); pse.setParam("transfer_status_file", transfer_status_file); pse.setParam("bucket_name",bucket_name); pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); pse.setParam("pathstage",pathStage); pse.setParam("error_message",ex.getMessage()); pse.setParam("sstep","1"); plugin.sendMsgEvent(pse); } pstep = 2; } private boolean deleteDirectory(File path) { if( path.exists() ) { File[] files = path.listFiles(); for(int i=0; i<files.length; i++) { if(files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return( path.delete() ); } public void run_test() { PerfTracker pt = new PerfTracker(); Thread ptt = new Thread(pt); ptt.start(); } private class PerfTracker extends Thread { private boolean isActive = false; public void run(){ try { isActive = true; System.out.println("PerfTracker running"); Long perfRate = plugin.getConfig().getLongParam("perfrate",5000L); while(isActive) { logPerf(); Thread.sleep(perfRate); } } catch(Exception ex) { logger.error("Static runner failure : " + ex.getMessage()); } } private void logPerf() { MsgEvent me = plugin.getSysInfo(); if(me != null) { /* Iterator it = me.getParams().entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); logger.info(pairs.getKey() + " = " + pairs.getValue()); //String plugin = pairs.getKey().toString(); } */ //cpu-per-cpu-load = CPU Load per processor: 1.0% 12.0% 8.0% 7.9% 0.0% 0.0% 0.0% 0.0% //cpu-core-count = 8 //String sCoreCountp = me.getParam("cpu-core-count-physical"); //String sCoreCountl = me.getParam("cpu-core-count-logical"); String sCoreCountp = me.getParam("cpu-core-count"); String sCoreCountl = me.getParam("cpu-core-count"); int pcoreCount = Integer.parseInt(sCoreCountp); String cpuPerLoad = me.getParam("cpu-per-cpu-load"); cpuPerLoad = cpuPerLoad.substring(cpuPerLoad.indexOf(": ") + 2); cpuPerLoad = cpuPerLoad.replace("%",""); String[] perCpu = cpuPerLoad.split(" "); String sCputPerLoadGrp = ""; for(String cpu : perCpu) { //logger.info(cpu); sCputPerLoadGrp += cpu + ":"; } sCputPerLoadGrp = sCputPerLoadGrp.substring(0,sCputPerLoadGrp.length() -1); String sMemoryTotal = me.getParam("memory-total"); Long memoryTotal = Long.parseLong(sMemoryTotal); String sMemoryAvailable = me.getParam("memory-available"); Long memoryAvailable = Long.parseLong(sMemoryAvailable); Long memoryUsed = memoryTotal - memoryAvailable; String sMemoryUsed = String.valueOf(memoryUsed); String sCpuIdleLoad = me.getParam("cpu-idle-load"); String sCpuUserLoad = me.getParam("cpu-user-load"); String sCpuNiceLoad = me.getParam("cpu-nice-load"); String sCpuSysLoad = me.getParam("cpu-sys-load"); float cpuIdleLoad = Float.parseFloat(sCpuIdleLoad); float cpuUserLoad = Float.parseFloat(sCpuUserLoad); float cpuNiceLoad = Float.parseFloat(sCpuNiceLoad); float cpuSysLoad = Float.parseFloat(sCpuSysLoad); float cpuTotalLoad = cpuIdleLoad + cpuUserLoad + cpuNiceLoad + cpuSysLoad; String smemoryUsed = String.valueOf(memoryUsed/1024/1024); //String sCpuTotalLoad = String.valueOf(cpuTotalLoad); boolean loadIsSane = false; if(cpuTotalLoad == 100.0) { loadIsSane = true; } //logger.info("MEM USED = " + smemoryUsed + " sTotalLoad = " + sCpuTotalLoad + " isSane = " + loadIsSane); String header = "ts,cpu-idle-load,cpu-user-load,cpu-nice-load,cpu-sys-load,cpu-core-count-physical,cpu-core-count-logical,cpu-core-load,load-sane,memory-total,memory-available,memory-used,process-phase\n"; String output = System.currentTimeMillis() + "," + sCpuIdleLoad + "," + sCpuUserLoad + "," + sCpuNiceLoad + "," + sCpuSysLoad + "," + sCoreCountp + "," + sCoreCountl + "," + sCputPerLoadGrp + "," + String.valueOf(loadIsSane) + "," + sMemoryTotal + "," + sMemoryAvailable + "," + sMemoryUsed + "," + ObjectFS.stagePhase + "\n"; String logPath = plugin.getConfig().getStringParam("perflogpath"); if(logPath != null) { try { Path logpath = Paths.get(logPath); //output += "\n"; if (!logpath.toFile().exists()) { Files.write(logpath, header.getBytes(), StandardOpenOption.CREATE); Files.write(logpath, output.getBytes(), StandardOpenOption.APPEND); } else { Files.write(logpath, output.getBytes(), StandardOpenOption.APPEND); } } catch (Exception e) { logger.error("Error Static Runner " + e.getMessage()); e.printStackTrace(); //exception handling left as an exercise for the reader } } } else { logger.error("me = null"); } } } public void executeCommand(String inDir, String outDir, boolean trackPerf) { pstep = 3; //start perf mon PerfTracker pt = null; if(trackPerf) { pt = new PerfTracker(); new Thread(pt).start(); } //String command = "docker run -t -v /home/gpackage:/gpackage -v /home/gdata/input/160427_D00765_0033_AHKM2CBCXX/Sample3:/gdata/input -v /home/gdata/output/f8de921b-fdfa-4365-bf7d-39817b9d1883:/gdata/output intrepo.uky.edu:5000/gbase /gdata/input/commands_main.sh"; //String command = "docker run -t -v /home/gpackage:/gpackage -v " + tmpInput + ":/gdata/input -v " + tmpOutput + ":/gdata/output intrepo.uky.edu:5000/gbase /gdata/input/commands_main.sh"; String command = "docker run -t -v /home/gpackage:/gpackage -v " + inDir + ":/gdata/input -v " + outDir + ":/gdata/output intrepo.uky.edu:5000/gbase /gdata/input/commands_main.sh"; StringBuffer output = new StringBuffer(); StringBuffer error = new StringBuffer(); Process p; try { p = Runtime.getRuntime().exec(command); BufferedReader outputFeed = new BufferedReader(new InputStreamReader(p.getInputStream())); String outputLine; long difftime = System.currentTimeMillis(); while ((outputLine = outputFeed.readLine()) != null) { output.append(outputLine); String[] outputStr = outputLine.split("\\|\\|"); //System.out.println(outputStr.length + ": " + outputLine); //for(String str : outputStr) { //System.out.println(outputStr.length + " " + str); for(int i = 0; i<outputStr.length; i++) { outputStr[i] = outputStr[i].trim(); } if((outputStr.length == 5) && ((outputLine.toLowerCase().startsWith("info")) || (outputLine.toLowerCase().startsWith("error")))) { Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US); cal.setTime(sdf.parse(outputStr[1].trim()));// all done long logdiff = (cal.getTimeInMillis() - difftime); difftime = cal.getTimeInMillis(); if(outputStr[0].toLowerCase().equals("info")) { //logger.info("Log diff = " + logdiff + " : " + outputStr[2] + " : " + outputStr[3] + " : " + outputStr[4]); ObjectFS.stagePhase = outputStr[3]; } else if (outputStr[0].toLowerCase().equals("error")) { logger.error("Pipeline Error : " + outputLine.toString()); } } logger.debug(outputLine); } /* if (!output.toString().equals("")) { //INFO : Mon May 9 20:35:42 UTC 2016 : UKHC Genomics pipeline V-1.0 : run_secondary_analysis.pl : Module Function run_locally() - execution successful logger.info(output.toString()); // clog.info(output.toString()); } BufferedReader errorFeed = new BufferedReader(new InputStreamReader(p.getErrorStream())); String errorLine; while ((errorLine = errorFeed.readLine()) != null) { error.append(errorLine); logger.error(errorLine); } if (!error.toString().equals("")) logger.error(error.toString()); // clog.error(error.toString()); */ p.waitFor(); if(trackPerf) { pt.isActive = false; } } catch (IOException ioe) { // WHAT!?! DO SOMETHIN'! logger.error(ioe.getMessage()); } catch (InterruptedException ie) { // WHAT!?! DO SOMETHIN'! logger.error(ie.getMessage()); } catch (Exception e) { // WHAT!?! DO SOMETHIN'! logger.error(e.getMessage()); } pstep = 2; } public void processSample(String seqId, String sampleId, String reqId, boolean trackPerf) { pstep = 3; String results_bucket_name = plugin.getConfig().getStringParam("results_bucket"); if (results_bucket_name == null || results_bucket_name.equals("")) { plugin.PathProcessorActive = false; MsgEvent error = plugin.genGMessage(MsgEvent.Type.ERROR, "Configuration value [results_bucket] is not properly set"); error.setParam("req_id", reqId); error.setParam("seq_id", seqId); error.setParam("sample_id", sampleId); error.setParam("transfer_status_file", transfer_status_file); error.setParam("bucket_name", bucket_name); error.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); error.setParam("pathstage", pathStage); error.setParam("ssstep", "0"); plugin.sendMsgEvent(error); } MsgEvent pse; int ssstep = 1; String workDirName = null; try { workDirName = incoming_directory; //create random tmp location workDirName = workDirName.replace(" if(!workDirName.endsWith("/")) { workDirName += "/"; } File workDir = new File(workDirName); if (workDir.exists()) { deleteDirectory(workDir); } workDir.mkdir(); String remoteDir = seqId + "/" + sampleId + "/"; logger.debug("Call to processSample seq_id: {}, sample_id: {}, req_id: {}", seqId, sampleId, reqId); ObjectEngine oe = new ObjectEngine(plugin); oe.createBucket(results_bucket_name); pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfering"); //me.setParam("inDir", remoteDir); //me.setParam("outDir", incoming_directory); pse.setParam("req_id", reqId); pse.setParam("seq_id", seqId); pse.setParam("sample_id", sampleId); pse.setParam("transfer_status_file", transfer_status_file); pse.setParam("bucket_name", bucket_name); pse.setParam("results_bucket_name", results_bucket_name); pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); pse.setParam("pathstage", pathStage); pse.setParam("ssstep", String.valueOf(ssstep)); plugin.sendMsgEvent(pse); oe.downloadDirectory(bucket_name, remoteDir, workDirName, seqId, sampleId); workDirName += remoteDir; List<String> filterList = new ArrayList<>(); logger.trace("Add [transfer_status_file] to [filterList]"); /* filterList.add(transfer_status_file); String inDir = incoming_directory; if (!inDir.endsWith("/")) { inDir = inDir + "/"; } */ //logger.debug("[inDir = {}]", inDir); oe = new ObjectEngine(plugin); if (oe.isSyncDir(bucket_name, remoteDir, workDirName, filterList)) { ssstep = 2; logger.debug("Directory Sycned [inDir = {}]", workDirName); Map<String, String> md5map = oe.getDirMD5(workDirName, filterList); logger.trace("Set MD5 hash"); setTransferFileMD5(workDirName + transfer_status_file, md5map); pse = plugin.genGMessage(MsgEvent.Type.INFO, "Directory Transfered"); pse.setParam("indir", workDirName); pse.setParam("req_id", reqId); pse.setParam("seq_id", seqId); pse.setParam("sample_id", sampleId); pse.setParam("transfer_status_file", transfer_status_file); pse.setParam("bucket_name", bucket_name); pse.setParam("results_bucket_name", results_bucket_name); pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); pse.setParam("pathstage", pathStage); pse.setParam("ssstep", String.valueOf(ssstep)); plugin.sendMsgEvent(pse); ssstep = 3; } } catch(Exception ex) { logger.error("run {}", ex.getMessage()); pse = plugin.genGMessage(MsgEvent.Type.ERROR,"Error Path Run"); pse.setParam("req_id", reqId); pse.setParam("seq_id", seqId); pse.setParam("sample_id", sampleId); pse.setParam("transfer_watch_file",transfer_watch_file); pse.setParam("transfer_status_file", transfer_status_file); pse.setParam("bucket_name",bucket_name); pse.setParam("results_bucket_name", results_bucket_name); pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); pse.setParam("pathstage",pathStage); pse.setParam("error_message",ex.getMessage()); pse.setParam("ssstep",String.valueOf(ssstep)); plugin.sendMsgEvent(pse); } //if is makes it through process the seq if(ssstep == 3) { logger.trace("seq_id=" + seqId + " sample_id=" + sampleId); try { //start perf mon PerfTracker pt = null; if (trackPerf) { pt = new PerfTracker(); new Thread(pt).start(); } pse = plugin.genGMessage(MsgEvent.Type.INFO, "Creating output directory"); pse.setParam("indir", workDirName); pse.setParam("req_id", reqId); pse.setParam("seq_id", seqId); pse.setParam("sample_id", sampleId); pse.setParam("transfer_status_file", transfer_status_file); pse.setParam("bucket_name", bucket_name); pse.setParam("results_bucket_name", results_bucket_name); pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); pse.setParam("pathstage", pathStage); pse.setParam("ssstep", String.valueOf(ssstep)); plugin.sendMsgEvent(pse); String resultDirName = outgoing_directory; //create random tmp location resultDirName = resultDirName.replace(" if (!resultDirName.endsWith("/")) { resultDirName += "/"; } resultDirName = resultDirName + seqId + "/" + sampleId + "/"; File resultDir = new File(resultDirName); if (resultDir.exists()) { deleteDirectory(resultDir); } resultDir.mkdir(); ssstep = 4; pse = plugin.genGMessage(MsgEvent.Type.INFO, "Starting Pipeline via Docker Container"); pse.setParam("indir", workDirName); pse.setParam("outdir", resultDirName); pse.setParam("req_id", reqId); pse.setParam("seq_id", seqId); pse.setParam("sample_id", sampleId); pse.setParam("transfer_status_file", transfer_status_file); pse.setParam("bucket_name", bucket_name); pse.setParam("results_bucket_name", results_bucket_name); pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); pse.setParam("pathstage", pathStage); pse.setParam("ssstep", String.valueOf(ssstep)); plugin.sendMsgEvent(pse); String command = "docker run -t -v /home/gpackage:/gpackage -v " + workDirName + ":/gdata/input -v " + resultDirName + ":/gdata/output intrepo.uky.edu:5000/gbase /gdata/input/commands_main.sh"; StringBuffer output = new StringBuffer(); StringBuffer error = new StringBuffer(); Process p; try { p = Runtime.getRuntime().exec(command); BufferedReader outputFeed = new BufferedReader(new InputStreamReader(p.getInputStream())); String outputLine; long difftime = System.currentTimeMillis(); while ((outputLine = outputFeed.readLine()) != null) { output.append(outputLine); String[] outputStr = outputLine.split("\\|\\|"); for (int i = 0; i < outputStr.length; i++) { outputStr[i] = outputStr[i].trim(); } if ((outputStr.length == 5) && ((outputLine.toLowerCase().startsWith("info")) || (outputLine.toLowerCase().startsWith("error")))) { Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US); cal.setTime(sdf.parse(outputStr[1].trim()));// all done long logdiff = (cal.getTimeInMillis() - difftime); difftime = cal.getTimeInMillis(); if (outputStr[0].toLowerCase().equals("info")) { //logger.info("Log diff = " + logdiff + " : " + outputStr[2] + " : " + outputStr[3] + " : " + outputStr[4]); if (!stagePhase.equals(outputStr[3])) { pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pipeline now in phase " + outputStr[3]); pse.setParam("indir", workDirName); pse.setParam("outdir", resultDirName); pse.setParam("req_id", reqId); pse.setParam("seq_id", seqId); pse.setParam("sample_id", sampleId); pse.setParam("transfer_status_file", transfer_status_file); pse.setParam("bucket_name", bucket_name); pse.setParam("results_bucket_name", results_bucket_name); pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); pse.setParam("pathstage", pathStage); pse.setParam("ssstep", String.valueOf(ssstep)); plugin.sendMsgEvent(pse); } ObjectFS.stagePhase = outputStr[3]; } else if (outputStr[0].toLowerCase().equals("error")) { logger.error("Pipeline Error : " + outputLine); pse = plugin.genGMessage(MsgEvent.Type.ERROR, "Pipeline now in phase " + outputStr[3]); pse.setParam("indir", workDirName); pse.setParam("outdir", resultDirName); pse.setParam("req_id", reqId); pse.setParam("seq_id", seqId); pse.setParam("sample_id", sampleId); pse.setParam("transfer_status_file", transfer_status_file); pse.setParam("bucket_name", bucket_name); pse.setParam("results_bucket_name", results_bucket_name); pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); pse.setParam("pathstage", pathStage); pse.setParam("ssstep", String.valueOf(ssstep)); pse.setParam("error_message", outputLine); plugin.sendMsgEvent(pse); } } logger.debug(outputLine); } p.waitFor(); if (trackPerf) { pt.isActive = false; } } catch (IOException ioe) { // WHAT!?! DO SOMETHIN'! logger.error("File read/write exception: {}", ioe.getMessage()); } catch (InterruptedException ie) { // WHAT!?! DO SOMETHIN'! logger.error("Process was interrupted: {}", ie.getMessage()); } catch (Exception e) { // WHAT!?! DO SOMETHIN'! logger.error("Exception: {}", e.getMessage()); } ssstep = 5; pse = plugin.genGMessage(MsgEvent.Type.INFO, "Pipeline has completed"); pse.setParam("indir", workDirName); pse.setParam("req_id", reqId); pse.setParam("seq_id", seqId); pse.setParam("sample_id", sampleId); pse.setParam("transfer_status_file", transfer_status_file); pse.setParam("bucket_name", bucket_name); pse.setParam("results_bucket_name", results_bucket_name); pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); pse.setParam("pathstage", pathStage); pse.setParam("ssstep", String.valueOf(ssstep)); pse.setParam("output_log", output.toString()); plugin.sendMsgEvent(pse); ObjectEngine oe = new ObjectEngine(plugin); ssstep = 6; pse = plugin.genGMessage(MsgEvent.Type.INFO, "Uploading Results Directory"); pse.setParam("indir", workDirName); pse.setParam("req_id", reqId); pse.setParam("seq_id", seqId); pse.setParam("sample_id", sampleId); pse.setParam("transfer_status_file", transfer_status_file); pse.setParam("bucket_name", bucket_name); pse.setParam("results_bucket_name", results_bucket_name); pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); pse.setParam("pathstage", pathStage); pse.setParam("ssstep", String.valueOf(ssstep)); plugin.sendMsgEvent(pse); oe.uploadDirectory(results_bucket_name, resultDirName, seqId + "/" + sampleId + "/"); List<String> filterList = new ArrayList<>(); logger.trace("Add [transfer_status_file] to [filterList]"); /* filterList.add(transfer_status_file); String inDir = incoming_directory; if (!inDir.endsWith("/")) { inDir = inDir + "/"; } */ //logger.debug("[inDir = {}]", inDir); oe = new ObjectEngine(plugin); if (oe.isSyncDir(bucket_name, seqId + "/" + sampleId + "/", resultDirName, filterList)) { ssstep = 7; logger.debug("Results Directory Sycned [inDir = {}]", workDirName); Map<String, String> md5map = oe.getDirMD5(workDirName, filterList); logger.trace("Set MD5 hash"); setTransferFileMD5(workDirName + transfer_status_file, md5map); pse = plugin.genGMessage(MsgEvent.Type.INFO, "Results Directory Transferred"); pse.setParam("indir", workDirName); pse.setParam("req_id", reqId); pse.setParam("seq_id", seqId); pse.setParam("sample_id", sampleId); pse.setParam("transfer_status_file", transfer_status_file); pse.setParam("bucket_name", bucket_name); pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); pse.setParam("pathstage", pathStage); pse.setParam("ssstep", String.valueOf(ssstep)); plugin.sendMsgEvent(pse); } /* UUID id = UUID.randomUUID(); //create random tmp location String tmpInput = incoming_directory + id.toString(); String tmpOutput = outgoing_directory + "/" + id.toString(); String tmpRemoteOutput = remoteDir + "/" + subDir + "/" + "primary"; tmpRemoteOutput = tmpRemoteOutput.replace("//","/"); File tmpOutputdir = new File(tmpOutput); if (commands_main.exists()) { deleteDirectory(tmpOutputdir); } tmpOutputdir.mkdir(); logger.trace("Creating tmp output location : " + tmpOutput); logger.info("Launching processing container:"); logger.info("Input Location: " + tmpInput); logger.info("Output Location: " + tmpOutput); logger.info("Remote Output Location: " + tmpRemoteOutput); //process data //String command = "docker run -t -v /home/gpackage:/gpackage -v /home/gdata/input/160427_D00765_0033_AHKM2CBCXX/Sample3:/gdata/input -v /home/gdata/output/f8de921b-fdfa-4365-bf7d-39817b9d1883:/gdata/output intrepo.uky.edu:5000/gbase /gdata/input/commands_main.sh"; //String command = "docker run -t -v /home/gpackage:/gpackage -v " + tmpInput + ":/gdata/input -v " + tmpOutput + ":/gdata/output intrepo.uky.edu:5000/gbase /gdata/input/commands_main.sh"; String command = "dir"; logger.info("Docker exec command: " + command); executeCommand(command); String content = "Hello File!"; String path = tmpOutput + "/testfile"; try { Files.write(Paths.get(path), content.getBytes(), StandardOpenOption.CREATE); } catch (Exception ex) { logger.error(ex.getMessage()); } //transfer data logger.info("Transfering " + tmpOutput + " to " + bucket_name + ":" + tmpRemoteOutput); ObjectEngine oe = new ObjectEngine(plugin); if (oe.uploadDirectory(bucket_name, tmpOutput, tmpRemoteOutput)) { //cleanup logger.trace("Removing tmp output location : " + tmpOutput); deleteDirectory(tmpOutputdir); } else { logger.error("Skipping! : commands_main.sh and config_files not found in subdirectory " + dir + "/" + subDir); } */ } catch (Exception e) { logger.error("processSample {}", e.getMessage()); pse = plugin.genGMessage(MsgEvent.Type.ERROR,"Error Path Run"); pse.setParam("req_id", reqId); pse.setParam("seq_id", seqId); pse.setParam("sample_id", sampleId); pse.setParam("transfer_watch_file",transfer_watch_file); pse.setParam("transfer_status_file", transfer_status_file); pse.setParam("bucket_name",bucket_name); pse.setParam("results_bucket_name", results_bucket_name); pse.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); pse.setParam("pathstage",pathStage); pse.setParam("error_message",e.getMessage()); pse.setParam("ssstep", String.valueOf(ssstep)); plugin.sendMsgEvent(pse); } } pstep = 2; } /* private void legacy() { logger.trace("Thread starting"); try { logger.trace("Setting [PathProcessorActive] to true"); plugin.PathProcessorActive = true; ObjectEngine oe = new ObjectEngine(plugin); logger.trace("Entering while-loop"); while (plugin.PathProcessorActive) { me = plugin.genGMessage(MsgEvent.Type.INFO,"Start Object Scan"); me.setParam("transfer_watch_file",transfer_watch_file); me.setParam("transfer_status_file", transfer_status_file); me.setParam("bucket_name",bucket_name); me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); me.setParam("pathstage",pathStage); me.setParam("pstep","2"); plugin.sendMsgEvent(me); try { //oe.deleteBucketContents(bucket_name); logger.trace("Populating [remoteDirs]"); List<String> remoteDirs = oe.listBucketDirs(bucket_name); for(String remoteDir : remoteDirs) { logger.trace("Remote Dir : " + remoteDir); } logger.trace("Populating [localDirs]"); List<String> localDirs = getWalkPath(incoming_directory); for(String localDir : localDirs) { logger.trace("Local Dir : " + localDir); } List<String> newDirs = new ArrayList<>(); for (String remoteDir : remoteDirs) { logger.trace("Checking for existance of RemoteDir [" + remoteDir + "] locally"); if (!localDirs.contains(remoteDir)) { logger.trace("RemoteDir [" + remoteDir + "] does not exist locally"); if (oe.doesObjectExist(bucket_name, remoteDir + transfer_watch_file)) { logger.debug("Adding [remoteDir = {}] to [newDirs]", remoteDir); newDirs.add(remoteDir); } } } if (!newDirs.isEmpty()) { logger.trace("[newDirs] has buckets to process"); processBucket(newDirs); } Thread.sleep(30000); } catch (Exception ex) { logger.error("run : while {}", ex.getMessage()); me = plugin.genGMessage(MsgEvent.Type.ERROR,"Error during Object scan"); me.setParam("transfer_watch_file",transfer_watch_file); me.setParam("transfer_status_file", transfer_status_file); me.setParam("bucket_name",bucket_name); me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); me.setParam("pathstage",pathStage); me.setParam("error_message",ex.getMessage()); me.setParam("pstep","2"); plugin.sendMsgEvent(me); } //message end of scan me = plugin.genGMessage(MsgEvent.Type.INFO,"End Object Scan"); me.setParam("transfer_watch_file",transfer_watch_file); me.setParam("transfer_status_file", transfer_status_file); me.setParam("bucket_name",bucket_name); me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); me.setParam("pathstage",pathStage); me.setParam("pstep","3"); plugin.sendMsgEvent(me); } } catch (Exception ex) { logger.error("run {}", ex.getMessage()); me = plugin.genGMessage(MsgEvent.Type.ERROR,"Error Path Run"); me.setParam("transfer_watch_file",transfer_watch_file); me.setParam("transfer_status_file", transfer_status_file); me.setParam("bucket_name",bucket_name); me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); me.setParam("pathstage",pathStage); me.setParam("error_message",ex.getMessage()); me.setParam("pstep","2"); plugin.sendMsgEvent(me); } } private void processBucket(List<String> newDirs) { logger.debug("Call to processBucket [newDir = {}]", newDirs.toString()); ObjectEngine oe = new ObjectEngine(plugin); for (String remoteDir : newDirs) { logger.debug("Downloading directory {} to [incoming_directory]", remoteDir); String seqId = remoteDir.substring(remoteDir.lastIndexOf("/") + 1, remoteDir.length()); me = plugin.genGMessage(MsgEvent.Type.INFO,"Directory Transfered"); me.setParam("inDir", remoteDir); me.setParam("outDir", incoming_directory); me.setParam("seq_id", seqId); me.setParam("transfer_watch_file",transfer_watch_file); me.setParam("transfer_status_file", transfer_status_file); me.setParam("bucket_name",bucket_name); me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); me.setParam("pathstage",pathStage); me.setParam("sstep","1"); plugin.sendMsgEvent(me); oe.downloadDirectory(bucket_name, remoteDir, incoming_directory); List<String> filterList = new ArrayList<>(); logger.trace("Add [transfer_status_file] to [filterList]"); filterList.add(transfer_status_file); String inDir = incoming_directory; if (!inDir.endsWith("/")) { inDir = inDir + "/"; } inDir = inDir + remoteDir; logger.debug("[inDir = {}]", inDir); oe = new ObjectEngine(plugin); if (oe.isSyncDir(bucket_name, remoteDir, inDir, filterList)) { logger.debug("Directory Sycned [inDir = {}]", inDir); Map<String, String> md5map = oe.getDirMD5(inDir, filterList); logger.trace("Set MD5 hash"); setTransferFileMD5(inDir + transfer_status_file, md5map); me = plugin.genGMessage(MsgEvent.Type.INFO,"Directory Transfered"); me.setParam("indir", inDir); me.setParam("outdir", remoteDir); me.setParam("seq_id", seqId); me.setParam("transfer_watch_file",transfer_watch_file); me.setParam("transfer_status_file", transfer_status_file); me.setParam("bucket_name",bucket_name); me.setParam("endpoint", plugin.getConfig().getStringParam("endpoint")); me.setParam("pathstage",pathStage); me.setParam("sstep","2"); plugin.sendMsgEvent(me); } } } */ private void setTransferFileMD5(String dir, Map<String, String> md5map) { logger.debug("Call to setTransferFileMD5 [dir = {}]", dir); try { PrintWriter out = null; try { logger.trace("Opening [dir] to write"); out = new PrintWriter(new BufferedWriter(new FileWriter(dir, true))); for (Map.Entry<String, String> entry : md5map.entrySet()) { String md5file = entry.getKey().replace(incoming_directory, ""); if (md5file.startsWith("/")) { md5file = md5file.substring(1); } out.write(md5file + ":" + entry.getValue() + "\n"); logger.debug("[md5file = {}, entry = {}] written", md5file, entry.getValue()); } } finally { try { assert out != null; out.flush(); out.close(); } catch (AssertionError e) { logger.error("setTransferFileMd5 - PrintWriter was pre-emptively shutdown"); } } } catch (Exception ex) { logger.error("setTransferFile {}", ex.getMessage()); } } private List<String> getWalkPath(String path) { logger.debug("Call to getWalkPath [path = {}]", path); if (!path.endsWith("/")) { path = path + "/"; } List<String> dirList = new ArrayList<>(); File root = new File(path); File[] list = root.listFiles(); if (list == null) { logger.trace("[list] is null, returning [dirList (empty array)]"); return dirList; } for (File f : list) { if (f.isDirectory()) { //walkPath( f.getAbsolutePath() ); String dir = f.getAbsolutePath().replace(path, ""); logger.debug("Adding \"{}/\" to [dirList]", dir); dirList.add(dir + "/"); } } return dirList; } }
package com.dd; import com.dd.circular.progress.button.R; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.util.AttributeSet; import android.widget.Button; public class CircularProgressButton extends Button { public static final int IDLE_STATE_PROGRESS = 0; public static final int ERROR_STATE_PROGRESS = -1; private StrokeGradientDrawable background; private CircularAnimatedDrawable mAnimatedDrawable; private CircularProgressDrawable mProgressDrawable; private State mState; private String mIdleText; private String mCompleteText; private String mErrorText; private int mColorIdle; private int mColorError; private int mColorProgress; private int mColorComplete; private int mColorIndicator; private int mColorIndicatorBackground; private int mIconComplete; private int mIconError; private int mStrokeWidth; private int mPaddingProgress; private float mCornerRadius; private boolean mIndeterminateProgressMode; private enum State { PROGRESS, IDLE, COMPLETE, ERROR } private int mMaxProgress; private int mProgress; private boolean mMorphingInProgress; public CircularProgressButton(Context context) { super(context); init(context, null); } public CircularProgressButton(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public CircularProgressButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs); } private void init(Context context, AttributeSet attributeSet) { mStrokeWidth = (int) getContext().getResources().getDimension(R.dimen.stroke_width); initAttributes(context, attributeSet); mMaxProgress = 100; mState = State.IDLE; setText(mIdleText); GradientDrawable gradientDrawable = (GradientDrawable) context.getResources().getDrawable(R.drawable.background).mutate(); gradientDrawable.setColor(mColorIdle); gradientDrawable.setCornerRadius(mCornerRadius); background = new StrokeGradientDrawable(gradientDrawable); background.setStrokeColor(mColorIdle); background.setStrokeWidth(mStrokeWidth); setBackgroundCompat(gradientDrawable); } private void initAttributes(Context context, AttributeSet attributeSet) { TypedArray attr = getTypedArray(context, attributeSet, R.styleable.CircularProgressButton); if (attr == null) { return; } try { mIdleText = attr.getString(R.styleable.CircularProgressButton_cpb_textIdle); mCompleteText = attr.getString(R.styleable.CircularProgressButton_cpb_textComplete); mErrorText = attr.getString(R.styleable.CircularProgressButton_cpb_textError); mIconComplete = attr.getResourceId(R.styleable.CircularProgressButton_cpb_iconComplete, 0); mIconError = attr.getResourceId(R.styleable.CircularProgressButton_cpb_iconError, 0); mCornerRadius = attr.getDimension(R.styleable.CircularProgressButton_cpb_cornerRadius, 0); mPaddingProgress = attr.getDimensionPixelSize(R.styleable.CircularProgressButton_cpb_paddingProgress, 0); int blue = getColor(R.color.blue); int red = getColor(R.color.red); int green = getColor(R.color.green); int white = getColor(R.color.white); int grey = getColor(R.color.grey); mColorIdle = attr.getColor(R.styleable.CircularProgressButton_cpb_colorIdle, blue); mColorError = attr.getColor(R.styleable.CircularProgressButton_cpb_colorError, red); mColorComplete = attr.getColor(R.styleable.CircularProgressButton_cpb_colorComplete, green); mColorProgress = attr.getColor(R.styleable.CircularProgressButton_cpb_colorProgress, white); mColorIndicator = attr.getColor(R.styleable.CircularProgressButton_cpb_colorIndicator, blue); mColorIndicatorBackground = attr.getColor(R.styleable.CircularProgressButton_cpb_colorIndicatorBackground, grey); } finally { attr.recycle(); } } protected int getColor(int id) { return getResources().getColor(id); } protected TypedArray getTypedArray(Context context, AttributeSet attributeSet, int[] attr) { return context.obtainStyledAttributes(attributeSet, attr, 0, 0); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mProgress > 0 && mState == State.PROGRESS && !mMorphingInProgress) { if (mIndeterminateProgressMode) { drawIndeterminateProgress(canvas); } else { drawProgress(canvas); } } } private void drawIndeterminateProgress(Canvas canvas) { if (mAnimatedDrawable == null) { int offset = (getWidth() - getHeight()) / 2; mAnimatedDrawable = new CircularAnimatedDrawable(mColorIndicator, mStrokeWidth); int left = offset + mPaddingProgress; int right = getWidth() - offset - mPaddingProgress; int bottom = getHeight() - mPaddingProgress; int top = mPaddingProgress; mAnimatedDrawable.setBounds(left, top, right, bottom); mAnimatedDrawable.setCallback(this); mAnimatedDrawable.start(); } else { mAnimatedDrawable.draw(canvas); } } private void drawProgress(Canvas canvas) { if (mProgressDrawable == null) { int offset = (getWidth() - getHeight()) / 2; int size = getHeight() - mPaddingProgress * 2; mProgressDrawable = new CircularProgressDrawable(size, mStrokeWidth, mColorIndicator); int left = offset + mPaddingProgress; mProgressDrawable.setBounds(left, mPaddingProgress, left, mPaddingProgress); } float sweepAngle = (360f / mMaxProgress) * mProgress; mProgressDrawable.setSweepAngle(sweepAngle); mProgressDrawable.draw(canvas); } public boolean isIndeterminateProgressMode() { return mIndeterminateProgressMode; } public void setIndeterminateProgressMode(boolean indeterminateProgressMode) { this.mIndeterminateProgressMode = indeterminateProgressMode; } @Override protected boolean verifyDrawable(Drawable who) { return who == mAnimatedDrawable || super.verifyDrawable(who); } private MorphingAnimation createMorphing() { mMorphingInProgress = true; MorphingAnimation animation = new MorphingAnimation(this, background); animation.setFromCornerRadius(mCornerRadius); animation.setToCornerRadius(mCornerRadius); animation.setFromWidth(getWidth()); animation.setToWidth(getWidth()); return animation; } private MorphingAnimation createProgressMorphing(float fromCorner, float toCorner, int fromWidth, int toWidth) { mMorphingInProgress = true; MorphingAnimation animation = new MorphingAnimation(this, background); animation.setFromCornerRadius(fromCorner); animation.setToCornerRadius(toCorner); animation.setPadding(mPaddingProgress); animation.setFromWidth(fromWidth); animation.setToWidth(toWidth); return animation; } private void morphToProgress() { setWidth(getWidth()); setText(null); MorphingAnimation animation = createProgressMorphing(mCornerRadius, getHeight(), getWidth(), getHeight()); animation.setFromColor(mColorIdle); animation.setToColor(mColorProgress); animation.setFromStrokeColor(mColorIdle); animation.setToStrokeColor(mColorIndicatorBackground); animation.setListener(mProgressStateListener); animation.start(); } private OnAnimationEndListener mProgressStateListener = new OnAnimationEndListener() { @Override public void onAnimationEnd() { mMorphingInProgress = false; mState = State.PROGRESS; } }; private void morphProgressToComplete() { MorphingAnimation animation = createProgressMorphing(getHeight(), mCornerRadius, getHeight(), getWidth()); animation.setFromColor(mColorProgress); animation.setToColor(mColorComplete); animation.setFromStrokeColor(mColorIndicator); animation.setToStrokeColor(mColorComplete); animation.setListener(mCompleteStateListener); animation.start(); } private void morphIdleToComplete() { MorphingAnimation animation = createMorphing(); animation.setFromColor(mColorIdle); animation.setToColor(mColorComplete); animation.setFromStrokeColor(mColorIdle); animation.setToStrokeColor(mColorComplete); animation.setListener(mCompleteStateListener); animation.start(); } private OnAnimationEndListener mCompleteStateListener = new OnAnimationEndListener() { @Override public void onAnimationEnd() { if (mIconComplete != 0) { setText(null); setIcon(mIconComplete); } else { setText(mCompleteText); } mMorphingInProgress = false; mState = State.COMPLETE; } }; private void morphCompleteToIdle() { MorphingAnimation animation = createMorphing(); animation.setFromColor(mColorComplete); animation.setToColor(mColorIdle); animation.setFromStrokeColor(mColorComplete); animation.setToStrokeColor(mColorIdle); animation.setListener(mIdleStateListener); animation.start(); } private void morphErrorToIdle() { MorphingAnimation animation = createMorphing(); animation.setFromColor(mColorError); animation.setToColor(mColorIdle); animation.setFromStrokeColor(mColorError); animation.setToStrokeColor(mColorIdle); animation.setListener(mIdleStateListener); animation.start(); } private OnAnimationEndListener mIdleStateListener = new OnAnimationEndListener() { @Override public void onAnimationEnd() { removeIcon(); setText(mIdleText); mMorphingInProgress = false; mState = State.IDLE; } }; private void morphIdleToError() { MorphingAnimation animation = createMorphing(); animation.setFromColor(mColorIdle); animation.setToColor(mColorError); animation.setFromStrokeColor(mColorIdle); animation.setToStrokeColor(mColorError); animation.setListener(mErrorStateListener); animation.start(); } private void morphProgressToError() { MorphingAnimation animation = createProgressMorphing(getHeight(), mCornerRadius, getHeight(), getWidth()); animation.setFromColor(mColorProgress); animation.setToColor(mColorError); animation.setFromStrokeColor(mColorIndicator); animation.setToStrokeColor(mColorError); animation.setListener(mErrorStateListener); animation.start(); } private OnAnimationEndListener mErrorStateListener = new OnAnimationEndListener() { @Override public void onAnimationEnd() { if (mIconComplete != 0) { setText(null); setIcon(mIconError); } else { setText(mErrorText); } mMorphingInProgress = false; mState = State.ERROR; } }; private void morphProgressToIdle() { MorphingAnimation animation = createProgressMorphing(getHeight(), mCornerRadius, getHeight(), getWidth()); animation.setFromColor(mColorProgress); animation.setToColor(mColorIdle); animation.setFromStrokeColor(mColorIndicator); animation.setToStrokeColor(mColorIdle); animation.setListener(new OnAnimationEndListener() { @Override public void onAnimationEnd() { removeIcon(); setText(mIdleText); mMorphingInProgress = false; mState = State.IDLE; } }); animation.start(); } private void setIcon(int icon) { Drawable drawable = getResources().getDrawable(icon); if (drawable != null) { int padding = (getWidth() / 2) - (drawable.getIntrinsicWidth() / 2); setCompoundDrawablesWithIntrinsicBounds(icon, 0, 0, 0); setPadding(padding, 0, 0, 0); } } protected void removeIcon() { setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); setPadding(0, 0, 0, 0); } /** * Set the View's background. Masks the API changes made in Jelly Bean. */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") public void setBackgroundCompat(Drawable drawable) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { setBackground(drawable); } else { setBackgroundDrawable(drawable); } } public void setProgress(int progress) { mProgress = progress; if (mMorphingInProgress || getWidth() == 0) { return; } if (mProgress >= mMaxProgress) { if (mState == State.PROGRESS) { morphProgressToComplete(); } else if (mState == State.IDLE) { morphIdleToComplete(); } } else if (mProgress > IDLE_STATE_PROGRESS) { if (mState == State.IDLE) { morphToProgress(); } else if (mState == State.PROGRESS) { invalidate(); } } else if (mProgress == ERROR_STATE_PROGRESS) { if (mState == State.PROGRESS) { morphProgressToError(); } else if (mState == State.IDLE) { morphIdleToError(); } } else if (mProgress == IDLE_STATE_PROGRESS) { if (mState == State.COMPLETE) { morphCompleteToIdle(); } else if (mState == State.PROGRESS) { morphProgressToIdle(); } else if (mState == State.ERROR) { morphErrorToIdle(); } } } public int getProgress() { return mProgress; } public void setBackgroundColor(int color) { background.getGradientDrawable().setColor(color); } public void setStrokeColor(int color) { background.setStrokeColor(color); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (changed) { setProgress(mProgress); } } }
package com.rizki.mufrizal.spring.oauth2.custom.configuration; import com.rizki.mufrizal.spring.oauth2.custom.service.OAuth2AccessTokenService; import com.rizki.mufrizal.spring.oauth2.custom.service.OAuth2CountAccessService; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.web.access.channel.ChannelProcessingFilter; @Configuration public class OAuth2Configuration { private static final String RESOURCE_ID = "customoauth2"; @Configuration @EnableResourceServer protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { @Autowired private OAuth2CountAccessService oAuth2CountAccessService; @Autowired private OAuth2AccessTokenService oAuth2AccessTokenService; @Override public void configure(ResourceServerSecurityConfigurer resourceServerSecurityConfigurer) throws Exception { TokenExtractorConfiguration tokenExtractorConfiguration = new TokenExtractorConfiguration(oAuth2CountAccessService, oAuth2AccessTokenService); resourceServerSecurityConfigurer .resourceId(RESOURCE_ID) .tokenExtractor(tokenExtractorConfiguration); } @Override public void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity .authorizeRequests()
package csum.confluence.permissionmgmt.service.impl; import com.atlassian.confluence.user.UserAccessor; import com.atlassian.crowd.embedded.api.CrowdDirectoryService; import com.atlassian.crowd.embedded.api.CrowdService; import com.atlassian.crowd.embedded.api.Directory; import com.atlassian.crowd.embedded.api.OperationType; import com.atlassian.crowd.embedded.impl.ImmutableUser; import com.atlassian.user.Group; import com.atlassian.user.GroupManager; import com.atlassian.user.User; import com.atlassian.user.UserManager; import com.atlassian.user.impl.DefaultUser; import com.atlassian.user.search.page.Pager; import com.atlassian.user.security.password.Credential; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import java.util.Iterator; import java.util.List; import java.util.Set; public class UserAndGroupManagementService { protected Log log = LogFactory.getLog(this.getClass()); protected CrowdService crowdService; protected CrowdDirectoryService crowdDirectoryService; protected GroupManager groupManager; protected UserAccessor userAccessor; @Autowired public UserAndGroupManagementService(CrowdService crowdService, CrowdDirectoryService crowdDirectoryService, GroupManager groupManager, UserAccessor userAccessor) { this.crowdDirectoryService = crowdDirectoryService; this.crowdService = crowdService; this.groupManager = groupManager; this.userAccessor = userAccessor; if (crowdService==null) { throw new RuntimeException("crowdService was not autowired in UserAndGroupManagementService"); } else if (crowdDirectoryService==null) { throw new RuntimeException("crowdDirectoryService was not autowired in UserAndGroupManagementService"); } else if (groupManager==null) { throw new RuntimeException("groupManager was not autowired in UserAndGroupManagementService"); } else if (userAccessor==null) { throw new RuntimeException("userAccessor was not autowired in UserAndGroupManagementService"); } } public User getUser(String username) { User user = null; try { com.atlassian.crowd.embedded.api.User crowdUser = crowdService.getUser(username); user = userAccessor.getUser(crowdUser.getName()); } catch (Throwable t) { log.error("Problem getting user '" + username + "'", t); } return user; } public boolean isReadOnly(Group group) { if (group == null) { log.warn("Attempted to check isReadOnly on null group. Returning false."); return true; } boolean result = false; try { result = groupManager.isReadOnly(group); } catch (Throwable t) { log.error("Problem checking isReadOnly status of group '" + group.getName() + "'. Will assume isn't read-only.", t); } return result; } // TODO: define directoryId via dropdown in plugin config? private Long findFirstWritableDirectoryId() { List<Directory> directories = crowdDirectoryService.findAllDirectories(); if (log.isDebugEnabled()) { log.debug("Attempting to find a crowd directory that allows user creation. Found " + directories.size() + " directories."); } for (int i=0; i<directories.size(); i++) { Directory directory = directories.get(i); if (directory!=null) { boolean writable = false; Set allowedOperations = directory.getAllowedOperations(); Iterator iter = allowedOperations.iterator(); while(iter.hasNext()) { OperationType operationType = (OperationType)iter.next(); if (operationType == OperationType.CREATE_USER) { writable = true; if (log.isDebugEnabled()) { log.debug("Directory with id " + directory.getId() + " and name " + directory.getName() + " allows user creation."); } return directory.getId(); } else { if (log.isDebugEnabled()) { log.debug("Directory with id " + directory.getId() + " and name " + directory.getName() + " does not allow user creation."); } } } } } log.warn("No crowd directory available currently that allows user creation. Please turn off the ability to create users in the Confluence Space User Management plugin, because there is no way to create users."); return null; } public User addUser(String userName, String email, String fullName) { User user = null; try { user = new DefaultUser(userName, email, fullName); userAccessor.createUser(user, Credential.NONE); if (user == null) { log.warn("userAccessor.createUser for " + userName + " returned null."); } } catch (Throwable t) { log.error("Problem creating user '" + userName + "'", t); } return user; } public Group getGroup(String groupName) { Group group = null; try { group = groupManager.getGroup(groupName); } catch (Throwable t) { log.error("Problem getting group '" + groupName + "'", t); } return group; } public Group addGroup(String groupName) { Group group = null; try { group = groupManager.createGroup(groupName); } catch (Throwable t) { log.error("Problem creating group '" + groupName + "'", t); } return group; } public void removeGroup(Group group) { if (group == null) { log.warn("Attempted to delete null group. Ignoring."); } else { try { groupManager.removeGroup(group); } catch (Throwable t) { log.error("Problem removing group with name '" + group.getName() + "'", t); } } } public Pager getMemberNames(Group group) { Pager pager = null; if (group == null) { log.warn("Attempted to get members of null group. Ignoring."); } else { try { pager = groupManager.getMemberNames(group); } catch (Throwable t) { log.error("Problem getting members of group '" + group.getName() + "'", t); } } return pager; } public void addMembership(Group group, User user) { if (group == null) { log.warn("Attempted to add user to null group. Ignoring."); } else if (user == null) { log.warn("Attempted to add null user to group. Ignoring."); } else { try { groupManager.addMembership(group, user); } catch (Throwable t) { log.error("Problem adding user '" + user.getName() + "' to group '" + group.getName() + "'", t); } } } public void removeMembership(Group group, User user) { if (group == null) { log.warn("Attempted to remove user from null group. Ignoring."); } else if (user == null) { log.warn("Attempted to remove null user from group. Ignoring."); } else { try { groupManager.removeMembership(group, user); } catch (Throwable t) { log.error("Problem removing user '" + user.getName() + "' from group '" + group.getName() + "'", t); } } } }
package dk.statsbiblioteket.newspaper.metadatachecker; import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector; import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.AttributeParsingEvent; import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.NodeBeginsParsingEvent; import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.NodeEndParsingEvent; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.TreeEventHandler; import dk.statsbiblioteket.util.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** Check xml data of known file postfixes against xsd schemas. */ public class SchemaValidatorEventHandler implements TreeEventHandler { /** A map from file postfix to a known schema for that file. */ private static final Map<String, String> POSTFIX_TO_XSD; private static final Map<String, String> POSTFIX_TO_TYPE; private static final Map<String, String> POSTFIX_TO_MESSAGE_PREFIX; static { Map<String, String> postfixToXsd = new HashMap<>(); postfixToXsd.put(".alto.xml", "alto-v2.0.xsd"); postfixToXsd.put(".mix.xml", "mix.xsd"); postfixToXsd.put(".mods.xml", "mods-3-1.xsd"); postfixToXsd.put(".edition.xml", "mods-3-1.xsd"); postfixToXsd.put(".film.xml", "film.xsd"); postfixToXsd.put(".jpylyzer.xml", "jpylyzer.xsd"); POSTFIX_TO_XSD = Collections.unmodifiableMap(postfixToXsd); Map<String, String> postfixToType = new HashMap<>(); postfixToType.put(".alto.xml", "metadata"); postfixToType.put(".mix.xml", "metadata"); postfixToType.put(".mods.xml", "metadata"); postfixToType.put(".edition.xml", "metadata"); postfixToType.put(".film.xml", "metadata"); postfixToType.put(".jpylyzer.xml", "jp2file"); POSTFIX_TO_TYPE = Collections.unmodifiableMap(postfixToType); Map<String, String> postfixToMessagePrefix = new HashMap<>(); postfixToMessagePrefix.put(".alto.xml", "2J: "); postfixToMessagePrefix.put(".mix.xml", "2K: "); postfixToMessagePrefix.put(".mods.xml", "2C: "); postfixToMessagePrefix.put(".edition.xml", "2D: "); postfixToMessagePrefix.put(".film.xml", "2E: "); postfixToMessagePrefix.put(".jpylyzer.xml", "2B: "); POSTFIX_TO_MESSAGE_PREFIX = Collections.unmodifiableMap(postfixToMessagePrefix); } /** Logger */ private final Logger log = LoggerFactory.getLogger(getClass()); /** The result collector results are collected in. */ private final ResultCollector resultCollector; /** A map of parsed schemas for a given schema file name. */ private Map<String, Schema> schemas = new HashMap<>(); /** * Initialise the event handler with the collector to collect results in. * * @param resultCollector The collector to collect results in. */ public SchemaValidatorEventHandler(ResultCollector resultCollector) { log.debug("Initialising {}", getClass().getName()); this.resultCollector = resultCollector; } @Override public void handleNodeBegin(NodeBeginsParsingEvent event) { // Do nothing } @Override public void handleNodeEnd(NodeEndParsingEvent event) { // Do nothing } @Override /** * For each attribute, if this is a known XML file postfix, check the appropriate schema for that XML file. * @event The attribute parsing event that is to be checked. */ public void handleAttribute(AttributeParsingEvent event) { for (Map.Entry<String, String> entry : POSTFIX_TO_XSD.entrySet()) { if (event.getName().endsWith(entry.getKey())) { checkSchema(event, entry.getValue()); break; } } } /** * Given an attribute parsing event and a schema file name, extract the data from the event, and validate it * against * the schema. * * @param event The attribute parsing event containing the data. * @param schemaFile The file name of the schema to check the data against. */ private void checkSchema(AttributeParsingEvent event, String schemaFile) { log.debug("Checking '{}' with schema '{}'", event.getName(), schemaFile); try { InputStream data = event.getData(); DocumentBuilderFactory spf = DocumentBuilderFactory.newInstance(); spf.setSchema(getSchema(schemaFile)); spf.setNamespaceAware(true); DocumentBuilder saxParser = spf.newDocumentBuilder(); saxParser.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { } @Override public void error(SAXParseException exception) throws SAXException { throw exception; } @Override public void fatalError(SAXParseException exception) throws SAXException { throw exception; } }); //TODO put this back in documentCache Document doc = saxParser.parse(data); } catch (SAXParseException e) { resultCollector.addFailure(event.getName(), getType(event.getName()), getClass().getSimpleName(), getMessagePrefix(event.getName()) + "Failure validating XML data: Line " + e.getLineNumber() + " Column " + e.getColumnNumber() + ": " + e .getMessage()); log.debug("Error validating '{}' with schema '{}': Line {} Column {}: {}", event.getName(), schemaFile, e.getLineNumber(), e.getColumnNumber(), e.getMessage(), e); } catch (SAXException e) { resultCollector.addFailure(event.getName(), "exception", getClass().getSimpleName(), getMessagePrefix( event.getName()) + "Failure validating XML data: " + e.toString(), Strings.getStackTrace(e)); log.debug("Error validating '{}' with schema '{}': {}", event.getName(), schemaFile, e.getMessage(), e); } catch (IOException e) { resultCollector.addFailure(event.getName(), "exception", getClass().getSimpleName(), getMessagePrefix(event.getName()) + "Failure reading data: " + e.toString(), Strings.getStackTrace(e)); log.debug("IO error reading '{}' while validating with schema '{}'", event.getName(), schemaFile, e); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); resultCollector.addFailure(event.getName(), "exception", getClass().getSimpleName(), getMessagePrefix(event.getName()) + "Unexpected failure processing data from '" + event.getName() + "': " + e.toString(), sw.toString()); log.error("Unexpected error while validating '{}' with schema '{}'", event.getName(), schemaFile, e); } } private String getType(String name) { for (Map.Entry<String, String> stringStringEntry : POSTFIX_TO_TYPE.entrySet()) { if (name.endsWith(stringStringEntry.getKey())) { return stringStringEntry.getValue(); } } return null; } private String getMessagePrefix(String name) { for (Map.Entry<String, String> stringStringEntry : POSTFIX_TO_MESSAGE_PREFIX.entrySet()) { if (name.endsWith(stringStringEntry.getKey())) { return stringStringEntry.getValue(); } } return ""; } /** * Create a new validator for the schema in the given schema file. Note: Validators are not thread safe! * * @param schemaFile The file name of the schema to get a validator for. * * @return A validator for the given schema. * @throws SAXException If the schema fails to parse. */ private Validator createValidator(String schemaFile) throws SAXException { Schema schema = getSchema(schemaFile); return schema.newValidator(); } /** * Given a schema file name, get a parsed version of the schema from the classpath. Note that parsed schemas are * cached. * * @param schemaFile The filename of the schema. * * @return The parsed schema. * @throws SAXException If the schema fails to parse. */ private synchronized Schema getSchema(String schemaFile) throws SAXException { if (schemas.get(schemaFile) == null) { log.debug("Cache miss for schema file {}", schemaFile); long start = System.currentTimeMillis(); URL schemaUrl = getClass().getClassLoader().getResource(schemaFile); Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaUrl); schemas.put(schemaFile, schema); log.debug("Loaded schema {} in {} ms", schemaFile, System.currentTimeMillis() - start); } return schemas.get(schemaFile); } @Override public void handleFinish() { // Do nothing } }
package org.mtransit.parser.ca_kingston_transit_bus; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.mtransit.parser.CleanUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.MTLog; import org.mtransit.parser.Pair; import org.mtransit.parser.SplitUtils; import org.mtransit.parser.SplitUtils.RouteTripSpec; import org.mtransit.parser.Utils; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.gtfs.data.GTripStop; import org.mtransit.parser.mt.data.MAgency; import org.mtransit.parser.mt.data.MDirectionType; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.mt.data.MTrip; import org.mtransit.parser.mt.data.MTripStop; public class KingstonTransitBusAgencyTools extends DefaultAgencyTools { public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-kingston-transit-bus-android/res/raw/"; args[2] = ""; // files-prefix } new KingstonTransitBusAgencyTools().start(args); } private HashSet<String> serviceIds; @Override public void start(String[] args) { MTLog.log("Generating Kingston Transit bus data..."); long start = System.currentTimeMillis(); this.serviceIds = extractUsefulServiceIds(args, this, true); super.start(args); MTLog.log("Generating Kingston Transit bus data... DONE in %s.", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludingAll() { return this.serviceIds != null && this.serviceIds.isEmpty(); } @Override public boolean excludeCalendar(GCalendar gCalendar) { if (this.serviceIds != null) { return excludeUselessCalendar(gCalendar, this.serviceIds); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { if (this.serviceIds != null) { return excludeUselessCalendarDate(gCalendarDates, this.serviceIds); } return super.excludeCalendarDate(gCalendarDates); } @Override public boolean excludeTrip(GTrip gTrip) { if (gTrip.getTripHeadsign().toLowerCase(Locale.ENGLISH).contains("not in service")) { return true; // exclude } if (this.serviceIds != null) { return excludeUselessTrip(gTrip, this.serviceIds); } return super.excludeTrip(gTrip); } @Override public boolean excludeRoute(GRoute gRoute) { return super.excludeRoute(gRoute); } @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_BUS; } private static final Pattern DIGITS = Pattern.compile("[\\d]+"); private static final String ROUTE_12A_RSN = "12A"; private static final long RID_ENDS_WITH_A = 1_000L; private static final long RID_ENDS_WITH_D = 4_000L; private static final long RID_ENDS_WITH_P = 16_000L; private static final long RID_ENDS_WITH_Q = 17_000L; private static final long RID_ENDS_WITH_W = 23_000L; @Override public long getRouteId(GRoute gRoute) { String routeShortName = gRoute.getRouteShortName(); if (StringUtils.isEmpty(routeShortName)) { routeShortName = gRoute.getRouteId(); } if (Utils.isDigitsOnly(routeShortName)) { return Long.parseLong(routeShortName); } Matcher matcher = DIGITS.matcher(routeShortName); if (matcher.find()) { int digits = Integer.parseInt(matcher.group()); String rsn = routeShortName.toLowerCase(Locale.ENGLISH); if (rsn.endsWith("a")) { return digits + RID_ENDS_WITH_A; } else if (rsn.endsWith("d")) { return digits + RID_ENDS_WITH_D; } else if (rsn.endsWith("p")) { return digits + RID_ENDS_WITH_P; } else if (rsn.endsWith("q")) { return digits + RID_ENDS_WITH_Q; } else if (rsn.endsWith("w")) { return digits + RID_ENDS_WITH_W; } } if ("COV".equals(routeShortName)) { return 99_001L; } throw new MTLog.Fatal("Unexpected route ID for '%s'!", gRoute); } private static final String ROUTE_1 = "St Lawrence College - Montreal St"; private static final String ROUTE_2 = "Kingston Ctr - Division St"; private static final String ROUTE_3 = "Kingston Ctr - Downtown Transfer Point"; private static final String ROUTE_4 = "Downtown Transfer Point - Cataraqui Ctr"; private static final String ROUTE_6 = "St Lawrence College - Cataraqui Ctr"; private static final String ROUTE_7 = "INVISTA Ctr - Division St / Dalton Ave"; private static final String ROUTE_8 = "Route 8"; // TODO private static final String ROUTE_9 = "Brock St / Barrie St - Cataraqui Ctr"; private static final String ROUTE_10 = "Cataraqui Ctr - Amherstview"; private static final String ROUTE_11 = "Kingston Ctr - Cataraqui Ctr"; private static final String ROUTE_12 = "Highway 15 - Kingston Ctr"; private static final String ROUTE_12A = "CFB Kingston - Downtown Transfer Point"; private static final String ROUTE_13 = "Downtown - SLC (Extra Bus)"; // not official private static final String ROUTE_14 = "Crossfield Ave / Waterloo Dr"; private static final String ROUTE_15 = "Reddendale - Cataraqui Woods / Cataraqui Ctr"; private static final String ROUTE_16 = "Bus Terminal - Train Station"; private static final String ROUTE_17 = "Queen's Shuttle / Main Campus - Queen's Shuttle / West Campus"; private static final String ROUTE_18 = "Train Station Circuit"; private static final String ROUTE_19 = "Queen's / Kingston General Hospital - Montreal St P&R"; private static final String ROUTE_20 = "Queen's Shuttle – Isabel / Tett Ctrs"; private static final String ROUTE_501 = "Express (Kingston Ctr - Downtown - Kingston Gen. Hospital - St Lawrence College - Cataraqui Ctr)"; private static final String ROUTE_502 = "Express (St Lawrence College - Kingston Gen. Hospital - Downtown - Kingston Ctr - Cataraqui Ctr)"; private static final String ROUTE_601 = "Innovation Dr P&R – Queen's / KGH"; private static final String ROUTE_602 = "Queen's / KGH – Innovation Dr P&R"; private static final String ROUTE_701 = "King's Crossing Ctr – Cataraqui Ctr"; private static final String ROUTE_702 = "Cataraqui Ctr - King's Crossing Ctr"; private static final String ROUTE_801 = "Montreal St. P&R - Queen's/Kingston Gen. Hospital"; private static final String ROUTE_802 = "Queen's/Kingston Gen. Hospital - Montreal St. P&R"; @Override public String getRouteLongName(GRoute gRoute) { if (StringUtils.isEmpty(gRoute.getRouteLongName())) { if (ROUTE_12A_RSN.equals(gRoute.getRouteShortName())) { return ROUTE_12A; } if ("18Q".equals(gRoute.getRouteShortName())) { return "Queen's Sunday Shuttle"; } if ("COV".equals(gRoute.getRouteShortName())) { return "Cataraqui Ctr"; // not official } Matcher matcher = DIGITS.matcher(gRoute.getRouteId()); if (matcher.find()) { int digits = Integer.parseInt(matcher.group()); switch (digits) { // @formatter:off case 1: return ROUTE_1; case 2: return ROUTE_2; case 3: return ROUTE_3; case 4: return ROUTE_4; case 6: return ROUTE_6; case 7: return ROUTE_7; case 8: return ROUTE_8; case 9: return ROUTE_9; case 10: return ROUTE_10; case 11: return ROUTE_11; case 12: return ROUTE_12; case 13: return ROUTE_13; case 14: return ROUTE_14; case 15: return ROUTE_15; case 16: return ROUTE_16; case 17: return ROUTE_17; case 18: return ROUTE_18; case 19: return ROUTE_19; case 20: return ROUTE_20; case 501: return ROUTE_501; case 502: return ROUTE_502; case 601: return ROUTE_601; case 602: return ROUTE_602; case 701: return ROUTE_701; case 702: return ROUTE_702; case 801: return ROUTE_801; case 802: return ROUTE_802; // @formatter:on } } throw new MTLog.Fatal("Unexpected route long name '%s'!", gRoute); } return super.getRouteLongName(gRoute); } @Override public boolean mergeRouteLongName(MRoute mRoute, MRoute mRouteToMerge) { throw new MTLog.Fatal("Unexpected routes to merge: %s & %s!", mRoute, mRouteToMerge); } private static final String AGENCY_COLOR = "009BC9"; @Override public String getAgencyColor() { return AGENCY_COLOR; } private static final String KINGSTON_GOSPEL_TEMPLE = "Kingston Gospel Temple"; private static final String CATARAQUI_CTR_TRANSFER_PT = "Cataraqui Ctr Transfer Pt"; private static final String MAIN_CAMPUS = "Main Campus"; private static final String WEST_CAMPUS = "West Campus"; private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2; static { HashMap<Long, RouteTripSpec> map2 = new HashMap<Long, RouteTripSpec>(); map2.put(14L, new RouteTripSpec(14L, // Waterloo Dr / Crossfield Ave MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, KINGSTON_GOSPEL_TEMPLE, MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, CATARAQUI_CTR_TRANSFER_PT) .addTripSort(MDirectionType.EAST.intValue(), Arrays.asList(new String[] { "S02084", // Cataraqui Centre Transfer Point Bay 7 "00850", // Centennial Drive "S00399" // Kingston Gospel Temple })) .addTripSort(MDirectionType.WEST.intValue(), Arrays.asList(new String[] { "S00399", // Kingston Gospel Temple "00410", // Centennial Drive "00097", // == Norwest Road "S02079", // Cataraqui Centre Transfer Point Bay 3 "S02084", // Cataraqui Centre Transfer Point Bay 7 })) .compileBothTripSort()); ALL_ROUTE_TRIPS2 = map2; } @Override public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { if (ALL_ROUTE_TRIPS2.containsKey(routeId)) { return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this); } return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop); } @Override public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips(); } return super.splitTrip(mRoute, gTrip, gtfs); } @Override public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this); } return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS); } @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return; // split } if (gTrip.getDirectionId() == null) { if (mRoute.getId() == 1L) { if (Arrays.asList( "Saint Lawrence College" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( "Montreal Street" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 1L + RID_ENDS_WITH_A) { if (Arrays.asList( "Downtown" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( "Montreal Street" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 2L) { if (Arrays.asList( "Kingston Centre" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( "Division Street" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 3L) { if (Arrays.asList( // Downtown "Downtown" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( // Kingston Ctr "Kingston Centre" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 3L + RID_ENDS_WITH_A) { if (Arrays.asList( "Downtown", "Downtown via KGH" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( "Kingston Centre" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 4L) { if (Arrays.asList( // Downtown "Kingston Centre", "Downtown via Princess St" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( // Cataraqui Ctr "Cataraqui Centre via Princess St" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 6L) { if (Arrays.asList( // St Lawrence College "Saint Lawrence College" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( // Cataraqui Ctr "Cataraqui Centre" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 7L) { if (Arrays.asList( // Rideau Hts "Rideau Heights via John Counter Blvd" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( // Invista Ctr "Invista Centre via John Counter Blvd" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 10L) { if (Arrays.asList( // Cataraqui Ctr "Cataraqui Centre" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( // Amherstview "Amherstview" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 11L) { if (Arrays.asList( // Kingston Ctr "Kingston Centre via Bath Road" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( // Cataraqui Ctr "Cataraqui Centre via Bath Road" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 12L) { if (Arrays.asList( // Kingston Ctr "Kingston Centre" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( // Hwy 15 "CFB Kingston via Downtown" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 15L) { if (Arrays.asList( // Cataraqui Woods / Ctr "Cataraqui Centre", "Cataraqui Centre/Cataraqui Woods" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( // Reddendale "Reddendale" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 16L) { if (Arrays.asList( // Train Sta "Bus Terminal", "Train Station via Kingston Centre" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( // Division / Dalton "Division/Dalton via Kingston Centre" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 501L) { if (Arrays.asList( // Downtown "Express - Downtown via Princess St" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( // Cataraqui Ctr "Express - Cataraqui Centre via Front/Bayridge" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 502L) { if (Arrays.asList( // Downtown "Express - Downtown via Bayridge/Front" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( // Cataraqui Ctr "Express - Cataraqui Centre via Princess" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 601L) { if (Arrays.asList( // Queen's / KGH "Express - Queen's/KGH via Downtown" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } } if (mRoute.getId() == 602L) { if (Arrays.asList( // Downtown "Downtown" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } if (Arrays.asList( // Innovation Dr "Express - Innovation Drive" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 1); return; } } if (mRoute.getId() == 701L) { if (Arrays.asList( // Cataraqui Ctr "Express - Cataraqui Centre via Brock/Bath", "Express - Cataraqui Centre via Downtown" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } } if (mRoute.getId() == 702L) { if (Arrays.asList( // King's Crossing "Express - King's Crossing via Division", "Express - King's Crossing via Downtown" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } } if (mRoute.getId() == 801L) { if (Arrays.asList( // Queen's / KGH "Express - Queen's/KGH via Downtown" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } } if (mRoute.getId() == 802L) { if (Arrays.asList( // Montreal St P&R "Express - Montreal Street Park & Ride" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), 0); return; } } throw new MTLog.Fatal("%s: Unexpected trip %s!", mRoute.getId(), gTrip.toStringPlus()); } mTrip.setHeadsignString( cleanTripHeadsign(gTrip.getTripHeadsign()), gTrip.getDirectionId() == null ? 0 : gTrip.getDirectionId() ); } private static final Pattern STARTS_WITH_EXPRESS = Pattern.compile("(^(express -) )*", Pattern.CASE_INSENSITIVE); @Override public String cleanTripHeadsign(String tripHeadsign) { tripHeadsign = STARTS_WITH_EXPRESS.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY); tripHeadsign = CleanUtils.keepToAndRemoveVia(tripHeadsign); tripHeadsign = CleanUtils.SAINT.matcher(tripHeadsign).replaceAll(CleanUtils.SAINT_REPLACEMENT); tripHeadsign = CleanUtils.removePoints(tripHeadsign); tripHeadsign = CleanUtils.cleanSlashes(tripHeadsign); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } @Override public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) { List<String> headsignsValues = Arrays.asList(mTrip.getHeadsignValue(), mTripToMerge.getHeadsignValue()); if (mTrip.getRouteId() == 4L) { if (Arrays.asList( "Kingston Ctr", "Downtown" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Downtown", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 15L) { if (Arrays.asList( "Kingston Ctr", "Reddendale" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Reddendale", mTrip.getHeadsignId()); return true; } else if (Arrays.asList( "Cataraqui Ctr", "Cataraqui Ctr / Cataraqui Woods" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Cataraqui Ctr", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 16L) { if (Arrays.asList( "Bus Terminal", "Train Sta" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Train Sta", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 17L + RID_ENDS_WITH_W) { // 17W if (Arrays.asList( StringUtils.EMPTY, "Queen's Main Campus", "Queen's West Campus" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Queen's West Campus", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 602L) { if (Arrays.asList( "Downtown", "Innovation Dr" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Innovation Dr", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 702L) { if (Arrays.asList( "Downtown", "King's Xing" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("King's Xing", mTrip.getHeadsignId()); return true; } } throw new MTLog.Fatal("Unexpected trips to merge: %s & %s!", mTrip, mTripToMerge); } private static final Pattern SIDE = Pattern.compile("((^|\\W){1}(side)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String SIDE_REPLACEMENT = "$2$4"; private static final Pattern EAST_ = Pattern.compile("((^|\\W){1}(east)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String EAST_REPLACEMENT = "$2E$4"; private static final Pattern WEST_ = Pattern.compile("((^|\\W){1}(west)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String WEST_REPLACEMENT = "$2W$4"; private static final Pattern NORTH_ = Pattern.compile("((^|\\W){1}(north)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String NORTH_REPLACEMENT = "$2N$4"; private static final Pattern SOUTH_ = Pattern.compile("((^|\\W){1}(south)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String SOUTH_REPLACEMENT = "$2S$4"; @Override public String cleanStopName(String gStopName) { gStopName = SIDE.matcher(gStopName).replaceAll(SIDE_REPLACEMENT); gStopName = EAST_.matcher(gStopName).replaceAll(EAST_REPLACEMENT); gStopName = WEST_.matcher(gStopName).replaceAll(WEST_REPLACEMENT); gStopName = NORTH_.matcher(gStopName).replaceAll(NORTH_REPLACEMENT); gStopName = SOUTH_.matcher(gStopName).replaceAll(SOUTH_REPLACEMENT); gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); gStopName = CleanUtils.CLEAN_AND.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT); gStopName = CleanUtils.cleanStreetTypes(gStopName); gStopName = CleanUtils.cleanNumbers(gStopName); gStopName = CleanUtils.removePoints(gStopName); return CleanUtils.cleanLabel(gStopName); } private static final String PLACE_CATC = "place_catc"; private static final String PLACE_CHCA = "place_chca"; private static final String PLACE_DWNP = "place_dwnp"; private static final String PLACE_GRDC = "place_grdc"; private static final String PLACE_KNGC = "place_kngc"; private static final String PLACE_MSPR = "place_mspr"; private static final String PLACE_RAIL = "place_rail"; @Override public String getStopCode(GStop gStop) { return gStop.getStopId(); // using stop ID as stop code (useful to match with GTFS real-time) } @Override public int getStopId(GStop gStop) { String stopId = gStop.getStopId(); if (stopId != null && stopId.length() > 0 && Utils.isDigitsOnly(stopId)) { return Integer.valueOf(stopId); // using stop code as stop ID } if (PLACE_CATC.equals(stopId)) { return 900000; } else if (PLACE_CHCA.equals(stopId)) { return 910000; } else if (PLACE_DWNP.equals(stopId)) { return 920000; } else if (PLACE_GRDC.equals(stopId)) { return 930000; } else if (PLACE_KNGC.equals(stopId)) { return 940000; } else if (PLACE_MSPR.equals(stopId)) { return 950000; } else if (PLACE_RAIL.equals(stopId)) { return 960000; } if ("Smspr1".equals(stopId)) { return 970000; } try { Matcher matcher = DIGITS.matcher(stopId); if (matcher.find()) { int digits = Integer.parseInt(matcher.group()); if (stopId.startsWith("S")) { return 190000 + digits; } throw new MTLog.Fatal("Unexpected stop ID for '%s'!", gStop); } } catch (Exception e) { throw new MTLog.Fatal(e, "Error while finding stop ID for '%s'!", gStop); } throw new MTLog.Fatal("Unexpected stop ID for '%s'!", gStop); } }
package org.mozilla.sync.sync; import android.support.annotation.WorkerThread; import android.util.Log; import ch.boye.httpclientandroidlib.HttpResponse; import org.mozilla.gecko.sync.repositories.domain.BookmarkRecordFactory; import org.mozilla.sync.FirefoxSyncException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Gets the bookmarks for the associated account from Firefox Sync. */ class FirefoxSyncBookmarks { private static final String BOOKMARKS_COLLECTION = "bookmarks"; private FirefoxSyncBookmarks() {} /** * Gets the bookmarks associated with the given account. * * Both the request and the callback occur on the calling thread (this is unintuitive: issue #3). * * @param itemLimit The number of items to fetch. If < 0, fetches all items. */ @WorkerThread // network request. static void getBlocking(final FirefoxSyncConfig syncConfig, final int itemLimit, final OnSyncComplete<BookmarkFolder> onComplete) { final SyncClientBookmarksResourceDelegate resourceDelegate = new SyncClientBookmarksResourceDelegate(syncConfig, onComplete); try { FirefoxSyncUtils.makeGetRequestForCollection(syncConfig, BOOKMARKS_COLLECTION, getArgs(itemLimit), resourceDelegate); } catch (final FirefoxSyncException e) { onComplete.onException(e); } } private static Map<String, String> getArgs(final int itemLimit) { if (itemLimit < 0) { return null; } // Fetch all items if < 0. final Map<String, String> args = new HashMap<>(1); args.put("limit", String.valueOf(itemLimit)); return args; } private static class SyncClientBookmarksResourceDelegate extends SyncBaseResourceDelegate<BookmarkFolder> { SyncClientBookmarksResourceDelegate(final FirefoxSyncConfig syncConfig, final OnSyncComplete<BookmarkFolder> onComplete) { super(syncConfig, onComplete); } @Override public void handleResponse(final HttpResponse response, final String responseBody) { final List<org.mozilla.gecko.sync.repositories.domain.BookmarkRecord> rawRecords; try { rawRecords = responseBodyToRawRecords(syncConfig, responseBody, BOOKMARKS_COLLECTION, new BookmarkRecordFactory()); } catch (final FirefoxSyncException e) { onComplete.onException(e); return; } final BookmarkFolder rootBookmarkFolder = rawRecordsToBookmarksTree(rawRecords); onComplete.onSuccess(new SyncCollectionResult<>(rootBookmarkFolder)); } private static BookmarkFolder rawRecordsToBookmarksTree(final List<org.mozilla.gecko.sync.repositories.domain.BookmarkRecord> rawRecords) { // Iterating over these a second time is inefficient (the first time creates the raw records list), but it // makes for cleaner code: fix if there are perf issues. // This would be less error-prone if we did the immutable, recursive solution but we run the // risk of hitting a StackOverflowException. There are some work-arounds (Visitor pattern?) // but they're probably not worth the complexity. // Note: we don't handle the case that bookmarks are corrupted or we retrieved a partial bookmarks list. final Map<String, BookmarkRecord> idToSeenBookmarks = new HashMap<>(rawRecords.size()); // Let's assume they'll mostly be bookmarks. final Map<String, BookmarkFolder> idToSeenFolders = new HashMap<>(); for (final org.mozilla.gecko.sync.repositories.domain.BookmarkRecord rawRecord : rawRecords) { if (rawRecord.isFolder()) { final BookmarkFolder folder = new BookmarkFolder(rawRecord); mutateSeenBookmarkItems(folder, idToSeenBookmarks, idToSeenFolders); idToSeenFolders.put(rawRecord.guid, folder); } else if (rawRecord.isBookmark()) { final BookmarkRecord bookmark = new BookmarkRecord(rawRecord); mutateSeenBookmarkItems(bookmark, idToSeenFolders); idToSeenBookmarks.put(rawRecord.guid, bookmark); } else if (rawRecord.isQuery() || rawRecord.isSeparator() || rawRecord.isLivemark() || rawRecord.isMicrosummary()) { // Do nothing. } else { Log.w(LOGTAG, "Ignoring unknown bookmark raw record type: " + rawRecord.type); } } return createRootBookmarkFolder(idToSeenBookmarks, idToSeenFolders); } private static void mutateSeenBookmarkItems(final BookmarkFolder folder, final Map<String, BookmarkRecord> idToSeenBookmarks, final Map<String, BookmarkFolder> idToSeenFolders) { final BookmarkFolder parentFolder = idToSeenFolders.get(folder.underlyingRecord.parentID); if (parentFolder != null) { folder.parentFolder = parentFolder; parentFolder.getSubfolders().add(folder); } for (final Object childIDObj : folder.underlyingRecord.children) { if (!(childIDObj instanceof String)) { Log.w(LOGTAG, "Ignoring child ID obj of unknown type."); continue; } final String childID = (String) childIDObj; final BookmarkRecord childRecord = idToSeenBookmarks.get(childID); if (childRecord != null) { folder.getBookmarks().add(childRecord); childRecord.parentFolder = folder; } } } private static void mutateSeenBookmarkItems(final BookmarkRecord bookmark, final Map<String, BookmarkFolder> idToSeenFolders) { final BookmarkFolder parentFolder = idToSeenFolders.get(bookmark.underlyingRecord.parentID); if (parentFolder != null) { bookmark.parentFolder = parentFolder; parentFolder.getBookmarks().add(bookmark); } } private static BookmarkFolder createRootBookmarkFolder(final Map<String, BookmarkRecord> idToSeenBookmarks, final Map<String, BookmarkFolder> idToSeenFolders) { // Fetched bookmarks can be orphaned from corruption or because the user specified some number of bookmarks // to fetch. When we see an orphan, we add it to the root folder. This is problematic because it does not // accurately represent the user's bookmarks and the hierarchy can change across invocations but this was // simplest to implement now and easiest to change later (issue final BookmarkFolder rootFolder = BookmarkFolder.createRootFolder(); for (final BookmarkRecord bookmark : idToSeenBookmarks.values()) { if (bookmark.underlyingRecord.parentID.equals(BookmarkFolder.ROOT_FOLDER_GUID) || bookmark.getParentFolder() == null) { // orphan. rootFolder.getBookmarks().add(bookmark); } } for (final BookmarkFolder folder : idToSeenFolders.values()) { if (folder.underlyingRecord.parentID.equals(BookmarkFolder.ROOT_FOLDER_GUID) || folder.getParentFolder() == null) { // orphan. rootFolder.getSubfolders().add(folder); } } return rootFolder; } } }
package org.mtransit.parser.ca_oakville_transit_bus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mtransit.parser.CleanUtils; import org.mtransit.parser.ColorUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.MTLog; import org.mtransit.parser.StringUtils; import org.mtransit.parser.Utils; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.mt.data.MAgency; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.mt.data.MTrip; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.mtransit.parser.StringUtils.EMPTY; public class OakvilleTransitBusAgencyTools extends DefaultAgencyTools { public static void main(@Nullable String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-oakville-transit-bus-android/res/raw/"; args[2] = ""; // files-prefix } new OakvilleTransitBusAgencyTools().start(args); } @Nullable private HashSet<Integer> serviceIdInts; @Override public void start(@NotNull String[] args) { MTLog.log("Generating Oakville Transit bus data..."); long start = System.currentTimeMillis(); this.serviceIdInts = extractUsefulServiceIdInts(args, this, true); super.start(args); MTLog.log("Generating Oakville Transit bus data... DONE in %s.", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludingAll() { return this.serviceIdInts != null && this.serviceIdInts.isEmpty(); } @Override public boolean excludeCalendar(@NotNull GCalendar gCalendar) { if (this.serviceIdInts != null) { return excludeUselessCalendarInt(gCalendar, this.serviceIdInts); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(@NotNull GCalendarDate gCalendarDates) { if (this.serviceIdInts != null) { return excludeUselessCalendarDateInt(gCalendarDates, this.serviceIdInts); } return super.excludeCalendarDate(gCalendarDates); } @Override public boolean excludeTrip(@NotNull GTrip gTrip) { if (this.serviceIdInts != null) { return excludeUselessTripInt(gTrip, this.serviceIdInts); } return super.excludeTrip(gTrip); } @NotNull @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_BUS; } @NotNull @Override public String getRouteLongName(@NotNull GRoute gRoute) { return CleanUtils.cleanLabel(gRoute.getRouteLongNameOrDefault().toLowerCase(Locale.ENGLISH)); } private static final String AGENCY_COLOR = "DCA122"; // GOLD (AGENCY LOGO SVG WIKIPEDIA) @NotNull @Override public String getAgencyColor() { return AGENCY_COLOR; } private static final Pattern DIGITS = Pattern.compile("[\\d]+"); private static final long RID_ENDS_WITH_A = 1_000L; private static final long RID_ENDS_WITH_B = 2_000L; private static final long RID_ENDS_WITH_E = 5_000L; private static final long RID_ENDS_WITH_N = 14_000L; private static final long RID_ENDS_WITH_S = 19_000L; private static final long RID_ENDS_WITH_W = 23_000L; @Override public long getRouteId(@NotNull GRoute gRoute) { //noinspection deprecation final String routeId = gRoute.getRouteId(); if (Utils.isDigitsOnly(routeId)) { return Long.parseLong(routeId); } Matcher matcher = DIGITS.matcher(routeId); if (matcher.find()) { long digits = Long.parseLong(matcher.group()); String routeIdLC = routeId.toLowerCase(Locale.ENGLISH); if (routeIdLC.endsWith("a")) { return RID_ENDS_WITH_A + digits; } else if (routeIdLC.endsWith("b")) { return RID_ENDS_WITH_B + digits; } else if (routeIdLC.endsWith("e")) { return RID_ENDS_WITH_E + digits; } else if (routeIdLC.endsWith("n")) { return RID_ENDS_WITH_N + digits; } else if (routeIdLC.endsWith("s")) { return RID_ENDS_WITH_S + digits; } else if (routeIdLC.endsWith("w")) { return RID_ENDS_WITH_W + digits; } } throw new MTLog.Fatal("Unexpected route ID for %s!", gRoute); } private static final String COLOR_SCHOOL_SPECIALS = "00529B"; // blue (not official) private static final String COLOR_SENIOR_SPECIALS = "5B6162"; // dark grey (not official) @SuppressWarnings("DuplicateBranchesInSwitch") @Nullable @Override public String getRouteColor(@NotNull GRoute gRoute) { String routeColor = gRoute.getRouteColor(); if (ColorUtils.WHITE.equalsIgnoreCase(routeColor)) { routeColor = null; // can't be white } if (StringUtils.isEmpty(routeColor)) { int routeId = (int) getRouteId(gRoute); switch (routeId) { // @formatter:off case 1: return "DE242C"; case 2: return "7F1C7D"; case 3: return "4D368A"; case 4: return "8A5032"; case 5: return "AD4D45"; case 5 + (int) RID_ENDS_WITH_A: return "AD4D45"; case 6: return "F05B72"; case 10: return "1C4E9D"; case 11: return "201B18"; case 12: return "365981"; case 13: return "2EA983"; case 14: return "00A7D8"; case 14 + (int) RID_ENDS_WITH_A: return "00A7D8"; // 14A case 15: return "EE3429"; case 17: return "1B6A4D"; case 18: return "333300"; case 19: return "A3238E"; case 20: return "00B5DA"; case 21: return "333300"; case 22: return "333300"; case 24: return "8CBA40"; case 25: return "333300"; case 26: return "B479A6"; case 28: return "CA7A2F"; case 32: return "9DC73E"; case 33: return "8F2E68"; case 34: return "CAAD35"; case 54: return null; // TODO case 55: return null; // TODO case 71: return COLOR_SCHOOL_SPECIALS; case 80: return COLOR_SCHOOL_SPECIALS; case 80 + (int) RID_ENDS_WITH_E: return COLOR_SCHOOL_SPECIALS; // 80E case 80 + (int) RID_ENDS_WITH_W: return COLOR_SCHOOL_SPECIALS; // 80W case 81: return COLOR_SCHOOL_SPECIALS; case 81 + (int) RID_ENDS_WITH_A: return COLOR_SCHOOL_SPECIALS; // 81A case 81 + (int) RID_ENDS_WITH_B: return COLOR_SCHOOL_SPECIALS; // 81B case 81 + (int) RID_ENDS_WITH_N: return COLOR_SCHOOL_SPECIALS; // 81N case 81 + (int) RID_ENDS_WITH_S: return COLOR_SCHOOL_SPECIALS; // 81S case 82: return COLOR_SCHOOL_SPECIALS; case 83: return COLOR_SCHOOL_SPECIALS; case 84: return COLOR_SCHOOL_SPECIALS; case 86: return COLOR_SCHOOL_SPECIALS; case 86 + (int) RID_ENDS_WITH_B: return COLOR_SCHOOL_SPECIALS; // 86B case 90: return COLOR_SENIOR_SPECIALS; case 91: return COLOR_SENIOR_SPECIALS; case 92: return COLOR_SENIOR_SPECIALS; case 102: return "221E1F"; case 120: return "DF241A"; case 121: return null; // TODO case 190: return "DB214C"; // @formatter:on default: throw new MTLog.Fatal("Unexpected route color for %s!", gRoute); } } return routeColor; } @Override public void setTripHeadsign(@NotNull MRoute mRoute, @NotNull MTrip mTrip, @NotNull GTrip gTrip, @NotNull GSpec gtfs) { if (mRoute.getId() == 81L + RID_ENDS_WITH_N) { // 81N if (gTrip.getDirectionIdOrDefault() == 1) { // FIXES 2 directions with same ID if ("Bronte and Richview".equals(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsignWithoutRealTime(gTrip.getTripHeadsign()), 0); return; } else if ("Loyola and Abbey Park".equals(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsignWithoutRealTime(gTrip.getTripHeadsign()), 1); return; } throw new MTLog.Fatal("Unexpected trip head-sign for %s!", gTrip.toStringPlus()); } } mTrip.setHeadsignString( cleanTripHeadsignWithoutRealTime(gTrip.getTripHeadsign()), gTrip.getDirectionIdOrDefault() ); } @Override public boolean mergeHeadsign(@NotNull MTrip mTrip, @NotNull MTrip mTripToMerge) { List<String> headsignsValues = Arrays.asList(mTrip.getHeadsignValue(), mTripToMerge.getHeadsignValue()); if (mTrip.getRouteId() == 4L) { if (Arrays.asList( "W - Oakville GO", "W - Bronte GO" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("W - Bronte GO", mTrip.getHeadsignId()); return true; } if (Arrays.asList( "E - Oakville GO", "E - Clarkson GO" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("E - Clarkson GO", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 5L) { if (Arrays.asList( "Hosp", "Uptown Core", "Dundas / 407 Carpool" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Dundas / 407 Carpool", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 6L) { if (Arrays.asList( "Oakville GO", "Bronte GO" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Bronte GO", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 14L + RID_ENDS_WITH_A) { // 14A if (Arrays.asList( "Burloak & Rebecca", "Appleby GO" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Appleby GO", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 34L) { if (Arrays.asList( "Bronte GO", "Pine Gln" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Pine Gln", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 81L + RID_ENDS_WITH_N) { // 81N if (Arrays.asList( "Bronte & Richview", "Loyola & Abbey Pk", "Abbey Pk" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Abbey Pk", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 90L) { if (Arrays.asList( "17 Stewart St.", "Stewart St.", "John R. Rhodes" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("John R. Rhodes", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 121L) { if (Arrays.asList( "Industry & South Service", "Southeast Industrial / Oakville GO" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Southeast Industrial / Oakville GO", mTrip.getHeadsignId()); return true; } } throw new MTLog.Fatal("Unexpected trips to merge %s & %s!", mTrip, mTripToMerge); } private static final Pattern STARTS_WITH_RSN = Pattern.compile("(^[\\d]+ )", Pattern.CASE_INSENSITIVE); private static final Pattern ENDS_WITH_ONLY = Pattern.compile("( only$)", Pattern.CASE_INSENSITIVE); private String cleanTripHeadsignWithoutRealTime(String tripHeadsign) { tripHeadsign = CleanUtils.toLowerCaseUpperCaseWords(Locale.ENGLISH, tripHeadsign, getIgnoredWords()); tripHeadsign = CleanUtils.keepToAndRemoveVia(tripHeadsign); tripHeadsign = STARTS_WITH_RSN.matcher(tripHeadsign).replaceAll(EMPTY); tripHeadsign = ENDS_WITH_ONLY.matcher(tripHeadsign).replaceAll(EMPTY); tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT); tripHeadsign = CleanUtils.cleanSlashes(tripHeadsign); tripHeadsign = CleanUtils.cleanBounds(tripHeadsign); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } // trip head signs used for real-time API @NotNull @Override public String cleanTripHeadsign(@NotNull String tripHeadsign) { return CleanUtils.cleanLabel(tripHeadsign); } private String[] getIgnoredWords() { return new String[]{ "GO", "OTMH", "YMCA", }; } @NotNull @Override public String cleanStopName(@NotNull String gStopName) { gStopName = CleanUtils.toLowerCaseUpperCaseWords(Locale.ENGLISH, gStopName, getIgnoredWords()); gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); gStopName = CleanUtils.CLEAN_AND.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT); gStopName = CleanUtils.cleanBounds(gStopName); gStopName = CleanUtils.cleanStreetTypes(gStopName); gStopName = CleanUtils.cleanNumbers(gStopName); return CleanUtils.cleanLabel(gStopName); } @Override public int getStopId(@NotNull GStop gStop) { return Integer.parseInt(gStop.getStopCode()); // use stop code as stop ID } }
// EventService.java package imagej.event; import imagej.AbstractService; import imagej.ImageJ; import imagej.Service; import java.util.List; import org.bushe.swing.event.SwingEventService; /** * Service for publishing and subscribing to ImageJ events. * * @author Curtis Rueden * @author Grant Harris */ @Service public final class EventService extends AbstractService { private org.bushe.swing.event.EventService eventBus; // -- Constructors -- public EventService() { // NB: Required by SezPoz. super(null); throw new UnsupportedOperationException(); } public EventService(final ImageJ context) { super(context); } // -- EventService methods -- public <E extends ImageJEvent> void publish(final E e) { e.setContext(getContext()); eventBus.publish(e); } public <E extends ImageJEvent> void subscribe(final Class<E> c, final EventSubscriber<E> subscriber) { eventBus.subscribe(c, subscriber); } public <E extends ImageJEvent> void subscribeStrongly(final Class<E> c, final EventSubscriber<E> subscriber) { eventBus.subscribeStrongly(c, subscriber); } public <E extends ImageJEvent> void unsubscribe(final Class<E> c, final EventSubscriber<E> subscriber) { eventBus.unsubscribe(c, subscriber); } public <E extends ImageJEvent> List<EventSubscriber<E>> getSubscribers( final Class<E> c) { // HACK - It appears that EventBus API is incorrect, in that // EventBus#getSubscribers(Class<T>) returns a List<T> when it should // actually be a List<EventSubscriber<T>>. This method works around the // problem with casts. @SuppressWarnings("rawtypes") final List list = eventBus.getSubscribers(c); @SuppressWarnings("unchecked") final List<EventSubscriber<E>> typedList = list; return typedList; } // -- IService methods -- @Override public void initialize() { // TODO - Use ThreadSafeEventService instead of SwingEventService. // Unfortunately, without further care elsewhere in the code (subject to // further investigation), using it results in a race condition where // JHotDraw partially repaints images before they are done being processed. // See ticket eventBus = new SwingEventService(); } }
package org.whitesource.agent.dependency.resolver.gradle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.whitesource.agent.Constants; import org.whitesource.agent.api.model.AgentProjectInfo; import org.whitesource.agent.api.model.Coordinates; import org.whitesource.agent.api.model.DependencyInfo; import org.whitesource.agent.api.model.DependencyType; import org.whitesource.agent.dependency.resolver.AbstractDependencyResolver; import org.whitesource.agent.dependency.resolver.ResolutionResult; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; public class GradleDependencyResolver extends AbstractDependencyResolver { private static final String BUILD_GRADLE = "**/*build.gradle"; private static final List<String> GRADLE_SCRIPT_EXTENSION = Arrays.asList(".gradle",".groovy", ".java", ".jar", ".war", ".ear", ".car", ".class"); private static final String JAR_EXTENSION = ".jar"; private static final String SETTINGS_GRADLE = "settings.gradle"; protected static final String COMMENT_START = "/*"; protected static final String COMMENT_END = "*/"; private GradleLinesParser gradleLinesParser; private GradleCli gradleCli; private ArrayList<String> topLevelFoldersNames; private boolean dependenciesOnly; private boolean gradleAggregateModules; private final Logger logger = LoggerFactory.getLogger(GradleDependencyResolver.class); public GradleDependencyResolver(boolean runAssembleCommand, boolean dependenciesOnly, boolean gradleAggregateModules){ super(); gradleLinesParser = new GradleLinesParser(runAssembleCommand); gradleCli = new GradleCli(); topLevelFoldersNames = new ArrayList<>(); this.dependenciesOnly = dependenciesOnly; this.gradleAggregateModules = gradleAggregateModules; } @Override protected ResolutionResult resolveDependencies(String projectFolder, String topLevelFolder, Set<String> bomFiles) { // each bom-file ( = build.gradle) represents a module - identify its folder and scan it using 'gradle dependencies' Collection<AgentProjectInfo> projects = new ArrayList<>(); String settingsFileContent = null; ArrayList<Integer[]> commentBlocks = null; if (bomFiles.size() > 1){ settingsFileContent = readSettingsFile(topLevelFolder); commentBlocks = findCommentBlocksInSettingsFile(settingsFileContent); } for (String bomFile : bomFiles){ String bomFileFolder = new File(bomFile).getParent(); File bomFolder = new File(new File(bomFile).getParent()); String moduleName = bomFolder.getName(); // making sure the module's folder is found inside the settings.gradle file if (settingsFileContent != null && !validateModule(moduleName, settingsFileContent, commentBlocks)){ continue; } List<DependencyInfo> dependencies = collectDependencies(bomFileFolder); if (dependencies.size() > 0) { AgentProjectInfo agentProjectInfo = new AgentProjectInfo(); agentProjectInfo.getDependencies().addAll(dependencies); if (!gradleAggregateModules) { Coordinates coordinates = new Coordinates(); coordinates.setArtifactId(moduleName); agentProjectInfo.setCoordinates(coordinates); } projects.add(agentProjectInfo); } } topLevelFoldersNames.add(topLevelFolder.substring(topLevelFolder.lastIndexOf(fileSeparator) + 1)); Collection<String> excludes = getExcludes(); Map<AgentProjectInfo, Path> projectInfoPathMap = projects.stream().collect(Collectors.toMap(projectInfo -> projectInfo, projectInfo -> { if (dependenciesOnly) { excludes.addAll(normalizeLocalPath(projectFolder, topLevelFolder, GRADLE_SCRIPT_EXTENSION, null)); } return Paths.get(topLevelFolder); })); ResolutionResult resolutionResult; if (!gradleAggregateModules) { resolutionResult = new ResolutionResult(projectInfoPathMap, excludes, getDependencyType(), topLevelFolder); } else { resolutionResult = new ResolutionResult(projectInfoPathMap.keySet().stream() .flatMap(project -> project.getDependencies().stream()).collect(Collectors.toList()), excludes, getDependencyType(), topLevelFolder); } return resolutionResult; } @Override protected Collection<String> getExcludes() { Set<String> excludes = new HashSet<>(); for (String topLeverFolderName : topLevelFoldersNames) { excludes.add(GLOB_PATTERN + topLeverFolderName + JAR_EXTENSION); } return excludes; } @Override public Collection<String> getSourceFileExtensions() { return GRADLE_SCRIPT_EXTENSION; } @Override protected DependencyType getDependencyType() { return DependencyType.GRADLE; } @Override protected String getDependencyTypeName() { return DependencyType.GRADLE.name(); } @Override protected String[] getBomPattern() { return new String[]{BUILD_GRADLE}; } @Override protected Collection<String> getLanguageExcludes() { return null; } private String readSettingsFile(String folder){ String content = ""; File settingsFile = new File(folder + fileSeparator + SETTINGS_GRADLE); if (settingsFile.isFile()){ try { content = new String(Files.readAllBytes(Paths.get(settingsFile.getPath()))); } catch (IOException e) { logger.warn("could not read settings file {} - {}", settingsFile.getPath(), e.getMessage()); logger.debug("stacktrace {}", e.getStackTrace()); } } return content; } private ArrayList<Integer[]> findCommentBlocksInSettingsFile(String content){ ArrayList<Integer[]> commentBlock = new ArrayList<>(); int startIndex = content.indexOf(COMMENT_START); int endIndex; while (startIndex > -1){ endIndex = content.indexOf(COMMENT_END, startIndex); commentBlock.add(new Integer[]{startIndex, endIndex}); startIndex = content.indexOf(COMMENT_START, endIndex); } return commentBlock; } /* valid modules are proceeded by ' or " or :, and followed by ' or ", and also not proceeded (in the same line) by = also - making sure the line isn't commented out //include 'echoserver' include 'client' rootProject.name = 'multi-project-gradle' only the second line is valid also - making sure the module isn't inside comment block */ private boolean validateModule(String moduleName, String settings, ArrayList<Integer[]> commentBlocks){ if (settings != null && settings.contains(moduleName)){ int startIndex = settings.indexOf(moduleName); char proceedingChar = settings.charAt(startIndex - 1); if (proceedingChar == Constants.QUOTATION_MARK.charAt(0) || proceedingChar == Constants.APOSTROPHE.charAt(0) || proceedingChar == Constants.COLON.charAt(0)){ int endIndex = startIndex + moduleName.length(); char followingChar = settings.charAt(endIndex); if (followingChar == Constants.QUOTATION_MARK.charAt(0) || followingChar == Constants.APOSTROPHE.charAt(0)){ while (settings.charAt(startIndex) != '\r' && startIndex > 0){ startIndex if (settings.charAt(startIndex) == Constants.EQUALS_CHAR){ return false; } // making sure there are no // before the module nams if (settings.charAt(startIndex) == Constants.FORWARD_SLASH.charAt(0) && startIndex > 0 && settings.charAt(startIndex-1) == Constants.FORWARD_SLASH.charAt(0)){ return false; } } // making sure the module isn't inside comment block if (commentBlocks != null) { for (Integer[] commentBlock : commentBlocks) { if (settings.indexOf(moduleName) > commentBlock[0] && endIndex < commentBlock[1]) { return false; } } } return true; } } } return false; } private List<DependencyInfo> collectDependencies(String rootDirectory) { List<DependencyInfo> dependencyInfos = new ArrayList<>(); List<String> lines = gradleCli.runGradleCmd(rootDirectory, gradleCli.getGradleCommandParams(MvnCommand.DEPENDENCIES)); if (lines != null) { dependencyInfos.addAll(gradleLinesParser.parseLines(lines, rootDirectory)); } return dependencyInfos; } }
package se.sics.cooja; import java.awt.Dimension; import java.awt.Point; import java.io.*; import java.util.*; import javax.swing.JInternalFrame; import org.apache.log4j.Logger; import org.jdom.*; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import se.sics.cooja.dialogs.*; /** * A simulation contains motes and ticks them one by one. When all motes has * been ticked once, the simulation sleeps for some specified time, and the * current simulation time is updated. Some observers (tick observers) are also * notified. * * When observing the simulation itself, the simulation state, added or deleted * motes etc are observed, as opposed to individual mote changes. Changes of * individual motes should instead be observed via corresponding mote * interfaces. * * @author Fredrik Osterlind */ public class Simulation extends Observable implements Runnable { private Vector<Mote> motes = new Vector<Mote>(); private Vector<MoteType> moteTypes = new Vector<MoteType>(); private int delayTime = 100; private int currentSimulationTime = 0; private int tickTime = 1; private String title = null; // Radio Medium private RadioMedium currentRadioMedium = null; private static Logger logger = Logger.getLogger(Simulation.class); private boolean isRunning = false; private boolean stopSimulation = false; private Thread thread = null; // Tick observable private class TickObservable extends Observable { private void allTicksPerformed() { setChanged(); notifyObservers(); } } private TickObservable tickObservable = new TickObservable(); /** * Add tick observer. This observer is notified once every tick loop, that is, * when all motes have been ticked. * * @see #deleteTickObserver(Observer) * @param newObserver * New observer */ public void addTickObserver(Observer newObserver) { tickObservable.addObserver(newObserver); } /** * Delete an existing tick observer. * * @see #addTickObserver(Observer) * @param observer * Observer to delete */ public void deleteTickObserver(Observer observer) { tickObservable.deleteObserver(observer); } public void run() { long lastStartTime = System.currentTimeMillis(); logger.info("Simulation main loop started, system time: " + lastStartTime); isRunning = true; // Notify observers simulation is starting this.setChanged(); this.notifyObservers(this); while (isRunning) { try { // Tick all motes for (Mote moteToTick : motes) { moteToTick.tick(currentSimulationTime); } // Increase simulation time currentSimulationTime += tickTime; // Notify tick observers tickObservable.allTicksPerformed(); // Sleep if (delayTime > 0) Thread.sleep(delayTime); if (stopSimulation) { // We should only tick once (and we just did), so abort now stopSimulation = false; isRunning = false; thread = null; } } catch (InterruptedException e) { isRunning = false; thread = null; break; } catch (IllegalArgumentException e) { logger.warn("llegalArgumentException:" + e); isRunning = false; thread = null; break; } catch (IllegalMonitorStateException e) { logger.warn("IllegalMonitorStateException:" + e); isRunning = false; thread = null; break; } } isRunning = false; thread = null; stopSimulation = false; // Notify observers simulation has stopped this.setChanged(); this.notifyObservers(this); logger.info("Simulation main loop stopped, system time: " + System.currentTimeMillis() + "\tDuration: " + (System.currentTimeMillis() - lastStartTime) + " ms"); } /** * Creates a new simulation with a delay time of 1 second. */ public Simulation() { // New simulation instance } /** * Starts this simulation (notifies observers). */ public void startSimulation() { if (!isRunning()) { thread = new Thread(this); thread.start(); } } /** * Stops this simulation (notifies observers). */ public void stopSimulation() { if (isRunning()) { stopSimulation = true; thread.interrupt(); // Wait until simulation stops if (Thread.currentThread() != thread) while (thread != null && thread.isAlive()) { try { Thread.sleep(10); } catch (InterruptedException e) { } } } // else logger.fatal("Could not stop simulation: isRunning=" + isRunning + // ", thread=" + thread); } /** * Starts simulation if stopped, ticks all motes once, and finally stop * simulation again. */ public void tickSimulation() { stopSimulation = true; if (!isRunning()) { thread = new Thread(this); thread.start(); } // Wait until simulation stops while (thread != null && thread.isAlive()) { try { Thread.sleep(10); } catch (InterruptedException e) { } } } /** * Loads a simulation configuration from given file. * * When loading mote types, user must recompile the actual library of each * type. User may also change mote type settings at this point. * * @see #saveSimulationConfig(File) * @param file * File to read * @return New simulation or null if recompiling failed or aborted * @throws UnsatisfiedLinkError * If associated libraries could not be loaded */ public static Simulation loadSimulationConfig(File file) throws UnsatisfiedLinkError { Simulation newSim = null; try { // Open config file SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(file); Element root = doc.getRootElement(); // Check that config file version is correct if (!root.getName().equals("simulation")) { logger.fatal("Not a COOJA simulation config xml file!"); return null; } // Build new simulation Collection<Element> config = root.getChildren(); newSim = new Simulation(); boolean createdOK = newSim.setConfigXML(config); if (!createdOK) { logger.info("Simulation not loaded"); return null; } // EXPERIMENTAL: Reload stored plugins boolean loadedPlugin = false; for (Element pluginElement: config.toArray(new Element[0])) { if (pluginElement.getName().equals("visplugin")) { Class<? extends VisPlugin> visPluginClass = GUI.currentGUI.tryLoadClass(GUI.currentGUI, VisPlugin.class, pluginElement.getText().trim()); try { VisPlugin openedPlugin = null; List list = pluginElement.getChildren(); Dimension size = new Dimension(100, 100); Point location = new Point(100, 100); for (Element pluginSubElement: (List<Element>) pluginElement.getChildren()) { if (pluginSubElement.getName().equals("constructor")) { if (pluginSubElement.getText().equals("sim")) { // Simulator plugin type openedPlugin = visPluginClass.getConstructor(new Class[]{Simulation.class}).newInstance(newSim); GUI.currentGUI.showPlugin(openedPlugin); } else if (pluginSubElement.getText().equals("gui")) { // GUI plugin type openedPlugin = visPluginClass.getConstructor(new Class[]{GUI.class}).newInstance(GUI.currentGUI); GUI.currentGUI.showPlugin(openedPlugin); } else if (pluginSubElement.getText().startsWith("mote: ")) { // Mote plugin type String moteNrString = pluginSubElement.getText().substring("mote: ".length()); int moteNr = Integer.parseInt(moteNrString); Mote mote = newSim.getMote(moteNr); openedPlugin = visPluginClass.getConstructor(new Class[]{Mote.class}).newInstance(mote); // Tag plugin with mote openedPlugin.putClientProperty("mote", mote); // Show plugin GUI.currentGUI.showPlugin(openedPlugin); } } else if (pluginSubElement.getName().equals("width")) { size.width = Integer.parseInt(pluginSubElement.getText()); openedPlugin.setSize(size); } else if (pluginSubElement.getName().equals("height")) { size.height = Integer.parseInt(pluginSubElement.getText()); openedPlugin.setSize(size); } else if (pluginSubElement.getName().equals("z")) { int zOrder = Integer.parseInt(pluginSubElement.getText()); GUI.currentGUI.setComponentZOrder(openedPlugin, zOrder); } else if (pluginSubElement.getName().equals("location_x")) { location.x = Integer.parseInt(pluginSubElement.getText()); openedPlugin.setLocation(location); } else if (pluginSubElement.getName().equals("location_y")) { location.y = Integer.parseInt(pluginSubElement.getText()); openedPlugin.setLocation(location); } else if (pluginSubElement.getName().equals("minimized")) { openedPlugin.setIcon(Boolean.parseBoolean(pluginSubElement.getText())); } else if (pluginSubElement.getName().equals("visplugin_config")) { openedPlugin.setConfigXML(pluginSubElement.getChildren()); } } } catch (Exception e) { logger.fatal("Error when startup up saved plugins: " + e); } } } } catch (JDOMException e) { logger.fatal("File not wellformed: " + e.getMessage()); return null; } catch (IOException e) { logger.fatal("No access to file: " + e.getMessage()); return null; } catch (Exception e) { logger.fatal("Exception when loading file: " + e); e.printStackTrace(); return null; } return newSim; } /** * Saves current simulation configuration to given file and notifies * observers. * * @see #loadSimulationConfig(File file) * @see #getConfigXML() * @param file * File to write */ public void saveSimulationConfig(File file) { try { // Create simulation XML Element root = new Element("simulation"); root.addContent(getConfigXML()); // EXPERIMENTAL: Store opened plugins information Element pluginElement, pluginSubElement; if (GUI.currentGUI != null) { for (JInternalFrame openedFrame: GUI.currentGUI.getAllFrames()) { VisPlugin openedPlugin = (VisPlugin) openedFrame; int pluginType = openedPlugin.getClass().getAnnotation(VisPluginType.class).value(); pluginElement = new Element("visplugin"); pluginElement.setText(openedPlugin.getClass().getName()); pluginSubElement = new Element("constructor"); if (pluginType == VisPluginType.GUI_PLUGIN) { pluginSubElement.setText("gui"); pluginElement.addContent(pluginSubElement); } else if (pluginType == VisPluginType.SIM_PLUGIN || pluginType == VisPluginType.SIM_STANDARD_PLUGIN) { pluginSubElement.setText("sim"); pluginElement.addContent(pluginSubElement); } else if (pluginType == VisPluginType.MOTE_PLUGIN && openedPlugin.getClientProperty("mote") != null) { Mote taggedMote = (Mote) openedPlugin.getClientProperty("mote"); for (int moteNr = 0; moteNr < getMotesCount(); moteNr++) { if (getMote(moteNr) == taggedMote) { pluginSubElement.setText("mote: " + moteNr); pluginElement.addContent(pluginSubElement); } } } else { logger.fatal("Warning! Could not write visplugin constructor information: " + pluginType + "@" + openedPlugin); } pluginSubElement = new Element("width"); pluginSubElement.setText("" + openedPlugin.getSize().width); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("z"); pluginSubElement.setText("" + GUI.currentGUI.getComponentZOrder(openedPlugin)); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("height"); pluginSubElement.setText("" + openedPlugin.getSize().height); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("location_x"); pluginSubElement.setText("" + openedPlugin.getLocation().x); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("location_y"); pluginSubElement.setText("" + openedPlugin.getLocation().y); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("minimized"); pluginSubElement.setText(new Boolean(openedPlugin.isIcon()).toString()); pluginElement.addContent(pluginSubElement); Collection pluginXML = openedPlugin.getConfigXML(); if (pluginXML != null) { pluginSubElement = new Element("visplugin_config"); pluginSubElement.addContent(pluginXML); pluginElement.addContent(pluginSubElement); } root.addContent(pluginElement); } } // Create config Document doc = new Document(root); // Write to file FileOutputStream out = new FileOutputStream(file); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); outputter.output(doc, out); out.close(); logger.info("Saved to file: " + file.getAbsolutePath()); } catch (Exception e) { logger.warn("Exception while saving simulation config: " + e); } this.setChanged(); this.notifyObservers(this); } /** * Returns the current simulation config represented by XML elements. This * config also includes the current radio medium, all mote types and motes. * * @see #saveSimulationConfig(File file) * @return Current simulation config */ public Collection<Element> getConfigXML() { Vector<Element> config = new Vector<Element>(); Element element; // Title element = new Element("title"); element.setText(title); config.add(element); // Delay time element = new Element("delaytime"); element.setText(Integer.toString(delayTime)); config.add(element); // Simulation time element = new Element("simtime"); element.setText(Integer.toString(currentSimulationTime)); config.add(element); // Tick time element = new Element("ticktime"); element.setText(Integer.toString(tickTime)); config.add(element); // Radio Medium element = new Element("radiomedium"); element.setText(currentRadioMedium.getClass().getName()); Collection radioMediumXML = currentRadioMedium.getConfigXML(); if (radioMediumXML != null) element.addContent(radioMediumXML); config.add(element); // Mote types for (MoteType moteType : getMoteTypes()) { element = new Element("motetype"); element.setText(moteType.getClass().getName()); Collection moteTypeXML = moteType.getConfigXML(); if (moteTypeXML != null) element.addContent(moteTypeXML); config.add(element); } // Motes for (Mote mote : motes) { element = new Element("mote"); element.setText(mote.getClass().getName()); Collection moteXML = mote.getConfigXML(); if (moteXML != null) element.addContent(moteXML); config.add(element); } return config; } /** * Sets the current simulation config depending on the given XML elements. * * @see #getConfigXML() * @param configXML * Config XML elements */ public boolean setConfigXML(Collection<Element> configXML) throws Exception { // Parse elements for (Element element : configXML) { // Title if (element.getName().equals("title")) { title = element.getText(); } // Delay time if (element.getName().equals("delaytime")) { delayTime = Integer.parseInt(element.getText()); } // Simulation time if (element.getName().equals("simtime")) { currentSimulationTime = Integer.parseInt(element.getText()); } // Tick time if (element.getName().equals("ticktime")) { tickTime = Integer.parseInt(element.getText()); } // Radio medium if (element.getName().equals("radiomedium")) { String radioMediumClassName = element.getText().trim(); Class<? extends RadioMedium> radioMediumClass = GUI.currentGUI .tryLoadClass(this, RadioMedium.class, radioMediumClassName); if (radioMediumClass != null) // Create radio medium specified in config currentRadioMedium = radioMediumClass.newInstance(); else logger.warn("Could not find radio medium class: " + radioMediumClassName); // Show configure simulation dialog boolean createdOK = CreateSimDialog.showDialog(GUI.frame, this); if (!createdOK) { logger.debug("Simulation not created, aborting"); throw new Exception("Load aborted by user"); } // Check if radio medium specific config should be applied if (radioMediumClassName .equals(currentRadioMedium.getClass().getName())) { currentRadioMedium.setConfigXML(element.getChildren()); } else { logger .info("Radio Medium changed - ignoring radio medium specific config"); } } // Mote type if (element.getName().equals("motetype")) { String moteTypeClassName = element.getText().trim(); Class<? extends MoteType> moteTypeClass = GUI.currentGUI.tryLoadClass( this, MoteType.class, moteTypeClassName); if (moteTypeClass == null) { logger.fatal("Could not load mote type class: " + moteTypeClassName); return false; } MoteType moteType = moteTypeClass.getConstructor((Class[]) null) .newInstance(); boolean createdOK = moteType.setConfigXML(this, element.getChildren()); if (createdOK) { addMoteType(moteType); } else { logger .fatal("Mote type was not created: " + element.getText().trim()); throw new Exception("All mote types were not recreated"); } } // Mote if (element.getName().equals("mote")) { Class<? extends Mote> moteClass = GUI.currentGUI.tryLoadClass(this, Mote.class, element.getText().trim()); Mote mote = moteClass.getConstructor((Class[]) null).newInstance(); if (mote.setConfigXML(this, element.getChildren())) { addMote(mote); } else { logger.fatal("Mote was not created: " + element.getText().trim()); throw new Exception("All motes were not recreated"); } } } return true; } /** * Removes a mote from this simulation * * @param mote * Mote to remove */ public void removeMote(Mote mote) { if (isRunning()) { stopSimulation(); motes.remove(mote); startSimulation(); } else motes.remove(mote); currentRadioMedium.unregisterMote(mote, this); this.setChanged(); this.notifyObservers(this); } /** * Adds a mote to this simulation * * @param mote * Mote to add */ public void addMote(Mote mote) { if (isRunning()) { stopSimulation(); motes.add(mote); startSimulation(); } else motes.add(mote); currentRadioMedium.registerMote(mote, this); this.setChanged(); this.notifyObservers(this); } /** * Get a mote from this simulation. * * @param pos * Position of mote * @return Mote */ public Mote getMote(int pos) { return motes.get(pos); } /** * Returns number of motes in this simulation. * * @return Number of motes */ public int getMotesCount() { return motes.size(); } /** * Returns all mote types in simulation. * * @return All mote types */ public Vector<MoteType> getMoteTypes() { return moteTypes; } /** * Returns mote type with given identifier. * * @param identifier * Mote type identifier * @return Mote type or null if not found */ public MoteType getMoteType(String identifier) { for (MoteType moteType : getMoteTypes()) { if (moteType.getIdentifier().equals(identifier)) return moteType; } return null; } /** * Adds given mote type to simulation. * * @param newMoteType */ public void addMoteType(MoteType newMoteType) { moteTypes.add(newMoteType); this.setChanged(); this.notifyObservers(this); } /** * Set delay time to delayTime. When all motes have been ticked, the * simulation waits for this time before ticking again. * * @param delayTime * New delay time (ms) */ public void setDelayTime(int delayTime) { this.delayTime = delayTime; this.setChanged(); this.notifyObservers(this); } /** * Returns current delay time. * * @return Delay time (ms) */ public int getDelayTime() { return delayTime; } /** * Set simulation time to simulationTime. * * @param simulationTime * New simulation time (ms) */ public void setSimulationTime(int simulationTime) { currentSimulationTime = simulationTime; this.setChanged(); this.notifyObservers(this); } /** * Returns current simulation time. * * @return Simulation time (ms) */ public int getSimulationTime() { return currentSimulationTime; } /** * Set tick time to tickTime. The tick time is the simulated time every tick * takes. When all motes have been ticked, current simulation time is * increased with tickTime. Default tick time is 1 ms. * * @see #getTickTime() * @see #getTickTimeInSeconds() * @param tickTime * New tick time (ms) */ public void setTickTime(int tickTime) { this.tickTime = tickTime; this.setChanged(); this.notifyObservers(this); } /** * Changes radio medium of this simulation to the given. * * @param radioMedium * New radio medium */ public void setRadioMedium(RadioMedium radioMedium) { // Remove current radio medium from observing motes if (currentRadioMedium != null) for (int i = 0; i < motes.size(); i++) currentRadioMedium.unregisterMote(motes.get(i), this); // Change current radio medium to new one if (radioMedium == null) { logger.fatal("Radio medium could not be created!"); return; } this.currentRadioMedium = radioMedium; // Add all current motes to be observered by new radio medium for (int i = 0; i < motes.size(); i++) currentRadioMedium.registerMote(motes.get(i), this); } /** * Get currently used radio medium. * * @return Currently used radio medium */ public RadioMedium getRadioMedium() { return currentRadioMedium; } /** * Get current tick time (ms). * * @see #setTickTime(int) * @return Current tick time (ms) */ public int getTickTime() { return tickTime; } /** * Get current tick time (seconds). * * @see #setTickTime(int) * @return Current tick time (seconds) */ public double getTickTimeInSeconds() { return ((double) tickTime) / 1000.0; } /** * Return true is simulation is running. * * @return True if simulation is running */ public boolean isRunning() { return isRunning && thread != null; } /** * Get current simulation title (short description). * * @return Title */ public String getTitle() { return title; } /** * Set simulation title. * * @param title * New title */ public void setTitle(String title) { this.title = title; } }
// Parameter.java package imagej.plugin; import imagej.plugin.gui.WidgetStyle; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * TODO * * @author Johannes Schindelin * @author Grant Harris * @author Curtis Rueden */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Parameter { /** Defines if the parameter is an output. */ boolean output() default false; /** * Defines the "visibility" of the parameter. * <p> * Choices are: * <ul> * <li>NORMAL: parameter is included in the history for purposes of data * provenance, and included as a parameter when recording scripts.</li> * <li>TRANSIENT: parameter is excluded from the history for the purposes of * data provenance, but still included as a parameter when recording scripts.</li> * <li>INVISIBLE: parameter is excluded from the history for the purposes of * data provenance, and also excluded as a parameter when recording scripts. * This option should only be used for parameters with no effect on the final * output, such as a "verbose" flag.</li> * </ul> */ // NB: We use the fully qualified name to work around a javac bug: ParamVisibility visibility() default imagej.plugin.ParamVisibility.NORMAL; /** Defines a label for the parameter. */ String label() default ""; /** Defines a description for the parameter. */ String description() default ""; /** Defines whether the parameter is required (i.e., no default). */ boolean required() default false; /** Defines whether to remember the most recent value of the parameter. */ boolean persist() default true; /** Defines a key to use for saving the value persistently. */ String persistKey() default ""; /** * Defines a function that is called whenever this parameter changes. * <p> * This mechanism enables interdependent parameters of various types. * For example, two int parameters "width" and "height" could update each * other when another boolean "Preserve aspect ratio" flag is set. * </p> */ String callback() default ""; /** Defines the preferred widget style. */ // NB: We use the fully qualified name to work around a javac bug: WidgetStyle style() default imagej.plugin.gui.WidgetStyle.DEFAULT; /** Defines the minimum allowed value (numeric parameters only). */ String min() default ""; /** Defines the maximum allowed value (numeric parameters only). */ String max() default ""; /** Defines the step size to use (numeric parameters only). */ String stepSize() default ""; /** * Defines the width of the input field in characters (text field parameters * only). */ int columns() default 6; /** Defines the list of possible values (multiple choice text fields only). */ String[] choices() default {}; }
package imj3.draft.processing; import static imj3.draft.segmentation.CommonSwingTools.item; import static imj3.draft.segmentation.CommonSwingTools.showEditDialog; import static net.sourceforge.aprog.swing.SwingTools.horizontalSplit; import static net.sourceforge.aprog.swing.SwingTools.scrollable; import static net.sourceforge.aprog.tools.Tools.cast; import static net.sourceforge.aprog.tools.Tools.unchecked; import imj2.pixel3d.MouseHandler; import imj3.draft.processing.VisualAnalysis.Session.ClassDescription; import imj3.draft.segmentation.CommonSwingTools; import imj3.draft.segmentation.CommonTools.Property; import imj3.draft.segmentation.ImageComponent; import imj3.tools.AwtImage2D; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDropEvent; import java.awt.event.MouseEvent; import java.io.File; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.prefs.Preferences; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JSplitPane; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import net.sourceforge.aprog.swing.SwingTools; import net.sourceforge.aprog.tools.IllegalInstantiationException; import net.sourceforge.aprog.tools.Tools; /** * @author codistmonk (creation 2015-02-13) */ public final class VisualAnalysis { private VisualAnalysis() { throw new IllegalInstantiationException(); } static final Preferences preferences = Preferences.userNodeForPackage(VisualAnalysis.class); public static final String IMAGE_FILE_PATH = "image.file.path"; /** * @param commandLineArguments * <br>Unused */ public static final void main(final String[] commandLineArguments) { SwingTools.useSystemLookAndFeel(); final Context context = new Context(); SwingUtilities.invokeLater(new Runnable() { @Override public final void run() { SwingTools.show(new MainPanel(context), VisualAnalysis.class.getSimpleName(), false); context.setImageFile(new File(preferences.get(IMAGE_FILE_PATH, ""))); } }); } /** * @author codistmonk (creation 2015-02-13) */ public static final class MainPanel extends JPanel { private final JTree tree; private final JSplitPane mainSplitPane; public MainPanel(final Context context) { super(new BorderLayout()); this.tree = new JTree(); this.mainSplitPane = horizontalSplit(scrollable(this.tree), scrollable(new JLabel("Drop file here"))); setModel(this.tree, context.setSession(new Session()).getSession()); final JToolBar toolBar = new JToolBar(); toolBar.add(new JLabel("TODO")); this.add(toolBar, BorderLayout.NORTH); this.add(this.mainSplitPane, BorderLayout.CENTER); this.mainSplitPane.getRightComponent().setDropTarget(new DropTarget() { @Override public final synchronized void drop(final DropTargetDropEvent event) { final File file = SwingTools.getFiles(event).get(0); context.setImageFile(file); preferences.put(IMAGE_FILE_PATH, file.getPath()); } /** * {@value}. */ private static final long serialVersionUID = 5442000733451223725L; }); this.setPreferredSize(new Dimension(800, 600)); context.setMainPanel(this); } public final void setContents(final Component component) { this.mainSplitPane.setRightComponent(scrollable(component)); } private static final long serialVersionUID = 2173077945563031333L; } /** * @author codistmonk (creation 2015-02-16) */ public static final class UIScaffold implements Serializable { private final Object object; private final Method[] stringGetter; private final Map<String, Method> propertyGetters; private final Map<String, Method> propertySetters; private final List<Method> inlineLists; private final Map<String, Method> nestedLists; public UIScaffold(final Object object) { this.object = object; this.stringGetter = new Method[1]; this.propertyGetters = new LinkedHashMap<>(); this.propertySetters = new LinkedHashMap<>(); this.inlineLists = new ArrayList<>(); this.nestedLists = new LinkedHashMap<>(); for (final Method method : object.getClass().getMethods()) { for (final Annotation annotation : method.getAnnotations()) { final StringGetter stringGetter0 = cast(StringGetter.class, annotation); final PropertyGetter propertyGetter = cast(PropertyGetter.class, annotation); final PropertySetter propertySetter = cast(PropertySetter.class, annotation); final InlineList inlineList = cast(InlineList.class, annotation); final NestedList nestedList = cast(NestedList.class, annotation); if (stringGetter0 != null) { this.stringGetter[0] = method; } if (propertyGetter != null) { this.propertyGetters.put(propertyGetter.value(), method); } if (propertySetter != null) { this.propertySetters.put(propertySetter.value(), method); } if (inlineList != null) { this.inlineLists.add(method); } if (nestedList != null) { this.nestedLists.put(nestedList.name(), method); } } } } public final Object getObject() { return this.object; } public final Method getStringGetter() { return this.stringGetter[0]; } public final Map<String, Method> getPropertyGetters() { return this.propertyGetters; } public final Map<String, Method> getPropertySetters() { return this.propertySetters; } public final List<Method> getInlineLists() { return this.inlineLists; } public final Map<String, Method> getNestedLists() { return this.nestedLists; } public final void edit(final String title, final Runnable actionIfOk) { final List<Property> properties = new ArrayList<>(); for (final Map.Entry<String, Method> entry : this.getPropertyGetters().entrySet()) { final Method setter = this.getPropertySetters().get(entry.getKey()); if (setter != null) { properties.add(new Property(entry.getKey(), () -> { try { return entry.getValue().invoke(this.getObject()); } catch (final Exception exception) { throw unchecked(exception); } }, string -> { try { return setter.invoke(this.getObject(), string); } catch (final Exception exception) { throw unchecked(exception); } })); } } showEditDialog(title, actionIfOk, properties.toArray(new Property[properties.size()])); } private static final long serialVersionUID = -5160722477511458349L; } public static final void setModel(final JTree tree, final Object object) { final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); final DefaultTreeModel model = new DefaultTreeModel(root); final UIScaffold scaffold = new UIScaffold(object); tree.setModel(model); if (scaffold.getStringGetter() != null) { final TreePath path = new TreePath(model.getPathToRoot(root)); model.valueForPathChanged(path, new EditableUserObject() { @Override public final String toString() { try { return (String) scaffold.getStringGetter().invoke(object); } catch (final Exception exception) { throw Tools.unchecked(exception); } } @Override public final void edit() { final String title = "Session"; scaffold.edit("Session", new Runnable() { @Override public final void run() { model.valueForPathChanged(path, root.getUserObject()); tree.getRootPane().validate(); } }); } private static final long serialVersionUID = 3506822059086373426L; }); } for (final Map.Entry<String, Method> entry : scaffold.getNestedLists().entrySet()) { model.insertNodeInto(new DefaultMutableTreeNode(entry.getKey()), root, model.getChildCount(root)); } new MouseHandler(null) { @Override public final void mouseClicked(final MouseEvent event) { this.mouseUsed(event); } @Override public final void mousePressed(final MouseEvent event) { this.mouseUsed(event); } @Override public final void mouseReleased(final MouseEvent event) { this.mouseUsed(event); } private final void mouseUsed(final MouseEvent event) { if (event.isPopupTrigger()) { final TreePath path = tree.getPathForLocation(event.getX(), event.getY()); final EditableUserObject editable = path == null ? null : cast(EditableUserObject.class, ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject()); if (editable != null) { final JPopupMenu popup = new JPopupMenu(); popup.add(item("Edit...", e -> editable.edit())); for (final Method inlineList : scaffold.getInlineLists()) { popup.add(item("Add " + inlineList.getAnnotation(InlineList.class).element() + "...", e -> { })); } for (final Map.Entry<String, Method> entry : scaffold.getNestedLists().entrySet()) { popup.add(item("Add " + entry.getValue().getAnnotation(NestedList.class).element() + "...", e -> { final ClassDescription newClassDescription = new ClassDescription(); final UIScaffold newClassDescriptionScaffold = new UIScaffold(newClassDescription); newClassDescriptionScaffold.edit("New class", new Runnable() { @Override public final void run() { final MutableTreeNode classesNode = (MutableTreeNode) model.getChild(root, 0); model.insertNodeInto(new DefaultMutableTreeNode(new EditableUserObject() { @Override public final void edit() { model.valueForPathChanged(new TreePath(model.getPathToRoot(classesNode)), this); } private static final long serialVersionUID = -3105991721448384700L; }),classesNode, model.getChildCount(classesNode)); } }); })); } popup.show(tree, event.getX(), event.getY()); } } } private static final long serialVersionUID = -475200304537897055L; }.addTo(tree); } /** * @author codistmonk (creation 2015-02-16) */ public static abstract interface EditableUserObject extends Serializable { public abstract void edit(); } /** * @author codistmonk (creation 2015-02-13) */ public static final class Context implements Serializable { private MainPanel mainPanel; private Session session; private File imageFile; public final MainPanel getMainPanel() { return this.mainPanel; } public final void setMainPanel(final MainPanel mainPanel) { this.mainPanel = mainPanel; } public final Session getSession() { return this.session; } public final Context setSession(final Session session) { this.session = session; return this; } public final File getImageFile() { return this.imageFile; } public final void setImageFile(final File imageFile) { if (imageFile.isFile()) { this.getMainPanel().setContents(new ImageComponent(AwtImage2D.awtRead(imageFile.getPath()))); this.imageFile = imageFile; } } private static final long serialVersionUID = -2487965125442868238L; } /** * @author codistmonk (creation 2015-02-16) */ public static final class Session implements Serializable { private String name = "session"; private final List<ClassDescription> classDescriptions = new ArrayList<>(); @StringGetter @PropertyGetter("name") public final String getName() { return this.name; } @PropertySetter("name") public final Session setName(final String name) { this.name = name; return this; } @NestedList(name="classes", element="class") public final List<ClassDescription> getClassDescriptions() { return this.classDescriptions; } private static final long serialVersionUID = -4539259556658072410L; /** * @author codistmonk (creation 2015-02-16) */ public static final class ClassDescription implements Serializable { private String name = "class"; private int label = 0xFF000000; @StringGetter @PropertyGetter("name") public final String getName() { return this.name; } @PropertySetter("name") public final ClassDescription setName(final String name) { this.name = name; return this; } public final int getLabel() { return this.label; } public final ClassDescription setLabel(final int label) { this.label = label; return this; } @PropertyGetter("label") public final String getLabelAsString() { return "#" + Integer.toHexString(this.getLabel()).toUpperCase(Locale.ENGLISH); } @PropertySetter("label") public final ClassDescription setLabel(final String labelAsString) { return this.setLabel((int) Long.parseLong(labelAsString.substring(1), 16)); } private static final long serialVersionUID = 4974707407567297906L; } } /** * @author codistmonk (creation 2015-02-16) */ @Retention(RetentionPolicy.RUNTIME) public static abstract @interface StringGetter { } /** * @author codistmonk (creation 2015-02-16) */ @Retention(RetentionPolicy.RUNTIME) public static abstract @interface PropertyGetter { public abstract String value(); } /** * @author codistmonk (creation 2015-02-16) */ @Retention(RetentionPolicy.RUNTIME) public static abstract @interface PropertySetter { public abstract String value(); } /** * @author codistmonk (creation 2015-02-16) */ @Retention(RetentionPolicy.RUNTIME) public static abstract @interface InlineList { public abstract String element(); } /** * @author codistmonk (creation 2015-02-16) */ @Retention(RetentionPolicy.RUNTIME) public static abstract @interface NestedList { public abstract String name(); public abstract String element(); } }
package cgeo.geocaching.connector.oc; import cgeo.geocaching.LogEntry; import cgeo.geocaching.Settings; import cgeo.geocaching.cgCache; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.utils.Log; import org.apache.commons.lang3.StringUtils; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import android.sax.Element; import android.sax.EndElementListener; import android.sax.EndTextElementListener; import android.sax.RootElement; import android.sax.StartElementListener; import android.util.Xml; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.regex.Pattern; public class OC11XMLParser { private static final String PARAGRAPH_END = "</p>"; private static final String PARAGRAPH_BEGIN = "<p>"; private static Pattern STRIP_DATE = Pattern.compile("\\+0([0-9]){1}\\:00"); private static class CacheHolder { public cgCache cache; public String latitude; public String longitude; } private static class CacheLog { public String cacheId; public LogEntry logEntry; } private static class CacheDescription { public String cacheId; public String shortDesc; public String desc; public String hint; } private static Date parseFullDate(final String date) { final SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); ISO8601DATEFORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); final String strippedDate = STRIP_DATE.matcher(date).replaceAll("+0$100"); try { return ISO8601DATEFORMAT.parse(strippedDate); } catch (ParseException e) { Log.e("OC11XMLParser.parseFullDate", e); } return null; } private static Date parseDayDate(final String date) { final SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.US); ISO8601DATEFORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); final String strippedDate = STRIP_DATE.matcher(date).replaceAll("+0$100"); try { return ISO8601DATEFORMAT.parse(strippedDate); } catch (ParseException e) { Log.e("OC11XMLParser.parseDayDate", e); } return null; } private static CacheSize getCacheSize(final String sizeId) { try { int size = Integer.parseInt(sizeId); switch (size) { case 1: return CacheSize.OTHER; case 2: return CacheSize.MICRO; case 3: return CacheSize.SMALL; case 4: return CacheSize.REGULAR; case 5: case 6: return CacheSize.LARGE; case 8: return CacheSize.VIRTUAL; default: break; } } catch (NumberFormatException e) { Log.e("OC11XMLParser.getCacheSize", e); } return CacheSize.NOT_CHOSEN; } private static CacheType getCacheType(final String typeId) { try { int type = Integer.parseInt(typeId); switch (type) { case 1: // Other/unbekannter Cachetyp return CacheType.UNKNOWN; case 2: // Trad./normaler Cache return CacheType.TRADITIONAL; case 3: // Multi/Multicache return CacheType.MULTI; case 4: // Virt./virtueller Cache return CacheType.VIRTUAL; case 5: // ICam./Webcam-Cache return CacheType.WEBCAM; case 6: // Event/Event-Cache return CacheType.EVENT; case 7: return CacheType.MYSTERY; case 8: // Math/Mathe-/Physikcache return CacheType.MYSTERY; case 9: // Moving/beweglicher Cache return CacheType.VIRTUAL; case 10: // Driv./Drive-In return CacheType.TRADITIONAL; } } catch (NumberFormatException e) { Log.e("OC11XMLParser.getCacheType", e); } return CacheType.UNKNOWN; } private static LogType getLogType(final int typeId) { switch (typeId) { case 1: return LogType.FOUND_IT; case 2: return LogType.DIDNT_FIND_IT; case 3: return LogType.NOTE; case 7: return LogType.ATTENDED; case 8: return LogType.WILL_ATTEND; default: return LogType.UNKNOWN; } } private static void setCacheStatus(final int statusId, final cgCache cache) { switch (statusId) { case 1: cache.setArchived(false); cache.setDisabled(false); break; case 2: cache.setArchived(false); cache.setDisabled(true); break; default: cache.setArchived(true); cache.setDisabled(false); break; } } private static void resetCache(final CacheHolder cacheHolder) { cacheHolder.cache = new cgCache(null); cacheHolder.cache.setReliableLatLon(true); cacheHolder.cache.setDescription(StringUtils.EMPTY); cacheHolder.latitude = "0.0"; cacheHolder.longitude = "0.0"; } private static void resetLog(final CacheLog log) { log.cacheId = StringUtils.EMPTY; log.logEntry = new LogEntry("", 0, LogType.UNKNOWN, ""); } private static void resetDesc(final CacheDescription desc) { desc.cacheId = StringUtils.EMPTY; desc.shortDesc = StringUtils.EMPTY; desc.desc = StringUtils.EMPTY; desc.hint = StringUtils.EMPTY; } public static Collection<cgCache> parseCaches(final InputStream stream) throws IOException { final int CACHE_PARSE_LIMIT = 250; final Map<String, cgCache> caches = new HashMap<String, cgCache>(); final CacheHolder cacheHolder = new CacheHolder(); final CacheLog logHolder = new CacheLog(); final CacheDescription descHolder = new CacheDescription(); final RootElement root = new RootElement("oc11xml"); final Element cacheNode = root.getChild("cache"); // cache cacheNode.setStartElementListener(new StartElementListener() { @Override public void start(Attributes attributes) { resetCache(cacheHolder); } }); cacheNode.setEndElementListener(new EndElementListener() { @Override public void end() { cgCache cache = cacheHolder.cache; Geopoint coords = new Geopoint(cacheHolder.latitude, cacheHolder.longitude); if (StringUtils.isNotBlank(cache.getGeocode()) && !coords.equals(Geopoint.ZERO) && !cache.isArchived() && caches.size() < CACHE_PARSE_LIMIT) { cache.setCoords(coords); cache.setDetailedUpdatedNow(); caches.put(cache.getCacheId(), cache); } } }); // cache.id cacheNode.getChild("id").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { cacheHolder.cache.setCacheId(body); } }); // cache.longitude cacheNode.getChild("longitude").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { String longitude = body.trim(); if (StringUtils.isNotBlank(longitude)) { cacheHolder.longitude = longitude; } } }); // cache.latitude cacheNode.getChild("latitude").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { String latitude = body.trim(); if (StringUtils.isNotBlank(latitude)) { cacheHolder.latitude = latitude; } } }); // cache.name cacheNode.getChild("name").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { final String content = body.trim(); cacheHolder.cache.setName(content); } }); // cache.waypoints[oc] cacheNode.getChild("waypoints").setStartElementListener(new StartElementListener() { @Override public void start(Attributes attrs) { if (attrs.getIndex("oc") > -1) { cacheHolder.cache.setGeocode(attrs.getValue("oc")); } if (attrs.getIndex("gccom") > -1) { String gccode = attrs.getValue("gccom"); if (!StringUtils.isBlank(gccode)) { cacheHolder.cache.setDescription(String.format("Listed on geocaching com: <a href=\"http://coord.info/%s\">%s</a><br /><br />", gccode, gccode)); } } } }); // cache.type[id] cacheNode.getChild("type").setStartElementListener(new StartElementListener() { @Override public void start(Attributes attrs) { if (attrs.getIndex("id") > -1) { final String typeId = attrs.getValue("id"); cacheHolder.cache.setType(getCacheType(typeId)); } } }); // cache.status[id] cacheNode.getChild("status").setStartElementListener(new StartElementListener() { @Override public void start(Attributes attrs) { if (attrs.getIndex("id") > -1) { try { final int statusId = Integer.parseInt(attrs.getValue("id")); setCacheStatus(statusId, cacheHolder.cache); } catch (NumberFormatException e) { Log.w(String.format("Failed to parse status of cache '%s'.", cacheHolder.cache.getGeocode())); } } } }); // cache.size[id] cacheNode.getChild("size").setStartElementListener(new StartElementListener() { @Override public void start(Attributes attrs) { if (attrs.getIndex("id") > -1) { final String typeId = attrs.getValue("id"); cacheHolder.cache.setSize(getCacheSize(typeId)); } } }); // cache.difficulty cacheNode.getChild("difficulty").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { final String content = body.trim(); try { cacheHolder.cache.setDifficulty(Float.valueOf(content)); } catch (NumberFormatException e) { Log.e("OC11XMLParser: unknown difficulty " + content, e); } } }); // cache.terrain cacheNode.getChild("terrain").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { final String content = body.trim(); try { cacheHolder.cache.setTerrain(Float.valueOf(content)); } catch (NumberFormatException e) { Log.e("OC11XMLParser: unknown terrain " + content, e); } } }); // cache.terrain cacheNode.getChild("datehidden").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { final String content = body.trim(); cacheHolder.cache.setHidden(parseFullDate(content)); } }); // cache.attributes.attribute cacheNode.getChild("attributes").getChild("attribute").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { if (StringUtils.isNotBlank(body)) { cacheHolder.cache.getAttributes().add(body.trim()); } } }); // cachedesc final Element cacheDesc = root.getChild("cachedesc"); cacheDesc.setStartElementListener(new StartElementListener() { @Override public void start(Attributes attributes) { resetDesc(descHolder); } }); cacheDesc.setEndElementListener(new EndElementListener() { @Override public void end() { final cgCache cache = caches.get(descHolder.cacheId); if (cache != null) { cache.setShortdesc(descHolder.shortDesc); cache.setDescription(cache.getDescription() + descHolder.desc); cache.setHint(descHolder.hint); } } }); // cachedesc.cacheid cacheDesc.getChild("cacheid").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { descHolder.cacheId = body; } }); // cachedesc.desc cacheDesc.getChild("shortdesc").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { final String content = body.trim(); descHolder.shortDesc = content; } }); // cachedesc.desc cacheDesc.getChild("desc").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { final String content = body.trim(); descHolder.desc = content; } }); // cachedesc.hint cacheDesc.getChild("hint").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { final String content = body.trim(); descHolder.hint = content; } }); // cachelog final Element cacheLog = root.getChild("cachelog"); cacheLog.setStartElementListener(new StartElementListener() { @Override public void start(Attributes attrs) { resetLog(logHolder); } }); cacheLog.setEndElementListener(new EndElementListener() { @Override public void end() { final cgCache cache = caches.get(logHolder.cacheId); if (cache != null && logHolder.logEntry.type != LogType.UNKNOWN) { cache.getLogs().prepend(logHolder.logEntry); if (logHolder.logEntry.type == LogType.FOUND_IT && StringUtils.equalsIgnoreCase(logHolder.logEntry.author, Settings.getOCConnectorUserName())) { cache.setFound(true); cache.setVisitedDate(logHolder.logEntry.date); } } } }); // cachelog.cacheid cacheLog.getChild("cacheid").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { logHolder.cacheId = body; } }); // cachelog.date cacheLog.getChild("date").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { try { logHolder.logEntry.date = parseDayDate(body).getTime(); } catch (NullPointerException e) { Log.w("Failed to parse log date", e); } } }); // cachelog.logtype cacheLog.getChild("logtype").setStartElementListener(new StartElementListener() { @Override public void start(Attributes attrs) { if (attrs.getIndex("id") > -1) { final String id = attrs.getValue("id"); try { final int typeId = Integer.parseInt(id); logHolder.logEntry.type = getLogType(typeId); } catch (NumberFormatException e) { Log.e("OC11XMLParser, unknown logtype " + id, e); } } } }); // cachelog.userid cacheLog.getChild("userid").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String finderName) { logHolder.logEntry.author = finderName; } }); // cachelog.text cacheLog.getChild("text").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String logText) { logHolder.logEntry.log = stripMarkup(logText); } }); try { Xml.parse(stream, Xml.Encoding.UTF_8, root.getContentHandler()); return caches.values(); } catch (SAXException e) { Log.e("Cannot parse .gpx file as oc11xml: could not parse XML - " + e.toString()); return null; } } /** * removes unneeded markup */ protected static String stripMarkup(String input) { if (StringUtils.startsWith(input, PARAGRAPH_BEGIN) && StringUtils.endsWith(input, PARAGRAPH_END)) { String inner = input.substring(PARAGRAPH_BEGIN.length(), input.length() - PARAGRAPH_END.length()); if (inner.indexOf(PARAGRAPH_BEGIN) < 0) { return inner; } } return input; } }
package de.longri.cachebox3.sqlite.dao; import com.badlogic.gdx.sql.SQLiteGdxDatabaseCursor; import com.badlogic.gdx.utils.Array; import de.longri.cachebox3.sqlite.Database; import de.longri.cachebox3.types.AbstractCache; import de.longri.cachebox3.types.AbstractWaypoint; import de.longri.cachebox3.types.ImmutableCache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class Cache3DAO extends AbstractCacheDAO { private final static Logger log = LoggerFactory.getLogger(Cache3DAO.class); private final DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public AbstractWaypointDAO getWaypointDAO() { return new Waypoint3DAO(); } @Override public boolean updateDatabase(Database database, AbstractCache abstractCache) { return writeOrUpdate(true, database, abstractCache); } @Override public void writeToDatabase(Database database, AbstractCache abstractCache) { writeOrUpdate(false, database, abstractCache); } private boolean writeOrUpdate(boolean update, Database database, AbstractCache abstractCache) { boolean noError = true; //Write to CacheCoreInfo Table Database.Parameters args = new Database.Parameters(); if (!update) args.put("Id", abstractCache.getId()); args.put("Latitude", abstractCache.latitude); args.put("Longitude", abstractCache.longitude); args.put("Size", abstractCache.getSize().ordinal()); args.put("Difficulty", (int) (abstractCache.getDifficulty() * 2)); args.put("Terrain", (int) (abstractCache.getTerrain() * 2)); args.put("Type", abstractCache.getType().ordinal()); args.put("Rating", (int) (abstractCache.getRating() * 200)); args.put("NumTravelbugs", abstractCache.getNumTravelbugs()); args.put("GcCode", abstractCache.getGcCode()); args.put("Name", abstractCache.getName()); args.put("PlacedBy", abstractCache.getPlacedBy()); args.put("Owner", abstractCache.getOwner()); args.put("GcId", abstractCache.getGcId()); args.put("BooleanStore", abstractCache.getBooleanStore()); args.put("FavPoints", abstractCache.getFavoritePoints()); args.put("Vote", (int) (abstractCache.getRating() * 2)); if (update) { if (database.update("CacheCoreInfo", args, "WHERE id=?", new String[]{Long.toString(abstractCache.getId())}) <= 0) { //Cache not inserted, can't write other information's! log.error("Cache {} not inserted on CacheCoreInfo table", abstractCache.toString()); return false; } } else { if (database.insert("CacheCoreInfo", args) <= 0) { //Cache not inserted, can't write other information's! log.error("Cache {} not inserted on CacheCoreInfo table", abstractCache.toString()); return false; } } //Write to CacheInfo table args.clear(); args.put("Id", abstractCache.getId()); args.put("DateHidden", iso8601Format.format(abstractCache.getDateHidden() == null ? new Date() : abstractCache.getDateHidden())); args.put("FirstImported", iso8601Format.format(new Date())); args.put("TourName", abstractCache.getTourName()); args.put("GPXFilename_Id", abstractCache.getGPXFilename_ID()); args.put("state", abstractCache.getState()); args.put("country", abstractCache.getCountry()); args.put("ApiStatus", abstractCache.getApiState()); if (update) { if (database.update("CacheInfo", args, "WHERE id=?", new String[]{Long.toString(abstractCache.getId())}) <= 0) { //CacheInfo not inserted, can't write other information's! log.error("Cache {} not inserted on CacheInfo table", abstractCache.toString()); noError = false; } } else { if (database.insert("CacheInfo", args) <= 0) { //CacheInfo not inserted, can't write other information's! log.error("Cache {} not inserted on CacheInfo table", abstractCache.toString()); noError = false; } } //Write to CacheText table args.clear(); args.put("Id", abstractCache.getId()); args.put("Url", abstractCache.getUrl(database)); args.put("Hint", abstractCache.getHint(database)); args.put("Description", abstractCache.getLongDescription(database)); args.put("Notes", abstractCache.getTmpNote()); args.put("Solver", abstractCache.getTmpSolver()); args.put("ShortDescription", abstractCache.getShortDescription(database)); if (update) { if (database.update("CacheText", args, "WHERE id=?", new String[]{Long.toString(abstractCache.getId())}) <= 0) { //CacheInfo not inserted, can't write other information's! log.error("Cache {} not inserted on CacheText table", abstractCache.toString()); noError = false; } } else { if (database.insert("CacheText", args) <= 0) { //CacheInfo not inserted, can't write other information's! log.error("Cache {} not inserted on CacheText table", abstractCache.toString()); noError = false; } } //Write to Attributes table args.clear(); args.put("Id", abstractCache.getId()); if (abstractCache.getAttributesPositive() != null) { args.put("AttributesPositive", abstractCache.getAttributesPositive().getLow()); args.put("AttributesPositiveHigh", abstractCache.getAttributesPositive().getHigh()); } if (abstractCache.getAttributesNegative() != null) { args.put("AttributesNegative", abstractCache.getAttributesNegative().getLow()); args.put("AttributesNegativeHigh", abstractCache.getAttributesNegative().getHigh()); } if (update) { if (database.update("Attributes", args, "WHERE id=?", new String[]{Long.toString(abstractCache.getId())}) <= 0) { //CacheInfo not inserted, can't write other information's! log.error("Cache {} not inserted on Attributes table", abstractCache.toString()); noError = false; } } else { if (database.insert("Attributes", args) <= 0) { //CacheInfo not inserted, can't write other information's! log.error("Cache {} not inserted on Attributes table", abstractCache.toString()); noError = false; } } args.clear(); //store Waypoints Array<AbstractWaypoint> waypoints = abstractCache.getWaypoints(); if (waypoints != null) { AbstractWaypointDAO WDAO = getWaypointDAO(); int n = waypoints.size; while (n AbstractWaypoint wp = waypoints.get(n); if (update) { if (!WDAO.updateDatabase(database, wp)) { WDAO.writeToDatabase(database, wp); } } else { WDAO.writeToDatabase(database, wp); } } } return noError; } @Override public void writeToDatabaseFound(Database database, AbstractCache abstractCache) { } @Override public AbstractCache getFromDbByCacheId(Database database, long cacheID, boolean withWaypoints) { String statement = "SELECT * from CacheCoreInfo WHERE Id=?"; SQLiteGdxDatabaseCursor cursor = database.rawQuery(statement, new String[]{String.valueOf(cacheID)}); cursor.moveToFirst(); if (!cursor.isAfterLast()) { AbstractCache cache = new ImmutableCache(cursor); if (withWaypoints) { cache.setWaypoints(getWaypointDAO().getWaypointsFromCacheID(database, cacheID, true)); } return cache; } return null; } @Override public boolean updateDatabaseCacheState(Database database, AbstractCache writeTmp) { return false; } }
package org.biojava.bio.alignment; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import org.biojava.bio.BioException; import org.biojava.bio.SimpleAnnotation; import org.biojava.bio.seq.Sequence; import org.biojava.bio.seq.SequenceIterator; import org.biojava.bio.seq.db.SequenceDB; import org.biojava.bio.seq.impl.SimpleGappedSequence; import org.biojava.bio.seq.impl.SimpleSequence; import org.biojava.bio.seq.io.SymbolTokenization; import org.biojava.bio.symbol.SimpleSymbolList; import org.biojava.bio.symbol.SymbolList; /** * Needleman and Wunsch defined the problem of global sequence alignments, from * the first till the last symbol of a sequence. This class is able to perform * such global sequence comparisons efficiently by dynamic programming. If * inserts and deletes are equally expensive and as expensive as the extension * of a gap, the alignment method of this class does not use affine gap * penalties. Otherwise it does. Those costs need four times as much memory, * which has significant effects on the run time, if the computer needs to swap. * * @author Andreas Dr&auml;ger * @author Gero Greiner * @author Mark Schreiber * @since 1.5 */ public class NeedlemanWunsch extends SequenceAlignment { /** * A matrix with the size length(sequence1) times length(sequence2) */ protected int[][] CostMatrix; /** * A matrix with the size length(alphabet) times length(alphabet) */ protected SubstitutionMatrix subMatrix; /** * The result of a successful alignment */ protected SimpleAlignment pairalign; /** * The result of a successful alignment as a simple String. */ protected String alignment; /** * Expenses for inserts. */ private short insert; /** * Expenses for deletes. */ private short delete; /** * Expenses for the extension of a gap. */ private short gapExt; /** * Expenses for matches. */ private short match; /** * Expenses for replaces. */ private short replace; /** * Constructs a new Object with the given parameters based on the * Needleman-Wunsch algorithm The alphabet of sequences to be aligned will * be taken from the given substitution matrix. * * @param match * This gives the costs for a match operation. It is only used, * if there is no entry for a certain match of two symbols in the * substitution matrix (default value). * @param replace * This is like the match parameter just the default, if there is * no entry in the substitution matrix object. * @param insert * The costs of a single insert operation. * @param delete * The expenses of a single delete operation. * @param gapExtend * The expenses of an extension of a existing gap (that is a * previous insert or delete. If the costs for insert and delete * are equal and also equal to gapExtend, no affine gap penalties * will be used, which saves a significant amount of memory. * @param subMat * The substitution matrix object which gives the costs for * matches and replaces. */ public NeedlemanWunsch(short match, short replace, short insert, short delete, short gapExtend, SubstitutionMatrix subMat) { this.subMatrix = subMat; this.insert = insert; this.delete = delete; this.gapExt = gapExtend; this.match = match; this.replace = replace; this.alignment = ""; } /** * Sets the substitution matrix to be used to the specified one. Afterwards * it is only possible to align sequences of the alphabet of this * substitution matrix. * * @param matrix * an instance of a substitution matrix. */ public void setSubstitutionMatrix(SubstitutionMatrix matrix) { this.subMatrix = matrix; } /** * Sets the penalty for an insert operation to the specified value. * * @param ins * costs for a single insert operation */ public void setInsert(short ins) { this.insert = ins; } /** * Sets the penalty for a delete operation to the specified value. * * @param del * costs for a single deletion operation */ public void setDelete(short del) { this.delete = del; } /** * Sets the penalty for an extension of any gap (insert or delete) to the * specified value. * * @param ge * costs for any gap extension */ public void setGapExt(short ge) { this.gapExt = ge; } /** * Sets the penalty for a match operation to the specified value. * * @param ma * costs for a single match operation */ public void setMatch(short ma) { this.match = ma; } /** * Sets the penalty for a replace operation to the specified value. * * @param rep * costs for a single replace operation */ public void setReplace(short rep) { this.replace = rep; } /** * Returns the current expenses of a single insert operation. * * @return insert */ public short getInsert() { return insert; } /** * Returns the current expenses of a single delete operation. * * @return delete */ public short getDelete() { return delete; } /** * Returns the current expenses of any extension of a gap operation. * * @return gapExt */ public short getGapExt() { return gapExt; } /** * Returns the current expenses of a single match operation. * * @return match */ public short getMatch() { return match; } /** * Returns the current expenses of a single replace operation. * * @return replace */ public short getReplace() { return replace; } /** * Prints a String representation of the CostMatrix for the given Alignment * on the screen. This can be used to get a better understanding of the * algorithm. There is no other purpose. This method also works for all * extensions of this class with all kinds of matrices. * * @param CostMatrix * The matrix that contains all expenses for swapping symbols. * @param queryChar * a character representation of the query sequence ( * <code>mySequence.seqString().toCharArray()</code>). * @param targetChar * a character representation of the target sequence. * @return a String representation of the matrix. */ public static String printCostMatrix(int[][] CostMatrix, char[] queryChar, char[] targetChar) { int line, col; StringBuilder output = new StringBuilder('\t'); String ls = System.getProperty("line.separator"); for (col = 0; col <= targetChar.length; col++) if (col == 0) { output.append('['); output.append(col); output.append("]\t"); } else { output.append('['); output.append(targetChar[col - 1]); output.append("]\t"); } for (line = 0; line <= queryChar.length; line++) { if (line == 0) { output.append(ls); output.append('['); output.append(line); output.append("]\t"); } else { output.append(ls); output.append('['); output.append(queryChar[line - 1]); output.append("]\t"); } for (col = 0; col <= targetChar.length; col++) { output.append(CostMatrix[line][col]); output.append('\t'); } } output.append(ls); output.append("delta[Edit] = "); output.append(CostMatrix[line - 1][col - 1]); output.append(ls); return output.toString(); } /** * prints the alignment String on the screen (standard output). * * @param align * The parameter is typically given by the * {@link #getAlignmentString() getAlignmentString()} method. */ public static void printAlignment(String align) { System.out.print(align); } /** * This method is good if one wants to reuse the alignment calculated by * this class in another BioJava class. It just performs * {@link #pairwiseAlignment(SymbolList, SymbolList) pairwiseAlignment} and * returns an <code>Alignment</code> instance containing the two aligned * sequences. * * @return Alignment object containing the two gapped sequences constructed * from query and target. * @throws Exception */ public Alignment getAlignment(SymbolList query, SymbolList target) throws Exception { pairwiseAlignment(query, target); return pairalign; } /** * This gives the edit distance according to the given parameters of this * certain object. It returns just the last element of the internal cost * matrix (left side down). So if you extend this class, you can just do the * following: * <code>int myDistanceValue = foo; this.CostMatrix = new int[1][1]; this.CostMatrix[0][0] = myDistanceValue;</code> * * @return returns the edit_distance computed with the given parameters. */ public int getEditDistance() { return CostMatrix[CostMatrix.length - 1][CostMatrix[CostMatrix.length - 1].length - 1]; } /** * This just computes the minimum of three integer values. * * @param x * @param y * @param z * @return Gives the minimum of three integers */ protected static int min(int x, int y, int z) { if ((x < y) && (x < z)) return x; if (y < z) return y; return z; } /* * (non-Javadoc) * * @see toolbox.align.SequenceAlignment#getAlignment() */ public String getAlignmentString() throws BioException { return alignment; } public Alignment getAlignment() { return pairalign; } /* * (non-Javadoc) * * @see * toolbox.align.SequenceAlignment#alignAll(org.biojava.bio.seq.SequenceIterator * , org.biojava.bio.seq.db.SequenceDB) */ public List<Alignment> alignAll(SequenceIterator source, SequenceDB subjectDB) throws NoSuchElementException, BioException { List<Alignment> l = new LinkedList<Alignment>(); while (source.hasNext()) { Sequence query = source.nextSequence(); // compare all the sequences of both sets. SequenceIterator target = subjectDB.sequenceIterator(); while (target.hasNext()) try { l.add(getAlignment(query, target.nextSequence())); // pairwiseAlignment(query, target.nextSequence()); } catch (Exception exc) { exc.printStackTrace(); } } return l; } /** * Global pairwise sequence alignment of two BioJava-Sequence objects * according to the Needleman-Wunsch-algorithm. * * @see org.biojava.bio.alignment.SequenceAlignment#pairwiseAlignment(org.biojava.bio.symbol.SymbolList, * org.biojava.bio.symbol.SymbolList) */ public int pairwiseAlignment(SymbolList query, SymbolList subject) throws BioException { Sequence squery = null; Sequence ssubject = null; if (query instanceof Sequence) { squery = (Sequence) query; } else { // make it a sequence squery = new SimpleSequence(query, "", "query", new SimpleAnnotation()); } if (subject instanceof Sequence) { ssubject = (Sequence) subject; } else { // make it a sequence ssubject = new SimpleSequence(subject, "", "subject", new SimpleAnnotation()); } SymbolTokenization st = null; st = subMatrix.getAlphabet().getTokenization("default"); if (squery.getAlphabet().equals(ssubject.getAlphabet()) && squery.getAlphabet().equals(subMatrix.getAlphabet())) { StringBuffer[] align = { new StringBuffer(), new StringBuffer() }; long time = System.currentTimeMillis(); int i, j; this.CostMatrix = new int[squery.length() + 1][ssubject.length() + 1]; /* * Variables for the traceback */ StringBuffer path = new StringBuffer(); // construct the matrix: CostMatrix[0][0] = 0; /* * If we want to have affine gap penalties, we have to initialise * additional matrices: If this is not necessary, we won't do that * (because it's expensive). */ if ((gapExt != delete) || (gapExt != insert)) { int[][] E = new int[squery.length() + 1][ssubject.length() + 1]; // Inserts int[][] F = new int[squery.length() + 1][ssubject.length() + 1]; // Deletes E[0][0] = F[0][0] = Integer.MAX_VALUE; // Double.MAX_VALUE; for (i = 1; i <= squery.length(); i++) { // CostMatrix[i][0] = CostMatrix[i-1][0] + delete; E[i][0] = Integer.MAX_VALUE; // Double.POSITIVE_INFINITY; CostMatrix[i][0] = F[i][0] = delete + i * gapExt; } for (j = 1; j <= ssubject.length(); j++) { // CostMatrix[0][j] = CostMatrix[0][j - 1] + insert; F[0][j] = Integer.MAX_VALUE; // Double.POSITIVE_INFINITY; CostMatrix[0][j] = E[0][j] = insert + j * gapExt; } for (i = 1; i <= squery.length(); i++) for (j = 1; j <= ssubject.length(); j++) { E[i][j] = Math.min(E[i][j - 1], CostMatrix[i][j - 1] + insert) + gapExt; F[i][j] = Math.min(F[i - 1][j], CostMatrix[i - 1][j] + delete) + gapExt; CostMatrix[i][j] = min(E[i][j], F[i][j], CostMatrix[i - 1][j - 1] - matchReplace(squery, ssubject, i, j)); } /* * Traceback for affine gap penalties. */ boolean[] gap_extend = { false, false }; j = this.CostMatrix[CostMatrix.length - 1].length - 1; for (i = this.CostMatrix.length - 1; i > 0;) { do { // only Insert. if (i == 0) { align[0].insert(0, '~'); align[1].insert(0, st.tokenizeSymbol(ssubject .symbolAt(j path.insert(0, ' '); // only Delete. } else if (j == 0) { align[0].insert(0, st.tokenizeSymbol(squery .symbolAt(i align[1].insert(0, '~'); path.insert(0, ' '); // Match/Replace } else if ((CostMatrix[i][j] == CostMatrix[i - 1][j - 1] - matchReplace(squery, ssubject, i, j)) && !(gap_extend[0] || gap_extend[1])) { if (squery.symbolAt(i) == ssubject.symbolAt(j)) path.insert(0, '|'); else path.insert(0, ' '); align[0].insert(0, st.tokenizeSymbol(squery .symbolAt(i align[1].insert(0, st.tokenizeSymbol(ssubject .symbolAt(j // Insert || finish gap if extended gap is // opened } else if (CostMatrix[i][j] == E[i][j] || gap_extend[0]) { // check if gap has been extended or freshly // opened gap_extend[0] = (E[i][j] != CostMatrix[i][j - 1] + insert + gapExt); align[0].insert(0, '-'); align[1].insert(0, st.tokenizeSymbol(ssubject .symbolAt(j path.insert(0, ' '); // Delete || finish gap if extended gap is // opened } else { // check if gap has been extended or freshly // opened gap_extend[1] = (F[i][j] != CostMatrix[i - 1][j] + delete + gapExt); align[0].insert(0, st.tokenizeSymbol(squery .symbolAt(i align[1].insert(0, '-'); path.insert(0, ' '); } } while (j > 0); } /* * No affine gap penalties, constant gap penalties, which is * much faster and needs less memory. */ } else { for (i = 1; i <= squery.length(); i++) CostMatrix[i][0] = CostMatrix[i - 1][0] + delete; for (j = 1; j <= ssubject.length(); j++) CostMatrix[0][j] = CostMatrix[0][j - 1] + insert; for (i = 1; i <= squery.length(); i++) for (j = 1; j <= ssubject.length(); j++) { CostMatrix[i][j] = min(CostMatrix[i - 1][j] + delete, CostMatrix[i][j - 1] + insert, CostMatrix[i - 1][j - 1] - matchReplace(squery, ssubject, i, j)); } /* * Traceback for constant gap penalties. */ j = this.CostMatrix[CostMatrix.length - 1].length - 1; // System.out.println(printCostMatrix(CostMatrix, // query.seqString().toCharArray(), // subject.seqString().toCharArray())); for (i = this.CostMatrix.length - 1; i > 0;) { do { // only Insert. if (i == 0) { align[0].insert(0, '~'); align[1].insert(0, st.tokenizeSymbol(ssubject .symbolAt(j path.insert(0, ' '); // only Delete. } else if (j == 0) { align[0].insert(0, st.tokenizeSymbol(squery .symbolAt(i align[1].insert(0, '~'); path.insert(0, ' '); // Match/Replace } else if (CostMatrix[i][j] == CostMatrix[i - 1][j - 1] - matchReplace(squery, ssubject, i, j)) { if (squery.symbolAt(i) == ssubject.symbolAt(j)) path.insert(0, '|'); else path.insert(0, ' '); align[0].insert(0, st.tokenizeSymbol(squery .symbolAt(i align[1].insert(0, st.tokenizeSymbol(ssubject .symbolAt(j // Insert } else if (CostMatrix[i][j] == CostMatrix[i][j - 1] + insert) { align[0].insert(0, '-'); align[1].insert(0, st.tokenizeSymbol(ssubject .symbolAt(j path.insert(0, ' '); // Delete } else { align[0].insert(0, st.tokenizeSymbol(squery .symbolAt(i align[1].insert(0, '-'); path.insert(0, ' '); } } while (j > 0); } } /* * From here both cases are equal again. */ squery = new SimpleGappedSequence(new SimpleSequence( new SimpleSymbolList(squery.getAlphabet().getTokenization( "token"), align[0].toString()), squery.getURN(), squery.getName(), squery.getAnnotation())); ssubject = new SimpleGappedSequence(new SimpleSequence( new SimpleSymbolList(ssubject.getAlphabet() .getTokenization("token"), align[1].toString()), ssubject.getURN(), ssubject.getName(), ssubject .getAnnotation())); Map<String, Sequence> m = new HashMap<String, Sequence>(); m.put(squery.getName(), squery); m.put(ssubject.getName(), ssubject); pairalign = new SimpleAlignment(m); // this.printCostMatrix(queryChar, targetChar); // only for // tests // important this.alignment = formatOutput(squery.getName(), // name of the // query // sequence ssubject.getName(), // name of the target sequence align, // the String representation of the alignment path, // String match/missmatch representation 0, // Start position of the alignment in the query // sequence CostMatrix.length - 1, // End position of the alignment // in the query sequence CostMatrix.length - 1, // length of the query sequence 0, // Start position of the alignment in the target // sequence CostMatrix[0].length - 1, // End position of the // alignment in the target sequence CostMatrix[0].length - 1, // length of the target // sequence getEditDistance(), // the edit distance System.currentTimeMillis() - time, subMatrix, st) + System.getProperty("line.separator"); // time // consumption // System.out.println(printCostMatrix(CostMatrix, // query.seqString().toCharArray(), // subject.seqString().toCharArray())); int score = getEditDistance(); pairalign.setScore(score); return score; } else throw new BioException( "Alphabet missmatch occured: sequences with different alphabet cannot be aligned."); } /** * This method computes the scores for the substitution of the i-th symbol * of query by the j-th symbol of subject. * * @param query * The query sequence * @param subject * The target sequence * @param i * The position of the symbol under consideration within the * query sequence (starting from one) * @param j * The position of the symbol under consideration within the * target sequence * @return The score for the given substitution. */ private int matchReplace(Sequence query, Sequence subject, int i, int j) { try { return subMatrix.getValueAt(query.symbolAt(i), subject.symbolAt(j)); } catch (Exception exc) { if (query.symbolAt(i).getMatches().contains(subject.symbolAt(j)) || subject.symbolAt(j).getMatches().contains( query.symbolAt(i))) return -match; return -replace; } } }
package ti.modules.titanium.ui; import java.util.ArrayList; import java.util.HashMap; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.annotations.Kroll; import org.appcelerator.kroll.common.AsyncResult; import org.appcelerator.kroll.common.Log; import org.appcelerator.kroll.common.TiConfig; import org.appcelerator.kroll.common.TiMessenger; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.TiContext; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.view.TiUIView; import ti.modules.titanium.ui.widget.TiUITableView; import android.app.Activity; import android.os.Message; @Kroll.proxy(creatableInModule=UIModule.class, propertyAccessors = { TiC.PROPERTY_FILTER_ATTRIBUTE, TiC.PROPERTY_FILTER_CASE_INSENSITIVE, TiC.PROPERTY_HEADER_TITLE, TiC.PROPERTY_HEADER_VIEW, TiC.PROPERTY_FOOTER_TITLE, TiC.PROPERTY_FOOTER_VIEW, TiC.PROPERTY_SEARCH, TiC.PROPERTY_SEPARATOR_COLOR }) public class TableViewProxy extends TiViewProxy { private static final String LCAT = "TableViewProxy"; private static final boolean DBG = TiConfig.LOGD; private static final int INSERT_ROW_BEFORE = 0; private static final int INSERT_ROW_AFTER = 1; private static final int MSG_UPDATE_VIEW = TiViewProxy.MSG_LAST_ID + 5001; private static final int MSG_SCROLL_TO_INDEX = TiViewProxy.MSG_LAST_ID + 5002; private static final int MSG_SET_DATA = TiViewProxy.MSG_LAST_ID + 5003; private static final int MSG_DELETE_ROW = TiViewProxy.MSG_LAST_ID + 5004; private static final int MSG_INSERT_ROW = TiViewProxy.MSG_LAST_ID + 5005; private static final int MSG_APPEND_ROW = TiViewProxy.MSG_LAST_ID + 5006; private static final int MSG_SCROLL_TO_TOP = TiViewProxy.MSG_LAST_ID + 5007; public static final String CLASSNAME_DEFAULT = "__default__"; public static final String CLASSNAME_HEADER = "__header__"; public static final String CLASSNAME_NORMAL = "__normal__"; class RowResult { int sectionIndex; TableViewSectionProxy section; TableViewRowProxy row; int rowIndexInSection; } private ArrayList<TableViewSectionProxy> localSections; public TableViewProxy() { super(); //eventManager.addOnEventChangeListener(this); } public TableViewProxy(TiContext tiContext) { this(); } @Override public void handleCreationDict(KrollDict dict) { Object data[] = null; if (dict.containsKey(TiC.PROPERTY_DATA)) { Object o = dict.get(TiC.PROPERTY_DATA); if (o != null && o instanceof Object[]) { data = (Object[]) o; dict.remove(TiC.PROPERTY_DATA); // don't override our data accessor } } super.handleCreationDict(dict); if (data != null) { processData(data); } } @Override public void releaseViews() { super.releaseViews(); if (localSections != null) { for (TableViewSectionProxy section : localSections) { section.releaseViews(); } } } @Override public TiUIView createView(Activity activity) { return new TiUITableView(this); } public TiUITableView getTableView() { return (TiUITableView) getOrCreateView(); } @Kroll.method public void updateRow(Object row, Object data, @Kroll.argument(optional=true) KrollDict options) { TableViewSectionProxy sectionProxy = null; int rowIndex = -1; if (row instanceof Number) { RowResult rr = new RowResult(); rowIndex = ((Number)row).intValue(); locateIndex(rowIndex, rr); sectionProxy = rr.section; } else if (row instanceof TableViewRowProxy) { ArrayList<TableViewSectionProxy> sections = getSectionsArray(); sectionLoop: for (int i = 0; i < sections.size(); i++) { ArrayList<TableViewRowProxy> rows = sections.get(i).rows; for (int j = 0; j < rows.size(); j++) { if (rows.get(j) == row) { sectionProxy = sections.get(i); rowIndex = j; break sectionLoop; } } } } if (sectionProxy != null) { sectionProxy.updateRowAt(rowIndex, rowProxyFor(data)); getTableView().setModelDirty(); updateView(); } } // options argument exists in order to maintain parity with iOS, do not remove @Kroll.method public void appendRow(Object rows, @Kroll.argument(optional=true) KrollDict options) { if (TiApplication.isUIThread()) { handleAppendRow(rows); return; } TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_APPEND_ROW), rows); } private void handleAppendRow(Object rows) { Object[] rowList = null; if (rows instanceof Object[]) { rowList = (Object[])rows; } else { rowList = new Object[] { rows }; } ArrayList<TableViewSectionProxy> sections = getSectionsArray(); if (sections.size() == 0) { processData(rowList); } else { for (int i = 0; i < rowList.length; i++) { TableViewRowProxy rowProxy = rowProxyFor(rowList[i]); TableViewSectionProxy lastSection = sections.get(sections.size() - 1); TableViewSectionProxy addedToSection = addRowToSection(rowProxy, lastSection); if (lastSection == null || !lastSection.equals(addedToSection)) { sections.add(addedToSection); } rowProxy.setProperty(TiC.PROPERTY_SECTION, addedToSection); rowProxy.setProperty(TiC.PROPERTY_PARENT, addedToSection); } } getTableView().setModelDirty(); updateView(); } @Kroll.method public void deleteRow(int index, @Kroll.argument(optional=true) KrollDict options) { if (TiApplication.isUIThread()) { handleDeleteRow(index); return; } Message message = getMainHandler().obtainMessage(MSG_DELETE_ROW); //Message msg = getUIHandler().obtainMessage(MSG_DELETE_ROW); message.arg1 = index; message.sendToTarget(); } private void handleDeleteRow(int index) { RowResult rr = new RowResult(); if (locateIndex(index, rr)) { rr.section.removeRowAt(rr.rowIndexInSection); getTableView().setModelDirty(); updateView(); } else { throw new IllegalStateException( "Index out of range. Non-existant row at " + index); } } @Kroll.method public int getIndexByName(String name) { int index = -1; int idx = 0; if (name != null) { for (TableViewSectionProxy section : getSections()) { for (TableViewRowProxy row : section.getRows()) { String rname = TiConvert.toString(row.getProperty(TiC.PROPERTY_NAME)); if (rname != null && name.equals(rname)) { index = idx; break; } idx++; } if (index > -1) { break; } } } return index; } @Kroll.method public void insertRowBefore(int index, Object data, @Kroll.argument(optional=true) KrollDict options) { if (TiApplication.isUIThread()) { handleInsertRowBefore(index, data); return; } TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_INSERT_ROW, INSERT_ROW_BEFORE, index), data); } private void handleInsertRowBefore(int index, Object data) { if (getSectionsArray().size() > 0) { if (index < 0) { index = 0; } RowResult rr = new RowResult(); if (locateIndex(index, rr)) { TableViewRowProxy rowProxy = rowProxyFor(data); rr.section.insertRowAt(rr.rowIndexInSection, rowProxy); } else { throw new IllegalStateException( "Index out of range. Non-existant row at " + index); } } else { // Add first row. Object[] args = { rowProxyFor(data) }; processData(args); } getTableView().setModelDirty(); updateView(); } @Kroll.method public void insertRowAfter(int index, Object data, @Kroll.argument(optional=true) KrollDict options) { if (TiApplication.isUIThread()) { handleInsertRowAfter(index, data); return; } TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_INSERT_ROW, INSERT_ROW_AFTER, index), data); } private void handleInsertRowAfter(int index, Object data) { RowResult rr = new RowResult(); if (locateIndex(index, rr)) { // TODO check for section TableViewRowProxy rowProxy = rowProxyFor(data); rr.section.insertRowAt(rr.rowIndexInSection + 1, rowProxy); getTableView().setModelDirty(); updateView(); } else { throw new IllegalStateException( "Index out of range. Non-existant row at " + index); } } @Kroll.getProperty @Kroll.method public TableViewSectionProxy[] getSections() { ArrayList<TableViewSectionProxy> sections = getSectionsArray(); return sections.toArray(new TableViewSectionProxy[sections.size()]); } public ArrayList<TableViewSectionProxy> getSectionsArray() { ArrayList<TableViewSectionProxy> sections = localSections; if (sections == null) { sections = new ArrayList<TableViewSectionProxy>(); localSections = sections; } return sections; } /** * If the row does not carry section information, it will be added * to the currentSection. If it does carry section information (i.e., a header), * that section will be created and the row added to it. Either way, * whichever section the row gets added to will be returned. */ private TableViewSectionProxy addRowToSection(TableViewRowProxy row, TableViewSectionProxy currentSection) { TableViewSectionProxy addedToSection = null; if (currentSection == null || row.hasProperty(TiC.PROPERTY_HEADER)) { addedToSection = new TableViewSectionProxy(); } else { addedToSection = currentSection; } if (row.hasProperty(TiC.PROPERTY_HEADER)) { addedToSection.setProperty(TiC.PROPERTY_HEADER_TITLE, row.getProperty(TiC.PROPERTY_HEADER)); } if (row.hasProperty(TiC.PROPERTY_FOOTER)) { addedToSection.setProperty(TiC.PROPERTY_FOOTER_TITLE, row.getProperty(TiC.PROPERTY_FOOTER)); } addedToSection.add(row); return addedToSection; } public void processData(Object[] data) { ArrayList<TableViewSectionProxy> sections = getSectionsArray(); sections.clear(); TableViewSectionProxy currentSection = null; if (hasProperty(TiC.PROPERTY_HEADER_TITLE)) { currentSection = new TableViewSectionProxy(); sections.add(currentSection); currentSection.setProperty(TiC.PROPERTY_HEADER_TITLE, getProperty(TiC.PROPERTY_HEADER_TITLE)); } if (hasProperty(TiC.PROPERTY_FOOTER_TITLE)) { if (currentSection == null) { currentSection = new TableViewSectionProxy(); sections.add(currentSection); } currentSection.setProperty(TiC.PROPERTY_FOOTER_TITLE, getProperty(TiC.PROPERTY_FOOTER_TITLE)); } for (int i = 0; i < data.length; i++) { Object o = data[i]; if (o instanceof HashMap || o instanceof TableViewRowProxy) { TableViewRowProxy rowProxy = rowProxyFor(o); TableViewSectionProxy addedToSection = addRowToSection(rowProxy, currentSection); if (currentSection == null || !currentSection.equals(addedToSection)) { currentSection = addedToSection; sections.add(currentSection); } } else if (o instanceof TableViewSectionProxy) { currentSection = (TableViewSectionProxy) o; sections.add(currentSection); currentSection.setParent(this); } } } @Kroll.setProperty @Kroll.method public void setData(Object[] args) { Object[] data = args; if (args != null && args.length > 0 && args[0] instanceof Object[]) { data = (Object[]) args[0]; } if (TiApplication.isUIThread()) { handleSetData(data); } else { TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_SET_DATA), data); } } private void handleSetData(Object[] data) { if (data != null) { processData(data); getTableView().setModelDirty(); updateView(); } } @Kroll.getProperty @Kroll.method public Object[] getData() { ArrayList<TableViewSectionProxy> sections = getSectionsArray(); if (sections != null) { return sections.toArray(); } return new Object[0]; } private TableViewRowProxy rowProxyFor(Object row) { TableViewRowProxy rowProxy = null; if (row instanceof TableViewRowProxy) { rowProxy = (TableViewRowProxy) row; } else { KrollDict rowDict = null; if (row instanceof KrollDict) { rowDict = (KrollDict) row; } else if (row instanceof HashMap) { rowDict = new KrollDict((HashMap) row); } if (rowDict != null) { rowProxy = new TableViewRowProxy(); rowProxy.handleCreationDict(rowDict); rowProxy.setProperty(TiC.PROPERTY_CLASS_NAME, CLASSNAME_NORMAL); rowProxy.setProperty(TiC.PROPERTY_ROW_DATA, row); rowProxy.setActivity(getActivity()); } } if (rowProxy == null) { Log.e(LCAT, "unable to create table view row proxy for object, likely an error in the type of the object passed in..."); return null; } rowProxy.setParent(this); return rowProxy; } private boolean locateIndex(int index, RowResult rowResult) { boolean found = false; int rowCount = 0; int sectionIndex = 0; for (TableViewSectionProxy section : getSections()) { int sectionRowCount = (int) section.getRowCount(); if (sectionRowCount + rowCount > index) { rowResult.section = section; rowResult.sectionIndex = sectionIndex; rowResult.row = section.getRows()[index - rowCount]; rowResult.rowIndexInSection = index - rowCount; found = true; break; } else { rowCount += sectionRowCount; } sectionIndex += 1; } return found; } public void updateView() { if (TiApplication.isUIThread()) { getTableView().updateView(); return; } TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_UPDATE_VIEW)); } @Kroll.method public void scrollToIndex(int index) { Message message = getMainHandler().obtainMessage(MSG_SCROLL_TO_INDEX); //Message msg = getUIHandler().obtainMessage(MSG_SCROLL_TO_INDEX); message.arg1 = index; message.sendToTarget(); } @Kroll.method public void scrollToTop(int index) { Message message = getMainHandler().obtainMessage(MSG_SCROLL_TO_TOP); //Message msg = getUIHandler().obtainMessage(MSG_SCROLL_TO_TOP); message.arg1 = index; message.sendToTarget(); } @Override public boolean handleMessage(Message msg) { if (msg.what == MSG_UPDATE_VIEW) { getTableView().updateView(); ((AsyncResult) msg.obj).setResult(0); return true; } else if (msg.what == MSG_SCROLL_TO_INDEX) { getTableView().scrollToIndex(msg.arg1); return true; } else if (msg.what == MSG_SET_DATA) { AsyncResult result = (AsyncResult) msg.obj; Object[] data = (Object[]) result.getArg(); handleSetData(data); result.setResult(0); return true; } else if (msg.what == MSG_INSERT_ROW) { AsyncResult result = (AsyncResult) msg.obj; if (msg.arg1 == INSERT_ROW_AFTER) { handleInsertRowAfter(msg.arg2, result.getArg()); } else { handleInsertRowBefore(msg.arg2, result.getArg()); } result.setResult(0); return true; } else if (msg.what == MSG_APPEND_ROW) { AsyncResult result = (AsyncResult) msg.obj; handleAppendRow(result.getArg()); result.setResult(0); return true; } else if (msg.what == MSG_DELETE_ROW) { handleDeleteRow(msg.arg1); return true; } else if (msg.what == MSG_SCROLL_TO_TOP) { getTableView().scrollToTop(msg.arg1); return true; } return super.handleMessage(msg); } // labels only send out click events when they are explicitly told to do so. // we need to tell each label child to enable clicks when a click listener is added @Override public void eventListenerAdded(String eventName, int count, KrollProxy proxy) { super.eventListenerAdded(eventName, count, proxy); if (eventName.equals(TiC.EVENT_CLICK) && proxy == this) { for (TableViewSectionProxy section : getSections()) { for (TableViewRowProxy row : section.getRows()) { row.setLabelsClickable(true); } } } } @Override public void eventListenerRemoved(String eventName, int count, KrollProxy proxy) { super.eventListenerRemoved(eventName, count, proxy); if (eventName.equals(TiC.EVENT_CLICK) && count == 0 && proxy == this) { for (TableViewSectionProxy section : getSections()) { for (TableViewRowProxy row : section.getRows()) { row.setLabelsClickable(false); } } } } }
package eu.nerro.wolappla.model; public class Device { private String name; private String macAddress; private String ipAddress; private int port; }
package hudson.model; import java.util.Map; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.export.Exported; public class RunParameterValue extends ParameterValue { private final String runId; @DataBoundConstructor public RunParameterValue(String name, String runId, String description) { super(name, description); this.runId = runId; } public RunParameterValue(String name, String runId) { super(name, null); this.runId = runId; } public Run getRun() { return Run.fromExternalizableId(runId); } public String getRunId() { return runId; } @Exported public String getJobName() { return runId.split(" } @Exported public String getNumber() { return runId.split(" } /** * Exposes the name/value as an environment variable. */ @Override public void buildEnvVars(AbstractBuild<?,?> build, Map<String,String> env) { env.put(name.toUpperCase(), Hudson.getInstance().getRootUrl() + getRun().getUrl()); } @Override public String getShortDescription() { return "(RunParameterValue) " + getName() + "='" + getRunId() + "'"; } }
package org.wildfly.swarm.container; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import java.util.stream.Collectors; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoadException; import org.jboss.modules.log.StreamModuleLogger; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.Domain; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.wildfly.swarm.bootstrap.modules.BootModuleLoader; /** * A WildFly-Swarm container. * * @author Bob McWhirter * @author Ken Finnigan */ public class Container { private Map<Class<? extends Fraction>, Fraction> fractions = new ConcurrentHashMap<>(); private List<Fraction> dependentFractions = new ArrayList<>(); private Set<Class<? extends Fraction>> defaultFractionTypes = new HashSet<>(); private List<SocketBindingGroup> socketBindingGroups = new ArrayList<>(); private Map<String, List<SocketBinding>> socketBindings = new HashMap<>(); private List<Interface> interfaces = new ArrayList<>(); private Server server; private Deployer deployer; private Domain domain; /** Command line args if any */ private String[] args; /** * Construct a new, un-started container. * * @throws Exception If an error occurs performing classloading and initialization magic. */ public Container() throws Exception { this(false); } /** * Construct a new, un-started container. * * @param debugBootstrap - flag to indicate if the module layer should be put into bootstrap debug mode. Same as * the jboss-module -debuglog mode which enables trace logging to System.out during the * initial bootstrap of the module layer. * @throws Exception If an error occurs performing classloading and initialization magic. */ public Container(boolean debugBootstrap) throws Exception { createServer(debugBootstrap); createShrinkWrapDomain(); } private void createShrinkWrapDomain() throws ModuleLoadException { ClassLoader originalCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(Container.class.getClassLoader()); this.domain = ShrinkWrap.getDefaultDomain(); } finally { Thread.currentThread().setContextClassLoader(originalCl); } } private void createServer(boolean debugBootstrap) throws Exception { if (System.getProperty("boot.module.loader") == null) { System.setProperty("boot.module.loader", BootModuleLoader.class.getName()); } if (debugBootstrap) { Module.setModuleLogger(new StreamModuleLogger(System.err)); } Module module = Module.getBootModuleLoader().loadModule(ModuleIdentifier.create("org.wildfly.swarm.runtime.container")); Class<?> serverClass = module.getClassLoader().loadClass("org.wildfly.swarm.runtime.container.RuntimeServer"); this.server = (Server) serverClass.newInstance(); } public void applyFractionDefaults(Server server) throws Exception { Set<Class<? extends Fraction>> availFractions = server.getFractionTypes(); // Process any dependent fractions from Application added fractions if (!this.dependentFractions.isEmpty()) { this.dependentFractions.stream().filter(dependentFraction -> this.fractions.get(dependentFraction.getClass()) == null).forEach(this::fraction); this.dependentFractions.clear(); } // Provide defaults for those remaining availFractions.stream().filter(fractionClass -> this.fractions.get(fractionClass) == null).forEach(fractionClass -> fractionDefault(server.createDefaultFor(fractionClass))); // Determine if any dependent fractions should override non Application added fractions if (!this.dependentFractions.isEmpty()) { this.dependentFractions.stream().filter(dependentFraction -> this.fractions.get(dependentFraction.getClass()) == null || (this.fractions.get(dependentFraction.getClass()) != null && this.defaultFractionTypes.contains(dependentFraction.getClass()))).forEach(this::fraction); this.dependentFractions.clear(); } } /** * Add a fraction to the container. * * @param fraction The fraction to add. * @return The container. */ public Container subsystem(Fraction fraction) { return fraction(fraction); } /** * Add a fraction to the container. * * @param fraction The fraction to add. * @return The container. */ public Container fraction(Fraction fraction) { this.fractions.put(fractionRoot(fraction.getClass()), fraction); fraction.initialize(new InitContext()); return this; } public List<Fraction> fractions() { return this.fractions.values().stream().collect(Collectors.toList()); } private void fractionDefault(Fraction defaultFraction) { if ( defaultFraction == null ) { return; } this.defaultFractionTypes.add(fractionRoot(defaultFraction.getClass())); fraction(defaultFraction); } private Class<? extends Fraction> fractionRoot(Class<? extends Fraction> fractionClass) { Class<? extends Fraction> fractionRoot = fractionClass; boolean rootFound = false; while (!rootFound) { Class<?>[] interfaces = fractionRoot.getInterfaces(); for (Class<?> anInterface : interfaces) { if (anInterface.getName().equals(Fraction.class.getName())) { rootFound = true; break; } } if (!rootFound) { fractionRoot = (Class<? extends Fraction>) fractionRoot.getSuperclass(); } } return fractionRoot; } /** * Add a fraction to the container that is a dependency of another fraction. * * @param fraction The dependent fraction to add. */ private void dependentFraction(Fraction fraction) { this.dependentFractions.add(fraction); } /** * Configure a network interface. * * @param name The name of the interface. * @param expression The expression to define the interface. * @return The container. */ public Container iface(String name, String expression) { this.interfaces.add(new Interface(name, expression)); return this; } public List<Interface> ifaces() { return this.interfaces; } /** * Configure a socket-binding-group. * * @param group The socket-binding group to add. * @return The container. */ public Container socketBindingGroup(SocketBindingGroup group) { this.socketBindingGroups.add(group); return this; } public List<SocketBindingGroup> socketBindingGroups() { return this.socketBindingGroups; } public SocketBindingGroup getSocketBindingGroup(String name) { for (SocketBindingGroup each : this.socketBindingGroups) { if (each.name().equals(name)) { return each; } } return null; } public Map<String, List<SocketBinding>> socketBindings() { return this.socketBindings; } void socketBinding(SocketBinding binding) { socketBinding("default-sockets", binding); } void socketBinding(String groupName, SocketBinding binding) { List<SocketBinding> list = this.socketBindings.get(groupName); if (list == null) { list = new ArrayList<>(); this.socketBindings.put(groupName, list); } for (SocketBinding each : list) { if (each.name().equals(binding.name())) { throw new RuntimeException("Socket binding '" + binding.name() + "' already configured for '" + each.portExpression() + "'"); } } list.add(binding); } /** * Start the container. * * @return The container. * @throws Exception if an error occurs. */ public Container start() throws Exception { this.deployer = this.server.start(this); return this; } /** * Stop the container, undeploying all deployments. * * @return THe container. * @throws Exception If an error occurs. */ public Container stop() throws Exception { this.server.stop(); return this; } /** * Start the container with a deployment. * <p/> * <p>Effectively calls {@code start().deploy(deployment)}</p> * * @param deployment The deployment to deploy. * @return The container. * @throws Exception if an error occurs. * @see #start() * @see #deploy(Archive) */ public Container start(Archive deployment) throws Exception { return start().deploy(deployment); } /** * Deploy the default WAR deployment. * <p/> * <p>For WAR-based applications, the primary WAR artifact iwll be deployed.</p> * * @return The container. * @throws Exception if an error occurs. */ public Container deploy() throws Exception { return deploy(createDefaultDeployment()); } /** * Deploy an archive. * * @param deployment The ShrinkWrap archive to deploy. * @return The container. * @throws Exception if an error occurs. */ public Container deploy(Archive deployment) throws Exception { this.deployer.deploy(deployment); return this; } /** * Get the possibly null container main method arguments. * @return main method arguments, possibly null */ public String[] getArgs() { return args; } /** * Set the main method arguments. This will be available as a ValueService<String[]> under the name * wildfly.swarm.main-args * @param args arguments passed to the main(String[]) method. */ public void setArgs(String[] args) { this.args = args; } /** * Initialization Context to be passed to Fractions to allow them to provide * additional functionality into the Container. */ public class InitContext { public void fraction(Fraction fraction) { Container.this.dependentFraction(fraction); } public void socketBinding(SocketBinding binding) { socketBinding("default-sockets", binding ); } public void socketBinding(String groupName, SocketBinding binding) { Container.this.socketBinding(groupName, binding ); } } protected Archive createDefaultDeployment() throws Exception { Module m1 = Module.getBootModuleLoader().loadModule(ModuleIdentifier.create("org.wildfly.swarm.bootstrap")); ServiceLoader<DefaultDeploymentFactory> providerLoader = m1.loadService(DefaultDeploymentFactory.class); Iterator<DefaultDeploymentFactory> providerIter = providerLoader.iterator(); if (!providerIter.hasNext()) { providerLoader = ServiceLoader.load(DefaultDeploymentFactory.class, ClassLoader.getSystemClassLoader()); providerIter = providerLoader.iterator(); } Map<String, DefaultDeploymentFactory> factories = new HashMap<>(); while (providerIter.hasNext()) { DefaultDeploymentFactory factory = providerIter.next(); DefaultDeploymentFactory current = factories.get(factory.getType()); if (current == null) { factories.put(factory.getType(), factory); } else { // if this one is high priority than the previously-seen // factory, replace it. if (factory.getPriority() > current.getPriority()) { factories.put(factory.getType(), factory); } } } DefaultDeploymentFactory factory = factories.get(determineDeploymentType()); if (factory == null) { throw new RuntimeException("Unable to create default deployment"); } return factory.create(this); } protected String determineDeploymentType() throws IOException { String artifact = System.getProperty("wildfly.swarm.app.path"); if (artifact != null) { int dotLoc = artifact.lastIndexOf('.'); if (dotLoc >= 0) { return artifact.substring(dotLoc + 1); } } artifact = System.getProperty("wildfly.swarm.app.artifact"); if (artifact != null) { int dotLoc = artifact.lastIndexOf('.'); if (dotLoc >= 0) { return artifact.substring(dotLoc + 1); } } if (Files.exists(Paths.get("pom.xml"))) { try (BufferedReader in = new BufferedReader(new FileReader(Paths.get("pom.xml").toFile()))) { String line = null; while ((line = in.readLine()) != null) { line = line.trim(); if (line.equals("<packaging>jar</packaging>")) { return "jar"; } else if (line.equals("<packaging>war</packaging>")) { return "war"; } } } } if (Files.exists(Paths.get("Mavenfile"))) { try (BufferedReader in = new BufferedReader(new FileReader(Paths.get("Mavenfile").toFile()))) { String line = null; while ((line = in.readLine()) != null) { line = line.trim(); if (line.equals("packaging :jar")) { return "jar"; } else if (line.equals("packaging :war")) { return "war"; } } } } return "unknown"; } }
package org.helioviewer.jhv.plugins.eveplugin.draw; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.helioviewer.jhv.base.Range; import org.helioviewer.jhv.base.interval.Interval; import org.helioviewer.jhv.base.logging.Log; import org.helioviewer.jhv.base.time.JHVDate; import org.helioviewer.jhv.data.datatype.event.JHVEventHighlightListener; import org.helioviewer.jhv.data.datatype.event.JHVRelatedEvents; import org.helioviewer.jhv.display.Displayer; import org.helioviewer.jhv.layers.Layers; import org.helioviewer.jhv.layers.LayersListener; import org.helioviewer.jhv.layers.TimeListener; import org.helioviewer.jhv.plugins.eveplugin.DrawConstants; import org.helioviewer.jhv.plugins.eveplugin.draw.YAxisElement.YAxisLocation; import org.helioviewer.jhv.plugins.eveplugin.lines.data.DownloadController; import org.helioviewer.jhv.plugins.eveplugin.view.linedataselector.LineDataSelectorElement; import org.helioviewer.jhv.plugins.eveplugin.view.linedataselector.LineDataSelectorModel; import org.helioviewer.jhv.plugins.eveplugin.view.linedataselector.LineDataSelectorModelListener; import org.helioviewer.jhv.viewmodel.view.View; public class DrawController implements LineDataSelectorModelListener, JHVEventHighlightListener, LayersListener, TimeListener, PlotAreaSpaceListener { private static DrawController instance; private Interval selectedInterval; private Interval availableInterval; private PlotAreaSpace pas; private final List<TimingListener> tListeners; private Rectangle graphSize; // private Rectangle graphArea; // private Rectangle plotArea; // private Rectangle leftAxisArea; private final List<GraphDimensionListener> gdListeners; private List<YAxisElement> yAxisSet; private final Map<DrawableType, Set<DrawableElement>> drawableElements; private final List<DrawControllerListener> listeners; private DrawController() { drawableElements = new HashMap<DrawableType, Set<DrawableElement>>(); listeners = new ArrayList<DrawControllerListener>(); yAxisSet = new ArrayList<YAxisElement>(); tListeners = new ArrayList<TimingListener>(); gdListeners = new ArrayList<GraphDimensionListener>(); graphSize = new Rectangle(); Date d = new Date(); availableInterval = new Interval(new Date(d.getTime() - 86400 * 1000), d); selectedInterval = availableInterval; LineDataSelectorModel.getSingletonInstance().addLineDataSelectorModelListener(this); pas = PlotAreaSpace.getSingletonInstance(); pas.addPlotAreaSpaceListener(this); } public static DrawController getSingletonInstance() { if (instance == null) { instance = new DrawController(); JHVRelatedEvents.addHighlightListener(instance); JHVRelatedEvents.addHighlightListener(Displayer.getSingletonInstance()); } return instance; } public void addDrawControllerListener(DrawControllerListener listener) { listeners.add(listener); } public void removeDrawControllerListener(DrawControllerListener listener) { listeners.remove(listener); } public void addGraphDimensionListener(GraphDimensionListener l) { gdListeners.add(l); } public void addTimingListener(TimingListener listener) { tListeners.add(listener); } public void updateDrawableElement(DrawableElement drawableElement, boolean needsFire) { addDrawableElement(drawableElement, false); if (needsFire && drawableElement.hasElementsToDraw()) { fireRedrawRequest(); } } private void addDrawableElement(DrawableElement element, boolean redraw) { Set<DrawableElement> elements = drawableElements.get(element.getDrawableElementType().getLevel()); if (elements == null) { elements = new HashSet<DrawableElement>(); drawableElements.put(element.getDrawableElementType().getLevel(), elements); } elements.add(element); if (element.getYAxisElement() != null) { if (!yAxisSet.contains(element.getYAxisElement())) { yAxisSet.add(element.getYAxisElement()); } } if (redraw) { fireRedrawRequest(); } } private void removeDrawableElement(DrawableElement element, boolean redraw, boolean keepYAxisElement) { Set<DrawableElement> elements = drawableElements.get(element.getDrawableElementType().getLevel()); if (elements != null && !keepYAxisElement) { elements.remove(element); if (elements.isEmpty()) { drawableElements.remove(element.getDrawableElementType().getLevel()); } createYAxisSet(); } if (redraw) { fireRedrawRequest(); } } public void removeDrawableElement(DrawableElement element) { removeDrawableElement(element, true, false); } public List<YAxisElement> getYAxisElements() { return yAxisSet; } public Map<DrawableType, Set<DrawableElement>> getDrawableElements() { return drawableElements; } public void setSelectedRange(Range selectedRange) { fireRedrawRequest(); } public void fireRedrawRequest() { for (DrawControllerListener l : listeners) { l.drawRequest(); } } public void setAvailableInterval(final Interval interval) { availableInterval = makeCompleteDay(interval.start, interval.end); fireAvailableIntervalChanged(); // request data if needed final Calendar calendar = new GregorianCalendar(); calendar.clear(); calendar.setTime(availableInterval.end); calendar.add(Calendar.DAY_OF_MONTH, -1); final Interval downloadInterval = new Interval(availableInterval.start, calendar.getTime()); DownloadController.getSingletonInstance().updateBands(downloadInterval, selectedInterval); setSelectedInterval(selectedInterval, false, false); } public final Interval getAvailableInterval() { return availableInterval; } @Override public void downloadStartded(LineDataSelectorElement element) { } @Override public void downloadFinished(LineDataSelectorElement element) { } @Override public void lineDataAdded(LineDataSelectorElement element) { } @Override public void lineDataRemoved(LineDataSelectorElement element) { fireRedrawRequest(); } @Override public void lineDataUpdated(LineDataSelectorElement element) { fireRedrawRequest(); } private void fireRedrawRequestMovieFrameChanged(final Date time) { for (DrawControllerListener l : listeners) { l.drawMovieLineRequest(time); } } @Override public void timeChanged(JHVDate date) { fireRedrawRequestMovieFrameChanged(date.getDate()); } public Date getLastDateWithData() { Date lastDate = null; for (Set<DrawableElement> des : drawableElements.values()) { for (DrawableElement de : des) { if (de.getLastDateWithData() != null) { if (lastDate == null || de.getLastDateWithData().before(lastDate)) { lastDate = de.getLastDateWithData(); } } } } return lastDate; } @Override public void eventHightChanged(JHVRelatedEvents event) { fireRedrawRequest(); } @Override public void layerAdded(View view) { Interval interval = new Interval(Layers.getStartDate().getDate(), Layers.getEndDate().getDate()); if (availableInterval == null) { availableInterval = interval; } else { Date start = availableInterval.start; if (interval.start.before(start)) { start = interval.start; } Date end = availableInterval.end; if (interval.end.after(end)) { end = interval.end; } setAvailableInterval(new Interval(start, end)); } TimeIntervalLockModel lockModel = TimeIntervalLockModel.getInstance(); if (lockModel.isLocked()) { setSelectedInterval(interval, true, false); lockModel.setLocked(true); } } @Override public void activeLayerChanged(View view) { if (view == null) { fireRedrawRequestMovieFrameChanged(null); } } private Interval makeCompleteDay(final Date start, final Date end) { Date endDate = end; if (end.getTime() > System.currentTimeMillis()) { endDate = new Date(); } final Calendar calendar = new GregorianCalendar(); calendar.clear(); calendar.setTime(start); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); Date s = calendar.getTime(); calendar.clear(); calendar.setTime(endDate); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); calendar.add(Calendar.DAY_OF_MONTH, 1); Date e = calendar.getTime(); return new Interval(s, e); } public Interval setSelectedInterval(final Interval newSelectedInterval, boolean useFullValueSpace, boolean resetAvailable) { setSelectedInterval(newSelectedInterval, useFullValueSpace, true, resetAvailable); return selectedInterval; } private void setSelectedInterval(final Interval newSelectedInterval, boolean useFullValueSpace, boolean willUpdatePlotAreaSpace, boolean resetAvailable) { if (newSelectedInterval.start.compareTo(newSelectedInterval.end) <= 0) { if (availableInterval.containsInclusive(newSelectedInterval)) { selectedInterval = newSelectedInterval; if (resetAvailable) { setAvailableInterval(newSelectedInterval); } } else { Date start = newSelectedInterval.start; Date end = newSelectedInterval.end; Date availableStart = availableInterval.start; Date availableEnd = availableInterval.end; boolean changeAvailableInterval = false; if (!availableInterval.containsPointInclusive(start) && !availableInterval.containsPointInclusive(end)) { changeAvailableInterval = true; availableStart = start; availableEnd = end; } if (start.equals(end)) { selectedInterval = new Interval(availableStart, availableEnd); } else { selectedInterval = new Interval(start, end); } if (changeAvailableInterval) { setAvailableInterval(new Interval(availableStart, availableEnd)); } } if (willUpdatePlotAreaSpace) { updatePlotAreaSpace(); } fireSelectedIntervalChanged(useFullValueSpace); fireRedrawRequest(); } else { Log.debug("Start was after end. Set by: "); Thread.dumpStack(); } } public Interval getSelectedInterval() { return selectedInterval; } private void fireSelectedIntervalChanged(boolean keepFullValueRange) { for (TimingListener listener : tListeners) { listener.selectedIntervalChanged(keepFullValueRange); } } private void updatePlotAreaSpace() { long diffAvailable = availableInterval.end.getTime() - availableInterval.start.getTime(); double diffPlotAreaTime = pas.getScaledMaxTime() - pas.getScaledMinTime(); double scaledSelectedStart = pas.getScaledMinTime() + (1.0 * (selectedInterval.start.getTime() - availableInterval.start.getTime()) * diffPlotAreaTime / diffAvailable); double scaledSelectedEnd = pas.getScaledMinTime() + (1.0 * (selectedInterval.end.getTime() - availableInterval.start.getTime()) * diffPlotAreaTime / diffAvailable); pas.setMinSelectedTimeDiff(60000.0 / diffAvailable); pas.setScaledSelectedTime(scaledSelectedStart, scaledSelectedEnd, true); } private void fireAvailableIntervalChanged() { for (TimingListener listener : tListeners) { listener.availableIntervalChanged(); } } @Override public void plotAreaSpaceChanged(double scaledMinTime, double scaledMaxTime, double scaledSelectedMinTime, double scaledSelectedMaxTime, boolean forced) { long diffTime = availableInterval.end.getTime() - availableInterval.start.getTime(); double scaleDiff = scaledMaxTime - scaledMinTime; double selectedMin = (scaledSelectedMinTime - scaledMinTime) / scaleDiff; double selectedMax = (scaledSelectedMaxTime - scaledMinTime) / scaleDiff; Date newSelectedStartTime = new Date(availableInterval.start.getTime() + Math.round(diffTime * selectedMin)); Date newSelectedEndTime = new Date(availableInterval.start.getTime() + Math.round(diffTime * selectedMax)); if (forced || !(newSelectedEndTime.equals(selectedInterval.end) && newSelectedStartTime.equals(selectedInterval.start))) { setSelectedInterval(new Interval(newSelectedStartTime, newSelectedEndTime), false, false, false); } } @Override public void availablePlotAreaSpaceChanged(double oldMinTime, double oldMaxTime, double newMinTime, double newMaxTime) { if (oldMinTime > newMinTime || oldMaxTime < newMaxTime) { double timeRatio = (availableInterval.end.getTime() - availableInterval.start.getTime()) / (oldMaxTime - oldMinTime); double startDifference = oldMinTime - newMinTime; double endDifference = newMaxTime - oldMaxTime; Date tempStartDate = new Date(availableInterval.start.getTime() - Math.round(startDifference * timeRatio)); Date tempEndDate = new Date(availableInterval.end.getTime() + Math.round(endDifference * timeRatio)); setAvailableInterval(new Interval(tempStartDate, tempEndDate)); } } public PlotAreaSpace getPlotAreaSpace() { return pas; } public void setGraphInformation(Rectangle graphSize) { this.graphSize = graphSize; fireGraphDimensionsChanged(); fireRedrawRequest(); } private void fireGraphDimensionsChanged() { for (GraphDimensionListener l : gdListeners) { l.graphDimensionChanged(); } } public Rectangle getPlotArea() { return new Rectangle(0, 0, getGraphWidth(), getGraphHeight()); } public Rectangle getGraphArea() { return new Rectangle(DrawConstants.GRAPH_LEFT_SPACE, DrawConstants.GRAPH_TOP_SPACE, getGraphWidth(), getGraphHeight()); } public Rectangle getLeftAxisArea() { return new Rectangle(0, DrawConstants.GRAPH_TOP_SPACE, DrawConstants.GRAPH_LEFT_SPACE, getGraphHeight() - (DrawConstants.GRAPH_TOP_SPACE + DrawConstants.GRAPH_BOTTOM_SPACE)); } private int getGraphHeight() { return graphSize.height - (DrawConstants.GRAPH_TOP_SPACE + DrawConstants.GRAPH_BOTTOM_SPACE); } private int getGraphWidth() { int twoYAxis = 0; if (getYAxisElements().size() >= 2) { twoYAxis = 1; } return graphSize.width - (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE + twoYAxis * DrawConstants.TWO_AXIS_GRAPH_RIGHT); } private void createYAxisSet() { YAxisElement[] tempArray = new YAxisElement[2]; for (Set<DrawableElement> elementsSet : drawableElements.values()) { for (DrawableElement de : elementsSet) { if (de.getYAxisElement() != null) { if (yAxisSet.contains(de.getYAxisElement())) { tempArray[yAxisSet.indexOf(de.getYAxisElement())] = de.getYAxisElement(); } } } } List<YAxisElement> newYAxisList = new ArrayList<YAxisElement>(); for (int i = 0; i < 2; i++) { if (tempArray[i] != null) { newYAxisList.add(tempArray[i]); } } yAxisSet = newYAxisList; } public boolean hasAxisAvailable() { return yAxisSet.size() < 2; } public boolean canBePutOnAxis(String unit) { for (YAxisElement el : yAxisSet) { if (el.getLabel().toLowerCase().equals(unit.toLowerCase())) { return true; } } return false; } public YAxisElement getYAxisElementForUnit(String unit) { for (YAxisElement el : yAxisSet) { if (el.getOriginalLabel().toLowerCase().equals(unit.toLowerCase())) { return el; } } return null; } public List<YAxisElement> getAllYAxisElementsForUnit(String unit) { List<YAxisElement> all = new ArrayList<YAxisElement>(); for (YAxisElement el : yAxisSet) { if (el.getOriginalLabel().toLowerCase().equals(unit.toLowerCase())) { all.add(el); } } return all; } public boolean canChangeAxis(String unitLabel) { return getAllYAxisElementsForUnit(unitLabel).size() == 2 || yAxisSet.size() < 2; } public YAxisElement.YAxisLocation getYAxisLocation(YAxisElement yAxisElement) { switch (yAxisSet.indexOf(yAxisElement)) { case 0: return YAxisElement.YAxisLocation.LEFT; case 1: return YAxisElement.YAxisLocation.RIGHT; } return YAxisLocation.LEFT; } }
package hudson.util; import hudson.FilePath; import hudson.Util; import hudson.EnvVars; import static hudson.Util.fixEmpty; import hudson.model.AbstractProject; import hudson.model.Hudson; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.net.HttpURLConnection; /** * Base class that provides the framework for doing on-the-fly form field validation. * * <p> * The {@link #check()} method is to be implemented by derived classes to perform * the validation. See hudson-behavior.js 'validated' CSS class and 'checkUrl' attribute. * * @author Kohsuke Kawaguchi */ public abstract class FormFieldValidator { protected final StaplerRequest request; protected final StaplerResponse response; private final boolean isAdminOnly; /** * * @param adminOnly * Pass true to only let admin users to run the check. This is necessary * for security reason, so that unauthenticated user cannot obtain sensitive * information or run a process that may have side-effect. */ protected FormFieldValidator(StaplerRequest request, StaplerResponse response, boolean adminOnly) { this.request = request; this.response = response; isAdminOnly = adminOnly; } /** * Runs the validation code. */ public final void process() throws IOException, ServletException { if(isAdminOnly && !Hudson.adminCheck(request,response)) return; // failed check check(); } protected abstract void check() throws IOException, ServletException; /** * Gets the parameter as a file. */ protected final File getFileParameter(String paramName) { return new File(Util.fixNull(request.getParameter(paramName))); } /** * Sends out an HTML fragment that indicates a success. */ public void ok() throws IOException, ServletException { response.setContentType("text/html"); response.getWriter().print("<div/>"); } /** * Sends out a string error message that indicates an error. * * @param message * Human readable message to be sent. <tt>error(null)</tt> * can be used as <tt>ok()</tt>. */ public void error(String message) throws IOException, ServletException { errorWithMarkup(message==null?null:Util.escape(message)); } public void warning(String message) throws IOException, ServletException { warningWithMarkup(message==null?null:Util.escape(message)); } /** * Sends out a string error message that indicates an error, * by formatting it with {@link String#format(String, Object[])} */ public void error(String format, Object... args) throws IOException, ServletException { error(String.format(format,args)); } public void warning(String format, Object... args) throws IOException, ServletException { warning(String.format(format,args)); } /** * Sends out an HTML fragment that indicates an error. * * <p> * This method must be used with care to avoid cross-site scripting * attack. * * @param message * Human readable message to be sent. <tt>error(null)</tt> * can be used as <tt>ok()</tt>. */ public void errorWithMarkup(String message) throws IOException, ServletException { _errorWithMarkup(message,"error"); } public void warningWithMarkup(String message) throws IOException, ServletException { _errorWithMarkup(message,"warning"); } private void _errorWithMarkup(String message, String cssClass) throws IOException, ServletException { if(message==null) { ok(); } else { response.setContentType("text/html;charset=UTF-8"); // 1x16 spacer needed for IE since it doesn't support min-height response.getWriter().print("<div class="+ cssClass +"><img src='"+ request.getContextPath()+Hudson.RESOURCE_PATH+"/images/none.gif' height=16 width=1>"+ message+"</div>"); } } /** * Convenient base class for checking the validity of URLs */ public static abstract class URLCheck extends FormFieldValidator { public URLCheck(StaplerRequest request, StaplerResponse response) { // can be used to check the existence of any file in file system // or other HTTP URLs inside firewall, so limit this to the admin. super(request, response, true); } /** * Opens the given URL and reads text content from it. * This method honors Content-type header. */ protected BufferedReader open(URL url) throws IOException { // use HTTP content type to find out the charset. URLConnection con = url.openConnection(); if (con == null) { // XXX is this even permitted by URL.openConnection? throw new IOException(url.toExternalForm()); } return new BufferedReader( new InputStreamReader(con.getInputStream(),getCharset(con))); } /** * Finds the string literal from the given reader. * @return * true if found, false otherwise. */ protected boolean findText(BufferedReader in, String literal) throws IOException { String line; while((line=in.readLine())!=null) if(line.indexOf(literal)!=-1) return true; return false; } /** * Calls the {@link #error(String)} method with a reasonable error message. * Use this method when the {@link #open(URL)} or {@link #findText(BufferedReader, String)} fails. * * @param url * Pass in the URL that was connected. Used for error diagnosis. */ protected void handleIOException(String url, IOException e) throws IOException, ServletException { // any invalid URL comes here if(e.getMessage().equals(url)) // Sun JRE (and probably others too) often return just the URL in the error. error("Unable to connect "+url); else error(e.getMessage()); } /** * Figures out the charset from the content-type header. */ private String getCharset(URLConnection con) { for( String t : con.getContentType().split(";") ) { t = t.trim().toLowerCase(); if(t.startsWith("charset=")) return t.substring(8); } // couldn't find it. HTML spec says default is US-ASCII, // but UTF-8 is a better choice since // (1) it's compatible with US-ASCII // (2) a well-written web applications tend to use UTF-8 return "UTF-8"; } } /** * Checks if the given value is an URL to some Hudson's top page. * @since 1.192 */ public static class HudsonURL extends URLCheck { public HudsonURL(StaplerRequest request, StaplerResponse response) { super(request, response); } protected void check() throws IOException, ServletException { String value = fixEmpty(request.getParameter("value")); if(value==null) {// nothing entered yet ok(); return; } if(!value.endsWith("/")) value+='/'; try { URL url = new URL(value); HttpURLConnection con = (HttpURLConnection)url.openConnection(); con.connect(); if(con.getResponseCode()!=200 || con.getHeaderField("X-Hudson")==null) { error(value+" is not Hudson ("+con.getResponseMessage()+")"); return; } ok(); } catch (IOException e) { handleIOException(value,e); } } } /** * Checks the file mask (specified in the 'value' query parameter) against * the current workspace. * @since 1.90. */ public static class WorkspaceFileMask extends FormFieldValidator { private final boolean errorIfNotExist; public WorkspaceFileMask(StaplerRequest request, StaplerResponse response) { this(request, response, true); } public WorkspaceFileMask(StaplerRequest request, StaplerResponse response, boolean errorIfNotExist) { super(request, response, false); this.errorIfNotExist = errorIfNotExist; } protected void check() throws IOException, ServletException { String value = fixEmpty(request.getParameter("value")); AbstractProject<?,?> p = Hudson.getInstance().getItemByFullName(request.getParameter("job"),AbstractProject.class); if(value==null || p==null) { ok(); // none entered yet, or something is seriously wrong return; } try { FilePath ws = getBaseDirectory(p); if(ws==null || !ws.exists()) {// no workspace. can't check ok(); return; } String msg = ws.validateAntFileMask(value); if(errorIfNotExist) error(msg); else warning(msg); } catch (InterruptedException e) { ok(); // coundn't check } } /** * The base directory from which the path name is resolved. */ protected FilePath getBaseDirectory(AbstractProject<?,?> p) { return p.getWorkspace(); } } /** * Checks a valid directory name (specified in the 'value' query parameter) against * the current workspace. * @since 1.116. */ public static class WorkspaceDirectory extends WorkspaceFilePath { public WorkspaceDirectory(StaplerRequest request, StaplerResponse response, boolean errorIfNotExist) { super(request, response, errorIfNotExist, false); } public WorkspaceDirectory(StaplerRequest request, StaplerResponse response) { this(request, response, true); } } /** * Checks a valid file name or directory (specified in the 'value' query parameter) against * the current workspace. * @since 1.160 */ public static class WorkspaceFilePath extends FormFieldValidator { private final boolean errorIfNotExist; private final boolean expectingFile; public WorkspaceFilePath(StaplerRequest request, StaplerResponse response, boolean errorIfNotExist, boolean expectingFile) { super(request, response, false); this.errorIfNotExist = errorIfNotExist; this.expectingFile = expectingFile; } protected void check() throws IOException, ServletException { String value = fixEmpty(request.getParameter("value")); AbstractProject<?, ?> p = getProject(); if(value==null || p==null) { ok(); // none entered yet, or something is seriously wrong return; } if(value.contains("*")) { // a common mistake is to use wildcard error("Wildcard is not allowed here"); return; } try { FilePath ws = getBaseDirectory(p); if(ws==null) {// can't check ok(); return; } if(!ws.exists()) {// no workspace. can't check ok(); return; } if(ws.child(value).exists()) { if (expectingFile) { if(!ws.child(value).isDirectory()) ok(); else error(value+" is not a file"); } else { if(ws.child(value).isDirectory()) ok(); else error(value+" is not a directory"); } } else { String msg = "No such "+(expectingFile?"file":"directory")+": " + value; if(errorIfNotExist) error(msg); else warning(msg); } } catch (InterruptedException e) { ok(); // coundn't check } } /** * The base directory from which the path name is resolved. */ protected FilePath getBaseDirectory(AbstractProject<?,?> p) { return p.getWorkspace(); } protected AbstractProject<?,?> getProject() { return Hudson.getInstance().getItemByFullName(request.getParameter("job"),AbstractProject.class); } } public static class Executable extends FormFieldValidator { public Executable(StaplerRequest request, StaplerResponse response) { super(request, response, true); } protected void check() throws IOException, ServletException { String exe = fixEmpty(request.getParameter("value")); if(exe==null) { ok(); // nothing entered yet return; } if(exe.indexOf(File.separatorChar)>=0) { // this is full path File f = new File(exe); if(f.exists()) { checkExecutable(f); return; } File fexe = new File(exe+".exe"); if(fexe.exists()) { checkExecutable(fexe); return; } error("There's no such file: "+exe); } else { // look in PATH String path = EnvVars.masterEnvVars.get("PATH"); if(path!=null) { for (String _dir : Util.tokenize(path,File.pathSeparator)) { File dir = new File(_dir); File f = new File(dir,exe); if(f.exists()) { checkExecutable(f); return; } File fexe = new File(dir,exe+".exe"); if(fexe.exists()) { checkExecutable(fexe); return; } } } // didn't find it error("There's no such executable "+exe+" in PATH:"+path); } } /** * Provides an opportunity for derived classes to do additional checks on the executable. */ protected void checkExecutable(File exe) throws IOException, ServletException { ok(); } } }
package org.synyx.urlaubsverwaltung.absence.web; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.context.MessageSource; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.synyx.urlaubsverwaltung.application.domain.Application; import org.synyx.urlaubsverwaltung.application.domain.ApplicationStatus; import org.synyx.urlaubsverwaltung.application.service.ApplicationService; import org.synyx.urlaubsverwaltung.department.Department; import org.synyx.urlaubsverwaltung.department.DepartmentService; import org.synyx.urlaubsverwaltung.period.DayLength; import org.synyx.urlaubsverwaltung.person.Person; import org.synyx.urlaubsverwaltung.person.PersonService; import org.synyx.urlaubsverwaltung.person.Role; import org.synyx.urlaubsverwaltung.publicholiday.PublicHolidaysService; import org.synyx.urlaubsverwaltung.settings.Settings; import org.synyx.urlaubsverwaltung.settings.SettingsService; import org.synyx.urlaubsverwaltung.sicknote.SickNote; import org.synyx.urlaubsverwaltung.sicknote.SickNoteService; import org.synyx.urlaubsverwaltung.workingtime.WorkingTimeService; import org.synyx.urlaubsverwaltung.workingtime.WorkingTimeSettings; import java.time.Clock; import java.time.Instant; import java.time.LocalDate; import java.time.Year; import java.time.ZoneId; import java.util.List; import java.util.Locale; import java.util.stream.Stream; import static java.time.temporal.TemporalAdjusters.firstDayOfMonth; import static java.time.temporal.TemporalAdjusters.lastDayOfMonth; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup; import static org.synyx.urlaubsverwaltung.absence.web.AbsenceOverviewDayType.ALLOWED_VACATION_FULL; import static org.synyx.urlaubsverwaltung.person.Role.DEPARTMENT_HEAD; import static org.synyx.urlaubsverwaltung.person.Role.OFFICE; import static org.synyx.urlaubsverwaltung.person.Role.SECOND_STAGE_AUTHORITY; @ExtendWith(MockitoExtension.class) class AbsenceOverviewViewControllerTest { private AbsenceOverviewViewController sut; @Mock private PersonService personService; @Mock private DepartmentService departmentService; @Mock private ApplicationService applicationService; @Mock private SickNoteService sickNoteService; @Mock private MessageSource messageSource; @Mock private PublicHolidaysService publicHolidayService; @Mock private SettingsService settingsService; @Mock private WorkingTimeService workingTimeService; private final Clock clock = Clock.systemUTC(); @BeforeEach void setUp() { final Settings settings = new Settings(); final WorkingTimeSettings workingTimeSettings = new WorkingTimeSettings(); settings.setWorkingTimeSettings(workingTimeSettings); when(settingsService.getSettings()).thenReturn(settings); when(publicHolidayService.getAbsenceTypeOfDate(any(), any())).thenReturn(DayLength.ZERO); sut = new AbsenceOverviewViewController(personService, departmentService, applicationService, sickNoteService, messageSource, clock, publicHolidayService, settingsService, workingTimeService); } @Test void applicationForLeaveVacationOverviewNoPermissions() throws Exception { final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(singletonList(department)); final var resultActions = perform(get("/web/absences")); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("departments", hasItem(department))) .andExpect(view().name("absences/absences_overview")); verifyNoMoreInteractions(departmentService); } @ParameterizedTest @EnumSource(value = Role.class, names = {"BOSS", "OFFICE"}) void applicationForLeaveVacationOverviewAllDepartments(Role role) throws Exception { final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); person.setPermissions(singletonList(role)); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(singletonList(department)); final var resultActions = perform(get("/web/absences")); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("departments", hasItem(department))) .andExpect(view().name("absences/absences_overview")); verifyNoMoreInteractions(departmentService); } @Test void applicationForLeaveVacationOverviewSECONDSTAGE() throws Exception { final Person ssa = new Person(); ssa.setFirstName("firstname"); ssa.setLastName("lastname"); ssa.setEmail("firstname.lastname@example.org"); ssa.setPermissions(singletonList(SECOND_STAGE_AUTHORITY)); when(personService.getSignedInUser()).thenReturn(ssa); final var department = department(); when(departmentService.getAllowedDepartmentsOfPerson(ssa)).thenReturn(singletonList(department)); final var resultActions = perform(get("/web/absences")); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("departments", hasItem(department))) .andExpect(view().name("absences/absences_overview")); verifyNoMoreInteractions(departmentService); } @Test void applicationForLeaveVacationOverviewDEPARTMENTHEAD() throws Exception { final Person departmentHead = new Person(); departmentHead.setPermissions(singletonList(DEPARTMENT_HEAD)); when(personService.getSignedInUser()).thenReturn(departmentHead); final var department = department(); when(departmentService.getAllowedDepartmentsOfPerson(departmentHead)).thenReturn(singletonList(department)); final ResultActions resultActions = perform(get("/web/absences")); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("departments", hasItem(department))) .andExpect(view().name("absences/absences_overview")); verifyNoMoreInteractions(departmentService); } @ParameterizedTest @NullSource @ValueSource(strings = {"", " "}) void ensureDefaultSelectedDepartmentIsTheFirstAvailable(String departmentName) throws Exception { final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); person.setPermissions(singletonList(OFFICE)); when(personService.getSignedInUser()).thenReturn(person); final var superheroes = department("superheroes"); final var villains = department("villains"); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(List.of(superheroes, villains)); final var resultActions = perform(get("/web/absences") .param("department", departmentName)); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("departments", allOf(hasItem(superheroes), hasItem(villains)))) .andExpect(model().attribute("selectedDepartments", hasItem("superheroes"))); } @Test void ensureSelectedDepartment() throws Exception { final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); person.setPermissions(singletonList(OFFICE)); when(personService.getSignedInUser()).thenReturn(person); final var superheroes = department("superheroes"); final var villains = department("villains"); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(List.of(superheroes, villains)); final var resultActions = perform(get("/web/absences") .param("department", "villains")); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("departments", allOf(hasItem(superheroes), hasItem(villains)))) .andExpect(model().attribute("selectedDepartments", hasItem("villains"))); } @Test void ensureMultipleSelectedDepartments() throws Exception { final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); person.setPermissions(singletonList(OFFICE)); when(personService.getSignedInUser()).thenReturn(person); final var superheroes = department("superheroes"); final var villains = department("villains"); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(List.of(superheroes, villains)); final var resultActions = perform(get("/web/absences") .param("department", "villains") .param("department", "superheroes")); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("departments", allOf(hasItem(superheroes), hasItem(villains)))) .andExpect(model().attribute("selectedDepartments", allOf(hasItem("superheroes"), hasItem("villains")))); } @ParameterizedTest @NullSource @ValueSource(strings = {""}) void ensureDefaultSelectedYearIsTheCurrentYear(String givenYearParam) throws Exception { final var expectedCurrentYear = LocalDate.now().getYear(); final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); person.setPermissions(singletonList(OFFICE)); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(List.of(department)); final var resultActions = perform(get("/web/absences") .param("year", givenYearParam)); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("currentYear", expectedCurrentYear)) .andExpect(model().attribute("selectedYear", expectedCurrentYear)); } @Test void ensureSelectedYear() throws Exception { final var expectedCurrentYear = LocalDate.now().getYear(); final var expectedSelectedYear = expectedCurrentYear - 1; final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); person.setPermissions(singletonList(OFFICE)); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(List.of(department)); final var resultActions = perform(get("/web/absences") .param("year", String.valueOf(expectedSelectedYear))); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("currentYear", expectedCurrentYear)) .andExpect(model().attribute("selectedYear", expectedSelectedYear)); } @Test void ensureSelectedMonthIsTheCurrentMonthWhenParamIsNotDefined() throws Exception { final var now = LocalDate.now(); final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); person.setPermissions(singletonList(OFFICE)); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(List.of(department)); final var resultActions = perform(get("/web/absences")); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("selectedMonth", String.valueOf(now.getMonthValue()))); } @Test void ensureSelectedMonthIsEmptyStringWhenParamIsDefinedAsEmptyString() throws Exception { final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); person.setPermissions(singletonList(OFFICE)); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(List.of(department)); final var resultActions = perform(get("/web/absences") .param("month", "")); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("selectedMonth", "")); } @Test void ensureSelectedMonthWhenParamIsDefined() throws Exception { final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); person.setPermissions(singletonList(OFFICE)); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(List.of(department)); final var resultActions = perform(get("/web/absences") .param("month", "1")); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("selectedMonth", "1")); } @Test void ensureMonthDayTextIsPadded() throws Exception { final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); department.setMembers(List.of(person)); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(singletonList(department)); final var resultActions = perform(get("/web/absences")); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("absenceOverview", hasProperty("months", contains( hasProperty("days", hasItems( allOf(hasProperty("dayOfMonth", is("01"))), allOf(hasProperty("dayOfMonth", is("02"))), allOf(hasProperty("dayOfMonth", is("03"))), allOf(hasProperty("dayOfMonth", is("04"))), allOf(hasProperty("dayOfMonth", is("05"))), allOf(hasProperty("dayOfMonth", is("06"))), allOf(hasProperty("dayOfMonth", is("07"))), allOf(hasProperty("dayOfMonth", is("08"))), allOf(hasProperty("dayOfMonth", is("09"))), allOf(hasProperty("dayOfMonth", is("10"))) )) )) )); } @Test void ensureOverviewForGivenYear() throws Exception { final Clock fixedClock = Clock.fixed(Instant.parse("2018-10-17T00:00:00.00Z"), ZoneId.systemDefault()); sut = new AbsenceOverviewViewController( personService, departmentService, applicationService, sickNoteService, messageSource, fixedClock, publicHolidayService, settingsService, workingTimeService); final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); department.setMembers(List.of(person)); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(singletonList(department)); final var resultActions = perform(get("/web/absences") .param("year", "2018") .locale(Locale.GERMANY)); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("selectedYear", 2018)) .andExpect(model().attribute("absenceOverview", hasProperty("months", hasSize(1)))); verify(messageSource).getMessage("month.october", new Object[]{}, Locale.GERMANY); verifyNoMoreInteractions(messageSource); } @Test void ensureOverviewForGivenMonthNovember() throws Exception { when(messageSource.getMessage(anyString(), any(), any())).thenReturn("awesome month text"); final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); department.setMembers(List.of(person)); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(singletonList(department)); final var resultActions = perform(get("/web/absences") .param("month", "11") .locale(Locale.GERMANY)); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("absenceOverview", hasProperty("months", contains(allOf( hasProperty("nameOfMonth", is("awesome month text")), hasProperty("persons", hasItem(allOf( hasProperty("firstName", is("boss")), hasProperty("days", hasSize(30)) ))), hasProperty("days", hasSize(30))) )))); verify(messageSource).getMessage("month.november", new Object[]{}, Locale.GERMANY); verifyNoMoreInteractions(messageSource); } @Test void ensureOverviewForGivenMonthDecember() throws Exception { when(messageSource.getMessage(anyString(), any(), any())).thenReturn("awesome month text"); final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); department.setMembers(List.of(person)); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(singletonList(department)); final var resultActions = perform(get("/web/absences") .param("month", "12") .locale(Locale.GERMANY)); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("absenceOverview", hasProperty("months", contains(allOf( hasProperty("nameOfMonth", is("awesome month text")), hasProperty("persons", hasItem(allOf( hasProperty("firstName", is("boss")), hasProperty("days", hasSize(31)) ))), hasProperty("days", hasSize(31))) )))); verify(messageSource).getMessage("month.december", new Object[]{}, Locale.GERMANY); verifyNoMoreInteractions(messageSource); } @Test void ensureOverviewForGivenYearAndGivenMonth() throws Exception { final Clock fixedClock = Clock.fixed(Instant.parse("2018-10-17T00:00:00.00Z"), ZoneId.systemDefault()); sut = new AbsenceOverviewViewController( personService, departmentService, applicationService, sickNoteService, messageSource, fixedClock, publicHolidayService, settingsService, workingTimeService); when(messageSource.getMessage(anyString(), any(), any())).thenReturn("awesome month text"); final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); department.setMembers(List.of(person)); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(singletonList(department)); final var resultActions = perform(get("/web/absences") .param("year", "2018") .param("month", "10") .locale(Locale.GERMANY)); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("absenceOverview", hasProperty("months", contains(allOf( hasProperty("nameOfMonth", is("awesome month text")), hasProperty("persons", hasItem(allOf( hasProperty("firstName", is("boss")), hasProperty("days") ))), hasProperty("days")) )))); verify(messageSource).getMessage("month.october", new Object[]{}, Locale.GERMANY); verifyNoMoreInteractions(messageSource); } @Test void ensureOverviewForGivenDepartment() throws Exception { final var person = new Person(); person.setFirstName("bruce"); person.setLastName("wayne"); person.setEmail("batman@example.org"); when(personService.getSignedInUser()).thenReturn(person); final var heroDepartment = department("heroes"); heroDepartment.setMembers(List.of(person)); final var joker = person("joker"); final var lex = person("lex"); final var harley = person("harley"); final var villainsDepartment = department("villains"); villainsDepartment.setMembers(List.of(joker, lex, harley)); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(List.of(heroDepartment, villainsDepartment)); final var resultActions = perform(get("/web/absences").locale(Locale.GERMANY) .param("department", "villains")); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("selectedDepartments", hasItem("villains"))) .andExpect(model().attribute("absenceOverview", hasProperty("months", hasItem(allOf( hasProperty("persons", hasSize(3)) ))))); } @Test void ensureDistinctPersonOverviewForGivenDepartments() throws Exception { final var person = new Person(); person.setFirstName("bruce"); person.setLastName("wayne"); person.setEmail("batman@example.org"); when(personService.getSignedInUser()).thenReturn(person); final var heroDepartment = department("heroes"); heroDepartment.setMembers(List.of(person)); final var joker = person("joker"); final var lex = person("lex"); final var harley = person("harley"); final var villainsDepartment = department("villains"); villainsDepartment.setMembers(List.of(joker, lex, harley, person)); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(List.of(heroDepartment, villainsDepartment)); final var resultActions = perform(get("/web/absences").locale(Locale.GERMANY) .param("department", "villains") .param("department", "heroes") ); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("selectedDepartments", allOf(hasItem("heroes"), hasItem("villains")))) .andExpect(model().attribute("absenceOverview", hasProperty("months", hasItem(allOf( hasProperty("persons", hasSize(4)) ))))); } @ParameterizedTest @EnumSource(value = Role.class, names = {"BOSS", "OFFICE"}) void ensureOverviewShowsAllPersonsThereAreNoDepartmentsFor(Role role) throws Exception { final var person = new Person(); person.setFirstName("bruce"); person.setLastName("wayne"); person.setEmail("batman@example.org"); person.setPermissions(singletonList(role)); when(personService.getSignedInUser()).thenReturn(person); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(emptyList()); final var personTwo = new Person(); personTwo.setFirstName("aa"); personTwo.setLastName("person two lastname"); personTwo.setEmail("person2@company.org"); final var personThree = new Person(); personThree.setFirstName("AA"); personThree.setLastName("AA lastname"); personThree.setEmail("person3@company.org"); when(personService.getActivePersons()).thenReturn(List.of(person, personTwo, personThree)); final var resultActions = perform(get("/web/absences").locale(Locale.GERMANY)); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("selectedDepartments", hasItem(""))) .andExpect(model().attribute("absenceOverview", hasProperty("months", hasItem(allOf( hasProperty("persons", hasSize(3)) ))))); } @Test void ensureOverviewIsEmptyWhenThereAreNoDepartmentsForADepartmentHead() throws Exception { final var person = new Person(); person.setFirstName("department head"); person.setPermissions(singletonList(SECOND_STAGE_AUTHORITY)); when(personService.getSignedInUser()).thenReturn(person); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(emptyList()); final var resultActions = perform(get("/web/absences").locale(Locale.GERMANY)); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("selectedDepartments", hasItem(""))) .andExpect(model().attribute("absenceOverview", hasProperty("months", hasItem(allOf( hasProperty("persons", empty()) ))))); } @Test void ensureOverviewDefaultCurrentYearAndMonth() throws Exception { final Clock fixedClock = Clock.fixed(Instant.parse("2020-10-17T00:00:00.00Z"), ZoneId.systemDefault()); sut = new AbsenceOverviewViewController( personService, departmentService, applicationService, sickNoteService, messageSource, fixedClock, publicHolidayService, settingsService, workingTimeService); when(messageSource.getMessage(anyString(), any(), any())).thenReturn("awesome month text"); final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); department.setMembers(List.of(person)); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(singletonList(department)); final var resultActions = perform(get("/web/absences").locale(Locale.GERMANY)); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("absenceOverview", hasProperty("months", contains(allOf( hasProperty("nameOfMonth", is("awesome month text")), hasProperty("persons", hasItem(allOf( hasProperty("firstName", is("boss")), hasProperty("days") ))), hasProperty("days")) )))); verify(messageSource).getMessage("month.october", new Object[]{}, Locale.GERMANY); verifyNoMoreInteractions(messageSource); } @Test void ensureOverviewPersonsAreSortedByFirstName() throws Exception { final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); when(personService.getSignedInUser()).thenReturn(person); final var personTwo = new Person(); personTwo.setFirstName("aa"); personTwo.setLastName("aa lastname"); personTwo.setEmail("person2@example.org"); final var personThree = new Person(); personThree.setFirstName("AA"); personThree.setLastName("AA lastname"); personThree.setEmail("person3@example.org"); final var department = department(); department.setMembers(List.of(person, personTwo, personThree)); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(singletonList(department)); final var resultActions = perform(get("/web/absences").locale(Locale.GERMANY)); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("absenceOverview", hasProperty("months", hasItem(allOf( hasProperty("persons", contains( hasProperty("firstName", is("AA")), hasProperty("firstName", is("aa")), hasProperty("firstName", is("boss")) )) ))))); } private static Stream<Arguments> dayLengthSickNoteTypeData() { return Stream.of( Arguments.of(DayLength.FULL, "activeSickNoteFull"), Arguments.of(DayLength.MORNING, "activeSickNoteMorning"), Arguments.of(DayLength.NOON, "activeSickNoteNoon") ); } @ParameterizedTest @MethodSource("dayLengthSickNoteTypeData") void ensureSickNoteOneDay(DayLength dayLength, String dtoDayTypeText) throws Exception { final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); department.setMembers(List.of(person)); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(singletonList(department)); final var sickNote = new SickNote(); sickNote.setStartDate(LocalDate.now(clock)); sickNote.setEndDate(LocalDate.now(clock)); sickNote.setDayLength(dayLength); sickNote.setPerson(person); final List<SickNote> sickNotes = List.of(sickNote); when(sickNoteService.getAllActiveByYear(Year.now(clock).getValue())).thenReturn(sickNotes); final var resultActions = perform(get("/web/absences").locale(Locale.GERMANY)); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("absenceOverview", hasProperty("months", contains( hasProperty("persons", hasItem( hasProperty("days", hasItems( hasProperty("type", is(dtoDayTypeText)) )) )) )) )); } private static Stream<Arguments> dayLengthVacationTypeData() { return Stream.of( Arguments.of(ApplicationStatus.ALLOWED, DayLength.FULL, "allowedVacationFull"), Arguments.of(ApplicationStatus.ALLOWED, DayLength.MORNING, "allowedVacationMorning"), Arguments.of(ApplicationStatus.ALLOWED, DayLength.NOON, "allowedVacationNoon"), Arguments.of(ApplicationStatus.WAITING, DayLength.FULL, "waitingVacationFull"), Arguments.of(ApplicationStatus.WAITING, DayLength.MORNING, "waitingVacationMorning"), Arguments.of(ApplicationStatus.WAITING, DayLength.NOON, "waitingVacationNoon") ); } @ParameterizedTest @MethodSource("dayLengthVacationTypeData") void ensureVacationOneDay(ApplicationStatus applicationStatus, DayLength dayLength, String dtoDayTypeText) throws Exception { final LocalDate now = LocalDate.now(clock); final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); department.setMembers(List.of(person)); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(singletonList(department)); final var application = new Application(); application.setStartDate(now); application.setEndDate(now); application.setPerson(person); application.setDayLength(dayLength); application.setStatus(applicationStatus); final List<Application> applications = List.of(application); when(applicationService.getApplicationsForACertainPeriodAndPerson(now.with(firstDayOfMonth()), now.with(lastDayOfMonth()), person)) .thenReturn(applications); final var resultActions = perform(get("/web/absences").locale(Locale.GERMANY)); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("absenceOverview", hasProperty("months", contains( hasProperty("persons", hasItem( hasProperty("days", hasItems( hasProperty("type", is(dtoDayTypeText)) )) )) )) )); } @Test void ensureNonDisplayableApplicationsAreIgnored() throws Exception { final LocalDate now = LocalDate.now(); final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); when(personService.getSignedInUser()).thenReturn(person); final var department = department(); department.setMembers(List.of(person)); when(departmentService.getAllowedDepartmentsOfPerson(person)).thenReturn(singletonList(department)); // create different applications with types that should not be considered in the overview final var revokedApplication = new Application(); revokedApplication.setStartDate(now); revokedApplication.setEndDate(now); revokedApplication.setPerson(person); revokedApplication.setDayLength(DayLength.FULL); revokedApplication.setStatus(ApplicationStatus.REVOKED); final var rejectedApplication = new Application(); rejectedApplication.setStartDate(now); rejectedApplication.setEndDate(now); rejectedApplication.setPerson(person); rejectedApplication.setDayLength(DayLength.FULL); rejectedApplication.setStatus(ApplicationStatus.REJECTED); final var cancelledApplication = new Application(); cancelledApplication.setStartDate(now); cancelledApplication.setEndDate(now); cancelledApplication.setPerson(person); cancelledApplication.setDayLength(DayLength.FULL); cancelledApplication.setStatus(ApplicationStatus.CANCELLED); // create application with type that should be displayed in the overview final var application = new Application(); application.setStartDate(now); application.setEndDate(now); application.setPerson(person); application.setDayLength(DayLength.FULL); application.setStatus(ApplicationStatus.ALLOWED); // "invalid" applications must come before the valid one in list, since the type determination for the overview // takes the first matching application from the list after the filters are applied. final List<Application> applications = List.of(revokedApplication, rejectedApplication, cancelledApplication, application); when(applicationService.getApplicationsForACertainPeriodAndPerson(now.with(firstDayOfMonth()), now.with(lastDayOfMonth()), person)) .thenReturn(applications); final var resultActions = perform(get("/web/absences").locale(Locale.GERMANY)); // confirm that type of correct application is returned resultActions .andExpect(status().isOk()) .andExpect(model().attribute("absenceOverview", hasProperty("months", contains( hasProperty("persons", hasItem( hasProperty("days", hasItem( hasProperty("type", is(ALLOWED_VACATION_FULL.getIdentifier())) )) )) )) )); } @Test void ensureWeekendsAndHolidays() throws Exception { final Clock fixedClock = Clock.fixed(Instant.parse("2020-12-01T00:00:00.00Z"), ZoneId.systemDefault()); sut = new AbsenceOverviewViewController( personService, departmentService, applicationService, sickNoteService, messageSource, fixedClock, publicHolidayService, settingsService, workingTimeService); final var person = new Person(); person.setFirstName("boss"); person.setLastName("the hoss"); person.setEmail("boss@example.org"); when(personService.getSignedInUser()).thenReturn(person); final var resultActions = perform(get("/web/absences").locale(Locale.GERMANY)); resultActions .andExpect(status().isOk()) .andExpect(model().attribute("absenceOverview", hasProperty("months", contains( hasProperty("days", contains( allOf(hasProperty("dayOfMonth", is("01")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("02")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("03")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("04")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("05")), hasProperty("weekend", is(true))), allOf(hasProperty("dayOfMonth", is("06")), hasProperty("weekend", is(true))), allOf(hasProperty("dayOfMonth", is("07")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("08")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("09")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("10")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("11")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("12")), hasProperty("weekend", is(true))), allOf(hasProperty("dayOfMonth", is("13")), hasProperty("weekend", is(true))), allOf(hasProperty("dayOfMonth", is("14")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("15")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("16")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("17")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("18")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("19")), hasProperty("weekend", is(true))), allOf(hasProperty("dayOfMonth", is("20")), hasProperty("weekend", is(true))), allOf(hasProperty("dayOfMonth", is("21")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("22")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("23")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("24")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("25")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("26")), hasProperty("weekend", is(true))), allOf(hasProperty("dayOfMonth", is("27")), hasProperty("weekend", is(true))), allOf(hasProperty("dayOfMonth", is("28")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("29")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("30")), hasProperty("weekend", is(false))), allOf(hasProperty("dayOfMonth", is("31")), hasProperty("weekend", is(false))) )) )) )); } private static Department department() { return department("superheroes"); } private static Department department(String name) { var department = new Department(); department.setName(name); return department; } private static Person person(String firstName) { var person = new Person(); person.setFirstName(firstName); person.setLastName(firstName + " lastname"); person.setEmail(firstName + "@example.org"); return person; } private ResultActions perform(MockHttpServletRequestBuilder builder) throws Exception { return standaloneSetup(sut).build().perform(builder); } }
package uk.ac.manchester.cs.owl.semspreadsheets.model.xssf.impl; import static org.junit.Assert.assertEquals; import java.util.List; import org.apache.poi.ss.usermodel.DataValidation; import org.apache.poi.ss.usermodel.DataValidationConstraint; import org.apache.poi.ss.usermodel.DataValidationHelper; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddressList; import org.apache.poi.xssf.usermodel.XSSFDataValidation; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.Test; import uk.ac.manchester.cs.owl.semspreadsheets.DocumentsCatalogue; import uk.ac.manchester.cs.owl.semspreadsheets.SpreadsheetTestHelper; import uk.ac.manchester.cs.owl.semspreadsheets.model.Sheet; import uk.ac.manchester.cs.owl.semspreadsheets.model.Workbook; import uk.ac.manchester.cs.owl.semspreadsheets.model.impl.GeneralSheetTests; public class SheetXSSFImplTest extends GeneralSheetTests { @Test public void testGetValidationData() throws Exception { SheetXSSFImpl sheet = (SheetXSSFImpl)getTestSheet(); List<XSSFDataValidation> validationData = sheet.getValidationData(); assertEquals(1,validationData.size()); XSSFDataValidation val = validationData.get(0); CellRangeAddress[] cellRangeAddresses = val.getRegions().getCellRangeAddresses(); assertEquals(1,cellRangeAddresses.length); CellRangeAddress rangeAddresses = cellRangeAddresses[0]; assertEquals(4,rangeAddresses.getFirstColumn()); assertEquals(4,rangeAddresses.getLastColumn()); assertEquals(11,rangeAddresses.getFirstRow()); assertEquals(11,rangeAddresses.getLastRow()); } @Test public void testClearValidationData() throws Exception { SheetXSSFImpl sheet = (SheetXSSFImpl)getTestSheet(); List<XSSFDataValidation> validationData = sheet.getValidationData(); assertEquals(1,validationData.size()); sheet.clearValidationData(); validationData = sheet.getValidationData(); assertEquals(0,validationData.size()); } @Test public void testGettingValidationsAfterAddingCustomInPOI() throws Exception { XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); List<XSSFDataValidation> dataValidations = sheet.getDataValidations(); //<-- works assertEquals(0, dataValidations.size()); //create the cell that will have the validation applied sheet.createRow(0).createCell(0); DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("SUM($A$1:$A$1) <= 3500"); CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); sheet.addValidationData(validation); dataValidations = sheet.getDataValidations(); //<-- raised XmlValueOutOfRangeException assertEquals(1, dataValidations.size()); } //opens the workbook src/test/resources/simple_annotated_book.xls protected Workbook getTestWorkbook() throws Exception { return SpreadsheetTestHelper.openWorkbookXSSF(DocumentsCatalogue.simpleAnnotatedXLSXWorkbookURI()); } //opens the first sheet from test workbook src/test/resources/simple_annotated_sheet.xls used for most of these tests protected Sheet getTestSheet() throws Exception { return (SheetXSSFImpl)getTestWorkbook().getSheet(0); } protected Workbook getBlankWorkbook() throws Exception { return SpreadsheetTestHelper.getBlankXSSFWorkbook(); } protected Sheet getBlankSheet() throws Exception { return SpreadsheetTestHelper.getBlankXSSFWorkbook().createSheet(); } }
package org.bitcoinj.core; import org.bitcoinj.script.Script; import org.bitcoinj.utils.ContextPropagatingThreadFactory; import org.bitcoinj.utils.Threading; import org.darkcoinj.DarkSendEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.security.SecureRandom; import java.util.ArrayList; import java.util.concurrent.locks.ReentrantLock; import static org.bitcoinj.core.MasternodeManager.MASTERNODES_DUMP_SECONDS; public class DarkSendPool { private static final Logger log = LoggerFactory.getLogger(DarkSendPool.class); ReentrantLock lock = Threading.lock("darksendpool"); // pool states for mixing public static final int POOL_STATUS_UNKNOWN = 0; // waiting for update public static final int POOL_STATUS_IDLE = 1; // waiting for update public static final int POOL_STATUS_QUEUE = 2; // waiting in a queue public static final int POOL_STATUS_ACCEPTING_ENTRIES = 3; // accepting entries public static final int POOL_STATUS_FINALIZE_TRANSACTION = 4; // master node will broadcast what it accepted public static final int POOL_STATUS_SIGNING = 5; // check inputs/outputs, sign final tx public static final int POOL_STATUS_TRANSMISSION = 6; // transmit transaction public static final int POOL_STATUS_ERROR = 7; // error public static final int POOL_STATUS_SUCCESS = 8; // success static final int MIN_PEER_PROTO_VERSION = 70054; // masternode entries ArrayList<DarkSendEntry> entries; // the finalized transaction ready for signing Transaction finalTransaction; long lastTimeChanged; int state; int entriesCount; int lastEntryAccepted; int countEntriesAccepted; ArrayList<TransactionInput> lockedCoins; String lastMessage; boolean unitTest; int sessionID; int sessionUsers; //N Users have said they'll join boolean sessionFoundMasternode; //If we've found a compatible masternode ArrayList<Transaction> vecSessionCollateral; int cachedLastSuccess; int minBlockSpacing; //required blocks between mixes Transaction txCollateral; long lastNewBlock; //debugging data String strAutoDenomResult; enum ErrorMessage { ERR_ALREADY_HAVE, ERR_DENOM, ERR_ENTRIES_FULL, ERR_EXISTING_TX, ERR_FEES, ERR_INVALID_COLLATERAL, ERR_INVALID_INPUT, ERR_INVALID_SCRIPT, ERR_INVALID_TX, ERR_MAXIMUM, ERR_MN_LIST, ERR_MODE, ERR_NON_STANDARD_PUBKEY, ERR_NOT_A_MN, ERR_QUEUE_FULL, ERR_RECENT, ERR_SESSION, ERR_MISSING_TX, ERR_VERSION, MSG_NOERR, MSG_SUCCESS, MSG_ENTRIES_ADDED }; // where collateral should be made out to public Script collateralPubKey; public Masternode submittedToMasternode; int sessionDenom; //Users must submit an denom matching this int cachedNumBlocks; //used for the overview screen Context context; public DarkSendPool(Context context) { this.context = context; /* DarkSend uses collateral addresses to trust parties entering the pool to behave themselves. If they don't it takes their money. */ cachedLastSuccess = 0; cachedNumBlocks = Integer.MAX_VALUE; //std::numeric_limits<int>::max(); unitTest = false; txCollateral = new Transaction(context.getParams()); minBlockSpacing = 0; lastNewBlock = 0; vecSessionCollateral = new ArrayList<Transaction>(); entries = new ArrayList<DarkSendEntry>(); finalTransaction = new Transaction(context.getParams()); setNull(); } static SecureRandom secureRandom = new SecureRandom(); void setNull() { // MN side sessionUsers = 0; vecSessionCollateral.clear(); // Client side entriesCount = 0; lastEntryAccepted = 0; countEntriesAccepted = 0; sessionFoundMasternode = false; // Both sides state = POOL_STATUS_IDLE; sessionID = 0; sessionDenom = 0; entries.clear(); finalTransaction.clearInputs(); finalTransaction.clearOutputs(); lastTimeChanged = Utils.currentTimeMillis(); // -- seed random number generator (used for ordering output lists) secureRandom.setSeed(secureRandom.generateSeed(12)); /*unsigned int seed = 0; RAND_bytes((unsigned char*)&seed, sizeof(seed)); std::srand(seed);*/ } static boolean oneThread = false; class ThreadCheckDarkSendPool implements Runnable { public volatile boolean exit = false; public void stop() { exit = true; } @Override public void run() { if(context.isLiteMode() && !context.allowInstantXinLiteMode()) return; //disable all Darksend/Masternode related functionality if(oneThread) return; oneThread = true; // Make this thread recognisable as the wallet flushing thread log.info(" int tick = 0; try { while (true && !exit) { Thread.sleep(1000); // try to sync from all available nodes, one step at a time context.masternodeSync.processTick(); if (context.masternodeSync.isBlockchainSynced()) { tick++; // check if we should activate or ping every few minutes, // start right after sync is considered to be done if (tick % Masternode.MASTERNODE_MIN_MNP_SECONDS == 15) context.activeMasternode.manageState(); if (tick % 60 == 0) { context.masternodeManager.processMasternodeConnections(); context.masternodeManager.checkAndRemove(); context.masternodePayments.checkAndRemove(); context.governanceManager.checkAndRemove(); context.instantSend.checkAndRemove(); } //hashengineering added this if(tick % 30 == 0) { log.info(context.masternodeManager.toString()); log.info(context.governanceManager.toString()); } if(tick % (60 * 5) == 0) { context.governanceManager.doMaintenance(); } if(tick % MASTERNODES_DUMP_SECONDS == 0) { context.masternodeSync.queueOnSyncStatusChanged(MasternodeSync.MASTERNODE_SYNC_FINISHED, 1.0f); } // check whether the outgoing simple transactions were auto locked // within the specific time frame if (tick % 2 == 0) { context.instantSend.notifyLockStatus(); } } } } catch(InterruptedException x) { x.printStackTrace(); } } }; Thread backgroundThread; ThreadCheckDarkSendPool threadCheckDarkSendPool = null; //dash public boolean startBackgroundProcessing() { if(backgroundThread == null) { threadCheckDarkSendPool = new ThreadCheckDarkSendPool(); backgroundThread = new ContextPropagatingThreadFactory("dash-privatesend").newThread(threadCheckDarkSendPool); backgroundThread.start(); return true; } else if(backgroundThread.getState() == Thread.State.TERMINATED) { //if the thread was stopped, start it again backgroundThread = new ContextPropagatingThreadFactory("dash-privatesend").newThread(threadCheckDarkSendPool); backgroundThread.start(); } return false; } public boolean isBackgroundRunning() { return backgroundThread == null ? false : backgroundThread.getState() != Thread.State.TERMINATED; } public void close() { threadCheckDarkSendPool.stop(); } }
package org.apache.jcs.auxiliary.lateral.socket.tcp; import java.util.Random; import junit.framework.TestCase; import org.apache.jcs.JCS; import org.apache.jcs.engine.CacheElement; import org.apache.jcs.engine.behavior.ICacheElement; /** * Tests the issue remove on put fuctionality. * * @author asmuts */ public class LateralTCPIssueRemoveOnPutUnitTest extends TestCase { private static boolean isSysOut = true; /** * Constructor for the TestDiskCache object. * * @param testName */ public LateralTCPIssueRemoveOnPutUnitTest( String testName ) { super( testName ); } /** * Test setup */ public void setUp() { JCS.setConfigFilename( "/TestTCPLateralIssueRemoveCache.ccf" ); } /** * * @throws Exception */ public void testPutLocalPutRemoteGetBusyVerifyRemoved() throws Exception { this.runTestForRegion( "region1", 1, 200, 1 ); } /** * Verify that a standard put works. * * Get the cache configured from a file. Create a tcp service to talk to * that cache. Put via the servive. Verify that the cache got the data. * * @throws Exception * */ public void testStandardPut() throws Exception { String region = "region1"; JCS cache = JCS.getInstance( region ); Thread.sleep( 100 ); TCPLateralCacheAttributes lattr2 = new TCPLateralCacheAttributes(); lattr2.setTcpListenerPort( 1102 ); lattr2.setTransmissionTypeName( "TCP" ); lattr2.setTcpServer( "localhost:1110" ); lattr2.setIssueRemoveOnPut( false ); // should still try to remove // lattr2.setAllowPut( false ); // Using the lateral, this service will put to and remove from // the cache instance above. // The cache thinks it is different since the listenerid is different LateralTCPService service = new LateralTCPService( lattr2 ); service.setListenerId( 123456 ); String keyToBeRemovedOnPut = "test1_notremoved"; ICacheElement element1 = new CacheElement( region, keyToBeRemovedOnPut, region + ":data-this shouldn't get removed, it should get to the cache." ); service.update( element1 ); Thread.sleep( 1000 ); Object testObj = cache.get( keyToBeRemovedOnPut ); p( "testStandardPut, test object = " + testObj ); assertNotNull( "The test object should not have been removed by a put.", testObj ); } /** * This tests issues tons of puts. It also check to see that a key that was * put in was removed by the clients remove command. * * @param region * Name of the region to access * @param range * @param numOps * @param testNum * * @exception Exception * If an error occurs */ public void runTestForRegion( String region, int range, int numOps, int testNum ) throws Exception { boolean show = true;// false; JCS cache = JCS.getInstance( region ); Thread.sleep( 100 ); TCPLateralCacheAttributes lattr2 = new TCPLateralCacheAttributes(); lattr2.setTcpListenerPort( 1102 ); lattr2.setTransmissionTypeName( "TCP" ); lattr2.setTcpServer( "localhost:1110" ); lattr2.setIssueRemoveOnPut( true ); // should still try to remove lattr2.setAllowPut( false ); // Using the lateral, this service will put to and remove from // the cache instance above. // The cache thinks it is different since the listenerid is different LateralTCPService service = new LateralTCPService( lattr2 ); service.setListenerId( 123456 ); String keyToBeRemovedOnPut = "test1"; cache.put( keyToBeRemovedOnPut, "this should get removed." ); ICacheElement element1 = new CacheElement( region, keyToBeRemovedOnPut, region + ":data-this shouldn't get there" ); service.update( element1 ); try { for ( int i = 1; i < numOps; i++ ) { Random ran = new Random( i ); int n = ran.nextInt( 4 ); int kn = ran.nextInt( range ); String key = "key" + kn; ICacheElement element = new CacheElement( region, key, region + ":data" + i + " junk asdfffffffadfasdfasf " + kn + ":" + n ); service.update( element ); if ( show ) { p( "put " + key ); } if ( i % 100 == 0 ) { System.out.println( cache.getStats() ); } } p( "Finished cycle of " + numOps ); } catch ( Exception e ) { p( e.toString() ); e.printStackTrace( System.out ); throw e; } JCS jcs = JCS.getInstance( region ); String key = "testKey" + testNum; String data = "testData" + testNum; jcs.put( key, data ); String value = (String) jcs.get( key ); assertEquals( "Couldn't put normally.", data, value ); // make sure the items we can find are in the correct region. for ( int i = 1; i < numOps; i++ ) { String keyL = "key" + i; String dataL = (String) jcs.get( keyL ); if ( dataL != null ) { assertTrue( "Incorrect region detected.", dataL.startsWith( region ) ); } } Thread.sleep( 200 ); Object testObj = cache.get( keyToBeRemovedOnPut ); p( "runTestForRegion, test object = " + testObj ); assertNull( "The test object should have been removed by a put.", testObj ); } /** * @param s * String to be printed */ public static void p( String s ) { if ( isSysOut ) { System.out.println( s ); } } }