answer
stringlengths
17
10.2M
package eu.amidst.huginlink.inference; import COM.hugin.HAPI.*; import eu.amidst.core.distribution.*; import eu.amidst.core.inference.InferenceAlgorithmForBN; import eu.amidst.core.models.BayesianNetwork; import eu.amidst.core.utils.BayesianNetworkGenerator; import eu.amidst.core.variables.Assignment; import eu.amidst.core.variables.HashMapAssignment; import eu.amidst.core.variables.Variable; import eu.amidst.huginlink.converters.BNConverterToHugin; import eu.amidst.huginlink.io.BNWriterToHugin; public class HuginInferenceForBN implements InferenceAlgorithmForBN { /** * The Bayesian network model in AMIDST format. */ BayesianNetwork amidstBN; /** * The Bayesian network model in Hugin format. */ Domain huginBN; /** * Sets an evidence to a Hugin variable. * * @param n the AMIDST variable to be evidenced. * @param value the evidenced value. * @throws ExceptionHugin */ private void setVarEvidence(Variable n, double value) throws ExceptionHugin { if (n.isMultinomial()){ ((DiscreteNode)huginBN.getNodeByName(n.getName())).selectState((long)value); } else if (n.isNormal()) { ((ContinuousChanceNode)huginBN.getNodeByName(n.getName())).enterValue(value); } else { throw new IllegalArgumentException("Variable type not allowed."); } } /** * Prints the belief of a Hugin node. * * @param node the node whose belief is printed. * @throws ExceptionHugin */ private void printBelief(Node node) throws ExceptionHugin { if (node instanceof DiscreteNode) { DiscreteNode dNode = (DiscreteNode) node; int n = (int) dNode.getNumberOfStates(); for (int i=0;i<n;i++) { System.out.print (" -> " + dNode.getStateLabel(i)+ " " + dNode.getBelief(i)); System.out.println(); } } else { ContinuousChanceNode ccNode = (ContinuousChanceNode) node; System.out.println (" - Mean : " + ccNode.getMean()); System.out.println (" - SD : " + Math.sqrt (ccNode.getVariance())); } } /** * Prints the beliefs of the Hugin network. * * @throws ExceptionHugin */ private void printBeliefs () throws ExceptionHugin { NodeList nodes = huginBN.getNodes(); java.util.ListIterator it = nodes.listIterator(); while (it.hasNext()) { Node node = (Node) it.next(); System.out.println(); System.out.println(node.getLabel() + " (" + node.getName() + ")"); printBelief(node); } } @Override public void runInference() { try { this.huginBN.compile(); huginBN.propagate(Domain.H_EQUILIBRIUM_SUM, Domain.H_EVIDENCE_MODE_NORMAL); } catch (ExceptionHugin exceptionHugin) { exceptionHugin.printStackTrace(); } } @Override public void setModel(BayesianNetwork model) { this.amidstBN = model; try { this.huginBN = BNConverterToHugin.convertToHugin(model); } catch (ExceptionHugin exceptionHugin) { exceptionHugin.printStackTrace(); } } @Override public BayesianNetwork getOriginalModel() { return amidstBN; } @Override public void setEvidence(Assignment assignment) { ((HashMapAssignment)assignment).entrySet().stream() .forEach(entry -> { try { this.setVarEvidence(entry.getKey(), entry.getValue().doubleValue()); } catch (ExceptionHugin exceptionHugin) { exceptionHugin.printStackTrace(); } }); } @Override public <E extends UnivariateDistribution> E getPosterior(Variable var) { try { Node huginNode = huginBN.getNodeByName(var.getName()); if (var.isMultinomial()) { Multinomial dist = new Multinomial(var); for(int i=0;i<var.getNumberOfStates();i++){ dist.setProbabilityOfState(i, ((DiscreteNode) huginNode).getBelief(i)); } return (E)dist; } else if (var.isNormal()) { Normal dist = new Normal(var); dist.setMean(((ContinuousChanceNode)huginNode).getMean()); dist.setSd(Math.sqrt(((ContinuousChanceNode) huginNode).getVariance())); return (E)dist; } else { throw new IllegalArgumentException("Variable type not allowed."); } } catch (ExceptionHugin exceptionHugin) { exceptionHugin.printStackTrace(); } return null; } @Override public double getLogProbabilityOfEvidence() { throw new UnsupportedOperationException("Method not implemented"); } @Override public void setSeed(int seed) { } public static void main(String args[]) throws ExceptionHugin { BayesianNetworkGenerator.setNumberOfDiscreteVars(2); BayesianNetworkGenerator.setNumberOfContinuousVars(2); BayesianNetwork bn = BayesianNetworkGenerator.generateNaiveBayes(2); BNWriterToHugin.saveToHuginFile(bn,"networks/inference.net"); Variable DiscreteVar0 = bn.getStaticVariables().getVariableById(0); Variable GaussianVar0 = bn.getStaticVariables().getVariableById(1); Variable GaussianVar1 = bn.getStaticVariables().getVariableById(2); Variable ClassVar = bn.getStaticVariables().getVariableById(3); // SET THE EVIDENCE HashMapAssignment assignment = new HashMapAssignment(2); //assignment.setValue(ClassVar, 0.0); assignment.setValue(DiscreteVar0, 1.0); assignment.setValue(GaussianVar0, -2.0); //assignment.setValue(GaussianVar1, 0.0); // INFERENCE HuginInferenceForBN inferenceForBN = new HuginInferenceForBN(); inferenceForBN.setModel(bn); inferenceForBN.setEvidence(assignment); inferenceForBN.runInference(); // POSTERIOR DISTRIBUTION System.out.println((inferenceForBN.getPosterior(ClassVar)).toString()); //System.out.println((inferenceForBN.getPosterior(DiscreteVar0)).toString()); //System.out.println((inferenceForBN.getPosterior(GaussianVar0)).toString()); //System.out.println((inferenceForBN.getPosterior(GaussianVar1)).toString()); } }
package ev3dev.utils.io; import com.sun.jna.LastErrorException; import com.sun.jna.NativeLong; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; import java.io.Closeable; import java.nio.ByteBuffer; public class NativeFile implements Closeable, AutoCloseable { protected int fd = -1; private ILibc libc; /** * Basic constructor. */ protected NativeFile() { this(new NativeLibc()); } /** * Basic constructor. * * @param libc standard C library interface to be used. */ protected NativeFile(ILibc libc) { this.libc = libc; } /** * Create a NativeFile object and open the associated file/device * for native access. * * @param fname the name of the file to open * @param flags Linux style file access flags * @throws LastErrorException when operations fails */ public NativeFile(String fname, int flags) throws LastErrorException { this(fname, flags, new NativeLibc()); } /** * Create a NativeFile object and open the associated file/device * for native access. * * @param fname the name of the file to open * @param flags Linux style file access flags * @param mode Linux style file access mode * @throws LastErrorException when operations fails */ public NativeFile(String fname, int flags, int mode) throws LastErrorException { this(fname, flags, mode, new NativeLibc()); } /** * Create a NativeFile object and open the associated file/device * for native access. * * @param fname the name of the file to open * @param flags Linux style file access flags * @param libc standard C library interface to be used. * @throws LastErrorException when operations fails */ public NativeFile(String fname, int flags, ILibc libc) throws LastErrorException { this.libc = libc; open(fname, flags); } /** * Create a NativeFile object and open the associated file/device * for native access. * * @param fname the name of the file to open * @param flags Linux style file access flags * @param mode Linux style file access mode * @param libc standard C library interface to be used. * @throws LastErrorException when operations fails */ public NativeFile(String fname, int flags, int mode, ILibc libc) throws LastErrorException { this.libc = libc; open(fname, flags, mode); } /** * Check whether this file has been open()en. * * @return True when the filedescriptor is valid. */ public boolean isOpen() { return fd != -1; } /** * Open the specified file/device for native access. * * @param fname the name of the file to open * @param flags Linux style file access flags * @throws LastErrorException when operations fails */ public void open(String fname, int flags) throws LastErrorException { fd = libc.open(fname, flags); } /** * Open the specified file/device for native access. * * @param fname the name of the file to open * @param flags Linux style file access flags * @param mode Linux style file access mode * @throws LastErrorException when operations fails */ public void open(String fname, int flags, int mode) throws LastErrorException { fd = libc.open(fname, flags, mode); } /** * Attempt to read the requested number of bytes from the associated file. * * @param buf location to store the read bytes * @param len number of bytes to attempt to read * @return number of bytes read * @throws LastErrorException when operations fails */ public int read(byte[] buf, int len) throws LastErrorException { return libc.read(fd, ByteBuffer.wrap(buf), len); } /** * Attempt to write the requested number of bytes to the associated file. * * @param buf location to store the read bytes * @param offset the offset within buf to take data from for the write * @param len number of bytes to attempt to read * @return number of bytes read * @throws LastErrorException when operations fails */ public int write(byte[] buf, int offset, int len) throws LastErrorException { return libc.write(fd, ByteBuffer.wrap(buf, offset, len), len); } /** * Attempt to read the requested number of byte from the associated file. * * @param buf location to store the read bytes * @param offset offset with buf to start storing the read bytes * @param len number of bytes to attempt to read * @return number of bytes read * @throws LastErrorException when operations fails */ public int read(byte[] buf, int offset, int len) throws LastErrorException { return libc.read(fd, ByteBuffer.wrap(buf, offset, len), len); } /** * Attempt to write the requested number of bytes to the associated file. * * @param buf location to store the read bytes * @param len number of bytes to attempt to read * @return number of bytes read * @throws LastErrorException when operations fails */ public int write(byte[] buf, int len) throws LastErrorException { return libc.write(fd, ByteBuffer.wrap(buf), len); } /** * Perform a Linux style ioctl operation on the associated file. * * @param req ioctl operation to be performed * @param info output as integer * @return Linux style ioctl return * @throws LastErrorException when operations fails */ public int ioctl(int req, IntByReference info) throws LastErrorException { return libc.ioctl(fd, req, info); } /** * Perform a Linux style ioctl operation on the associated file. * * @param req ioctl operation to be performed * @param info input as integer * @return Linux style ioctl return * @throws LastErrorException when operations fails */ public int ioctl(int req, int info) throws LastErrorException { return libc.ioctl(fd, req, info); } /** * Perform a Linux style ioctl operation on the associated file. * * @param req ioctl operation to be performed * @param buf pointer to ioctl parameters * @return Linux style ioctl return * @throws LastErrorException when operations fails */ public int ioctl(int req, Pointer buf) throws LastErrorException { return libc.ioctl(fd, req, buf); } /** * Perform a Linux style ioctl operation on the associated file. * * @param req ioctl operation to be performed * @param buf byte array containing the ioctl parameters if any * @return Linux style ioctl return * @throws LastErrorException when operations fails */ public int ioctl(int req, byte[] buf) throws LastErrorException { return libc.ioctl(fd, req, buf); } /** * Close the associated file * * @throws LastErrorException when operations fails */ @Override public void close() throws LastErrorException { if (fd != -1) { int copy = fd; fd = -1; libc.close(copy); } } /** * Map a portion of the associated file into memory and return a pointer * that can be used to access that memory. * * @param len size of the region to map * @param prot protection for the memory region * @param flags Linux mmap flags * @param off offset within the file for the start of the region * @return a pointer that can be used to access the mapped data * @throws LastErrorException when operations fails */ public Pointer mmap(long len, int prot, int flags, long off) throws LastErrorException { Pointer p = libc.mmap(new Pointer(0), new NativeLong(len), prot, flags, fd, new NativeLong(off)); if (p.equals(new Pointer(-1))) { throw new LastErrorException("mmap() failed"); } return p; } /** * Unmap mapped memory region. * * @param addr Mapped address. * @param len Region length. * @throws LastErrorException when operations fails */ public void munmap(Pointer addr, long len) throws LastErrorException { libc.munmap(addr, new NativeLong(len)); } }
package org.inaturalist.android; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.inaturalist.android.INaturalistApp.INotificationCallback; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.cocosw.bottomsheet.BottomSheet; import com.flurry.android.FlurryAgent; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener; import com.handmark.pulltorefresh.library.PullToRefreshListView; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.graphics.Typeface; import android.os.Handler; import android.content.BroadcastReceiver; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.WindowManager; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public class ObservationListActivity extends BaseFragmentActivity implements INotificationCallback, DialogInterface.OnClickListener, ObservationCursorAdapter.OnLoadingMoreResultsListener { public static String TAG = "INAT:ObservationListActivity"; public final static String PARAM_FROM_OBS_EDITOR = "from_obs_editor"; private boolean[] mIsGrid = new boolean[] { false, false, false }; private NewsReceiver mNewsReceiver; private SyncCompleteReceiver mSyncCompleteReceiver; private int mLastIndex; private int mLastTop; private ViewGroup mSyncingTopBar; private ObservationCursorAdapter mObservationListAdapter; private ObservationCursorAdapter mObservationGridAdapter; private ActivityHelper mHelper; private String mLastMessage; private INaturalistApp mApp; private TextView mSyncingStatus; private TextView mCancelSync; private boolean mUserCanceledSync = false; // When the user chose to pause/stop sync while in auto sync mode private boolean mSyncRequested = false; private Menu mMenu; private TabLayout mTabLayout; private ViewPager mViewPager; private String mViewType; private final static String VIEW_TYPE_OBSERVATIONS = "observations"; private final static String VIEW_TYPE_SPECIES = "species"; private final static String VIEW_TYPE_IDENTIFICATIONS = "identifications"; private ProgressBar mLoadingIdentifications; private TextView mIdentificationsEmpty; private ImageView mIdentificationsEmptyIcon; private PullToRefreshListView mIdentificationsList; private PullToRefreshGridViewExtended mIdentificationsGrid; private ProgressBar mLoadingSpecies; private TextView mSpeciesEmpty; private ImageView mSpeciesEmptyIcon; private PullToRefreshListView mSpeciesList; private PullToRefreshGridViewExtended mSpeciesGrid; private ProgressBar mLoadingObservations; private TextView mObservationsEmpty; private ImageView mObservationsEmptyIcon; private PullToRefreshListView mObservationsList; private PullToRefreshGridViewExtended mObservationsGrid; private ArrayList<JSONObject> mSpecies; private ArrayList<JSONObject> mIdentifications; private int mTotalIdentifications = 0; private int mTotalSpecies = 0; private UserSpeciesAdapter mSpeciesListAdapter; private UserSpeciesAdapter mSpeciesGridAdapter; private UserIdentificationsAdapter mIdentificationsListAdapter; private UserIdentificationsAdapter mIdentificationsGridAdapter; private BetterJSONObject mUser; private UserDetailsReceiver mUserDetailsReceiver; private ObservationSyncProgressReceiver mObservationSyncProgressReceiver; private ViewGroup mOnboardingSyncing; private View mOnboardingSyncingClose; private boolean mSelectedBottomGrid = false; private TextView mAddButtonText; private boolean mFromObsEdit = false; private ViewGroup mLoadingMoreResults; @Override protected void onStart() { super.onStart(); FlurryAgent.onStartSession(this, INaturalistApp.getAppContext().getString(R.string.flurry_api_key)); FlurryAgent.logEvent(this.getClass().getSimpleName()); } @Override protected void onStop() { super.onStop(); FlurryAgent.onEndSession(this); } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } @Override public void onClick(DialogInterface dialogInterface, int i) { // User chose to cancel sync mApp.setCancelSync(true); refreshSyncBar(); } @Override public void onLoadingMoreResultsStart() { mLoadingMoreResults.setVisibility(View.VISIBLE); } @Override public void onLoadingMoreResultsFinish() { mLoadingMoreResults.setVisibility(View.GONE); } @Override public void onLoadingMoreResultsFailed() { mLoadingMoreResults.setVisibility(View.GONE); (new Handler()).postDelayed(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), getResources().getString(R.string.not_connected), Toast.LENGTH_LONG).show(); } }, 100); } private class SyncCompleteReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "Got ACTION_SYNC_COMPLETE"); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mObservationsList.onRefreshComplete(); mObservationsList.refreshDrawableState(); mObservationsGrid.onRefreshComplete(); mObservationsGrid.refreshDrawableState(); mObservationListAdapter.refreshCursor(); mObservationGridAdapter.refreshCursor(); refreshSyncBar(); if (mApp.loggedIn() && !mApp.getIsSyncing() && (mObservationListAdapter.getCount() == 0)) { // Show a "no observations" message if (mObservationsEmpty != null) mObservationsEmpty.setText(R.string.no_observations_found_new); } DecimalFormat formatter = new DecimalFormat(" SharedPreferences settings = mApp.getPrefs(); ((TextView) mTabLayout.getTabAt(0).getCustomView().findViewById(R.id.count)).setText(formatter.format(settings.getInt("observation_count", mObservationListAdapter.getCount()))); mSyncRequested = false; if (!mApp.getIsSyncing()) { if ((intent != null) && (!intent.getBooleanExtra(INaturalistService.SYNC_CANCELED, false))) { // Sync finished mUserCanceledSync = false; refreshSyncBar(); refreshViewState(); try { JSONObject eventParams = new JSONObject(); eventParams.put(AnalyticsClient.EVENT_PARAM_VIA, AnalyticsClient.EVENT_VALUE_UPLOAD_COMPLETE); AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_SYNC_STOPPED, eventParams); } catch (JSONException e) { e.printStackTrace(); } // Trigger another sync if needed - in case the user added more obs in the meantime while sync was running triggerSyncIfNeeded(); } // Decide if to show onboarding message SharedPreferences prefs = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); boolean hasOnboardedSyncing = prefs.getBoolean("onboarded_syncing", false); if (!intent.getBooleanExtra(INaturalistService.FIRST_SYNC, false)) { mOnboardingSyncing.setVisibility(hasOnboardedSyncing || !mApp.loggedIn() ? View.GONE : View.VISIBLE); } } } } public static Intent createIntent(Context context) { Intent i = new Intent(context, ObservationListActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); return i; } /** Shows the sync required bottom bar, if needed */ private void refreshSyncBar() { int syncCount = 0; int photoSyncCount = 0; if (mApp.getAutoSync()) { // Auto sync is on - no need for manual sync (only if the sync wasn't paused by the user) if (!mUserCanceledSync) { if (mSyncingTopBar != null) mSyncingTopBar.setVisibility(View.GONE); return; } } Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "((_updated_at > _synced_at AND _synced_at IS NOT NULL) OR (_synced_at IS NULL)) AND (_updated_at > _created_at)", null, Observation.SYNC_ORDER); syncCount = c.getCount(); c.close(); Cursor opc = getContentResolver().query(ObservationPhoto.CONTENT_URI, new String[]{ ObservationPhoto._ID, ObservationPhoto._OBSERVATION_ID, ObservationPhoto._PHOTO_ID, ObservationPhoto.PHOTO_URL, ObservationPhoto._UPDATED_AT, ObservationPhoto._SYNCED_AT }, "((photo_url IS NULL) AND (_updated_at IS NOT NULL) AND (_synced_at IS NULL)) OR " + "((photo_url IS NULL) AND (_updated_at IS NOT NULL) AND (_synced_at IS NOT NULL) AND (_updated_at > _synced_at)) OR " + "(is_deleted = 1)", null, ObservationPhoto._ID); photoSyncCount = opc.getCount(); opc.close(); if (mSyncingTopBar != null) { if ((syncCount > 0) || (photoSyncCount > 0)) { int count = (syncCount > 0 ? syncCount : photoSyncCount); if (count == 1) { mSyncingStatus.setText(R.string.sync_1_observation); } else { mSyncingStatus.setText(String.format(getResources().getString(R.string.sync_x_observations), count)); } mSyncingTopBar.setVisibility(View.VISIBLE); mUserCanceledSync = true; // To make it so that the button on the sync bar will trigger a sync mCancelSync.setText(R.string.upload); } else { mSyncingTopBar.setVisibility(View.GONE); } } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.observation_list); setTitle(R.string.observations); getSupportActionBar().setElevation(0); AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_ME); mHelper = new ActivityHelper(this); mApp = (INaturalistApp)getApplication(); if (savedInstanceState != null) { mLastMessage = savedInstanceState.getString("mLastMessage"); mUserCanceledSync = savedInstanceState.getBoolean("mUserCanceledSync"); mIsGrid = savedInstanceState.getBooleanArray("mIsGrid"); mViewType = savedInstanceState.getString("mViewType"); mUser = (BetterJSONObject) savedInstanceState.getSerializable("user"); mSpecies = loadListFromBundle(savedInstanceState, "mSpecies"); mIdentifications = loadListFromBundle(savedInstanceState, "mIdentifications"); mTotalIdentifications = savedInstanceState.getInt("mTotalIdentifications"); mTotalSpecies = savedInstanceState.getInt("mTotalSpecies"); mFromObsEdit = savedInstanceState.getBoolean("mFromObsEdit"); } else { SharedPreferences settings = mApp.getPrefs(); String isGridArray = settings.getString("me_screen_list_grid", null); if (isGridArray != null) { int i = 0; for (String value : isGridArray.split(",")) { mIsGrid[i] = Boolean.valueOf(value); i++; } } mViewType = VIEW_TYPE_OBSERVATIONS; mFromObsEdit = getIntent().getBooleanExtra(PARAM_FROM_OBS_EDITOR, false); } SharedPreferences pref = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); String username = pref.getString("username", null); if (username == null) { if (!mApp.shownOnboarding()) { // Show login/onboarding screen mApp.setShownOnboarding(true); Intent intent = new Intent(this, OnboardingActivity.class); intent.putExtra(OnboardingActivity.SHOW_SKIP, true); startActivity(intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP)); } } INaturalistApp app = (INaturalistApp)(getApplication()); app.setNotificationCallback(this); Intent intent = getIntent(); if (intent.getData() == null) { intent.setData(Observation.CONTENT_URI); } onDrawerCreate(savedInstanceState); initializeTabs(); triggerSyncIfNeeded(); refreshViewState(); // Clear out any old cached photos Intent serviceIntent = new Intent(INaturalistService.ACTION_CLEAR_OLD_PHOTOS_CACHE, null, ObservationListActivity.this, INaturalistService.class); startService(serviceIntent); // Get the user's activities serviceIntent = new Intent(INaturalistService.ACTION_GET_USER_UPDATES, null, this, INaturalistService.class); serviceIntent.putExtra(INaturalistService.FOLLOWING, false); startService(serviceIntent); } private void refreshViewState() { DecimalFormat formatter = new DecimalFormat(" if (mLoadingObservations != null) { if (mApp.loggedIn() && mApp.getIsSyncing() && (mObservationListAdapter.getCount() == 0)) { // Show a "downloading ..." message instead of "no observations yet" mObservationsEmpty.setText(R.string.downloading_observations); mObservationsEmptyIcon.setVisibility(View.GONE); mLoadingObservations.setVisibility(View.VISIBLE); ((TextView) mTabLayout.getTabAt(0).getCustomView().findViewById(R.id.count)).setVisibility(View.GONE); ((ProgressBar) mTabLayout.getTabAt(0).getCustomView().findViewById(R.id.loading)).setVisibility(View.VISIBLE); mObservationsGrid.setVisibility(View.GONE); mObservationsList.setVisibility(View.GONE); } else { ((TextView) mTabLayout.getTabAt(0).getCustomView().findViewById(R.id.count)).setVisibility(View.VISIBLE); ((ProgressBar) mTabLayout.getTabAt(0).getCustomView().findViewById(R.id.loading)).setVisibility(View.GONE); SharedPreferences settings = mApp.getPrefs(); ((TextView) mTabLayout.getTabAt(0).getCustomView().findViewById(R.id.count)).setText(formatter.format(settings.getInt("observation_count", mObservationListAdapter.getCount()))); mLoadingObservations.setVisibility(View.GONE); if (mIsGrid[0]) { mObservationsGrid.setVisibility(View.VISIBLE); mObservationsList.setVisibility(View.GONE); } else { mObservationsGrid.setVisibility(View.GONE); mObservationsList.setVisibility(View.VISIBLE); } if (mObservationListAdapter.getCount() == 0) { mObservationsEmptyIcon.setVisibility(View.VISIBLE); mObservationsEmpty.setVisibility(View.VISIBLE); mAddButtonText.setVisibility(View.VISIBLE); } else { mObservationsEmptyIcon.setVisibility(View.GONE); mObservationsEmpty.setVisibility(View.GONE); mAddButtonText.setVisibility(View.GONE); } mObservationsEmpty.setText(R.string.no_observations_found_new); } } if (mLoadingSpecies != null) { if ((mSpecies == null) && (mApp.loggedIn())) { ((TextView) mTabLayout.getTabAt(1).getCustomView().findViewById(R.id.count)).setVisibility(View.GONE); ((ProgressBar) mTabLayout.getTabAt(1).getCustomView().findViewById(R.id.loading)).setVisibility(View.VISIBLE); mLoadingSpecies.setVisibility(View.VISIBLE); mSpeciesEmpty.setVisibility(View.GONE); mSpeciesEmptyIcon.setVisibility(View.GONE); mSpeciesList.setVisibility(View.GONE); mSpeciesGrid.setVisibility(View.GONE); } else { ((TextView) mTabLayout.getTabAt(1).getCustomView().findViewById(R.id.count)).setVisibility(View.VISIBLE); ((ProgressBar) mTabLayout.getTabAt(1).getCustomView().findViewById(R.id.loading)).setVisibility(View.GONE); ((TextView) mTabLayout.getTabAt(1).getCustomView().findViewById(R.id.count)).setText(formatter.format(mTotalSpecies)); mLoadingSpecies.setVisibility(View.GONE); if ((mSpecies == null) || (mSpecies.size() == 0)) { mSpeciesEmpty.setVisibility(View.VISIBLE); mSpeciesEmptyIcon.setVisibility(View.VISIBLE); mSpeciesList.setVisibility(View.GONE); mSpeciesGrid.setVisibility(View.GONE); mSpeciesListAdapter = new UserSpeciesAdapter(this, new ArrayList<JSONObject>()); mSpeciesGridAdapter = new UserSpeciesAdapter(this, new ArrayList<JSONObject>(), UserSpeciesAdapter.VIEW_TYPE_GRID, mSpeciesGrid); } else { mSpeciesEmpty.setVisibility(View.GONE); mSpeciesEmptyIcon.setVisibility(View.GONE); if (mIsGrid[1]) { mSpeciesGrid.setVisibility(View.VISIBLE); mSpeciesList.setVisibility(View.GONE); } else { mSpeciesGrid.setVisibility(View.GONE); mSpeciesList.setVisibility(View.VISIBLE); } mSpeciesListAdapter = new UserSpeciesAdapter(this, mSpecies); mSpeciesGridAdapter = new UserSpeciesAdapter(this, mSpecies, UserSpeciesAdapter.VIEW_TYPE_GRID, mSpeciesGrid); } mSpeciesGrid.setAdapter(mSpeciesGridAdapter); mSpeciesList.setAdapter(mSpeciesListAdapter); mSpeciesList.setOnScrollListener(mSpeciesListAdapter); mSpeciesGrid.setOnScrollListener(mSpeciesGridAdapter); } } if (mLoadingIdentifications != null) { if ((mIdentifications == null) && (mApp.loggedIn())) { ((TextView) mTabLayout.getTabAt(2).getCustomView().findViewById(R.id.count)).setVisibility(View.GONE); ((ProgressBar) mTabLayout.getTabAt(2).getCustomView().findViewById(R.id.loading)).setVisibility(View.VISIBLE); mLoadingIdentifications.setVisibility(View.VISIBLE); mIdentificationsEmpty.setVisibility(View.GONE); mIdentificationsEmptyIcon.setVisibility(View.GONE); mIdentificationsList.setVisibility(View.GONE); mIdentificationsGrid.setVisibility(View.GONE); } else { ((TextView) mTabLayout.getTabAt(2).getCustomView().findViewById(R.id.count)).setVisibility(View.VISIBLE); ((ProgressBar) mTabLayout.getTabAt(2).getCustomView().findViewById(R.id.loading)).setVisibility(View.GONE); ((TextView) mTabLayout.getTabAt(2).getCustomView().findViewById(R.id.count)).setText(formatter.format(mTotalIdentifications)); mLoadingIdentifications.setVisibility(View.GONE); if ((mIdentifications == null) || (mIdentifications.size() == 0)) { mIdentificationsEmpty.setVisibility(View.VISIBLE); mIdentificationsEmptyIcon.setVisibility(View.VISIBLE); mIdentificationsList.setVisibility(View.GONE); mIdentificationsGrid.setVisibility(View.GONE); mIdentificationsListAdapter = new UserIdentificationsAdapter(this, new ArrayList<JSONObject>(), mApp.currentUserLogin()); mIdentificationsGridAdapter = new UserIdentificationsAdapter(this, new ArrayList<JSONObject>(), mApp.currentUserLogin(), true, mIdentificationsGrid); } else { mIdentificationsEmpty.setVisibility(View.GONE); mIdentificationsEmptyIcon.setVisibility(View.GONE); mIdentificationsListAdapter = new UserIdentificationsAdapter(this, mIdentifications, mApp.currentUserLogin()); mIdentificationsGridAdapter = new UserIdentificationsAdapter(this, mIdentifications, mApp.currentUserLogin(), true, mIdentificationsGrid); if (mIsGrid[2]) { mIdentificationsGrid.setVisibility(View.VISIBLE); mIdentificationsList.setVisibility(View.GONE); } else { mIdentificationsGrid.setVisibility(View.GONE); mIdentificationsList.setVisibility(View.VISIBLE); } } mIdentificationsList.setAdapter(mIdentificationsListAdapter); mIdentificationsGrid.setAdapter(mIdentificationsGridAdapter); // Make sure the images get loaded only when the user stops scrolling mIdentificationsList.setOnScrollListener(mIdentificationsListAdapter); mIdentificationsGrid.setOnScrollListener(mIdentificationsGridAdapter); } } refreshGridListMenuIcon(); } private void triggerSyncIfNeeded() { boolean hasOldObs = hasOldObservations(); if ((mApp.getAutoSync() && !mApp.getIsSyncing() && (!mSyncRequested)) || (hasOldObs)) { int syncCount = 0; int photoSyncCount = 0; if (!hasOldObs) { Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "((_updated_at > _synced_at AND _synced_at IS NOT NULL) OR (_synced_at IS NULL) OR (is_deleted = 1))", null, Observation.SYNC_ORDER); syncCount = c.getCount(); c.close(); c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "((photo_url IS NULL) AND (_updated_at IS NOT NULL) AND (_synced_at IS NULL)) OR " + "((photo_url IS NULL) AND (_updated_at IS NOT NULL) AND (_synced_at IS NOT NULL) AND (_updated_at > _synced_at) AND (id IS NOT NULL)) OR " + "(is_deleted = 1)" , null, ObservationPhoto.DEFAULT_SORT_ORDER); photoSyncCount = c.getCount(); c.close(); } Log.d(TAG, String.format("triggerSyncIfNeeded: hasOldOBs: %b; syncCount: %d; photoSyncCount: %d; mUserCanceledSync: %b", hasOldObs, syncCount, photoSyncCount, mUserCanceledSync)); // Trigger a sync (in case of auto-sync and unsynced obs OR when having old-style observations) if (hasOldObs || (((syncCount > 0) || (photoSyncCount > 0)) && (!mUserCanceledSync) && (isNetworkAvailable()))) { mSyncRequested = true; Intent serviceIntent = new Intent(INaturalistService.ACTION_SYNC, null, ObservationListActivity.this, INaturalistService.class); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); startService(serviceIntent); if (mSyncingTopBar != null) { mSyncingStatus.setText(R.string.syncing); mSyncingTopBar.setVisibility(View.VISIBLE); } } } } // Checks to see if there are any observations that have the "old" way of saving photos private boolean hasOldObservations() { Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "(photo_filename IS NULL) AND (photo_url IS NULL)", null, ObservationPhoto.DEFAULT_SORT_ORDER); int count = c.getCount(); c.close(); return count > 0; } @SuppressLint("NewApi") @Override public void onPause() { super.onPause(); Log.d(TAG, "onPause"); // save last position of list so we can resume there later if (mObservationsGrid != null) { AbsListView lv = mIsGrid[0] ? mObservationsGrid.getRefreshableView() : mObservationsList.getRefreshableView(); mLastIndex = lv.getFirstVisiblePosition(); View v = lv.getChildAt(0); mLastTop = (v == null) ? 0 : v.getTop(); } // Save listview/gridview preferences SharedPreferences settings = mApp.getPrefs(); SharedPreferences.Editor settingsEditor = settings.edit(); settingsEditor.putString("me_screen_list_grid", String.format("%s,%s,%s", mIsGrid[0], mIsGrid[1], mIsGrid[2])); settingsEditor.apply(); safeUnregisterReceiver(mObservationSyncProgressReceiver); safeUnregisterReceiver(mNewsReceiver); safeUnregisterReceiver(mUserDetailsReceiver); safeUnregisterReceiver(mSyncCompleteReceiver); safeUnregisterReceiver(mConnectivityListener); } @Override public void onResume() { super.onResume(); if (mApp == null) { mApp = (INaturalistApp) getApplicationContext(); } if (mFromObsEdit) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { finishAndRemoveTask(); } else { finish(); } } if (!mApp.loggedIn()) { if ((mTotalIdentifications > 0) || (mTotalIdentifications > 0)) { mTotalSpecies = 0; mTotalIdentifications = 0; mSpecies = null; mIdentifications = null; refreshViewState(); } } mUserDetailsReceiver = new UserDetailsReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(INaturalistService.USER_DETAILS_RESULT); filter.addAction(INaturalistService.SPECIES_COUNT_RESULT); filter.addAction(INaturalistService.USER_OBSERVATIONS_RESULT); filter.addAction(INaturalistService.IDENTIFICATIONS_RESULT); safeRegisterReceiver(mUserDetailsReceiver, filter); mObservationSyncProgressReceiver = new ObservationSyncProgressReceiver(); IntentFilter filter2 = new IntentFilter(); filter2.addAction(INaturalistService.OBSERVATION_SYNC_PROGRESS); safeRegisterReceiver(mObservationSyncProgressReceiver, filter2); mSyncCompleteReceiver = new SyncCompleteReceiver(); IntentFilter filter3 = new IntentFilter(INaturalistService.ACTION_SYNC_COMPLETE); Log.i(TAG, "Registering ACTION_SYNC_COMPLETE"); safeRegisterReceiver(mSyncCompleteReceiver, filter3); mConnectivityListener = new ConnectivityBroadcastReceiver(); IntentFilter filter4 = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); Log.i(TAG, "Registering CONNECTIVITY_ACTION"); safeRegisterReceiver(mConnectivityListener, filter4); mNewsReceiver = new NewsReceiver(); IntentFilter filter5 = new IntentFilter(); filter5.addAction(INaturalistService.UPDATES_RESULT); safeRegisterReceiver(mNewsReceiver, filter5); if (mLoadingObservations != null) { if (mIsGrid[0]) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { GridView grid = mObservationsGrid.getRefreshableView(); grid.setSelectionFromTop(mLastIndex, mLastTop); } } else { ListView lv = mObservationsList.getRefreshableView(); lv.setSelectionFromTop(mLastIndex, mLastTop); } mObservationListAdapter.refreshCursor(); mObservationListAdapter.refreshPhotoInfo(); if (mObservationGridAdapter != null) mObservationGridAdapter.refreshCursor(); DecimalFormat formatter = new DecimalFormat(" SharedPreferences settings = mApp.getPrefs(); ((TextView) mTabLayout.getTabAt(0).getCustomView().findViewById(R.id.count)).setText(formatter.format(settings.getInt("observation_count", mObservationListAdapter.getCount()))); } refreshSyncBar(); if (mLoadingObservations != null) { INaturalistApp app = (INaturalistApp) (getApplication()); if (app.getIsSyncing()) { // We're still syncing if ((mLastMessage != null) && (!mApp.getAutoSync())) mSyncingStatus.setText(mLastMessage); app.setNotificationCallback(this); if (!app.getAutoSync()) mCancelSync.setText(R.string.stop); } (new Handler()).postDelayed(new Runnable() { @Override public void run() { if (mApp.loggedIn() && mApp.getIsSyncing() && (mObservationListAdapter.getCount() == 0)) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.downloading_observations), Toast.LENGTH_LONG).show(); } } }, 100); if (mApp.loggedIn() && mApp.getIsSyncing() && (mObservationListAdapter.getCount() == 0)) { // Show a "downloading ..." message instead of "no observations yet" mObservationsEmpty.setText(R.string.downloading_observations); mLoadingObservations.setVisibility(View.VISIBLE); ((TextView) mTabLayout.getTabAt(0).getCustomView().findViewById(R.id.count)).setVisibility(View.GONE); ((ProgressBar) mTabLayout.getTabAt(0).getCustomView().findViewById(R.id.loading)).setVisibility(View.VISIBLE); refreshViewState(); getUserDetails(INaturalistService.ACTION_GET_SPECIFIC_USER_DETAILS); getUserDetails(INaturalistService.ACTION_GET_USER_IDENTIFICATIONS); getUserDetails(INaturalistService.ACTION_GET_USER_SPECIES_COUNT); } else { if (mObservationListAdapter.getCount() == 0) { mObservationsEmptyIcon.setVisibility(View.VISIBLE); mObservationsEmpty.setVisibility(View.VISIBLE); mAddButtonText.setVisibility(View.VISIBLE); } else { mObservationsEmptyIcon.setVisibility(View.GONE); mObservationsEmpty.setVisibility(View.GONE); mAddButtonText.setVisibility(View.GONE); } } } if (mApp.loggedIn() && (!mApp.getIsSyncing() && ((mObservationListAdapter == null) || (mObservationListAdapter.getCount() > 0)))) { if (mUser == null) getUserDetails(INaturalistService.ACTION_GET_SPECIFIC_USER_DETAILS); if (mIdentifications == null) getUserDetails(INaturalistService.ACTION_GET_USER_IDENTIFICATIONS); if (mSpecies == null) getUserDetails(INaturalistService.ACTION_GET_USER_SPECIES_COUNT); } triggerSyncIfNeeded(); } @Override protected void onSaveInstanceState(Bundle outState) { if (mLastMessage != null) outState.putString("mLastMessage", mLastMessage); outState.putBoolean("mUserCanceledSync", mUserCanceledSync); outState.putBooleanArray("mIsGrid", mIsGrid); outState.putString("mViewType", mViewType); outState.putSerializable("user", mUser); outState.putInt("mTotalIdentifications", mTotalIdentifications); outState.putInt("mTotalSpecies", mTotalSpecies); outState.putBoolean("mFromObsEdit", mFromObsEdit); saveListToBundle(outState, mSpecies, "mSpecies"); saveListToBundle(outState, mIdentifications, "mIdentifications"); super.onSaveInstanceState(outState); } private boolean isLoggedIn() { SharedPreferences prefs = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); return prefs.getString("username", null) != null; } @Override public void onNotification(String title, final String content) { mLastMessage = content; runOnUiThread(new Runnable() { @Override public void run() { if (mSyncingStatus != null) { mSyncingStatus.setText(content); int visibility; if (mApp.loggedIn() && mApp.getIsSyncing() && (mObservationListAdapter.getCount() == 0)) { visibility = View.GONE; } else { visibility = mApp.getIsSyncing() ? View.VISIBLE : View.GONE; } mSyncingTopBar.setVisibility(visibility); mObservationListAdapter.refreshCursor(); mObservationGridAdapter.refreshCursor(); } } }); } private ConnectivityBroadcastReceiver mConnectivityListener = null; private class ConnectivityBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { return; } boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); if (!noConnectivity) { // We're connected to the Internet - try syncing again triggerSyncIfNeeded(); } } } private void onRefreshView(final PullToRefreshBase pullToRefresh) { if (!isNetworkAvailable() || !isLoggedIn()) { Thread t = (new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } runOnUiThread(new Runnable() { @Override public void run() { pullToRefresh.onRefreshComplete(); } }); } })); t.start(); if (!isNetworkAvailable()) { Toast.makeText(getApplicationContext(), R.string.not_connected, Toast.LENGTH_LONG).show(); } else if (!isLoggedIn()) { Toast.makeText(getApplicationContext(), R.string.please_sign_in, Toast.LENGTH_LONG).show(); } return; } // Start sync Intent serviceIntent = new Intent(INaturalistService.ACTION_PULL_OBSERVATIONS, null, ObservationListActivity.this, INaturalistService.class); startService(serviceIntent); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.my_observations_menu, menu); mMenu = menu; refreshGridListMenuIcon(); return true; } private void refreshGridListMenuIcon() { if (mMenu != null) { int index = mViewPager.getCurrentItem(); if (!mIsGrid[index]) { mMenu.getItem(0).setIcon(R.drawable.grid_view_gray); } else { mMenu.getItem(0).setIcon(R.drawable.list_view_gray); } switch (index) { case 0: mMenu.getItem(0).setEnabled(true); break; case 1: mMenu.getItem(0).setEnabled(mSpecies != null); break; case 2: mMenu.getItem(0).setEnabled(mIdentifications != null); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.observation_view_type: mIsGrid[mViewPager.getCurrentItem()] = !mIsGrid[mViewPager.getCurrentItem()]; mLastIndex = 0; mLastTop = 0; refreshViewState(); return true; case R.id.search_observations: startActivity(new Intent(ObservationListActivity.this, ObservationSearchActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP)); return true; } return super.onOptionsItemSelected(item); } public class ObservationsPageAdapter extends PagerAdapter { final int PAGE_COUNT = 3; private Context mContext; public ObservationsPageAdapter(Context context) { mContext = context; } @Override public int getCount() { return PAGE_COUNT; } private void initPullToRefreshList(PullToRefreshBase pullToRefresh, ViewGroup layout) { pullToRefresh.getLoadingLayoutProxy().setPullLabel(getResources().getString(R.string.pull_to_refresh)); pullToRefresh.getLoadingLayoutProxy().setReleaseLabel(getResources().getString(R.string.release_to_refresh)); pullToRefresh.getLoadingLayoutProxy().setRefreshingLabel(getResources().getString(R.string.refreshing)); pullToRefresh.setReleaseRatio(2.5f); } @Override public Object instantiateItem(ViewGroup collection, int position) { LayoutInflater inflater = LayoutInflater.from(mContext); ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.observations_list_grid, collection, false); ((ViewGroup) layout.findViewById(R.id.loading_more_results)).setVisibility(View.GONE); switch (position) { case 2: mLoadingIdentifications = (ProgressBar) layout.findViewById(R.id.loading); mIdentificationsEmpty = (TextView) layout.findViewById(R.id.empty); mIdentificationsEmpty.setText(R.string.no_identifications_found); mIdentificationsEmptyIcon = (ImageView) layout.findViewById(R.id.empty_icon); mIdentificationsEmptyIcon.setImageResource(R.drawable.ic_empty_id); mIdentificationsList = (PullToRefreshListView) layout.findViewById(R.id.list); mIdentificationsList.setMode(PullToRefreshBase.Mode.DISABLED); mIdentificationsGrid = (PullToRefreshGridViewExtended) layout.findViewById(R.id.grid); mIdentificationsGrid.setMode(PullToRefreshBase.Mode.DISABLED); layout.findViewById(R.id.syncing_top_bar).setVisibility(View.GONE); layout.findViewById(R.id.add_observation).setVisibility(View.GONE); initPullToRefreshList(mIdentificationsList, layout); initPullToRefreshList(mIdentificationsGrid, layout); OnItemClickListener onIdentificationsClick = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { JSONObject item = (JSONObject) view.getTag(); Intent intent = new Intent(ObservationListActivity.this, ObservationViewerActivity.class); intent.putExtra("observation", item.optJSONObject("observation").toString()); intent.putExtra("read_only", true); intent.putExtra("reload", true); startActivity(intent); try { JSONObject eventParams = new JSONObject(); eventParams.put(AnalyticsClient.EVENT_PARAM_VIA, AnalyticsClient.EVENT_VALUE_IDENTIFICATIONS_TAB); AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_NAVIGATE_OBS_DETAILS, eventParams); } catch (JSONException e) { e.printStackTrace(); } } }; mIdentificationsList.setOnItemClickListener(onIdentificationsClick); mIdentificationsGrid.setOnItemClickListener(onIdentificationsClick); break; case 1: mLoadingSpecies = (ProgressBar) layout.findViewById(R.id.loading); mSpeciesEmpty = (TextView) layout.findViewById(R.id.empty); mSpeciesEmpty.setText(R.string.no_species_found); mSpeciesEmptyIcon = (ImageView) layout.findViewById(R.id.empty_icon); mSpeciesEmptyIcon.setImageResource(R.drawable.ic_empty_leaf); mSpeciesList = (PullToRefreshListView) layout.findViewById(R.id.list); mSpeciesList.setMode(PullToRefreshBase.Mode.DISABLED); mSpeciesGrid = (PullToRefreshGridViewExtended) layout.findViewById(R.id.grid); mSpeciesGrid.setMode(PullToRefreshBase.Mode.DISABLED); layout.findViewById(R.id.syncing_top_bar).setVisibility(View.GONE); layout.findViewById(R.id.add_observation).setVisibility(View.GONE); initPullToRefreshList(mSpeciesList, layout); initPullToRefreshList(mSpeciesGrid, layout); OnItemClickListener onSpeciesClick = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { JSONObject item = (JSONObject) view.getTag(); if (item == null) return; Intent intent = new Intent(ObservationListActivity.this, TaxonActivity.class); intent.putExtra(TaxonActivity.TAXON, new BetterJSONObject(item)); intent.putExtra(TaxonActivity.OBSERVATION, new BetterJSONObject(item)); intent.putExtra(TaxonActivity.DOWNLOAD_TAXON, true); startActivity(intent); } }; mSpeciesList.setOnItemClickListener(onSpeciesClick); mSpeciesGrid.setOnItemClickListener(onSpeciesClick); break; case 0: mLoadingObservations = (ProgressBar) layout.findViewById(R.id.loading); mObservationsEmpty = (TextView) layout.findViewById(R.id.empty); mObservationsEmpty.setText(R.string.no_observations_found_new); mObservationsEmptyIcon = (ImageView) layout.findViewById(R.id.empty_icon); mObservationsEmptyIcon.setImageResource(R.drawable.ic_empty_binoculars); mObservationsList = (PullToRefreshListView) layout.findViewById(R.id.list); mObservationsGrid = (PullToRefreshGridViewExtended) layout.findViewById(R.id.grid); mLoadingMoreResults = (ViewGroup) layout.findViewById(R.id.loading_more_results); mOnboardingSyncing = (ViewGroup) layout.findViewById(R.id.onboarding_syncing); mOnboardingSyncingClose = layout.findViewById(R.id.onboarding_syncing_close); mOnboardingSyncingClose.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mOnboardingSyncing.setVisibility(View.GONE); SharedPreferences prefs = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); prefs.edit().putBoolean("onboarded_syncing", true).commit(); } }); initPullToRefreshList(mObservationsList, layout); initPullToRefreshList(mObservationsGrid, layout); OnItemClickListener onClick = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { Uri uri = ContentUris.withAppendedId(getIntent().getData(), id); String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) { // The caller is waiting for us to return a note selected by // the user. The have clicked on one, so return it now. setResult(RESULT_OK, new Intent().setData(uri)); } else { if ((!mObservationListAdapter.isLocked(uri)) || (mObservationListAdapter.isLocked(uri) && !mApp.getIsSyncing())) { // Launch activity to view/edit the currently selected item startActivity(new Intent(Intent.ACTION_VIEW, uri, ObservationListActivity.this, ObservationViewerActivity.class)); try { JSONObject eventParams = new JSONObject(); eventParams.put(AnalyticsClient.EVENT_PARAM_VIA, AnalyticsClient.EVENT_VALUE_ME_TAB); AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_NAVIGATE_OBS_DETAILS, eventParams); } catch (JSONException e) { e.printStackTrace(); } } } } }; mObservationsList.setOnItemClickListener(onClick); mObservationsGrid.setOnItemClickListener(onClick); mSyncingTopBar = (ViewGroup) layout.findViewById(R.id.syncing_top_bar); mSyncingTopBar.setVisibility(View.GONE); mSyncingStatus = (TextView) layout.findViewById(R.id.syncing_status); mCancelSync = (TextView) layout.findViewById(R.id.cancel_sync); if (mApp.getAutoSync()) { // Auto sync mCancelSync.setText(R.string.stop); } else { // Manual mCancelSync.setText(R.string.upload); } mCancelSync.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (!mUserCanceledSync) { // User chose to cancel sync mUserCanceledSync = true; mApp.setCancelSync(true); mCancelSync.setText(R.string.resume); mSyncingStatus.setText(R.string.syncing_paused); try { JSONObject eventParams = new JSONObject(); eventParams.put(AnalyticsClient.EVENT_PARAM_VIA, AnalyticsClient.EVENT_VALUE_STOP_UPLOAD_BUTTON); AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_SYNC_STOPPED, eventParams); } catch (JSONException e) { e.printStackTrace(); } } else { // User chose to resume sync if (!isNetworkAvailable()) { try { JSONObject eventParams = new JSONObject(); eventParams.put(AnalyticsClient.EVENT_PARAM_ALERT, getString(R.string.not_connected)); AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_SYNC_FAILED, eventParams); } catch (JSONException e) { e.printStackTrace(); } Toast.makeText(getApplicationContext(), R.string.not_connected, Toast.LENGTH_LONG).show(); return; } else if (!isLoggedIn()) { // User not logged-in - redirect to onboarding screen startActivity(new Intent(ObservationListActivity.this, OnboardingActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP)); try { JSONObject eventParams = new JSONObject(); eventParams.put(AnalyticsClient.EVENT_PARAM_VIA, AnalyticsClient.EVENT_VALUE_AUTH_REQUIRED); AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_SYNC_STOPPED, eventParams); } catch (JSONException e) { e.printStackTrace(); } return; } mUserCanceledSync = false; mApp.setCancelSync(false); mCancelSync.setText(R.string.stop); mSyncingStatus.setText(R.string.syncing); // Re-sync Intent serviceIntent = new Intent(INaturalistService.ACTION_SYNC, null, ObservationListActivity.this, INaturalistService.class); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); startService(serviceIntent); Log.d(TAG, "Start sync by button"); } } }); String login = mApp.currentUserLogin(); // Perform a managed query. The Activity will handle closing and requerying the cursor // when needed. String conditions = "(_synced_at IS NULL"; if (login != null) { conditions += " OR user_login = '" + login + "'"; } conditions += ") AND (is_deleted = 0 OR is_deleted is NULL) "; // Don't show deleted observations conditions += " AND ((id > " + mApp.getPrefs().getInt("last_downloaded_id", 0) + ")"; // Don't show obs that was downloaded through activity screen, etc. (not "naturally" by user) conditions += " OR (_synced_at IS NULL))"; final Cursor cursor = getContentResolver().query(getIntent().getData(), Observation.PROJECTION, conditions, null, Observation.DEFAULT_SORT_ORDER); mObservationListAdapter = new ObservationCursorAdapter(ObservationListActivity.this, cursor); mObservationGridAdapter = new ObservationCursorAdapter(ObservationListActivity.this, cursor, true, mObservationsGrid); mObservationsGrid.setAdapter(mObservationGridAdapter); mObservationsList.setAdapter(mObservationListAdapter); mObservationGridAdapter.setOnLoadingMoreResultsListener(ObservationListActivity.this); mObservationListAdapter.setOnLoadingMoreResultsListener(ObservationListActivity.this); mObservationsList.setOnScrollListener(mObservationListAdapter); mObservationsGrid.setOnScrollListener(mObservationGridAdapter); // Set a listener to be invoked when the list should be refreshed. mObservationsList.setOnRefreshListener(new OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { onRefreshView(mObservationsList); } }); mObservationsGrid.setOnRefreshListener(new OnRefreshListener<GridView>() { @Override public void onRefresh(PullToRefreshBase<GridView> refreshView) { onRefreshView(mObservationsGrid); } }); refreshSyncBar(); View addButton = (View) layout.findViewById(R.id.add_observation); mAddButtonText = (TextView) layout.findViewById(R.id.add_observation_text); addButton.setVisibility(View.VISIBLE); mAddButtonText.setVisibility(mObservationListAdapter.getCount() > 0 ? View.GONE : View.VISIBLE); OnClickListener onAddObs = new OnClickListener() { @Override public void onClick(View v) { AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_NEW_OBS_START); showNewObsMenu(); } }; addButton.setOnClickListener(onAddObs); mAddButtonText.setOnClickListener(onAddObs); if (mApp.loggedIn() && mApp.getIsSyncing() && (mObservationListAdapter.getCount() == 0)) { // Show a "downloading ..." message instead of "no observations yet" mObservationsEmpty.setText(R.string.downloading_observations); mLoadingObservations.setVisibility(View.VISIBLE); ((TextView) mTabLayout.getTabAt(0).getCustomView().findViewById(R.id.count)).setVisibility(View.GONE); ((ProgressBar) mTabLayout.getTabAt(0).getCustomView().findViewById(R.id.loading)).setVisibility(View.VISIBLE); } break; } collection.addView(layout); refreshViewState(); return layout; } @Override public void destroyItem(ViewGroup collection, int position, Object view) { collection.removeView((View) view); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } } // Method to add a TabHost private void addTab(int position, View tabContent) { TabLayout.Tab tab = mTabLayout.getTabAt(position); tab.setCustomView(tabContent); } private View createTabContent(String tabName, int count) { ViewGroup view = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.my_observations_tab, null); TextView countText = (TextView) view.findViewById(R.id.count); TextView tabNameText = (TextView) view.findViewById(R.id.tab_name); DecimalFormat formatter = new DecimalFormat(" countText.setText(formatter.format(count)); tabNameText.setText(tabName); return view; } // Tabs Creation private void initializeTabs() { mTabLayout = (TabLayout) findViewById(R.id.tabs); mViewPager = (ViewPager) findViewById(R.id.view_pager); mViewPager.setOffscreenPageLimit(3); // So we wouldn't have to recreate the views every time ObservationsPageAdapter adapter = new ObservationsPageAdapter(this); mViewPager.setAdapter(adapter); mTabLayout.setupWithViewPager(mViewPager); addTab(0, createTabContent(getString(R.string.project_observations), 1000)); addTab(1, createTabContent(getString(R.string.project_species), 2000)); addTab(2, createTabContent(getString(R.string.identifications), 3000)); TabLayout.OnTabSelectedListener tabListener = new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { TextView tabNameText = (TextView) tab.getCustomView().findViewById(R.id.tab_name); tabNameText.setTextColor(Color.parseColor("#000000")); mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { View tabView = tab.getCustomView(); TextView tabNameText = (TextView) tabView.findViewById(R.id.tab_name); tabNameText.setTypeface(null, Typeface.NORMAL); tabNameText.setTextColor(Color.parseColor("#ACACAC")); } @Override public void onTabReselected(TabLayout.Tab tab) { } }; mTabLayout.setOnTabSelectedListener(tabListener); ViewPager.OnPageChangeListener pageListener = new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { switch (position) { case 2: mViewType = VIEW_TYPE_IDENTIFICATIONS; break; case 1: mViewType = VIEW_TYPE_SPECIES; break; case 0: default: mViewType = VIEW_TYPE_OBSERVATIONS; break; } refreshGridListMenuIcon(); } @Override public void onPageScrollStateChanged(int state) { } }; mViewPager.addOnPageChangeListener(pageListener); if (mViewType.equals(VIEW_TYPE_OBSERVATIONS)) { tabListener.onTabSelected(mTabLayout.getTabAt(0)); } else if (mViewType.equals(VIEW_TYPE_SPECIES)) { tabListener.onTabSelected(mTabLayout.getTabAt(1)); } else if (mViewType.equals(VIEW_TYPE_IDENTIFICATIONS)) { tabListener.onTabSelected(mTabLayout.getTabAt(2)); } } private class ObservationSyncProgressReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle extras = intent.getExtras(); Integer obsId = extras.getInt(INaturalistService.OBSERVATION_ID); Float progress = extras.getFloat(INaturalistService.PROGRESS); if ((obsId == null) || (progress == null) || (mObservationListAdapter == null) || (mObservationGridAdapter == null)) { return; } mObservationListAdapter.updateProgress(obsId, progress); mObservationListAdapter.notifyDataSetChanged(); mObservationGridAdapter.updateProgress(obsId, progress); mObservationGridAdapter.notifyDataSetChanged(); } } private class UserDetailsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle extras = intent.getExtras(); String username = extras.getString(INaturalistService.USERNAME); if (!username.equals(mApp.currentUserLogin())) { // Results returned for another user return; } String error = extras.getString("error"); if (error != null) { mHelper.alert(String.format(getString(R.string.couldnt_load_user_details), error)); return; } boolean isSharedOnApp = intent.getBooleanExtra(INaturalistService.IS_SHARED_ON_APP, false); Object object = null; BetterJSONObject resultsObject; JSONArray results = null; if (isSharedOnApp) { object = mApp.getServiceResult(intent.getAction()); } else { object = intent.getSerializableExtra(actionToResultsParam(intent.getAction())); } int totalResults = 0; if (object == null) { // Network error of some kind if (intent.getAction().equals(INaturalistService.IDENTIFICATIONS_RESULT)) { mTotalIdentifications = 0; mIdentifications = new ArrayList<>(); } else if (intent.getAction().equals(INaturalistService.SPECIES_COUNT_RESULT)) { mTotalSpecies = 0; mSpecies = new ArrayList<>(); } refreshViewState(); return; } if (object != null) { if (intent.getAction().equals(INaturalistService.USER_DETAILS_RESULT)) { // Extended user details mUser = (BetterJSONObject) object; if (mUser.has("observations_count") && !mUser.isNull("observation_count")) { SharedPreferences settings = mApp.getPrefs(); settings.edit().putInt("observation_count", mUser.getInt("observations_count")).commit(); } if (mUser.has("identifications_count") && !mUser.isNull("identifications_count")) { mTotalIdentifications = mUser.getInt("identifications_count"); } refreshUserDetails(); refreshViewState(); return; } else if (intent.getAction().equals(INaturalistService.SPECIES_COUNT_RESULT)) { // Species count result resultsObject = (BetterJSONObject) object; totalResults = resultsObject.getInt("total_results") == null ? 0 : resultsObject.getInt("total_results"); SerializableJSONArray resultsArray = resultsObject.getJSONArray("results"); results = resultsArray != null ? resultsArray.getJSONArray() : new JSONArray(); } else { // Identifications result results = ((SerializableJSONArray) object).getJSONArray(); totalResults = results.length(); } } ArrayList<JSONObject> resultsArray = new ArrayList<JSONObject>(); if (results == null) { refreshViewState(); return; } for (int i = 0; i < results.length(); i++) { try { JSONObject item = results.getJSONObject(i); resultsArray.add(item); } catch (JSONException e) { e.printStackTrace(); } } if (intent.getAction().equals(INaturalistService.SPECIES_COUNT_RESULT)) { mSpecies = resultsArray; mTotalSpecies = totalResults; } else if (intent.getAction().equals(INaturalistService.IDENTIFICATIONS_RESULT)) { mIdentifications = resultsArray; } refreshViewState(); } private String actionToResultsParam(String action) { if (action.equals(INaturalistService.USER_DETAILS_RESULT)) { return INaturalistService.USER; } else if (action.equals(INaturalistService.SPECIES_COUNT_RESULT)) { return INaturalistService.SPECIES_COUNT_RESULT; } else if (action.equals(INaturalistService.USER_OBSERVATIONS_RESULT)) { return INaturalistService.OBSERVATIONS; } else if (action.equals(INaturalistService.IDENTIFICATIONS_RESULT)) { return INaturalistService.IDENTIFICATIONS; } else { return null; } } } private void getUserDetails(String action) { Intent serviceIntent = new Intent(action, null, this, INaturalistService.class); serviceIntent.putExtra(INaturalistService.USERNAME, mApp.currentUserLogin()); startService(serviceIntent); } private void saveListToBundle(Bundle outState, ArrayList<JSONObject> list, String key) { if (list != null) { JSONArray arr = new JSONArray(list); outState.putString(key, arr.toString()); } } private ArrayList<JSONObject> loadListFromBundle(Bundle savedInstanceState, String key) { ArrayList<JSONObject> results = new ArrayList<JSONObject>(); String obsString = savedInstanceState.getString(key); if (obsString != null) { try { JSONArray arr = new JSONArray(obsString); for (int i = 0; i < arr.length(); i++) { results.add(arr.getJSONObject(i)); } return results; } catch (JSONException exc) { exc.printStackTrace(); return null; } } else { return null; } } private class NewsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (!intent.getAction().equals(INaturalistService.UPDATES_RESULT)) { return; } Bundle extras = intent.getExtras(); String error = extras.getString("error"); if (error != null) { return; } boolean isSharedOnApp = intent.getBooleanExtra(INaturalistService.IS_SHARED_ON_APP, false); SerializableJSONArray resultsJSON; if (isSharedOnApp) { resultsJSON = (SerializableJSONArray) mApp.getServiceResult(intent.getAction()); } else { resultsJSON = (SerializableJSONArray) intent.getSerializableExtra(INaturalistService.RESULTS); } if (resultsJSON == null) { return; } JSONArray results = resultsJSON.getJSONArray(); ArrayList<JSONObject> resultsArray = new ArrayList<JSONObject>(); if (results == null) { return; } // Count how many unread activities are there int unreadActivities = 0; for (int i = 0; i < results.length(); i++) { try { JSONObject item = results.getJSONObject(i); if (!item.getBoolean("viewed")) unreadActivities++; } catch (JSONException e) { e.printStackTrace(); } } SharedPreferences settings = mApp.getPrefs(); settings.edit().putInt("unread_activities", unreadActivities).commit(); } } }
// My Answer for CodeIQ Q431 //CodeIQ Q431 // Quiz-Title: Restricted Words // Hello World // PerlqqqwRuby%Q%q%w // AppleScript(osascript)/C/C++/C#/Clojure/D/Erlang/Fortran/Go/Groovy/Haskell/ // Hello Algorithm/HSP/Java/JavaScript(Node.js)/Kuin/Lisp/Lua/OCaml/Pascal/ // Perl/PHP/Pike/Python/R/Ruby/Scala/Scheme/Smalltalk/VB.Net // Java package codeiq; class JavaHelloWorld { public static void main(String[] args) { int one = (int)Math.signum(Math.PI); int two = one + one; int four = two + two; StringBuilder sb = new StringBuilder(new JavaHelloWorld().getClass().getName()); sb.delete(one - one, sb.length() - four - four - two); sb.insert(one + four, new java.util.Date().toString().charAt(one + two)); System.out.println(sb.toString()); } }
package com.facebook.imagepipeline.core; import javax.annotation.concurrent.ThreadSafe; import java.lang.Exception; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.atomic.AtomicLong; import android.net.Uri; import com.facebook.cache.common.CacheKey; import com.facebook.common.internal.Objects; import com.facebook.common.internal.Preconditions; import com.facebook.common.internal.Supplier; import com.facebook.common.references.CloseableReference; import com.facebook.common.util.UriUtil; import com.facebook.datasource.DataSource; import com.facebook.datasource.DataSources; import com.facebook.datasource.SettableDataSource; import com.facebook.imagepipeline.cache.BitmapMemoryCacheKey; import com.facebook.imagepipeline.cache.BufferedDiskCache; import com.facebook.imagepipeline.cache.MemoryCache; import com.facebook.imagepipeline.cache.CacheKeyFactory; import com.facebook.imagepipeline.common.Priority; import com.facebook.imagepipeline.datasource.CloseableProducerToDataSourceAdapter; import com.facebook.imagepipeline.datasource.ProducerToDataSourceAdapter; import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.imagepipeline.memory.PooledByteBuffer; import com.facebook.imagepipeline.producers.Producer; import com.facebook.imagepipeline.producers.SettableProducerContext; import com.facebook.imagepipeline.listener.ForwardingRequestListener; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.listener.RequestListener; import bolts.Continuation; import com.android.internal.util.Predicate; import com.facebook.imagepipeline.request.ImageRequestBuilder; import bolts.Task; /** * The entry point for the image pipeline. */ @ThreadSafe public class ImagePipeline { private static final CancellationException PREFETCH_EXCEPTION = new CancellationException("Prefetching is not enabled"); private final ProducerSequenceFactory mProducerSequenceFactory; private final RequestListener mRequestListener; private final Supplier<Boolean> mIsPrefetchEnabledSupplier; private final MemoryCache<CacheKey, CloseableImage> mBitmapMemoryCache; private final MemoryCache<CacheKey, PooledByteBuffer> mEncodedMemoryCache; private final BufferedDiskCache mMainBufferedDiskCache; private final BufferedDiskCache mSmallImageBufferedDiskCache; private final CacheKeyFactory mCacheKeyFactory; private AtomicLong mIdCounter; public ImagePipeline( ProducerSequenceFactory producerSequenceFactory, Set<RequestListener> requestListeners, Supplier<Boolean> isPrefetchEnabledSupplier, MemoryCache<CacheKey, CloseableImage> bitmapMemoryCache, MemoryCache<CacheKey, PooledByteBuffer> encodedMemoryCache, BufferedDiskCache mainBufferedDiskCache, BufferedDiskCache smallImageBufferedDiskCache, CacheKeyFactory cacheKeyFactory) { mIdCounter = new AtomicLong(); mProducerSequenceFactory = producerSequenceFactory; mRequestListener = new ForwardingRequestListener(requestListeners); mIsPrefetchEnabledSupplier = isPrefetchEnabledSupplier; mBitmapMemoryCache = bitmapMemoryCache; mEncodedMemoryCache = encodedMemoryCache; mMainBufferedDiskCache = mainBufferedDiskCache; mSmallImageBufferedDiskCache = smallImageBufferedDiskCache; mCacheKeyFactory = cacheKeyFactory; } /** * Generates unique id for RequestFuture. * * @return unique id */ private String generateUniqueFutureId() { return String.valueOf(mIdCounter.getAndIncrement()); } /** * Returns a DataSource supplier that will on get submit the request for execution and return a * DataSource representing the pending results of the task. * * @param imageRequest the request to submit (what to execute). * @param bitmapCacheOnly whether to only look for the image in the bitmap cache * @return a DataSource representing pending results and completion of the request */ public Supplier<DataSource<CloseableReference<CloseableImage>>> getDataSourceSupplier( final ImageRequest imageRequest, final Object callerContext, final boolean bitmapCacheOnly) { return new Supplier<DataSource<CloseableReference<CloseableImage>>>() { @Override public DataSource<CloseableReference<CloseableImage>> get() { if (bitmapCacheOnly) { return fetchImageFromBitmapCache(imageRequest, callerContext); } else { return fetchDecodedImage(imageRequest, callerContext); } } @Override public String toString() { return Objects.toStringHelper(this) .add("uri", imageRequest.getSourceUri()) .toString(); } }; } /** * Returns a DataSource supplier that will on get submit the request for execution and return a * DataSource representing the pending results of the task. * * @param imageRequest the request to submit (what to execute). * @return a DataSource representing pending results and completion of the request */ public Supplier<DataSource<CloseableReference<PooledByteBuffer>>> getEncodedImageDataSourceSupplier( final ImageRequest imageRequest, final Object callerContext) { return new Supplier<DataSource<CloseableReference<PooledByteBuffer>>>() { @Override public DataSource<CloseableReference<PooledByteBuffer>> get() { return fetchEncodedImage(imageRequest, callerContext); } @Override public String toString() { return Objects.toStringHelper(this) .add("uri", imageRequest.getSourceUri()) .toString(); } }; } /** * Submits a request for bitmap cache lookup. * * @param imageRequest the request to submit * @return a DataSource representing the image */ public DataSource<CloseableReference<CloseableImage>> fetchImageFromBitmapCache( ImageRequest imageRequest, Object callerContext) { try { Producer<CloseableReference<CloseableImage>> producerSequence = mProducerSequenceFactory.getDecodedImageProducerSequence(imageRequest); return submitFetchRequest( producerSequence, imageRequest, ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE, callerContext); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } } /** * Submits a request for execution and returns a DataSource representing the pending decoded * image(s). * <p>The returned DataSource must be closed once the client has finished with it. * @param imageRequest the request to submit * @return a DataSource representing the pending decoded image(s) */ public DataSource<CloseableReference<CloseableImage>> fetchDecodedImage( ImageRequest imageRequest, Object callerContext) { try { Producer<CloseableReference<CloseableImage>> producerSequence = mProducerSequenceFactory.getDecodedImageProducerSequence(imageRequest); return submitFetchRequest( producerSequence, imageRequest, ImageRequest.RequestLevel.FULL_FETCH, callerContext); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } } /** * Submits a request for execution and returns a DataSource representing the pending encoded * image(s). * * <p> The ResizeOptions in the imageRequest will be ignored for this fetch * * <p>The returned DataSource must be closed once the client has finished with it. * * @param imageRequest the request to submit * @return a DataSource representing the pending encoded image(s) */ public DataSource<CloseableReference<PooledByteBuffer>> fetchEncodedImage( ImageRequest imageRequest, Object callerContext) { Preconditions.checkNotNull(imageRequest.getSourceUri()); try { Producer<CloseableReference<PooledByteBuffer>> producerSequence = mProducerSequenceFactory.getEncodedImageProducerSequence(imageRequest); // The resize options are used to determine whether images are going to be downsampled during // decode or not. For the case where the image has to be downsampled and it's a local image it // will be kept as a FileInputStream until decoding instead of reading it in memory. Since // this method returns an encoded image, it should always be read into memory. Therefore, the // resize options are ignored to avoid treating the image as if it was to be downsampled // during decode. if (imageRequest.getResizeOptions() != null) { imageRequest = ImageRequestBuilder.fromRequest(imageRequest) .setResizeOptions(null) .build(); } return submitFetchRequest( producerSequence, imageRequest, ImageRequest.RequestLevel.FULL_FETCH, callerContext); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } } /** * Submits a request for prefetching to the bitmap cache. * @param imageRequest the request to submit * @return a DataSource that can safely be ignored. */ public DataSource<Void> prefetchToBitmapCache( ImageRequest imageRequest, Object callerContext) { if (!mIsPrefetchEnabledSupplier.get()) { return DataSources.immediateFailedDataSource(PREFETCH_EXCEPTION); } try { Producer<Void> producerSequence = mProducerSequenceFactory.getDecodedImagePrefetchProducerSequence(imageRequest); return submitPrefetchRequest( producerSequence, imageRequest, ImageRequest.RequestLevel.FULL_FETCH, callerContext); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } } /** * Submits a request for prefetching to the disk cache. * @param imageRequest the request to submit * @return a DataSource that can safely be ignored. */ public DataSource<Void> prefetchToDiskCache( ImageRequest imageRequest, Object callerContext) { if (!mIsPrefetchEnabledSupplier.get()) { return DataSources.immediateFailedDataSource(PREFETCH_EXCEPTION); } try { Producer<Void> producerSequence = mProducerSequenceFactory.getEncodedImagePrefetchProducerSequence(imageRequest); return submitPrefetchRequest( producerSequence, imageRequest, ImageRequest.RequestLevel.FULL_FETCH, callerContext); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } } /** * Removes all images with the specified {@link Uri} from memory cache. * @param uri The uri of the image to evict */ public void evictFromMemoryCache(final Uri uri) { Predicate<CacheKey> bitmapCachePredicate = predicateForUri(uri); mBitmapMemoryCache.removeAll(bitmapCachePredicate); final String cacheKeySourceString = mCacheKeyFactory.getCacheKeySourceUri(uri).toString(); Predicate<CacheKey> encodedCachePredicate = new Predicate<CacheKey>() { @Override public boolean apply(CacheKey key) { return key.toString().equals(cacheKeySourceString); } }; mEncodedMemoryCache.removeAll(encodedCachePredicate); } /** * <p>If you have supplied your own cache key factory when configuring the pipeline, this method * may not work correctly. It will only work if the custom factory builds the cache key entirely * from the URI. If that is not the case, use {@link #evictFromDiskCache(ImageRequest)}. * @param uri The uri of the image to evict */ public void evictFromDiskCache(final Uri uri) { evictFromDiskCache(ImageRequest.fromUri(uri)); } /** * Removes all images with the specified {@link Uri} from disk cache. * * @param imageRequest The imageRequest for the image to evict from disk cache */ public void evictFromDiskCache(final ImageRequest imageRequest) { final CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest); mMainBufferedDiskCache.remove(cacheKey); mSmallImageBufferedDiskCache.remove(cacheKey); } /** * <p>If you have supplied your own cache key factory when configuring the pipeline, this method * may not work correctly. It will only work if the custom factory builds the cache key entirely * from the URI. If that is not the case, use {@link #evictFromMemoryCache(Uri)} and * {@link #evictFromDiskCache(ImageRequest)} separately. * @param uri The uri of the image to evict */ public void evictFromCache(final Uri uri) { evictFromMemoryCache(uri); evictFromDiskCache(uri); } /** * Clear the memory caches */ public void clearMemoryCaches() { Predicate<CacheKey> allPredicate = new Predicate<CacheKey>() { @Override public boolean apply(CacheKey key) { return true; } }; mBitmapMemoryCache.removeAll(allPredicate); mEncodedMemoryCache.removeAll(allPredicate); } /** * Clear disk caches */ public void clearDiskCaches() { mMainBufferedDiskCache.clearAll(); mSmallImageBufferedDiskCache.clearAll(); } /** * Clear all the caches (memory and disk) */ public void clearCaches() { clearMemoryCaches(); clearDiskCaches(); } /** * Returns whether the image is stored in the bitmap memory cache. * * @param uri the uri for the image to be looked up. * @return true if the image was found in the bitmap memory cache, false otherwise */ public boolean isInBitmapMemoryCache(final Uri uri) { Predicate<CacheKey> bitmapCachePredicate = predicateForUri(uri); return mBitmapMemoryCache.contains(bitmapCachePredicate); } /** * Returns whether the image is stored in the bitmap memory cache. * * @param imageRequest the imageRequest for the image to be looked up. * @return true if the image was found in the bitmap memory cache, false otherwise. */ public boolean isInBitmapMemoryCache(final ImageRequest imageRequest) { final CacheKey cacheKey = mCacheKeyFactory.getBitmapCacheKey(imageRequest); CloseableReference<CloseableImage> ref = mBitmapMemoryCache.get(cacheKey); try { return CloseableReference.isValid(ref); } finally { CloseableReference.closeSafely(ref); } } /** * Returns whether the image is stored in the disk cache. * * <p>If you have supplied your own cache key factory when configuring the pipeline, this method * may not work correctly. It will only work if the custom factory builds the cache key entirely * from the URI. If that is not the case, use {@link #isInDiskCache(ImageRequest)}. * * @param uri the uri for the image to be looked up. * @return true if the image was found in the disk cache, false otherwise. */ public DataSource<Boolean> isInDiskCache(final Uri uri) { return isInDiskCache(ImageRequest.fromUri(uri)); } /** * Returns whether the image is stored in the disk cache. * * @param imageRequest the imageRequest for the image to be looked up. * @return true if the image was found in the disk cache, false otherwise. */ public DataSource<Boolean> isInDiskCache(final ImageRequest imageRequest) { final CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest); final SettableDataSource<Boolean> dataSource = SettableDataSource.create(); mMainBufferedDiskCache.contains(cacheKey) .continueWithTask( new Continuation<Boolean, Task<Boolean>>() { @Override public Task<Boolean> then(Task<Boolean> task) throws Exception { if (!task.isCancelled() && !task.isFaulted() && task.getResult()) { return Task.forResult(true); } return mSmallImageBufferedDiskCache.contains(cacheKey); } }) .continueWith( new Continuation<Boolean, Void>() { @Override public Void then(Task<Boolean> task) throws Exception { dataSource.setResult(!task.isCancelled() && !task.isFaulted() && task.getResult()); return null; } }); return dataSource; } private <T> DataSource<CloseableReference<T>> submitFetchRequest( Producer<CloseableReference<T>> producerSequence, ImageRequest imageRequest, ImageRequest.RequestLevel lowestPermittedRequestLevelOnSubmit, Object callerContext) { try { ImageRequest.RequestLevel lowestPermittedRequestLevel = ImageRequest.RequestLevel.getMax( imageRequest.getLowestPermittedRequestLevel(), lowestPermittedRequestLevelOnSubmit); SettableProducerContext settableProducerContext = new SettableProducerContext( imageRequest, generateUniqueFutureId(), mRequestListener, callerContext, lowestPermittedRequestLevel, /* isPrefetch */ false, imageRequest.getProgressiveRenderingEnabled() || !UriUtil.isNetworkUri(imageRequest.getSourceUri()), imageRequest.getPriority()); return CloseableProducerToDataSourceAdapter.create( producerSequence, settableProducerContext, mRequestListener); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } } private DataSource<Void> submitPrefetchRequest( Producer<Void> producerSequence, ImageRequest imageRequest, ImageRequest.RequestLevel lowestPermittedRequestLevelOnSubmit, Object callerContext) { try { ImageRequest.RequestLevel lowestPermittedRequestLevel = ImageRequest.RequestLevel.getMax( imageRequest.getLowestPermittedRequestLevel(), lowestPermittedRequestLevelOnSubmit); SettableProducerContext settableProducerContext = new SettableProducerContext( imageRequest, generateUniqueFutureId(), mRequestListener, callerContext, lowestPermittedRequestLevel, /* isPrefetch */ true, /* isIntermediateResultExpected */ false, Priority.LOW); return ProducerToDataSourceAdapter.create( producerSequence, settableProducerContext, mRequestListener); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } } private Predicate<CacheKey> predicateForUri(Uri uri) { final String cacheKeySourceString = mCacheKeyFactory.getCacheKeySourceUri(uri).toString(); return new Predicate<CacheKey>() { @Override public boolean apply(CacheKey key) { if (key instanceof BitmapMemoryCacheKey) { return ((BitmapMemoryCacheKey) key).getSourceUriString().equals(cacheKeySourceString); } return false; } }; } }
package com.facebook.imagepipeline.core; import android.net.Uri; import bolts.Continuation; import bolts.Task; import com.facebook.cache.common.CacheKey; import com.facebook.callercontext.CallerContextVerifier; import com.facebook.common.internal.Objects; import com.facebook.common.internal.Preconditions; import com.facebook.common.internal.Predicate; import com.facebook.common.internal.Supplier; import com.facebook.common.memory.PooledByteBuffer; import com.facebook.common.references.CloseableReference; import com.facebook.common.util.UriUtil; import com.facebook.datasource.DataSource; import com.facebook.datasource.DataSources; import com.facebook.datasource.SimpleDataSource; import com.facebook.imagepipeline.cache.BufferedDiskCache; import com.facebook.imagepipeline.cache.CacheKeyFactory; import com.facebook.imagepipeline.cache.MemoryCache; import com.facebook.imagepipeline.common.Priority; import com.facebook.imagepipeline.datasource.CloseableProducerToDataSourceAdapter; import com.facebook.imagepipeline.datasource.ProducerToDataSourceAdapter; import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.imagepipeline.listener.ForwardingRequestListener; import com.facebook.imagepipeline.listener.ForwardingRequestListener2; import com.facebook.imagepipeline.listener.RequestListener; import com.facebook.imagepipeline.listener.RequestListener2; import com.facebook.imagepipeline.producers.InternalRequestListener; import com.facebook.imagepipeline.producers.Producer; import com.facebook.imagepipeline.producers.SettableProducerContext; import com.facebook.imagepipeline.producers.ThreadHandoffProducerQueue; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; import com.facebook.imagepipeline.systrace.FrescoSystrace; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; /** The entry point for the image pipeline. */ @ThreadSafe public class ImagePipeline { private static final CancellationException PREFETCH_EXCEPTION = new CancellationException("Prefetching is not enabled"); private final ProducerSequenceFactory mProducerSequenceFactory; private final RequestListener mRequestListener; private final RequestListener2 mRequestListener2; private final Supplier<Boolean> mIsPrefetchEnabledSupplier; private final MemoryCache<CacheKey, CloseableImage> mBitmapMemoryCache; private final MemoryCache<CacheKey, PooledByteBuffer> mEncodedMemoryCache; private final BufferedDiskCache mMainBufferedDiskCache; private final BufferedDiskCache mSmallImageBufferedDiskCache; private final CacheKeyFactory mCacheKeyFactory; private final ThreadHandoffProducerQueue mThreadHandoffProducerQueue; private final Supplier<Boolean> mSuppressBitmapPrefetchingSupplier; private AtomicLong mIdCounter; private final Supplier<Boolean> mLazyDataSource; private final @Nullable CallerContextVerifier mCallerContextVerifier; private final ImagePipelineConfig mConfig; public ImagePipeline( ProducerSequenceFactory producerSequenceFactory, Set<RequestListener> requestListeners, Set<RequestListener2> requestListener2s, Supplier<Boolean> isPrefetchEnabledSupplier, MemoryCache<CacheKey, CloseableImage> bitmapMemoryCache, MemoryCache<CacheKey, PooledByteBuffer> encodedMemoryCache, BufferedDiskCache mainBufferedDiskCache, BufferedDiskCache smallImageBufferedDiskCache, CacheKeyFactory cacheKeyFactory, ThreadHandoffProducerQueue threadHandoffProducerQueue, Supplier<Boolean> suppressBitmapPrefetchingSupplier, Supplier<Boolean> lazyDataSource, @Nullable CallerContextVerifier callerContextVerifier, ImagePipelineConfig config) { mIdCounter = new AtomicLong(); mProducerSequenceFactory = producerSequenceFactory; mRequestListener = new ForwardingRequestListener(requestListeners); mRequestListener2 = new ForwardingRequestListener2(requestListener2s); mIsPrefetchEnabledSupplier = isPrefetchEnabledSupplier; mBitmapMemoryCache = bitmapMemoryCache; mEncodedMemoryCache = encodedMemoryCache; mMainBufferedDiskCache = mainBufferedDiskCache; mSmallImageBufferedDiskCache = smallImageBufferedDiskCache; mCacheKeyFactory = cacheKeyFactory; mThreadHandoffProducerQueue = threadHandoffProducerQueue; mSuppressBitmapPrefetchingSupplier = suppressBitmapPrefetchingSupplier; mLazyDataSource = lazyDataSource; mCallerContextVerifier = callerContextVerifier; mConfig = config; } /** * Generates unique id for RequestFuture. * * @return unique id */ public String generateUniqueFutureId() { return String.valueOf(mIdCounter.getAndIncrement()); } /** * Returns a DataSource supplier that will on get submit the request for execution and return a * DataSource representing the pending results of the task. * * @param imageRequest the request to submit (what to execute). * @param callerContext the caller context of the caller of data source supplier * @param requestLevel which level to look down until for the image * @return a DataSource representing pending results and completion of the request */ public Supplier<DataSource<CloseableReference<CloseableImage>>> getDataSourceSupplier( final ImageRequest imageRequest, final Object callerContext, final ImageRequest.RequestLevel requestLevel) { return new Supplier<DataSource<CloseableReference<CloseableImage>>>() { @Override public DataSource<CloseableReference<CloseableImage>> get() { return fetchDecodedImage(imageRequest, callerContext, requestLevel); } @Override public String toString() { return Objects.toStringHelper(this).add("uri", imageRequest.getSourceUri()).toString(); } }; } /** * Returns a DataSource supplier that will on get submit the request for execution and return a * DataSource representing the pending results of the task. * * @param imageRequest the request to submit (what to execute). * @param callerContext the caller context of the caller of data source supplier * @param requestLevel which level to look down until for the image * @param requestListener additional image request listener independent of ImageRequest listeners * @return a DataSource representing pending results and completion of the request */ public Supplier<DataSource<CloseableReference<CloseableImage>>> getDataSourceSupplier( final ImageRequest imageRequest, final Object callerContext, final ImageRequest.RequestLevel requestLevel, final @Nullable RequestListener requestListener) { return new Supplier<DataSource<CloseableReference<CloseableImage>>>() { @Override public DataSource<CloseableReference<CloseableImage>> get() { return fetchDecodedImage(imageRequest, callerContext, requestLevel, requestListener); } @Override public String toString() { return Objects.toStringHelper(this).add("uri", imageRequest.getSourceUri()).toString(); } }; } /** * Returns a DataSource supplier that will on get submit the request for execution and return a * DataSource representing the pending results of the task. * * @param imageRequest the request to submit (what to execute). * @param callerContext the caller context of the caller of data source supplier * @param requestLevel which level to look down until for the image * @param requestListener additional image request listener independent of ImageRequest listeners * @param uiComponentId optional UI component ID requesting the image * @return a DataSource representing pending results and completion of the request */ public Supplier<DataSource<CloseableReference<CloseableImage>>> getDataSourceSupplier( final ImageRequest imageRequest, final Object callerContext, final ImageRequest.RequestLevel requestLevel, final @Nullable RequestListener requestListener, final @Nullable String uiComponentId) { return new Supplier<DataSource<CloseableReference<CloseableImage>>>() { @Override public DataSource<CloseableReference<CloseableImage>> get() { return fetchDecodedImage( imageRequest, callerContext, requestLevel, requestListener, uiComponentId); } @Override public String toString() { return Objects.toStringHelper(this).add("uri", imageRequest.getSourceUri()).toString(); } }; } /** * Returns a DataSource supplier that will on get submit the request for execution and return a * DataSource representing the pending results of the task. * * @param imageRequest the request to submit (what to execute). * @return a DataSource representing pending results and completion of the request */ public Supplier<DataSource<CloseableReference<PooledByteBuffer>>> getEncodedImageDataSourceSupplier( final ImageRequest imageRequest, final Object callerContext) { return new Supplier<DataSource<CloseableReference<PooledByteBuffer>>>() { @Override public DataSource<CloseableReference<PooledByteBuffer>> get() { return fetchEncodedImage(imageRequest, callerContext); } @Override public String toString() { return Objects.toStringHelper(this).add("uri", imageRequest.getSourceUri()).toString(); } }; } /** * Submits a request for bitmap cache lookup. * * @param imageRequest the request to submit * @param callerContext the caller context for image request * @return a DataSource representing the image */ public DataSource<CloseableReference<CloseableImage>> fetchImageFromBitmapCache( ImageRequest imageRequest, Object callerContext) { return fetchDecodedImage( imageRequest, callerContext, ImageRequest.RequestLevel.BITMAP_MEMORY_CACHE); } /** * Submits a request for execution and returns a DataSource representing the pending decoded * image(s). * * <p>The returned DataSource must be closed once the client has finished with it. * * @param imageRequest the request to submit * @param callerContext the caller context for image request * @return a DataSource representing the pending decoded image(s) */ public DataSource<CloseableReference<CloseableImage>> fetchDecodedImage( ImageRequest imageRequest, Object callerContext) { return fetchDecodedImage(imageRequest, callerContext, ImageRequest.RequestLevel.FULL_FETCH); } /** * Submits a request for execution and returns a DataSource representing the pending decoded * image(s). * * <p>The returned DataSource must be closed once the client has finished with it. * * @param imageRequest the request to submit * @param callerContext the caller context for image request * @param requestListener additional image request listener independent of ImageRequest listeners * @return a DataSource representing the pending decoded image(s) */ public DataSource<CloseableReference<CloseableImage>> fetchDecodedImage( ImageRequest imageRequest, Object callerContext, @Nullable RequestListener requestListener) { return fetchDecodedImage( imageRequest, callerContext, ImageRequest.RequestLevel.FULL_FETCH, requestListener); } /** * Submits a request for execution and returns a DataSource representing the pending decoded * image(s). * * <p>The returned DataSource must be closed once the client has finished with it. * * @param imageRequest the request to submit * @param callerContext the caller context for image request * @param lowestPermittedRequestLevelOnSubmit the lowest request level permitted for image request * @return a DataSource representing the pending decoded image(s) */ public DataSource<CloseableReference<CloseableImage>> fetchDecodedImage( ImageRequest imageRequest, Object callerContext, ImageRequest.RequestLevel lowestPermittedRequestLevelOnSubmit) { return fetchDecodedImage( imageRequest, callerContext, lowestPermittedRequestLevelOnSubmit, null); } /** * Submits a request for execution and returns a DataSource representing the pending decoded * image(s). * * <p>The returned DataSource must be closed once the client has finished with it. * * @param imageRequest the request to submit * @param callerContext the caller context for image request * @param lowestPermittedRequestLevelOnSubmit the lowest request level permitted for image reques * @param requestListener additional image request listener independent of ImageRequest listeners * @return a DataSource representing the pending decoded image(s) */ public DataSource<CloseableReference<CloseableImage>> fetchDecodedImage( ImageRequest imageRequest, Object callerContext, ImageRequest.RequestLevel lowestPermittedRequestLevelOnSubmit, @Nullable RequestListener requestListener) { return fetchDecodedImage( imageRequest, callerContext, lowestPermittedRequestLevelOnSubmit, requestListener, null); } /** * Submits a request for execution and returns a DataSource representing the pending decoded * image(s). * * <p>The returned DataSource must be closed once the client has finished with it. * * @param imageRequest the request to submit * @param callerContext the caller context for image request * @param lowestPermittedRequestLevelOnSubmit the lowest request level permitted for image reques * @param requestListener additional image request listener independent of ImageRequest listeners * @param uiComponentId optional UI component ID that is requesting the image * @return a DataSource representing the pending decoded image(s) */ public DataSource<CloseableReference<CloseableImage>> fetchDecodedImage( ImageRequest imageRequest, Object callerContext, ImageRequest.RequestLevel lowestPermittedRequestLevelOnSubmit, @Nullable RequestListener requestListener, @Nullable String uiComponentId) { try { Producer<CloseableReference<CloseableImage>> producerSequence = mProducerSequenceFactory.getDecodedImageProducerSequence(imageRequest); return submitFetchRequest( producerSequence, imageRequest, lowestPermittedRequestLevelOnSubmit, callerContext, requestListener, uiComponentId); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } } /** * Submits a request for execution and returns a DataSource representing the pending encoded * image(s). * * <p>The ResizeOptions in the imageRequest will be ignored for this fetch * * <p>The returned DataSource must be closed once the client has finished with it. * * @param imageRequest the request to submit * @return a DataSource representing the pending encoded image(s) */ public DataSource<CloseableReference<PooledByteBuffer>> fetchEncodedImage( ImageRequest imageRequest, Object callerContext) { return fetchEncodedImage(imageRequest, callerContext, null); } /** * Submits a request for execution and returns a DataSource representing the pending encoded * image(s). * * <p>The ResizeOptions in the imageRequest will be ignored for this fetch * * <p>The returned DataSource must be closed once the client has finished with it. * * @param imageRequest the request to submit * @return a DataSource representing the pending encoded image(s) */ public DataSource<CloseableReference<PooledByteBuffer>> fetchEncodedImage( ImageRequest imageRequest, Object callerContext, @Nullable RequestListener requestListener) { Preconditions.checkNotNull(imageRequest.getSourceUri()); try { Producer<CloseableReference<PooledByteBuffer>> producerSequence = mProducerSequenceFactory.getEncodedImageProducerSequence(imageRequest); // The resize options are used to determine whether images are going to be downsampled during // decode or not. For the case where the image has to be downsampled and it's a local image it // will be kept as a FileInputStream until decoding instead of reading it in memory. Since // this method returns an encoded image, it should always be read into memory. Therefore, the // resize options are ignored to avoid treating the image as if it was to be downsampled // during decode. if (imageRequest.getResizeOptions() != null) { imageRequest = ImageRequestBuilder.fromRequest(imageRequest).setResizeOptions(null).build(); } return submitFetchRequest( producerSequence, imageRequest, ImageRequest.RequestLevel.FULL_FETCH, callerContext, requestListener, null); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } } /** * Submits a request for prefetching to the bitmap cache. * * <p>Beware that if your network fetcher doesn't support priorities prefetch requests may slow * down images which are immediately required on screen. * * @param imageRequest the request to submit * @return a DataSource that can safely be ignored. */ public DataSource<Void> prefetchToBitmapCache(ImageRequest imageRequest, Object callerContext) { return prefetchToBitmapCache(imageRequest, callerContext, Priority.MEDIUM); } private DataSource<Void> prefetchToBitmapCache( ImageRequest imageRequest, Object callerContext, Priority priority) { if (!mIsPrefetchEnabledSupplier.get()) { return DataSources.immediateFailedDataSource(PREFETCH_EXCEPTION); } try { final Boolean shouldDecodePrefetches = imageRequest.shouldDecodePrefetches(); final boolean skipBitmapCache = shouldDecodePrefetches != null ? !shouldDecodePrefetches // use imagerequest param if specified : mSuppressBitmapPrefetchingSupplier .get(); // otherwise fall back to pipeline's default Producer<Void> producerSequence = skipBitmapCache ? mProducerSequenceFactory.getEncodedImagePrefetchProducerSequence(imageRequest) : mProducerSequenceFactory.getDecodedImagePrefetchProducerSequence(imageRequest); return submitPrefetchRequest( producerSequence, imageRequest, ImageRequest.RequestLevel.FULL_FETCH, callerContext, priority); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } } /** * Submits a request for prefetching to the disk cache with a default priority. * * <p>Beware that if your network fetcher doesn't support priorities prefetch requests may slow * down images which are immediately required on screen. * * @param imageRequest the request to submit * @return a DataSource that can safely be ignored. */ public DataSource<Void> prefetchToDiskCache(ImageRequest imageRequest, Object callerContext) { return prefetchToDiskCache(imageRequest, callerContext, Priority.MEDIUM); } /** * Submits a request for prefetching to the disk cache. * * <p>Beware that if your network fetcher doesn't support priorities prefetch requests may slow * down images which are immediately required on screen. * * @param imageRequest the request to submit * @param priority custom priority for the fetch * @return a DataSource that can safely be ignored. */ public DataSource<Void> prefetchToDiskCache( ImageRequest imageRequest, Object callerContext, Priority priority) { if (!mIsPrefetchEnabledSupplier.get()) { return DataSources.immediateFailedDataSource(PREFETCH_EXCEPTION); } try { Producer<Void> producerSequence = mProducerSequenceFactory.getEncodedImagePrefetchProducerSequence(imageRequest); return submitPrefetchRequest( producerSequence, imageRequest, ImageRequest.RequestLevel.FULL_FETCH, callerContext, priority); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } } /** * Submits a request for prefetching to the encoded cache with a default priority. * * <p>Beware that if your network fetcher doesn't support priorities prefetch requests may slow * down images which are immediately required on screen. * * @param imageRequest the request to submit * @return a DataSource that can safely be ignored. */ public DataSource<Void> prefetchToEncodedCache(ImageRequest imageRequest, Object callerContext) { return prefetchToEncodedCache(imageRequest, callerContext, Priority.MEDIUM); } /** * Submits a request for prefetching to the encoded cache. * * <p>Beware that if your network fetcher doesn't support priorities prefetch requests may slow * down images which are immediately required on screen. * * @param imageRequest the request to submit * @param priority custom priority for the fetch * @return a DataSource that can safely be ignored. */ public DataSource<Void> prefetchToEncodedCache( ImageRequest imageRequest, Object callerContext, Priority priority) { if (!mIsPrefetchEnabledSupplier.get()) { return DataSources.immediateFailedDataSource(PREFETCH_EXCEPTION); } try { Producer<Void> producerSequence = mProducerSequenceFactory.getEncodedImagePrefetchProducerSequence(imageRequest); return submitPrefetchRequest( producerSequence, imageRequest, ImageRequest.RequestLevel.FULL_FETCH, callerContext, priority); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } } /** * Removes all images with the specified {@link Uri} from memory cache. * * @param uri The uri of the image to evict */ public void evictFromMemoryCache(final Uri uri) { Predicate<CacheKey> predicate = predicateForUri(uri); mBitmapMemoryCache.removeAll(predicate); mEncodedMemoryCache.removeAll(predicate); } /** * If you have supplied your own cache key factory when configuring the pipeline, this method may * not work correctly. It will only work if the custom factory builds the cache key entirely from * the URI. If that is not the case, use {@link #evictFromDiskCache(ImageRequest)}. * * @param uri The uri of the image to evict */ public void evictFromDiskCache(final Uri uri) { evictFromDiskCache(ImageRequest.fromUri(uri)); } /** * Removes all images with the specified {@link Uri} from disk cache. * * @param imageRequest The imageRequest for the image to evict from disk cache */ public void evictFromDiskCache(final ImageRequest imageRequest) { CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest, null); mMainBufferedDiskCache.remove(cacheKey); mSmallImageBufferedDiskCache.remove(cacheKey); } /** * If you have supplied your own cache key factory when configuring the pipeline, this method may * not work correctly. It will only work if the custom factory builds the cache key entirely from * the URI. If that is not the case, use {@link #evictFromMemoryCache(Uri)} and {@link * #evictFromDiskCache(ImageRequest)} separately. * * @param uri The uri of the image to evict */ public void evictFromCache(final Uri uri) { evictFromMemoryCache(uri); evictFromDiskCache(uri); } /** Clear the memory caches */ public void clearMemoryCaches() { Predicate<CacheKey> allPredicate = new Predicate<CacheKey>() { @Override public boolean apply(CacheKey key) { return true; } }; mBitmapMemoryCache.removeAll(allPredicate); mEncodedMemoryCache.removeAll(allPredicate); } /** Clear disk caches */ public void clearDiskCaches() { mMainBufferedDiskCache.clearAll(); mSmallImageBufferedDiskCache.clearAll(); } /** * Current disk caches size * * @return size in Bytes */ public long getUsedDiskCacheSize() { return mMainBufferedDiskCache.getSize() + mSmallImageBufferedDiskCache.getSize(); } /** Clear all the caches (memory and disk) */ public void clearCaches() { clearMemoryCaches(); clearDiskCaches(); } /** * Returns whether the image is stored in the bitmap memory cache. * * @param uri the uri for the image to be looked up. * @return true if the image was found in the bitmap memory cache, false otherwise */ public boolean isInBitmapMemoryCache(final Uri uri) { if (uri == null) { return false; } Predicate<CacheKey> bitmapCachePredicate = predicateForUri(uri); return mBitmapMemoryCache.contains(bitmapCachePredicate); } /** @return The Bitmap MemoryCache */ public MemoryCache<CacheKey, CloseableImage> getBitmapMemoryCache() { return mBitmapMemoryCache; } /** * Returns whether the image is stored in the bitmap memory cache. * * @param imageRequest the imageRequest for the image to be looked up. * @return true if the image was found in the bitmap memory cache, false otherwise. */ public boolean isInBitmapMemoryCache(final ImageRequest imageRequest) { if (imageRequest == null) { return false; } final CacheKey cacheKey = mCacheKeyFactory.getBitmapCacheKey(imageRequest, null); CloseableReference<CloseableImage> ref = mBitmapMemoryCache.get(cacheKey); try { return CloseableReference.isValid(ref); } finally { CloseableReference.closeSafely(ref); } } /** * Returns whether the image is stored in the encoded memory cache. * * @param uri the uri for the image to be looked up. * @return true if the image was found in the encoded memory cache, false otherwise */ public boolean isInEncodedMemoryCache(final Uri uri) { if (uri == null) { return false; } Predicate<CacheKey> encodedCachePredicate = predicateForUri(uri); return mEncodedMemoryCache.contains(encodedCachePredicate); } /** * Returns whether the image is stored in the encoded memory cache. * * @param imageRequest the imageRequest for the image to be looked up. * @return true if the image was found in the encoded memory cache, false otherwise. */ public boolean isInEncodedMemoryCache(final ImageRequest imageRequest) { if (imageRequest == null) { return false; } final CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest, null); CloseableReference<PooledByteBuffer> ref = mEncodedMemoryCache.get(cacheKey); try { return CloseableReference.isValid(ref); } finally { CloseableReference.closeSafely(ref); } } /** * Returns whether the image is stored in the disk cache. Performs disk cache check synchronously. * It is not recommended to use this unless you know what exactly you are doing. Disk cache check * is a costly operation, the call will block the caller thread until the cache check is * completed. * * @param uri the uri for the image to be looked up. * @return true if the image was found in the disk cache, false otherwise. */ public boolean isInDiskCacheSync(final Uri uri) { return isInDiskCacheSync(uri, ImageRequest.CacheChoice.SMALL) || isInDiskCacheSync(uri, ImageRequest.CacheChoice.DEFAULT); } /** * Returns whether the image is stored in the disk cache. Performs disk cache check synchronously. * It is not recommended to use this unless you know what exactly you are doing. Disk cache check * is a costly operation, the call will block the caller thread until the cache check is * completed. * * @param uri the uri for the image to be looked up. * @param cacheChoice the cacheChoice for the cache to be looked up. * @return true if the image was found in the disk cache, false otherwise. */ public boolean isInDiskCacheSync(final Uri uri, final ImageRequest.CacheChoice cacheChoice) { ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(uri).setCacheChoice(cacheChoice).build(); return isInDiskCacheSync(imageRequest); } /** * Performs disk cache check synchronously. It is not recommended to use this unless you know what * exactly you are doing. Disk cache check is a costly operation, the call will block the caller * thread until the cache check is completed. * * @param imageRequest the imageRequest for the image to be looked up. * @return true if the image was found in the disk cache, false otherwise. */ public boolean isInDiskCacheSync(final ImageRequest imageRequest) { final CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest, null); final ImageRequest.CacheChoice cacheChoice = imageRequest.getCacheChoice(); switch (cacheChoice) { case DEFAULT: return mMainBufferedDiskCache.diskCheckSync(cacheKey); case SMALL: return mSmallImageBufferedDiskCache.diskCheckSync(cacheKey); default: return false; } } /** * Returns whether the image is stored in the disk cache. * * <p>If you have supplied your own cache key factory when configuring the pipeline, this method * may not work correctly. It will only work if the custom factory builds the cache key entirely * from the URI. If that is not the case, use {@link #isInDiskCache(ImageRequest)}. * * @param uri the uri for the image to be looked up. * @return true if the image was found in the disk cache, false otherwise. */ public DataSource<Boolean> isInDiskCache(final Uri uri) { return isInDiskCache(ImageRequest.fromUri(uri)); } /** * Returns whether the image is stored in the disk cache. * * @param imageRequest the imageRequest for the image to be looked up. * @return true if the image was found in the disk cache, false otherwise. */ public DataSource<Boolean> isInDiskCache(final ImageRequest imageRequest) { final CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest, null); final SimpleDataSource<Boolean> dataSource = SimpleDataSource.create(); mMainBufferedDiskCache .contains(cacheKey) .continueWithTask( new Continuation<Boolean, Task<Boolean>>() { @Override public Task<Boolean> then(Task<Boolean> task) throws Exception { if (!task.isCancelled() && !task.isFaulted() && task.getResult()) { return Task.forResult(true); } return mSmallImageBufferedDiskCache.contains(cacheKey); } }) .continueWith( new Continuation<Boolean, Void>() { @Override public Void then(Task<Boolean> task) throws Exception { dataSource.setResult(!task.isCancelled() && !task.isFaulted() && task.getResult()); return null; } }); return dataSource; } /** @return {@link CacheKey} for doing bitmap cache lookups in the pipeline. */ @Nullable public CacheKey getCacheKey(@Nullable ImageRequest imageRequest, @Nullable Object callerContext) { if (FrescoSystrace.isTracing()) { FrescoSystrace.beginSection("ImagePipeline#getCacheKey"); } final CacheKeyFactory cacheKeyFactory = mCacheKeyFactory; CacheKey cacheKey = null; if (cacheKeyFactory != null && imageRequest != null) { if (imageRequest.getPostprocessor() != null) { cacheKey = cacheKeyFactory.getPostprocessedBitmapCacheKey(imageRequest, callerContext); } else { cacheKey = cacheKeyFactory.getBitmapCacheKey(imageRequest, callerContext); } } if (FrescoSystrace.isTracing()) { FrescoSystrace.endSection(); } return cacheKey; } /** * Returns a reference to the cached image * * @param cacheKey * @return a closeable reference or null if image was not present in cache */ @Nullable public CloseableReference<CloseableImage> getCachedImage(@Nullable CacheKey cacheKey) { MemoryCache<CacheKey, CloseableImage> memoryCache = mBitmapMemoryCache; if (memoryCache == null || cacheKey == null) { return null; } CloseableReference<CloseableImage> closeableImage = memoryCache.get(cacheKey); if (closeableImage != null && !closeableImage.get().getQualityInfo().isOfFullQuality()) { closeableImage.close(); return null; } return closeableImage; } public boolean hasCachedImage(@Nullable CacheKey cacheKey) { MemoryCache<CacheKey, CloseableImage> memoryCache = mBitmapMemoryCache; if (memoryCache == null || cacheKey == null) { return false; } return memoryCache.contains(cacheKey); } private <T> DataSource<CloseableReference<T>> submitFetchRequest( Producer<CloseableReference<T>> producerSequence, ImageRequest imageRequest, ImageRequest.RequestLevel lowestPermittedRequestLevelOnSubmit, Object callerContext, @Nullable RequestListener requestListener, @Nullable String uiComponentId) { if (FrescoSystrace.isTracing()) { FrescoSystrace.beginSection("ImagePipeline#submitFetchRequest"); } final RequestListener2 requestListener2 = new InternalRequestListener( getRequestListenerForRequest(imageRequest, requestListener), mRequestListener2); if (mCallerContextVerifier != null) { mCallerContextVerifier.verifyCallerContext(callerContext, false); } try { ImageRequest.RequestLevel lowestPermittedRequestLevel = ImageRequest.RequestLevel.getMax( imageRequest.getLowestPermittedRequestLevel(), lowestPermittedRequestLevelOnSubmit); SettableProducerContext settableProducerContext = new SettableProducerContext( imageRequest, generateUniqueFutureId(), uiComponentId, requestListener2, callerContext, lowestPermittedRequestLevel, /* isPrefetch */ false, imageRequest.getProgressiveRenderingEnabled() || !UriUtil.isNetworkUri(imageRequest.getSourceUri()), imageRequest.getPriority(), mConfig); return CloseableProducerToDataSourceAdapter.create( producerSequence, settableProducerContext, requestListener2); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } finally { if (FrescoSystrace.isTracing()) { FrescoSystrace.endSection(); } } } public <T> DataSource<CloseableReference<T>> submitFetchRequest( Producer<CloseableReference<T>> producerSequence, SettableProducerContext settableProducerContext, RequestListener requestListener) { if (FrescoSystrace.isTracing()) { FrescoSystrace.beginSection("ImagePipeline#submitFetchRequest"); } try { final RequestListener2 requestListener2 = new InternalRequestListener(requestListener, mRequestListener2); return CloseableProducerToDataSourceAdapter.create( producerSequence, settableProducerContext, requestListener2); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } finally { if (FrescoSystrace.isTracing()) { FrescoSystrace.endSection(); } } } public ProducerSequenceFactory getProducerSequenceFactory() { return mProducerSequenceFactory; } private DataSource<Void> submitPrefetchRequest( Producer<Void> producerSequence, ImageRequest imageRequest, ImageRequest.RequestLevel lowestPermittedRequestLevelOnSubmit, Object callerContext, Priority priority) { final RequestListener2 requestListener = new InternalRequestListener( getRequestListenerForRequest(imageRequest, null), mRequestListener2); if (mCallerContextVerifier != null) { mCallerContextVerifier.verifyCallerContext(callerContext, true); } try { ImageRequest.RequestLevel lowestPermittedRequestLevel = ImageRequest.RequestLevel.getMax( imageRequest.getLowestPermittedRequestLevel(), lowestPermittedRequestLevelOnSubmit); SettableProducerContext settableProducerContext = new SettableProducerContext( imageRequest, generateUniqueFutureId(), requestListener, callerContext, lowestPermittedRequestLevel, /* isPrefetch */ true, /* isIntermediateResultExpected */ false, priority, mConfig); return ProducerToDataSourceAdapter.create( producerSequence, settableProducerContext, requestListener); } catch (Exception exception) { return DataSources.immediateFailedDataSource(exception); } } public RequestListener getRequestListenerForRequest( ImageRequest imageRequest, @Nullable RequestListener requestListener) { if (requestListener == null) { if (imageRequest.getRequestListener() == null) { return mRequestListener; } return new ForwardingRequestListener(mRequestListener, imageRequest.getRequestListener()); } else { if (imageRequest.getRequestListener() == null) { return new ForwardingRequestListener(mRequestListener, requestListener); } return new ForwardingRequestListener( mRequestListener, requestListener, imageRequest.getRequestListener()); } } public RequestListener getCombinedRequestListener(@Nullable RequestListener listener) { if (listener == null) { return mRequestListener; } return new ForwardingRequestListener(mRequestListener, listener); } private Predicate<CacheKey> predicateForUri(final Uri uri) { return new Predicate<CacheKey>() { @Override public boolean apply(CacheKey key) { return key.containsUri(uri); } }; } public void pause() { mThreadHandoffProducerQueue.startQueueing(); } public void resume() { mThreadHandoffProducerQueue.stopQueuing(); } public boolean isPaused() { return mThreadHandoffProducerQueue.isQueueing(); } public Supplier<Boolean> isLazyDataSource() { return mLazyDataSource; } /** @return The CacheKeyFactory implementation used by ImagePipeline */ public CacheKeyFactory getCacheKeyFactory() { return mCacheKeyFactory; } public ImagePipelineConfig getConfig() { return mConfig; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.ac.cs.man.openphacts.queryexpander; import java.net.URLEncoder; import java.util.Set; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import uk.ac.cs.man.openphacts.queryexpander.mapper.BridgeDBMapper; import uk.ac.cs.man.openphacts.queryexpander.queryLoader.Ops1_1QueryLoader; import uk.ac.cs.man.openphacts.queryexpander.queryLoader.QueryCaseLoader; import uk.ac.cs.man.openphacts.queryexpander.queryLoader.SparqlLoader; /** * * @author Christian */ public class QueryExpanderWsServer { private QueryExpander queryExpander; public QueryExpanderWsServer() throws QueryExpansionException{ BridgeDBMapper imsMapper = BridgeDBFactory.getBridgeDBMapper(); queryExpander = new QueryExpanderImpl(imsMapper); } @GET @Produces(MediaType.TEXT_HTML) public Response welcomeMessage() { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" " + "\"http: sb.append("<html xmlns=\"http: sb.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-1\"/>\n"); sb.append("<head>\n"); sb.append("<title>Manchester OpenPhacts Query Expander</title></head>\n"); sb.append("<FRAMESET rows=\"150, 200\">\n"); sb.append("<FRAME src=\"QueryExpander/top\" name=\"topFrame\">\n"); sb.append("<FRAME src=\"QueryExpander/examples\" name =\"bottomFrame\">\n"); sb.append("</FRAMESET>\n"); sb.append("<NOFRAMES>"); sb.append("<P>this page requires frames! Trust Me!"); sb.append("</NOFRAMES>\n"); sb.append("</FRAMESET>\n"); sb.append("</html>"); return Response.ok(sb.toString(), MediaType.TEXT_HTML).build(); } @GET @Produces(MediaType.TEXT_HTML) @Path("/top") public Response topFrame(@QueryParam("query") @DefaultValue("SELECT *\nWHERE { \n?s ?p ?o\n}") String query) { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" " + "\"http: sb.append("<html xmlns=\"http: sb.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-1\"/>\n"); sb.append("<body>\n"); sb.append("<FORM METHOD=GET ACTION=\"expand\" Target=\"bottomFrame\" >\n"); sb.append("<h2>Enter your query:</H2>\n"); sb.append("<TEXTAREA NAME=query ROWS=15 COLS=100>\n"); sb.append(query); sb.append("\n"); sb.append("</TEXTAREA>\n"); sb.append("<BR>\n"); sb.append("<INPUT TYPE=submit VALUE=\"Expand this query\">\n"); sb.append("</FORM>\n"); sb.append("</body>\n"); sb.append("</html>"); return Response.ok(sb.toString(), MediaType.TEXT_HTML).build(); } @GET @Produces(MediaType.TEXT_HTML) @Path("/examples") public Response exampleFrame() { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" " + "\"http: sb.append("<html xmlns=\"http: sb.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-1\"/>\n"); appendToggler(sb); sb.append("<body onload=\"hideDetails()\">\n"); sb.append("<h2>Groups of Examples:</H2>\n"); sb.append("<H2 onclick=\"toggleItem('ops')\" style=\"color:blue;\"> <u>Queries used in Open Phacts</u></H2>\n"); loaderExamples(sb, new Ops1_1QueryLoader(), "ops"); sb.append("<H2 onclick=\"toggleItem('sparql')\" style=\"color:blue;\"> <u>Queries found in Sparql 1.1 specifications</u></H2>\n"); loaderExamples(sb, new SparqlLoader(), "sparql"); sb.append("</body>"); sb.append("</html>"); return Response.ok(sb.toString(), MediaType.TEXT_HTML).build(); } private void appendToggler(StringBuilder sb){ sb.append("<head>\n"); sb.append("<title> New Document </title>\n"); sb.append("<script language=\"javascript\">\n"); sb.append("function getItem(id)\n"); sb.append("{\n"); sb.append(" var itm = false;\n"); sb.append(" if(document.getElementById)\n"); sb.append(" itm = document.getElementById(id);\n"); sb.append(" else if(document.all)\n"); sb.append(" itm = document.all[id];\n"); sb.append(" else if(document.layers)\n"); sb.append(" itm = document.layers[id];\n"); sb.append(" return itm;\n"); sb.append("}\n\n"); sb.append("function toggleItem(id)\n"); sb.append("{\n"); sb.append(" itm = getItem(id);\n"); sb.append(" if(!itm)\n"); sb.append(" return false;\n"); sb.append(" if(itm.style.display == 'none')\n"); sb.append(" itm.style.display = '';\n"); sb.append(" else\n"); sb.append(" itm.style.display = 'none';\n"); sb.append(" return false;\n"); sb.append("}\n\n"); sb.append("function hideDetails()\n"); sb.append("{\n"); sb.append(" toggleItem('ops')\n"); sb.append(" toggleItem('sparql')\n"); sb.append(" return true;\n"); sb.append("}\n\n"); sb.append("</script>\n"); sb.append("</head>\n"); sb.append("\n"); } public void loaderExamples(StringBuilder sb, QueryCaseLoader loader, String group) { sb.append("<ul id =\""); sb.append(group); sb.append("\" >\n"); Set<String> queryKeys = loader.keySet(); for (String queryKey:queryKeys){ sb.append("<li><a href=\"top?query="); sb.append(URLEncoder.encode(loader.getOriginalQuery(queryKey))); sb.append("\" target=\"topFrame\">"); sb.append(loader.getQueryName(queryKey)); sb.append("</a></li>\n"); } sb.append("</ul>"); } @GET @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @Path("/expand") public ExpanderBean expandXML(@QueryParam("query") String query) throws QueryExpansionException{ if (query == null){ throw new QueryExpansionException ("query paramater is missing!"); } ExpanderBean result = new ExpanderBean(); result.setOrginalQuery(query); result.setExpandedQuery(queryExpander.expand(query)); return result; } @GET @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @Path("/expandXML") public ExpanderBean expandAsXML(@QueryParam("query") String query) throws QueryExpansionException{ return expandXML(query); } @GET @Produces(MediaType.TEXT_HTML) @Path("/expand") public Response expandHtml(@QueryParam("query") String query) throws QueryExpansionException{ if (query == null){ throw new QueryExpansionException ("query paramater is missing!"); } System.out.println(query); String result = queryExpander.expand(query); System.out.println(result); StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" " + "\"http: sb.append("<html xmlns=\"http: sb.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-1\"/>\n"); appendToggler(sb); sb.append("<body>\n"); sb.append("<a href=\"examples\">Return to example Index.</a>\n"); sb.append("<a href=\"expandXML?query="); sb.append(URLEncoder.encode(query)); sb.append("\">View Xml/Jason result</a>\n"); sb.append("<h2>Expanded Query</H2>\n"); sb.append("<textarea ROWS=15 COLS=100>"); sb.append(result); sb.append("</textarea>"); sb.append("</body>"); sb.append("</html>"); return Response.ok(sb.toString(), MediaType.TEXT_HTML).build(); } }
package org.rabix.engine.processor.handler.impl; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.rabix.bindings.BindingException; import org.rabix.bindings.model.Job; import org.rabix.bindings.model.Job.JobStatus; import org.rabix.bindings.model.LinkMerge; import org.rabix.bindings.model.dag.DAGContainer; import org.rabix.bindings.model.dag.DAGLink; import org.rabix.bindings.model.dag.DAGLinkPort; import org.rabix.bindings.model.dag.DAGLinkPort.LinkPortType; import org.rabix.bindings.model.dag.DAGNode; import org.rabix.common.helper.InternalSchemaHelper; import org.rabix.engine.JobHelper; import org.rabix.engine.db.DAGNodeDB; import org.rabix.engine.event.Event; import org.rabix.engine.event.impl.ContextStatusEvent; import org.rabix.engine.event.impl.InputUpdateEvent; import org.rabix.engine.event.impl.JobStatusEvent; import org.rabix.engine.event.impl.OutputUpdateEvent; import org.rabix.engine.model.ContextRecord.ContextStatus; import org.rabix.engine.model.JobRecord; import org.rabix.engine.model.JobRecord.PortCounter; import org.rabix.engine.model.LinkRecord; import org.rabix.engine.model.VariableRecord; import org.rabix.engine.processor.EventProcessor; import org.rabix.engine.processor.handler.EventHandler; import org.rabix.engine.processor.handler.EventHandlerException; import org.rabix.engine.service.ContextRecordService; import org.rabix.engine.service.JobRecordService; import org.rabix.engine.service.JobRecordService.JobState; import org.rabix.engine.service.LinkRecordService; import org.rabix.engine.service.VariableRecordService; import org.rabix.engine.status.EngineStatusCallback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; public class JobStatusEventHandler implements EventHandler<JobStatusEvent> { private final Logger logger = LoggerFactory.getLogger(JobStatusEventHandler.class); private final DAGNodeDB dagNodeDB; private final ScatterHandler scatterHelper; private final EventProcessor eventProcessor; private final JobRecordService jobRecordService; private final LinkRecordService linkRecordService; private final VariableRecordService variableRecordService; private final ContextRecordService contextRecordService; private EngineStatusCallback engineStatusCallback; @Inject public JobStatusEventHandler(final DAGNodeDB dagNodeDB, final JobRecordService jobRecordService, final LinkRecordService linkRecordService, final VariableRecordService variableRecordService, final ContextRecordService contextRecordService, final EventProcessor eventProcessor, final ScatterHandler scatterHelper) { this.dagNodeDB = dagNodeDB; this.scatterHelper = scatterHelper; this.eventProcessor = eventProcessor; this.jobRecordService = jobRecordService; this.linkRecordService = linkRecordService; this.contextRecordService = contextRecordService; this.variableRecordService = variableRecordService; } public void initialize(EngineStatusCallback engineStatusCallback) { this.engineStatusCallback = engineStatusCallback; } @Override public void handle(JobStatusEvent event) throws EventHandlerException { JobRecord jobRecord = jobRecordService.find(event.getJobId(), event.getContextId()); switch (event.getState()) { case READY: jobRecord.setState(JobState.READY); jobRecordService.update(jobRecord); ready(jobRecord, event.getContextId()); if (!jobRecord.isContainer() && !jobRecord.isScatterWrapper()) { Job job; try { job = JobHelper.createJob(jobRecord, JobStatus.READY, jobRecordService, variableRecordService, linkRecordService, contextRecordService, dagNodeDB); try { engineStatusCallback.onJobReady(job); } catch (Exception e) { logger.error("Failed to call onReady callback for Job " + job.getId(), e); throw new EventHandlerException("Failed to call onReady callback for Job " + job.getId(), e); } } catch (BindingException e1) { logger.info("Failed to create job", e1); } } break; case RUNNING: jobRecord.setState(JobState.RUNNING); jobRecordService.update(jobRecord); break; case COMPLETED: if (jobRecord.isRoot()) { try { if(!jobRecord.isContainer()) { // if root is CommandLineTool create OutputUpdateEvents for (PortCounter portCounter : jobRecord.getOutputCounters()) { Object output = event.getResult().get(portCounter.getPort()); eventProcessor.send(new OutputUpdateEvent(jobRecord.getRootId(), jobRecord.getId(), portCounter.getPort(), output, 1)); } } eventProcessor.send(new ContextStatusEvent(event.getContextId(), ContextStatus.COMPLETED)); Job rootJob = JobHelper.createRootJob(jobRecord, JobStatus.COMPLETED, jobRecordService, variableRecordService, linkRecordService, contextRecordService, dagNodeDB, event.getResult()); engineStatusCallback.onJobRootCompleted(rootJob); deleteRecords(rootJob.getId()); } catch (Exception e) { logger.error("Failed to call onRootCompleted callback for Job " + jobRecord.getRootId(), e); throw new EventHandlerException("Failed to call onRootCompleted callback for Job " + jobRecord.getRootId(), e); } } else { for (PortCounter portCounter : jobRecord.getOutputCounters()) { Object output = event.getResult().get(portCounter.getPort()); eventProcessor.addToQueue(new OutputUpdateEvent(jobRecord.getRootId(), jobRecord.getId(), portCounter.getPort(), output, 1)); } } break; case FAILED: eventProcessor.addToQueue(new ContextStatusEvent(event.getContextId(), ContextStatus.FAILED)); if (jobRecord.isRoot()) { try { Job rootJob = JobHelper.createRootJob(jobRecord, JobStatus.FAILED, jobRecordService, variableRecordService, linkRecordService, contextRecordService, dagNodeDB, null); engineStatusCallback.onJobRootFailed(rootJob); deleteRecords(rootJob.getId()); } catch (Exception e) { logger.error("Failed to call onRootFailed callback for Job " + jobRecord.getRootId(), e); throw new EventHandlerException("Failed to call onRootFailed callback for Job " + jobRecord.getRootId(), e); } } else { try { Job failedJob = JobHelper.createJob(jobRecord, JobStatus.FAILED, jobRecordService, variableRecordService, linkRecordService, contextRecordService, dagNodeDB); engineStatusCallback.onJobFailed(failedJob); } catch (Exception e) { logger.error("Failed to call onFailed callback for Job " + jobRecord.getId(), e); throw new EventHandlerException("Failed to call onFailed callback for Job " + jobRecord.getId(), e); } } break; default: break; } } private void deleteRecords(String rootId) { jobRecordService.delete(rootId); variableRecordService.delete(rootId); linkRecordService.delete(rootId); } /** * Job is ready */ public void ready(JobRecord job, String contextId) throws EventHandlerException { job.setState(JobState.READY); DAGNode node = dagNodeDB.get(InternalSchemaHelper.normalizeId(job.getId()), contextId); StringBuilder readyJobLogging = new StringBuilder(" --- JobRecord ").append(job.getId()).append(" is ready.").append(" Job isBlocking=").append(job.isBlocking()).append("\n"); for (PortCounter portCounter : job.getInputCounters()) { readyJobLogging.append(" --- Input port ").append(portCounter.getPort()).append(", isScatter=").append(portCounter.isScatter()).append(", isBlocking ").append(job.isInputPortBlocking(node, portCounter.getPort())).append("\n"); } readyJobLogging.append(" --- All scatter ports ").append(job.getScatterPorts()).append("\n"); logger.debug(readyJobLogging.toString()); if (job.isContainer()) { job.setState(JobState.RUNNING); DAGContainer containerNode; if (job.isScattered()) { containerNode = (DAGContainer) node; } else { containerNode = (DAGContainer) node; } List<String> jobs = rollOutContainer(job, containerNode, contextId); List<LinkRecord> containerLinks = linkRecordService.findBySourceAndSourceType(job.getId(), LinkPortType.INPUT, contextId); if (containerLinks.isEmpty()) { Set<String> immediateReadyNodeIds = findImmediateReadyNodes(containerNode); for (String readyNodeId : immediateReadyNodeIds) { JobRecord childJobRecord = jobRecordService.find(readyNodeId, contextId); if(childJobRecord.isContainer() || childJobRecord.isScatterWrapper()) { ready(childJobRecord, contextId); } else { JobStatusEvent jobStatusEvent = new JobStatusEvent(childJobRecord.getId(), contextId, JobState.READY, null); eventProcessor.send(jobStatusEvent); } } } else { for (LinkRecord link : containerLinks) { VariableRecord sourceVariable = variableRecordService.find(link.getSourceJobId(), link.getSourceJobPort(), LinkPortType.INPUT, contextId); VariableRecord destinationVariable = variableRecordService.find(link.getDestinationJobId(), link.getDestinationJobPort(), LinkPortType.INPUT, contextId); if(destinationVariable == null) { for(String jobId: jobs) { VariableRecord stepVariable = new VariableRecord(contextId, jobId, sourceVariable.getPortId(), LinkPortType.INPUT, sourceVariable.getValue(), null); variableRecordService.create(stepVariable); } checkIfChildJobsAreReady(job, containerNode); continue; } Event updateEvent = new InputUpdateEvent(contextId, destinationVariable.getJobId(), destinationVariable.getPortId(), sourceVariable.getValue(), link.getPosition()); eventProcessor.send(updateEvent); } } } else if (!job.isScattered() && job.getScatterPorts().size() > 0) { job.setState(JobState.RUNNING); for (String port : job.getScatterPorts()) { VariableRecord variable = variableRecordService.find(job.getId(), port, LinkPortType.INPUT, contextId); scatterHelper.scatterPort(job, port, variable.getValue(), 1, null, false, false); } } } private Set<String> findImmediateReadyNodes(DAGNode node) { if (node instanceof DAGContainer) { Set<String> nodesWithoutDestination = new HashSet<>(); for (DAGNode child : ((DAGContainer) node).getChildren()) { nodesWithoutDestination.add(child.getId()); } for (DAGLink link : ((DAGContainer) node).getLinks()) { nodesWithoutDestination.remove(link.getDestination().getDagNodeId()); } return nodesWithoutDestination; } return Collections.<String>emptySet(); } /** * Unwraps {@link DAGContainer} */ private List<String> rollOutContainer(JobRecord job, DAGContainer containerNode, String contextId) { List<String> createdJobs = new ArrayList<String>(); for (DAGNode node : containerNode.getChildren()) { String newJobId = InternalSchemaHelper.concatenateIds(job.getId(), InternalSchemaHelper.getLastPart(node.getId())); createdJobs.add(newJobId); JobRecord childJob = scatterHelper.createJobRecord(newJobId, job.getExternalId(), node, false, contextId); jobRecordService.create(childJob); StringBuilder childJobLogBuilder = new StringBuilder("\n -- JobRecord ").append(newJobId).append(", isBlocking ").append(childJob.isBlocking()).append("\n"); for (DAGLinkPort port : node.getInputPorts()) { if(port.getTransform() != null) { childJob.setBlocking(true); } VariableRecord childVariable = new VariableRecord(contextId, newJobId, port.getId(), LinkPortType.INPUT, port.getDefaultValue(), node.getLinkMerge(port.getId(), port.getType())); childJobLogBuilder.append(" -- Input port ").append(port.getId()).append(", isScatter ").append(port.isScatter()).append("\n"); variableRecordService.create(childVariable); } for (DAGLinkPort port : node.getOutputPorts()) { childJobLogBuilder.append(" -- Output port ").append(port.getId()).append(", isScatter ").append(port.isScatter()).append("\n"); VariableRecord childVariable = new VariableRecord(contextId, newJobId, port.getId(), LinkPortType.OUTPUT, null, node.getLinkMerge(port.getId(), port.getType())); variableRecordService.create(childVariable); } logger.debug(childJobLogBuilder.toString()); } for (DAGLink link : containerNode.getLinks()) { String originalJobID = InternalSchemaHelper.normalizeId(job.getId()); String sourceNodeId = originalJobID; String linkSourceNodeId = link.getSource().getDagNodeId(); if (linkSourceNodeId.startsWith(originalJobID)) { if (linkSourceNodeId.equals(sourceNodeId)) { sourceNodeId = job.getId(); } else { sourceNodeId = InternalSchemaHelper.concatenateIds(job.getId(), InternalSchemaHelper.getLastPart(linkSourceNodeId)); } } String destinationNodeId = originalJobID; String linkDestinationNodeId = link.getDestination().getDagNodeId(); if (linkDestinationNodeId.startsWith(originalJobID)) { if (linkDestinationNodeId.equals(destinationNodeId)) { destinationNodeId = job.getId(); } else { destinationNodeId = InternalSchemaHelper.concatenateIds(job.getId(), InternalSchemaHelper.getLastPart(linkDestinationNodeId)); } } LinkRecord childLink = new LinkRecord(contextId, sourceNodeId, link.getSource().getId(), LinkPortType.valueOf(link.getSource().getType().toString()), destinationNodeId, link.getDestination().getId(), LinkPortType.valueOf(link.getDestination().getType().toString()), link.getPosition()); linkRecordService.create(childLink); handleLinkPort(jobRecordService.find(sourceNodeId, contextId), link.getSource(), true); handleLinkPort(jobRecordService.find(destinationNodeId, contextId), link.getDestination(), false); } return createdJobs; } /** * Handle links for roll-out */ private void handleLinkPort(JobRecord job, DAGLinkPort linkPort, boolean isSource) { if (linkPort.getType().equals(LinkPortType.INPUT)) { if (job.getState().equals(JobState.PENDING)) { job.incrementPortCounter(linkPort, LinkPortType.INPUT); job.increaseInputPortIncoming(linkPort.getId()); if (job.getInputPortIncoming(linkPort.getId()) > 1) { if (LinkMerge.isBlocking(linkPort.getLinkMerge())) { job.setBlocking(true); } } } } else { job.incrementPortCounter(linkPort, LinkPortType.OUTPUT); if (isSource) { job.getOutputCounter(linkPort.getId()).updatedAsSource(1); } job.increaseOutputPortIncoming(linkPort.getId()); } jobRecordService.update(job); } private void checkIfChildJobsAreReady(JobRecord job, DAGContainer containerNode) throws EventHandlerException { List<JobRecord> jobs = jobRecordService.find(job.getRootId()); for(JobRecord childJob: jobs) { if(childJob.getParentId() != null && childJob.getParentId().equals(job.getExternalId())) { for(PortCounter inputPort: childJob.getInputCounters()){ if(inputPort.getCounter() != 0) { continue; } } if(childJob.getState() == JobState.PENDING) { ready(childJob, job.getRootId()); } } } } }
package name.matco.hotspot.api; import java.io.IOException; import java.util.Properties; import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature; @ApplicationPath("/") public class App extends ResourceConfig { public final static String RESOURCE_UUID_PATH = "/{uuid:[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}}"; public final static String RESOURCE_SPOT_UUID_PATH = "/{spotUuid:[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}}"; private static Properties PROPERTIES; public App() { packages(getClass().getPackage().getName()); //dependencies injection register(new AppBinder()); //jersey advanced features register(JacksonFeature.class); register(MultiPartFeature.class); //authentication register(RolesAllowedDynamicFeature.class); //register(AuthenticationRequestFilter.class); } public static Properties getAppProperties() { if(PROPERTIES == null) { PROPERTIES = new Properties(); try { PROPERTIES.load(App.class.getResourceAsStream("/config.properties")); } catch(final IOException e) { e.printStackTrace(); } PROPERTIES.putAll(System.getProperties()); } return PROPERTIES; } }
package net.fusejna; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; import java.util.regex.Pattern; import net.fusejna.StructFlock.FlockWrapper; import net.fusejna.StructFuseFileInfo.FileInfoWrapper; import net.fusejna.StructStat.StatWrapper; import net.fusejna.StructStatvfs.StatvfsWrapper; import net.fusejna.StructTimeBuffer.TimeBufferWrapper; import net.fusejna.types.*; import net.fusejna.types.TypeMode.ModeWrapper; import net.fusejna.types.TypeMode.NodeType; import com.sun.jna.Function; import com.sun.jna.Pointer; public abstract class FuseFilesystem { private static @interface FuseMethod { } private static @interface UserMethod { } private static final String defaultFilesystemName = "userfs-"; private static final Pattern regexNormalizeFilesystemName = Pattern.compile("[a-zA-Z]"); private final ReentrantLock mountLock = new ReentrantLock(); private final AutoUnmountHook unmountHook = new AutoUnmountHook(this); private File mountPoint = null; private Logger logger = null; @FuseMethod final int _access(final String path, final int access) { return access(path, access); } @FuseMethod final int _bmap(final String path, final StructFuseFileInfo info) { final FileInfoWrapper wrapper = new FileInfoWrapper(path, info); final int result = bmap(path, wrapper); wrapper.write(); return result; } @FuseMethod final int _chmod(final String path, final TypeMode mode) { return chmod(path, new ModeWrapper(mode)); } @FuseMethod final int _chown(final String path, final TypeUid uid, final TypeGid gid) { return chown(path, uid.longValue(), gid.longValue()); } @FuseMethod final int _create(final String path, final TypeMode mode, final StructFuseFileInfo info) { final FileInfoWrapper wrapper = new FileInfoWrapper(path, info); final int result = create(path, new ModeWrapper(mode), wrapper); wrapper.write(); return result; } @FuseMethod final void _destroy() { destroy(); } @FuseMethod final int _fgetattr(final String path, final StructStat stat, final StructFuseFileInfo info) { final StatWrapper swrapper = new StatWrapper(path, stat); defaultStat(swrapper, FuseJna.getUid(), FuseJna.getGid()); final FileInfoWrapper fwrapper = new FileInfoWrapper(path, info); final int result = fgetattr(path, swrapper, fwrapper); swrapper.write(); fwrapper.write(); return result; } @FuseMethod final int _flush(final String path, final StructFuseFileInfo info) { return flush(path, new FileInfoWrapper(path, info)); } @FuseMethod final int _fsync(final String path, final int datasync, final StructFuseFileInfo info) { return fsync(path, datasync, new FileInfoWrapper(path, info)); } @FuseMethod final int _fsyncdir(final String path, final int datasync, final StructFuseFileInfo info) { final FileInfoWrapper wrapper = new FileInfoWrapper(path, info); final int result = fsyncdir(path, datasync, wrapper); wrapper.write(); return result; } @FuseMethod final int _ftruncate(final String path, final TypeOff offset, final StructFuseFileInfo info) { final FileInfoWrapper wrapper = new FileInfoWrapper(path, info); final int result = ftruncate(path, offset.longValue(), wrapper); wrapper.write(); return result; } @FuseMethod final int _getattr(final String path, final StructStat stat) { final StatWrapper wrapper = new StatWrapper(path, stat); defaultStat(wrapper, FuseJna.getUid(), FuseJna.getGid()); final int result = getattr(path, wrapper); wrapper.write(); return result; } @FuseMethod final int _getxattr(final String path, final String xattr, final Pointer buffer, final TypeSize size, final TypeUInt32 position) { final long sizeValue = size.longValue(); if (buffer == null || sizeValue == 0L) { return 0; } final ByteBuffer buf = buffer.getByteBuffer(0, sizeValue); final int result = getxattr(path, xattr, buf, sizeValue, position == null ? 0L : position.longValue()); if (result == 0) { try { buf.put((byte) 0); } catch (final BufferOverflowException e) { return ErrorCodes.ERANGE(); } } return result; } @FuseMethod final void _init(final StructFuseConnInfo conn) { init(); } @FuseMethod final int _link(final String path, final String target) { return link(path, target); } @FuseMethod final int _listxattr(final String path, final Pointer buffer, final TypeSize size) { final long sizeValue = size.longValue(); if (buffer == null || sizeValue == 0L) { return 0; } final XattrListFiller filler = new XattrListFiller(buffer.getByteBuffer(0, sizeValue), sizeValue); return listxattr(path, filler); } @FuseMethod final int _lock(final String path, final StructFuseFileInfo info, final int cmd, final StructFlock flock) { final FileInfoWrapper fileWrapper = new FileInfoWrapper(path, info); final FlockWrapper flockWrapper = new FlockWrapper(path, flock); final int result = lock(path, fileWrapper, FlockCommand.fromBits(cmd), flockWrapper); fileWrapper.write(); flockWrapper.write(); return result; } @FuseMethod final int _mkdir(final String path, final TypeMode mode) { return mkdir(path, new ModeWrapper(mode)); } @FuseMethod final int _mknod(final String path, final TypeMode mode, final TypeDev dev) { return mknod(path, new ModeWrapper(mode), dev.longValue()); } @FuseMethod final int _open(final String path, final StructFuseFileInfo info) { final FileInfoWrapper wrapper = new FileInfoWrapper(path, info); final int result = open(path, wrapper); wrapper.write(); return result; } @FuseMethod final int _opendir(final String path, final StructFuseFileInfo info) { final FileInfoWrapper wrapper = new FileInfoWrapper(path, info); final int result = opendir(path, wrapper); wrapper.write(); return result; } @FuseMethod final int _read(final String path, final Pointer buffer, final TypeSize size, final TypeOff offset, final StructFuseFileInfo info) { final long bufSize = size.longValue(); final long readOffset = offset.longValue(); final ByteBuffer buf = buffer.getByteBuffer(0, bufSize); final FileInfoWrapper wrapper = new FileInfoWrapper(path, info); final int result = read(path, buf, bufSize, readOffset, wrapper); wrapper.write(); return result; } @FuseMethod final int _readdir(final String path, final Pointer buf, final Pointer fillFunction, final TypeOff offset, final StructFuseFileInfo info) { return readdir(path, new DirectoryFillerImpl(buf, Function.getFunction(fillFunction))); } @FuseMethod final int _readlink(final String path, final Pointer buffer, final TypeSize size) { final long bufSize = size.longValue(); final ByteBuffer buf = buffer.getByteBuffer(0, bufSize); final int result = readlink(path, buf, bufSize); if (result == 0) { try { buf.put((byte) 0); } catch (final BufferOverflowException e) { return ErrorCodes.EFAULT(); } } return result; } @FuseMethod final int _release(final String path, final StructFuseFileInfo info) { return release(path, new FileInfoWrapper(path, info)); } @FuseMethod final int _releasedir(final String path, final StructFuseFileInfo info) { final FileInfoWrapper wrapper = new FileInfoWrapper(path, info); final int result = releasedir(path, wrapper); wrapper.write(); return result; } @FuseMethod final int _removexattr(final String path, final String xattr) { return removexattr(path, xattr); } @FuseMethod final int _rename(final String path, final String newName) { return rename(path, newName); } @FuseMethod final int _rmdir(final String path) { return rmdir(path); } @FuseMethod final int _setxattr(final String path, final Pointer buffer, final TypeSize size, final int flags, final TypeUInt32 position) { final long sizeValue = size.longValue(); final ByteBuffer buf = buffer.getByteBuffer(0, sizeValue); return setxattr(path, buf, sizeValue, flags, position == null ? 0L : position.longValue()); } @FuseMethod final int _statfs(final String path, final StructStatvfs statsvfs) { final StatvfsWrapper wrapper = new StatvfsWrapper(path, statsvfs); final int result = statfs(path, wrapper); wrapper.write(); return result; } @FuseMethod final int _symlink(final String path, final String target) { return symlink(path, target); } @FuseMethod final int _truncate(final String path, final TypeOff offset) { return truncate(path, offset.longValue()); } @FuseMethod final int _unlink(final String path) { return unlink(path); } @FuseMethod final int _utimens(final String path, final StructTimeBuffer timebuffer) { final TimeBufferWrapper wrapper = new TimeBufferWrapper(timebuffer); final int result = utimens(path, wrapper); wrapper.write(); return result; } @FuseMethod final int _write(final String path, final Pointer buffer, final TypeSize size, final TypeOff offset, final StructFuseFileInfo info) { final long bufSize = size.longValue(); final long writeOffset = offset.longValue(); final ByteBuffer buf = buffer.getByteBuffer(0, bufSize); final FileInfoWrapper wrapper = new FileInfoWrapper(path, info); final int result = write(path, buf, bufSize, writeOffset, wrapper); wrapper.write(); return result; } @UserMethod public abstract int access(final String path, final int access); public abstract void afterUnmount(final File mountPoint); public abstract void beforeUnmount(final File mountPoint); @UserMethod public abstract int bmap(final String path, final FileInfoWrapper info); @UserMethod public abstract int chmod(final String path, final ModeWrapper mode); @UserMethod public abstract int chown(final String path, final long uid, final long gid); @UserMethod public abstract int create(final String path, final ModeWrapper mode, final FileInfoWrapper info); /** * Subclasses may override this to customize the default parameters applied to the stat structure, or to prevent such * behavior (by overriding this method with an empty one) * * @param stat * The */ protected void defaultStat(final StatWrapper wrapper, final long uid, final long gid) { // Set some sensible defaults wrapper.setMode(NodeType.DIRECTORY).setAllTimesMillis(System.currentTimeMillis()).nlink(1).uid(FuseJna.getUid()) .gid(FuseJna.getGid()); } @UserMethod public abstract void destroy(); @UserMethod public abstract int fgetattr(final String path, final StatWrapper stat, final FileInfoWrapper info); @UserMethod public abstract int flush(final String path, final FileInfoWrapper info); @UserMethod public abstract int fsync(final String path, int datasync, final FileInfoWrapper info); @UserMethod public abstract int fsyncdir(final String path, int datasync, final FileInfoWrapper info); @UserMethod public abstract int ftruncate(final String path, final long offset, final FileInfoWrapper info); @UserMethod public abstract int getattr(final String path, final StatWrapper stat); /** * Returns the raw fuse_context structure. Only valid when called while a filesystem operation is taking place. * * @return The fuse_context structure by reference. */ protected final StructFuseContext getFuseContext() { if (!isMounted()) { throw new IllegalStateException("Cannot get FUSE context if the filesystem is not mounted."); } return FuseJna.getFuseContext(); } /** * Returns the gid field of the fuse context. Only valid when called while a filesystem operation is taking place. * * @return The group ID of the process executing an operation on this filesystem. */ protected TypeGid getFuseContextGid() { return getFuseContext().gid; } /** * Returns the pid field of the fuse context. Only valid when called while a filesystem operation is taking place. * * @return The process ID of the process executing an operation on this filesystem. */ protected TypePid getFuseContextPid() { return getFuseContext().pid; } /** * Returns the uid field of the fuse context. Only valid when called while a filesystem operation is taking place. * * @return The user ID of the user running the process executing an operation of this filesystem. */ protected TypeUid getFuseContextUid() { return getFuseContext().uid; } final String getFuseName() { String name = getName(); if (name == null) { return defaultFilesystemName; } name = regexNormalizeFilesystemName.matcher(name).replaceAll(""); if (name.isEmpty()) { return defaultFilesystemName; } return name.toLowerCase(); } final Logger getLogger() { return logger; } public final File getMountPoint() { mountLock.lock(); final File mountPoint = this.mountPoint; mountLock.unlock(); return mountPoint; } protected abstract String getName(); protected abstract String[] getOptions(); final AutoUnmountHook getUnmountHook() { return unmountHook; } @UserMethod public abstract int getxattr(final String path, final String xattr, final ByteBuffer buf, final long size, final long position); @FuseMethod public abstract void init(); public final boolean isMounted() { return getMountPoint() != null; } @UserMethod public abstract int link(final String path, final String target); @UserMethod public abstract int listxattr(final String path, final XattrListFiller filler); @UserMethod public abstract int lock(final String path, final FileInfoWrapper info, final FlockCommand command, final FlockWrapper flock); protected final FuseFilesystem log(final boolean logging) { return log(logging ? Logger.getLogger(getClass().getCanonicalName()) : null); } protected final FuseFilesystem log(final Logger logger) { mountLock.lock(); if (mountPoint != null) { mountLock.unlock(); throw new IllegalStateException("Cannot turn logging on/orr when filesystem is already mounted."); } this.logger = logger; mountLock.unlock(); return this; } @UserMethod public abstract int mkdir(final String path, final ModeWrapper mode); @UserMethod public abstract int mknod(final String path, final ModeWrapper mode, final long dev); public final void mount(final File mountPoint) throws FuseException { mount(mountPoint, true); } public final void mount(final File mountPoint, final boolean blocking) throws UnsatisfiedLinkError, FuseException { mountLock.lock(); if (isMounted()) { throw new IllegalStateException(getFuseName() + " is already mounted at " + this.mountPoint); } this.mountPoint = mountPoint; mountLock.unlock(); FuseJna.mount(this, mountPoint, blocking); onMount(mountPoint); } public final void mount(final String mountPoint) throws FuseException { mount(new File(mountPoint), true); } public abstract void onMount(final File mountPoint); @UserMethod public abstract int open(final String path, final FileInfoWrapper info); @UserMethod public abstract int opendir(final String path, final FileInfoWrapper info); @UserMethod public abstract int read(final String path, final ByteBuffer buffer, final long size, final long offset, final FileInfoWrapper info); @UserMethod public abstract int readdir(final String path, final DirectoryFiller filler); @UserMethod public abstract int readlink(final String path, final ByteBuffer buffer, final long size); @UserMethod public abstract int release(final String path, final FileInfoWrapper info); @UserMethod public abstract int releasedir(final String path, final FileInfoWrapper info); @UserMethod public abstract int removexattr(final String path, final String xattr); @UserMethod public abstract int rename(final String path, final String newName); @UserMethod public abstract int rmdir(final String path); void setFinalMountPoint(final File mountPoint) { mountLock.lock(); this.mountPoint = mountPoint; mountLock.unlock(); } @UserMethod public abstract int setxattr(final String path, final ByteBuffer buf, final long size, final int flags, final long position); @UserMethod public abstract int statfs(final String path, final StatvfsWrapper wrapper); @UserMethod public abstract int symlink(final String path, final String target); @UserMethod public abstract int truncate(final String path, final long offset); @UserMethod public abstract int unlink(final String path); public final void unmount() throws IOException, FuseException { mountLock.lock(); if (!isMounted()) { return; } try { beforeUnmount(mountPoint); FuseJna.unmount(this); final File oldMountPoint = mountPoint; mountPoint = null; afterUnmount(oldMountPoint); } finally { mountLock.unlock(); } } @UserMethod public abstract int utimens(final String path, final TimeBufferWrapper wrapper); @UserMethod public abstract int write(final String path, final ByteBuffer buf, final long bufSize, final long writeOffset, final FileInfoWrapper info); }
package net.imagej.ops; import java.util.List; import org.scijava.ValidityProblem; import org.scijava.command.CommandInfo; import org.scijava.module.Module; import org.scijava.module.ModuleItem; /** * Container class for a possible operation match between an {@link OpRef} and * an {@link OpInfo}, as computed by the {@link OpMatchingService}. * * @author Curtis Rueden * @see OpMatchingService */ public class OpCandidate { public static enum StatusCode { MATCH, INVALID_MODULE, TOO_FEW_OUTPUTS, OUTPUT_TYPES_DO_NOT_MATCH, TOO_MANY_ARGS, TOO_FEW_ARGS, ARG_TYPES_DO_NOT_MATCH, REQUIRED_ARG_IS_NULL, CANNOT_CONVERT, DOES_NOT_CONFORM, OTHER } private final OpEnvironment ops; private final OpRef ref; private final OpInfo info; private Module module; private StatusCode code; private String message; private ModuleItem<?> item; private Object[] args; public OpCandidate(final OpEnvironment ops, final OpRef ref, final OpInfo info) { this.ops = ops; this.ref = ref; this.info = info; } /** Gets the op execution environment of the desired match. */ public OpEnvironment ops() { return ops; } /** Gets the op reference describing the desired match. */ public OpRef getRef() { return ref; } /** Gets the {@link OpInfo} metadata describing the op to match against. */ public OpInfo opInfo() { return info; } /** * Gets the {@link CommandInfo} metadata describing the op to match against. * * @see OpInfo#cInfo() */ public CommandInfo cInfo() { return info.cInfo(); } /** Gets the op's input parameters. */ public List<ModuleItem<?>> inputs() { return opInfo().inputs(); } /** Gets the op's output parameters. */ public List<ModuleItem<?>> outputs() { return opInfo().outputs(); } /** Sets the module instance associated with the attempted match. */ public void setModule(final Module module) { this.module = module; } /** Gets the module instance associated with the attempted match. */ public Module getModule() { return module; } /** Sets the status of the matching attempt. */ public void setStatus(final StatusCode code) { setStatus(code, null, null); } /** Sets the status of the matching attempt. */ public void setStatus(final StatusCode code, final String message) { setStatus(code, message, null); } /** Sets the status of the matching. */ public void setStatus(final StatusCode code, final String message, final ModuleItem<?> item) { this.code = code; this.message = message; this.item = item; } /** Gets the matching status code. */ public StatusCode getStatusCode() { return code; } /** Gets a message elaborating on the matching status, if any. */ public String getStatusMessage() { return message; } /** * Gets the status item related to the matching status, if any. Typically, if * set, this is the parameter for which matching failed. */ public ModuleItem<?> getStatusItem() { return item; } /** Gets a descriptive status message in human readable form. */ public String getStatus() { final StatusCode statusCode = getStatusCode(); if (statusCode == null) return null; final StringBuilder sb = new StringBuilder(); switch (statusCode) { case MATCH: sb.append("MATCH"); break; case INVALID_MODULE: sb.append("Invalid op: " + info.cInfo().getDelegateClassName()); final List<ValidityProblem> problems = info.cInfo().getProblems(); final int problemCount = problems.size(); if (problemCount > 0) sb.append(" ("); int no = 0; for (final ValidityProblem problem : problems) { if (no++ > 0) sb.append("; "); if (problemCount > 1) sb.append(no + ". "); sb.append(problem.getMessage()); } if (problemCount > 0) sb.append(")"); break; case TOO_FEW_OUTPUTS: sb.append("Too few outputs"); break; case OUTPUT_TYPES_DO_NOT_MATCH: sb.append("Output types do not match"); break; case TOO_MANY_ARGS: sb.append("Too many arguments"); break; case TOO_FEW_ARGS: sb.append("Not enough arguments"); break; case ARG_TYPES_DO_NOT_MATCH: sb.append("Argument types do not match"); break; case REQUIRED_ARG_IS_NULL: sb.append("Missing required argument"); break; case CANNOT_CONVERT: sb.append("Inconvertible type"); break; case DOES_NOT_CONFORM: sb.append("Inputs do not conform to op rules"); break; default: return getStatusMessage(); } final String msg = getStatusMessage(); if (msg != null) sb.append(": " + msg); return sb.toString(); } public Object[] getArgs() { return args; } public void setArgs(final Object[] args) { this.args = args; } @Override public String toString() { return info.toString(); } }
package net.krinsoft.chat; import com.pneumaticraft.commandhandler.CommandHandler; import net.krinsoft.chat.commands.*; import net.krinsoft.irc.IRCBot; import net.krinsoft.irc.InvalidIRCBotException; import net.krinsoft.chat.listeners.IRCListener; import net.krinsoft.chat.listeners.PlayerListener; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Set; /** * @author krinsdeath (Jeff Wardian) */ public class ChatCore extends JavaPlugin { // listeners private PlayerListener pListener; private IRCListener ircListener; private ChannelManager channelManager; private WorldManager worldManager; private PlayerManager playerManager; private CommandHandler commandHandler; private boolean debug = true; private boolean allow_channels = true; private boolean allow_whispers = true; private boolean allow_afk = true; @Override public void onEnable() { initConfiguration(); initEvents(); log("v" + getDescription().getVersion() + " enabled."); } @Override public void onDisable() { pListener = null; playerManager.saveConfig(); playerManager.clean(); channelManager.saveConfig(); channelManager.clean(); worldManager.clean(); if (irc_bot != null) { irc_bot.clean(); } log("v" + getDescription().getVersion() + " disabled."); } @Override public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) { if (!isEnabled()) { cs.sendMessage(ChatColor.RED + "no."); return true; } ArrayList<String> allArgs = new ArrayList<String>(Arrays.asList(args)); allArgs.add(0, label); return this.commandHandler.locateAndRunCommand(cs, allArgs); } public void initConfiguration() { registerConfiguration(); registerGroups(); channelManager = new ChannelManager(this); worldManager = new WorldManager(this); playerManager = new PlayerManager(this); connectIRCBot(allow_irc); } private void initEvents() { // set up the listeners initListeners(); getServer().getPluginManager().registerEvents(pListener, this); getServer().getPluginManager().registerEvents(ircListener, this); } private void initListeners() { pListener = new PlayerListener(this); ircListener = new IRCListener(this); initCommands(); } private void initCommands() { // set up the handlers CSPermissions permissionHandler = new CSPermissions(); commandHandler = new CommandHandler(this, permissionHandler); // register the commands if (allow_afk) { commandHandler.registerCommand(new AfkCommand(this)); } if (allow_whispers) { commandHandler.registerCommand(new WhisperCommand(this)); } if (allow_channels) { commandHandler.registerCommand(new ChannelAdminCommand(this)); commandHandler.registerCommand(new ChannelCreateCommand(this)); commandHandler.registerCommand(new ChannelInfoCommand(this)); commandHandler.registerCommand(new ChannelInviteCommand(this)); commandHandler.registerCommand(new ChannelJoinCommand(this)); commandHandler.registerCommand(new ChannelListCommand(this)); commandHandler.registerCommand(new ChannelMessageCommand(this)); commandHandler.registerCommand(new ChannelPartCommand(this)); } if (allow_irc) { commandHandler.registerCommand(new IRCCommand(this)); commandHandler.registerCommand(new IRCConnectCommand(this)); commandHandler.registerCommand(new IRCCreateCommand(this)); commandHandler.registerCommand(new IRCListCommand(this)); commandHandler.registerCommand(new IRCQuitCommand(this)); } commandHandler.registerCommand(new BaseCommand(this)); commandHandler.registerCommand(new DebugCommand(this)); commandHandler.registerCommand(new GroupOptionCommand(this)); commandHandler.registerCommand(new NickCommand(this)); commandHandler.registerCommand(new ReloadCommand(this)); commandHandler.registerCommand(new TargetCommand(this)); commandHandler.registerCommand(new VersionCommand(this)); } public void debug(String message) { if (debug) { message = "[Debug] " + message; getLogger().info(message); } } public void log(String message) { getLogger().info(message); } public void warn(String message) { getLogger().warning(message); } // WORLDS public WorldManager getWorldManager() { return this.worldManager; } // CHANNELS public ChannelManager getChannelManager() { return this.channelManager; } // PLAYERS public PlayerManager getPlayerManager() { return this.playerManager; } // PLUGIN OPTIONS // public void setDebug(boolean val) { debug = val; log("Debug mode: " + (val ? "enabled" : "disabled")); } public void setAllowChannels(boolean val) { allow_channels = val; debug("Channels: " + (val ? "allowed" : "denied")); } public void setAllowWhispers(boolean val) { allow_whispers = val; debug("Whispers: " + (val ? "allowed" : "denied")); } public void setAllowAfk(boolean val) { allow_afk = val; debug("Afk: " + (val ? "allowed" : "denied")); } public void setAllowIRC(boolean val) { allow_irc = val; debug("IRC: " + (val ? "allowed" : "denied")); } // IRC BOT CONFIGURATION // private boolean allow_irc = false; private IRCBot irc_bot = null; public IRCBot getIRCBot() { return irc_bot; } public void connectIRCBot(boolean val) { try { allow_irc = val; if (allow_irc) { irc_bot = new IRCBot(this); channelManager.connect(); } else { if (irc_bot != null) { irc_bot.clean(); } } } catch (IOException e) { warn("An error occurred while initializing the IRC Bot."); e.printStackTrace(); irc_bot = null; } catch (InvalidIRCBotException e) { warn(e.getLocalizedMessage()); irc_bot = null; } } // CONFIGURATION METHODS // private FileConfiguration configuration; private File config; private boolean OP_FALLBACK; private String DEFAULT_GROUP; private String OP_GROUP; private void registerConfiguration() { config = new File(getDataFolder(), "config.yml"); if (!config.exists()) { getConfig().setDefaults(YamlConfiguration.loadConfiguration(this.getClass().getResourceAsStream("/defaults/config.yml"))); getConfig().options().copyDefaults(true); getConfig().options().header( "Any group can have a format section, which overrides the 'global' format.\n" + "Variables, denoted by the use of a % (percent sign)\n" + "placeholder\n" + "placeholder\n" + "placeholder\n" + "placeholder\n" ); saveConfig(); } setDebug(getConfig().getBoolean("plugin.debug")); setAllowChannels(getConfig().getBoolean("plugin.allow_channels")); setAllowWhispers(getConfig().getBoolean("plugin.allow_whispers")); setAllowAfk(getConfig().getBoolean("plugin.allow_afk")); setAllowIRC(getConfig().getBoolean("plugin.allow_irc")); OP_FALLBACK = getConfig().getBoolean("plugin.op_fallback", false); } public FileConfiguration getConfig() { if (configuration == null) { configuration = YamlConfiguration.loadConfiguration(config); configuration.setDefaults(YamlConfiguration.loadConfiguration(config)); } return configuration; } public void saveConfig() { try { getConfig().save(config); } catch (Exception e) { warn("An error occurred while saving the file 'config.yml'"); } } public ConfigurationSection getGroupNode(String key) { return getConfig().getConfigurationSection("groups." + key); } public Set<String> getGroups() { return getConfig().getConfigurationSection("groups").getKeys(false); } private void registerGroups() { int defs = Integer.MAX_VALUE; int ops = 0; for (String key : getGroups()) { int weight = getGroupNode(key).getInt("weight"); if (weight < defs) { defs = weight; DEFAULT_GROUP = key; } if (weight > ops) { ops = weight; OP_GROUP = key; } debug("Registering group node: 'chatsuite.groups." + key + "' with weight '" + weight + "'"); Permission perm = new Permission("chatsuite.groups." + key); if (getServer().getPluginManager().getPermission("chatsuite.groups." + key) == null) { getServer().getPluginManager().addPermission(perm); } } debug("DEFAULT GROUP: " + DEFAULT_GROUP); getServer().getPluginManager().getPermission("chatsuite.groups." + DEFAULT_GROUP).setDefault(PermissionDefault.TRUE); if (OP_FALLBACK) { debug("OP GROUP: " + OP_GROUP); getServer().getPluginManager().getPermission("chatsuite.groups." + OP_GROUP).setDefault(PermissionDefault.OP); } } public String getDefaultGroup() { return DEFAULT_GROUP; } public String getOpGroup() { if (!OP_FALLBACK) { return DEFAULT_GROUP; } return OP_GROUP; } }
package nl.ovapi.rid.model; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.TimeZone; import lombok.Getter; import lombok.Setter; import lombok.ToString; import nl.ovapi.bison.model.KV17cvlinfo; import nl.ovapi.bison.model.KV17cvlinfo.Mutation; import nl.ovapi.bison.model.KV17cvlinfo.Mutation.MutationType; import nl.ovapi.bison.model.KV6posinfo; import nl.ovapi.bison.model.KV6posinfo.Type; import nl.ovapi.exceptions.StopNotFoundException; import nl.ovapi.exceptions.TooEarlyException; import nl.ovapi.exceptions.TooOldException; import nl.ovapi.exceptions.UnknownKV6PosinfoType; import nl.ovapi.rid.gtfsrt.Utils; import nl.ovapi.rid.model.JourneyPattern.JourneyPatternPoint; import nl.ovapi.rid.model.TimeDemandGroup.TimeDemandGroupPoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Maps; import com.google.transit.realtime.GtfsRealtime.TripDescriptor; import com.google.transit.realtime.GtfsRealtime.TripDescriptor.ScheduleRelationship; import com.google.transit.realtime.GtfsRealtime.TripUpdate; import com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeEvent; import com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate; import com.google.transit.realtime.GtfsRealtime.VehicleDescriptor; import com.google.transit.realtime.GtfsRealtimeOVapi; import com.google.transit.realtime.GtfsRealtimeOVapi.OVapiStopTimeUpdate; import com.google.transit.realtime.GtfsRealtimeOVapi.OVapiTripDescriptor; @ToString() public class Journey { @Getter @Setter /** * Trip_id of this journey */ private Long id; @Getter @Setter /** * DataOwnerCode:LinePlanningNumber:Journeynumber of trip, matches with KV6/17 */ private String privateCode; @Getter @Setter /** * JourneyPattern of the Journey */ private JourneyPattern journeypattern; @Getter @Setter /** * TimeDemandGroup of the Journey */ private TimeDemandGroup timedemandgroup; private Map<Integer, Long> realizedArrivals; private Map<Integer, Long> realizedDepartures; @Getter @Setter /** * Departuretime of the Journey, in seconds since midnight of operatingday (00:00:00). */ private Integer departuretime; @Getter @Setter /** * Indicates whether Journey is accessible to Journey */ private Boolean wheelchairaccessible; @Getter @Setter /** * agency_id of journey eg. (HTMBUZZ, BRENG, CXX). * Is not equal to DataOwnerCode!. */ private String agencyId; @Getter @Setter /** * ISO-8601 formatted (YYYY-MM-DD) OperatingDay. */ private String operatingDay; @Getter /** * Last received KV6posinfo for this Journey */ private KV6posinfo posinfo; @Getter @Setter /** * Indicates whether the trip is canceled */ private boolean isCanceled; private Map<Integer, ArrayList<Mutation>> mutations; @Getter @Setter /** * Map with last received posinfo for reinforcementnumber. */ private Map<Integer, KV6posinfo> reinforcements; public Journey() { mutations = Maps.newHashMap(); reinforcements = Maps.newHashMap(); realizedArrivals = Maps.newHashMap(); realizedDepartures = Maps.newHashMap(); } public void clearKV6(){ posinfo = null; } private static final boolean RECORD_TIMES = true; private static final int PUNCTUALITY_FLOOR = 15; // seconds private static final int DEFAULT_SPEED = (int) (75 / 3.6); // meters per // seconds private static final int LONGHAUL_SPEED = (int) (95 / 3.6); // meters per // seconds private static final int SHORTHAUL_SPEED = (int) (45 / 3.6); // meters per // seconds private static final int MIN_PUNCTUALITY = -300; // Minimum allowed // punctuality. private static final int MIN_STOPWAITTIME = -300; // Time it takes to unload a bus at a major stop eg a trainstation. // punctuality. private static final Logger _log = LoggerFactory.getLogger(Journey.class); /** * @return GTFS-Realtime TripDescriptor for this Journey */ public TripDescriptor.Builder tripDescriptor(){ TripDescriptor.Builder tripDescriptor = TripDescriptor.newBuilder(); tripDescriptor.setStartDate(operatingDay.replace("-", "")); tripDescriptor.setTripId(id.toString()); tripDescriptor.setScheduleRelationship(isCanceled ? ScheduleRelationship.CANCELED : ScheduleRelationship.SCHEDULED); OVapiTripDescriptor.Builder extension = OVapiTripDescriptor.newBuilder(); extension.setRealtimeTripId(privateCode); tripDescriptor.setExtension(GtfsRealtimeOVapi.ovapiTripdescriptor, extension.build()); return tripDescriptor; } private StopTimeEvent.Builder stopTimeEventArrival(TimeDemandGroupPoint tpt,JourneyPatternPoint pt, int punctuality){ StopTimeEvent.Builder stopTimeEvent = StopTimeEvent.newBuilder(); stopTimeEvent.setDelay(punctuality); stopTimeEvent.setTime(getDepartureEpoch()+tpt.getTotaldrivetime()+punctuality); return stopTimeEvent; } private StopTimeEvent.Builder stopTimeEventArrivalRecorded(TimeDemandGroupPoint tpt, long time){ StopTimeEvent.Builder stopTimeEvent = StopTimeEvent.newBuilder(); long targettime = getDepartureEpoch()+tpt.getTotaldrivetime(); int delay = (int)(time-targettime); if (Math.abs(delay) < PUNCTUALITY_FLOOR || delay < MIN_PUNCTUALITY*2){ stopTimeEvent.setDelay(0); stopTimeEvent.setTime(targettime); }else{ stopTimeEvent.setDelay(delay); stopTimeEvent.setTime(time); } return stopTimeEvent; } public boolean hasMutations(){ return mutations.size() > 0 || isCanceled; } public StopTimeEvent.Builder stopTimeEventDeparture(TimeDemandGroupPoint tpt,JourneyPatternPoint pt, int punctuality){ StopTimeEvent.Builder stopTimeEvent = StopTimeEvent.newBuilder(); if (mutations.containsKey(pt.getPointorder())){ for (Mutation m : mutations.get(pt.getPointorder())){ if (m.getMutationtype() == MutationType.LAG){ punctuality = Math.max(punctuality, m.getLagtime()); } } } stopTimeEvent.setDelay(punctuality); stopTimeEvent.setTime(getDepartureEpoch()+tpt.getTotaldrivetime()+tpt.getStopwaittime()+punctuality); return stopTimeEvent; } public StopTimeEvent.Builder stopTimeEventDepartureRecorded(TimeDemandGroupPoint tpt, long time){ StopTimeEvent.Builder stopTimeEvent = StopTimeEvent.newBuilder(); long targettime = getDepartureEpoch()+tpt.getTotaldrivetime()+tpt.getStopwaittime(); int delay = (int)(time-targettime); if (Math.abs(delay) < PUNCTUALITY_FLOOR || delay < MIN_PUNCTUALITY*2){ stopTimeEvent.setDelay(0); stopTimeEvent.setTime(targettime); }else{ stopTimeEvent.setDelay(delay); stopTimeEvent.setTime(time); } return stopTimeEvent; } /** * @return POSIX time when journey end in seconds since January 1st 1970 00:00:00 UTC */ public long getEndEpoch(){ try { Calendar c = Calendar.getInstance(TimeZone.getDefault()); c.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(getOperatingDay())); c.set(Calendar.HOUR, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); c.add(Calendar.SECOND, getDeparturetime()); c.add(Calendar.SECOND, timedemandgroup.getPoints().get(timedemandgroup.getPoints().size()-1).getTotaldrivetime()); if (posinfo != null && posinfo.getPunctuality() != null){ c.add(Calendar.SECOND, Math.abs(posinfo.getPunctuality())); } return c.getTimeInMillis()/1000; } catch (ParseException e) { return -1; } } /** * @return POSIX time when journey is scheduled to start in seconds since January 1st 1970 00:00:00 UTC */ public long getDepartureEpoch(){ try { Calendar c = Calendar.getInstance(TimeZone.getDefault()); c.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(getOperatingDay())); c.set(Calendar.HOUR, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); c.add(Calendar.SECOND, getDeparturetime()); return c.getTimeInMillis()/1000; } catch (ParseException e) { return -1; } } private StopTimeUpdate.Builder recordedTimes(TimeDemandGroupPoint tpt, JourneyPatternPoint pt){ if (!RECORD_TIMES) return null; StopTimeUpdate.Builder stopTimeUpdate = StopTimeUpdate.newBuilder(); boolean stopcanceled = isCanceled; boolean destChanged = false; if (mutations.containsKey(pt.getPointorder())){ // Check if mutation exists with cancel for (Mutation m : mutations.get(pt.getPointorder())){ if (m.getMutationtype() == MutationType.SHORTEN){ stopcanceled = true; } if (m.getMutationtype() == MutationType.CHANGEDESTINATION && !destChanged){ destChanged = true; String destination = m.getDestinationname50(); if (destination == null){ destination = m.getDestinationname16(); } if (destination == null){ destination = m.getDestinationdisplay16(); } if (destination != null){ OVapiStopTimeUpdate.Builder ovapiStopTimeUpdate = OVapiStopTimeUpdate.newBuilder(); ovapiStopTimeUpdate.setStopHeadsign(destination); stopTimeUpdate.setExtension(GtfsRealtimeOVapi.ovapiStopTimeUpdate, ovapiStopTimeUpdate.build()); } } } } stopTimeUpdate.setStopSequence(pt.getPointorder()); stopTimeUpdate.setStopId(pt.getPointref().toString()); if (!pt.isScheduled()) return null; // Dummy point if (stopcanceled){ stopTimeUpdate.setScheduleRelationship(StopTimeUpdate.ScheduleRelationship.SKIPPED); return stopTimeUpdate; } if (realizedArrivals.containsKey(pt.getPointorder())) stopTimeUpdate.setArrival(stopTimeEventArrivalRecorded(tpt,realizedArrivals.get(pt.getPointorder()))); if (realizedDepartures.containsKey(pt.getPointorder())) stopTimeUpdate.setDeparture(stopTimeEventDepartureRecorded(tpt,realizedDepartures.get(pt.getPointorder()))); if ((pt.isWaitpoint() ||pt.getPointorder() <= 1) && stopTimeUpdate.hasArrival() && stopTimeUpdate.getArrival().getDelay() < 0 && !stopTimeUpdate.hasDeparture()){ StopTimeEvent.Builder stopTimeEvent = StopTimeEvent.newBuilder(); stopTimeEvent.setTime(getDepartureTime(tpt.getPointorder())); stopTimeEvent.setDelay(0); stopTimeUpdate.setDeparture(stopTimeEvent); } if (stopTimeUpdate.hasDeparture() && !stopTimeUpdate.hasArrival()){ StopTimeEvent.Builder stopTimeEvent = StopTimeEvent.newBuilder(); long time = stopTimeUpdate.getDeparture().getTime(); int delay = stopTimeUpdate.getDeparture().getDelay(); long targettime = getDepartureEpoch()+tpt.getTotaldrivetime(); if (delay > MIN_PUNCTUALITY*2){ if (tpt.getStopwaittime() == 0){ stopTimeEvent.setTime(time); stopTimeEvent.setDelay(delay); }else if (delay <= 0){ stopTimeEvent.setTime(targettime); stopTimeEvent.setDelay(0); }else{ int waittime = Math.min(tpt.getStopwaittime(),MIN_STOPWAITTIME); stopTimeEvent.setTime(time-waittime); stopTimeEvent.setDelay((int)(targettime-(time-waittime))); } }else{ stopTimeEvent.setTime(targettime); stopTimeEvent.setDelay(0); } stopTimeUpdate.setArrival(stopTimeEvent); } if (!stopTimeUpdate.hasDeparture() && stopTimeUpdate.hasArrival()){ StopTimeEvent.Builder stopTimeEvent = StopTimeEvent.newBuilder(); long time = stopTimeUpdate.getArrival().getTime(); int delay = stopTimeUpdate.getArrival().getDelay(); time += tpt.getStopwaittime(); if (delay < 0 && pt.isWaitpoint()){ delay = 0; time = getDepartureEpoch()+tpt.getTotaldrivetime()+tpt.getStopwaittime(); } if (delay > MIN_PUNCTUALITY*2){ stopTimeEvent.setTime(time+tpt.getStopwaittime()); stopTimeEvent.setDelay(delay); stopTimeUpdate.setDeparture(stopTimeEvent); }else{ long targettime = getDepartureEpoch()+tpt.getTotaldrivetime(); stopTimeEvent.setTime(targettime); stopTimeEvent.setDelay(0); stopTimeUpdate.setDeparture(stopTimeEvent); } } if (!stopTimeUpdate.hasArrival() && !stopTimeUpdate.hasDeparture()){ StopTimeEvent.Builder stopTimeEvent = StopTimeEvent.newBuilder(); long targettime = getDepartureEpoch()+tpt.getTotaldrivetime(); stopTimeEvent.setTime(targettime); stopTimeEvent.setDelay(0); stopTimeUpdate.setArrival(stopTimeEvent); targettime += tpt.getStopwaittime(); stopTimeEvent.setTime(targettime); stopTimeEvent.setDelay(0); stopTimeUpdate.setDeparture(stopTimeEvent); } if (!stopTimeUpdate.hasArrival() || !stopTimeUpdate.hasDeparture()){ _log.error("Missing \n{}",stopTimeUpdate.build()); } return stopTimeUpdate; } private long getDepartureTime(int pointorder){ for (TimeDemandGroupPoint tpt : getTimedemandgroup().getPoints()){ if (tpt.getPointorder().equals(pointorder)){ return getDepartureEpoch()+tpt.getTotaldrivetime()+tpt.getStopwaittime(); } } throw new IllegalArgumentException("Pointorder "+pointorder+"does not exist"); } private long getArrivalTime(int pointorder){ for (TimeDemandGroupPoint tpt : getTimedemandgroup().getPoints()){ if (tpt.getPointorder().equals(pointorder)){ return getDepartureEpoch()+tpt.getTotaldrivetime(); } } throw new IllegalArgumentException("Pointorder "+pointorder+"does not exist"); } private TripUpdate.Builder filter(TripUpdate.Builder tripUpdate){ if (tripUpdate.getStopTimeUpdateCount() == 0) return tripUpdate; tripUpdate.getStopTimeUpdateOrBuilderList(); long lastTime = Long.MAX_VALUE; for (int i = tripUpdate.getStopTimeUpdateCount()-1; i >= 0; i--){ //Filter negative dwells and stoptimes StopTimeUpdate.Builder update = tripUpdate.getStopTimeUpdateBuilder(i); if (update.getScheduleRelationship() == StopTimeUpdate.ScheduleRelationship.NO_DATA || update.getScheduleRelationship() == StopTimeUpdate.ScheduleRelationship.SKIPPED || update.hasExtension(GtfsRealtimeOVapi.ovapiStopTimeUpdate)){ continue; } if (!update.hasDeparture() || !update.hasArrival()){ //System.out.println(tripUpdate.build()); //System.out.println(update.build()); _log.error("Departure or arrival is missing"); } if (update.getDeparture().getTime() > lastTime){ int offset = (int) (lastTime - update.getDeparture().getTime()); update.getDepartureBuilder().setTime(update.getDeparture().getTime()+offset); update.getDepartureBuilder().setDelay((int)(update.getDepartureBuilder().getTime()-getDepartureTime(update.getStopSequence()))); } lastTime = update.getDeparture().getTime(); if (update.getArrival().getTime() > lastTime){ int offset = (int) (lastTime - update.getArrival().getTime()); update.getArrivalBuilder().setTime(update.getArrival().getTime()+offset); update.getArrivalBuilder().setDelay((int)(update.getArrivalBuilder().getTime()-getArrivalTime(update.getStopSequence()))); } lastTime = update.getArrival().getTime(); } ArrayList<StopTimeUpdate.Builder> updates = new ArrayList<StopTimeUpdate.Builder>(); int lastDelay = Integer.MIN_VALUE; StopTimeUpdate.ScheduleRelationship lastSchedule = StopTimeUpdate.ScheduleRelationship.SCHEDULED; boolean hadStopTimeExtension = false; List<StopTimeUpdate.Builder> unfilteredUpdates = tripUpdate.getStopTimeUpdateBuilderList(); for (int i = 0; i < unfilteredUpdates.size(); i++){ StopTimeUpdate.Builder update = unfilteredUpdates.get(i); if (update.getScheduleRelationship() == StopTimeUpdate.ScheduleRelationship.NO_DATA || update.getScheduleRelationship() == StopTimeUpdate.ScheduleRelationship.SKIPPED || update.hasExtension(GtfsRealtimeOVapi.ovapiStopTimeUpdate)){ if (update.hasArrival()){ update.clearArrival(); } if (update.hasDeparture()){ update.clearDeparture(); } updates.add(update); //No data lastDelay = Integer.MIN_VALUE; lastSchedule = update.hasScheduleRelationship() ? StopTimeUpdate.ScheduleRelationship.SCHEDULED : update.getScheduleRelationship(); hadStopTimeExtension = update.hasExtension(GtfsRealtimeOVapi.ovapiStopTimeUpdate); continue; } boolean override = lastSchedule != update.getScheduleRelationship() || hadStopTimeExtension != update.hasExtension(GtfsRealtimeOVapi.ovapiStopTimeUpdate); if (update.hasArrival()){ if ((update.getArrival().getDelay() == lastDelay && !override ) || (i == 0 && update.getDeparture().getDelay() == update.getArrival().getDelay())){ update.clearArrival(); }else{ lastDelay = update.getArrival().getDelay(); } } if (update.hasDeparture()){ if (update.getDeparture().getDelay() == lastDelay && (i != 0) && !override){ update.clearDeparture(); }else{ lastDelay = update.getDeparture().getDelay(); } } if (update.hasArrival() || update.hasDeparture()){ updates.add(update); } lastSchedule = update.hasScheduleRelationship() ? StopTimeUpdate.ScheduleRelationship.SCHEDULED : update.getScheduleRelationship(); hadStopTimeExtension = update.hasExtension(GtfsRealtimeOVapi.ovapiStopTimeUpdate); } tripUpdate.clearStopTimeUpdate(); for (StopTimeUpdate.Builder update: updates){ tripUpdate.addStopTimeUpdate(update); } return tripUpdate; } public TripUpdate.Builder updateTimes(KV6posinfo posinfo) { boolean passed = posinfo.getMessagetype() != KV6posinfo.Type.DELAY; int punctuality = Math .max(MIN_PUNCTUALITY, posinfo.getPunctuality() == null ? 0 : posinfo.getPunctuality()); TripUpdate.Builder tripUpdate = TripUpdate.newBuilder(); tripUpdate.setTrip(tripDescriptor()); tripUpdate.setTimestamp(posinfo.getTimestamp()); if (isCanceled){ return tripUpdate; } VehicleDescriptor.Builder vehicleDesc = posinfo.getVehicleDescription(); if (vehicleDesc != null) tripUpdate.setVehicle(vehicleDesc); switch (posinfo.getMessagetype()) {// These types do not contain // information regarding punctuality case INIT: realizedArrivals = Maps.newHashMap(); realizedDepartures = Maps.newHashMap(); case END: case OFFROUTE: if (getPosinfo() != null && !hasMutations() && getPosinfo().getMessagetype() != Type.OFFROUTE) return null; //We've already sent out NO_DATE for (int i = 0; i < timedemandgroup.getPoints().size(); i++) { TimeDemandGroupPoint tpt = timedemandgroup.getPoints().get(i); JourneyPatternPoint pt = journeypattern.getPoint(tpt.pointorder); if (!pt.isScheduled()) continue; StopTimeUpdate.Builder recordedTimes = recordedTimes(tpt,pt); if (recordedTimes != null){ tripUpdate.addStopTimeUpdate(recordedTimes); }else if (posinfo.getMessagetype() == Type.OFFROUTE){ StopTimeUpdate.Builder noData = StopTimeUpdate.newBuilder(); noData.setStopSequence(pt.getPointorder()); noData.setStopId(pt.getPointref().toString()); noData.setScheduleRelationship(StopTimeUpdate.ScheduleRelationship.NO_DATA); tripUpdate.addStopTimeUpdate(noData); if (!hasMutations()) break; } } this.posinfo = posinfo; tripUpdate = filter(tripUpdate); if (tripUpdate.getStopTimeUpdateCount() > 0) return tripUpdate; default: break; } int passageseq = 0; int elapsedtime = 0; for (int i = 0; i < timedemandgroup.getPoints().size(); i++) { TimeDemandGroupPoint tpt = timedemandgroup.getPoints().get(i); JourneyPatternPoint pt = journeypattern.getPoint(tpt.pointorder); if (pt.getOperatorpointref().equals(posinfo.getUserstopcode())) { if (posinfo.getPassagesequencenumber() - passageseq > 0) { passageseq++; // Userstop equal but posinfo relates to n-th // passing } else { elapsedtime = tpt.getTotaldrivetime()+tpt.getStopwaittime(); passed = false; switch (posinfo.getMessagetype()) { case ARRIVAL: if (RECORD_TIMES) realizedArrivals.put(pt.getPointorder(), posinfo.getTimestamp()); long targetArrivalTime = getDepartureEpoch()+tpt.getTotaldrivetime(); int newPunctuality = (int)(posinfo.getTimestamp()-targetArrivalTime); if (newPunctuality > -60 && newPunctuality - punctuality < 600){ punctuality = newPunctuality; } if ((pt.isWaitpoint() || i == 0) && punctuality < 0) punctuality = 0; break; case DEPARTURE: long targetDepartureTime = getDepartureEpoch()+tpt.getTotaldrivetime()+tpt.getStopwaittime(); newPunctuality = (int)(posinfo.getTimestamp()-targetDepartureTime); if (RECORD_TIMES && (!pt.isWaitpoint() || newPunctuality > 0)) realizedDepartures.put(pt.getPointorder(), posinfo.getTimestamp()); if ((pt.isWaitpoint() || i == 0) && punctuality < 0) punctuality = 0; break; case ONSTOP: if ((pt.isWaitpoint() || i == 0) && punctuality < 0) punctuality = 0; targetDepartureTime = getDepartureEpoch()+tpt.getTotaldrivetime()+tpt.getStopwaittime(); newPunctuality = (int)(posinfo.getTimestamp()-targetDepartureTime); if (newPunctuality > -30 && newPunctuality - punctuality < 600){ punctuality = newPunctuality; } break; default: break; } } StopTimeUpdate.Builder recorded = recordedTimes(tpt,pt); if (recorded != null){ tripUpdate.addStopTimeUpdate(recorded); } } else if (!passed) { //Stops not visted by the vehicle StopTimeUpdate.Builder stopTimeUpdate = StopTimeUpdate.newBuilder(); stopTimeUpdate.setStopSequence(tpt.getPointorder()); stopTimeUpdate.setStopId(pt.getPointref().toString()); stopTimeUpdate.setArrival(stopTimeEventArrival(tpt,pt,punctuality)); boolean stopcanceled = isCanceled; boolean destChanged = false; if (mutations.containsKey(tpt.getPointorder())){ // Check if mutation exists with cancel for (Mutation m : mutations.get(tpt.getPointorder())){ if (m.getMutationtype() == MutationType.SHORTEN){ stopcanceled = true; } if (m.getMutationtype() == MutationType.CHANGEDESTINATION && !destChanged){ destChanged = true; String destination = m.getDestinationname50(); if (destination == null){ destination = m.getDestinationname16(); } if (destination == null){ destination = m.getDestinationdisplay16(); } if (destination != null){ OVapiStopTimeUpdate.Builder ovapiStopTimeUpdate = OVapiStopTimeUpdate.newBuilder(); ovapiStopTimeUpdate.setStopHeadsign(destination); stopTimeUpdate.setExtension(GtfsRealtimeOVapi.ovapiStopTimeUpdate, ovapiStopTimeUpdate.build()); } } } } stopTimeUpdate.setScheduleRelationship( stopcanceled ? StopTimeUpdate.ScheduleRelationship.SKIPPED : StopTimeUpdate.ScheduleRelationship.SCHEDULED); if (pt.isWaitpoint() && punctuality < 0) punctuality = 0; if (tpt.getStopwaittime() != 0 && punctuality > 0) { //Minimize delay by cutting into dwells int stopwaittime = tpt.getStopwaittime(); if (stopwaittime > 100 ) { punctuality -= stopwaittime-MIN_STOPWAITTIME; punctuality = Math.max(0, punctuality); } } stopTimeUpdate.setDeparture(stopTimeEventDeparture(tpt,pt,punctuality)); if (pt.isScheduled()){ tripUpdate.addStopTimeUpdate(stopTimeUpdate); } punctuality = stopTimeUpdate.getDeparture().getDelay(); if (i+1 < timedemandgroup.getPoints().size()){ TimeDemandGroupPoint ntpt = timedemandgroup.getPoints().get(i+1); JourneyPatternPoint npt = journeypattern.getPoint(ntpt.pointorder); int distanceToNext = npt.getDistancefromstartroute() - pt.getDistancefromstartroute(); int secondsToNext = ntpt.getTotaldrivetime() - (tpt.getTotaldrivetime()+tpt.getStopwaittime()); int speed = DEFAULT_SPEED; if (distanceToNext > 10000) { speed = LONGHAUL_SPEED; } else if (distanceToNext < 1000) { speed = SHORTHAUL_SPEED; } int fastest = distanceToNext / speed; if ((punctuality > 0 || secondsToNext < fastest) && i != timedemandgroup.getPoints().size() - 1) { punctuality -= (secondsToNext - fastest); if (punctuality < 0) { punctuality = 0; } } else if (punctuality < 0 && i != timedemandgroup.getPoints().size() - 1) { punctuality = decayeddelay(punctuality, tpt.getTotaldrivetime() - elapsedtime); } if (Math.abs(punctuality) < PUNCTUALITY_FLOOR) { punctuality = 0; } } }else{ //JourneyPatternPoint has been passed. StopTimeUpdate.Builder recorded = recordedTimes(tpt,pt); if (recorded != null){ tripUpdate.addStopTimeUpdate(recorded); } } } this.posinfo = posinfo; tripUpdate = filter(tripUpdate); if (tripUpdate.getStopTimeUpdateCount() > 0) return tripUpdate; else return null; } private int decayeddelay(int delay, int elapsedtime) { if (delay == 0) return 0; double vlamba = 1.0 / 500.0; double decay = Math.exp(-vlamba * elapsedtime); int decayeddelay = (int) (decay * delay); return decayeddelay; } private void parseMutateJourney(Long timestamp, Mutation m) { switch (m.getMutationtype()) { case CANCEL: isCanceled = true; break; case RECOVER: isCanceled = false; break; default: break; } } private JourneyPatternPoint getJourneyStop (String userstopcode,int passageSequencenumber){ for (int i = 0; i < timedemandgroup.getPoints().size(); i++) { TimeDemandGroupPoint tpt = timedemandgroup.getPoints().get(i); JourneyPatternPoint pt = journeypattern.getPoint(tpt.pointorder); if (pt.getOperatorpointref().equals(userstopcode)){ if (passageSequencenumber > 0){ passageSequencenumber }else{ return pt; } } } return null; } private void parseMutateJourneyStop(Long timestamp, Mutation m) throws StopNotFoundException { JourneyPatternPoint pst = getJourneyStop(m.getUserstopcode(),m.getPassagesequencenumber()); if (pst == null) { throw new StopNotFoundException(m.toString()); } if (!mutations.containsKey(pst.getPointorder())) mutations.put(pst.getPointorder(), new ArrayList<Mutation>()); switch (m.getMutationtype()) { case CHANGEDESTINATION: case CHANGEPASSTIMES: case LAG: case RECOVER: case CANCEL: case SHORTEN: mutations.get(pst.getPointorder()).add(m); break; default: _log.info("Unknown mutationtype {}",m); break; } } public TripUpdate.Builder update(ArrayList<KV17cvlinfo> cvlinfos) { long timestamp = 0; if (cvlinfos.size() == 0){ return null; } mutations.clear(); for (KV17cvlinfo cvlinfo : cvlinfos) { for (Mutation mut : cvlinfo.getMutations()) { try { timestamp = Math.max(timestamp, cvlinfo.getTimestamp()); switch (mut.getMessagetype()) { case KV17MUTATEJOURNEY: parseMutateJourney(cvlinfo.getTimestamp(), mut); continue; case KV17MUTATEJOURNEYSTOP: parseMutateJourneyStop(cvlinfo.getTimestamp(), mut); continue; } } catch (Exception e) { _log.error("Error applying KV17",e); } } } int posinfoAge = (posinfo == null) ? Integer.MAX_VALUE : (int)(Utils.currentTimeSecs()-posinfo.getTimestamp()); if (timestamp == 0) timestamp = Utils.currentTimeSecs(); if (posinfo != null && posinfoAge < 120){ TripUpdate.Builder timeUpdate = updateTimes(posinfo); timeUpdate.setTimestamp(timestamp); return timeUpdate; }else{ KV6posinfo posinfo = new KV6posinfo(); posinfo.setMessagetype(Type.DELAY); //Fake KV6posinfo to get things moving posinfo.setPunctuality(0); posinfo.setTimestamp(timestamp); return updateTimes(posinfo); } } public TripUpdate.Builder update(KV6posinfo posinfo) throws StopNotFoundException,UnknownKV6PosinfoType, TooEarlyException, TooOldException { long currentTime = Utils.currentTimeSecs(); if (posinfo.getTimestamp()<currentTime-120){ throw new TooOldException(posinfo.toString()); } long departureTime = getDepartureEpoch(); if (currentTime < departureTime){ int timeDeltaSeconds = (int)(departureTime-Utils.currentTimeSecs()); if (timeDeltaSeconds>=3600){ switch(posinfo.getMessagetype()){ case INIT: break; default: throw new TooEarlyException(posinfo.toString()); } } } if (posinfo.getUserstopcode() != null && !journeypattern.contains(posinfo.getUserstopcode())) { throw new StopNotFoundException(posinfo.toString()); } return updateTimes(posinfo); } }
package org.boon.primitive; import org.boon.cache.Cache; import org.boon.cache.CacheType; import org.boon.cache.SimpleCache; import org.boon.core.reflection.FastStringUtils; import sun.nio.cs.Surrogate; import java.io.IOException; import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import static org.boon.Boon.puts; import static org.boon.Exceptions.die; import static org.boon.primitive.CharScanner.*; import static org.boon.primitive.CharScanner.parseLong; public class CharBuf extends Writer implements CharSequence { protected int capacity = 16; protected int location = 0; protected char[] buffer; public CharBuf( char[] buffer ) { this.buffer = buffer; this.capacity = buffer.length; } public CharBuf( byte[] bytes ) { this.buffer = null; this.addAsUTF( bytes ); } public static CharBuf createExact( final int capacity ) { return new CharBuf( capacity ) { public CharBuf add( char[] chars ) { Chr._idx( buffer, location, chars ); location += chars.length; return this; } }; } public static CharBuf create( int capacity ) { return new CharBuf( capacity ); } public static CharBuf create( char[] buffer ) { return new CharBuf( buffer ); } public static CharBuf createFromUTF8Bytes( byte[] buffer ) { return new CharBuf( buffer ); } protected CharBuf( int capacity ) { this.capacity = capacity; init(); } protected CharBuf() { init(); } @Override public void write( char[] cbuf, int off, int len ) { if ( off == 0 && cbuf.length == len ) { this.add( cbuf ); } else { char[] buffer = Arrays.copyOfRange( cbuf, off, off + len ); this.add( buffer ); } } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } public void init() { buffer = new char[ capacity ]; } public final CharBuf add( String str ) { add( FastStringUtils.toCharArray( str ) ); return this; } public final CharBuf addString( String str ) { add( FastStringUtils.toCharArray( str ) ); return this; } public final CharBuf addObject ( Object object ) { String str = object.toString(); addString ( str ); return this; } public final CharBuf add( int i ) { add ( Integer.toString ( i )); return this; } private Cache <Integer, char[]> icache; public final CharBuf addInt( int i ) { switch (i) { case 0: addChar('0'); return this; case 1: addChar('1'); return this; case -1: addChar('-'); addChar('1'); return this; } addInt( Integer.valueOf( i ) ); return this; } public final CharBuf addInt( Integer key ) { if (icache == null) { icache = new SimpleCache<> ( 20, CacheType.LRU ); } char [] chars = icache.get ( key ); if ( chars == null ) { String str = Integer.toString ( key ); chars = FastStringUtils.toCharArray ( str ); icache.put ( key, chars ); } addChars ( chars ); return this; } final char [] trueChars = "true".toCharArray (); final char [] falseChars = "false".toCharArray (); public final CharBuf add( boolean b ) { addChars ( b ? trueChars : falseChars ); return this; } public final CharBuf addBoolean( boolean b ) { add ( Boolean.toString ( b )); return this; } public final CharBuf add( byte i ) { add ( Byte.toString ( i )); return this; } public final CharBuf addByte( byte i ) { addInt ( i ); return this; } public final CharBuf add( short i ) { add ( Short.toString ( i )); return this; } public final CharBuf addShort( short i ) { addInt ( i ); return this; } public final CharBuf add( long l ) { add ( Long.toString ( l )); return this; } public final CharBuf add( double d ) { add ( Double.toString ( d ) ); return this; } private Cache <Double, char[]> dcache; public final CharBuf addDouble( double d ) { addDouble( Double.valueOf( d ) ); return this; } public final CharBuf addDouble( Double key ) { if (dcache == null) { dcache = new SimpleCache<> ( 20, CacheType.LRU ); } char [] chars = dcache.get ( key ); if ( chars == null ) { String str = Double.toString ( key ); chars = FastStringUtils.toCharArray ( str ); dcache.put ( key, chars ); } add ( chars ); return this; } public final CharBuf add( float d ) { add ( Float.toString ( d )); return this; } private Cache <Float, char[]> fcache; public final CharBuf addFloat( float d ) { addFloat( Float.valueOf( d ) ); return this; } public final CharBuf addFloat( Float key ) { if (fcache == null) { fcache = new SimpleCache<> ( 20, CacheType.LRU ); } char [] chars = fcache.get ( key ); if ( chars == null ) { String str = Float.toString ( key ); chars = FastStringUtils.toCharArray ( str ); fcache.put ( key, chars ); } add ( chars ); return this; } public final CharBuf addChar( byte i ) { add( ( char ) i ); return this; } public final CharBuf addChar( int i ) { add( ( char ) i ); return this; } public final CharBuf addChar( short i ) { add( ( char ) i ); return this; } public final CharBuf addChar( final char ch ) { int _location = location; char [] _buffer = buffer; int _capacity = capacity; if ( 1 + _location > _capacity ) { _buffer = Chr.grow( _buffer ); } _buffer [_location] = ch; _capacity = _buffer.length; _location ++; location = _location; buffer = _buffer; capacity = _capacity; return this; } public CharBuf addLine( String str ) { add( str.toCharArray() ); add( '\n' ); return this; } public CharBuf addLine( CharSequence str ) { add( str.toString() ); add( '\n' ); return this; } public CharBuf add( char[] chars ) { if ( chars.length + location > capacity ) { buffer = Chr.grow( buffer, buffer.length * 2 + chars.length ); capacity = buffer.length; } Chr._idx( buffer, location, chars ); location += chars.length; return this; } public final CharBuf addChars( char[] chars ) { if ( chars.length + location > capacity ) { buffer = Chr.grow( buffer, buffer.length * 2 + chars.length ); capacity = buffer.length; } arraycopy ( chars, 0, buffer, location, chars.length ); location += chars.length; return this; } public final CharBuf addQuoted( char[] chars ) { int _location = location; char [] _buffer = buffer; int _capacity = capacity; int sizeNeeded = chars.length + 2 + _location; if ( sizeNeeded > _capacity ) { _buffer = Chr.grow( _buffer, sizeNeeded * 2 ); _capacity = _buffer.length; } _buffer [_location] = '"'; _location++; arraycopy( chars, 0, _buffer, _location, chars.length ); _location += (chars.length); _buffer [_location] = '"'; _location++; location = _location; buffer = _buffer; capacity = _capacity; return this; } public final CharBuf addJsonEscapedString( String jsonString ) { char[] charArray = FastStringUtils.toCharArray ( jsonString ); return addJsonEscapedString ( charArray ); } public static void main (String... args) { puts ((int) '\b', "bell"); puts ((int) '\t', "tab"); puts ((int) '\n', "newline"); puts ((int) '\f', "feed"); puts ((int) '\r', "return"); puts ((int) '"', "quote"); puts ((int) '/', "fslash"); puts ((int) '\\', "slash"); puts ((int) ' ', "space"); puts ((int) 'z', "z"); } private static boolean isJSONControl ( int c ) { /* Anything less than space is a control character. */ if ( c < 30 ) { return true; /* 34 is double quote. */ } else if (c == 34 ){ return true; /* 47 is back slash. */ } else if (c == 47) { return true; /* 92 is forward slash. */ }else if (c == 92) { return true; } return false; } private static boolean hasAnyJSONControlChars ( final char[] charArray ) { int index = 0; char c; while ( true ) { c = charArray[ index ]; if ( isJSONControl ( c )) { return true; } if ( ++index >= charArray.length) return false; } } public final CharBuf addJsonEscapedString( final char[] charArray ) { if (charArray.length == 0 ) return this; if ( hasAnyJSONControlChars ( charArray )) { return doAddJsonEscapedString(charArray); } else { return this.addQuoted ( charArray ); } } private final CharBuf doAddJsonEscapedString( char[] charArray ) { char [] _buffer = buffer; int _location = this.location; int ensureThisMuch = charArray.length * 2; int sizeNeeded = (ensureThisMuch) + _location; if ( sizeNeeded > capacity ) { int growBy = ( _buffer.length * 2 ) < sizeNeeded ? sizeNeeded : (_buffer.length*2); _buffer = Chr.grow( buffer, growBy); capacity = _buffer.length; } _buffer[_location] = '"'; _location ++; int index = 0; while ( true ) { char c = charArray[ index ]; if ( ++index >= charArray.length) break; if ( isJSONControl ( c )) { switch ( c ) { case '\"': _buffer[_location] = '\\'; _location ++; _buffer[_location] = '"'; _location ++; break; case '\\': _buffer[_location] = '\\'; _location ++; _buffer[_location] = '\\'; _location ++; break; case '/': _buffer[_location] = '\\'; _location ++; _buffer[_location] = '/'; _location ++; break; case '\b': _buffer[_location] = '\\'; _location ++; _buffer[_location] = 'b'; _location ++; break; case '\f': _buffer[_location] = '\\'; _location ++; _buffer[_location] = 'f'; _location ++; break; case '\n': _buffer[_location] = '\\'; _location ++; _buffer[_location] = 'n'; _location ++; break; case '\r': _buffer[_location] = '\\'; _location ++; _buffer[_location] = 'r'; _location ++; break; case '\t': _buffer[_location] = '\\'; _location ++; _buffer[_location] = 't'; _location ++; break; } }else { _buffer[_location] = c; _location ++; } } _buffer[_location] = '"'; _location ++; buffer = _buffer; location = _location; return this; } public final CharBuf addJsonFieldName( char[] chars ) { int _location = location; char [] _buffer = buffer; int _capacity = capacity; int sizeNeeded = chars.length + 2 + _location; if ( sizeNeeded > _capacity ) { _buffer = Chr.grow( _buffer, sizeNeeded * 2 ); _capacity = _buffer.length; } _buffer [_location] = '"'; _location++; arraycopy( chars, 0, _buffer, _location, chars.length ); _location += (chars.length); _buffer [_location] = '"'; _location++; _buffer [_location] = ':'; _location++; location = _location; buffer = _buffer; capacity = _capacity; return this; } public final CharBuf addQuoted( String str ) { final char[] chars = FastStringUtils.toCharArray ( str ); addQuoted ( chars ); return this; } public CharBuf add( char[] chars, final int length ) { if ( length + location < capacity ) { Chr._idx( buffer, location, chars, length ); } else { buffer = Chr.grow( buffer, buffer.length * 2 + length ); Chr._idx( buffer, location, chars ); capacity = buffer.length; } location += length; return this; } public CharBuf add( byte[] chars ) { if ( chars.length + location < capacity ) { Chr._idx( buffer, location, chars ); } else { buffer = Chr.grow( buffer, buffer.length * 2 + chars.length ); Chr._idx( buffer, location, chars ); capacity = buffer.length; } location += chars.length; return this; } private final static void sysstemarraycopy (final char [] src, final int srcPos, final char [] dest, final int destPos, final int length) { System.arraycopy( src, srcPos, dest, destPos, length ); } private final static void directArraycopy (final char [] src, final int srcPos, final char [] dest, final int destPos, final int length) { int destIndex = destPos; for (int index = srcPos; index < srcPos + length; index++, destIndex++ ) { dest [destIndex] = src[index]; } } private final static void arraycopy (final char [] src, final int srcPos, final char [] dest, final int destPos, final int length) { sysstemarraycopy( src, srcPos, dest, destPos, length ); } public CharBuf add( byte[] bytes, int start, int end ) { int charsLength = end - start ; if ( charsLength + location > capacity ) { buffer = Chr.grow( buffer, buffer.length * 2 + charsLength ); } Chr._idx( buffer, location, bytes, start, end ); capacity = buffer.length; location += charsLength; return this; } public final CharBuf add( char ch ) { if ( 1 + location < capacity ) { buffer [location] = ch; } else { buffer = Chr.grow( buffer ); buffer [location] = ch; capacity = buffer.length; } location += 1; return this; } @Override public int length () { return len(); } @Override public char charAt ( int index ) { return buffer [ index ]; } @Override public CharSequence subSequence ( int start, int end ) { return new String (buffer, start, end - start); } public String toString() { return new String( buffer, 0, location ); } public int len() { return location; } public char[] toCharArray() { return this.buffer; } public void _len( int location ) { this.location = location; } public char[] readForRecycle() { this.location = 0; return this.buffer; } private static double powersOf10[] = { 1.0, 10.0, 100.0, 1_000.0, 10_000.0, 100_000.0, 1_000_000.0, 10_000_000.0, 100_000_000.0, 1_000_000_000.0, 10_000_000_000.0, 100_000_000_000.0, 1_000_000_000_000.0, 10_000_000_000_000.0, 100_000_000_000_000.0, }; private static float fpowersOf10[] = { 1.0f, 10.0f, 100.0f, 1_000.0f, 10_000.0f, 100_000.0f, 1_000_000.0f, 10_000_000.0f, 100_000_000.0f, 1_000_000_000.0f, }; public double doubleValue() { boolean simple = true; int digitsPastPoint = 0; boolean foundPoint = false; boolean negative = false; int startIndex = 0; double sign; if ( buffer[ startIndex ] == '-' ) { startIndex++; negative = true; sign = -1.0; } else { negative = false; sign = 1.0; } loop: for ( int index = startIndex; index < location; index++ ) { char ch = buffer[ index ]; switch ( ch ) { case 'e': simple = false; break loop; case 'E': simple = false; break loop; case 'F': simple = false; break loop; case 'f': simple = false; break loop; case '.': foundPoint = true; continue loop; } if ( foundPoint ) { digitsPastPoint++; if ( digitsPastPoint >= powersOf10.length ) { simple = true; break; } } } if ( simple ) { long value; final int length = location - startIndex; if ( isInteger( buffer, startIndex, length, negative ) ) { value = parseIntIgnoreDot( buffer, startIndex, length ); } else { value = parseLongIgnoreDot( buffer, startIndex, length ); } if ( digitsPastPoint < powersOf10.length ) { double power = powersOf10[ digitsPastPoint ] * sign; return value / power; } } return Double.parseDouble( toString() ) * sign; } public float floatValue() { boolean simple = true; int digitsPastPoint = 0; boolean foundPoint = false; float sign; int startIndex = 0; if ( buffer[ startIndex ] == '-' ) { startIndex++; sign = -1.0f; } else { sign = 1.0f; } int length = location - startIndex; if ( length > 10 ) { return Float.parseFloat( toString() ) * sign; } loop: for ( int index = startIndex; index < location; index++ ) { char ch = buffer[ index ]; switch ( ch ) { case 'e': simple = false; break loop; case 'E': simple = false; break loop; case 'F': simple = false; break loop; case 'f': simple = false; break loop; case '.': foundPoint = true; continue loop; } if ( foundPoint ) { digitsPastPoint++; if ( digitsPastPoint >= powersOf10.length ) { simple = true; break; } } } if ( simple ) { int value; value = parseIntIgnoreDot( buffer, startIndex, length ); if ( digitsPastPoint < powersOf10.length ) { float power = fpowersOf10[ digitsPastPoint ] * sign; return value / power; } } return Float.parseFloat( toString() ) * sign; } public int intValue() { int sign = 1; int startIndex = 0; if ( buffer[ startIndex ] == '-' ) { startIndex++; sign = -1; } return parseInt( buffer, startIndex, location - startIndex ) * sign; } public long longValue() { long sign = 1; int startIndex = 0; if ( buffer[ startIndex ] == '-' ) { startIndex++; sign = -1; } return parseLong( buffer, startIndex, location - startIndex ) * sign; } public byte byteValue() { return ( byte ) intValue(); } public short shortValue() { return ( short ) intValue(); } public Number toIntegerWrapper() { int sign = 1; boolean negative = false; int startIndex = 0; if ( buffer[ startIndex ] == '-' ) { startIndex++; sign = -1; negative = true; } if ( isInteger( buffer, startIndex, location - startIndex, negative ) ) { return intValue() * sign; } else { return longValue() * sign; } } public void addAsUTF( byte[] value ) { if ( this.buffer == null ) { this.buffer = new char[ value.length ]; } else if ( this.buffer.length < value.length ) { buffer = Chr.grow( buffer, value.length - buffer.length ); } for ( int index = 0; index < value.length; index++ ) { int __currentChar = value[ index ]; if ( __currentChar >= 0 ) { this.addChar( __currentChar ); } else { utf8MultiByte( __currentChar, index, value ); } } } // [C2..DF] [80..BF] private static boolean isMalformed2( int b1, int b2 ) { return ( b1 & 0x1e ) == 0x0 || ( b2 & 0xc0 ) != 0x80; } // [E0] [A0..BF] [80..BF] // [E1..EF] [80..BF] [80..BF] private static boolean isMalformed3( int b1, int b2, int b3 ) { return ( b1 == ( byte ) 0xe0 && ( b2 & 0xe0 ) == 0x80 ) || ( b2 & 0xc0 ) != 0x80 || ( b3 & 0xc0 ) != 0x80; } // [F0] [90..BF] [80..BF] [80..BF] // [F1..F3] [80..BF] [80..BF] [80..BF] // [F4] [80..8F] [80..BF] [80..BF] // only check 80-be range here, the [0xf0,0x80...] and [0xf4,0x90-...] // will be checked by Surrogate.neededFor(uc) private static boolean isMalformed4( int b2, int b3, int b4 ) { return ( b2 & 0xc0 ) != 0x80 || ( b3 & 0xc0 ) != 0x80 || ( b4 & 0xc0 ) != 0x80; } private final void utf8MultiByte( final int b1, int __index, byte[] bytes ) { boolean ok = true; if ( ( b1 >> 5 ) == -2 ) { int b2; ok = __index + 1 < bytes.length || die( "unable to parse 2 byte utf 8 - b2" ); __index++; b2 = bytes[ __index ]; if ( isMalformed2( b1, b2 ) ) { addChar( ' } else { addChar( ( ( b1 << 6 ) ^ b2 ) ^ 0x0f80 ); } } else if ( ( b1 >> 4 ) == -2 ) { int b2; int b3; ok = __index + 1 < bytes.length || die( "unable to parse 3 byte utf 8 - b2" ); __index++; b2 = bytes[ __index ]; ok = __index + 1 < bytes.length || die( "unable to parse 3 byte utf 8 - b3" ); __index++; b3 = bytes[ __index ]; if ( isMalformed3( b1, b2, b3 ) ) { addChar( ' } else { addChar( ( ( b1 << 12 ) ^ ( b2 << 6 ) ^ b3 ) ^ 0x1f80 ); } } else if ( ( b1 >> 3 ) == -2 ) { int b2; int b3; int b4; ok = __index + 1 < bytes.length || die( "unable to parse 4 byte utf 8 - b2" ); __index++; b2 = bytes[ __index ]; ok = __index + 1 < bytes.length || die( "unable to parse 4 byte utf 8 - b3" ); __index++; b3 = bytes[ __index ]; ok = __index + 1 < bytes.length || die( "unable to parse 4 byte utf 8 - b4" ); __index++; b4 = bytes[ __index ]; int uc = ( ( b1 & 0x07 ) << 18 ) | ( ( b2 & 0x3f ) << 12 ) | ( ( b3 & 0x3f ) << 6 ) | ( b4 & 0x3f ); if ( isMalformed4( b2, b3, b4 ) && !Surrogate.neededFor( uc ) ) { addChar( ' } else { final char high = Surrogate.high( uc ); final char low = Surrogate.low( uc ); addChar( high ); addChar( low ); } } } final static char [] nullChars = "null".toCharArray (); public final void addNull () { this.add ( nullChars ); } public void removeLastChar () { location } private Cache <BigDecimal, char[]> bigDCache; public CharBuf addBigDecimal( BigDecimal key ) { if (bigDCache == null) { bigDCache = new SimpleCache<> ( 20, CacheType.LRU ); } char [] chars = bigDCache.get ( key ); if ( chars == null ) { String str = key.toString(); chars = FastStringUtils.toCharArray ( str ); bigDCache.put ( key, chars ); } add ( chars ); return this; } private Cache <BigInteger, char[]> bigICache; public CharBuf addBigInteger( BigInteger key ) { if (bigICache == null) { bigICache = new SimpleCache<> ( 20, CacheType.LRU ); } char [] chars = bigICache.get ( key ); if ( chars == null ) { String str = key.toString(); chars = FastStringUtils.toCharArray ( str ); bigICache.put ( key, chars ); } add ( chars ); return this; } private Cache <Long, char[]> lcache; public final CharBuf addLong( long l ) { addLong(Long.valueOf( l )); return this; } public final CharBuf addLong( Long key ) { if (lcache == null) { lcache = new SimpleCache<> ( 20, CacheType.LRU ); } char [] chars = lcache.get ( key ); if ( chars == null ) { String str = Long.toString ( key ); chars = FastStringUtils.toCharArray ( str ); lcache.put ( key, chars ); } add ( chars ); return this; } /** * Turn a single bytes into two hex character representation. * * @param decoded the byte to serializeObject. */ public CharSequence addHex( final int decoded ) { int _location = location; char [] _buffer = buffer; int _capacity = capacity; if ( 2 + _location > _capacity ) { _buffer = Chr.grow( _buffer ); _capacity = _buffer.length; } _buffer [_location] = (char) encodeNibbleToHexAsciiCharByte( ( decoded >> 4 ) & 0x0F ); _location ++; _buffer [_location] = (char) encodeNibbleToHexAsciiCharByte( decoded & 0x0F );; _location ++; location = _location; buffer = _buffer; capacity = _capacity; return this; } /** * Turns a single nibble into an ascii HEX digit. * * @param nibble the nibble to serializeObject. * @return the encoded nibble (1/2 byte). */ protected static int encodeNibbleToHexAsciiCharByte( final int nibble ) { switch ( nibble ) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: return nibble + 0x30; // 0x30('0') - 0x39('9') case 0x0A: case 0x0B: case 0x0C: case 0x0D: case 0x0E: case 0x0F: return nibble + 0x57; // 0x41('a') - 0x46('f') default: die( "illegal nibble: " + nibble ); return -1; } } }
package com.temenos.interaction.sdk; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; import org.odata4j.edm.EdmProperty; import org.odata4j.edm.EdmSimpleType; import org.odata4j.edm.EdmType; import com.temenos.interaction.core.entity.EntityMetadata; import com.temenos.interaction.core.entity.Metadata; import com.temenos.interaction.core.entity.vocabulary.Term; import com.temenos.interaction.core.entity.vocabulary.Vocabulary; import com.temenos.interaction.core.entity.vocabulary.terms.TermComplexGroup; import com.temenos.interaction.core.entity.vocabulary.terms.TermComplexType; import com.temenos.interaction.core.entity.vocabulary.terms.TermIdField; import com.temenos.interaction.core.entity.vocabulary.terms.TermListType; import com.temenos.interaction.core.entity.vocabulary.terms.TermMandatory; import com.temenos.interaction.core.entity.vocabulary.terms.TermValueType; import com.temenos.interaction.odataext.entity.MetadataOData4j; import com.temenos.interaction.sdk.adapter.InteractionAdapter; import com.temenos.interaction.sdk.adapter.edmx.EDMXAdapter; import com.temenos.interaction.sdk.command.Commands; import com.temenos.interaction.sdk.command.Parameter; import com.temenos.interaction.sdk.entity.EMEntity; import com.temenos.interaction.sdk.entity.EMProperty; import com.temenos.interaction.sdk.entity.EMTerm; import com.temenos.interaction.sdk.entity.EntityModel; import com.temenos.interaction.sdk.interaction.IMResourceStateMachine; import com.temenos.interaction.sdk.interaction.state.IMState; import com.temenos.interaction.sdk.interaction.transition.IMCollectionStateTransition; import com.temenos.interaction.sdk.interaction.transition.IMEntityStateTransition; import com.temenos.interaction.sdk.interaction.transition.IMTransition; import com.temenos.interaction.sdk.interaction.InteractionModel; import com.temenos.interaction.sdk.rimdsl.RimDslGenerator; /** * This class is the main entry point to the IRIS SDK. It is a simple front end * for generating JPA classes, and associated configuration files. With these * classes and config files in place we can then fill a mock database with * appropriate values and enable IRIS to respond to resource requests from User * Agents. * */ public class JPAResponderGen { public final static String JPA_CONFIG_FILE = "jpa-persistence.xml"; public final static String SPRING_CONFIG_FILE = "spring-beans.xml"; public final static String SPRING_RESOURCEMANAGER_FILE = "resourcemanager-context.xml"; public final static String RESPONDER_INSERT_FILE = "responder_insert.sql"; public final static String RESPONDER_SETTINGS_FILE = "responder.properties"; public final static String BEHAVIOUR_CLASS_FILE = "Behaviour.java"; public final static String METADATA_FILE = "metadata.xml"; public final static Parameter COMMAND_SERVICE_DOCUMENT = new Parameter("ServiceDocument", false, ""); public final static Parameter COMMAND_EDM_DATA_SERVICES = new Parameter("edmDataServices", true, ""); public final static Parameter COMMAND_METADATA = new Parameter("Metadata", false, ""); public final static Parameter COMMAND_METADATA_SOURCE_ODATAPRODUCER = new Parameter("producer", true, "odataProducer"); public final static Parameter COMMAND_METADATA_SOURCE_MODEL = new Parameter("edmMetadata", true, "edmMetadata"); private final boolean strictOData; //Indicates whether it should generate strict odata paths etc. (e.g. Flight(1)/flightschedule rather than FlightSchedule(2051)) /* * create a new instance of the engine */ VelocityEngine ve = new VelocityEngine(); /** * Construct an instance of this class */ public JPAResponderGen() { this(true); } /** * Construct an instance of this class * @param strictOData indicates whether to generate a strict odata model */ public JPAResponderGen(boolean strictOData) { this.strictOData = strictOData; // load .vm templates using classloader ve.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath." + VelocityEngine.RESOURCE_LOADER + ".class", ClasspathResourceLoader.class.getName()); ve.init(); } /** * Generate project artefacts from conceptual interaction and metadata models. * @param metadata metadata model * @param interactionModel Conceptual interaction model * @param srcOutputPath Path to output directory * @param configOutputPath Path to configuration files directory * @param generateMockResponder Indicates whether to generate artifacts for a mock responder * @return true if successful, false otherwise */ public boolean generateArtifacts(InteractionAdapter adapter, File srcOutputPath, File configOutputPath, boolean generateMockResponder) { return generateArtifacts(adapter.getEntityModel(), adapter.getInteractionModel(), adapter.getCommands(), adapter.getEntitiesInfo(), srcOutputPath, configOutputPath, generateMockResponder); } public boolean generateArtifacts(InteractionAdapter adapter, File srcOutputPath, File configOutputPath) { return generateArtifacts(adapter, srcOutputPath, configOutputPath, true); } public boolean generateArtifacts(Metadata metadata, InteractionModel interactionModel, File srcOutputPath, File configOutputPath, boolean generateMockResponder) { //Create commands Commands commands = getDefaultCommands(); return generateArtifacts(metadata, interactionModel, commands, srcOutputPath, configOutputPath, generateMockResponder); } /** * Generate project artefacts from conceptual interaction and metadata models. * @param metadata metadata model * @param interactionModel Conceptual interaction model * @param commands Commands * @param srcOutputPath Path to output directory * @param configOutputPath Path to configuration files directory * @param generateMockResponder Indicates whether to generate artifacts for a mock responder * @return true if successful, false otherwise */ public boolean generateArtifacts(Metadata metadata, InteractionModel interactionModel, Commands commands, File srcOutputPath, File configOutputPath, boolean generateMockResponder) { //Create the entity model String modelName = metadata.getModelName(); EntityModel entityModel = createEntityModelFromMetadata(modelName, metadata); //Add error entities for(IMState state : interactionModel.getErrorHandlerStates()) { EMEntity emEntity = new EMEntity(state.getName()); EMProperty empErrorMvGroup = new EMProperty("ErrorsMvGroup"); empErrorMvGroup.addVocabularyTerm(new EMTerm(TermIdField.TERM_NAME, "true")); empErrorMvGroup.addVocabularyTerm(new EMTerm(TermListType.TERM_NAME, "true")); empErrorMvGroup.addVocabularyTerm(new EMTerm(TermComplexType.TERM_NAME, "true")); emEntity.addProperty(empErrorMvGroup); EMProperty empCode = new EMProperty("Code"); empCode.addVocabularyTerm(new EMTerm(TermComplexGroup.TERM_NAME, "ErrorsMvGroup")); emEntity.addProperty(empCode); EMProperty empInfo = new EMProperty("Info"); empInfo.addVocabularyTerm(new EMTerm(TermComplexGroup.TERM_NAME, "ErrorsMvGroup")); emEntity.addProperty(empInfo); EMProperty empText = new EMProperty("Text"); empText.addVocabularyTerm(new EMTerm(TermComplexGroup.TERM_NAME, "ErrorsMvGroup")); emEntity.addProperty(empText); EMProperty empType = new EMProperty("Type"); empType.addVocabularyTerm(new EMTerm(TermComplexGroup.TERM_NAME, "ErrorsMvGroup")); emEntity.addProperty(empType); entityModel.addEntity(emEntity); } //Obtain resource information String namespace = modelName + Metadata.MODEL_SUFFIX; List<EntityInfo> entitiesInfo = new ArrayList<EntityInfo>(); for (EntityMetadata entityMetadata: metadata.getEntitiesMetadata().values()) { EntityInfo entityInfo = createEntityInfoFromEntityMetadata(namespace, entityMetadata); addNavPropertiesToEntityInfo(entityInfo, interactionModel); entitiesInfo.add(entityInfo); } return generateArtifacts(entityModel, interactionModel, commands, entitiesInfo, srcOutputPath, configOutputPath, generateMockResponder); } /** * Generate project artefacts from conceptual interaction and metadata models. * @param entityModel the entity metadata * @param interactionModel Conceptual interaction model * @param commands Commands * @param srcOutputPath Path to output directory * @param configOutputPath Path to configuration files directory * @param generateMockResponder Indicates whether to generate artifacts for a mock responder * @return true if successful, false otherwise */ public boolean generateArtifacts(EntityModel entityModel, InteractionModel interactionModel, Commands commands, List<EntityInfo> entitiesInfo, File srcOutputPath, File configOutputPath, boolean generateMockResponder) { boolean ok = true; //Write other artefacts if(!writeArtefacts(entityModel.getModelName(), entitiesInfo, commands, entityModel, interactionModel, srcOutputPath, configOutputPath, generateMockResponder)) { ok = false; } return ok; } /** * Returns a character stream representing the RIM from the conceptual interaction and metadata models. * @param interactionModel Conceptual interaction model * @param commands Commands * @return RIM as character stream * @throws Exception */ public InputStream getRIM(InteractionModel interactionModel, Commands commands) throws Exception { RimDslGenerator rimDslGenerator = new RimDslGenerator(ve); String dsl = rimDslGenerator.generateRimDsl(interactionModel, commands, strictOData); return new ByteArrayInputStream(dsl.getBytes()); } private boolean writeArtefacts(String modelName, List<EntityInfo> entitiesInfo, Commands commands, EntityModel entityModel, InteractionModel interactionModel, File srcOutputPath, File configOutputPath, boolean generateMockResponder) { boolean ok = true; String namespace = modelName + Metadata.MODEL_SUFFIX; interactionModel.setDomain(namespace); //Create the source directory new File(srcOutputPath + "/" + namespace.replace(".", "/")).mkdirs(); // generate metadata.xml if (!writeMetadata(configOutputPath, generateMetadata(entityModel))) { ok = false; } // generate spring configuration files if (!writeSpringConfiguration(configOutputPath, SPRING_CONFIG_FILE, generateSpringConfiguration(namespace, modelName, commands))) { ok = false; } // generate the rim DSL RimDslGenerator rimDslGenerator = new RimDslGenerator(ve); String rimDslFilename = modelName + ".rim"; if (!writeRimDsl(configOutputPath, rimDslFilename, rimDslGenerator.generateRimDsl(interactionModel, commands, strictOData))) { ok = false; } if(generateMockResponder) { //Write JPA classes for(EntityInfo entityInfo : entitiesInfo) { if(!generateJPAEntity(entityInfo, srcOutputPath)) { ok = false; } } // generate persistence.xml if (!writeJPAConfiguration(configOutputPath, generateJPAConfiguration(entitiesInfo))) { ok = false; } // generate spring configuration for JPA database if (!writeSpringConfiguration(configOutputPath, SPRING_RESOURCEMANAGER_FILE, generateSpringResourceManagerContext(modelName))) { ok = false; } // generate responder insert if (!writeResponderDML(configOutputPath, generateResponderDML(entitiesInfo))) { ok = false; } // generate responder settings if (!writeResponderSettings(configOutputPath, generateResponderSettings(modelName))) { ok = false; } } return ok; } private boolean generateJPAEntity(EntityInfo entityInfo, File srcOutputPath) { //Generate JPA class if(entityInfo.isJpaEntity()) { String path = srcOutputPath.getPath() + "/" + entityInfo.getPackageAsPath(); if (!writeClass(path, formClassFilename(path, entityInfo), generateJPAEntityClass(entityInfo))) { return false; } } return true; } /** * Utility method to form class filename. * @param srcTargetDir * @param entityInfo * @return */ public static String formClassFilename(String path, EntityInfo entityInfo) { return path + "/" + entityInfo.getClazz() + ".java"; } protected boolean writeClass(String path, String classFileName, String generatedClass) { FileOutputStream fos = null; try { new File(path).mkdirs(); fos = new FileOutputStream(classFileName); fos.write(generatedClass.getBytes("UTF-8")); } catch (IOException e) { // TODO add slf4j logger here e.printStackTrace(); return false; } finally { try { if (fos != null) fos.close(); } catch (IOException e) { // don't hide original exception } } return true; } public EntityInfo createEntityInfoFromEntityMetadata(String namespace, EntityMetadata entityMetadata) { FieldInfo keyInfo = null; List<FieldInfo> properties = new ArrayList<FieldInfo>(); for(String propertyName : entityMetadata.getPropertyVocabularyKeySet()) { String type = entityMetadata.getTermValue(propertyName, TermValueType.TERM_NAME); if(entityMetadata.getTermValue(propertyName, TermIdField.TERM_NAME).equals("true")) { keyInfo = new FieldInfo(propertyName, javaType(MetadataOData4j.termValueToEdmType(type)), null); } else { List<String> annotations = new ArrayList<String>(); if(type.equals(TermValueType.TIMESTAMP)) { annotations.add("@Temporal(TemporalType.TIMESTAMP)"); } else if(type.equals(TermValueType.DATE)) { annotations.add("@Temporal(TemporalType.DATE)"); } else if(type.equals(TermValueType.TIME)) { annotations.add("@Temporal(TemporalType.TIME)"); } FieldInfo field = new FieldInfo(propertyName, javaType(MetadataOData4j.termValueToEdmType(type)), annotations); properties.add(field); } } //Check if user has specified the name of the JPA entities String jpaNamespace = System.getProperty("jpaNamespace"); boolean isJpaEntity = (jpaNamespace == null || jpaNamespace.equals(namespace)); return new EntityInfo(entityMetadata.getEntityName(), namespace, keyInfo, properties, new ArrayList<JoinInfo>(), isJpaEntity); } /* * Create a EntityModel object from a Metadata container */ private EntityModel createEntityModelFromMetadata(String modelName, Metadata metadata) { //Create the entity model EntityModel entityModel = new EntityModel(modelName); for (EntityMetadata entityMetadata: metadata.getEntitiesMetadata().values()) { EMEntity emEntity = new EMEntity(entityMetadata.getEntityName()); for(String propertyName : entityMetadata.getPropertyVocabularyKeySet()) { EMProperty emProperty = new EMProperty(propertyName); Vocabulary propertyVoc = entityMetadata.getPropertyVocabulary(propertyName); if(propertyVoc != null) { for(Term term : propertyVoc.getTerms()) { emProperty.addVocabularyTerm(new EMTerm(term.getName(), term.getValue())); } } emEntity.addProperty(emProperty); } entityModel.addEntity(emEntity); } return entityModel; } public static String javaType(EdmType type) { // TODO support complex type keys? assert(type.isSimple()); String javaType = null; if (EdmSimpleType.INT64 == type) { javaType = "Long"; } else if (EdmSimpleType.INT32 == type) { javaType = "Integer"; } else if (EdmSimpleType.INT16 == type) { javaType = "Integer"; } else if (EdmSimpleType.STRING == type) { javaType = "String"; } else if (EdmSimpleType.DATETIME == type) { javaType = "java.util.Date"; } else if (EdmSimpleType.TIME == type) { javaType = "java.util.Date"; } else if (EdmSimpleType.DECIMAL == type) { javaType = "java.math.BigDecimal"; } else if (EdmSimpleType.SINGLE == type) { javaType = "Float"; } else if (EdmSimpleType.DOUBLE == type) { javaType = "Double"; } else if (EdmSimpleType.BOOLEAN == type) { javaType = "Boolean"; } else if (EdmSimpleType.GUID == type) { javaType = "String"; } else if (EdmSimpleType.BINARY == type) { javaType = "String"; } else { // TODO support types other than Long and String throw new RuntimeException("Entity property type " + type.getFullyQualifiedTypeName() + " not supported"); } return javaType; } /* * Create a property with vocabulary term from the Edmx property */ public static EMProperty createEMProperty(EdmProperty property) { EMProperty emProperty = new EMProperty(property.getName()); if(property.isNullable()) { emProperty.addVocabularyTerm(new EMTerm(TermMandatory.TERM_NAME, "true")); } //Set the value type vocabulary term EdmType type = property.getType(); if (type.equals(EdmSimpleType.DATETIME)) { emProperty.addVocabularyTerm(new EMTerm(TermValueType.TERM_NAME, TermValueType.TIMESTAMP)); } else if (type.equals(EdmSimpleType.TIME)) { emProperty.addVocabularyTerm(new EMTerm(TermValueType.TERM_NAME, TermValueType.TIME)); } else if (type.equals(EdmSimpleType.INT64) || type.equals(EdmSimpleType.INT32) || type.equals(EdmSimpleType.INT16)) { emProperty.addVocabularyTerm(new EMTerm(TermValueType.TERM_NAME, TermValueType.INTEGER_NUMBER)); } else if (type.equals(EdmSimpleType.SINGLE) || type.equals(EdmSimpleType.DOUBLE) || type.equals(EdmSimpleType.DECIMAL)) { emProperty.addVocabularyTerm(new EMTerm(TermValueType.TERM_NAME, TermValueType.NUMBER)); } else if (type.equals(EdmSimpleType.BOOLEAN)) { emProperty.addVocabularyTerm(new EMTerm(TermValueType.TERM_NAME, TermValueType.BOOLEAN)); } return emProperty; } protected boolean writeJPAConfiguration(File sourceDir, String generatedPersistenceXML) { FileOutputStream fos = null; try { File metaInfDir = new File(sourceDir.getPath() + "/META-INF"); metaInfDir.mkdirs(); fos = new FileOutputStream(new File(metaInfDir, JPA_CONFIG_FILE)); fos.write(generatedPersistenceXML.getBytes("UTF-8")); } catch (IOException e) { // TODO add slf4j logger here e.printStackTrace(); return false; } finally { try { if (fos != null) fos.close(); } catch (IOException e) { // don't hide original exception } } return true; } protected boolean writeSpringConfiguration(File sourceDir, String filename, String generatedSpringXML) { FileOutputStream fos = null; try { File metaInfDir = new File(sourceDir.getPath() + "/META-INF"); metaInfDir.mkdirs(); File f = new File(metaInfDir, filename); if(!f.exists()) { fos = new FileOutputStream(f); fos.write(generatedSpringXML.getBytes("UTF-8")); } } catch (IOException e) { // TODO add slf4j logger here e.printStackTrace(); return false; } finally { try { if (fos != null) fos.close(); } catch (IOException e) { // don't hide original exception } } return true; } protected boolean writeResponderDML(File sourceDir, String generateResponderDML) { FileOutputStream fos = null; try { File metaInfDir = new File(sourceDir.getPath() + "/META-INF"); metaInfDir.mkdirs(); fos = new FileOutputStream(new File(metaInfDir, RESPONDER_INSERT_FILE)); fos.write(generateResponderDML.getBytes("UTF-8")); } catch (IOException e) { // TODO add slf4j logger here e.printStackTrace(); return false; } finally { try { if (fos != null) fos.close(); } catch (IOException e) { // don't hide original exception } } return true; } protected boolean writeMetadata(File sourceDir, String generatedMetadata) { FileOutputStream fos = null; try { File metaInfDir = new File(sourceDir.getPath()); metaInfDir.mkdirs(); File f = new File(metaInfDir, METADATA_FILE); if(!f.exists()) { fos = new FileOutputStream(f); fos.write(generatedMetadata.getBytes("UTF-8")); } } catch (IOException e) { // TODO add slf4j logger here e.printStackTrace(); return false; } finally { try { if (fos != null) fos.close(); } catch (IOException e) { // don't hide original exception } } return true; } protected boolean writeRimDsl(File sourceDir, String rimDslFilename, String generatedRimDsl) { FileOutputStream fos = null; try { File dir = new File(sourceDir.getPath()); dir.mkdirs(); File f = new File(dir, rimDslFilename); if(!f.exists()) { fos = new FileOutputStream(f); fos.write(generatedRimDsl.getBytes("UTF-8")); } } catch (IOException e) { // TODO add slf4j logger here e.printStackTrace(); return false; } finally { try { if (fos != null) fos.close(); } catch (IOException e) { // don't hide original exception } } return true; } protected boolean writeResponderSettings(File sourceDir, String generateResponderSettings) { FileOutputStream fos = null; try { File metaInfDir = new File(sourceDir.getPath()); metaInfDir.mkdirs(); File f = new File(metaInfDir, RESPONDER_SETTINGS_FILE); if(!f.exists()) { fos = new FileOutputStream(f); fos.write(generateResponderSettings.getBytes("UTF-8")); } } catch (IOException e) { // TODO add slf4j logger here e.printStackTrace(); return false; } finally { try { if (fos != null) fos.close(); } catch (IOException e) { // don't hide original exception } } return true; } /** * Generate a JPA Entity from the provided info * @precondition {@link EntityInfo} non null * @precondition {@link EntityInfo} contain a valid package, class name, key, and fields * @postcondition A valid java class, that may be serialised and compiled, or pushed into * the {@link ClassLoader.defineClass} * @param jpaEntityClass * @return */ public String generateJPAEntityClass(EntityInfo jpaEntityClass) { assert(jpaEntityClass != null); VelocityContext context = new VelocityContext(); context.put("jpaentity", jpaEntityClass); Template t = ve.getTemplate("/JPAEntity.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); return sw.toString(); } /** * Generate the JPA configuration for the provided JPA entities. * @param entitiesInfo * @return */ public String generateJPAConfiguration(List<EntityInfo> entitiesInfo) { VelocityContext context = new VelocityContext(); context.put("entitiesInfo", entitiesInfo); Template t = ve.getTemplate("/jpa-persistence.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); return sw.toString(); } /** * Generate the Spring configuration for the provided resources. */ public String generateSpringConfiguration(String namespace, String modelName, Commands commands) { VelocityContext context = new VelocityContext(); context.put("behaviourClass", namespace + "." + modelName + "Behaviour"); context.put("commands", commands); Template t = ve.getTemplate("/spring-beans.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); return sw.toString(); } /** * Generate the Spring configuration for the provided resources. * @param entityContainerNamespace * @return */ public String generateSpringResourceManagerContext(String entityContainerNamespace) { VelocityContext context = new VelocityContext(); context.put("entityContainerNamespace", entityContainerNamespace); Template t = ve.getTemplate("/resourcemanager-context.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); return sw.toString(); } /** * Generate the responder_insert.sql provided resources. * @return */ public String generateResponderDML(List<EntityInfo> entitiesInfo) { VelocityContext context = new VelocityContext(); context.put("entitiesInfo", entitiesInfo); Template t = ve.getTemplate("/responder_insert.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); return sw.toString(); } /** * Generate the metadata file * @param entityModel The entity model * @return The generated metadata */ public String generateMetadata(EntityModel entityModel) { VelocityContext context = new VelocityContext(); context.put("entityModel", entityModel); Template t = ve.getTemplate("/metadata.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); return sw.toString(); } /** * Generate responder settings * @return */ public String generateResponderSettings(String responderName) { VelocityContext context = new VelocityContext(); context.put("responderName", responderName); Template t = ve.getTemplate("/responder_settings.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); return sw.toString(); } public static void main(String[] args) { boolean ok = true; if (args != null && args.length == 2) { String edmxFilePath = args[0]; String targetDirectoryStr = args[1]; File edmxFile = new File(edmxFilePath); File targetDirectory = new File(targetDirectoryStr); // check our configuration if (!edmxFile.exists()) { System.out.println("EDMX file not found"); ok = false; } if (!targetDirectory.exists() || !targetDirectory.isDirectory()) { System.out.println("Target directory is invalid"); ok = false; } if (ok) { JPAResponderGen rg = new JPAResponderGen(); System.out.println("Writing source and configuration to [" + targetDirectory + "]"); ok = rg.generateArtifacts(new EDMXAdapter(edmxFilePath), targetDirectory, targetDirectory, true); } } else { ok = false; } if (!ok) { System.out.print(usage()); } } public static String usage() { StringBuffer sb = new StringBuffer(); sb.append("\n") .append("Generates an IRIS JPA responder from an EDMX file.\n") .append("\n") .append("java ").append(JPAResponderGen.class.getName()).append(" [EDMX file] [target directory]\n"); return sb.toString(); } /** * Returns a list of default commands * @return */ public static Commands getDefaultCommands() { Commands commands = new Commands(); //Add RIM events commands.addRimEvent("GET", Commands.HTTP_COMMAND_GET); commands.addRimEvent("POST", Commands.HTTP_COMMAND_POST); commands.addRimEvent("PUT", Commands.HTTP_COMMAND_PUT); commands.addRimEvent("DELETE", Commands.HTTP_COMMAND_DELETE); //Add commands commands.addCommand(Commands.GET_SERVICE_DOCUMENT, "com.temenos.interaction.commands.odata.GETMetadataCommand", COMMAND_SERVICE_DOCUMENT, COMMAND_EDM_DATA_SERVICES); commands.addCommand(Commands.GET_METADATA, "com.temenos.interaction.commands.odata.GETMetadataCommand", COMMAND_METADATA, COMMAND_EDM_DATA_SERVICES); commands.addCommand(Commands.GET_EXCEPTION, "com.temenos.interaction.core.command.GETExceptionCommand"); commands.addCommand(Commands.GET_NOOP, "com.temenos.interaction.core.command.NoopGETCommand"); commands.addCommand(Commands.GET_ENTITY, "com.temenos.interaction.commands.odata.GETEntityCommand", COMMAND_METADATA_SOURCE_ODATAPRODUCER); commands.addCommand(Commands.GET_ENTITIES, "com.temenos.interaction.commands.odata.GETEntitiesCommand", COMMAND_METADATA_SOURCE_ODATAPRODUCER); commands.addCommand(Commands.CREATE_ENTITY, "com.temenos.interaction.commands.odata.CreateEntityCommand", COMMAND_METADATA_SOURCE_ODATAPRODUCER); commands.addCommand(Commands.GET_NAV_PROPERTY, "com.temenos.interaction.commands.odata.GETNavPropertyCommand", COMMAND_METADATA_SOURCE_ODATAPRODUCER); commands.addCommand(Commands.UPDATE_ENTITY, "com.temenos.interaction.commands.odata.UpdateEntityCommand", COMMAND_METADATA_SOURCE_ODATAPRODUCER); commands.addCommand(Commands.DELETE_ENTITY, "com.temenos.interaction.commands.odata.DeleteEntityCommand", COMMAND_METADATA_SOURCE_ODATAPRODUCER); return commands; } /* * Add transition properties to entity info */ public static void addNavPropertiesToEntityInfo(EntityInfo entityInfo, InteractionModel interactionModel) { IMResourceStateMachine rsm = interactionModel.findResourceStateMachine(entityInfo.getClazz()); if (rsm != null) { for(IMTransition transition : rsm.getEntityStateTransitions()) { List<FieldInfo> properties = entityInfo.getAllFieldInfos(); List<String> annotations = new ArrayList<String>(); if (transition instanceof IMCollectionStateTransition) { //Transition to collection state //TODO fix reciprocal links //annotations.add("@OneToMany(cascade = CascadeType.ALL, mappedBy = \"" + transition.getTargetStateName() + "\")"); //properties.add(new FieldInfo(transition.getTargetStateName(), "Collection<" + transition.getTargetEntityName() + ">", annotations)); } else if(transition instanceof IMEntityStateTransition){ //Transition to entity state IMEntityStateTransition t = (IMEntityStateTransition) transition; annotations.add("@JoinColumn(name = \"" + t.getLinkProperty() + "\", referencedColumnName = \"" + t.getTargetResourceStateMachine().getMappedEntityProperty() + "\", insertable = false, updatable = false)"); annotations.add("@ManyToOne(optional = false)"); properties.add(new FieldInfo(t.getTargetState().getName(), t.getTargetResourceStateMachine().getEntityName(), annotations)); } } } } }
package com.temenos.interaction.sdk; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; import org.odata4j.edm.EdmAssociation; import org.odata4j.edm.EdmAssociationEnd; import org.odata4j.edm.EdmDataServices; import org.odata4j.edm.EdmEntityType; import org.odata4j.edm.EdmMultiplicity; import org.odata4j.edm.EdmNavigationProperty; import org.odata4j.edm.EdmProperty; import org.odata4j.edm.EdmSimpleType; import org.odata4j.edm.EdmType; import org.odata4j.format.xml.EdmxFormatParser; import org.odata4j.internal.InternalUtil; import org.odata4j.stax2.XMLEventReader2; import com.temenos.interaction.sdk.interaction.IMResourceStateMachine; import com.temenos.interaction.sdk.interaction.InteractionModel; import com.temenos.interaction.sdk.util.ReferentialConstraintParser; /** * This class is the main entry point to the IRIS SDK. It is a simple front end * for generating JPA classes, and associated configuration files. With these * classes and config files in place we can then fill a mock database with * appropriate values and enable IRIS to respond to resource requests from User * Agents. * */ public class JPAResponderGen { private final static String JPA_CONFIG_FILE = "persistence.xml"; private final static String SPRING_CONFIG_FILE = "spring-beans.xml"; private final static String RESPONDER_INSERT_FILE = "responder_insert.sql"; private final static String BEHAVIOUR_CLASS_FILE = "Behaviour.java"; /* * create a new instance of the engine */ VelocityEngine ve = new VelocityEngine(); public JPAResponderGen() { // load .vm templates using classloader ve.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath." + VelocityEngine.RESOURCE_LOADER + ".class", ClasspathResourceLoader.class.getName()); ve.init(); } /** * Generate JPA responder artifacts. Including JPA classes, persistence.xml, and DML bootstrapping. * @param is * @param srcOutputPath * @param configOutputPath * @return */ public boolean generateArtifacts(String edmxFile, File srcOutputPath, File configOutputPath) { InputStream isEdmx; try { isEdmx = new FileInputStream(edmxFile); } catch (FileNotFoundException e) { return false; } XMLEventReader2 reader = InternalUtil.newXMLEventReader(new BufferedReader(new InputStreamReader(isEdmx))); EdmDataServices ds = new EdmxFormatParser().parseMetadata(reader); boolean ok = true; List<ResourceInfo> resourcesInfo = new ArrayList<ResourceInfo>(); //Make sure we have at least one entity container if(ds.getSchemas().size() == 0 || ds.getSchemas().get(0).getEntityContainers().size() == 0) { return false; } // generate JPA classes for (EdmEntityType t : ds.getEntityTypes()) { EntityInfo entityInfo = createEntityInfoFromEdmEntityType(t); //Generate JPA class if(entityInfo.isJpaEntity()) { String fqOutputDir = srcOutputPath.getPath() + "/" + entityInfo.getPackageAsPath(); new File(fqOutputDir).mkdirs(); if (!writeClass(formClassFilename(srcOutputPath.getPath(), entityInfo), generateJPAEntityClass(entityInfo))) { return false; } } //Entity resource String resourcePath = "GET+/" + entityInfo.getClazz() + "({id})"; String commandType = "com.temenos.interaction.commands.odata.GETEntityCommand"; resourcesInfo.add(new ResourceInfo(resourcePath, entityInfo, commandType)); //Collection resource EntityInfo entityFeedInfo = createEntityInfoFromEdmEntityType(t); entityFeedInfo.setFeedEntity(); //This is a feed of OEntities and should not exist as a JPA entity resourcePath = "GET+/" + entityFeedInfo.getClazz(); commandType = "com.temenos.interaction.commands.odata.GETEntitiesCommand"; resourcesInfo.add(new ResourceInfo(resourcePath, entityFeedInfo, commandType)); } //Create interaction model InteractionModel interactionModel = new InteractionModel(); for (EdmEntityType entityType : ds.getEntityTypes()) { //ResourceStateMachine with one collection and one resource entity state String entityName = entityType.getName(); String collectionStateName = entityName.toLowerCase() + "s"; String entityStateName = entityName.toLowerCase(); String mappedEntityProperty = entityType.getKeys().size() > 0 ? entityType.getKeys().get(0) : "id"; IMResourceStateMachine rsm = new IMResourceStateMachine(entityName, collectionStateName, entityStateName, mappedEntityProperty); interactionModel.addResourceStateMachine(rsm); } //Add navigation properties to interaction model for (EdmEntityType entityType : ds.getEntityTypes()) { String entityName = entityType.getName(); IMResourceStateMachine rsm = interactionModel.findResourceStateMachine(entityName); //Use navigation properties to define state transitions if(entityType.getNavigationProperties() != null) { for (EdmNavigationProperty np : entityType.getNavigationProperties()) { EdmAssociationEnd targetEnd = np.getToRole(); boolean isTargetCollection = targetEnd.getMultiplicity().equals(EdmMultiplicity.MANY); EdmEntityType targetEntityType = targetEnd.getType(); String targetEntityName = targetEntityType.getName(); IMResourceStateMachine targetRsm = interactionModel.findResourceStateMachine(targetEntityName); EdmAssociation association = np.getRelationship(); String linkProperty = ReferentialConstraintParser.getLinkProperty(association.getName(), edmxFile); //Reciprocal link state name String reciprocalLinkState = ""; for(EdmNavigationProperty npTarget : targetEntityType.getNavigationProperties()) { String targetNavPropTargetEntityName = npTarget.getToRole().getType().getName(); if(targetNavPropTargetEntityName.equals(entityName)) { reciprocalLinkState = npTarget.getName(); } } rsm.addTransition(targetEntityName, linkProperty, np.getName(), isTargetCollection, reciprocalLinkState, targetRsm); } } } // generate persistence.xml if (!writeJPAConfiguration(configOutputPath, generateJPAConfiguration(resourcesInfo))) { ok = false; } // generate spring-beans.xml String entityContainerNamespace = ds.getSchemas().get(0).getEntityContainers().get(0).getName(); if (!writeSpringConfiguration(configOutputPath, generateSpringConfiguration(resourcesInfo, entityContainerNamespace, interactionModel))) { ok = false; } // generate responder insert if (!writeResponderDML(configOutputPath, generateResponderDML(resourcesInfo))) { ok = false; } // generate Behaviour class String behaviourFilePath = srcOutputPath + "/" + entityContainerNamespace.replace(".", "/") + "/" + BEHAVIOUR_CLASS_FILE; if (!writeBehaviourClass(behaviourFilePath, generateBehaviourClass(entityContainerNamespace, interactionModel))) { ok = false; } return ok; } /** * Utility method to form class filename. * @param srcTargetDir * @param entityInfo * @return */ public static String formClassFilename(String srcTargetDir, EntityInfo entityInfo) { return srcTargetDir + "/" + entityInfo.getPackageAsPath() + "/" + entityInfo.getClazz() + ".java"; } private boolean writeClass(String classFileName, String generatedClass) { FileOutputStream fos = null; try { fos = new FileOutputStream(classFileName); fos.write(generatedClass.getBytes("UTF-8")); } catch (IOException e) { // TODO add slf4j logger here e.printStackTrace(); return false; } finally { try { if (fos != null) fos.close(); } catch (IOException e) { // don't hide original exception } } return true; } public EntityInfo createEntityInfoFromEdmEntityType(EdmType type) { if (!(type instanceof EdmEntityType)) return null; EdmEntityType entityType = (EdmEntityType) type; // think OData4j only support single keys at the moment FieldInfo keyInfo = null; if (entityType.getKeys().size() > 0) { String keyName = entityType.getKeys().get(0); EdmType key = null; for (EdmProperty e : entityType.getProperties()) { if (e.getName().equals(keyName)) { key = e.getType(); } } keyInfo = new FieldInfo(keyName, javaType(key), null); } List<FieldInfo> properties = new ArrayList<FieldInfo>(); for (EdmProperty property : entityType.getProperties()) { // add additional configuration by annotations List<String> annotations = new ArrayList<String>(); if (property.getType().equals(EdmSimpleType.DATETIME)) { annotations.add("@Temporal(TemporalType.TIMESTAMP)"); } else if (property.getType().equals(EdmSimpleType.TIME)) { annotations.add("@Temporal(TemporalType.TIME)"); } FieldInfo field = new FieldInfo(property.getName(), javaType(property.getType()), annotations); properties.add(field); } //Check if user has specified the name of the JPA entities String jpaNamespace = System.getProperty("jpaNamespace"); boolean isJpaEntity = (jpaNamespace == null || jpaNamespace.equals(entityType.getNamespace())); return new EntityInfo(entityType.getName(), entityType.getNamespace(), keyInfo, properties, isJpaEntity); } private String javaType(EdmType type) { // TODO support complex type keys? assert(type.isSimple()); String javaType = null; if (EdmSimpleType.INT64 == type) { javaType = "Long"; } else if (EdmSimpleType.INT32 == type) { javaType = "Integer"; } else if (EdmSimpleType.INT16 == type) { javaType = "Integer"; } else if (EdmSimpleType.STRING == type) { javaType = "String"; } else if (EdmSimpleType.DATETIME == type) { javaType = "java.util.Date"; } else if (EdmSimpleType.TIME == type) { javaType = "java.util.Date"; } else if (EdmSimpleType.DECIMAL == type) { javaType = "java.math.BigDecimal"; } else if (EdmSimpleType.GUID == type) { javaType = "String"; } else if (EdmSimpleType.BINARY == type) { javaType = "String"; } else { // TODO support types other than Long and String throw new RuntimeException("Entity property type " + type.getFullyQualifiedTypeName() + " not supported"); } return javaType; } private boolean writeJPAConfiguration(File sourceDir, String generatedPersistenceXML) { FileOutputStream fos = null; try { File metaInfDir = new File(sourceDir.getPath() + "/META-INF"); metaInfDir.mkdirs(); fos = new FileOutputStream(new File(metaInfDir, JPA_CONFIG_FILE)); fos.write(generatedPersistenceXML.getBytes("UTF-8")); } catch (IOException e) { // TODO add slf4j logger here e.printStackTrace(); return false; } finally { try { if (fos != null) fos.close(); } catch (IOException e) { // don't hide original exception } } return true; } private boolean writeSpringConfiguration(File sourceDir, String generatedSpringXML) { FileOutputStream fos = null; try { File metaInfDir = new File(sourceDir.getPath() + "/META-INF"); metaInfDir.mkdirs(); fos = new FileOutputStream(new File(metaInfDir, SPRING_CONFIG_FILE)); fos.write(generatedSpringXML.getBytes("UTF-8")); } catch (IOException e) { // TODO add slf4j logger here e.printStackTrace(); return false; } finally { try { if (fos != null) fos.close(); } catch (IOException e) { // don't hide original exception } } return true; } private boolean writeResponderDML(File sourceDir, String generatedSpringXML) { FileOutputStream fos = null; try { File metaInfDir = new File(sourceDir.getPath() + "/META-INF"); metaInfDir.mkdirs(); fos = new FileOutputStream(new File(metaInfDir, RESPONDER_INSERT_FILE)); fos.write(generatedSpringXML.getBytes("UTF-8")); } catch (IOException e) { // TODO add slf4j logger here e.printStackTrace(); return false; } finally { try { if (fos != null) fos.close(); } catch (IOException e) { // don't hide original exception } } return true; } private boolean writeBehaviourClass(String path, String generatedBehaviourClass) { FileOutputStream fos = null; try { fos = new FileOutputStream(new File(path)); fos.write(generatedBehaviourClass.getBytes("UTF-8")); } catch (IOException e) { // TODO add slf4j logger here e.printStackTrace(); return false; } finally { try { if (fos != null) fos.close(); } catch (IOException e) { // don't hide original exception } } return true; } /** * Generate a JPA Entity from the provided info * @precondition {@link EntityInfo} non null * @precondition {@link EntityInfo} contain a valid package, class name, key, and fields * @postcondition A valid java class, that may be serialised and compiled, or pushed into * the {@link ClassLoader.defineClass} * @param jpaEntityClass * @return */ public String generateJPAEntityClass(EntityInfo jpaEntityClass) { assert(jpaEntityClass != null); VelocityContext context = new VelocityContext(); context.put("jpaentity", jpaEntityClass); Template t = ve.getTemplate("/JPAEntity.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); return sw.toString(); } /** * Generate the JPA configuration for the provided JPA entities. * @param resourcesInfo * @return */ public String generateJPAConfiguration(List<ResourceInfo> resourcesInfo) { VelocityContext context = new VelocityContext(); context.put("resourcesInfo", resourcesInfo); Template t = ve.getTemplate("/persistence.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); return sw.toString(); } /** * Generate the Spring configuration for the provided resources. * @param resourcesInfo * @return */ public String generateSpringConfiguration(List<ResourceInfo> resourcesInfo, String entityContainerNamespace, InteractionModel interactionModel) { VelocityContext context = new VelocityContext(); context.put("resourcesInfo", resourcesInfo); context.put("behaviourClass", entityContainerNamespace + ".Behaviour"); context.put("interactionModel", interactionModel); Template t = ve.getTemplate("/spring-beans.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); return sw.toString(); } /** * Generate the responder_insert.sql provided resources. * @param resourcesInfo * @return */ public String generateResponderDML(List<ResourceInfo> resourcesInfo) { VelocityContext context = new VelocityContext(); context.put("resourcesInfo", resourcesInfo); Template t = ve.getTemplate("/responder_insert.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); return sw.toString(); } /** * Generate the behaviour class. * @param resourcesInfo * @return */ public String generateBehaviourClass(String entityContainerNamespace, InteractionModel interactionModel) { VelocityContext context = new VelocityContext(); context.put("behaviourNamespace", entityContainerNamespace); context.put("interactionModel", interactionModel); Template t = ve.getTemplate("/behaviour.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); return sw.toString(); } public static void main(String[] args) { boolean ok = true; if (args != null && args.length == 2) { String edmxFilePath = args[0]; String targetDirectoryStr = args[1]; File edmxFile = new File(edmxFilePath); File targetDirectory = new File(targetDirectoryStr); // check our configuration if (!edmxFile.exists()) { System.out.println("EDMX file not found"); ok = false; } if (!targetDirectory.exists() || !targetDirectory.isDirectory()) { System.out.println("Target directory is invalid"); ok = false; } if (ok) { JPAResponderGen rg = new JPAResponderGen(); System.out.println("Writing source and configuration to [" + targetDirectory + "]"); ok = rg.generateArtifacts(edmxFilePath, targetDirectory, targetDirectory); } } else { ok = false; } if (!ok) { System.out.print(usage()); } } public static String usage() { StringBuffer sb = new StringBuffer(); sb.append("\n") .append("Generates an IRIS JPA responder from an EDMX file.\n") .append("\n") .append("java ").append(JPAResponderGen.class.getName()).append(" [EDMX file] [target directory]\n"); return sb.toString(); } }
package com.java110.oa.bmo.oaWorkflowForm.impl; import com.alibaba.fastjson.JSONObject; import com.java110.core.factory.GenerateCodeFactory; import com.java110.dto.oaWorkflow.OaWorkflowDto; import com.java110.dto.oaWorkflowData.OaWorkflowDataDto; import com.java110.dto.oaWorkflowForm.OaWorkflowFormDto; import com.java110.dto.user.UserDto; import com.java110.entity.audit.AuditUser; import com.java110.intf.common.IOaWorkflowUserInnerServiceSMO; import com.java110.intf.oa.IOaWorkflowDataInnerServiceSMO; import com.java110.intf.oa.IOaWorkflowFormInnerServiceSMO; import com.java110.intf.oa.IOaWorkflowInnerServiceSMO; import com.java110.intf.user.IUserInnerServiceSMO; import com.java110.oa.bmo.oaWorkflowForm.IGetOaWorkflowFormBMO; import com.java110.utils.util.Assert; import com.java110.utils.util.BeanConvertUtil; import com.java110.utils.util.DateUtil; import com.java110.utils.util.StringUtil; import com.java110.vo.ResultVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Service("getOaWorkflowFormBMOImpl") public class GetOaWorkflowFormBMOImpl implements IGetOaWorkflowFormBMO { @Autowired private IOaWorkflowFormInnerServiceSMO oaWorkflowFormInnerServiceSMOImpl; @Autowired private IOaWorkflowInnerServiceSMO oaWorkflowInnerServiceSMOImpl; @Autowired private IUserInnerServiceSMO userInnerServiceSMOImpl; @Autowired private IOaWorkflowUserInnerServiceSMO oaWorkflowUserInnerServiceSMOImpl; @Autowired private IOaWorkflowDataInnerServiceSMO oaWorkflowDataInnerServiceSMOImpl; /** * @param oaWorkflowFormDto * @return */ public ResponseEntity<String> get(OaWorkflowFormDto oaWorkflowFormDto) { int count = oaWorkflowFormInnerServiceSMOImpl.queryOaWorkflowFormsCount(oaWorkflowFormDto); List<OaWorkflowFormDto> oaWorkflowFormDtos = null; if (count > 0) { oaWorkflowFormDtos = oaWorkflowFormInnerServiceSMOImpl.queryOaWorkflowForms(oaWorkflowFormDto); } else { oaWorkflowFormDtos = new ArrayList<>(); } ResultVo resultVo = new ResultVo((int) Math.ceil((double) count / (double) oaWorkflowFormDto.getRow()), count, oaWorkflowFormDtos); ResponseEntity<String> responseEntity = new ResponseEntity<String>(resultVo.toString(), HttpStatus.OK); return responseEntity; } /** * {"schemaVersion":1,"exporter":{"name":"form-js","version":"0.1.0"}, * "components":[{"text":"# Text","type":"text"},{"key":"textfield2","label":"","type":"textfield"},{"key":"number2","label":"Number","type":"number"}, * {"key":"checkbox2","label":"Checkbox","type":"checkbox"}, * {"key":"radio2","label":"Radio","type":"radio","values":[{"label":"Value","value":"value"}]}, * {"key":"select2","label":"Select","type":"select","values":[{"label":"Value","value":"value"}]}, * {"text":"# Text","type":"text"},{"key":"textarea1","label":"","type":"textarea"}, * {"key":"textdate1","label":"","type":"textdate"}, * {"key":"textdatetime1","label":"","type":"textdatetime"}, * {"action":"submit","key":"button1","label":"Button","type":"button"}],"type":"default"} * * @param paramIn * @return */ @Override public ResponseEntity<String> queryOaWorkflowFormData(Map paramIn) { OaWorkflowFormDto oaWorkflowFormDto = new OaWorkflowFormDto(); oaWorkflowFormDto.setFlowId(paramIn.get("flowId").toString()); oaWorkflowFormDto.setStoreId(paramIn.get("storeId").toString()); oaWorkflowFormDto.setRow(1); oaWorkflowFormDto.setPage(1); List<OaWorkflowFormDto> oaWorkflowFormDtos = oaWorkflowFormInnerServiceSMOImpl.queryOaWorkflowForms(oaWorkflowFormDto); Assert.listOnlyOne(oaWorkflowFormDtos, ""); paramIn.put("tableName", oaWorkflowFormDtos.get(0).getTableName()); int count = oaWorkflowFormInnerServiceSMOImpl.queryOaWorkflowFormDataCount(paramIn); List<Map> datas = null; if (count > 0) { datas = oaWorkflowFormInnerServiceSMOImpl.queryOaWorkflowFormDatas(paramIn); } else { datas = new ArrayList<>(); } ResultVo resultVo = new ResultVo((int) Math.ceil((double) count / (int) paramIn.get("row")), count, datas); ResponseEntity<String> responseEntity = new ResponseEntity<String>(resultVo.toString(), HttpStatus.OK); return responseEntity; } /** * * * @param reqJson * @return */ @Override public ResponseEntity<String> saveOaWorkflowFormData(JSONObject reqJson) { OaWorkflowFormDto oaWorkflowFormDto = new OaWorkflowFormDto(); oaWorkflowFormDto.setFlowId(reqJson.get("flowId").toString()); oaWorkflowFormDto.setStoreId(reqJson.get("storeId").toString()); oaWorkflowFormDto.setRow(1); oaWorkflowFormDto.setPage(1); List<OaWorkflowFormDto> oaWorkflowFormDtos = oaWorkflowFormInnerServiceSMOImpl.queryOaWorkflowForms(oaWorkflowFormDto); Assert.listOnlyOne(oaWorkflowFormDtos, ""); OaWorkflowDto oaWorkflowDto = new OaWorkflowDto(); oaWorkflowDto.setStoreId(reqJson.getString("storeId")); oaWorkflowDto.setFlowId(reqJson.getString("flowId")); List<OaWorkflowDto> oaWorkflowDtos = oaWorkflowInnerServiceSMOImpl.queryOaWorkflows(oaWorkflowDto); Assert.listOnlyOne(oaWorkflowDtos, ""); if (!OaWorkflowDto.STATE_COMPLAINT.equals(oaWorkflowDtos.get(0).getState())) { throw new IllegalArgumentException(oaWorkflowDtos.get(0).getFlowName() + ""); } if (StringUtil.isEmpty(oaWorkflowDtos.get(0).getProcessDefinitionKey())) { throw new IllegalArgumentException(oaWorkflowDtos.get(0).getFlowName() + ""); } UserDto userDto = new UserDto(); userDto.setUserId(reqJson.getString("userId")); List<UserDto> userDtos = userInnerServiceSMOImpl.getUsers(userDto); Assert.listOnlyOne(userDtos, ""); reqJson.put("id", GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_flowId)); reqJson.put("state", "1001"); reqJson.put("createUserId", reqJson.getString("userId")); reqJson.put("createUserName", userDtos.get(0).getUserName()); reqJson.put("tableName", oaWorkflowFormDtos.get(0).getTableName()); int flag = oaWorkflowFormInnerServiceSMOImpl.saveOaWorkflowFormData(reqJson); if (flag < 1) { throw new IllegalArgumentException(""); } reqJson.put("processDefinitionKey", oaWorkflowDtos.get(0).getProcessDefinitionKey()); oaWorkflowUserInnerServiceSMOImpl.startProcess(reqJson); return ResultVo.success(); } /** * * * @param paramIn * @return */ @Override public ResponseEntity<String> queryOaWorkflowUserTaskFormData(JSONObject paramIn) { OaWorkflowDto oaWorkflowDto = new OaWorkflowDto(); oaWorkflowDto.setStoreId(paramIn.getString("storeId")); oaWorkflowDto.setFlowId(paramIn.getString("flowId")); List<OaWorkflowDto> oaWorkflowDtos = oaWorkflowInnerServiceSMOImpl.queryOaWorkflows(oaWorkflowDto); Assert.listOnlyOne(oaWorkflowDtos, ""); OaWorkflowFormDto oaWorkflowFormDto = new OaWorkflowFormDto(); oaWorkflowFormDto.setFlowId(paramIn.get("flowId").toString()); oaWorkflowFormDto.setStoreId(paramIn.get("storeId").toString()); oaWorkflowFormDto.setRow(1); oaWorkflowFormDto.setPage(1); List<OaWorkflowFormDto> oaWorkflowFormDtos = oaWorkflowFormInnerServiceSMOImpl.queryOaWorkflowForms(oaWorkflowFormDto); Assert.listOnlyOne(oaWorkflowFormDtos, ""); AuditUser auditUser = new AuditUser(); auditUser.setProcessDefinitionKey(oaWorkflowDtos.get(0).getProcessDefinitionKey()); auditUser.setFlowId(paramIn.getString("flowId")); auditUser.setUserId(paramIn.getString("userId")); auditUser.setStoreId(paramIn.getString("storeId")); auditUser.setPage(paramIn.getInteger("page")); auditUser.setRow(paramIn.getInteger("row")); long count = oaWorkflowUserInnerServiceSMOImpl.getUserTaskCount(auditUser); List<JSONObject> datas = null; if (count > 0) { datas = oaWorkflowUserInnerServiceSMOImpl.getUserTasks(auditUser); freshFormData(datas, paramIn, oaWorkflowFormDtos.get(0)); } else { datas = new ArrayList<>(); } ResultVo resultVo = new ResultVo((int) Math.ceil((double) count / (double) paramIn.getInteger("row")), count, datas); ResponseEntity<String> responseEntity = new ResponseEntity<String>(resultVo.toString(), HttpStatus.OK); return responseEntity; } /** * * * @param paramIn * @return */ @Override public ResponseEntity<String> queryOaWorkflowUserHisTaskFormData(JSONObject paramIn) { OaWorkflowDto oaWorkflowDto = new OaWorkflowDto(); oaWorkflowDto.setStoreId(paramIn.getString("storeId")); oaWorkflowDto.setFlowId(paramIn.getString("flowId")); List<OaWorkflowDto> oaWorkflowDtos = oaWorkflowInnerServiceSMOImpl.queryOaWorkflows(oaWorkflowDto); Assert.listOnlyOne(oaWorkflowDtos, ""); OaWorkflowFormDto oaWorkflowFormDto = new OaWorkflowFormDto(); oaWorkflowFormDto.setFlowId(paramIn.get("flowId").toString()); oaWorkflowFormDto.setStoreId(paramIn.get("storeId").toString()); oaWorkflowFormDto.setRow(1); oaWorkflowFormDto.setPage(1); List<OaWorkflowFormDto> oaWorkflowFormDtos = oaWorkflowFormInnerServiceSMOImpl.queryOaWorkflowForms(oaWorkflowFormDto); Assert.listOnlyOne(oaWorkflowFormDtos, ""); OaWorkflowDataDto oaWorkflowDataDto = new OaWorkflowDataDto(); oaWorkflowDataDto.setFlowId(paramIn.getString("flowId")); oaWorkflowDataDto.setStaffId(paramIn.getString("userId")); oaWorkflowDataDto.setStoreId(paramIn.getString("storeId")); oaWorkflowDataDto.setPage(paramIn.getInteger("page")); oaWorkflowDataDto.setRow(paramIn.getInteger("row")); oaWorkflowDataDto.setHis("Y"); long count = oaWorkflowDataInnerServiceSMOImpl.queryOaWorkflowDatasCount(oaWorkflowDataDto); List<JSONObject> datas = new ArrayList<>(); if (count > 0) { List<OaWorkflowDataDto> oaWorkflowDataDtos = oaWorkflowDataInnerServiceSMOImpl.queryOaWorkflowDatas(oaWorkflowDataDto); for (OaWorkflowDataDto oaWorkflowDataDto1 : oaWorkflowDataDtos) { datas.add(BeanConvertUtil.beanCovertJson(oaWorkflowDataDto1)); } freshFormData(datas, paramIn, oaWorkflowFormDtos.get(0)); } ResultVo resultVo = new ResultVo((int) Math.ceil((double) count / (double) paramIn.getInteger("row")), count, datas); ResponseEntity<String> responseEntity = new ResponseEntity<String>(resultVo.toString(), HttpStatus.OK); return responseEntity; } @Override public ResponseEntity<String> auditOaWorkflow(JSONObject reqJson) { OaWorkflowDto oaWorkflowDto = new OaWorkflowDto(); oaWorkflowDto.setStoreId(reqJson.getString("storeId")); oaWorkflowDto.setFlowId(reqJson.getString("flowId")); List<OaWorkflowDto> oaWorkflowDtos = oaWorkflowInnerServiceSMOImpl.queryOaWorkflows(oaWorkflowDto); Assert.listOnlyOne(oaWorkflowDtos, ""); OaWorkflowFormDto oaWorkflowFormDto = new OaWorkflowFormDto(); oaWorkflowFormDto.setFlowId(reqJson.get("flowId").toString()); oaWorkflowFormDto.setStoreId(reqJson.get("storeId").toString()); oaWorkflowFormDto.setRow(1); oaWorkflowFormDto.setPage(1); List<OaWorkflowFormDto> oaWorkflowFormDtos = oaWorkflowFormInnerServiceSMOImpl.queryOaWorkflowForms(oaWorkflowFormDto); Assert.listOnlyOne(oaWorkflowFormDtos, ""); Map paramMap = new HashMap(); paramMap.put("storeId", reqJson.getString("storeId")); paramMap.put("id", reqJson.getString("id")); paramMap.put("tableName", oaWorkflowFormDtos.get(0).getTableName()); paramMap.put("page", 1); paramMap.put("row", 1); List<Map> formDatas = oaWorkflowFormInnerServiceSMOImpl.queryOaWorkflowFormDatas(paramMap); Assert.listOnlyOne(formDatas, ""); reqJson.put("startUserId", formDatas.get(0).get("create_user_id")); if ("1100".equals(reqJson.getString("auditCode"))) { reqJson.put("nextUserId", reqJson.getString("staffId")); boolean isLastTask = oaWorkflowUserInnerServiceSMOImpl.completeTask(reqJson); if (isLastTask) { reqJson.put("state", "1005"); } else { reqJson.put("state", "1002"); } reqJson.put("tableName", oaWorkflowFormDtos.get(0).getTableName()); oaWorkflowFormInnerServiceSMOImpl.updateOaWorkflowFormData(reqJson); } else if ("1300".equals(reqJson.getString("auditCode"))) { reqJson.put("nextUserId", reqJson.getString("staffId")); oaWorkflowUserInnerServiceSMOImpl.changeTaskToOtherUser(reqJson); reqJson.put("state", "1004"); reqJson.put("tableName", oaWorkflowFormDtos.get(0).getTableName()); oaWorkflowFormInnerServiceSMOImpl.updateOaWorkflowFormData(reqJson); } else if ("1200".equals(reqJson.getString("auditCode")) || "1400".equals(reqJson.getString("auditCode")) ) { oaWorkflowUserInnerServiceSMOImpl.goBackTask(reqJson); reqJson.put("state", "1003"); reqJson.put("tableName", oaWorkflowFormDtos.get(0).getTableName()); oaWorkflowFormInnerServiceSMOImpl.updateOaWorkflowFormData(reqJson); } else { throw new IllegalArgumentException(""); } return ResultVo.success(); } @Override public ResponseEntity<String> getNextTask(JSONObject reqJson) { List<JSONObject> tasks = oaWorkflowUserInnerServiceSMOImpl.nextAllNodeTaskList(reqJson); return ResultVo.createResponseEntity(tasks); } @Override public ResponseEntity<String> queryOaWorkflowUser(JSONObject paramIn) { OaWorkflowDto oaWorkflowDto = new OaWorkflowDto(); oaWorkflowDto.setStoreId(paramIn.getString("storeId")); oaWorkflowDto.setFlowId(paramIn.getString("flowId")); List<OaWorkflowDto> oaWorkflowDtos = oaWorkflowInnerServiceSMOImpl.queryOaWorkflows(oaWorkflowDto); Assert.listOnlyOne(oaWorkflowDtos, ""); OaWorkflowFormDto oaWorkflowFormDto = new OaWorkflowFormDto(); oaWorkflowFormDto.setFlowId(paramIn.get("flowId").toString()); oaWorkflowFormDto.setStoreId(paramIn.get("storeId").toString()); oaWorkflowFormDto.setRow(1); oaWorkflowFormDto.setPage(1); List<OaWorkflowFormDto> oaWorkflowFormDtos = oaWorkflowFormInnerServiceSMOImpl.queryOaWorkflowForms(oaWorkflowFormDto); Assert.listOnlyOne(oaWorkflowFormDtos, ""); OaWorkflowDataDto oaWorkflowDataDto = new OaWorkflowDataDto(); oaWorkflowDataDto.setFlowId(paramIn.getString("flowId")); oaWorkflowDataDto.setBusinessKey(paramIn.getString("id")); oaWorkflowDataDto.setStoreId(paramIn.getString("storeId")); oaWorkflowDataDto.setPage(paramIn.getInteger("page")); oaWorkflowDataDto.setRow(paramIn.getInteger("row")); long count = oaWorkflowDataInnerServiceSMOImpl.queryOaWorkflowDatasCount(oaWorkflowDataDto); List<JSONObject> datas = new ArrayList<>(); if (count > 0) { List<OaWorkflowDataDto> oaWorkflowDataDtos = oaWorkflowDataInnerServiceSMOImpl.queryOaWorkflowDatas(oaWorkflowDataDto); for (OaWorkflowDataDto oaWorkflowDataDto1 : oaWorkflowDataDtos) { datas.add(BeanConvertUtil.beanCovertJson(oaWorkflowDataDto1)); } freshFormData(datas, paramIn, oaWorkflowFormDtos.get(0)); } ResultVo resultVo = new ResultVo((int) Math.ceil((double) count / (double) paramIn.getInteger("row")), count, datas); ResponseEntity<String> responseEntity = new ResponseEntity<String>(resultVo.toString(), HttpStatus.OK); return responseEntity; } /** * * * @param datas */ private void freshFormData(List<JSONObject> datas, JSONObject paramIn, OaWorkflowFormDto oaWorkflowFormDto) { List<String> ids = new ArrayList<>(); List<String> userIds = new ArrayList<>(); for (JSONObject data : datas) { ids.add(data.getString("id")); userIds.add(data.getString("staffId")); } if (ids.size() < 1) { return; } Map paramMap = new HashMap(); paramMap.put("storeId", paramIn.getString("storeId")); paramMap.put("ids", ids.toArray(new String[ids.size()])); paramMap.put("tableName", oaWorkflowFormDto.getTableName()); paramMap.put("page", 1); paramMap.put("row", ids.size()); List<Map> formDatas = oaWorkflowFormInnerServiceSMOImpl.queryOaWorkflowFormDatas(paramMap); long duration = 0L; for (JSONObject data : datas) { for (Map form : formDatas) { if (data.getString("id").equals(form.get("id"))) { data.putAll(form); } } if (data.containsKey("startTime") && data.containsKey("endTime")) { try { if (data.getString("endTime") == null) { duration = DateUtil.getCurrentDate().getTime() - DateUtil.getDateFromString(data.getString("startTime"), DateUtil.DATE_FORMATE_STRING_A).getTime(); } else { duration = DateUtil.getDateFromString(data.getString("endTime"), DateUtil.DATE_FORMATE_STRING_A).getTime() - DateUtil.getDateFromString(data.getString("startTime"), DateUtil.DATE_FORMATE_STRING_A).getTime(); } } catch (Exception e) { duration = 0; } data.put("duration", getCostTime(duration)); } } if (userIds.size() < 1) { return; } UserDto userDto = new UserDto(); userDto.setUserIds(userIds.toArray(new String[userIds.size()])); List<UserDto> userDtos = userInnerServiceSMOImpl.getStaffs(userDto); for (JSONObject data : datas) { for (UserDto userDto1 : userDtos) { if(data.getString("staffId").equals(userDto1.getUserId())){ data.put("orgName",userDto1.getOrgName()); data.put("staffName",userDto1.getUserName()); } } } } public String getCostTime(Long time) { if (time == null) { return "00:00"; } long hours = time / (1000 * 60 * 60); long minutes = (time - hours * (1000 * 60 * 60)) / (1000 * 60); String diffTime = ""; if (minutes < 10) { diffTime = hours + ":0" + minutes; } else { diffTime = hours + ":" + minutes; } return diffTime; } }
package org.fosstrak.tdt; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.MarshalException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.ValidationException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.epcglobalinc.tdt.EpcTagDataTranslation; import org.epcglobalinc.tdt.Field; import org.epcglobalinc.tdt.GEPC64; import org.epcglobalinc.tdt.GEPC64Entry; import org.epcglobalinc.tdt.Level; import org.epcglobalinc.tdt.LevelTypeList; import org.epcglobalinc.tdt.ModeList; import org.epcglobalinc.tdt.Option; import org.epcglobalinc.tdt.PadDirectionList; import org.epcglobalinc.tdt.Rule; import org.epcglobalinc.tdt.Scheme; import org.w3c.dom.Document; import org.xml.sax.SAXException; /** * * This class provides methods for translating an electronic product code (EPC) * between various levels of representation including BINARY, TAG_ENCODING, * PURE_IDENTITY and LEGACY formats. An additional output level ONS_HOSTNAME may * be defined for some coding schemes. * * @author Mark Harrison [University of Cambridge] - mark.harrison@cantab.net * @author James Brusey * @author Jochen Mader - jochen@pramari.com * @author Christian Floerkemeier */ public class TDTEngine { // - Class/Member Variables -/ /** * prefix_tree_map is a map of levels to prefix trees. Each prefix tree is a * Trie structure (see wikipedia) that is useful for quickly finding a * matching prefix. */ private Map<LevelTypeList, PrefixTree<PrefixMatch>> prefix_tree_map = new HashMap<LevelTypeList, PrefixTree<PrefixMatch>>(); /** * HashMap gs1cpi is an associative array providing a lookup between either * a GS1 Company Prefix and the corresponding integer-based Company Prefix * Index, where one of these has been registered for use with 64-bit EPCs - * or the reverse lookup from Company Prefix Index to GS1 Company Prefix. * Note that this is an optimization to avoid having to do an xpath trawl * through the CPI table each time. */ private HashMap<String, String> gs1cpi = new HashMap<String, String>(); /** The gepc64 table xml. */ private String GEPC64xml; // - Constructors -/ /** * Legacy constructor for a new Tag Data Translation engine. * * @param confdir * the string value of the path to a configuration directory * consisting of two subdirectories, <code>schemes</code> and * <code>auxiliary</code>. * * <p> * When the class TDTEngine is constructed, the path to a local * directory must be specified, by passing it as a single string * parameter to the constructor method (without any trailing * slash or file separator). e.g. * <code><pre>TDTEngine engine = new TDTEngine("/opt/TDT");</pre></code> * </p> * <p> * The specified directory must contain two subdirectories named * auxiliary and schemes. The Tag Data Translation definition * files for the various coding schemes should be located inside * the subdirectory called <code>schemes</code>. Any auxiliary * lookup files (such as <code>ManagerTranslation.xml</code>) * should be located inside the subdirectory called * <code>auxiliary</code>. * * Files within the schemes directory ending in <code>.xml</code> * are read in and unmarshalled using JAXB. */ @Deprecated public TDTEngine(String confdir) throws FileNotFoundException, MarshalException, ValidationException, TDTException { try { Unmarshaller unmar = getUnmarshaller(); URL scheme = new URL(confdir + "/schemes/"); URL aux = new URL(confdir + "/auxiliary/ManagerTranslation.xml"); Set<URL> schemes = new HashSet<URL>(); schemes.add(scheme); URLConnection urlcon = scheme.openConnection(); urlcon.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(urlcon .getInputStream())); String line; for (; (line = in.readLine()) != null;) { if (line.endsWith(".xml")) { loadEpcTagDataTranslation(unmar, new URL(scheme.toString() + line)); } } loadGEPC64Table(unmar, aux); } catch (MalformedURLException e) { throw new FileNotFoundException(e.getMessage()); } catch (IOException e) { throw new FileNotFoundException(e.getMessage()); } catch (JAXBException e) { throw new MarshalException(e); } } /** * Constructor for a new Tag Data Translation engine. This constructor uses * the schemes included on the classpath in a directory called schemes * (or from within the jar). The ManagerTranslation.xml file is loaded from a directory * called auxiliary on the classpath. All schemes used need to be listed in a file schemes/schemes.list * * @throws IOException * thrown if the url is unreachable * @throws JAXBException * thrown if the schemes could not be parsed */ public TDTEngine() throws IOException, JAXBException { Unmarshaller unmar = getUnmarshaller(); URL auxiliary = this.getClass().getClassLoader().getResource( "auxiliary/ManagerTranslation.xml"); URL schemes = TDTEngine.class.getClassLoader().getResource( "schemes/schemes.list"); URLConnection urlcon = schemes.openConnection(); urlcon.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(urlcon .getInputStream())); String line; for (; (line = in.readLine()) != null;) { loadEpcTagDataTranslation(unmar, TDTEngine.class.getClassLoader() .getResource("schemes/" + line)); } loadGEPC64Table(unmar, auxiliary); } /** * Constructor for a new Tag Data Translation engine. All files are * unmarshalled using JAXB. * * @param auxiliary * URL to the auxiliary file containing a GEPC64Table * @param schemes * directory containing the schemes, all files ending in xml are * read and parsed * @throws IOException * thrown if the url is unreachable * @throws JAXBException * thrown if the files could not be parsed */ public TDTEngine(URL auxiliary, URL schemes) throws IOException, JAXBException { Unmarshaller unmar = getUnmarshaller(); URLConnection urlcon = schemes.openConnection(); urlcon.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(urlcon .getInputStream())); String line; for (; (line = in.readLine()) != null;) { if (line.endsWith(".xml")) { loadEpcTagDataTranslation(unmar, new URL(schemes.toString() + line)); } } loadGEPC64Table(unmar, auxiliary); } /** * Constructor for a new Tag Data Translation engine. All files are * unmarshalled using JAXB. * * @param auxiliary * URL to the auxiliary file containing a GEPC64Table * @param schemes * set containing several urls pointing to directories containing * the schemes. All files ending in xml are read and parsed. * @param absolute * true if the given URLs are absolute * @throws IOException * thrown if the url is unreachable * @throws JAXBException * thrown if the files could not be parsed */ public TDTEngine(URL auxiliary, Set<URL> schemes, boolean absolute) throws JAXBException, IOException { Unmarshaller unmar = getUnmarshaller(); for (URL scheme : schemes) { if (absolute) { loadEpcTagDataTranslation(unmar, scheme); continue; } URLConnection urlcon = scheme.openConnection(); urlcon.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(urlcon .getInputStream())); String line; for (; (line = in.readLine()) != null;) { if (line.endsWith(".xml")) { loadEpcTagDataTranslation(unmar, new URL(schemes.toString() + line)); } } } loadGEPC64Table(unmar, auxiliary); } /** * Creates the unmarshaller. * * @return * @throws JAXBException */ private Unmarshaller getUnmarshaller() throws JAXBException { JAXBContext context = JAXBContext.newInstance( EpcTagDataTranslation.class, GEPC64.class, GEPC64Entry.class); return context.createUnmarshaller(); } /** * Load an xml file from the given url and unmarshal it into an * EPCTagDataTranslation. * * @param unmar * @param schemeUrl * @throws IOException * @throws JAXBException */ private void loadEpcTagDataTranslation(Unmarshaller unmar, URL schemeUrl) throws IOException, JAXBException { URLConnection urlcon = schemeUrl.openConnection(); urlcon.connect(); // xml doesn't have enough info for jaxb to figure out // the // classname, so we are doing explicit loading JAXBElement<EpcTagDataTranslation> el = unmar.unmarshal( new StreamSource(urlcon.getInputStream()), EpcTagDataTranslation.class); EpcTagDataTranslation tdt = el.getValue(); initFromTDT(tdt); } /** * Load an xml file from the given url and unmarshal it into a GEPC64Table. * * @param unmar * @param auxiliary * @throws IOException * @throws JAXBException */ private void loadGEPC64Table(Unmarshaller unmar, URL auxiliary) throws IOException, JAXBException { URLConnection urlcon = auxiliary.openConnection(); urlcon.connect(); // load the GEPC64Table JAXBElement<GEPC64> el = unmar.unmarshal(new StreamSource(urlcon .getInputStream()), GEPC64.class); GEPC64 cpilookup = el.getValue(); for (GEPC64Entry entry : cpilookup.getEntry()) { String comp = entry.getCompanyPrefix(); String indx = entry.getIndex().toString(); gs1cpi.put(indx, comp); gs1cpi.put(comp, indx); } } // - Methods -/ private class PrefixMatch { private Scheme s; private Level level; public PrefixMatch(Scheme s, Level level) { this.s = s; this.level = level; } public Scheme getScheme() { return s; } public Level getLevel() { return level; } } /** initialise various indices */ private void initFromTDT(EpcTagDataTranslation tdt) { for (Scheme ss : tdt.getScheme()) { // create an index so that we can find a scheme based on tag length for (Level level : ss.getLevel()) { String s = level.getPrefixMatch(); if (s != null) { // insert into prefix tree according to level type. PrefixTree<PrefixMatch> prefix_tree = prefix_tree_map .get(level.getType()); if (prefix_tree == null) { prefix_tree = new PrefixTree<PrefixMatch>(); prefix_tree_map.put(level.getType(), prefix_tree); } prefix_tree.insert(s, new PrefixMatch(ss, level)); } } } } /** * Given an input string, and optionally a tag length, find a scheme / level * with a matching prefix and tag length. */ private PrefixMatch findPrefixMatch(String input, String tagLength) { List<PrefixMatch> match_list = new ArrayList<PrefixMatch>(); for (PrefixTree<PrefixMatch> tree : prefix_tree_map.values()) { List<PrefixMatch> list = tree.search(input); if (!list.isEmpty()) { if (tagLength == null) match_list.addAll(list); else { for (PrefixMatch match : list) { if (match.getScheme().getTagLength().equals(tagLength)) match_list.add(match); } } } } if (match_list.isEmpty()) throw new TDTException( "No schemes or levels matched the input value"); else if (match_list.size() > 1) throw new TDTException( "More than one scheme/level matched the input value"); else return match_list.get(0); } /** * Given an input string, level, and optionally a tag length, find a * matching prefix. */ private PrefixMatch findPrefixMatch(String input, String tagLength, LevelTypeList level_type) { List<PrefixMatch> match_list = new ArrayList<PrefixMatch>(); PrefixTree<PrefixMatch> tree = prefix_tree_map.get(level_type); assert tree != null; List<PrefixMatch> list = tree.search(input); if (!list.isEmpty()) { if (tagLength == null) match_list.addAll(list); else { for (PrefixMatch match : list) if (match.getScheme().getTagLength() == tagLength) match_list.add(match); } } if (match_list.isEmpty()) throw new TDTException( "No schemes or levels matched the input value"); else if (match_list.size() > 1) throw new TDTException( "More than one scheme/level matched the input value"); else return match_list.get(0); } /** * Translates the input string of a specified input level to a specified * outbound level of the same coding scheme. For example, the input string * value may be a tag-encoding URI and the outbound level specified by * string outboundlevel may be BINARY, in which case the return value is a * binary representation expressed as a string. * * <p> * Note that this version of the method requires that the user specify the * input level, rather than searching for it. However it still automatically * finds the scheme used. * </p> * * @param input * input tag coding * @param inputLevel * level such as BINARY, or TAG_ENCODING. * @param tagLength * tag length such as VALUE_64 or VALUE_96. * @param inputParameters * a map with any additional properties. * @param outputLevel * required output level. * @return output tag coding */ public String convert(String input, LevelTypeList inputLevel, String tagLength, Map<String, String> inputParameters, LevelTypeList outputLevel) { PrefixMatch match = findPrefixMatch(input, tagLength, inputLevel); return convertLevel(match.getScheme(), match.getLevel(), input, inputParameters, outputLevel); } /** * The convert method translates a String input to a specified outbound * level of the same coding scheme. For example, the input string value may * be a tag-encoding URI and the outbound level specified by string * outboundlevel may be BINARY, in which case the return value is a binary * representation expressed as a string. * * @param input * the identifier to be converted. * @param inputParameters * additional parameters which need to be provided because they * cannot always be determined from the input value alone. * Examples include the taglength, companyprefixlength and filter * values. * @param outputLevel * the outbound level required for the ouput. Permitted values * include BINARY, TAG_ENCODING, PURE_IDENTITY, LEGACY and * ONS_HOSTNAME. * @return the identifier converted to the output level. */ public String convert(String input, Map<String, String> inputParameters, LevelTypeList outputLevel) { String tagLength = null; if (inputParameters.containsKey("taglength")) { // in principle, the user should provide a // TagLengthList object in the parameter list. String s = inputParameters.get("taglength"); tagLength = s; } PrefixMatch match = findPrefixMatch(input, tagLength); return convertLevel(match.getScheme(), match.getLevel(), input, inputParameters, outputLevel); } /** * convert from a particular scheme / level */ private String convertLevel(Scheme tdtscheme, Level tdtlevel, String input, Map<String, String> inputParameters, LevelTypeList outboundlevel) { String outboundstring; Map<String, String> extraparams = // new NoisyMap (new HashMap<String, String>(inputParameters)); // get the scheme's option key, which is the name of a // parameter whose value is matched to the option key of the // level. String optionkey = tdtscheme.getOptionKey(); String optionValue = extraparams.get(optionkey); // the name of a parameter which allows the appropriate option // to be selected // now consider the various options within the scheme and // level for each option element inside the level, check // whether the pattern attribute matches as a regular // expression String matchingOptionKey = null; Option matchingOption = null; Matcher prefixMatcher = null; for (Option opt : tdtlevel.getOption()) { if (optionValue == null || optionValue.equals(opt.getOptionKey())) { // possible match Matcher matcher = Pattern.compile(opt.getPattern()).matcher( input); if (matcher.matches()) { if (prefixMatcher != null) throw new TDTException("Multiple patterns matched"); prefixMatcher = matcher; matchingOptionKey = opt.getOptionKey(); matchingOption = opt; } } } if (prefixMatcher == null) throw new TDTException("No patterns matched"); optionValue = matchingOptionKey; for (Field field : matchingOption.getField()) { BigInteger seq = field.getSeq(); String strfieldname = field.getName(); String strfieldvalue = prefixMatcher.group(seq.intValue()); // System.out.println(" processing field " + strfieldname + " = '" // + strfieldvalue + "'"); if (field.getCompaction() == null) { // if compaction is null, treat field as an integer if (field.getCharacterSet() != null) { // if the character set // is specified Matcher charsetmatcher = Pattern.compile( "^" + field.getCharacterSet() + "$").matcher( strfieldvalue); if (!charsetmatcher.matches()) { throw new TDTException( "field " + strfieldname + " (" + strfieldvalue + ") does not conform to the allowed character set (" + field.getCharacterSet() + ") "); } } BigInteger bigvalue = null; if (tdtlevel.getType() == LevelTypeList.BINARY) { // if the // input was // BINARY bigvalue = new BigInteger(strfieldvalue, 2); extraparams.put(strfieldname, bigvalue.toString()); } else { if (field.getDecimalMinimum() != null || field.getDecimalMaximum() != null) bigvalue = new BigInteger(strfieldvalue); extraparams.put(strfieldname, strfieldvalue); } if (field.getDecimalMinimum() != null) { // if the decimal // minimum is // specified BigInteger bigmin = new BigInteger(field .getDecimalMinimum()); if (bigvalue.compareTo(bigmin) == -1) { // throw an // exception if the // field value is // less than the // decimal minimum throw new TDTException("field " + strfieldname + " (" + bigvalue + ") is less than DecimalMinimum (" + field.getDecimalMinimum() + ") allowed"); } } if (field.getDecimalMaximum() != null) { // if the decimal // maximum is // specified BigInteger bigmax = new BigInteger(field .getDecimalMaximum()); if (bigvalue.compareTo(bigmax) == 1) { // throw an excpetion // if the field // value is greater // than the decimal // maximum throw new TDTException("field " + strfieldname + " (" + bigvalue + ") is greater than DecimalMaximum (" + field.getDecimalMaximum() + ") allowed"); } } // after extracting the field, it may be necessary to pad it. padField(extraparams, field); } else { // compaction is specified - interpret binary as a string value // using a truncated byte per character String compaction = field.getCompaction(); PadDirectionList padDir = field.getPadDir(); String padchar = field.getPadChar(); String s; if ("5-bit".equals(compaction)) // "5-bit" s = bin2uppercasefive(strfieldvalue); else if ("6-bit".equals(compaction)) // 6-bit s = bin2alphanumsix(strfieldvalue); else if ("7-bit".equals(compaction)) // 7-bit s = bin2asciiseven(strfieldvalue); else if ("8-bit".equals(compaction)) // 8-bit s = bin2bytestring(strfieldvalue); else throw new Error("unsupported compaction method " + compaction); extraparams.put(strfieldname, stripPadChar(s, padDir, padchar)); } } // for each field; /** * the EXTRACT rules are performed after parsing the input, in order to * determine additional fields that are to be derived from the fields * obtained by the pattern match process */ int seq = 0; for (Rule tdtrule : tdtlevel.getRule()) { if (tdtrule.getType() == ModeList.EXTRACT) { assert seq < tdtrule.getSeq().intValue() : "Rule out of sequence order"; seq = tdtrule.getSeq().intValue(); processRules(extraparams, tdtrule); } } /** * Now we need to consider the corresponding output level and output * option. The scheme must remain the same, as must the value of * optionkey (to select the corresponding option element nested within * the required outbound level) */ Level tdtoutlevel = findLevel(tdtscheme, outboundlevel); Option tdtoutoption = findOption(tdtoutlevel, optionValue); /** * the FORMAT rules are performed before formatting the output, in order * to determine additional fields that are required for preparation of * the outbound format */ seq = 0; for (Rule tdtrule : tdtoutlevel.getRule()) { if (tdtrule.getType() == ModeList.FORMAT) { assert seq < tdtrule.getSeq().intValue() : "Rule out of sequence order"; seq = tdtrule.getSeq().intValue(); processRules(extraparams, tdtrule); } } /** * Now we need to ensure that all fields required for the outbound * grammar are suitably padded etc. processPadding takes care of firstly * padding the non-binary fields if padChar and padDir, length are * specified then (if necessary) converting to binary and padding the * binary representation to the left with zeros if the bit string is has * fewer bits than the bitLength attribute specifies. N.B. TDTv1.1 will * be more specific about bit-level padding rather than assuming that it * is always to the left with the zero bit. */ // System.out.println(" prior to processPadding, " + extraparams); for (Field field : tdtoutoption.getField()) { // processPadding(extraparams, field, outboundlevel, tdtoutoption); padField(extraparams, field); if (outboundlevel == LevelTypeList.BINARY) binaryPadding(extraparams, field); } /** * Construct the output from the specified grammar (in ABNF format) * together with the field values stored in inputparams */ outboundstring = buildGrammar(tdtoutoption.getGrammar(), extraparams); // System.out.println("final extraparams = " + extraparams); // System.out.println("returned " + outboundstring); return outboundstring; } /** * * Converts a binary string into a large integer (numeric string) */ public String bin2dec(String binary) { BigInteger dec = new BigInteger(binary, 2); return dec.toString(); } /** * * Converts a large integer (numeric string) to a binary string */ public String dec2bin(String decimal) { // TODO: required? if (decimal == null) { decimal = "1"; } BigInteger bin = new BigInteger(decimal); return bin.toString(2); } /** * * Converts a hexadecimal string to a binary string */ public String hex2bin(String hex) { BigInteger bin = new BigInteger(hex.toLowerCase(), 16); return bin.toString(2); } /** * * Converts a binary string to a hexadecimal string */ public String bin2hex(String binary) { BigInteger hex = new BigInteger(binary, 2); return hex.toString(16).toUpperCase(); } /** * Returns a string built using a particular grammar. Single-quotes strings * are counted as literal strings, whereas all other strings appearing in * the grammar require substitution with the corresponding value from the * extraparams hashmap. */ private String buildGrammar(String grammar, Map<String, String> extraparams) { StringBuilder outboundstring = new StringBuilder(); String[] fields = Pattern.compile("\\s+").split(grammar); for (int i = 0; i < fields.length; i++) { if (fields[i].substring(0, 1).equals("'")) { outboundstring.append(fields[i].substring(1, fields[i].length() - 1)); } else { outboundstring.append(extraparams.get(fields[i])); } } return outboundstring.toString(); } /** * * Converts the value of a specified fieldname from the extraparams map into * binary, either handling it as a large integer or taking into account the * compaction of each ASCII byte that is specified in the TDT definition * file for that particular field */ private String fieldToBinary(Field field, Map<String, String> extraparams) { // really need an index to find field number given fieldname; String fieldname = field.getName(); String value = extraparams.get(fieldname); String compaction = field.getCompaction(); if (compaction == null) { value = dec2bin(value); } else { if ("5-bit".equals(compaction)) { value = uppercasefive2bin(value); } else if ("6-bit".equals(compaction)) { value = alphanumsix2bin(value); } else if ("7-bit".equals(compaction)) { value = asciiseven2bin(value); } else if ("8-bit".equals(compaction)) { value = bytestring2bin(value); } else throw new Error("Unsupported compaction " + compaction); } return value; } /** * pad a value according the field definition. */ private void padField(Map<String, String> extraparams, Field field) { String name = field.getName(); String value = extraparams.get(name); PadDirectionList padDir = field.getPadDir(); int requiredLength = 0; if (field.getLength() != null) { requiredLength = field.getLength().intValue(); } // assert value != null; if (value == null) return; String padCharString = field.getPadChar(); // if no pad char specified, don't attempt padding if (padCharString == null) return; assert padCharString.length() > 0; char padChar = padCharString.charAt(0); StringBuilder buf = new StringBuilder(requiredLength); if (padDir == PadDirectionList.LEFT) { for (int i = 0; i < requiredLength - value.length(); i++) buf.append(padChar); buf.append(value); } else if (padDir == PadDirectionList.RIGHT) { buf.append(value); for (int i = 0; i < requiredLength - value.length(); i++) buf.append(padChar); } assert buf.length() == requiredLength; if (requiredLength != value.length()) { // System.out.println(" updated " + name + " to '" + buf + "'"); extraparams.put(name, buf.toString()); } /* * else { StringBuilder mybuf = new StringBuilder(); for (int i = 0; i < * value.length(); i++) { if (i > 0) mybuf.append(','); * mybuf.append('\''); mybuf.append(value.charAt(i)); * mybuf.append('\''); } * * * System.out.println(" field " + name + " not padded as " + * mybuf.toString() + " is already " + requiredLength + * " characters long"); } */ } /** * If the outbound level is BINARY, convert the string field to binary, then * pad to the left with the appropriate number of zero bits to reach a * number of bits specified by the bitLength attribute of the TDT definition * file. */ private void binaryPadding(Map<String, String> extraparams, Field tdtfield) { String fieldname = tdtfield.getName(); int reqbitlength = tdtfield.getBitLength().intValue(); String value; String binaryValue = fieldToBinary(tdtfield, extraparams); if (binaryValue.length() < reqbitlength) { int extraBitLength = reqbitlength - binaryValue.length(); StringBuilder zeroPaddedBinaryValue = new StringBuilder(""); for (int i = 0; i < extraBitLength; i++) { zeroPaddedBinaryValue.append("0"); } zeroPaddedBinaryValue.append(binaryValue); value = zeroPaddedBinaryValue.toString(); } else { if (binaryValue.length() > reqbitlength) throw new TDTException("Binary value [" + binaryValue + "] for field " + fieldname + " exceeds maximum allowed " + reqbitlength + " bits. Decimal value was " + extraparams.get(fieldname)); value = binaryValue; } extraparams.put(fieldname, value); } /** * Removes leading or trailing characters equal to padchar from the * start/end of the string specified as the first parameter. The second * parameter specified the stripping direction as "LEFT" or "RIGHT" and the * third parameter specifies the character to be stripped. */ private String stripPadChar(String field, PadDirectionList paddir, String padchar) { String rv; if (paddir == null || padchar == null) rv = field; else { String pattern; if (paddir == PadDirectionList.RIGHT) pattern = "[" + padchar + "]+$"; else // if (paddir == PadDirectionList.LEFT) pattern = "^[" + padchar + "]+"; rv = field.replaceAll(pattern, ""); } return rv; } /** * * Adds additional entries to the extraparams hashmap by processing various * rules defined in the TDT definition files. Typically used for string * processing functions, lookup in tables, calculation of check digits etc. */ private void processRules(Map<String, String> extraparams, Rule tdtrule) { String tdtfunction = tdtrule.getFunction(); int openbracket = tdtfunction.indexOf("("); assert openbracket != -1; String params = tdtfunction.substring(openbracket + 1, tdtfunction .length() - 1); String rulename = tdtfunction.substring(0, openbracket); String[] parameter = params.split(","); String newfieldname = tdtrule.getNewFieldName(); // System.out.println(tdtfunction + " " + parameter[0] + " " + // extraparams.get(parameter[0])); /** * Stores in the hashmap extraparams the value obtained from a lookup in * a specified XML table. * * The first parameter is the given value already known. This is denoted * as $1 in the corresponding XPath expression * * The second parameter is the string filename of the table which must * be present in the auxiliary subdirectory * * The third parameter is the column in which the supplied input value * should be sought * * The fourth parameter is the column whose value should be read for the * corresponding row, in order to obtain the result of the lookup. * * The rule in the definition file may contain an XPath expression and a * URL where the table may be obtained. */ if (rulename.equals("TABLELOOKUP")) { // parameter[0] is given value // parameter[1] is table // parameter[2] is input column supplied // parameter[3] is output column required assert parameter.length == 4 : "incorrect number of parameters to tablelookup " + params; if (parameter[1].equals("tdt64bitcpi")) { String s = extraparams.get(parameter[0]); assert s != null : tdtfunction + " when " + parameter[0] + " is null"; String t = gs1cpi.get(s); assert t != null : "gs1cpi[" + s + "] is null"; assert newfieldname != null; extraparams.put(newfieldname, t); // extraparams.put(newfieldname, // gs1cpi.get(extraparams.get(parameter[0]))); } else { // JPB! the following is untested String tdtxpath = tdtrule.getTableXPath(); String tdttableurl = tdtrule.getTableURL(); String tdtxpathsub = tdtxpath.replaceAll("\\$1", extraparams .get(parameter[0])); extraparams.put(newfieldname, xpathlookup( "ManagerTranslation.xml", tdtxpathsub)); } } /** * Stores the length of the specified string under the new fieldname * specified by the corresponding rule of the definition file. */ if (rulename.equals("LENGTH")) { assert extraparams.get(parameter[0]) != null : tdtfunction + " when " + parameter[0] + " is null"; if (extraparams.get(parameter[0]) != null) { extraparams.put(newfieldname, Integer.toString(extraparams.get( parameter[0]).length())); } } /** * Stores a GS1 check digit in the extraparams hashmap, keyed under the * new fieldname specified by the corresponding rule of the definition * file. */ if (rulename.equals("GS1CHECKSUM")) { assert extraparams.get(parameter[0]) != null : tdtfunction + " when " + parameter[0] + " is null"; if (extraparams.get(parameter[0]) != null) { extraparams.put(newfieldname, gs1checksum(extraparams .get(parameter[0]))); } } /** * Obtains a substring of the string provided as the first parameter. If * only a single second parameter is specified, then this is considered * as the start index and all characters from the start index onwards * are stored in the extraparams hashmap under the key named * 'newfieldname' in the corresponding rule of the definition file. If a * second and third parameter are specified, then the second parameter * is the start index and the third is the length of characters * required. A substring consisting characters from the start index up * to the required length of characters is stored in the extraparams * hashmap, keyed under the new fieldname specified by the corresponding * rule of the defintion file. */ if (rulename.equals("SUBSTR")) { assert extraparams.get(parameter[0]) != null : tdtfunction + " when " + parameter[0] + " is null"; if (parameter.length == 2) { if (extraparams.get(parameter[0]) != null) { int start = getIntValue(parameter[1], extraparams); if (start >= 0) { extraparams.put(newfieldname, extraparams.get( parameter[0]).substring(start)); } } } if (parameter.length == 3) { // need to check that this variation is // correct - c.f. Perl substr assert extraparams.get(parameter[0]) != null : tdtfunction + " when " + parameter[0] + " is null"; if (extraparams.get(parameter[0]) != null) { int start = getIntValue(parameter[1], extraparams); int end = getIntValue(parameter[2], extraparams); if ((start >= 0) && (end >= 0)) { extraparams.put(newfieldname, extraparams.get( parameter[0]).substring(start, start + end)); } } } } /** * Concatenates specified string parameters together. Literal values * must be enclosed within single or double quotes or consist of * unquoted digits. Other unquoted strings are considered as fieldnames * and the corresponding value from the extraparams hashmap are * inserted. The result of the concatenation (and substitution) of the * strings is stored as a new entry in the extraparams hashmap, keyed * under the new fieldname specified by the rule. */ if (rulename.equals("CONCAT")) { StringBuilder buffer = new StringBuilder(); for (int p1 = 0; p1 < parameter.length; p1++) { Matcher matcher = Pattern.compile("\"(.*?)\"|'(.*?)'|[0-9]") .matcher(parameter[p1]); if (matcher.matches()) { buffer.append(parameter[p1]); } else { assert extraparams.get(parameter[p1]) != null : tdtfunction + " when " + parameter[p1] + " is null"; if (extraparams.get(parameter[p1]) != null) { buffer.append(extraparams.get(parameter[p1])); } } } extraparams.put(newfieldname, buffer.toString()); } } /** * * Returns the value of a specified fieldname from the specified hashmap and * returns an integer value or throws an exception if the value is not an * integer */ private int getIntValue(String fieldname, Map<String, String> extraparams) { Matcher checkint = Pattern.compile("^\\d+$").matcher(fieldname); int rv; if (checkint.matches()) { rv = Integer.parseInt(fieldname); } else { if (extraparams.containsKey(fieldname)) { rv = Integer.parseInt(extraparams.get(fieldname)); } else { rv = -1; throw new TDTException("No integer value for " + fieldname + " can be found - check extraparams"); } } return rv; } /** * * Performs an XPATH lookup in an xml document. The document has been loaded * into a private member. The XPATH expression is supplied as the second * string parameter The return value is of type string e.g. this is * currently used primarily for looking up the Company Prefix Index for * encoding a GS1 Company Prefix into a 64-bit EPC tag * */ private String xpathlookup(String xml, String expression) { try { // Parse the XML as a W3C document. DocumentBuilder builder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document document = builder.parse(GEPC64xml); XPath xpath = XPathFactory.newInstance().newXPath(); String rv = (String) xpath.evaluate(expression, document, XPathConstants.STRING); return rv; } catch (ParserConfigurationException e) { System.err.println("ParserConfigurationException caught..."); e.printStackTrace(); return null; } catch (XPathExpressionException e) { System.err.println("XPathExpressionException caught..."); e.printStackTrace(); return null; } catch (SAXException e) { System.err.println("SAXException caught..."); e.printStackTrace(); return null; } catch (IOException e) { System.err.println("IOException caught..."); e.printStackTrace(); return null; } } // auxiliary functions /** * * Converts a binary string input into a byte string, using 8-bits per * character byte */ private String bytestring2bin(String bytestring) { String binary; StringBuilder buffer = new StringBuilder(""); int len = bytestring.length(); byte[] bytes = bytestring.getBytes(); for (int i = 0; i < len; i++) { buffer.append(padBinary(dec2bin(Integer.toString(bytes[i])), 8)); } binary = buffer.toString(); return binary; } /** * * Converts a byte string input into a binary string, using 8-bits per * character byte */ private String bin2bytestring(String binary) { String bytestring; StringBuilder buffer = new StringBuilder(""); int len = binary.length(); for (int i = 0; i < len; i += 8) { int j = Integer.parseInt(bin2dec(padBinary(binary.substring(i, i + 8), 8))); buffer.append((char) j); } bytestring = buffer.toString(); return bytestring; } /** * * Converts an ASCII string input into a binary string, using 7-bit * compaction of each ASCII byte */ private String asciiseven2bin(String asciiseven) { String binary; StringBuilder buffer = new StringBuilder(""); int len = asciiseven.length(); byte[] bytes = asciiseven.getBytes(); for (int i = 0; i < len; i++) { buffer.append(padBinary(dec2bin(Integer.toString(bytes[i] % 128)), 8).substring(1, 8)); } binary = buffer.toString(); return binary; } /** * * Converts a binary string input into an ASCII string output, assuming that * 7-bit compaction was used */ private String bin2asciiseven(String binary) { String asciiseven; StringBuilder buffer = new StringBuilder(""); int len = binary.length(); for (int i = 0; i < len; i += 7) { int j = Integer.parseInt(bin2dec(padBinary(binary.substring(i, i + 7), 8))); buffer.append((char) j); } asciiseven = buffer.toString(); return asciiseven; } /** * Converts an alphanumeric string input into a binary string, using 6-bit * compaction of each ASCII byte */ private String alphanumsix2bin(String alphanumsix) { String binary; StringBuilder buffer = new StringBuilder(""); int len = alphanumsix.length(); byte[] bytes = alphanumsix.getBytes(); for (int i = 0; i < len; i++) { buffer .append(padBinary(dec2bin(Integer.toString(bytes[i] % 64)), 8).substring(2, 8)); } binary = buffer.toString(); return binary; } /** * * Converts a binary string input into a character string output, assuming * that 6-bit compaction was used */ private String bin2alphanumsix(String binary) { String alphanumsix; StringBuilder buffer = new StringBuilder(""); int len = binary.length(); for (int i = 0; i < len; i += 6) { int j = Integer.parseInt(bin2dec(padBinary(binary.substring(i, i + 6), 8))); if (j < 32) { j += 64; } buffer.append((char) j); } alphanumsix = buffer.toString(); return alphanumsix; } /** * Converts an upper case character string input into a binary string, using * 5-bit compaction of each ASCII byte */ private String uppercasefive2bin(String uppercasefive) { String binary; StringBuilder buffer = new StringBuilder(""); int len = uppercasefive.length(); byte[] bytes = uppercasefive.getBytes(); for (int i = 0; i < len; i++) { buffer .append(padBinary(dec2bin(Integer.toString(bytes[i] % 32)), 8).substring(3, 8)); } binary = buffer.toString(); return binary; } /** * * Converts a binary string input into a character string output, assuming * that 5-bit compaction was used */ private String bin2uppercasefive(String binary) { String uppercasefive; StringBuilder buffer = new StringBuilder(""); int len = binary.length(); for (int i = 0; i < len; i += 5) { int j = Integer.parseInt(bin2dec(padBinary(binary.substring(i, i + 5), 8))); buffer.append((char) (j + 64)); } uppercasefive = buffer.toString(); return uppercasefive; } /** * Pads a binary value supplied as a string first parameter to the left with * leading zeros in order to reach a required number of bits, as expressed * by the second parameter, reqlen. Returns a string value corresponding to * the binary value left padded to the required number of bits. */ private String padBinary(String binary, int reqlen) { String rv; int l = binary.length(); int pad = (reqlen - (l % reqlen)) % reqlen; StringBuilder buffer = new StringBuilder(""); for (int i = 0; i < pad; i++) { buffer.append("0"); } buffer.append(binary); rv = buffer.toString(); return rv; } /** * Calculates the check digit for a supplied input string (assuming that the * check digit will be the digit immediately following the supplied input * string). GS1 (formerly EAN.UCC) check digit calculation methods are used. */ private String gs1checksum(String input) { int checksum; int weight; int total = 0; int len = input.length(); int d; for (int i = 0; i < len; i++) { if (i % 2 == 0) { weight = -3; } else { weight = -1; } d = Integer.parseInt(input.substring(len - 1 - i, len - i)); total += weight * d; } checksum = (10 + total % 10) % 10; return Integer.toString(checksum); } /** * find a level by its type in a scheme. This involves iterating through the * list of levels. The main reason for doing it this way is to avoid being * dependent on the order in which the levels are coded in the xml, which is * not explicitly constrained. */ private Level findLevel(Scheme scheme, LevelTypeList levelType) { Level level = null; for (Level lev : scheme.getLevel()) { if (lev.getType() == levelType) { level = lev; break; } } if (level == null) throw new Error("Couldn't find type " + levelType + " in scheme " + scheme); return level; } /** * find a option by its type in a scheme. This involves iterating through * the list of options. The main reason for doing it this way is to avoid * being dependent on the order in which the options are coded in the xml, * which is not explicitly constrained. */ private Option findOption(Level level, String optionKey) { Option option = null; for (Option opt : level.getOption()) { if (opt.getOptionKey().equals(optionKey)) { option = opt; break; } } if (option == null) throw new Error("Couldn't find option for " + optionKey + " in level " + level); return option; } }
package org.geotools.gis; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.util.HashSet; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JMenu; import javax.swing.JMenuBar; import org.geotools.data.FileDataStore; import org.geotools.data.FileDataStoreFinder; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.map.FeatureLayer; import org.geotools.map.Layer; import org.geotools.map.MapContent; import org.geotools.map.event.MapLayerListEvent; import org.geotools.map.event.MapLayerListListener; import org.geotools.styling.BasicPolygonStyle; import org.geotools.styling.Style; import org.geotools.swing.JMapFrame; import org.geotools.swing.action.SafeAction; import org.geotools.swing.data.JFileDataStoreChooser; import org.opengis.filter.identity.Identifier; import org.opengis.geometry.Envelope; public class MapViewer { public MapContent map; public JMapFrame show; public SelectionTool selectionTool = new SelectionTool(); public MapViewer() { map = new MapContent(); show = new JMapFrame(map); JButton btnAddLayer = new JButton(""); btnAddLayer.setToolTipText("Add new layer"); btnAddLayer.setIcon(new ImageIcon(MapViewer.class.getResource("/icons/import.png"))); btnAddLayer.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { addLayerFromFile(); } catch (Exception e1) { e1.printStackTrace() ;System.out.println("Can't open file"); } } }); JButton btnData = new JButton(""); btnData.setToolTipText("Data tables"); btnData.setIcon(new ImageIcon(MapViewer.class.getResource("/icons/data.png"))); btnData.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { App.dataTables.setVisible(true); } }); JButton btnSelect = new JButton(""); btnSelect.setToolTipText("Select objects"); btnSelect.setIcon(new ImageIcon(MapViewer.class.getResource("/org/geotools/swing/icons/pointer.png"))); btnSelect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { show.getMapPane().setCursorTool(selectionTool); } }); JButton btnZoomSelected = new JButton(""); btnZoomSelected.setToolTipText("Zooms to selected objects"); btnZoomSelected.setIcon(new ImageIcon(MapViewer.class.getResource("/icons/zoom.png"))); btnZoomSelected.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Envelope envelope = selectionTool.getSelectedEnvelope(); if (null != envelope) { show.getMapPane().setDisplayArea(envelope); } } }); JButton btnClear = new JButton(""); btnClear.setToolTipText("Clear selected features"); btnClear.setIcon(new ImageIcon(MapViewer.class.getResource("/icons/clear.png"))); btnClear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectionTool.clearSelection(); } }); show.enableStatusBar(true); show.enableToolBar(true); show.enableLayerTable(true); show.setTitle("GIS"); show.setExtendedState(JMapFrame.MAXIMIZED_BOTH); // maximize the window show.getToolBar().addSeparator(); show.getToolBar().add(btnAddLayer); show.getToolBar().add(btnData); show.getToolBar().add(btnClear); show.getToolBar().remove(0); show.getToolBar().add(btnSelect, 0); show.getToolBar().add(btnZoomSelected, 1); map.addMapLayerListListener(new MapLayerListListener() { @Override public void layerRemoved(MapLayerListEvent event) { App.dataController.mapData.remove(event.getLayer().getFeatureSource().getName().toString()); } @Override public void layerPreDispose(MapLayerListEvent arg0) { // TODO Auto-generated method stub } @Override public void layerMoved(MapLayerListEvent arg0) { // TODO Auto-generated method stub } @Override public void layerChanged(MapLayerListEvent arg0) { // TODO Auto-generated method stub } @Override public void layerAdded(MapLayerListEvent arg0) { // TODO Auto-generated method stub } }); show.enableInputMethods(true); JMenuBar menubar = new JMenuBar(); show.getToolBar().add(menubar); JMenu dataMenu = new JMenu("Skaičiuoti"); menubar.add(dataMenu); dataMenu.add(new SafeAction("Bendrą upių tinklo ilgį administraciniuose vienetuose") { public void action(ActionEvent e) throws Throwable { Calculations.calculateRiversLength(); } }); dataMenu.add(new SafeAction("Bendrą kelių tinklo ilgį administraciniuose vienetuose") { public void action(ActionEvent e) throws Throwable { } }); show.setVisible(true); } private void addLayerFromFile() throws Exception { File file = JFileDataStoreChooser.showOpenFile("shp", null); if (file == null) { return; } FileDataStore store = FileDataStoreFinder.getDataStore(file); SimpleFeatureSource source = store.getFeatureSource(); if (App.dataController.mapData.containsKey(source.getName().toString())) { return; } App.dataController.mapData.put(source.getName().toString(), source); App.dataTables.featureTypeCBox.addItem(source.getName().toString()); addMapLayer(source); } public void addLayerFromFile(String path) throws IOException { File file = new File(path); FileDataStore store = FileDataStoreFinder.getDataStore(file); SimpleFeatureSource source = store.getFeatureSource(); if (App.dataController.mapData.containsKey(source.getName().toString())) { return; } App.dataController.mapData.put(source.getName().toString(), source); App.dataTables.featureTypeCBox.addItem(source.getName().toString()); addMapLayer(source); } public void addMapLayer(SimpleFeatureSource source) { Style style = new BasicPolygonStyle(); Layer layer = new FeatureLayer(source, style); map.addLayer(layer); selectionTool.updateMapView(layer, new HashSet<Identifier>()); } }
package net.localizethat.tasks; import java.io.File; import java.text.ParseException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.persistence.EntityManager; import javax.swing.JButton; import javax.swing.JTextArea; import javax.swing.SwingWorker; import net.localizethat.Main; import net.localizethat.model.DtdFile; import net.localizethat.model.LocaleContainer; import net.localizethat.model.LocaleContent; import net.localizethat.model.LocaleFile; import net.localizethat.model.LocalePath; import net.localizethat.model.ParseableFile; import net.localizethat.model.jpa.LocaleContainerJPAHelper; import net.localizethat.model.jpa.LocaleFileJPAHelper; import net.localizethat.util.gui.JStatusBar; /** * SwingWorker task that performs an update process in the locale paths passed in the constructor * @author rpalomares */ public class UpdateProductWorker extends SwingWorker<List<LocaleContent>, String> { private final JTextArea feedbackArea; private final JButton editChangesButton; private final JStatusBar statusBar; private final Iterator<LocalePath> localePathIterator; private final List<LocaleContent> newAndModifiedList; private final EntityManager em; private int filesAdded; private int filesModified; private int filesDeleted; private int foldersAdded; private int foldersModified; private int foldersDeleted; public UpdateProductWorker(JTextArea feedbackArea, JButton editChangesButton, Iterator<LocalePath> localePathIterator) { this.feedbackArea = feedbackArea; this.editChangesButton = editChangesButton; this.localePathIterator = localePathIterator; this.statusBar = Main.mainWindow.getStatusBar(); this.em = Main.emf.createEntityManager(); this.newAndModifiedList = new ArrayList<>(10); } @Override protected List<LocaleContent> doInBackground() { int totalFilesAdded = 0; int totalFilesModified = 0; int totalFilesDeleted = 0; int totalFoldersAdded = 0; int totalFoldersModified = 0; int totalFoldersDeleted = 0; em.getTransaction().begin(); while (localePathIterator.hasNext()) { if (isCancelled()) { break; } LocalePath lp = localePathIterator.next(); publish("Processing " + lp.getFilePath()); processPath(lp); if (isCancelled()) { publish("Update process cancelled, work done until now can't be undone"); if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } break; } else { totalFilesAdded += filesAdded; totalFilesModified += filesModified; totalFilesDeleted += filesDeleted; totalFoldersAdded += foldersAdded; totalFoldersModified += foldersModified; totalFoldersDeleted += foldersDeleted; publish(" Files... Added: " + filesAdded + "; Modified: " + filesModified + "; Deleted: " + filesDeleted); publish(" Folders... Added: " + foldersAdded + "; Modified: " + foldersModified + "; Deleted: " + foldersDeleted); } } if (em.isJoinedToTransaction()) { em.getTransaction().commit(); } em.close(); publish("Total Files... Added: " + totalFilesAdded + "; Modified: " + totalFilesModified + "; Deleted: " + totalFilesDeleted); publish("Total Folders... Added: " + totalFoldersAdded + "; Modified: " + totalFoldersModified + "; Deleted: " + totalFoldersDeleted); return newAndModifiedList; } @Override protected void process(List<String> messages) { for(String message : messages) { feedbackArea.append(message); feedbackArea.append(System.getProperty("line.separator")); } } @Override protected void done() { statusBar.endProgress(); editChangesButton.setEnabled(true); } private void processPath(LocalePath lp) { // Initialize the counters for each path filesAdded = 0; filesModified = 0; filesDeleted = 0; foldersAdded = 0; foldersModified = 0; foldersDeleted = 0; LocaleContainer lc = lp.getLocaleContainer(); processContainer(lp.getFilePath(), lc); } private void processContainer(String currentPath, LocaleContainer lc) { File curDir = new File(currentPath); File[] childFiles = curDir.listFiles(); LocaleContainerJPAHelper lcHelper = new LocaleContainerJPAHelper(em); LocaleFileJPAHelper lfHelper = new LocaleFileJPAHelper(em); if (isCancelled()) { return; } // Take the real files & dirs in the disk and add those missing in the datamodel try { if (!em.isJoinedToTransaction()) { em.getTransaction().begin(); } for (File curFile : childFiles) { if (isCancelled()) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } if (curFile.isDirectory()) { boolean exists = (lc.hasChild(curFile.getName(), true)); if (!exists) { LocaleContainer newLc = new LocaleContainer(curFile.getName(), lc); lc.addChild(newLc); foldersAdded++; em.persist(newLc); } } else { boolean exists = (lc.hasFileChild(curFile.getName(), true)); if (!exists) { LocaleFile lf = LocaleFile.createFile(curFile.getName(), lc); lc.addFileChild(lf); filesAdded++; em.persist(lf); } } } em.getTransaction().commit(); } catch (Exception e) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } if (isCancelled()) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } // Remove directories (LocaleContainer items) no longer present in the disk try { em.getTransaction().begin(); for (Iterator<LocaleContainer> iterator = lc.getChildren().iterator(); iterator.hasNext();) { if (isCancelled()) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } LocaleContainer lcChild = iterator.next(); lcChild = em.merge(lcChild); File result = fileExistsInArray(childFiles, lcChild.getName()); boolean exists = (result != null && result.isDirectory()); if (!exists) { lcChild.setParent(null); iterator.remove(); lcHelper.removeRecursively(lcChild); foldersDeleted++; } else { // Remove the entry in the directory entries array to mark it as processed removeFileFromArray(childFiles, result); } } em.getTransaction().commit(); } catch (NullPointerException e) { e.printStackTrace(); } catch (Exception e) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } if (isCancelled()) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } // Remove files (LocaleFiles items) no longer present in the disk try { em.getTransaction().begin(); for(Iterator<? extends LocaleFile> iterator = lc.getFileChildren().iterator(); iterator.hasNext();) { if (isCancelled()) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } LocaleFile lfChild = iterator.next(); em.merge(lfChild); File result = fileExistsInArray(childFiles, lfChild.getName()); boolean exists = (result != null && !result.isDirectory()); if (!exists) { lfChild.setParent(null); iterator.remove(); lfHelper.removeRecursively(lfChild); filesDeleted++; } else { removeFileFromArray(childFiles, result); } } em.getTransaction().commit(); } catch (NullPointerException e) { e.printStackTrace(); } catch (Exception e) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } if (isCancelled()) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } // At this point, the datamodel for currentPath matches the disk contents // Traverse the datamodel LocaleContainers (folders/dirs) for(LocaleContainer lcChild : lc.getChildren()) { processContainer(currentPath + "/" + lcChild.getName(), lcChild); } // Traverse the datamodel LocaleFiles (files) for(LocaleFile lfChild : lc.getFileChildren()) { if (isCancelled()) { if (em.isJoinedToTransaction()) { em.getTransaction().rollback(); } return; } processFile(currentPath + "/" + lfChild.getName(), lfChild); } } private boolean processFile(String filePath, LocaleFile lf) { try { // if (lf instanceof ParseableFile) { if (lf instanceof DtdFile) { ParseableFile pf = (ParseableFile) lf; newAndModifiedList.addAll(pf.update(this.em)); } filesModified++; return true; } catch (ParseException ex) { return false; } } private File fileExistsInArray(File[] fileArray, String filename) { File result = null; for(File f : fileArray) { if ((f != null) && (f.getName().equals(filename))) { result = f; break; } } return result; } private boolean removeFileFromArray(File[] fileArray, File fileToRemove) { boolean result = false; for(int i = 0; i < fileArray.length; i++) { if ((fileArray[i] != null) && (fileArray[i].equals(fileToRemove))) { fileArray[i] = null; result = true; break; } } return result; } }
package org.gmagnotta.log; import java.util.Date; /** * Represents an information that should be logged */ public class LogEvent { private static final String UNSET_MARKER = "UNSET"; private LogLevel logLevel; private String sourceClass; private Date date; private String threadName; private String message; private Throwable throwable; private String marker; /** * Create new log * * @param logLevel * log level * @param sourceClass * source class * @param date * log date * @param threadName * the name of thread who generate the log * @param message * log message */ public LogEvent(LogLevel logLevel, Class<?> sourceClass, Date date, String threadName, String message) { this(logLevel, sourceClass.getName(), date, threadName, message); } /** * Create new log * * @param logLevel * log level * @param sourceClass * source class * @param date * log date * @param threadName * the name of thread who generate the log * @param message * log message */ public LogEvent(LogLevel logLevel, String sourceClass, Date date, String threadName, String message) { this(UNSET_MARKER, logLevel, sourceClass, date, threadName, message); } /** * Create new log * * @param marker * marker string to attach to this event * @param logLevel * log level * @param sourceClass * source class * @param date * log date * @param threadName * the name of thread who generate the log * @param message * log message */ public LogEvent(String marker, LogLevel logLevel, String sourceClass, Date date, String threadName, String message) { this.marker = marker; this.logLevel = logLevel; this.sourceClass = sourceClass; this.date = date; this.threadName = threadName; this.message = message; } /** * Create new log * * @param logLevel * log level * @param sourceClass * source class * @param date * log date * @param threadName * the name of thread who generate the log * @param message * log message * @param throwable * throwable to log */ public LogEvent(LogLevel logLevel, Class<?> sourceClass, Date date, String threadName, String message, Throwable throwable) { this(logLevel, sourceClass.getName(), date, threadName, message); } /** * Create new log * * @param logLevel * log level * @param sourceClass * source class * @param date * log date * @param threadName * the name of thread who generate the log * @param message * log message * @param throwable * throwable to log */ public LogEvent(LogLevel logLevel, String sourceClass, Date date, String threadName, String message, Throwable throwable) { this(UNSET_MARKER, logLevel, sourceClass, date, threadName, message, throwable); } /** * Create new log * * @param marker * marker string to attach to this event * @param logLevel * log level * @param sourceClass * source class * @param date * log date * @param threadName * the name of thread who generate the log * @param message * log message * @param throwable * throwable to log */ public LogEvent(String marker, LogLevel logLevel, String sourceClass, Date date, String threadName, String message, Throwable throwable) { this.marker = marker; this.logLevel = logLevel; this.sourceClass = sourceClass; this.date = date; this.threadName = threadName; this.message = message; this.throwable = throwable; } /** * Get marker if present * * @return marker if present or null */ public String getMarker() { return marker; } /** * Get log level * * @return log level */ public LogLevel getLogLevel() { return logLevel; } /** * Get source class * * @return source class */ public String getSourceClass() { return sourceClass; } /** * Get log date * * @return log date */ public Date getDate() { return date; } /** * Get name of thread who generate this log * * @return thread name */ public String getThreadName() { return threadName; } /** * Get log message * * @return log message */ public String getMessage() { return message; } /** * Get throwable to log * * @return throwable or null if not throwable is defined for this log */ public Throwable getThrowable() { return throwable; } }
package org.imirsel.nema.model; import java.io.Serializable; import java.util.Date; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.JoinColumn; import javax.persistence.Transient; import org.hibernate.annotations.GenerationTime; import org.hibernate.annotations.Proxy; /** * Represents a NEMA DIY job. * * @author shirk * @since 1.0 */ @Entity @Table(name="job") @Proxy(lazy=false) public class Job implements Serializable, Cloneable { /** * Version of this class. */ private static final long serialVersionUID = 3383935885803288343L; static public enum JobStatus { UNKNOWN(-1), SCHEDULED(0), SUBMITTED(1), STARTED(2), FINISHED(3), FAILED(4), ABORTED(5); private final int code; private JobStatus(int code) { this.code = code; } public int getCode() { return code; } @Override public String toString() { String name = null; switch (code) { case -1: { name = "Unknown"; break; } case 0: { name = "Scheduled"; break; } case 1: { name = "Submitted"; break; } case 2: { name = "Started"; break; } case 3: { name = "Finished"; break; } case 4: { name = "Failed"; break; } case 5: { name = "Aborted"; break; } } return name; } static public JobStatus toJobStatus(int code) { JobStatus status = null; switch (code) { case -1: { status = JobStatus.UNKNOWN; break; } case 0: { status = JobStatus.SCHEDULED; break; } case 1: { status = JobStatus.SUBMITTED; break; } case 2: { status = JobStatus.STARTED; break; } case 3: { status = JobStatus.FINISHED; break; } case 4: { status = JobStatus.FAILED; break; } case 5: { status = JobStatus.ABORTED; break; } } return status; } } private Long id; private String token; private String name; private String description; private String host; private Integer port; private Integer execPort; private Date submitTimestamp; private Date startTimestamp; private Date endTimestamp; private Date updateTimestamp; private Integer statusCode = -1; private Long ownerId; private String ownerEmail; private Flow flow; private Integer numTries = 0; private String executionInstanceId; private Set<JobResult> results; @Id @Column(name="id") @GeneratedValue(strategy = GenerationType.IDENTITY) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name="description",length=20000000) public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Column(name="host") public String getHost() { return host; } public void setHost(String host) { this.host = host; } @Column(name="port") public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } @Column(name="submitTimestamp") public Date getSubmitTimestamp() { return submitTimestamp; } public void setSubmitTimestamp(Date submitTimestamp) { this.submitTimestamp = submitTimestamp; } @Column(name="startTimestamp",updatable=false,insertable=false) public Date getStartTimestamp() { return startTimestamp; } public void setStartTimestamp(Date startTimestamp) { this.startTimestamp = startTimestamp; } @Column(name="endTimestamp") public Date getEndTimestamp() { return endTimestamp; } public void setEndTimestamp(Date endTimestamp) { this.endTimestamp = endTimestamp; } @Column(name="statusCode",nullable=false) public Integer getStatusCode() { return statusCode; } public void setStatusCode(Integer statusCode) { // This is a nasty hack to work around the race condition that exists // when the Meandre server updates the job as started, and then the // flow service writes it as submitted. if(this.statusCode==2 && statusCode < 2) { return; } if(!this.statusCode.equals(statusCode)) { setUpdateTimestamp(new Date()); this.statusCode = statusCode; } } @Column(name="token",nullable=false) public String getToken() { return token; } public void setToken(String token) { this.token = token; } @Column(name="name",nullable=false) public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name="updateTimestamp",updatable=false,insertable=false) @org.hibernate.annotations.Generated(GenerationTime.ALWAYS) public Date getUpdateTimestamp() { return updateTimestamp; } public void setUpdateTimestamp(Date updateTimestamp) { this.updateTimestamp = updateTimestamp; } @Column(name="ownerId", nullable=false) public Long getOwnerId() { return ownerId; } public void setOwnerId(Long ownerId) { this.ownerId = ownerId; } @Column(name="ownerEmail", nullable=false) public String getOwnerEmail() { return ownerEmail; } public void setOwnerEmail(String ownerEmail) { this.ownerEmail = ownerEmail; } @JoinColumn(name = "flowInstanceId") @ManyToOne(fetch=FetchType.EAGER,optional=false) public Flow getFlow() { return flow; } public void setFlow(Flow flow) { this.flow = flow; } @Column(name="executionInstanceId",length=20000000) public String getExecutionInstanceId() { return executionInstanceId; } public void setExecutionInstanceId(String executionInstanceId) { this.executionInstanceId = executionInstanceId; } @Transient public JobStatus getJobStatus() { return JobStatus.toJobStatus(statusCode); } public void setJobStatus(JobStatus status) { this.statusCode = status.getCode(); } @JoinColumn(name="id") @OneToMany(mappedBy="job", fetch=FetchType.EAGER) public Set<JobResult> getResults() { return results; } public void setResults(Set<JobResult> results) { this.results = results; } @Transient public boolean isRunning() { return getJobStatus() == JobStatus.STARTED; } @Transient public boolean isDone() { if (statusCode == JobStatus.FINISHED.getCode() || statusCode == JobStatus.FAILED.getCode() || statusCode == JobStatus.ABORTED.getCode()) { return true; } return false; } @Column(name="numTries",nullable=false) public Integer getNumTries() { return numTries; } public void setNumTries(Integer numTries) { this.numTries = numTries; } public void incrementNumTries() { numTries++; } @Column(name="execPort") public Integer getExecPort() { return execPort; } public void setExecPort(Integer execPort) { this.execPort = execPort; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Job other = (Job) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public Job clone() { Job clone = new Job(); clone.setId(this.getId()); clone.setName(this.getName()); clone.setDescription(this.getDescription()); clone.setSubmitTimestamp(this.getSubmitTimestamp()); clone.setStartTimestamp(this.getStartTimestamp()); clone.setEndTimestamp(this.getEndTimestamp()); clone.setUpdateTimestamp(this.getUpdateTimestamp()); clone.setHost(this.getHost()); clone.setPort(this.getPort()); clone.setFlow(this.getFlow()); clone.setExecPort(this.getExecPort()); clone.setExecutionInstanceId(this.getExecutionInstanceId()); clone.setStatusCode(this.getStatusCode()); clone.setNumTries(this.getNumTries()); clone.setOwnerEmail(this.getOwnerEmail()); clone.setOwnerId(this.getOwnerId()); clone.setResults(this.getResults()); clone.setToken(this.getToken()); return clone; } }
package net.ssehub.kernel_haven.util; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.TimeoutException; /** * A blocking queue that can send data from one thread to another. One thread can push data into the queue, that will * be read from the other thread. If the queue is currently empty, the reading thread will wait until there is data * available. The writing thread has to signal that is done (via {@link #end()}), in which case all subsequent read * accesses will return <code>null</code> (once the backed up data is depleted). For this reason, the writing thread * must never write null into the queue. * <br/> * <h2>Usage</h2> * <b>Reading:</b> * This class is {@link Iterable}, so for-each loops can be used to read all data (until the writing thread said, that * it is done). Alternatively, the queue can be read until it returns <code>null</code>, e.g. like so: * <pre> * {@code * Element elem; * while ((elem = queue.get()) != null) { * ... * }}</pre> * <b>Writing:</b> * Push data in the queue via the {@link #add(Object)} method. Signal the end, by calling {@link #end()}. If * {@link #end()} is not called, then the other thread doesn't know when to stop waiting for data, and thus a deadlock * can appear. * <pre> * {@code * BlockingQueue<T> queue = new BlockingQueue<>(); * queue.add(...); * ... * queue.end();}</pre> * <b>Adding further elements</b> after {@link #end()} was called is not possible. If "extending" an existing, ended * queue is necessary, create a new one and copy the data over: * <pre> * {@code * BlockingQueue<T> newQueue = new BlockingQueue<>(); * T elem; * while ((elem = oldQueue.get()) != null) { * newQueue.add(elem); * } * newQueue.add(new_element); * ... * newQueue.end();}</pre> * * @param <T> The type of data that is send between the threads. * * @author Adam * @author Alice * */ public class BlockingQueue<T> implements Iterable<T> { private Queue<T> internalQueue; private boolean end; /** * Creates an empty queue. */ public BlockingQueue() { internalQueue = new LinkedList<>(); } /** * Returns the next element in this queue. If the queue is empty, then this waits until * the other thread inserts data. * * @return The next element in the queue, or <code>null</code> if the other thread * signaled that it does not want to insert any more data. */ public T get() { T result = null; try { result = get(0); } catch (TimeoutException e) { // can't happen } return result; } /** * Returns the next element in this queue. If the queue is empty, then this waits until * the other thread inserts data. * * @param timeout The maximum amount of milliseconds to wait until a {@link TimeoutException} is thrown. * 0 here means no timeout. * @return The next element in the queue, or <code>null</code> if the other thread * signaled that it does not want to insert any more data. * * @throws TimeoutException If the timeout exceeded. */ public T get(long timeout) throws TimeoutException { T result = null; synchronized (internalQueue) { if (internalQueue.isEmpty() && !end) { boolean waitSuccess = false; while (!waitSuccess) { try { internalQueue.wait(timeout); waitSuccess = true; } catch (InterruptedException e) { } } } result = internalQueue.poll(); if (result == null && !end) { throw new TimeoutException(); } } return result; } /** * Returns, but does not remove, the next element in this queue. If the queue is empty, then this waits until * the other thread inserts data. * * @return The next element in the queue, or <code>null</code> if the other thread * signaled that it does not want to insert any more data. */ public T peek() { T result = null; try { result = peek(0); } catch (TimeoutException e) { // can't happen } return result; } /** * Returns, but does not remove, the next element in this queue. If the queue is empty, then this waits until * the other thread inserts data. * * @param timeout The maximum amount of milliseconds to wait until a {@link TimeoutException} is thrown. * 0 here means no timeout. * @return The next element in the queue, or <code>null</code> if the other thread * signaled that it does not want to insert any more data. * * @throws TimeoutException If the timeout exceeded. */ public T peek(long timeout) throws TimeoutException { T result = null; synchronized (internalQueue) { if (internalQueue.isEmpty() && !end) { boolean waitSuccess = false; while (!waitSuccess) { try { internalQueue.wait(timeout); waitSuccess = true; } catch (InterruptedException e) { } } } result = internalQueue.peek(); if (result == null && !end) { throw new TimeoutException(); } } return result; } public void add(T element) { synchronized (internalQueue) { if (end) { throw new IllegalStateException("Trying to add new elements while end() has already been called"); } internalQueue.add(element); internalQueue.notifyAll(); } } /** * Signals that no more data is added after this call. This allows get() to return <code>null</code> * once all existing data has been read out. */ public void end() { synchronized (internalQueue) { end = true; internalQueue.notifyAll(); } } /** * Returns whether the other thread has signaled that it does not want to send anymore data or not. This does not * mean that there are no items left in the queue, but rather that no new items will be added. * * @return Whether the other thread signaled the end of this queue. */ public boolean isEnd() { synchronized (internalQueue) { return end; } } @Override public Iterator<T> iterator() { return new Iterator<T>() { @Override public boolean hasNext() { return peek() != null; } @Override public T next() { return get(); } }; } }
package com.intellij.psi.impl.compiled; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiNameHelper; import com.intellij.psi.impl.cache.ModifierFlags; import com.intellij.psi.impl.cache.TypeInfo; import com.intellij.psi.impl.java.stubs.*; import com.intellij.psi.impl.java.stubs.impl.*; import com.intellij.psi.stubs.PsiFileStub; import com.intellij.psi.stubs.StubElement; import com.intellij.util.ArrayUtil; import com.intellij.util.Consumer; import com.intellij.util.Function; import com.intellij.util.cls.ClsFormatException; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.org.objectweb.asm.*; import java.io.IOException; import java.lang.reflect.Array; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.List; import java.util.Map; import java.util.Set; import static com.intellij.openapi.util.Pair.pair; import static com.intellij.util.BitUtil.isSet; /** * @author max */ public class StubBuildingVisitor<T> extends ClassVisitor { private static final Logger LOG = Logger.getInstance(StubBuildingVisitor.class); private static final String DOUBLE_POSITIVE_INF = "1.0 / 0.0"; private static final String DOUBLE_NEGATIVE_INF = "-1.0 / 0.0"; private static final String DOUBLE_NAN = "0.0d / 0.0"; private static final String FLOAT_POSITIVE_INF = "1.0f / 0.0"; private static final String FLOAT_NEGATIVE_INF = "-1.0f / 0.0"; private static final String FLOAT_NAN = "0.0f / 0.0"; private static final String SYNTHETIC_CLASS_INIT_METHOD = "<clinit>"; private static final String SYNTHETIC_INIT_METHOD = "<init>"; private static final int ASM_API = Opcodes.API_VERSION; private final T mySource; private final InnerClassSourceStrategy<T> myInnersStrategy; private final StubElement myParent; private final int myAccess; private final String myShortName; private final Function<String, String> myMapping; private final boolean myAnonymousInner; private final boolean myLocalClassInner; private boolean myNoAnnotationOffsets; private String myInternalName; private PsiClassStub<?> myResult; private PsiModifierListStub myModList; public StubBuildingVisitor(T classSource, InnerClassSourceStrategy<T> innersStrategy, StubElement parent, int access, String shortName) { this(classSource, innersStrategy, parent, access, shortName, false, false); } public StubBuildingVisitor(T classSource, InnerClassSourceStrategy<T> innersStrategy, StubElement parent, int access, String shortName, boolean anonymousInner, boolean localClassInner) { super(ASM_API); mySource = classSource; myInnersStrategy = innersStrategy; myParent = parent; myAccess = access; myShortName = shortName; myMapping = createMapping(classSource); myAnonymousInner = anonymousInner; myLocalClassInner = localClassInner; //noinspection ConstantConditions myNoAnnotationOffsets = ASM_API > Opcodes.ASM6 && !(classSource == null && innersStrategy.getClass().getName().startsWith("org.jetbrains.kotlin.")); } public PsiClassStub<?> getResult() { return myResult; } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { myInternalName = name; String parentName = myParent instanceof PsiClassStub ? ((PsiClassStub)myParent).getQualifiedName() : myParent instanceof PsiJavaFileStub ? ((PsiJavaFileStub)myParent).getPackageName() : null; String fqn = myAnonymousInner || myLocalClassInner ? null : getFqn(name, myShortName, parentName); String shortName = myShortName != null && name.endsWith(myShortName) ? myShortName : fqn != null ? PsiNameHelper.getShortClassName(fqn) : myShortName; int flags = myAccess | access; boolean isDeprecated = isSet(flags, Opcodes.ACC_DEPRECATED); boolean isInterface = isSet(flags, Opcodes.ACC_INTERFACE); boolean isEnum = isSet(flags, Opcodes.ACC_ENUM); boolean isAnnotationType = isSet(flags, Opcodes.ACC_ANNOTATION); short stubFlags = PsiClassStubImpl.packFlags(isDeprecated, isInterface, isEnum, false, false, isAnnotationType, false, false, myAnonymousInner, myLocalClassInner); myResult = new PsiClassStubImpl(JavaStubElementTypes.CLASS, myParent, fqn, shortName, null, stubFlags); myModList = new PsiModifierListStubImpl(myResult, packClassFlags(flags)); ClassInfo info = null; if (signature != null) { try { info = parseClassSignature(signature); } catch (ClsFormatException e) { if (LOG.isDebugEnabled()) LOG.debug("source=" + mySource + " signature=" + signature, e); } } if (info == null) { info = parseClassDescription(superName, interfaces); } newTypeParameterList(myResult, info.typeParameters); if (myResult.isInterface()) { if (info.interfaceNames != null && myResult.isAnnotationType()) { info.interfaceNames.remove(CommonClassNames.JAVA_LANG_ANNOTATION_ANNOTATION); } newReferenceList(JavaStubElementTypes.EXTENDS_LIST, myResult, ArrayUtil.toStringArray(info.interfaceNames)); newReferenceList(JavaStubElementTypes.IMPLEMENTS_LIST, myResult, ArrayUtil.EMPTY_STRING_ARRAY); } else { if (info.superName == null || "java/lang/Object".equals(superName) || myResult.isEnum() && "java/lang/Enum".equals(superName)) { newReferenceList(JavaStubElementTypes.EXTENDS_LIST, myResult, ArrayUtil.EMPTY_STRING_ARRAY); } else { newReferenceList(JavaStubElementTypes.EXTENDS_LIST, myResult, new String[]{info.superName}); } newReferenceList(JavaStubElementTypes.IMPLEMENTS_LIST, myResult, ArrayUtil.toStringArray(info.interfaceNames)); } } private String getFqn(@NotNull String internalName, @Nullable String shortName, @Nullable String parentName) { if (shortName == null || !internalName.endsWith(shortName)) { return myMapping.fun(internalName); } if (internalName.length() == shortName.length()) { return shortName; } if (parentName == null) { parentName = myMapping.fun(internalName.substring(0, internalName.length() - shortName.length() - 1)); } return parentName + '.' + shortName; } private ClassInfo parseClassSignature(String signature) throws ClsFormatException { ClassInfo result = new ClassInfo(); CharacterIterator iterator = new StringCharacterIterator(signature); result.typeParameters = SignatureParsing.parseTypeParametersDeclaration(iterator, myMapping); result.superName = SignatureParsing.parseTopLevelClassRefSignature(iterator, myMapping); while (iterator.current() != CharacterIterator.DONE) { String name = SignatureParsing.parseTopLevelClassRefSignature(iterator, myMapping); if (name == null) throw new ClsFormatException(); if (result.interfaceNames == null) result.interfaceNames = ContainerUtil.newSmartList(); result.interfaceNames.add(name); } return result; } private ClassInfo parseClassDescription(String superClass, String[] superInterfaces) { ClassInfo result = new ClassInfo(); result.typeParameters = ContainerUtil.emptyList(); result.superName = superClass != null ? myMapping.fun(superClass) : null; result.interfaceNames = superInterfaces == null ? null : ContainerUtil.map(superInterfaces, myMapping); return result; } private static void newTypeParameterList(StubElement<?> parent, List<Pair<String, String[]>> parameters) { PsiTypeParameterListStub listStub = new PsiTypeParameterListStubImpl(parent); for (Pair<String, String[]> parameter : parameters) { PsiTypeParameterStub parameterStub = new PsiTypeParameterStubImpl(listStub, parameter.first); newReferenceList(JavaStubElementTypes.EXTENDS_BOUND_LIST, parameterStub, parameter.second); } } private static void newReferenceList(@NotNull JavaClassReferenceListElementType type, StubElement parent, @NotNull String[] types) { new PsiClassReferenceListStubImpl(type, parent, types); } private static int packCommonFlags(int access) { int flags = 0; if (isSet(access, Opcodes.ACC_PRIVATE)) flags |= ModifierFlags.PRIVATE_MASK; else if (isSet(access, Opcodes.ACC_PROTECTED)) flags |= ModifierFlags.PROTECTED_MASK; else if (isSet(access, Opcodes.ACC_PUBLIC)) flags |= ModifierFlags.PUBLIC_MASK; else flags |= ModifierFlags.PACKAGE_LOCAL_MASK; if (isSet(access, Opcodes.ACC_STATIC)) flags |= ModifierFlags.STATIC_MASK; if (isSet(access, Opcodes.ACC_FINAL)) flags |= ModifierFlags.FINAL_MASK; return flags; } private static int packClassFlags(int access) { int flags = packCommonFlags(access); if (isSet(access, Opcodes.ACC_ABSTRACT)) flags |= ModifierFlags.ABSTRACT_MASK; return flags; } private static int packFieldFlags(int access) { int flags = packCommonFlags(access); if (isSet(access, Opcodes.ACC_VOLATILE)) flags |= ModifierFlags.VOLATILE_MASK; if (isSet(access, Opcodes.ACC_TRANSIENT)) flags |= ModifierFlags.TRANSIENT_MASK; return flags; } private static int packMethodFlags(int access, boolean isInterface) { int flags = packCommonFlags(access); if (isSet(access, Opcodes.ACC_SYNCHRONIZED)) flags |= ModifierFlags.SYNCHRONIZED_MASK; if (isSet(access, Opcodes.ACC_NATIVE)) flags |= ModifierFlags.NATIVE_MASK; if (isSet(access, Opcodes.ACC_STRICT)) flags |= ModifierFlags.STRICTFP_MASK; if (isSet(access, Opcodes.ACC_ABSTRACT)) flags |= ModifierFlags.ABSTRACT_MASK; else if (isInterface && !isSet(access, Opcodes.ACC_STATIC)) flags |= ModifierFlags.DEFAULT_MASK; return flags; } @Override public void visitSource(String source, String debug) { ((PsiClassStubImpl)myResult).setSourceFileName(source); } @Override public void visitOuterClass(String owner, String name, String desc) { if (myParent instanceof PsiFileStub) { throw new OutOfOrderInnerClassException(); } } @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return new AnnotationTextCollector(desc, myMapping, text -> new PsiAnnotationStubImpl(myModList, text)); } @Override public void visitInnerClass(String name, String outerName, String innerName, int access) { if (isSet(access, Opcodes.ACC_SYNTHETIC)) return; String jvmClassName = innerName; boolean isAnonymousInner = innerName == null; boolean isLocalClassInner = !isAnonymousInner && outerName == null; if (innerName == null || outerName == null) { int $index; if (myInternalName.equals(name) || ($index = name.lastIndexOf('$')) == -1) { return; } else if (isAnonymousInner) { jvmClassName = name.substring($index + 1); innerName = jvmClassName; outerName = name.substring(0, $index); } else { // isLocalClassInner outerName = name.substring(0, $index); jvmClassName = name.substring($index + 1); } } if (myParent instanceof PsiFileStub && myInternalName.equals(name)) { throw new OutOfOrderInnerClassException(); // our result is inner class } if (myInternalName.equals(outerName)) { T innerClass = myInnersStrategy.findInnerClass(jvmClassName, mySource); if (innerClass != null) { StubBuildingVisitor<T> visitor = new StubBuildingVisitor<>(innerClass, myInnersStrategy, myResult, access, innerName, isAnonymousInner, isLocalClassInner); visitor.myNoAnnotationOffsets = myNoAnnotationOffsets; myInnersStrategy.accept(innerClass, visitor); } } } @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (isSet(access, Opcodes.ACC_SYNTHETIC)) return null; if (name == null) return null; byte flags = PsiFieldStubImpl.packFlags(isSet(access, Opcodes.ACC_ENUM), isSet(access, Opcodes.ACC_DEPRECATED), false, false); TypeInfo type = fieldType(desc, signature); String initializer = constToString(value, type.text, false, myMapping); PsiFieldStub stub = new PsiFieldStubImpl(myResult, name, type, initializer, flags); PsiModifierListStub modList = new PsiModifierListStubImpl(stub, packFieldFlags(access)); return new FieldAnnotationCollectingVisitor(modList, myMapping); } private TypeInfo fieldType(String desc, String signature) { String type = null; if (signature != null) { try { type = SignatureParsing.parseTypeString(new StringCharacterIterator(signature), myMapping); } catch (ClsFormatException e) { if (LOG.isDebugEnabled()) LOG.debug("source=" + mySource + " signature=" + signature, e); } } if (type == null) { type = toJavaType(Type.getType(desc), myMapping); } return TypeInfo.fromString(type, false); } private static final String[] parameterNames = {"p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"}; @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { // JLS 13.1 says: Any constructs introduced by the compiler that do not have a corresponding construct in the source code // must be marked as synthetic, except for default constructors and the class initialization method. // However Scala compiler erroneously generates ACC_BRIDGE instead of ACC_SYNTHETIC flag for in-trait implementation delegation. // See IDEA-78649 if (isSet(access, Opcodes.ACC_SYNTHETIC)) return null; if (name == null) return null; if (SYNTHETIC_CLASS_INIT_METHOD.equals(name)) return null; // skip semi-synthetic enum methods boolean isEnum = myResult.isEnum(); if (isEnum) { if ("values".equals(name) && desc.startsWith("()")) return null; //noinspection SpellCheckingInspection if ("valueOf".equals(name) && desc.startsWith("(Ljava/lang/String;)")) return null; } boolean isConstructor = SYNTHETIC_INIT_METHOD.equals(name); boolean isDeprecated = isSet(access, Opcodes.ACC_DEPRECATED); boolean isVarargs = isSet(access, Opcodes.ACC_VARARGS); boolean isStatic = isSet(access, Opcodes.ACC_STATIC); boolean isAnnotationMethod = myResult.isAnnotationType(); byte flags = PsiMethodStubImpl.packFlags(isConstructor, isAnnotationMethod, isVarargs, isDeprecated, false, false); String canonicalMethodName = isConstructor ? myResult.getName() : name; MethodInfo info = null; boolean generic = false; if (signature != null) { try { info = parseMethodSignature(signature, exceptions); generic = true; } catch (ClsFormatException e) { if (LOG.isDebugEnabled()) LOG.debug("source=" + mySource + " signature=" + signature, e); } } if (info == null) { info = parseMethodDescription(desc, exceptions); } PsiMethodStubImpl stub = new PsiMethodStubImpl(myResult, canonicalMethodName, TypeInfo.fromString(info.returnType, false), flags, null); PsiModifierListStub modList = new PsiModifierListStubImpl(stub, packMethodFlags(access, myResult.isInterface())); newTypeParameterList(stub, info.typeParameters); boolean isEnumConstructor = isEnum && isConstructor; boolean isInnerClassConstructor = isConstructor && myParent instanceof PsiClassStub && !isSet(myModList.getModifiersMask(), Opcodes.ACC_STATIC) && !isGroovyClosure(canonicalMethodName); List<String> args = info.argTypes; if (!generic && isEnumConstructor && args.size() >= 2 && CommonClassNames.JAVA_LANG_STRING.equals(args.get(0)) && "int".equals(args.get(1))) { // omit synthetic enum constructor parameters args = args.subList(2, args.size()); } PsiParameterListStubImpl parameterList = new PsiParameterListStubImpl(stub); int paramCount = args.size(); PsiParameterStubImpl[] paramStubs = new PsiParameterStubImpl[paramCount]; for (int i = 0; i < paramCount; i++) { // omit synthetic inner class constructor parameter if (i == 0 && !generic && isInnerClassConstructor) continue; String arg = args.get(i); boolean isEllipsisParam = isVarargs && i == paramCount - 1; TypeInfo typeInfo = TypeInfo.fromString(arg, isEllipsisParam); String paramName = i < parameterNames.length ? parameterNames[i] : "p" + (i + 1); PsiParameterStubImpl parameterStub = new PsiParameterStubImpl(parameterList, paramName, typeInfo, isEllipsisParam, true); paramStubs[i] = parameterStub; new PsiModifierListStubImpl(parameterStub, 0); } newReferenceList(JavaStubElementTypes.THROWS_LIST, stub, ArrayUtil.toStringArray(info.throwTypes)); int localVarIgnoreCount = isEnumConstructor ? 3 : isStatic ? 0 : 1; int paramIgnoreCount = myNoAnnotationOffsets ? 0 : isEnumConstructor ? 2 : isInnerClassConstructor ? 1 : 0; return new MethodAnnotationCollectingVisitor(stub, modList, localVarIgnoreCount, paramIgnoreCount, paramCount, paramStubs, myMapping); } private boolean isGroovyClosure(String canonicalMethodName) { if (canonicalMethodName != null && canonicalMethodName.startsWith("_closure")) { PsiClassReferenceListStub extendsList = myResult.findChildStubByType(JavaStubElementTypes.EXTENDS_LIST); if (extendsList != null) { String[] names = extendsList.getReferencedNames(); return names.length == 1 && "groovy.lang.Closure".equals(names[0]); } } return false; } private MethodInfo parseMethodSignature(String signature, String[] exceptions) throws ClsFormatException { MethodInfo result = new MethodInfo(); CharacterIterator iterator = new StringCharacterIterator(signature); result.typeParameters = SignatureParsing.parseTypeParametersDeclaration(iterator, myMapping); if (iterator.current() != '(') throw new ClsFormatException(); iterator.next(); if (iterator.current() == ')') { result.argTypes = ContainerUtil.emptyList(); } else { result.argTypes = ContainerUtil.newSmartList(); while (iterator.current() != ')' && iterator.current() != CharacterIterator.DONE) { result.argTypes.add(SignatureParsing.parseTypeString(iterator, myMapping)); } if (iterator.current() != ')') throw new ClsFormatException(); } iterator.next(); result.returnType = SignatureParsing.parseTypeString(iterator, myMapping); result.throwTypes = null; while (iterator.current() == '^') { iterator.next(); if (result.throwTypes == null) result.throwTypes = ContainerUtil.newSmartList(); result.throwTypes.add(SignatureParsing.parseTypeString(iterator, myMapping)); } if (exceptions != null && (result.throwTypes == null || exceptions.length > result.throwTypes.size())) { // a signature may be inconsistent with exception list - in this case, the more complete list takes precedence result.throwTypes = ContainerUtil.map(exceptions, myMapping); } return result; } private MethodInfo parseMethodDescription(String desc, String[] exceptions) { MethodInfo result = new MethodInfo(); result.typeParameters = ContainerUtil.emptyList(); result.returnType = toJavaType(Type.getReturnType(desc), myMapping); result.argTypes = ContainerUtil.map(Type.getArgumentTypes(desc), type -> toJavaType(type, myMapping)); result.throwTypes = exceptions == null ? null : ContainerUtil.map(exceptions, myMapping); return result; } private static class ClassInfo { private List<Pair<String, String[]>> typeParameters; private String superName; private List<String> interfaceNames; } private static class MethodInfo { private List<Pair<String, String[]>> typeParameters; private String returnType; private List<String> argTypes; private List<String> throwTypes; } private static class AnnotationTextCollector extends AnnotationVisitor { private final StringBuilder myBuilder = new StringBuilder(); private final Function<String, String> myMapping; private final Consumer<? super String> myCallback; private boolean hasPrefix; private boolean hasParams; private AnnotationTextCollector(@Nullable String desc, Function<String, String> mapping, Consumer<? super String> callback) { super(ASM_API); myMapping = mapping; myCallback = callback; if (desc != null) { hasPrefix = true; myBuilder.append('@').append(toJavaType(Type.getType(desc), myMapping)); } } @Override public void visit(String name, Object value) { valuePairPrefix(name); myBuilder.append(constToString(value, null, true, myMapping)); } @Override public void visitEnum(String name, String desc, String value) { valuePairPrefix(name); myBuilder.append(toJavaType(Type.getType(desc), myMapping)).append('.').append(value); } private void valuePairPrefix(String name) { if (!hasParams) { hasParams = true; if (hasPrefix) { myBuilder.append('('); } } else { myBuilder.append(','); } if (name != null) { myBuilder.append(name).append('='); } } @Override public AnnotationVisitor visitAnnotation(String name, String desc) { valuePairPrefix(name); return new AnnotationTextCollector(desc, myMapping, text -> myBuilder.append(text)); } @Override public AnnotationVisitor visitArray(String name) { valuePairPrefix(name); myBuilder.append('{'); return new AnnotationTextCollector(null, myMapping, text -> myBuilder.append(text).append('}')); } @Override public void visitEnd() { if (hasPrefix && hasParams) { myBuilder.append(')'); } myCallback.consume(myBuilder.toString()); } } private static class FieldAnnotationCollectingVisitor extends FieldVisitor { private final PsiModifierListStub myModList; private final Function<String, String> myMapping; private Set<String> myFilter; private FieldAnnotationCollectingVisitor(PsiModifierListStub modList, Function<String, String> mapping) { super(ASM_API); myModList = modList; myMapping = mapping; } @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return new AnnotationTextCollector(desc, myMapping, text -> { if (myFilter == null) myFilter = ContainerUtil.newTroveSet(); myFilter.add(text); new PsiAnnotationStubImpl(myModList, text); }); } @Override public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) { return new AnnotationTextCollector(desc, myMapping, text -> { if (typePath == null && (myFilter == null || !myFilter.contains(text))) { new PsiAnnotationStubImpl(myModList, text); } }); } } private static class MethodAnnotationCollectingVisitor extends MethodVisitor { private final PsiMethodStub myOwner; private final PsiModifierListStub myModList; private final int myLocalVarIgnoreCount; private final int myParamIgnoreCount; private final int myParamCount; private final PsiParameterStubImpl[] myParamStubs; private final Function<String, String> myMapping; private int myParamNameIndex; private int myUsedParamSize; private int myUsedParamCount; private List<Set<String>> myFilters; private MethodAnnotationCollectingVisitor(PsiMethodStub owner, PsiModifierListStub modList, int localVarIgnoreCount, int paramIgnoreCount, int paramCount, PsiParameterStubImpl[] paramStubs, Function<String, String> mapping) { super(ASM_API); myOwner = owner; myModList = modList; myLocalVarIgnoreCount = localVarIgnoreCount; myParamIgnoreCount = paramIgnoreCount; myParamCount = paramCount; myParamStubs = paramStubs; myMapping = mapping; } @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return new AnnotationTextCollector(desc, myMapping, text -> { if (accepted(0, text)) { new PsiAnnotationStubImpl(myModList, text); } }); } @Override public AnnotationVisitor visitParameterAnnotation(int parameter, String desc, boolean visible) { return parameter < myParamIgnoreCount ? null : new AnnotationTextCollector(desc, myMapping, text -> { int idx = parameter - myParamIgnoreCount; if (accepted(idx + 1, text)) { new PsiAnnotationStubImpl(myOwner.findParameter(idx).getModList(), text); } }); } @Override public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) { TypeReference ref = new TypeReference(typeRef); return new AnnotationTextCollector(desc, myMapping, text -> { if (ref.getSort() == TypeReference.METHOD_RETURN && typePath == null && accepted(0, text)) { new PsiAnnotationStubImpl(myModList, text); } else if (ref.getSort() == TypeReference.METHOD_FORMAL_PARAMETER && typePath == null) { int idx = ref.getFormalParameterIndex(); if (accepted(idx + 1, text)) { new PsiAnnotationStubImpl(myOwner.findParameter(idx).getModList(), text); } } }); } @Override public AnnotationVisitor visitAnnotationDefault() { return new AnnotationTextCollector(null, myMapping, text -> ((PsiMethodStubImpl)myOwner).setDefaultValueText(text)); } @Override public void visitParameter(String name, int access) { if (!isSet(access, Opcodes.ACC_SYNTHETIC) && myParamNameIndex < myParamCount) { setParameterName(name, myParamNameIndex); myParamNameIndex++; } } @Override public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) { if (index >= myLocalVarIgnoreCount) { int paramIndex = index - myLocalVarIgnoreCount == myUsedParamSize ? myUsedParamCount : index - myLocalVarIgnoreCount; if (paramIndex < myParamCount) { setParameterName(name, paramIndex); myUsedParamCount = paramIndex + 1; myUsedParamSize += "D".equals(desc) || "J".equals(desc) ? 2 : 1; } } } private void setParameterName(String name, int paramIndex) { if (ClsParsingUtil.isJavaIdentifier(name, LanguageLevel.HIGHEST)) { PsiParameterStubImpl stub = myParamStubs[paramIndex]; if (stub != null) stub.setName(name); } } private boolean accepted(int index, String text) { if (myFilters == null) { myFilters = ContainerUtil.newArrayListWithCapacity(myParamCount + 1); for (int i = 0; i < myParamCount + 1; i++) myFilters.add(null); } Set<String> filter = myFilters.get(index); if (filter == null) myFilters.set(index, filter = ContainerUtil.newTroveSet()); return filter.add(text); } } @Nullable private static String constToString(@Nullable Object value, @Nullable String type, boolean anno, Function<? super String, String> mapping) { if (value == null) return null; if (value instanceof String) { return "\"" + StringUtil.escapeStringCharacters((String)value) + "\""; } if (value instanceof Boolean || value instanceof Short || value instanceof Byte) { return value.toString(); } if (value instanceof Character) { return "'" + StringUtil.escapeCharCharacters(value.toString()) + "'"; } if (value instanceof Long) { return value.toString() + 'L'; } if (value instanceof Integer) { if ("boolean".equals(type)) { if (value.equals(0)) return "false"; if (value.equals(1)) return "true"; } if ("char".equals(type)) { char ch = (char)((Integer)value).intValue(); return "'" + StringUtil.escapeCharCharacters(String.valueOf(ch)) + "'"; } return value.toString(); } if (value instanceof Double) { double d = (Double)value; if (Double.isInfinite(d)) { return d > 0 ? DOUBLE_POSITIVE_INF : DOUBLE_NEGATIVE_INF; } if (Double.isNaN(d)) { return DOUBLE_NAN; } return Double.toString(d); } if (value instanceof Float) { float v = (Float)value; if (Float.isInfinite(v)) { return v > 0 ? FLOAT_POSITIVE_INF : FLOAT_NEGATIVE_INF; } else if (Float.isNaN(v)) { return FLOAT_NAN; } else { return Float.toString(v) + 'f'; } } if (value.getClass().isArray()) { StringBuilder buffer = new StringBuilder(); buffer.append('{'); for (int i = 0, length = Array.getLength(value); i < length; i++) { if (i > 0) buffer.append(", "); buffer.append(constToString(Array.get(value, i), type, anno, mapping)); } buffer.append('}'); return buffer.toString(); } if (anno && value instanceof Type) { return toJavaType((Type)value, mapping) + ".class"; } return null; } private static String toJavaType(Type type, Function<? super String, String> mapping) { int dimensions = 0; if (type.getSort() == Type.ARRAY) { dimensions = type.getDimensions(); type = type.getElementType(); } String text = type.getSort() == Type.OBJECT ? mapping.fun(type.getInternalName()) : type.getClassName(); if (dimensions > 0) text += StringUtil.repeat("[]", dimensions); return text; } private static Function<String, String> createMapping(Object classSource) { byte[] bytes = null; if (classSource instanceof ClsFileImpl.FileContentPair) { bytes = ((ClsFileImpl.FileContentPair)classSource).getContent(); } else if (classSource instanceof VirtualFile) { try { bytes = ((VirtualFile)classSource).contentsToByteArray(false); } catch (IOException ignored) { } } if (bytes != null) { Function<String, String> mapping = createMapping(bytes); if (mapping != null) { return mapping; } } return GUESSING_MAPPER; } private static Function<String, String> createMapping(byte[] classBytes) { final Map<String, Pair<String, String>> mapping = ContainerUtil.newHashMap(); try { new ClassReader(classBytes).accept(new ClassVisitor(ASM_API) { @Override public void visitInnerClass(String name, String outerName, String innerName, int access) { if (outerName != null && innerName != null) { mapping.put(name, pair(outerName, innerName)); } } }, ClsFileImpl.EMPTY_ATTRIBUTES, ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES); } catch (Exception ignored) { } if (!mapping.isEmpty()) { return new Function<String, String>() { @Override public String fun(String internalName) { String className = internalName; if (className.indexOf('$') >= 0) { Pair<String, String> p = mapping.get(className); if (p == null) { return GUESSING_MAPPER.fun(className); } className = p.first; if (p.second != null) { className = fun(p.first) + '.' + p.second; mapping.put(className, pair(className, null)); } } return className.replace('/', '.'); } }; } return null; } public static final Function<String, String> GUESSING_MAPPER = internalName -> { String canonicalText = internalName; if (canonicalText.indexOf('$') >= 0) { StringBuilder sb = new StringBuilder(canonicalText); boolean updated = false; int start = canonicalText.lastIndexOf('/') + 2; // -1 => 1 if no package; skip first char in class name for (int p = start; p < sb.length(); p++) { char c = sb.charAt(p); if (c == '$' && p < sb.length() - 1 && sb.charAt(p + 1) != '$') { sb.setCharAt(p, '.'); updated = true; } } if (updated) { canonicalText = sb.toString(); } } return canonicalText.replace('/', '.'); }; public static AnnotationVisitor getAnnotationTextCollector(String desc, Consumer<? super String> consumer) { return new AnnotationTextCollector(desc, GUESSING_MAPPER, consumer); } }
package org.jfclere.h2demo; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.PushBuilder; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.BufferedInputStream; import java.io.InputStream; /** * Servlet implementation class */ /* push the images */ /* send the html page */
package nl.mpi.arbil.importexport; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Hashtable; import java.util.StringTokenizer; import nl.mpi.arbil.GuiHelper; import nl.mpi.arbil.ImdiField; import nl.mpi.arbil.LinorgWindowManager; import nl.mpi.arbil.data.*; public class ArbilCsvImporter { ImdiTreeObject destinationCorpusNode; public ArbilCsvImporter(ImdiTreeObject destinationCorpusNodeLocal) { destinationCorpusNode = destinationCorpusNodeLocal; } public void doImport() { File[] selectedFiles = LinorgWindowManager.getSingleInstance().showFileSelectBox("Import CSV", false, true, false); if (selectedFiles != null && selectedFiles.length > 0) { // return "CSV File (comma or tab separated values)"; // return selectedFile.getName().toLowerCase().endsWith(".csv"); for (File currentFile : selectedFiles) { processCsvFile(currentFile); } } } private void cleanQuotes(String[] arrayToClean, String fileType) { if (arrayToClean.length > 0) { if (fileType.indexOf("\"") != -1) { arrayToClean[0] = arrayToClean[0].replaceAll("^\"", ""); arrayToClean[arrayToClean.length - 1] = arrayToClean[arrayToClean.length - 1].replaceAll("\"$", ""); } } } private void processCsvFile(File inputFile) { String csvHeaders[] = null; String fileType = ","; try { BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile)); String currentLine = ""; String remainderOfLastLine = ""; StringTokenizer stringTokeniser = null; while ((currentLine = bufferedReader.readLine()) != null) { if (csvHeaders == null) { fileType = "\"\\t\""; csvHeaders = currentLine.split(fileType); if (csvHeaders.length == 1) { fileType = "\t"; csvHeaders = currentLine.split(fileType); } if (csvHeaders.length == 1) { fileType = "\",\""; csvHeaders = currentLine.split(fileType); } if (csvHeaders.length == 1) { fileType = ","; csvHeaders = currentLine.split(fileType); } cleanQuotes(csvHeaders, fileType); } else { boolean skipLine = false; if (fileType.contains("\"")) { // some fields will contain line breaks and they, must be reassembled here // but this can only be done if the file contains quotes around each feild if (!currentLine.endsWith("\"")) { remainderOfLastLine = remainderOfLastLine + "\n" + currentLine; skipLine = true; } else if (remainderOfLastLine.length() > 0) { currentLine = remainderOfLastLine + "\n" + currentLine; remainderOfLastLine = ""; } } if (!skipLine) { String nodeType = ImdiSchema.imdiPathSeparator + "METATRANSCRIPT" + ImdiSchema.imdiPathSeparator + "Session"; ImdiTreeObject addedImdiObject = ImdiLoader.getSingleInstance().getImdiObject(null, new MetadataBuilder().addChildNode(destinationCorpusNode,nodeType, null, null, null)); addedImdiObject.waitTillLoaded(); Hashtable<String, ImdiField[]> addedNodesFields = addedImdiObject.getFields(); String[] currentLineArray = currentLine.split(fileType); cleanQuotes(currentLineArray, fileType); for (int columnCounter = 0; columnCounter < csvHeaders.length && columnCounter < currentLineArray.length; columnCounter++) { System.out.println(csvHeaders[columnCounter] + " : " + currentLineArray[columnCounter]); ImdiField[] currentFieldArray = addedNodesFields.get(csvHeaders[columnCounter]); if (currentFieldArray != null) { // TODO: check that the field does not already have a value and act accordingly (add new description?) if it does currentFieldArray[0].setFieldValue(currentLineArray[columnCounter], false, true); } } } } } } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } }
package com.semmle.extractor.java; import java.lang.reflect.*; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import com.github.codeql.Logger; import static com.github.codeql.ClassNamesKt.getIrDeclBinaryName; import static com.github.codeql.ClassNamesKt.getIrClassVirtualFile; import org.jetbrains.kotlin.ir.declarations.IrClass; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.kotlin.ir.declarations.IrDeclaration; import org.jetbrains.kotlin.ir.declarations.IrDeclarationWithName; import org.jetbrains.org.objectweb.asm.ClassVisitor; import org.jetbrains.org.objectweb.asm.ClassReader; import org.jetbrains.org.objectweb.asm.Opcodes; import com.semmle.util.concurrent.LockDirectory; import com.semmle.util.concurrent.LockDirectory.LockingMode; import com.semmle.util.data.Pair; import com.semmle.util.exception.CatastrophicError; import com.semmle.util.exception.NestedError; import com.semmle.util.exception.ResourceError; import com.semmle.util.extraction.PopulationSpecFile; import com.semmle.util.extraction.SpecFileEntry; import com.semmle.util.files.FileUtil; import com.semmle.util.io.WholeIO; import com.semmle.util.process.Env; import com.semmle.util.process.Env.Var; import com.semmle.util.trap.dependencies.TrapDependencies; import com.semmle.util.trap.dependencies.TrapSet; import com.semmle.util.trap.pathtransformers.PathTransformer; public class OdasaOutput { // By default we use lockless TRAP writing, but this can be set // if we want to use the old TRAP locking for any reason. private final boolean use_trap_locking = Env.systemEnv().getBoolean("CODEQL_EXTRACTOR_JAVA_TRAP_LOCKING", false); // either these are set ... private final File trapFolder; private final File sourceArchiveFolder; // ... or this one is set private final PopulationSpecFile specFile; private File currentSourceFile; private TrapSet trapsCreated; private TrapDependencies trapDependenciesForSource; private SpecFileEntry currentSpecFileEntry; // should origin tracking be used? private final boolean trackClassOrigins; private final Logger log; /** DEBUG only: just use the given file as the root for TRAP, source archive etc */ OdasaOutput(File outputRoot, Logger log) { this.trapFolder = new File(outputRoot, "trap"); this.sourceArchiveFolder = new File(outputRoot, "src_archive"); this.specFile = null; this.trackClassOrigins = false; this.log = log; } public OdasaOutput(boolean trackClassOrigins, Logger log) { String trapFolderVar = Env.systemEnv().getFirstNonEmpty("CODEQL_EXTRACTOR_JAVA_TRAP_DIR", Var.TRAP_FOLDER.name()); if (trapFolderVar != null) { String sourceArchiveVar = Env.systemEnv().getFirstNonEmpty("CODEQL_EXTRACTOR_JAVA_SOURCE_ARCHIVE_DIR", Var.SOURCE_ARCHIVE.name()); if (sourceArchiveVar == null) throw new ResourceError(Var.TRAP_FOLDER + " was set to '" + trapFolderVar + "', but " + Var.SOURCE_ARCHIVE + " was not set"); this.trapFolder = new File(trapFolderVar); this.sourceArchiveFolder = new File(sourceArchiveVar); this.specFile = null; } else { this.trapFolder = null; this.sourceArchiveFolder = null; String specFileVar = Env.systemEnv().get(Var.ODASA_JAVA_LAYOUT); if (specFileVar == null) throw new ResourceError("Neither " + Var.TRAP_FOLDER + " nor " + Var.ODASA_JAVA_LAYOUT + " was set"); this.specFile = new PopulationSpecFile(new File(specFileVar)); } this.trackClassOrigins = trackClassOrigins; this.log = log; } public File getTrapFolder() { return trapFolder; } public boolean getTrackClassOrigins() { return trackClassOrigins; } /** * Set the source file that is currently being processed. This may affect * things like trap and source archive directories, and persists as a * setting until this method is called again. * @param f the current source file */ public void setCurrentSourceFile(File f) { currentSourceFile = f; currentSpecFileEntry = entryFor(); trapsCreated = new TrapSet(); trapsCreated.addSource(PathTransformer.std().fileAsDatabaseString(f)); trapDependenciesForSource = null; } /** The output paths for that file, or null if it shouldn't be included */ private SpecFileEntry entryFor() { if (specFile != null) return specFile.getEntryFor(currentSourceFile); else return new SpecFileEntry(trapFolder, sourceArchiveFolder, Arrays.asList(PathTransformer.std().fileAsDatabaseString(currentSourceFile))); } /* * Trap sets and dependencies. */ public void writeTrapSet() { trapsCreated.save(trapSetFor(currentSourceFile).toPath()); } private File trapSetFor(File file) { return FileUtil.appendAbsolutePath( currentSpecFileEntry.getTrapFolder(), PathTransformer.std().fileAsDatabaseString(file) + ".set"); } public void addDependency(IrDeclaration sym, String signature) { String path = trapFilePathForDecl(sym, signature); trapDependenciesForSource.addDependency(path); } /* * Source archive. */ /** * Write the given source file to the right source archive, encoded in UTF-8, * or do nothing if the file shouldn't be populated. */ public void writeCurrentSourceFileToSourceArchive(String contents) { if (currentSpecFileEntry != null && currentSpecFileEntry.getSourceArchivePath() != null) { File target = sourceArchiveFileFor(currentSourceFile); target.getParentFile().mkdirs(); new WholeIO().write(target, contents); } } public void writeFileToSourceArchive(File srcFile) { File target = sourceArchiveFileFor(srcFile); target.getParentFile().mkdirs(); String contents = new WholeIO().strictread(srcFile); new WholeIO().write(target, contents); } private File sourceArchiveFileFor(File file) { return FileUtil.appendAbsolutePath(currentSpecFileEntry.getSourceArchivePath(), PathTransformer.std().fileAsDatabaseString(file)); } /* * Trap file names and paths. */ private static final String CLASSES_DIR = "classes"; private static final String JARS_DIR = "jars"; private static final String MODULES_DIR = "modules"; private File getTrapFileForCurrentSourceFile() { if (currentSpecFileEntry == null) return null; return trapFileFor(currentSourceFile); } private File getTrapFileForJarFile(File jarFile) { if (!jarFile.getAbsolutePath().endsWith(".jar")) return null; return FileUtil.appendAbsolutePath( currentSpecFileEntry.getTrapFolder(), JARS_DIR + "/" + PathTransformer.std().fileAsDatabaseString(jarFile) + ".trap.gz"); } private File getTrapFileForModule(String moduleName) { return FileUtil.appendAbsolutePath( currentSpecFileEntry.getTrapFolder(), MODULES_DIR + "/" + moduleName + ".trap.gz"); } private File trapFileFor(File file) { return FileUtil.appendAbsolutePath(currentSpecFileEntry.getTrapFolder(), PathTransformer.std().fileAsDatabaseString(file) + ".trap.gz"); } private File getTrapFileForDecl(IrDeclaration sym, String signature) { if (currentSpecFileEntry == null) return null; return trapFileForDecl(sym, signature); } private File trapFileForDecl(IrDeclaration sym, String signature) { return FileUtil.fileRelativeTo(currentSpecFileEntry.getTrapFolder(), trapFilePathForDecl(sym, signature)); } private String trapFilePathForDecl(IrDeclaration sym, String signature) { String binaryName = getIrDeclBinaryName(sym); String binaryNameWithSignature = binaryName + signature; // TODO: Reinstate this? //if (getTrackClassOrigins()) // classId += "-" + StringDigestor.digest(sym.getSourceFileId()); String result = CLASSES_DIR + "/" + binaryName.replace('.', '/') + signature + ".members" + ".trap.gz"; return result; } /* * Deletion of existing trap files. */ private void deleteTrapFileAndDependencies(IrDeclaration sym, String signature) { File trap = trapFileForDecl(sym, signature); if (trap.exists()) { trap.delete(); File depFile = new File(trap.getParentFile(), trap.getName().replace(".trap.gz", ".dep")); if (depFile.exists()) depFile.delete(); File metadataFile = new File(trap.getParentFile(), trap.getName().replace(".trap.gz", ".metadata")); if (metadataFile.exists()) metadataFile.delete(); } } /* * Trap writers. */ /** * Get a {@link TrapFileManager} to write members * about a declaration, or <code>null</code> if the declaration shouldn't be populated. * * @param sym * The declaration's symbol, including, in particular, its fully qualified * binary class name. * @param signature * Any unique suffix needed to distinguish `sym` from other declarations with the same name. * For functions for example, this means its parameter signature. */ private TrapFileManager getMembersWriterForDecl(File trap, File trapFileBase, TrapClassVersion trapFileVersion, IrDeclaration sym, String signature) { if (use_trap_locking) { TrapClassVersion currVersion = TrapClassVersion.fromSymbol(sym, log); String shortName = sym instanceof IrDeclarationWithName ? ((IrDeclarationWithName)sym).getName().asString() : "(name unknown)"; if (trap.exists()) { // Only re-write an existing trap file if we encountered a newer version of the same class. TrapClassVersion trapVersion = readVersionInfo(trap); if (!currVersion.isValid()) { log.warn("Not rewriting trap file for: " + shortName + " " + trapVersion + " " + currVersion + " " + trap); } else if (currVersion.newerThan(trapVersion)) { log.trace("Rewriting trap file for: " + shortName + " " + trapVersion + " " + currVersion + " " + trap); deleteTrapFileAndDependencies(sym, signature); } else { return null; } } else { log.trace("Writing trap file for: " + shortName + " " + currVersion + " " + trap); } } else { // If the TRAP file already exists then we // don't need to write it. if (trap.exists()) { log.warn("Not rewriting trap file for " + trap.toString() + " as it exists"); return null; } // If the TRAP file was written in the past, and // then renamed to its trap-old name, then we // don't need to rewrite it only to rename it // again. File trapFileDir = trap.getParentFile(); File trapOld = new File(trapFileDir, trap.getName().replace(".trap.gz", ".trap-old.gz")); if (trapOld.exists()) { log.warn("Not rewriting trap file for " + trap.toString() + " as the trap-old exists"); return null; } // Otherwise, if any newer TRAP file has already // been written then we don't need to write // anything. if (trapFileBase != null && trapFileVersion != null && trapFileDir.exists()) { String trapFileBaseName = trapFileBase.getName(); for (File f: FileUtil.list(trapFileDir)) { String name = f.getName(); Matcher m = selectClassVersionComponents.matcher(name); if (m.matches() && m.group(1).equals(trapFileBaseName)) { TrapClassVersion v = new TrapClassVersion(Integer.valueOf(m.group(2)), Integer.valueOf(m.group(3)), Long.valueOf(m.group(4)), m.group(5)); if (v.newerThan(trapFileVersion)) { log.warn("Not rewriting trap file for " + trap.toString() + " as " + f.toString() + " exists"); return null; } } } } } return trapWriter(trap, sym, signature); } private TrapFileManager trapWriter(File trapFile, IrDeclaration sym, String signature) { if (!trapFile.getName().endsWith(".trap.gz")) throw new CatastrophicError("OdasaOutput only supports writing to compressed trap files"); String relative = FileUtil.relativePath(trapFile, currentSpecFileEntry.getTrapFolder()); trapFile.getParentFile().mkdirs(); trapsCreated.addTrap(relative); return concurrentWriter(trapFile, relative, log, sym, signature); } private TrapFileManager concurrentWriter(File trapFile, String relative, Logger log, IrDeclaration sym, String signature) { if (trapFile.exists()) return null; return new TrapFileManager(trapFile, relative, true, log, sym, signature); } public class TrapFileManager implements AutoCloseable { private TrapDependencies trapDependenciesForClass; private File trapFile; private IrDeclaration sym; private String signature; private boolean hasError = false; private TrapFileManager(File trapFile, String relative, boolean concurrentCreation, Logger log, IrDeclaration sym, String signature) { trapDependenciesForClass = new TrapDependencies(relative); this.trapFile = trapFile; this.sym = sym; this.signature = signature; } public File getFile() { return trapFile; } public void addDependency(IrDeclaration dep, String signature) { trapDependenciesForClass.addDependency(trapFilePathForDecl(dep, signature)); } public void addDependency(IrClass c) { addDependency(c, ""); } public void close() { if (hasError) { return; } writeTrapDependencies(trapDependenciesForClass); // If we are using TRAP locking then we // need to write a metadata file. if (use_trap_locking) { // Record major/minor version information for extracted class files. // This is subsequently used to determine whether to re-extract (a newer version of) the same class. File metadataFile = new File(trapFile.getAbsolutePath().replace(".trap.gz", ".metadata")); try { Map<String, String> versionMap = new LinkedHashMap<>(); TrapClassVersion tcv = TrapClassVersion.fromSymbol(sym, log); versionMap.put(MAJOR_VERSION, String.valueOf(tcv.getMajorVersion())); versionMap.put(MINOR_VERSION, String.valueOf(tcv.getMinorVersion())); versionMap.put(LAST_MODIFIED, String.valueOf(tcv.getLastModified())); versionMap.put(EXTRACTOR_NAME, tcv.getExtractorName()); FileUtil.writePropertiesCSV(metadataFile, versionMap); } catch (IOException e) { log.warn("Could not save trap metadata file: " + metadataFile.getAbsolutePath(), e); } } } private void writeTrapDependencies(TrapDependencies trapDependencies) { String dep = trapDependencies.trapFile().replace(".trap.gz", ".dep"); trapDependencies.save( currentSpecFileEntry.getTrapFolder().toPath().resolve(dep)); } public void setHasError() { hasError = true; } } /* * Trap file locking. */ private final Pattern selectClassVersionComponents = Pattern.compile("(.*)#(-?[0-9]+)\\.(-?[0-9]+)-(-?[0-9]+)-(.*)\\.trap\\.gz"); /** * <b>CAUTION</b>: to avoid the potential for deadlock between multiple concurrent extractor processes, * only one source file {@link TrapLocker} may be open at any time, and the lock must be obtained * <b>before</b> any <b>class</b> file lock. * * Trap file extensions (and paths) ensure that source and class file locks are distinct. * * @return a {@link TrapLocker} for the currently processed source file, which must have been * previously set by a call to {@link OdasaOutput#setCurrentSourceFile(File)}. */ public TrapLocker getTrapLockerForCurrentSourceFile() { return new TrapLocker((IrClass)null, null); } /** * <b>CAUTION</b>: to avoid the potential for deadlock between multiple concurrent extractor processes, * only one jar file {@link TrapLocker} may be open at any time, and the lock must be obtained * <b>after</b> any <b>source</b> file lock. Only one jar or class file lock may be open at any time. * * Trap file extensions (and paths) ensure that source and jar file locks are distinct. * * @return a {@link TrapLocker} for the trap file corresponding to the given jar file. */ public TrapLocker getTrapLockerForJarFile(File jarFile) { return new TrapLocker(jarFile); } /** * <b>CAUTION</b>: to avoid the potential for deadlock between multiple concurrent extractor processes, * only one module {@link TrapLocker} may be open at any time, and the lock must be obtained * <b>after</b> any <b>source</b> file lock. Only one jar or class file or module lock may be open at any time. * * Trap file extensions (and paths) ensure that source and module file locks are distinct. * * @return a {@link TrapLocker} for the trap file corresponding to the given module. */ public TrapLocker getTrapLockerForModule(String moduleName) { return new TrapLocker(moduleName); } /** * <b>CAUTION</b>: to avoid the potential for deadlock between multiple concurrent extractor processes, * only one class file {@link TrapLocker} may be open at any time, and the lock must be obtained * <b>after</b> any <b>source</b> file lock. Only one jar or class file lock may be open at any time. * * Trap file extensions (and paths) ensure that source and class file locks are distinct. * * @return a {@link TrapLocker} for the trap file corresponding to the given class symbol. */ public TrapLocker getTrapLockerForDecl(IrDeclaration sym, String signature) { return new TrapLocker(sym, signature); } public class TrapLocker implements AutoCloseable { private final IrDeclaration sym; private final File trapFile; // trapFileBase is used when doing lockless TRAP file writing. // It is trapFile without the #metadata.trap.gz suffix. private File trapFileBase = null; private TrapClassVersion trapFileVersion = null; private final String signature; private TrapLocker(IrDeclaration decl, String signature) { this.sym = decl; this.signature = signature; if (sym==null) { log.error("Null symbol passed for Kotlin TRAP locker"); trapFile = null; } else { File normalTrapFile = getTrapFileForDecl(sym, signature); if (use_trap_locking) { trapFile = normalTrapFile; } else { // We encode the metadata into the filename, so that the // TRAP filenames for different metadatas don't overlap. trapFileVersion = TrapClassVersion.fromSymbol(sym, log); String baseName = normalTrapFile.getName().replace(".trap.gz", ""); // If a class has lots of inner classes, then we get lots of files // in a single directory. This makes our directory listings later slow. // To avoid this, rather than using files named .../Foo*, we use .../Foo/Foo*. trapFileBase = new File(new File(normalTrapFile.getParentFile(), baseName), baseName); trapFile = new File(trapFileBase.getPath() + '#' + trapFileVersion.toString() + ".trap.gz"); } } } private TrapLocker(File jarFile) { sym = null; signature = null; trapFile = getTrapFileForJarFile(jarFile); } private TrapLocker(String moduleName) { sym = null; signature = null; trapFile = getTrapFileForModule(moduleName); } public TrapFileManager getTrapFileManager() { if (trapFile!=null) { if (use_trap_locking) { lockTrapFile(trapFile); } return getMembersWriterForDecl(trapFile, trapFileBase, trapFileVersion, sym, signature); } else { return null; } } @Override public void close() { if (trapFile!=null) { try { if (use_trap_locking) { unlockTrapFile(trapFile); } } catch (NestedError e) { log.warn("Error unlocking trap file " + trapFile.getAbsolutePath(), e); } // If we are writing TRAP file locklessly, then now that we // have finished writing our TRAP file, we want to rename // and TRAP file that matches our trapFileBase but doesn't // have the latest metadata. // Renaming it to trap-old means that it won't be imported, // but we can still use its presence to avoid future // invocations rewriting it, and it means that the information // is in the TRAP directory if we need it for debugging. if (!use_trap_locking && sym != null) { File trapFileDir = trapFileBase.getParentFile(); String trapFileBaseName = trapFileBase.getName(); List<Pair<File, TrapClassVersion>> pairs = new LinkedList<Pair<File, TrapClassVersion>>(); for (File f: FileUtil.list(trapFileDir)) { String name = f.getName(); Matcher m = selectClassVersionComponents.matcher(name); if (m.matches()) { if (m.group(1).equals(trapFileBaseName)) { TrapClassVersion v = new TrapClassVersion(Integer.valueOf(m.group(2)), Integer.valueOf(m.group(3)), Long.valueOf(m.group(4)), m.group(5)); pairs.add(new Pair<File, TrapClassVersion>(f, v)); } else { // Everything in this directory should be for the same TRAP file base log.error("Unexpected sibling " + m.group(1) + " when extracting " + trapFileBaseName); } } } if (pairs.isEmpty()) { log.error("Wrote TRAP file, but no TRAP files exist for " + trapFile.getAbsolutePath()); } else { Comparator<Pair<File, TrapClassVersion>> comparator = new Comparator<Pair<File, TrapClassVersion>>() { @Override public int compare(Pair<File, TrapClassVersion> p1, Pair<File, TrapClassVersion> p2) { TrapClassVersion v1 = p1.snd(); TrapClassVersion v2 = p2.snd(); if (v1.equals(v2)) { return 0; } else if (v1.newerThan(v2)) { return 1; } else { return -1; } } }; TrapClassVersion latestVersion = Collections.max(pairs, comparator).snd(); for (Pair<File, TrapClassVersion> p: pairs) { if (!latestVersion.equals(p.snd())) { File f = p.fst(); File fOld = new File(f.getParentFile(), f.getName().replace(".trap.gz", ".trap-old.gz")); // We aren't interested in whether or not this succeeds; // it may fail because a concurrent extractor has already // renamed it. f.renameTo(fOld); } } } } } } private LockDirectory getExtractorLockDir() { return LockDirectory.instance(currentSpecFileEntry.getTrapFolder(), log); } private void lockTrapFile(File trapFile) { getExtractorLockDir().blockingLock(LockingMode.Exclusive, trapFile, "Java extractor lock"); } private void unlockTrapFile(File trapFile) { boolean success = getExtractorLockDir().maybeUnlock(LockingMode.Exclusive, trapFile); if (!success) { log.warn("Trap file was not locked: " + trapFile); } } } /* * Class version tracking. */ private static final String MAJOR_VERSION = "majorVersion"; private static final String MINOR_VERSION = "minorVersion"; private static final String LAST_MODIFIED = "lastModified"; private static final String EXTRACTOR_NAME = "extractorName"; private static class TrapClassVersion { private int majorVersion; private int minorVersion; private long lastModified; private String extractorName; // May be null if not given public int getMajorVersion() { return majorVersion; } public int getMinorVersion() { return minorVersion; } public long getLastModified() { return lastModified; } public String getExtractorName() { return extractorName; } private TrapClassVersion(int majorVersion, int minorVersion, long lastModified, String extractorName) { this.majorVersion = majorVersion; this.minorVersion = minorVersion; this.lastModified = lastModified; this.extractorName = extractorName; } @Override public boolean equals(Object obj) { if (obj instanceof TrapClassVersion) { TrapClassVersion other = (TrapClassVersion)obj; return majorVersion == other.majorVersion && minorVersion == other.minorVersion && lastModified == other.lastModified && extractorName.equals(other.extractorName); } else { return false; } } private boolean newerThan(TrapClassVersion tcv) { // Classes being compiled from source have major version 0 but should take precedence // over any classes with the same qualified name loaded from the classpath // in previous or subsequent extractor invocations. if (tcv.majorVersion == 0 && majorVersion != 0) return false; else if (majorVersion == 0 && tcv.majorVersion != 0) return true; // Always consider the Kotlin extractor superior to the Java extractor, because we may decode and extract // Kotlin metadata that the Java extractor can't understand: if(!Objects.equals(tcv.extractorName, extractorName)) { if (Objects.equals(tcv.extractorName, "kotlin")) return false; if (Objects.equals(extractorName, "kotlin")) return true; } // Otherwise, determine precedence in the following order: // majorVersion, minorVersion, lastModified. return tcv.majorVersion < majorVersion || (tcv.majorVersion == majorVersion && tcv.minorVersion < minorVersion) || (tcv.majorVersion == majorVersion && tcv.minorVersion == minorVersion && tcv.lastModified < lastModified); } private static Map<String, Map<String, Long>> jarFileEntryTimeStamps = new HashMap<>(); private static Map<String, Long> getZipFileEntryTimeStamps(String path, Logger log) { try { Map<String, Long> result = new HashMap<>(); ZipFile zf = new ZipFile(path); Enumeration<? extends ZipEntry> entries = zf.entries(); while (entries.hasMoreElements()) { ZipEntry ze = entries.nextElement(); result.put(ze.getName(), ze.getLastModifiedTime().toMillis()); } return result; } catch(IOException e) { log.warn("Failed to get entry timestamps from " + path, e); return null; } } private static long getVirtualFileTimeStamp(VirtualFile vf, Logger log) { if (vf.getFileSystem().getProtocol().equals("jar")) { String[] parts = vf.getPath().split("!/"); if (parts.length == 2) { String jarFilePath = parts[0]; String entryPath = parts[1]; if (!jarFileEntryTimeStamps.containsKey(jarFilePath)) { jarFileEntryTimeStamps.put(jarFilePath, getZipFileEntryTimeStamps(jarFilePath, log)); } Map<String, Long> entryTimeStamps = jarFileEntryTimeStamps.get(jarFilePath); if (entryTimeStamps != null) { Long entryTimeStamp = entryTimeStamps.get(entryPath); if (entryTimeStamp != null) return entryTimeStamp; else log.warn("Couldn't find timestamp for jar file " + jarFilePath + " entry " + entryPath); } } else { log.warn("Expected JAR-file path " + vf.getPath() + " to have exactly one '!/' separator"); } } // For all files except for jar files, and a fallback in case of I/O problems reading a jar file: return vf.getTimeStamp(); } private static TrapClassVersion fromSymbol(IrDeclaration sym, Logger log) { VirtualFile vf = sym instanceof IrClass ? getIrClassVirtualFile((IrClass)sym) : sym.getParent() instanceof IrClass ? getIrClassVirtualFile((IrClass)sym.getParent()) : null; if(vf == null) return new TrapClassVersion(-1, 0, 0, null); final int[] versionStore = new int[1]; try { // Opcodes has fields called ASM4, ASM5, ... // We want to use the latest one that there is. Field asmField = null; int asmNum = -1; for(Field f : Opcodes.class.getDeclaredFields()) { String name = f.getName(); if(name.startsWith("ASM")) { try { int i = Integer.parseInt(name.substring(3)); if(i > asmNum) { asmNum = i; asmField = f; } } catch (NumberFormatException ex) { // Do nothing; this field doesn't have a name of the right format } } } int asm = asmField.getInt(null); ClassVisitor versionGetter = new ClassVisitor(asm) { public void visit(int version, int access, java.lang.String name, java.lang.String signature, java.lang.String superName, java.lang.String[] interfaces) { versionStore[0] = version; } }; (new ClassReader(vf.contentsToByteArray())).accept(versionGetter, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); return new TrapClassVersion(versionStore[0] & 0xffff, versionStore[0] >> 16, getVirtualFileTimeStamp(vf, log), "kotlin"); } catch(IllegalAccessException e) { log.warn("Failed to read class file version information", e); return new TrapClassVersion(-1, 0, 0, null); } catch(IOException e) { log.warn("Failed to read class file version information", e); return new TrapClassVersion(-1, 0, 0, null); } } private boolean isValid() { return majorVersion>=0 && minorVersion>=0; } @Override public String toString() { return majorVersion + "." + minorVersion + "-" + lastModified + "-" + extractorName; } } private TrapClassVersion readVersionInfo(File trap) { int majorVersion = 0; int minorVersion = 0; long lastModified = 0; String extractorName = null; File metadataFile = new File(trap.getAbsolutePath().replace(".trap.gz", ".metadata")); if (metadataFile.exists()) { Map<String,String> metadataMap = FileUtil.readPropertiesCSV(metadataFile); try { majorVersion = Integer.parseInt(metadataMap.get(MAJOR_VERSION)); minorVersion = Integer.parseInt(metadataMap.get(MINOR_VERSION)); lastModified = Long.parseLong(metadataMap.get(LAST_MODIFIED)); extractorName = metadataMap.get(EXTRACTOR_NAME); } catch (NumberFormatException e) { log.warn("Invalid class file version for " + trap.getAbsolutePath(), e); } } else { log.warn("Trap metadata file does not exist: " + metadataFile.getAbsolutePath()); } return new TrapClassVersion(majorVersion, minorVersion, lastModified, extractorName); } }
package org.pentaho.di.ui.repository.repositoryexplorer.controllers; import java.util.Collection; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.pentaho.di.core.Const; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.ui.core.database.dialog.DatabaseDialog; import org.pentaho.di.ui.core.dialog.ErrorDialog; import org.pentaho.di.ui.repository.repositoryexplorer.ControllerInitializationException; import org.pentaho.di.ui.repository.repositoryexplorer.IUISupportController; import org.pentaho.di.ui.repository.repositoryexplorer.RepositoryExplorer; import org.pentaho.di.ui.repository.repositoryexplorer.model.UIDatabaseConnection; import org.pentaho.di.ui.repository.repositoryexplorer.model.UIDatabaseConnections; import org.pentaho.ui.xul.binding.Binding; import org.pentaho.ui.xul.binding.BindingConvertor; import org.pentaho.ui.xul.binding.BindingFactory; import org.pentaho.ui.xul.binding.DefaultBindingFactory; import org.pentaho.ui.xul.components.XulButton; import org.pentaho.ui.xul.containers.XulTree; import org.pentaho.ui.xul.impl.AbstractXulEventHandler; import org.pentaho.ui.xul.swt.tags.SwtDialog; public class ConnectionsController extends AbstractXulEventHandler implements IUISupportController { private static Class<?> PKG = RepositoryExplorer.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private XulTree connectionsTable = null; protected BindingFactory bf = null; private Repository repository = null;; private boolean isRepReadOnly = true; private Binding bindButtonNew = null; private Binding bindButtonEdit = null; private Binding bindButtonRemove = null; private Shell shell = null; private boolean initComplete = false; private UIDatabaseConnections dbConnectionList = new UIDatabaseConnections(); private DatabaseDialog databaseDialog; public ConnectionsController() { } @Override public String getName() { return "connectionsController"; //$NON-NLS-1$ } public void init(Repository repository) throws ControllerInitializationException { this.repository = repository; setRepReadOnly(this.repository.getRepositoryMeta().getRepositoryCapabilities().isReadOnly()); // Load the SWT Shell from the explorer dialog shell = ((SwtDialog) document.getElementById("repository-explorer-dialog")).getShell(); //$NON-NLS-1$ bf = new DefaultBindingFactory(); bf.setDocument(this.getXulDomContainer().getDocumentRoot()); if (bf != null) { createBindings(); } setEnableButtons(false); initComplete = true; } private DatabaseDialog getDatabaseDialog(){ if(databaseDialog != null){ return databaseDialog; } databaseDialog = new DatabaseDialog(shell); return databaseDialog; } private void createBindings() { connectionsTable = (XulTree) document.getElementById("connections-table"); //$NON-NLS-1$ // Bind the connection table to a list of connections bf.setBindingType(Binding.Type.ONE_WAY); try { bf.createBinding(dbConnectionList, "children", connectionsTable, "elements").fireSourceChanged(); //$NON-NLS-1$ //$NON-NLS-2$ (bindButtonNew = bf.createBinding(this, "repReadOnly", "connections-new", "disabled")).fireSourceChanged(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ (bindButtonEdit = bf.createBinding(this, "repReadOnly", "connections-edit", "disabled")).fireSourceChanged(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ (bindButtonRemove = bf.createBinding(this, "repReadOnly", "connections-remove", "disabled")).fireSourceChanged(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (repository != null) { bf.createBinding(connectionsTable, "selectedItems", this, "enableButtons", //$NON-NLS-1$ //$NON-NLS-2$ new BindingConvertor<List<UIDatabaseConnection>, Boolean>() { @Override public Boolean sourceToTarget(List<UIDatabaseConnection> dbConnList) { // Enable / Disable New,Edit,Remove buttons if (dbConnList != null && dbConnList.size() > 0) { return true; } return false; } @Override public List<UIDatabaseConnection> targetToSource(Boolean enable) { return null; } }); } } catch (Exception ex) { // convert to runtime exception so it bubbles up through the UI throw new RuntimeException(ex); } refreshConnectionList(); } public Repository getRepository() { return repository; } public void setRepReadOnly(boolean isRepReadOnly) { try { if (this.isRepReadOnly != isRepReadOnly) { this.isRepReadOnly = isRepReadOnly; if (initComplete) { bindButtonNew.fireSourceChanged(); bindButtonEdit.fireSourceChanged(); bindButtonRemove.fireSourceChanged(); } } } catch (Exception e) { // convert to runtime exception so it bubbles up through the UI throw new RuntimeException(e); } } public boolean isRepReadOnly() { return isRepReadOnly; } private void refreshConnectionList() { try { dbConnectionList.clear(); ObjectId[] dbIdList = repository.getDatabaseIDs(false); for (ObjectId dbId : dbIdList) { DatabaseMeta dbMeta = repository.loadDatabaseMeta(dbId, null); // Add the database connection to the list dbConnectionList.add(new UIDatabaseConnection(dbMeta)); } } catch (KettleException e) { // convert to runtime exception so it bubbles up through the UI throw new RuntimeException(e); } } public void createConnection() { try { DatabaseMeta databaseMeta = new DatabaseMeta(); databaseMeta.initializeVariablesFrom(null); getDatabaseDialog().setDatabaseMeta(databaseMeta); String dbName = getDatabaseDialog().open(); if (dbName != null && !dbName.equals(""))//$NON-NLS-1$ { // See if this user connection exists... ObjectId idDatabase = repository.getDatabaseID(dbName); if (idDatabase == null) { repository.insertLogEntry(BaseMessages.getString(PKG, "ConnectionsController.Message.CreatingDatabase", getDatabaseDialog().getDatabaseMeta().getName()));//$NON-NLS-1$ repository.save(getDatabaseDialog().getDatabaseMeta(), Const.VERSION_COMMENT_INITIAL_VERSION, null); } else { MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); mb.setMessage(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Create.AlreadyExists.Message")); //$NON-NLS-1$ mb.setText(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Create.AlreadyExists.Title")); //$NON-NLS-1$ mb.open(); } } // We should be able to tell the difference between a cancel and an empty database name // else { // MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); // mb.setMessage(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Edit.MissingName.Message")); //$NON-NLS-1$ // mb.setText(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Edit.MissingName.Title")); //$NON-NLS-1$ // mb.open(); } catch (KettleException e) { new ErrorDialog( shell, BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Create.UnexpectedError.Title"), //$NON-NLS-1$ BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Create.UnexpectedError.Message"), e); //$NON-NLS-1$ } finally { refreshConnectionList(); } } public void editConnection() { try { Collection<UIDatabaseConnection> connections = connectionsTable.getSelectedItems(); if (connections != null && !connections.isEmpty()) { // Grab the first item in the list & send it to the database dialog DatabaseMeta databaseMeta = ((UIDatabaseConnection) connections.toArray()[0]).getDatabaseMeta(); // Make sure this connection already exists and store its id for updating ObjectId idDatabase = repository.getDatabaseID(databaseMeta.getName()); if (idDatabase == null) { MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); mb.setMessage(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Edit.DoesNotExists.Message")); //$NON-NLS-1$ mb.setText(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Edit.DoesNotExists.Title")); //$NON-NLS-1$ mb.open(); } else { getDatabaseDialog().setDatabaseMeta(databaseMeta); String dbName = getDatabaseDialog().open(); if (dbName != null && !dbName.equals("")) //$NON-NLS-1$ { repository.insertLogEntry(BaseMessages.getString(PKG, "ConnectionsController.Message.UpdatingDatabase", databaseMeta.getName()));//$NON-NLS-1$ repository.save(databaseMeta, Const.VERSION_COMMENT_EDIT_VERSION, null); } // We should be able to tell the difference between a cancel and an empty database name // else { // MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); // mb.setMessage(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Edit.MissingName.Message")); //$NON-NLS-1$ // mb.setText(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Edit.MissingName.Title")); //$NON-NLS-1$ // mb.open(); } } else { MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); mb.setMessage(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Edit.NoItemSelected.Message")); //$NON-NLS-1$ mb.setText(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Edit.NoItemSelected.Title")); //$NON-NLS-1$ mb.open(); } } catch (KettleException e) { new ErrorDialog( shell, BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Create.UnexpectedError.Title"), //$NON-NLS-1$ BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Create.UnexpectedError.Message"), e); //$NON-NLS-1$ } finally { refreshConnectionList(); } } public void removeConnection() { try { Collection<UIDatabaseConnection> connections = connectionsTable.getSelectedItems(); if (connections != null && !connections.isEmpty()) { // Grab the first item in the list & send it to the database dialog DatabaseMeta databaseMeta = ((UIDatabaseConnection) connections.toArray()[0]).getDatabaseMeta(); // Make sure this connection already exists and store its id for updating ObjectId idDatabase = repository.getDatabaseID(databaseMeta.getName()); if (idDatabase == null) { MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); mb.setMessage(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Delete.DoesNotExists.Message", databaseMeta.getName())); //$NON-NLS-1$ mb.setText(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Delete.Title")); //$NON-NLS-1$ mb.open(); } else { repository.deleteDatabaseMeta(databaseMeta.getName()); } } else { MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); mb.setMessage(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Edit.NoItemSelected.Message")); //$NON-NLS-1$ mb.setText(BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Delete.Title")); //$NON-NLS-1$ mb.open(); } } catch (KettleException e) { new ErrorDialog( shell, BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Create.UnexpectedError.Title"), //$NON-NLS-1$ BaseMessages.getString(PKG, "RepositoryExplorerDialog.Connection.Create.UnexpectedError.Message"), e); //$NON-NLS-1$ } finally { refreshConnectionList(); } } public void setEnableButtons(boolean enable) { // Convenience - Leave 'new' enabled, modify 'edit' and 'remove' enableButtons(true, enable, enable); } public void enableButtons(boolean enableNew, boolean enableEdit, boolean enableRemove) { XulButton bNew = (XulButton) document.getElementById("connections-new"); //$NON-NLS-1$ XulButton bEdit = (XulButton) document.getElementById("connections-edit"); //$NON-NLS-1$ XulButton bRemove = (XulButton) document.getElementById("connections-remove"); //$NON-NLS-1$ bNew.setDisabled(!enableNew); bEdit.setDisabled(!enableEdit); bRemove.setDisabled(!enableRemove); } }
package org.jtrfp.trcl.math; public final class Vect3D { private static final boolean CATCH_NAN = true; private static final boolean CATCH_POS_INF = false; private static final boolean CATCH_NEG_INF = false; public static void subtract(double[] l, double[] r, double[] dest) { dest[0]=l[0]-r[0]; dest[1]=l[1]-r[1]; dest[2]=l[2]-r[2]; checkValues(l); checkValues(r); checkValues(dest); }//end subtract public static boolean isAnyEqual(double [] valuesToCheck, double compare){ boolean result = false; for(double d:valuesToCheck) result |= d==compare; return result; }//end isAnyNaN() public static boolean isAnyEqual(float [] valuesToCheck, float compare){ boolean result = false; for(float f:valuesToCheck) result |= f==compare; return result; }//end isAnyEqual() public static boolean isAnyNaN(float... valuesToCheck) { boolean result = false; for(float f:valuesToCheck) result |= Float.isNaN(f); return result; } public static boolean isAnyNaN(double... valuesToCheck) { boolean result = false; for(double d:valuesToCheck) result |= Double.isNaN(d); return result; } // If all switches are false, this should completely compile out in JIT private static void checkValues(double [] vals){ if(CATCH_NAN) assert !isAnyNaN(vals); if(CATCH_POS_INF) assert !isAnyEqual(vals,Double.POSITIVE_INFINITY); if(CATCH_NEG_INF) assert !isAnyEqual(vals,Double.NEGATIVE_INFINITY); } private static void checkValues(float [] vals){ if(CATCH_NAN) assert !isAnyNaN(vals); if(CATCH_POS_INF) assert !isAnyEqual(vals,Float.POSITIVE_INFINITY); if(CATCH_NEG_INF) assert !isAnyEqual(vals,Float.NEGATIVE_INFINITY); } public static double[] scalarMultiply(double [] src, double scalar, double[] dest) { dest[0]=src[0]*scalar; dest[1]=src[1]*scalar; dest[2]=src[2]*scalar; checkValues(src); checkValues(dest); return dest; } public static double[] normalize(double[] src){ return normalize(src,new double[3]); } public static double[] normalize(double[] src, double [] dest) { final double norm = norm(src); dest[0]=src[0]/norm; dest[1]=src[1]/norm; dest[2]=src[2]/norm; checkValues(src); checkValues(dest); return dest; } public static double norm(double[] src) { final double x=src[0]; final double y=src[1]; final double z=src[2]; checkValues(src); return Math.sqrt(x*x+y*y+z*z); } public static double [] add(double[] l, double rx, double ry, double rz, double[] dest) { dest[0]=l[0]+rx; dest[1]=l[1]+ry; dest[2]=l[2]+rz; checkValues(l);checkValues(dest); return dest; } public static double[] add(double[] l, double[] r, double[] dest) { dest[0]=l[0]+r[0]; dest[1]=l[1]+r[1]; dest[2]=l[2]+r[2]; checkValues(l); checkValues(r); checkValues(dest); return dest; } public static double distance(double[] l, double[] r) { checkValues(l); checkValues(r); final double dx=l[0]-r[0]; final double dy=l[1]-r[1]; final double dz=l[2]-r[2]; return Math.sqrt(dx*dx + dy*dy + dz*dz); } public static double taxicabDistance(double [] l, double [] r){ checkValues(l); checkValues(r); final double dx=Math.abs(l[0]-r[0]); final double dy=Math.abs(l[1]-r[1]); final double dz=Math.abs(l[2]-r[2]); return dx+dy+dz; } public static double[] negate(double[] in) { in[0]=-in[0]; in[1]=-in[1]; in[2]=-in[2]; return in; } public static double [] cross(double [] l, double [] r, double []dest){ checkValues(l); checkValues(r); dest[0]=l[1]*r[2]-l[2]*r[1]; dest[1]=l[2]*r[0]-l[0]*r[2]; dest[2]=l[0]*r[1]-l[1]*r[0]; return dest; } public static double distanceXZ(double[] l, double[] r) { checkValues(l);checkValues(r); final double dx=l[0]-r[0]; final double dz=l[2]-r[2]; return Math.sqrt(dx*dx + dz*dz); } public static float [] normalize(float[] val) { checkValues(val); final double norm = norm(val); val[0]/=norm; val[1]/=norm; val[2]/=norm; return val; } private static double norm(float[] val) { checkValues(val); int a=0; for(float v:val) a+=v*v; return Math.sqrt(a); } public static float[] scalarMultiply(float[] src, int scalar, float[] dest) { dest[0]=src[0]*scalar; dest[1]=src[1]*scalar; dest[2]=src[2]*scalar; checkValues(src); checkValues(dest); return dest; }//end scalarMultiply() }//end Vect3D
package org.myrobotlab.service; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.interfaces.ServiceInterface; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.config.PirConfig; import org.myrobotlab.service.config.ServiceConfig; import org.myrobotlab.service.data.PinData; import org.myrobotlab.service.interfaces.PinArrayControl; import org.myrobotlab.service.interfaces.PinListener; import org.slf4j.Logger; public class Pir extends Service implements PinListener { public final static Logger log = LoggerFactory.getLogger(Pir.class); private static final long serialVersionUID = 1L; String controllerName; /** * yep there are 3 states to a binary sensor true/false .... and unknown - we * start with "unknown" */ Boolean active = null; boolean isEnabled = false; String pin; transient PinArrayControl pinControl; int rateHz = 1; Long lastChangeTs = null; public Pir(String n, String id) { super(n, id); registerForInterfaceChange(PinArrayControl.class); } @Deprecated /* use attach(String) or attachPinArrayControl(PinArrayControl) */ public void attach(PinArrayControl control, String pin) { setPin(pin); attachPinArrayControl(control); } @Override public void attach(String name) { ServiceInterface si = Runtime.getService(name); if (si instanceof PinArrayControl) { attachPinArrayControl((PinArrayControl) si); } else { error("do not know how to attach to %s of type %s", name, si.getSimpleName()); } } public void attachPinArrayControl(PinArrayControl control) { try { if (this.pinControl != null) { info("already attached detach first"); return; } this.pinControl = control; controllerName = control.getName(); if (pin == null) { error("pin should be set before attaching"); } pinControl.attach(getName()); broadcastState(); } catch (Exception e) { error(e); } } @Override public void detach(String name) { ServiceInterface si = Runtime.getService(name); if (si instanceof PinArrayControl) { // FIXME - problem - what if someone else is using this pin ? // FIXME - should disable in the context of this service's name ((PinArrayControl) si).disablePin(pin); detachPinArrayControl((PinArrayControl) si); } else { error("do not know how to detach to %s of type %s", name, si.getSimpleName()); } active = null; isEnabled = false; broadcastState(); } public void detachPinArrayControl(PinArrayControl control) { try { if (control == null) { log.warn("detaching null"); return; } if (controllerName != null) { if (!controllerName.equals(control.getName())) { log.warn("attempting to detach {} but this pir is attached to {}", control.getName(), controllerName); return; } } // FYI - we could detach like this without a reference - good for remote // send(controllerName, "detach", getName()); pinControl.detach(getName()); this.pinControl = null; controllerName = null; broadcastState(); } catch (Exception e) { error(e); } } public void disable() { if (pinControl == null) { error("pin control not set"); return; } if (pin == null) { error("pin not set"); return; } // FIXME - use pinListener pub/sub pinControl.disablePin(pin); isEnabled = false; active = null; broadcastState(); } public void enable() { enable(rateHz); } public void enable(int pollBySecond) { if (pinControl == null) { error("pin control not set"); return; } if (pin == null) { error("pin not set"); return; } pinControl.enablePin(pin, pollBySecond); isEnabled = true; broadcastState(); } @Override public PirConfig getConfig() { PirConfig config = new PirConfig(); config.controller = controllerName; config.pin = pin; config.enable = isEnabled; config.rate = rateHz; return config; } @Override public String getPin() { return pin; } public int getRate() { return rateHz; } public boolean isActive() { return active; } public boolean isEnabled() { return isEnabled; } public ServiceConfig apply(ServiceConfig c) { PirConfig config = (PirConfig) c; if (config.pin != null) setPin(config.pin); if (config.rate != null) setRate(config.rate); if (config.controller != null) { try { attach(config.controller); } catch (Exception e) { error(e); } } if (config.enable) { enable(); } else { disable(); } return c; } @Override public void onPin(PinData pindata) { log.info("onPin {}", pindata); boolean sense = (pindata.value != 0); // sparse publishing only on state change if (active == null) { invoke("publishSense", sense); active = sense; } else if (active != sense) { // state change invoke("publishSense", sense); active = sense; lastChangeTs = System.currentTimeMillis(); } } public Boolean publishSense(Boolean b) { return b; } public void setPin(String pin) { this.pin = pin; } @Deprecated /* use attach(String) */ public void setPinArrayControl(PinArrayControl pinControl) { this.pinControl = pinControl; controllerName = pinControl.getName(); } public void setRate(int rateHz) { this.rateHz = rateHz; } public Long getLastChangeTs() { return lastChangeTs; } public static void main(String[] args) { try { LoggingFactory.init("info"); Pir pir = (Pir) Runtime.start("pir", "Pir"); pir.setPin("D6"); Runtime.start("webgui", "WebGui"); Arduino mega = (Arduino) Runtime.start("mega", "Arduino"); mega.connect("/dev/ttyACM2"); boolean done = true; if (done) { return; } mega.attach(pir); // Runtime.setAllVirtual(true); mega.connect("/dev/ttyACM0"); pir.setPin("D23"); pir.attach(mega); pir.enable(); } catch (Exception e) { log.error("main threw", e); } } }
package org.titans.fyp; import java.io.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class Calculation { public static String output_folder = "./LawIE/DocVector/Output"; public List<List<Double>> CalDocumentVector(List<String> inputWordList, HashSet<String> vocabulary, double[][] t_matrix) { List<List<Double>> DocumentVector = new ArrayList<List<Double>>(); File f = new File(output_folder); FilenameFilter textFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".txt"); } }; File[] files = f.listFiles(textFilter); for (int docIndex = 0; docIndex < files.length; docIndex++) { try { String fileName = (files[docIndex]).getCanonicalPath(); DocumentVector.add(docVector(fileName, docIndex, inputWordList, vocabulary, t_matrix)); } catch (IOException e) { e.printStackTrace(); } } return DocumentVector; } public static int getIndex(HashSet<String> set, String value) { int result = 0; for (String entry : set) { if (entry.equals(value)) { return result; } result++; } return result; } public List<Double> docVector(String fileName, int docIndex, List<String> inputWordList, HashSet<String> vocabulary, double[][] t_matrix) { BufferedReader br = null; List<Double> docVector = new ArrayList<Double>(); try { br = new BufferedReader(new FileReader(fileName)); StringBuilder sb = new StringBuilder(); String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { sb.append(sCurrentLine.toLowerCase()); sb.append(" "); } String paragraph = sb.toString(); for (String word : inputWordList) { if (paragraph.contains(word)) { int index = getIndex(vocabulary, word); try { docVector.add(t_matrix[index][docIndex]); } catch (Exception e) { e.printStackTrace(); } } else { docVector.add(0.0); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return docVector; } private List<List<Double>> normalize_vectors(List<List<Double>> document_vector) { for (int i = 0; i < document_vector.size(); i++) { Double sum = 0.0; for (int j = 0; j < document_vector.get(i).size(); j++) { sum += document_vector.get(i).get(j); } for (int j = 0; j < document_vector.get(i).size(); j++) { if (!sum.equals(0.0)) { document_vector.get(i).set(j, document_vector.get(i).get(j) / sum); } } } return document_vector; } private void serialize_document_vector(List<List<Double>> document_vector) { try { FileOutputStream fileOut = new FileOutputStream(Tf_idf_Calculator.serialized_folder + File.separator + "document_vector.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(document_vector); out.close(); fileOut.close(); System.out.printf("Serialized data is saved in " + Tf_idf_Calculator.serialized_folder + File.separator + "document_vector.ser"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private List<String> getPWordList() { List<String> p_words_list = null; try { File file = new File(Tf_idf_Calculator.serialized_folder + File.separator + "p_list.ser"); if (file.exists()) { System.out.println("P_LIST serialized file found. Reading from it"); FileInputStream fileIn = new FileInputStream(file); ObjectInputStream in = new ObjectInputStream(fileIn); p_words_list = (List<String>) in.readObject(); in.close(); fileIn.close(); } else { System.out.println("P_LIST word serlized file not found in" + Tf_idf_Calculator.serialized_folder + File.separator + "p_list.ser"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return p_words_list; } private HashSet<String> getVocabulary() { HashSet<String> vocabulary = null; try { File file = new File(Tf_idf_Calculator.serialized_folder + File.separator + "vocabulary.ser"); if (file.exists()) { System.out.println("Vocabulary serialized file found. Reading from it"); FileInputStream fileIn = new FileInputStream(file); ObjectInputStream in = new ObjectInputStream(fileIn); vocabulary = (HashSet<String>) in.readObject(); in.close(); fileIn.close(); } else { System.out.println("Vocabulary serialized file not found in " + Tf_idf_Calculator.serialized_folder + File.separator + "vocabulary.ser"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return vocabulary; } private double[][] getTMatrix() { double[][] t_matrix = null; try { File file = new File(Tf_idf_Calculator.serialized_folder + File.separator + "t_matrix.ser"); if (file.exists()) { System.out.println("t_matrix serialized file found. Reading from it"); FileInputStream fileIn = new FileInputStream(file); ObjectInputStream in = new ObjectInputStream(fileIn); t_matrix = (double[][]) in.readObject(); in.close(); fileIn.close(); } else { System.out.println("t_matrix serialized file not found in " + Tf_idf_Calculator.serialized_folder + File.separator + "t_matrix.ser"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return t_matrix; } public static void main(String[] args) { if (args.length == 2) { Tf_idf_Calculator.serialized_folder = args[0]; output_folder = args[1]; System.out.println("Serialized Folder = " + Tf_idf_Calculator.serialized_folder); System.out.println("Output Folder = " + output_folder); } if (args.length == 3) { Tf_idf_Calculator.cases_folder_path = args[0]; Tf_idf_Calculator.serialized_folder = args[1]; output_folder = args[2]; System.out.println("Cases Folder = " + Tf_idf_Calculator.cases_folder_path); System.out.println("Serialized Folder = " + Tf_idf_Calculator.serialized_folder); System.out.println("Output Folder = " + output_folder); } Calculation cal = new Calculation(); List<String> p_words_list = cal.getPWordList(); HashSet<String> vocabulary = cal.getVocabulary(); double[][] t_matrix = cal.getTMatrix(); List<List<Double>> document_vector = cal.CalDocumentVector(p_words_list, vocabulary, t_matrix); document_vector = cal.normalize_vectors(document_vector); cal.serialize_document_vector(document_vector); } }
package com.intellij.codeInsight.documentation; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.TargetElementUtilBase; import com.intellij.codeInsight.hint.HintManagerImpl; import com.intellij.codeInsight.hint.ParameterInfoController; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.ide.BrowserUtil; import com.intellij.ide.DataManager; import com.intellij.ide.util.gotoByName.ChooseByNameBase; import com.intellij.lang.Language; import com.intellij.lang.LanguageDocumentation; import com.intellij.lang.documentation.CompositeDocumentationProvider; import com.intellij.lang.documentation.DocumentationProvider; import com.intellij.lang.documentation.ExtensibleDocumentationProvider; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.*; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.psi.*; import com.intellij.psi.presentation.java.SymbolPresentationUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.ui.popup.AbstractPopup; import com.intellij.ui.popup.NotLookupOrSearchCondition; import com.intellij.ui.popup.PopupUpdateProcessor; import com.intellij.util.Alarm; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.lang.ref.WeakReference; import java.util.LinkedHashSet; import java.util.Set; public class DocumentationManager { @NonNls public static final String JAVADOC_LOCATION_AND_SIZE = "javadoc.popup"; private final Project myProject; private Editor myEditor = null; private ParameterInfoController myParameterInfoController; private final Alarm myUpdateDocAlarm = new Alarm(Alarm.ThreadToUse.OWN_THREAD); private WeakReference<JBPopup> myDocInfoHintRef; private Component myPreviouslyFocused = null; public static final Key<SmartPsiElementPointer> ORIGINAL_ELEMENT_KEY = Key.create("Original element"); @NonNls public static final String PSI_ELEMENT_PROTOCOL = "psi_element: @NonNls private static final String DOC_ELEMENT_PROTOCOL = "doc_element: private final ActionManagerEx myActionManagerEx; private static final int ourFlagsForTargetElements = TargetElementUtilBase.getInstance().getAllAccepted(); public static DocumentationManager getInstance(Project project) { return ServiceManager.getService(project, DocumentationManager.class); } public DocumentationManager(Project project, ActionManagerEx managerEx) { myProject = project; myActionManagerEx = managerEx; final AnActionListener actionListener = new AnActionListener() { public void beforeActionPerformed(AnAction action, DataContext dataContext) { final JBPopup hint = getDocInfoHint(); if (hint != null) { if (action instanceof HintManagerImpl.ActionToIgnore) return; if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN)) return; if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_UP)) return; if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_PAGE_DOWN)) return; if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_PAGE_UP)) return; if (action == ActionManagerEx.getInstanceEx().getAction(IdeActions.ACTION_EDITOR_ESCAPE)) return; hint.cancel(); } } public void beforeEditorTyping(char c, DataContext dataContext) { final JBPopup hint = getDocInfoHint(); if (hint != null) { hint.cancel(); } } public void afterActionPerformed(final AnAction action, final DataContext dataContext) { } }; myActionManagerEx.addAnActionListener(actionListener, project); } public JBPopup showJavaDocInfo(@NotNull final PsiElement element, final PsiElement original) { PopupUpdateProcessor updateProcessor = new PopupUpdateProcessor() { public void updatePopup(Object lookupItemObject) { if (lookupItemObject instanceof PsiElement) { doShowJavaDocInfo((PsiElement)lookupItemObject, true, false, this, original); } } }; return doShowJavaDocInfo(element, true, false, updateProcessor, original); } @Nullable public JBPopup showJavaDocInfo(final Editor editor, @Nullable final PsiFile file, boolean requestFocus) { myEditor = editor; final Project project = getProject(file); PsiDocumentManager.getInstance(project).commitAllDocuments(); final PsiElement list = ParameterInfoController.findArgumentList(file, editor.getCaretModel().getOffset(), -1); if (list != null) { myParameterInfoController = ParameterInfoController.findControllerAtOffset(editor, list.getTextRange().getStartOffset()); } final PsiElement originalElement = file != null ? file.findElementAt(editor.getCaretModel().getOffset()) : null; PsiElement element = findTargetElement(editor, file, originalElement); if (element == null && myParameterInfoController != null) { final Object[] objects = myParameterInfoController.getSelectedElements(); if (objects != null && objects.length > 0) { if (objects[0] instanceof PsiElement) { element = (PsiElement)objects[0]; } } } if (element == null && file == null) return null; //file == null for text field editor if (element == null) { // look if we are within a javadoc comment element = originalElement; if (element == null) return null; PsiComment comment = PsiTreeUtil.getParentOfType(element, PsiComment.class); if (comment == null) return null; element = comment.getParent(); //if (!(element instanceof PsiDocCommentOwner)) return null; } storeOriginalElement(project, originalElement, element); final PopupUpdateProcessor updateProcessor = new PopupUpdateProcessor() { public void updatePopup(Object lookupIteObject) { if (lookupIteObject instanceof PsiElement) { doShowJavaDocInfo((PsiElement)lookupIteObject, false, false, this, originalElement); return; } DocumentationProvider documentationProvider = getProviderFromElement(file); PsiElement element = null; if (documentationProvider!=null) { element = documentationProvider.getDocumentationElementForLookupItem( PsiManager.getInstance(myProject), lookupIteObject, originalElement ); } if (element == null) return; if (myEditor != null) { final PsiFile file = element.getContainingFile(); if (file != null) { Editor editor = myEditor; showJavaDocInfo(myEditor, file, false); myEditor = editor; } } else { doShowJavaDocInfo(element, false, false, this, originalElement); } } }; return doShowJavaDocInfo(element, false, requestFocus, updateProcessor, originalElement); } private JBPopup doShowJavaDocInfo(PsiElement element, boolean heavyWeight, boolean requestFocus, PopupUpdateProcessor updateProcessor, PsiElement originalElement) { Project project = getProject(element); final DocumentationComponent component = new DocumentationComponent(this); final JBPopup hint = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component) .setRequestFocusCondition(project, NotLookupOrSearchCondition.INSTANCE) .setProject(project) .addListener(updateProcessor) .addUserData(updateProcessor) .setForceHeavyweight(heavyWeight) .setDimensionServiceKey(myProject, JAVADOC_LOCATION_AND_SIZE, false) .setResizable(true) .setMovable(true) .setTitle(getTitle(element)) .setCancelCallback(new Computable<Boolean>() { public Boolean compute() { if (fromQuickSearch()) { ((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).unregisterHint(); } Disposer.dispose(component); myEditor = null; myPreviouslyFocused = null; myParameterInfoController = null; return Boolean.TRUE; } }) .createPopup(); AbstractPopup oldHint = (AbstractPopup)getDocInfoHint(); if (oldHint != null) { DocumentationComponent oldComponent = (DocumentationComponent)oldHint.getComponent(); PsiElement element1 = oldComponent.getElement(); if (Comparing.equal(element, element1)) { if (requestFocus) { component.getComponent().requestFocus(); } return oldHint; } oldHint.cancel(); } component.setHint(hint); fetchDocInfo(getDefaultCollector(element, originalElement), component); myDocInfoHintRef = new WeakReference<JBPopup>(hint); myPreviouslyFocused = WindowManagerEx.getInstanceEx().getFocusedComponent(project); if (fromQuickSearch()) { ((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).registerHint(hint); } return hint; } private static String getTitle(final PsiElement element) { final String title = SymbolPresentationUtil.getSymbolPresentableText(element); return CodeInsightBundle.message("javadoc.info.title", title != null ? title : element.getText()); } public static void storeOriginalElement(final Project project, final PsiElement originalElement, final PsiElement element) { if (element == null) return; try { element.putUserData( ORIGINAL_ELEMENT_KEY, SmartPointerManager.getInstance(project).createSmartPsiElementPointer(originalElement) ); } catch (RuntimeException ex) { // PsiPackage does not allow putUserData } } @Nullable public PsiElement findTargetElement(final Editor editor, @Nullable final PsiFile file, PsiElement contextElement) { PsiElement element = editor != null ? TargetElementUtilBase.findTargetElement(editor, ourFlagsForTargetElements) : null; // Allow context doc over xml tag content if (element != null || contextElement != null) { final PsiElement adjusted = TargetElementUtilBase.getInstance() .adjustElement(editor, ourFlagsForTargetElements, element, contextElement); if (adjusted != null) { element = adjusted; } } if (element == null && editor != null) { element = getElementFromLookup(editor, file); } storeOriginalElement(myProject, contextElement, element); return element; } @Nullable public PsiElement getElementFromLookup(final Editor editor, final PsiFile file) { final PsiElement contextElement = file.findElementAt(editor.getCaretModel().getOffset()); PsiElement element = null; final PsiReference ref = TargetElementUtilBase.findReference(editor, editor.getCaretModel().getOffset()); if (ref != null) { element = TargetElementUtilBase.getInstance().adjustReference(ref); if (element == null && ref instanceof PsiPolyVariantReference) { element = ref.getElement(); } } final Lookup activeLookup = LookupManager.getInstance(myProject).getActiveLookup(); if (activeLookup != null) { LookupElement item = activeLookup.getCurrentItem(); if (item != null) { final DocumentationProvider documentationProvider = getProviderFromElement(file); if (documentationProvider!=null) { element = documentationProvider.getDocumentationElementForLookupItem( PsiManager.getInstance(myProject), item.getObject(), ref != null ? ref.getElement():contextElement ); } } } return element; } private boolean fromQuickSearch() { return myPreviouslyFocused != null && myPreviouslyFocused.getParent() instanceof ChooseByNameBase.JPanelProvider; } private DocumentationCollector getDefaultCollector(@NotNull final PsiElement _element, @Nullable final PsiElement originalElement) { final SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(_element.getProject()); return new DocumentationCollector() { private final SmartPsiElementPointer element = smartPointerManager.createSmartPsiElementPointer(_element); private final SmartPsiElementPointer original = originalElement == null ? null : smartPointerManager.createSmartPsiElementPointer(originalElement); @Nullable public String getDocumentation() throws Exception { PsiElement element1 = element.getElement(); final DocumentationProvider provider = getProviderFromElement(element1, original == null ? null : original.getElement()); if (provider != null && myParameterInfoController != null) { final Object[] objects = myParameterInfoController.getSelectedElements(); if (objects.length > 0) { @NonNls StringBuffer sb = null; for(Object o:objects) { PsiElement parameter = null; if (o instanceof PsiElement) { parameter = (PsiElement)o; } if (parameter != null) { final SmartPsiElementPointer originalElement = parameter.getUserData(ORIGINAL_ELEMENT_KEY); final String str2 = provider.generateDoc(parameter, originalElement != null ? originalElement.getElement() : null); if (str2 == null) continue; if (sb == null) sb = new StringBuffer(); sb.append(str2); sb.append("<br>"); } else { sb = null; break; } } if (sb != null) return sb.toString(); } } final SmartPsiElementPointer originalElement = element1 != null ? element1.getUserData(ORIGINAL_ELEMENT_KEY) : null; return provider != null ? provider.generateDoc(element1, originalElement != null ? originalElement.getElement() : null) : null; } @Nullable public PsiElement getElement() { return element.getElement(); } }; } @Nullable public JBPopup getDocInfoHint() { if (myDocInfoHintRef == null) return null; JBPopup hint = myDocInfoHintRef.get(); if (hint == null || !hint.isVisible()) { myDocInfoHintRef = null; return null; } return hint; } public void fetchDocInfo(final DocumentationCollector provider, final DocumentationComponent component) { doFetchDocInfo(component, provider, true); } public void fetchDocInfo(final PsiElement element, final DocumentationComponent component) { doFetchDocInfo(component, getDefaultCollector(element, null), true); } public void queueFetchDocInfo(final DocumentationCollector provider, final DocumentationComponent component) { doFetchDocInfo(component, provider, false); } public void queueFetchDocInfo(final PsiElement element, final DocumentationComponent component) { queueFetchDocInfo(getDefaultCollector(element, null), component); } private void doFetchDocInfo(final DocumentationComponent component, final DocumentationCollector provider, final boolean cancelRequests) { component.startWait(); if (cancelRequests) { myUpdateDocAlarm.cancelAllRequests(); } if (component.isEmpty()) { component.setText(CodeInsightBundle.message("javadoc.fetching.progress")); } myUpdateDocAlarm.addRequest(new Runnable() { public void run() { final Throwable[] ex = new Throwable[1]; final String text = ApplicationManager.getApplication().runReadAction(new Computable<String>() { @Nullable public String compute() { try { return provider.getDocumentation(); } catch (Throwable e) { ex[0] = e; } return null; } }); if (ex[0] != null) { //noinspection SSBasedInspection SwingUtilities.invokeLater(new Runnable() { public void run() { component.setText(CodeInsightBundle.message("javadoc.external.fetch.error.message", ex[0].getLocalizedMessage()), true); } }); return; } final PsiElement element = ApplicationManager.getApplication().runReadAction(new Computable<PsiElement>() { @Nullable public PsiElement compute() { return provider.getElement(); } }); //noinspection SSBasedInspection SwingUtilities.invokeLater(new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { PsiDocumentManager.getInstance(myProject).commitAllDocuments(); } }); if (!element.isValid()) return; if (text == null) { component.setText(CodeInsightBundle.message("no.documentation.found"), true); } else if (text.length() == 0) { component.setText(component.getText(), true); } else { component.setData(element, text); } final AbstractPopup jbPopup = (AbstractPopup)getDocInfoHint(); if(jbPopup==null){ return; } jbPopup.setCaption(getTitle(element)); final String dimensionServiceKey = jbPopup.getDimensionServiceKey(); Dimension dimension = component.getPreferredSize(); final Dimension storedSize = dimensionServiceKey != null ? DimensionService.getInstance().getSize(dimensionServiceKey, getProject(element)) : null; if (storedSize != null) { dimension = storedSize; } final Window window = SwingUtilities.getWindowAncestor(component); if (window != null) { window.setBounds(window.getX(), window.getY(), dimension.width, dimension.height); window.validate(); window.repaint(); } } }); } }, 10); } @NotNull public static DocumentationProvider getProviderFromElement(final PsiElement element) { return getProviderFromElement(element, null); } @NotNull private static DocumentationProvider getProviderFromElement(final PsiElement element, PsiElement originalElement) { if (originalElement == null) { originalElement = getOriginalElement(element); } PsiFile containingFile = originalElement != null ? originalElement.getContainingFile() : element != null ? element.getContainingFile() : null; Set<DocumentationProvider> result = new LinkedHashSet<DocumentationProvider>(); final Language containingFileLanguage = containingFile != null ? containingFile.getLanguage() : null; DocumentationProvider originalProvider = containingFile != null ? LanguageDocumentation.INSTANCE.forLanguage(containingFileLanguage) : null; final Language elementLanguage = element != null ? element.getLanguage() : null; DocumentationProvider elementProvider = element == null || elementLanguage.is(containingFileLanguage) ? null : LanguageDocumentation.INSTANCE.forLanguage(elementLanguage); ContainerUtil.addIfNotNull(originalProvider, result); ContainerUtil.addIfNotNull(elementProvider, result); if (containingFile != null) { final Language baseLanguage = containingFile.getViewProvider().getBaseLanguage(); if (!baseLanguage.is(containingFileLanguage)) { ContainerUtil.addIfNotNull(LanguageDocumentation.INSTANCE.forLanguage(baseLanguage), result); } } // return extensible documentation provider even if the list is empty return new CompositeDocumentationProvider(result); } @Nullable public static PsiElement getOriginalElement(final PsiElement element) { SmartPsiElementPointer originalElementPointer = element!=null ? element.getUserData(ORIGINAL_ELEMENT_KEY):null; return originalElementPointer != null ? originalElementPointer.getElement() : null; } void navigateByLink(final DocumentationComponent component, String url) { component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); final PsiElement psiElement = component.getElement(); final PsiManager manager = PsiManager.getInstance(getProject(psiElement)); if (url.startsWith(PSI_ELEMENT_PROTOCOL)) { final String refText = url.substring(PSI_ELEMENT_PROTOCOL.length()); DocumentationProvider provider = getProviderFromElement(psiElement); if (provider!=null) { final PsiElement targetElement = provider.getDocumentationElementForLink(manager, refText, psiElement); if (targetElement != null) { fetchDocInfo(getDefaultCollector(targetElement, null), component); } } } else { final String docUrl = url; fetchDocInfo (new DocumentationCollector() { public String getDocumentation() throws Exception { if (docUrl.startsWith(DOC_ELEMENT_PROTOCOL)) { final DocumentationProvider provider = getProviderFromElement(psiElement); if (provider instanceof ExtensibleDocumentationProvider) { final ExtensibleDocumentationProvider documentationProvider = (ExtensibleDocumentationProvider)provider; final String text = documentationProvider .getExternalDocumentation(docUrl.substring(DOC_ELEMENT_PROTOCOL.length()), getProject(psiElement)); if (text != null) { return text; } documentationProvider.openExternalDocumentation(psiElement, getOriginalElement(psiElement)); } } else { BrowserUtil.launchBrowser(docUrl); } return ""; } public PsiElement getElement() { //String loc = getElementLocator(docUrl); //if (loc != null) { // PsiElement context = component.getElement(); // return JavaDocUtil.findReferenceTarget(context.getManager(), loc, context); return psiElement; } }, component); } component.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } void showHint(final JBPopup hint) { if (myEditor != null) { hint.showInBestPositionFor(myEditor); } else if (myPreviouslyFocused != null) { hint.showInBestPositionFor(DataManager.getInstance().getDataContext(myPreviouslyFocused)); } else { hint.showInBestPositionFor(DataManager.getInstance().getDataContext()); } } public void requestFocus() { if (fromQuickSearch()) { myPreviouslyFocused.getParent().requestFocus(); } } public Project getProject(@Nullable final PsiElement element) { assert element == null || myProject == element.getProject(); return myProject; } @SuppressWarnings({"HardCodedStringLiteral"}) public static void createHyperlink(StringBuilder buffer, String refText,String label,boolean plainLink) { buffer.append("<a href=\""); buffer.append("psi_element: buffer.append(refText); buffer.append("\">"); if (!plainLink) { buffer.append("<code>"); } buffer.append(label); if (!plainLink) { buffer.append("</code>"); } buffer.append("</a>"); } private static interface DocumentationCollector { @Nullable String getDocumentation() throws Exception; @Nullable PsiElement getElement(); } }
package projacker; public class Waveform implements Element { private Instrument parent; private WaveFile sibling; private Octave child = new Octave( this ); private boolean squareWave; private int octave, numCycles; public Waveform( Instrument parent ) { this.parent = parent; sibling = new WaveFile( parent ); } public String getToken() { return "Waveform"; } public Element getParent() { return parent; } public Element getSibling() { return sibling; } public Element getChild() { return child; } public void begin( String value ) { System.out.println( getToken() + ": " + value ); if( "Sawtooth".equals( value ) ) { squareWave = false; } else if( "Square".equals( value.toString() ) ) { squareWave = true; } else { throw new IllegalArgumentException( "Invalid waveform type: " + value ); } setOctave( 0 ); setNumCycles( 1 ); } public void end() { /* Ptolemy's scale: C=1 D=9/8 E=5/4 F=4/3 G=3/2 A=5/3 B=15/8 */ AudioData audioData = generate( squareWave, numCycles, 1, 1 ); if( octave > 0 ) { audioData = audioData.resample( audioData.getSamplingRate() >> octave ); } parent.setAudioData( audioData ); parent.setLoopStart( 0 ); parent.setLoopLength( parent.getAudioData().getSampleData().length ); } public void setOctave( int octave ) { this.octave = octave; } public void setNumCycles( int cycles ) { if( cycles < 1 ) { throw new IllegalArgumentException( "Invalid number of cycles: " + cycles ); } this.numCycles = cycles; } public void setDetune( int semitones ) { } /* Generate a sawtooth or square waveform with phase-modulation chorus if cycles is greater than 1. */ public static AudioData generate( boolean square, int cycles, int ratio1, int ratio2 ) { int cycleLen = 256 * ratio1 * ratio2; byte[] buf = new byte[ cycleLen * cycles ]; for( int cycle = 0; cycle < cycles; cycle++ ) { int phase = 128 + Math.round( ( float ) Math.cos( 2 * Math.PI * cycle / cycles ) * 128f ); if( square ) { for( int idx = 0; idx < cycleLen; idx++ ) { int a1 = ( ( ( idx * ratio1 / ratio2 ) & 0x80 ) >> 7 ) * 127 - 64; int a2 = ( ( ( idx + phase ) & 0x80 ) >> 7 ) * 127 - 64; buf[ cycle * cycleLen + idx ] = ( byte ) ( a1 + a2 ); } } else { for( int idx = 0; idx < cycleLen; idx++ ) { int a1 = ( ( idx * ratio1 / ratio2 ) % 256 - 128 ) / 2; int a2 = ( ( idx + phase ) % 256 - 128 ) / 2; buf[ cycle * cycleLen + idx ] = ( byte ) ( a1 + a2 ); } } } return new AudioData( buf, 256 * 262 ); } }
package picard.sam; import htsjdk.samtools.SAMValidationError; import htsjdk.samtools.SamFileValidator; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.ValidationStringency; import htsjdk.samtools.BamIndexValidator.IndexValidationStringency; import htsjdk.samtools.reference.ReferenceSequenceFile; import htsjdk.samtools.reference.ReferenceSequenceFileFactory; import htsjdk.samtools.util.IOUtil; import org.broadinstitute.barclay.argparser.Argument; import org.broadinstitute.barclay.argparser.CommandLineProgramProperties; import htsjdk.samtools.util.Log; import org.broadinstitute.barclay.help.DocumentedFeature; import picard.PicardException; import picard.cmdline.CommandLineProgram; import picard.cmdline.StandardOptionDefinitions; import picard.cmdline.programgroups.SamOrBam; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; @CommandLineProgramProperties( summary = ValidateSamFile.USAGE_SUMMARY + ValidateSamFile.USAGE_DETAILS, oneLineSummary = ValidateSamFile.USAGE_SUMMARY, programGroup = SamOrBam.class) @DocumentedFeature public class ValidateSamFile extends CommandLineProgram { private static final Log log = Log.getInstance(ValidateSamFile.class); static final String USAGE_SUMMARY = "Validates a SAM or BAM file."; static final String USAGE_DETAILS = "<p>This tool reports on the validity of a SAM or BAM file relative to the SAM format " + "specification. This is useful for troubleshooting errors encountered with other tools that may be caused by improper " + "formatting, faulty alignments, incorrect flag values, etc. </p> " + "<p>By default, the tool runs in VERBOSE mode and will exit after finding 100 errors and output them to the console (stdout). " + "Therefore, it is often more practical to run this tool initially using the MODE=SUMMARY option. This mode outputs a summary " + "table listing the numbers of all 'errors' and 'warnings'.</p> "+ "<p>When fixing errors in your file, it is often useful to prioritize the severe validation errors and ignore the " + "errors/warnings of lesser concern. This can be done using the IGNORE and/or IGNORE_WARNINGS arguments. For helpful " + "suggestions on error prioritization, please follow this link to obtain additional documentation on <a href='https: "<p>After identifying and fixing your 'warnings/errors', we recommend that you rerun this tool to validate your SAM/BAM " + "file prior to proceeding with your downstream analysis. This will verify that all problems in your file have been addressed.</p>" + "<h4>Usage example:</h4>" + "<pre>" + "java -jar picard.jar ValidateSamFile \\<br />" + " I=input.bam \\<br />" + " MODE=SUMMARY" + "</pre>" + "<p>To obtain a complete list with descriptions of both 'ERROR' and 'WARNING' messages, please see our additional " + " <a href='https: ""+ "<hr />"; public enum Mode {VERBOSE, SUMMARY} @Argument(shortName = StandardOptionDefinitions.INPUT_SHORT_NAME, doc = "Input SAM/BAM file") public File INPUT; @Argument(shortName = StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc = "Output file or standard out if missing", optional = true) public File OUTPUT; @Argument(shortName = "M", doc = "Mode of output") public Mode MODE = Mode.VERBOSE; @Argument(doc = "List of validation error types to ignore.", optional = true) public List<SAMValidationError.Type> IGNORE = new ArrayList<SAMValidationError.Type>(); @Argument(shortName = "MO", doc = "The maximum number of lines output in verbose mode") public Integer MAX_OUTPUT = 100; @Argument(doc = "If true, only report errors and ignore warnings.") public boolean IGNORE_WARNINGS = false; @Argument(doc = "DEPRECATED. Use INDEX_VALIDATION_STRINGENCY instead. If true and input is " + "a BAM file with an index file, also validates the index. Until this parameter is retired " + "VALIDATE INDEX and INDEX_VALIDATION_STRINGENCY must agree on whether to validate the index.") public boolean VALIDATE_INDEX = true; @Argument(doc = "If set to anything other than IndexValidationStringency.NONE and input is " + "a BAM file with an index file, also validates the index at the specified stringency. " + "Until VALIDATE_INDEX is retired, VALIDATE INDEX and INDEX_VALIDATION_STRINGENCY " + "must agree on whether to validate the index.") public IndexValidationStringency INDEX_VALIDATION_STRINGENCY = IndexValidationStringency.EXHAUSTIVE; @Argument(shortName = "BISULFITE", doc = "Whether the SAM or BAM file consists of bisulfite sequenced reads. " + "If so, C->T is not counted as an error in computing the value of the NM tag.") public boolean IS_BISULFITE_SEQUENCED = false; @Argument(doc = "Relevant for a coordinate-sorted file containing read pairs only. " + "Maximum number of file handles to keep open when spilling mate info to disk. " + "Set this number a little lower than the per-process maximum number of file that may be open. " + "This number can be found by executing the 'ulimit -n' command on a Unix system.") public int MAX_OPEN_TEMP_FILES = 8000; @Argument(shortName = "SMV", doc = "If true, this tool will not attempt to validate mate information. " + "In general cases, this option should not be used. However, in cases where samples have very " + "high duplication or chimerism rates (> 10%), the mate validation process often requires extremely " + "large amounts of memory to run, so this flag allows you to forego that check.") public boolean SKIP_MATE_VALIDATION = false; public static void main(final String[] args) { System.exit(new ValidateSamFile().instanceMain(args)); } /** * Return types for doWork() */ enum ReturnTypes { FAILED(-1), // failed to complete execution SUCCESSFUL(0), // ran successfully WARNINGS(1), // warnings but no errors ERRORS_WARNINGS(2), // errors and warnings ERRORS(3); // errors but no warnings private final int value; ReturnTypes(final int value) { this.value = value; } int value() { return value; } } /** * Do the work after command line has been parsed. * * @return -1 - failed to complete execution, 0 - ran successfully without warnings or errors, 1 - warnings but no errors, * 2 - errors and warnings, 3 - errors but no warnings * */ @Override protected int doWork() { try { IOUtil.assertFileIsReadable(INPUT); ReferenceSequenceFile reference = null; if (REFERENCE_SEQUENCE != null) { IOUtil.assertFileIsReadable(REFERENCE_SEQUENCE); reference = ReferenceSequenceFileFactory.getReferenceSequenceFile(REFERENCE_SEQUENCE); } final PrintWriter out; if (OUTPUT != null) { IOUtil.assertFileIsWritable(OUTPUT); try { out = new PrintWriter(OUTPUT); } catch (FileNotFoundException e) { // we already asserted this so we should not get here throw new PicardException("Unexpected exception", e); } } else { out = new PrintWriter(System.out); } boolean result; final SamReaderFactory factory = SamReaderFactory.makeDefault().referenceSequence(REFERENCE_SEQUENCE) .validationStringency(ValidationStringency.SILENT) .enable(SamReaderFactory.Option.VALIDATE_CRC_CHECKSUMS); final SamReader samReader = factory.open(INPUT); if (samReader.type() != SamReader.Type.BAM_TYPE) VALIDATE_INDEX = false; factory.setOption(SamReaderFactory.Option.CACHE_FILE_BASED_INDEXES, VALIDATE_INDEX); factory.reapplyOptions(samReader); final SamFileValidator validator = new SamFileValidator(out, MAX_OPEN_TEMP_FILES); validator.setErrorsToIgnore(IGNORE); validator.setSkipMateValidation(SKIP_MATE_VALIDATION); validator.setBisulfiteSequenced(IS_BISULFITE_SEQUENCED); validator.setIgnoreWarnings(IGNORE_WARNINGS); if (MODE == Mode.SUMMARY) { validator.setVerbose(false, 0); } else { validator.setVerbose(true, MAX_OUTPUT); } if (VALIDATE_INDEX) { validator.setIndexValidationStringency(VALIDATE_INDEX ? IndexValidationStringency.EXHAUSTIVE : IndexValidationStringency.NONE); } if (IOUtil.isRegularPath(INPUT)) { // Do not check termination if reading from a stream validator.validateBamFileTermination(INPUT); } result = false; switch (MODE) { case SUMMARY: result = validator.validateSamFileSummary(samReader, reference); break; case VERBOSE: result = validator.validateSamFileVerbose(samReader, reference); break; } out.flush(); if (result) { return ReturnTypes.SUCCESSFUL.value(); // ran successfully with no warnings or errors } else { if (validator.getNumErrors() == 0) { if (validator.getNumWarnings() > 0) { return ReturnTypes.WARNINGS.value(); // warnings but no errors } else { log.error("SAM file validation fails without warnings or errors."); return ReturnTypes.FAILED.value(); } } else { if (validator.getNumWarnings() > 0) { return ReturnTypes.ERRORS_WARNINGS.value(); // errors and warnings } else { return ReturnTypes.ERRORS.value(); // errors but no warnings } } } } catch (Exception e) { log.error(e.getMessage()); return ReturnTypes.FAILED.value(); // failed to complete execution } } @Override protected String[] customCommandLineValidation() { if ((!VALIDATE_INDEX && INDEX_VALIDATION_STRINGENCY != IndexValidationStringency.NONE) || (VALIDATE_INDEX && INDEX_VALIDATION_STRINGENCY == IndexValidationStringency.NONE)) { return new String[]{"VALIDATE_INDEX and INDEX_VALIDATION_STRINGENCY must be consistent: " + "VALIDATE_INDEX is " + VALIDATE_INDEX + " and INDEX_VALIDATION_STRINGENCY is " + INDEX_VALIDATION_STRINGENCY}; } return super.customCommandLineValidation(); } }
package ee.ria.xroad.proxy.clientproxy; import ee.ria.xroad.common.CodedException; import ee.ria.xroad.common.SystemProperties; import ee.ria.xroad.common.conf.globalconf.GlobalConf; import ee.ria.xroad.common.conf.serverconf.ServerConf; import ee.ria.xroad.common.identifier.CentralServiceId; import ee.ria.xroad.common.identifier.ClientId; import ee.ria.xroad.common.identifier.ServiceId; import ee.ria.xroad.common.message.JaxbUtils; import ee.ria.xroad.common.message.ProtocolVersion; import ee.ria.xroad.common.message.SoapBuilder; import ee.ria.xroad.common.message.SoapFault; import ee.ria.xroad.common.message.SoapHeader; import ee.ria.xroad.common.message.SoapMessage; import ee.ria.xroad.common.message.SoapMessageDecoder; import ee.ria.xroad.common.message.SoapMessageImpl; import ee.ria.xroad.common.util.HttpHeaders; import ee.ria.xroad.common.util.MimeTypes; import ee.ria.xroad.common.util.MimeUtils; import ee.ria.xroad.proxy.common.WsdlRequestData; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.http.conn.ssl.NoopHostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.Marshaller; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.UUID; import static ee.ria.xroad.common.ErrorCodes.X_INVALID_REQUEST; import static org.apache.commons.lang.StringUtils.isBlank; /** * A processor of WSDL requests. */ @Slf4j @RequiredArgsConstructor public class WsdlRequestProcessor { // These are public for proxy testsuite: GetWsdlMessage purposes public static final String PARAM_INSTANCE_IDENTIFIER = "xRoadInstance"; public static final String PARAM_MEMBER_CLASS = "memberClass"; public static final String PARAM_MEMBER_CODE = "memberCode"; public static final String PARAM_SERVICE_CODE = "serviceCode"; // these are package-private for unit test purposes static final String PARAM_SUBSYSTEM_CODE = "subsystemCode"; static final String PARAM_VERSION = "version"; private static final String GET_WSDL = "getWsdl"; private static final String PROXY_LOCAL_HTTPS_ENDPOINT = "https://127.0.0.1:" + SystemProperties.getClientProxyHttpsPort(); private static final String PROXY_LOCAL_HTTP_ENDPOINT = "http://127.0.0.1:" + SystemProperties.getClientProxyHttpPort(); private final HttpServletRequest request; private final HttpServletResponse response; void process() throws Exception { ClientId client = ServerConf.getIdentifier().getOwner(); ServiceId service = getServiceId(); log.trace("process({}, {})", client, service); SoapMessageImpl message = createMessage(client, service); if (log.isTraceEnabled()) { log.trace("message:\n{}", message.getXml()); } HttpURLConnection connection = createConnection(message); try (InputStream in = connection.getInputStream(); SoapDecoderCallback callback = new SoapDecoderCallback()) { SoapMessageDecoder decoder = new SoapMessageDecoder(connection.getContentType(), callback); decoder.parse(in); } } private SoapMessageImpl createMessage(ClientId client, final ServiceId service) throws Exception { ServiceId implementingService = GlobalConf.getServiceId(service); log.debug("Implementing service: {}", implementingService); SoapHeader header = new SoapHeader(); header.setClient(client); header.setService(createGetWsdlService(implementingService)); header.setQueryId(UUID.randomUUID().toString()); header.setProtocolVersion(new ProtocolVersion()); SoapBuilder sb = new SoapBuilder(); sb.setHeader(header); sb.setCreateBodyCallback(soapBody -> { WsdlRequestData req = new WsdlRequestData(); req.setServiceCode(implementingService.getServiceCode()); req.setServiceVersion(implementingService.getServiceVersion()); Marshaller marshaller = JaxbUtils.createMarshaller(req.getClass()); marshaller.marshal(req, soapBody); }); return sb.build(); } private ServiceId createGetWsdlService(ServiceId service) { return ServiceId.create(service.getClientId(), GET_WSDL, service.getServiceVersion()); } // package-private for unit-test purposes ServiceId getServiceId() { String instance = request.getParameter(PARAM_INSTANCE_IDENTIFIER); if (isBlank(instance)) { throw new CodedException(X_INVALID_REQUEST, "Must specify instance identifier"); } String serviceCode = request.getParameter(PARAM_SERVICE_CODE); if (isBlank(serviceCode)) { throw new CodedException(X_INVALID_REQUEST, "Must specify service code"); } String memberClass = request.getParameter(PARAM_MEMBER_CLASS); String memberCode = request.getParameter(PARAM_MEMBER_CODE); String subsystemCode = request.getParameter(PARAM_SUBSYSTEM_CODE); String version = request.getParameter(PARAM_VERSION); try { // Central Service? if (isBlank(memberClass) && isBlank(memberCode)) { return CentralServiceId.create(instance, serviceCode); } else { // Service return ServiceId.create(instance, memberClass, memberCode, subsystemCode, serviceCode, version); } } catch (Exception e) { throw new CodedException(X_INVALID_REQUEST, e.getMessage()); } } HttpURLConnection createConnection(SoapMessageImpl message) throws Exception { final HttpURLConnection urlConnection; if (request.isSecure()) { HttpsURLConnection tmp = (HttpsURLConnection) new URL(PROXY_LOCAL_HTTPS_ENDPOINT).openConnection(); tmp.setSSLSocketFactory(InternalSslSocketFactory.getInstance()); tmp.setHostnameVerifier(NoopHostnameVerifier.INSTANCE); urlConnection = tmp; } else { urlConnection = (HttpURLConnection) new URL(PROXY_LOCAL_HTTP_ENDPOINT).openConnection(); } urlConnection.setDoInput(true); urlConnection.setDoOutput(true); // Use the same timeouts as client proxy to server proxy connections. urlConnection.setConnectTimeout(SystemProperties.getClientProxyTimeout()); urlConnection.setReadTimeout(SystemProperties.getClientProxyHttpClientTimeout()); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty( HttpHeaders.CONTENT_TYPE, MimeUtils.contentTypeWithCharset(MimeTypes.TEXT_XML, StandardCharsets.UTF_8.name())); IOUtils.write(message.getBytes(), urlConnection.getOutputStream()); if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { urlConnection.disconnect(); throw new RuntimeException("Received HTTP error: " + urlConnection.getResponseCode() + " - " + urlConnection.getResponseMessage()); } return urlConnection; } private class SoapDecoderCallback implements SoapMessageDecoder.Callback { @Override public void soap(SoapMessage message, Map<String, String> headers) throws Exception { // discard } @Override public void attachment(String contentType, InputStream content, Map<String, String> additionalHeaders) throws Exception { log.trace("attachment({})", contentType); response.setContentType(contentType); IOUtils.copy(content, response.getOutputStream()); } @Override public void fault(SoapFault fault) throws Exception { log.error("Received fault {}", fault.getXml()); throw fault.toCodedException(); } @Override public void onCompleted() { log.trace("onCompleted()"); } @Override public void onError(Exception t) throws Exception { log.error("Error while reading response", t); throw t; } } }
package pw.amel.civspell; import pw.amel.civspell.builtin.*; import pw.amel.civspell.commands.GiveSpellItem; import pw.amel.civspell.commands.ReloadCommand; import pw.amel.civspell.gameplay.SpellCastListener; import org.bukkit.plugin.java.JavaPlugin; public class CivSpells extends JavaPlugin { public SpellConfig config; @Override public void onEnable() { // Meta effects: Effects that change how the spell executes addEffect("nop", NopEffect.class); addEffect("fail", FailEffect.class); // Basic effect effects: Effects that cause a simple change in the game, like playing a sound or // giving the caster a potion effect. addEffect("throwpot", ThrowPotionEffect.class); addEffect("sound", SoundEffect.class); addEffect("removetriggeritem", RemoveTriggerItemEffect.class); saveDefaultConfig(); this.config = new SpellConfig(getConfig(), this); getCommand("csgiveitem").setExecutor(new GiveSpellItem(this)); getCommand("csreload").setExecutor(new ReloadCommand(this)); getServer().getPluginManager().registerEvents(new SpellCastListener(this), this); } /** * Adds an effect with the given name. * @param name The name of the effect that the user will refer to in their configuration. * @param effect The effect. It must implement Effect and have a public constructor that takes a * ConfigurationSection as its only argument. */ public void addEffect(String name, Class<?> effect) { EffectManager.addEffect(name, effect); } }
package quantisan.qte_lmax; import com.lmax.api.*; import com.lmax.api.account.LoginCallback; import com.lmax.api.account.LoginRequest; import com.lmax.api.heartbeat.HeartbeatCallback; import com.lmax.api.heartbeat.HeartbeatEventListener; import com.lmax.api.heartbeat.HeartbeatRequest; import com.lmax.api.heartbeat.HeartbeatSubscriptionRequest; import com.lmax.api.orderbook.*; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; public class ThinBot implements LoginCallback, HeartbeatEventListener, OrderBookEventListener, StreamFailureListener, SessionDisconnectedListener, Runnable { final static Logger logger = LoggerFactory.getLogger(ThinBot.class); private final static String EXCHANGE_NAME = "ticks"; private final static int HEARTBEAT_PERIOD = 4 * 60 * 1000; private final static int reconnectTries = 5; private final static String brokerUrl = "https://testapi.lmaxtrader.com"; private Session session; private int reconnectCount; private ConnectionFactory factory; private Connection connection; private Channel channel; public static void loginLmax(String url) { LmaxApi lmaxApi = new LmaxApi(url); ThinBot thinBot = new ThinBot(); lmaxApi.login(new LoginRequest("quantisan2", "J63VFqmXBaQStdAxKnD7", LoginRequest.ProductType.CFD_DEMO), thinBot); } public static void main(String[] args) { loginLmax(brokerUrl); } @Override public void onLoginSuccess(Session session) { logger.info("Logged in, account details: {}.", session.getAccountDetails()); this.session = session; this.reconnectCount = 0; session.registerHeartbeatListener(this); session.registerOrderBookEventListener(this); session.registerStreamFailureListener(this); session.registerSessionDisconnectedListener(this); // subscribe to heatbeat // session.subscribe(new HeartbeatSubscriptionRequest(), new Callback() { public void onSuccess() { } @Override public void onFailure(final FailureResponse failureResponse) { throw new RuntimeException("Heartbeat subscription failed"); } }); // subscribe to instrument data // for (long instrumentId = 4001; instrumentId < 4018; instrumentId++) subscribeToInstrument(session, instrumentId); subscribeToInstrument(session, 100637); // Gold subscribeToInstrument(session, 100639); // Silver // RabbitMQ factory = new ConnectionFactory(); factory.setHost("localhost"); try { connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); } catch (IOException e) { logger.error("Can't open a rabbitmq connection.", e); System.exit(1); } new Thread(this).start(); // heartbeat request session.start(); try { channel.close(); connection.close(); } catch (IOException e) { logger.error("Can't close rabbitmq connection.", e); System.exit(1); } } @Override public void onLoginFailure(FailureResponse failureResponse) { throw new RuntimeException("Unable to login: " + failureResponse.getDescription(), failureResponse.getException()); } @Override public void notifyStreamFailure(Exception e) { logger.error("Stream failure. {}.", e); } // // Market data @Override public void notify(OrderBookEvent orderBookEvent) { Tick tick = new Tick(orderBookEvent); if(tick.isValid()) { try { String routingKey = getRouting(tick.getInstrumentName()); String message = tick.toString(); channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes()); logger.debug("Sent {}", tick.toString()); } catch (IOException e) { logger.error("Error publishing tick.", e); } } } private String getRouting(String inst) { return "lmax." + inst.toLowerCase(); } private void subscribeToInstrument(final Session session, final long instrumentId) { session.subscribe(new OrderBookSubscriptionRequest(instrumentId), new Callback() { public void onSuccess() { logger.debug("Subscribed to instrument {}.", instrumentId); } public void onFailure(final FailureResponse failureResponse) { logger.warn("Failed to subscribe to instrument: {}.", instrumentId); logger.warn("{}. : {}.", failureResponse.getMessage(), failureResponse.getDescription()); } }); } // // // Heart Beat @Override public void notify(long accountId, String token) { } private void requestHeartbeat() { this.session.requestHeartbeat(new HeartbeatRequest("token"), new HeartbeatCallback() { @Override public void onSuccess(String token) { } @Override public void onFailure(FailureResponse failureResponse) { logger.warn(failureResponse.getMessage(), failureResponse.getDescription()); throw new RuntimeException("Heartbeat receive failed"); } }); } @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { Thread.sleep(HEARTBEAT_PERIOD); requestHeartbeat(); } } catch (InterruptedException e) { logger.warn("Fail to request heartbeat: {}.", e); } } // @Override public void notifySessionDisconnected() { if (++reconnectCount <= reconnectTries) { logger.warn("Session disconnected - attempting to log in again (attempt {})", reconnectCount); loginLmax(brokerUrl); } else { logger.error("Session disconnected - aborting after too many reconnect attempts"); System.exit(1); } } }
package org.languagetool.gui; import org.languagetool.Language; import org.languagetool.tools.StringTools; import java.io.*; import java.util.*; /** * Configuration like list of disabled rule IDs, server mode etc. * Configuration is loaded from and stored to a properties file. * * @author Daniel Naber */ public class Configuration { static final int DEFAULT_SERVER_PORT = 8081; // TODO: should be HTTPServerConfig.DEFAULT_PORT but we don't have that dependency static final int FONT_STYLE_INVALID = -1; static final int FONT_SIZE_INVALID = -1; private static final String CONFIG_FILE = "languagetool.properties"; private static final String DISABLED_RULES_CONFIG_KEY = "disabledRules"; private static final String ENABLED_RULES_CONFIG_KEY = "enabledRules"; private static final String DISABLED_CATEGORIES_CONFIG_KEY = "disabledCategories"; private static final String LANGUAGE_CONFIG_KEY = "language"; private static final String MOTHER_TONGUE_CONFIG_KEY = "motherTongue"; private static final String AUTO_DETECT_CONFIG_KEY = "autoDetect"; private static final String SERVER_RUN_CONFIG_KEY = "serverMode"; private static final String SERVER_PORT_CONFIG_KEY = "serverPort"; private static final String USE_GUI_CONFIG_KEY = "useGUIConfig"; private static final String FONT_NAME_CONFIG_KEY = "font.name"; private static final String FONT_STYLE_CONFIG_KEY = "font.style"; private static final String FONT_SIZE_CONFIG_KEY = "font.size"; private static final String LF_NAME_CONFIG_KEY = "lookAndFeelName"; private static final String DELIMITER = ","; private static final String EXTERNAL_RULE_DIRECTORY = "extRulesDirectory"; private File configFile; private final HashMap<String, String> configForOtherLangs = new HashMap<>(); private Set<String> disabledRuleIds = new HashSet<>(); private Set<String> enabledRuleIds = new HashSet<>(); private Set<String> disabledCategoryNames = new HashSet<>(); private Language language; private Language motherTongue; private boolean runServer; private boolean autoDetect; private boolean guiConfig; private String fontName; private int fontStyle; private int fontSize; private int serverPort = DEFAULT_SERVER_PORT; private String externalRuleDirectory; private String lookAndFeelName; /** * Uses the configuration file from the default location. * @param lang The language for the configuration, used to distinguish * rules that are enabled or disabled per language. */ public Configuration(final Language lang) throws IOException { this(new File(System.getProperty("user.home")), CONFIG_FILE, lang); } public Configuration(final File baseDir, final String filename, final Language lang) throws IOException { this(); if (!baseDir.isDirectory()) { throw new IllegalArgumentException("Not a directory: " + baseDir); } configFile = new File(baseDir, filename); loadConfiguration(lang); } public Configuration(final File baseDir, final Language lang) throws IOException { this(baseDir, CONFIG_FILE, lang); } Configuration() { fontStyle = FONT_STYLE_INVALID; fontSize = FONT_SIZE_INVALID; } /** * * Returns a copy of the given configuration. * * @param configuration the object to copy. * @return the copy. * @since 2.6 */ Configuration copy(Configuration configuration) { Configuration copy = new Configuration(); copy.restoreState(configuration); return copy; } /** * Restore the state of this object from configuration * * @param configuration the object from which we will read the state * @since 2.6 */ void restoreState(Configuration configuration) { this.configFile = configuration.configFile; this.language = configuration.language; this.motherTongue = configuration.motherTongue; this.runServer = configuration.runServer; this.autoDetect = configuration.autoDetect; this.guiConfig = configuration.guiConfig; this.fontName = configuration.fontName; this.fontStyle = configuration.fontStyle; this.fontSize = configuration.fontSize; this.serverPort = configuration.serverPort; this.lookAndFeelName = configuration.lookAndFeelName; this.externalRuleDirectory = configuration.externalRuleDirectory; this.disabledRuleIds.clear(); this.disabledRuleIds.addAll(configuration.disabledRuleIds); this.enabledRuleIds.clear(); this.enabledRuleIds.addAll(configuration.enabledRuleIds); this.disabledCategoryNames.clear(); this.disabledCategoryNames.addAll(configuration.disabledCategoryNames); this.configForOtherLangs.clear(); for (String key : configuration.configForOtherLangs.keySet()) { this.configForOtherLangs.put(key, configuration.configForOtherLangs.get(key)); } } public Set<String> getDisabledRuleIds() { return disabledRuleIds; } public Set<String> getEnabledRuleIds() { return enabledRuleIds; } public Set<String> getDisabledCategoryNames() { return disabledCategoryNames; } public void setDisabledRuleIds(final Set<String> ruleIDs) { disabledRuleIds = ruleIDs; } public void setEnabledRuleIds(final Set<String> ruleIDs) { enabledRuleIds = ruleIDs; } public void setDisabledCategoryNames(final Set<String> categoryNames) { disabledCategoryNames = categoryNames; } public Language getLanguage() { return language; } public void setLanguage(final Language language) { this.language = language; } public Language getMotherTongue() { return motherTongue; } public void setMotherTongue(final Language motherTongue) { this.motherTongue = motherTongue; } public boolean getAutoDetect() { return autoDetect; } public void setAutoDetect(final boolean autoDetect) { this.autoDetect = autoDetect; } public boolean getRunServer() { return runServer; } public void setRunServer(final boolean runServer) { this.runServer = runServer; } public int getServerPort() { return serverPort; } public void setUseGUIConfig(final boolean useGUIConfig) { this.guiConfig = useGUIConfig; } public boolean getUseGUIConfig() { return guiConfig; } public void setServerPort(final int serverPort) { this.serverPort = serverPort; } public String getExternalRuleDirectory() { return externalRuleDirectory; } public void setExternalRuleDirectory(final String path) { externalRuleDirectory = path; } /** * * Returns the name of the GUI's editing textarea font. * * @return the name of the font. * @since 2.6 * * @see java.awt.Font#getFamily() */ public String getFontName() { return fontName; } /** * * Sets the name of the GUI's editing textarea font. * * @param fontName the name of the font. * @since 2.6 * * @see java.awt.Font#getFamily() */ public void setFontName(String fontName) { this.fontName = fontName; } /** * * Returns the style of the GUI's editing textarea font. * * @return the style of the font. * @since 2.6 * * @see java.awt.Font#getStyle() */ public int getFontStyle() { return fontStyle; } /** * * Sets the style of the GUI's editing textarea font. * * @param fontStyle the style of the font. * @since 2.6 * * @see java.awt.Font#getStyle() */ public void setFontStyle(int fontStyle) { this.fontStyle = fontStyle; } /** * * Returns the size of the GUI's editing textarea font. * * @return the size of the font. * @since 2.6 * * @see java.awt.Font#getSize() */ public int getFontSize() { return fontSize; } /** * * Sets the size of the GUI's editing textarea font. * * @param fontSize the size of the font. * @since 2.6 * * @see java.awt.Font#getSize() */ public void setFontSize(int fontSize) { this.fontSize = fontSize; } /** * * Returns the name of the GUI's LaF. * * @return the name of the LaF. * @since 2.6 * * @see javax.swing.UIManager.LookAndFeelInfo#getName() */ public String getLookAndFeelName() { return this.lookAndFeelName; } /** * * Sets the name of the GUI's LaF. * * @param lookAndFeelName the name of the LaF. * @since 2.6 @see * * @see javax.swing.UIManager.LookAndFeelInfo#getName() */ public void setLookAndFeelName(String lookAndFeelName) { this.lookAndFeelName = lookAndFeelName; } private void loadConfiguration(final Language lang) throws IOException { final String qualifier = getQualifier(lang); try (FileInputStream fis = new FileInputStream(configFile)) { final Properties props = new Properties(); props.load(fis); disabledRuleIds.addAll(getListFromProperties(props, DISABLED_RULES_CONFIG_KEY + qualifier)); enabledRuleIds.addAll(getListFromProperties(props, ENABLED_RULES_CONFIG_KEY + qualifier)); disabledCategoryNames.addAll(getListFromProperties(props, DISABLED_CATEGORIES_CONFIG_KEY + qualifier)); final String languageStr = (String) props.get(LANGUAGE_CONFIG_KEY); if (languageStr != null) { language = Language.getLanguageForShortName(languageStr); } final String motherTongueStr = (String) props.get(MOTHER_TONGUE_CONFIG_KEY); if (motherTongueStr != null && !motherTongueStr.equals("xx")) { motherTongue = Language.getLanguageForShortName(motherTongueStr); } autoDetect = "true".equals(props.get(AUTO_DETECT_CONFIG_KEY)); guiConfig = "true".equals(props.get(USE_GUI_CONFIG_KEY)); runServer = "true".equals(props.get(SERVER_RUN_CONFIG_KEY)); fontName = (String) props.get(FONT_NAME_CONFIG_KEY); if (props.get(FONT_STYLE_CONFIG_KEY) != null) { try { fontStyle = Integer.parseInt((String) props.get(FONT_STYLE_CONFIG_KEY)); } catch (NumberFormatException e) { // Ignore } } if (props.get(FONT_SIZE_CONFIG_KEY) != null) { try { fontSize = Integer.parseInt((String) props.get(FONT_SIZE_CONFIG_KEY)); } catch (NumberFormatException e) { // Ignore } } lookAndFeelName = (String) props.get(LF_NAME_CONFIG_KEY); final String serverPortString = (String) props.get(SERVER_PORT_CONFIG_KEY); if (serverPortString != null) { serverPort = Integer.parseInt(serverPortString); } final String extRules = (String) props.get(EXTERNAL_RULE_DIRECTORY); if (extRules != null) { externalRuleDirectory = extRules; } //store config for other languages loadConfigForOtherLanguages(lang, props); } catch (final FileNotFoundException e) { // file not found: okay, leave disabledRuleIds empty } } private String getQualifier(final Language lang) { String qualifier = ""; if (lang != null) { qualifier = "." + lang.getShortNameWithCountryAndVariant(); } return qualifier; } private void loadConfigForOtherLanguages(final Language lang, final Properties prop) { for (Language otherLang : Language.getAllLanguages()) { if (!otherLang.equals(lang)) { final String languageSuffix = "." + otherLang.getShortNameWithCountryAndVariant(); storeConfigKeyFromProp(prop, DISABLED_RULES_CONFIG_KEY + languageSuffix); storeConfigKeyFromProp(prop, ENABLED_RULES_CONFIG_KEY + languageSuffix); storeConfigKeyFromProp(prop, DISABLED_CATEGORIES_CONFIG_KEY + languageSuffix); } } } private void storeConfigKeyFromProp(final Properties prop, final String key) { if (prop.containsKey(key)) { configForOtherLangs.put(key, prop.getProperty(key)); } } private Collection<? extends String> getListFromProperties(final Properties props, final String key) { final String value = (String) props.get(key); final List<String> list = new ArrayList<>(); if (value != null) { final String[] names = value.split(DELIMITER); list.addAll(Arrays.asList(names)); } return list; } public void saveConfiguration(final Language lang) throws IOException { final Properties props = new Properties(); final String qualifier = getQualifier(lang); addListToProperties(props, DISABLED_RULES_CONFIG_KEY + qualifier, disabledRuleIds); addListToProperties(props, ENABLED_RULES_CONFIG_KEY + qualifier, enabledRuleIds); addListToProperties(props, DISABLED_CATEGORIES_CONFIG_KEY + qualifier, disabledCategoryNames); if (language != null && !language.isExternal()) { // external languages won't be known at startup, so don't save them props.setProperty(LANGUAGE_CONFIG_KEY, language.getShortNameWithCountryAndVariant()); } if (motherTongue != null) { props.setProperty(MOTHER_TONGUE_CONFIG_KEY, motherTongue.getShortName()); } props.setProperty(AUTO_DETECT_CONFIG_KEY, Boolean.toString(autoDetect)); props.setProperty(USE_GUI_CONFIG_KEY, Boolean.toString(guiConfig)); props.setProperty(SERVER_RUN_CONFIG_KEY, Boolean.toString(runServer)); props.setProperty(SERVER_PORT_CONFIG_KEY, Integer.toString(serverPort)); if (fontName != null) { props.setProperty(FONT_NAME_CONFIG_KEY, fontName); } if (fontStyle != FONT_STYLE_INVALID) { props.setProperty(FONT_STYLE_CONFIG_KEY, Integer.toString(fontStyle)); } if (fontSize != FONT_SIZE_INVALID) { props.setProperty(FONT_SIZE_CONFIG_KEY, Integer.toString(fontSize)); } if (this.lookAndFeelName != null) { props.setProperty(LF_NAME_CONFIG_KEY, lookAndFeelName); } if (externalRuleDirectory != null) { props.setProperty(EXTERNAL_RULE_DIRECTORY, externalRuleDirectory); } for (final String key : configForOtherLangs.keySet()) { props.setProperty(key, configForOtherLangs.get(key)); } try (FileOutputStream fos = new FileOutputStream(configFile)) { props.store(fos, "LanguageTool configuration"); } } private void addListToProperties(final Properties props, final String key, final Set<String> list) { if (list == null) { props.setProperty(key, ""); } else { props.setProperty(key, StringTools.listToString(list, DELIMITER)); } } }
package ru.lj.alamar.microbe; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Arrays; import java.util.Locale; import java.util.Properties; import java.util.Random; import ru.yandex.bolts.collection.Cf; import ru.yandex.bolts.collection.ListF; import ru.yandex.bolts.collection.MapF; import ru.yandex.bolts.collection.Tuple2; import ru.yandex.bolts.collection.Tuple2List; /** * @author ilyak */ public class Model { public enum Stat { AVG, DEV, BOX; } private static final DecimalFormat FMT = new DecimalFormat("0. public static void main(String[] args) throws Exception { if (args.length == 0) { System.err.println("Usage: model {model-name} [RNG-seed] [key=value]..."); System.err.println("See MODELS directory"); System.exit(1); } if (args.length > 1 && args[1] == null) { args = new String[] { args[0] }; /* anti-maven */ } args[0] = args[0].replace(".properties", ""); String modelFullName = modelWithParameters(args); PrintWriter out = output(modelFullName); String title = args[0] + " " + Cf.list(args).drop(1).mkString(" "); try { Properties model = loadModel(args, out); print(out, "model = " + title); Random r = new XorShiftRandom(Long.parseLong(model.getProperty("seed"))); int steps = Integer.parseInt(model.getProperty("steps")); ListF<Float> avgFitness = runSimulation(r, model, steps, out); Chart.drawChart(modelFullName, title, avgFitness, avgFitness.size() < steps); } finally { out.close(); System.out.println("Simulation complete for model: " + title); } } static ListF<Float> runSimulation(Random r, Properties model, int steps, PrintWriter out) throws IOException { ListF<Microbe> microbes = Cf.arrayList(); int population = Integer.parseInt(model.getProperty("population")); float normalFitness = Float.parseFloat(model.getProperty("normal.fitness")); int chromosomes = Integer.parseInt(model.getProperty("chromosomes")); int genes = Integer.parseInt(model.getProperty("genes")); for (int i = 0; i < population; i++) { microbes.add(new Microbe(normalFitness, chromosomes, genes, false, i)); } int variploidPopulation = Integer.parseInt(model.getProperty("variploid.population")); for (int i = 0; i < variploidPopulation; i++) { microbes.add(new Microbe(normalFitness, chromosomes, genes, true, i + population)); } float geneMutationChance = Float.parseFloat(model.getProperty("gene.mutation.chance")); float negativeEffect = Float.parseFloat(model.getProperty("negative.effect")); float mutationPositiveChance = Float.parseFloat(model.getProperty("mutation.positive.chance")); float positiveEffect = Float.parseFloat(model.getProperty("positive.effect")); float luckRatio = Float.parseFloat(model.getProperty("luck.ratio")); float conversionRatio = Float.parseFloat(model.getProperty("conversion.ratio")); float crossingRatio = Float.parseFloat(model.getProperty("crossing.ratio")); int maxVariploidChromosomes = Integer.parseInt(model.getProperty("max.variploid.chromosomes")); float downsizeChance = Float.parseFloat(model.getProperty("downsize.chance")); float horizontalTransferRatio = Float.parseFloat(model.getProperty("horizontal.transfer.ratio")); float chromosomeSubstitutionRatio = Float.parseFloat(model.getProperty("chromosome.substitution.ratio")); float chromosomeExchangeRatio = Float.parseFloat(model.getProperty("chromosome.exchange.ratio")); boolean inexactDuplication = "true".equalsIgnoreCase(model.getProperty("inexact.chromosome.duplication")); boolean mitosis = "true".equalsIgnoreCase(model.getProperty("mitosis")); Stat stat = Stat.valueOf(model.getProperty("stat").toUpperCase()); if (stat == Stat.DEV) { print(out, "step\tpopulation\taverage fitness\tstandard deviation"); } else if (stat == Stat.BOX) { print(out, "step\tpopulation\tmedian\t10%\t25%\t75%\t90%"); } else { print(out, "step\tpopulation\taverage fitness"); } ListF<Float> dataset = Cf.arrayList(); for (int s = 0; s < steps; s++) { float totalFitness = 0f; float totalChromosomes = 0; float[] fitnesses = new float[microbes.size()]; int i = 0; for (Microbe microbe : microbes) { float fitness = microbe.fitness(); totalFitness += fitness; fitnesses[i++] = fitness; microbe.mutate(r, geneMutationChance, negativeEffect, mutationPositiveChance, positiveEffect); totalChromosomes += microbe.getChromosomes().length; } for (int t = 0; t < conversionRatio * totalChromosomes; t++) { Microbe target = microbes.get(r.nextInt(microbes.size())); target.conversion(r); } for (int t = 0; t < crossingRatio * totalChromosomes; t++) { Microbe target = microbes.get(r.nextInt(microbes.size())); target.crossing(r); } for (int t = 0; t < horizontalTransferRatio * totalChromosomes; t++) { Microbe donor = microbes.get(r.nextInt(microbes.size())); Microbe recipient = microbes.get(r.nextInt(microbes.size())); recipient.horizontalTransfer(r, donor); } for (int t = 0; t < chromosomeSubstitutionRatio * totalChromosomes; t++) { Microbe donor = microbes.get(r.nextInt(microbes.size())); Microbe recipient = microbes.get(r.nextInt(microbes.size())); recipient.chromosomeSubstitution(r, donor); } for (int t = 0; t < chromosomeExchangeRatio * totalChromosomes; t++) { Microbe donor = microbes.get(r.nextInt(microbes.size())); Microbe recipient = microbes.get(r.nextInt(microbes.size())); recipient.chromosomeExchange(r, donor); } int[] ploidy = new int[10]; for (Microbe microbe : microbes) { if (microbe.getPloidy() <= 9) { ploidy[microbe.isChangePloidy() ? microbe.getPloidy() : 0]++; } } microbes = Microbe.selectOffspring(r, microbes, luckRatio, maxVariploidChromosomes, inexactDuplication, downsizeChance, mitosis); if (microbes.isEmpty()) { break; } float avgFitness = totalFitness / (float) microbes.size(); String statCols = computeStat(stat, avgFitness, fitnesses); print(out, s + "\t" + microbes.size() + "\t" + statCols); if (variploidPopulation > 0) { printPloidy(out, ploidy, microbes.size()); } if (microbes.size() == (population + variploidPopulation)) { dataset.add(avgFitness); } if (s % 10 == 0) { out.flush(); } } /*for (Microbe microbe : microbes.shuffle()) { for (float[] chromosome : microbe.getChromosomes()) { for (float gene : chromosome) { out.print(FMT.format(gene)); out.print("\t"); } out.println(); } out.println(); }*/ if (microbes.isNotEmpty()) { outputChromosomeStats(out, microbes, normalFitness, genes); } return dataset; } private static void outputChromosomeStats(PrintWriter out, ListF<Microbe> microbes, float normalFitness, int genes) { Tuple2List<Integer, float[]> idxChromosomes = Tuple2List.arrayList(); for (Microbe microbe : microbes) { for (float[] chromosome : microbe.getChromosomes()) { int idx = (int) chromosome[0]; idxChromosomes.add(idx, chromosome); } } MapF<Integer, ListF<float[]>> idxToChromosomes = idxChromosomes.groupBy1(); out.println("Chromosome histogram: "); out.println(idxToChromosomes.mapValues(Cf.List.sizeF()).entries().sortBy2().take(20).reverse().mkString("\n", "\t")); for (Tuple2<Integer, ListF<float[]>> entry : idxToChromosomes.entries().sortBy2(Cf.List.sizeF().andThenNaturalComparator().invert()).take(20)) { int count = entry.get2().size(); print(out, " print(out, "#" + entry.get1()); print(out, "chromosome\tgene\tavg\tdev"); if (count <= 1) continue; float avgAvgGene = 0f; float[] avgGenes = new float[genes]; float[] geneAcrossChromosomes = new float[count]; for (int g = 1; g <= genes; g++) { int i = 0; float avgGene = 0f; for (float[] chromosome : entry.get2()) { avgGene += chromosome[g] / normalFitness; geneAcrossChromosomes[i++] = chromosome[g] / normalFitness; } avgGene = avgGene / (float) count; avgGenes[g - 1] = avgGene; avgAvgGene += avgGene; print(out, "c" + entry.get1() + "\tg" + g + "\t" + computeStat(Stat.DEV, avgGene, geneAcrossChromosomes)); } avgAvgGene = avgAvgGene / (float) genes; print(out, "c" + entry.get1() + "\tavg\t" + computeStat(Stat.DEV, avgAvgGene, avgGenes)); } } static String computeStat(Stat stat, float avgFitness, float[] fitnesses) { if (stat == Stat.DEV) { float sdev = 0f; for (float fitness : fitnesses) { sdev += (avgFitness - fitness) * (avgFitness - fitness); } float devFitness = (float) Math.sqrt(sdev / (fitnesses.length - 1f)); return FMT.format(avgFitness) + "\t" + FMT.format(devFitness); } if (stat == Stat.BOX) { Arrays.sort(fitnesses); float median = fitnesses[fitnesses.length / 2]; float lowBox = fitnesses[fitnesses.length / 4]; float highBox = fitnesses[(fitnesses.length / 4) * 3]; float lowWhisker = fitnesses[fitnesses.length / 10]; float highWhisker = fitnesses[(fitnesses.length / 10) * 9]; return FMT.format(median) + "\t" + FMT.format(lowWhisker) + "\t" + FMT.format(lowBox) + "\t" + FMT.format(highBox) + "\t" + FMT.format(highWhisker); } return FMT.format(avgFitness); } private static final int BAR_WIDTH = 50; static void printPloidy(PrintWriter out, int[] ploidy, int population) throws IOException { StringBuilder bar = new StringBuilder(); StringBuilder table = new StringBuilder(); for (int i = 0; i < 10; i++) { for (int b = 0; b < (ploidy[i] * BAR_WIDTH + population / 2) / population; b++) { bar.append(i == 0 ? "M" : Integer.toString(i)); } table.append("\t").append(ploidy[i]); } print(out, bar.append(table).toString()); } static void print(PrintWriter out, String line) { System.out.println(line); out.println(line); } static PrintWriter output(String modelName) throws IOException { File output = new File("models/" + modelName + ".csv"); if (output.exists()) { System.err.println("Creating back-up copy of simulation results"); output.renameTo(new File(output.getPath() + ".bak")); } System.err.println("Writing simulation results to: " + output.getPath()); return new PrintWriter(output); } static String modelWithParameters(String[] args) { String modelName = args[0]; for (int a = 1; a < args.length; a++) { modelName += "-" + args[a].replaceAll(" ", "").replaceAll("=", "-").replaceAll("\\.", ""); } return modelName; } static Properties loadModel(String[] args, final PrintWriter out) throws IOException { Properties model = new Properties() { public String getProperty(String name) { String value = super.getProperty(name); print(out, name + " = " + value); return value; } }; loadPropertiesFile(model, "default"); loadPropertiesFile(model, args[0]); String baseModelName = model.getProperty("base.model"); if (baseModelName != null) { // No support for nesting! // XXX do we need it at all when we have command-line properties? loadPropertiesFile(model, baseModelName); loadPropertiesFile(model, args[0]); } for (int a = 1; a < args.length; a++) { String arg = args[a]; if (arg.matches("^[0-9]+$")) { model.setProperty("seed", arg); continue; } int eq = arg.indexOf("="); if (eq <= 0) { throw new RuntimeException("Cannot parse key=value: " + arg); } model.setProperty(arg.substring(0, eq).trim(), arg.substring(eq + 1).trim()); } return model; } static void loadPropertiesFile(Properties model, String modelName) throws IOException { FileInputStream stream = new FileInputStream(new File("models/" + modelName + ".properties")); try { model.load(stream); } finally { try { stream.close(); } catch (Exception e) { System.err.println(e); } } } }
package seedu.task.model.task; import java.util.Comparator; import java.util.Objects; import seedu.task.commons.util.CollectionUtil; import seedu.task.model.tag.UniqueTagList; /** * Represents a Task in the ToDo List. Guarantees: details are present and not * null, field values are validated. */ public class Task implements ReadOnlyTask, Comparable<Task> { private Description description; private Priority priority; private Timing startTiming; private Timing endTiming; private boolean complete; private UniqueTagList tags; /** * Every field must be present and not null. */ public Task(Description description, Priority priority, Timing startTiming, Timing endTiming, UniqueTagList tags) { assert !CollectionUtil.isAnyNull(description, priority, startTiming, tags); this.description = description; this.priority = priority; this.startTiming = startTiming; this.endTiming = endTiming; this.complete = false; this.tags = new UniqueTagList(tags); // protect internal tags from // changes in the arg list } /** * Creates a copy of the given ReadOnlyTask. */ public Task(ReadOnlyTask source) { this(source.getDescription(), source.getPriority(), source.getStartTiming(), source.getEndTiming(), source.getTags()); } public void setDescription(Description description) { assert description != null; this.description = description; } @Override public Description getDescription() { return description; } public void setPriority(Priority priority) { assert priority != null; this.priority = priority; } @Override public Priority getPriority() { return priority; } public void setStartTiming(Timing startTiming) { assert startTiming != null; this.startTiming = startTiming; } @Override public Timing getStartTiming() { return startTiming; } public void setEndTiming(Timing endTiming) { assert endTiming != null; this.endTiming = endTiming; } @Override public Timing getEndTiming() { return endTiming; } public void setComplete() { this.complete = true; } @Override public boolean isComplete() { return this.complete; } @Override public UniqueTagList getTags() { return new UniqueTagList(tags); } /** * Replaces this task's tags with the tags in the argument tag list. */ public void setTags(UniqueTagList replacement) { tags.setTags(replacement); } /** * Updates this task with the details of {@code replacement}. */ public void resetData(ReadOnlyTask replacement) { assert replacement != null; this.setDescription(replacement.getDescription()); this.setPriority(replacement.getPriority()); this.setStartTiming(replacement.getStartTiming()); this.setEndTiming(replacement.getEndTiming()); this.setTags(replacement.getTags()); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof ReadOnlyTask // instanceof handles nulls && this.isSameStateAs((ReadOnlyTask) other)); } @Override public int hashCode() { // use this method for custom fields hashing instead of implementing // your own return Objects.hash(description, priority, startTiming, endTiming, tags); } @Override public String toString() { return getAsText(); } /** * Results in Tasks sorted by completed state, followed by priority, endTiming, startTiming * and lastly by description. * Note: If a and b are tasks and a.compareTo(b) == 0, that does not imply * a.equals(b). */ @Override public int compareTo(Task compareTask) { int compareToResult = 0; if (this.isComplete() && compareTask.isComplete()) { compareToResult = 0; } else if (this.isComplete()) { compareToResult = -1; } else if (compareTask.isComplete()) { compareToResult = 1; } if (compareToResult == 0) { compareToResult = this.priority.compareTo(compareTask.priority); } if (compareToResult == 0) { compareToResult = this.endTiming.compareTo(compareTask.endTiming); } if (compareToResult == 0) { compareToResult = this.startTiming.compareTo(compareTask.startTiming); } if (compareToResult == 0) { compareToResult = this.getDescription().compareTo(compareTask.getDescription()); } return compareToResult; } public static Comparator<Task> TaskComparator = new Comparator<Task>() { @Override public int compare(Task task1, Task task2) { return task1.compareTo(task2); } }; }
package au.gov.ga.geodesy.support.mapper.dozer.populator; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.dozer.event.DozerEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import au.gov.ga.geodesy.support.utils.GMLGeoTools; import au.gov.ga.geodesy.support.utils.GMLGmlTools; import au.gov.ga.geodesy.support.utils.GMLMiscTools; import au.gov.xml.icsm.geodesyml.v_0_3.SiteLocationType; /** * The translate simply copied the Countries (in Sopac Sitelog XML) across to the GeoesyML CountryCode elements. * This cleans those up by converting to the actual CountryCodes. * * @author brookes * */ public class SiteLocationTypePopulator extends GeodesyMLElementPopulator<SiteLocationType> { Logger logger = LoggerFactory.getLogger(getClass()); @Override void checkAllRequiredElementsPopulated(SiteLocationType siteLocationType) { checkElementPopulated(siteLocationType, "city", GMLMiscTools.getEmptyString()); checkElementPopulated(siteLocationType, "state", GMLMiscTools.getEmptyString()); checkElementPopulated(siteLocationType, "countryCodeISO", GMLMiscTools.getEmptyString()); checkElementPopulated(siteLocationType, "tectonicPlate", GMLGmlTools.getEmptyCodeType()); checkElementPopulated(siteLocationType, "approximatePositionITRF", GMLGeoTools.buildZeroApproximatePositionITRF()); } @Override public void postWritingDestinationValue(DozerEvent event) { super.postWritingDestinationValue(event); SiteLocationType siteLocationType = (SiteLocationType) event.getDestinationObject(); String country = siteLocationType.getCountryCodeISO(); String code = COUNTRY_CODES_ALPHA_3.lookupCode(country); siteLocationType.setCountryCodeISO(code); logger.debug(String.format("Change country: '%s' to code '%s'", country, code)); } public static class COUNTRY_CODES_ALPHA_3 { private static Map<String, String> codeToCountry = new HashMap<>(); private static Map<String, String> countryToCode = new HashMap<>(); private static String[] codesArrayList = new String[] {"ABW", "Aruba", "AFG", "Afghanistan", "AGO", "Angola", "AIA", "Anguilla", "ALA", "Åland Islands", "ALB", "Albania", "AND", "Andorra", "ARE", "United Arab Emirates", "ARG", "Argentina", "ARM", "Armenia", "ASM", "American Samoa", "ATA", "Antarctica", "ATF", "French Southern Territories", "ATG", "Antigua and Barbuda", "AUS", "Australia", "AUT", "Austria", "AZE", "Azerbaijan", "BDI", "Burundi", "BEL", "Belgium", "BEN", "Benin", "BES", "Bonaire, Sint Eustatius and Saba", "BFA", "Burkina Faso", "BGD", "Bangladesh", "BGR", "Bulgaria", "BHR", "Bahrain", "BHS", "Bahamas", "BIH", "Bosnia and Herzegovina", "BLM", "Saint Barthélemy", "BLR", "Belarus", "BLZ", "Belize", "BMU", "Bermuda", "BOL", "Bolivia, Plurinational State of", "BRA", "Brazil", "BRB", "Barbados", "BRN", "Brunei Darussalam", "BTN", "Bhutan", "BVT", "Bouvet Island", "BWA", "Botswana", "CAF", "Central African Republic", "CAN", "Canada", "CCK", "Cocos (Keeling) Islands", "CHE", "Switzerland", "CHL", "Chile", "CHN", "China", "CIV", "Côte d'Ivoire", "CMR", "Cameroon", "COD", "Congo, the Democratic Republic of the", "COG", "Congo", "COK", "Cook Islands", "COL", "Colombia", "COM", "Comoros", "CPV", "Cabo Verde", "CRI", "Costa Rica", "CUB", "Cuba", "CUW", "Curaçao", "CXR", "Christmas Island", "CYM", "Cayman Islands", "CYP", "Cyprus", "CZE", "Czech Republic", "DEU", "Germany", "DJI", "Djibouti", "DMA", "Dominica", "DNK", "Denmark", "DOM", "Dominican Republic", "DZA", "Algeria", "ECU", "Ecuador", "EGY", "Egypt", "ERI", "Eritrea", "ESH", "Western Sahara", "ESP", "Spain", "EST", "Estonia", "ETH", "Ethiopia", "FIN", "Finland", "FJI", "Fiji", "FLK", "Falkland Islands (Malvinas)", "FRA", "France", "FRO", "Faroe Islands", "FSM", "Micronesia, Federated States of", "GAB", "Gabon", "GBR", "United Kingdom", "GEO", "Georgia", "GGY", "Guernsey", "GHA", "Ghana", "GIB", "Gibraltar", "GIN", "Guinea", "GLP", "Guadeloupe", "GMB", "Gambia", "GNB", "Guinea-Bissau", "GNQ", "Equatorial Guinea", "GRC", "Greece", "GRD", "Grenada", "GRL", "Greenland", "GTM", "Guatemala", "GUF", "French Guiana", "GUM", "Guam", "GUY", "Guyana", "HKG", "Hong Kong", "HMD", "Heard Island and McDonald Islands", "HND", "Honduras", "HRV", "Croatia", "HTI", "Haiti", "HUN", "Hungary", "IDN", "Indonesia", "IMN", "Isle of Man", "IND", "India", "IOT", "British Indian Ocean Territory", "IRL", "Ireland", "IRN", "Iran, Islamic Republic of", "IRQ", "Iraq", "ISL", "Iceland", "ISR", "Israel", "ITA", "Italy", "JAM", "Jamaica", "JEY", "Jersey", "JOR", "Jordan", "JPN", "Japan", "KAZ", "Kazakhstan", "KEN", "Kenya", "KGZ", "Kyrgyzstan", "KHM", "Cambodia", "KIR", "Kiribati", "KNA", "Saint Kitts and Nevis", "KOR", "Korea, Republic of", "KWT", "Kuwait", "LAO", "Lao People's Democratic Republic", "LBN", "Lebanon", "LBR", "Liberia", "LBY", "Libya", "LCA", "Saint Lucia", "LIE", "Liechtenstein", "LKA", "Sri Lanka", "LSO", "Lesotho", "LTU", "Lithuania", "LUX", "Luxembourg", "LVA", "Latvia", "MAC", "Macao", "MAF", "Saint Martin (French part)", "MAR", "Morocco", "MCO", "Monaco", "MDA", "Moldova, Republic of", "MDG", "Madagascar", "MDV", "Maldives", "MEX", "Mexico", "MHL", "Marshall Islands", "MKD", "Macedonia, the former Yugoslav Republic of", "MLI", "Mali", "MLT", "Malta", "MMR", "Myanmar", "MNE", "Montenegro", "MNG", "Mongolia", "MNP", "Northern Mariana Islands", "MOZ", "Mozambique", "MRT", "Mauritania", "MSR", "Montserrat", "MTQ", "Martinique", "MUS", "Mauritius", "MWI", "Malawi", "MYS", "Malaysia", "MYT", "Mayotte", "NAM", "Namibia", "NCL", "New Caledonia", "NER", "Niger", "NFK", "Norfolk Island", "NGA", "Nigeria", "NIC", "Nicaragua", "NIU", "Niue", "NLD", "Netherlands", "NOR", "Norway", "NPL", "Nepal", "NRU", "Nauru", "NZL", "New Zealand", "OMN", "Oman", "PAK", "Pakistan", "PAN", "Panama", "PCN", "Pitcairn", "PER", "Peru", "PHL", "Philippines", "PLW", "Palau", "PNG", "Papua New Guinea", "POL", "Poland", "PRI", "Puerto Rico", "PRK", "Korea, Democratic People's Republic of", "PRT", "Portugal", "PRY", "Paraguay", "PSE", "Palestine, State of", "PYF", "French Polynesia", "QAT", "Qatar", "REU", "Réunion", "ROU", "Romania", "RUS", "Russian Federation", "RWA", "Rwanda", "SAU", "Saudi Arabia", "SDN", "Sudan", "SEN", "Senegal", "SGP", "Singapore", "SGS", "South Georgia and the South Sandwich Islands", "SHN", "Saint Helena, Ascension and Tristan da Cunha", "SJM", "Svalbard and Jan Mayen", "SLB", "Solomon Islands", "SLE", "Sierra Leone", "SLV", "El Salvador", "SMR", "San Marino", "SOM", "Somalia", "SPM", "Saint Pierre and Miquelon", "SRB", "Serbia", "SSD", "South Sudan", "STP", "Sao Tome and Principe", "SUR", "Suriname", "SVK", "Slovakia", "SVN", "Slovenia", "SWE", "Sweden", "SWZ", "Swaziland", "SXM", "Sint Maarten (Dutch part)", "SYC", "Seychelles", "SYR", "Syrian Arab Republic", "TCA", "Turks and Caicos Islands", "TCD", "Chad", "TGO", "Togo", "THA", "Thailand", "TJK", "Tajikistan", "TKL", "Tokelau", "TKM", "Turkmenistan", "TLS", "Timor-Leste", "TON", "Tonga", "TTO", "Trinidad and Tobago", "TUN", "Tunisia", "TUR", "Turkey", "TUV", "Tuvalu", "TWN", "Taiwan, Province of China", "TZA", "Tanzania, United Republic of", "UGA", "Uganda", "UKR", "Ukraine", "UMI", "United States Minor Outlying Islands", "URY", "Uruguay", "USA", "United States of America", "UZB", "Uzbekistan", "VAT", "Holy See (Vatican City State)", "VCT", "Saint Vincent and the Grenadines", "VEN", "Venezuela, Bolivarian Republic of", "VGB", "Virgin Islands, British", "VIR", "Virgin Islands, U.S.", "VNM", "Viet Nam", "VUT", "Vanuatu", "WLF", "Wallis and Futuna", "WSM", "Samoa", "YEM", "Yemen", "ZAF", "South Africa", "ZMB", "Zambia", "ZWE", "Zimbabwe"}; static { if (codesArrayList.length % 2 != 0) { throw new RuntimeException("codesArrayList has changed - it should be even (code, country)*"); } for (int i = 0; i < codesArrayList.length; i += 2) { codeToCountry.put(codesArrayList[i].toUpperCase(), codesArrayList[i + 1].toUpperCase()); countryToCode.put(codesArrayList[i + 1].toUpperCase(), codesArrayList[i].toUpperCase()); } } public static String lookupCode(String country) { if (StringUtils.isBlank(country)) { return ""; } if (countryToCode.containsKey(country.toUpperCase())) { return countryToCode.get(country.toUpperCase()); } else { return country; } } public static String lookupCountry(String code) { if (StringUtils.isBlank(code)) { return ""; } if (codeToCountry.containsKey(code.toUpperCase())) { return codeToCountry.get(code.toUpperCase()); } else { return code; } } } }
package org.lenskit.data.dao.file; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.google.common.collect.Lists; import it.unimi.dsi.fastutil.longs.LongSet; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Test; import org.lenskit.data.dao.DataAccessObject; import org.lenskit.data.entities.*; import org.lenskit.data.ratings.Rating; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class StaticDataSourceTest { private EntityFactory factory = new EntityFactory(); private ObjectReader reader = new ObjectMapper().reader(); @Test public void testSomeEvents() { StaticDataSource layout = new StaticDataSource(); List<Entity> ratings = Lists.<Entity>newArrayList(factory.rating(1L, 20L, 3.5), factory.rating(1L, 21L, 4.5)); layout.addSource(ratings); // we should have one collection source for entities assertThat(layout.getSourcesForType(CommonTypes.RATING), contains(instanceOf(CollectionEntitySource.class))); DataAccessObject dao = layout.get(); assertThat(dao.getEntityTypes(), containsInAnyOrder(CommonTypes.RATING, CommonTypes.USER, CommonTypes.ITEM)); assertThat(dao.lookupEntity(CommonTypes.RATING, ratings.get(0).getId()), equalTo(ratings.get(0))); assertThat(dao.query(CommonTypes.RATING) .withAttribute(CommonAttributes.ITEM_ID, 20L) .get(), contains(ratings.get(0))); assertThat(dao.query(CommonTypes.RATING) .withAttribute(CommonAttributes.USER_ID, 1L) .get(), contains(ratings.toArray())); assertThat(dao.getEntityIds(CommonTypes.USER), contains(1L)); assertThat(dao.getEntityIds(CommonTypes.ITEM), containsInAnyOrder(20L, 21L)); assertThat(dao.query(CommonTypes.USER).get(), contains(Entities.create(CommonTypes.USER, 1))); assertThat(dao.query(CommonTypes.ITEM).get(), containsInAnyOrder(Entities.create(CommonTypes.ITEM, 20), Entities.create(CommonTypes.ITEM, 21))); } @Test public void testIndexedEvents() { StaticDataSource layout = new StaticDataSource(); layout.addIndex(CommonTypes.RATING, CommonAttributes.USER_ID); List<Entity> ratings = Lists.<Entity>newArrayList(factory.rating(1L, 20L, 3.5), factory.rating(1L, 21L, 4.5)); layout.addSource(ratings); DataAccessObject dao = layout.get(); assertThat(dao.getEntityTypes(), containsInAnyOrder(CommonTypes.RATING, CommonTypes.USER, CommonTypes.ITEM)); assertThat(dao.lookupEntity(CommonTypes.RATING, ratings.get(0).getId()), equalTo(ratings.get(0))); assertThat(dao.query(CommonTypes.RATING) .withAttribute(CommonAttributes.ITEM_ID, 20L) .get(), contains(ratings.get(0))); assertThat(dao.query(CommonTypes.RATING) .withAttribute(CommonAttributes.USER_ID, 1L) .get(), contains(ratings.toArray())); assertThat(dao.getEntityIds(CommonTypes.USER), contains(1L)); assertThat(dao.getEntityIds(CommonTypes.ITEM), containsInAnyOrder(20L, 21L)); assertThat(dao.query(CommonTypes.USER).get(), contains(Entities.create(CommonTypes.USER, 1))); assertThat(dao.query(CommonTypes.ITEM).get(), containsInAnyOrder(Entities.create(CommonTypes.ITEM, 20), Entities.create(CommonTypes.ITEM, 21))); } @Test public void testLoadRatings() throws IOException, URISyntaxException { URI baseURI = TextEntitySourceTest.class.getResource("ratings.csv").toURI(); JsonNode node = reader.readTree("{\"file\": \"ratings.csv\", \"format\": \"csv\"}"); StaticDataSource daoProvider = StaticDataSource.fromJSON(node, baseURI); // we should have one text source for ratings assertThat(daoProvider.getSourcesForType(CommonTypes.RATING), contains(instanceOf(TextEntitySource.class))); DataAccessObject dao = daoProvider.get(); verifyRatingsCsvData(dao); } @Test public void testLoadRatingsList() throws IOException, URISyntaxException { URI baseURI = TextEntitySourceTest.class.getResource("ratings.csv").toURI(); JsonNode node = reader.readTree("[{\"file\": \"ratings.csv\", \"format\": \"csv\"}]"); StaticDataSource daoProvider = StaticDataSource.fromJSON(node, baseURI); DataAccessObject dao = daoProvider.get(); verifyRatingsCsvData(dao); } @Test public void testLoadRatingsMap() throws IOException, URISyntaxException { URI baseURI = TextEntitySourceTest.class.getResource("ratings.csv").toURI(); JsonNode node = reader.readTree("{\"ratings\":{\"file\": \"ratings.csv\", \"format\": \"csv\"}}"); StaticDataSource daoProvider = StaticDataSource.fromJSON(node, baseURI); DataAccessObject dao = daoProvider.get(); verifyRatingsCsvData(dao); } @Test public void testLoadRatingsDeriveBobcats() throws IOException, URISyntaxException { URI baseURI = TextEntitySourceTest.class.getResource("ratings.csv").toURI(); JsonNode node = reader.readTree("[{\"file\": \"ratings.csv\", \"format\": \"csv\"}, {\"type\": \"derived\", \"source_type\": \"rating\", \"entity_type\": \"bobcat\", \"source_attribute\": \"item\"}]"); StaticDataSource daoProvider = StaticDataSource.fromJSON(node, baseURI); // we should have one text source for ratings; derived aren't sources assertThat(daoProvider.getSourcesForType(CommonTypes.RATING), contains(instanceOf(TextEntitySource.class))); DataAccessObject dao = daoProvider.get(); verifyRatingsCsvData(dao, EntityType.forName("bobcat")); // we should have have a bunch of bobcats LongSet bobcats = dao.getEntityIds(EntityType.forName("bobcat")); assertThat(bobcats, equalTo(dao.getEntityIds(CommonTypes.ITEM))); } @Test public void testLoadInvalidDataSource() throws URISyntaxException, IOException { URI baseURI = TextEntitySourceTest.class.getResource("ratings.csv").toURI(); JsonNode node = reader.readTree("\"foobar\""); try { StaticDataSource daoProvider = StaticDataSource.fromJSON(node, baseURI); fail("JSON parsing succeeded, should have failed on string"); } catch (IllegalArgumentException e) { /* expected */ } } private void verifyRatingsCsvData(DataAccessObject dao, EntityType... extraTypes) { EntityType[] ets = new EntityType[3 + extraTypes.length]; ets[0] = CommonTypes.RATING; ets[1] = CommonTypes.USER; ets[2] = CommonTypes.ITEM; System.arraycopy(extraTypes, 0, ets, 3, extraTypes.length); assertThat(dao.getEntityTypes(), containsInAnyOrder(ets)); List<Entity> ratings = dao.query(CommonTypes.RATING).get(); assertThat(ratings, hasSize(2)); // turn this off because packed loading violates! // assertThat(ratings, (Matcher) everyItem(instanceOf(Rating.class))); Entity first = ratings.get(0); assertThat(first.getType(), equalTo(EntityType.forName("rating"))); assertThat(first.getId(), equalTo(1L)); assertThat(first.get(CommonAttributes.ENTITY_ID), equalTo(1L)); assertThat(first.get(CommonAttributes.ITEM_ID), equalTo(20L)); assertThat(first.get(CommonAttributes.USER_ID), equalTo(10L)); assertThat(first.get(CommonAttributes.RATING), equalTo(3.5)); assertThat(first.hasAttribute(CommonAttributes.TIMESTAMP), equalTo(false)); Entity second = ratings.get(1); assertThat(second.getType(), equalTo(EntityType.forName("rating"))); assertThat(second.getId(), equalTo(2L)); assertThat(second.get(CommonAttributes.ENTITY_ID), equalTo(2L)); assertThat(second.get(CommonAttributes.ITEM_ID), equalTo(20L)); assertThat(second.get(CommonAttributes.USER_ID), equalTo(11L)); assertThat(second.get(CommonAttributes.RATING), equalTo(4.0)); assertThat(second.hasAttribute(CommonAttributes.TIMESTAMP), equalTo(false)); // we have two users assertThat(dao.query(CommonTypes.USER).get(), containsInAnyOrder(Entities.create(CommonTypes.USER, 10), Entities.create(CommonTypes.USER, 11))); // and one item assertThat(dao.query(CommonTypes.ITEM).get(), contains(Entities.create(CommonTypes.ITEM, 20))); // check a view query List<Rating> rlist = dao.query(Rating.class) .get(); assertThat(rlist, hasSize(2)); assertThat(rlist, (Matcher) equalTo(ratings)); } }
package ca.corefacility.bioinformatics.irida.ria.web.files; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.format.Formatter; import org.springframework.format.datetime.DateFormatter; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import ca.corefacility.bioinformatics.irida.model.joins.Join; import ca.corefacility.bioinformatics.irida.model.project.Project; import ca.corefacility.bioinformatics.irida.model.project.ReferenceFile; import ca.corefacility.bioinformatics.irida.ria.utilities.converters.FileSizeConverter; import ca.corefacility.bioinformatics.irida.service.ProjectService; import ca.corefacility.bioinformatics.irida.service.ReferenceFileService; /** * Controller for all {@link ReferenceFile} related views * * @author Josh Adam <josh.adam@phac-aspc.gc.ca> */ @Controller @RequestMapping("/referenceFiles") public class ReferenceFileController { private static final Logger logger = LoggerFactory.getLogger(ReferenceFileController.class); // Converters Formatter<Date> dateFormatter; private ProjectService projectService; private ReferenceFileService referenceFileService; private FileSizeConverter fileSizeConverter; @Autowired public ReferenceFileController(ProjectService projectService, ReferenceFileService referenceFileService) { this.projectService = projectService; this.referenceFileService = referenceFileService; this.fileSizeConverter = new FileSizeConverter(); this.dateFormatter = new DateFormatter(); } @RequestMapping(value = "/download/{fileId}") public void downloadReferenceFile(@PathVariable Long fileId, HttpServletResponse response) throws IOException { ReferenceFile file = referenceFileService.read(fileId); Path path = file.getFile(); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getLabel() + "\""); Files.copy(path, response.getOutputStream()); response.flushBuffer(); } @RequestMapping("/project/{projectId}/new") public @ResponseBody Map<String, String> createNewReferenceFile(@PathVariable Long projectId, @RequestParam("files[]") MultipartFile files) throws IOException { logger.debug("Adding reference file to project " + projectId); logger.trace("Uploaded file size: " + files.getSize() + " bytes"); Project project = projectService.read(projectId); logger.trace("Read project " + projectId); // Prepare a new reference file using the multipart file supplied by the caller Path temp = Files.createTempDirectory(null); Path target = temp.resolve(files.getOriginalFilename()); files.transferTo(target.toFile()); logger.debug("Wrote temp file to " + target); ReferenceFile referenceFile = new ReferenceFile(target); Join<Project, ReferenceFile> projectReferenceFileJoin = projectService .addReferenceFileToProject(project, referenceFile); logger.debug("Created reference file in project " + projectId); ReferenceFile file = projectReferenceFileJoin.getObject(); Map<String, String> result = new HashMap<>(); Path path = file.getFile(); long size = 0; if (Files.exists(path)) { size = Files.size(path); } result.put("size", fileSizeConverter.convert(size)); result.put("id", file.getId().toString()); result.put("label", file.getLabel()); result.put("createdDate", dateFormatter.print(file.getCreatedDate(), LocaleContextHolder.getLocale())); // Clean up temporary files Files.deleteIfExists(target); Files.deleteIfExists(temp); return result; } @RequestMapping("/delete") public @ResponseBody String deleteReferenceFile(@RequestParam Long fileId, HttpServletResponse response) { String result = "success"; try { referenceFileService.delete(fileId); } catch (Exception e) { // This is required else the client does not know that an error was thrown! response.setStatus(HttpServletResponse.SC_BAD_REQUEST); logger.error(e.getLocalizedMessage()); result = "error"; } return result; } }
package ca.corefacility.bioinformatics.irida.ria.web.models.tables; import java.util.List; import java.util.stream.Collectors; import org.springframework.data.domain.Sort; public class AntTableRequest { private AntPagination pagination; private List<AntSort> order; public Sort getSort() { if (order != null && order.size() > 0) { return Sort.by(order.stream().map(AntSort::getOrder).collect(Collectors.toList())); } return Sort.unsorted(); } public int getPageSize() { return pagination.getPageSize(); } public int getPage() { return pagination.getCurrent(); } public void setOrder(List<AntSort> order) { this.order = order; } public void setPagination(AntPagination pagination) { this.pagination = pagination; } }
package tars.commons.core; /** * Container for user visible messages. */ public class Messages { public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command"; public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s"; public static final String MESSAGE_INVALID_DATE = "Invalid date time entered!"; public static final String MESSAGE_INVALID_END_DATE = "End dateTime should be after start dateTime."; public static final String MESSAGE_INVALID_TASK_DISPLAYED_INDEX = "The task index provided is invalid"; public static final String MESSAGE_PERSONS_LISTED_OVERVIEW = "%1$d tasks listed!"; public static final String MESSAGE_TASK_CANNOT_BE_FOUND = "Task cannot be found!"; public static final String MESSAGE_DUPLICATE_TASK= "This task already exists in tars"; }
package com.almightyalpaca.discord.jdabutler.commands.commands; import com.almightyalpaca.discord.jdabutler.Bot; import com.almightyalpaca.discord.jdabutler.EmbedUtil; import com.almightyalpaca.discord.jdabutler.commands.Command; import com.kantenkugel.discordbot.versioncheck.VersionCheckerRegistry; import com.kantenkugel.discordbot.versioncheck.items.VersionedItem; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.MessageBuilder; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.Role; import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent; import java.time.OffsetDateTime; import java.util.List; import java.util.stream.Collectors; import static com.kantenkugel.discordbot.versioncheck.VersionCheckerRegistry.EXPERIMENTAL_ITEM; public class AnnouncementCommand implements Command { @Override public void dispatch(final User sender, final TextChannel channel, final Message message, final String content, final GuildMessageReceivedEvent event) { if(!channel.getGuild().equals(Bot.getGuildJda())) { this.sendFailed(message); return; } final String[] args = content.split("\\s\\|\\s", 3); if (args.length < 2) { this.sendFailed(message); return; } final Role role; String image = null; if(args.length == 3) { if(args[0].equals("experimental")) { if(!Bot.isAdmin(sender)) { this.sendFailed(message); return; } role = EXPERIMENTAL_ITEM.getAnnouncementRole(); image = EmbedUtil.JDA_ICON; } else { VersionedItem item = VersionCheckerRegistry.getItem(args[0]); if(item == null) { channel.sendMessage("Item with name " + args[0] + " doesn't exist!").queue(); return; } if(!item.canAnnounce(sender) && !Bot.isAdmin(sender)) { this.sendFailed(message); return; } role = item.getAnnouncementRole(); if(item.getName().equalsIgnoreCase("jda")) image = EmbedUtil.JDA_ICON; if(role == null) { channel.sendMessage("This item has no announcement role set up!").queue(); return; } } } else { List<VersionedItem> items = VersionCheckerRegistry.getVersionedItems().stream() .filter(i -> i.getAnnouncementRoleId() != 0 && i.getAnnouncementChannelId() == channel.getIdLong() && (Bot.isAdmin(sender) || i.canAnnounce(sender))) .collect(Collectors.toList()); if(channel.getIdLong() == EXPERIMENTAL_ITEM.getAnnouncementChannelId() && Bot.isAdmin(sender)) items.add(EXPERIMENTAL_ITEM); switch(items.size()) { case 0: channel.sendMessage("No roles set up for this channel or you do not have access to them").queue(); return; case 1: VersionedItem item = items.get(0); role = item.getAnnouncementRole(); if(role == null) { channel.sendMessage("Item has invalid role id set up").queue(); return; } if(item.getName().equalsIgnoreCase("jda") || item == EXPERIMENTAL_ITEM) image = EmbedUtil.JDA_ICON; break; default: channel.sendMessage("Too many roles set up for this channel. You have to manually specify one via command.").queue(); return; } } message.delete().queue(); @SuppressWarnings("ConstantConditions") final MessageBuilder mb = new MessageBuilder().append(role.getAsMention()); final EmbedBuilder eb = new EmbedBuilder(); EmbedUtil.setColor(eb); eb.setTitle(args.length == 3 ? args[1].trim() : args[0].trim(), null); eb.setDescription(args.length == 3 ? args[2].trim() : args[1].trim()); eb.setTimestamp(OffsetDateTime.now()); eb.setThumbnail(image); eb.setFooter(sender.getName(), sender.getEffectiveAvatarUrl()); mb.setEmbed(eb.build()); role.getManager().setMentionable(true).queue(s -> channel.sendMessage(mb.build()).queue(m -> role.getManager().setMentionable(false).queue())); } @Override public String getHelp() { return "`announce [ROLE | ]TITLE | TEXT`"; } @Override public String getName() { return "announce"; } }
package com.clevergang.dbtests.repository.impl.jdbctemplate; import com.clevergang.dbtests.repository.api.DataRepository; import com.clevergang.dbtests.repository.api.data.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import java.math.BigDecimal; import java.util.List; import java.util.stream.Collectors; /** * Spring JDBCTemplate implementation of the DataRepository * * @author Bretislav Wajtr */ @Repository public class JDBCDataRepositoryImpl implements DataRepository { private static final Logger logger = LoggerFactory.getLogger(JDBCDataRepositoryImpl.class); private final NamedParameterJdbcTemplate jdbcTemplate; // NOTE: I would recommend to handle creation and caching of SimpleJdbcInsert instances like depicted here, for two reasons: // 1. In order to SimpleJdbcInsert to be effective, it cannot be created for each call - remember that during first use of // SimpleJdbcInsert, metadata for the table are fetched from database and this costs some time. So best way how to use SimpleJdbcInsert // is to reuse single instance. // 2. I wouldn't put instances of SimpleJdbcInsert to some external cache, but, like here, tie the instance of SimpleJdbcInsert with DAO bean. // That way it's ensured, that when the DAO bean is recreated so are be recreated all SimpleJdbcInsert instances the DAO bean depends on... private final SimpleJdbcInsert insertIntoProject; @SuppressWarnings("SpringJavaAutowiringInspection") @Autowired public JDBCDataRepositoryImpl(NamedParameterJdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; this.insertIntoProject = new SimpleJdbcInsert((JdbcTemplate) jdbcTemplate.getJdbcOperations()) .withTableName("project") .usingGeneratedKeyColumns("pid"); } @Override public Company findCompany(Integer pid) { logger.info("Finding Company by ID using JDBCTemplate"); String query = "SELECT pid, address, name " + "FROM company " + "WHERE pid = :pid"; MapSqlParameterSource params = new MapSqlParameterSource() .addValue("pid", pid); /* * Note that you can use BeanPropertyRowMapper instead (see findDepartment()) */ RowMapper<Company> mapper = (rs, rowNum) -> { Company row = new Company(); row.setPid(rs.getInt("pid")); row.setAddress(rs.getString("address")); row.setName(rs.getString("name")); return row; }; Company company = jdbcTemplate.queryForObject(query, params, mapper); logger.info("Found company: " + company); return company; } @Override public Company findCompanyUsingSimpleStaticStatement(Integer pid) { String query; query = "SELECT pid, address, name " + "FROM company " + "WHERE pid = " + pid; RowMapper<Company> mapper = (rs, rowNum) -> { Company row = new Company(); row.setPid(rs.getInt("pid")); row.setAddress(rs.getString("address")); row.setName(rs.getString("name")); return row; }; // In Spring's JDBCTemplate it's pretty easy to execute the query using static Statement (not the PreparedStatement): // In this DAO we autowired NamedParameterJdbcTemplate, which does not allow static statements, but this class // is just a wrapper around original JdbcTemplate which allows static statements -> so we used getJdbcOperations() // to get such original object and then just used one of it's methods which internally calls the static // statement (see javadoc for each JdbcOperations#query*() method) Company company = jdbcTemplate.getJdbcOperations().queryForObject(query, mapper); logger.info("Found company: " + company); return company; } @Override public Department findDepartment(Integer pid) { String query = "SELECT pid, company_pid, name" + " FROM department " + " WHERE pid = :pid"; MapSqlParameterSource params = new MapSqlParameterSource() .addValue("pid", pid); // using BeanPropertyRowMapper is easier, but with much worse performance than custom RowMapper return jdbcTemplate.queryForObject(query, params, BeanPropertyRowMapper.newInstance(Department.class)); } @Override public List<Employee> employeesWithSalaryGreaterThan(Integer minSalary) { logger.info("Looking for employeesWithSalaryGreaterThan using JDBCTemplate"); String query = "SELECT * " + " FROM employee" + " WHERE salary > :salary"; MapSqlParameterSource params = new MapSqlParameterSource() .addValue("salary", minSalary); // using BeanPropertyRowMapper is easier, but with much worse performance than custom RowMapper return jdbcTemplate.query(query, params, BeanPropertyRowMapper.newInstance(Employee.class)); } @Override public Integer insertProject(Project project) { MapSqlParameterSource params = new MapSqlParameterSource() .addValue("name", project.getName()) .addValue("datestarted", project.getDate()); return insertIntoProject.executeAndReturnKey(params).intValue(); } @Override public List<Integer> insertProjects(List<Project> projects) { MapSqlParameterSource[] paramsList = projects .stream() .map(project -> new MapSqlParameterSource() .addValue("name", project.getName()) .addValue("datestarted", project.getDate())) .toArray(MapSqlParameterSource[]::new); // NOTE: Here we used SimpleJdbcInsert to insert the rows, but you can also use more traditional way // by specifying the statment to be executed (handy when you need to do some customizations of the statement). // See insertDepartments() method for an example. insertIntoProject.executeBatch(paramsList); // FIXME JDBCTemplate cannot return IDs for every row after batch update!! return null; } @Override public void updateEmployee(Employee employeeToUpdate) { logger.info("Updating employee using JDBC Template"); String updateStatement = " UPDATE EMPLOYEE SET " + " department_pid = :department_pid, " + " name = :name," + " surname = :surname," + " email = :email," + " salary = :salary" + " WHERE pid = :pid"; MapSqlParameterSource params = new MapSqlParameterSource() .addValue("department_pid", employeeToUpdate.getDepartmentPid()) .addValue("name", employeeToUpdate.getName()) .addValue("surname", employeeToUpdate.getSurname()) .addValue("email", employeeToUpdate.getEmail()) .addValue("salary", employeeToUpdate.getSalary()) .addValue("pid", employeeToUpdate.getPid()); jdbcTemplate.update(updateStatement, params); } @Override public List<ProjectsWithCostsGreaterThanOutput> getProjectsWithCostsGreaterThan(int totalCostBoundary) { String query; query = "WITH project_info AS (\n" + " SELECT project.pid project_pid, project.name project_name, salary monthly_cost, company.name company_name\n" + " FROM project\n" + " JOIN projectemployee ON project.pid = projectemployee.project_pid\n" + " JOIN employee ON projectemployee.employee_pid = employee.pid\n" + " LEFT JOIN department ON employee.department_pid = department.pid\n" + " LEFT JOIN company ON department.company_pid = company.pid\n" + "),\n" + "project_cost AS (\n" + " SELECT project_pid, sum(monthly_cost) total_cost\n" + " FROM project_info GROUP BY project_pid\n" + ")\n" + "SELECT project_name, total_cost, company_name, sum(monthly_cost) company_cost FROM project_info\n" + " JOIN project_cost USING (project_pid)\n" + "WHERE total_cost > :totalCostBoundary\n" + "GROUP BY project_name, total_cost, company_name\n" + "ORDER BY company_name"; MapSqlParameterSource params = new MapSqlParameterSource() .addValue("totalCostBoundary", totalCostBoundary); RowMapper<ProjectsWithCostsGreaterThanOutput> mapper = (rs, rowNum) -> { ProjectsWithCostsGreaterThanOutput row = new ProjectsWithCostsGreaterThanOutput(); row.setProjectName(rs.getString("project_name")); row.setTotalCost(rs.getBigDecimal("total_cost")); row.setCompanyName(rs.getString("company_name")); row.setCompanyCost(rs.getBigDecimal("company_cost")); return row; }; return jdbcTemplate.query(query, params, mapper); } @Override public Employee findEmployee(Integer pid) { String query; query = "SELECT pid, email, name, salary, surname, department_pid AS departmentPid FROM employee WHERE pid = :pid"; MapSqlParameterSource params = new MapSqlParameterSource() .addValue("pid", pid); // using BeanPropertyRowMapper is easier, but with much worse performance than custom RowMapper return jdbcTemplate.queryForObject(query, params, BeanPropertyRowMapper.newInstance(Employee.class)); } @Override public RegisterEmployeeOutput callRegisterEmployee(String name, String surname, String email, BigDecimal salary, String departmentName, String companyName) { String query; //noinspection SqlResolve query = "SELECT employee_id, department_id, company_id FROM register_employee(\n" + " _name := :name, \n" + " _surname := :surname, \n" + " _email := :email, \n" + " _salary := :salary, \n" + " _department_name := :departmentName, \n" + " _company_name := :companyName\n" + ")"; MapSqlParameterSource params = new MapSqlParameterSource() .addValue("name", name) .addValue("surname", surname) .addValue("email", email) .addValue("salary", salary) .addValue("departmentName", departmentName) .addValue("companyName", companyName); RowMapper<RegisterEmployeeOutput> mapper = (rs, rowNum) -> { RegisterEmployeeOutput row = new RegisterEmployeeOutput(); row.setEmployeePid(rs.getInt("employee_id")); row.setDepartmentPid(rs.getInt("department_id")); row.setCompanyPid(rs.getInt("company_id")); return row; }; return jdbcTemplate.queryForObject(query, params, mapper); } @Override public Integer getProjectsCount() { String query = "SELECT count(*) FROM project"; return jdbcTemplate.getJdbcOperations().queryForObject(query, Integer.class); } @Override public List<Department> findDepartmentsOfCompany(Company company) { String query = "SELECT pid, company_pid, name" + " FROM department " + " WHERE company_pid = :pid" + " ORDER BY pid"; MapSqlParameterSource params = new MapSqlParameterSource() .addValue("pid", company.getPid()); return jdbcTemplate.query(query, params, BeanPropertyRowMapper.newInstance(Department.class)); } @Override public void deleteDepartments(List<Department> departmentsToDelete) { List<Integer> ids = departmentsToDelete.stream() .map(Department::getPid) .collect(Collectors.toList()); MapSqlParameterSource params = new MapSqlParameterSource() .addValue("pids", ids); String updateStatement = "DELETE FROM department WHERE pid IN (:pids)"; jdbcTemplate.update(updateStatement, params); } @Override public void updateDepartments(List<Department> departmentsToUpdate) { //language=PostgreSQL String updateStatement = "UPDATE department SET " + "company_pid = :company_pid, " + "name = :name " + "WHERE pid = :pid"; batchUpdateDepartments(departmentsToUpdate, updateStatement); } @Override public void insertDepartments(List<Department> departmentsToInsert) { //language=PostgreSQL String insertStatement = " INSERT INTO department (company_pid, name) " + " VALUES (:company_pid, :name)"; batchUpdateDepartments(departmentsToInsert, insertStatement); } @Override public Project findProject(Integer pid) { String query; query = "SELECT pid, name, datestarted AS date" + " FROM project " + " WHERE pid = :pid"; MapSqlParameterSource params = new MapSqlParameterSource() .addValue("pid", pid); // using BeanPropertyRowMapper is easier, but with much worse performance than custom RowMapper return jdbcTemplate.queryForObject(query, params, BeanPropertyRowMapper.newInstance(Project.class)); } private void batchUpdateDepartments(List<Department> departmentsToInsert, String statement) { MapSqlParameterSource[] paramsList = departmentsToInsert .stream() .map(department -> new MapSqlParameterSource() .addValue("pid", department.getPid()) .addValue("company_pid", department.getCompanyPid()) .addValue("name", department.getName()) ) .toArray(MapSqlParameterSource[]::new); jdbcTemplate.batchUpdate(statement, paramsList); } }
package water.api; import hex.DGLM.CaseMode; import hex.DGLM.Family; import hex.DGLM.GLMModel; import hex.DGLM.Link; import hex.KMeans.KMeansModel; import hex.rf.Confusion; import hex.rf.RFModel; import java.io.File; import java.util.*; import water.*; import water.ValueArray.Column; import water.util.*; import com.google.common.base.Objects; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import com.google.gson.JsonObject; /** All arguments related classes are defined in this guy. * * Argument is the base class for all arguments, which then branches to * different still abstract subclasses that specify how are any given HTML input * elements being drawn. * * From these a proper Arguments that define particular value types are then * subclassed. * * When an argument is created, its pointer is stored in the _arguments array * list so that the request knows how many arguments and in which order it has. * * Because request objects and therefore also argument objects one per * application, while the codepath can be multithreaded (server decides this), * the argument state is not preserved in the argument itself, but in the * Record static object that is kept thread local and must be properly * initialized at each iteration by calling reset() method on the argument. * * See the respective classes for more details. * * NOTE add more arguments to this class as they are needed and keep them here. * * @author peta */ public class RequestArguments extends RequestStatics { // Helper functions /** Returns a json object containing all arguments specified to the page. * * Useful for redirects and polling. */ protected JsonObject argumentsToJson() { JsonObject result = new JsonObject(); for (Argument a : _arguments) { if (a.specified()) result.addProperty(a._name,a.originalValue()); } return result; } protected static int vaColumnNameToIndex(ValueArray va, String input) { // first check if we have string match for (int i = 0; i < va._cols.length; ++i) { String colName = va._cols[i]._name; if (colName == null) colName = String.valueOf(i); if (colName.equals(input)) return i; } try { int i = Integer.parseInt(input); if ((i<0) || (i>=va._cols.length)) return -1; return i; } catch (NumberFormatException e) { return -1; } } /** Compute union of categories in model column and data column. * The result is ordered and the values are unique. */ protected static String[] vaCategoryNames(ValueArray.Column modelCol, ValueArray.Column dataCol, int maxClasses) throws IllegalArgumentException { String[] result = Confusion.domain(modelCol, dataCol); if (result.length > maxClasses) throw new IllegalArgumentException("The column has more than "+maxClasses+" values. Are you sure you have that many classes?"); return result; } protected static String[] vaCategoryNames(ValueArray.Column col, int maxClasses) throws IllegalArgumentException { String[] domain = col._domain; if ((domain == null) || (domain.length == 0)) { int min = (int) col._min; if (col._min!= min) throw new IllegalArgumentException("Only integer or enum columns can be classes!"); int max = (int) col._max; if (col._max != max) throw new IllegalArgumentException("Only integer or enum columns can be classes!"); if (max - min > maxClasses) // arbitrary number throw new IllegalArgumentException("The column has more than "+maxClasses+" values. Are you sure you have that many classes?"); String[] result = new String[max-min+1]; for (int i = 0; i <= max - min; ++i) result[i] = String.valueOf(min+i); return result; } else { return domain; } } // Record /** List of arguments for the request. Automatically filled in by the argument * constructors. */ protected final ArrayList<Argument> _arguments = new ArrayList(); /** Argument state record. * * Contains all state required for the argument and a few functions to operate * on the state. */ protected static class Record<T> { /** Determines the original input value of the argument. null if the value * was not supplied, or was empty. Retains the original value even if the * argument value is wrong. */ public String _originalValue = null; /** Parsed value. If the parse was successful, or default value if the * checking failed, or the argument is not required and was missing. Note * that default value may very well be null and thus you cannot check this * for null of determine validity. */ public T _value = null; /** Reason why the argument is disabled, or null if it is enabled. A * disabled argument cannot be edited by the user yet. */ public String _disabledReason = null; /** True if the argument's value stored in _value is valid, that is either * correctly parsed, or not present and default value used. Note that if * checking fails, the defaultValue is stored in _value, but _valid is * false. */ public boolean _valid = false; /** Returns true if the argument is disabled. */ public boolean disabled() { return _disabledReason != null; } /** Returns true if the argument is valid. */ public boolean valid() { return _valid; } /** Returns if the argument is specified by user. returns true only if it is * valid and parsing the argument was successful. * @return */ public boolean specified() { return valid() && _originalValue != null; } } // A string used to display the query element part of the argument protected static final String _queryHtml = "\n<dl class='dl-horizontal'>" + "<dt style='padding-top:3px'><span rel='tooltip' title='%TOOLTIP_DESCRIPTION' data-placement='left'>%ASTERISK %NAME</span></dt>" + "<dd>%ELEMENT %COMMENT</dd>" + "</dl>" ; // Argument public abstract class Argument<T> { /** As with request's _requestHelp, this provides the extended help that * will be displayed on the help and wiki pages. Specify this in the * particular request constructor. */ public String _requestHelp; /** True if the argument should not appear in the automatically generated * query. */ public boolean _hideInQuery = false; /** * True if the argument should be only read-only. */ public boolean _readOnly = false; /** Override this method to provide parsing of the input string to the Java * expected value. The input is guaranteed to be non-empty when this method * is called and all prerequisities are guaranteed to be valid before this * method is called. */ protected abstract T parse(String input) throws IllegalArgumentException; /** Returns the default value of the argument. Note that the method will be * called also on required arguments, in which case it is ok return null. * * It is kept abstract because defining a proper default value might be * tricky and in many case you do not want it to be null. Overriding it * always makes you think:) */ protected abstract T defaultValue(); /** Returns the javascript code that will be executed when the query is * loaded that associates the given callback JS function with the on change * event of the input. This method is only called if the element should * refresh the webpage upon its change. */ protected abstract String jsRefresh(String callbackName); /** Returns the javascript code that will be executed when the value of * the argument is to be determined. It must contain a return statement, * that returns the string that should be sent back to the request for the * given arhument. */ protected abstract String jsValue(); /** If there is any additional javascript that should be dumped to the * query page, it should be defined here. Please follow chaining rules. */ protected String jsAddons() { return ""; } /** Returns the HTML elements of the argument query only. This should return * the elements in HTML that will be used to enter the value. For instance * the input text, selection, etc. */ protected abstract String queryElement(); /* A little bonus extra text out to the right */ protected String queryComment() { return ""; } /** Returns the query description. This is a concise description of a * correct value for the argument. generally used as a placeholder in the * html query elements. */ protected abstract String queryDescription(); /** Any query addons can be specified here. These will be displayed with * the query html code and should be used for instance for default value * calculators, etc. */ protected String queryAddons() { return ""; } /** Returns the html query for the given argument, including the full * formatting. That means not only the queryElement, but also the argument * name in front of it, etc. * * You may want to override this if you wont different form layouts to be * present. */ protected String query() { RString result = new RString(_queryHtml); result.replace("ID",_name); result.replace("NAME", JSON2HTML(_name)); if (disabled()) result.replace("ELEMENT","<div class='alert alert-info' style='padding-top:4px;padding-bottom:4px;margin-bottom:5px'>"+record()._disabledReason+"</div>"); else result.replace("ELEMENT",queryElement()); result.replace("TOOLTIP_DESCRIPTION", queryDescription()); result.replace("COMMENT",queryComment()); if (_required) result.replace("ASTERISK","<span style='color:#ff0000'>* </span>"); return result.toString(); } /** Creates the request help page part for the given argument. Displays its * JSON name, query name (the one in HTML), value type and the request help * provided by the argument. */ public final JsonObject requestHelp() { JsonObject r = new JsonObject(); r.addProperty(NAME, _name); r.addProperty(DESCRIPTION, queryDescription()); r.addProperty(HELP, _requestHelp); return r; } /** Name of the argument. This must correspond to the name of the JSON * request argument. */ public final String _name; /** True if the argument is required, false if it may be skipped. */ public final boolean _required; /** True if change of the value in the query controls should trigger an * automatic refresh of the query form. * * This is set by the setrefreshOnChange() method. It is automatically set * for any controls that are prerequisites for other controls and can be * manually select for other controls by users (do it in the request * constructor). */ private boolean _refreshOnChange; /** List of all prerequisite arguments for the current argument. All the * prerequisite arguments must be created before the current argument. */ public ArrayList<Argument<T>> _prerequisites = null; /** The thread local argument state record. Must be initialized at the * beginning of each request before it can be used. */ private ThreadLocal<Record> _argumentRecord = new ThreadLocal(); /** Creates the argument of given name. Also specifies whether the argument * is required or not. This cannot be changed later. */ protected Argument(String name, boolean required) { assert Check.paramName(name); _name = name; _required = required; _refreshOnChange = false; _arguments.add(this); } /** Adds the given argument as a prerequisite. This means that current * argument will not be checked and/or reported in queries as a control form * unless all its prerequisite arguments are in a valid state. (the argument * will be disabled if not all its prerequisites are satisfied). */ protected final void addPrerequisite(Argument arg) { if (_prerequisites == null) _prerequisites = new ArrayList(); _prerequisites.add(arg); arg.setRefreshOnChange(); } /** Returns the thread local argument state record. */ protected final Record<T> record() { return _argumentRecord.get(); } /** Disables the argument with given reason. If the argument is already * disabled, its reason is overwritten by the new one. * * NOTE disable(null) effectively enables the argument, that is why the * assert! */ public final void disable(String reason) { assert (reason != null); record()._disabledReason = reason; } /** Disables the argument and makes its input value empty. This is the * preferred way of disabling arguments. */ public final void disable(String reason, Properties args) { assert (reason != null); disable(reason); args.remove(_name); } /** Returns whether the argument is disabled or not. */ public final boolean disabled() { return record().disabled(); } /** Makes the argument refresh the query page on its change automatically. * If you want this behavior to be disabled for the argument, overwrite this * method to error. */ protected void setRefreshOnChange() { _refreshOnChange = true; } /** Returns true if the argument refreshes the query automatically on its * change. */ public boolean refreshOnChange() { return _refreshOnChange; } /** Returns true if the argument is valid. Valid means specified by user * and parsed properly, or not required and not specified. */ public final boolean valid() { return record().valid(); } /** Returns true if the argument is specified by the user. That is if the * argument value was submitted by the user and parsed correctly. */ public final boolean specified() { return record().specified(); } /** Returns the value of the argument. This is either the value parsed, if * specified, or defaultValue. Note that default value is returned also for * invalid arguments. */ public final T value() { return record()._value; } /** Returns the input value submitted by the user, if specified. */ public final String originalValue() { return record()._originalValue; } /** Resets the argument by creating it a new thread local state. Everything * is null and the argument is not valid. */ public final void reset() { _argumentRecord.set(new Record()); } /** Checks that the argument supplied is correct. This method is called for * each argument and is given the HTTP supplied argument value. If the value * was not supplied, input contains an empty string. * * The argument must already be reseted before calling this method. * * If the argument is disabled, the function does not do anything except * setting the original value in the record. * * If the prerequisites of the argument are not all valid, then the argument * is disabled and function returns. * * Then the argument is parsed if provided, or an error thrown if the input * is empty and the argument is required. * * At the end of the function the value is either the result of a successful * parse() call or a defaultValue or null if the argument is disabled. * However if the argument is disabled a defaultValue should not be called. */ public void check(String input) throws IllegalArgumentException { // get the record -- we assume we have been reset properly Record record = record(); // check that the input is canonical == value or null and store it to the // record if (input.isEmpty()) input = null; record._originalValue = input; // there is not much to do if we are disabled if (record.disabled()) { record._value = null; return; } // check that we have all prerequisites properly initialized if (_prerequisites != null) { for (Argument dep : _prerequisites) if (!dep.valid()) { record._disabledReason = "Not all prerequisite arguments have been supplied: "+dep._name; record._value = null; return; } } // if input is null, throw if required, otherwise use the default value if (input == null) { if (_required) throw new IllegalArgumentException("Argument "+_name+" is required, but not specified"); record._value = defaultValue(); record._valid = true; // parse the argument, if parse throws we will still be invalid correctly } else { try { record._value = parse(input); record._valid = true; } catch (IllegalArgumentException e) { record._value = defaultValue(); Throwables.propagate(e); } } } } // InputText /** Argument that uses simple text input to define its value. * * This is the simplest argument. Uses the classic input element. All * functionality is supported. * * @param <T> */ public abstract class InputText<T> extends Argument<T> { public InputText(String name, boolean required) { super(name, required); } /** A query element is the default HTML form input. * * The id of the element is the name of the argument. Placeholder is the * query description and the value is filled in either as the value * submitted, or as the toString() method on defaultValue. */ @Override protected String queryElement() { // first determine the value to put in the field Record record = record(); String value = record._originalValue; // if no original value was supplied, try the one provided by the // default value if (value == null) { T v = defaultValue(); value = (v == null) ? "" : v.toString(); } return "<input" + (_readOnly ? " disabled" : "")+ " class='span5' type='text' name='"+_name+"' id='"+_name+"' placeholder='"+queryDescription()+"' "+ (!value.isEmpty() ? (" value='"+value+"' />") : "/>"); } /** JS refresh is a default jQuery hook to the change() method. */ @Override protected String jsRefresh(String callbackName) { return "$('#"+_name+"').change('"+_name+"',"+callbackName+");"; } /** JS value is the simple jQuery val() method. */ @Override protected String jsValue() { return "return $('#"+_name+"').val();"; } } // TypeaheadInputText /** Typeahead enabled text input. * * Typeahead is enabled using the jQuery typeahead plugin. You must specify * the JSON request which provides the typeahead, and the data name in the * response that contains the array of strings corresponding to the typeahead * options. Optionally you can specify the typeahead limit (how many options * will be displayed), which is 1024 by default. * * The typeahead json request must take Str argument filter and Int optional * argument limit. */ public abstract class TypeaheadInputText<T> extends InputText<T> { /** href of the json request supplying the typeahead values. */ protected final String _typeaheadHref; /** Typeahead limit. If more than this limit options will be available, the * typeahead will be disabled. */ protected final int _typeaheadLimit; /** Creates the typeahead. */ protected TypeaheadInputText(Class<? extends TypeaheadRequest> href, String name, boolean required) { super(name, required); _typeaheadHref = href.getSimpleName(); _typeaheadLimit = 1024; } /** Adds the json to hook initialize the typeahead functionality. It is * jQuery typeahead plugin standard initialization with async filler. */ @Override protected String jsAddons() { RString s = new RString("" + "$('#%ID').typeahead({\n" + " source:\n" + " function(query,process) {\n" + " return $.get('%HREF', { filter: query, limit: %LIMIT }, function (data) {\n" + " return process(data.%DATA_NAME);\n" + " });\n" + " },\n" + "});\n" + "\n"); s.replace("ID", _name); s.replace("HREF", _typeaheadHref); s.replace("LIMIT", _typeaheadLimit); s.replace("DATA_NAME", ITEMS); return super.jsAddons()+s.toString(); } } // InputCheckBox /** A boolean argument that is represented as the checkbox. * * The only allowed values for a boolean checkbox are "0" for false, "1" for * true. If the argument is not required, then default value will be used. * * Please note that due to the nature of a checkbox, the html query will * always specify this argument to its default value, or to false if the user * did not specify it explicitly. */ public abstract class InputCheckBox extends Argument<Boolean> { /** Default value. */ public final Boolean _defaultValue; /** Creates the argument with specified default value. */ public InputCheckBox(String name, boolean defaultValue) { super(name, false); // checkbox is never required _defaultValue = defaultValue; } /** Creates the argument as required one. This has only effect on JSON, for * HTML it means the default value is false effectively. */ public InputCheckBox(String name) { super(name, true); _defaultValue = null; } /** Parses the value. 1 to true and 0 to false. Anything else is an error. */ @Override public Boolean parse(String input) { if (input.equals("1")) return true; if (input.equals("0")) return false; if (input.equals("true")) return true; if (input.equals("false")) return false; throw new IllegalArgumentException(input+" is not valid boolean value. Only 1 and 0 are allowed."); } /** Displays the query element. This is just the checkbox followed by the * description. */ @Override protected String queryElement() { // first determine the value to put in the field Record record = record(); String value = record._originalValue; // if no original value was supplied, use the provided one if (value == null) { Boolean v = defaultValue(); value = ((v == null) || (v == false)) ? "" : "1" ; } return "<input value='1' class='span5' type='checkbox' name='"+_name+"' id='"+_name+"' "+ (value.equals("1") ? (" checked />") : "/>")+"&nbsp;&nbsp;"+queryDescription(); } /** Refresh only taps to jQuery change event. */ @Override protected String jsRefresh(String callbackName) { return "$('#"+_name+"').change('"+_name+"',"+callbackName+");"; } /** Returns 1 if the checkbox is checked and 0 otherwise. */ @Override protected String jsValue() { return "return $('#"+_name+"').is(':checked') ? '1' : '0';"; } /** Returns the default value. */ @Override protected Boolean defaultValue() { return _defaultValue; } } // InputSelect /** Select element from the list of options. * * Array of values and arrays of names can be specified together with the * selected element's value. */ public abstract class InputSelect<T> extends Argument<T> { /** Override this method to provide the values for the options. These will * be the possible values returned by the form's input and should be the * possible values for the JSON argument. */ protected abstract String[] selectValues(); /** Returns which value should be selected. This is *not* the default value * itself, as the default values may be of any type, but the input value * that should be selected in the browser. */ protected abstract String selectedItemValue(); /** Override this method to determine the value names, that is the names * displayed in the browser. Return null, if the value strings should be * used (this is default behavior). */ protected String[] selectNames() { return null; } /** Constructor just calls super. */ public InputSelect(String name, boolean required) { super(name, required); } /** Displays the query element. It is a select tag with option tags inside. * If the argument is required then additional empty value is added with * name "Please select..." that ensures that the user selects actual value. */ @Override protected String queryElement() { StringBuilder sb = new StringBuilder(); sb.append("<select id='"+_name+"' name='"+_name+"'>"); String selected = selectedItemValue(); String[] values = selectValues(); String[] names = selectNames(); if (names == null) names = values; assert (values.length == names.length); if (_required) sb.append("<option value=''>Please select...</option>"); for (int i = 0 ; i < values.length; ++i) { if (values[i].equals(selected)) sb.append("<option value='"+values[i]+"' selected>"+names[i]+"</option>"); else sb.append("<option value='"+values[i]+"'>"+names[i]+"</option>"); } sb.append("</select>"); return sb.toString(); } /** Refresh is supported using standard jQuery change event. */ @Override protected String jsRefresh(String callbackName) { return "$('#"+_name+"').change('"+_name+"',"+callbackName+");"; } /** Get value is supported by the standard val() jQuery function. */ @Override protected String jsValue() { return "return $('#"+_name+"').val();"; } } // MultipleCheckbox /** Displays multiple checkboxes for different values. Returns a list of the * checked values separated by commas. */ public abstract class MultipleSelect<T> extends Argument<T> { /** Override this method to provide the values for the options. These will * be the possible values returned by the form's input and should be the * possible values for the JSON argument. */ protected abstract String[] selectValues(); /** Returns true if the given option (by its value) is selected. False * otherwise. */ protected abstract boolean isSelected(String value); /** Override this method to determine the value names, that is the names * displayed in the browser. Return null, if the value strings should be * used (this is default behavior). */ protected String[] selectNames() { return null; } /** Constructor just calls super. Is never required, translates to the * default value. */ public MultipleSelect(String name) { super(name, false); } /** Displays the query element. It is a tabled list of all possibilities * with an optional scrollbar on the right. */ @Override protected String queryElement() { String[] values = selectValues(); String[] names = selectNames(); if (names == null) names = values; assert (values.length == names.length); if (values.length == 0) return "<div class='alert alert-error'>No editable controls under current setup</div>"; StringBuilder sb = new StringBuilder(); sb.append("<select multiple"); sb.append(" size='").append(Math.min(10, values.length)).append("'"); sb.append(" id='").append(_name).append("' >"); for (int i = 0 ; i < values.length; ++i) { sb.append("<option value='").append(values[i]).append("' "); if( isSelected(values[i]) ) sb.append("selected='true' "); sb.append(">").append(names[i]).append("</option>"); } sb.append("</select>"); return sb.toString(); } /** Refresh is supported using standard jQuery change event. Each * possibility's checkbox is instrumented. */ @Override protected String jsRefresh(String callbackName) { return "$('#"+_name+"').change('"+_name+"',"+callbackName+");"; } /** Get value is supported by a JS function that enumerates over the * possibilities. If checked, the value of the possibility is appended to * a comma separated list. */ @Override protected String jsValue() { return "var tmp = $('#"+_name+"').val(); return tmp == null ? \"\" : tmp.join(',');"; } } // MultipleText private static final String _multipleTextValueJS = " var str = ''\n" + " for (var i = 0; i < %NUMITEMS; ++i) {\n" + " var element = $('#%NAME'+i);\n" + " if (element.val() != '') {\n" + " if (str == '')\n" + " str = element.attr('name') + '=' +element.val();\n" + " else\n" + " str = str + ',' + element.attr('name') + '=' + element.val();\n" + " }\n" + " }\n" + " return str;\n" ; public abstract class MultipleText<T> extends Argument<T> { protected abstract String[] textValues(); protected abstract String[] textNames(); protected String[] textPrefixes() { return null; } protected String[] textSuffixes() { return null; } protected String textSuffix() { return null; } public MultipleText(String name, boolean required) { super(name, required); } /** Displays the query element. It is a tabled list of all possibilities * with an optional scrollbar on the right. */ @Override protected String queryElement() { StringBuilder sb = new StringBuilder(); sb.append("<div style='max-height:300px;overflow:auto'>"); String[] prefixes = textPrefixes(); String[] values = textValues(); String[] names = textNames(); String[] suffixes = textSuffixes(); if (prefixes == null) prefixes = names; if (suffixes == null && textSuffix() != null) { suffixes = new String[names.length]; String suffix = textSuffix(); for(int i = 0; i<names.length; i++) suffixes[i] = suffix; } if (values == null) { values = new String[prefixes.length]; for (int i = 0; i < values.length; ++i) values[i] = ""; } assert (prefixes.length == values.length); if (values.length == 0) sb.append("<div class='alert alert-error'>No editable controls under current setup</div>"); for (int i = 0 ; i < values.length; ++i) { sb.append("<div class='input-prepend" + (suffixes!=null?" input-append":"") + "'>"); sb.append("<span class='add-on'>" + prefixes[i]+"</span>"); sb.append("<input class='span3' name='"+names[i]+"' id='"+_name+String.valueOf(i)+"' type='text' value='"+values[i]+"' placeholder='"+queryDescription()+"'>"); if (suffixes!=null) sb.append("<span class='add-on'>" + suffixes[i]+"</span>"); sb.append("</div>"); } sb.append("</div>"); return sb.toString(); } /** Refresh is supported using standard jQuery change event. Each text * input is instrumented. */ @Override protected String jsRefresh(String callbackName) { int size = textNames().length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < size; ++i) sb.append("$('#"+_name+String.valueOf(i)+"').change('"+_name+"',"+callbackName+");\n"); return sb.toString(); } /** Get value is supported by a JS function that enumerates over the * possibilities. If checked, the value of the possibility is appended to * a comma separated list. */ @Override protected String jsValue() { int size = textNames().length; RString result = new RString(_multipleTextValueJS); result.replace("NUMITEMS",size); result.replace("NAME",_name); return result.toString(); } } // UserDefinedArguments // Place your used defined arguments here. // Str /** A string value. * * Any string can be a proper value. If required, empty string is not allowed. */ public class Str extends InputText<String> { public final String _defaultValue; public Str(String name) { super(name,true); _defaultValue = null; } public Str(String name, String defaultValue) { super(name, false); _defaultValue = defaultValue; } @Override protected String parse(String input) throws IllegalArgumentException { return input; } @Override protected String defaultValue() { return _defaultValue; } @Override protected String queryDescription() { return _required ? "Any non-empty string" : "Any string"; } } public static class NumberSequence { public final double [] _arr; final String _str; public NumberSequence(double [] val, String str){ _arr = val; _str = str; } public NumberSequence(String str, boolean mul, double defaultStep){ this(parseArray(str,mul,defaultStep),str); } private static double [] parseArray(String input, boolean mul, double defaultStep){ String str = input.trim().toLowerCase(); if( str.startsWith("seq") ) { throw new RuntimeException("unimplemented"); } if( str.contains(":") ) { String [] parts = str.split(":"); if(parts.length != 2 && parts.length != 3 )throw new IllegalArgumentException("Value "+input+" is not a valid number sequence."); double step = defaultStep; if( parts.length == 3 ){ step = Double.parseDouble(parts[2]); } double from = Double.parseDouble(parts[0]); double to = Double.parseDouble(parts[1]); if(to == from) return new double[]{from}; if(to < from)throw new IllegalArgumentException("Value "+input+" is not a valid number sequence."); if(step == 0)throw new IllegalArgumentException("Value "+input+" is not a valid number sequence."); int n = mul ? (int)((Math.log(to) - Math.log(from))/Math.log(step)) : (int)(( to - from )/ step ); double [] res = new double[n]; for( int i = 0; i < n; ++i ) { res[i] = from; if( mul) from *= step; else from += step; } return res; } else if( str.contains(",") ) { String [] parts = str.split(","); double [] res = new double[parts.length]; for(int i = 0; i < parts.length; ++i) res[i] = Double.parseDouble(parts[i]); return res; } else { return new double [] {Double.parseDouble(str)}; } } static NumberSequence parse(String input, boolean mul, double defaultStep){ return new NumberSequence(parseArray(input, mul, defaultStep),null); } public String toString(){ if(_str != null)return _str; if(_arr == null || _arr.length == 0)return""; StringBuilder res = new StringBuilder(); res.append(_arr[0]); for(int i = 1; i < _arr.length; ++i) res.append("," + _arr[i]); return res.toString(); } } public class RSeq extends InputText<NumberSequence> { boolean _multiplicative; NumberSequence _dVal; double _defaultStep; @Override public String queryComment(){ return disabled()?"":"Comma separated list of values. Or range specified as from:to:step" + (_multiplicative?"(*).":"(+)."); } public RSeq(String name, boolean req, boolean mul){ this(name,req,null,mul); } public RSeq(String name, boolean req, NumberSequence dVal, boolean mul){ super(name,req); _dVal = dVal; _multiplicative = mul; _defaultStep = mul?10:1; } @Override protected NumberSequence parse(String input) throws IllegalArgumentException { try { return NumberSequence.parse(input, _multiplicative, _defaultStep); } catch (NumberFormatException e) { throw new IllegalArgumentException("Value "+input+" is not a valid number sequence."); } } @Override protected NumberSequence defaultValue() { return _dVal; } @Override protected String queryDescription() { return "Number sequence. Comma separated list of values. Or range specified as from:to:step."; } } // Int public class Int extends InputText<Integer> { public final Integer _defaultValue; public final int _min; public final int _max; public Int(String name) { this(name, Integer.MIN_VALUE, Integer.MAX_VALUE); } public Int(String name, int min, int max) { super(name,true); _defaultValue = null; _min = min; _max = max; } public Int(String name, Integer defaultValue) { this(name, defaultValue, Integer.MIN_VALUE, Integer.MAX_VALUE); } public Int(String name, Integer defaultValue, int min, int max) { super(name,false); _defaultValue = defaultValue; _min = min; _max = max; } @Override protected Integer parse(String input) throws IllegalArgumentException { try { int i = Integer.parseInt(input); if ((i< _min) || (i > _max)) throw new IllegalArgumentException("Value "+i+" is not between "+_min+" and "+_max+" (inclusive)"); return i; } catch (NumberFormatException e) { throw new IllegalArgumentException("Value "+input+" is not a valid integer."); } } @Override protected Integer defaultValue() { return _defaultValue; } @Override protected String queryDescription() { return ((_min == Integer.MIN_VALUE) && (_max == Integer.MAX_VALUE)) ? "Integer value" : "Integer from "+_min+" to "+_max; } } // LongInt public class LongInt extends InputText<Long> { public final Long _defaultValue; public final long _min; public final long _max; public final String _comment; public LongInt(String name) { this(name, Long.MIN_VALUE, Long.MAX_VALUE); } public LongInt(String name, long min, long max) { super(name,true); _defaultValue = null; _min = min; _max = max; _comment = ""; } public LongInt(String name, Long defaultValue, String comment) { this(name, defaultValue, Long.MIN_VALUE, Long.MAX_VALUE, comment); } public LongInt(String name, Long defaultValue, long min, long max, String comment) { super(name,false); _defaultValue = defaultValue; _min = min; _max = max; _comment = comment; } @Override protected Long parse(String input) throws IllegalArgumentException { try { long i = Long.parseLong(input); if ((i< _min) || (i > _max)) throw new IllegalArgumentException("Value "+i+" is not between "+_min+" and "+_max+" (inclusive)"); return i; } catch (NumberFormatException e) { throw new IllegalArgumentException("Value "+input+" is not a valid long integer."); } } @Override protected Long defaultValue() { return _defaultValue; } @Override protected String queryComment() { return _comment; } @Override protected String queryDescription() { return ((_min == Long.MIN_VALUE) && (_max == Long.MAX_VALUE)) ? "Integer value" : "Integer from "+_min+" to "+_max; } } // Real public class Real extends InputText<Double> { public final Double _defaultValue; public double _min; public double _max; public final String _comment; public Real(String name) { this(name, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); } public Real(String name, double min, double max) { super(name,true); _defaultValue = null; _min = min; _max = max; _comment = ""; } public Real(String name, Double defaultValue) { this(name, defaultValue, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, ""); } public Real(String name, Double defaultValue, String comment) { this(name, defaultValue, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, comment); } public Real(String name, Double defaultValue, double min, double max, String comment) { super(name,false); _defaultValue = defaultValue; _min = min; _max = max; _comment = comment; } @Override protected Double parse(String input) throws IllegalArgumentException { try { double i = Double.parseDouble(input); if ((i< _min) || (i > _max)) throw new IllegalArgumentException("Value "+i+" is not between "+_min+" and "+_max+" (inclusive)"); return i; } catch (NumberFormatException e) { throw new IllegalArgumentException("Value "+input+" is not a valid real number."); } } @Override protected Double defaultValue() { return _defaultValue; } @Override protected String queryComment() { return _comment; } @Override protected String queryDescription() { return ((_min == Double.NEGATIVE_INFINITY) && (_max == Double.POSITIVE_INFINITY)) ? "Real value" : "Real from "+_min+" to "+_max; } } public class CaseModeSelect extends EnumArgument<CaseMode> { public CaseModeSelect(H2OHexKey key,H2OHexKeyCol classCol, EnumArgument<Family> family, String name, CaseMode defaultValue) { super(name, defaultValue); addPrerequisite(_key = key); addPrerequisite(_classCol = classCol); addPrerequisite(_family = family); setRefreshOnChange(); } public final H2OHexKey _key; public final H2OHexKeyCol _classCol; public final EnumArgument<Family> _family; @Override public String[] selectValues(){ if(_key.value() == null || _classCol.value() == null || _key.value()._cols[_classCol.value()]._domain == null) return super.selectValues(); return new String[]{CaseMode.eq.toString(), CaseMode.neq.toString()}; } // HTML note: defaultValue has to match one of value provided by selectValues. // In other case, UI will show that a first value is selected, but this code will not // receive any notification about selected value and user will need to // select value explicitely again!!! @Override public CaseMode defaultValue() { if(_family.value() == Family.binomial){ Column c = _key.value()._cols[_classCol.value()]; if (c._domain!=null ) return CaseMode.eq; if (c._min < 0 || c._max > 1) return CaseMode.gt; } return CaseMode.none; } } class LinkArg extends EnumArgument<Link> { final EnumArgument<Family> _f; public LinkArg(EnumArgument<Family> f ,String name) { super(name,f.defaultValue().defaultLink); addPrerequisite(_f = f); } @Override protected Link defaultValue() { return _f.value().defaultLink; } } // Binomial GLM 'case' selection. Only useful for binomial GLM where the // response column is NOT 0/1 - names a value to be treated as 1 and all // other values are treated as zero. public class CaseSelect extends Real { public final H2OHexKey _key; public final H2OHexKeyCol _classCol; public final CaseModeSelect _caseMode; public CaseSelect(H2OHexKey key, H2OHexKeyCol classCol, CaseModeSelect mode, String name) { super(name); addPrerequisite(_key= key); addPrerequisite(_classCol=classCol); addPrerequisite(_caseMode = mode); } @Override protected Double defaultValue() { if(_caseMode.value() == CaseMode.none)return Double.NaN; Column c = _key.value()._cols[_classCol.value()]; return (_caseMode.value() == CaseMode.eq || Double.isNaN(c._mean))?c._max:c._mean; } @Override protected Double parse(String input) throws IllegalArgumentException { // Set min & max at the last second, after key/column selection has been // cleared up ValueArray.Column C = _key.value()._cols[_classCol.value()]; _min = C._min; _max = C._max; double x = super.parse(input); // Then the normal parsing step if( Double.isNaN(x) && (C._scale!=1 || _min != 0 || _max != 1) ) throw new IllegalArgumentException("Class column is not boolean, 'case' needs to specify what value to treat as TRUE; valid values range from "+_min+" to "+_max); return x; } @Override protected String queryDescription() { return "Value from the " + _classCol._name + " column."; } } // Bool public class Bool extends InputCheckBox { public final String _description; public Bool(String name, boolean defaultValue, String description) { super(name, defaultValue); _description = description; } @Override protected String queryDescription() { return _description; } } // EnumClass public class EnumArgument<T extends Enum<T>> extends InputSelect<T> { protected final Class<T> _enumClass; private final T _defaultValue; public EnumArgument(String name, T defaultValue, boolean refreshOnChange) { this(name,defaultValue); if(refreshOnChange)setRefreshOnChange(); } public EnumArgument(String name, T defaultValue) { super(name, false); _defaultValue = defaultValue; _enumClass = (Class<T>) defaultValue.getClass(); } public EnumArgument(String name, Class enumClass) { super(name, true); _defaultValue = null; _enumClass = enumClass; } @Override protected String[] selectValues() { T[] _enums = _enumClass.getEnumConstants(); String[] result = new String[_enums.length]; for (int i = 0; i < _enums.length; ++i) result[i] = _enums[i].toString(); return result; } @Override protected String selectedItemValue() { T v = value(); if (v == null) return ""; return v.toString(); } @Override protected T parse(String input) throws IllegalArgumentException { for (T v : _enumClass.getEnumConstants()) if (v.toString().equals(input)) return v; throw new IllegalArgumentException("Only "+Arrays.toString(selectValues())+" accepted for argument "+_name); } @Override protected T defaultValue() { return _defaultValue; } @Override protected String queryDescription() { return "Any of "+Arrays.toString(selectValues()); } } // ExistingFile public class ExistingFile extends TypeaheadInputText<File> { public ExistingFile(String name) { super(TypeaheadFileRequest.class, name, true); } @Override protected File parse(String input) throws IllegalArgumentException { File f = new File(input); if( !f.exists() ) throw new IllegalArgumentException("File "+input+" not found!"); return f; } @Override protected String queryDescription() { return "Existing file or directory"; } @Override protected File defaultValue() { return null; } } // H2OKey public class H2OKey extends InputText<Key> { public final Key _defaultValue; public H2OKey(String name) { this(name, true); } public H2OKey(String name, boolean required) { super(name, required); _defaultValue = null; } public H2OKey(String name, String keyName) { this(name, Key.make(keyName)); } public H2OKey(String name, Key key) { super(name, false); _defaultValue = key; } @Override protected Key parse(String input) throws IllegalArgumentException { Key k = Key.make(input); return k; } @Override protected Key defaultValue() { return _defaultValue; } @Override protected String queryDescription() { return "Valid H2O key"; } } // H2OExistingKey public class H2OExistingKey extends TypeaheadInputText<Value> { public final Key _defaultValue; public H2OExistingKey(String name) { super(TypeaheadKeysRequest.class, name, true); _defaultValue = null; } public H2OExistingKey(String name, String keyName) { this(name, Key.make(keyName)); } public H2OExistingKey(String name, Key key) { super(TypeaheadKeysRequest.class, name, false); _defaultValue = key; } @Override protected Value parse(String input) throws IllegalArgumentException { Key k = Key.make(input); Value v = DKV.get(k); if (v == null) throw new IllegalArgumentException("Key "+input+" not found!"); return v; } @Override protected Value defaultValue() { if (_defaultValue == null) return null; return DKV.get(_defaultValue); } @Override protected String queryDescription() { return "An existing H2O key"; } } // H2OHexKey public class H2OHexKey extends TypeaheadInputText<ValueArray> { public final Key _defaultKey; public H2OHexKey(String name) { super(TypeaheadHexKeyRequest.class, name, true); _defaultKey = null; } public H2OHexKey(String name, String keyName) { this(name, Key.make(keyName)); } public H2OHexKey(String name, Key key) { super(TypeaheadHexKeyRequest.class, name, false); _defaultKey = key; } @Override protected ValueArray parse(String input) throws IllegalArgumentException { Key k = Key.make(input); Value v = DKV.get(k); if (v == null) throw new IllegalArgumentException("Key "+input+" not found!"); if (!v.isArray()) throw new IllegalArgumentException("Key "+input+" is not a valid HEX key"); return v.get(); } @Override protected ValueArray defaultValue() { if(_defaultKey == null) return null; return DKV.get(_defaultKey).get(); } @Override protected String queryDescription() { return "An existing H2O HEX key"; } } public class H2OModelKey<TM extends Model, TK extends TypeaheadKeysRequest> extends TypeaheadInputText<TM> { public H2OModelKey(TK tkr, String name, boolean req) { super(tkr.getClass(), name, req); } @Override protected TM parse(String input) throws IllegalArgumentException { if( input!=null && input.length()>0 ) { Key k = Key.make(input); Value v = DKV.get(k); if (v != null) return v.get(); } throw new IllegalArgumentException("Key "+input+" not found!"); } @Override protected String queryDescription() { return "An existing H2O Model key"; } @Override protected TM defaultValue() { return null; } } public class H2OGLMModelKey extends H2OModelKey<GLMModel, TypeaheadGLMModelKeyRequest> { public H2OGLMModelKey(String name, boolean req) { super(new TypeaheadGLMModelKeyRequest(),name, req); } } public class RFModelKey extends H2OModelKey<RFModel, TypeaheadRFModelKeyRequest> { public RFModelKey(String name) { super(new TypeaheadRFModelKeyRequest(),name, true); } } public class H2OKMeansModelKey extends H2OModelKey<KMeansModel, TypeaheadKMeansModelKeyRequest> { public H2OKMeansModelKey(String name, boolean req) { super(new TypeaheadKMeansModelKeyRequest(),name, req); } } // StringListArgument // NO EMPTY string in values public class StringList extends InputSelect<String> { public final String[] _values; public final int _defaultIndex; public StringList(String name, String[] values) { super(name, true); _values = values; _defaultIndex = -1; } public StringList(String name, String[] values, int defaultIndex) { super(name, false); _values = values; _defaultIndex = defaultIndex; } @Override protected String[] selectValues() { return _values; } @Override protected String selectedItemValue() { if (_required && (!valid())) return ""; return value(); } @Override protected String parse(String input) throws IllegalArgumentException { for (String s : _values) if (s.equals(input)) return input; throw new IllegalArgumentException("Invalid value "+input+", only "+Arrays.toString(_values)+" allowed"); } @Override protected String defaultValue() { if (_defaultIndex == -1) return null; return _values[_defaultIndex]; } @Override protected String queryDescription() { return "Any of "+Arrays.toString(_values); } } // H2OHexKeyCol public class H2OHexKeyCol extends InputSelect<Integer> { public final int _defaultCol; public final H2OHexKey _key; public H2OHexKeyCol(String name, H2OHexKey key) { super(name, true); _key = key; _defaultCol = 0; addPrerequisite(key); } public H2OHexKeyCol(String name, H2OHexKey key, int defaultCol) { super(name, false); _key = key; _defaultCol = defaultCol; addPrerequisite(key); } @Override protected String[] selectValues() { ValueArray va = _key.value(); String[] result = new String[va._cols.length]; for(int i = 0; i < result.length; ++i) result[i] = va._cols[i]._name == null ? String.valueOf(i) : va._cols[i]._name; return result; } @Override protected String selectedItemValue() { if (value() == null) return ""; if (_key.value() == null) return ""; return String.valueOf(_key.value()._cols[value()]._name); } @Override protected Integer parse(String input) throws IllegalArgumentException { ValueArray va = _key.value(); int colIdx = vaColumnNameToIndex(va, input); if (colIdx == -1) throw new IllegalArgumentException(input+" not a name of column, or a column index"); return colIdx; } @Override protected Integer defaultValue() { if (_defaultCol>=0) return _defaultCol; return _key.value()._cols.length + _defaultCol; } @Override protected String queryDescription() { return "Column name"; } } public class HexKeyClassCol extends H2OHexKeyCol { public HexKeyClassCol(String name, H2OHexKey key ) { super(name, key, -1); } @Override protected Integer parse(String input) throws IllegalArgumentException { Integer i = super.parse(input); // called for error checking vaCategoryNames(_key.value()._cols[i], Integer.MAX_VALUE); return i; } } public class HexColumnSelect extends MultipleSelect<int[]> { public final H2OHexKey _key; public HexColumnSelect(String name, H2OHexKey key) { super(name); addPrerequisite(_key = key); } public boolean shouldIgnore(int i, ValueArray.Column ca ) { return false; } public void checkLegality(int i, ValueArray.Column c) throws IllegalArgumentException { } protected Comparator<Integer> colComp(final ValueArray ary){ return null; } ArrayList<Integer> _selectedCols; // All the columns I'm willing to show the user // Select which columns I'll show the user @Override protected String queryElement() { ValueArray va = _key.value(); ArrayList<Integer> cols = Lists.newArrayList(); for (int i = 0; i < va._cols.length; ++i) if( !shouldIgnore(i, va._cols[i]) ) cols.add(i); Comparator<Integer> cmp = colComp(va); if(cmp != null) Collections.sort(cols,cmp); _selectedCols = cols; return super.queryElement(); } // "values" to send back and for in URLs. Use numbers for density (shorter URLs). @Override protected final String[] selectValues() { String [] res = new String[_selectedCols.size()]; int idx = 0; for(int i : _selectedCols) res[idx++] = String.valueOf(i); return res; } // "names" to select in the boxes. @Override protected String[] selectNames() { ValueArray va = _key.value(); String [] res = new String[_selectedCols.size()]; int idx = 0; for(int i:_selectedCols) res[idx++] = va._cols[i]._name; return res; } @Override protected boolean isSelected(String value) { ValueArray va = _key.value(); int[] val = value(); if (val == null) return false; int idx = vaColumnNameToIndex(va, value); return Ints.contains(val, idx); } @Override protected int[] parse(String input) throws IllegalArgumentException { ValueArray va = _key.value(); ArrayList<Integer> al = new ArrayList(); for (String col : input.split(",")) { col = col.trim(); int idx = vaColumnNameToIndex(va, col); if (idx == -1) throw new IllegalArgumentException("Column "+col+" not part of key "+va._key); if (al.contains(idx)) throw new IllegalArgumentException("Column "+col+" is already ignored."); checkLegality(idx, va._cols[idx]); al.add(idx); } return Ints.toArray(al); } @Override protected int[] defaultValue() { return new int[0]; } @Override protected String queryDescription() { return "Columns to select"; } } public class HexNonClassColumnSelect extends HexColumnSelect { public final H2OHexKeyCol _classCol; public HexNonClassColumnSelect(String name, H2OHexKey key, H2OHexKeyCol classCol) { super(name, key); addPrerequisite(_classCol = classCol); } @Override public boolean shouldIgnore(int i, Column ca) { return i == _classCol.value(); } @Override public void checkLegality(int i, Column c) throws IllegalArgumentException { if( i == _classCol.value() ) throw new IllegalArgumentException("Class column "+i+" cannot be ignored"); } } public class HexAllColumnSelect extends HexColumnSelect { public HexAllColumnSelect(String name, H2OHexKey key) { super(name, key); } @Override protected int[] defaultValue() { int[] cols = new int[_key.value()._cols.length]; for( int i = 0; i < cols.length; i++ ) cols[i]=i; return cols; } } // By default, all on - except *constant* columns public class HexNonConstantColumnSelect extends HexNonClassColumnSelect { public HexNonConstantColumnSelect(String name, H2OHexKey key, H2OHexKeyCol classCol) { super(name, key, classCol); } @Override public String [] selectNames(){ ValueArray va = _key.value(); String [] res = new String [_selectedCols.size()]; int idx = 0; for(int cid: _selectedCols){ Column c = va._cols[cid]; double ratio = c._n/(double)va._numrows; if(ratio < 0.99){ res[idx++] = c._name + " (" + Math.round((1-ratio)*100) + "% NAs)"; } else res[idx++] = c._name; } return res; } @Override protected Comparator<Integer> colComp(final ValueArray ary){ ValueArray va = _key.value(); final double ratio = 1.0/va._numrows; return new Comparator<Integer>() { @Override public int compare(Integer x, Integer y) { Column xc = ary._cols[x]; Column yc = ary._cols[y]; double xRatio = xc._n*ratio; double yRatio = yc._n*ratio; if(xRatio > 0.9 && yRatio > 0.9) return 0; if(xRatio <= 0.9 && yRatio <= 0.9) return Double.compare(1-xRatio, 1-yRatio); if(xRatio <= 0.9) return 1; return -1; } }; } double _maxNAsRatio = 0.1; ThreadLocal<TreeSet<String>> _constantColumns = new ThreadLocal<TreeSet<String>>(); ThreadLocal<Integer> _badColumns = new ThreadLocal<Integer>(); @Override public boolean shouldIgnore(int i, ValueArray.Column ca ) { if(ca._min == ca._max){ if(_constantColumns.get() == null) _constantColumns.set(new TreeSet<String>()); _constantColumns.get().add(Objects.firstNonNull(ca._name, String.valueOf(i))); return true; } return super.shouldIgnore(i, ca); } String _comment = ""; @Override protected int[] defaultValue() { ValueArray va = _key.value(); int [] res = new int[va._cols.length]; int selected = 0; for(int i = 0; i < va._cols.length; ++i) if(!shouldIgnore(i,va._cols[i])) if((1.0 - (double)va._cols[i]._n/va._numrows) <= _maxNAsRatio) res[selected++] = i; else { int val = 0; if(_badColumns.get() != null) val = _badColumns.get(); _badColumns.set(val+1); } return Arrays.copyOfRange(res,0,selected); } @Override public String queryComment(){ if(_constantColumns.get() == null || _constantColumns.get().isEmpty())return ""; TreeSet<String> ignoredCols = _constantColumns.get(); if(_badColumns.get() != null && _badColumns.get() > 0) return "<div class='alert'><b> There were " + _badColumns.get() + " bad columns not selected by default. Ignoring " + _constantColumns.get().size() + " constant columns</b>: " + ignoredCols.toString() +"</div>"; else return "<div class='alert'><b>Ignoring " + _constantColumns.get().size() + " constant columns</b>: " + ignoredCols.toString() +"</div>"; } } // H2OHexCategoryWeights public class H2OCategoryWeights extends MultipleText<double[]> { public final RFModelKey _modelKey; public final H2OHexKey _key; public final H2OHexKeyCol _classCol; public final double _defaultValue; public H2OCategoryWeights(String name, RFModelKey modelKey, H2OHexKey key, H2OHexKeyCol classCol, double defaultValue) { super(name,false); _modelKey = modelKey; _key = key; _classCol = classCol; _defaultValue = defaultValue; if (modelKey!=null) addPrerequisite(modelKey); addPrerequisite(key); addPrerequisite(classCol); } public H2OCategoryWeights(String name, H2OHexKey key, H2OHexKeyCol classCol, double defaultValue) { this(name, null, key, classCol, defaultValue); } protected String[] determineColumnClassNames(int maxClasses) throws IllegalArgumentException { ValueArray va = _key.value(); ValueArray.Column dataCol = va._cols[_classCol.value()]; if (_modelKey!=null) { ValueArray.Column modelCol = _modelKey.value().response(); return vaCategoryNames(modelCol, dataCol, maxClasses); } else { return vaCategoryNames(dataCol, maxClasses); } } @Override protected String[] textValues() { double[] val = value(); String[] result = new String[val.length]; for (int i = 0; i < val.length; ++i) result[i] = String.valueOf(val[i]); return result; } @Override protected String[] textNames() { try { return determineColumnClassNames(1024); } catch (IllegalArgumentException e) { return new String[0]; } } @Override protected double[] parse(String input) throws IllegalArgumentException { // determine the arity of the column HashMap<String,Integer> classNames = new HashMap(); String[] names = determineColumnClassNames(1024); for (int i = 0; i < names.length; ++i) classNames.put(names[i],i); double[] result = new double[names.length]; for (int i = 0; i < result.length; ++i) result[i] = _defaultValue; // now parse the given string and update the weights int start = 0; byte[] bsource = input.getBytes(); while (start < bsource.length) { while (start < bsource.length && bsource[start]==' ') ++start; // whitespace; String className; double classWeight; int end = 0; if (bsource[start] == ',') { ++start; end = input.indexOf(',',start); className = input.substring(start,end); ++end; } else { end = input.indexOf('=',start); className = input.substring(start,end); } start = end; while (start < bsource.length && bsource[start]==' ') ++start; // whitespace; if (bsource[start]!='=') throw new IllegalArgumentException("Expected = after the class name."); ++start; end = input.indexOf(',',start); try { if (end == -1) { classWeight = Double.parseDouble(input.substring(start)); start = bsource.length; } else { classWeight = Double.parseDouble(input.substring(start,end)); start = end + 1; } } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid double format for weight value"); } if (!classNames.containsKey(className)) throw new IllegalArgumentException("Category "+className+" not found!"); result[classNames.get(className)] = classWeight; } return result; } @Override protected double[] defaultValue() throws IllegalArgumentException { try { String[] names = determineColumnClassNames(1024); double[] result = new double[names.length]; for (int i = 0; i < result.length; ++i) result[i] = _defaultValue; return result; } catch( IllegalArgumentException e ) { return new double[0]; } } @Override protected String queryDescription() { return "Category weight (positive)"; } } // H2OCategoryStrata public class H2OCategoryStrata extends MultipleText<int[]> { public final H2OHexKey _key; public final H2OHexKeyCol _classCol; public final int _defaultValue; public H2OCategoryStrata(String name, H2OHexKey key, H2OHexKeyCol classCol, int defaultValue) { super(name,false); _key = key; _classCol = classCol; _defaultValue = defaultValue; addPrerequisite(key); addPrerequisite(classCol); } protected String[] determineColumnClassNames(int maxClasses) throws IllegalArgumentException { ValueArray va = _key.value(); ValueArray.Column classCol = va._cols[_classCol.value()]; return vaCategoryNames(classCol, maxClasses); } @Override protected String[] textValues() { int[] val = value(); String[] result = new String[val.length]; for (int i = 0; i < val.length; ++i) result[i] = String.valueOf(val[i]); return result; } @Override protected String[] textNames() { try { return determineColumnClassNames(1024); } catch (IllegalArgumentException e) { return new String[0]; } } @Override protected int[] parse(String input) throws IllegalArgumentException { // determine the arity of the column HashMap<String,Integer> classNames = new HashMap(); String[] names = determineColumnClassNames(1024); for (int i = 0; i < names.length; ++i) classNames.put(names[i],i); int[] result = new int[names.length]; for (int i = 0; i < result.length; ++i) result[i] = _defaultValue; int start = 0; byte[] bsource = input.getBytes(); while (start < bsource.length) { while (start < bsource.length && bsource[start]==' ') ++start; // whitespace; String className; int classWeight; int end = 0; if (bsource[start] == ',') { ++start; end = input.indexOf(',',start); className = input.substring(start,end); ++end; } else { end = input.indexOf('=',start); className = input.substring(start,end); } start = end; while (start < bsource.length && bsource[start]==' ') ++start; // whitespace; if (bsource[start]!='=') throw new IllegalArgumentException("Expected = after the class name."); ++start; end = input.indexOf(',',start); try { if (end == -1) { classWeight = Integer.parseInt(input.substring(start)); start = bsource.length; } else { classWeight = Integer.parseInt(input.substring(start,end)); start = end + 1; } } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid integer format for strata value"); } if (!classNames.containsKey(className)) throw new IllegalArgumentException("Category "+className+" not found!"); result[classNames.get(className)] = classWeight; } return result; } @Override protected int[] defaultValue() { try { String[] names = determineColumnClassNames(1024); int[] result = new int[names.length]; for (int i = 0; i < result.length; ++i) result[i] = _defaultValue; return result; } catch (IllegalArgumentException e) { return new int[0]; } } @Override protected String queryDescription() { return "Category strata sampling rates (in %)"; } public Map<Integer,Integer> convertToMap() { int[] v = value(); if ((v == null) || (v.length == 0)) return null; Map<Integer,Integer> result = new HashMap(); for (int i = 0; i < v.length; ++i) result.put(i, v[i]); return result; } @Override protected String textSuffix() { return "%"; }; } public class NTree extends Int { final RFModelKey _modelKey; public NTree(String name, final RFModelKey modelKey) { super(name, 50, 0, Integer.MAX_VALUE); _modelKey = modelKey; addPrerequisite(modelKey); } @Override protected Integer parse(String input) throws IllegalArgumentException { Integer N = super.parse(input); RFModel model = _modelKey.value(); // if (N > model.treeCount()) return N; } @Override protected Integer defaultValue() { RFModel model = _modelKey.value(); return model != null ? model.treeCount() : 0; } } }
package xjon.jum.proxy; import xjon.jum.init.UselessBlocks; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.oredict.OreDictionary; public class CommonProxy { public void registerRenders() { } private void addOreDictionary() { OreDictionary.registerOre("oreUseless", UselessBlocks.useless_ore); OreDictionary.registerOre("oreSuperUseless", UselessBlocks.better_useless_ore); } }
package com.skelril.skree.content.zone.group.shnugglesprime; import net.minecraft.entity.monster.EntityZombie; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.living.monster.Giant; import org.spongepowered.api.entity.living.monster.Zombie; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.projectile.Projectile; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.block.ChangeBlockEvent; import org.spongepowered.api.event.entity.DestructEntityEvent; import org.spongepowered.api.event.entity.SpawnEntityEvent; import org.spongepowered.api.event.item.inventory.DropItemEvent; import org.spongepowered.api.text.Text; import java.util.Optional; public class ShnugglesPrimeListener { private final ShnugglesPrimeManager manager; public ShnugglesPrimeListener(ShnugglesPrimeManager manager) { this.manager = manager; } @Listener public void onEntitySpawn(SpawnEntityEvent event) { event.getEntities().removeAll(event.filterEntities(e -> { if (manager.getApplicableZone(e).isPresent()) { if (e instanceof Giant) { return true; } return e instanceof Projectile || (e instanceof Zombie && ((EntityZombie) e).isChild()); } return true; })); } @Listener public void onBlockChange(ChangeBlockEvent event) { Optional<Player> player = event.getCause().first(Player.class); if (player.isPresent() && manager.getApplicableZone(player.get()).isPresent()) { event.setCancelled(true); } } @Listener public void onEntityDrop(DropItemEvent.Destruct event) { Optional<Zombie> zombie = event.getCause().first(Zombie.class); if (zombie.isPresent() && manager.getApplicableZone(zombie.get()).isPresent()) { event.setCancelled(true); } } @Listener public void onPlayerDeath(DestructEntityEvent.Death event) { Entity entity = event.getTargetEntity(); if (!(entity instanceof Player)) { return; } Player player = (Player) entity; Optional<ShnugglesPrimeInstance> optInst = manager.getApplicableZone(player); if (optInst.isPresent()) { ShnugglesPrimeInstance inst = optInst.get(); inst.healBoss(.33F); // TODO inventory protection & removal of drops here String deathMessage; switch (inst.getLastAttack().orElse(null)) { case WRATH: deathMessage = " discovered how tasty the boss's wrath is"; break; case CORRUPTION: deathMessage = " embraced the boss's corruption"; break; case BLINDNESS: deathMessage = " did not die seeing"; break; case TANGO_TIME: deathMessage = " found out the boss has two left feet"; break; case EVERLASTING: deathMessage = " needs not pester invincible overlords"; break; case FIRE: deathMessage = " died to a terrible inferno"; break; case BASK_IN_MY_GLORY: deathMessage = " basked in the glory of the boss"; break; case DARK_POTIONS: deathMessage = " was the victim of dark magic"; break; case MINION_LEECH: deathMessage = " has been consumed by the boss"; break; default: deathMessage = " died while attempting to slay the boss"; break; } event.setMessage(Text.of(player.getName(), deathMessage)); } } }
package eu.socialsensor.framework.client.search.solr; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.UpdateResponse; import org.apache.solr.common.util.NamedList; import eu.socialsensor.framework.client.search.Query; import eu.socialsensor.framework.client.search.SearchEngineResponse; /** * * @author cmartin - c.j.martin-dancausa@rgu.ac.uk */ public class SolrTopicDetectionItemHandler { private Logger logger = Logger.getLogger(SolrTopicDetectionItemHandler.class); private SolrServer server; private static SolrTopicDetectionItemHandler INSTANCE = null; private SolrTopicDetectionItemHandler(String collection) { try { server = new HttpSolrServer(collection); } catch (Exception e) { Logger.getRootLogger().info(e.getMessage()); } } //implementing Singleton pattern public static SolrTopicDetectionItemHandler getInstance(String collection) { if (INSTANCE == null) { INSTANCE = new SolrTopicDetectionItemHandler(collection); } return INSTANCE; } @SuppressWarnings("finally") public boolean deleteItem(String itemId) { boolean status = false; try { server.deleteByQuery("id:" + itemId); UpdateResponse response = server.commit(); int statusId = response.getStatus(); if (statusId == 0) { status = true; } } catch (SolrServerException ex) { logger.error(ex.getMessage()); } catch (IOException ex) { logger.error(ex.getMessage()); } finally { return status; } } @SuppressWarnings("finally") public boolean deleteItems(Query query) { boolean status = false; try { server.deleteByQuery(query.getQueryString()); UpdateResponse response = server.commit(); int statusId = response.getStatus(); if (statusId == 0) { status = true; } } catch (SolrServerException ex) { logger.error(ex.getMessage()); } catch (IOException ex) { logger.error(ex.getMessage()); } finally { return status; } } // public SearchEngineResponse<Item> findItems(SolrQuery query) { // return search(query); // public List<Item> findItemsByTimeslotId(String timeslotId) { // SolrQuery solrQuery = new SolrQuery("timeslotId:\"" + timeslotId + "\""); // solrQuery.setRows(100000000); // SearchEngineResponse<Item> response = search(solrQuery); // List<Item> items = response.getResults(); // if (!items.isEmpty()) { // return items; // } else { // Logger.getRootLogger().info("no tweet for this timeslotId found!!"); // return null; public Map<String, SolrTopicDetectionItem> findItems(long lowerBound, long upperBound) { Map<String, SolrTopicDetectionItem> itemsMap=new HashMap<String, SolrTopicDetectionItem>(); SolrQuery solrQuery = new SolrQuery("publicationTime: ["+lowerBound+" TO "+upperBound+"}"); solrQuery.setRows(10000000); SearchEngineResponse<SolrTopicDetectionItem> response = search(solrQuery); List<SolrTopicDetectionItem> items = response.getResults(); if (!items.isEmpty()) { for (SolrTopicDetectionItem item:items) itemsMap.put(item.getId(), item); return itemsMap; } else { Logger.getRootLogger().info("no tweets found!!"); return null; } } public SolrTopicDetectionItem findItem(String itemId) { SolrQuery solrQuery = new SolrQuery("id:\"" + itemId + "\""); solrQuery.setRows(1); SearchEngineResponse<SolrTopicDetectionItem> response = search(solrQuery); List<SolrTopicDetectionItem> items = response.getResults(); if (!items.isEmpty()) { return items.get(0); } else { Logger.getRootLogger().info("no tweet for this id found!!"); return null; } } @SuppressWarnings("unchecked") public Map<String,Integer> getItemTermsId(String id) { Map<String,Integer> terms=new HashMap<String,Integer>(); SolrQuery query = new SolrQuery("id:"+id); query.setRequestHandler("/tvrh"); query.setParam("tv.fl", "title"); query.setParam("f.title.tv.tf", true); query.setRows(2000000); logger.info(query.toString()); QueryResponse rsp; try { rsp = server.query(query); } catch (SolrServerException e) { logger.warn("Problem with the query in getTermsItem method (SolrTopicDetectionItemHandler class) from socialsensor-framework-client module"); e.printStackTrace(); return null; } logger.info("Elapsed time: " + rsp.getElapsedTime()); NamedList<NamedList<Object>> termsVectors; NamedList<Object> itemTermsVectors; if ((termsVectors = (NamedList<NamedList<Object>>) rsp.getResponse().get("termVectors")) == null) { logger.warn("No term vectors found..."); return terms; } for (int i = 0; i < termsVectors.size(); i++) { try { itemTermsVectors = (NamedList<Object>) termsVectors.getVal(i); } catch (Exception e) { continue; } NamedList<NamedList<Object>> itemTerms; Iterator<Entry<String, NamedList<Object>>> itemTermsIterator; if ((itemTerms = (NamedList<NamedList<Object>>) itemTermsVectors.get("title")) == null) { return terms; } itemTermsIterator = itemTerms.iterator(); while (itemTermsIterator.hasNext()) { Entry<String,NamedList<Object>> ngram=itemTermsIterator.next(); terms.put(ngram.getKey(), new Integer(ngram.getValue().get("tf").toString())); //System.out.println(ngram.getKey()+" -- tf-idf: "+ngram.getValue().get("tf-idf").toString()); } } return terms; } @SuppressWarnings("unchecked") public Map<String, List<String>> getItemTermsTimeslot(String typeTerm) { logger.info("Get "+typeTerm+" from current timeslot"); Map<String, List<String>> itemsTerms = new HashMap<String, List<String>>(); SolrQuery query = new SolrQuery("*:*"); query.setRequestHandler("/tvrh"); query.setParam("tv.fl", typeTerm); query.setParam("f."+typeTerm+".tv.tf", true); query.setRows(2000000); logger.info(query.toString()); QueryResponse rsp; try { rsp = server.query(query); } catch (SolrServerException e) { logger.warn("Problem with the query in getTermsItem method (SolrTopicDetectionItemHandler class) from socialsensor-framework-client module"); e.printStackTrace(); return null; } logger.info("Elapsed time: " + rsp.getElapsedTime()); NamedList<NamedList<Object>> itemsTermsVectors; if ((itemsTermsVectors = (NamedList<NamedList<Object>>) rsp.getResponse().get("termVectors")) == null) { logger.warn("No term vectors found..."); return itemsTerms; } NamedList<Object> itemTermsVectors; NamedList<NamedList<Object>> itemTerms; Iterator<Entry<String, NamedList<Object>>> itemTermsIterator; for (int i = 0; i < itemsTermsVectors.size(); i++) { try { itemTermsVectors = (NamedList<Object>) itemsTermsVectors.getVal(i); } catch (Exception e) { continue; } if ((itemTerms = (NamedList<NamedList<Object>>) itemTermsVectors.get(typeTerm)) == null) { itemsTerms.put(itemsTermsVectors.getName(i), new ArrayList<String>()); continue; } itemTermsIterator = itemTerms.iterator(); List<String> terms = new ArrayList<String>(); while (itemTermsIterator.hasNext()) { terms.add(itemTermsIterator.next().getKey()); //System.out.println(ngram.getKey()+" -- tf-idf: "+ngram.getValue().get("tf-idf").toString()); } itemsTerms.put(itemsTermsVectors.getName(i), terms); } return itemsTerms; } @SuppressWarnings("unchecked") public Map<String, List<String>> getItemTermsTimeslot(String typeTerm, long lowerBound, long upperBound) { logger.info("Get "+typeTerm+" from current timeslot"); Map<String, List<String>> itemsTerms = new HashMap<String, List<String>>(); SolrQuery query = new SolrQuery("publicationTime: ["+lowerBound+" TO "+upperBound+"}"); query.setRequestHandler("/tvrh"); query.setParam("tv.fl", typeTerm); query.setParam("f."+typeTerm+".tv.tf", true); query.setRows(2000000); logger.info(query.toString()); QueryResponse rsp; try { rsp = server.query(query); } catch (SolrServerException e) { logger.warn("Problem with the query in getTermsItem method (SolrTopicDetectionItemHandler class) from socialsensor-framework-client module"); e.printStackTrace(); return null; } logger.info("Elapsed time: " + rsp.getElapsedTime()); NamedList<NamedList<Object>> itemsTermsVectors; if ((itemsTermsVectors = (NamedList<NamedList<Object>>) rsp.getResponse().get("termVectors")) == null) { logger.warn("No term vectors found..."); return itemsTerms; } NamedList<Object> itemTermsVectors; NamedList<NamedList<Object>> itemTerms; Iterator<Entry<String, NamedList<Object>>> itemTermsIterator; for (int i = 0; i < itemsTermsVectors.size(); i++) { try { itemTermsVectors = (NamedList<Object>) itemsTermsVectors.getVal(i); } catch (Exception e) { continue; } if ((itemTerms = (NamedList<NamedList<Object>>) itemTermsVectors.get(typeTerm)) == null) { itemsTerms.put(itemsTermsVectors.getName(i), new ArrayList<String>()); continue; } itemTermsIterator = itemTerms.iterator(); List<String> terms = new ArrayList<String>(); while (itemTermsIterator.hasNext()) { terms.add(itemTermsIterator.next().getKey()); //System.out.println(ngram.getKey()+" -- tf-idf: "+ngram.getValue().get("tf-idf").toString()); } itemsTerms.put(itemsTermsVectors.getName(i), terms); } return itemsTerms; } // @SuppressWarnings("unchecked") // public Map<String, Integer> getAllDyscoKeywords(String dyscoId) { // logger.info("Getting terms from dysco: " + dyscoId); // int cont; // // Getting term vectors from Solr // Map<String, Integer> terms = new HashMap<String, Integer>(); // SolrQuery query = new SolrQuery("dyscoId:\"" + dyscoId + "\""); // query.setRequestHandler("/tvrh"); // query.setParam("tv.fl", "text"); // query.setParam("f.text.tv.tf", true); // query.setRows(100000); // QueryResponse rsp; // try { // rsp = server.query(query); // } catch (SolrServerException e) { // e.printStackTrace(); // return null; // logger.info("Elapsed time: " + rsp.getElapsedTime()); // NamedList<NamedList<Object>> termVectors; // if ((termVectors = (NamedList<NamedList<Object>>) rsp.getResponse().get("termVectors")) == null) { // logger.warn("No term vectors found..."); // return terms; // NamedList<Object> termVectorsItemId; // NamedList<NamedList<Object>> ngrams; // Iterator<Entry<String, NamedList<Object>>> ngramsIterator; // Entry<String, NamedList<Object>> ngram; // for (int i = 0; i < termVectors.size(); i++) { // if (!termVectors.getName(i).contains("Twitter")) { // continue; // termVectorsItemId = termVectors.getVal(i); // if ((ngrams = (NamedList<NamedList<Object>>) termVectorsItemId.get("text")) == null) { // logger.warn("No text property found for item: " + termVectors.getName(i)); // return terms; // ngramsIterator = ngrams.iterator(); // while (ngramsIterator.hasNext()) { // ngram = ngramsIterator.next(); // cont = Integer.parseInt(ngram.getValue().get("tf").toString()); // if (terms.containsKey(ngram.getKey())) { // cont += terms.get(ngram.getKey()); // terms.put(ngram.getKey(), cont); // return terms; private SearchEngineResponse<SolrTopicDetectionItem> search(SolrQuery query) { SearchEngineResponse<SolrTopicDetectionItem> response = new SearchEngineResponse<SolrTopicDetectionItem>(); //// query.setRows(450); //// query.setFacet(true); //// query.addFacetField("sentiment"); //// query.setFacetLimit(4); //// query.set(FacetParams.FACET_DATE, "creationDate"); //// query.set(FacetParams.FACET_DATE_START, "NOW/DAY-5YEARS"); //// query.set(FacetParams.FACET_DATE_END, "NOW/DAY"); //// query.set(FacetParams.FACET_DATE_GAP, "+1YEAR"); QueryResponse rsp; System.out.println("query: " + query.toString()); try { rsp = server.query(query); } catch (SolrServerException e) { logger.info(e.getMessage()); return null; } response.setNumFound(rsp.getResults().getNumFound()); List<SolrTopicDetectionItem> solrTopicDetectionItems = rsp.getBeans(SolrTopicDetectionItem.class); if (solrTopicDetectionItems != null) { Logger.getRootLogger().info("got: " + solrTopicDetectionItems.size() + " topicDetectionItems from Solr"); } response.setResults(solrTopicDetectionItems); return response; } // public void updateItemFields(String id, String dyscoId, Date creationDate) throws SolrServerException, IOException { // SolrInputDocument doc = new SolrInputDocument(); // doc.addField("id", id); // HashMap<String, Object> dyscoIdMap = new HashMap<String, Object>(); //need better api for this??? // dyscoIdMap.put("set", dyscoId); // doc.addField("dyscoId", dyscoIdMap); // HashMap<String, Object> dateMap = new HashMap<String, Object>(); //need better api for this??? // dateMap.put("set", creationDate); // doc.addField("creationDate", dateMap); // server.add(doc); // server.commit(); // public void updateItems(List<Item> items, Date creationDate, String dyscoId) throws SolrServerException, IOException { // List<SolrInputDocument> docs = new ArrayList<SolrInputDocument>(); // for (Item item : items) { // SolrInputDocument doc = new SolrInputDocument(); // doc.addField("id", item.getId()); // HashMap<String, Object> dyscoIdMap = new HashMap<String, Object>(); //need better api for this??? // dyscoIdMap.put("set", dyscoId); // doc.addField("dyscoId", dyscoIdMap); // HashMap<String, Object> dateMap = new HashMap<String, Object>(); //need better api for this??? // dateMap.put("set", creationDate); // doc.addField("creationDate", dateMap); // docs.add(doc); // if (docs.size() > 0) { // Logger.getRootLogger().info("is going to index: " + docs.size() + " documents to Solr"); // server.add(docs); // server.commit(); }
package org._3pq.jgrapht.alg; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org._3pq.jgrapht.Graph; import org._3pq.jgrapht.event.ConnectedComponentTraversalEvent; import org._3pq.jgrapht.event.GraphEdgeChangeEvent; import org._3pq.jgrapht.event.GraphListener; import org._3pq.jgrapht.event.GraphVertexChangeEvent; import org._3pq.jgrapht.event.TraversalListenerAdapter; import org._3pq.jgrapht.event.VertexTraversalEvent; import org._3pq.jgrapht.traverse.BreadthFirstIterator; /** * Allows obtaining various connectivity aspects of a graph. The <i>inspected * graph</i> is specified at construction time and cannot be modified. * Currently, the inspector supports connected components for an undirected * graph and weakly connected components for a directed graph. (TODO: * implement Tarjan's algorithm for strongly connected component discovery.) * * <p> * The inspector methods work in a lazy fashion: no computation is performed * unless immediately necessary. Computation are done once and results and * cached within this class for future need. * </p> * * <p> * The inspector is also a {@link org._3pq.jgrapht.event.GraphListener}. If * added as a listener to the inspected graph, the inspector will amend * internal cached results instead of recomputing them. It is efficient when a * few modifications are applied to a large graph. If many modifications are * expected it will not be efficient due to added overhead on graph update * operations. If inspector is added as listener to a graph other than the one * it inspects, results are undefined. * </p> * * @author Barak Naveh * @author John V. Sichi (original author of a similar class in OpenJGraph) * * @since Aug 6, 2003 */ public class ConnectivityInspector implements GraphListener { List m_connectedSets; Map m_vertexToConnectedSet; private Graph m_graph; /** * Creates a connectivity inspector for the specified graph. * * @param g the graph for which a connectivity inspector to be created. */ public ConnectivityInspector( Graph g ) { init( ); m_graph = g; } /** * Test if the inspected graph is connected. An empty graph is <i>not</i> * considered connected. * * @return <code>true</code> if and only if inspected graph is connected. */ public boolean isGraphConnected( ) { return lazyFindConnectedSets( ).size( ) == 1; } public Set connectedSetOf( Object vertex ) { Set connectedSet = (Set) m_vertexToConnectedSet.get( vertex ); if( connectedSet == null ) { connectedSet = new HashSet( ); BreadthFirstIterator i = new BreadthFirstIterator( m_graph, vertex, true ); while( i.hasNext( ) ) { connectedSet.add( i.next( ) ); } m_vertexToConnectedSet.put( vertex, connectedSet ); } return connectedSet; } public List connectedSets( ) { return lazyFindConnectedSets( ); } /** * @see GraphListener#edgeAdded(GraphEdgeChangeEvent) */ public void edgeAdded( GraphEdgeChangeEvent e ) { init( ); // for now invalidate cached results, in the future need to amend them. } /** * @see GraphListener#edgeRemoved(GraphEdgeChangeEvent) */ public void edgeRemoved( GraphEdgeChangeEvent e ) { init( ); // for now invalidate cached results, in the future need to amend them. } /** * Tests if there is a path from the specified source vertex to the * specified target vertices. For a directed graph, direction is ignored * for this interpretation of path. * * <p> * Note: Future versions of this method might not ignore edge directions * for directed graphs. * </p> * * @param sourceVertex one end of the path. * @param targetVertex another end of the path. * * @return <code>true</code> if and only if there is a path from the source * vertex to the target vertex. */ public boolean pathExists( Object sourceVertex, Object targetVertex ) { /* * TODO: Ignoring edge direction for directed graph may be * confusing. For directed graphs, consider Dijkstra's algorithm. */ Set sourceSet = connectedSetOf( sourceVertex ); return sourceSet.contains( targetVertex ); } /** * @see org._3pq.jgrapht.event.VertexSetListener#vertexAdded(GraphVertexChangeEvent) */ public void vertexAdded( GraphVertexChangeEvent e ) { init( ); // for now invalidate cached results, in the future need to amend them. } /** * @see org._3pq.jgrapht.event.VertexSetListener#vertexRemoved(GraphVertexChangeEvent) */ public void vertexRemoved( GraphVertexChangeEvent e ) { init( ); // for now invalidate cached results, in the future need to amend them. } private void init( ) { m_connectedSets = null; m_vertexToConnectedSet = new HashMap( ); } private List lazyFindConnectedSets( ) { if( m_connectedSets == null ) { m_connectedSets = new ArrayList( ); Set vertexSet = m_graph.vertexSet( ); if( vertexSet.size( ) > 0 ) { BreadthFirstIterator i = new BreadthFirstIterator( m_graph, null, true ); i.addTraversalListener( new MyTraversalListener( ) ); while( i.hasNext( ) ) { i.next( ); } } } return m_connectedSets; } /** * A traversal listener that groups all vertices according to to their * containing connected set. * * @author Barak Naveh * * @since Aug 6, 2003 */ private class MyTraversalListener extends TraversalListenerAdapter { private Set m_currentConnectedSet; /** * @see TraversalListenerAdapter#connectedComponentFinished(ConnectedComponentTraversalEvent) */ public void connectedComponentFinished( ConnectedComponentTraversalEvent e ) { m_connectedSets.add( m_currentConnectedSet ); } /** * @see TraversalListenerAdapter#connectedComponentStarted(ConnectedComponentTraversalEvent) */ public void connectedComponentStarted( ConnectedComponentTraversalEvent e ) { m_currentConnectedSet = new HashSet( ); } /** * @see TraversalListenerAdapter#vertexTraversed(Object) */ public void vertexTraversed( VertexTraversalEvent e ) { Object v = e.getVertex( ); m_currentConnectedSet.add( v ); m_vertexToConnectedSet.put( v, m_currentConnectedSet ); } } }
package org.anddev.andengine.util.pool; import java.util.Collections; import java.util.Stack; import org.anddev.andengine.util.Debug; /** * @author Valentin Milea * @author Nicolas Gramlich * * @since 22:19:55 - 31.08.2010 * @param <T> */ public abstract class GenericPool<T> { // Constants // Fields private final Stack<T> mAvailableItems = new Stack<T>(); private int mUnrecycledCount; private final int mGrowth; // Constructors public GenericPool() { this(0); } public GenericPool(final int pInitialSize) { this(pInitialSize, 1); } public GenericPool(final int pInitialSize, final int pGrowth) { if(pGrowth < 0) { throw new IllegalArgumentException("pGrowth must be at least 0!"); } this.mGrowth = pGrowth; if(pInitialSize > 0) { this.batchAllocatePoolItems(pInitialSize); } } // Getter & Setter public synchronized int getUnrecycledCount() { return this.mUnrecycledCount; } // Methods for/from SuperClass/Interfaces protected abstract T onAllocatePoolItem(); // Methods protected void onHandleRecycleItem(final T pItem) { } protected T onHandleAllocatePoolItem() { return this.onAllocatePoolItem(); } protected void onHandleObtainItem(final T pItem) { } public synchronized void batchAllocatePoolItems(final int pCount) { final Stack<T> availableItems = this.mAvailableItems; for(int i = pCount - 1; i >= 0; i availableItems.push(this.onHandleAllocatePoolItem()); } } public synchronized T obtainPoolItem() { final T item; if(this.mAvailableItems.size() > 0) { item = this.mAvailableItems.pop(); } else { if(this.mGrowth == 1) { item = this.onHandleAllocatePoolItem(); } else { this.batchAllocatePoolItems(this.mGrowth); item = this.mAvailableItems.pop(); } Debug.i(this.getClass().getName() + "<" + item.getClass().getSimpleName() +"> was exhausted, with " + this.mUnrecycledCount + " item not yet recycled. Allocated " + this.mGrowth + " more."); } this.onHandleObtainItem(item); this.mUnrecycledCount++; return item; } public synchronized void recyclePoolItem(final T pItem) { if(pItem == null) { throw new IllegalArgumentException("Cannot recycle null item!"); } this.onHandleRecycleItem(pItem); this.mAvailableItems.push(pItem); this.mUnrecycledCount if(this.mUnrecycledCount < 0) { Debug.e("More items recycled than obtained!"); } } public synchronized void shufflePoolItems() { Collections.shuffle(this.mAvailableItems); } // Inner and Anonymous Classes }
package org.apache.bsf.engines.jython; import java.io.ByteArrayInputStream; import java.util.Vector; import org.python.util.*; import org.python.core.*; import org.apache.bsf.*; import org.apache.bsf.util.BSFEngineImpl; import org.apache.bsf.util.BSFFunctions; public class JythonEngine extends BSFEngineImpl { BSFPythonInterpreter interp; /** * call the named method of the given object. */ public Object call (Object object, String method, Object[] args) throws BSFException { try { PyObject[] pyargs = Py.EmptyObjects; if (args != null) { pyargs = new PyObject[args.length]; for (int i = 0; i < pyargs.length; i++) pyargs[i] = Py.java2py(args[i]); } if (object != null) { PyObject o = Py.java2py(object); return unwrap(o.invoke(method, pyargs)); } PyObject m = interp.get(method); if (m == null) m = interp.eval(method); if (m != null) { return unwrap(m.__call__(pyargs)); } return null; } catch (PyException e) { throw new BSFException (BSFException.REASON_EXECUTION_ERROR, "exception from Jython:\n" + e, e); } } /** * Declare a bean */ public void declareBean (BSFDeclaredBean bean) throws BSFException { interp.set (bean.name, bean.bean); } /** * Evaluate an anonymous function (differs from eval() in that apply() * handles multiple lines). */ public Object apply (String source, int lineNo, int columnNo, Object funcBody, Vector paramNames, Vector arguments) throws BSFException { try { /* We wrapper the original script in a function definition, and * evaluate the function. A hack, no question, but it allows * apply() to pretend to work on Jython. */ StringBuffer script = new StringBuffer(byteify(funcBody.toString())); int index = 0; script.insert(0, "def bsf_temp_fn():\n"); while (index < script.length()) { if (script.charAt(index) == '\n') { script.insert(index+1, '\t'); } index++; } interp.exec (script.toString ()); Object result = interp.eval ("bsf_temp_fn()"); if (result != null && result instanceof PyJavaInstance) result = ((PyJavaInstance)result).__tojava__(Object.class); return result; } catch (PyException e) { throw new BSFException (BSFException.REASON_EXECUTION_ERROR, "exception from Jython:\n" + e, e); } } /** * Evaluate an expression. */ public Object eval (String source, int lineNo, int columnNo, Object script) throws BSFException { try { Object result = interp.eval (byteify(script.toString ())); if (result != null && result instanceof PyJavaInstance) result = ((PyJavaInstance)result).__tojava__(Object.class); return result; } catch (PyException e) { throw new BSFException (BSFException.REASON_EXECUTION_ERROR, "exception from Jython:\n" + e, e); } } /** * Execute a script. */ public void exec (String source, int lineNo, int columnNo, Object script) throws BSFException { try { interp.exec (byteify(script.toString ())); } catch (PyException e) { throw new BSFException (BSFException.REASON_EXECUTION_ERROR, "exception from Jython:\n" + e, e); } } /** * Execute script code, emulating console interaction. */ public void iexec (String source, int lineNo, int columnNo, Object script) throws BSFException { String scriptStr = byteify(script.toString()); int newline = scriptStr.indexOf("\n"); if (newline > -1) scriptStr = scriptStr.substring(0, newline); try { if (interp.buffer.length() > 0) interp.buffer.append("\n"); interp.buffer.append(scriptStr); if (!(interp.runsource(interp.buffer.toString()))) interp.resetbuffer(); } catch (PyException e) { interp.resetbuffer(); throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception from Jython:\n" + e, e); } } /** * Initialize the engine. */ public void initialize (BSFManager mgr, String lang, Vector declaredBeans) throws BSFException { super.initialize (mgr, lang, declaredBeans); // create an interpreter interp = new BSFPythonInterpreter (); // ensure that output and error streams are re-directed correctly interp.setOut(System.out); interp.setErr(System.err); // register the mgr with object name "bsf" interp.set ("bsf", new BSFFunctions (mgr, this)); // Declare all declared beans to the interpreter int size = declaredBeans.size (); for (int i = 0; i < size; i++) { declareBean ((BSFDeclaredBean) declaredBeans.elementAt (i)); } } /** * Undeclare a previously declared bean. */ public void undeclareBean (BSFDeclaredBean bean) throws BSFException { interp.set (bean.name, null); } public Object unwrap(PyObject result) { if (result != null) { Object ret = result.__tojava__(Object.class); if (ret != Py.NoConversion) return ret; } return result; } private String byteify (String orig) { // Ugh. Jython likes to be fed bytes, rather than the input string. ByteArrayInputStream bais = new ByteArrayInputStream(orig.getBytes()); StringBuffer s = new StringBuffer(); int c; while ((c = bais.read()) >= 0) { s.append((char)c); } return s.toString(); } private class BSFPythonInterpreter extends InteractiveInterpreter { public BSFPythonInterpreter() { super(); } // Override runcode so as not to print the stack dump public void runcode(PyObject code) { try { this.exec(code); } catch (PyException exc) { throw exc; } } } }
package org.spongepowered.common.mixin.core.entity.effect; import com.flowpowered.math.vector.Vector3i; import com.google.common.collect.Lists; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.effect.EntityLightningBolt; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.BlockPos; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.data.Transaction; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.data.manipulator.DataManipulator; import org.spongepowered.api.data.manipulator.mutable.entity.ExpirableData; import org.spongepowered.api.data.value.mutable.MutableBoundedValue; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.EntitySnapshot; import org.spongepowered.api.entity.weather.Lightning; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.action.LightningEvent; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.block.SpongeBlockSnapshotBuilder; import org.spongepowered.common.data.manipulator.mutable.entity.SpongeExpirableData; import org.spongepowered.common.data.value.SpongeValueFactory; import org.spongepowered.common.entity.SpongeEntitySnapshotBuilder; import org.spongepowered.common.interfaces.entity.IMixinEntityLightningBolt; import org.spongepowered.common.util.VecHelper; import java.util.List; @Mixin(EntityLightningBolt.class) public abstract class MixinEntityLightningBolt extends MixinEntityWeatherEffect implements Lightning, IMixinEntityLightningBolt { public Cause cause = Cause.source(this).build(); private final List<Entity> struckEntities = Lists.newArrayList(); private final List<EntitySnapshot> struckEntitySnapshots = Lists.newArrayList(); private final List<Transaction<BlockSnapshot>> struckBlocks = Lists.newArrayList(); private boolean effect = false; @Shadow private int lightningState; @Override public boolean isEffect() { return this.effect; } @Override public void setEffect(boolean effect) { this.effect = effect; } @Redirect(method = "<init>", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;setBlockState(Lnet/minecraft/util/BlockPos;Lnet/minecraft/block/state/IBlockState;)Z")) public boolean onStrikeBlockInit(net.minecraft.world.World world, BlockPos pos, IBlockState blockState) { return onStrikeBlock(world, pos, blockState); } @Redirect(method = "onUpdate()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;setBlockState(Lnet/minecraft/util/BlockPos;Lnet/minecraft/block/state/IBlockState;)Z")) public boolean onStrikeBlockUpdate(net.minecraft.world.World world, BlockPos pos, IBlockState blockState) { return onStrikeBlock(world, pos, blockState); } private boolean onStrikeBlock(net.minecraft.world.World world, BlockPos pos, IBlockState blockState) { if (!this.effect && ((World) world).containsBlock(pos.getX(), pos.getY(), pos.getZ())) { Vector3i pos3i = VecHelper.toVector(pos); Transaction<BlockSnapshot> transaction = new Transaction<BlockSnapshot>(new SpongeBlockSnapshotBuilder() .blockState((BlockState) world.getBlockState(pos)).world(((World) world).getProperties()).position(pos3i).build(), new SpongeBlockSnapshotBuilder().blockState((BlockState) blockState).world(((World) world).getProperties()).position(pos3i) .build()); if (!this.struckBlocks.contains(transaction)) { this.struckBlocks.add(transaction); } return true; } return false; } @Redirect(method = "onUpdate()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;onStruckByLightning(Lnet/minecraft/entity/effect/EntityLightningBolt;)V")) public void onStrikeEntity(net.minecraft.entity.Entity mcEntity, EntityLightningBolt lightningBolt) { if (!this.effect) { Entity entity = (Entity) mcEntity; if (!this.struckEntities.contains(entity)) { this.struckEntities.add(entity); this.struckEntitySnapshots.add(new SpongeEntitySnapshotBuilder().from(mcEntity).build()); } } } @Inject(method = "onUpdate", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/effect/EntityLightningBolt;setDead()V")) public void onLivingTimeExpired(CallbackInfo ci) { if (this.isDead) { return; } World world = (World) this.worldObj; LightningEvent.Strike strike = SpongeEventFactory.createLightningEventStrike(this.cause, this.struckEntities, this.struckEntitySnapshots, world, this.struckBlocks); Sponge.getEventManager().post(strike); if (!strike.isCancelled()) { for (Transaction<BlockSnapshot> bt : strike.getTransactions()) { if (bt.isValid()) { BlockSnapshot bs = bt.getFinal(); world.setBlock(bs.getPosition(), bs.getState()); } } for (Entity e : strike.getEntities()) { ((net.minecraft.entity.Entity) e).onStruckByLightning((EntityLightningBolt) (Object) this); } SpongeImpl.postEvent(SpongeEventFactory.createLightningEventPost(this.cause)); } } @Override public void readFromNbt(NBTTagCompound compound) { super.readFromNbt(compound); if (compound.hasKey("effect")) { this.effect = compound.getBoolean("effect"); } } @Override public void writeToNbt(NBTTagCompound compound) { super.writeToNbt(compound); compound.setBoolean("effect", this.effect); } @Override public Cause getCause() { return this.cause; } @Override public void setCause(Cause cause) { this.cause = cause; } // Data delegated methods @Override public ExpirableData getExpiringData() { return new SpongeExpirableData(this.lightningState, 2); } @Override public MutableBoundedValue<Integer> expireTicks() { return SpongeValueFactory.boundedBuilder(Keys.EXPIRATION_TICKS) .minimum((int) Short.MIN_VALUE) .maximum(2) .defaultValue(2) .actualValue(this.lightningState) .build(); } @Override public void supplyVanillaManipulators(List<DataManipulator<?, ?>> manipulators) { super.supplyVanillaManipulators(manipulators); manipulators.add(getExpiringData()); } }
package org.apache.xerces.impl.xs.models; import org.apache.xerces.xni.QName; import org.apache.xerces.impl.dtd.models.CMNode; import org.apache.xerces.impl.xs.SchemaSymbols; import org.apache.xerces.impl.xs.XSDeclarationPool; import org.apache.xerces.impl.xs.XSComplexTypeDecl; import org.apache.xerces.impl.xs.XSParticleDecl; import org.apache.xerces.impl.xs.XSModelGroupImpl; import org.apache.xerces.impl.xs.XSElementDecl; import org.apache.xerces.impl.xs.models.*; /** * This class constructs content models for a given grammar. * * @author Elena Litani, IBM * @author Sandy Gao, IBM * * @version $Id$ */ public class CMBuilder { // REVISIT: should update the decl pool to cache XSCM objects too private XSDeclarationPool fDeclPool = null; // It never changes, so a static member is good enough private static XSEmptyCM fEmptyCM = new XSEmptyCM(); // needed for DFA construction private int fLeafCount; // needed for UPA private int fParticleCount; public CMBuilder() { fDeclPool = null; } public CMBuilder(XSDeclarationPool pool) { fDeclPool = pool; } public void setDeclPool(XSDeclarationPool declPool) { fDeclPool = declPool; } /** * Get content model for the a given type * * @param typeDecl get content model for which complex type * @return a content model validator */ public XSCMValidator getContentModel(XSComplexTypeDecl typeDecl) { // for complex type with empty or simple content, // there is no content model validator short contentType = typeDecl.fContentType; if (contentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE || contentType == XSComplexTypeDecl.CONTENTTYPE_EMPTY) { return null; } XSParticleDecl particle = typeDecl.fParticle; // if the content is element only or mixed, but no particle // is defined, return the empty content model if (particle == null) return fEmptyCM; // if the content model contains "all" model group, // we create an "all" content model, otherwise a DFA content model XSCMValidator cmValidator = null; if (particle.fType == XSParticleDecl.PARTICLE_MODELGROUP && ((XSModelGroupImpl)particle.fValue).fCompositor == XSModelGroupImpl.MODELGROUP_ALL) { cmValidator = createAllCM(particle); } else { cmValidator = createDFACM(particle); } // if the validator returned is null, it means there is nothing in // the content model, so we return the empty content model. if (cmValidator == null) cmValidator = fEmptyCM; return cmValidator; } XSCMValidator createAllCM(XSParticleDecl particle) { if (particle.fMaxOccurs == 0) return null; // create an all content model. the parameter indicates whether // the <all> itself is optional XSAllCM allContent = new XSAllCM(particle.fMinOccurs == 0); // get the model group, and add all children of it to the content model XSModelGroupImpl group = (XSModelGroupImpl)particle.fValue; for (int i = 0; i < group.fParticleCount; i++) { // for all non-empty particles if (group.fParticles[i].fType != XSParticleDecl.PARTICLE_EMPTY && group.fParticles[i].fMaxOccurs != 0) // add the element decl to the all content model allContent.addElement((XSElementDecl)group.fParticles[i].fValue, group.fParticles[i].fMinOccurs == 0); } return allContent; } XSCMValidator createDFACM(XSParticleDecl particle) { fLeafCount = 0; fParticleCount = 0; // convert particle tree to CM tree CMNode node = buildSyntaxTree(particle); if (node == null) return null; // build DFA content model from the CM tree return new XSDFACM(node, fLeafCount); } // 1. convert particle tree to CM tree: // 2. expand all occurrence values: a{n, unbounded} -> a, a, ..., a+ // a{n, m} -> a, a, ..., a?, a?, ... // 3. convert model groups (a, b, c, ...) or (a | b | c | ...) to // binary tree: (((a,b),c),...) or (((a|b)|c)|...) // 4. make sure each leaf node (XSCMLeaf) has a distinct position private CMNode buildSyntaxTree(XSParticleDecl particle) { int maxOccurs = particle.fMaxOccurs; int minOccurs = particle.fMinOccurs; short type = particle.fType; CMNode nodeRet = null; if ((type == XSParticleDecl.PARTICLE_WILDCARD) || (type == XSParticleDecl.PARTICLE_ELEMENT)) { // (task 1) element and wildcard particles should be converted to // leaf nodes // REVISIT: Make a clone of the leaf particle, so that if there // are two references to the same group, we have two different // leaf particles for the same element or wildcard decl. // This is useful for checking UPA. nodeRet = new XSCMLeaf(particle.fType, particle.fValue, fParticleCount++, fLeafCount++); // (task 2) expand occurrence values nodeRet = expandContentModel(nodeRet, minOccurs, maxOccurs); } else if (type == XSParticleDecl.PARTICLE_MODELGROUP) { // (task 1,3) convert model groups to binary trees XSModelGroupImpl group = (XSModelGroupImpl)particle.fValue; CMNode temp = null; for (int i = 0; i < group.fParticleCount; i++) { // first convert each child to a CM tree temp = buildSyntaxTree(group.fParticles[i]); // then combine them using binary operation if (temp != null) { if (nodeRet == null) { nodeRet = temp; } else { nodeRet = new XSCMBinOp(group.fCompositor, nodeRet, temp); } } } // (task 2) expand occurrence values if (nodeRet != null) nodeRet = expandContentModel(nodeRet, minOccurs, maxOccurs); } return nodeRet; } // 2. expand all occurrence values: a{n, unbounded} -> a, a, ..., a+ // a{n, m} -> a, a, ..., a?, a?, ... // 4. make sure each leaf node (XSCMLeaf) has a distinct position private CMNode expandContentModel(CMNode node, int minOccurs, int maxOccurs) { CMNode nodeRet = null; if (minOccurs==1 && maxOccurs==1) { nodeRet = node; } else if (minOccurs==0 && maxOccurs==1) { //zero or one nodeRet = new XSCMUniOp(XSParticleDecl.PARTICLE_ZERO_OR_ONE, node); } else if (minOccurs == 0 && maxOccurs==SchemaSymbols.OCCURRENCE_UNBOUNDED) { //zero or more nodeRet = new XSCMUniOp(XSParticleDecl.PARTICLE_ZERO_OR_MORE, node); } else if (minOccurs == 1 && maxOccurs==SchemaSymbols.OCCURRENCE_UNBOUNDED) { //one or more nodeRet = new XSCMUniOp(XSParticleDecl.PARTICLE_ONE_OR_MORE, node); } else if (maxOccurs == SchemaSymbols.OCCURRENCE_UNBOUNDED) { // => a,a,..,a+ // create a+ node first, then put minOccurs-1 a's in front of it // for the first time "node" is used, we don't need to make a copy // and for other references to node, we make copies nodeRet = new XSCMUniOp(XSParticleDecl.PARTICLE_ONE_OR_MORE, node); for (int i=0; i < minOccurs-1; i++) { // (task 4) we need to call copyNode here, so that we append // an entire new copy of the node (a subtree). this is to ensure // all leaf nodes have distinct position nodeRet = new XSCMBinOp(XSModelGroupImpl.MODELGROUP_SEQUENCE, copyNode(node), nodeRet); } } else { // {n,m} => a,a,a,...(a),(a),... // first n a's, then m-n a?'s. // copyNode is called, for the same reason as above if (minOccurs > 0) { nodeRet = node; for (int i=0; i<minOccurs-1; i++) { nodeRet = new XSCMBinOp(XSModelGroupImpl.MODELGROUP_SEQUENCE, nodeRet, copyNode(node)); } } if (maxOccurs > minOccurs) { node = new XSCMUniOp(XSParticleDecl.PARTICLE_ZERO_OR_ONE, node); if (nodeRet == null) { nodeRet = node; } else { nodeRet = new XSCMBinOp(XSModelGroupImpl.MODELGROUP_SEQUENCE, nodeRet, copyNode(node)); } for (int i=minOccurs; i<maxOccurs-1; i++) { nodeRet = new XSCMBinOp(XSModelGroupImpl.MODELGROUP_SEQUENCE, nodeRet, copyNode(node)); } } } return nodeRet; } // 4. make sure each leaf node (XSCMLeaf) has a distinct position private CMNode copyNode(CMNode node) { int type = node.type(); // for choice or sequence, copy the two subtrees, and combine them if (type == XSModelGroupImpl.MODELGROUP_CHOICE || type == XSModelGroupImpl.MODELGROUP_SEQUENCE) { XSCMBinOp bin = (XSCMBinOp)node; node = new XSCMBinOp(type, copyNode(bin.getLeft()), copyNode(bin.getRight())); } // for ?+*, copy the subtree, and put it in a new ?+* node else if (type == XSParticleDecl.PARTICLE_ZERO_OR_MORE || type == XSParticleDecl.PARTICLE_ONE_OR_MORE || type == XSParticleDecl.PARTICLE_ZERO_OR_ONE) { XSCMUniOp uni = (XSCMUniOp)node; node = new XSCMUniOp(type, copyNode(uni.getChild())); } // for element/wildcard (leaf), make a new leaf node, // with a distinct position else if (type == XSParticleDecl.PARTICLE_ELEMENT || type == XSParticleDecl.PARTICLE_WILDCARD) { XSCMLeaf leaf = (XSCMLeaf)node; node = new XSCMLeaf(leaf.type(), leaf.getLeaf(), leaf.getParticleId(), fLeafCount++); } return node; } }
package org.appwork.storage.simplejson; /** * @author thomas */ public class JSonFactory { public static boolean DEBUG = false; private int global = 0; private char c; private final String str; final StringBuilder sb; private final StringBuilder sb2; private int counter; private String debug; public JSonFactory(final String json) { this.str = json; this.sb = new StringBuilder(); this.sb2 = new StringBuilder(); this.counter = 0; } private ParserException bam(final String expected) { final String pre = this.str.substring(Math.max(this.global - 20, 0), this.global); final StringBuilder sb = new StringBuilder(); sb.append(expected); sb.append("\r\n\t"); sb.append(pre); sb.append(this.str.substring(this.global, Math.min(this.str.length(), this.global + 20))); sb.append("\r\n\t"); for (int i = 1; i < pre.length(); i++) { sb.append("-"); } sb.append('\u2934'); return new ParserException(sb.toString()); } private String findString() throws ParserException { // string try { this.sb.delete(0, this.sb.length()); this.c = this.str.charAt(this.global++); if (this.c != '\"') { throw this.bam("'\"' expected"); } boolean escaped = false; while (true) { this.c = this.str.charAt(this.global++); switch (this.c) { case '\"': return this.sb.toString(); case '\\': escaped = true; while ((this.c = this.str.charAt(this.global++)) == '\\') { escaped = !escaped; if (!escaped) { this.sb.append("\\"); } } if (escaped) { switch (this.c) { case '"': this.sb.append('"'); continue; case 'r': this.sb.append('\r'); continue; case 'n': this.sb.append('\n'); continue; case 't': this.sb.append('\t'); continue; case 'f': this.sb.append('\f'); continue; case 'b': this.sb.append('\b'); continue; case 'u': this.sb2.delete(0, this.sb2.length()); // this.global++; this.counter = this.global + 4; for (; this.global < this.counter; this.global++) { this.c = this.getChar(); if (this.sb2.length() > 0 || this.c != '0') { this.sb2.append(this.c); } } // this.global--; this.sb.append((char) Short.parseShort(this.sb2.toString(), 16)); continue; default: throw this.bam("illegal escape char"); } } else { this.global } break; default: this.sb.append(this.c); } } } catch (final StringIndexOutOfBoundsException e) { this.global throw this.bam("Unexpected End of String \"" + this.sb.toString()); } } private char getChar() throws ParserException { if (JSonFactory.DEBUG) { final String pos = this.str.substring(0, this.global); this.debug = pos + this.str.substring(this.global) + "\r\n"; for (int i = 0; i < pos.length(); i++) { this.debug += "-"; } this.debug += '\u2934'; System.err.println(this.debug); } if(global>=str.length()){ throw this.bam("Ended unexpected"); } return this.str.charAt(this.global); } public JSonNode parse() throws ParserException { final JSonNode ret = this.parseValue(); this.skipWhiteSpace(); if (this.global != this.str.length()) { this.global++; throw this.bam("Unexpected End of JSonString"); } return ret; } private JSonArray parseArray() throws ParserException { this.global++; final JSonArray ret = new JSonArray(); while (true) { // skip whitespace this.skipWhiteSpace(); this.c = this.getChar(); switch (this.c) { case ']': this.global++; return ret; case ',': throw this.bam("Value missing"); default: ret.add(this.parseValue()); this.skipWhiteSpace(); this.c = this.getChar(); switch (this.c) { case ',': // ok another round: this.global++; continue; case ']': // end this.global++; return ret; default: throw this.bam("']' or ',' expected"); } } } } private JSonValue parseNumber() throws ParserException, NoNumberException { this.sb.delete(0, this.sb.length()); boolean pointFound = false; boolean potFound = false; this.c = this.getChar(); if (this.c == '+' || this.c == '-' || Character.isDigit(this.c)) { this.sb.append(this.c); while (this.global + 1 < this.str.length()) { this.global++; this.c = this.getChar(); if (Character.isDigit(this.c) || !pointFound && this.c == '.' || pointFound && this.c == 'e' || pointFound && this.c == 'E' || potFound && this.c == '+' || potFound && this.c == '-') { if (this.c == '.') { pointFound = true; } else if (pointFound && (this.c == 'e' || this.c == 'E')) { potFound = true; } this.sb.append(this.c); } else { this.global break; } } this.global++; if (pointFound) { return new JSonValue(Double.parseDouble(this.sb.toString())); } else { return new JSonValue(Long.parseLong(this.sb.toString())); } } else { throw new NoNumberException(); } } private JSonObject parseObject() throws ParserException { String key; this.global++; final JSonObject ret = new JSonObject(); while (true) { // check for object end markers this.skipWhiteSpace(); this.c = this.getChar(); switch (this.c) { case '}': this.global++; return ret; case '"': key = this.findString(); this.skipWhiteSpace(); this.c = this.getChar(); if (this.c != ':') { throw this.bam("':' expected"); } this.global++; this.skipWhiteSpace(); ret.put(key, this.parseValue()); this.skipWhiteSpace(); if(global>=str.length()){ throw this.bam("} or , expected"); } this.c = this.getChar(); switch (this.c) { case ',': // ok another value...probably this.global++; continue; case '}': // end of object: this.global++; return ret; default: throw this.bam("', or }' expected"); } default: throw this.bam("\", or }' expected"); } } } private JSonValue parseString() throws ParserException { return new JSonValue(this.findString()); } private JSonNode parseValue() throws ParserException { this.global = this.skipWhiteSpace(); switch (this.getChar()) { case '{': return this.parseObject(); case '[': return this.parseArray(); case 'n': // null this.global += 4; return new JSonValue(null); case 't': // true; this.global += 4; return new JSonValue(true); case 'f': // false; this.global += 5; return new JSonValue(false); case '"': return this.parseString(); } try { return this.parseNumber(); } catch (final NoNumberException e) { this.global++; throw this.bam("Illegal Char"); } } private int skipWhiteSpace() { while (this.global < this.str.length()) { if (!Character.isWhitespace(this.str.charAt(this.global++))) { this.global break; } } return this.global; } }
package org.caleydo.view.bicluster.physics; import java.awt.geom.Rectangle2D; import org.caleydo.view.bicluster.util.Vec2d; /** * @author Samuel Gratzl * */ public class Physics { public static Vec2d distance(Rectangle2D a, Rectangle2D b) { // return circleDistance(a, b); return aabbDistance(a, b); } public static Vec2d aabbDistance(Rectangle2D a, Rectangle2D b) { final Vec2d distVec = new Vec2d(); distVec.setX(a.getCenterX() - b.getCenterX()); distVec.setY(a.getCenterY() - b.getCenterY()); final double d = distVec.length(); distVec.scale(1. / d); // aka normalize double r1; // = getRadius(a); double r2; // = getRadius(b); double ray_pos_x = b.getCenterX(); double ray_pos_y = b.getCenterY(); Vec2d ray_dir = distVec; r1 = d - raxBoxIntersection(ray_pos_x, ray_pos_y, ray_dir, a); // as starting from b r2 = raxBoxIntersection(ray_pos_x, ray_pos_y, ray_dir, b); final double d_real = d - r1 - r2; distVec.scale(d_real); return distVec; } /** * computes the intersection point (as distance to the given ray) to the given box * * @param ray_pos * @param ray_dir * @param r * @return */ static double raxBoxIntersection(double ray_pos_x, double ray_pos_y, Vec2d ray_dir, Rectangle2D r) { final double min_x = r.getMinX(); final double min_y = r.getMinY(); final double max_x = r.getMaxX(); final double max_y = r.getMaxY(); double tmp; double tmin = 0; double tmax = 0; if (ray_dir.x() != 0) { // corner case = 0 tmin = (min_x - ray_pos_x) / ray_dir.x(); tmax = (max_x - ray_pos_x) / ray_dir.x(); if (tmin > tmax) { tmp = tmin; tmin = tmax; tmax = tmp; } } if (ray_dir.y() != 0) { // corner case = 0 double tymin = (min_y - ray_pos_y) / ray_dir.y(); double tymax = (max_y - ray_pos_y) / ray_dir.y(); if (tymin > tymax) { tmp = tymin; tymin = tymax; tymax = tmp; } if (ray_dir.x() != 0) { if ((tmin > tymax) || (tymin > tmax)) return 0; if (tymin > tmin) tmin = tymin; if (tymax < tmax) tmax = tymax; } else { tmin = tymin; tmax = tymax; } } tmin = Math.abs(tmin); if (tmax < tmin) return tmax; return tmin; } private static Vec2d circleDistance(Rectangle2D a, Rectangle2D b) { Vec2d distVec = new Vec2d(); distVec.setX(a.getCenterX() - b.getCenterX()); distVec.setY(a.getCenterY() - b.getCenterY()); double distance = distVec.length(); double r1 = getRadius(a); double r2 = getRadius(b); distance -= r1 + r2; distVec.normalize(); distVec.scale(distance); return distVec; } /** * @param a * @return */ private static double getRadius(Rectangle2D a) { return Math.max(a.getWidth(), a.getHeight()) * 0.5f; } public static void main(String[] args) { Rectangle2D a = new Rectangle2D.Double(0, 0, 2, 2); Rectangle2D b = new Rectangle2D.Double(4, 0, 2, 2); Rectangle2D c = new Rectangle2D.Double(0, 3, 2, 2); Rectangle2D d = new Rectangle2D.Double(3, 3, 2, 2); Rectangle2D e = new Rectangle2D.Double(4, 3, 2, 2); System.out.println("AABB\t\tcircle"); System.out.println(String.format("%f\t%f", aabbDistance(a, b).length(), circleDistance(a, b).length())); System.out.println(String.format("%f\t%f", aabbDistance(a, c).length(), circleDistance(a, b).length())); System.out.println(String.format("%f\t%f", aabbDistance(a, d).length(), circleDistance(a, b).length())); System.out.println(String.format("%f\t%f", aabbDistance(a, e).length(), circleDistance(a, b).length())); } }
package org.concord.data.state; import java.awt.CardLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import org.concord.data.state.ui.UnitEditPanel; import org.concord.framework.otrunk.OTChangeEvent; import org.concord.framework.otrunk.OTResourceList; import org.concord.swing.CustomDialog; /** * OTUnitValueEditView * * This view allows the user to change the units of the value object * * Date created: Sep 25, 2007 * * @author Ingrid Moncada<p> * */ public class OTUnitValueEditView extends OTUnitValueView implements MouseListener, ActionListener { protected JLabel valueLabel; protected JLabel unitLabel; protected JComboBox unitSelection; protected CardLayout unitLayout; protected JPanel unitPanel; protected JButton unitsChangeButton; protected JPanel viewPanel; protected boolean selected; protected boolean useComboBox = true; protected boolean autoSelectable = false; protected boolean mouseSelectionEnabled = false; protected OTResourceList unitSelectionList; public OTUnitValueEditView() { super(); } /** * @see org.concord.data.state.OTUnitValueView#getUnitValueView() */ protected JComponent getUnitValueView() { valueLabel = new JLabel(); unitLabel = new JLabel(); viewPanel = new JPanel(); if (useComboBox){ unitSelection = new JComboBox(); unitSelection.setOpaque(false); unitPanel = new JPanel(); unitLayout = new CardLayout(); unitPanel.setLayout(unitLayout); unitPanel.add(unitLabel, "view"); unitPanel.add(unitSelection, "edit"); //viewPanel.setLayout(new GridLayout(1,2)); //viewPanel.setLayout(new FlowLayout(FlowLayout.LEADING)); viewPanel.setLayout(new BoxLayout(viewPanel, BoxLayout.X_AXIS)); viewPanel.add(valueLabel); viewPanel.add(Box.createHorizontalStrut(10)); viewPanel.add(unitPanel); } else{ unitsChangeButton = new JButton("..."); unitsChangeButton.setSize(new Dimension(30, 18)); unitsChangeButton.setMaximumSize(new Dimension(30, 18)); unitsChangeButton.setPreferredSize(new Dimension(30, 18)); JPanel buttonPanel = new JPanel(); buttonPanel.add(unitsChangeButton); unitsChangeButton.addActionListener(this); viewPanel.setLayout(new GridLayout(1,3)); viewPanel.add(valueLabel); viewPanel.add(unitLabel); viewPanel.add(buttonPanel); } viewPanel.setOpaque(true); setSelected(autoSelectable); if (mouseSelectionEnabled && !autoSelectable){ viewPanel.addMouseListener(this); } updateView(); return viewPanel; } /** * @see org.concord.data.state.OTUnitValueView#updateView() */ protected void updateView() { String strValue = getStringValue(otObject, nf, false); valueLabel.setText(strValue); unitLabel.setText(" " + otObject.getUnit()); fillUnitSelection(); } public void setSelected(boolean b) { selected = b; if (unitLayout == null) return; if (selected){ // viewPanel.setBackground(Color.gray); unitLayout.show(unitPanel, "edit"); } else{ // viewPanel.setBackground(null); unitLayout.show(unitPanel, "view"); } } public boolean isSelected() { return selected; } public void mouseClicked(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mouseReleased(MouseEvent e){} /** * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent) */ public void mousePressed(MouseEvent e) { if (autoSelectable) return; setSelected(!isSelected()); } /** * Called when the user presses the "change units" button * or when the user selects a unit in the combo box * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { String newUnit = (String)unitSelection.getSelectedItem(); //Check that they selected a different unit if (newUnit.equals(otObject.getUnit())) return; //Special case when they didn't have a unit or a value originally //then it doesn't matter what the conversion rate is if (otObject.getUnit().equals("") || Float.isNaN(otObject.getValue())){ //Just change unit, don't bother showing dialog otObject.setUnit(newUnit); return; } //UnitEditPanel editUnitPanel = new UnitEditPanel(otObject); UnitEditPanel editUnitPanel = new UnitEditPanel(otObject, newUnit); //Pop up a dialog to allow changing units int retVal = CustomDialog.showOKCancelDialog( viewPanel, editUnitPanel, "Change the units"); if (retVal == JOptionPane.OK_OPTION){ //Change unit OTUnitValue newValue = editUnitPanel.getNewValue(); //Do an atomic change otObject.setDoNotifyChangeListeners(false); otObject.setValue(newValue.getValue()); otObject.setUnit(newValue.getUnit()); otObject.setDoNotifyChangeListeners(true); otObject.notifyOTChange("unit", OTChangeEvent.OP_CHANGE, otObject, null); String strMsg = editUnitPanel.getErrorMessage(); if (strMsg != null){ JOptionPane.showMessageDialog(viewPanel, strMsg, "Conversion value error", JOptionPane.ERROR_MESSAGE); updateView(); } } else{ //Show original value updateView(); } } /** * Fills the combo box with all the possible units to choose */ protected void fillUnitSelection() { unitSelection.removeActionListener(this); unitSelection.removeAllItems(); unitSelection.addItem(otObject.getUnit()); if (unitSelectionList != null){ for (int i=0; i < unitSelectionList.size(); i++){ String strUnit = (String)unitSelectionList.get(i); if (!strUnit.equals(otObject.getUnit())){ unitSelection.addItem(strUnit); } } } unitSelection.addActionListener(this); } /** * Sets the list that will be used when selecting the unit from the combo box * @param list */ public void setUnitSelectionList(OTResourceList list) { unitSelectionList = list; fillUnitSelection(); } }
package org.concord.sensor.serial; /** * @author scott * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class ByteBufferStream { byte [] inBuf; int offset; int endOffset; boolean lowNibble = false; public static final float readFloat(byte [] inBuf, int offset) { int valueInt = ((0xFF & inBuf[offset]) << 24) | ((0xFF & inBuf[offset + 1]) << 16) | ((0xFF & inBuf[offset + 2]) << 8) | (0xFF & inBuf[offset + 3]); return Float.intBitsToFloat(valueInt); } public static final int readUShort(byte [] inBuf, int offset) { int value =((inBuf[offset] & 0xFF) << 8) | (inBuf[offset+1] & 0xFF); return value; } public static final short readShort(byte [] inBuf, int offset) { int value =((inBuf[offset]) << 8) | (inBuf[offset+1] & 0xFF); return (short)value; } public static final long readULong(byte [] inBuf, int offset) { long value = ((long)((inBuf[offset++] & 0xFFL) << 24)) | ((inBuf[offset++] & 0xFF) << 16) | ((inBuf[offset++] & 0xFF) << 8) | (inBuf[offset] & 0xFF); return value; } public static final void writeULong(long value, byte [] buf, int offset) { buf[offset] = (byte)((value & 0xFF000000) >> 24); buf[offset+1] = (byte)((value & 0x00FF0000) >> 16); buf[offset+2] = (byte)((value & 0x0000FF00) >> 8); buf[offset+3] = (byte)(value & 0x000000FF); } public static final void writeUShort(int value, byte [] buf, int offset) { buf[offset] = (byte)((value & 0x0000FF00) >> 8); buf[offset+1] = (byte)(value & 0x000000FF); } public ByteBufferStream(byte [] buffer, int offset, int length) { inBuf = buffer; this.offset = offset; this.endOffset = offset+length; } public float readFloat() { if(lowNibble) { throw new RuntimeException("unread low nibble"); } float value = readFloat(inBuf, offset); offset += 4; return value; } public int readUShort() { if(lowNibble) { throw new RuntimeException("unread low nibble"); } int value = readUShort(inBuf, offset); offset += 2; return value; } public int readUByte() { if(lowNibble) { throw new RuntimeException("unread low nibble"); } int value = (inBuf[offset] & 0xFF); offset++; return value; } public int readUNibble() { int value; if(lowNibble){ value = (inBuf[offset] & 0xF); offset++; lowNibble = false; } else { value = ((inBuf[offset] & 0xF0) >> 4); // don't increase offset just set lowNibble lowNibble = true; } return value; } public String readCRTermString() { if(lowNibble) { throw new RuntimeException("unread low nibble"); } String returnStr = ""; while(offset < endOffset){ byte currChar = inBuf[offset++]; if(currChar == 0x0D) break; returnStr += (char)currChar; } return returnStr; } }
package org.exist.xmldb.test; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import junit.framework.TestCase; import org.exist.dom.XMLUtil; import org.exist.util.XMLFilenameFilter; import org.xmldb.api.*; import org.xmldb.api.base.*; import org.xmldb.api.modules.*; public class CreateCollectionsTest extends TestCase { private final static String URI = "xmldb:exist: private final static String DRIVER = "org.exist.xmldb.DatabaseImpl"; public Collection root = null; public CreateCollectionsTest(String arg0) { super(arg0); } protected void setUp() { try { // initialize driver Class cl = Class.forName(DRIVER); Database database = (Database) cl.newInstance(); database.setProperty("create-database", "true"); DatabaseManager.registerDatabase(database); // try to get collection root = DatabaseManager.getCollection(URI); } catch (ClassNotFoundException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } catch (XMLDBException e) { e.printStackTrace(); } } public void testCreateCollection() { assertNotNull(root); try { System.out.println( "Created Collection: " + root.getName() + "( " + root.getClass() + " )"); Service[] services = root.getServices(); System.out.println("services array: " + services); assertTrue( "Collection must provide at least one Service", services != null && services.length > 0); System.out.println(" number of services: " + services.length); for (int i = 0; i < services.length; i++) { System.out.println( " Service: " + services[i].getName() + "( " + services[i].getClass() + " )"); } Collection parentCollection = root.getParentCollection(); System.out.println("root parentCollection: " + parentCollection); assertNull("root collection has no parent", parentCollection); CollectionManagementService service = (CollectionManagementService) root.getService( "CollectionManagementService", "1.0"); assertNotNull(service); Collection testCollection = service.createCollection("test"); assertNotNull(testCollection); int ccc = testCollection.getChildCollectionCount(); assertTrue( "Collection just created: ChildCollectionCount==0", ccc == 0); assertTrue( "Collection state should be Open after creation", testCollection.isOpen()); String directory = "samples/shakespeare"; System.out.println(" System.out.println("storing all XML files in directory " +directory+"..."); System.out.println(" File f = new File(directory); File files[] = f.listFiles(new XMLFilenameFilter()); for (int i = 0; i < files.length; i++) { storeResourceFromFile(files[i], testCollection); } HashSet fileNamesJustStored = new HashSet(); for (int i = 0; i < files.length; i++) { String file = files[i].toString(); int lastSeparator = file.lastIndexOf(File.separatorChar); fileNamesJustStored.add(file.substring(lastSeparator + 1)); } System.out.println("fileNames stored: " + fileNamesJustStored.toString()); String[] resourcesNames = testCollection.listResources(); int resourceCount = testCollection.getResourceCount(); System.out.println( "testCollection.getResourceCount()=" + resourceCount); ArrayList fileNamesPresentInDatabase = new ArrayList(); for (int i = 0; i < resourcesNames.length; i++) { fileNamesPresentInDatabase.add( resourcesNames[i]); } assertTrue( "resourcesNames must contain fileNames just stored", fileNamesPresentInDatabase. containsAll( fileNamesJustStored) ); String fileToRemove = "macbeth.xml"; Resource resMacbeth = testCollection.getResource(fileToRemove); assertNotNull("getResource(" + fileToRemove + "\")", resMacbeth); testCollection.removeResource(resMacbeth); assertTrue( "After removal resource count must decrease", testCollection.getResourceCount() == resourceCount - 1); // restore the resource just removed : storeResourceFromFile( new File( directory + File.separatorChar + fileToRemove), testCollection); byte[] data = storeBinaryResourceFromFile( new File( "webapp/logo.jpg"), testCollection); Object content = testCollection.getResource("logo.jpg").getContent(); byte[] dataStored = (byte[])content; assertTrue("After storing binary resource, data out==data in", Arrays.equals(dataStored, data) ); } catch (XMLDBException e) { e.printStackTrace(); fail(e.getMessage()); } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); } } private XMLResource storeResourceFromFile( File file, Collection testCollection) throws XMLDBException, IOException { System.out.println("storing " + file.getAbsolutePath()); XMLResource res; String xml; res = (XMLResource) testCollection.createResource( file.getName(), "XMLResource"); assertNotNull("storeResourceFromFile", res); xml = XMLUtil.readFile(file, "UTF-8"); res.setContent(xml); testCollection.storeResource(res); System.out.println("stored " + file.getAbsolutePath()); return res; } private byte[] storeBinaryResourceFromFile( File file, Collection testCollection) throws XMLDBException, IOException { System.out.println("storing " + file.getAbsolutePath()); Resource res = (BinaryResource) testCollection.createResource( file.getName(), "BinaryResource" ); assertNotNull("store binary Resource From File", res); // Get an array of bytes from the file: FileInputStream istr = new FileInputStream(file); BufferedInputStream bstr = new BufferedInputStream( istr ); // promote int size = (int) file.length(); // get the file size (in bytes) byte[] data = new byte[size]; // allocate byte array of right size bstr.read( data, 0, size ); // read into byte array bstr.close(); res.setContent(data); testCollection.storeResource(res); System.out.println("stored " + file.getAbsolutePath()); return data; } public void testMultipleCreates() { try { Collection rootColl = DatabaseManager.getCollection("xmldb:exist: CollectionManagementService cms = (CollectionManagementService) rootColl.getService("CollectionManagementService", "1.0"); assertNotNull(cms); cms.createCollection("dummy1"); printChildren(rootColl); Collection c1 = rootColl.getChildCollection("dummy1"); assertNotNull(c1); cms.setCollection(c1); cms.createCollection("dummy2"); Collection c2 = c1.getChildCollection("dummy2"); assertNotNull(c2); cms.setCollection(c2); cms.createCollection("dummy3"); Collection c3 = c2.getChildCollection("dummy3"); assertNotNull(c3); cms.setCollection(rootColl); cms.removeCollection("dummy1"); printChildren(rootColl); c1 = rootColl.getChildCollection("dummy1"); assertNull(c1); } catch(Exception e) { e.printStackTrace(); fail(e.getMessage()); } } private static void printChildren(Collection c) throws XMLDBException { System.out.print("Children of " + c.getName() + ":"); String[] names = c.listChildCollections(); for (int i = 0; i < names.length; i++) System.out.print(" " + names[i]); System.out.println(); } public static void main(String[] args) { junit.textui.TestRunner.run(CreateCollectionsTest.class); //junit.swingui.TestRunner.run(LexerTest.class); } }
package org.exist.xslt; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXTransformerFactory; import org.apache.log4j.Logger; import org.exist.storage.DBBroker; /** * Allows the TransformerFactory that is used for XSLT to be * chosen through configuration settings in conf.xml * * Within eXist this class should be used instead of * directly calling SAXTransformerFactory.newInstance() directly * * @author Adam Retter <adam.retter@devon.gov.uk> */ public class TransformerFactoryAllocator { /* * problem is that even when a Xalan is defined in conf.xml, if Saxon JAR's * are on the classpath then when we create a Xalan TransformerFactory and * newInstance() is called on it, it returns a Saxon TransformerFactory :-( */ private final static Logger LOG = Logger.getLogger(TransformerFactoryAllocator.class); //private constructor private TransformerFactoryAllocator() { } /** * Get the TransformerFactory defined in conf.xml * If the class can't be found or the given class doesn't implement * the required interface, the default factory is returned. * * @param broker A database broker, used for reading the conf.xml configuration * * @return A SAXTransformerFactory, for which newInstance() can then be called * * * Typical usage: * * Instead of SAXTransformerFactory.newInstance() use * TransformerFactoryAllocator.getTransformerFactory(broker).newInstance() */ public static SAXTransformerFactory getTransformerFactory(DBBroker broker) { SAXTransformerFactory factory; //get the transformer class name from conf.xml String transformerFactoryClassName = (String)broker.getConfiguration().getProperty("transformer.class"); LOG.debug("transformerFactoryClassName=" + transformerFactoryClassName); LOG.debug("javax.xml.transform.TransformerFactory=" + System.getProperty("javax.xml.transform.TransformerFactory")); //was a TransformerFactory class specified if(transformerFactoryClassName == null) { //no, use the system default factory = (SAXTransformerFactory)TransformerFactory.newInstance(); } else { //try and load the specified TransformerFactory class try { factory = (SAXTransformerFactory) Class.forName(transformerFactoryClassName).newInstance(); } catch(ClassNotFoundException cnfe) { LOG.debug("Cannot find the requested TrAX factory '" + transformerFactoryClassName + "'. Using default TrAX Transformer Factory instead." ); //fallback to system default factory = (SAXTransformerFactory)TransformerFactory.newInstance(); } catch(ClassCastException cce) { LOG.debug( "The indicated class '" + transformerFactoryClassName + "' is not a TrAX Transformer Factory. " +"Using default TrAX Transformer Factory instead." ); //fallback to system default factory = (SAXTransformerFactory)TransformerFactory.newInstance(); } catch(Exception e) { LOG.debug( "Error found loading the requested TrAX Transformer Factory '" + transformerFactoryClassName + "'. Using default TrAX Transformer Factory instead." ); //fallback to system default factory = (SAXTransformerFactory)TransformerFactory.newInstance(); } } return factory; } }
package org.wyona.yanel.impl.resources.login; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.servlet.YanelServlet; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import javax.servlet.http.HttpServletResponse; import org.wyona.security.core.api.Identity; import org.wyona.security.core.api.User; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.params.BasicHttpParams; /** * Handle OAuth 2.0 callback */ public class OAuth2CallbackResource extends Resource implements ViewableV2 { private static Logger log = LogManager.getLogger(OAuth2CallbackResource.class); /** * @see org.wyona.yanel.core.api.attributes.ViewableV2#exists() */ public boolean exists() throws Exception { return true; } /** * @see org.wyona.yanel.core.api.attributes.ViewableV2#getSize() */ public long getSize() throws Exception { return -1; } /** * @see org.wyona.yanel.core.api.attributes.ViewableV2#getView(String) */ public View getView(String viewId) throws Exception { View view = new View(); view.setResponse(false); // this resource writes the response itself HttpServletResponse response = getEnvironment().getResponse(); try { String state = getEnvironment().getRequest().getParameter("state"); log.warn("TODO: Check state '" + state + "' ..."); if (false) { throw new Exception("Checking 'state' parameter failed!"); } String token_endpoint = getDiscoveryDocument(); String code = getEnvironment().getRequest().getParameter("code"); String id_token = getAccessAndIdToken(token_endpoint, code); if (id_token == null) { throw new Exception("Getting 'id_token' failed!"); } Payload userInfo = getPayload(id_token); String email = userInfo.getEmail(); User user = null; if (getRealm().getIdentityManager().getUserManager().existsAlias(email)) { String trueId = realm.getIdentityManager().getUserManager().getTrueId(userInfo.getEmail()); user = realm.getIdentityManager().getUserManager().getUser(trueId, true); } else { log.warn("User '" + email + "' does not exist yet, hence create account and login user ..."); user = getRealm().getIdentityManager().getUserManager().createUser(userInfo.getId(), "TODO:gmail", email, null); getRealm().getIdentityManager().getUserManager().createAlias(email, user.getID()); addUserToGroups(user); } YanelServlet.setIdentity(new Identity(user, email), getEnvironment().getRequest().getSession(true), realm); response.setHeader("Location", "en/projects/index.html"); // TODO: Make configurable response.setStatus(307); } catch(Exception e) { log.error(e.getMessage()); response.setStatus(500); } return view; } /** * Add registered user to particular groups by default * @param user User to be added to groups */ private void addUserToGroups(User user) throws Exception { // TODO: See src/resources/registration/src/java/org/wyona/yanel/resources/registration/UserRegistrationResource.java#addUserToGroups(User) String groupsCSV = getResourceConfigProperty("groups"); if (groupsCSV != null) { String[] groupIDs = null; if (groupsCSV.indexOf(",") >= 0) { groupIDs = groupsCSV.split(","); } else { groupIDs = new String[1]; groupIDs[0] = groupsCSV; } for (int i = 0; i < groupIDs.length; i++) { if (getRealm().getIdentityManager().getGroupManager().existsGroup(groupIDs[i])) { log.debug("Add user '" + user.getEmail() + "' to group: " + groupIDs[i]); getRealm().getIdentityManager().getGroupManager().getGroup(groupIDs[i]).addMember(user); } else { log.warn("No such group: " + groupIDs[i]); } } } } /** * @return URL of token endpoint */ private String getDiscoveryDocument() { return "https: } private String getAccessAndIdToken(String token_endpoint, String code) { int connectionTimeout = 2000; int socketTimeout = 25000; try { StringBuilder qs = new StringBuilder("?"); qs.append("code=" + code); qs.append("&"); qs.append("client_id=" + getResourceConfigProperty("client_id")); qs.append("&"); qs.append("client_secret=" + getResourceConfigProperty("client_secret")); qs.append("&"); qs.append("redirect_uri=" + getResourceConfigProperty("redirect_uri")); qs.append("&"); qs.append("grant_type=authorization_code"); java.net.URL url = new java.net.URL(token_endpoint); log.warn("DEBUG: Get Access and Id Token from '" + url + qs + "' ..."); DefaultHttpClient httpClient = getHttpClient(url, null, null, connectionTimeout, socketTimeout); HttpPost httpPost = new HttpPost(url.toString() + qs); //httpPost.setEntity(new StringEntity("{\"code\":\"" + code + "\",\"client_id\":\"" + getResourceConfigProperty("client_id") + "\"}", "utf-8")); HttpResponse response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { java.io.InputStream in = response.getEntity().getContent(); in.close(); log.warn("DEBUG: Response code 200 ..."); return "TODO"; } else { log.error("Response code '" + response.getStatusLine().getStatusCode() + "'"); return null; } } catch(Exception e) { log.error(e, e); return null; } } /** * Get http client using SSL if necessary and basic authentication set * @param username Username for basic authentication * @param password Password for basic authentication * @param connectionTimeout Value of CONNECTION_TIMEOUT * @param socketTimeout Value of SO_TIMEOUT * @return http client * TODO: Re-use org.wyona.yanel.core.source.HttpResolver#getHttpClient(...) */ private DefaultHttpClient getHttpClient(java.net.URL url, String username, String password, int connectionTimeout, int socketTimeout) throws Exception { HttpParams httpParams = new BasicHttpParams(); if (connectionTimeout >= 0) { HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout); } else { log.warn("No connection timeout set, hence use default value: " + HttpConnectionParams.getConnectionTimeout(httpParams)); } if (socketTimeout >= 0) { HttpConnectionParams.setSoTimeout(httpParams, socketTimeout); } else { log.warn("No socket timeout set, hence use default value: " + HttpConnectionParams.getSoTimeout(httpParams)); } String yanelVersion = org.wyona.yanel.core.Yanel.getInstance().getVersion(); HttpProtocolParams.setUserAgent(httpParams, "Yanel/" + yanelVersion + " HttpResolver"); DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); if (url.getProtocol().equals("https")) { httpClient.getConnectionManager().getSchemeRegistry().register(new org.apache.http.conn.scheme.Scheme("https", 443, getSSLFactory())); } else { log.warn("Unsecure connection: " + url); } if (username != null && password != null) { log.debug("Set BASIC AUTH for username '" + username + "'..."); httpClient.getCredentialsProvider().setCredentials(new org.apache.http.auth.AuthScope(url.getHost(), url.getPort()), new org.apache.http. auth.UsernamePasswordCredentials(username, password)); } else { log.debug("No BASIC AUTH credentials set."); } return httpClient; } /** * Get SSL factory * TODO: Re-use org.wyona.yanel.core.source.HttpResolver#getSSLFactory() */ private org.apache.http.conn.ssl.SSLSocketFactory getSSLFactory() throws Exception { // TODO: Make SSLSocketFactory configurable... // INFO: Just trust the certificate without checking/comparing a list of trusted certificates org.apache.http.conn.ssl.SSLSocketFactory factory = new org.apache.http.conn.ssl.SSLSocketFactory(new org.apache.http.conn.ssl.TrustStrategy() { public boolean isTrusted(final java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { return true; } }, org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //org.apache.http.conn.ssl.SSLSocketFactory factory = new org.apache.http.conn.ssl.SSLSocketFactory(getSSLContext(), new org.apache.http.conn.ssl.StrictHostnameVerifier()); return factory; } /** * Get user information */ private Payload getPayload(String id_token) { // TODO: Analyze JWT, e.g. get unique user Id and user email and ... see https://developers.google.com/identity/protocols/OpenIDConnect#obtainuserinfo Payload payload = new Payload("10769150350006150715113082367", "michaelwechner@gmail.com"); return payload; } /** * @see org.wyona.yanel.core.api.attributes.ViewableV2#getViewDescriptors() */ public ViewDescriptor[] getViewDescriptors() { log.warn("Not implemented!"); return null; } } class Payload { private String sub; private String email; public Payload(String sub, String email) { this.sub = sub; this.email = email; } public String getEmail() { return email; } public String getId() { return sub; } }
/* * $Id: LockssRepositoryImpl.java,v 1.44 2004-01-10 00:53:36 eaalto Exp $ */ package org.lockss.repository; import java.io.*; import java.net.*; import java.util.*; import java.net.MalformedURLException; import org.lockss.app.*; import org.lockss.daemon.*; import org.lockss.plugin.*; import org.lockss.util.*; import org.apache.commons.collections.LRUMap; import org.apache.commons.collections.ReferenceMap; /** * LockssRepository is used to organize the urls being cached. * It keeps a memory cache of the most recently used nodes as a * least-recently-used map, and also caches weak references to the instances * as they're doled out. This ensures that two instances of the same node are * never created, as the weak references only disappear when the object is * finalized (they go to null when the last hard reference is gone, then are * removed from the cache on finalize()). */ public class LockssRepositoryImpl extends BaseLockssManager implements LockssRepository { /** * Configuration parameter name for Lockss cache location. */ public static final String PARAM_CACHE_LOCATION = Configuration.PREFIX + "cache.location"; /** * Name of top directory in which the urls are cached. */ public static final String CACHE_ROOT_NAME = "cache"; // needed only for unit tests static String cacheLocation = null; // used for name mapping static HashMap nameMap = null; // starts with a '#' so no possibility of clashing with a URL static final String AU_ID_FILE = "#au_id_file"; static final String AU_ID_PROP = "au.id"; static final String PLUGIN_ID_PROP = "plugin.id"; static String lastPluginDir = ""+(char)('a'-1); /** * Maximum number of node instances to cache. */ public static final int MAX_LRUMAP_SIZE = 12; // this contains a '#' so that it's not defeatable by strings which // match the prefix in a url (like '../tmp/') private static final String TEST_PREFIX = "/#tmp"; private String rootLocation; private LRUMap nodeCache; private ReferenceMap refMap; private int cacheHits = 0; private int cacheMisses = 0; private int refHits = 0; private int refMisses = 0; private static Logger logger = Logger.getLogger("LockssRepository"); LockssRepositoryImpl(String rootPath) { rootLocation = rootPath; if (!rootLocation.endsWith(File.separator)) { // this shouldn't happen rootLocation += File.separator; } nodeCache = new LRUMap(MAX_LRUMAP_SIZE); refMap = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.WEAK); } public void stopService() { // mainly important in testing to blank this lastPluginDir = ""+(char)('a'-1); nameMap = null; } protected void setConfig(Configuration config, Configuration oldConfig, Set changedKeys) { // at some point we'll have to respond to changes in the available disk // space list } /** Called between initService() and startService(), then whenever the * AU's config changes. * @param auConfig the new configuration */ public void setAuConfig(Configuration auConfig) { } public RepositoryNode getNode(String url) throws MalformedURLException { return getNode(url, false); } public RepositoryNode createNewNode(String url) throws MalformedURLException { return getNode(url, true); } public void deleteNode(String url) throws MalformedURLException { RepositoryNode node = getNode(url, false); if (node!=null) { node.markAsDeleted(); } } public void deactivateNode(String url) throws MalformedURLException { RepositoryNode node = getNode(url, false); if (node!=null) { node.deactivateContent(); } } public int cusCompare(CachedUrlSet cus1, CachedUrlSet cus2) { // check that they're in the same AU if (!cus1.getArchivalUnit().equals(cus2.getArchivalUnit())) { return LockssRepository.NO_RELATION; } CachedUrlSetSpec spec1 = cus1.getSpec(); CachedUrlSetSpec spec2 = cus2.getSpec(); String url1 = cus1.getUrl(); String url2 = cus2.getUrl(); // check for top-level urls if (spec1.isAu() || spec2.isAu()) { if (spec1.equals(spec2)) { return LockssRepository.SAME_LEVEL_OVERLAP; } else if (spec1.isAu()) { return LockssRepository.ABOVE; } else { return LockssRepository.BELOW; } } if (!url1.endsWith(UrlUtil.URL_PATH_SEPARATOR)) { url1 += UrlUtil.URL_PATH_SEPARATOR; } if (!url2.endsWith(UrlUtil.URL_PATH_SEPARATOR)) { url2 += UrlUtil.URL_PATH_SEPARATOR; } if (url1.equals(url2)) { //the urls are on the same level; check for overlap if (spec1.isDisjoint(spec2)) { return LockssRepository.SAME_LEVEL_NO_OVERLAP; } else { return LockssRepository.SAME_LEVEL_OVERLAP; } } else if (url1.startsWith(url2)) { // url1 is a sub-directory of url2 if (spec2.isSingleNode()) { return LockssRepository.SAME_LEVEL_NO_OVERLAP; } else if (cus2.containsUrl(url1)) { // child return LockssRepository.BELOW; } else { // cus2 probably has a range which excludes url1 return LockssRepository.NO_RELATION; } } else if (url2.startsWith(url1)) { // url2 is a sub-directory of url1 if (spec1.isSingleNode()) { return LockssRepository.SAME_LEVEL_NO_OVERLAP; } else if (cus1.containsUrl(url2)) { // parent return LockssRepository.ABOVE; } else { // cus1 probably has a range which excludes url2 return LockssRepository.NO_RELATION; } } else { // no connection between the two urls return LockssRepository.NO_RELATION; } } private synchronized RepositoryNode getNode(String url, boolean create) throws MalformedURLException { String urlKey; boolean isAuUrl = false; if (AuUrl.isAuUrl(url)) { urlKey = AuUrl.PROTOCOL; isAuUrl = true; } else { try { URL testUrl = new URL(url); String path = testUrl.getPath(); if (path.indexOf("/.")>=0) { if (FileUtil.isLegalPath(path)) { // canonicalize to remove urls including '..' and '.' path = TEST_PREFIX + path; File testFile = new File(path); String canonPath = testFile.getCanonicalPath(); String sysDepPrefix = FileUtil.sysDepPath(TEST_PREFIX); int pathIndex = canonPath.indexOf(sysDepPrefix) + sysDepPrefix.length(); urlKey = testUrl.getProtocol() + ": testUrl.getHost().toLowerCase() + FileUtil.sysIndepPath(canonPath.substring(pathIndex)); } else { logger.error("Illegal URL detected: "+url); throw new MalformedURLException("Illegal URL detected."); } url = urlKey; } else { // clean path, no testing needed urlKey = url; } } catch (IOException ie) { logger.error("Error testing URL: "+ie); throw new MalformedURLException ("Error testing URL."); } } // check LRUMap cache for node RepositoryNode node = (RepositoryNode)nodeCache.get(urlKey); if (node!=null) { cacheHits++; return node; } else { cacheMisses++; } // check weak reference map for node node = (RepositoryNode)refMap.get(urlKey); if (node!=null) { refHits++; nodeCache.put(urlKey, node); return node; } else { refMisses++; } String nodeLocation; if (isAuUrl) { // base directory of ArchivalUnit nodeLocation = rootLocation; node = new AuNodeImpl(url, nodeLocation, this); } else { nodeLocation = LockssRepositoryImpl.mapUrlToFileLocation(rootLocation, url); node = new RepositoryNodeImpl(url, nodeLocation, this); } if (!create) { // if not creating, check for existence File nodeDir = new File(nodeLocation); if (!nodeDir.exists()) { return null; } if (!nodeDir.isDirectory()) { logger.error("Cache file not a directory: "+nodeLocation); throw new LockssRepository.RepositoryStateException("Invalid cache file."); } } // add to node cache and weak reference cache nodeCache.put(urlKey, node); refMap.put(urlKey, node); return node; } int getCacheHits() { return cacheHits; } int getCacheMisses() { return cacheMisses; } int getRefHits() { return refHits; } int getRefMisses() { return refMisses; } void consistencyCheck(RepositoryNodeImpl node) { logger.warning("Inconsistent node state found; node content deactivated."); if (!node.cacheLocationFile.exists()) { node.cacheLocationFile.mkdirs(); } // manually deactivate node.deactivateContent(); } // static calls /** * Factory method to create new LockssRepository instances. * @param au the {@link ArchivalUnit} * @return the new LockssRepository instance */ public static LockssRepository createNewLockssRepository(ArchivalUnit au) { // XXX needs to handle multiple disks/repository locations cacheLocation = Configuration.getParam(PARAM_CACHE_LOCATION); if (cacheLocation == null) { logger.error("Couldn't get " + PARAM_CACHE_LOCATION + " from Configuration"); throw new LockssRepository.RepositoryStateException( "Couldn't load param."); } cacheLocation = extendCacheLocation(cacheLocation); return new LockssRepositoryImpl( LockssRepositoryImpl.mapAuToFileLocation(cacheLocation, au)); } static String extendCacheLocation(String cacheDir) { StringBuffer buffer = new StringBuffer(cacheDir); if (!cacheDir.endsWith(File.separator)) { buffer.append(File.separator); } buffer.append(CACHE_ROOT_NAME); buffer.append(File.separator); return buffer.toString(); } /** * mapAuToFileLocation() is the method used to resolve {@link ArchivalUnit}s * into directory names. This maps a given au to directories, using the * cache root as the base. Given an au with PluginId of 'plugin' and AuId * of 'au', it would return the string '<rootLocation>/plugin/au/'. * @param rootLocation the root for all ArchivalUnits * @param au the ArchivalUnit to resolve * @return the directory location */ public static String mapAuToFileLocation(String rootLocation, ArchivalUnit au) { StringBuffer buffer = new StringBuffer(rootLocation); if (!rootLocation.endsWith(File.separator)) { buffer.append(File.separator); } getAuDir(au, buffer); buffer.append(File.separator); return buffer.toString(); } public static String mapUrlToFileLocation(String rootLocation, String urlStr) throws MalformedURLException { int totalLength = rootLocation.length() + urlStr.length(); URL url = new URL(urlStr); StringBuffer buffer = new StringBuffer(totalLength); buffer.append(rootLocation); if (!rootLocation.endsWith(File.separator)) { buffer.append(File.separator); } buffer.append(url.getHost().toLowerCase()); buffer.append(File.separator); buffer.append(url.getProtocol()); buffer.append(StringUtil.replaceString(url.getPath(), "/", File.separator)); return buffer.toString(); } // name mapping functions static void getAuDir(ArchivalUnit au, StringBuffer buffer) { if (nameMap == null) { loadNameMap(buffer.toString()); } String auKey = getAuKey(au); String auDir = (String)nameMap.get(auKey); if (auDir == null) { logger.debug3("Creating new au directory for '" + auKey + "'."); while (true) { auDir = getNewPluginDir(); File testDir = new File(buffer.toString() + auDir); if (!testDir.exists()) { break; } else { logger.debug3("Existing directory found at '"+auDir+ "'. Creating another..."); } } logger.debug3("New au directory: "+auDir); nameMap.put(auKey, auDir); String auLocation = buffer.toString() + auDir; Properties idProps = new Properties(); idProps.setProperty(AU_ID_PROP, au.getAuId()); saveAuIdProperties(auLocation, idProps); } buffer.append(auDir); } static void loadNameMap(String rootLocation) { logger.debug3("Loading name map for '" + rootLocation + "'."); nameMap = new HashMap(); File rootFile = new File(rootLocation); if (!rootFile.exists()) { rootFile.mkdirs(); logger.debug3("Creating root directory at '" + rootLocation + "'."); return; } File[] pluginAus = rootFile.listFiles(); for (int ii = 0; ii < pluginAus.length; ii++) { String dirName = pluginAus[ii].getName(); if (dirName.compareTo(lastPluginDir) == 1) { lastPluginDir = dirName; } Properties idProps = getAuIdProperties(pluginAus[ii].getAbsolutePath()); if (idProps==null) { // if no properties were found, just continue continue; } nameMap.put(idProps.getProperty(AU_ID_PROP), dirName); } } static String getNewPluginDir() { String newPluginDir = ""; boolean charChanged = false; // go through and increment the first non-'z' char for (int ii=lastPluginDir.length()-1; ii>=0; ii char curChar = lastPluginDir.charAt(ii); if (!charChanged) { if (curChar < 'z') { curChar++; charChanged = true; newPluginDir = curChar + newPluginDir; } else { newPluginDir += 'a'; } } else { newPluginDir = curChar + newPluginDir; } } if (!charChanged) { newPluginDir += 'a'; } lastPluginDir = newPluginDir; return newPluginDir; } static Properties getAuIdProperties(String location) { File propFile = new File(location + File.separator + AU_ID_FILE); try { InputStream is = new BufferedInputStream(new FileInputStream(propFile)); Properties idProps = new Properties(); idProps.load(is); is.close(); return idProps; } catch (Exception e) { logger.warning("Error loading au id from " + propFile.getPath() + "."); return null; } } static void saveAuIdProperties(String location, Properties props) { File propDir = new File(location); if (!propDir.exists()) { logger.debug("Creating directory '"+propDir.getAbsolutePath()+"'"); propDir.mkdirs(); } File propFile = new File(propDir, AU_ID_FILE); try { logger.debug3("Saving au id properties at '" + location + "'."); OutputStream os = new BufferedOutputStream(new FileOutputStream(propFile)); props.store(os, "ArchivalUnit id info"); os.close(); propFile.setReadOnly(); } catch (IOException ioe) { logger.error("Couldn't write properties for " + propFile.getPath() + ".", ioe); throw new LockssRepository.RepositoryStateException( "Couldn't write au id properties file."); } } static String getAuKey(ArchivalUnit au) { return au.getAuId(); } public static class Factory implements LockssAuManager.Factory { public LockssAuManager createAuManager(ArchivalUnit au) { return createNewLockssRepository(au); } } }
package org.lwjgl.opengl.swt; import java.nio.IntBuffer; import java.util.HashSet; import java.util.Set; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.ARBMultisample; import org.lwjgl.opengl.ARBRobustness; import org.lwjgl.opengl.GL; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL32; import org.lwjgl.opengl.GL43; import org.lwjgl.opengl.NVMultisampleCoverage; import org.lwjgl.opengl.WGL; import org.lwjgl.opengl.WGLARBContextFlushControl; import org.lwjgl.opengl.WGLARBCreateContext; import org.lwjgl.opengl.WGLARBCreateContextProfile; import org.lwjgl.opengl.WGLARBCreateContextRobustness; import org.lwjgl.opengl.WGLARBMultisample; import org.lwjgl.opengl.WGLARBPixelFormat; import org.lwjgl.opengl.WGLARBPixelFormatFloat; import org.lwjgl.opengl.WGLARBRobustnessApplicationIsolation; import org.lwjgl.opengl.WGLEXTCreateContextES2Profile; import org.lwjgl.opengl.WGLEXTFramebufferSRGB; import org.lwjgl.opengl.WGLNVMultisampleCoverage; import org.lwjgl.opengl.swt.GLData.API; import org.lwjgl.opengl.swt.GLData.Profile; import org.lwjgl.opengl.swt.GLData.ReleaseBehavior; import org.lwjgl.system.APIUtil; import org.lwjgl.system.APIUtil.APIVersion; import org.lwjgl.system.Checks; import org.lwjgl.system.JNI; import org.lwjgl.system.MemoryUtil; import org.lwjgl.system.windows.GDI32; import org.lwjgl.system.windows.PIXELFORMATDESCRIPTOR; import org.lwjgl.system.windows.User32; /** * Windows-specific implementation of methods for GLCanvas. * * @author Kai Burjack */ class PlatformWin32GLCanvas implements PlatformGLCanvas { private static final String USE_OWNDC_KEY = "org.eclipse.swt.internal.win32.useOwnDC"; private long wglDelayBeforeSwapNVAddr = 0L; private boolean wglDelayBeforeSwapNVAddr_set = false; private static boolean atLeast32(int major, int minor) { return major == 3 && minor >= 2 || major > 3; } private static boolean atLeast30(int major, int minor) { return major == 3 && minor >= 0 || major > 3; } private static boolean validVersionGL(int major, int minor) { return (major == 0 && minor == 0) || // unspecified gets highest supported version on Nvidia (major >= 1 && minor >= 0) && (major != 1 || minor <= 5) && (major != 2 || minor <= 1) && (major != 3 || minor <= 3) && (major != 4 || minor <= 5); } private static boolean validVersionGLES(int major, int minor) { return (major == 0 && minor == 0) || // unspecified gets 1.1 on Nvidia (major >= 1 && minor >= 0) && (major != 1 || minor <= 1) && (major != 2 || minor <= 0); } /** * Validate the given {@link GLData} and throw an exception on validation error. * * @param attribs * the {@link GLData} to validate */ public static void validateAttributes(GLData attribs) { if (attribs.alphaSize < 0) { throw new IllegalArgumentException("Alpha bits cannot be less than 0"); } if (attribs.redSize < 0) { throw new IllegalArgumentException("Red bits cannot be less than 0"); } if (attribs.greenSize < 0) { throw new IllegalArgumentException("Green bits cannot be less than 0"); } if (attribs.blueSize < 0) { throw new IllegalArgumentException("Blue bits cannot be less than 0"); } if (attribs.stencilSize < 0) { throw new IllegalArgumentException("Stencil bits cannot be less than 0"); } if (attribs.depthSize < 0) { throw new IllegalArgumentException("Depth bits cannot be less than 0"); } if (attribs.forwardCompatible && !atLeast30(attribs.majorVersion, attribs.minorVersion)) { throw new IllegalArgumentException("Forward-compatibility is only defined for OpenGL version 3.0 and above"); } if (attribs.samples < 0) { throw new IllegalArgumentException("Invalid samples count"); } if (attribs.profile != null && !atLeast32(attribs.majorVersion, attribs.minorVersion)) { throw new IllegalArgumentException("Context profiles are only defined for OpenGL version 3.2 and above"); } if (attribs.api == null) { throw new IllegalArgumentException("Unspecified client API"); } if (attribs.api == API.GL && !validVersionGL(attribs.majorVersion, attribs.minorVersion)) { throw new IllegalArgumentException("Invalid OpenGL version"); } if (attribs.api == API.GLES && !validVersionGLES(attribs.majorVersion, attribs.minorVersion)) { throw new IllegalArgumentException("Invalid OpenGL ES version"); } if (!attribs.doubleBuffer && attribs.swapInterval != null) { throw new IllegalArgumentException("Swap interval set but not using double buffering"); } if (attribs.colorSamplesNV < 0) { throw new IllegalArgumentException("Invalid color samples count"); } if (attribs.colorSamplesNV > attribs.samples) { throw new IllegalArgumentException("Color samples greater than number of (coverage) samples"); } if (attribs.swapGroupNV < 0) { throw new IllegalArgumentException("Invalid swap group"); } if (attribs.swapBarrierNV < 0) { throw new IllegalArgumentException("Invalid swap barrier"); } if ((attribs.swapGroupNV > 0 || attribs.swapBarrierNV > 0) && !attribs.doubleBuffer) { throw new IllegalArgumentException("Swap group or barrier requested but not using double buffering"); } if (attribs.swapBarrierNV > 0 && attribs.swapGroupNV == 0) { throw new IllegalArgumentException("Swap barrier requested but no valid swap group set"); } if (attribs.loseContextOnReset && !attribs.robustness) { throw new IllegalArgumentException("Lose context notification requested but not using robustness"); } if (attribs.contextResetIsolation && !attribs.robustness) { throw new IllegalArgumentException("Context reset isolation requested but not using robustness"); } } /** * Encode the pixel format attributes stored in the given {@link GLData} into the given {@link IntBuffer} for wglChoosePixelFormatARB to * consume. */ private void encodePixelFormatAttribs(IntBuffer ib, GLData attribs) { ib.put(WGLARBPixelFormat.WGL_DRAW_TO_WINDOW_ARB).put(1); ib.put(WGLARBPixelFormat.WGL_SUPPORT_OPENGL_ARB).put(1); ib.put(WGLARBPixelFormat.WGL_ACCELERATION_ARB).put(WGLARBPixelFormat.WGL_FULL_ACCELERATION_ARB); if (attribs.doubleBuffer) ib.put(WGLARBPixelFormat.WGL_DOUBLE_BUFFER_ARB).put(1); if (attribs.pixelFormatFloat) ib.put(WGLARBPixelFormat.WGL_PIXEL_TYPE_ARB).put(WGLARBPixelFormatFloat.WGL_TYPE_RGBA_FLOAT_ARB); else ib.put(WGLARBPixelFormat.WGL_PIXEL_TYPE_ARB).put(WGLARBPixelFormat.WGL_TYPE_RGBA_ARB); if (attribs.redSize > 0) ib.put(WGLARBPixelFormat.WGL_RED_BITS_ARB).put(attribs.redSize); if (attribs.greenSize > 0) ib.put(WGLARBPixelFormat.WGL_GREEN_BITS_ARB).put(attribs.greenSize); if (attribs.blueSize > 0) ib.put(WGLARBPixelFormat.WGL_BLUE_BITS_ARB).put(attribs.blueSize); if (attribs.alphaSize > 0) ib.put(WGLARBPixelFormat.WGL_ALPHA_BITS_ARB).put(attribs.alphaSize); if (attribs.depthSize > 0) ib.put(WGLARBPixelFormat.WGL_DEPTH_BITS_ARB).put(attribs.depthSize); if (attribs.stencilSize > 0) ib.put(WGLARBPixelFormat.WGL_STENCIL_BITS_ARB).put(attribs.stencilSize); if (attribs.accumRedSize > 0) ib.put(WGLARBPixelFormat.WGL_ACCUM_RED_BITS_ARB).put(attribs.accumRedSize); if (attribs.accumGreenSize > 0) ib.put(WGLARBPixelFormat.WGL_ACCUM_GREEN_BITS_ARB).put(attribs.accumGreenSize); if (attribs.accumBlueSize > 0) ib.put(WGLARBPixelFormat.WGL_ACCUM_BLUE_BITS_ARB).put(attribs.accumBlueSize); if (attribs.accumAlphaSize > 0) ib.put(WGLARBPixelFormat.WGL_ACCUM_ALPHA_BITS_ARB).put(attribs.accumAlphaSize); if (attribs.accumRedSize > 0 || attribs.accumGreenSize > 0 || attribs.accumBlueSize > 0 || attribs.accumAlphaSize > 0) ib.put(WGLARBPixelFormat.WGL_ACCUM_BITS_ARB).put(attribs.accumRedSize + attribs.accumGreenSize + attribs.accumBlueSize + attribs.accumAlphaSize); if (attribs.sRGB) ib.put(WGLEXTFramebufferSRGB.WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT).put(1); if (attribs.samples > 0) { ib.put(WGLARBMultisample.WGL_SAMPLE_BUFFERS_ARB).put(1); ib.put(WGLARBMultisample.WGL_SAMPLES_ARB).put(attribs.samples); if (attribs.colorSamplesNV > 0) { ib.put(WGLNVMultisampleCoverage.WGL_COLOR_SAMPLES_NV).put(attribs.colorSamplesNV); } } ib.put(0); } public int checkStyle(Composite parent, int style) { // Somehow we need to temporarily set 'org.eclipse.swt.internal.win32.useOwnDC' // to true or else context creation on Windows fails... if (parent != null) { if (!org.eclipse.swt.internal.win32.OS.IsWinCE && org.eclipse.swt.internal.win32.OS.WIN32_VERSION >= org.eclipse.swt.internal.win32.OS.VERSION(6, 0)) { parent.getDisplay().setData(USE_OWNDC_KEY, Boolean.TRUE); } } return style; } public void resetStyle(Composite parent) { parent.getDisplay().setData(USE_OWNDC_KEY, Boolean.FALSE); } public long create(GLCanvas canvas, GLData attribs, GLData effective) { Canvas dummycanvas = new Canvas(canvas.getParent(), checkStyle(canvas.getParent(), canvas.getStyle())); long context = 0L; try { context = create(canvas.handle, dummycanvas.handle, attribs, effective); } catch (SWTException e) { SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH, e); } final long finalContext = context; dummycanvas.dispose(); Listener listener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.Dispose: deleteContext(finalContext); break; } } }; canvas.addListener(SWT.Dispose, listener); return context; } private long create(long windowHandle, long dummyWindowHandle, GLData attribs, GLData effective) throws SWTException { // Validate context attributes validateAttributes(attribs); // Find this exact pixel format, though for now without multisampling. This comes later! PIXELFORMATDESCRIPTOR pfd = PIXELFORMATDESCRIPTOR.create(); pfd.nSize((short) PIXELFORMATDESCRIPTOR.SIZEOF); pfd.nVersion((short) 1); // this should always be 1 pfd.dwLayerMask(GDI32.PFD_MAIN_PLANE); pfd.iPixelType(GDI32.PFD_TYPE_RGBA); int flags = GDI32.PFD_DRAW_TO_WINDOW | GDI32.PFD_SUPPORT_OPENGL; if (attribs.doubleBuffer) flags |= GDI32.PFD_DOUBLEBUFFER; if (attribs.stereo) flags |= GDI32.PFD_STEREO; pfd.dwFlags(flags); pfd.cRedBits((byte) attribs.redSize); pfd.cGreenBits((byte) attribs.greenSize); pfd.cBlueBits((byte) attribs.blueSize); pfd.cAlphaBits((byte) attribs.alphaSize); pfd.cDepthBits((byte) attribs.depthSize); pfd.cStencilBits((byte) attribs.stencilSize); pfd.cAccumRedBits((byte) attribs.accumRedSize); pfd.cAccumGreenBits((byte) attribs.accumGreenSize); pfd.cAccumBlueBits((byte) attribs.accumBlueSize); pfd.cAccumAlphaBits((byte) attribs.accumAlphaSize); pfd.cAccumBits((byte) (attribs.accumRedSize + attribs.accumGreenSize + attribs.accumBlueSize + attribs.accumAlphaSize)); long hDCdummy = User32.GetDC(dummyWindowHandle); int pixelFormat = GDI32.ChoosePixelFormat(hDCdummy, pfd); if (pixelFormat == 0 || !GDI32.SetPixelFormat(hDCdummy, pixelFormat, pfd)) { // Pixel format unsupported User32.ReleaseDC(dummyWindowHandle, hDCdummy); throw new SWTException("Unsupported pixel format"); } /* * Next, create a dummy context using Opengl32.lib's wglCreateContext. This should ALWAYS work, but won't give us a "new"/"core" context if we requested * that and also does not support multisampling. But we use this "dummy" context then to request the required WGL function pointers to create a new * OpenGL >= 3.0 context and with optional multisampling. */ long dummyContext = WGL.wglCreateContext(hDCdummy); if (dummyContext == 0L) { User32.ReleaseDC(dummyWindowHandle, hDCdummy); throw new SWTException("Failed to create OpenGL context"); } final APIBuffer buffer = new APIBuffer(); // Save current context to restore it later final long currentContext = WGL.wglGetCurrentContext(); final long currentDc = WGL.wglGetCurrentDC(); // Make the new dummy context current boolean success = WGL.wglMakeCurrent(hDCdummy, dummyContext); if (!success) { User32.ReleaseDC(dummyWindowHandle, hDCdummy); WGL.wglDeleteContext(dummyContext); throw new SWTException("Failed to make OpenGL context current"); } // Query supported WGL extensions String wglExtensions = null; long wglGetExtensionsStringARBAddr = WGL.wglGetProcAddress("wglGetExtensionsStringARB"); if (wglGetExtensionsStringARBAddr != 0L) { long str = JNI.callPP(wglGetExtensionsStringARBAddr, hDCdummy); if (str != 0L) { wglExtensions = MemoryUtil.memASCII(str); } else { wglExtensions = ""; } } else { // Try the EXT extension long wglGetExtensionsStringEXTAddr = WGL.wglGetProcAddress("wglGetExtensionsStringEXT"); if (wglGetExtensionsStringEXTAddr != 0L) { long str = JNI.callP(wglGetExtensionsStringEXTAddr); if (str != 0L) { wglExtensions = MemoryUtil.memASCII(str); } else { wglExtensions = ""; } } else { wglExtensions = ""; } } String[] splitted = wglExtensions.split(" "); Set<String> wglExtensionsList = new HashSet<String>(splitted.length); for (String str : splitted) { wglExtensionsList.add(str); } success = User32.ReleaseDC(dummyWindowHandle, hDCdummy); if (!success) { WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Could not release dummy DC"); } // For some constellations of context attributes, we can stop right here. if (!atLeast30(attribs.majorVersion, attribs.minorVersion) && attribs.samples == 0 && !attribs.sRGB && !attribs.pixelFormatFloat && attribs.contextReleaseBehavior == null && !attribs.robustness && attribs.api != API.GLES) { /* Finally, create the real context on the real window */ long hDC = User32.GetDC(windowHandle); GDI32.SetPixelFormat(hDC, pixelFormat, pfd); success = WGL.wglDeleteContext(dummyContext); if (!success) { WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Could not delete dummy GL context"); } long context = WGL.wglCreateContext(hDC); if (attribs.swapInterval != null) { boolean has_WGL_EXT_swap_control = wglExtensionsList.contains("WGL_EXT_swap_control"); if (!has_WGL_EXT_swap_control) { User32.ReleaseDC(windowHandle, hDC); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Swap interval requested but WGL_EXT_swap_control is unavailable"); } if (attribs.swapInterval < 0) { // Only allowed if WGL_EXT_swap_control_tear is available boolean has_WGL_EXT_swap_control_tear = wglExtensionsList.contains("WGL_EXT_swap_control_tear"); if (!has_WGL_EXT_swap_control_tear) { User32.ReleaseDC(windowHandle, hDC); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Negative swap interval requested but WGL_EXT_swap_control_tear is unavailable"); } } // Make context current to set the swap interval success = WGL.wglMakeCurrent(hDC, context); if (!success) { User32.ReleaseDC(windowHandle, hDC); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Could not make GL context current"); } long wglSwapIntervalEXTAddr = WGL.wglGetProcAddress("wglSwapIntervalEXT"); if (wglSwapIntervalEXTAddr != 0L) { JNI.callI(wglSwapIntervalEXTAddr, attribs.swapInterval); } } if (attribs.swapGroupNV > 0 || attribs.swapBarrierNV > 0) { // Only allowed if WGL_NV_swap_group is available boolean has_WGL_NV_swap_group = wglExtensionsList.contains("WGL_NV_swap_group"); if (!has_WGL_NV_swap_group) { User32.ReleaseDC(windowHandle, hDC); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Swap group or barrier requested but WGL_NV_swap_group is unavailable"); } // Make context current to join swap group and/or barrier success = WGL.wglMakeCurrent(hDC, context); try { wglNvSwapGroupAndBarrier(attribs, buffer, buffer.address(), hDC); } catch (SWTException e) { User32.ReleaseDC(windowHandle, hDC); WGL.wglMakeCurrent(currentDc, currentContext); throw e; } } success = User32.ReleaseDC(windowHandle, hDC); if (!success) { WGL.wglMakeCurrent(currentDc, currentContext); WGL.wglDeleteContext(context); throw new SWTException("Could not release DC"); } /* Check if we want to share context */ if (attribs.shareContext != null) { success = WGL.wglShareLists(context, attribs.shareContext.context); if (!success) { WGL.wglMakeCurrent(currentDc, currentContext); WGL.wglDeleteContext(context); throw new SWTException("Failed while configuring context sharing."); } } // Describe pixel format int pixFmtIndex = GDI32.DescribePixelFormat(hDC, pixelFormat, pfd); if (pixFmtIndex == 0) { WGL.wglMakeCurrent(currentDc, currentContext); WGL.wglDeleteContext(context); throw new SWTException("Failed to describe pixel format."); } effective.redSize = pfd.cRedBits(); effective.greenSize = pfd.cGreenBits(); effective.blueSize = pfd.cBlueBits(); effective.alphaSize = pfd.cAlphaBits(); effective.depthSize = pfd.cDepthBits(); effective.stencilSize = pfd.cStencilBits(); int pixelFormatFlags = pfd.dwFlags(); effective.doubleBuffer = (pixelFormatFlags & GDI32.PFD_DOUBLEBUFFER) != 0; effective.stereo = (pixelFormatFlags & GDI32.PFD_STEREO) != 0; effective.accumRedSize = pfd.cAccumRedBits(); effective.accumGreenSize = pfd.cAccumGreenBits(); effective.accumBlueSize = pfd.cAccumBlueBits(); effective.accumAlphaSize = pfd.cAccumAlphaBits(); // Restore old context WGL.wglMakeCurrent(currentDc, currentContext); return context; } // Check for WGL_ARB_create_context support if (!wglExtensionsList.contains("WGL_ARB_create_context")) { WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Extended context attributes requested but WGL_ARB_create_context is unavailable"); } // Obtain wglCreateContextAttribsARB function pointer long wglCreateContextAttribsARBAddr = WGL.wglGetProcAddress("wglCreateContextAttribsARB"); if (wglCreateContextAttribsARBAddr == 0L) { WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("WGL_ARB_create_context available but wglCreateContextAttribsARB is NULL"); } IntBuffer attribList = BufferUtils.createIntBuffer(64); long attribListAddr = MemoryUtil.memAddress(attribList); long hDC = User32.GetDC(windowHandle); // Obtain wglChoosePixelFormatARB if multisampling or sRGB or floating point pixel format is requested if (attribs.samples > 0 || attribs.sRGB || attribs.pixelFormatFloat) { long wglChoosePixelFormatAddr = WGL.wglGetProcAddress("wglChoosePixelFormatARB"); if (wglChoosePixelFormatAddr == 0L) { // Try EXT function (the WGL constants are the same in both extensions) wglChoosePixelFormatAddr = WGL.wglGetProcAddress("wglChoosePixelFormatEXT"); if (wglChoosePixelFormatAddr == 0L) { User32.ReleaseDC(windowHandle, hDC); WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("No support for wglChoosePixelFormatARB/EXT. Cannot query supported pixel formats."); } } if (attribs.samples > 0) { // Check for ARB or EXT extension (their WGL constants have the same value) boolean has_WGL_ARB_multisample = wglExtensionsList.contains("WGL_ARB_multisample"); boolean has_WGL_EXT_multisample = wglExtensionsList.contains("WGL_EXT_multisample"); if (!has_WGL_ARB_multisample && !has_WGL_EXT_multisample) { User32.ReleaseDC(windowHandle, hDC); WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Multisampling requested but neither WGL_ARB_multisample nor WGL_EXT_multisample available"); } if (attribs.colorSamplesNV > 0) { boolean has_WGL_NV_multisample_coverage = wglExtensionsList.contains("WGL_NV_multisample_coverage"); if (!has_WGL_NV_multisample_coverage) { User32.ReleaseDC(windowHandle, hDC); WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Color samples requested but WGL_NV_multisample_coverage is unavailable"); } } } if (attribs.sRGB) { // Check for WGL_EXT_framebuffer_sRGB boolean has_WGL_EXT_framebuffer_sRGB = wglExtensionsList.contains("WGL_EXT_framebuffer_sRGB"); if (!has_WGL_EXT_framebuffer_sRGB) { User32.ReleaseDC(windowHandle, hDC); WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("sRGB color space requested but WGL_EXT_framebuffer_sRGB is unavailable"); } } if (attribs.pixelFormatFloat) { // Check for WGL_ARB_pixel_format_float boolean has_WGL_ARB_pixel_format_float = wglExtensionsList.contains("WGL_ARB_pixel_format_float"); if (!has_WGL_ARB_pixel_format_float) { User32.ReleaseDC(windowHandle, hDC); WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Floating-point format requested but WGL_ARB_pixel_format_float is unavailable"); } } // Query matching pixel formats encodePixelFormatAttribs(attribList, attribs); success = JNI.callPPPPPI(wglChoosePixelFormatAddr, hDC, attribListAddr, 0L, 1, buffer.address() + 4, buffer.address()) == 1; int numFormats = buffer.buffer().getInt(0); if (!success || numFormats == 0) { User32.ReleaseDC(windowHandle, hDC); WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("No supported pixel format found."); } pixelFormat = buffer.buffer().getInt(4); // Describe pixel format for the PIXELFORMATDESCRIPTOR to match the chosen format int pixFmtIndex = GDI32.DescribePixelFormat(hDC, pixelFormat, pfd); if (pixFmtIndex == 0) { User32.ReleaseDC(windowHandle, hDC); WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Failed to validate supported pixel format."); } // Obtain extended pixel format attributes long wglGetPixelFormatAttribivAddr = WGL.wglGetProcAddress("wglGetPixelFormatAttribivARB"); if (wglGetPixelFormatAttribivAddr == 0L) { // Try EXT function (function signature is the same) wglGetPixelFormatAttribivAddr = WGL.wglGetProcAddress("wglGetPixelFormatAttribivEXT"); if (wglGetPixelFormatAttribivAddr == 0L) { User32.ReleaseDC(windowHandle, hDC); WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("No support for wglGetPixelFormatAttribivARB/EXT. Cannot get effective pixel format attributes."); } } attribList.rewind(); attribList.put(WGLARBPixelFormat.WGL_DOUBLE_BUFFER_ARB); attribList.put(WGLARBPixelFormat.WGL_STEREO_ARB); attribList.put(WGLARBPixelFormat.WGL_PIXEL_TYPE_ARB); attribList.put(WGLARBPixelFormat.WGL_RED_BITS_ARB); attribList.put(WGLARBPixelFormat.WGL_GREEN_BITS_ARB); attribList.put(WGLARBPixelFormat.WGL_BLUE_BITS_ARB); attribList.put(WGLARBPixelFormat.WGL_ALPHA_BITS_ARB); attribList.put(WGLARBPixelFormat.WGL_ACCUM_RED_BITS_ARB); attribList.put(WGLARBPixelFormat.WGL_ACCUM_GREEN_BITS_ARB); attribList.put(WGLARBPixelFormat.WGL_ACCUM_BLUE_BITS_ARB); attribList.put(WGLARBPixelFormat.WGL_ACCUM_ALPHA_BITS_ARB); attribList.put(WGLARBPixelFormat.WGL_DEPTH_BITS_ARB); attribList.put(WGLARBPixelFormat.WGL_STENCIL_BITS_ARB); IntBuffer attribValues = BufferUtils.createIntBuffer(attribList.position()); long attribValuesAddr = MemoryUtil.memAddress(attribValues); success = JNI.callPPPI(wglGetPixelFormatAttribivAddr, hDC, pixelFormat, GDI32.PFD_MAIN_PLANE, attribList.position(), attribListAddr, attribValuesAddr) == 1; if (!success) { User32.ReleaseDC(windowHandle, hDC); WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Failed to get pixel format attributes."); } effective.doubleBuffer = attribValues.get(0) == 1; effective.stereo = attribValues.get(1) == 1; int pixelType = attribValues.get(2); effective.pixelFormatFloat = pixelType == WGLARBPixelFormatFloat.WGL_TYPE_RGBA_FLOAT_ARB; effective.redSize = attribValues.get(3); effective.greenSize = attribValues.get(4); effective.blueSize = attribValues.get(5); effective.alphaSize = attribValues.get(6); effective.accumRedSize = attribValues.get(7); effective.accumGreenSize = attribValues.get(8); effective.accumBlueSize = attribValues.get(9); effective.accumAlphaSize = attribValues.get(10); effective.depthSize = attribValues.get(11); effective.stencilSize = attribValues.get(12); } // Compose the attributes list attribList.rewind(); if (attribs.api == API.GL && atLeast30(attribs.majorVersion, attribs.minorVersion) || attribs.api == API.GLES && attribs.majorVersion > 0) { attribList.put(WGLARBCreateContext.WGL_CONTEXT_MAJOR_VERSION_ARB).put(attribs.majorVersion); attribList.put(WGLARBCreateContext.WGL_CONTEXT_MINOR_VERSION_ARB).put(attribs.minorVersion); } int profile = 0; if (attribs.api == API.GL) { if (attribs.profile == Profile.COMPATIBILITY) { profile = WGLARBCreateContextProfile.WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; } else if (attribs.profile == Profile.CORE) { profile = WGLARBCreateContextProfile.WGL_CONTEXT_CORE_PROFILE_BIT_ARB; } } else if (attribs.api == API.GLES) { boolean has_WGL_EXT_create_context_es2_profile = wglExtensionsList.contains("WGL_EXT_create_context_es2_profile"); if (!has_WGL_EXT_create_context_es2_profile) { User32.ReleaseDC(windowHandle, hDC); WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("OpenGL ES API requested but WGL_EXT_create_context_es2_profile is unavailable"); } profile = WGLEXTCreateContextES2Profile.WGL_CONTEXT_ES2_PROFILE_BIT_EXT; } if (profile > 0) { boolean has_WGL_ARB_create_context_profile = wglExtensionsList.contains("WGL_ARB_create_context_profile"); if (!has_WGL_ARB_create_context_profile) { User32.ReleaseDC(windowHandle, hDC); WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("OpenGL profile requested but WGL_ARB_create_context_profile is unavailable"); } attribList.put(WGLARBCreateContextProfile.WGL_CONTEXT_PROFILE_MASK_ARB).put(profile); } int contextFlags = 0; if (attribs.debug) { contextFlags |= WGLARBCreateContext.WGL_CONTEXT_DEBUG_BIT_ARB; } if (attribs.forwardCompatible) { contextFlags |= WGLARBCreateContext.WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; } if (attribs.robustness) { // Check for WGL_ARB_create_context_robustness boolean has_WGL_ARB_create_context_robustness = wglExtensions.contains("WGL_ARB_create_context_robustness"); if (!has_WGL_ARB_create_context_robustness) { User32.ReleaseDC(windowHandle, hDC); WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Context with robust buffer access requested but WGL_ARB_create_context_robustness is unavailable"); } contextFlags |= WGLARBCreateContextRobustness.WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB; if (attribs.loseContextOnReset) { attribList.put(WGLARBCreateContextRobustness.WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB).put( WGLARBCreateContextRobustness.WGL_LOSE_CONTEXT_ON_RESET_ARB); // Note: WGL_NO_RESET_NOTIFICATION_ARB is default behaviour and need not be specified. } if (attribs.contextResetIsolation) { // Check for WGL_ARB_robustness_application_isolation or WGL_ARB_robustness_share_group_isolation boolean has_WGL_ARB_robustness_application_isolation = wglExtensions.contains("WGL_ARB_robustness_application_isolation"); boolean has_WGL_ARB_robustness_share_group_isolation = wglExtensions.contains("WGL_ARB_robustness_share_group_isolation"); if (!has_WGL_ARB_robustness_application_isolation && !has_WGL_ARB_robustness_share_group_isolation) { User32.ReleaseDC(windowHandle, hDC); WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException( "Robustness isolation requested but neither WGL_ARB_robustness_application_isolation nor WGL_ARB_robustness_share_group_isolation available"); } contextFlags |= WGLARBRobustnessApplicationIsolation.WGL_CONTEXT_RESET_ISOLATION_BIT_ARB; } } if (contextFlags > 0) attribList.put(WGLARBCreateContext.WGL_CONTEXT_FLAGS_ARB).put(contextFlags); if (attribs.contextReleaseBehavior != null) { boolean has_WGL_ARB_context_flush_control = wglExtensionsList.contains("WGL_ARB_context_flush_control"); if (!has_WGL_ARB_context_flush_control) { User32.ReleaseDC(windowHandle, hDC); WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Context release behavior requested but WGL_ARB_context_flush_control is unavailable"); } if (attribs.contextReleaseBehavior == ReleaseBehavior.NONE) attribList.put(WGLARBContextFlushControl.WGL_CONTEXT_RELEASE_BEHAVIOR_ARB).put(WGLARBContextFlushControl.WGL_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB); else if (attribs.contextReleaseBehavior == ReleaseBehavior.FLUSH) attribList.put(WGLARBContextFlushControl.WGL_CONTEXT_RELEASE_BEHAVIOR_ARB) .put(WGLARBContextFlushControl.WGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB); } attribList.put(0).put(0); // Set pixelformat success = GDI32.SetPixelFormat(hDC, pixelFormat, pfd); if (!success) { User32.ReleaseDC(windowHandle, hDC); WGL.wglDeleteContext(dummyContext); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Failed to set pixel format."); } // And create new context with it long newCtx = JNI.callPPPP(wglCreateContextAttribsARBAddr, hDC, attribs.shareContext != null ? attribs.shareContext.context : 0L, attribListAddr); WGL.wglDeleteContext(dummyContext); if (newCtx == 0L) { User32.ReleaseDC(windowHandle, hDC); WGL.wglMakeCurrent(currentDc, currentContext); throw new SWTException("Failed to create OpenGL context."); } // Make context current for next operations WGL.wglMakeCurrent(hDC, newCtx); if (attribs.swapInterval != null) { boolean has_WGL_EXT_swap_control = wglExtensionsList.contains("WGL_EXT_swap_control"); if (!has_WGL_EXT_swap_control) { User32.ReleaseDC(windowHandle, hDC); WGL.wglMakeCurrent(currentDc, currentContext); WGL.wglDeleteContext(newCtx); throw new SWTException("Swap interval requested but WGL_EXT_swap_control is unavailable"); } if (attribs.swapInterval < 0) { // Only allowed if WGL_EXT_swap_control_tear is available boolean has_WGL_EXT_swap_control_tear = wglExtensionsList.contains("WGL_EXT_swap_control_tear"); if (!has_WGL_EXT_swap_control_tear) { User32.ReleaseDC(windowHandle, hDC); WGL.wglMakeCurrent(currentDc, currentContext); WGL.wglDeleteContext(newCtx); throw new SWTException("Negative swap interval requested but WGL_EXT_swap_control_tear is unavailable"); } } long wglSwapIntervalEXTAddr = WGL.wglGetProcAddress("wglSwapIntervalEXT"); if (wglSwapIntervalEXTAddr != 0L) { JNI.callI(wglSwapIntervalEXTAddr, attribs.swapInterval); } } if (attribs.swapGroupNV > 0 || attribs.swapBarrierNV > 0) { // Only allowed if WGL_NV_swap_group is available boolean has_WGL_NV_swap_group = wglExtensionsList.contains("WGL_NV_swap_group"); if (!has_WGL_NV_swap_group) { User32.ReleaseDC(windowHandle, hDC); WGL.wglMakeCurrent(currentDc, currentContext); WGL.wglDeleteContext(newCtx); throw new SWTException("Swap group or barrier requested but WGL_NV_swap_group is unavailable"); } try { wglNvSwapGroupAndBarrier(attribs, buffer, buffer.address(), hDC); } catch (SWTException e) { User32.ReleaseDC(windowHandle, hDC); WGL.wglMakeCurrent(currentDc, currentContext); WGL.wglDeleteContext(newCtx); throw e; } } User32.ReleaseDC(windowHandle, hDC); long getInteger = GL.getFunctionProvider().getFunctionAddress("glGetIntegerv"); long getString = GL.getFunctionProvider().getFunctionAddress("glGetString"); effective.api = attribs.api; if (atLeast30(attribs.majorVersion, attribs.minorVersion)) { JNI.callPV(getInteger, GL30.GL_MAJOR_VERSION, buffer.address()); effective.majorVersion = buffer.intValue(0); JNI.callPV(getInteger, GL30.GL_MINOR_VERSION, buffer.address()); effective.minorVersion = buffer.intValue(0); JNI.callPV(getInteger, GL30.GL_CONTEXT_FLAGS, buffer.address()); int effectiveContextFlags = buffer.intValue(0); effective.debug = (effectiveContextFlags & GL43.GL_CONTEXT_FLAG_DEBUG_BIT) != 0; effective.forwardCompatible = (effectiveContextFlags & GL30.GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT) != 0; effective.robustness = (effectiveContextFlags & ARBRobustness.GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB) != 0; } else if (attribs.api == API.GL) { APIVersion version = APIUtil.apiParseVersion(MemoryUtil.memUTF8(Checks.checkPointer(JNI.callP(getString, GL11.GL_VERSION)))); effective.majorVersion = version.major; effective.minorVersion = version.minor; } else if (attribs.api == API.GLES) { APIVersion version = APIUtil.apiParseVersion(MemoryUtil.memUTF8(Checks.checkPointer(JNI.callP(getString, GL11.GL_VERSION))), "OpenGL ES"); effective.majorVersion = version.major; effective.minorVersion = version.minor; } if (attribs.api == API.GL && atLeast32(effective.majorVersion, effective.minorVersion)) { JNI.callPV(getInteger, GL32.GL_CONTEXT_PROFILE_MASK, buffer.address()); int effectiveProfileMask = buffer.intValue(0); boolean core = (effectiveProfileMask & GL32.GL_CONTEXT_CORE_PROFILE_BIT) != 0; boolean comp = (effectiveProfileMask & GL32.GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0; if (comp) { effective.profile = Profile.COMPATIBILITY; } else if (core) { effective.profile = Profile.CORE; } else { effective.profile = null; } } if (attribs.samples >= 1) { JNI.callPV(getInteger, ARBMultisample.GL_SAMPLES_ARB, buffer.address()); effective.samples = buffer.intValue(0); JNI.callPV(getInteger, ARBMultisample.GL_SAMPLE_BUFFERS_ARB, buffer.address()); effective.sampleBuffers = buffer.intValue(0); boolean has_WGL_NV_multisample_coverage = wglExtensionsList.contains("WGL_NV_multisample_coverage"); if (has_WGL_NV_multisample_coverage) { JNI.callPV(getInteger, NVMultisampleCoverage.GL_COLOR_SAMPLES_NV, buffer.address()); effective.colorSamplesNV = buffer.intValue(0); } } // Restore old context WGL.wglMakeCurrent(currentDc, currentContext); return newCtx; } private void wglNvSwapGroupAndBarrier(GLData attribs, APIBuffer buffer, long bufferAddr, long hDC) throws SWTException { int success; long wglQueryMaxSwapGroupsNVAddr = WGL.wglGetProcAddress("wglQueryMaxSwapGroupsNV"); success = JNI.callPPPI(wglQueryMaxSwapGroupsNVAddr, hDC, bufferAddr, bufferAddr + 4); int maxGroups = buffer.buffer().getInt(0); if (maxGroups < attribs.swapGroupNV) { throw new SWTException("Swap group exceeds maximum group index"); } int maxBarriers = buffer.buffer().getInt(4); if (maxBarriers < attribs.swapBarrierNV) { throw new SWTException("Swap barrier exceeds maximum barrier index"); } if (attribs.swapGroupNV > 0) { long wglJoinSwapGroupNVAddr = WGL.wglGetProcAddress("wglJoinSwapGroupNV"); if (wglJoinSwapGroupNVAddr == 0L) { throw new SWTException("WGL_NV_swap_group available but wglJoinSwapGroupNV is NULL"); } success = JNI.callPI(wglJoinSwapGroupNVAddr, hDC, attribs.swapGroupNV); if (success == 0) { throw new SWTException("Failed to join swap group"); } if (attribs.swapBarrierNV > 0) { long wglBindSwapBarrierNVAddr = WGL.wglGetProcAddress("wglBindSwapBarrierNV"); if (wglBindSwapBarrierNVAddr == 0L) { throw new SWTException("WGL_NV_swap_group available but wglBindSwapBarrierNV is NULL"); } success = JNI.callI(wglBindSwapBarrierNVAddr, attribs.swapGroupNV, attribs.swapBarrierNV); if (success == 0) { throw new SWTException("Failed to bind swap barrier. Probably no G-Sync card installed."); } } } } public boolean isCurrent(long context) { long ret = WGL.wglGetCurrentContext(); return ret == context; } public boolean makeCurrent(GLCanvas canvas, long context) { long hDC = User32.GetDC(canvas.handle); boolean ret = WGL.wglMakeCurrent(hDC, context); User32.ReleaseDC(canvas.handle, hDC); return ret; } public boolean deleteContext(long context) { boolean ret = WGL.wglDeleteContext(context); return ret; } public boolean swapBuffers(GLCanvas canvas) { long hDC = User32.GetDC(canvas.handle); boolean ret = GDI32.SwapBuffers(hDC); User32.ReleaseDC(canvas.handle, hDC); return ret; } public boolean delayBeforeSwapNV(GLCanvas canvas, float seconds) { if (!wglDelayBeforeSwapNVAddr_set) { wglDelayBeforeSwapNVAddr = WGL.wglGetProcAddress("wglDelayBeforeSwapNV"); wglDelayBeforeSwapNVAddr_set = true; } if (wglDelayBeforeSwapNVAddr == 0L) { throw new UnsupportedOperationException("wglDelayBeforeSwapNV is unavailable"); } long hDC = User32.GetDC(canvas.handle); int ret = JNI.callPI(wglDelayBeforeSwapNVAddr, hDC, seconds); User32.ReleaseDC(canvas.handle, hDC); return ret == 1; } }
package collections1; import static kiss.API.*; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; public class Collections1 { void testProgram(){ int x = 0; assert x == 0; } void testHashSet() { // Showing that sets don't restore another value if there is a equal // value that is already in the set. Set<String> uniqueNames = new HashSet<String>(); uniqueNames.add("john smith"); uniqueNames.add("john smith"); println(uniqueNames); assert (uniqueNames.size() == 2) == false; assert uniqueNames.size() == 1; uniqueNames.add("john tom"); assert uniqueNames.size() == 2; uniqueNames.add("susan peak"); uniqueNames.add("John Tom"); uniqueNames.add("john tom"); assert uniqueNames.size() == 4; try(Close out = outExpect("john smith", EOL, "susan peak", EOL, "john tom", EOL, "John Tom", EOL)){ for (String uniqueName : uniqueNames){ println(uniqueName); } } } void testTreeSet(){ Set<Integer> numbers = new TreeSet<Integer>(); numbers.add(1); numbers.add(1); numbers.add(2); numbers.add(7); numbers.add(0); assert numbers.size() == 4; numbers.add(10); numbers.add(1); numbers.remove(1); assert numbers.size() == 4; try(Close out = outExpect(0, EOL, 2, EOL, 7, EOL, 10, EOL)){ for(Integer number : numbers) println(number); } } }
package org.ojalgo.matrix.decomposition; import java.math.BigDecimal; import org.ojalgo.access.Access2D; import org.ojalgo.access.Structure2D; import org.ojalgo.array.Array1D; import org.ojalgo.array.BasicArray; import org.ojalgo.matrix.MatrixUtils; import org.ojalgo.matrix.store.MatrixStore; import org.ojalgo.scalar.ComplexNumber; /** * [A] = [V][D][V]<sup>-1</sup> ([A][V] = [V][D]) * <ul> * <li>[A] = any square matrix.</li> * <li>[V] = contains the eigenvectors as columns.</li> * <li>[D] = a diagonal matrix with the eigenvalues on the diagonal (possibly in blocks).</li> * </ul> * <p> * [A] is normal if [A][A]<sup>H</sup> = [A]<sup>H</sup>[A], and [A] is normal if and only if there exists a * unitary matrix [Q] such that [A] = [Q][D][Q]<sup>H</sup>. Hermitian matrices are normal. * </p> * <p> * [V] and [D] can always be calculated in the sense that they will satisfy [A][V] = [V][D], but it is not * always possible to calculate [V]<sup>-1</sup>. (Check the rank and/or the condition number of [V] to * determine the validity of [V][D][V]<sup>-1</sup>.) * </p> * <p> * The eigenvalues (and their corresponding eigenvectors) of a non-symmetric matrix could be complex. * </p> * * @author apete */ public interface Eigenvalue<N extends Number> extends MatrixDecomposition<N>, MatrixDecomposition.Hermitian<N>, MatrixDecomposition.Determinant<N>, MatrixDecomposition.Values<N> { interface Factory<N extends Number> extends MatrixDecomposition.Factory<Eigenvalue<N>> { default Eigenvalue<N> make(final boolean hermitian) { return this.make(TYPICAL, hermitian); } default Eigenvalue<N> make(final Structure2D typical) { if (typical instanceof Access2D) { return this.make(typical, MatrixUtils.isHermitian((Access2D<?>) typical)); } else { return this.make(typical, false); } } Eigenvalue<N> make(Structure2D typical, boolean hermitian); } public static final Factory<BigDecimal> BIG = (typical, hermitian) -> hermitian ? new HermitianEvD.Big() : null; public static final Factory<ComplexNumber> COMPLEX = (typical, hermitian) -> hermitian ? new HermitianEvD.Complex() : null; public static final Factory<Double> PRIMITIVE = new Factory<Double>() { public Eigenvalue<Double> make(final Structure2D typical) { if ((8192L < typical.countColumns()) && (typical.count() <= BasicArray.MAX_ARRAY_SIZE)) { return new DynamicEvD.Primitive(); } else { return new RawEigenvalue.Dynamic(); } } public Eigenvalue<Double> make(final Structure2D typical, final boolean hermitian) { if ((8192L < typical.countColumns()) && (typical.count() <= BasicArray.MAX_ARRAY_SIZE)) { return hermitian ? new HermitianEvD.Primitive() : new GeneralEvD.Primitive(); } else { return hermitian ? new RawEigenvalue.Symmetric() : new RawEigenvalue.General(); } } }; public static <N extends Number> Eigenvalue<N> make(final Access2D<N> typical) { return Eigenvalue.make(typical, MatrixUtils.isHermitian(typical)); } @SuppressWarnings("unchecked") public static <N extends Number> Eigenvalue<N> make(final Access2D<N> typical, final boolean hermitian) { final N tmpNumber = typical.get(0L, 0L); if (tmpNumber instanceof BigDecimal) { return (Eigenvalue<N>) BIG.make(typical, hermitian); } else if (tmpNumber instanceof ComplexNumber) { return (Eigenvalue<N>) COMPLEX.make(typical, hermitian); } else if (tmpNumber instanceof Double) { return (Eigenvalue<N>) PRIMITIVE.make(typical, hermitian); } else { throw new IllegalArgumentException(); } } /** * The only requirements on [D] are that it should contain the eigenvalues and that [A][V] = [V][D]. The * ordering of the eigenvalues is not specified. * <ul> * <li>If [A] is real and symmetric then [D] is (purely) diagonal with real eigenvalues.</li> * <li>If [A] is real but not symmetric then [D] is block-diagonal with real eigenvalues in 1-by-1 blocks * and complex eigenvalues in 2-by-2 blocks.</li> * <li>If [A] is complex then [D] is (purely) diagonal with complex eigenvalues.</li> * </ul> * * @return The (block) diagonal eigenvalue matrix. */ MatrixStore<N> getD(); /** * <p> * Even for real matrices the eigenvalues are potentially complex numbers. Typically they need to be * expressed as complex numbers when [A] is not symmetric. * </p> * <p> * The eigenvalues in this array should always be ordered in descending order - largest (modulus) first. * </p> * * @return The eigenvalues in an ordered array. */ Array1D<ComplexNumber> getEigenvalues(); /** * A matrix' trace is the sum of the diagonal elements. It is also the sum of the eigenvalues. This method * should return the sum of the eigenvalues. * * @return The matrix' trace */ ComplexNumber getTrace(); /** * The columns of [V] represent the eigenvectors of [A] in the sense that [A][V] = [V][D]. * * @return The eigenvector matrix. */ MatrixStore<N> getV(); /** * If [A] is hermitian then [V][D][V]<sup>-1</sup> becomes [Q][D][Q]<sup>H</sup>... */ boolean isHermitian(); /** * The eigenvalues in D (and the eigenvectors in V) are not necessarily ordered. This is a property of the * algorithm/implementation, not the data. * * @return true if they are ordered */ boolean isOrdered(); default MatrixStore<N> reconstruct() { return MatrixUtils.reconstruct(this); } }
package org.opencms.importexport; import org.opencms.file.CmsFile; import org.opencms.file.CmsFolder; import org.opencms.file.CmsObject; import org.opencms.file.CmsProperty; import org.opencms.file.CmsPropertydefinition; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.types.CmsResourceTypeFolder; import org.opencms.file.types.CmsResourceTypePlain; import org.opencms.file.types.CmsResourceTypeXmlPage; import org.opencms.file.types.I_CmsResourceType; import org.opencms.lock.CmsLockException; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.I_CmsConstants; import org.opencms.main.OpenCms; import org.opencms.report.I_CmsReport; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import org.opencms.workplace.I_CmsWpConstants; import org.opencms.xml.CmsXmlUtils; import org.opencms.xml.page.CmsXmlPage; import java.io.File; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; import java.util.zip.ZipFile; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Node; /** * Implementation of the OpenCms Import Interface ({@link org.opencms.importexport.I_CmsImport}) for * the import version 2.<p> * * This import format was used in OpenCms 5.0.0 - 5.1.2.<p> * * @author Michael Emmerich (m.emmerich@alkacon.com) * @author Thomas Weckert (t.weckert@alkacon.com) * * @see org.opencms.importexport.A_CmsImport */ public class CmsImportVersion2 extends A_CmsImport { /** The version number of this import implementation. */ private static final int C_IMPORT_VERSION = 2; /** The runtime property name for old webapp names. */ private static final String C_COMPATIBILITY_WEBAPPNAMES = "compatibility.support.webAppNames"; /** Web application names for conversion support. */ protected List m_webAppNames; /** Old webapp URL for import conversion. */ protected String m_webappUrl; /** folder storage for page file and body conversion. */ private List m_folderStorage; /** page file storage for page file and body co.version. */ private List m_pageStorage; /** * @see org.opencms.importexport.I_CmsImport#getVersion() * @return the version number of this import implementation */ public int getVersion() { return CmsImportVersion2.C_IMPORT_VERSION; } /** * Initializes all member variables before the import is started.<p> * * This is required since there is only one instance for * each import version that is kept in memory and reused.<p> */ protected void initialize() { m_convertToXmlPage = true; m_webAppNames = new ArrayList(); super.initialize(); } /** * Cleans up member variables after the import is finished.<p> * * This is required since there is only one instance for * each import version that is kept in memory and reused.<p> */ protected void cleanUp() { m_pageStorage = null; m_folderStorage = null; m_webAppNames = null; m_webappUrl = null; super.cleanUp(); } /** * Imports the resources for a module.<p> * @param cms the current cms object * @param importPath the path in the cms VFS to import into * @param report a report object to output the progress information to * @param digest digest for taking a fingerprint of the files * @param importResource the import-resource (folder) to load resources from * @param importZip the import-resource (zip) to load resources from * @param docXml the xml manifest-file * @param excludeList filenames of files and folders which should not * be (over)written in the virtual file system (not used when null) * @param writtenFilenames filenames of the files and folder which have actually been * successfully written (not used when null) * @param fileCodes code of the written files (for the registry) * (not used when null) * @param propertyName name of a property to be added to all resources * @param propertyValue value of that property * @throws CmsException if something goes wrong */ public synchronized void importResources(CmsObject cms, String importPath, I_CmsReport report, MessageDigest digest, File importResource, ZipFile importZip, Document docXml, Vector excludeList, Vector writtenFilenames, Vector fileCodes, String propertyName, String propertyValue) throws CmsException { // initialize the import initialize(); m_cms = cms; m_importPath = importPath; m_report = report; m_digest = digest; m_importResource = importResource; m_importZip = importZip; m_docXml = docXml; m_importingChannelData = false; m_folderStorage = new ArrayList(); m_pageStorage = new ArrayList(); m_importedPages = new ArrayList(); m_linkStorage = new HashMap(); m_linkPropertyStorage = new HashMap(); if (OpenCms.getRunLevel() > 1) { if ((OpenCms.getMemoryMonitor() != null) && OpenCms.getMemoryMonitor().enabled()) { OpenCms.getMemoryMonitor().register(this.getClass().getName() + "." + "m_folderStorage", m_folderStorage); OpenCms.getMemoryMonitor().register(this.getClass().getName() + "." + "m_pageStorage", m_pageStorage); OpenCms.getMemoryMonitor().register(this.getClass().getName() + "." + "m_importedPages", m_importedPages); OpenCms.getMemoryMonitor().register(this.getClass().getName() + "." + "m_linkStorage", m_linkStorage); OpenCms.getMemoryMonitor().register(this.getClass().getName() + "." + "m_linkPropertyStorage", m_linkPropertyStorage); } } try { // first import the user information if (m_cms.isAdmin()) { importGroups(); importUsers(); } // now import the VFS resources importAllResources(excludeList, writtenFilenames, fileCodes, propertyName, propertyValue); convertPointerToSiblings(); } catch (CmsException e) { throw e; } finally { cleanUp(); } } /** * Imports the resources and writes them to the cms.<p> * * @param excludeList filenames of files and folders which should not * be (over)written in the virtual file system (not used when null) * @param writtenFilenames filenames of the files and folder which have actually been * successfully written (not used when null) * @param fileCodes code of the written files (for the registry) * (not used when null) * @param propertyName name of a property to be added to all resources * @param propertyValue value of that property * @throws CmsException if something goes wrong */ private void importAllResources(Vector excludeList, Vector writtenFilenames, Vector fileCodes, String propertyName, String propertyValue) throws CmsException { List fileNodes = null, acentryNodes = null; Element currentElement = null, currentEntry = null; String source = null, destination = null, resourceTypeName = null, timestamp = null, uuid = null, uuidresource = null; long lastmodified = 0; int resourceTypeId = I_CmsConstants.C_UNKNOWN_ID; List properties = null; boolean old_overwriteCollidingResources = false; if (m_importingChannelData) { m_cms.getRequestContext().saveSiteRoot(); m_cms.getRequestContext().setSiteRoot(I_CmsConstants.VFS_FOLDER_CHANNELS); } if (excludeList == null) { excludeList = new Vector(); } try { m_webAppNames = getCompatibilityWebAppNames(); } catch (Exception e) { if (OpenCms.getLog(this).isErrorEnabled()) { OpenCms.getLog(this).error("Error getting compatibility web-app names", e); } m_report.println(e); } if (m_webAppNames == null) { m_webAppNames = Collections.EMPTY_LIST; } // get the old webapp url from the OpenCms properties m_webappUrl = OpenCms.getImportExportManager().getOldWebAppUrl(); if (m_webappUrl == null) { // use a default value m_webappUrl = "http://localhost:8080/opencms/opencms"; } // cut last "/" from webappUrl if present if (m_webappUrl.endsWith("/")) { m_webappUrl = m_webappUrl.substring(0, m_webappUrl.lastIndexOf("/")); } // get list of unwanted properties List deleteProperties = OpenCms.getImportExportManager().getIgnoredProperties(); // get list of immutable resources List immutableResources = OpenCms.getImportExportManager().getImmutableResources(); if (DEBUG > 0) { System.err.println("Import: Immutable resources size is " + immutableResources.size()); } // save the value of the boolean flag whether colliding resources should be overwritten old_overwriteCollidingResources = OpenCms.getImportExportManager().overwriteCollidingResources(); // force v1 and v2 imports to overwrite colliding resources, because they dont have resource // UUIDs in their manifest anyway OpenCms.getImportExportManager().setOverwriteCollidingResources(true); try { // get all file-nodes fileNodes = m_docXml.selectNodes("//" + I_CmsConstants.C_EXPORT_TAG_FILE); int importSize = fileNodes.size(); // walk through all files in manifest for (int i = 0; i < importSize; i++) { m_report.print(" ( " + (i + 1) + " / " + importSize + " ) ", I_CmsReport.C_FORMAT_NOTE); currentElement = (Element) fileNodes.get(i); // get all information for a file-import source = CmsImport.getChildElementTextValue(currentElement, I_CmsConstants.C_EXPORT_TAG_SOURCE); destination = CmsImport.getChildElementTextValue(currentElement, I_CmsConstants.C_EXPORT_TAG_DESTINATION); resourceTypeName = CmsImport.getChildElementTextValue(currentElement, I_CmsConstants.C_EXPORT_TAG_TYPE); if (C_RESOURCE_TYPE_NEWPAGE_NAME.equals(resourceTypeName)) { resourceTypeId = C_RESOURCE_TYPE_NEWPAGE_ID; } else if (C_RESOURCE_TYPE_PAGE_NAME.equals(resourceTypeName)) { // resource with a "legacy" resource type are imported using the "plain" resource // type because you cannot import a resource without having the resource type object resourceTypeId = CmsResourceTypePlain.C_RESOURCE_TYPE_ID; } else if (C_RESOURCE_TYPE_LINK_NAME.equals(resourceTypeName)) { // set resource type of legacy "link" which is converted later resourceTypeId = C_RESOURCE_TYPE_LINK_ID; } else { I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(resourceTypeName); resourceTypeId = type.getTypeId(); } uuid = CmsImport.getChildElementTextValue(currentElement, I_CmsConstants.C_EXPORT_TAG_UUIDSTRUCTURE); uuidresource = CmsImport.getChildElementTextValue(currentElement, I_CmsConstants.C_EXPORT_TAG_UUIDRESOURCE); if ((timestamp = CmsImport.getChildElementTextValue(currentElement, I_CmsConstants.C_EXPORT_TAG_LASTMODIFIED)) != null) { lastmodified = Long.parseLong(timestamp); } else { lastmodified = System.currentTimeMillis(); } // if the type is "script" set it to plain if ("script".equals(resourceTypeName)) { resourceTypeName = CmsResourceTypePlain.C_RESOURCE_TYPE_NAME; } if (OpenCms.getLog(this).isDebugEnabled()) { OpenCms.getLog(this).debug("Import: Original resource name is " + destination); } String translatedName = m_cms.getRequestContext().addSiteRoot(m_importPath + destination); if (CmsResourceTypeFolder.C_RESOURCE_TYPE_NAME.equals(resourceTypeName)) { translatedName += I_CmsConstants.C_FOLDER_SEPARATOR; } if (OpenCms.getLog(this).isDebugEnabled()) { OpenCms.getLog(this).debug("Import: Translated resource name is " + translatedName); } boolean resourceNotImmutable = checkImmutable(translatedName, immutableResources); translatedName = m_cms.getRequestContext().removeSiteRoot(translatedName); if (resourceNotImmutable && (!excludeList.contains(translatedName))) { // print out the information to the report m_report.print(m_report.key("report.importing"), I_CmsReport.C_FORMAT_NOTE); m_report.print(translatedName); m_report.print(m_report.key("report.dots")); // get all properties properties = readPropertiesFromManifest(currentElement, propertyName, propertyValue, deleteProperties); // import the specified file CmsResource res = importResource(source, destination, uuid, uuidresource, resourceTypeId, resourceTypeName, lastmodified, properties, writtenFilenames, fileCodes); List aceList = new ArrayList(); if (res != null) { // write all imported access control entries for this file acentryNodes = currentElement.selectNodes("*/" + I_CmsConstants.C_EXPORT_TAG_ACCESSCONTROL_ENTRY); // collect all access control entries for (int j = 0; j < acentryNodes.size(); j++) { currentEntry = (Element)acentryNodes.get(j); // get the data of the access control entry String id = CmsImport.getChildElementTextValue(currentEntry, I_CmsConstants.C_EXPORT_TAG_ID); String acflags = CmsImport.getChildElementTextValue(currentEntry, I_CmsConstants.C_EXPORT_TAG_FLAGS); String allowed = CmsImport.getChildElementTextValue(currentEntry, I_CmsConstants.C_EXPORT_TAG_ACCESSCONTROL_ALLOWEDPERMISSIONS); String denied = CmsImport.getChildElementTextValue(currentEntry, I_CmsConstants.C_EXPORT_TAG_ACCESSCONTROL_DENIEDPERMISSIONS); // add the entry to the list aceList.add(getImportAccessControlEntry(res, id, allowed, denied, acflags)); } importAccessControlEntries(res, aceList); } else { // resource import failed, since no CmsResource was created m_report.print(m_report.key("report.skipping"), I_CmsReport.C_FORMAT_OK); m_report.println(translatedName); } } else { // skip the file import, just print out the information to the report m_report.print(m_report.key("report.skipping"), I_CmsReport.C_FORMAT_NOTE); m_report.println(translatedName); } } // now merge the body and page control files. this only has to be done if the import // version is below version 3 if (getVersion() < 3 && m_convertToXmlPage) { mergePageFiles(); removeFolders(); } } catch (Exception exc) { if (OpenCms.getLog(this).isErrorEnabled()) { OpenCms.getLog(this).error(exc); } m_report.println(exc); throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc); } finally { if (m_importingChannelData) { m_cms.getRequestContext().restoreSiteRoot(); } // set the flag to overwrite colliding resources back to its original value OpenCms.getImportExportManager().setOverwriteCollidingResources(old_overwriteCollidingResources); } } /** * Imports a resource (file or folder) into the cms.<p> * * @param source the path to the source-file * @param destination the path to the destination-file in the cms * @param uuid the structure uuid of the resource * @param uuidresource the resource uuid of the resource * @param resourceTypeId the ID of the file's resource type * @param resourceTypeName the name of the file's resource type * @param lastmodified the timestamp of the file * @param properties a hashtable with properties for this resource * @param writtenFilenames filenames of the files and folder which have actually been successfully written * not used when null * @param fileCodes code of the written files (for the registry) * not used when null * * @return imported resource */ private CmsResource importResource(String source, String destination, String uuid, String uuidresource, int resourceTypeId, String resourceTypeName, long lastmodified, List properties, Vector writtenFilenames, Vector fileCodes) { boolean success = true; byte[] content = null; String fullname = null; CmsResource res = null; String targetName = null; try { if (m_importingChannelData) { // try to read an existing channel to get the channel id String channelId = null; try { if ((resourceTypeName.equalsIgnoreCase(CmsResourceTypeFolder.C_RESOURCE_TYPE_NAME)) && (!destination.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR))) { destination += I_CmsConstants.C_FOLDER_SEPARATOR; } CmsResource channel = m_cms.readResource(I_CmsConstants.C_ROOT + destination); channelId = m_cms.readPropertyObject(m_cms.getSitePath(channel), I_CmsConstants.C_PROPERTY_CHANNELID, false).getValue(); } catch (Exception e) { // ignore the exception, a new channel id will be generated } if (channelId != null) { properties.add(new CmsProperty(I_CmsConstants.C_PROPERTY_CHANNELID, channelId, null)); } } // get the file content if (source != null) { content = getFileBytes(source); } content = convertContent(source, destination, content, resourceTypeName); // get all required information to create a CmsResource int size=0; if (content!=null) { size=content.length; } // get the required UUIDs CmsUUID curUser=m_cms.getRequestContext().currentUser().getId(); CmsUUID newUuidstructure= new CmsUUID(); CmsUUID newUuidresource = new CmsUUID(); if (uuid!=null) { newUuidstructure = new CmsUUID(uuid); } if (uuidresource!=null) { newUuidresource = new CmsUUID(uuidresource); } // extract the name of the resource form the destination targetName=destination; if (targetName.endsWith("/")) { targetName=targetName.substring(0, targetName.length()-1); } boolean isFolder = false; try { isFolder = CmsFolder.isFolderType(resourceTypeId); } catch (Throwable t) { // the specified resource type ID might be of an unknown resource type. // as another option, check the content length and resource type name // to determine if the resource is a folder or not. isFolder = ((content.length == 0) && CmsResourceTypeFolder.C_RESOURCE_TYPE_NAME.equalsIgnoreCase(resourceTypeName)); } // create a new CmsResource CmsResource resource=new CmsResource( newUuidstructure, newUuidresource, targetName, resourceTypeId, isFolder, 0, m_cms.getRequestContext().currentProject().getId(), I_CmsConstants.C_STATE_NEW, lastmodified, curUser, lastmodified, curUser, CmsResource.DATE_RELEASED_DEFAULT, CmsResource.DATE_EXPIRED_DEFAULT, 1, size ); if (C_RESOURCE_TYPE_LINK_ID == resourceTypeId) { // store links for later conversion m_report.print(m_report.key("report.storing_link"), I_CmsReport.C_FORMAT_NOTE); m_linkStorage.put(m_importPath + destination, new String(content)); m_linkPropertyStorage.put(m_importPath + destination, properties); res = resource; } else { // import this resource in the VFS String resName = m_importPath+destination; res = m_cms.importResource(resName, resource, content, properties); try { m_cms.unlockResource(resName); } catch (CmsLockException e) { if (OpenCms.getLog(this).isDebugEnabled()) { OpenCms.getLog(this).debug("Unable to unlock resource " + resName + " (continuing anyway)"); } } } if (res != null) { if (C_RESOURCE_TYPE_PAGE_NAME.equals(resourceTypeName)) { m_importedPages.add(I_CmsConstants.C_FOLDER_SEPARATOR + destination); } m_report.println(m_report.key("report.ok"), I_CmsReport.C_FORMAT_OK); } } catch (Exception exc) { if (OpenCms.getLog(this).isErrorEnabled()) { OpenCms.getLog(this).error("Error importing resource " + targetName, exc); } // an error while importing the file success = false; m_report.println(exc); try { // Sleep some time after an error so that the report output has a chance to keep up Thread.sleep(1000); } catch (Exception e) { } } byte[] digestContent = {0}; if (content != null) { digestContent = m_digest.digest(content); } if (success && (fullname != null)) { if (writtenFilenames != null) { writtenFilenames.addElement(fullname); } if (fileCodes != null) { fileCodes.addElement(new String(digestContent)); } } return res; } /** * Performs all required pre-import steps.<p> * * The content is *NOT* changed in the implementation of this class.<p> * * @param source the source path of the resource * @param destination the destination path of the resource * @param content the content of the resource * @param resType the type of the resource * @return the (prepared) content of the resource */ protected byte[] convertContent(String source, String destination, byte[] content, String resType) { // if the import is older than version 3, some additional conversions must be made if (getVersion() < 3) { if ("page".equals(resType)) { if (DEBUG > 0) { System.err.println(" System.err.println("[" + this.getClass().getName() + ".convertContent()]: storing resource " + source + "."); } // if the imported resource is a page, store its path inside the VFS for later // integration with its body m_pageStorage.add(destination); } else if ("folder".equals(resType)) { // check if the imported resource is a folder. Folders created in the /system/bodies/ folder if (destination.startsWith(I_CmsWpConstants.C_VFS_PATH_BODIES.substring(1))) { // must be remove since we do not use body files anymore. m_folderStorage.add(destination); } } } return content; } /** * Merges the page control files and their corresponding bodies into a single files.<p> * * * @throws CmsException if something goes wrong */ private void mergePageFiles() throws CmsException { // check if the template property exists. If not, create it. try { m_cms.readPropertydefinition(I_CmsConstants.C_PROPERTY_TEMPLATE); } catch (CmsException e) { // the template propertydefintion does not exist. So create it. m_cms.createPropertydefinition(I_CmsConstants.C_PROPERTY_TEMPLATE); } // copy all propertydefinitions of the old page to the new page List definitions = m_cms.readAllPropertydefinitions(); Iterator j = definitions.iterator(); while (j.hasNext()) { CmsPropertydefinition definition = (CmsPropertydefinition)j.next(); // check if this propertydef already exits try { m_cms.readPropertydefinition(definition.getName()); } catch (Exception e) { m_cms.createPropertydefinition(definition.getName()); } } // iterate through the list of all page controlfiles found during the import process int size = m_pageStorage.size(); m_report.println(m_report.key("report.merge_start"), I_CmsReport.C_FORMAT_HEADLINE); Iterator i = m_pageStorage.iterator(); int counter = 1; while (i.hasNext()) { String resname = (String)i.next(); // adjust the resourcename if nescessary if (!resname.startsWith("/")) { resname = "/" + resname; } m_report.print("( " + counter + " / " + size + " ) ", I_CmsReport.C_FORMAT_NOTE); m_report.print(m_report.key("report.merge") + " " , I_CmsReport.C_FORMAT_NOTE); m_report.print(resname, I_CmsReport.C_FORMAT_DEFAULT); try { mergePageFile(resname); } catch (Exception e) { if (OpenCms.getLog(this).isErrorEnabled()) { OpenCms.getLog(this).error("Error merging page file " + resname, e); } m_report.println(e); } counter++; } // free mem m_pageStorage.clear(); } /** * Merges a single page.<p> * * @param resourcename the resource name of the page * @throws Exception if something goes wrong */ private void mergePageFile(String resourcename) throws Exception { if (OpenCms.getLog(this).isDebugEnabled()) { OpenCms.getLog(this).debug("Start merging " + resourcename); } // in OpenCms versions <5 node names have not been case sensitive. thus, nodes are read both in upper // and lower case letters, or have to be tested for equality ignoring upper/lower case... // get the header file CmsFile pagefile = m_cms.readFile(resourcename, CmsResourceFilter.ALL); Document contentXml = CmsXmlUtils.unmarshalHelper(pagefile.getContents(), null); // get the <masterTemplate> node to check the content. this node contains the name of the template file. String masterTemplateNodeName = "//masterTemplate"; Node masterTemplateNode = contentXml.selectSingleNode(masterTemplateNodeName); if (masterTemplateNode == null) { masterTemplateNode = contentXml.selectSingleNode(masterTemplateNodeName.toLowerCase()); } if (masterTemplateNode == null) { masterTemplateNode = contentXml.selectSingleNode(masterTemplateNodeName.toUpperCase()); } // there is only one <masterTemplate> allowed String mastertemplate = null; if (masterTemplateNode != null) { // get the name of the mastertemplate mastertemplate = masterTemplateNode.getText().trim(); } // get the <ELEMENTDEF> nodes to check the content. // this node contains the information for the body element. String elementDefNodeName = "//ELEMENTDEF"; Node bodyNode = contentXml.selectSingleNode(elementDefNodeName); if (bodyNode == null) { bodyNode = contentXml.selectSingleNode(elementDefNodeName.toLowerCase()); } // there is only one <ELEMENTDEF> allowed if (bodyNode != null) { String bodyclass = null; String bodyname = null; Map bodyparams = null; List nodes = ((Element)bodyNode).elements(); for (int i = 0, n = nodes.size(); i < n; i++) { Node node = (Node) nodes.get(i); if ("CLASS".equalsIgnoreCase(node.getName())) { bodyclass = node.getText().trim(); } else if ("TEMPLATE".equalsIgnoreCase(node.getName())) { bodyname = node.getText().trim(); if (!bodyname.startsWith("/")) { bodyname = CmsResource.getFolderPath(resourcename) + bodyname; } } else if ("PARAMETER".equalsIgnoreCase(node.getName())) { Element paramElement = (Element)node; if (bodyparams == null) { bodyparams = new HashMap(); } bodyparams.put((paramElement.attribute("name")).getText(), paramElement.getTextTrim()); } } if (mastertemplate == null || bodyname == null) { throw new CmsException("Could not merge page file '" + resourcename + "', mastertemplate=" + mastertemplate + ", bodyname=" + bodyname); } // lock the resource, so that it can be manipulated m_cms.lockResource(resourcename); // get all properties List properties = m_cms.readPropertyObjects(resourcename, false); // now get the content of the bodyfile and insert it into the control file CmsFile bodyfile = m_cms.readFile(bodyname, CmsResourceFilter.IGNORE_EXPIRATION); //get the encoding String encoding = CmsProperty.get(I_CmsConstants.C_PROPERTY_CONTENT_ENCODING, properties).getValue(); if (encoding == null) { encoding = OpenCms.getSystemInfo().getDefaultEncoding(); } if (m_convertToXmlPage) { if (OpenCms.getLog(this).isDebugEnabled()) { OpenCms.getLog(this).debug("Start converting to XML"); } CmsXmlPage xmlPage = CmsXmlPageConverter.convertToXmlPage( m_cms, bodyfile.getContents(), getLocale(resourcename, properties), encoding); if (OpenCms.getLog(this).isDebugEnabled()) { OpenCms.getLog(this).debug("End converting to XML"); } if (xmlPage != null) { pagefile.setContents(xmlPage.marshal()); // set the type to xml page pagefile.setType(CmsResourceTypeXmlPage.C_RESOURCE_TYPE_ID); } } // add the template and other required properties CmsProperty newProperty = new CmsProperty(I_CmsConstants.C_PROPERTY_TEMPLATE, mastertemplate, null); // property lists must not contain equal properties properties.remove(newProperty); properties.add(newProperty); // if set, add the bodyclass as property if (bodyclass != null && !"".equals(bodyclass)) { newProperty = new CmsProperty(I_CmsConstants.C_PROPERTY_TEMPLATE, mastertemplate, null); newProperty.setAutoCreatePropertyDefinition(true); properties.remove(newProperty); properties.add(newProperty); } // if set, add bodyparams as properties if (bodyparams != null) { for (Iterator p = bodyparams.keySet().iterator(); p.hasNext();) { String key = (String)p.next(); newProperty = new CmsProperty(key, (String)bodyparams.get(key), null); newProperty.setAutoCreatePropertyDefinition(true); properties.remove(newProperty); properties.add(newProperty); } } if (OpenCms.getLog(this).isDebugEnabled()) { OpenCms.getLog(this).debug("Start importing XML page"); } // now import the resource m_cms.importResource(resourcename, pagefile, pagefile.getContents(), properties); // finally delete the old body file, it is not needed anymore m_cms.lockResource(bodyname); m_cms.deleteResource(bodyname, I_CmsConstants.C_DELETE_OPTION_PRESERVE_SIBLINGS); if (OpenCms.getLog(this).isDebugEnabled()) { OpenCms.getLog(this).debug("End importing XML page"); } m_report.println(" " + m_report.key("report.ok"), I_CmsReport.C_FORMAT_OK); } else { // there are more than one template nodes in this control file // convert the resource into a plain text file // lock the resource, so that it can be manipulated m_cms.lockResource(resourcename); // set the type to plain pagefile.setType(CmsResourceTypePlain.C_RESOURCE_TYPE_ID); // write all changes m_cms.writeFile(pagefile); // done, unlock the resource m_cms.unlockResource(resourcename); if (OpenCms.getLog(this).isInfoEnabled()) { OpenCms.getLog(this).info("Cannot convert XML structure of " + resourcename); } m_report.println(" " + m_report.key("report.notconverted"), I_CmsReport.C_FORMAT_OK); } if (OpenCms.getLog(this).isDebugEnabled()) { OpenCms.getLog(this).debug("End merging " + resourcename); } } /** * Deletes the folder structure which has been creating while importing the body files..<p> * * @throws CmsException if something goes wrong */ private void removeFolders() throws CmsException { int size = m_folderStorage.size(); m_report.println(m_report.key("report.delfolder_start"), I_CmsReport.C_FORMAT_HEADLINE); // iterate though all collected folders. Iteration must start at the end of the list, // as folders habe to be deleted in the reverse order. int counter = 1; for (int j=(size-1); j>=0; j String resname = (String)m_folderStorage.get(j); resname = (resname.startsWith("/") ? "" : "/") + resname + (resname.endsWith("/") ? "" : "/"); // now check if the folder is really empty. Only delete empty folders List files = m_cms.getFilesInFolder(resname, CmsResourceFilter.IGNORE_EXPIRATION); if (files.size() == 0) { List folders = m_cms.getSubFolders(resname, CmsResourceFilter.IGNORE_EXPIRATION); if (folders.size() == 0) { m_report.print("( " + counter + " / " + size + " ) ", I_CmsReport.C_FORMAT_NOTE); m_report.print(m_report.key("report.delfolder") + " " , I_CmsReport.C_FORMAT_NOTE); m_report.print(resname, I_CmsReport.C_FORMAT_DEFAULT); m_cms.lockResource(resname); m_cms.deleteResource(resname, I_CmsConstants.C_DELETE_OPTION_PRESERVE_SIBLINGS); m_report.println(m_report.key("report.ok"), I_CmsReport.C_FORMAT_OK); counter++; } } } } /** * Gets the encoding from the &lt;?XML ...&gt; tag if present.<p> * * @param content the file content * @return String the found encoding */ protected String getEncoding(String content) { String encoding = content; int index = encoding.toLowerCase().indexOf("encoding=\""); // encoding attribute found, get the value if (index != -1) { encoding = encoding.substring(index + 10); if ((index = encoding.indexOf("\"")) != -1) { encoding = encoding.substring(0, index); return encoding.toUpperCase(); } } // no encoding attribute found return ""; } /** * Sets the right encoding and returns the result.<p> * * @param content the filecontent * @param encoding the encoding to use * @return modified content */ protected String setEncoding(String content, String encoding) { if (content.toLowerCase().indexOf("<?xml") == -1) { return content; } else { // XML information present, replace encoding // set the encoding only if it does not exist String xmlTag = content.substring(0, content.indexOf(">") + 1); if (xmlTag.toLowerCase().indexOf("encoding") == -1) { content = content.substring(content.indexOf(">") + 1); content = "<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>" + content; } } return content; } /** * Translates directory Strings from OpenCms 4.x structure to new 5.0 structure.<p> * * @param content the filecontent * @param rules the translation rules * @return String the manipulated file content */ public static String setDirectories(String content, String[] rules) { // get translation rules for (int i = 0; i < rules.length; i++) { String actRule = rules[i]; // cut String "/default/vfs/" from rule actRule = CmsStringUtil.substitute(actRule, "/default/vfs", ""); // divide rule into search and replace parts and delete regular expressions StringTokenizer ruleT = new StringTokenizer(actRule, " ruleT.nextToken(); String search = ruleT.nextToken(); search = search.substring(0, search.lastIndexOf("(.*)")); String replace = ruleT.nextToken(); replace = replace.substring(0, replace.lastIndexOf("$1")); // scan content for paths if the replace String is not present if (content.indexOf(replace) == -1 && content.indexOf(search) != -1) { // ensure subdirectories of the same name are not replaced search = "([}>\"'\\[]\\s*)" + search; replace = "$1" + replace; content = CmsStringUtil.substitutePerl(content, search, replace, "g"); } } return content; } /** * Returns the compatibility web app names.<p> * * @return the compatibility web app names */ private List getCompatibilityWebAppNames() throws Exception { List webAppNamesOri = new ArrayList(); String configuredWebAppNames = (String)OpenCms.getRuntimeProperty(C_COMPATIBILITY_WEBAPPNAMES); if (configuredWebAppNames != null && configuredWebAppNames.length() != 0) { // split the comma separated list of web app names StringTokenizer tokenizer = new StringTokenizer(configuredWebAppNames, ",;"); while (tokenizer.hasMoreTokens()) { webAppNamesOri.add(tokenizer.nextToken()); } } List webAppNames = new ArrayList(); for (int i = 0; i < webAppNamesOri.size(); i++) { // remove possible white space String name = ((String)webAppNamesOri.get(i)).trim(); if (name != null && !"".equals(name)) { webAppNames.add(name); if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) { OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Old context path : " + (i + 1) + " - " + name); } } } if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) { OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Old context support : " + ((webAppNames.size() > 0) ? "enabled" : "disabled")); } // check if list is null if (webAppNames == null) { webAppNames = new ArrayList(); } // add current context to webapp names list if (!webAppNames.contains(OpenCms.getSystemInfo().getOpenCmsContext())) { webAppNames.add(OpenCms.getSystemInfo().getOpenCmsContext()); } return webAppNames; } /** * Imports a single user.<p> * @param name user name * @param description user description * @param flags user flags * @param password user password * @param firstname firstname of the user * @param lastname lastname of the user * @param email user email * @param address user address * @param type user type * @param userInfo user info * @param userGroups user groups * * @throws CmsException in case something goes wrong */ protected void importUser(String name, String description, String flags, String password, String firstname, String lastname, String email, String address, String type, Hashtable userInfo, Vector userGroups) throws CmsException { if (!"com.opencms.legacy.CmsLegacyPasswordHandler".equals(OpenCms.getPasswordHandler().getClass().getName())) { password = convertDigestEncoding(password); } super.importUser(name, description, flags, password, firstname, lastname, email, address, type, userInfo, userGroups); } }
package org.opencms.ui.apps.user; import org.opencms.db.CmsUserSettings; import org.opencms.file.CmsGroup; import org.opencms.file.CmsObject; import org.opencms.file.CmsProject; import org.opencms.file.CmsResource; import org.opencms.file.CmsUser; import org.opencms.main.CmsException; import org.opencms.main.CmsIllegalArgumentException; import org.opencms.main.CmsIllegalStateException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.security.CmsDefaultValidationHandler; import org.opencms.security.CmsOrganizationalUnit; import org.opencms.security.CmsPasswordInfo; import org.opencms.security.CmsRole; import org.opencms.security.CmsSecurityException; import org.opencms.security.I_CmsPasswordHandler; import org.opencms.security.I_CmsPasswordSecurityEvaluator; import org.opencms.security.I_CmsPasswordSecurityEvaluator.SecurityLevel; import org.opencms.site.CmsSite; import org.opencms.ui.A_CmsUI; import org.opencms.ui.CmsVaadinUtils; import org.opencms.ui.apps.CmsPageEditorConfiguration; import org.opencms.ui.apps.CmsSitemapEditorConfiguration; import org.opencms.ui.apps.I_CmsWorkplaceAppConfiguration; import org.opencms.ui.apps.Messages; import org.opencms.ui.components.CmsBasicDialog; import org.opencms.ui.components.CmsUserDataFormLayout; import org.opencms.ui.components.CmsUserDataFormLayout.EditLevel; import org.opencms.ui.components.OpenCmsTheme; import org.opencms.ui.components.fileselect.CmsPathSelectField; import org.opencms.ui.dialogs.permissions.CmsPrincipalSelect; import org.opencms.ui.dialogs.permissions.CmsPrincipalSelect.WidgetType; import org.opencms.ui.login.CmsLoginController; import org.opencms.ui.login.CmsPasswordForm; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import org.opencms.workplace.CmsWorkplaceLoginHandler; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.mail.EmailException; import com.vaadin.data.provider.DataProvider; import com.vaadin.data.provider.ListDataProvider; import com.vaadin.server.UserError; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Component; import com.vaadin.ui.TabSheet; import com.vaadin.ui.TabSheet.SelectedTabChangeEvent; import com.vaadin.ui.TabSheet.SelectedTabChangeListener; import com.vaadin.ui.Window; import com.vaadin.v7.data.Item; import com.vaadin.v7.data.Property.ValueChangeEvent; import com.vaadin.v7.data.Property.ValueChangeListener; import com.vaadin.v7.data.Validator; import com.vaadin.v7.data.util.IndexedContainer; import com.vaadin.v7.event.FieldEvents.TextChangeEvent; import com.vaadin.v7.event.FieldEvents.TextChangeListener; import com.vaadin.v7.ui.CheckBox; import com.vaadin.v7.ui.ComboBox; import com.vaadin.v7.ui.Label; import com.vaadin.v7.ui.TextArea; import com.vaadin.v7.ui.TextField; /** * Class for the dialog to edit user settings.<p> */ @SuppressWarnings("deprecation") public class CmsUserEditDialog extends CmsBasicDialog implements I_CmsPasswordFetcher { /** * Validator for the eamil field.<p> */ class EmailValidator implements Validator { /**vaadin serial id.*/ private static final long serialVersionUID = 8943898736907290076L; /** * @see com.vaadin.data.Validator#validate(java.lang.Object) */ public void validate(Object value) throws InvalidValueException { if (value == null) { throw new InvalidValueException( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_VALIDATION_EMAIL_EMPTY_0)); } try { CmsUser.checkEmail((String)value); } catch (CmsIllegalArgumentException e) { throw new InvalidValueException( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_VALIDATION_EMAIL_INVALID_0)); } } } /** * Validator for the login name field.<p> */ class LoginNameValidator implements Validator { /**vaadin serial id.*/ private static final long serialVersionUID = -6768717591898665618L; /** * @see com.vaadin.data.Validator#validate(java.lang.Object) */ public void validate(Object value) throws InvalidValueException { if (value == null) { throw new InvalidValueException( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_VALIDATION_LOGINNAME_EMPTY_0)); } try { CmsDefaultValidationHandler handler = new CmsDefaultValidationHandler(); handler.checkUserName((String)value); } catch (CmsIllegalArgumentException e) { throw new InvalidValueException( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_VALIDATION_LOGINNAME_INVALID_0)); } if (userAlreadyExists((String)value)) { throw new InvalidValueException( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_VALIDATION_LOGINNAME_DOUBLE_0)); } } } /** * Validator for password fields.<p> */ class PasswordValidator implements Validator { /**vaadin serial id.*/ private static final long serialVersionUID = 64216980175982548L; /** * @see com.vaadin.data.Validator#validate(java.lang.Object) */ public void validate(Object value) throws InvalidValueException { if (isPasswordMismatchingConfirm()) { throw new InvalidValueException( CmsVaadinUtils.getMessageText( Messages.GUI_USERMANAGEMENT_USER_VALIDATION_PASSWORD_NOT_EQUAL_CONFIRM_0)); } if (!isNewUser()) { if ((value == null) | CmsStringUtil.isEmptyOrWhitespaceOnly((String)value)) { return; //ok, password was not changed for existing user } } if (!isPasswordValid()) { throw new InvalidValueException( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_VALIDATION_PASSWORD_INVALID_0)); } } } /** * Validator for start view and start site field.<p> */ class StartPathValidator implements Validator { /**vaadin serial id.*/ private static final long serialVersionUID = -4257155941690487831L; /** * @see com.vaadin.data.Validator#validate(java.lang.Object) */ public void validate(Object value) throws InvalidValueException { if (!m_visSites) { return; } if (!isSiteNull()) { if (!isSitePathValid()) { throw new InvalidValueException( CmsVaadinUtils.getMessageText( Messages.GUI_USERMANAGEMENT_USER_VALIDATION_START_PATH_NOT_VALID_0)); } } } } /** * Validator for start view and start site field.<p> */ class StartSiteValidator implements Validator { /**vaadin serial id.*/ private static final long serialVersionUID = -4257155941690487831L; /** * @see com.vaadin.data.Validator#validate(java.lang.Object) */ public void validate(Object value) throws InvalidValueException { if (!m_visSites) { return; } if (isSiteNull()) { throw new InvalidValueException( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_USER_VALIDATION_STARTSITE_EMPTY_0)); } } } /** * Validator for start view and start site field.<p> */ class StartViewValidator implements Validator { /**vaadin serial id.*/ private static final long serialVersionUID = -4257155941690487831L; /** * @see com.vaadin.data.Validator#validate(java.lang.Object) */ public void validate(Object value) throws InvalidValueException { if (!isSiteNull()) { if (isRootSiteSelected() & !isStartViewAvailableOnRoot()) { throw new InvalidValueException( CmsVaadinUtils.getMessageText( Messages.GUI_USERMANAGEMENT_USER_VALIDATION_STARTVIEW_NOTFORROOT_0)); } } } } /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsUserEditDialog.class); /**vaadin serial id.*/ private static final long serialVersionUID = -5198443053070008413L; /**Flag indicates is user is in webou. */ boolean m_isWebOU; /**Password form. */ CmsPasswordForm m_pw; /**vaadin component.*/ ComboBox m_site; /**Holder for authentification fields. */ // private VerticalLayout m_authHolder; /**vaadin component.*/ CmsPathSelectField m_startfolder; /**vaadin component.*/ private Button m_cancel; /**CmsObject. */ private CmsObject m_cms; /**vaadin component.*/ private TextArea m_description; /**vaadin component.*/ private CheckBox m_enabled; /**vaadin component. */ private CheckBox m_forceResetPassword; /**vaadin component. */ private CheckBox m_sendEmail; /**Vaadin component. */ private Button m_generateButton; /**Visible sites? */ protected boolean m_visSites = true; /**Select view for principals.*/ private CmsPrincipalSelect m_group; /**vaadin component.*/ private ComboBox m_language; /**vaadin component.*/ private TextField m_loginname; /**Flag indicates if name was empty. */ private boolean m_name_was_empty; /**vaadin component. */ private Button m_next; /**vaadin component.*/ private Button m_ok; /**vaadin component.*/ private Label m_ou; /**vaadin component.*/ private ComboBox m_project; /**vaadin component. */ private ComboBox m_role; /**vaadin component.*/ private CheckBox m_selfmanagement; /** Label containing invisible dummy password fields to dissuade Firefox from saving the password *after* the user edit dialog. */ private Label m_dummyPasswordLabel; /**vaadin component.*/ private ComboBox m_startview; /**vaadin component.*/ private TabSheet m_tab; /**vaadin component.*/ private CmsUser m_user; /**User data form.<p>*/ private CmsUserDataFormLayout m_userdata; private CmsUserEditParameters m_editParams = new CmsUserEditParameters(); /** * public constructor.<p> * @param callingOu * * @param cms CmsObject * @param userId id of user * @param window to be closed * @param app */ public CmsUserEditDialog(CmsObject cms, CmsUUID userId, final Window window, final CmsAccountsApp app) { CmsVaadinUtils.readAndLocalizeDesign(this, CmsVaadinUtils.getWpMessagesForCurrentLocale(), null); setPasswordFields(); try { m_cms = OpenCms.initCmsObject(cms); m_startfolder.disableSiteSwitch(); m_user = m_cms.readUser(userId); m_editParams = app.getUserEditParameters(m_user); if (m_user.isWebuser()) { m_sendEmail.setVisible(false); m_sendEmail.setValue(Boolean.FALSE); m_forceResetPassword.setVisible(false); m_forceResetPassword.setValue(Boolean.FALSE); m_selfmanagement.setVisible(false); m_selfmanagement.setValue(Boolean.FALSE); m_isWebOU = true; } else { m_selfmanagement.setValue(new Boolean(true)); } displayResourceInfoDirectly(Collections.singletonList(CmsAccountsApp.getPrincipalInfo(m_user))); m_group.setVisible(false); m_role.setVisible(false); m_loginname.setValue(m_user.getSimpleName()); m_loginname.setEnabled(false); m_ou.setValue(m_user.getOuFqn().isEmpty() ? "/" : m_user.getOuFqn()); m_description.setValue(m_user.getDescription()); m_selfmanagement.setValue(new Boolean(!m_user.isManaged())); m_enabled.setValue(new Boolean(m_user.isEnabled())); CmsUserSettings settings = new CmsUserSettings(m_user); init(window, app, settings, m_editParams.isEditEnabled()); m_sendEmail.setEnabled(false); m_forceResetPassword.setValue( CmsUserTable.USER_PASSWORD_STATUS.get(m_user.getId()) == null ? Boolean.FALSE : CmsUserTable.USER_PASSWORD_STATUS.get(m_user.getId())); m_next.setVisible(false); setupStartFolder(settings.getStartFolder()); m_loginname.setEnabled(false); if (!m_editParams.isEditEnabled()) { m_description.setEnabled(false); } if (!m_editParams.isPasswordChangeEnabled()) { m_pw.setVisible(false); m_forceResetPassword.setVisible(false); m_sendEmail.setVisible(false); m_generateButton.setVisible(false); } } catch (CmsException e) { LOG.error("Can't read user", e); } } /** * public constructor for new user case.<p> * * @param cms CmsObject * @param window Window * @param ou organizational unit */ public CmsUserEditDialog(CmsObject cms, final Window window, String ou, final CmsAccountsApp app) { CmsVaadinUtils.readAndLocalizeDesign(this, CmsVaadinUtils.getWpMessagesForCurrentLocale(), null); CmsOrganizationalUnit myOu = null; try { m_cms = OpenCms.initCmsObject(cms); myOu = OpenCms.getOrgUnitManager().readOrganizationalUnit(m_cms, ou); m_isWebOU = false; m_sendEmail.setValue(Boolean.TRUE); m_forceResetPassword.setValue(Boolean.TRUE); if (myOu.hasFlagWebuser()) { m_role.setVisible(false); m_sendEmail.setVisible(false); m_sendEmail.setValue(Boolean.FALSE); m_forceResetPassword.setVisible(false); m_forceResetPassword.setValue(Boolean.FALSE); m_selfmanagement.setVisible(false); m_selfmanagement.setValue(Boolean.FALSE); m_isWebOU = true; } else { iniRole(m_cms, ou, m_role, LOG); m_role.select(CmsRole.EDITOR.forOrgUnit(ou)); m_selfmanagement.setValue(new Boolean(true)); } } catch (CmsException e) { LOG.error("Unable to read OU", e); } setPasswordFields(); m_ou.setValue(ou.isEmpty() ? "/" : ou); m_group.setWidgetType(WidgetType.groupwidget); try { CmsGroup group = m_cms.readGroup(ou + OpenCms.getDefaultUsers().getGroupUsers()); m_group.setValue(group.getName()); } catch (CmsException e1) { //There is no user group -> ok, keep field empty } m_group.setRealPrincipalsOnly(true); m_group.setOU(m_ou.getValue()); try { m_group.setIncludeWebOus(OpenCms.getOrgUnitManager().readOrganizationalUnit(m_cms, ou).hasFlagWebuser()); } catch (CmsException e) { } m_enabled.setValue(Boolean.TRUE); init(window, app, null, true); setupStartFolder(null); m_tab.addSelectedTabChangeListener(new SelectedTabChangeListener() { private static final long serialVersionUID = -2579639520410382246L; public void selectedTabChange(SelectedTabChangeEvent event) { setButtonVisibility(); } }); setButtonVisibility(); } /** * Initialized the role ComboBox.<p> * * @param cms CmsObject * @param ou to load roles for * @param roleComboBox ComboBox * @param log LOG */ protected static void iniRole(CmsObject cms, String ou, com.vaadin.ui.ComboBox<CmsRole> roleComboBox, Log log) { try { List<CmsRole> roles = OpenCms.getRoleManager().getRoles(cms, ou, false); CmsRole.applySystemRoleOrder(roles); DataProvider provider = new ListDataProvider<CmsRole>(roles); roleComboBox.setDataProvider(provider); roleComboBox.setItemCaptionGenerator(role -> { try { return role.getDisplayName(cms, A_CmsUI.get().getLocale()); } catch (CmsException e) { return ""; } }); roleComboBox.setEmptySelectionAllowed(false); } catch (CmsException e) { if (log != null) { log.error("Unable to read roles.", e); } } } /** * Initialized the role ComboBox.<p> * * @param cms CmsObject * @param ou to load roles for * @param roleComboBox ComboBox * @param log LOG */ protected static void iniRole(CmsObject cms, String ou, ComboBox roleComboBox, Log log) { try { List<CmsRole> roles = OpenCms.getRoleManager().getRoles(cms, ou, false); CmsRole.applySystemRoleOrder(roles); IndexedContainer container = new IndexedContainer(); container.addContainerProperty("caption", String.class, ""); for (CmsRole role : roles) { Item item = container.addItem(role); item.getItemProperty("caption").setValue(role.getDisplayName(cms, A_CmsUI.get().getLocale())); } roleComboBox.setContainerDataSource(container); roleComboBox.setItemCaptionPropertyId("caption"); roleComboBox.setNullSelectionAllowed(false); roleComboBox.setNewItemsAllowed(false); } catch (CmsException e) { if (log != null) { log.error("Unable to read roles.", e); } } } /** * Sends an email to the user.<p> * * @param newUser is the user new? */ protected static void sendMail( CmsObject cms, String password, CmsUser user, boolean newUser, boolean changePassword) { sendMail(cms, password, user, user.getOuFqn(), newUser, changePassword); } protected static void sendMail( CmsObject cms, String password, CmsUser user, String ou, boolean newUser, boolean changePassword) { if (CmsStringUtil.isEmptyOrWhitespaceOnly(user.getEmail())) { return; } CmsSendPasswordNotification notification = new CmsSendPasswordNotification( cms, password, user, ou, cms.getRequestContext().getCurrentUser(), OpenCms.getLinkManager().getWorkplaceLink(cms, CmsWorkplaceLoginHandler.LOGIN_HANDLER, false), newUser, changePassword); try { notification.send(); } catch (EmailException e) { LOG.error("Unable to send email with password", e); } } /** * @see org.opencms.ui.apps.user.I_CmsPasswordFetcher#fetchPassword(java.lang.String) */ public void fetchPassword(String password) { m_pw.getPassword1Field().setValue(password); m_pw.getPassword2Field().setValue(password); m_forceResetPassword.setValue(Boolean.TRUE); m_sendEmail.setValue(Boolean.TRUE); m_sendEmail.setEnabled(true); } /** * Checks if a new user should be created.<p> * * @return true, if create user function */ protected boolean isNewUser() { return m_user == null; } /**m_next * Is password not matching to confirm field?<p> * * @return true, if password not equal to confirm */ protected boolean isPasswordMismatchingConfirm() { return !m_pw.getPassword1().equals(m_pw.getPassword2()); } /** * Validates the password fields.<p> * * @return true if password is valid (and confirm field matches password field).<p> */ protected boolean isPasswordValid() { if ((m_pw.getPassword1() == null) | (m_pw.getPassword2() == null)) { return false; } try { CmsPasswordInfo pwdInfo = new CmsPasswordInfo(); pwdInfo.setNewPwd(m_pw.getPassword1()); pwdInfo.setConfirmation(m_pw.getPassword2()); pwdInfo.validate(); return true; } catch (CmsIllegalArgumentException | CmsIllegalStateException e) { LOG.error("New password is not ok", e); return false; } } /** * Checks if currently the root site is chosen as start site.<p> * * @return true if root site was selected */ protected boolean isRootSiteSelected() { return m_site.getValue().equals(""); } /** * Checks if the chosen site is valid.<p> * * @return true if site is null */ protected boolean isSiteNull() { return m_site.getValue() == null; } /** * Checks if the given path is valid resource in site.<p> * * @return true if the resource is valid */ protected boolean isSitePathValid() { try { CmsObject cmsLocal = OpenCms.initCmsObject(m_cms); cmsLocal.getRequestContext().setSiteRoot((String)m_site.getValue()); if (m_startfolder.getValue().length() <= ((String)m_site.getValue()).length()) { return false; } return cmsLocal.existsResource(m_startfolder.getValue().substring(((String)m_site.getValue()).length())); } catch (CmsException e) { LOG.error("Unabel to ini CmsObject", e); return false; } } /** * Checks if the currently chosen start view is visible for root site.<p> * * @return true if app is available for root site */ protected boolean isStartViewAvailableOnRoot() { if (!m_startview.isEnabled()) { return false; } return !m_startview.getValue().equals(CmsPageEditorConfiguration.APP_ID) & !m_startview.getValue().equals(CmsSitemapEditorConfiguration.APP_ID); } /** * Checks if all fields are valid. If not the tab of the first invalid field gets chosen.<p> * * @return true, if everything is ok */ protected boolean isValid() { boolean[] ret = new boolean[4]; ret[0] = m_loginname.isValid(); ret[1] = m_isWebOU ? true : m_userdata.isValid() | m_name_was_empty; ret[2] = m_isWebOU ? true : m_site.isValid() & m_startview.isValid() & m_startfolder.isValid(); ret[3] = m_pw.getPassword1Field().isValid(); for (int i = 0; i < ret.length; i++) { if (!ret[i]) { m_tab.setSelectedTab(i); break; } } return ret[0] & ret[1] & ret[2] & ret[3]; } /** * Saves the canged user data.<p> */ protected void save() { boolean newUser = false; try { if (m_user == null) { createNewUser(); newUser = true; } else { saveUser(); } saveUserSettings(); if (m_sendEmail.getValue().booleanValue() & m_sendEmail.isEnabled()) { sendMail(m_cms, m_pw.getPassword1(), m_user, newUser, m_forceResetPassword.getValue().booleanValue()); } } catch (CmsException e) { LOG.error("Unable to save user", e); } } /** * Sets the visibility of the buttons.<p> */ protected void setButtonVisibility() { Component tab = m_tab.getSelectedTab(); int pos = m_tab.getTabPosition(m_tab.getTab(tab)); //TODO: check if necessary (when it was finally known which tabs web ou users should see.. int maxPos = m_isWebOU ? 3 : 3; //has to be changed if number of tabs is changed for web OU user m_next.setVisible(pos < maxPos); m_ok.setVisible(pos == maxPos); } /** * En/Diables the email box.<p> */ protected void setEmailBox() { m_sendEmail.setEnabled( !CmsStringUtil.isEmptyOrWhitespaceOnly(m_pw.getPassword1()) | !CmsStringUtil.isEmptyOrWhitespaceOnly(m_pw.getPassword2())); } /** * Sets the start folder depending on current set site field.<p> * * @param startFolder default value or null */ protected void setupStartFolder(String startFolder) { try { CmsObject cmsCopy = OpenCms.initCmsObject(m_cms); if (m_site.getValue() != null) { cmsCopy.getRequestContext().setSiteRoot((String)m_site.getValue()); } else { cmsCopy.getRequestContext().setSiteRoot(""); } m_startfolder.requireFolder(); m_startfolder.disableSiteSwitch(); String defaultFolder = OpenCms.getWorkplaceManager().getDefaultUserSettings().getStartFolder(); if ((startFolder == null) && (CmsStringUtil.isEmptyOrWhitespaceOnly(defaultFolder) || !cmsCopy.existsResource(defaultFolder))) { defaultFolder = "/"; } m_startfolder.setValue( cmsCopy.getRequestContext().addSiteRoot(startFolder == null ? defaultFolder : startFolder)); m_startfolder.setCmsObject(cmsCopy); m_startfolder.setUseRootPaths(true); if (!m_visSites) { try { List<CmsResource> ouResources = OpenCms.getOrgUnitManager().getResourcesForOrganizationalUnit( cmsCopy, m_ou.getValue()); if (!ouResources.isEmpty()) { m_startfolder.setValue(ouResources.get(0).getRootPath()); } } catch (CmsException e1) { LOG.error("unable to read resources for ou", e1); } } m_startfolder.setEnabled(m_visSites); } catch (CmsException e) { LOG.error("Unable to ini CmsObject", e); } } /** * Sets up the validators.<p> */ protected void setupValidators() { if (m_loginname.getValidators().size() == 0) { m_loginname.addValidator(new LoginNameValidator()); m_pw.getPassword1Field().addValidator(new PasswordValidator()); m_site.addValidator(new StartSiteValidator()); m_startview.addValidator(new StartViewValidator()); m_startfolder.addValidator(new StartPathValidator()); } } /**Switches to the next tab.*/ protected void switchTab() { Component tab = m_tab.getSelectedTab(); int pos = m_tab.getTabPosition(m_tab.getTab(tab)); if (m_isWebOU) { if (pos == 0) { pos = 1; } } m_tab.setSelectedTab(pos + 1); } /** * Checks if given user exists.<p> * * @param username to check * @return boolean */ protected boolean userAlreadyExists(String username) { if (m_user != null) { return false; } CmsUser user = null; try { user = m_cms.readUser(m_ou.getValue() + username); } catch (CmsException e) { return false; } return user != null; } /** * Checks whether the passwords match.<p> * * @param password2 the password 2 value */ void checkPasswordMatch(String password2) { if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(password2)) { showPasswordMatchError(!password2.equals(m_pw.getPassword1())); } } /** * Checks the security level of the given password.<p> * * @param password the password */ void checkSecurity(String password) { I_CmsPasswordHandler handler = OpenCms.getPasswordHandler(); try { handler.validatePassword(password); if (handler instanceof I_CmsPasswordSecurityEvaluator) { SecurityLevel level = ((I_CmsPasswordSecurityEvaluator)handler).evaluatePasswordSecurity(password); m_pw.setErrorPassword1(null, OpenCmsTheme.SECURITY + "-" + level.name()); } else { m_pw.setErrorPassword1(null, OpenCmsTheme.SECURITY_STRONG); } } catch (CmsSecurityException e) { m_pw.setErrorPassword1( new UserError(e.getLocalizedMessage(A_CmsUI.get().getLocale())), OpenCmsTheme.SECURITY_INVALID); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_pw.getPassword2())) { showPasswordMatchError(!password.equals(m_pw.getPassword2())); } } /** * Returns a CmsObject with request set to given site.<p> * * @param siteRoot to be used * @return CmsObject */ CmsObject getCmsObjectWithSite(String siteRoot) { if (siteRoot == null) { siteRoot = "/"; } try { CmsObject res = OpenCms.initCmsObject(m_cms); res.getRequestContext().setSiteRoot(siteRoot); return res; } catch (CmsException e) { LOG.error("Unable to initialize CmsObject", e); return m_cms; } } /** * Initializes the site combo box.<p> * * @param settings user settings */ void iniSite(CmsUserSettings settings) { List<CmsSite> sitesList = OpenCms.getSiteManager().getAvailableSites(m_cms, true, false, m_ou.getValue()); IndexedContainer container = new IndexedContainer(); container.addContainerProperty("caption", String.class, ""); CmsSite firstNoRootSite = null; for (CmsSite site : sitesList) { if (CmsStringUtil.isEmptyOrWhitespaceOnly(site.getSiteRoot())) { if (hasRole(CmsRole.VFS_MANAGER) | ((m_user == null) && Arrays.asList( CmsRole.ACCOUNT_MANAGER.forOrgUnit(m_ou.getValue()), CmsRole.ADMINISTRATOR.forOrgUnit(m_ou.getValue()), CmsRole.WORKPLACE_MANAGER.forOrgUnit(m_ou.getValue()), CmsRole.DATABASE_MANAGER.forOrgUnit(m_ou.getValue()), CmsRole.PROJECT_MANAGER.forOrgUnit(m_ou.getValue()), CmsRole.VFS_MANAGER.forOrgUnit(m_ou.getValue()), CmsRole.ROOT_ADMIN.forOrgUnit(m_ou.getValue())).contains( ((CmsRole)(m_role.getValue())).forOrgUnit(m_ou.getValue())))) { Item item = container.addItem(site.getSiteRoot()); item.getItemProperty("caption").setValue(site.getTitle()); } } else { if (firstNoRootSite == null) { firstNoRootSite = site; } Item item = container.addItem(site.getSiteRoot()); item.getItemProperty("caption").setValue(site.getTitle()); } } if (container.size() == 0) { if (!container.containsId(A_CmsUI.getCmsObject().getRequestContext().getSiteRoot())) { Item defaultItem = container.addItem(A_CmsUI.getCmsObject().getRequestContext().getSiteRoot()); defaultItem.getItemProperty("caption").setValue( A_CmsUI.getCmsObject().getRequestContext().getSiteRoot()); } m_visSites = false; } m_site.setContainerDataSource(container); m_site.setItemCaptionPropertyId("caption"); m_site.setNewItemsAllowed(false); m_site.setNullSelectionAllowed(false); if (settings != null) { if (settings.getStartSite().length() >= 1) { m_site.select(settings.getStartSite().substring(0, settings.getStartSite().length() - 1)); } else { LOG.error("The start site is unvalid configured"); } } else { String defaultSite = OpenCms.getWorkplaceManager().getDefaultUserSettings().getStartSite(); if (container.containsId(defaultSite)) { m_site.select(defaultSite); } else if (firstNoRootSite != null) { m_site.select(firstNoRootSite.getSiteRoot()); } else { m_site.select(container.getItemIds().get(0)); } } } /** * Initializes the start view.<p> * * @param settings user settings */ void iniStartView(CmsUserSettings settings) { IndexedContainer container = getStartViewContainer("caption"); if (container.size() > 0) { m_startview.setEnabled(true); m_startview.setContainerDataSource(container); m_startview.setItemCaptionPropertyId("caption"); m_startview.setNullSelectionAllowed(false); m_startview.setNewItemsAllowed(false); if (container.getItemIds().size() > 0) { if (settings != null) { m_startview.select(settings.getStartView()); } else { String defaultView = OpenCms.getWorkplaceManager().getDefaultUserSettings().getStartView(); if (container.containsId(defaultView)) { m_startview.select(defaultView); } else { m_startview.select(container.getItemIds().get(0)); } } } } else { m_startview.setEnabled(false); } } /** * Shows or hides the not matching passwords error.<p> * * @param show <code>true</code> to show the error */ void showPasswordMatchError(boolean show) { if (show) { m_pw.setErrorPassword2( new UserError(CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_PWCHANGE_PASSWORD_MISMATCH_0)), OpenCmsTheme.SECURITY_INVALID); } else { m_pw.setErrorPassword2(null, OpenCmsTheme.SECURITY_STRONG); } } /** * Creates new user.<p> * * @throws CmsException exception */ private void createNewUser() throws CmsException { //Password was checked by validator before String ou = m_ou.getValue(); if (!ou.endsWith("/")) { ou += "/"; } CmsUser user = m_cms.createUser(ou + m_loginname.getValue(), m_pw.getPassword1(), "", null); updateUser(user); m_cms.writeUser(user); if (!CmsStringUtil.isEmptyOrWhitespaceOnly(m_group.getValue())) { m_cms.addUserToGroup(user.getName(), m_group.getValue()); } if (m_role.isVisible()) { OpenCms.getRoleManager().addUserToRole(m_cms, (CmsRole)m_role.getValue(), user.getName()); } m_user = user; } /** * Returns the start view container.<p> * * @param caption of the container * @return indexed container */ private IndexedContainer getStartViewContainer(String caption) { List<I_CmsWorkplaceAppConfiguration> apps = OpenCms.getWorkplaceAppManager().getDefaultQuickLaunchConfigurations(); IndexedContainer res = new IndexedContainer(); res.addContainerProperty(caption, String.class, ""); for (I_CmsWorkplaceAppConfiguration app : apps) { if (hasRoleForApp(app)) { Item item = res.addItem(app.getId()); item.getItemProperty(caption).setValue(app.getName(A_CmsUI.get().getLocale())); } } return res; } /** * Checks if user, which gets edited, has given role.<p> * * @param role to be checked * @return true if user has role (or a parent role) */ private boolean hasRole(CmsRole role) { if (m_user != null) { return OpenCms.getRoleManager().hasRole(m_cms, m_user.getName(), CmsRole.VFS_MANAGER); } return false; } /** * Checks if user, which gets edited, has role for given app.<p> * * @param app to be checked * @return true if user has role */ private boolean hasRoleForApp(I_CmsWorkplaceAppConfiguration app) { if (m_user != null) { return OpenCms.getRoleManager().hasRole(m_cms, m_user.getName(), app.getRequiredRole()); } if (!CmsStringUtil.isEmptyOrWhitespaceOnly(m_group.getValue())) { try { CmsGroup group = m_cms.readGroup(m_group.getValue()); CmsRole roleFromGroup = CmsRole.valueOf(group); CmsRole roleFromField = (CmsRole)m_role.getValue(); if ((roleFromGroup == null) || !roleFromGroup.getChildren(true).contains(roleFromField)) { roleFromGroup = roleFromField; } if (roleFromGroup == null) { return false; } List<CmsRole> groupRoles = roleFromGroup.getChildren(true); groupRoles.add(roleFromGroup); List<String> roleNames = new ArrayList<String>(); for (CmsRole gr : groupRoles) { roleNames.add(gr.getRoleName()); } return roleNames.contains(app.getRequiredRole().getRoleName()); } catch (CmsException e) { LOG.error("Unable to read group", e); } } return true; } /** * Initializes the language combo box.<p> * * @param settings user settings */ private void iniLanguage(CmsUserSettings settings) { IndexedContainer container = CmsVaadinUtils.getLanguageContainer("caption"); m_language.setContainerDataSource(container); m_language.setItemCaptionPropertyId("caption"); m_language.setNewItemsAllowed(false); m_language.setNullSelectionAllowed(false); if (settings != null) { m_language.select(settings.getLocale()); } else { if (OpenCms.getWorkplaceManager().getDefaultUserSettings().getLocale() != null) { m_language.select(OpenCms.getWorkplaceManager().getDefaultUserSettings().getLocale()); } else { m_language.select(m_language.getItemIds().iterator().next()); } } } /** * Initializes the project combo box.<p> * * @param settings of user */ private void iniProject(CmsUserSettings settings) { try { List<CmsProject> projects = OpenCms.getOrgUnitManager().getAllAccessibleProjects( m_cms, m_ou.getValue(), false); for (CmsProject project : projects) { m_project.addItem(project.getSimpleName()); } m_project.setNewItemsAllowed(false); m_project.setNullSelectionAllowed(false); if (settings != null) { String projString = settings.getStartProject(); if (projString.contains("/")) { projString = projString.split("/")[projString.split("/").length - 1]; } m_project.select(projString); } else { String defaultProject = OpenCms.getWorkplaceManager().getDefaultUserSettings().getStartProject(); if (m_project.containsId(defaultProject)) { m_project.select(defaultProject); } else if (m_project.containsId("Offline")) { m_project.select("Offline"); } else { Iterator<?> it = m_project.getItemIds().iterator(); String p = (String)it.next(); while (p.equals(CmsProject.ONLINE_PROJECT_NAME) & it.hasNext()) { p = (String)it.next(); } m_project.select(p); } } } catch (CmsException e) { LOG.error("Unable to read projects", e); } } /** * A initialization method.<p> * * @param window to be closed * @param app * @param settings user settings, null if new user */ private void init(final Window window, final CmsAccountsApp app, final CmsUserSettings settings, boolean enabled) { m_userdata.initFields(m_user, enabled ? EditLevel.all : EditLevel.none); if (m_user != null) { if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_user.getFirstname()) | CmsStringUtil.isEmptyOrWhitespaceOnly(m_user.getLastname()) | CmsStringUtil.isEmptyOrWhitespaceOnly(m_user.getEmail())) { m_name_was_empty = true; } } iniLanguage(settings); iniProject(settings); iniSite(settings); iniStartView(settings); m_site.addValueChangeListener(new ValueChangeListener() { private static final long serialVersionUID = 5111762655156037899L; public void valueChange(ValueChangeEvent event) { setupStartFolder(null); } }); m_ok.addClickListener(new ClickListener() { private static final long serialVersionUID = -2579639520410382246L; public void buttonClick(ClickEvent event) { setupValidators(); if (isValid()) { save(); window.close(); app.reload(); } } }); m_next.addClickListener(new ClickListener() { private static final long serialVersionUID = -8584899970290349959L; public void buttonClick(ClickEvent event) { setupValidators(); switchTab(); } }); m_cancel.addClickListener(new ClickListener() { private static final long serialVersionUID = 5803825104722705175L; public void buttonClick(ClickEvent event) { window.close(); } }); if (m_user == null) { m_role.addValueChangeListener(new ValueChangeListener() { private static final long serialVersionUID = 5697126133686172725L; public void valueChange(ValueChangeEvent event) { iniSite(settings); iniStartView(settings); } }); m_group.addValueChangeListener(new ValueChangeListener() { private static final long serialVersionUID = 1512940002751242094L; public void valueChange(ValueChangeEvent event) { iniStartView(settings); iniSite(settings); } }); } m_site.addValueChangeListener(new ValueChangeListener() { private static final long serialVersionUID = -169973382455098800L; public void valueChange(ValueChangeEvent event) { m_startfolder.setCmsObject(getCmsObjectWithSite((String)m_site.getValue())); } }); m_generateButton.addClickListener(new Button.ClickListener() { private static final long serialVersionUID = 4128513094772586752L; public void buttonClick(ClickEvent event) { final Window windowDialog = CmsBasicDialog.prepareWindow(CmsBasicDialog.DialogWidth.content); windowDialog.setCaption( CmsVaadinUtils.getMessageText(Messages.GUI_USERMANAGEMENT_GEN_PASSWORD_CAPTION_0)); CmsGeneratePasswordDialog dialog = new CmsGeneratePasswordDialog( CmsUserEditDialog.this, new Runnable() { public void run() { windowDialog.close(); } }); windowDialog.setContent(dialog); A_CmsUI.get().addWindow(windowDialog); } }); } /** * Saves changes to an existing user.<p> * * @throws CmsException exception */ private void saveUser() throws CmsException { updateUser(m_user); if (!CmsStringUtil.isEmptyOrWhitespaceOnly(m_pw.getPassword1())) { if (isPasswordValid()) { m_cms.setPassword(m_user.getName(), m_pw.getPassword1()); } } m_cms.writeUser(m_user); } /** * Saves the user settings.<p> * * @throws CmsException exception */ private void saveUserSettings() throws CmsException { CmsUserSettings settings = new CmsUserSettings(m_user); settings.setLocale((Locale)m_language.getValue()); settings.setStartSite((String)m_site.getValue() + "/"); settings.setStartProject(m_ou.getValue() + (String)m_project.getValue()); if (m_visSites) { settings.setStartFolder(m_startfolder.getValue().substring(((String)m_site.getValue()).length())); if (!CmsStringUtil.isEmptyOrWhitespaceOnly((String)m_startview.getValue())) { settings.setStartView((String)m_startview.getValue()); } } settings.save(m_cms); } /** * Sets the password fields.<p> */ private void setPasswordFields() { m_dummyPasswordLabel.setContentMode(com.vaadin.v7.shared.ui.label.ContentMode.HTML); // ugly hack to prevent Firefox from asking user to save password on every click which causes the history token to change after editing a user String pwd = "<input type=\"password\" value=\"password\">"; m_dummyPasswordLabel.setValue("<div style=\"display: none;\">" + pwd + pwd + "</div>"); m_pw.hideOldPassword(); m_pw.setHeaderVisible(false); if (OpenCms.getPasswordHandler() instanceof I_CmsPasswordSecurityEvaluator) { m_pw.setSecurityHint( ((I_CmsPasswordSecurityEvaluator)OpenCms.getPasswordHandler()).getPasswordSecurityHint( A_CmsUI.get().getLocale())); } m_pw.getOldPasswordField().setImmediate(true); m_pw.getPassword1Field().setImmediate(true); m_pw.getPassword2Field().setImmediate(true); m_pw.getPassword1Field().addTextChangeListener(new TextChangeListener() { private static final long serialVersionUID = 1L; public void textChange(TextChangeEvent event) { checkSecurity(event.getText()); setEmailBox(); } }); m_pw.getPassword2Field().addTextChangeListener(new TextChangeListener() { private static final long serialVersionUID = 1L; public void textChange(TextChangeEvent event) { checkSecurity(m_pw.getPassword1()); checkPasswordMatch(event.getText()); setEmailBox(); } }); } /** * Sets the password status for the user.<p> * * @param user CmsUser * @param reset true or false */ private void setUserPasswordStatus(CmsUser user, boolean reset) { if (reset) { user.setAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_PASSWORD_RESET, "true"); } else { user.deleteAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_PASSWORD_RESET); } CmsUserTable.USER_PASSWORD_STATUS.put(user.getId(), new Boolean(reset)); } /** * Read form and updates a given user according to form.<p> * * @param user to be updated */ private void updateUser(CmsUser user) { setUserPasswordStatus(user, m_forceResetPassword.getValue().booleanValue()); user.setDescription(m_description.getValue()); user.setManaged(!m_selfmanagement.getValue().booleanValue()); boolean enabled = m_enabled.getValue().booleanValue(); user.setEnabled(enabled); if (enabled) { user.getAdditionalInfo().remove(CmsLoginController.KEY_ACCOUNT_LOCKED); } m_userdata.submit(user, m_cms, new Runnable() { public void run() { } }, true); } }
package org.owasp.esapi.reference; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.util.Arrays; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import org.owasp.esapi.ESAPI; import org.owasp.esapi.ValidationErrorList; import org.owasp.esapi.errors.EncodingException; import org.owasp.esapi.errors.IntrusionException; import org.owasp.esapi.errors.ValidationAvailabilityException; import org.owasp.esapi.errors.ValidationException; import org.owasp.validator.html.AntiSamy; import org.owasp.validator.html.CleanResults; import org.owasp.validator.html.Policy; import org.owasp.validator.html.PolicyException; import org.owasp.validator.html.ScanException; public class DefaultValidator implements org.owasp.esapi.Validator { /** OWASP AntiSamy markup verification policy */ private Policy antiSamyPolicy = null; /** constants */ private static final int MAX_CREDIT_CARD_LENGTH = 19; private static final int MAX_PARAMETER_NAME_LENGTH = 100; private static final int MAX_PARAMETER_VALUE_LENGTH = 65535; public DefaultValidator() { } public boolean isValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws IntrusionException { try { getValidInput( context, input, type, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws ValidationException, IntrusionException { try { context = ESAPI.encoder().canonicalize( context ); String canonical = ESAPI.encoder().canonicalize( input ); if ( type == null || type.length() == 0 ) { throw new RuntimeException( "Validation misconfiguration, specified type to validate against was null: context=" + context + ", type=" + type + "), input=" + input ); } if (isEmpty(canonical)) { if (allowNull) return null; throw new ValidationException( context + ": Input required.", "Input required: context=" + context + ", type=" + type + "), input=" + input, context ); } if (canonical.length() > maxLength) { throw new ValidationException( context + ": Invalid input. The maximum length of " + maxLength + " characters was exceeded.", "Input exceeds maximum allowed length of " + maxLength + " by " + (canonical.length()-maxLength) + " characters: context=" + context + ", type=" + type + "), input=" + input, context ); } Pattern p = ((DefaultSecurityConfiguration)ESAPI.securityConfiguration()).getValidationPattern( type ); if ( p == null ) { try { p = Pattern.compile( type ); } catch( PatternSyntaxException e ) { throw new RuntimeException( "Validation misconfiguration, specified type to validate against was null: context=" + context + ", type=" + type + "), input=" + input ); } } if ( !p.matcher(canonical).matches() ) { throw new ValidationException( context + ": Invalid input. Please conform to: " + p.pattern() + " with a maximum length of " + maxLength, "Invalid input: context=" + context + ", type=" + type + "( " + p.pattern() + "), input=" + input, context ); } return canonical; } catch (EncodingException e) { throw new ValidationException( context + ": Invalid input. An encoding error occurred.", "Error canonicalizing user input", e, context); } } public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidInput(context, input, type, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /** * Returns true if input is a valid date according to the specified date format. */ public boolean isValidDate(String context, String input, DateFormat format, boolean allowNull) throws IntrusionException { try { getValidDate( context, input, format, allowNull); return true; } catch( Exception e ) { return false; } } /* * Returns a valid date as a Date. Invalid input will generate a descriptive ValidationException, * and input that is clearly an attack will generate a descriptive IntrusionException. * * @see org.owasp.esapi.interfaces.IValidator#getValidDate(java.lang.String) */ public Date getValidDate(String context, String input, DateFormat format, boolean allowNull) throws ValidationException, IntrusionException { try { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input date required", "Input date required: context=" + context + ", input=" + input, context ); } Date date = format.parse(input); return date; } catch (Exception e) { throw new ValidationException( context + ": Invalid date must follow " + format + " format", "Invalid date: context=" + context + ", format=" + format + ", input=" + input, e, context); } } /* * Returns a valid date as a Date. Invalid input will generate a descriptive ValidationException, * and input that is clearly an attack will generate a descriptive IntrusionException. * * @see org.owasp.esapi.interfaces.IValidator#getValidDate(java.lang.String) */ public Date getValidDate(String context, String input, DateFormat format, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidDate(context, input, format, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return null; } /* * Returns true if input is "safe" HTML. Implementors should reference the OWASP AntiSamy project for ideas * on how to do HTML validation in a whitelist way, as this is an extremely difficult problem. * * @see org.owasp.esapi.interfaces.IValidator#isValidSafeHTML(java.lang.String) */ public boolean isValidSafeHTML(String context, String input, int maxLength, boolean allowNull) throws IntrusionException { try { if ( antiSamyPolicy == null ) { if (ESAPI.securityConfiguration().getResourceDirectory() == null) { //load via classpath ClassLoader loader = getClass().getClassLoader(); InputStream in = null; try { in = loader.getResourceAsStream("antisamy-esapi.xml"); if (in != null) { antiSamyPolicy = Policy.getInstance(in); } } catch (Exception e) { antiSamyPolicy = null; } finally { if (in != null) try { in.close (); } catch (Throwable ignore) {} } if (antiSamyPolicy == null) { throw new IllegalArgumentException ("Can't load antisamy-esapi.xml as a classloader resource"); } } else { //load via fileio antiSamyPolicy = Policy.getInstance( ESAPI.securityConfiguration().getResourceDirectory() + "antisamy-esapi.xml"); } } AntiSamy as = new AntiSamy(); CleanResults test = as.scan(input, antiSamyPolicy); return(test.getErrorMessages().size() == 0); } catch (Exception e) { return false; } } /* * Returns canonicalized and validated "safe" HTML. Implementors should reference the OWASP AntiSamy project for ideas * on how to do HTML validation in a whitelist way, as this is an extremely difficult problem. * * @see org.owasp.esapi.interfaces.IValidator#getValidSafeHTML(java.lang.String) */ public String getValidSafeHTML( String context, String input, int maxLength, boolean allowNull ) throws ValidationException, IntrusionException { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input HTML required", "Input HTML required: context=" + context + ", input=" + input, context ); } if (input.length() > maxLength) { throw new ValidationException( context + ": Invalid HTML. You enterted " + input.length() + " characters. Input can not exceed " + maxLength + " characters.", context + " input exceedes maxLength by " + (input.length()-maxLength) + " characters", context); } try { if ( antiSamyPolicy == null ) { if (ESAPI.securityConfiguration().getResourceDirectory() == null) { //load via classpath ClassLoader loader = getClass().getClassLoader(); InputStream in = null; try { in = loader.getResourceAsStream("antisamy-esapi.xml"); if (in != null) { antiSamyPolicy = Policy.getInstance(in); } } catch (Exception e) { antiSamyPolicy = null; } finally { if (in != null) try { in.close (); } catch (Throwable ignore) {} } if (antiSamyPolicy == null) { throw new IllegalArgumentException ("Can't load antisamy-esapi.xml as a classloader resource"); } } else { //load via fileio antiSamyPolicy = Policy.getInstance( ESAPI.securityConfiguration().getResourceDirectory() + "antisamy-esapi.xml"); } } AntiSamy as = new AntiSamy(); CleanResults test = as.scan(input, antiSamyPolicy); List errors = test.getErrorMessages(); if ( errors.size() > 0 ) { // just create new exception to get it logged and intrusion detected new ValidationException( "Invalid HTML input: context=" + context, "Invalid HTML input: context=" + context + ", errors=" + errors, context ); } return(test.getCleanHTML().trim()); } catch (ScanException e) { throw new ValidationException( context + ": Invalid HTML input", "Invalid HTML input: context=" + context + " error=" + e.getMessage(), e, context ); } catch (PolicyException e) { throw new ValidationException( context + ": Invalid HTML input", "Invalid HTML input does not follow rules in antisamy-esapi.xml: context=" + context + " error=" + e.getMessage(), e, context ); } } /** * ValidationErrorList variant of getValidSafeHTML */ public String getValidSafeHTML(String context, String input, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidSafeHTML(context, input, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /* * Returns true if input is a valid credit card. Maxlength is mandated by valid credit card type. * * @see org.owasp.esapi.interfaces.IValidator#isValidCreditCard(java.lang.String) */ public boolean isValidCreditCard(String context, String input, boolean allowNull) throws IntrusionException { try { getValidCreditCard( context, input, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns a canonicalized and validated credit card number as a String. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidCreditCard(String context, String input, boolean allowNull) throws ValidationException, IntrusionException { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input credit card required", "Input credit card required: context=" + context + ", input=" + input, context ); } String canonical = getValidInput( context, input, "CreditCard", MAX_CREDIT_CARD_LENGTH, allowNull); // perform Luhn algorithm checking StringBuffer digitsOnly = new StringBuffer(); char c; for (int i = 0; i < canonical.length(); i++) { c = canonical.charAt(i); if (Character.isDigit(c)) { digitsOnly.append(c); } } int sum = 0; int digit = 0; int addend = 0; boolean timesTwo = false; for (int i = digitsOnly.length() - 1; i >= 0; i digit = Integer.parseInt(digitsOnly.substring(i, i + 1)); if (timesTwo) { addend = digit * 2; if (addend > 9) { addend -= 9; } } else { addend = digit; } sum += addend; timesTwo = !timesTwo; } int modulus = sum % 10; if (modulus != 0) throw new ValidationException( context + ": Invalid credit card input", "Invalid credit card input: context=" + context, context ); return canonical; } /** * ValidationErrorList variant of getValidCreditCard */ public String getValidCreditCard(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidCreditCard(context, input, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /** * Returns true if the directory path (not including a filename) is valid. * * */ public boolean isValidDirectoryPath(String context, String input, boolean allowNull) throws IntrusionException { try { getValidDirectoryPath( context, input, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns a canonicalized and validated directory path as a String. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidDirectoryPath(String context, String input, boolean allowNull) throws ValidationException, IntrusionException { try { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input directory path required", "Input directory path required: context=" + context + ", input=" + input, context ); } // do basic validation String canonical = getValidInput( context, input, "DirectoryName", 255, false); // get the canonical path without the drive letter if present String cpath = new File(canonical).getCanonicalPath().replaceAll( "\\\\", "/"); String temp = cpath.toLowerCase(); if (temp.length() >= 2 && temp.charAt(0) >= 'a' && temp.charAt(0) <= 'z' && temp.charAt(1) == ':') { cpath = cpath.substring(2); } // prepare the input without the drive letter if present String escaped = canonical.replaceAll( "\\\\", "/"); temp = escaped.toLowerCase(); if (temp.length() >= 2 && temp.charAt(0) >= 'a' && temp.charAt(0) <= 'z' && temp.charAt(1) == ':') { escaped = escaped.substring(2); } // the path is valid if the input matches the canonical path if (!escaped.equals(cpath.toLowerCase())) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context ); } return canonical; } catch (IOException e) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory name does not exist: context=" + context + ", input=" + input, e, context ); } } /** * ValidationErrorList variant of getValidDirectoryPath */ public String getValidDirectoryPath(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidDirectoryPath(context, input, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /** * Returns true if input is a valid file name. */ public boolean isValidFileName(String context, String input, boolean allowNull) throws IntrusionException { try { getValidFileName( context, input, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns a canonicalized and validated file name as a String. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidFileName(String context, String input, boolean allowNull) throws ValidationException, IntrusionException { String canonical = ""; // detect path manipulation try { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input file name required", "Input required: context=" + context + ", input=" + input, context ); } // do basic validation canonical = ESAPI.encoder().canonicalize(input); getValidInput( context, input, "FileName", 255, true ); File f = new File(canonical); String c = f.getCanonicalPath(); String cpath = c.substring(c.lastIndexOf(File.separator) + 1); // the path is valid if the input matches the canonical path if (!input.equals(cpath.toLowerCase())) { throw new ValidationException( context + ": Invalid file name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context ); } } catch (IOException e) { throw new ValidationException( context + ": Invalid file name", "Invalid file name does not exist: context=" + context + ", canonical=" + canonical, e, context ); } catch (EncodingException ee) { throw new IntrusionException( context + ": Invalid file name", "Invalid file name: context=" + context + ", canonical=" + canonical, ee ); } // verify extensions List extensions = ESAPI.securityConfiguration().getAllowedFileExtensions(); Iterator i = extensions.iterator(); while (i.hasNext()) { String ext = (String) i.next(); if (input.toLowerCase().endsWith(ext.toLowerCase())) { return canonical; } } throw new ValidationException( context + ": Invalid file name does not have valid extension ( "+ESAPI.securityConfiguration().getAllowedFileExtensions()+")", "Invalid file name does not have valid extension ( "+ESAPI.securityConfiguration().getAllowedFileExtensions()+"): context=" + context+", input=" + input, context ); } /** * Returns a canonicalized and validated file name as a String. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidFileName(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidFileName(context, input, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /* * Returns true if input is a valid number. * * @see org.owasp.esapi.interfaces.IValidator#isValidNumber(java.lang.String) */ public boolean isValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws IntrusionException { try { getValidNumber(context, input, minValue, maxValue, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns a validated number as a double. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws ValidationException, IntrusionException { Double minDoubleValue = new Double(minValue); Double maxDoubleValue = new Double(maxValue); return getValidDouble(context, input, minDoubleValue.doubleValue(), maxDoubleValue.doubleValue(), allowNull); } public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidNumber(context, input, minValue, maxValue, allowNull); } catch (ValidationException e) { errors.addError(context, e); } //not sure what to return on error return new Double(0); } /* * Returns true if input is a valid number. * * @see org.owasp.esapi.interfaces.IValidator#isValidNumber(java.lang.String) */ public boolean isValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws IntrusionException { return isValidDouble( context, input, minValue, maxValue, allowNull ); } /** * Returns a validated number as a double. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws ValidationException, IntrusionException { if (minValue > maxValue) { //should this be a RunTime? throw new ValidationException( context + ": Invalid double input: context", "Validation parameter error for double: maxValue ( " + maxValue + ") must be greater than minValue ( " + minValue + ") for " + context, context ); } if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input required: context", "Input required: context=" + context + ", input=" + input, context ); } try { Double d = new Double(Double.parseDouble(input)); if (d.isInfinite()) throw new ValidationException( "Invalid double input: context=" + context, "Invalid double input is infinite: context=" + context + ", input=" + input, context ); if (d.isNaN()) throw new ValidationException( "Invalid double input: context=" + context, "Invalid double input is infinite: context=" + context + ", input=" + input, context ); if (d.doubleValue() < minValue) throw new ValidationException( "Invalid double input must be between " + minValue + " and " + maxValue + ": context=" + context, "Invalid double input must be between " + minValue + " and " + maxValue + ": context=" + context + ", input=" + input, context ); if (d.doubleValue() > maxValue) throw new ValidationException( "Invalid double input must be between " + minValue + " and " + maxValue + ": context=" + context, "Invalid double input must be between " + minValue + " and " + maxValue + ": context=" + context + ", input=" + input, context ); return d; } catch (NumberFormatException e) { throw new ValidationException( context + ": Invalid double input", "Invalid double input format: context=" + context + ", input=" + input, e, context); } } public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidDouble(context, input, minValue, maxValue, allowNull); } catch (ValidationException e) { errors.addError(context, e); } //not sure what to return on error return new Double(0); } /* * Returns true if input is a valid number. * * @see org.owasp.esapi.interfaces.IValidator#isValidInteger(java.lang.String) */ public boolean isValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws IntrusionException { try { getValidInteger( context, input, minValue, maxValue, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns a validated number as a double. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws ValidationException, IntrusionException { if (minValue > maxValue) { //should this be a RunTime? throw new ValidationException( context + ": Invalid Integer", "Validation parameter error for double: maxValue ( " + maxValue + ") must be greater than minValue ( " + minValue + ") for " + context, context ); } if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input required", "Input required: context=" + context + ", input=" + input, context ); } try { int i = Integer.parseInt(input); if (i < minValue || i > maxValue ) throw new ValidationException( context + ": Invalid Integer. Value must be between " + minValue + " and " + maxValue, "Invalid int input must be between " + minValue + " and " + maxValue + ": context=" + context + ", input=" + input, context ); return new Integer(i); } catch (NumberFormatException e) { throw new ValidationException( context + ": Invalid integer input", "Invalid int input: context=" + context + ", input=" + input, e, context ); } } public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidInteger(context, input, minValue, maxValue, allowNull); } catch (ValidationException e) { errors.addError(context, e); } //not sure what to return on error return new Integer(0); } /** * Returns true if input is valid file content. */ public boolean isValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws IntrusionException { try { getValidFileContent( context, input, maxBytes, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns validated file content as a byte array. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws ValidationException, IntrusionException { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input required", "Input required: context=" + context + ", input=" + input, context ); } long esapiMaxBytes = ESAPI.securityConfiguration().getAllowedFileUploadSize(); if (input.length > esapiMaxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + esapiMaxBytes + " bytes", "Exceeded ESAPI max length", context ); if (input.length > maxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + maxBytes + " bytes", "Exceeded maxBytes ( " + input.length + ")", context ); return input; } public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidFileContent(context, input, maxBytes, allowNull); } catch (ValidationException e) { errors.addError(context, e); } //not sure what to return on error return input; } /** * Returns true if a file upload has a valid name, path, and content. */ public boolean isValidFileUpload(String context, String directorypath, String filename, byte[] content, int maxBytes, boolean allowNull) throws IntrusionException { return( isValidFileName( context, filename, allowNull ) && isValidDirectoryPath( context, directorypath, allowNull ) && isValidFileContent( context, content, maxBytes, allowNull ) ); } /** * Validates the filepath, filename, and content of a file. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public void assertValidFileUpload(String context, String directorypath, String filename, byte[] content, int maxBytes, boolean allowNull) throws ValidationException, IntrusionException { getValidFileName( context, filename, allowNull ); getValidDirectoryPath( context, directorypath, allowNull ); getValidFileContent( context, content, maxBytes, allowNull ); } /** * ValidationErrorList variant of assertValidFileUpload */ public void assertValidFileUpload(String context, String filepath, String filename, byte[] content, int maxBytes, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { assertValidFileUpload(context, filepath, filename, content, maxBytes, allowNull); } catch (ValidationException e) { errors.addError(context, e); } } /** * Validates the current HTTP request by comparing parameters, headers, and cookies to a predefined whitelist of allowed * characters. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. * * Uses current HTTPRequest saved in EASPI Authenticator */ public boolean isValidHTTPRequest() throws IntrusionException { try { assertIsValidHTTPRequest(); return true; } catch( Exception e ) { return false; } } /** * Validates the current HTTP request by comparing parameters, headers, and cookies to a predefined whitelist of allowed * characters. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public boolean isValidHTTPRequest(HttpServletRequest request) throws IntrusionException { try { assertIsValidHTTPRequest(request); return true; } catch( Exception e ) { return false; } } /** * Validates the current HTTP request by comparing parameters, headers, and cookies to a predefined whitelist of allowed * characters. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. * * Uses current HTTPRequest saved in EASPI Authenticator * */ public void assertIsValidHTTPRequest() throws ValidationException, IntrusionException { HttpServletRequest request = ESAPI.httpUtilities().getCurrentRequest(); assertIsValidHTTPRequest(request); } /** * Validates the current HTTP request by comparing parameters, headers, and cookies to a predefined whitelist of allowed * characters. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ private void assertIsValidHTTPRequest(HttpServletRequest request) throws ValidationException, IntrusionException { if (request == null) { throw new ValidationException( "Input required: HTTP request is null", "Input required: HTTP request is null" ); } if ( !request.getMethod().equals( "GET") && !request.getMethod().equals("POST") ) { throw new IntrusionException( "Bad HTTP method received", "Bad HTTP method received: " + request.getMethod() ); } Iterator i1 = request.getParameterMap().entrySet().iterator(); while (i1.hasNext()) { Map.Entry entry = (Map.Entry) i1.next(); String name = (String) entry.getKey(); getValidInput( "HTTP request parameter: " + name, name, "HTTPParameterName", MAX_PARAMETER_NAME_LENGTH, false ); String[] values = (String[]) entry.getValue(); Iterator i3 = Arrays.asList(values).iterator(); while (i3.hasNext()) { String value = (String) i3.next(); getValidInput( "HTTP request parameter: " + name, value, "HTTPParameterValue", MAX_PARAMETER_VALUE_LENGTH, true ); } } if (request.getCookies() != null) { Iterator i2 = Arrays.asList(request.getCookies()).iterator(); while (i2.hasNext()) { Cookie cookie = (Cookie) i2.next(); String name = cookie.getName(); getValidInput( "HTTP request cookie: " + name, name, "HTTPCookieName", MAX_PARAMETER_NAME_LENGTH, true ); String value = cookie.getValue(); getValidInput( "HTTP request cookie: " + name, value, "HTTPCookieValue", MAX_PARAMETER_VALUE_LENGTH, true ); } } Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (name != null && !name.equalsIgnoreCase( "Cookie")) { getValidInput( "HTTP request header: " + name, name, "HTTPHeaderName", MAX_PARAMETER_NAME_LENGTH, true ); Enumeration e2 = request.getHeaders(name); while (e2.hasMoreElements()) { String value = (String) e2.nextElement(); getValidInput( "HTTP request header: " + name, value, "HTTPHeaderValue", MAX_PARAMETER_VALUE_LENGTH, true ); } } } } /* * Returns true if input is a valid list item. * * @see org.owasp.esapi.interfaces.IValidator#isValidListItem(java.util.List, * java.lang.String) */ public boolean isValidListItem(String context, String input, List list) { try { getValidListItem( context, input, list); return true; } catch( Exception e ) { return false; } } /** * Returns the list item that exactly matches the canonicalized input. Invalid or non-matching input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidListItem(String context, String input, List list) throws ValidationException, IntrusionException { if (list.contains(input)) return input; throw new ValidationException( context + ": Invalid list item", "Invalid list item: context=" + context + ", input=" + input, context ); } /** * ValidationErrorList variant of getValidListItem */ public String getValidListItem(String context, String input, List list, ValidationErrorList errors) throws IntrusionException { try { return getValidListItem(context, input, list); } catch (ValidationException e) { errors.addError(context, e); } return input; } /* * Returns true if the parameters in the current request contain all required parameters and only optional ones in addition. * * @see org.owasp.esapi.interfaces.IValidator#isValidParameterSet(java.util.Set, * java.util.Set, java.util.Set) */ public boolean isValidHTTPRequestParameterSet(String context, Set requiredNames, Set optionalNames) { try { assertIsValidHTTPRequestParameterSet( context, requiredNames, optionalNames); return true; } catch( Exception e ) { return false; } } /** * Validates that the parameters in the current request contain all required parameters and only optional ones in * addition. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public void assertIsValidHTTPRequestParameterSet(String context, Set required, Set optional) throws ValidationException, IntrusionException { HttpServletRequest request = ESAPI.httpUtilities().getCurrentRequest(); Set actualNames = request.getParameterMap().keySet(); // verify ALL required parameters are present Set missing = new HashSet(required); missing.removeAll(actualNames); if (missing.size() > 0) { throw new ValidationException( context + ": Invalid HTTP request missing parameters", "Invalid HTTP request missing parameters " + missing + ": context=" + context, context ); } // verify ONLY optional + required parameters are present Set extra = new HashSet(actualNames); extra.removeAll(required); extra.removeAll(optional); if (extra.size() > 0) { throw new ValidationException( context + ": Invalid HTTP request extra parameters " + extra, "Invalid HTTP request extra parameters " + extra + ": context=" + context, context ); } } /** * ValidationErrorList variant of assertIsValidHTTPRequestParameterSet */ public void assertIsValidHTTPRequestParameterSet(String context, Set required, Set optional, ValidationErrorList errors) throws IntrusionException { try { assertIsValidHTTPRequestParameterSet(context, required, optional); } catch (ValidationException e) { errors.addError(context, e); } } public boolean isValidPrintable(String context, byte[] input, int maxLength, boolean allowNull) throws IntrusionException { try { getValidPrintable( context, input, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns canonicalized and validated printable characters as a byte array. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public byte[] getValidPrintable(String context, byte[] input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException(context + ": Input bytes required", "Input bytes required: HTTP request is null", context ); } if (input.length > maxLength) { throw new ValidationException(context + ": Input bytes can not exceed " + maxLength + " bytes", "Input exceeds maximum allowed length of " + maxLength + " by " + (input.length-maxLength) + " bytes: context=" + context + ", input=" + input, context); } for (int i = 0; i < input.length; i++) { if (input[i] < 33 || input[i] > 126) { throw new ValidationException(context + ": Invalid input bytes: context=" + context, "Invalid non-ASCII input bytes, context=" + context + ", input=" + input, context); } } return input; } /** * ValidationErrorList variant of getValidPrintable */ public byte[] getValidPrintable(String context, byte[] input,int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidPrintable(context, input, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /* * Returns true if input is valid printable ASCII characters (32-126). * * @see org.owasp.esapi.interfaces.IValidator#isValidPrintable(java.lang.String) */ public boolean isValidPrintable(String context, String input, int maxLength, boolean allowNull) throws IntrusionException { try { getValidPrintable( context, input, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns canonicalized and validated printable characters as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidPrintable(String context, String input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException { String canonical = ""; try { canonical = ESAPI.encoder().canonicalize(input); return new String( getValidPrintable( context, canonical.getBytes(), maxLength, allowNull) ); } catch (EncodingException e) { throw new ValidationException( context + ": Invalid printable input", "Invalid encoding of printable input, context=" + context + ", input=" + input, e, context); } } /** * ValidationErrorList variant of getValidPrintable */ public String getValidPrintable(String context, String input,int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidPrintable(context, input, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /** * Returns true if input is a valid redirect location. */ public boolean isValidRedirectLocation(String context, String input, boolean allowNull) throws IntrusionException { return ESAPI.validator().isValidInput( context, input, "Redirect", 512, allowNull); } /** * Returns a canonicalized and validated redirect location as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidRedirectLocation(String context, String input, boolean allowNull) throws ValidationException, IntrusionException { return ESAPI.validator().getValidInput( context, input, "Redirect", 512, allowNull); } /** * ValidationErrorList variant of getValidRedirectLocation */ public String getValidRedirectLocation(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidRedirectLocation(context, input, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /** * This implementation reads until a newline or the specified number of * characters. * * @param in * the in * @param max * the max * @return the string * @throws ValidationException * the validation exception * @see org.owasp.esapi.Validator#safeReadLine(java.io.InputStream, * int) */ public String safeReadLine(InputStream in, int max) throws ValidationException { if (max <= 0) throw new ValidationAvailabilityException( "Invalid input", "Invalid readline. Must read a positive number of bytes from the stream"); StringBuffer sb = new StringBuffer(); int count = 0; int c; try { while (true) { c = in.read(); if ( c == -1 ) { if (sb.length() == 0) return null; break; } if (c == '\n' || c == '\r') break; count++; if (count > max) { throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Read more than maximum characters allowed (" + max + ")"); } sb.append((char) c); } return sb.toString(); } catch (IOException e) { throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Problem reading from input stream", e); } } /** * Helper function to check if a String is empty * * @param input string input value * @return boolean response if input is empty or not */ private final boolean isEmpty(String input) { return (input==null || input.trim().length() == 0); } /** * Helper function to check if a byte array is empty * * @param input string input value * @return boolean response if input is empty or not */ private final boolean isEmpty(byte[] input) { return (input==null || input.length == 0); } }
package org.jamocha.parser; import java.util.Collection; import java.util.Iterator; import org.jamocha.rete.BoundParam; import org.jamocha.rete.Fact; import org.jamocha.rete.Slot; public class JamochaValue { public static final JamochaValue NIL = new JamochaValue(JamochaType.NIL, null); public static final JamochaValue TRUE = new JamochaValue( JamochaType.BOOLEAN, Boolean.valueOf(true)); public static final JamochaValue FALSE = new JamochaValue( JamochaType.BOOLEAN, Boolean.valueOf(false)); public static final JamochaValue EMPTY_LIST = new JamochaValue( JamochaType.LIST, new JamochaValue[] {}); public static JamochaValue singletonList(JamochaValue value) { if (value == null || value.equals(NIL)) { return EMPTY_LIST; } return new JamochaValue(JamochaType.LIST, new JamochaValue[] { value }); } public static JamochaValue newBoolean(boolean value) { return value ? TRUE : FALSE; } public static JamochaValue newLong(long value) { return new JamochaValue(JamochaType.LONG, value); } public static JamochaValue newDouble(double value) { return new JamochaValue(JamochaType.DOUBLE, value); } public static JamochaValue newString(String value) { return new JamochaValue(JamochaType.STRING, value); } public static JamochaValue newObject(Object value) { return new JamochaValue(JamochaType.OBJECT, value); } public static JamochaValue newIdentifier(String value) { return new JamochaValue(JamochaType.IDENTIFIER, value); } public static JamochaValue newFact(Fact value) { return new JamochaValue(JamochaType.FACT, value); } public static JamochaValue newFactId(long value) { return new JamochaValue(JamochaType.FACT_ID, value); } public static JamochaValue newList(JamochaValue[] values) { return new JamochaValue(JamochaType.LIST, values); } public static JamochaValue newBinding(BoundParam value) { return new JamochaValue(JamochaType.BINDING, value); } public static JamochaValue newSlot(Slot value) { return new JamochaValue(JamochaType.SLOT, value); } private JamochaType type; private Object value; private JamochaValue(JamochaType type, Object value) { if (type == null) { throw new IllegalArgumentException("type of a value can't be null."); } if (!JamochaType.NIL.equals(type) && value == null) { throw new IllegalArgumentException("the value for type " + type + " can't be null."); } this.type = type; switch (type) { case BOOLEAN: if (value instanceof Boolean) { this.value = value; } else { this.value = Boolean.TRUE; } break; case DOUBLE: case LONG: if (value instanceof Number) { this.value = value; } else { throw new IllegalArgumentException("the value for type " + type + " must be of type java.lang.Number."); } break; case STRING: if (value instanceof String) { this.value = value; } else { throw new IllegalArgumentException("the value for type " + type + " must be of type java.lang.String."); } break; case FACT: if (value instanceof Fact) { this.value = value; } else { throw new IllegalArgumentException("the value for type " + type + " must be of type org.jamocha.rete.Fact."); } break; case FACT_ID: if (value instanceof Long) { this.value = value; } else { throw new IllegalArgumentException("the value for type " + type + " must be of type java.lang.Long."); } break; case LIST: if (value instanceof JamochaValue[]) { this.value = value; } else { throw new IllegalArgumentException("the value for type " + type + " must be of type org.jamocha.parser.JamochaValue[]."); } break; case NIL: case OBJECT: this.value = value; } this.type = type; this.value = value; } public JamochaValue(Object object) { if (object == null) { type = JamochaType.NIL; } else if (object instanceof Long || object instanceof Integer || object instanceof Short || object instanceof Byte) { value = ((Number) object).longValue(); type = JamochaType.LONG; } else if (object instanceof Double || object instanceof Float) { value = ((Number) object).doubleValue(); type = JamochaType.DOUBLE; } else if (object instanceof String) { value = object; type = JamochaType.STRING; } else if (object instanceof Boolean) { value = object; type = JamochaType.BOOLEAN; } else if (object instanceof Collection) { Collection collection = (Collection) object; JamochaValue[] array = new JamochaValue[collection.size()]; Iterator it = collection.iterator(); for (int i = 0; i < collection.size() && it.hasNext(); ++i) { array[i] = new JamochaValue(it.next()); } } else { value = object; type = JamochaType.OBJECT; } } public JamochaType getType() { return type; } public Object getObjectValue() { return value; } public Slot getSlotValue() { assert (type.equals(JamochaType.SLOT)); return (Slot) value; } public boolean getBooleanValue() { assert (type.equals(JamochaType.BOOLEAN)); return ((Boolean) value).booleanValue(); } public double getDoubleValue() { assert (type.equals(JamochaType.DOUBLE)); return ((Number) value).doubleValue(); } public long getLongValue() { assert (type.equals(JamochaType.LONG)); return ((Number) value).longValue(); } public String getStringValue() { assert (type.equals(JamochaType.STRING)); return (String) value; } public String getIdentifierValue() { assert (type.equals(JamochaType.IDENTIFIER)); return (String) value; } public Fact getFactValue() { assert (type.equals(JamochaType.FACT)); return (Fact) value; } public long getFactIdValue() { assert (type.equals(JamochaType.FACT_ID)); return ((Number) value).longValue(); } public JamochaValue getListValue(int index) { assert (type.equals(JamochaType.LIST)); return ((JamochaValue[]) value)[index]; } public int getListCount() { assert (type.equals(JamochaType.LIST)); return ((JamochaValue[]) value).length; } @Override public String toString() { switch (type) { case NIL: return "NIL"; case STRING: return "\"" + value + "\""; case FACT_ID: return "f-" + value.toString(); case LIST: StringBuilder sb = new StringBuilder(); sb.append('['); JamochaValue[] list = (JamochaValue[]) value; for (int i = 0; i < list.length; ++i) { sb.append(list[i].toString()); if (i < list.length - 1) { sb.append(", "); } } sb.append(']'); return sb.toString(); default: return value.toString(); } } public JamochaValue implicitCast(JamochaType type) throws IllegalConversionException { if (type.equals(JamochaType.UNDEFINED) || type.equals(this.type)) { return this; } if (type.equals(JamochaType.LIST)) { return singletonList(this); } switch (this.type) { case BOOLEAN: switch (type) { case BOOLEAN: return this; case DOUBLE: return JamochaValue .newDouble(((Boolean) value).booleanValue() ? 1.0 : 0.0); case LONG: return JamochaValue .newLong(((Boolean) value).booleanValue() ? 1 : 0); } case DOUBLE: switch (type) { case BOOLEAN: return JamochaValue .newBoolean(((Number) value).doubleValue() != 0.0); case DOUBLE: return this; case LONG: return JamochaValue.newLong(((Number) value).longValue()); } case LONG: switch (type) { case BOOLEAN: return JamochaValue .newBoolean(((Number) value).longValue() != 0); case DOUBLE: return JamochaValue.newDouble(((Number) value).doubleValue()); case LONG: return this; case FACT_ID: return JamochaValue.newFactId((Long)value); } break; case FACT_ID: switch (type) { case BOOLEAN: return JamochaValue .newBoolean(((Number) value).longValue() != 0); case DOUBLE: return JamochaValue.newDouble(((Number) value).doubleValue()); case LONG: return JamochaValue.newLong((Long)value); case FACT_ID: return this; } break; case FACT: switch (type) { case FACT_ID: return JamochaValue.newFactId(((Fact) value).getFactId()); } } throw new IllegalConversionException("Unable to cast " + this.type + " to type " + type + "."); } public boolean is(JamochaType type) { if (this.type.equals(type)) { return true; } return false; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((type == null) ? 0 : type.hashCode()); result = PRIME * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; final JamochaValue other = (JamochaValue) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } }
package org.pentaho.di.repository; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.pentaho.di.core.Const; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.xml.XMLHandler; import org.w3c.dom.Document; import org.w3c.dom.Node; //import java.util.ArrayList; public class RepositoriesMeta { private LogWriter log; private List<DatabaseMeta> databases; // Repository connections private List<RepositoryMeta> repositories; // List of repositories public RepositoriesMeta(LogWriter log) { this.log = log; clear(); } public void clear() { databases = new ArrayList<DatabaseMeta>(); repositories = new ArrayList<RepositoryMeta>(); } public void addDatabase(DatabaseMeta ci) { databases.add(ci); } public void addRepository(RepositoryMeta ri) { repositories.add(ri); } public void addDatabase(int p, DatabaseMeta ci) { databases.add(p, ci); } public void addRepository(int p, RepositoryMeta ri) { repositories.add(p, ri); } public DatabaseMeta getDatabase(int i) { return (DatabaseMeta)databases.get(i); } public RepositoryMeta getRepository(int i) { return (RepositoryMeta)repositories.get(i); } public void removeDatabase(int i) { if (i<0 || i>=databases.size()) return; databases.remove(i); } public void removeRepository(int i) { if (i<0 || i>=repositories.size()) return; repositories.remove(i); } public int nrDatabases() { return databases.size(); } public int nrRepositories() { return repositories.size(); } public DatabaseMeta searchDatabase(String name) { for (int i=0;i<nrDatabases();i++) { if (getDatabase(i).getName().equalsIgnoreCase(name)) return getDatabase(i); } return null; } public RepositoryMeta searchRepository(String name) { for (int i=0;i<nrRepositories();i++) { String repName=getRepository(i).getName(); if (repName!=null && repName.equalsIgnoreCase(name)) return getRepository(i); } return null; } public int indexOfDatabase(DatabaseMeta di) { return databases.indexOf(di); } public int indexOfRepository(RepositoryMeta ri) { return repositories.indexOf(ri); } public RepositoryMeta findRepository(String name) { for (int i=0;i<nrRepositories();i++) { RepositoryMeta ri = getRepository(i); if (ri.getName().equalsIgnoreCase(name)) return ri; } return null; } // We read the repositories from the file: public boolean readData() { File file = new File(Const.getKettleLocalRepositoriesFile()); if (!file.exists() || !file.isFile()) { log.logDetailed(toString(), "No repositories file found in the local directory: "+file.getAbsolutePath()); file = new File(Const.getKettleUserRepositoriesFile()); } log.logBasic(toString(), "Reading repositories XML file: "+file.getAbsoluteFile()); DocumentBuilderFactory dbf; DocumentBuilder db; Document doc; try { // Check and open XML document dbf = DocumentBuilderFactory.newInstance(); db = dbf.newDocumentBuilder(); try { doc = db.parse(file); } catch(FileNotFoundException ef) { InputStream is = getClass().getResourceAsStream("/org/pentaho/di/repository/repositories.xml"); if (is!=null) { doc = db.parse(is); } else { log.logError(toString(), "Error opening file: "+file.getAbsoluteFile()+" : "+ef.toString()); return false; } } // InfoHandler sir = new InfoHandler(doc); // Clear the information clear(); // Get the <repositories> node: Node repsnode = XMLHandler.getSubNode(doc, "repositories"); // Handle connections int nrconn = XMLHandler.countNodes(repsnode, "connection"); log.logDebug(toString(), "We have "+nrconn+" connections..."); for (int i=0;i<nrconn;i++) { log.logDebug(toString(), "Looking at connection Node dbnode = XMLHandler.getSubNodeByNr(repsnode, "connection", i); DatabaseMeta dbcon = new DatabaseMeta(dbnode); addDatabase(dbcon); log.logDebug(toString(), "Read connection : "+dbcon.getName()); } // Handle repositories... int nrreps = XMLHandler.countNodes(repsnode, "repository"); log.logDebug(toString(), "We have "+nrreps+" repositories..."); for (int i=0;i<nrreps;i++) { Node repnode = XMLHandler.getSubNodeByNr(repsnode, "repository", i); log.logDebug(toString(), "Looking at repository RepositoryMeta repinfo = new RepositoryMeta(); if (repinfo.loadXML(repnode, databases)) { addRepository(repinfo); log.logDebug(toString(), "Read repository : "+repinfo.getName()); } } } catch(Exception e) { log.logError(toString(), "Error reading information from file : "+e.toString()); log.logError(toString(), Const.getStackTracker(e)); clear(); return false; } return true; } public String getXML() { String retval=""; retval+="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+Const.CR; retval+="<repositories>"+Const.CR; for (int i=0;i<nrDatabases();i++) { DatabaseMeta conn = getDatabase(i); retval+=conn.getXML(); } for (int i=0;i<nrRepositories();i++) { RepositoryMeta ri = getRepository(i); retval+=ri.getXML(); } retval+=" </repositories>"+Const.CR; return retval; } public boolean writeData() { try { //TODO fix default repository creation to use LAF parameters FileOutputStream fos = new FileOutputStream(new File(Const.getKettleUserRepositoriesFile())); fos.write(getXML().getBytes()); fos.close(); } catch(FileNotFoundException e) { log.logError("Repository", "Writing repository we got error : "+e.toString()); return false; } catch(IOException ie) { log.logError("Repository", "Writing repository we got IO error : "+ie.toString()); return false; } return true; } public String toString() { return getClass().getSimpleName(); } }
package org.pentaho.di.trans.steps.addxml; import org.pentaho.di.core.row.ValueMeta; /** * Describes a single field in an XML output file * * @author Matt * @since 14-jan-2006 * */ public class XMLField implements Cloneable { private String fieldName; private String elementName; private int type; private String format; private int length; private int precision; private String currencySymbol; private String decimalSymbol; private String groupingSymbol; private boolean attribute; private String nullString; public XMLField(String fieldName, String elementName, int type, String format, int length, int precision, String currencySymbol, String decimalSymbol, String groupSymbol, String nullString, boolean attribute) { this.fieldName = fieldName; this.elementName = elementName; this.type = type; this.format = format; this.length = length; this.precision = precision; this.currencySymbol = currencySymbol; this.decimalSymbol = decimalSymbol; this.groupingSymbol = groupSymbol; this.nullString = nullString; this.attribute = attribute; } public XMLField() { } public int compare(Object obj) { XMLField field = (XMLField)obj; return fieldName.compareTo(field.getFieldName()); } public boolean equal(Object obj) { XMLField field = (XMLField)obj; return fieldName.equals(field.getFieldName()); } public Object clone() { try { Object retval = super.clone(); return retval; } catch(CloneNotSupportedException e) { return null; } } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public String getFieldName() { return fieldName; } public void setFieldName(String fieldname) { this.fieldName = fieldname; } public int getType() { return type; } public String getTypeDesc() { return ValueMeta.getTypeDesc(type); } public void setType(int type) { this.type = type; } public void setType(String typeDesc) { this.type = ValueMeta.getType(typeDesc); } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public String getGroupingSymbol() { return groupingSymbol; } public void setGroupingSymbol(String group_symbol) { this.groupingSymbol = group_symbol; } public String getDecimalSymbol() { return decimalSymbol; } public void setDecimalSymbol(String decimal_symbol) { this.decimalSymbol = decimal_symbol; } public String getCurrencySymbol() { return currencySymbol; } public void setCurrencySymbol(String currency_symbol) { this.currencySymbol = currency_symbol; } public int getPrecision() { return precision; } public void setPrecision(int precision) { this.precision = precision; } public String getNullString() { return nullString; } public void setNullString(String null_string) { this.nullString = null_string; } public String toString() { return fieldName+":"+getTypeDesc()+":"+elementName; } /** * @return Returns the elementName. */ public String getElementName() { return elementName; } /** * @param elementName The elementName to set. */ public void setElementName(String elementName) { this.elementName = elementName; } /** * Flags if the field should be encoded as attribute instead of a child node. * @return */ public boolean isAttribute() { return attribute; } public void setAttribute(boolean attribute) { this.attribute = attribute; } }
package org.stagemonitor.logging; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.stagemonitor.core.metrics.metrics2.MetricName.name; import java.util.Map; import com.codahale.metrics.Meter; import com.codahale.metrics.SharedMetricRegistries; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.stagemonitor.core.Stagemonitor; import org.stagemonitor.core.metrics.metrics2.MetricName; public class MeterLoggingInstrumenterTest { private Logger logger = LoggerFactory.getLogger(getClass()); @BeforeClass public static void attachProfiler() { Stagemonitor.init(); } @AfterClass public static void clear() { Stagemonitor.reset(); SharedMetricRegistries.clear(); } @Test public void testLogging() throws Exception { logger.error("test"); final Map<MetricName, Meter> meters = Stagemonitor.getMetric2Registry().getMeters(); assertNotNull(meters.get(name("logging").tag("log_level", "error").build())); assertEquals(1, meters.get(name("logging").tag("log_level", "error").build()).getCount()); } }
package org.subethamail.core.injector; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.BlockingQueue; import javax.annotation.security.RolesAllowed; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.inject.Current; import javax.mail.Address; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.subethamail.common.MailUtils; import org.subethamail.common.NotFoundException; import org.subethamail.common.SubEthaMessage; import org.subethamail.common.io.LimitExceededException; import org.subethamail.common.io.LimitingInputStream; import org.subethamail.core.admin.i.Encryptor; import org.subethamail.core.admin.i.ExpiredException; import org.subethamail.core.filter.FilterRunner; import org.subethamail.core.injector.i.Injector; import org.subethamail.core.plugin.i.HoldException; import org.subethamail.core.plugin.i.IgnoreException; import org.subethamail.core.post.OutboundMTA; import org.subethamail.core.post.PostOffice; import org.subethamail.core.queue.InjectedQueueItem; import org.subethamail.core.util.OwnerAddress; import org.subethamail.core.util.SubEtha; import org.subethamail.core.util.SubEthaEntityManager; import org.subethamail.core.util.VERPAddress; import org.subethamail.entity.EmailAddress; import org.subethamail.entity.Mail; import org.subethamail.entity.MailingList; import org.subethamail.entity.Person; import org.subethamail.entity.Subscription; import org.subethamail.entity.Mail.HoldType; import org.subethamail.entity.i.Permission; import com.caucho.config.Name; /** * @author Jeff Schnitzer * @author Scott Hernandez */ @Stateless(name="Injector") @RolesAllowed(Person.ROLE_ADMIN) @TransactionAttribute(TransactionAttributeType.REQUIRED) public class InjectorBean implements Injector { private final static Logger log = LoggerFactory.getLogger(InjectorBean.class); /** * We bounce injected messages larger than this amount, in bytes. * Must be hardcoded because JavaMail creates a byte[] representation, * and we don't want huge files taking down our JVM. */ public static final int MAX_MESSAGE_BYTES = 1000 * 1000 * 10; /** * The oldest bounce message we are willing to consider valid. This * is to prevent anyone that finds an old bounce token for a user * from using it to mailiciously unsubscribe that person. */ public static final long MAX_BOUNCE_AGE_MILLIS = 1000 * 60 * 60 * 24 * 7; /** * The maximum bounce count at which we disable mail delivery for a user. * This is not actually a literal number of bounces, it's a number that * tends to go up as bounces occur and tends to go down when bounces do * not occur. */ public static final long MAX_BOUNCE_THRESHOLD = 7; /** * Minimum number of milliseconds between hold notification emails. It might * be longer if a steady stream arrives. The logic actually only sends a * notification if it has been more than this interval since the last message * from the user was held. Currently 24 hours. */ public static final long MIN_HOLD_NOTIFICATION_INTERVAL_MILLIS = 1000 * 60 * 60 * 24; /** * How far back to look for the parent of a message by subject. */ public static final long MAX_SUBJECT_THREAD_PARENT_AGE_MILLIS = 1000L * 60L * 60L * 24L * 30L; /** The "inbound queue" which processes injections */ @SuppressWarnings("unchecked") // @InjectQueue @Name("inject") BlockingQueue inboundQueue; @Current FilterRunner filterRunner; @Current Encryptor encryptor; @Current Detacher detacher; @Current PostOffice postOffice; @OutboundMTA private Session mailSession; @SubEtha protected SubEthaEntityManager em; /* * (non-Javadoc) * @see org.subethamail.core.injector.i.Injector#accept(java.lang.String) */ public boolean accept(String toAddress) { if (log.isDebugEnabled()) log.debug("Checking if we want address " + toAddress); try { InternetAddress addy = new InternetAddress(toAddress); // Maybe it's a VERP bounce? VERPAddress verp = VERPAddress.getVERPBounce(addy.getAddress()); if (verp != null) addy = new InternetAddress(verp.getEmail()); // check if this is for a list here else { // Maybe it's an owner address? String ownerList = OwnerAddress.getList(addy.getAddress()); if (ownerList != null) addy = new InternetAddress(ownerList); } try { this.em.getMailingList(addy); return true; } catch (NotFoundException ex) { return false; } } catch (MessagingException ex) { throw new RuntimeException(ex); } } /* * (non-Javadoc) * @see org.subethamail.core.injector.i.Injector#inject(java.lang.String, java.lang.String, byte[]) */ public boolean inject(String fromAddress, String toAddress, byte[] mailData) throws LimitExceededException { return this.inject(fromAddress, toAddress, new ByteArrayInputStream(mailData)); } /* * (non-Javadoc) * @see org.subethamail.core.injector.i.Injector#inject(java.lang.String, java.lang.String, byte[]) */ public boolean inject(String envelopeSender, String envelopeRecipient, InputStream mailData) throws LimitExceededException { if (log.isDebugEnabled()) { if (!mailData.markSupported()) mailData = new BufferedInputStream(mailData); mailData.mark(8192); } try { return this.injectImpl(envelopeSender, envelopeRecipient, mailData); } catch (LimitExceededException ex) { throw ex; } catch (Exception ex) { if (log.isDebugEnabled()) { try { mailData.reset(); Reader reader = new InputStreamReader(mailData); StringBuilder builder = new StringBuilder(); while (reader.ready()) builder.append((char)reader.read()); log.debug("Mail body was: " + builder); } catch (IOException e) {} } if (ex instanceof RuntimeException) throw (RuntimeException)ex; else throw new RuntimeException(ex); } } /** * Factors out the exception catching. */ @SuppressWarnings("unchecked") protected boolean injectImpl(String envelopeSender, String envelopeRecipient, InputStream mailData) throws MessagingException, LimitExceededException, IOException { if (log.isDebugEnabled()) log.debug("Injecting message sent to " + envelopeRecipient); InternetAddress recipientAddy = new InternetAddress(envelopeRecipient); // Must check for recipient VERP bounce VERPAddress recipientVerp = VERPAddress.getVERPBounce(recipientAddy.getAddress()); if (recipientVerp != null) { this.handleBounce(recipientVerp); return true; } // Check for -owner mail String listForOwner = OwnerAddress.getList(envelopeRecipient); if (listForOwner != null) recipientAddy = new InternetAddress(listForOwner); // Figure out which list this is for MailingList toList; try { toList = this.em.getMailingList(recipientAddy); } catch (NotFoundException ex) { log.error("Unknown destination: " + recipientAddy); return false; } if (log.isDebugEnabled()) log.debug("Message is for list: " + toList); // Parse up the message mailData = new LimitingInputStream(mailData, MAX_MESSAGE_BYTES); SubEthaMessage msg = new SubEthaMessage(this.mailSession, mailData); // If the message is looping, silently accept and drop it. The // X-Loop header is added by the deliverator. if (msg.hasXLoop(toList.getEmail())) return true; // Now that we have the basic building blocks, see if we // should be forwarding the mail to owners instead if (listForOwner != null) { this.handleOwnerMail(toList, msg); return true; } // Make sure we have a unique message id if (this.isDuplicateMessage(toList, msg)) msg.replaceMessageID(); // If it stays null, no moderation required HoldType hold = null; String holdMsg = null; // Run it through the plugin stack try { this.filterRunner.onInject(msg, toList); } catch (IgnoreException ex) { if (log.isDebugEnabled()) log.debug("Plugin ignoring message", ex); // Maybe we should return false instead? return true; } catch (HoldException ex) { if (log.isDebugEnabled()) log.debug("Plugin holding message", ex); hold = HoldType.HARD; holdMsg = ex.getMessage(); } // Find out if the message should be held for moderation if (hold == null) hold = this.holdOrNot(msg, envelopeSender, toList); if (log.isDebugEnabled()) log.debug("Hold? " + hold); Mail mail = new Mail(envelopeSender, msg, toList, hold); this.em.persist(mail); this.em.flush(); // Convert all binary attachments to references and then set the content this.detacher.detach(msg, mail); mail.setContent(msg); if (mail.getHold() != null) { InternetAddress senderAddy = msg.getSenderWithFallback(envelopeSender); if (senderAddy != null) { // We don't want to send too many of these notification messages // because they might cause too much backscatter from spam. We // compromise on sending at most one per time period. Date cutoff = new Date(System.currentTimeMillis() - MIN_HOLD_NOTIFICATION_INTERVAL_MILLIS); int recentHolds = this.em.countRecentHeldMail(senderAddy.getAddress(), cutoff); if (recentHolds <= 1) // count includes the current held msg { // Send instructions so that user can self-moderate // Or send a message saying "you must wait for admin approval", use holdMsg if available this.postOffice.sendPosterMailHoldNotice(toList, senderAddy.getAddress(), mail, holdMsg); } } if (hold == HoldType.HARD) { for (Subscription sub: toList.getSubscriptions()) { if (sub.getRole().getPermissions().contains(Permission.APPROVE_MESSAGES)) if (sub.getDeliverTo() != null) this.postOffice.sendModeratorMailHoldNotice(sub.getDeliverTo(), toList, mail, msg, holdMsg); } } } else { this.threadMail(mail, msg); try { this.inboundQueue.put(new InjectedQueueItem(mail)); } catch (InterruptedException ex) { throw new RuntimeException(ex); } } return true; } /** * Note that holding a message is an "or" process, checking the * Sender field, each of the From fields (there can be more than * one), and the envelope sender. Anything that allows the message * to go through is ok. Also note that HARD overrides * SOFT. * * @return the appropriate hold for the message to the given list, or null * if no hold is necessary and the email can go through. */ protected HoldType holdOrNot(SubEthaMessage msg, String envelopeSender, MailingList toList) throws MessagingException { // Note that any and all of these fields could be null. HoldType hold = this.holdOrNot((InternetAddress)msg.getSender(), toList); if (hold == null) return null; Address[] froms = msg.getFrom(); if (froms != null) { for (Address addy: froms) { HoldType fromHold = this.holdOrNot((InternetAddress)addy, toList); if (fromHold == null) return null; else hold = this.prioritize(hold, fromHold); } } InternetAddress envelope = new InternetAddress(envelopeSender); HoldType envHold = this.holdOrNot(envelope, toList); if (envHold == null) return null; else return this.prioritize(hold, envHold); } /** * The "priorities" of holds - HARD overrides SOFT, but null overrides both */ protected HoldType prioritize(HoldType a, HoldType b) { if (a == null || b == null) return null; else if (a.equals(HoldType.HARD) || b.equals(HoldType.HARD)) return HoldType.HARD; else return HoldType.SOFT; } /** * @return the appropriate hold for the given sender to the specified list, * or null if there should be no hold. */ protected HoldType holdOrNot(InternetAddress senderAddy, MailingList toList) { // Figure out who sent it, if we know Person author = null; if (senderAddy != null) { EmailAddress addy = this.em.findEmailAddress(senderAddy.getAddress()); if (addy != null) author = addy.getPerson(); } if (log.isDebugEnabled()) log.debug("Checking hold status for " + author + " to list " + toList.getName()); if (toList.getPermissionsFor(author).contains(Permission.POST)) { return null; } else { // If the user is actually a subscriber, let's make it a HARD hold so the // moderators are alerted. if (author != null && author.getSubscription(toList.getId()) != null) return HoldType.HARD; else return HoldType.SOFT; } } /* * (non-Javadoc) * @see org.subethamail.core.injector.i.Injector#importMessage(java.lang.Long, java.lang.String, java.io.InputStream, boolean, java.util.Date) */ public Date importMessage(Long listId, String envelopeSender, InputStream mailData, boolean ignoreDuplicate, Date fallbackDate) throws NotFoundException { if (log.isDebugEnabled()) log.debug("Importing message from " + envelopeSender + " into list " + listId); try { // Figure out which list this is for MailingList toList = this.em.get(MailingList.class, listId); // Parse up the message mailData = new LimitingInputStream(mailData, MAX_MESSAGE_BYTES); SubEthaMessage msg = new SubEthaMessage(this.mailSession, mailData); // Check to see if the message is a duplicate. if (this.isDuplicateMessage(toList, msg)) { // Are we dropping duplicates? if (ignoreDuplicate) return msg.getSentDate(); else msg.replaceMessageID(); } // If it stays null, no moderation required HoldType hold = null; // Run it through the plugin stack try { this.filterRunner.onInject(msg, toList); } catch (IgnoreException ex) { if (log.isDebugEnabled()) log.debug("Plugin ignoring message", ex); return msg.getSentDate(); } catch (HoldException ex) { if (log.isDebugEnabled()) log.debug("Plugin holding message", ex); hold = HoldType.HARD; } Date sentDate = msg.getSentDate(); if (sentDate == null) sentDate = fallbackDate; Mail mail = new Mail(envelopeSender, msg, toList, hold, sentDate); this.em.persist(mail); // Convert all binary attachments to references and then set the content this.detacher.detach(msg, mail); mail.setContent(msg); if (mail.getHold() == null) this.threadMail(mail, msg); return msg.getSentDate(); } catch (MessagingException ex) { throw new RuntimeException(ex); } catch (IOException ex) { throw new RuntimeException(ex); } } /** * Forwards the message to all owners of the list. The return * address will be VERPed. * * @param list list whose owner(s) should receive the mail * @param msg is the message to forward */ protected void handleOwnerMail(MailingList list, SubEthaMessage msg) throws MessagingException { for (Subscription sub: list.getSubscriptions()) { if (sub.getRole().isOwner() && sub.getDeliverTo() != null) { Address destination = new InternetAddress(sub.getDeliverTo().getId()); // Set up the VERP bounce address byte[] token = this.encryptor.encryptString(sub.getDeliverTo().getId()); msg.setEnvelopeFrom(VERPAddress.encodeVERP(list.getEmail(), token)); Transport.send(msg, new Address[] { destination }); sub.getDeliverTo().bounceDecay(); } } } /** * @return true if a message with the id already exists in the list */ protected boolean isDuplicateMessage(MailingList list, SubEthaMessage msg) throws MessagingException { String messageId = msg.getMessageID(); if (messageId != null) { try { this.em.getMailByMessageId(list.getId(), messageId); return true; } catch (NotFoundException ex) { return false; } } return true; } /** * Handle a bounce message. Note we don't really care what the * message data was, just what the VERP address was. */ protected void handleBounce(VERPAddress verp) { if (log.isDebugEnabled()) log.debug("Handling bounce from list " + verp.getEmail()); try { String originalEmail = this.encryptor.decryptString(verp.getToken(), MAX_BOUNCE_AGE_MILLIS); if (log.isDebugEnabled()) log.debug("Bounced from " + originalEmail); EmailAddress found = this.em.getEmailAddress(originalEmail); found.bounceIncrement(); if (found.getBounces() > MAX_BOUNCE_THRESHOLD) { // Unsubscribe the address from any delivery for (Subscription sub: found.getPerson().getSubscriptions().values()) { if (found.equals(sub.getDeliverTo())) { sub.setDeliverTo(null); if (log.isWarnEnabled()) log.warn("Stopping delivery of " + sub.getList().getName() + " to " + found.getId() + " due to excessive bounces"); } } // TODO: somehow notify the person, perhaps at one of their other addresses? // TODO: notify the administrator? } } catch (NotFoundException ex) { // User already unsubscribed the address, great log.debug("Address already removed"); } catch (ExpiredException ex) { // Token is too old, ignore it log.debug("Token is too old"); } catch (GeneralSecurityException ex) { // Problem decoding the token? Someone's messing with us. log.debug("Token is invalid"); } } /** * Places the mail in a thread hierarchy, possibly updating a variety * of other mails which are part of the hierarchy. * * When this completes, the mail may have a parent and children. */ protected void threadMail(Mail mail, SubEthaMessage msg) throws MessagingException { if (log.isDebugEnabled()) log.debug("Threading mail " + mail); // STEP ONE: Figure who we want to be our parent. List<String> wantedReference = new ArrayList<String>(); // If there is an InReplyTo, that tops the list String inReplyTo = msg.getInReplyTo(); if (inReplyTo != null) wantedReference.add(inReplyTo); // Now add the references field. Careful that the // last reference might be duplicate of inReplyTo String[] references = msg.getReferences(); if (references != null) { // Walk it backwards because recent refs are at the end for (int i=(references.length-1); i>=0; i { if (!wantedReference.contains(references[i])) wantedReference.add(references[i]); } } if (log.isDebugEnabled()) log.debug("Wanted references is " + wantedReference); // STEP TWO: Find an acceptable candidate to be our thread parent, // and eliminate any candidates that are inferior. Mail parent = null; for (int i=0; i<wantedReference.size(); i++) { String candidate = wantedReference.get(i); try { parent = this.em.getMailByMessageId(mail.getList().getId(), candidate); if (log.isDebugEnabled()) log.debug("Found parent at choice " + i + ", max " + (wantedReference.size()-1)); // Got one, eliminate anything from wantedReference that is at this // level or later. Do it from the end to make ArrayList happy. for (int delInd=wantedReference.size()-1; delInd>=i; delInd wantedReference.remove(delInd); break; } catch (NotFoundException ex) {} } // If that didn't help us, try the desperate step of matching on subject if (parent == null) { String subj = mail.getSubject(); subj = MailUtils.cleanRe(subj); Date cutoff = new Date(System.currentTimeMillis() - MAX_SUBJECT_THREAD_PARENT_AGE_MILLIS); // This is a little ugly - grab two because the current mail will show up in the search List<Mail> found = this.em.findRecentMailBySubject(mail.getList().getId(), subj, cutoff, 2); for (Mail foundMail: found) { // The current mail itself should show up in the search if (foundMail == mail) continue; parent = foundMail; if (log.isDebugEnabled()) log.debug("Found parent using subject match"); break; } } if (log.isDebugEnabled()) log.debug("Best thread ancestor found is " + parent); // Intermission - we can now set the mail's parent and wantedReference if (parent != null) { mail.setParent(parent); parent.getReplies().add(mail); } mail.setWantedReference(wantedReference); // STEP THREE: Find anyone looking for us as a parent and insert us in // their thread ancestry. Watch out for loops. List<Mail> descendants = this.em.findMailWantingParent(mail.getList().getId(), mail.getMessageId()); outer: for (Mail descendant: descendants) { if (log.isDebugEnabled()) log.debug("Replacing parent of " + descendant); // Check for a loop Mail checkForLoop = descendant; while (checkForLoop != null) { if (checkForLoop == mail) { if (log.isWarnEnabled()) log.warn("Found a mail loop, parent=" + mail + ", child=" + descendant); // Ignore this link and remove the wanted rerference descendant.getWantedReference().remove(mail.getMessageId()); continue outer; } checkForLoop = checkForLoop.getParent(); } // Remove from the old parent, if exists if (descendant.getParent() != null) { Mail oldParent = descendant.getParent(); oldParent.getReplies().remove(descendant); } // Add the new parent descendant.setParent(mail); mail.getReplies().add(descendant); // Prune the wantedReference collection, possibly to empty List<String> wanted = descendant.getWantedReference(); for (int i=wanted.size()-1; i>=0; i { String removed = wanted.remove(i); if (mail.getMessageId().equals(removed)) break; } } } }
package stroom.data.retention.shared; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Objects; @JsonInclude(Include.NON_NULL) public class DataRetentionDeleteSummary { @JsonProperty private final String feedName; @JsonProperty private final String metaType; @JsonProperty private final int ruleNumber; @JsonProperty private final String ruleName; @JsonProperty private final int count; @JsonCreator public DataRetentionDeleteSummary(@JsonProperty("feedName") final String feedName, @JsonProperty("metaType") final String metaType, @JsonProperty("ruleNumber") final int ruleNumber, @JsonProperty("ruleName") final String ruleName, @JsonProperty("count") final int count) { this.feedName = Objects.requireNonNull(feedName); this.metaType = Objects.requireNonNull(metaType); this.ruleNumber = ruleNumber; this.ruleName = Objects.requireNonNull(ruleName); this.count = count; } public String getFeedName() { return feedName; } public String getMetaType() { return metaType; } public int getRuleNumber() { return ruleNumber; } public String getRuleName() { return ruleName; } public int getCount() { return count; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DataRetentionDeleteSummary that = (DataRetentionDeleteSummary) o; return ruleNumber == that.ruleNumber && count == that.count && feedName.equals(that.feedName) && metaType.equals(that.metaType) && ruleName.equals(that.ruleName); } @Override public int hashCode() { return Objects.hash(feedName, metaType, ruleNumber, ruleName, count); } }
package org.jboss.as.subsystem.test; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEFAULT_INTERFACE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INET_ADDRESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INTERFACE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PATH; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PORT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PORT_OFFSET; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RELATIVE_TO; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SYSTEM_PROPERTY; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.Resource; import org.jboss.as.controller.resource.InterfaceDefinition; import org.jboss.as.controller.services.path.PathManagerService; import org.jboss.as.controller.services.path.PathResourceDefinition; import org.jboss.as.server.ServerEnvironment; import org.jboss.as.server.controller.resources.SystemPropertyResourceDefinition; import org.jboss.as.server.services.net.SocketBindingGroupResourceDefinition; import org.jboss.as.server.services.net.SpecifiedInterfaceAddHandler; import org.jboss.as.server.services.net.SpecifiedInterfaceRemoveHandler; import org.jboss.dmr.ModelNode; /** * Allows easy initialization of parts of the model that subsystems frequently need * * @author <a href="kabir.khan@jboss.com">Kabir Khan</a> */ public class ControllerInitializer { public static final String INTERFACE_NAME = "test-interface"; public static final String SOCKET_BINDING_GROUP_NAME = "test-socket-binding-group"; protected volatile String bindAddress = "localhost"; protected volatile String portOffset; protected final Map<String, String> systemProperties = new HashMap<String, String>(); protected final Map<String, Integer> socketBindings = new HashMap<String, Integer>(); protected final Map<String, OutboundSocketBinding> outboundSocketBindings = new HashMap<String, OutboundSocketBinding>(); protected final Map<String, PathInfo> paths = new HashMap<String, PathInfo>(); private volatile PathManagerService pathManager; private volatile TestControllerAccessor testControllerAccessor; /** * Sets the controller being created. Internal use only. * * @param testControllerAccessor the controller being created. */ void setTestModelControllerAccessor(TestControllerAccessor testControllerAccessor) { this.testControllerAccessor = testControllerAccessor; } void setPathManger(PathManagerService pathManager) { this.pathManager = pathManager; } /** * Adds a system property to the model. * This initializes the system property part of the model with the operations to add it. * * @param key the system property name * @param value the system property value */ public void addSystemProperty(String key, String value) { if (key == null) { throw new IllegalArgumentException("Null key"); } if (value == null) { throw new IllegalArgumentException("Null value"); } systemProperties.put(key, value); } /** * Sets the bindAddress that will be used for socket bindings. * The default is 'localhost' * * @param address the default bind address */ public void setBindAddress(String address) { if (address == null) { throw new IllegalArgumentException("Null address"); } bindAddress = address; } /** * Adds a socket binding to the model. * This initializes the interface and socket binding group part of the model with the operations to add it. * * @param name the socket binding name * @param port the socket binding port */ public void addSocketBinding(String name, int port) { if (name == null) { throw new IllegalArgumentException("Null name"); } if (port < 0) { throw new IllegalArgumentException("Null port"); } socketBindings.put(name, port); } /** * Adds a remote outbound socket binding to the model. * * @param name the socket binding name * @param destinationHost The destination host * @param destinationPort the destination port */ public void addRemoteOutboundSocketBinding(final String name, final String destinationHost, final int destinationPort) { if (name == null) { throw new IllegalArgumentException("Null name"); } if (destinationPort < 0) { throw new IllegalArgumentException("Negative destination port"); } if (destinationHost == null || destinationHost.trim().isEmpty()) { throw new IllegalArgumentException("Null or empty destination host"); } outboundSocketBindings.put(name, new OutboundSocketBinding(destinationHost, destinationPort, true)); } /** * Adds a path to the model * This initializes the path part of the model with the operations to add it. * * @param name the name of the path * @param path the absolute path, or the name of a path (if used with {@code relativeTo} * @param relativeTo a path relative to {@code path} */ public void addPath(String name, String path, String relativeTo) { if (name == null) { throw new IllegalArgumentException("Null name"); } if (path == null) { throw new IllegalArgumentException("Null path"); } PathInfo pathInfo = new PathInfo(name, path, relativeTo); paths.put(name, pathInfo); } /** * Adds the port offset to the model (optional). * * @param portOffset the port offset ({@code null} means no offset will be added) */ public void setPortOffset(String portOffset) { this.portOffset = portOffset; } /** * Called by framework to set up the model * * @param rootResource the root model resource * @param rootRegistration the root model registry */ protected void initializeModel(Resource rootResource, ManagementResourceRegistration rootRegistration) { initializeSystemPropertiesModel(rootResource, rootRegistration); initializeSocketBindingsModel(rootResource, rootRegistration); initializePathsModel(rootResource, rootRegistration); } /** * Called by framework to get the additional boot operations * * @return the additional boot operations */ protected List<ModelNode> initializeBootOperations(){ List<ModelNode> ops = new ArrayList<ModelNode>(); initializeSystemPropertiesOperations(ops); initializePathsOperations(ops); initializeSocketBindingsOperations(ops); initializeRemoteOutboundSocketBindingsOperations(ops); return ops; } /** * Initializes the system properties part of the model * * @param rootResource the root model resource * @param rootRegistration the root model registry */ protected void initializeSystemPropertiesModel(Resource rootResource, ManagementResourceRegistration rootRegistration) { if (systemProperties.size() == 0) { return; } rootResource.getModel().get(SYSTEM_PROPERTY); rootRegistration.registerSubModel(SystemPropertyResourceDefinition.createForStandaloneServer(testControllerAccessor.getServerEnvironment())); } /** * Initializes the interface, socket binding group and socket binding part of the model * * @param rootResource the root model resource * @param rootRegistration the root model registry */ protected void initializeSocketBindingsModel(Resource rootResource, ManagementResourceRegistration rootRegistration) { if (socketBindings.size() == 0 && outboundSocketBindings.isEmpty()) { return; } rootResource.getModel().get(INTERFACE); rootResource.getModel().get(SOCKET_BINDING_GROUP); MethodHandles.Lookup lookup = MethodHandles.lookup(); try { //= lookup.findConstructor(InterfaceDefinition.class, MethodType.methodType(void.class, InterfaceAddHandler.class, OperationStepHandler.class, boolean.class, boolean.class)); MethodHandle handle = lookup.unreflectConstructor(InterfaceDefinition.class.getConstructors()[0]); InterfaceDefinition id = (InterfaceDefinition)handle.invoke(SpecifiedInterfaceAddHandler.INSTANCE, SpecifiedInterfaceRemoveHandler.INSTANCE, true, false); rootRegistration.registerSubModel(id); } catch (Throwable e) { throw new RuntimeException("Could not register interface definition", e); } //TODO socket-binding-group currently lives in controller and the child RDs live in server so they currently need passing in from here rootRegistration.registerSubModel(SocketBindingGroupResourceDefinition.INSTANCE); } /** * Initializes the interface, socket binding group and socket binding part of the model * * @param rootResource the root model resource * @param rootRegistration the root model registry */ protected void initializePathsModel(Resource rootResource, ManagementResourceRegistration rootRegistration) { if (paths.size() == 0) { return; } rootResource.getModel().get(PATH); PathResourceDefinition def = PathResourceDefinition.createSpecified(pathManager); if (rootRegistration.getSubModel(PathAddress.pathAddress(def.getPathElement())) != null) { //Older versions of core model tests seem to register this resource, while in newer it does not get registered, //so let's remove it here if it exists already rootRegistration.unregisterSubModel(def.getPathElement()); } rootRegistration.registerSubModel(def); } /** * Creates the additional add system property operations * * @param ops the operations list to add our ops to */ protected void initializeSystemPropertiesOperations(List<ModelNode> ops) { for (Map.Entry<String, String> prop : systemProperties.entrySet()) { ModelNode op = new ModelNode(); op.get(OP).set(ADD); op.get(OP_ADDR).set(PathAddress.pathAddress(PathElement.pathElement(SYSTEM_PROPERTY, prop.getKey())).toModelNode()); op.get(VALUE).set(prop.getValue()); ops.add(op); } } /** * Creates the additional add interface, socket binding group and socket binding operations * * @param ops the operations list to add our ops to */ protected void initializeSocketBindingsOperations(List<ModelNode> ops) { if (socketBindings.isEmpty() && outboundSocketBindings.isEmpty()) { return; } //Add the interface /*ModelNode criteria = new ModelNode(); criteria.get(INET_ADDRESS).set(bindAddress); ModelNode op = InterfaceAddHandler.getAddInterfaceOperation( PathAddress.pathAddress(PathElement.pathElement(INTERFACE, INTERFACE_NAME)).toModelNode(), criteria);*/ ModelNode op = Util.createAddOperation(PathAddress.pathAddress(PathElement.pathElement(INTERFACE, INTERFACE_NAME))); op.get(INET_ADDRESS).set(bindAddress); ops.add(op); //Add the socket binding group op = new ModelNode(); op.get(OP).set(ADD); op.get(OP_ADDR).set(PathAddress.pathAddress(PathElement.pathElement(SOCKET_BINDING_GROUP, SOCKET_BINDING_GROUP_NAME)).toModelNode()); op.get(DEFAULT_INTERFACE).set(INTERFACE_NAME); if (portOffset != null) { op.get(PORT_OFFSET).set(portOffset); } ops.add(op); for (Map.Entry<String, Integer> binding : socketBindings.entrySet()) { op = new ModelNode(); op.get(OP).set(ADD); op.get(OP_ADDR).set(PathAddress.pathAddress(PathElement.pathElement(SOCKET_BINDING_GROUP, SOCKET_BINDING_GROUP_NAME), PathElement.pathElement(SOCKET_BINDING, binding.getKey())).toModelNode()); op.get(PORT).set(binding.getValue()); ops.add(op); } } /** * Creates and add to the <code>ops</code> the <code>add</code> operation for the * remote outbound socket configurations * * @param ops the operations list to add our ops to */ protected void initializeRemoteOutboundSocketBindingsOperations(List<ModelNode> ops) { if (outboundSocketBindings.size() == 0) { return; } for (Map.Entry<String, OutboundSocketBinding> entry : outboundSocketBindings.entrySet()) { final OutboundSocketBinding binding = entry.getValue(); if (!binding.isRemote()) { // skip local outbound socket bindings continue; } final String bindingName = entry.getKey(); final ModelNode op = new ModelNode(); op.get(OP).set(ADD); final PathAddress address = PathAddress.pathAddress(PathElement.pathElement(SOCKET_BINDING_GROUP, SOCKET_BINDING_GROUP_NAME), PathElement.pathElement(ModelDescriptionConstants.REMOTE_DESTINATION_OUTBOUND_SOCKET_BINDING, bindingName)); op.get(OP_ADDR).set(address.toModelNode()); // setup the other parameters for the add operation op.get(HOST).set(binding.getDestination()); op.get(PORT).set(binding.getDestinationPort()); // add the ADD operation to the operations list ops.add(op); } } protected void initializePathsOperations(List<ModelNode> ops) { if (paths.size() == 0) { return; } for (PathInfo path : paths.values()) { ModelNode op = new ModelNode(); op.get(OP).set(ADD); op.get(OP_ADDR).set(PathAddress.pathAddress(PathElement.pathElement(PATH, path.getName())).toModelNode()); op.get(PATH).set(path.getPath()); if (path.getRelativeTo() != null) { op.get(RELATIVE_TO).set(path.getRelativeTo()); } ops.add(op); } } private static class PathInfo { private final String name; private final String path; private final String relativeTo; public PathInfo(String name, String path, String relativeTo) { this.name = name; this.path = path; this.relativeTo = relativeTo; } public String getName() { return name; } public String getPath() { return path; } public String getRelativeTo() { return relativeTo; } } private static class OutboundSocketBinding { private final String destination; private final int port; private final boolean remote; OutboundSocketBinding(final String destination, final int port, final boolean remote) { this.destination = destination; this.port = port; this.remote = remote; } int getDestinationPort() { return this.port; } String getDestination() { return this.destination; } boolean isRemote() { return this.remote; } } public interface TestControllerAccessor { ServerEnvironment getServerEnvironment(); } }
package io.takari.maven.plugins.compile.jdt; import static org.apache.maven.plugin.testing.resources.TestResources.cp; import static org.apache.maven.plugin.testing.resources.TestResources.rm; import static org.apache.maven.plugin.testing.resources.TestResources.touch; import io.takari.maven.plugins.compile.CompileRule; import java.io.File; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.testing.resources.TestResources; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; public class CompileJdtTest { @Rule public final TestResources resources = new TestResources(); @Rule public final CompileRule mojos = new CompileRule() { @Override public org.apache.maven.plugin.MojoExecution newMojoExecution() { MojoExecution execution = super.newMojoExecution(); Xpp3Dom compilerId = new Xpp3Dom("compilerId"); compilerId.setValue("jdt"); execution.getConfiguration().addChild(compilerId); return execution; }; }; /** * Asserts specified output exists and is not older than specified input */ protected static void assertBuildOutput(File basedir, String input, String output) { File inputFile = new File(basedir, input); File outputFile = new File(basedir, output); Assert.assertTrue("output is older than input", outputFile.lastModified() >= inputFile.lastModified()); } @Test public void testBasic() throws Exception { File basedir = resources.getBasedir("compile-jdt/basic"); // initial build mojos.compile(basedir); mojos.assertBuildOutputs(basedir, "target/classes/basic/Basic1.class", "target/classes/basic/Basic2.class"); assertBuildOutput(basedir, "src/main/java/basic/Basic1.java", "target/classes/basic/Basic1.class"); assertBuildOutput(basedir, "src/main/java/basic/Basic2.java", "target/classes/basic/Basic2.class"); // no-change rebuild mojos.compile(basedir); mojos.assertBuildOutputs(basedir, new String[0]); mojos.assertCarriedOverOutputs(basedir, "target/classes/basic/Basic1.class", "target/classes/basic/Basic2.class"); // one file changed cp(basedir, "src/main/java/basic/Basic1.java-changed", "src/main/java/basic/Basic1.java"); mojos.compile(basedir); mojos.assertBuildOutputs(basedir, "target/classes/basic/Basic1.class"); assertBuildOutput(basedir, "src/main/java/basic/Basic1.java", "target/classes/basic/Basic1.class"); } @Test public void testBasic_timestampChangeRebuild() throws Exception { File basedir = resources.getBasedir("compile-jdt/basic"); File classes = new File(basedir, "target/classes"); // initial build mojos.compile(basedir); mojos.assertBuildOutputs(classes, "basic/Basic1.class", "basic/Basic2.class"); // move back timestamp, round to 10s to accommodate filesystem timestamp rounding long timestamp = System.currentTimeMillis() - 20000L; timestamp = timestamp - (timestamp % 10000L); new File(classes, "basic/Basic1.class").setLastModified(timestamp); touch(basedir, "src/main/java/basic/Basic1.java"); mojos.compile(basedir); mojos.assertBuildOutputs(classes, "basic/Basic1.class"); // timestamp is the same if the file is the same Assert.assertEquals(timestamp, new File(classes, "basic/Basic1.class").lastModified()); } @Test public void testSupertype() throws Exception { File basedir = resources.getBasedir("compile-jdt/supertype"); // initial build mojos.compile(basedir); mojos.assertBuildOutputs(basedir, "target/classes/supertype/SubClass.class", "target/classes/supertype/SuperClass.class", "target/classes/supertype/SuperInterface.class"); // non-structural change cp(basedir, "src/main/java/supertype/SuperClass.java-comment", "src/main/java/supertype/SuperClass.java"); cp(basedir, "src/main/java/supertype/SuperInterface.java-comment", "src/main/java/supertype/SuperInterface.java"); mojos.compile(basedir); mojos.assertBuildOutputs(basedir, "target/classes/supertype/SuperClass.class", "target/classes/supertype/SuperInterface.class"); // superclass change cp(basedir, "src/main/java/supertype/SuperClass.java-member", "src/main/java/supertype/SuperClass.java"); mojos.compile(basedir); mojos.assertBuildOutputs(basedir, "target/classes/supertype/SubClass.class", "target/classes/supertype/SuperClass.class"); } @Test public void testSupertype_superClassChangeDoesNotTriggerRebuildOfImplementedInterfaces() throws Exception { File basedir = resources.getBasedir("compile-jdt/supertype"); // initial build mojos.compile(basedir); mojos.assertBuildOutputs(basedir, "target/classes/supertype/SubClass.class", "target/classes/supertype/SuperClass.class", "target/classes/supertype/SuperInterface.class"); // superclass insignificant change cp(basedir, "src/main/java/supertype/SuperClass.java-methodBody", "src/main/java/supertype/SuperClass.java"); mojos.compile(basedir); mojos.assertBuildOutputs(basedir, "target/classes/supertype/SuperClass.class"); // superclass significant change cp(basedir, "src/main/java/supertype/SuperClass.java-member", "src/main/java/supertype/SuperClass.java"); mojos.compile(basedir); mojos.assertBuildOutputs(basedir, "target/classes/supertype/SubClass.class", "target/classes/supertype/SuperClass.class"); } @Test public void testCircular() throws Exception { File basedir = mojos.compile(resources.getBasedir("compile-jdt/circular")); mojos.assertBuildOutputs(basedir, "target/classes/circular/ClassA.class", "target/classes/circular/ClassB.class"); cp(basedir, "src/main/java/circular/ClassA.java-changed", "src/main/java/circular/ClassA.java"); mojos.compile(basedir); mojos.assertBuildOutputs(basedir, "target/classes/circular/ClassA.class", "target/classes/circular/ClassB.class"); } @Test public void testReference() throws Exception { File basedir = mojos.compile(resources.getBasedir("compile-jdt/reference")); mojos.assertBuildOutputs(basedir, "target/classes/reference/Parameter.class", "target/classes/reference/Type.class"); // no change rebuild mojos.compile(basedir); mojos.assertBuildOutputs(basedir, new String[0]); Assert.assertTrue(new File(basedir, "target/classes/reference/Parameter.class").canRead()); Assert.assertTrue(new File(basedir, "target/classes/reference/Type.class").canRead()); // insignificant change cp(basedir, "src/main/java/reference/Parameter.java-comment", "src/main/java/reference/Parameter.java"); mojos.compile(basedir); mojos.assertBuildOutputs(basedir, "target/classes/reference/Parameter.class"); Assert.assertTrue(new File(basedir, "target/classes/reference/Type.class").canRead()); // significant change cp(basedir, "src/main/java/reference/Parameter.java-method", "src/main/java/reference/Parameter.java"); mojos.compile(basedir); mojos.assertBuildOutputs(basedir, "target/classes/reference/Parameter.class", "target/classes/reference/Type.class"); } @Test public void testMissing() throws Exception { final String[] messages = {"ERROR Error.java [6:12] Missing cannot be resolved to a type", "ERROR Error.java [8:20] Missing cannot be resolved to a type"}; File basedir = resources.getBasedir("compile-jdt/missing"); try { mojos.compile(basedir); Assert.fail(); } catch (MojoExecutionException expected) { // expected } mojos.assertBuildOutputs(basedir, "target/classes/missing/Other.class"); Assert.assertFalse(new File(basedir, "target/classes/missing/Error.class").exists()); mojos.assertMessages(basedir, "src/main/java/missing/Error.java", messages); // no change rebuild try { mojos.compile(basedir); Assert.fail(); } catch (MojoExecutionException expected) { // expected } mojos.assertBuildOutputs(basedir, new String[0]); mojos.assertMessages(basedir, "src/main/java/missing/Error.java", messages); // fix the problem cp(basedir, "src/main/java/missing/Missing.java-missing", "src/main/java/missing/Missing.java"); mojos.compile(basedir); mojos.assertBuildOutputs(basedir, "target/classes/missing/Error.class", "target/classes/missing/Missing.class"); // reintroduce the problem rm(basedir, "src/main/java/missing/Missing.java"); try { mojos.compile(basedir); Assert.fail(); } catch (MojoExecutionException expected) { // expected } mojos.assertDeletedOutputs(basedir, "target/classes/missing/Error.class", "target/classes/missing/Missing.class"); } @Test public void testMultifile() throws Exception { File basedir = mojos.compile(resources.getBasedir("compile-jdt/multifile")); mojos.assertBuildOutputs(basedir, "target/classes/multifile/ClassA.class", "target/classes/multifile/ClassB.class", "target/classes/multifile/ClassB$Nested.class"); touch(basedir, "src/main/java/multifile/ClassA.java"); cp(basedir, "src/main/java/multifile/ClassB.java-changed", "src/main/java/multifile/ClassB.java"); try { mojos.compile(basedir); Assert.fail(); } catch (MojoExecutionException expected) { // expected } // TODO assert expected error messages mojos.assertBuildOutputs(basedir, "target/classes/multifile/ClassB.class"); mojos.assertDeletedOutputs(basedir, "target/classes/multifile/ClassA.class", "target/classes/multifile/ClassB$Nested.class"); } @Test public void testSecondaryType() throws Exception { File basedir = mojos.compile(resources.getBasedir("compile-jdt/secondary-type")); File classes = new File(basedir, "target/classes"); mojos.assertBuildOutputs(classes , "secondary/Primary.class" , "secondary/Secondary.class" , "secondary/SecondarySubclass.class" , "secondary/SecondarySubclassClient.class"); touch(basedir, "src/main/java/secondary/SecondarySubclassClient.java"); mojos.compile(basedir); mojos.assertBuildOutputs(classes , "secondary/SecondarySubclassClient.class"); } @Test public void testRemovedTypes() throws Exception { File basedir = mojos.compile(resources.getBasedir("compile-jdt/removed-types")); File classes = new File(basedir, "target/classes"); mojos.assertBuildOutputs(classes , "removed/A.class" , "removed/B.class" , "removed/Dummy.class"); rm(basedir, "src/main/java/removed/A.java"); rm(basedir, "src/main/java/removed/B.java"); mojos.compile(basedir); mojos.assertDeletedOutputs(classes , "removed/A.class" , "removed/B.class"); } }
package com.ysu.zyw.tc.components.rpc.httpx; import com.google.common.collect.Maps; import com.ysu.zyw.tc.base.constant.TcConstant; import com.ysu.zyw.tc.base.ex.TcException; import com.ysu.zyw.tc.base.utils.TcDateUtils; import lombok.Getter; import lombok.Setter; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.BooleanUtils; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.util.*; import org.springframework.web.client.RestTemplate; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.Resource; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URLEncoder; import java.util.*; import java.util.function.Supplier; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; /** * @warn do not directly return the responseEntity to springmvc's controller, * because this responseEntity means the response of the next layer, and the * springmvc's return value means the response of this layer, and the response * of next layer will carry some special response headers(such as encoding, * transfer-encoding gzip etc.), and those response header has it's own meaning. * <p> * for example, the lower layer server encoding the response to gzip, and add a * header named content-encoding: gzip, and upper layer receive the response * carry a header named content-encoding: gzip, and directly return it to * springmvc controller, springmvc(or container, proxy etc) see this header, * they do not encoding the response to gzip, but the user do not encoding * the response stream to gzip, but set a header content-encoding: gzip, so * this will lead to a mistake. */ @Slf4j public class TcHttpxService { @Getter @Setter @Resource private RestTemplate restTemplate; @Getter @Setter private boolean camouflageException; public <T> ResponseEntity<T> getText4Entity(@Nonnull String url, @Nullable Map<String, String> pathVariables, @Nullable HttpHeaders httpHeaders, @Nonnull MultiValueMap<String, String> requestBody, @Nonnull ParameterizedTypeReference<T> typeReference) { checkNotNull(url); checkNotNull(typeReference); HttpEntity<Void> httpEntity = new HttpEntity<>(null, addReqContentType(httpHeaders, MediaType.APPLICATION_FORM_URLENCODED_VALUE)); String expandVars = expandVars(requestBody); String expandUrl = StringUtils.hasText(expandVars) ? (url + "?" + expandVars) : url; return execute(expandUrl, HttpMethod.GET, httpEntity, typeReference, pathVariables); } public <T> ResponseEntity<T> postText4Entity(@Nonnull String url, @Nullable Map<String, String> pathVariables, @Nullable HttpHeaders httpHeaders, @Nonnull MultiValueMap<String, String> requestBody, @Nonnull ParameterizedTypeReference<T> typeReference) { checkNotNull(url); checkNotNull(requestBody); checkNotNull(typeReference); HttpEntity<?> httpEntity = new HttpEntity<>(requestBody, addReqContentType(httpHeaders, MediaType.APPLICATION_FORM_URLENCODED_VALUE)); return execute(url, HttpMethod.POST, httpEntity, typeReference, pathVariables); } public <T> ResponseEntity<T> postJson4Entity(@Nonnull String url, @Nullable Map<String, String> pathVariables, @Nullable HttpHeaders httpHeaders, @Nonnull Object requestBody, @Nonnull ParameterizedTypeReference<T> typeReference) { checkNotNull(url); checkNotNull(requestBody); checkNotNull(typeReference); HttpEntity<?> httpEntity = new HttpEntity<>(requestBody, addReqContentType(httpHeaders, MediaType.APPLICATION_JSON_UTF8_VALUE)); return execute(url, HttpMethod.POST, httpEntity, typeReference, pathVariables); } public MultiValueMap<String, String> copy2MultiValueMap(@Nullable Object obj) { if (Objects.isNull(obj)) { return new LinkedMultiValueMap<>(); } if (obj instanceof Collection || obj.getClass().isArray() || ClassUtils.isPrimitiveOrWrapper(obj.getClass()) || obj instanceof String) { throw new TcException("list / primitive / string value is not supported"); } MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>(); copy2MultiValueMap(multiValueMap, TcConstant.Str.BLANK, obj); return multiValueMap; } protected void copy2MultiValueMap(MultiValueMap<String, String> multiValueMap, String currentPath, Object obj) { if (Objects.isNull(obj)) { return; } if (ClassUtils.isPrimitiveOrWrapper(obj.getClass()) || obj instanceof String) { // is primitive type multiValueMap.set(currentPath, urlEncode(String.valueOf(obj))); } else if (obj instanceof Map) { // is map Map<?, ?> rValue = (Map) obj; rValue.entrySet().forEach(entry -> { checkArgument(entry.getKey() instanceof String, "map key must is string"); String key = String.valueOf(entry.getKey()); String oKey = StringUtils.hasText(currentPath) ? (currentPath + TcConstant.Str.DOT + key) : key; Object oValue = entry.getValue(); copy2MultiValueMap(multiValueMap, oKey, oValue); }); } else if (obj instanceof Collection) { // is collection Collection value = (Collection) obj; int index = 0; for (Object oValue : value) { String oKey = currentPath + "[" + index + "]"; copy2MultiValueMap(multiValueMap, oKey, oValue); index++; } } else if (obj.getClass().isArray()) { // is array for (int i = 0; i < Array.getLength(obj); i++) { String oKey = currentPath + "[" + i + "]"; copy2MultiValueMap(multiValueMap, oKey, Array.get(obj, i)); } } else { // is pojo ReflectionUtils.doWithFields(obj.getClass(), field -> { try { String key = field.getName(); Method readMethod = findPropertyReadMethod(key, field.getDeclaringClass()); String oKey = StringUtils.hasText(currentPath) ? (currentPath + TcConstant.Str.DOT + key) : key; Object oValue = readMethod.invoke(obj); copy2MultiValueMap(multiValueMap, oKey, oValue); } catch (InvocationTargetException | NoSuchMethodException e) { throw new RuntimeException(e); } }); } } protected Method findPropertyReadMethod(String propertyName, Class<?> clazz) throws NoSuchMethodException { Method propertyReadMethod = null; String methodName = "get" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1); try { propertyReadMethod = clazz.getMethod(methodName); } catch (NoSuchMethodException e) { // ignore } if (propertyReadMethod == null) { methodName = "is" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1); try { propertyReadMethod = clazz.getMethod(methodName); } catch (NoSuchMethodException e) { // ignore } } if (propertyReadMethod == null) { // boolean property named isXxx read property is isXxx, not isIsXxx methodName = propertyName; // if no such get method at all, throw NoSuchMethodException. propertyReadMethod = clazz.getMethod(methodName); } checkArgument(propertyReadMethod.getParameterCount() == 0, "get method can not have args"); return propertyReadMethod; } protected String expandVars(MultiValueMap<String, String> form) { checkNotNull(form); return form.entrySet().stream() .map(pair -> pair.getValue().stream() .map(value -> pair.getKey() + "=" + urlEncode(value)) .collect(Collectors.joining("&"))) .collect(Collectors.joining("&")); } @SneakyThrows public String urlEncode(String value) { return URLEncoder.encode(value, "UTF-8"); } protected HttpHeaders addReqContentType(HttpHeaders httpHeaders, String mediaType) { HttpHeaders newHttpHeaders = new HttpHeaders(); if (Objects.nonNull(httpHeaders)) { newHttpHeaders.putAll(httpHeaders); } newHttpHeaders.set(HttpHeaders.CONTENT_TYPE, mediaType); return newHttpHeaders; } protected <T> ResponseEntity<T> execute(String url, HttpMethod httpMethod, HttpEntity<?> httpEntity, ParameterizedTypeReference<T> typeReference, Map<String, String> uriVariables) { if (Objects.isNull(uriVariables)) { uriVariables = Maps.newHashMap(); } if (BooleanUtils.isTrue(camouflageException)) { try { return doExecute(url, httpMethod, httpEntity, typeReference, uriVariables); } catch (Exception e) { // camouflage exception log.error("", e); return doCamouflageException(); } } else { return doExecute(url, httpMethod, httpEntity, typeReference, uriVariables); } } protected <T> ResponseEntity<T> doExecute(String url, HttpMethod httpMethod, HttpEntity<?> httpEntity, ParameterizedTypeReference<T> typeReference, Map<String, String> uriVariables) { Date now = new Date(); if (log.isInfoEnabled()) { log.info("start call http api [{}:{}], url vars [{}], request body [{}]", httpMethod, url, uriVariables, httpEntity); } ResponseEntity<T> responseEntity = restTemplate.exchange(url, httpMethod, httpEntity, typeReference, uriVariables); if (log.isInfoEnabled()) { log.info("call http api [{}:{}] finish, response code [{}], take time [{}]", httpMethod, url, httpEntity, TcDateUtils.duration(now, new Date())); } return responseEntity; } protected <T> ResponseEntity<T> doCamouflageException() { return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } public <T> T orElseGet(@Nonnull ResponseEntity<T> responseEntity, @Nonnull Supplier<T> defaultValueSupplier) { checkNotNull(responseEntity); checkNotNull(defaultValueSupplier); if (responseEntity.getStatusCode().is2xxSuccessful()) { return responseEntity.getBody(); } else { return defaultValueSupplier.get(); } } public <T> T orElseThrow(@Nonnull ResponseEntity<T> responseEntity, @Nonnull Supplier<RuntimeException> exceptionSupplier) { checkNotNull(responseEntity); checkNotNull(exceptionSupplier); if (responseEntity.getStatusCode().is2xxSuccessful()) { return responseEntity.getBody(); } else { throw exceptionSupplier.get(); } } }
package pitt.search.semanticvectors; import java.lang.IllegalArgumentException; import java.util.ArrayList; import java.util.LinkedList; import java.util.Enumeration; import pitt.search.semanticvectors.LuceneUtils; import pitt.search.semanticvectors.VectorSearcher; import pitt.search.semanticvectors.VectorStore; import pitt.search.semanticvectors.VectorUtils; /** * Class for searching vector stores using different scoring functions. * Each VectorSearcher implements a particular scoring function which is * normally query dependent, so each query needs its own VectorSearcher. */ abstract public class VectorSearcher{ private VectorStore queryVecStore; private VectorStore searchVecStore; private LuceneUtils luceneUtils; /** * This needs to be filled in for each subclass. It takes an individual * vector and assigns it a relevance score for this VectorSearcher. */ public abstract float getScore(float[] testVector); /** * Performs basic initialization; subclasses should normally call super() to use this. * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) */ public VectorSearcher(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils) { this.queryVecStore = queryVecStore; this.searchVecStore = searchVecStore; this.luceneUtils = luceneUtils; } /** * This nearest neighbor search is implemented in the abstract * VectorSearcher class itself: this enables all subclasses to reuse * the search whatever scoring method they implement. Since query * expressions are built into the VectorSearcher, * getNearestNeighbors no longer takes a query vector as an * argument. * @param numResults the number of results / length of the result list. */ public LinkedList<SearchResult> getNearestNeighbors(int numResults) { LinkedList<SearchResult> results = new LinkedList<SearchResult>(); float score, threshold = -1; Enumeration<ObjectVector> vecEnum = searchVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Initialize result list if just starting. if (results.size() == 0) { ObjectVector firstElement = vecEnum.nextElement(); score = getScore(firstElement.getVector()); results.add(new SearchResult(score, firstElement)); continue; } // Test this element. ObjectVector testElement = vecEnum.nextElement(); score = getScore(testElement.getVector()); // This is a way of using the Lucene Index to get term and // document frequency information to reweight all results. It // seems to be good at moving excessively common terms further // down the results. Note that using this means that scores // returned are no longer just cosine similarities. if (this.luceneUtils != null) { score = score * luceneUtils.getGlobalTermWeightFromString((String) testElement.getObject()); } if (score > threshold) { boolean added = false; for (int i = 0; i < results.size(); ++i) { // Add to list if this is right place. if (score > results.get(i).getScore() && added == false) { results.add(i, new SearchResult(score, testElement)); added = true; } } // Prune list if there are already numResults. if (results.size() > numResults) { results.removeLast(); threshold = results.getLast().getScore(); } else { if (added == false) { results.add(new SearchResult(score, testElement)); } } } } return results; } /** * Class for searching a vector store using cosine similarity. * Takes a sum of positive query terms and optionally negates some terms. */ static public class VectorSearcherCosine extends VectorSearcher { float[] queryVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherCosine(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.queryVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, queryTerms); if (VectorUtils.isZeroVector(this.queryVector)) { throw new ZeroVectorException("Query vector is zero ... no results."); } } public float getScore(float[] testVector) { //testVector = VectorUtils.getNormalizedVector(testVector); return VectorUtils.scalarProduct(this.queryVector, testVector); } } /** * Class for searching a vector store using sparse cosine similarity. * Takes a sum of positive query terms and optionally negates some terms. */ static public class VectorSearcherCosineSparse extends VectorSearcher { float[] queryVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherCosineSparse(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); float[] fullQueryVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, queryTerms); if (VectorUtils.isZeroVector(fullQueryVector)) { throw new ZeroVectorException("Query vector is zero ... no results."); } short[] sparseQueryVector = VectorUtils.floatVectorToSparseVector(fullQueryVector, 20); this.queryVector = VectorUtils.sparseVectorToFloatVector(sparseQueryVector, Flags.dimension); } public float getScore(float[] testVector) { //testVector = VectorUtils.getNormalizedVector(testVector); short[] sparseTestVector = VectorUtils.floatVectorToSparseVector(testVector, 40); testVector = VectorUtils.sparseVectorToFloatVector(sparseTestVector, Flags.dimension); return VectorUtils.scalarProduct(this.queryVector, testVector); } } /** * Class for searching a vector store using tensor product * similarity. The class takes a seed tensor as a training * example. This tensor should be entangled (a superposition of * several individual products A * B) for non-trivial results. */ static public class VectorSearcherTensorSim extends VectorSearcher { private float[][] trainingTensor; private float[] partnerVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. This should be a list of one or more * tilde-separated training pairs, e.g., <code>paris~france * berlin~germany</code> followed by a list of one or more search * terms, e.g., <code>london birmingham</code>. */ public VectorSearcherTensorSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.trainingTensor = VectorUtils.createZeroTensor(Flags.dimension); // Collect tensor training relations. int i = 0; while (queryTerms[i].indexOf("~") > 0) { System.err.println("Training pair: " + queryTerms[i]); String[] trainingTerms = queryTerms[i].split("~"); if (trainingTerms.length != 2) { System.err.println("Tensor training terms must be pairs split by individual" + " '~' character. Error with: '" + queryTerms[i] + "'"); } float[] trainingVec1 = queryVecStore.getVector(trainingTerms[0]); float[] trainingVec2 = queryVecStore.getVector(trainingTerms[1]); if (trainingVec1 != null && trainingVec2 != null) { float[][] trainingPair = VectorUtils.getOuterProduct(trainingVec1, trainingVec2); this.trainingTensor = VectorUtils.getTensorSum(trainingTensor, trainingPair); } ++i; } // Check to see that we got a non-zero training tensor before moving on. if (VectorUtils.isZeroTensor(trainingTensor)) { throw new ZeroVectorException("Tensor training relation is zero ... no results."); } this.trainingTensor = VectorUtils.getNormalizedTensor(trainingTensor); // This is an explicit way of taking a slice of the last i // terms. There may be a quicker way of doing this. String[] partnerTerms = new String[queryTerms.length - i]; for (int j = 0; j < queryTerms.length - i; ++j) { partnerTerms[j] = queryTerms[i + j]; } this.partnerVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, partnerTerms); if (VectorUtils.isZeroVector(this.partnerVector)) { throw new ZeroVectorException("Query vector is zero ... no results."); } } /** * @param testVector Vector being tested. * Scores are hopefully high when the relationship between queryVector * and testVector is analogous to the relationship between rel1 and rel2. */ public float getScore(float[] testVector) { float[][] testTensor = VectorUtils.getOuterProduct(this.partnerVector, testVector); return VectorUtils.getInnerProduct(this.trainingTensor, testTensor); } } /** * Class for searching a vector store using convolution similarity. * Interface is similar to that for VectorSearcherTensorSim. */ static public class VectorSearcherConvolutionSim extends VectorSearcher { private float[] trainingConvolution; private float[] partnerVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. This should be a list of one or more * tilde-separated training pairs, e.g., <code>paris~france * berlin~germany</code> followed by a list of one or more search * terms, e.g., <code>london birmingham</code>. */ public VectorSearcherConvolutionSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.trainingConvolution = new float[2 * Flags.dimension - 1]; for (int i = 0; i < 2 * Flags.dimension - 1; ++i) { this.trainingConvolution[i] = 0; } // Collect tensor training relations. int i = 0; while (queryTerms[i].indexOf("~") > 0) { System.err.println("Training pair: " + queryTerms[i]); String[] trainingTerms = queryTerms[i].split("~"); if (trainingTerms.length != 2) { System.err.println("Tensor training terms must be pairs split by individual" + " '~' character. Error with: '" + queryTerms[i] + "'"); } float[] trainingVec1 = queryVecStore.getVector(trainingTerms[0]); float[] trainingVec2 = queryVecStore.getVector(trainingTerms[1]); if (trainingVec1 != null && trainingVec2 != null) { float[] trainingPair = VectorUtils.getConvolutionFromVectors(trainingVec1, trainingVec2); for (int j = 0; j < 2 * Flags.dimension - 1; ++j) { this.trainingConvolution[j] += trainingPair[j]; } } ++i; } // Check to see that we got a non-zero training tensor before moving on. if (VectorUtils.isZeroVector(trainingConvolution)) { throw new ZeroVectorException("Convolution training relation is zero ... no results."); } this.trainingConvolution = VectorUtils.getNormalizedVector(trainingConvolution); String[] partnerTerms = new String[queryTerms.length - i]; for (int j = 0; j < queryTerms.length - i; ++j) { partnerTerms[j] = queryTerms[i + j]; } this.partnerVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, partnerTerms); if (VectorUtils.isZeroVector(this.partnerVector)) { throw new ZeroVectorException("Query vector is zero ... no results."); } } /** * @param testVector Vector being tested. * Scores are hopefully high when the relationship between queryVector * and testVector is analogoues to the relationship between rel1 and rel2. */ public float getScore(float[] testVector) { float[] testConvolution = VectorUtils.getConvolutionFromVectors(this.partnerVector, testVector); testConvolution = VectorUtils.getNormalizedVector(testConvolution); return VectorUtils.scalarProduct(this.trainingConvolution, testConvolution); } } /** * Class for searching a vector store using quantum disjunction similarity. */ static public class VectorSearcherSubspaceSim extends VectorSearcher { private ArrayList<float[]> disjunctSpace; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherSubspaceSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.disjunctSpace = new ArrayList(); for (int i = 0; i < queryTerms.length; ++i) { System.out.println("\t" + queryTerms[i]); // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); float[] tmpVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, tmpTerms); if (tmpVector != null) { this.disjunctSpace.add(tmpVector); } } if (this.disjunctSpace.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } VectorUtils.orthogonalizeVectors(this.disjunctSpace); } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ public float getScore(float[] testVector) { return VectorUtils.getSumScalarProduct(testVector, disjunctSpace); } } /** * Class for searching a vector store using minimum distance similarity. */ static public class VectorSearcherMaxSim extends VectorSearcher { private ArrayList<float[]> disjunctVectors; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMaxSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.disjunctVectors = new ArrayList(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); float[] tmpVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, tmpTerms); if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } if (this.disjunctVectors.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ public float getScore(float[] testVector) { float score = -1; float max_score = -1; for (int i = 0; i < disjunctVectors.size(); ++i) { score = VectorUtils.scalarProduct(this.disjunctVectors.get(i), testVector); if (score > max_score) { max_score = score; } } return max_score; } } /** * Class for searching a permuted vector store using cosine similarity. * Uses implementation of rotation for permutation proposed by Sahlgren et al 2008 * Should find the term that appears frequently in the position p relative to the * index term (i.e. sat +1 would find a term occurring frequently immediately after "sat" */ static public class VectorSearcherPerm extends VectorSearcher { float[] theAvg; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "?" appears, terms best fitting into this position will be returned */ public VectorSearcherPerm(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws IllegalArgumentException, ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); try { theAvg = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(queryVecStore,luceneUtils,queryTerms); } catch (IllegalArgumentException e) { System.err.println("Couldn't create permutation VectorSearcher ..."); throw e; } if (VectorUtils.isZeroVector(theAvg)) { throw new ZeroVectorException("Permutation query vector is zero ... no results."); } } public float getScore(float[] testVector) { return VectorUtils.scalarProduct(theAvg, testVector); } } /** * Class for searching a permuted vector store using cosine similarity. * Uses implementation of rotation for permutation proposed by Sahlgren et al 2008 * Should find the term that appears frequently in the position p relative to the * index term (i.e. sat +1 would find a term occurring frequently immediately after "sat" * This is a variant that takes into account differt results obtained when using either * permuted or random index vectors as the cue terms, by taking the mean of the results * obtained with each of these options */ static public class BalancedVectorSearcherPerm extends VectorSearcher { float[] oneDirection; float[] otherDirection; VectorStore searchVecStore, queryVecStore; LuceneUtils luceneUtils; String[] queryTerms; /** * @param queryVecStore Vector store to use for query generation (this is also reversed). * @param searchVecStore The vector store to search (this is also reversed). * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "?" appears, terms best fitting into this position will be returned */ public BalancedVectorSearcherPerm(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws IllegalArgumentException, ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.queryVecStore = queryVecStore; this.searchVecStore = searchVecStore; this.luceneUtils = luceneUtils; try { oneDirection = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(queryVecStore,luceneUtils,queryTerms); otherDirection = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(searchVecStore,luceneUtils,queryTerms); } catch (IllegalArgumentException e) { System.err.println("Couldn't create permutation VectorSearcher ..."); throw e; } if (VectorUtils.isZeroVector(oneDirection)) { throw new ZeroVectorException("Permutation query vector is zero ... no results."); } } /** * This overides the nearest neighbor class implemented in the abstract * VectorSearcher class * @param numResults the number of results / length of the result list. */ public LinkedList getNearestNeighbors(int numResults) { LinkedList<SearchResult> results = new LinkedList(); float score,score1, score2, threshold = -1; Enumeration<ObjectVector> vecEnum = searchVecStore.getAllVectors(); Enumeration<ObjectVector> vecEnum2 = queryVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Initialize result list if just starting. if (results.size() == 0) { ObjectVector firstElement = vecEnum.nextElement(); score = getScore(firstElement.getVector()); score2= getScore(vecEnum2.nextElement().getVector()); results.add(new SearchResult(Math.max(score,score2), firstElement)); continue; } // Test this element. ObjectVector testElement = vecEnum.nextElement(); ObjectVector testElement2 = vecEnum2.nextElement(); score1 = getScore(testElement.getVector()); score2 = getScore2(VectorUtils.getNormalizedVector(testElement2.getVector())); score = Math.max(score1,score2); // This is a way of using the Lucene Index to get term and // document frequency information to reweight all results. It // seems to be good at moving excessively common terms further // down the results. Note that using this means that scores // returned are no longer just cosine similarities. if (this.luceneUtils != null) { score = score * luceneUtils.getGlobalTermWeightFromString((String) testElement.getObject()); } if (score > threshold) { boolean added = false; for (int i = 0; i < results.size(); ++i) { // Add to list if this is right place. if (score > results.get(i).getScore() && added == false) { results.add(i, new SearchResult(score, testElement)); added = true; } } // Prune list if there are already numResults. if (results.size() > numResults) { results.removeLast(); threshold = results.getLast().getScore(); } else { if (added == false) { results.add(new SearchResult(score, testElement)); } } }} return results; } public float getScore(float[] testVector) { return VectorUtils.scalarProduct(oneDirection, testVector); } public float getScore2(float[] testVector) { return VectorUtils.scalarProduct(otherDirection, VectorUtils.getNormalizedVector(testVector)); } } }
package fr.adrienbrault.idea.symfony2plugin.tests.config.yaml; import com.intellij.psi.PsiElement; import fr.adrienbrault.idea.symfony2plugin.config.yaml.YamlElementPatternHelper; import fr.adrienbrault.idea.symfony2plugin.tests.SymfonyLightCodeInsightFixtureTestCase; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author Daniel Espendiller <daniel@espendiller.net> * @see fr.adrienbrault.idea.symfony2plugin.config.yaml.YamlElementPatternHelper */ public class YamlElementPatternHelperTest extends SymfonyLightCodeInsightFixtureTestCase { private String[] dataProviders() { return new String[] { " <caret>a\n", " '<caret>'\n", " \"<caret>\"\n", " <caret>a: foo\n", " '<caret>': foo\n", " \"<caret>\": foo\n", }; } public void testGetOrmRoot() { for (String s : dataProviders()) { assertTrue(YamlElementPatternHelper.getOrmRoot().accepts(createCaretElement( "class\\Foo:\n" + s, "foo.orm.yml")) ); } } public void testGetWithFirstRootKey() { for (String s : dataProviders()) { assertTrue(YamlElementPatternHelper.getWithFirstRootKey().accepts(createCaretElement( "class\\Foo:\n" + s, "foo.orm.yml")) ); } } public void testGetParentKeyName() { for (String s : dataProviders()) { assertTrue(YamlElementPatternHelper.getParentKeyName("requirements").accepts(createCaretElement( "requirements:\n" + s, "foo.orm.yml")) ); } } public void testGetSingleLineScalarKey() { assertTrue(YamlElementPatternHelper.getSingleLineScalarKey("class").accepts(createCaretElement( "class: <caret>a" ))); assertTrue(YamlElementPatternHelper.getSingleLineScalarKey("class").accepts(createCaretElement( "class: '<caret>'" ))); assertTrue(YamlElementPatternHelper.getSingleLineScalarKey("class").accepts(createCaretElement( "class: \"<caret>\"" ))); } public void testGetOrmParentLookup() { for (String s : dataProviders()) { assertTrue(YamlElementPatternHelper.getOrmParentLookup("requirements").accepts(createCaretElement( "requirements:\n" + s, "foo.orm.yml")) ); } } public void testGetFilterOnPrevParent() { assertTrue(YamlElementPatternHelper.getFilterOnPrevParent("services").accepts(createCaretElement( "services:\n" + " foo:\n" + " <caret>a: foo\n" , "foo.orm.yml")) ); } public void testGetInsideKeyValue() { assertTrue(YamlElementPatternHelper.getInsideKeyValue("tags").accepts(createCaretElement( "services:\n" + " foo:\n" + " tags:\n" + " - { name: <caret>}\n" )) ); assertTrue(YamlElementPatternHelper.getInsideKeyValue("services").accepts(createCaretElement( "services:\n" + " foo:\n" + " tags:\n" + " - { name: <caret>}\n" )) ); } public void testGetSuperParentArrayKey() { assertTrue(YamlElementPatternHelper.getSuperParentArrayKey("services").accepts(createCaretElement( "services:\n" + " foo:\n" + " <caret>a\n" + " car: foo\n" ))); // @TODO: PhpStorm <= 9 drop if(true) return; assertTrue(YamlElementPatternHelper.getSuperParentArrayKey("services").accepts(createCaretElement( "services:\n" + " foo:\n" + " \"<caret>\"\n" + " car: foo\n" ))); assertTrue(YamlElementPatternHelper.getSuperParentArrayKey("services").accepts(createCaretElement( "services:\n" + " foo:\n" + " '<caret>'\n" + " car: foo\n" ))); assertTrue(YamlElementPatternHelper.getSuperParentArrayKey("services").accepts(createCaretElement( "services:\n" + " foo:\n" + " <caret>a: foo\n" ))); assertTrue(YamlElementPatternHelper.getSuperParentArrayKey("services").accepts(createCaretElement( "services:\n" + " foo:\n" + " car: foo\n" + " <caret>a" ))); assertFalse(YamlElementPatternHelper.getSuperParentArrayKey("services").accepts(createCaretElement( "service:\n" + " foo:\n" + " car: foo\n" + " <caret>a" ))); } private PsiElement createCaretElement(@NotNull String contents) { return createCaretElement(contents, null); } private PsiElement createCaretElement(@NotNull String contents, @Nullable String file) { if(file == null) { file = "services.yml"; } myFixture.configureByText(file, contents); return myFixture.getFile().findElementAt(myFixture.getCaretOffset()); } }
package com.scispike.ws; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; import com.scispike.callback.Callback; import com.scispike.callback.Event; import com.scispike.callback.EventEmitter; import com.scispike.test.Util; public class SocketTest { @Test public void TestSocketCreation() { final CountDownLatch signal = new CountDownLatch(1); final CountDownLatch waitForHeartbeats = new CountDownLatch(1); Callback<String, String> connected = new Callback<String, String>() { @Override public void call(String error, String... args) { Assert.assertNull(error); } }; final Socket s = Util.getSocket(connected); s.hb_interval=400; EventEmitter<String> connect = s.getConnectEmitter(); connect.on("error", new Event<String>() { @Override public void onEmit(String... data) { signal.countDown(); waitForHeartbeats.countDown(); throw new RuntimeException(data[0]); } }); connect.on("connect", new Event<String>() { @Override public void onEmit(String... data) { Assert.assertTrue(true); signal.countDown(); s.resetHeartbeat(); s.hb.put(s.urlPrefix, true); } }); s.connect(); try { signal.await(1,TimeUnit.MINUTES);// wait for connect Assert.assertEquals(signal.getCount(), 0); Assert.assertEquals(s.isConnected(), true); waitForHeartbeats.await(1,TimeUnit.SECONDS); } catch (InterruptedException e) { Assert.fail(e.getMessage()); } } }
package guitests; import static org.junit.Assert.assertTrue; import static seedu.geekeep.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import org.junit.Test; import guitests.guihandles.PersonCardHandle; import seedu.geekeep.commons.core.Messages; import seedu.geekeep.logic.commands.UpdateCommand; import seedu.geekeep.model.tag.Tag; import seedu.geekeep.model.task.DateTime; import seedu.geekeep.model.task.Location; import seedu.geekeep.model.task.Title; import seedu.geekeep.testutil.PersonBuilder; import seedu.geekeep.testutil.TestTask; // TODO: reduce GUI tests by transferring some tests to be covered by lower level tests. public class UpdateCommandTest extends AddressBookGuiTest { // The list of persons in the person list panel is expected to match this list. // This list is updated with every successful call to assertEditSuccess(). TestTask[] expectedTasksList = td.getTypicalPersons(); /** * Checks whether the edited person has the correct updated details. * * @param filteredPersonListIndex index of person to edit in filtered list * @param addressBookIndex index of person to edit in the address book. * Must refer to the same person as {@code filteredPersonListIndex} * @param detailsToEdit details to edit the person with as input to the edit command * @param editedPerson the expected person after editing the person's details */ private void assertEditSuccess(int filteredPersonListIndex, int addressBookIndex, String detailsToEdit, TestTask editedPerson) { commandBox.runCommand("update " + filteredPersonListIndex + " " + detailsToEdit); // confirm the new card contains the right data PersonCardHandle editedCard = taskListPanel.navigateToPerson(editedPerson.getTitle().fullTitle); assertMatching(editedPerson, editedCard); // confirm the list now contains all previous persons plus the person with updated details expectedTasksList[addressBookIndex - 1] = editedPerson; assertTrue(taskListPanel.isListMatching(expectedTasksList)); assertResultMessage(String.format(UpdateCommand.MESSAGE_EDIT_TASK_SUCCESS, editedPerson)); } @Test public void edit_allFieldsSpecified_success() throws Exception { String detailsToEdit = "Bobby s/2017-04-01T10:16:30 e/2017-05-01T10:16:30 l/Block 123, Bobby Street 3 t/husband"; int addressBookIndex = 1; TestTask editedPerson = new PersonBuilder().withName("Bobby") .withEndDateTime("2017-05-01T10:16:30") .withStartDateTime("2017-04-01T10:16:30") .withLocation("Block 123, Bobby Street 3") .withTags("husband").build(); assertEditSuccess(addressBookIndex, addressBookIndex, detailsToEdit, editedPerson); } @Test public void edit_clearTags_success() throws Exception { String detailsToEdit = "t/"; int addressBookIndex = 2; TestTask personToEdit = expectedTasksList[addressBookIndex - 1]; TestTask editedPerson = new PersonBuilder(personToEdit).withTags().build(); assertEditSuccess(addressBookIndex, addressBookIndex, detailsToEdit, editedPerson); } @Test public void edit_duplicatePerson_failure() { commandBox.runCommand("update 3 Alice Pauline s/2017-04-01T10:16:30 e/2017-05-01T10:16:30 " + "l/123, Jurong West Ave 6, #08-111 t/friends"); assertResultMessage(UpdateCommand.MESSAGE_DUPLICATE_TASK); } @Test public void edit_findThenEdit_success() throws Exception { commandBox.runCommand("find Elle"); String detailsToEdit = "Belle"; int filteredPersonListIndex = 1; int addressBookIndex = 5; TestTask personToEdit = expectedTasksList[addressBookIndex - 1]; TestTask editedPerson = new PersonBuilder(personToEdit).withName("Belle").build(); assertEditSuccess(filteredPersonListIndex, addressBookIndex, detailsToEdit, editedPerson); } @Test public void edit_invalidPersonIndex_failure() { commandBox.runCommand("update 8 Bobby"); assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } @Test public void edit_invalidValues_failure() { commandBox.runCommand("update 1 *&"); assertResultMessage(Title.MESSAGE_TITLE_CONSTRAINTS); commandBox.runCommand("update 1 e/abcd"); assertResultMessage(DateTime.MESSAGE_DATETIME_CONSTRAINTS); commandBox.runCommand("update 1 s/yahoo!!!"); assertResultMessage(DateTime.MESSAGE_DATETIME_CONSTRAINTS); commandBox.runCommand("update 1 l/"); assertResultMessage(Location.MESSAGE_LOCATION_CONSTRAINTS);
package com.twu.biblioteca; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.junit.Assert.assertEquals; public class BibliotecaAppTest { private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); @Test public void testListBooksAndQuit() { String expected = "Welcome!\n" + getMenuOptionsString() + "\n" + "Book List:\n" + " Title Author Year\n" + " "(1)Head First Java Kathy Sierra, Bert Bates 2005\n" + "(2)Hadoop: The Definitive Guide Tom White 2009\n" + "(3)Java: A Beginner's Guide Herbert Schildt 2011\n" + "(4)Effective Java Joshua Bloch 2001\n" + "(5)Java All-in-One For Dummies Doug Lowe 2014\n" + "(6)Learning Java Patrick Niemeyer, Daniel Leuck 2013\n" + "\n" + getMenuOptionsString() + "\n" + "Quit!\n"; BibliotecaApp.program(new ByteArrayInputStream("l\nq\n".getBytes()), new PrintStream(outContent)); String actual = getTerminalOutput(); assertEquals(expected, actual); } @Test public void testCheckoutAndQuit() { String expected = "Welcome!\n" + getMenuOptionsString() + "\n" + "Book List:\n" + " Title Author Year\n" + " "(1)Head First Java Kathy Sierra, Bert Bates 2005\n" + "(2)Hadoop: The Definitive Guide Tom White 2009\n" + "(3)Java: A Beginner's Guide Herbert Schildt 2011\n" + "(4)Effective Java Joshua Bloch 2001\n" + "(5)Java All-in-One For Dummies Doug Lowe 2014\n" + "(6)Learning Java Patrick Niemeyer, Daniel Leuck 2013\n" + "\n" + "Select book to checkout: enter index\n" + "\n" + "Thank you! Enjoy the book.\n" + "\n" + getMenuOptionsString() + "\n" + "Quit!\n"; BibliotecaApp.program(new ByteArrayInputStream("c\n1\nq\n".getBytes()), new PrintStream(outContent)); String actual = getTerminalOutput(); assertEquals(expected, actual); } @Test public void testCheckoutAndListBooks() { String expected = "Welcome!\n" + getMenuOptionsString() + "\n" + "Book List:\n" + " Title Author Year\n" + " "(1)Head First Java Kathy Sierra, Bert Bates 2005\n" + "(2)Hadoop: The Definitive Guide Tom White 2009\n" + "(3)Java: A Beginner's Guide Herbert Schildt 2011\n" + "(4)Effective Java Joshua Bloch 2001\n" + "(5)Java All-in-One For Dummies Doug Lowe 2014\n" + "(6)Learning Java Patrick Niemeyer, Daniel Leuck 2013\n" + "\n" + "Select book to checkout: enter index\n" + "\n" + "Thank you! Enjoy the book.\n" + "\n" + getMenuOptionsString() + "\n" + "Book List:\n" + " Title Author Year\n" + " "(1)Head First Java Kathy Sierra, Bert Bates 2005\n" + "(2)Hadoop: The Definitive Guide Tom White 2009\n" + "(3)Effective Java Joshua Bloch 2001\n" + "(4)Java All-in-One For Dummies Doug Lowe 2014\n" + "(5)Learning Java Patrick Niemeyer, Daniel Leuck 2013\n" + "\n" + getMenuOptionsString() + "\n" + "Quit!\n"; BibliotecaApp.program(new ByteArrayInputStream("c\n3\nl\nq\n".getBytes()), new PrintStream(outContent)); String actual = getTerminalOutput(); assertEquals(expected, actual); } @Test public void testFailedCheckoutAndListBooks() { String expected = "Welcome!\n" + getMenuOptionsString() + "\n" + "Book List:\n" + " Title Author Year\n" + " "(1)Head First Java Kathy Sierra, Bert Bates 2005\n" + "(2)Hadoop: The Definitive Guide Tom White 2009\n" + "(3)Java: A Beginner's Guide Herbert Schildt 2011\n" + "(4)Effective Java Joshua Bloch 2001\n" + "(5)Java All-in-One For Dummies Doug Lowe 2014\n" + "(6)Learning Java Patrick Niemeyer, Daniel Leuck 2013\n" + "\n" + "Select book to checkout: enter index\n" + "\n" + "That book is not available!\n" + "\n" + getMenuOptionsString() + "\n" + "Book List:\n" + " Title Author Year\n" + " "(1)Head First Java Kathy Sierra, Bert Bates 2005\n" + "(2)Hadoop: The Definitive Guide Tom White 2009\n" + "(3)Java: A Beginner's Guide Herbert Schildt 2011\n" + "(4)Effective Java Joshua Bloch 2001\n" + "(5)Java All-in-One For Dummies Doug Lowe 2014\n" + "(6)Learning Java Patrick Niemeyer, Daniel Leuck 2013\n" + "\n" + getMenuOptionsString() + "\n" + "Quit!\n"; BibliotecaApp.program(new ByteArrayInputStream("c\n8\nl\nq\n".getBytes()), new PrintStream(outContent)); String actual = getTerminalOutput(); assertEquals(expected, actual); } @Test public void testInvalidSelectMenuOptionWithChar() { String expected = "Welcome!\n" + getMenuOptionsString() + "\n" + "Select a valid option!\n" + getMenuOptionsString() + "\n" + "Quit!\n"; BibliotecaApp.program(new ByteArrayInputStream("p\nq\n".getBytes()), new PrintStream(outContent)); String actual = getTerminalOutput(); assertEquals(expected, actual); } @Test public void testInvalidSelectMenuOptionWithCorrectCharButMore() { String expected = "Welcome!\n" + getMenuOptionsString() + "\n" + "Select a valid option!\n" + getMenuOptionsString() + "\n" + "Quit!\n"; BibliotecaApp.program(new ByteArrayInputStream("l hh\nq\n".getBytes()), new PrintStream(outContent)); String actual = getTerminalOutput(); assertEquals(expected, actual); } @Test public void testInvalidSelectMenuOptionWithWord() { String expected = "Welcome!\n" + getMenuOptionsString() + "\n" + "Select a valid option!\n" + getMenuOptionsString() + "\n" + "Quit!\n"; BibliotecaApp.program(new ByteArrayInputStream("line\nq\n".getBytes()), new PrintStream(outContent)); String actual = getTerminalOutput(); assertEquals(expected, actual); } @Test public void testReturnFirstBookAndListBooks() { String expected = "Welcome!\n" + getMenuOptionsString() + "\n" + "Book List:\n" + " Title Author Year\n" + " "(1)Head First Java Kathy Sierra, Bert Bates 2005\n" + "(2)Hadoop: The Definitive Guide Tom White 2009\n" + "(3)Java: A Beginner's Guide Herbert Schildt 2011\n" + "(4)Effective Java Joshua Bloch 2001\n" + "(5)Java All-in-One For Dummies Doug Lowe 2014\n" + "(6)Learning Java Patrick Niemeyer, Daniel Leuck 2013\n" + "\n" + "Select book to checkout: enter index\n" + "\n" + "Thank you! Enjoy the book.\n" + "\n" + getMenuOptionsString() + "\n" + "Enter title of the book you are returning:\n" + "\n" + "Thank you for returning the book.\n" + "\n" + getMenuOptionsString() + "\n" + "Book List:\n" + " Title Author Year\n" + " "(1)Hadoop: The Definitive Guide Tom White 2009\n" + "(2)Java: A Beginner's Guide Herbert Schildt 2011\n" + "(3)Effective Java Joshua Bloch 2001\n" + "(4)Java All-in-One For Dummies Doug Lowe 2014\n" + "(5)Learning Java Patrick Niemeyer, Daniel Leuck 2013\n" + "(6)Head First Java Kathy Sierra, Bert Bates 2005\n" + "\n" + getMenuOptionsString() + "\n" + "Quit!\n"; BibliotecaApp.program(new ByteArrayInputStream("c\n1\nr\nHead First Java\nl\nq\n".getBytes()), new PrintStream(outContent)); String actual = getTerminalOutput(); assertEquals(expected, actual); } @Test public void testReturnAvailableBookAndListBooks() { String expected = "Welcome!\n" + getMenuOptionsString() + "\n" + "Book List:\n" + " Title Author Year\n" + " "(1)Head First Java Kathy Sierra, Bert Bates 2005\n" + "(2)Hadoop: The Definitive Guide Tom White 2009\n" + "(3)Java: A Beginner's Guide Herbert Schildt 2011\n" + "(4)Effective Java Joshua Bloch 2001\n" + "(5)Java All-in-One For Dummies Doug Lowe 2014\n" + "(6)Learning Java Patrick Niemeyer, Daniel Leuck 2013\n" + "\n" + "Select book to checkout: enter index\n" + "\n" + "Thank you! Enjoy the book.\n" + "\n" + getMenuOptionsString() + "\n" + "Enter title of the book you are returning:\n" + "\n" + "Thank you for returning the book.\n" + "\n" + getMenuOptionsString() + "\n" + "Book List:\n" + " Title Author Year\n" + " "(1)Head First Java Kathy Sierra, Bert Bates 2005\n" + "(2)Hadoop: The Definitive Guide Tom White 2009\n" + "(3)Java: A Beginner's Guide Herbert Schildt 2011\n" + "(4)Effective Java Joshua Bloch 2001\n" + "(5)Learning Java Patrick Niemeyer, Daniel Leuck 2013\n" + "(6)Java All-in-One For Dummies Doug Lowe 2014\n" + "\n" + getMenuOptionsString() + "\n" + "Quit!\n"; BibliotecaApp.program(new ByteArrayInputStream("c\n5\nr\nJava All-in-One For Dummies\nl\nq\n".getBytes()), new PrintStream(outContent)); String actual = getTerminalOutput(); assertEquals(expected, actual); } @Test public void testMisspeltReturnAndListBooks() { String expected = "Welcome!\n" + getMenuOptionsString() + "\n" + "Book List:\n" + " Title Author Year\n" + " "(1)Head First Java Kathy Sierra, Bert Bates 2005\n" + "(2)Hadoop: The Definitive Guide Tom White 2009\n" + "(3)Java: A Beginner's Guide Herbert Schildt 2011\n" + "(4)Effective Java Joshua Bloch 2001\n" + "(5)Java All-in-One For Dummies Doug Lowe 2014\n" + "(6)Learning Java Patrick Niemeyer, Daniel Leuck 2013\n" + "\n" + "Select book to checkout: enter index\n" + "\n" + "Thank you! Enjoy the book.\n" + "\n" + getMenuOptionsString() + "\n" + "Enter title of the book you are returning:\n" + "\n" + "That is not a valid book to return.\n" + "\n" + getMenuOptionsString() + "\n" + "Book List:\n" + " Title Author Year\n" + " "(1)Head First Java Kathy Sierra, Bert Bates 2005\n" + "(2)Hadoop: The Definitive Guide Tom White 2009\n" + "(3)Java: A Beginner's Guide Herbert Schildt 2011\n" + "(4)Effective Java Joshua Bloch 2001\n" + "(5)Learning Java Patrick Niemeyer, Daniel Leuck 2013\n" + "\n" + getMenuOptionsString() + "\n" + "Quit!\n"; BibliotecaApp.program(new ByteArrayInputStream("c\n5\nr\nJava All-in-One For Dummie\nl\nq\n".getBytes()), new PrintStream(outContent)); String actual = getTerminalOutput(); assertEquals(expected, actual); } @Test public void testInvalidReturnAndListBooks() { String expected = "Welcome!\n" + getMenuOptionsString() + "\n" + "Book List:\n" + " Title Author Year\n" + " "(1)Head First Java Kathy Sierra, Bert Bates 2005\n" + "(2)Hadoop: The Definitive Guide Tom White 2009\n" + "(3)Java: A Beginner's Guide Herbert Schildt 2011\n" + "(4)Effective Java Joshua Bloch 2001\n" + "(5)Java All-in-One For Dummies Doug Lowe 2014\n" + "(6)Learning Java Patrick Niemeyer, Daniel Leuck 2013\n" + "\n" + "Select book to checkout: enter index\n" + "\n" + "Thank you! Enjoy the book.\n" + "\n" + getMenuOptionsString() + "\n" + "Enter title of the book you are returning:\n" + "\n" + "That is not a valid book to return.\n" + "\n" + getMenuOptionsString() + "\n" + "Book List:\n" + " Title Author Year\n" + " "(1)Head First Java Kathy Sierra, Bert Bates 2005\n" + "(2)Hadoop: The Definitive Guide Tom White 2009\n" + "(3)Java: A Beginner's Guide Herbert Schildt 2011\n" + "(4)Effective Java Joshua Bloch 2001\n" + "(5)Learning Java Patrick Niemeyer, Daniel Leuck 2013\n" + "\n" + getMenuOptionsString() + "\n" + "Quit!\n"; BibliotecaApp.program(new ByteArrayInputStream("c\n5\nr\n&\nl\nq\n".getBytes()), new PrintStream(outContent)); String actual = getTerminalOutput(); assertEquals(expected, actual); } @Test public void testListMovies() { String expected = "Welcome!\n" + getMenuOptionsString() + "\n" + "Movie List:\n" + " Title Year Director Rating\n" + " "(1)Casablanca 1942 Michael Curtiz 9\n" + "(2)The Godfather 1972 Francis Coppola 9\n" + "(3)Date Movie 2006 Aaron Seltzer 2\n" + "(4)Avatar 2009 James Cameron 8\n" + "(5)Iron Man 2008 Jon Favreau 7\n" + "\n" + getMenuOptionsString() + "\n" + "Quit!\n"; BibliotecaApp.program(new ByteArrayInputStream("m\nq\n".getBytes()), new PrintStream(outContent)); String actual = getTerminalOutput(); assertEquals(expected, actual); } private String getTerminalOutput() { String text = outContent.toString(); text = text.replaceAll("\r\n", "\n"); return text; } private String getMenuOptionsString() { return "Menu Options:\n" + "\tList Books: enter \"b\"\n" + "\tCheckout Book: enter \"c\"\n" + "\tReturn Book: enter \"r\"\n" + "\tList Movies: enter \"m\"\n" + "\tQuit: enter \"q\"\n"; } }
package integration; import com.codeborne.selenide.Configuration; import com.codeborne.selenide.SelenideElement; import com.codeborne.selenide.impl.ScreenShotLaboratory; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import static com.codeborne.selenide.Selenide.$; import static com.codeborne.selenide.WebDriverRunner.getWebDriver; import static com.codeborne.selenide.WebDriverRunner.isHtmlUnit; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.*; import static org.junit.Assume.assumeFalse; public class ScreenshotTest extends IntegrationTest { @Before public void openTestPage() { assumeFalse(isHtmlUnit()); openFile("page_with_big_divs.html"); } @Test public void canTakeScreenshotOfElement() throws IOException { SelenideElement element = $("#small_div"); File screenshot = element.screenshot(); String info = "(Screenshot of element: " + screenshot.getAbsolutePath() + ") "; BufferedImage img = ImageIO.read(screenshot); assertEquals("Screenshot doesn't fit width " + info, img.getWidth(), element.getSize().getWidth()); assertEquals("Screenshot doesn't fit height " + info, img.getHeight(), element.getSize().getHeight()); assertTrue("Screenshot file should be located in " + Configuration.reportsFolder + ", but was: " + screenshot.getPath(), screenshot.getPath().startsWith(Configuration.reportsFolder)); } @Test @Ignore public void resizeBigImageWidth() { SelenideElement element = $("#wide_div"); BufferedImage img = element.screenshotAsImage(); assertThat("Screenshot doesn't fit width", img.getWidth(), is(lessThan(element.getSize().getWidth()))); } @Test @Ignore public void resizeBigImageHeight() { SelenideElement element = $("#big_div"); BufferedImage img = new ScreenShotLaboratory().takeScreenshotAsImage(element); assertThat("Screenshot doesn't fit height", img.getHeight(), is(lessThan(element.getSize().getHeight()))); } @Test @Ignore public void resizeBigImage() throws IOException { SelenideElement element = $("#huge_div"); BufferedImage img = $("#huge_div").screenshotAsImage(); byte[] screen = ((TakesScreenshot) getWebDriver()).getScreenshotAs(OutputType.BYTES); BufferedImage tmp = ImageIO.read(new ByteArrayInputStream(screen)); String errorDetails = String.format("element.location: %s, element.size: %s, screen.size: (%s,%s)", element.getLocation(), element.getSize(), tmp.getWidth(), tmp.getHeight()); assertThat("Screenshot doesn't fit width - " + errorDetails, img.getWidth(), is(lessThan(element.getSize().getWidth()))); assertThat("Screenshot doesn't fit height - " + errorDetails, img.getHeight(), is(lessThan(element.getSize().getHeight()))); } }
package io.pivio; import org.apache.commons.cli.*; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.file.Paths; import static org.assertj.core.api.Assertions.*; public class ConfigurationTest { private Configuration configuration; @Before public void setUp() throws Exception { configuration = new Configuration(); } @Test public void testSourceParameterGivenInCommandLine() throws ParseException { String[] args = {"-source", "/home/nothing/test"}; CommandLine commandLine = configuration.parseCommandLine(args); configuration.setParameter(commandLine); String source = configuration.getParameter("source"); assertThat(source).isEqualTo("/home/nothing/test"); } @Test public void testSourceParameterNotGivenInCommandLine() throws ParseException, IOException { String[] args = {}; CommandLine commandLine = configuration.parseCommandLine(args); configuration.setParameter(commandLine); String source = configuration.getParameter("source"); String expectedResult = new java.io.File( "." ).getCanonicalPath(); assertThat(source).isEqualTo(expectedResult); } @Test public void testSourceParameterAddedInCommandLineParser() throws ParseException { String[] args = {"-source", "xxx"}; CommandLine commandLine = configuration.parseCommandLine(args); assertThat(commandLine.hasOption("source")).isTrue(); } @Test public void testGetParameterSource() throws Exception { String[] args = {"-source", "xxx"}; CommandLine commandLine = configuration.parseCommandLine(args); configuration.setParameter(commandLine); String option = "source"; String parameter = configuration.getParameter(option); assertThat(parameter).isEqualTo("xxx"); } @Test public void testGetParameterGitRemoteSpecified() throws Exception { String[] args = {"-gitremote", "demo"}; CommandLine commandLine = configuration.parseCommandLine(args); configuration.setParameter(commandLine); String option = "gitremote"; String parameter = configuration.getParameter(option); assertThat(parameter).isEqualTo("demo"); } @Test public void testGetParameterGitRemoteOrigin() throws Exception { String[] args = {}; CommandLine commandLine = configuration.parseCommandLine(args); configuration.setParameter(commandLine); String option = "gitremote"; String parameter = configuration.getParameter(option); assertThat(parameter).isEqualTo("origin"); } @Test public void testGetParameterUploadServerDefault() throws Exception { String[] args = {}; CommandLine commandLine = configuration.parseCommandLine(args); configuration.setParameter(commandLine); String option = Configuration.SWITCH_SERVICE_URL; String parameter = configuration.getParameter(option); assertThat(parameter).isEqualTo("http://localhost:9123"); } @Test public void testGetParameterUploadServerSpecified() throws Exception { String[] args = {"-"+Configuration.SWITCH_SERVICE_URL, "http://test"}; CommandLine commandLine = configuration.parseCommandLine(args); configuration.setParameter(commandLine); String option = Configuration.SWITCH_SERVICE_URL; String parameter = configuration.getParameter(option); assertThat(parameter).isEqualTo("http://test"); } @Test public void testGetParameterYamlSpecified() throws Exception { String[] args = {"-file", "test.yaml"}; CommandLine commandLine = configuration.parseCommandLine(args); configuration.setParameter(commandLine); String option = "file"; String parameter = configuration.getParameter(option); assertThat(parameter).isEqualTo("test.yaml"); } @Test public void testGetParameterYamlDefault() throws Exception { String[] args = {}; CommandLine commandLine = configuration.parseCommandLine(args); configuration.setParameter(commandLine); String option = "file"; String parameter = configuration.getParameter(option); assertThat(parameter).isEqualTo("pivio.yaml"); } @Test public void testVerboseParameter() throws Exception { String[] args = {"-verbose"}; CommandLine commandLine = configuration.parseCommandLine(args); configuration.setParameter(commandLine); assertThat(configuration.isVerbose()).isTrue(); } @Test public void testYamlPathSourceDir() throws Exception { String[] args = {"-source", "/tmp"}; CommandLine commandLine = configuration.parseCommandLine(args); configuration.setParameter(commandLine); assertThat(configuration.getYamlFilePath()).isEqualTo("/tmp/pivio.yaml"); } @Test public void testYamlPathSourceDirDefault() throws Exception { String[] args = {}; CommandLine commandLine = configuration.parseCommandLine(args); configuration.setParameter(commandLine); assertThat(configuration.getYamlFilePath()).isEqualTo(System.getProperty("user.dir")+"/pivio.yaml"); } @Test public void testParameterFileOverwritesParameterSource() throws Exception { String[] args = {"-source", "/tmp", "-file", "/var/test.yaml"}; CommandLine commandLine = configuration.parseCommandLine(args); configuration.setParameter(commandLine); assertThat(configuration.getYamlFilePath()).isEqualTo("/var/test.yaml"); } @Test public void testNoFileOrSourceIYamlFileInCurrentDir() throws Exception { String[] args = {}; CommandLine commandLine = configuration.parseCommandLine(args); configuration.setParameter(commandLine); assertThat(configuration.getYamlFilePath()).isEqualTo(Paths.get("").toAbsolutePath().toString()+ "/pivio.yaml"); } }
package org.storage; import static org.junit.Assert.*; import java.util.*; import org.dml.storage.Level2.*; import org.dml.storage.berkeleydb.generics.*; import org.dml.storage.commons.*; import org.junit.*; import org.q.*; import org.toolza.Timer; public class TestSetOfNodes extends BaseTest_for_Storage { /** * @param type1 * @param subType1 */ public TestSetOfNodes( final StorageType type1, final BDBStorageSubType subType1 ) { super( type1, subType1 ); } private L0Set_OfChildren set1; private NodeGeneric setParent; /* * (non-Javadoc) * * @see org.storage.TestBase_for_Storage#overridden_setUp() */ @Override public void overridden_setUp() { setParent = storage.createNewUniqueNode(); set1 = new L0Set_OfChildren( storage, setParent ); } @Test public void testWithout() { final Timer t = new Timer( Timer.TYPE.MILLIS ); t.start(); assertTrue( set1.size() == 0 ); final NodeGeneric one = storage.createNewUniqueNode(); assertNotNull( one ); assertFalse( set1.ensureIsAddedToSet( one ) ); assertTrue( set1.size() == 1 ); assertTrue( set1.ensureIsAddedToSet( one ) ); assertTrue( setParent.equals( set1.getSelf() ) ); assertTrue( setParent != set1.getSelf() );// they diff due to clone assertFalse( set1.contains( setParent ) );// didn't already exit final boolean ret = set1.ensureIsAddedToSet( setParent );// add itself to set ie. circular IS allowed assertFalse( ret );// didn't already exit assertTrue( set1.contains( setParent ) ); assertTrue( set1.remove( setParent ) ); assertFalse( set1.contains( setParent ) ); final int startSize = set1.size(); final NodeGeneric two = storage.createNewUniqueNode(); assertNotNull( two ); assertTrue( two != one ); assertFalse( set1.ensureIsAddedToSet( two ) ); assertTrue( set1.size() == ( startSize + 1 ) ); assertTrue( storage.isVector( set1.getSelf(), two ) ); final NodeGeneric three = storage.createNewUniqueNode(); assertNotNull( three ); assertFalse( set1.ensureIsAddedToSet( three ) ); assertTrue( storage.isVector( set1.getSelf(), three ) ); assertTrue( set1.size() == ( startSize + 2 ) ); final IteratorGeneric_OnChildNodes iter = set1.getIterator(); assertTrue( iter.goFirst().equals( one ) ); assertNull( iter.goPrev() );// even tho errored here, // cursor pos is unchanged iter.goTo( one ); assertTrue( two.equals( iter.goNext() ) ); iter.goTo( two ); assertTrue( three.equals( iter.goNext() ) ); assertNull( iter.goNext() ); iter.goTo( two ); assertTrue( one.equals( iter.goPrev() ) ); iter.goTo( three ); assertTrue( two.equals( iter.goPrev() ) ); NodeGeneric now = iter.goFirst(); while ( now != null ) { now = iter.goNext(); } assertTrue( storage.isVector( setParent, two ) ); // XXX: remove while iter is still active will fail, due to lock! // threw = false; // try { set1.remove( two ); // } catch ( final Throwable t ) { // if ( Q.isBareException( t, LockNotAvailableException.class ) ) { // threw = true; // } else { // Q.rethrow( t ); // assertTrue( threw ); // iter.goTo( two ); // iter.delete(); // iter.close(); assertFalse( storage.isVector( setParent, two ) ); assertTrue( iter.size() == 2 ); assertTrue( set1.size() == 2 ); // assertTrue( this.set1.remove( two ) ); final IteratorGeneric_OnChildNodes iter2 = iter;// this.set1.getIterator( ); // iter2.goFirst(); // while ( iter2.now() != null ) { // System.out.println( "iter2=" + iter2.now() ); // iter2.goNext(); assertNull( iter2.goTo( two ) ); iter2.goTo( one ); assertNull( iter2.goPrev() ); now = iter2.goTo( three ); assertNull( iter2.goNext() ); final NodeGeneric now2 = iter2.goTo( three ); assertTrue( now != now2 );// diff instances, always returning new BerkNodeAdapter() assertTrue( now.equals( now2 ) ); assertTrue( iter2.goPrev().equals( one ) ); iter2.goTo( one ); now = iter2.goNext(); assertTrue( now.equals( three ) ); assertTrue( iter2.size() == 2 ); assertTrue( now.equals( three ) ); assertTrue( storage.isVector( set1.getSelf(), three ) ); assertTrue( iter2.size() == 2 ); iter2.delete();// delete after count() ! assertFalse( storage.isVector( set1.getSelf(), three ) ); assertTrue( iter2.size() == 1 ); iter2.success(); iter2.finished(); assertFalse( storage.isVector( set1.getSelf(), three ) ); final NodeGeneric dsotParent = storage.createNewUniqueNode(); final L0DomainSet_OfChildren dsot = new L0DomainSet_OfChildren( storage, dsotParent, setParent ); assertTrue( set1.getSelf().equals( setParent ) ); try { final L0DomainSet_OfChildren adsot = new L0DomainSet_OfChildren( storage, set1.getSelf(), setParent ); Q.fail(); } catch ( final AssertionError ae ) { // good } final L0Set_OfChildren sot3 = new L0Set_OfChildren( storage, dsotParent ); assertTrue( sot3.getSelf().equals( dsot.getSelf() ) ); // assertFalse( sot3.equals( dsot ) ); // already used testEquals for this // assertFalse( dsot.equals( sot3 ) ); final L0DomainSet_OfChildren dsot3 = new L0DomainSet_OfChildren( storage, dsot.getSelf(), dsot.getDomain() ); final L0Set_OfChildren dsot4 = new L0DomainSet_OfChildren( storage, dsot.getSelf(), dsot.getDomain() ); assertTrue( dsot != dsot4 ); assertTrue( dsot3 != dsot4 ); assertTrue( dsot3 != dsot ); assertTrue( dsot.equals( dsot3 ) ); assertTrue( dsot.equals( dsot4 ) ); assertTrue( dsot4.equals( dsot ) ); final L0DomainSet_OfChildren dsot5 = new L0DomainSet_OfChildren( storage, dsot.getSelf(), storage.createNewUniqueNode() ); try { // same set but different domains?, which reminds me // XXX:we should not be able to `new` same set with two different domains; thing is we only detect this here when // equals happens between them; this is why we should keep constraints metadata in the database as opposed to fields dsot.equals( dsot5 ); Q.fail(); } catch ( final BadCallError bce ) { // good Q.markAsHandled( bce ); } dsot.hashCode(); final HashSet<L0Set_OfChildren> hm = new HashSet<L0Set_OfChildren>(); assertTrue( hm.add( dsot ) ); assertTrue( hm.add( set1 ) ); assertTrue( hm.size() == 2 ); assertFalse( hm.add( dsot ) ); assertFalse( hm.add( set1 ) ); assertTrue( hm.size() == 2 ); assertTrue( hm.contains( dsot ) ); assertFalse( hm.add( dsot3 ) ); assertTrue( hm.contains( dsot ) ); assertTrue( hm.contains( dsot3 ) ); assertTrue( dsot3 != dsot ); assertTrue( dsot3.equals( dsot ) ); assertTrue( hm.size() == 2 ); assertTrue( dsot.getSelf().equals( dsotParent ) ); assertTrue( dsot.getSelf() != dsotParent );// diff due to cloned assertTrue( dsot.getDomain() != setParent );// diff due to cloned assertTrue( dsot.getDomain().equals( setParent ) ); assertFalse( dsot.ensureIsAddedToSet( one ) ); assertTrue( dsot.contains( one ) ); assertFalse( dsot.contains( three ) ); assertFalse( set1.contains( three ) ); assertFalse( storage.isVector( set1.getSelf(), three ) ); try { dsot.ensureIsAddedToSet( three );// it's not in domain Q.fail();// asserts disabled? } catch ( final AssertionError ae ) { // right } assertFalse( dsot.isValidChild( three ) ); assertFalse( dsot.contains( three ) ); try { dsot.ensureIsAddedToSet( two );// it's not in domain either Q.fail(); } catch ( final AssertionError ae ) { // right } assertFalse( dsot.contains( two ) ); assertFalse( set1.ensureIsAddedToSet( two ) ); assertFalse( dsot.ensureIsAddedToSet( two ) ); assertTrue( dsot.contains( two ) ); // can add self, but now self is NOT in domain! so NO try { dsot.ensureIsAddedToSet( dsot.getSelf() ); Q.fail(); } catch ( final AssertionError ae ) { // good } assertFalse( dsot.contains( dsot.getSelf() ) ); assertFalse( set1.ensureIsAddedToSet( dsotParent ) ); // can add self, if self is in domain! YES now assertFalse( dsot.ensureIsAddedToSet( dsot.getSelf() ) ); assertTrue( dsot.contains( dsot.getSelf() ) ); try { dsot.ensureIsAddedToSet( dsot.getDomain() );// cannot add domain to set Q.fail(); } catch ( final AssertionError ae ) { // good } assertFalse( dsot.contains( dsot.getDomain() ) ); assertTrue( set1.size() == 3 ); set1.clearAll(); assertTrue( set1.size() == 0 ); assertTrue( set1.isEmpty() ); set1.clearAll(); assertTrue( set1.size() == 0 ); assertTrue( set1.isEmpty() ); t.stop(); System.out.println( t.getDeltaPrintFriendly() ); } @Test public void testAlreadyExisting() { final NodeGeneric l1 = storage.createNewUniqueNode(); assertNotNull( l1 ); final L0Set_OfChildren sos = new L0Set_OfChildren( storage, set1.getSelf() ); assertFalse( set1.ensureIsAddedToSet( l1 ) ); assertTrue( set1.size() == 1 ); assertTrue( sos.size() == 1 ); final L0Set_OfChildren sos2 = new L0Set_OfChildren( storage, set1.getSelf() ); assertTrue( sos2.size() == 1 ); assertTrue( sos.equals( sos2 ) ); assertTrue( sos.equals( set1 ) ); assertTrue( set1.equals( sos ) ); assertTrue( sos != set1 ); assertTrue( sos2 != set1 ); assertTrue( sos != sos2 ); final NodeGeneric domain = storage.createNewUniqueNode(); L0Set_OfChildren dsos; // doesn't check integrity, thus not throws here: dsos = new L0DomainSet_OfChildren( storage, sos2.getSelf(), domain ); assertFalse( storage.ensureVector( domain, l1 ) ); dsos = new L0DomainSet_OfChildren( storage, sos2.getSelf(), domain ); assertTrue( dsos.getSelf().equals( sos2.getSelf() ) ); assertTrue( dsos.size() == 1 ); } @Test public void testEquals() { final NodeGeneric domain = storage.createNewUniqueNode(); final NodeGeneric self1 = storage.createNewUniqueNode(); final L0DomainSet_OfChildren dsos = new L0DomainSet_OfChildren( storage, self1, domain ); final L0Set_OfChildren sos = new L0Set_OfChildren( storage, self1 ); assertFalse( domain.equals( dsos ) ); assertFalse( dsos.equals( domain ) ); assertFalse( sos.equals( domain ) ); assertFalse( domain.equals( sos ) ); assertTrue( sos.equals( self1 ) ); assertTrue( self1.equals( sos ) ); assertTrue( dsos.equals( self1 ) ); assertTrue( self1.equals( dsos ) ); // two diff class types using the same self, is detected when equals is performed: try { dsos.equals( sos ); Q.fail(); } catch ( final BadCallError bce ) { Q.markAsHandled( bce ); } try { assertFalse( sos.equals( dsos ) ); Q.fail(); } catch ( final BadCallError bce ) { Q.markAsHandled( bce ); } // now comparing two diff class types with diff self, will return fail w/o complaining // only if same self it would complain, because can use only one self for one type of class ie. Pointer and Set can't be // using same self; because their constraints would clash final NodeGeneric n2 = storage.createNewUniqueNode(); final L0DomainSet_OfChildren x = new L0DomainSet_OfChildren( storage, n2, domain ); assertFalse( x.equals( set1 ) ); assertFalse( set1.equals( x ) ); // of the same type ie. both Set or both Pointer; as opposed to one Set and one Pointer final L0DomainSet_OfChildren x2 = new L0DomainSet_OfChildren( storage, n2, domain ); assertTrue( x2.equals( x ) ); assertTrue( x.equals( x2 ) ); } @Test public void testPointer() { final NodeGeneric ptrParent = storage.createNewUniqueNode(); assertNotNull( ptrParent ); final Extension_Pointer_ToChild ptr = Extension_Pointer_ToChild.createExclusively_PointerToChild( storage, ptrParent ); assertFalse( storage.isVector( ptr, ptrParent ) ); assertTrue( ptr.getSelf() != ptrParent ); System.out.println( ptr.getSelfImpl().getClass() ); System.out.println( ptr.getSelf().getClass() ); System.out.println( ptrParent.getClass() ); final boolean ret = ptr.getSelf().equals( ptrParent ); assertTrue( ret ); assertNull( ptr.getPointeeChild() ); final NodeGeneric newL = storage.createNewUniqueNode(); assertNotNull( newL ); assertFalse( storage.ensureVector( ptrParent, newL ) ); try { Extension_Pointer_ToChild.createExclusively_PointerToChild( storage, ptrParent ); Q.fail(); } catch ( final BadCallError bce ) { Q.markAsHandled( bce ); } // this is valid even if it's using the same self as ptr because it's same extension type final Extension_Pointer_ToChild ptr2 = Extension_Pointer_ToChild.getExclusively_PointerToChild( storage, ptrParent ); assertNotNull( ptr2.getPointeeChild() ); assertTrue( ptr2.getPointeeChild().equals( newL ) ); assertTrue( ptr2.getPointeeChild() != newL ); assertTrue( ptr.getPointeeChild().equals( ptr2.getPointeeChild() ) ); assertTrue( ptr.getPointeeChild() != ptr2.getPointeeChild() ); assertTrue( ptr != ptr2 ); assertTrue( ptr.equals( ptr2 ) ); // this is not valid, since it uses same self as ptr2 final L0DomainPointer_ToChild dptr = new L0DomainPointer_ToChild( storage, ptr2.getSelf(), set1.getSelf() ); try { dptr.getPointeeChild();// detects that pointee is not in domain! Q.fail(); } catch ( final AssertionError ae ) {// FIXME: AssertionError is way too generic // it detected! // Q.markAsHandled( ae ); oh i see here, since it's an assert thrown, is not added in tree especially since not // using aspectj to hook each method call to catch any thrown exceptions (such as those from an `assert`) } // XXX: yes comparing different types but HashMap does this all the time so we're allowing it w/o throws // XXX: but in this case, we throw because! they are using the same self, which will induce a bug later try { dptr.equals( ptr ); Q.fail(); } catch ( final BadCallError bce ) { Q.markAsHandled( bce ); } try { ptr.equals( dptr ); Q.fail(); } catch ( final BadCallError bce ) { Q.markAsHandled( bce ); } dptr.hashCode(); final HashSet<Extension_Pointer_ToChild> hm = new HashSet<Extension_Pointer_ToChild>(); assertTrue( hm.add( dptr ) ); assertTrue( dptr.getSelf().equals( ptr.getSelf() ) ); assert dptr.getSelf().equals( ptr.getSelf() ); assertTrue( hm.add( ptr ) ); assertTrue( hm.size() == 2 ); assertTrue( hm.contains( dptr ) ); assertTrue( hm.contains( ptr ) ); // assertFalse( hm.add( ptr2 ) ); // // assertTrue( hm.contains( ptr ) ); // assertTrue( hm.contains( ptr2 ) ); // assertTrue( ptr2 != ptr ); // assertTrue( ptr2.equals( ptr ) ); // assertTrue( hm.size() == 2 ); assertFalse( set1.ensureIsAddedToSet( newL ) ); assertTrue( dptr.getPointeeChild().equals( newL ) ); final L0NonNullDomainPointer_ToChild nndptr = new L0NonNullDomainPointer_ToChild( storage, dptr.getSelf(), dptr.getDomain() ); assertTrue( newL.equals( nndptr.getPointeeChild() ) ); assertTrue( newL != nndptr.getPointeeChild() ); assertTrue( dptr.getDomain().equals( nndptr.getDomain() ) ); assertTrue( dptr.getDomain() != nndptr.getDomain() ); dptr.setPointee( null ); assertNull( dptr.getPointeeChild() ); try { System.out.println( nndptr.getPointeeChild() ); Q.fail(); } catch ( final AssertionError ae ) { // good } final L0NonNullDomainPointer_ToChild nndptr2 = new L0NonNullDomainPointer_ToChild( storage, dptr.getSelf(), dptr.getDomain() ); try { nndptr2.getPointeeChild(); Q.fail(); } catch ( final AssertionError ae ) { // good } try { nndptr2.setPointee( null ); Q.fail(); } catch ( final AssertionError ae ) { // good } nndptr2.setPointee( newL ); assertTrue( newL.equals( nndptr.getPointeeChild() ) ); } }
package org.takes.http; import com.google.common.base.Joiner; import com.jcabi.http.request.JdkRequest; import com.jcabi.http.response.RestResponse; import com.jcabi.matchers.RegexMatchers; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.ServerSocket; import java.net.Socket; import java.net.URI; import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Ignore; import org.junit.Test; import org.takes.Request; import org.takes.Response; import org.takes.Take; import org.takes.facets.fork.FkRegex; import org.takes.facets.fork.TkFork; import org.takes.rq.RqHeaders; import org.takes.rq.RqSocket; import org.takes.tk.TkText; /** * Test case for {@link BkBasic}. * * @author Dmitry Zaytsev (dmitry.zaytsev@gmail.com) * @version $Id$ * @since 0.15.2 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) * @checkstyle MultipleStringLiteralsCheck (500 lines) * @todo #516:15min Move header names from BkBasic to public constants. * Reusable header names will help in many situations. For example - in new * integration tests. */ @SuppressWarnings( { "PMD.ExcessiveImports", "PMD.TooManyMethods" }) public final class BkBasicTest { /** * Hello world. */ private static final String HELLO_WORLD = "Hello World!"; /** * Carriage return constant. */ private static final String CRLF = "\r\n"; /** * POST header constant. */ private static final String POST = "POST / HTTP/1.1"; /** * Host header constant. */ private static final String HOST = "Host:localhost"; /** * BkBasic can handle socket data. * * @throws IOException If some problem inside */ @Test public void handlesSocket() throws IOException { final MkSocket socket = BkBasicTest.createMockSocket(); final ByteArrayOutputStream baos = socket.bufferedOutput(); new BkBasic(new TkText(BkBasicTest.HELLO_WORLD)).accept(socket); MatcherAssert.assertThat( baos.toString(), Matchers.containsString("Hello World") ); } /** * BkBasic can return HTTP status 404 when accessing invalid URL. * * @throws IOException if any I/O error occurs. */ @Test public void returnsProperResponseCodeOnInvalidUrl() throws IOException { new FtRemote( new TkFork( new FkRegex("/path/a", new TkText("a")), new FkRegex("/path/b", new TkText("b")) ) ).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(String.format("%s/path/c", home)) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_NOT_FOUND); } } ); } /** * BkBasic produces headers with addresses without slashes. * * @throws IOException If some problem inside */ @Test public void addressesInHeadersAddedWithoutSlashes() throws IOException { final Socket socket = BkBasicTest.createMockSocket(); final AtomicReference<Request> ref = new AtomicReference<Request>(); new BkBasic( new Take() { @Override public Response act(final Request req) { ref.set(req); return new Response() { @Override public Iterable<String> head() throws IOException { return Collections.singletonList("HTTP/1.1 200 OK"); } @Override public InputStream body() throws IOException { return req.body(); } }; } } ).accept(socket); final Request request = ref.get(); final RqHeaders.Smart smart = new RqHeaders.Smart( new RqHeaders.Base(request) ); MatcherAssert.assertThat( smart.single( "X-Takes-LocalAddress", "" ), Matchers.not( Matchers.containsString("/") ) ); MatcherAssert.assertThat( smart.single( "X-Takes-RemoteAddress", "" ), Matchers.not( Matchers.containsString("/") ) ); MatcherAssert.assertThat( new RqSocket(request).getLocalAddress(), Matchers.notNullValue() ); MatcherAssert.assertThat( new RqSocket(request).getRemoteAddress(), Matchers.notNullValue() ); } /** * BkBasic can handle two requests in one connection. * * @throws Exception If some problem inside */ @Test public void handlesTwoRequestInOneConnection() throws Exception { final String text = "Hello Twice!"; final ByteArrayOutputStream output = new ByteArrayOutputStream(); final ServerSocket server = new ServerSocket(0); try { new Thread( new Runnable() { @Override public void run() { try { new BkBasic(new TkText(text)).accept( server.accept() ); } catch (final IOException exception) { throw new IllegalStateException(exception); } } } ).start(); final Socket socket = new Socket( server.getInetAddress(), server.getLocalPort() ); try { socket.getOutputStream().write( Joiner.on(BkBasicTest.CRLF).join( BkBasicTest.POST, BkBasicTest.HOST, "Content-Length: 11", "", "Hello First", BkBasicTest.POST, BkBasicTest.HOST, "Content-Length: 12", "", "Hello Second" ).getBytes() ); final InputStream input = socket.getInputStream(); // @checkstyle MagicNumber (1 line) final byte[] buffer = new byte[4096]; for (int count = input.read(buffer); count != -1; count = input.read(buffer)) { output.write(buffer, 0, count); } } finally { socket.close(); } } finally { server.close(); } MatcherAssert.assertThat( output.toString(), RegexMatchers.containsPattern( String.format("(?s)%s.*?%s", text, text) ) ); } /** * BkBasic can return HTTP status 411 when a persistent connection request * has no Content-Length. * * @throws Exception If some problem inside */ @Ignore @Test public void returnsProperResponseCodeOnNoContentLength() throws Exception { final ByteArrayOutputStream output = new ByteArrayOutputStream(); final ServerSocket server = new ServerSocket(0); try { new Thread( new Runnable() { @Override public void run() { try { new BkBasic(new TkText("411 Test")).accept( server.accept() ); } catch (final IOException exception) { throw new IllegalStateException(exception); } } } ).start(); final Socket socket = new Socket( server.getInetAddress(), server.getLocalPort() ); try { socket.getOutputStream().write( Joiner.on(BkBasicTest.CRLF).join( BkBasicTest.POST, BkBasicTest.HOST, "", BkBasicTest.HELLO_WORLD ).getBytes() ); final InputStream input = socket.getInputStream(); // @checkstyle MagicNumber (1 line) final byte[] buffer = new byte[4096]; for (int count = input.read(buffer); count != -1; count = input.read(buffer)) { output.write(buffer, 0, count); } } finally { socket.close(); } } finally { server.close(); } MatcherAssert.assertThat( output.toString(), Matchers.containsString("HTTP/1.1 411 Length Required") ); } /** * BkBasic can accept no content-length on closed connection. * * @throws Exception If some problem inside */ @Ignore @Test public void acceptsNoContentLengthOnClosedConnection() throws Exception { final String text = "Close Test"; final ByteArrayOutputStream output = new ByteArrayOutputStream(); final ServerSocket server = new ServerSocket(0); try { new Thread( new Runnable() { @Override public void run() { try { new BkBasic(new TkText(text)).accept( server.accept() ); } catch (final IOException exception) { throw new IllegalStateException(exception); } } } ).start(); final Socket socket = new Socket( server.getInetAddress(), server.getLocalPort() ); try { socket.getOutputStream().write( Joiner.on(BkBasicTest.CRLF).join( BkBasicTest.POST, BkBasicTest.HOST, "Connection: Close", "", BkBasicTest.HELLO_WORLD ).getBytes() ); final InputStream input = socket.getInputStream(); // @checkstyle MagicNumber (1 line) final byte[] buffer = new byte[4096]; for (int count = input.read(buffer); count != -1; count = input.read(buffer)) { output.write(buffer, 0, count); } } finally { socket.close(); } } finally { server.close(); } MatcherAssert.assertThat( output.toString(), Matchers.containsString(text) ); } /** * Creates Socket mock for reuse. * * @return Prepared Socket mock * @throws IOException If some problem inside */ private static MkSocket createMockSocket() throws IOException { return new MkSocket( new ByteArrayInputStream( Joiner.on(BkBasicTest.CRLF).join( "GET / HTTP/1.1", BkBasicTest.HOST, "Content-Length: 2", "", "hi" ).getBytes() ) ); } }
package com.matthewtamlin.spyglass.library.util; import com.matthewtamlin.spyglass.library.default_adapters.DefaultAdapter; import com.matthewtamlin.spyglass.library.handler_adapters.HandlerAdapter; import com.matthewtamlin.spyglass.library.meta_annotations.Default; import com.matthewtamlin.spyglass.library.meta_annotations.Handler; import com.matthewtamlin.spyglass.library.meta_annotations.Use; import com.matthewtamlin.spyglass.library.use_adapters.UseAdapter; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull; import static com.matthewtamlin.spyglass.library.util.AnnotationUtil.getUseAnnotations; @SuppressWarnings("TryWithIdenticalCatches") // Can't actually collapse blocks until API 19 public class AdapterUtil { private static final String EXCEPTION_MESSAGE = "Could not instantiate class %1$s. " + "Does the class have a public no-arg constructor?"; public static HandlerAdapter<?, Annotation> getHandlerAdapter(final Field field) { checkNotNull(field, "Argument \'field\' cannot be null."); final Annotation handlerAnnotation = AnnotationUtil.getHandlerAnnotation(field); if (handlerAnnotation == null) { return null; } final Class<? extends HandlerAdapter> adapterClass = handlerAnnotation .annotationType() .getAnnotation(Handler.class) .adapterClass(); try { return adapterClass.newInstance(); } catch (final InstantiationException e) { throw new RuntimeException(String.format(EXCEPTION_MESSAGE, adapterClass), e); } catch (final IllegalAccessException e) { throw new RuntimeException(String.format(EXCEPTION_MESSAGE, adapterClass), e); } } public static HandlerAdapter<?, Annotation> getHandlerAdapter(final Method method) { checkNotNull(method, "Argument \'method\' cannot be null."); final Annotation handlerAnnotation = AnnotationUtil.getHandlerAnnotation(method); if (handlerAnnotation == null) { return null; } final Class<? extends HandlerAdapter> adapterClass = handlerAnnotation .annotationType() .getAnnotation(Handler.class) .adapterClass(); try { return adapterClass.newInstance(); } catch (final InstantiationException e) { throw new RuntimeException(String.format(EXCEPTION_MESSAGE, adapterClass), e); } catch (final IllegalAccessException e) { throw new RuntimeException(String.format(EXCEPTION_MESSAGE, adapterClass), e); } } public static DefaultAdapter<?, Annotation> getDefaultAdapter(final Field field) { checkNotNull(field, "Argument \'field\' cannot be null."); final Annotation defaultAnnotation = AnnotationUtil.getDefaultAnnotation(field); if (defaultAnnotation == null) { return null; } final Class<? extends DefaultAdapter> adapterClass = defaultAnnotation .annotationType() .getAnnotation(Default.class) .adapterClass(); try { return adapterClass.newInstance(); } catch (final InstantiationException e) { throw new RuntimeException(String.format(EXCEPTION_MESSAGE, adapterClass), e); } catch (final IllegalAccessException e) { throw new RuntimeException(String.format(EXCEPTION_MESSAGE, adapterClass), e); } } public static DefaultAdapter<?, Annotation> getDefaultAdapter(final Method method) { checkNotNull(method, "Argument \'method\' cannot be null."); final Annotation defaultAnnotation = AnnotationUtil.getDefaultAnnotation(method); if (defaultAnnotation == null) { return null; } final Class<? extends DefaultAdapter> adapterClass = defaultAnnotation .annotationType() .getAnnotation(Default.class) .adapterClass(); try { return adapterClass.newInstance(); } catch (final InstantiationException e) { throw new RuntimeException(String.format(EXCEPTION_MESSAGE, adapterClass), e); } catch (final IllegalAccessException e) { throw new RuntimeException(String.format(EXCEPTION_MESSAGE, adapterClass), e); } } public static Map<Integer, UseAdapter> getUseAdapters(final Method method) { checkNotNull(method, "Argument \'method \' cannot be null."); final Map<Integer, UseAdapter> adapters = new HashMap<>(); final Map<Integer, Annotation> useAnnotations = getUseAnnotations(method); for (final Integer i : useAnnotations.keySet()) { final Class<? extends UseAdapter> adapterClass = useAnnotations .get(i) .annotationType() .getAnnotation(Use.class) .adapterClass(); try { adapters.put(i, adapterClass.newInstance()); } catch (final InstantiationException e) { throw new RuntimeException(String.format(EXCEPTION_MESSAGE, adapterClass), e); } catch (final IllegalAccessException e) { throw new RuntimeException(String.format(EXCEPTION_MESSAGE, adapterClass), e); } } return adapters; } }
package GuiElements; import javax.swing.JPanel; import java.awt.GridBagLayout; import javax.swing.JTextArea; import java.awt.GridBagConstraints; import java.awt.Insets; import java.awt.Dimension; import javax.swing.JTextPane; import javax.swing.JLabel; import java.awt.Font; import javax.swing.border.LineBorder; import java.awt.Color; import java.awt.Component; import javax.swing.Box; public class ChatWindowPanelSender extends JPanel{ private JLabel lbl_cnfrmMessage; public ChatWindowPanelSender(String inputText, String timeStamp) { //panel properties setBackground(Color.WHITE); setBorder(new LineBorder(Color.GREEN)); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.rowWeights = new double[]{2.0, 0.0, 0.0}; gridBagLayout.columnWeights = new double[]{2.0}; setLayout(gridBagLayout); //text pane JTextPane textpn_chatText = new JTextPane(); textpn_chatText.setBorder(new LineBorder(Color.GRAY, 2)); textpn_chatText.setText(inputText); textpn_chatText.setEditable(false); GridBagConstraints gbc_textpn_chatText = new GridBagConstraints(); gbc_textpn_chatText.insets = new Insets(0, 0, 5, 0); gbc_textpn_chatText.fill = GridBagConstraints.BOTH; gbc_textpn_chatText.gridx = 0; gbc_textpn_chatText.gridy = 0; add(textpn_chatText, gbc_textpn_chatText); //time-stamp label JLabel lbl_chatTimeStamp = new JLabel(timeStamp); lbl_chatTimeStamp.setBorder(null); lbl_chatTimeStamp.setBackground(Color.WHITE); lbl_chatTimeStamp.setFont(new Font("Ubuntu Light", Font.PLAIN, 10)); GridBagConstraints gbc_lbl_chatTimeStamp = new GridBagConstraints(); gbc_lbl_chatTimeStamp.insets = new Insets(0, 0, 5, 0); gbc_lbl_chatTimeStamp.anchor = GridBagConstraints.EAST; gbc_lbl_chatTimeStamp.gridx = 0; gbc_lbl_chatTimeStamp.gridy = 1; add(lbl_chatTimeStamp, gbc_lbl_chatTimeStamp); //showMsg("message received"); //here is an example of how you should call it! } //call this function on the panel when the acknowledgment is received void showMsg(String msg){ lbl_cnfrmMessage=new JLabel(msg); lbl_cnfrmMessage.setBorder(null); lbl_cnfrmMessage.setBackground(Color.WHITE); lbl_cnfrmMessage.setFont(new Font("Ubuntu Light", Font.PLAIN, 10)); GridBagConstraints gbc_lbl_cnfrmMessage = new GridBagConstraints(); gbc_lbl_cnfrmMessage.anchor = GridBagConstraints.SOUTHEAST; gbc_lbl_cnfrmMessage.gridx = 0; gbc_lbl_cnfrmMessage.gridy = 2; add(lbl_cnfrmMessage, gbc_lbl_cnfrmMessage); } }
package nammari.network.ui; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.Loader; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import nammari.network.R; import nammari.network.loader.EndlessNetworkLoader; import nammari.network.loader.ErrorAwareLoader; import nammari.network.logger.Logger; import nammari.network.ui.widget.ItemDecorationAlbumColumns; import nammari.network.ui.widget.PaddingItemDecoration; import nammari.network.util.LoaderErrorAwareHelper; public abstract class EndlessMultiStateAbsListFragment<T> extends MultiStateAbsFragmentWithLoader implements LoaderCallbacks<T>, OnClickListener { // to update ui protected Handler mHandler; // wrapper adapter private NetworkWrapperAdapter adapter; // /** // * Some times we can't fire the loaded in the onActivityCreated method for // * example in this project SearchResultFragment can't have the query // * parameter when creating the activity it will be provided in // * onHandleSearch ( after ) the fragment created // * // */ // protected boolean fireLoaderInOnActivityCreated = true; public EndlessMultiStateAbsListFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setRetainInstance(true); if (getListType() == LIST_TYPE.GRID_VIEW) { setHasOptionsMenu(true); } } public static abstract class GridEndlessMultiStateFragment<T> extends EndlessMultiStateAbsListFragment<T> { public GridEndlessMultiStateFragment() { } @Override protected LIST_TYPE getListType() { return LIST_TYPE.GRID_VIEW; } } public static abstract class ListEndlessMultiStateFragment<T> extends EndlessMultiStateAbsListFragment<T> { public ListEndlessMultiStateFragment() { } @Override protected LIST_TYPE getListType() { return LIST_TYPE.LIST_VIEW; } } public static abstract class StaggeredGridEndlessMultiStateFragment<T> extends EndlessMultiStateAbsListFragment<T> { public StaggeredGridEndlessMultiStateFragment() { } @Override protected LIST_TYPE getListType() { return LIST_TYPE.STAGGERED_GRID; } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (supportSwipeToRefreshLayout() && getSwipeRefreshLayout() != null) { setRefreshForSwipeRefreshLayout(isLoading()); } super.onCreateOptionsMenu(menu, inflater); } @Override public void onAttach(Context context) { super.onAttach(context); mHandler = new Handler(); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); RecyclerView list = getRecyclerView(); list.setFadingEdgeLength(0); if (includeItemDecoration()) { int paddingBetweenItems = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2.0f, getResources().getDisplayMetrics()); if (getListType() == LIST_TYPE.GRID_VIEW || getListType() == LIST_TYPE.STAGGERED_GRID) { list.addItemDecoration(new ItemDecorationAlbumColumns(paddingBetweenItems, getGridSpan())); } else { list.addItemDecoration(new PaddingItemDecoration(paddingBetweenItems, 0)); } } if (supportEndless()) { list.addOnScrollListener(new EndlessRecyclerViewScrollListener()); } } public class EndlessRecyclerViewScrollListener extends RecyclerView.OnScrollListener { public EndlessRecyclerViewScrollListener() { if (getListType() == LIST_TYPE.STAGGERED_GRID) { visibleThreshold = visibleThreshold * getStaggeredSpanCount(); } } private int visibleThreshold = 5; public int getLastVisibleItemPosition(int[] lastVisibleItemPositions) { int maxPosition = 0; for (int i = 0; i < lastVisibleItemPositions.length; i++) { if (i == 0) { maxPosition = lastVisibleItemPositions[i]; } else if (lastVisibleItemPositions[i] > maxPosition) { maxPosition = lastVisibleItemPositions[i]; } } return maxPosition; } public int getFirstVisibleItemPosition(int[] firstVisibleItemPositions) { int minPosition = 0; for (int i = 0; i < firstVisibleItemPositions.length; i++) { if (i == 0) { minPosition = firstVisibleItemPositions[i]; } else if (firstVisibleItemPositions[i] < minPosition) { minPosition = firstVisibleItemPositions[i]; } } return minPosition; } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { boolean scrollReachedTarget; if (getListType() == LIST_TYPE.STAGGERED_GRID) { StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager(); int[] lastVisibleItemPositions = layoutManager.findLastVisibleItemPositions(null); int[] firstVisibleItemPositions = layoutManager.findLastVisibleItemPositions(null); int lastVisibleItemPosition = getLastVisibleItemPosition(lastVisibleItemPositions); int firstVisibleITemPosition = getFirstVisibleItemPosition(firstVisibleItemPositions); int visibleItemCount = lastVisibleItemPosition - firstVisibleITemPosition; int totalItemCount = layoutManager.getItemCount(); scrollReachedTarget = firstVisibleITemPosition + visibleItemCount + visibleThreshold >= totalItemCount; } else { LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); int visibleItemCount = layoutManager.findLastVisibleItemPosition() - layoutManager.findFirstVisibleItemPosition(); int firstVisibleItem = layoutManager.findFirstVisibleItemPosition(); int totalItemCount = layoutManager.getItemCount(); scrollReachedTarget = firstVisibleItem + visibleItemCount + visibleThreshold >= totalItemCount; } if (!isLoading() && !hasError() && hasMoreResults() && scrollReachedTarget) { if (isAdded()) { final EndlessNetworkLoader<?> loader = (EndlessNetworkLoader) getLoaderManager().getLoader( getEndlessNetworkLoaderId()); loader.setUseMax(true); } loadMore(); } if (supportSwipeToRefreshLayout()) { int topRowVerticalPosition = (recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop(); getSwipeRefreshLayout().setEnabled(topRowVerticalPosition >= 0); } } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } } protected boolean includeItemDecoration() { return true; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); adapter = new NetworkWrapperAdapter(getMainAdapter(getActivity()), getActivity()); setListAdapter(adapter); Logger.logInfo("from onActivityCreated", "from onActivityCreate"); showLoadingView(true); getLoaderManager().initLoader(getEndlessNetworkLoaderId(), null, this); } protected class NetworkWrapperAdapter extends RecyclerView.Adapter { private static final int VIEW_TYPE_LOADING = 22; private final MainNetworkAdapter<T> mainAdapter; private final LayoutInflater inflater; public NetworkWrapperAdapter(MainNetworkAdapter<T> mainAdapter, Context context) { super(); this.mainAdapter = mainAdapter; this.inflater = LayoutInflater.from(context); } @Override public int getItemCount() { return mainAdapter.getItemCount() + (supportEndless() ? (getListType() == LIST_TYPE.GRID_VIEW ? (hasError() ? 1 : 0) : ((isLoading() && mainAdapter.getItemCount() == 0)// ...this // the first // load || hasMoreResults() // ...or there's another // page || hasError() // ...or there's an error ? 1 : 0)) : 0); } @Override public long getItemId(int position) { return getItemViewType(position) == VIEW_TYPE_LOADING ? -1 : mainAdapter.getItemId(position); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == VIEW_TYPE_LOADING) { return new ListLoadingViewHolder(inflater.inflate(R.layout.list_endless_loading_view, parent, false)); } else { return mainAdapter.onCreateViewHolder(parent, viewType - 1); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (position < mainAdapter.getItemCount()) { mainAdapter.onBindViewHolder(holder, position); } else { ListLoadingViewHolder holder1 = (ListLoadingViewHolder) holder; if (hasError() && !isLoading()) { // show error holder1.loading_container .setVisibility(View.GONE); holder1.error_container.setVisibility(View.VISIBLE); holder1.button1 .setOnClickListener(EndlessMultiStateAbsListFragment.this); } else { // show loading holder1.error_container .setVisibility(View.GONE); holder1.loading_container.setVisibility(View.VISIBLE); } } } public void addData(T data) { if (mainAdapter != null) { mainAdapter.deliverNewResult(data); } } @Override public int getItemViewType(int position) { if (mainAdapter.getItemCount() == 0 || position >= mainAdapter.getItemCount()) { return VIEW_TYPE_LOADING; } else { return mainAdapter.getItemViewType(position); } } public MainNetworkAdapter<? extends T> getMainAdapter() { return mainAdapter; } } static class ListLoadingViewHolder extends RecyclerView.ViewHolder { View loading_container; View button1; View error_container; public ListLoadingViewHolder(View itemView) { super(itemView); loading_container = itemView.findViewById(R.id.loading_container); button1 = itemView.findViewById(R.id.button1); error_container = itemView.findViewById(R.id.error_container); } } @Override public void onLoadFinished(Loader<T> arg0, T arg1) { if (arg0.getId() == getEndlessNetworkLoaderId()) { if (adapter != null) { adapter.addData(arg1); adapter.notifyDataSetChanged(); } } if (adapter != null) { adapter.notifyDataSetChanged(); } ErrorAwareLoader __loader = (ErrorAwareLoader) arg0; Logger.logDebug("hasError", "" + __loader.containsError()); LoaderErrorAwareHelper.updateSingleLoaderStatus(this, __loader); refreshActionbar(); mHandler.post(new Runnable() { @Override public void run() { setRefreshForSwipeRefreshLayout(false); } }); } @Override public void onClick(View v) { if (v.getId() == R.id.button1) { if (!isLoading()) { loadMore(); mHandler.post(new Runnable() { @Override public void run() { if (adapter != null) { adapter.notifyDataSetChanged(); } } }); } } } /** * @author nammari * This class used to force users of this class to use it as base * class for their main adapter such that when the loader finishes * his task the loaded data can be assigned to the main adapter */ public static abstract class MainNetworkAdapter<T> extends RecyclerView.Adapter { protected LayoutInflater inflater; protected Context mContext; public MainNetworkAdapter(Context context) { this.inflater = LayoutInflater.from(context); this.mContext = context; } public abstract void deliverNewResult(T data); public abstract void clearData(); } // get the id for the network loader protected abstract int getEndlessNetworkLoaderId(); // get the main adapter that contains your custom views protected abstract MainNetworkAdapter<T> getMainAdapter(Context context); // loader access @SuppressWarnings("unchecked") protected boolean isLoading() { if (isAdded()) { final Loader<?> loader = getLoaderManager().getLoader( getEndlessNetworkLoaderId()); if (loader != null) { return ((EndlessNetworkLoader<T>) loader).isLoading(); } } return true; } @SuppressWarnings("unchecked") protected boolean hasError() { if (isAdded()) { final Loader<?> loader = getLoaderManager().getLoader( getEndlessNetworkLoaderId()); if (loader != null) { return ((EndlessNetworkLoader<T>) loader).hasError(); } } return false; } @SuppressWarnings("unchecked") protected boolean hasMoreResults() { if (isAdded()) { final Loader<?> loader = getLoaderManager().getLoader( getEndlessNetworkLoaderId()); if (loader != null) { return ((EndlessNetworkLoader<T>) loader).hasMoreResults(); } } return true; } protected void loadMore() { if (isAdded()) { final Loader<?> loader = getLoaderManager().getLoader( getEndlessNetworkLoaderId()); if (loader != null) { loader.forceLoad(); } } refreshActionbar(); } @SuppressWarnings("unchecked") protected void refresh(boolean forceRefresh) { if (isLoading() && !forceRefresh) { return; } if (isAdded()) { EndlessNetworkLoader<?> loader = (EndlessNetworkLoader) getLoaderManager().getLoader( getEndlessNetworkLoaderId()); loader.init(); loader.refresh(); loader.setUseMax(false); } loadMore(); } private final Runnable mForceRefresh = new Runnable() { @Override public void run() { refresh(true); } }; protected final void refreshActionbar() { mHandler.post(mRefreshActionbarUI); } private final Runnable mRefreshActionbarUI = new Runnable() { @Override public void run() { if (getActivity() != null) { (getActivity()) .supportInvalidateOptionsMenu(); } } }; public NetworkWrapperAdapter getAdapter() { return adapter; } @Override public void showErrorUI(boolean animate) { if (getAdapter().getMainAdapter().getItemCount() > 1) { // show the list showRecylcerView(isResumed()); return; } super.showErrorUI(animate); } protected boolean supportEndless() { return true; } @Override protected void onSwipeRefresh() { super.onSwipeRefresh(); mHandler.post(mForceRefresh); if (getAdapter().getItemCount() > 1) { showMainUI(true); } } @Override protected final GridLayoutManager.SpanSizeLookup getSpanSizeLookup() { return new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return (adapter.getItemViewType(position) == NetworkWrapperAdapter.VIEW_TYPE_LOADING) ? getGridSpan() : 1; } }; } }
package com.novoda.downloadmanager; import org.junit.Before; import org.junit.Test; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class LiteBatchFileBuilderTest { private static final String ANY_NETWORK_ADDRESS = "http://ak.assets.com/some-file"; private final InternalBatchBuilder batchBuilder = mock(InternalBatchBuilder.class); private final StorageRoot storageRoot = mock(StorageRoot.class); private final DownloadBatchId downloadBatchId = mock(DownloadBatchId.class); private final LiteBatchFileBuilder liteBatchFileBuilder = new LiteBatchFileBuilder( storageRoot, downloadBatchId, ANY_NETWORK_ADDRESS ); @Before public void setUp() { given(downloadBatchId.rawId()).willReturn("my-movie"); } @Test public void concatenatesAllPaths() { given(storageRoot.path()).willReturn("root"); liteBatchFileBuilder .withParentBuilder(batchBuilder) .saveTo("my/path", "my-movie.mp4") .apply(); verify(batchBuilder).withFile(batchFileWithPath("root/my-movie/my/path/my-movie.mp4")); } @Test public void doesNotAddDuplicateSeparators() { given(storageRoot.path()).willReturn("/root/"); given(downloadBatchId.rawId()).willReturn("/my-movie/"); liteBatchFileBuilder .withParentBuilder(batchBuilder) .saveTo("/my/path/", "/my-movie.mp4") .apply(); verify(batchBuilder).withFile(batchFileWithPath("/root/my-movie/my/path/my-movie.mp4")); } @Test public void ignoresEmptyPath() { given(storageRoot.path()).willReturn("root"); liteBatchFileBuilder .withParentBuilder(batchBuilder) .saveTo("", "my-movie.mp4") .apply(); verify(batchBuilder).withFile(batchFileWithPath("root/my-movie/my-movie.mp4")); } @Test public void ignoreSeparatorAsPath() { given(storageRoot.path()).willReturn("root/"); liteBatchFileBuilder .withParentBuilder(batchBuilder) .saveTo("/", "/my-movie.mp4") .apply(); verify(batchBuilder).withFile(batchFileWithPath("root/my-movie/my-movie.mp4")); } @Test public void doesNotIgnoreSeparatorAsRoot() { given(storageRoot.path()).willReturn("/"); liteBatchFileBuilder .withParentBuilder(batchBuilder) .saveTo("my/path", "/my-movie.mp4") .apply(); verify(batchBuilder).withFile(batchFileWithPath("/my-movie/my/path/my-movie.mp4")); } private BatchFile batchFileWithPath(String path) { return new BatchFile( ANY_NETWORK_ADDRESS, Optional.absent(), path ); } }
package com.litesalt.batch.entity; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSONObject; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.Pipeline; import redis.clients.jedis.Response; /** * @author Paul-xiong * @date 2017226 * @description redis */ public class RedisRowBatchQueue<T> extends RowBatchQueue<T> { private final static String DEFAULT_HOST = "localhost"; private final static int DEFAULT_PORT = 6379; private final static String DEFAULT_REDIS_KEY = "rowBatchQueue"; private final Logger logger = LoggerFactory.getLogger(RedisRowBatchQueue.class); private JedisPool jedisPool; private String redisKey; public RedisRowBatchQueue(Class<T> clazz) { this(clazz, DEFAULT_HOST, DEFAULT_PORT); } public RedisRowBatchQueue(Class<T> clazz, String host, int port) { this(clazz, host, port, DEFAULT_REDIS_KEY); } public RedisRowBatchQueue(Class<T> clazz, String host, int port, String redisKey) { super(clazz); this.jedisPool = new JedisPool(new JedisPoolConfig(), host, port, 3000); this.redisKey = redisKey; } @Override public void put(T t) { Jedis jedis = null; try { jedis = this.jedisPool.getResource(); String value = JSONObject.toJSONString(t); this.logger.debug("start: rpush redis. key={}, value={}", redisKey, value); jedis.rpush(redisKey, value); } catch (Exception e) { this.logger.error("Redis exception: {}", e.getMessage(), e); } finally { if (jedis != null) { jedis.close(); } } } @Override public T take() { List<T> take = take(1); if (take != null && take.size() > 0) { return take.get(0); } return null; } @Override public List<T> take(long len) { List<T> rt = new ArrayList<T>(); Jedis jedis = null; try { if (len > 0) { jedis = this.jedisPool.getResource(); Pipeline pipe = jedis.pipelined(); List<Response<String>> responseList = new ArrayList<Response<String>>(); while (len > 0) { responseList.add(pipe.lpop(redisKey)); len } pipe.sync(); for (Response<String> response : responseList) { String item = response.get(); if (StringUtils.isNotBlank(item)) { rt.add(JSONObject.parseObject(item, clazz)); } } } } catch (Exception e) { this.logger.error("Redis exception: {}", e.getMessage(), e); } finally { if (jedis != null) { jedis.close(); } } return rt; } @Override public List<T> takeAll() { try (Jedis jedis = this.jedisPool.getResource()) { Long len = jedis.llen(redisKey); return take(len != null ? len : 0); } catch (Exception e) { this.logger.error("Redis exception: {}", e.getMessage(), e); return new ArrayList<T>(); } } }
package java.lang; public final class String implements Comparable<String> { private Object data; private int offset; private int length; private int hash; public String(char[] data, int offset, int length, boolean copy) { this((Object) data, offset, length, copy); } public String(char[] data, int offset, int length) { this(data, offset, length, true); } public String(char[] data) { this(data, 0, data.length); } public String(byte[] data, int offset, int length, boolean copy) { this((Object) data, offset, length, copy); } public String(byte[] data, int offset, int length) { this(data, offset, length, true); } public String(byte[] data) { this(data, 0, data.length); } private String(Object data, int offset, int length, boolean copy) { int l; if (data instanceof char[]) { l = ((char[]) data).length; } else { l = ((byte[]) data).length; } if (offset < 0 || offset + length > l) { throw new IndexOutOfBoundsException (offset + " < 0 or " + offset + " + " + length + " > " + l); } if (copy) { Object c; if (data instanceof char[]) { c = new char[length]; } else { c = new byte[length]; } System.arraycopy(data, offset, c, 0, length); this.data = c; this.length = length; } else { this.data = data; this.offset = offset; this.length = length; } } public String toString() { return this; } public int length() { return length; } public int hashCode() { if (hash == 0) { int h = 0; for (int i = 0; i < length; ++i) h = (h * 31) + charAt(i); hash = h; } return hash; } public boolean equals(Object o) { return this == o || (o instanceof String && compareTo((String) o) == 0); } public boolean equalsIgnoreCase(String s) { return this == s || compareToIgnoreCase(s) == 0; } public int compareTo(String s) { if (this == s) return 0; int idx = 0; int result; int end = (length < s.length ? length : s.length); while (idx < end) { if ((result = charAt(idx) - s.charAt(idx)) != 0) { return result; } idx++; } return length - s.length; } public int compareToIgnoreCase(String s) { if (this == s) return 0; int idx = 0; int result; int end = (length < s.length ? length : s.length); while (idx < end) { if ((result = Character.toLowerCase(charAt(idx)) - Character.toLowerCase(s.charAt(idx))) != 0) { return result; } idx++; } return length - s.length; } public String trim() { int start = -1; for (int i = 0; i < length; ++i) { char c = charAt(i); if (start == -1 && ! Character.isWhitespace(c)) { start = i; break; } } int end = -1; for (int i = length - 1; i >= 0; --i) { char c = charAt(i); if (end == -1 && ! Character.isWhitespace(c)) { end = i + 1; break; } } if (start >= end) { return ""; } else { return substring(start, end); } } public String toLowerCase() { char[] b = new char[length]; for (int i = 0; i < length; ++i) { b[i] = Character.toLowerCase(charAt(i)); } return new String(b, 0, length, false); } public String toUpperCase() { char[] b = new char[length]; for (int i = 0; i < length; ++i) { b[i] = Character.toUpperCase(charAt(i)); } return new String(b, 0, length, false); } public int indexOf(int c) { return indexOf(c, 0); } public int indexOf(int c, int start) { for (int i = start; i < length; ++i) { if (charAt(i) == c) { return i; } } return -1; } public int lastIndexOf(int c) { for (int i = length - 1; i >= 0; --i) { if (charAt(i) == c) { return i; } } return -1; } public int indexOf(String s) { return indexOf(s, 0); } public int indexOf(String s, int start) { if (s.length == 0) return start; for (int i = start; i < length - s.length + 1; ++i) { int j = 0; for (; j < s.length; ++j) { if (charAt(i + j) != s.charAt(j)) { break; } } if (j == s.length) { return i; } } return -1; } public int lastIndexOf(String s) { if (s.length == 0) return length; for (int i = length - s.length; i >= 0; --i) { int j = 0; for (; j < s.length && i + j < length; ++j) { if (charAt(i + j) != s.charAt(j)) { break; } } if (j == s.length) { return i; } } return -1; } public String substring(int start) { return substring(start, length); } public String substring(int start, int end) { if (start >= 0 && end >= start && end <= length) { if (start == 0 && end == length) { return this; } else if (end - start == 0) { return ""; } else { return new String(data, offset + start, end - start, false); } } else { throw new IndexOutOfBoundsException (start + " not in (0, " + end + ") or " + end + " > " + length); } } public boolean startsWith(String s) { if (length >= s.length) { return substring(0, s.length).compareTo(s) == 0; } else { return false; } } public boolean endsWith(String s) { if (length >= s.length) { return substring(length - s.length).compareTo(s) == 0; } else { return false; } } public String concat(String s) { if (s.length() == 0) { return this; } else { return this + s; } } public void getBytes(int srcOffset, int srcLength, byte[] dst, int dstOffset) { if (srcOffset < 0 || srcOffset + srcLength > length) { throw new IndexOutOfBoundsException(); } if (data instanceof char[]) { char[] src = (char[]) data; for (int i = 0; i < srcLength; ++i) { dst[i + dstOffset] = (byte) src[i + offset + srcOffset]; } } else { byte[] src = (byte[]) data; System.arraycopy(src, offset + srcOffset, dst, dstOffset, srcLength); } } public byte[] getBytes() { byte[] b = new byte[length]; getBytes(0, length, b, 0); return b; } public byte[] getBytes(String format) throws java.io.UnsupportedEncodingException { return getBytes(); } public void getChars(int srcOffset, int srcLength, char[] dst, int dstOffset) { if (srcOffset < 0 || srcOffset + srcLength > length) { throw new IndexOutOfBoundsException(); } if (data instanceof char[]) { char[] src = (char[]) data; System.arraycopy(src, offset + srcOffset, dst, dstOffset, srcLength); } else { byte[] src = (byte[]) data; for (int i = 0; i < srcLength; ++i) { dst[i + dstOffset] = (char) src[i + offset + srcOffset]; } } } public char[] toCharArray() { char[] b = new char[length]; getChars(0, length, b, 0); return b; } public char charAt(int index) { if (index < 0 || index > length) { throw new IndexOutOfBoundsException(); } if (data instanceof char[]) { return ((char[]) data)[index + offset]; } else { return (char) ((byte[]) data)[index + offset]; } } public String[] split(String s) { String[] array = new String[(length / s.length) + 1]; int index = 0; int last = 0; int position = 0; for (int i = 0; i < length - s.length + 1;) { int j; for (j = 0; j < s.length; ++j) { if (charAt(i + j) != s.charAt(j)) { break; } } if (j == s.length) { if (i > 0) { if (i > position) { last = index; } array[index++] = substring(position, i); } i = position = i + s.length; } else { ++ i; } } if (position < length) { last = index; array[index] = substring(position, length); } if (last + 1 < array.length) { String[] a = new String[last + 1]; System.arraycopy(array, 0, a, 0, last + 1); array = a; } return array; } public native String intern(); public static String valueOf(Object s) { return s == null ? "null" : s.toString(); } public static String valueOf(boolean v) { return Boolean.toString(v); } public static String valueOf(byte v) { return Byte.toString(v); } public static String valueOf(short v) { return Short.toString(v); } public static String valueOf(char v) { return Character.toString(v); } public static String valueOf(int v) { return Integer.toString(v); } public static String valueOf(long v) { return Long.toString(v); } public static String valueOf(float v) { return Float.toString(v); } public static String valueOf(double v) { return Double.toString(v); } }
package com.codahale.metrics; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicLong; public class InstrumentedThreadFactory implements ThreadFactory { private static final AtomicLong nameCounter = new AtomicLong(); private final ThreadFactory factory; final Counter created; final Counter running; final Counter finished; public InstrumentedThreadFactory(ThreadFactory factory, MetricRegistry registry) { this(factory, registry, "instrumented-thread-factory-" + nameCounter.incrementAndGet()); } public InstrumentedThreadFactory(ThreadFactory factory, MetricRegistry registry, String name) { this.factory = factory; this.created = registry.counter(name + ".created"); this.running = registry.counter(name + ".running"); this.finished = registry.counter(name + ".finished"); } @Override public Thread newThread(Runnable runnable) { Runnable wrappedRunnable = new InstrumentedRunnable(runnable); Thread thread = factory.newThread(wrappedRunnable); created.inc(); return thread; } private class InstrumentedRunnable implements Runnable { private final Runnable task; InstrumentedRunnable(Runnable task) { this.task = task; } @Override public void run() { running.inc(); try { task.run(); } finally { running.dec(); finished.inc(); } } } }
package org.apache.geronimo.common.net.protocol; import java.net.URL; import java.net.URLStreamHandler; import java.util.List; import java.util.LinkedList; import java.util.Iterator; import java.util.StringTokenizer; import java.util.Map; import java.lang.reflect.Field; import java.security.AccessController; import java.security.PrivilegedAction; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.StringUtils; import org.apache.geronimo.common.NullArgumentException; import org.apache.geronimo.common.Classes; import org.apache.geronimo.common.ThrowableHandler; public class Protocols { private static final Log log = LogFactory.getLog(Protocols.class); // Protocol Handler Packages // public static final String HANDLER_PACKAGES = "java.protocol.handler.pkgs"; public static final String SYSTEM_HANDLER_PACKAGES = System.getProperty(HANDLER_PACKAGES); static List parseHandlerPackages(final String pkgs) { assert pkgs != null; List list = new LinkedList(); if (pkgs != null) { StringTokenizer stok = new StringTokenizer(pkgs, "|"); while (stok.hasMoreTokens()) { list.add(stok.nextToken().trim()); } } return list; } public static List getSystemHandlerPackages() { return parseHandlerPackages(SYSTEM_HANDLER_PACKAGES); } public static List getHandlerPackages() { String handlersProperty = System.getProperty(HANDLER_PACKAGES); if (handlersProperty != null) { return parseHandlerPackages(handlersProperty); } else { return new LinkedList(); } } public static void setHandlerPackages(final List packages) { if (packages == null || packages.size() == 0) { System.getProperties().remove(HANDLER_PACKAGES); } else { String pkgs = StringUtils.join(packages.toArray(), "|"); System.setProperty(HANDLER_PACKAGES, pkgs); } } public static void appendHandlerPackage(final String name) { if (name == null) { throw new NullArgumentException("name"); } List list = getHandlerPackages(); list.add(name); setHandlerPackages(list); } public static void prependHandlerPackage(final String name) { if (name == null) { throw new NullArgumentException("name"); } List list = getHandlerPackages(); list.add(0, name); setHandlerPackages(list); } // URL Stream Handlers // public static Class getURLStreamHandlerType(final String protocol) { if (protocol == null) { throw new NullArgumentException("protocol"); } Iterator iter = getHandlerPackages().iterator(); while (iter.hasNext()) { String pkg = (String)iter.next(); String classname = pkg + "." + protocol + ".Handler"; try { return Classes.loadClass(classname); } catch (ClassNotFoundException e) { ThrowableHandler.add(e); } } return null; } public static URLStreamHandler createURLStreamHandler(final String protocol) { // protocol checked by getURLStreamHandlerType Class type = getURLStreamHandlerType(protocol); if (type != null) { try { Object obj = type.newInstance(); if (obj instanceof URLStreamHandler) { return (URLStreamHandler)obj; } else { // Handler is not instance of URLStreamHandler; ignoring } } catch (Exception e) { ThrowableHandler.add(e); } } return null; } /** * Preload the specific protocol handlers, so that URL knows about * them even if the handler factory is changed. */ public static void preloadURLStreamHandlers(final String[] protocols) { if (protocols == null) { throw new NullArgumentException("protocols"); } for (int i=0; i<protocols.length; i++) { if (protocols[i] == null) { throw new NullArgumentException("protocols", i); } try { URL url = new URL(protocols[i], "", -1, ""); } catch (Exception ignore) {} } } public static void registerURLStreamHandler(final String protocol, final URLStreamHandler handler) { if (protocol == null) { throw new NullArgumentException("protocol"); } if (handler == null) { throw new NullArgumentException("handler"); } // This way is "naughty" but works great Map handlers = (Map)AccessController.doPrivileged( new PrivilegedAction() { public Object run() { try { Field field = URL.class.getDeclaredField("handlers"); field.setAccessible(true); return field.get(null); } catch (Exception e) { log.warn("Failed to access URL 'handlers' field", e); } return null; } } ); if (handlers != null) { handlers.put(protocol, handler); } } }
package com.haulmont.cuba.desktop.gui.components; import com.haulmont.cuba.desktop.gui.data.TableModelAdapter; import com.haulmont.cuba.desktop.sys.vcl.JXTableExt; import com.haulmont.cuba.gui.data.CollectionDatasource; import org.apache.commons.lang.ObjectUtils; import org.jdesktop.swingx.JXTable; import javax.swing.event.ChangeEvent; import javax.swing.table.TableCellEditor; import java.awt.*; /** * @author krivopustov * @version $Id$ */ public class DesktopTable extends DesktopAbstractTable<JXTable> { public DesktopTable() { impl = new JXTableExt() { @Override public void setFont(Font font) { super.setFont(font); applyFont(this, font); } @Override public void editingStopped(ChangeEvent e) { TableCellEditor editor = getCellEditor(); if (editor != null) { Object value = editor.getCellEditorValue(); DesktopTable tableComponent = DesktopTable.this; if (editingColumn >= 0) { Column editColumn = tableComponent.getColumns().get(editingColumn); if (tableComponent.isEditable() && editColumn.isEditable() && !tableModel.isGeneratedColumn(editColumn)) { setValueAt(value, editingRow, editingColumn); } removeEditor(); } } } }; initComponent(); impl.setColumnControlVisible(true); tableSettings = new SwingXTableSettings(impl, columnsOrder); } @Override protected void initTableModel(CollectionDatasource datasource) { tableModel = new TableModelAdapter(datasource, columnsOrder, true); impl.setModel(tableModel); } @Override public void setSortable(boolean sortable) { super.setSortable(sortable); impl.setSortable(sortable); } @Override public void setEditable(boolean editable) { super.setEditable(editable); impl.setEditable(editable); } }
package name.abuchen.portfolio.ui.util; import java.util.Collections; import java.util.List; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import name.abuchen.portfolio.model.Bookmark; import name.abuchen.portfolio.model.Client; import name.abuchen.portfolio.model.ClientSettings; import name.abuchen.portfolio.model.Security; import name.abuchen.portfolio.ui.Messages; import name.abuchen.portfolio.ui.editor.PortfolioPart; import name.abuchen.portfolio.ui.views.settings.SettingsView; public class BookmarkMenu extends MenuManager { private final Security security; private final Client client; private final PortfolioPart editor; public BookmarkMenu(PortfolioPart editor, Security security) { super(Messages.MenuOpenSecurityOnSite); this.security = security; this.editor = editor; this.client = editor.getClient(); addDefaultPages(); } private void addDefaultPages() { for (Bookmark bookmark : client.getSettings().getBookmarks()) { if (bookmark.isSeparator()) { add(new Separator()); } else { add(new SimpleAction(bookmark.getLabel(), a -> DesktopAPI.browse(bookmark.constructURL(client, security)))); } } // check for urls in notes of security add(new Separator()); security.getCustomBookmarks() .forEach(bm -> add(new SimpleAction(bm.getLabel(), a -> DesktopAPI.browse(bm.getPattern())))); add(new Separator()); MenuManager templatesMenu = new MenuManager(Messages.LabelTaxonomyTemplates); add(templatesMenu); List<Bookmark> templates = ClientSettings.getDefaultBookmarks(); Collections.sort(templates, (r, l) -> r.getLabel().compareTo(l.getLabel())); templates.forEach(bookmark -> templatesMenu.add(new SimpleAction(bookmark.getLabel(), a -> DesktopAPI.browse(bookmark.constructURL(client, security))))); add(new Separator()); add(new SimpleAction(Messages.BookmarkMenu_EditBookmarks, a -> editor.activateView(SettingsView.class, Integer.valueOf(0)))); } }
package org.jill.game.level; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.jill.game.gui.menu.ClassicMenu; import org.jill.game.gui.menu.MenuInterface; import org.jill.game.level.cfg.LevelConfiguration; import org.jill.openjill.core.api.message.statusbar.inventory.EnumInventoryObject; import org.jill.openjill.core.api.message.statusbar.inventory.InventoryItemMessage; import org.jill.game.screen.ControlArea; import org.jill.game.screen.InventoryArea; import org.jill.jn.BackgroundLayer; import org.jill.openjill.core.api.entities.BackgroundEntity; import org.jill.openjill.core.api.entities.ObjectEntity; import org.jill.openjill.core.api.jill.JillConst; import org.jill.openjill.core.api.keyboard.KeyboardLayout; import org.jill.openjill.core.api.message.EnumMessageType; import org.simplegame.InterfaceSimpleGameHandleInterface; /** * This class manage all of execution method of game (run, pause, cheat, key, * update background, update object...). * * @author Emeric MARTINEAU */ public abstract class AbstractExecutingStdLevel extends AbstractMenuJillLevel { /** * Number of pressed key to activate cheat code. */ private static final int CHEAT_CODE_NUMBER = 3; /** * Turtle swith. */ protected boolean turtleSwitch = false; /** * Load game. */ protected MenuInterface menuStd; /** * Control area. */ protected ControlArea controlArea; /** * Inventory area. */ protected InventoryArea inventoryArea; /** * Screen to draw. */ protected BufferedImage drawingScreen; /** * G2 for drawing screen. */ protected Graphics2D g2DrawingScreen; /** * Screen rectangle. */ protected Rectangle screenRect; /** * Object rectangle (only for optimization). */ protected Rectangle objRect = new Rectangle(); /** * Player rectangle (only for optimization). */ protected Rectangle playerRect = new Rectangle(); /** * If need update inventory screen. */ protected boolean updateInventoryScreen = false; /** * Keyboard object share between object (include player). */ protected KeyboardLayout keyboardLayout; /** * Object to draw. */ protected List<ObjectEntity> listObjectToDraw = new ArrayList<>(); /** * Cheat count. */ protected int cheatCount; /** * Cheat count for gem. */ protected int gemCheatCount; /** * Cheat for high jump. */ protected int highJumpCheatCount; /** * True if player invicible. */ protected boolean invincibility; /** * False if pause game. */ protected boolean runGame; /** * Current list of oject currently on screen. */ private final List<ObjectEntity> listObjectCurrentlyDisplayedOnScreen = new ArrayList<>(); public AbstractExecutingStdLevel(final LevelConfiguration cfgLevel) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException { super(cfgLevel); constructor(); // To preserve add 2 invincibility after load game for (EnumInventoryObject item : this.inventoryArea.getObjects()) { if (item == EnumInventoryObject.INVINCIBILITY) { this.invincibility = true; } } } /** * Construct this object. */ private void constructor() { keyboardLayout = new KeyboardLayout(); controlArea = new ControlArea(pictureCache, statusBar); inventoryArea = new InventoryArea(pictureCache, statusBar, this.messageDispatcher); inventoryArea.setLevel( this.levelConfiguration.getLevelNumber()); messageDispatcher.addHandler(EnumMessageType.INVENTORY_ITEM, inventoryArea); messageDispatcher.addHandler(EnumMessageType.INVENTORY_LIFE, inventoryArea); messageDispatcher.addHandler(EnumMessageType.INVENTORY_POINT, inventoryArea); messageDispatcher.addHandler(EnumMessageType.INVENTORY_ITEM, controlArea); offsetX = 0; offsetY = 0; drawingScreen = createGameScreen(); g2DrawingScreen = drawingScreen.createGraphics(); messageDispatcher.addHandler(EnumMessageType.INVENTORY_ITEM, this); messageDispatcher.addHandler(EnumMessageType.INVENTORY_LIFE, this); messageDispatcher.addHandler(EnumMessageType.INVENTORY_POINT, this); cheatCount = 0; gemCheatCount = 0; highJumpCheatCount = 0; invincibility = false; runGame = true; // TODO explain why '* 2' ???? screenRect = new Rectangle(0, 0, this.statusBar.getGameAreaConf().getWidth() + JillConst.X_UPDATE_SCREEN_BORDER * 2, this.statusBar.getGameAreaConf().getHeight() + JillConst.Y_UPDATE_SCREEN_BORDER * 2); } /** * Create game screen for draw background and object. * * @return picture */ protected BufferedImage createGameScreen() { return statusBar.createGameScreen(); } /** * Draw control. */ protected final void drawControl() { statusBar.drawControl(controlArea.drawControl()); } /** * Draw inventory & control area. */ protected final void drawInventory() { statusBar.drawInventory(inventoryArea.drawInventory()); statusBar.drawControl(controlArea.drawControl()); updateInventoryScreen = false; } @Override protected void doRun() { if (keyboard.isOtherKey()) { switch (keyboard.consumeOtherKey()) { case 'p' : case 'P' : runGame = !runGame; break; case 'n' : case 'N' : // TODO noise break; case 'q' : case 'Q' : menu.setEnable(true); return; case 's' : case 'S' : saveGame(); break; case 'r' : case 'R' : loadGame(); break; case 't' : case 'T' : controlArea.setTurtleMode(!controlArea.isTurtleMode()); drawControl(); break; case 'x' : case 'X' : if (invincibility) { break; } cheatCount++; if (cheatCount == CHEAT_CODE_NUMBER) { messageDispatcher.sendMessage( EnumMessageType.INVENTORY_ITEM, new InventoryItemMessage( EnumInventoryObject.INVINCIBILITY, true)); messageDispatcher.sendMessage( EnumMessageType.INVENTORY_ITEM, new InventoryItemMessage( EnumInventoryObject.RED_KEY, true)); cheatCount = 0; invincibility = true; } break; case 'g' : case 'G' : gemCheatCount++; if (gemCheatCount == CHEAT_CODE_NUMBER) { messageDispatcher.sendMessage( EnumMessageType.INVENTORY_ITEM, new InventoryItemMessage( EnumInventoryObject.GEM, true)); gemCheatCount = 0; } break; case 'h' : case 'H' : highJumpCheatCount++; if (highJumpCheatCount == CHEAT_CODE_NUMBER) { messageDispatcher.sendMessage( EnumMessageType.INVENTORY_ITEM, new InventoryItemMessage( EnumInventoryObject.HIGH_JUMP, true)); highJumpCheatCount = 0; } break; default: } } if (keyboard.isUp()) { //offsetY += JillConst.BLOCK_SIZE; keyboardLayout.setUp(true); } if (keyboard.isDown()) { //offsetY -= JillConst.BLOCK_SIZE; keyboardLayout.setDown(true); } if (keyboard.isRight()) { //offsetX -= JillConst.BLOCK_SIZE; keyboardLayout.setRight(true); } if (keyboard.isLeft()) { //offsetX += JillConst.BLOCK_SIZE; keyboardLayout.setLeft(true); } if (keyboard.isFire()) { keyboardLayout.setFire(true); } if (keyboard.isJump()) { keyboardLayout.setJump(true); } currentDisplayScreen = statusBar.getStatusBar(); if (runGame) { doRunNext(); } } /** * Run. */ protected void doRunNext() { boolean turtleMode = controlArea.isTurtleMode(); if ((turtleMode && turtleSwitch) || !turtleMode) { // Execute if not in turtle mode or turtle mode and execute cycle if (keyboardLayout.isFire()) { doPlayerFire(); } // Update background updateBackground(); // Draw object list updateObject(); // Move player movePlayer(); if (updateInventoryScreen) { drawInventory(); } // Copy background screen on g2DrawingScreen.drawImage(background, offsetX, offsetY, null); // Draw object drawObject(); // Draw background statusBar.drawGameScreen(drawingScreen); } turtleSwitch = !turtleSwitch; } /** * Draw object if displayed. */ private void updateObject() { int lOffsetX = Math.abs(offsetX); int lOffsetY = Math.abs(offsetY); screenRect.setLocation(lOffsetX - JillConst.X_UPDATE_SCREEN_BORDER, lOffsetY - JillConst.Y_UPDATE_SCREEN_BORDER); // Set player bounds playerRect.setBounds(player.getX(), player.getY(), player.getWidth(), player.getHeight()); // Grap list of object on screen for (ObjectEntity obj : listObject) { objRect.setBounds(obj.getX(), obj.getY(), obj.getWidth(), obj.getHeight()); if (screenRect.intersects(objRect)) { listObjectCurrentlyDisplayedOnScreen.add(obj); } } listObjectCurrentlyDisplayedOnScreen.add(player); int zaphold; // Update and object touch for (ObjectEntity obj1 : listObjectCurrentlyDisplayedOnScreen) { objRect.setBounds(obj1.getX(), obj1.getY(), obj1.getWidth(), obj1.getHeight()); // Decreate touch player flag zaphold = obj1.getZapHold(); if (zaphold > 0) { obj1.setZapHold(zaphold - 1); } obj1.msgUpdate(); listObjectToDraw.add(obj1); for (ObjectEntity obj2 : listObjectCurrentlyDisplayedOnScreen) { playerRect.setBounds(obj2.getX(), obj2.getY(), obj2.getWidth(), obj2.getHeight()); // Check object collision. // Skip if same object // Skip if obj1 is player because, msgKeyboard call after and // if don't skip when object collision state of player update // twice if (obj1 != obj2 && obj1 != player && playerRect.intersects(objRect)) { obj1.msgKeyboard(obj2, keyboardLayout); obj1.msgTouch(obj2); } } } // Reset last object. Check if need redraw inventory for backcolor. this.updateInventoryScreen = this.inventoryArea.isNeedRedraw() || this.updateInventoryScreen; listObjectCurrentlyDisplayedOnScreen.clear(); // Call manually to update player.msgKeyboard(player, keyboardLayout); // Remove object from list for (ObjectEntity obj : listObjectToRemove) { listObject.remove(obj); } listObjectToRemove.clear(); // Add object from list for (ObjectEntity obj : listObjectToAdd) { listObject.add(obj); } listObjectToAdd.clear(); } /** * Update background. */ private void updateBackground() { final int startX = Math.abs(offsetX) / JillConst.BLOCK_SIZE; final int startY = Math.abs(offsetY) / JillConst.BLOCK_SIZE; final int endX = Math.min(startX + screenWidthBlock, BackgroundLayer.MAP_WIDTH); final int endY = Math.min(startY + screenHeightBlock, BackgroundLayer.MAP_HEIGHT); BackgroundEntity back; BufferedImage tilePicture; for (int indexBackX = startX; indexBackX < endX; indexBackX++) { for (int indexBackY = startY; indexBackY < endY; indexBackY++) { back = backgroundObject[indexBackX][indexBackY]; if (back.isMsgUpdate()) { back.msgUpdate(); tilePicture = back.getPicture(); g2Background.drawImage(tilePicture, indexBackX * JillConst.BLOCK_SIZE, indexBackY * JillConst.BLOCK_SIZE, null); } } } } /** * Draw objet always on screen. */ private void drawObject() { for (ObjectEntity currentObject : listObjectAlwaysOnScreen) { g2DrawingScreen.drawImage(currentObject.msgDraw(), currentObject.getX(), currentObject.getY(), null); } for (ObjectEntity currentObject : listObjectToDraw) { g2DrawingScreen.drawImage(currentObject.msgDraw(), currentObject.getX() + offsetX, currentObject.getY() + offsetY, null); } // NOTE : Disable in 0.0.28 cause, new collision method do this //g2DrawingScreen.drawImage(player.msgDraw(), player.getX() + offsetX, // player.getY() + offsetY, null); listObjectToDraw.clear(); } @Override protected void initMenu() { this.menuStd = new ClassicMenu("exit_menu.json", pictureCache); this.menu = menuStd; } @Override protected void menuEntryValidate(final int value) { if (value == 0) { doMenuValidate(); } else { menu.setEnable(false); } } @Override protected void doEscape() { menu.setEnable(true); keyboard.unescape(); } /** * Return start screen class. * * @return class */ protected Class<? extends InterfaceSimpleGameHandleInterface> getStartScreenClass() { return this.levelConfiguration.getStartScreen(); } /** * Move player. */ protected abstract void movePlayer(); @Override public void recieveMessage(final EnumMessageType type, final Object msg) { super.recieveMessage(type, msg); // if (type == EnumMessageType.INVENTORY) { // // Catch call to know if need update inventory screen // // Use boolean to ensure that all add/remove item are passed // updateInventoryScreen = true; } /** * Save current game. */ protected abstract void saveGame(); /** * load new game. */ protected abstract void loadGame(); /** * Call when menu is validate. */ protected void doMenuValidate() { changeScreenManager(getStartScreenClass()); } /** * Player fire. */ protected abstract void doPlayerFire(); }
package org.opennms.netmgt.syslogd; import static org.junit.Assert.assertEquals; import static org.opennms.core.utils.InetAddressUtils.addr; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.UndeclaredThrowableException; import java.net.BindException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.io.IOUtils; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.ValidationException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.opennms.core.concurrent.WaterfallExecutor; import org.opennms.core.spring.BeanUtils; import org.opennms.core.test.ConfigurationTestUtils; import org.opennms.core.test.MockLogAppender; import org.opennms.core.test.OpenNMSJUnit4ClassRunner; import org.opennms.core.test.db.annotations.JUnitTemporaryDatabase; import org.opennms.core.utils.InetAddressUtils; import org.opennms.netmgt.config.SyslogdConfigFactory; import org.opennms.netmgt.config.syslogd.HideMessage; import org.opennms.netmgt.config.syslogd.Match; import org.opennms.netmgt.config.syslogd.UeiList; import org.opennms.netmgt.config.syslogd.UeiMatch; import org.opennms.netmgt.dao.mock.MockEventIpcManager; import org.opennms.netmgt.eventd.Eventd; import org.opennms.netmgt.model.events.EventBuilder; import org.opennms.netmgt.model.events.EventListener; import org.opennms.netmgt.model.events.EventProxy; import org.opennms.netmgt.utils.TcpEventProxy; import org.opennms.netmgt.xml.event.Event; import org.opennms.netmgt.xml.event.Events; import org.opennms.netmgt.xml.event.Log; import org.opennms.test.JUnitConfigurationEnvironment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.transaction.annotation.Transactional; @RunWith(OpenNMSJUnit4ClassRunner.class) @ContextConfiguration(locations={ "classpath:/META-INF/opennms/applicationContext-soa.xml", "classpath:/META-INF/opennms/applicationContext-dao.xml", "classpath:/META-INF/opennms/applicationContext-commonConfigs.xml", "classpath:/META-INF/opennms/applicationContext-daemon.xml", "classpath:/META-INF/opennms/applicationContext-setupIpLike-enabled.xml", "classpath:/META-INF/opennms/mockEventIpcManager.xml", "classpath:/META-INF/opennms/applicationContext-databasePopulator.xml", "classpath:/META-INF/opennms/applicationContext-eventDaemon.xml", "classpath:/syslogdTest.xml", "classpath:/META-INF/opennms/applicationContext-minimal-conf.xml" }) @JUnitConfigurationEnvironment @JUnitTemporaryDatabase public class SyslogdLoadTest implements InitializingBean { private static final Logger LOG = LoggerFactory.getLogger(SyslogdLoadTest.class); private EventCounter m_eventCounter; private static final String MATCH_PATTERN = "^.*\\s(19|20)\\d\\d([-/.])(0[1-9]|1[012])\\2(0[1-9]|[12][0-9]|3[01])(\\s+)(\\S+)(\\s)(\\S.+)"; private static final int HOST_GROUP = 6; private static final int MESSAGE_GROUP = 8; private static final HideMessage HIDE_MESSAGE = new HideMessage(); private static final String DISCARD_UEI = "DISCARD-MATCHING-MESSAGES"; private static final UeiList UEI_LIST = new UeiList(); @Autowired private MockEventIpcManager m_eventIpcManager; @Autowired private Eventd m_eventd; private Syslogd m_syslogd; private final ExecutorService m_executorService = Executors.newCachedThreadPool(); static { UeiMatch ueiMatch; Match match; for (int i = 0; i < 10000; i++) { /* <ueiMatch> * <match type="regex" expression=".*foo0: .*load test (\S+) on ((pts\/\d+)|(tty\d+)).*"/><uei>uei.example.org/syslog/loadTest/foo0</uei> * </ueiMatch> */ ueiMatch = new UeiMatch(); match = new Match(); match.setType("regex"); match.setExpression(String.format(".*foo%d: .*load test (\\S+) on ((pts\\/\\d+)|(tty\\d+)).*", i)); ueiMatch.setMatch(match); ueiMatch.setUei(String.format("uei.example.org/syslog/loadTest/foo%d", i)); UEI_LIST.addUeiMatch(ueiMatch); } } @Override public void afterPropertiesSet() throws Exception { BeanUtils.assertAutowiring(this); } @Before public void setUp() throws Exception { MockLogAppender.setupLogging(true, "WARN"); loadSyslogConfiguration("/etc/syslogd-loadtest-configuration.xml"); m_eventCounter = new EventCounter(); this.m_eventIpcManager.addEventListener(m_eventCounter); } @After public void tearDown() throws Exception { if (m_syslogd != null) { m_syslogd.stop(); } } private void loadSyslogConfiguration(final String configuration) throws IOException, MarshalException, ValidationException { InputStream stream = null; try { stream = ConfigurationTestUtils.getInputStreamForResource(this, configuration); SyslogdConfigFactory cf = new SyslogdConfigFactory(stream); SyslogdConfigFactory.setInstance(cf); } finally { if (stream != null) { IOUtils.closeQuietly(stream); } } } private void startSyslogdGracefully() { ConvertToEvent.invalidate(); try { m_syslogd = new Syslogd(); m_syslogd.init(); m_syslogd.start(); } catch (UndeclaredThrowableException ute) { if (ute.getCause() instanceof BindException) { LOG.warn("received a bind exception", ute); // continue, this was expected } else { throw ute; } } } @Test @Transactional public void testDefaultSyslogd() throws Exception { startSyslogdGracefully(); final int eventCount = 100; List<Integer> foos = new ArrayList<Integer>(); for (int i = 0; i < eventCount; i++) { int eventNum = Double.valueOf(Math.random() * 10000).intValue(); foos.add(eventNum); } m_eventCounter.setAnticipated(eventCount); String testPduFormat = "2010-08-19 localhost foo%d: load test %d on tty1"; SyslogClient sc = new SyslogClient(null, 10, SyslogClient.LOG_USER); final long start = System.currentTimeMillis(); // Test by directly invoking the SyslogConnection task for (int i = 0; i < eventCount; i++) { int foo = foos.get(i); DatagramPacket pkt = sc.getPacket(SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo)); WaterfallExecutor.waterfall(m_executorService, new SyslogConnection(pkt, MATCH_PATTERN, HOST_GROUP, MESSAGE_GROUP, UEI_LIST, HIDE_MESSAGE, DISCARD_UEI)); } /* // Test by sending over a java.net socket final DatagramSocket socket = new DatagramSocket(); for (int i = 0; i < eventCount; i++) { int foo = foos.get(i); DatagramPacket pkt = sc.getPacket(SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo)); socket.send(pkt); } socket.close(); // Test by sending over an NIO channel SocketAddress address = new InetSocketAddress(InetAddressUtils.getLocalHostAddress(), SyslogClient.PORT); final DatagramChannel channel = DatagramChannel.open(); final ByteBuffer buffer = ByteBuffer.allocate(0xffff); buffer.clear(); System.err.println("Starting to send packets"); long startTime = System.currentTimeMillis(); for (int i = 0; i < eventCount; i++) { int foo = foos.get(i); buffer.put(SyslogClient.getPacketPayload(SyslogClient.LOG_USER, null, SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo))); buffer.flip(); channel.send(buffer, address); buffer.clear(); } System.err.println(String.format("Sent %d packets in %d milliseconds", eventCount, System.currentTimeMillis() - startTime)); channel.close(); */ long mid = System.currentTimeMillis(); m_eventCounter.waitForFinish(120000); long end = System.currentTimeMillis(); final long total = (end - start); final double eventsPerSecond = (eventCount * 1000.0 / total); System.err.println(String.format("total time: %d, wait time: %d, events per second: %8.4f", total, (end - mid), eventsPerSecond)); } @Test @Transactional public void testRfcSyslog() throws Exception { loadSyslogConfiguration("/etc/syslogd-rfc-configuration.xml"); startSyslogdGracefully(); m_eventCounter.anticipate(); InetAddress address = InetAddress.getLocalHost(); // handle an invalid packet byte[] bytes = "<34>1 2010-08-19T22:14:15.000Z localhost - - - - BOMfoo0: load test 0 on tty1\0".getBytes(); DatagramPacket pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT); WaterfallExecutor.waterfall(m_executorService, new SyslogConnection(pkt, MATCH_PATTERN, HOST_GROUP, MESSAGE_GROUP, UEI_LIST, HIDE_MESSAGE, DISCARD_UEI)); // handle a valid packet bytes = "<34>1 2003-10-11T22:14:15.000Z plonk -ev/pts/8\0".getBytes(); pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT); WaterfallExecutor.waterfall(m_executorService, new SyslogConnection(pkt, MATCH_PATTERN, HOST_GROUP, MESSAGE_GROUP, UEI_LIST, HIDE_MESSAGE, DISCARD_UEI)); m_eventCounter.waitForFinish(120000); assertEquals(1, m_eventCounter.getCount()); } @Test @Transactional public void testNGSyslog() throws Exception { loadSyslogConfiguration("/etc/syslogd-syslogng-configuration.xml"); startSyslogdGracefully(); m_eventCounter.anticipate(); InetAddress address = InetAddress.getLocalHost(); // handle an invalid packet byte[] bytes = "<34>main: 2010-08-19 localhost foo0: load test 0 on tty1\0".getBytes(); DatagramPacket pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT); WaterfallExecutor.waterfall(m_executorService, new SyslogConnection(pkt, MATCH_PATTERN, HOST_GROUP, MESSAGE_GROUP, UEI_LIST, HIDE_MESSAGE, DISCARD_UEI)); // handle a valid packet bytes = "<34>monkeysatemybrain!\0".getBytes(); pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT); WaterfallExecutor.waterfall(m_executorService, new SyslogConnection(pkt, MATCH_PATTERN, HOST_GROUP, MESSAGE_GROUP, UEI_LIST, HIDE_MESSAGE, DISCARD_UEI)); m_eventCounter.waitForFinish(120000); assertEquals(1, m_eventCounter.getCount()); } @Test @Transactional public void testEventd() throws Exception { m_eventd.start(); EventProxy ep = createEventProxy(); Log eventLog = new Log(); Events events = new Events(); eventLog.setEvents(events); int eventCount = 10000; m_eventCounter.setAnticipated(eventCount); for (int i = 0; i < eventCount; i++) { int eventNum = Double.valueOf(Math.random() * 300).intValue(); String expectedUei = "uei.example.org/syslog/loadTest/foo" + eventNum; final EventBuilder eb = new EventBuilder(expectedUei, "SyslogdLoadTest"); Event thisEvent = eb.setInterface(addr("127.0.0.1")) .setLogDest("logndisplay") .setLogMessage("A load test has been received as a Syslog Message") .getEvent(); // LOG.debug("event = {}", thisEvent); events.addEvent(thisEvent); } long start = System.currentTimeMillis(); ep.send(eventLog); long mid = System.currentTimeMillis(); // wait up to 2 minutes for the events to come through m_eventCounter.waitForFinish(120000); long end = System.currentTimeMillis(); m_eventd.stop(); final long total = (end - start); final double eventsPerSecond = (eventCount * 1000.0 / total); System.err.println(String.format("total time: %d, wait time: %d, events per second: %8.4f", total, (end - mid), eventsPerSecond)); } private static EventProxy createEventProxy() throws UnknownHostException { /* * Rather than defaulting to localhost all the time, give an option in properties */ String proxyHostName = "127.0.0.1"; String proxyHostPort = "5837"; String proxyHostTimeout = String.valueOf(TcpEventProxy.DEFAULT_TIMEOUT); InetAddress proxyAddr = null; EventProxy proxy = null; proxyAddr = InetAddressUtils.addr(proxyHostName); if (proxyAddr == null) { proxy = new TcpEventProxy(); } else { proxy = new TcpEventProxy(new InetSocketAddress(proxyAddr, Integer.parseInt(proxyHostPort)), Integer.parseInt(proxyHostTimeout)); } return proxy; } public static class EventCounter implements EventListener { private AtomicInteger m_eventCount = new AtomicInteger(0); private int m_expectedCount = 0; @Override public String getName() { return "eventCounter"; } // Me love you, long time. public void waitForFinish(final long time) { final long start = System.currentTimeMillis(); while (this.getCount() < m_expectedCount) { if (System.currentTimeMillis() - start > time) { LOG.warn("waitForFinish timeout ({}) reached", time); break; } try { Thread.sleep(50); } catch (final InterruptedException e) { LOG.warn("thread was interrupted while sleeping", e); Thread.currentThread().interrupt(); } } } public void setAnticipated(final int eventCount) { m_expectedCount = eventCount; } public int getCount() { return m_eventCount.get(); } public void anticipate() { m_expectedCount++; } @Override public void onEvent(final Event e) { final int current = m_eventCount.incrementAndGet(); if (current % 100 == 0) { System.err.println(current + " out of " + m_expectedCount + " expected events received"); } } } }