answer
stringlengths
17
10.2M
//The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess. //The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. //Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers). //In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. //Write a function to determine the knight's minimum initial health so that he is able to rescue the princess. //For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN. //-2 (K) -3 3 //-5 -10 1 //10 30 -5 (P) //Notes: //The knight's health has no upper bound. //Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. package org.leituo.leetcode.dpHard; public class DungeonGame { class Solution{ //Think reverse //extra memory to handle HP needed to finish dungeon //loop reversely, last one need 1 HP, //each room choose right or bottom, always choose the easy one(min) //if cur HP needed is <=0, set to 1 public int calculateMinimumHP(int[][] dungeon) { int rowL = dungeon.length; int colL = dungeon[0].length; int[][] hp = new int[rowL+1][colL+1];//min hp need before step on i, j point. for(int i=0; i<=rowL;i++) for(int j=0; j<=colL;j++) hp[i][j] = Integer.MAX_VALUE;//like a wall hp[rowL][colL-1] = 1;//remian at least 1 health hp[rowL-1][colL] = 1; for(int row = rowL-1; row >=0 ; row for(int col = colL-1; col >=0; col int needed = Math.min(hp[row+1][col], hp[row][col+1]) - dungeon[row][col]; hp[row][col] = needed <= 0? 1 : needed; } } return hp[0][0]; } } class SolutionLessRAM { //Same idea, use sliding window to use less memory public int calculateMinimumHP(int[][] dungeon) { if(dungeon == null || dungeon.length < 1 || dungeon[0].length < 1) return 1; int rows = dungeon.length; int cols = dungeon[0].length; int[] data = new int[cols + 1];//extra dummy, for easy if/else handling for(int k = 0; k < cols - 1; k++) data[k] = Integer.MAX_VALUE;//set wall data[cols] = data[cols-1] = 1;//extra dummy for(int i = rows - 1; i >= 0; i for(int j = cols - 1; j >= 0; j int needHP = Math.min(data[j], data[j+1]) - dungeon[i][j];//always choose the easy path data[j] = needHP < 1 ? 1 : needHP; } data[cols] = Integer.MAX_VALUE;//set back wall } return data[0]; } } }
package org.objectweb.asm.tree; import org.objectweb.asm.CodeAdapter; import org.objectweb.asm.Label; import org.objectweb.asm.Attribute; /** * A {@link CodeAdapter CodeAdapter} that constructs a tree representation of * the methods it vists. Each <tt>visit</tt><i>XXX</i> method of this class * constructs an <i>XXX</i><tt>Node</tt> and adds it to the {@link #methodNode * methodNode} node. */ public class TreeCodeAdapter extends CodeAdapter { /** * A tree representation of the method that is being visited by this visitor. */ public MethodNode methodNode; /** * Constructs a new {@link TreeCodeAdapter TreeCodeAdapter} object. * * @param methodNode the method node to be used to store the tree * representation constructed by this code visitor. */ public TreeCodeAdapter (final MethodNode methodNode) { super(null); this.methodNode = methodNode; } public void visitInsn (final int opcode) { AbstractInsnNode n = new InsnNode(opcode); methodNode.instructions.add(n); } public void visitIntInsn (final int opcode, final int operand) { AbstractInsnNode n = new IntInsnNode(opcode, operand); methodNode.instructions.add(n); } public void visitVarInsn (final int opcode, final int var) { AbstractInsnNode n = new VarInsnNode(opcode, var); methodNode.instructions.add(n); } public void visitTypeInsn (final int opcode, final String desc) { AbstractInsnNode n = new TypeInsnNode(opcode, desc); methodNode.instructions.add(n); } public void visitFieldInsn ( final int opcode, final String owner, final String name, final String desc) { AbstractInsnNode n = new FieldInsnNode(opcode, owner, name, desc); methodNode.instructions.add(n); } public void visitMethodInsn ( final int opcode, final String owner, final String name, final String desc) { AbstractInsnNode n = new MethodInsnNode(opcode, owner, name, desc); methodNode.instructions.add(n); } public void visitJumpInsn (final int opcode, final Label label) { AbstractInsnNode n = new JumpInsnNode(opcode, label); methodNode.instructions.add(n); } public void visitLabel (final Label label) { methodNode.instructions.add(label); } public void visitLdcInsn (final Object cst) { AbstractInsnNode n = new LdcInsnNode(cst); methodNode.instructions.add(n); } public void visitIincInsn (final int var, final int increment) { AbstractInsnNode n = new IincInsnNode(var, increment); methodNode.instructions.add(n); } public void visitTableSwitchInsn ( final int min, final int max, final Label dflt, final Label labels[]) { AbstractInsnNode n = new TableSwitchInsnNode(min, max, dflt, labels); methodNode.instructions.add(n); } public void visitLookupSwitchInsn ( final Label dflt, final int keys[], final Label labels[]) { AbstractInsnNode n = new LookupSwitchInsnNode(dflt, keys, labels); methodNode.instructions.add(n); } public void visitMultiANewArrayInsn (final String desc, final int dims) { AbstractInsnNode n = new MultiANewArrayInsnNode(desc, dims); methodNode.instructions.add(n); } public void visitTryCatchBlock ( final Label start, final Label end, final Label handler, final String type) { TryCatchBlockNode n = new TryCatchBlockNode(start, end, handler, type); methodNode.tryCatchBlocks.add(n); } public void visitMaxs (final int maxStack, final int maxLocals) { methodNode.maxStack = maxStack; methodNode.maxLocals = maxLocals; } public void visitLocalVariable ( final String name, final String desc, final Label start, final Label end, final int index) { LocalVariableNode n = new LocalVariableNode(name, desc, start, end, index); methodNode.localVariables.add(n); } public void visitLineNumber (final int line, final Label start) { LineNumberNode n = new LineNumberNode(line, start); methodNode.lineNumbers.add(n); } public void visitAttribute (final Attribute attr) { attr.next = methodNode.codeAttrs; methodNode.codeAttrs = attr; } }
package com.intellij.cvsSupport2.cvsoperations.cvsContent; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NonNls; import java.io.File; import java.util.regex.Pattern; class DirectoryContentListener { private String myModulePath; private final DirectoryContent myDirectoryContent = new DirectoryContent(); @NonNls private static final String FILE_MESSAGE_PREFIX = "fname "; @NonNls private static final String MODULE_MESSAGE_PREFIX = "cvs server: ignoring module "; @NonNls private static final String MODULE_MESSAGE_PREFIX_2 = "cvs server: Updating "; @NonNls private static final Pattern NEW_DIRECTORY_PATTERN = Pattern.compile("cvs .*: New directory.*-- ignored"); private String myModuleName; public void messageSent(String message) { if (directoryMessage(message)) { String directoryName = directoryNameFromMessage(message); if (myModulePath != null) directoryName = myModulePath + "/" + new File(directoryName).getName(); myDirectoryContent.addSubDirectory(directoryName); } else if (fileMessage(message)) { String fileName = fileNameFromMessage(message); if ((myModuleName != null) && StringUtil.startsWithConcatenationOf(fileName, myModuleName, "/")) { fileName = fileName.substring(myModuleName.length() + 1); } int slashPos = fileName.indexOf('/'); if (slashPos > 0) { String directoryName = fileName.substring(0, slashPos); myDirectoryContent.addSubDirectory(directoryName); } else { if (myModulePath != null) fileName = myModulePath + "/" + new File(fileName).getName(); myDirectoryContent.addFile(fileName); } } else if (moduleMessage_ver1(message)) { String moduleName = moduleNameFromMessage_ver1(message); myDirectoryContent.addModule(moduleName); } else if (moduleMessage_ver2(message)) { String moduleName = moduleNameFromMessage_ver2(message); myDirectoryContent.addModule(moduleName); } } private String moduleNameFromMessage_ver2(final String message) { String prefix = updatingModulePrefix2(); return message.substring(prefix.length()); } private static String moduleNameFromMessage_ver1(String message) { return message.substring(MODULE_MESSAGE_PREFIX.length()); } public static boolean moduleMessage_ver1(String message) { return message.startsWith(MODULE_MESSAGE_PREFIX); } public boolean moduleMessage_ver2(String message) { if (myModuleName == null) { return false; } return message.startsWith(updatingModulePrefix2()); } private String updatingModulePrefix2() { return MODULE_MESSAGE_PREFIX_2 + myModuleName + "/"; } public static String fileNameFromMessage(String message) { return message.substring(FILE_MESSAGE_PREFIX.length()); } public void setModulePath(String modulePath) { myModulePath = modulePath; } public static boolean fileMessage(String message) { return message.startsWith(FILE_MESSAGE_PREFIX); } public static boolean directoryMessage(String message) { return NEW_DIRECTORY_PATTERN.matcher(message).matches(); } public static String directoryNameFromMessage(String message) { byte directoryNameBeginMarker = '`'; byte directoryNameendMarker = '\''; int beginIndex = message.indexOf(directoryNameBeginMarker) + 1; int endIndex = message.indexOf(directoryNameendMarker); return message.substring(beginIndex, endIndex); } public DirectoryContent getDirectoryContent() { return myDirectoryContent; } //public void addModule(String name) { // myDirectoryContent.addModule(name); public void setModuleName(final String moduleLocation) { myModuleName = moduleLocation; } }
package org.sugr.gearshift; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Locale; import org.sugr.gearshift.G.FilterBy; import org.sugr.gearshift.G.SortBy; import org.sugr.gearshift.G.SortOrder; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.FragmentManager; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.Loader; import android.text.Html; import android.text.Spanned; import android.util.SparseBooleanArray; import android.view.ActionMode; 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.widget.AbsListView.MultiChoiceModeListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.Filter; import android.widget.Filter.FilterListener; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; /** * A list fragment representing a list of Torrents. This fragment * also supports tablet devices by allowing list items to be given an * 'activated' state upon selection. This helps indicate which item is * currently being viewed in a {@link TorrentDetailFragment}. * <p> * Activities containing this fragment MUST implement the {@link Callbacks} * interface. */ public class TorrentListFragment extends ListFragment { /** * The serialization (saved instance state) Bundle key representing the * activated item position. Only used on tablets. */ private static final String STATE_ACTIVATED_POSITION = "activated_position"; /** * The fragment's current callback object, which is notified of list item * clicks. */ private Callbacks mCallbacks = sDummyCallbacks; /** * The current activated item position. Only used on tablets. */ private int mActivatedPosition = ListView.INVALID_POSITION; private boolean mAltSpeed = false; private boolean mRefreshing = true; private ActionMode mActionMode; private int mChoiceMode = ListView.CHOICE_MODE_NONE; private TransmissionProfileListAdapter mProfileAdapter; private TorrentListAdapter mTorrentListAdapter; private TransmissionProfile mCurrentProfile; private TransmissionSession mSession; // private TransmissionSessionStats mSessionStats; private boolean mScrollToTop = false; /** * A callback interface that all activities containing this fragment must * implement. This mechanism allows activities to be notified of item * selections. */ public interface Callbacks { /** * Callback for when an item has been selected. */ public void onItemSelected(Torrent torrent); } /** * A dummy implementation of the {@link Callbacks} interface that does * nothing. Used only when this fragment is not attached to an activity. */ private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onItemSelected(Torrent torrent) { } }; private LoaderCallbacks<TransmissionProfile[]> mProfileLoaderCallbacks = new LoaderCallbacks<TransmissionProfile[]>() { @Override public android.support.v4.content.Loader<TransmissionProfile[]> onCreateLoader( int id, Bundle args) { return new TransmissionProfileSupportLoader(getActivity()); } @Override public void onLoadFinished( android.support.v4.content.Loader<TransmissionProfile[]> loader, TransmissionProfile[] profiles) { mCurrentProfile = null; mProfileAdapter.clear(); if (profiles.length > 0) { mProfileAdapter.addAll(profiles); } else { mProfileAdapter.add(TransmissionProfileListAdapter.EMPTY_PROFILE); setEmptyText(R.string.no_profiles_empty_list); mRefreshing = false; getActivity().invalidateOptionsMenu(); } String currentId = TransmissionProfile.getCurrentProfileId(getActivity()); int index = 0; for (TransmissionProfile prof : profiles) { if (prof.getId().equals(currentId)) { ActionBar actionBar = getActivity().getActionBar(); if (actionBar != null) actionBar.setSelectedNavigationItem(index); mCurrentProfile = prof; break; } index++; } if (mCurrentProfile == null && profiles.length > 0) { mCurrentProfile = profiles[0]; } ((TransmissionSessionInterface) getActivity()).setProfile(mCurrentProfile); if (mCurrentProfile == null) { getActivity().getSupportLoaderManager().destroyLoader(G.TORRENTS_LOADER_ID); } else { getActivity().getSupportLoaderManager().restartLoader(G.TORRENTS_LOADER_ID, null, mTorrentLoaderCallbacks); } } @Override public void onLoaderReset( android.support.v4.content.Loader<TransmissionProfile[]> loader) { mProfileAdapter.clear(); } }; private LoaderCallbacks<TransmissionData> mTorrentLoaderCallbacks = new LoaderCallbacks<TransmissionData>() { @Override public android.support.v4.content.Loader<TransmissionData> onCreateLoader( int id, Bundle args) { G.logD("Starting the torrents loader with profile " + mCurrentProfile); if (mCurrentProfile == null) return null; TransmissionDataLoader loader = new TransmissionDataLoader(getActivity(), mCurrentProfile); return loader; } @Override public void onLoadFinished( android.support.v4.content.Loader<TransmissionData> loader, TransmissionData data) { boolean invalidateMenu = false; G.logD("Data loaded: " + data.torrents.size() + " torrents, error: " + data.error + " , removed: " + data.hasRemoved + ", added: " + data.hasAdded + ", changed: " + data.hasStatusChanged + ", metadata: " + data.hasMetadataNeeded); mSession = data.session; ((TransmissionSessionInterface) getActivity()).setSession(data.session); /* if (data.stats != null) mSessionStats = data.stats;*/ if (mSession != null && mAltSpeed != mSession.isAltSpeedLimitEnabled()) { mAltSpeed = mSession.isAltSpeedLimitEnabled(); invalidateMenu = true; } boolean filtered = false; View error = getView().findViewById(R.id.fatal_error_layer); if (data.error == 0 && error.getVisibility() != View.GONE) { error.setVisibility(View.GONE); ((TransmissionSessionInterface) getActivity()).setProfile(mCurrentProfile); } if (data.torrents.size() > 0 || data.error > 0 || mTorrentListAdapter.getUnfilteredCount() > 0) { /* The notifyDataSetChanged method sets this to true */ mTorrentListAdapter.setNotifyOnChange(false); boolean notifyChange = true; if (data.error == 0) { if (data.hasRemoved || data.hasAdded || data.hasStatusChanged || data.hasMetadataNeeded || mTorrentListAdapter.getUnfilteredCount() == 0) { notifyChange = false; if (data.hasRemoved || data.hasAdded) { ((TransmissionSessionInterface) getActivity()).setTorrents(data.torrents); } mTorrentListAdapter.clear(); mTorrentListAdapter.addAll(data.torrents); mTorrentListAdapter.repeatFilter(); filtered = true; } } else { if (data.error == TransmissionData.Errors.DUPLICATE_TORRENT) { Toast.makeText(getActivity(), R.string.duplicate_torrent, Toast.LENGTH_SHORT).show(); } else if (data.error == TransmissionData.Errors.INVALID_TORRENT) { Toast.makeText(getActivity(), R.string.invalid_torrent, Toast.LENGTH_SHORT).show(); } else { error.setVisibility(View.VISIBLE); TextView text = (TextView) getView().findViewById(R.id.transmission_error); ((TransmissionSessionInterface) getActivity()).setProfile(null); if (data.error == TransmissionData.Errors.NO_CONNECTIVITY) { text.setText(Html.fromHtml(getString(R.string.no_connectivity_empty_list))); } else if (data.error == TransmissionData.Errors.ACCESS_DENIED) { text.setText(Html.fromHtml(getString(R.string.access_denied_empty_list))); } else if (data.error == TransmissionData.Errors.NO_JSON) { text.setText(Html.fromHtml(getString(R.string.no_json_empty_list))); } else if (data.error == TransmissionData.Errors.NO_CONNECTION) { text.setText(Html.fromHtml(getString(R.string.no_connection_empty_list))); } else if (data.error == TransmissionData.Errors.THREAD_ERROR) { text.setText(Html.fromHtml(getString(R.string.thread_error_empty_list))); } else if (data.error == TransmissionData.Errors.RESPONSE_ERROR) { text.setText(Html.fromHtml(getString(R.string.response_error_empty_list))); } else if (data.error == TransmissionData.Errors.TIMEOUT) { text.setText(Html.fromHtml(getString(R.string.timeout_empty_list))); } } } if (data.torrents.size() > 0) { if (notifyChange) { mTorrentListAdapter.notifyDataSetChanged(); } } else { mTorrentListAdapter.notifyDataSetInvalidated(); } if (data.error == 0) { FragmentManager manager = getActivity().getSupportFragmentManager(); TorrentListMenuFragment menu = (TorrentListMenuFragment) manager.findFragmentById(R.id.torrent_list_menu); if (menu != null) { menu.notifyTorrentListUpdate(data.torrents, data.session); } if (!filtered) { TorrentDetailFragment detail = (TorrentDetailFragment) manager.findFragmentByTag( TorrentDetailFragment.TAG); if (detail != null) { detail.notifyTorrentListChanged(data.hasRemoved, data.hasAdded, data.hasStatusChanged); if (data.hasStatusChanged) { invalidateMenu = true; } } } } } if (mRefreshing) { mRefreshing = false; invalidateMenu = true; } if (invalidateMenu) getActivity().invalidateOptionsMenu(); } @Override public void onLoaderReset( android.support.v4.content.Loader<TransmissionData> loader) { mTorrentListAdapter.clear(); } }; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public TorrentListFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); getActivity().setProgressBarIndeterminateVisibility(true); ActionBar actionBar = getActivity().getActionBar(); if (actionBar != null) { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); mProfileAdapter = new TransmissionProfileListAdapter(getActivity()); actionBar.setListNavigationCallbacks(mProfileAdapter, new ActionBar.OnNavigationListener() { @Override public boolean onNavigationItemSelected(int pos, long id) { TransmissionProfile profile = mProfileAdapter.getItem(pos); if (profile != TransmissionProfileListAdapter.EMPTY_PROFILE) { final Loader<TransmissionData> loader = getActivity().getSupportLoaderManager() .getLoader(G.TORRENTS_LOADER_ID); mCurrentProfile = profile; TransmissionProfile.setCurrentProfile(profile, getActivity()); ((TransmissionSessionInterface) getActivity()).setProfile(profile); ((TransmissionDataLoader) loader).setProfile(profile); mRefreshing = true; getActivity().invalidateOptionsMenu(); } return false; } }); actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE); } getActivity().getSupportLoaderManager().initLoader(G.PROFILES_LOADER_ID, null, mProfileLoaderCallbacks); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Restore the previously serialized activated item position. if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) { setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION)); } mTorrentListAdapter = new TorrentListAdapter(getActivity()); // SwingLeftInAnimationAdapter wrapperAdapter = new SwingLeftInAnimationAdapter(mTorrentListAdapter); // wrapperAdapter.setListView(getListView()); // setListAdapter(wrapperAdapter); setListAdapter(mTorrentListAdapter); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); final ListView list = getListView(); list.setChoiceMode(mChoiceMode); list.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (!((TorrentListActivity) getActivity()).isDetailPanelShown()) { list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); setActivatedPosition(position); return true; } return false; }}); list.setMultiChoiceModeListener(new MultiChoiceModeListener() { private HashSet<Integer> mSelectedTorrentIds; @Override public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) { final Loader<TransmissionData> loader = getActivity().getSupportLoaderManager() .getLoader(G.TORRENTS_LOADER_ID); if (loader == null) return false; final int[] ids = new int[mSelectedTorrentIds.size()]; int index = 0; for (Integer id : mSelectedTorrentIds) ids[index++] = id; AlertDialog.Builder builder; switch (item.getItemId()) { case R.id.select_all: ListView v = getListView(); for (int i = 0; i < mTorrentListAdapter.getCount(); i++) { if (!v.isItemChecked(i)) { v.setItemChecked(i, true); } } return true; case R.id.remove: case R.id.delete: builder = new AlertDialog.Builder(getActivity()) .setCancelable(false) .setNegativeButton(android.R.string.no, null); builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { ((TransmissionDataLoader) loader).setTorrentsRemove(ids, item.getItemId() == R.id.delete); mRefreshing = true; getActivity().invalidateOptionsMenu(); mode.finish(); } }) .setMessage(item.getItemId() == R.id.delete ? R.string.delete_selected_confirmation : R.string.remove_selected_confirmation) .show(); return true; case R.id.resume: ((TransmissionDataLoader) loader).setTorrentsAction("torrent-start", ids); break; case R.id.pause: ((TransmissionDataLoader) loader).setTorrentsAction("torrent-stop", ids); break; case R.id.move: LayoutInflater inflater = getActivity().getLayoutInflater(); builder = new AlertDialog.Builder(getActivity()) .setTitle(R.string.set_location) .setCancelable(false) .setNegativeButton(android.R.string.no, null) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Spinner location = (Spinner) ((AlertDialog) dialog).findViewById(R.id.location_choice); CheckBox move = (CheckBox) ((AlertDialog) dialog).findViewById(R.id.move); String dir = (String) location.getSelectedItem(); ((TransmissionDataLoader) loader).setTorrentsLocation( ids, dir, move.isChecked()); mRefreshing = true; getActivity().invalidateOptionsMenu(); mode.finish(); } }).setView(inflater.inflate(R.layout.torrent_location_dialog, null)); AlertDialog dialog = builder.create(); dialog.show(); Spinner location; TransmissionProfileDirectoryAdapter adapter = new TransmissionProfileDirectoryAdapter( getActivity(), android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); adapter.addAll(mSession.getDownloadDirectories()); adapter.sort(); location = (Spinner) dialog.findViewById(R.id.location_choice); location.setAdapter(adapter); return true; case R.id.verify: ((TransmissionDataLoader) loader).setTorrentsAction("torrent-verify", ids); break; case R.id.reannounce: ((TransmissionDataLoader) loader).setTorrentsAction("torrent-reannounce", ids); break; default: return true; } mRefreshing = true; getActivity().invalidateOptionsMenu(); mode.finish(); return true; } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.torrent_list_multiselect, menu); mSelectedTorrentIds = new HashSet<Integer>(); mActionMode = mode; return true; } @Override public void onDestroyActionMode(ActionMode mode) { G.logD("Destroying context menu"); mActionMode = null; mSelectedTorrentIds = null; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { if (checked) mSelectedTorrentIds.add(mTorrentListAdapter.getItem(position).getId()); else mSelectedTorrentIds.remove(mTorrentListAdapter.getItem(position).getId()); ArrayList<Torrent> torrents = ((TransmissionSessionInterface) getActivity()).getTorrents(); boolean hasPaused = false; boolean hasRunning = false; for (Torrent t : torrents) { if (mSelectedTorrentIds.contains(t.getId())) { if (t.getStatus() == Torrent.Status.STOPPED) { hasPaused = true; } else { hasRunning = true; } } } Menu menu = mode.getMenu(); MenuItem item = menu.findItem(R.id.resume); item.setVisible(hasPaused).setEnabled(hasPaused); item = menu.findItem(R.id.pause); item.setVisible(hasRunning).setEnabled(hasRunning); }}); } @Override public void onAttach(Activity activity) { super.onAttach(activity); // Activities containing this fragment must implement its callbacks. if (!(activity instanceof Callbacks)) { throw new IllegalStateException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); // Reset the active callbacks interface to the dummy implementation. mCallbacks = sDummyCallbacks; } @Override public void onListItemClick(ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); if (mActionMode == null) listView.setChoiceMode(mChoiceMode); // Notify the active callbacks interface (the activity, if the // fragment is attached to one) that an item has been selected. mCallbacks.onItemSelected(mTorrentListAdapter.getItem(position)); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mActivatedPosition != ListView.INVALID_POSITION) { // Serialize and persist the activated item position. outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_torrent_list, container, false); return rootView; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.torrent_list_options, menu); MenuItem item = menu.findItem(R.id.menu_refresh); if (mRefreshing) item.setActionView(R.layout.action_progress_bar); else item.setActionView(null); item = menu.findItem(R.id.menu_alt_speed); if (mSession == null) { item.setVisible(false); } else { item.setVisible(true); if (mAltSpeed) { item.setIcon(R.drawable.ic_menu_alt_speed_on); item.setTitle(R.string.alt_speed_label_off); } else { item.setIcon(R.drawable.ic_menu_alt_speed_off); item.setTitle(R.string.alt_speed_label_on); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { Loader<TransmissionData> loader; switch (item.getItemId()) { case R.id.menu_alt_speed: loader = getActivity().getSupportLoaderManager() .getLoader(G.TORRENTS_LOADER_ID); if (loader != null) { mAltSpeed = !mAltSpeed; mSession.setAltSpeedLimitEnabled(mAltSpeed); ((TransmissionDataLoader) loader).setSession(mSession, "alt-speed-enabled"); getActivity().invalidateOptionsMenu(); } return true; case R.id.menu_refresh: loader = getActivity().getSupportLoaderManager() .getLoader(G.TORRENTS_LOADER_ID); if (loader != null) { loader.onContentChanged(); mRefreshing = !mRefreshing; getActivity().invalidateOptionsMenu(); } return true; default: return super.onOptionsItemSelected(item); } } public void setEmptyText(int stringId) { Spanned text = Html.fromHtml(getString(stringId)); ((TextView) getListView().getEmptyView()).setText(text); } public void setEmptyText(String text) { ((TextView) getListView().getEmptyView()).setText(text); } /** * Turns on activate-on-click mode. When this mode is on, list items will be * given the 'activated' state when touched. */ public void setActivateOnItemClick(boolean activateOnItemClick) { // When setting CHOICE_MODE_SINGLE, ListView will automatically // give items the 'activated' state when touched. mChoiceMode = activateOnItemClick ? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_NONE; getListView().setChoiceMode(mChoiceMode); } public void setListFilter(FilterBy e) { mTorrentListAdapter.filter(e); mScrollToTop = true; } public void setListFilter(SortBy e) { mTorrentListAdapter.filter(e); mScrollToTop = true; } public void setListFilter(SortOrder e) { mTorrentListAdapter.filter(e); mScrollToTop = true; } public void setListDirectoryFilter(String e) { mTorrentListAdapter.filterDirectory(e); mScrollToTop = true; } public void setRefreshing(boolean refreshing) { mRefreshing = refreshing; getActivity().invalidateOptionsMenu(); } private void setActivatedPosition(int position) { if (position == ListView.INVALID_POSITION) { getListView().setItemChecked(mActivatedPosition, false); } else { getListView().setItemChecked(position, true); } mActivatedPosition = position; } private static class TransmissionProfileListAdapter extends ArrayAdapter<TransmissionProfile> { public static final TransmissionProfile EMPTY_PROFILE = new TransmissionProfile(); public TransmissionProfileListAdapter(Context context) { super(context, 0); add(EMPTY_PROFILE); } @Override public View getView(int position, View convertView, ViewGroup parent) { View rowView = convertView; TransmissionProfile profile = getItem(position); if (rowView == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = vi.inflate(R.layout.torrent_profile_selector, null); } TextView name = (TextView) rowView.findViewById(R.id.name); TextView summary = (TextView) rowView.findViewById(R.id.summary); if (profile == EMPTY_PROFILE) { name.setText(R.string.no_profiles); if (summary != null) summary.setText(R.string.create_profile_in_settings); } else { name.setText(profile.getName()); if (summary != null) summary.setText((profile.getUsername().length() > 0 ? profile.getUsername() + "@" : "") + profile.getHost() + ":" + profile.getPort()); } return rowView; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View rowView = convertView; if (rowView == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = vi.inflate(R.layout.torrent_profile_selector_dropdown, null); } return getView(position, rowView, parent); } } private class TorrentListAdapter extends ArrayAdapter<Torrent> { private final Object mLock = new Object(); private ArrayList<Torrent> mObjects = new ArrayList<Torrent>(); private ArrayList<Torrent> mOriginalValues; private TorrentFilter mFilter; private CharSequence mCurrentConstraint; private FilterListener mCurrentFilterListener; private TorrentComparator mTorrentComparator = new TorrentComparator(); private FilterBy mFilterBy = FilterBy.ALL; private SortBy mSortBy = mTorrentComparator.getSortBy(); private SortBy mBaseSort = mTorrentComparator.getBaseSort(); private SortOrder mSortOrder = mTorrentComparator.getSortOrder(); private String mDirectory; private SparseBooleanArray mTorrentAdded = new SparseBooleanArray(); private SharedPreferences mSharedPrefs; public TorrentListAdapter(Context context) { super(context, R.layout.torrent_list_item, R.id.name); mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); if (mSharedPrefs.contains(G.PREF_LIST_SEARCH)) { mCurrentConstraint = mSharedPrefs.getString( G.PREF_LIST_SEARCH, null); } if (mSharedPrefs.contains(G.PREF_LIST_FILTER)) { try { mFilterBy = FilterBy.valueOf( mSharedPrefs.getString(G.PREF_LIST_FILTER, "") ); } catch (Exception e) { mFilterBy = FilterBy.ALL; } } if (mSharedPrefs.contains(G.PREF_LIST_DIRECTORY)) { mDirectory = mSharedPrefs.getString(G.PREF_LIST_DIRECTORY, null); } if (mSharedPrefs.contains(G.PREF_LIST_SORT_BY)) { try { mSortBy = SortBy.valueOf( mSharedPrefs.getString(G.PREF_LIST_SORT_BY, "") ); } catch (Exception e) { mSortBy = mTorrentComparator.getSortBy(); } } if (mSharedPrefs.contains(G.PREF_BASE_SORT)) { try { mBaseSort = SortBy.valueOf( mSharedPrefs.getString(G.PREF_BASE_SORT, "") ); } catch (Exception e) { mBaseSort = mTorrentComparator.getBaseSort(); } } if (mSharedPrefs.contains(G.PREF_LIST_SORT_ORDER)) { try { mSortOrder = SortOrder.valueOf( mSharedPrefs.getString(G.PREF_LIST_SORT_ORDER, "") ); } catch (Exception e) { mSortOrder = mTorrentComparator.getSortOrder(); } } mTorrentComparator.setSortingMethod(mSortBy, mSortOrder); mTorrentComparator.setBaseSort(mBaseSort); } @Override public View getView(int position, View convertView, ViewGroup parent) { View rowView = convertView; Torrent torrent = getItem(position); if (rowView == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = vi.inflate(R.layout.torrent_list_item, parent, false); } TextView name = (TextView) rowView.findViewById(R.id.name); TextView traffic = (TextView) rowView.findViewById(R.id.traffic); ProgressBar progress = (ProgressBar) rowView.findViewById(R.id.progress); TextView status = (TextView) rowView.findViewById(R.id.status); name.setText(torrent.getName()); if (torrent.getMetadataPercentComplete() < 1) { progress.setSecondaryProgress((int) (torrent.getMetadataPercentComplete() * 100)); progress.setProgress(0); } else if (torrent.getPercentDone() < 1) { progress.setSecondaryProgress((int) (torrent.getPercentDone() * 100)); progress.setProgress(0); } else { progress.setSecondaryProgress(100); float limit = torrent.getActiveSeedRatioLimit(); float current = torrent.getUploadRatio(); if (limit == -1) { progress.setProgress(100); } else { if (current >= limit) { progress.setProgress(100); } else { progress.setProgress((int) (current / limit * 100)); } } } traffic.setText(torrent.getTrafficText()); status.setText(torrent.getStatusText()); boolean enabled = true; switch(torrent.getStatus()) { case Torrent.Status.STOPPED: case Torrent.Status.CHECK_WAITING: case Torrent.Status.DOWNLOAD_WAITING: case Torrent.Status.SEED_WAITING: enabled = false; break; default: enabled = true; break; } name.setEnabled(enabled); traffic.setEnabled(enabled); status.setEnabled(enabled); if (!mTorrentAdded.get(torrent.getId(), false)) { rowView.setTranslationY(100); rowView.setAlpha((float) 0.3); rowView.setRotationX(10); rowView.animate().setDuration(300).translationY(0).alpha(1).rotationX(0).start(); mTorrentAdded.append(torrent.getId(), true); } return rowView; } @Override public void addAll(Collection<? extends Torrent> collection) { synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues.addAll(collection); } else { mObjects.addAll(collection); } super.addAll(collection); } } @Override public void clear() { synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues = null; } if (mObjects != null) { mObjects.clear(); } super.clear(); } } @Override public int getCount() { synchronized(mLock) { return mObjects == null ? 0 : mObjects.size(); } } public int getUnfilteredCount() { synchronized(mLock) { if (mOriginalValues != null) { return mOriginalValues.size(); } else { return mObjects.size(); } } } @Override public Torrent getItem(int position) { return mObjects.get(position); } @Override public int getPosition(Torrent item) { return mObjects.indexOf(item); } @Override public Filter getFilter() { if (mFilter == null) mFilter = new TorrentFilter(); return mFilter; } /* public void filter(CharSequence constraint, FilterListener listener) { String prefix = constraint.toString().toLowerCase(Locale.getDefault()); Editor e = mSharedPrefs.edit(); mCurrentConstraint = constraint; e.putString(G.PREF_LIST_SEARCH, prefix); e.apply(); mCurrentFilterListener = listener; getFilter().filter(mCurrentConstraint, listener); mTorrentAdded = new SparseBooleanArray(); } */ public void filter(FilterBy by) { mFilterBy = by; applyFilter(by.name(), G.PREF_LIST_FILTER); } public void filter(SortBy by) { mSortBy = by; applyFilter(by.name(), G.PREF_LIST_SORT_BY); } public void filter(SortOrder order) { mSortOrder = order; applyFilter(order.name(), G.PREF_LIST_SORT_ORDER); } public void filterDirectory(String directory) { mDirectory = directory; applyFilter(directory, G.PREF_LIST_DIRECTORY); } public void repeatFilter() { if (mCurrentProfile != null) { getFilter().filter(mCurrentConstraint, mCurrentFilterListener); } } private void applyFilter(String value, String pref) { Editor e = mSharedPrefs.edit(); e.putString(pref, value); e.apply(); mTorrentComparator.setSortingMethod(mSortBy, mSortOrder); repeatFilter(); mTorrentAdded = new SparseBooleanArray(); } private class TorrentFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence prefix) { FilterResults results = new FilterResults(); ArrayList<Torrent> resultList; if (mOriginalValues == null) { synchronized (mLock) { mOriginalValues = new ArrayList<Torrent>(mObjects); } } if (prefix == null) { prefix = ""; } if (prefix.length() == 0 && mFilterBy == FilterBy.ALL && mDirectory == null) { ArrayList<Torrent> list; synchronized (mLock) { list = new ArrayList<Torrent>(mOriginalValues); } resultList = list; } else { ArrayList<Torrent> values; synchronized (mLock) { values = new ArrayList<Torrent>(mOriginalValues); } final int count = values.size(); final ArrayList<Torrent> newValues = new ArrayList<Torrent>(); String prefixString = prefix.toString().toLowerCase(Locale.getDefault()); for (int i = 0; i < count; i++) { final Torrent torrent = values.get(i); if (mFilterBy == FilterBy.DOWNLOADING) { if (torrent.getStatus() != Torrent.Status.DOWNLOADING) continue; } else if (mFilterBy == FilterBy.SEEDING) { if (torrent.getStatus() != Torrent.Status.SEEDING) continue; } else if (mFilterBy == FilterBy.PAUSED) { if (torrent.getStatus() != Torrent.Status.STOPPED) continue; } else if (mFilterBy == FilterBy.COMPLETE) { if (torrent.getPercentDone() != 1) continue; } else if (mFilterBy == FilterBy.INCOMPLETE) { if (torrent.getPercentDone() >= 1) continue; } else if (mFilterBy == FilterBy.ACTIVE) { if (torrent.isStalled() || torrent.isFinished() || ( torrent.getStatus() != Torrent.Status.DOWNLOADING && torrent.getStatus() != Torrent.Status.SEEDING )) continue; } else if (mFilterBy == FilterBy.CHECKING) { if (torrent.getStatus() != Torrent.Status.CHECKING) continue; } if (mDirectory != null) { if (torrent.getDownloadDir() == null || !torrent.getDownloadDir().equals(mDirectory)) continue; } if (prefix.length() == 0) { newValues.add(torrent); } else if (prefix.length() > 0) { final String valueText = torrent.getName().toLowerCase(Locale.getDefault()); if (valueText.startsWith(prefixString)) { newValues.add(torrent); } else { final String[] words = valueText.split(" "); final int wordCount = words.length; // Start at index 0, in case valueText starts with space(s) for (int k = 0; k < wordCount; k++) { if (words[k].startsWith(prefixString)) { newValues.add(torrent); break; } } } } } resultList = newValues; } Collections.sort(resultList, mTorrentComparator); results.values = resultList; results.count = resultList.size(); return results; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, FilterResults results) { mObjects = (ArrayList<Torrent>) results.values; TransmissionSessionInterface context = (TransmissionSessionInterface) getActivity(); if (context == null) { return; } if (results.count > 0) { context.setTorrents((ArrayList<Torrent>) results.values); FragmentManager manager = getActivity().getSupportFragmentManager(); TorrentDetailFragment detail = (TorrentDetailFragment) manager.findFragmentByTag( TorrentDetailFragment.TAG); if (detail != null) { detail.notifyTorrentListChanged(true, true, false); } notifyDataSetChanged(); } else { if (mTorrentListAdapter.getUnfilteredCount() == 0) { setEmptyText(R.string.no_torrents_empty_list); } else if (mTorrentListAdapter.getCount() == 0) { ((TransmissionSessionInterface) getActivity()) .setTorrents(null); setEmptyText(R.string.no_filtered_torrents_empty_list); } notifyDataSetInvalidated(); } if (mScrollToTop) getListView().setSelectionAfterHeaderView(); } } } }
package org.jboss.reddeer.requirements.jre; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * Class contains JRE configuration used by JRE requirement * that is configurable from outside via Requirement feature. * */ @XmlRootElement(name = "jre-requirement", namespace = "http: public class JREConfiguration { private String name; private String path; private double version; /** * Gets name of this requirement to be used in eclipse. * @return JRE name */ public String getName() { return name; } /** * Gets path of where the JRE is installed . * @return path to JRE */ public String getPath() { return path; } /** * Gets version of JRE. * * @return the version */ public double getVersion() { return version; } private static String safeProperty(String s) { if (s != null && s.startsWith("${") && s.endsWith("}")) { String key = s.substring(2, s.length() - 1); String v = System.getProperty(key); if (v != null) { return v; } } return s; } /** * Sets name of this JRE used in eclipse. * @param name Name of this JRE. */ @XmlElement(namespace = "http: public void setName(String name) { this.name = safeProperty(name); } /** * Sets path to JRE. * @param path Path to JRE. */ @XmlElement(namespace = "http: public void setPath(String path) { this.path = safeProperty(path); } /** * Sets version of JRE. * @param version Version of JRE. */ @XmlElement(namespace = "http: public void setVersion(double version) { this.version = version; } }
package ibis.satin.impl.rewriter; import ibis.compile.util.BT_Analyzer; import java.util.ArrayList; import java.util.HashMap; import java.util.Vector; import org.apache.bcel.Repository; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.LocalVariable; import org.apache.bcel.classfile.LocalVariableTable; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.ATHROW; import org.apache.bcel.generic.BranchInstruction; import org.apache.bcel.generic.ClassGen; import org.apache.bcel.generic.CodeExceptionGen; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.INVOKEVIRTUAL; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InstructionList; import org.apache.bcel.generic.LocalVariableGen; import org.apache.bcel.generic.LocalVariableInstruction; import org.apache.bcel.generic.MethodGen; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.ReturnInstruction; import org.apache.bcel.generic.Type; final class MethodTable { static class SpawnTableEntry { ArrayList<CodeExceptionGen> catchBlocks; /* indexed on spawnId */ boolean hasInlet; boolean[] isLocalUsed; SpawnTableEntry() { // do nothing } boolean[] analyseUsedLocals(MethodGen mg, CodeExceptionGen catchBlock, boolean verbose) { int maxLocals = mg.getMaxLocals(); InstructionHandle end = getEndOfCatchBlock(mg, catchBlock); // Start with all false. boolean[] used = new boolean[maxLocals]; if (verbose) { System.out.println("analysing used locals for " + mg + ", maxLocals = " + maxLocals); } if (end == null) { if (verbose) { System.out.println("finally clause; assuming all locals " + "are used"); } for (int j = 0; j < maxLocals; j++) { used[j] = true; } return used; } Instruction endIns = end.getInstruction(); if (!(endIns instanceof ReturnInstruction) && !(endIns instanceof ATHROW)) { if (verbose) { System.out.println("no return at end of inlet, assuming " + "all locals are used"); } // They are all used. for (int j = 0; j < maxLocals; j++) { used[j] = true; } return used; } for (InstructionHandle i = catchBlock.getHandlerPC(); i != end && i != null; i = i.getNext()) { Instruction curr = i.getInstruction(); if (verbose) { System.out.println("ins: " + curr); } if (curr instanceof BranchInstruction) { InstructionHandle dest = ((BranchInstruction) curr) .getTarget(); if (dest.getPosition() < catchBlock.getHandlerPC() .getPosition() || // backjump out of handler dest.getPosition() > end.getPosition()) { // forward jump beyond catch if (verbose) { System.out .println("inlet contains a jump to exit, " + "assuming all locals are used"); } // They are all used. for (int j = 0; j < maxLocals; j++) { used[j] = true; } return used; } /* No, not good, could be inside a conditional. } else if (curr instanceof ReturnInstruction || curr instanceof ATHROW) { if (verbose) { System.out.println("return:"); for (int k = 0; k < used.length; k++) { if (!used[k]) { System.out.println("RET: local " + k + " is unused"); } } } // System.out.println("inlet local opt triggered"); return used; */ } else if (curr instanceof LocalVariableInstruction) { LocalVariableInstruction l = (LocalVariableInstruction) curr; used[l.getIndex()] = true; if (verbose) { System.out.println("just used local " + l.getIndex()); } } } return used; } SpawnTableEntry(SpawnTableEntry orig, MethodGen mg, MethodGen origM) { isLocalUsed = new boolean[origM.getMaxLocals()]; hasInlet = orig.hasInlet; if (hasInlet) { /* copy and rewite exception table */ CodeExceptionGen origE[] = origM.getExceptionHandlers(); CodeExceptionGen newE[] = mg.getExceptionHandlers(); catchBlocks = new ArrayList<CodeExceptionGen>(); for (int i = 0; i < orig.catchBlocks.size(); i++) { CodeExceptionGen origCatch = orig.catchBlocks .get(i); for (int j = 0; j < origE.length; j++) { if (origCatch == origE[j]) { catchBlocks.add(newE[j]); break; } } } } } } static class MethodTableEntry { Method m; MethodGen mg; boolean containsInlet; MethodTableEntry clone; int nrSpawns; SpawnTableEntry[] spawnTable; boolean isClone; Type[] typesOfParams; Type[] typesOfParamsNoThis; int startLocalAlloc; MethodTableEntry() { /* do nothing */ } MethodTableEntry(MethodTableEntry orig, MethodGen mg) { this.mg = mg; containsInlet = orig.containsInlet; clone = null; nrSpawns = orig.nrSpawns; isClone = true; typesOfParams = orig.typesOfParams; typesOfParamsNoThis = orig.typesOfParamsNoThis; startLocalAlloc = orig.startLocalAlloc; spawnTable = new SpawnTableEntry[orig.spawnTable.length]; for (int i = 0; i < spawnTable.length; i++) { spawnTable[i] = new SpawnTableEntry(orig.spawnTable[i], mg, orig.mg); } } void print(java.io.PrintStream out) { out.println("Method: " + m); out.println("params(" + typesOfParams.length + "): "); for (int i = 0; i < typesOfParams.length; i++) { out.println(" " + typesOfParams[i]); } out.println("This method contains " + nrSpawns + " spawn(s)"); if (isClone) { out.println("This method is a clone of an inlet method"); } else { out.println("This method is not a clone of an inlet method"); } if (containsInlet) { out.println("This method contains an inlet"); } else { out.println("This method does not contain an inlet"); } out.println(" } } private Vector<MethodTableEntry> methodTable; /* a vector of MethodTableEntries */ private JavaClass spawnableClass; private Satinc self; private boolean verbose; JavaClass c; private static HashMap<JavaClass, BT_Analyzer> analyzers = new HashMap<JavaClass, BT_Analyzer>(); private boolean available_slot(Type[] types, int ind, Type t) { Type tp = types[ind]; if (tp != null) { if (t.equals(tp)) { return true; } return false; } if (t.equals(Type.LONG) || t.equals(Type.DOUBLE)) { if (types[ind + 1] != null) { return false; } types[ind + 1] = Type.VOID; } types[ind] = t; return true; } // Make each stack position indicate a single type of variable. private void rewriteLocals(MethodGen m, ConstantPoolGen cpg) { // First, analyze how many stack positions are for parameters. // We won't touch those. int parameterpos = m.isStatic() ? 0 : 1; Type[] parameters = m.getArgumentTypes(); parameterpos += parameters.length; for (int i = 0; i < parameters.length; i++) { if (parameters[i].equals(Type.LONG) || parameters[i].equals(Type.DOUBLE)) { parameterpos++; } } LocalVariableGen[] locals = m.getLocalVariables(); int maxpos = m.getMaxLocals(); Type[] types = new Type[2 * locals.length + maxpos]; for (int i = 0; i < locals.length; i++) { int ind = locals[i].getIndex(); if (ind < parameterpos) { continue; } Type t = locals[i].getType(); if (!available_slot(types, ind, t)) { // Give this local a new stack position. locals[i].setIndex(maxpos); types[maxpos] = t; rewriteLocal(locals[i].getStart(), locals[i].getEnd(), ind, maxpos); // And give all other locals that have the same old stack // position and the same type this new stack position. for (int j = i + 1; j < locals.length; j++) { if (locals[j].getIndex() == ind && locals[j].getType().equals(t)) { locals[j].setIndex(maxpos); rewriteLocal(locals[j].getStart(), locals[j].getEnd(), ind, maxpos); } } maxpos++; if (t.equals(Type.LONG) || t.equals(Type.DOUBLE)) { // longs and doubles need two stack positions. types[maxpos] = Type.VOID; maxpos++; } } } // Rewrite all locals that are not in the LocalVariableTable. // Javac sometimes generates these for synchronized blocks. // Here, we give them a new index, so that they at least do not // collide with locals in the LocalVariableTable. // For now, if they occur in an inlet handler, they will not be // rewritten! ArrayList<Integer> newLocals = new ArrayList<Integer>(); InstructionList il = m.getInstructionList(); if (il == null) { return; } for (InstructionHandle h = il.getStart(); h != null; h = h.getNext()) { Instruction ins = h.getInstruction(); if (ins instanceof LocalVariableInstruction) { LocalVariableInstruction lins = (LocalVariableInstruction) ins; int pos = lins.getIndex(); if (pos >= parameterpos) { // Stay away from the method parameters. LocalVariableGen lg = getLocal(m, lins, h.getPosition()); if (lg == null) { int local = lins.getIndex(); Type tp = lins.getType(cpg); while (local >= newLocals.size()) { newLocals.add(null); } if (newLocals.get(local) == null) { newLocals.set(local, Integer.valueOf(maxpos)); maxpos++; if (tp.equals(Type.LONG) || tp.equals(Type.DOUBLE)) { maxpos++; } } Integer i = newLocals.get(local); lins.setIndex(i.intValue()); } } } } } // Rewrite instructions where local is used. void rewriteLocal(InstructionHandle fromH, InstructionHandle toH, int oldindex, int newindex) { InstructionHandle h = fromH; if (h.getPrev() != null) { h = h.getPrev(); // This instruction should contain the store. } while (h != null && h != toH) { Instruction ins = h.getInstruction(); if (ins instanceof LocalVariableInstruction) { LocalVariableInstruction lins = (LocalVariableInstruction) ins; if (lins.getIndex() == oldindex) { lins.setIndex(newindex); } } h = h.getNext(); } } MethodTable(JavaClass c, ClassGen gen_c, Satinc self, boolean verbose) { this.verbose = verbose; this.self = self; this.c = c; spawnableClass = Repository.lookupClass("ibis.satin.Spawnable"); methodTable = new Vector<MethodTableEntry>(); Method[] methods = gen_c.getMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; MethodGen mg = new MethodGen(m, c.getClassName(), gen_c .getConstantPool()); rewriteLocals(mg, gen_c.getConstantPool()); mg.setMaxLocals(); mg.setMaxStack(); gen_c.removeMethod(m); Satinc.removeLocalTypeTables(mg); m = mg.getMethod(); gen_c.addMethod(m); // mg = new MethodGen(m, c.getClassName(), gen_c.getConstantPool()); if (mg.getName().equals("<clinit>")) { /* MethodGen clinit = */new MethodGen(m, c.getClassName(), gen_c.getConstantPool()); } MethodTableEntry e = new MethodTableEntry(); e.nrSpawns = calcNrSpawns(mg); e.spawnTable = new SpawnTableEntry[e.nrSpawns]; e.m = m; e.mg = mg; e.typesOfParams = this.getParamTypesThis(m); e.typesOfParamsNoThis = this.getParamTypesNoThis(m); if (mg.getInstructionList() != null) { fillSpawnTable(e); } methodTable.addElement(e); } } void print(java.io.PrintStream out) { out.print(" out.print("method table of class " + c.getClassName()); out.println(" for (int i = 0; i < methodTable.size(); i++) { MethodTableEntry m = methodTable.elementAt(i); m.print(out); } out.println(" } private void fillSpawnTable(MethodTableEntry me) { InstructionList il = me.mg.getInstructionList(); InstructionHandle[] ins = il.getInstructionHandles(); il.setPositions(); int spawnId = 0; for (int k = 0; k < ins.length; k++) { if (ins[k].getInstruction() instanceof INVOKEVIRTUAL) { Method target = self.findMethod((INVOKEVIRTUAL) (ins[k] .getInstruction())); JavaClass cl = self.findMethodClass((INVOKEVIRTUAL) (ins[k] .getInstruction())); if (isSpawnable(target, cl)) { // we have a spawn! analyzeSpawn(me, ins[k], spawnId); spawnId++; } } } } private void analyzeSpawn(MethodTableEntry me, InstructionHandle spawnIns, int spawnId) { SpawnTableEntry se = me.spawnTable[spawnId] = new SpawnTableEntry(); se.isLocalUsed = new boolean[me.mg.getMaxLocals()]; CodeExceptionGen[] exceptions = me.mg.getExceptionHandlers(); // We have a spawn. Is it in a try block? for (int j = 0; j < exceptions.length; j++) { CodeExceptionGen e = exceptions[j]; int startPC = e.getStartPC().getPosition(); int endPC = e.getEndPC().getPosition(); int PC = spawnIns.getPosition(); if (verbose) { System.err.println("startPC = " + startPC + ", endPC = " + endPC + ", PC = " + PC); } if (PC >= startPC && PC <= endPC) { /* ok, we have an inlet, add try-catch block info to table */ me.containsInlet = true; se.hasInlet = true; if (se.catchBlocks == null) { se.catchBlocks = new ArrayList<CodeExceptionGen>(); } se.catchBlocks.add(e); if (verbose) { System.out.println("spawn " + spawnId + " with inlet " + e); } boolean[] used = se.analyseUsedLocals(me.mg, e, verbose); for (int k = 0; k < used.length; k++) { if (used[k]) { se.isLocalUsed[k] = true; } } } } if (verbose) { System.out.println(me.m + ": unused locals in all inlets: "); for (int k = 0; k < se.isLocalUsed.length; k++) { if (!se.isLocalUsed[k]) { System.out.println("local " + k + " is unused"); } else { System.out.println("local " + k + " is used"); } } } } private Type[] getParamTypesNoThis(Method m) { return Type.getArgumentTypes(m.getSignature()); } private Type[] getParamTypesThis(Method m) { Type[] params = getParamTypesNoThis(m); if (m.isStatic()) { return params; } Type[] newparams = new Type[1 + params.length]; newparams[0] = new ObjectType(c.getClassName()); for (int i = 0; i < params.length; i++) { newparams[i + 1] = params[i]; } return newparams; } private int calcNrSpawns(MethodGen mg) { InstructionList il = mg.getInstructionList(); if (il == null) { return 0; } InstructionHandle[] ins = il.getInstructionHandles(); int count = 0; for (int i = 0; i < ins.length; i++) { if (ins[i].getInstruction() instanceof INVOKEVIRTUAL) { Method target = self.findMethod((INVOKEVIRTUAL) (ins[i] .getInstruction())); JavaClass cl = self.findMethodClass((INVOKEVIRTUAL) (ins[i] .getInstruction())); if (isSpawnable(target, cl)) { count++; } } } return count; } private BT_Analyzer getAnalyzer(JavaClass cl) { BT_Analyzer b = analyzers.get(cl); if (b == null) { b = new BT_Analyzer(cl, spawnableClass, verbose); b.start(false); analyzers.put(cl, b); } return b; } boolean isSpawnable(Method m, JavaClass cl) { BT_Analyzer analyzer = getAnalyzer(cl); // System.out.println("isSpawnable: method = " + m + ", class = " + // cl.getClassName()); if (! analyzer.hasSpecialMethods()) { return false; } return analyzer.isSpecial(m); } void addCloneToInletTable(Method mOrig, MethodGen mg) { for (int i = 0; i < methodTable.size(); i++) { MethodTableEntry e = methodTable.elementAt(i); if (e.m.equals(mOrig)) { MethodTableEntry newE = new MethodTableEntry(e, mg); methodTable.addElement(newE); e.clone = newE; return; } } System.err.println("illegal method in addCloneToInletTable: " + mOrig); System.exit(1); } private MethodTableEntry findMethod(MethodGen mg) { for (int i = 0; i < methodTable.size(); i++) { MethodTableEntry e = methodTable.elementAt(i); if (e.mg == mg) { return e; } } System.err.println("Unable to find method " + mg); new Exception().printStackTrace(); System.exit(1); return null; } private MethodTableEntry findMethod(Method m) { for (int i = 0; i < methodTable.size(); i++) { MethodTableEntry e = methodTable.elementAt(i); if (e.m == m) { return e; } } System.err.println("Unable to find method " + m); new Exception().printStackTrace(); System.exit(1); return null; } boolean hasInlet(Method m, int spawnId) { MethodTableEntry e = findMethod(m); return e.spawnTable[spawnId].hasInlet; } boolean isLocalUsedInInlet(Method m, int localNr) { MethodTableEntry e = findMethod(m); if (localNr >= e.mg.getMaxLocals()) { System.out.println("eek, local nr too large: " + localNr + ", max: " + e.mg.getMaxLocals()); } for (int i = 0; i < e.spawnTable.length; i++) { if (e.spawnTable[i].isLocalUsed[localNr]) { return true; } } return false; } Type[] typesOfParams(Method m) { MethodTableEntry e = findMethod(m); return e.typesOfParams; } Type[] typesOfParamsNoThis(Method m) { MethodTableEntry e = findMethod(m); return e.typesOfParamsNoThis; } ArrayList<CodeExceptionGen> getCatchTypes(MethodGen m, int spawnId) { MethodTableEntry e = findMethod(m); return e.spawnTable[spawnId].catchBlocks; } Method getExceptionHandlingClone(Method m) { return findMethod(m).clone.m; } boolean containsInlet(MethodGen m) { return findMethod(m).containsInlet; } boolean containsInlet(Method m) { return findMethod(m).containsInlet; } boolean isClone(MethodGen m) { return findMethod(m).isClone; } boolean isClone(Method m) { return findMethod(m).isClone; } int nrSpawns(Method m) { return findMethod(m).nrSpawns; } void setStartLocalAlloc(MethodGen m, InstructionHandle i) { m.getInstructionList().setPositions(); findMethod(m).startLocalAlloc = i.getPosition(); } int getStartLocalAlloc(Method m) { return findMethod(m).startLocalAlloc; } static InstructionHandle getEndOfCatchBlock(MethodGen m, CodeExceptionGen catchBlock) { if (catchBlock.getCatchType() == null) { // finally clause, no local variable! return null; } LocalVariableGen[] lt = m.getLocalVariables(); InstructionHandle handler = catchBlock.getHandlerPC(); for (int i = 0; i < lt.length; i++) { InstructionHandle start = lt[i].getStart(); InstructionHandle end = lt[i].getEnd(); // dangerous, javac is one instruction further... if ((start == handler || start == handler.getNext() || start == handler .getNext().getNext()) && lt[i].getType().equals(catchBlock.getCatchType())) { // System.out.println("found range of catch block: " // + handler + " - " + end); return end.getPrev(); } } System.err .println("Could not find end of catch block, did you compile " + "with the '-g' option?"); System.exit(1); return null; } private static LocalVariableTable getLocalTable(Method m) { LocalVariableTable lt = m.getLocalVariableTable(); if (lt == null) { System.err.println("Could not get local variable table, did you " + "compile with the '-g' option?"); System.exit(1); } return lt; } private final LocalVariableGen[] getLocalTable(MethodGen m) { LocalVariableGen[] lt = m.getLocalVariables(); if (lt == null) { System.err.println("Could not get local variable table, did you " + "compile with the '-g' option?"); System.exit(1); } return lt; } static String getParamName(Method m, int paramNr) { LocalVariable[] lt = getLocalTable(m).getLocalVariableTable(); int minPos = Integer.MAX_VALUE; String res = null; for (int i = 0; i < lt.length; i++) { LocalVariable l = lt[i]; if (l.getIndex() == paramNr) { int startPos = l.getStartPC(); if (startPos < minPos) { minPos = startPos; res = l.getName(); } } } if (res != null) { return res; } System.err.println("getParamName: could not find name of param " + paramNr); System.exit(1); return null; } static String getParamNameNoThis(Method m, int paramNr) { if (!m.isStatic()) { paramNr++; } return getParamName(m, paramNr); } Type getParamType(Method m, int paramNr) { return findMethod(m).typesOfParams[paramNr]; } final LocalVariableGen getLocal(MethodGen m, LocalVariableInstruction curr, int pos) { int localNr = curr.getIndex(); LocalVariableGen[] lt = getLocalTable(m); for (int i = 0; i < lt.length; i++) { // Watch out. The first initialization seems not to be included in // the range given in the local variable table! if (localNr == lt[i].getIndex()) { // System.err.println("Looking for local " + localNr // + " on position " + pos); // System.err.println("found one with range " // + lt[i].getStart().getPrev().getPosition() + ", " // + lt[i].getEnd().getPosition()); if (pos >= lt[i].getStart().getPrev().getPosition() && pos < (lt[i].getEnd().getPosition())) { return lt[i]; } } } return null; } String getLocalName(MethodGen m, LocalVariableInstruction curr, int pos) { LocalVariableGen a = getLocal(m, curr, pos); if (a == null) { return null; } return a.getName(); } Type getLocalType(MethodGen m, LocalVariableInstruction curr, int pos) { LocalVariableGen a = getLocal(m, curr, pos); if (a == null) { return null; } return a.getType(); } static String generatedLocalName(Type type, String name) { return name + "_" + type.toString().replace('.', '_').replace('[', '_').replace(']', '_').replace('$', '_'); } static String[] getAllLocalDecls(Method m) { LocalVariable[] lt = getLocalTable(m).getLocalVariableTable(); Vector<String> v = new Vector<String>(); for (int i = 0; i < lt.length; i++) { LocalVariable l = lt[i]; Type tp = Type.getType(l.getSignature()); String e = tp.toString() + " " + generatedLocalName(tp, l.getName()) + ";"; if (!v.contains(e)) { v.addElement(e); } } String[] result = new String[v.size()]; result = v.toArray(result); // for (int i = 0; i < v.size(); i++) { // result[i] = (String) v.elementAt(i); // System.out.println("localdecls for " + m + ": " + result[i]); return result; } static Type[] getAllLocalTypes(Method m) { LocalVariable[] lt = getLocalTable(m).getLocalVariableTable(); Type[] result = new Type[lt.length]; for (int i = 0; i < lt.length; i++) { LocalVariable l = lt[i]; Type tp = Type.getType(l.getSignature()); result[i] = tp; } return result; } static String[] getAllLocalNames(Method m) { LocalVariable[] lt = getLocalTable(m).getLocalVariableTable(); String[] result = new String[lt.length]; for (int i = 0; i < lt.length; i++) { LocalVariable l = lt[i]; Type tp = Type.getType(l.getSignature()); String e = generatedLocalName(tp, l.getName()); result[i] = e; } return result; } boolean containsSpawnedCall(MethodGen m) { InstructionList code = m.getInstructionList(); if (code == null) { return false; } InstructionHandle ih[] = code.getInstructionHandles(); for (int i = 0; i < ih.length; i++) { Instruction ins = ih[i].getInstruction(); if (ins instanceof INVOKEVIRTUAL) { Method target = self.findMethod((INVOKEVIRTUAL) (ins)); JavaClass cl = self.findMethodClass((INVOKEVIRTUAL) (ins)); if (isSpawnable(target, cl)) { return true; } } } return false; } boolean containsSpawnedCall(Method m) { MethodGen mg = getMethodGen(m); return containsSpawnedCall(mg); } static int realMaxLocals(MethodGen m) { m.setMaxLocals(); return m.getMaxLocals(); } MethodGen getMethodGen(Method m) { MethodTableEntry e = findMethod(m); if (e == null) { return null; } return e.mg; } void replace(Method orig, Method newm) { MethodTableEntry e = findMethod(orig); e.m = newm; } void setMethod(MethodGen mg, Method m) { MethodTableEntry e = findMethod(mg); e.m = m; } }
package org.topcased.requirement.core.utils; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature.Setting; import org.eclipse.emf.ecore.EcorePackage; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.util.ECrossReferenceAdapter; import org.eclipse.emf.ecore.xmi.XMLResource; import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain; import org.eclipse.emf.edit.domain.EditingDomain; import org.eclipse.emf.edit.provider.ComposedAdapterFactory; import org.eclipse.osgi.util.NLS; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.services.ISourceProviderService; import org.topcased.facilities.util.EditorUtil; import org.topcased.requirement.AttributeAllocate; import org.topcased.requirement.AttributeConfiguration; import org.topcased.requirement.AttributeLink; import org.topcased.requirement.CurrentRequirement; import org.topcased.requirement.HierarchicalElement; import org.topcased.requirement.ObjectAttribute; import org.topcased.requirement.RequirementProject; import org.topcased.requirement.SpecialChapter; import org.topcased.requirement.TrashChapter; import org.topcased.requirement.UpstreamModel; import org.topcased.requirement.core.RequirementCorePlugin; import org.topcased.requirement.core.extensions.IEditorServices; import org.topcased.requirement.core.extensions.IModelAttachmentPolicy; import org.topcased.requirement.core.extensions.ModelAttachmentPolicyManager; import org.topcased.requirement.core.extensions.SupportingEditorsManager; import org.topcased.requirement.core.internal.Messages; import org.topcased.requirement.core.services.RequirementModelSourceProvider; import org.topcased.requirement.util.RequirementCacheAdapter; import org.topcased.requirement.util.RequirementResource; import ttm.Document; import ttm.Requirement; /** * Utilities for the search in the Requirement Model * * @author <a href="mailto:christophe.mertz@c-s.fr">Christophe Mertz</a> * @author <a href="mailto:sebastien.gabel@c-s.fr">Sebastien GABEL</a> * @author <a href="mailto:maxime.audrain@c-s.fr">Maxime AUDRAIN</a> * */ public final class RequirementUtils { /** Prefix for deleted documents */ private static final String DELETED_PREFIX = "deleted_";//$NON-NLS-1$ /** Pattern for detecting ident of deleted documents */ private static final Pattern DELETED_DOCUMENT_PATTERN = Pattern.compile(DELETED_PREFIX.concat("\\d\\d\\d\\d-\\d\\d-\\d\\d(_\\d\\d-\\d\\d)?"));//$NON-NLS-1$ /** Format string for constructing ident of deleted documents */ private static final String DELETED_DOCUMENT_IDENT_FORMAT = DELETED_PREFIX.concat("%s"); /** Date format for constructing ident of deleted documents */ private static final String DELETED_DOCUMENT_DATE_FORMAT = "yyyy-MM-dd_HH-mm"; /** * The shared adapter factory */ private static ComposedAdapterFactory adapterFactory; static { // Create an adapter factory that yields item providers. adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE); } /** * Private constructor */ private RequirementUtils() { // cannot be instancied } /** * Gets the adapter factory * * @return The adapter factory */ public static ComposedAdapterFactory getAdapterFactory() { return adapterFactory; } /** * Gets the adapter factory from the editing domain (mainly used for label providers) * * @param editingDomain the modeler's editing domain * @return the editing domain's adapter factory or default adapter factory if unavailable * @see #getAdapterFactory() */ public static AdapterFactory getAdapterFactory(EditingDomain editingDomain) { if (editingDomain instanceof AdapterFactoryEditingDomain) { AdapterFactoryEditingDomain topcasedDomain = (AdapterFactoryEditingDomain) editingDomain; if (topcasedDomain.getAdapterFactory() instanceof ComposedAdapterFactory) { ComposedAdapterFactory factory = (ComposedAdapterFactory) topcasedDomain.getAdapterFactory(); return factory; } } return getAdapterFactory(); } /** * Get all objects clazz in the resource * * @param resource : a model * @param clazz : the object to search in the model * @return */ public static Collection<EObject> getAllObjects(Resource resource, java.lang.Class< ? > clazz) { Collection<EObject> result = new ArrayList<EObject>(); if (resource != null && !resource.getContents().isEmpty()) { for (Iterator<EObject> h = resource.getContents().get(0).eAllContents(); h.hasNext();) { EObject currEo = h.next(); if (clazz.isInstance(currEo)) { result.add(currEo); } } } return result; } /** * Gets all objects instance of clazz in the target model referenced in the model of requirement * * @param the clazz to search * * @return collection of model objects or empty collection */ public static Collection<EObject> getAllObjects(EClass classifier) { IEditorServices services = getSpecificServices(null); if (services != null) { Resource modelResource = services.getModelResource(null); if (modelResource.getContents().size() > 0) { EObject model = modelResource.getContents().get(0); return services.getAllModelObjects(model, classifier); } } return new ArrayList<EObject>(); } /** * Gets all Upstream Requirements from a starting point. * * @param starting The model object representing the starting point. * @return A collection of Upstream Requirements found from the starting point. */ public static Collection<Requirement> getUpstreams(EObject starting) { Collection<Requirement> result = new ArrayList<Requirement>(); for (Iterator<EObject> h = starting.eAllContents(); h.hasNext();) { EObject current = h.next(); if (current instanceof Requirement) { result.add((Requirement) current); } } return result; } /** * Gets all {@link org.topcased.requirement.Requirement} starting from a starting point that should be of type * {@link HierarchicalElement}. * * @param starting The model object representing the starting point. * @return A collection of Current Requirements found from the starting point */ public static Collection<org.topcased.requirement.Requirement> getCurrents(EObject starting) { Collection<org.topcased.requirement.Requirement> result = new ArrayList<org.topcased.requirement.Requirement>(); if (starting != null) { for (Iterator<EObject> h = starting.eAllContents(); h.hasNext();) { EObject current = h.next(); if (current instanceof org.topcased.requirement.Requirement) { result.add((org.topcased.requirement.Requirement) current); } } } return result; } /** * Gets all Current Requirements for a Resource. * * @param resource The requirement model as an EMF {@link Resource} * @return A collection of Current Requirements found from the starting point */ public static Collection<org.topcased.requirement.Requirement> getAllCurrents(Resource resource) { if (resource != null) { return getCurrents(resource.getContents().get(0)); } return Collections.emptyList(); } /** * Gets all Upstream Requirements for a Resource. * * @param resource The requirement model as an EMF {@link Resource} * @return A collection of Upstream Requirements found from the starting point */ public static Collection<Requirement> getAllUpstreams(Resource resource) { if (resource != null) { return getUpstreams(resource.getContents().get(0)); } return Collections.emptyList(); } /** * Determines if the upstream requirement is linked (link_to attribute) to a current requirement * * @param an upstream requirement * @return true if the upstream requirement is linked (link_to attribute) to a current requirement */ public static Boolean isLinked(Requirement req) { for (Setting setting : getCrossReferences(req)) { if (setting.getEObject() instanceof AttributeLink) { return true; } } return false; } /** * Determines if the upstream requirement is partial (link_to attribute) * * @param an upstream requirement * @return true if the upstream requirement is partial (link_to attribute) */ public static Boolean isPartial(Requirement req) { for (Setting setting : getCrossReferences(req)) { if (setting.getEObject() instanceof AttributeLink) { AttributeLink link = (AttributeLink) setting.getEObject(); if (link.getPartial()) { return true; } } } return false; } /** * Get the cross references of the source object from the requirement cache adapter * * @param source * @return collection of settings */ public static Collection<Setting> getCrossReferences(EObject source) { Collection<Setting> collection = Collections.<Setting> emptyList(); if (source == null) { return collection; } ECrossReferenceAdapter adapter = RequirementCacheAdapter.getExistingRequirementCacheAdapter(source); if (adapter == null) { adapter = ECrossReferenceAdapter.getCrossReferenceAdapter(source); } if (adapter != null) { collection = adapter.getNonNavigableInverseReferences(source); } return collection; } /** * Count the number of children of type Hierarchical Element * * @param hierarchicalElement * * @return the number of children of type Hierarchical Element */ public static int countChildrens(Object hierarchicalElement) { int result = 0; if (!(hierarchicalElement instanceof HierarchicalElement)) { return result; } for (Iterator<EObject> children = ((HierarchicalElement) hierarchicalElement).eAllContents(); children.hasNext();) { EObject currEo = children.next(); if (currEo instanceof HierarchicalElement && (((HierarchicalElement) currEo).getParent() == hierarchicalElement)) { result++; } } return result; } /** * Get a resource from a file and load it * * @param file The model path * @return the resource */ public static Resource getResource(IPath path) { ResourceSet resourceSet = new ResourceSetImpl(); URI fileURI = URI.createPlatformResourceURI(path.toString(), true); return resourceSet.getResource(fileURI, true); } /** * Get a file path from a resource URI * * @param resourceURI The resource URI * @return the model path */ public static IPath getPath(URI resourceURI) { String scheme = resourceURI.scheme(); IPath path = null; if ("platform".equals(scheme)) //$NON-NLS-1$ { path = Path.fromPortableString(resourceURI.toPlatformString(true)); } else if ("file".equals(scheme)) //$NON-NLS-1$ { URI platformURI = resourceURI.deresolve(URI.createURI(ResourcesPlugin.getWorkspace().getRoot().getLocationURI().toString()+"/"),false,false,true); path = new Path("/" + platformURI.toString()); } return path; } /** * Get a file path from a resource * * @param resource The resource * @return the model path */ public static IPath getPath(Resource resource) { URI uri = resource.getURI(); return getPath(uri); } /** * Gets the IFile of a resource * * @param resource * * @return the IFile of a resource */ public static IFile getFile(Resource resource) { IPath path = getPath(resource); if (path != null) { return ResourcesPlugin.getWorkspace().getRoot().getFile(path); } return null; } /** * Deletes a given resource * * @param resource */ public static void deleteResource(Resource resource) { try { URI uri = resource.getURI(); IResource toDelete = ResourcesPlugin.getWorkspace().getRoot().findMember(uri.toPlatformString(true)); if (toDelete != null && toDelete.isAccessible() && toDelete.exists()) { toDelete.delete(true, new NullProgressMonitor()); toDelete.refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor()); } } catch (CoreException e) { RequirementCorePlugin.log("Error while deleting Requirement model. Please, delete it manually.", IStatus.ERROR, e); //$NON-NLS-1$ } } /** * Gets the EObject corresponding to the clazz in the resource * * @param resource : the requirement model * @param clazz * * @return EObject of the RequirementProject */ public static EObject getRoot(Resource resource, java.lang.Class< ? > clazz) { if (resource != null) { for (EObject o : resource.getContents()) { if (clazz.isInstance(o)) { return o; } } } return null; } /** * Saves a resource * * @param resource */ public static void saveResource(Resource resource) { try { Map<Object, Object> options = new HashMap<Object, Object>(); options.put(XMLResource.OPTION_ENCODING, "UTF-8"); //$NON-NLS-1$ resource.save(options); } catch (IOException exception) { RequirementCorePlugin.log(exception); } } /** * Loads the requirement model if required. * * @param uri The uri of the requirement model * @param domain The shared editing domain */ public static void loadRequirementModel(URI uri, EditingDomain domain) { // Gets the requirement model from the editing domain or loads it if // it's the first time domain.getResourceSet().getResource(uri, true); if (domain instanceof AdapterFactoryEditingDomain) { AdapterFactoryEditingDomain adapterFactoryDomain = (AdapterFactoryEditingDomain) domain; if (adapterFactoryDomain.getAdapterFactory() instanceof ComposedAdapterFactory) { ComposedAdapterFactory factory = (ComposedAdapterFactory) adapterFactoryDomain.getAdapterFactory(); factory.addAdapterFactory(RequirementUtils.getAdapterFactory()); } } } /** * Unloads the requirement model from the editing domain * * @param domain The shared editing domain * @return true if the resource has been successfully removed from the editing domain */ public static boolean unloadRequirementModel(EditingDomain domain) { if (domain instanceof AdapterFactoryEditingDomain) { AdapterFactoryEditingDomain adapterFactoryDomain = (AdapterFactoryEditingDomain) domain; if (adapterFactoryDomain.getAdapterFactory() instanceof ComposedAdapterFactory) { ComposedAdapterFactory factory = (ComposedAdapterFactory) adapterFactoryDomain.getAdapterFactory(); factory.removeAdapterFactory(RequirementUtils.getAdapterFactory()); } } Resource requirementRsc = getRequirementModel(domain); if (requirementRsc != null) { // Unload the requirement resource and notify commands that the // hasRequirement variable has changed requirementRsc.unload(); return domain.getResourceSet().getResources().remove(requirementRsc); } return false; } /** * Gets the requirement model as an EMF resource. * * @param domain the editing domain of the active modeler * @return the requirement model as a requirement resource */ public static RequirementResource getRequirementModel(EditingDomain domain) { if (domain != null) { for (Resource resource : domain.getResourceSet().getResources()) { if (resource instanceof RequirementResource) { return (RequirementResource) resource; } } } return null; } /** * Determines if the given editing domain contains a loaded requirement model related to other resources. * * @param domain the editing domain of the active modeler * @return true if the requirement model is found inside the editing domain, false otherwise. */ public static boolean hasRequirementModel(EditingDomain domain) { Resource rsc = getRequirementModel(domain); return rsc != null && rsc.isLoaded(); } /** * Gets a set of models loaded in the Topcased editing domain. * * @return all models loaded as a set of Resources. * @deprecated use {@link #getAllObjects(EClass)} instead */ public static Set<Resource> getTargetModels() { Set<Resource> toReturn = new HashSet<Resource>(); IEditorServices services = getSpecificServices(null); if (services != null) { return Collections.singleton(services.getModelResource(null)); } return toReturn; } /** * Gets the {@link RequirementProject} model object contained in this EMF resource. * * @param requirement The requirement model * @return The {@link RequirementProject} found inside this resource. */ public static RequirementProject getRequirementProject(EditingDomain editingDomain) { RequirementResource requirementModel = RequirementUtils.getRequirementModel(editingDomain); return getRequirementProject(requirementModel); } /** * Gets the {@link RequirementProject} model object contained in this EMF resource. * * @param requirement The requirement model * @return The {@link RequirementProject} found inside this resource. */ public static RequirementProject getRequirementProject(Resource requirement) { return (RequirementProject) getRoot(requirement, RequirementProject.class); } /** * Gets the {@link AttributeConfiguration} model object contained in a {@link RequirementProject}. * * @param requirement The resource representing a requirement model * @return the current attribute configuration. */ public static AttributeConfiguration getAttributeConfiguration(Resource requirement) { RequirementProject project = getRequirementProject(requirement); if (project != null) { return project.getAttributeConfiguration(); } return null; } /** * Gets the {@link AttributeConfiguration} model object contained in a {@link RequirementProject}. * * @param editingDomain The configuration must be searched inside the domain. * @return the current attribute configuration. */ public static AttributeConfiguration getAttributeConfiguration(EditingDomain editingDomain) { RequirementResource requirementModel = RequirementUtils.getRequirementModel(editingDomain); return RequirementUtils.getAttributeConfiguration(requirementModel); } /** * Gets the {@link UpstreamModel} model object contained in a {@link RequirementProject}. * * @param requirement The resource representing a requirement model * @return the upstream model found. */ public static UpstreamModel getUpstreamModel(Resource requirement) { RequirementProject project = (RequirementProject) getRoot(requirement, RequirementProject.class); if (project != null) { return project.getUpstreamModel(); } return null; } /** * Gets the {@link Document} model objects contained under the {@link UpstreamModel}. * * @param requirement The resource representing a requirement model * @return the upstream model found. */ public static List<Document> getUpstreamDocuments(Resource requirement) { UpstreamModel upstreamModel = getUpstreamModel(requirement); if (upstreamModel != null) { return upstreamModel.getDocuments(); } return Collections.emptyList(); } /** * Gets the Trash Chapter model object contained in a Requirement Project. * * @param editingDomain The trash chapter must be searched inside the domain. * @return the special trash chapter found. */ public static TrashChapter getTrashChapter(EditingDomain editingDomain) { RequirementProject project = getRequirementProject(editingDomain); if (project != null) { for (SpecialChapter chapter : project.getChapter()) { if (chapter instanceof TrashChapter) { return (TrashChapter) chapter; } } } return null; } /** * Before displaying the choose dialog, we need to compute the content to display according to the selected object. * * @param selected The first element selected * @return An object collection to pass to the dialog. */ public static Collection<Object> getChooseDialogContent(Object selected) { Collection<Object> listObjects = new ArrayList<Object>(); // this is the value inserted to reset the affected value listObjects.add(""); //$NON-NLS-1$ if (selected instanceof AttributeAllocate) { // add all the model elements listObjects.addAll(RequirementUtils.getAllObjects(EcorePackage.eINSTANCE.getEModelElement())); } else { if (!(selected instanceof AttributeLink)) { listObjects.addAll(RequirementUtils.getAllObjects(EcorePackage.eINSTANCE.getEModelElement())); } ObjectAttribute objAtt = (ObjectAttribute) selected; listObjects.addAll(RequirementUtils.getAllUpstreams(objAtt.eResource())); listObjects.addAll(RequirementUtils.getAllCurrents(objAtt.eResource())); } return listObjects; } /** * Gets the hierarchical element for a given model object. * * @param toFind The EObject for which the corresponding hierarchical element must be found. */ public static HierarchicalElement getHierarchicalElementFor(Object toFind) { if (toFind instanceof EObject) { return getHierarchicalElementFor((EObject) toFind); } return null; } /** * Gets the hierarchical element for a given model object. * * @param toFind The EObject for which the corresponding hierarchical element must be found. */ public static HierarchicalElement getHierarchicalElementFor(EObject toFind) { for (Setting setting : getCrossReferences(toFind)) { if (setting.getEObject() instanceof HierarchicalElement) { return (HierarchicalElement) setting.getEObject(); } } return null; } /** * Opens the given diagram resource given in parameter. * * @param resourceToClose The diagram resource to close * @return <code>true</code> if the diagram editor has been closed, <code>false</code> otherwise. */ public static void openDiagramEditor(IPath resourceToOpen) { try { IFile fileToOpen = ResourcesPlugin.getWorkspace().getRoot().getFile(resourceToOpen); EditorUtil.open(fileToOpen); } catch (PartInitException e) { RequirementCorePlugin.log(e); } } /** * Closes the given resource if already opened. * * @param resourceToClose The diagram resource to close * @return <code>true</code> if the diagram editor has been closed, <code>false</code> otherwise. */ public static boolean closeDiagramEditor(IPath resourceToClose) { boolean closed = false; // Look for a reference to the target model editor ? for (IEditorReference editorRef : PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getEditorReferences()) { try { String resourceName = editorRef.getEditorInput().getName(); if (resourceToClose.lastSegment().equals(resourceName)) { IEditorPart part = editorRef.getEditor(false); if (part != null && part instanceof IEditorPart) { IEditorPart editor = (IEditorPart) part; editor.doSave(new NullProgressMonitor()); closed = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeEditor(part, false); } } } catch (PartInitException e) { RequirementCorePlugin.log(e); } } return closed; } /** * * Notify commands that the isImpacted variable has changed. Handle the enablement/disablement of commands when no * current requirement are impacted */ public static void fireIsImpactedVariableChanged() { Boolean noRequirementImpacted = true; IEditorServices services = getSpecificServices(null); // Modeler modeler = Utils.getCurrentModeler(); ISourceProviderService spc = (ISourceProviderService) PlatformUI.getWorkbench().getService(ISourceProviderService.class); RequirementModelSourceProvider myPro = (RequirementModelSourceProvider) spc.getSourceProvider(RequirementModelSourceProvider.IS_IMPACTED); if (services != null && myPro != null) { Resource requirement = getRequirementModel(services.getEditingDomain(null)); if (requirement != null) { Collection<EObject> allRequirement = RequirementUtils.getAllObjects(requirement, CurrentRequirement.class); // checks that all CurrentRequirement are marked as not // impacted. for (EObject aReq : allRequirement) { if (aReq instanceof CurrentRequirement && ((CurrentRequirement) aReq).isImpacted()) { // action must be disabled. noRequirementImpacted = false; break; } } myPro.setIsImpactedState(noRequirementImpacted); } } // if (modeler != null && myPro != null) // Resource requirement = RequirementUtils.getRequirementModel(modeler.getEditingDomain()); // if (requirement != null) // Collection<EObject> allRequirement = RequirementUtils.getAllObjects(requirement, CurrentRequirement.class); // // checks that all CurrentRequirement are marked as not // // impacted. // for (EObject aReq : allRequirement) // if (aReq instanceof CurrentRequirement && ((CurrentRequirement) aReq).isImpacted()) // // action must be disabled. // isImpacted = false; // break; // myPro.setIsImpactedState(isImpacted); } /** * * Notify commands that the hasRequirement variable has changed. Handle the enablement/disablement of commands when * there is a requirement model attached to the current modeler. */ public static void fireHasRequirementVariableChanged() { boolean enable = false; ISourceProviderService service = (ISourceProviderService) PlatformUI.getWorkbench().getService(ISourceProviderService.class); RequirementModelSourceProvider provider = (RequirementModelSourceProvider) service.getSourceProvider(RequirementModelSourceProvider.HAS_REQUIREMENT_MODEL); IEditorServices services = getSpecificServices(null); if (services != null) { EditingDomain domain = services.getEditingDomain(null); if (domain != null) { IModelAttachmentPolicy policy = ModelAttachmentPolicyManager.getInstance().getModelPolicy(domain); if (policy != null) { enable = policy.getLinkedTargetModel(domain.getResourceSet()) != null; } else { String extension = domain.getResourceSet().getResources().get(0).getURI().fileExtension(); String msg = NLS.bind(Messages.getString("ModelAttachmentPolicyManager.0"), extension); RequirementCorePlugin.log(msg, Status.ERROR, null);//$NON-NLS-1$ enable = false; } } } // Modeler modeler = Utils.getCurrentModeler(); // if (modeler != null) // IModelAttachmentPolicy policy = // ModelAttachmentPolicyManager.getInstance().getModelPolicy(modeler.getEditingDomain()); // if (policy != null) // enable = policy.getLinkedTargetModel(modeler.getEditingDomain().getResourceSet()) != null; // else // enable = // DefaultAttachmentPolicy.getInstance().getLinkedTargetModel(modeler.getEditingDomain().getResourceSet()) != // null; // else // enable = false; // ModelSet resSet = EditorUtils.getDiResourceSet(); // if (resSet != null) // IModel reqModel = resSet.getModel("org.topcased.requirement.papyrus.requirementModel"); // if (reqModel != null) // enable = true; provider.setHasRequirementState(enable); } /** * * Notify commands that the IsSectionEnabled variable has changed. Handle the enablement/disablement of commands * when the requirement property section is shown/hidden. */ public static void fireIsSectionEnabledVariableChanged(boolean enable) { ISourceProviderService service = (ISourceProviderService) PlatformUI.getWorkbench().getService(ISourceProviderService.class); RequirementModelSourceProvider provider = (RequirementModelSourceProvider) service.getSourceProvider(RequirementModelSourceProvider.IS_SECTION_ENABLED); provider.setIsSectionEnabledState(enable); } /** * Get the currently active editor, whatever its type * * @return the active editor or null */ public static IEditorPart getCurrentEditor() { IWorkbench workbench = PlatformUI.getWorkbench(); if (workbench != null) { IWorkbenchWindow activeWorkbenchWindow = workbench.getActiveWorkbenchWindow(); if (activeWorkbenchWindow != null) { IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage(); if (activePage != null) { return activePage.getActiveEditor(); } } } return null; } /** * Get the services specific to an editor. * * @param editor the editor to find services for, or null to take the currently active editor * @return appropriated services or null if none */ public static IEditorServices getSpecificServices(IEditorPart editor) { if (editor == null) { editor = getCurrentEditor(); } if (editor != null) { return SupportingEditorsManager.getInstance().getServices(editor); } return null; } /** * Get ident to use for a document containing deleted requirements * * @param date the deletion date * @return ident to use */ public static String getDeletedDocumentIdent(Date date) { DateFormat dateFormat = new SimpleDateFormat(DELETED_DOCUMENT_DATE_FORMAT); return String.format(DELETED_DOCUMENT_IDENT_FORMAT, dateFormat.format(date)); } /** * Test if ident of a document correspond to a document containing deleted requirements * * @param ident ident to test * @return true if format is correct for deleted documents */ public static boolean isDeletedDocumentIdent(String ident) { return DELETED_DOCUMENT_PATTERN.matcher(ident).matches(); } public static Set<CurrentRequirement> getLinkedCurrentRequirements(ttm.Requirement upstreamReq) { Set<CurrentRequirement> currentReqs = new HashSet<CurrentRequirement>(); if (upstreamReq.eResource() != null) { for (Setting setting : getCrossReferences(upstreamReq)) { if (setting.getEObject() instanceof AttributeLink) { AttributeLink attr = (AttributeLink) setting.getEObject(); if (attr.eContainer() instanceof CurrentRequirement) { currentReqs.add((CurrentRequirement) attr.eContainer()); } } } } return currentReqs; } }
package com.opengamma.component.factory.web; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import org.fudgemsg.FudgeContext; import org.joda.beans.BeanBuilder; import org.joda.beans.BeanDefinition; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaProperty; import org.joda.beans.Property; import org.joda.beans.PropertyDefinition; import org.joda.beans.impl.direct.DirectBeanBuilder; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import org.springframework.web.context.ServletContextAware; import com.opengamma.component.ComponentRepository; import com.opengamma.component.factory.AbstractComponentFactory; import com.opengamma.core.change.AggregatingChangeManager; import com.opengamma.core.change.ChangeManager; import com.opengamma.core.change.ChangeProvider; import com.opengamma.core.position.PositionSource; import com.opengamma.core.security.SecuritySource; import com.opengamma.engine.ComputationTargetResolver; import com.opengamma.engine.view.ViewDefinitionRepository; import com.opengamma.engine.view.ViewProcessor; import com.opengamma.financial.aggregation.PortfolioAggregationFunctions; import com.opengamma.financial.view.ManageableViewDefinitionRepository; import com.opengamma.livedata.UserPrincipal; import com.opengamma.master.config.ConfigMaster; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesMaster; import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotMaster; import com.opengamma.master.portfolio.PortfolioMaster; import com.opengamma.master.position.PositionMaster; import com.opengamma.master.security.SecurityMaster; import com.opengamma.util.fudgemsg.OpenGammaFudgeContext; import com.opengamma.web.server.AggregatedViewDefinitionManager; import com.opengamma.web.server.push.ConnectionManagerImpl; import com.opengamma.web.server.push.LongPollingConnectionManager; import com.opengamma.web.server.push.MasterChangeManager; import com.opengamma.web.server.push.WebPushServletContextUtils; import com.opengamma.web.server.push.analytics.AnalyticsColumnsJsonWriter; import com.opengamma.web.server.push.analytics.AnalyticsViewManager; import com.opengamma.web.server.push.analytics.formatting.ResultsFormatter; import com.opengamma.web.server.push.rest.AggregatorNamesResource; import com.opengamma.web.server.push.rest.MarketDataSnapshotListResource; import com.opengamma.web.server.push.rest.MasterType; import com.opengamma.web.server.push.rest.ViewDefinitionEntriesResource; import com.opengamma.web.server.push.rest.ViewsResource; import com.opengamma.web.server.push.rest.json.AnalyticsColumnGroupsMessageBodyWriter; import com.opengamma.web.server.push.rest.json.DependencyGraphGridStructureMessageBodyWriter; import com.opengamma.web.server.push.rest.json.PortfolioGridStructureMessageBodyWriter; import com.opengamma.web.server.push.rest.json.PrimitivesGridStructureMessageBodyWriter; import com.opengamma.web.server.push.rest.json.ViewportResultsMessageBodyWriter; import com.opengamma.web.server.push.rest.json.ViewportVersionMessageBodyWriter; /** * Component factory for the main website viewports (for analytics). */ @BeanDefinition public class WebsiteViewportsComponentFactory extends AbstractComponentFactory { /** * The configuration master. */ @PropertyDefinition(validate = "notNull") private ConfigMaster _configMaster; /** * The security master. */ @PropertyDefinition(validate = "notNull") private SecurityMaster _securityMaster; /** * The security source. */ @PropertyDefinition(validate = "notNull") private SecuritySource _securitySource; /** * The position master. */ @PropertyDefinition(validate = "notNull") private PositionMaster _positionMaster; /** * The portfolio master. */ @PropertyDefinition(validate = "notNull") private PortfolioMaster _portfolioMaster; /** * The position source. */ @PropertyDefinition(validate = "notNull") private PositionSource _positionSource; /** * The computation target resolver. */ @PropertyDefinition(validate = "notNull") private ComputationTargetResolver _computationTargetResolver; /** * The time-series master. */ @PropertyDefinition(validate = "notNull") private HistoricalTimeSeriesMaster _historicalTimeSeriesMaster; /** * The user master. */ @PropertyDefinition(validate = "notNull") private PositionMaster _userPositionMaster; /** * The user master. */ @PropertyDefinition(validate = "notNull") private PortfolioMaster _userPortfolioMaster; /** * The combined view definition repository. */ @PropertyDefinition(validate = "notNull") private ViewDefinitionRepository _viewDefinitionRepository; /** * The user view definition repository. */ @PropertyDefinition(validate = "notNull") private ManageableViewDefinitionRepository _userViewDefinitionRepository; /** * The view processor. */ @PropertyDefinition(validate = "notNull") private ViewProcessor _viewProcessor; /** * The portfolio aggregation functions. */ @PropertyDefinition(validate = "notNull") private PortfolioAggregationFunctions _portfolioAggregationFunctions; /** * The market data snapshot master. */ @PropertyDefinition(validate = "notNull") private MarketDataSnapshotMaster _marketDataSnapshotMaster; /** * The user. */ @PropertyDefinition(validate = "notNull") private UserPrincipal _user; /** * The fudge context. */ @PropertyDefinition(validate = "notNull") private FudgeContext _fudgeContext = OpenGammaFudgeContext.getInstance(); @Override public void init(ComponentRepository repo, LinkedHashMap<String, String> configuration) { final LongPollingConnectionManager longPolling = buildLongPolling(); ChangeManager changeMgr = buildChangeManager(); MasterChangeManager masterChangeMgr = buildMasterChangeManager(); final ConnectionManagerImpl connectionMgr = new ConnectionManagerImpl(changeMgr, masterChangeMgr, longPolling); AggregatorNamesResource aggregatorsResource = new AggregatorNamesResource(getPortfolioAggregationFunctions().getMappedFunctions().keySet()); MarketDataSnapshotListResource snapshotResource = new MarketDataSnapshotListResource(getMarketDataSnapshotMaster()); AggregatedViewDefinitionManager aggregatedViewDefManager = new AggregatedViewDefinitionManager( getPositionSource(), getSecuritySource(), getViewDefinitionRepository(), getUserViewDefinitionRepository(), getUserPortfolioMaster(), getUserPositionMaster(), getPortfolioAggregationFunctions().getMappedFunctions()); AnalyticsViewManager analyticsViewManager = new AnalyticsViewManager(getViewProcessor(), aggregatedViewDefManager, getMarketDataSnapshotMaster(), getComputationTargetResolver()); ResultsFormatter resultsFormatter = new ResultsFormatter(); AnalyticsColumnsJsonWriter columnWriter = new AnalyticsColumnsJsonWriter(resultsFormatter); repo.getRestComponents().publishResource(aggregatorsResource); repo.getRestComponents().publishResource(snapshotResource); repo.getRestComponents().publishResource(new ViewsResource(analyticsViewManager, connectionMgr)); repo.getRestComponents().publishHelper(new ViewportVersionMessageBodyWriter()); repo.getRestComponents().publishHelper(new PrimitivesGridStructureMessageBodyWriter(columnWriter)); repo.getRestComponents().publishHelper(new PortfolioGridStructureMessageBodyWriter(columnWriter)); repo.getRestComponents().publishHelper(new DependencyGraphGridStructureMessageBodyWriter(columnWriter)); repo.getRestComponents().publishHelper(new AnalyticsColumnGroupsMessageBodyWriter(columnWriter)); repo.getRestComponents().publishHelper(new ViewportResultsMessageBodyWriter(resultsFormatter)); repo.getRestComponents().publishHelper(new ViewDefinitionEntriesResource(getViewDefinitionRepository())); // these items need to be available to the servlet, but aren't important enough to be published components repo.registerServletContextAware(new ServletContextAware() { @Override public void setServletContext(ServletContext servletContext) { WebPushServletContextUtils.setConnectionManager(servletContext, connectionMgr); WebPushServletContextUtils.setLongPollingConnectionManager(servletContext, longPolling); } }); } protected LongPollingConnectionManager buildLongPolling() { return new LongPollingConnectionManager(); } protected ChangeManager buildChangeManager() { List<ChangeProvider> providers = new ArrayList<ChangeProvider>(); providers.add(getPositionMaster()); providers.add(getPortfolioMaster()); providers.add(getSecurityMaster()); providers.add(getHistoricalTimeSeriesMaster()); providers.add(getConfigMaster()); return new AggregatingChangeManager(providers); } protected MasterChangeManager buildMasterChangeManager() { Map<MasterType, ChangeProvider> providers = new HashMap<MasterType, ChangeProvider>(); providers.put(MasterType.POSITION, getPositionMaster()); providers.put(MasterType.PORTFOLIO, getPortfolioMaster()); providers.put(MasterType.SECURITY, getSecurityMaster()); providers.put(MasterType.TIME_SERIES, getHistoricalTimeSeriesMaster()); providers.put(MasterType.CONFIG, getConfigMaster()); return new MasterChangeManager(providers); } ///CLOVER:OFF /** * The meta-bean for {@code WebsiteViewportsComponentFactory}. * @return the meta-bean, not null */ public static WebsiteViewportsComponentFactory.Meta meta() { return WebsiteViewportsComponentFactory.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(WebsiteViewportsComponentFactory.Meta.INSTANCE); } @Override public WebsiteViewportsComponentFactory.Meta metaBean() { return WebsiteViewportsComponentFactory.Meta.INSTANCE; } @Override protected Object propertyGet(String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case 10395716: // configMaster return getConfigMaster(); case -887218750: // securityMaster return getSecurityMaster(); case -702456965: // securitySource return getSecuritySource(); case -1840419605: // positionMaster return getPositionMaster(); case -772274742: // portfolioMaster return getPortfolioMaster(); case -1655657820: // positionSource return getPositionSource(); case 1562222174: // computationTargetResolver return getComputationTargetResolver(); case 173967376: // historicalTimeSeriesMaster return getHistoricalTimeSeriesMaster(); case 1808868758: // userPositionMaster return getUserPositionMaster(); case 686514815: // userPortfolioMaster return getUserPortfolioMaster(); case -952415422: // viewDefinitionRepository return getViewDefinitionRepository(); case -1371772371: // userViewDefinitionRepository return getUserViewDefinitionRepository(); case -1697555603: // viewProcessor return getViewProcessor(); case 940303425: // portfolioAggregationFunctions return getPortfolioAggregationFunctions(); case 2090650860: // marketDataSnapshotMaster return getMarketDataSnapshotMaster(); case 3599307: // user return getUser(); case -917704420: // fudgeContext return getFudgeContext(); } return super.propertyGet(propertyName, quiet); } @Override protected void propertySet(String propertyName, Object newValue, boolean quiet) { switch (propertyName.hashCode()) { case 10395716: // configMaster setConfigMaster((ConfigMaster) newValue); return; case -887218750: // securityMaster setSecurityMaster((SecurityMaster) newValue); return; case -702456965: // securitySource setSecuritySource((SecuritySource) newValue); return; case -1840419605: // positionMaster setPositionMaster((PositionMaster) newValue); return; case -772274742: // portfolioMaster setPortfolioMaster((PortfolioMaster) newValue); return; case -1655657820: // positionSource setPositionSource((PositionSource) newValue); return; case 1562222174: // computationTargetResolver setComputationTargetResolver((ComputationTargetResolver) newValue); return; case 173967376: // historicalTimeSeriesMaster setHistoricalTimeSeriesMaster((HistoricalTimeSeriesMaster) newValue); return; case 1808868758: // userPositionMaster setUserPositionMaster((PositionMaster) newValue); return; case 686514815: // userPortfolioMaster setUserPortfolioMaster((PortfolioMaster) newValue); return; case -952415422: // viewDefinitionRepository setViewDefinitionRepository((ViewDefinitionRepository) newValue); return; case -1371772371: // userViewDefinitionRepository setUserViewDefinitionRepository((ManageableViewDefinitionRepository) newValue); return; case -1697555603: // viewProcessor setViewProcessor((ViewProcessor) newValue); return; case 940303425: // portfolioAggregationFunctions setPortfolioAggregationFunctions((PortfolioAggregationFunctions) newValue); return; case 2090650860: // marketDataSnapshotMaster setMarketDataSnapshotMaster((MarketDataSnapshotMaster) newValue); return; case 3599307: // user setUser((UserPrincipal) newValue); return; case -917704420: // fudgeContext setFudgeContext((FudgeContext) newValue); return; } super.propertySet(propertyName, newValue, quiet); } @Override protected void validate() { JodaBeanUtils.notNull(_configMaster, "configMaster"); JodaBeanUtils.notNull(_securityMaster, "securityMaster"); JodaBeanUtils.notNull(_securitySource, "securitySource"); JodaBeanUtils.notNull(_positionMaster, "positionMaster"); JodaBeanUtils.notNull(_portfolioMaster, "portfolioMaster"); JodaBeanUtils.notNull(_positionSource, "positionSource"); JodaBeanUtils.notNull(_computationTargetResolver, "computationTargetResolver"); JodaBeanUtils.notNull(_historicalTimeSeriesMaster, "historicalTimeSeriesMaster"); JodaBeanUtils.notNull(_userPositionMaster, "userPositionMaster"); JodaBeanUtils.notNull(_userPortfolioMaster, "userPortfolioMaster"); JodaBeanUtils.notNull(_viewDefinitionRepository, "viewDefinitionRepository"); JodaBeanUtils.notNull(_userViewDefinitionRepository, "userViewDefinitionRepository"); JodaBeanUtils.notNull(_viewProcessor, "viewProcessor"); JodaBeanUtils.notNull(_portfolioAggregationFunctions, "portfolioAggregationFunctions"); JodaBeanUtils.notNull(_marketDataSnapshotMaster, "marketDataSnapshotMaster"); JodaBeanUtils.notNull(_user, "user"); JodaBeanUtils.notNull(_fudgeContext, "fudgeContext"); super.validate(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { WebsiteViewportsComponentFactory other = (WebsiteViewportsComponentFactory) obj; return JodaBeanUtils.equal(getConfigMaster(), other.getConfigMaster()) && JodaBeanUtils.equal(getSecurityMaster(), other.getSecurityMaster()) && JodaBeanUtils.equal(getSecuritySource(), other.getSecuritySource()) && JodaBeanUtils.equal(getPositionMaster(), other.getPositionMaster()) && JodaBeanUtils.equal(getPortfolioMaster(), other.getPortfolioMaster()) && JodaBeanUtils.equal(getPositionSource(), other.getPositionSource()) && JodaBeanUtils.equal(getComputationTargetResolver(), other.getComputationTargetResolver()) && JodaBeanUtils.equal(getHistoricalTimeSeriesMaster(), other.getHistoricalTimeSeriesMaster()) && JodaBeanUtils.equal(getUserPositionMaster(), other.getUserPositionMaster()) && JodaBeanUtils.equal(getUserPortfolioMaster(), other.getUserPortfolioMaster()) && JodaBeanUtils.equal(getViewDefinitionRepository(), other.getViewDefinitionRepository()) && JodaBeanUtils.equal(getUserViewDefinitionRepository(), other.getUserViewDefinitionRepository()) && JodaBeanUtils.equal(getViewProcessor(), other.getViewProcessor()) && JodaBeanUtils.equal(getPortfolioAggregationFunctions(), other.getPortfolioAggregationFunctions()) && JodaBeanUtils.equal(getMarketDataSnapshotMaster(), other.getMarketDataSnapshotMaster()) && JodaBeanUtils.equal(getUser(), other.getUser()) && JodaBeanUtils.equal(getFudgeContext(), other.getFudgeContext()) && super.equals(obj); } return false; } @Override public int hashCode() { int hash = 7; hash += hash * 31 + JodaBeanUtils.hashCode(getConfigMaster()); hash += hash * 31 + JodaBeanUtils.hashCode(getSecurityMaster()); hash += hash * 31 + JodaBeanUtils.hashCode(getSecuritySource()); hash += hash * 31 + JodaBeanUtils.hashCode(getPositionMaster()); hash += hash * 31 + JodaBeanUtils.hashCode(getPortfolioMaster()); hash += hash * 31 + JodaBeanUtils.hashCode(getPositionSource()); hash += hash * 31 + JodaBeanUtils.hashCode(getComputationTargetResolver()); hash += hash * 31 + JodaBeanUtils.hashCode(getHistoricalTimeSeriesMaster()); hash += hash * 31 + JodaBeanUtils.hashCode(getUserPositionMaster()); hash += hash * 31 + JodaBeanUtils.hashCode(getUserPortfolioMaster()); hash += hash * 31 + JodaBeanUtils.hashCode(getViewDefinitionRepository()); hash += hash * 31 + JodaBeanUtils.hashCode(getUserViewDefinitionRepository()); hash += hash * 31 + JodaBeanUtils.hashCode(getViewProcessor()); hash += hash * 31 + JodaBeanUtils.hashCode(getPortfolioAggregationFunctions()); hash += hash * 31 + JodaBeanUtils.hashCode(getMarketDataSnapshotMaster()); hash += hash * 31 + JodaBeanUtils.hashCode(getUser()); hash += hash * 31 + JodaBeanUtils.hashCode(getFudgeContext()); return hash ^ super.hashCode(); } /** * Gets the configuration master. * @return the value of the property, not null */ public ConfigMaster getConfigMaster() { return _configMaster; } /** * Sets the configuration master. * @param configMaster the new value of the property, not null */ public void setConfigMaster(ConfigMaster configMaster) { JodaBeanUtils.notNull(configMaster, "configMaster"); this._configMaster = configMaster; } /** * Gets the the {@code configMaster} property. * @return the property, not null */ public final Property<ConfigMaster> configMaster() { return metaBean().configMaster().createProperty(this); } /** * Gets the security master. * @return the value of the property, not null */ public SecurityMaster getSecurityMaster() { return _securityMaster; } /** * Sets the security master. * @param securityMaster the new value of the property, not null */ public void setSecurityMaster(SecurityMaster securityMaster) { JodaBeanUtils.notNull(securityMaster, "securityMaster"); this._securityMaster = securityMaster; } /** * Gets the the {@code securityMaster} property. * @return the property, not null */ public final Property<SecurityMaster> securityMaster() { return metaBean().securityMaster().createProperty(this); } /** * Gets the security source. * @return the value of the property, not null */ public SecuritySource getSecuritySource() { return _securitySource; } /** * Sets the security source. * @param securitySource the new value of the property, not null */ public void setSecuritySource(SecuritySource securitySource) { JodaBeanUtils.notNull(securitySource, "securitySource"); this._securitySource = securitySource; } /** * Gets the the {@code securitySource} property. * @return the property, not null */ public final Property<SecuritySource> securitySource() { return metaBean().securitySource().createProperty(this); } /** * Gets the position master. * @return the value of the property, not null */ public PositionMaster getPositionMaster() { return _positionMaster; } /** * Sets the position master. * @param positionMaster the new value of the property, not null */ public void setPositionMaster(PositionMaster positionMaster) { JodaBeanUtils.notNull(positionMaster, "positionMaster"); this._positionMaster = positionMaster; } /** * Gets the the {@code positionMaster} property. * @return the property, not null */ public final Property<PositionMaster> positionMaster() { return metaBean().positionMaster().createProperty(this); } /** * Gets the portfolio master. * @return the value of the property, not null */ public PortfolioMaster getPortfolioMaster() { return _portfolioMaster; } /** * Sets the portfolio master. * @param portfolioMaster the new value of the property, not null */ public void setPortfolioMaster(PortfolioMaster portfolioMaster) { JodaBeanUtils.notNull(portfolioMaster, "portfolioMaster"); this._portfolioMaster = portfolioMaster; } /** * Gets the the {@code portfolioMaster} property. * @return the property, not null */ public final Property<PortfolioMaster> portfolioMaster() { return metaBean().portfolioMaster().createProperty(this); } /** * Gets the position source. * @return the value of the property, not null */ public PositionSource getPositionSource() { return _positionSource; } /** * Sets the position source. * @param positionSource the new value of the property, not null */ public void setPositionSource(PositionSource positionSource) { JodaBeanUtils.notNull(positionSource, "positionSource"); this._positionSource = positionSource; } /** * Gets the the {@code positionSource} property. * @return the property, not null */ public final Property<PositionSource> positionSource() { return metaBean().positionSource().createProperty(this); } /** * Gets the computation target resolver. * @return the value of the property, not null */ public ComputationTargetResolver getComputationTargetResolver() { return _computationTargetResolver; } /** * Sets the computation target resolver. * @param computationTargetResolver the new value of the property, not null */ public void setComputationTargetResolver(ComputationTargetResolver computationTargetResolver) { JodaBeanUtils.notNull(computationTargetResolver, "computationTargetResolver"); this._computationTargetResolver = computationTargetResolver; } /** * Gets the the {@code computationTargetResolver} property. * @return the property, not null */ public final Property<ComputationTargetResolver> computationTargetResolver() { return metaBean().computationTargetResolver().createProperty(this); } /** * Gets the time-series master. * @return the value of the property, not null */ public HistoricalTimeSeriesMaster getHistoricalTimeSeriesMaster() { return _historicalTimeSeriesMaster; } /** * Sets the time-series master. * @param historicalTimeSeriesMaster the new value of the property, not null */ public void setHistoricalTimeSeriesMaster(HistoricalTimeSeriesMaster historicalTimeSeriesMaster) { JodaBeanUtils.notNull(historicalTimeSeriesMaster, "historicalTimeSeriesMaster"); this._historicalTimeSeriesMaster = historicalTimeSeriesMaster; } /** * Gets the the {@code historicalTimeSeriesMaster} property. * @return the property, not null */ public final Property<HistoricalTimeSeriesMaster> historicalTimeSeriesMaster() { return metaBean().historicalTimeSeriesMaster().createProperty(this); } /** * Gets the user master. * @return the value of the property, not null */ public PositionMaster getUserPositionMaster() { return _userPositionMaster; } /** * Sets the user master. * @param userPositionMaster the new value of the property, not null */ public void setUserPositionMaster(PositionMaster userPositionMaster) { JodaBeanUtils.notNull(userPositionMaster, "userPositionMaster"); this._userPositionMaster = userPositionMaster; } /** * Gets the the {@code userPositionMaster} property. * @return the property, not null */ public final Property<PositionMaster> userPositionMaster() { return metaBean().userPositionMaster().createProperty(this); } /** * Gets the user master. * @return the value of the property, not null */ public PortfolioMaster getUserPortfolioMaster() { return _userPortfolioMaster; } /** * Sets the user master. * @param userPortfolioMaster the new value of the property, not null */ public void setUserPortfolioMaster(PortfolioMaster userPortfolioMaster) { JodaBeanUtils.notNull(userPortfolioMaster, "userPortfolioMaster"); this._userPortfolioMaster = userPortfolioMaster; } /** * Gets the the {@code userPortfolioMaster} property. * @return the property, not null */ public final Property<PortfolioMaster> userPortfolioMaster() { return metaBean().userPortfolioMaster().createProperty(this); } /** * Gets the combined view definition repository. * @return the value of the property, not null */ public ViewDefinitionRepository getViewDefinitionRepository() { return _viewDefinitionRepository; } /** * Sets the combined view definition repository. * @param viewDefinitionRepository the new value of the property, not null */ public void setViewDefinitionRepository(ViewDefinitionRepository viewDefinitionRepository) { JodaBeanUtils.notNull(viewDefinitionRepository, "viewDefinitionRepository"); this._viewDefinitionRepository = viewDefinitionRepository; } /** * Gets the the {@code viewDefinitionRepository} property. * @return the property, not null */ public final Property<ViewDefinitionRepository> viewDefinitionRepository() { return metaBean().viewDefinitionRepository().createProperty(this); } /** * Gets the user view definition repository. * @return the value of the property, not null */ public ManageableViewDefinitionRepository getUserViewDefinitionRepository() { return _userViewDefinitionRepository; } /** * Sets the user view definition repository. * @param userViewDefinitionRepository the new value of the property, not null */ public void setUserViewDefinitionRepository(ManageableViewDefinitionRepository userViewDefinitionRepository) { JodaBeanUtils.notNull(userViewDefinitionRepository, "userViewDefinitionRepository"); this._userViewDefinitionRepository = userViewDefinitionRepository; } /** * Gets the the {@code userViewDefinitionRepository} property. * @return the property, not null */ public final Property<ManageableViewDefinitionRepository> userViewDefinitionRepository() { return metaBean().userViewDefinitionRepository().createProperty(this); } /** * Gets the view processor. * @return the value of the property, not null */ public ViewProcessor getViewProcessor() { return _viewProcessor; } /** * Sets the view processor. * @param viewProcessor the new value of the property, not null */ public void setViewProcessor(ViewProcessor viewProcessor) { JodaBeanUtils.notNull(viewProcessor, "viewProcessor"); this._viewProcessor = viewProcessor; } /** * Gets the the {@code viewProcessor} property. * @return the property, not null */ public final Property<ViewProcessor> viewProcessor() { return metaBean().viewProcessor().createProperty(this); } /** * Gets the portfolio aggregation functions. * @return the value of the property, not null */ public PortfolioAggregationFunctions getPortfolioAggregationFunctions() { return _portfolioAggregationFunctions; } /** * Sets the portfolio aggregation functions. * @param portfolioAggregationFunctions the new value of the property, not null */ public void setPortfolioAggregationFunctions(PortfolioAggregationFunctions portfolioAggregationFunctions) { JodaBeanUtils.notNull(portfolioAggregationFunctions, "portfolioAggregationFunctions"); this._portfolioAggregationFunctions = portfolioAggregationFunctions; } /** * Gets the the {@code portfolioAggregationFunctions} property. * @return the property, not null */ public final Property<PortfolioAggregationFunctions> portfolioAggregationFunctions() { return metaBean().portfolioAggregationFunctions().createProperty(this); } /** * Gets the market data snapshot master. * @return the value of the property, not null */ public MarketDataSnapshotMaster getMarketDataSnapshotMaster() { return _marketDataSnapshotMaster; } /** * Sets the market data snapshot master. * @param marketDataSnapshotMaster the new value of the property, not null */ public void setMarketDataSnapshotMaster(MarketDataSnapshotMaster marketDataSnapshotMaster) { JodaBeanUtils.notNull(marketDataSnapshotMaster, "marketDataSnapshotMaster"); this._marketDataSnapshotMaster = marketDataSnapshotMaster; } /** * Gets the the {@code marketDataSnapshotMaster} property. * @return the property, not null */ public final Property<MarketDataSnapshotMaster> marketDataSnapshotMaster() { return metaBean().marketDataSnapshotMaster().createProperty(this); } /** * Gets the user. * @return the value of the property, not null */ public UserPrincipal getUser() { return _user; } /** * Sets the user. * @param user the new value of the property, not null */ public void setUser(UserPrincipal user) { JodaBeanUtils.notNull(user, "user"); this._user = user; } /** * Gets the the {@code user} property. * @return the property, not null */ public final Property<UserPrincipal> user() { return metaBean().user().createProperty(this); } /** * Gets the fudge context. * @return the value of the property, not null */ public FudgeContext getFudgeContext() { return _fudgeContext; } /** * Sets the fudge context. * @param fudgeContext the new value of the property, not null */ public void setFudgeContext(FudgeContext fudgeContext) { JodaBeanUtils.notNull(fudgeContext, "fudgeContext"); this._fudgeContext = fudgeContext; } /** * Gets the the {@code fudgeContext} property. * @return the property, not null */ public final Property<FudgeContext> fudgeContext() { return metaBean().fudgeContext().createProperty(this); } /** * The meta-bean for {@code WebsiteViewportsComponentFactory}. */ public static class Meta extends AbstractComponentFactory.Meta { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code configMaster} property. */ private final MetaProperty<ConfigMaster> _configMaster = DirectMetaProperty.ofReadWrite( this, "configMaster", WebsiteViewportsComponentFactory.class, ConfigMaster.class); /** * The meta-property for the {@code securityMaster} property. */ private final MetaProperty<SecurityMaster> _securityMaster = DirectMetaProperty.ofReadWrite( this, "securityMaster", WebsiteViewportsComponentFactory.class, SecurityMaster.class); /** * The meta-property for the {@code securitySource} property. */ private final MetaProperty<SecuritySource> _securitySource = DirectMetaProperty.ofReadWrite( this, "securitySource", WebsiteViewportsComponentFactory.class, SecuritySource.class); /** * The meta-property for the {@code positionMaster} property. */ private final MetaProperty<PositionMaster> _positionMaster = DirectMetaProperty.ofReadWrite( this, "positionMaster", WebsiteViewportsComponentFactory.class, PositionMaster.class); /** * The meta-property for the {@code portfolioMaster} property. */ private final MetaProperty<PortfolioMaster> _portfolioMaster = DirectMetaProperty.ofReadWrite( this, "portfolioMaster", WebsiteViewportsComponentFactory.class, PortfolioMaster.class); /** * The meta-property for the {@code positionSource} property. */ private final MetaProperty<PositionSource> _positionSource = DirectMetaProperty.ofReadWrite( this, "positionSource", WebsiteViewportsComponentFactory.class, PositionSource.class); /** * The meta-property for the {@code computationTargetResolver} property. */ private final MetaProperty<ComputationTargetResolver> _computationTargetResolver = DirectMetaProperty.ofReadWrite( this, "computationTargetResolver", WebsiteViewportsComponentFactory.class, ComputationTargetResolver.class); /** * The meta-property for the {@code historicalTimeSeriesMaster} property. */ private final MetaProperty<HistoricalTimeSeriesMaster> _historicalTimeSeriesMaster = DirectMetaProperty.ofReadWrite( this, "historicalTimeSeriesMaster", WebsiteViewportsComponentFactory.class, HistoricalTimeSeriesMaster.class); /** * The meta-property for the {@code userPositionMaster} property. */ private final MetaProperty<PositionMaster> _userPositionMaster = DirectMetaProperty.ofReadWrite( this, "userPositionMaster", WebsiteViewportsComponentFactory.class, PositionMaster.class); /** * The meta-property for the {@code userPortfolioMaster} property. */ private final MetaProperty<PortfolioMaster> _userPortfolioMaster = DirectMetaProperty.ofReadWrite( this, "userPortfolioMaster", WebsiteViewportsComponentFactory.class, PortfolioMaster.class); /** * The meta-property for the {@code viewDefinitionRepository} property. */ private final MetaProperty<ViewDefinitionRepository> _viewDefinitionRepository = DirectMetaProperty.ofReadWrite( this, "viewDefinitionRepository", WebsiteViewportsComponentFactory.class, ViewDefinitionRepository.class); /** * The meta-property for the {@code userViewDefinitionRepository} property. */ private final MetaProperty<ManageableViewDefinitionRepository> _userViewDefinitionRepository = DirectMetaProperty.ofReadWrite( this, "userViewDefinitionRepository", WebsiteViewportsComponentFactory.class, ManageableViewDefinitionRepository.class); /** * The meta-property for the {@code viewProcessor} property. */ private final MetaProperty<ViewProcessor> _viewProcessor = DirectMetaProperty.ofReadWrite( this, "viewProcessor", WebsiteViewportsComponentFactory.class, ViewProcessor.class); /** * The meta-property for the {@code portfolioAggregationFunctions} property. */ private final MetaProperty<PortfolioAggregationFunctions> _portfolioAggregationFunctions = DirectMetaProperty.ofReadWrite( this, "portfolioAggregationFunctions", WebsiteViewportsComponentFactory.class, PortfolioAggregationFunctions.class); /** * The meta-property for the {@code marketDataSnapshotMaster} property. */ private final MetaProperty<MarketDataSnapshotMaster> _marketDataSnapshotMaster = DirectMetaProperty.ofReadWrite( this, "marketDataSnapshotMaster", WebsiteViewportsComponentFactory.class, MarketDataSnapshotMaster.class); /** * The meta-property for the {@code user} property. */ private final MetaProperty<UserPrincipal> _user = DirectMetaProperty.ofReadWrite( this, "user", WebsiteViewportsComponentFactory.class, UserPrincipal.class); /** * The meta-property for the {@code fudgeContext} property. */ private final MetaProperty<FudgeContext> _fudgeContext = DirectMetaProperty.ofReadWrite( this, "fudgeContext", WebsiteViewportsComponentFactory.class, FudgeContext.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap( this, (DirectMetaPropertyMap) super.metaPropertyMap(), "configMaster", "securityMaster", "securitySource", "positionMaster", "portfolioMaster", "positionSource", "computationTargetResolver", "historicalTimeSeriesMaster", "userPositionMaster", "userPortfolioMaster", "viewDefinitionRepository", "userViewDefinitionRepository", "viewProcessor", "portfolioAggregationFunctions", "marketDataSnapshotMaster", "user", "fudgeContext"); /** * Restricted constructor. */ protected Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case 10395716: // configMaster return _configMaster; case -887218750: // securityMaster return _securityMaster; case -702456965: // securitySource return _securitySource; case -1840419605: // positionMaster return _positionMaster; case -772274742: // portfolioMaster return _portfolioMaster; case -1655657820: // positionSource return _positionSource; case 1562222174: // computationTargetResolver return _computationTargetResolver; case 173967376: // historicalTimeSeriesMaster return _historicalTimeSeriesMaster; case 1808868758: // userPositionMaster return _userPositionMaster; case 686514815: // userPortfolioMaster return _userPortfolioMaster; case -952415422: // viewDefinitionRepository return _viewDefinitionRepository; case -1371772371: // userViewDefinitionRepository return _userViewDefinitionRepository; case -1697555603: // viewProcessor return _viewProcessor; case 940303425: // portfolioAggregationFunctions return _portfolioAggregationFunctions; case 2090650860: // marketDataSnapshotMaster return _marketDataSnapshotMaster; case 3599307: // user return _user; case -917704420: // fudgeContext return _fudgeContext; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder<? extends WebsiteViewportsComponentFactory> builder() { return new DirectBeanBuilder<WebsiteViewportsComponentFactory>(new WebsiteViewportsComponentFactory()); } @Override public Class<? extends WebsiteViewportsComponentFactory> beanType() { return WebsiteViewportsComponentFactory.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return _metaPropertyMap$; } /** * The meta-property for the {@code configMaster} property. * @return the meta-property, not null */ public final MetaProperty<ConfigMaster> configMaster() { return _configMaster; } /** * The meta-property for the {@code securityMaster} property. * @return the meta-property, not null */ public final MetaProperty<SecurityMaster> securityMaster() { return _securityMaster; } /** * The meta-property for the {@code securitySource} property. * @return the meta-property, not null */ public final MetaProperty<SecuritySource> securitySource() { return _securitySource; } /** * The meta-property for the {@code positionMaster} property. * @return the meta-property, not null */ public final MetaProperty<PositionMaster> positionMaster() { return _positionMaster; } /** * The meta-property for the {@code portfolioMaster} property. * @return the meta-property, not null */ public final MetaProperty<PortfolioMaster> portfolioMaster() { return _portfolioMaster; } /** * The meta-property for the {@code positionSource} property. * @return the meta-property, not null */ public final MetaProperty<PositionSource> positionSource() { return _positionSource; } /** * The meta-property for the {@code computationTargetResolver} property. * @return the meta-property, not null */ public final MetaProperty<ComputationTargetResolver> computationTargetResolver() { return _computationTargetResolver; } /** * The meta-property for the {@code historicalTimeSeriesMaster} property. * @return the meta-property, not null */ public final MetaProperty<HistoricalTimeSeriesMaster> historicalTimeSeriesMaster() { return _historicalTimeSeriesMaster; } /** * The meta-property for the {@code userPositionMaster} property. * @return the meta-property, not null */ public final MetaProperty<PositionMaster> userPositionMaster() { return _userPositionMaster; } /** * The meta-property for the {@code userPortfolioMaster} property. * @return the meta-property, not null */ public final MetaProperty<PortfolioMaster> userPortfolioMaster() { return _userPortfolioMaster; } /** * The meta-property for the {@code viewDefinitionRepository} property. * @return the meta-property, not null */ public final MetaProperty<ViewDefinitionRepository> viewDefinitionRepository() { return _viewDefinitionRepository; } /** * The meta-property for the {@code userViewDefinitionRepository} property. * @return the meta-property, not null */ public final MetaProperty<ManageableViewDefinitionRepository> userViewDefinitionRepository() { return _userViewDefinitionRepository; } /** * The meta-property for the {@code viewProcessor} property. * @return the meta-property, not null */ public final MetaProperty<ViewProcessor> viewProcessor() { return _viewProcessor; } /** * The meta-property for the {@code portfolioAggregationFunctions} property. * @return the meta-property, not null */ public final MetaProperty<PortfolioAggregationFunctions> portfolioAggregationFunctions() { return _portfolioAggregationFunctions; } /** * The meta-property for the {@code marketDataSnapshotMaster} property. * @return the meta-property, not null */ public final MetaProperty<MarketDataSnapshotMaster> marketDataSnapshotMaster() { return _marketDataSnapshotMaster; } /** * The meta-property for the {@code user} property. * @return the meta-property, not null */ public final MetaProperty<UserPrincipal> user() { return _user; } /** * The meta-property for the {@code fudgeContext} property. * @return the meta-property, not null */ public final MetaProperty<FudgeContext> fudgeContext() { return _fudgeContext; } } ///CLOVER:ON }
package nl.idgis.publisher.service.geoserver.rest; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.apache.commons.codec.binary.Base64; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.Response; import akka.event.LoggingAdapter; import nl.idgis.publisher.utils.FutureUtils; public class DefaultGeoServerRest implements GeoServerRest { private static final String RECURSE = "?recurse=true"; private final LoggingAdapter log; private final String authorization; private final String restLocation; private final String serviceLocation; private final FutureUtils f; private final AsyncHttpClient asyncHttpClient; public DefaultGeoServerRest(FutureUtils f, LoggingAdapter log, String serviceLocation, String user, String password) throws Exception { this.f = f; this.log = log; this.restLocation = serviceLocation + "rest/"; this.serviceLocation = serviceLocation; this.authorization = "Basic " + new String(Base64.encodeBase64((user + ":" + password).getBytes())); asyncHttpClient = new AsyncHttpClient(); } private CompletableFuture<Optional<Document>> get(String path) { return get(path, true, false); } private CompletableFuture<Optional<Document>> get(String path, boolean appendSuffix, boolean namespaceAware) { String url = path + (appendSuffix ? ".xml" : ""); log.debug("fetching {}", url); CompletableFuture<Optional<Document>> future = new CompletableFuture<>(); asyncHttpClient.prepareGet(url) .addHeader("Authorization", authorization) .execute(new AsyncCompletionHandler<Response>() { @Override public Response onCompleted(Response response) throws Exception { try { int responseCode = response.getStatusCode(); if(responseCode == HttpURLConnection.HTTP_OK) { InputStream stream = response.getResponseBodyAsStream(); Document document = parse(stream, namespaceAware); stream.close(); future.complete(Optional.of(document)); } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND) { future.complete(Optional.empty()); } else { future.completeExceptionally(new GeoServerException(path, responseCode)); } } catch(Exception e) { future.completeExceptionally(new GeoServerException(path, e)); } return response; } @Override public void onThrowable(Throwable t){ future.completeExceptionally(t); } }); return future; } private CompletableFuture<Void> delete(String path) { log.debug("deleting {}", path); CompletableFuture<Void> future = new CompletableFuture<>(); asyncHttpClient.prepareDelete(path) .addHeader("Authorization", authorization) .execute(new AsyncCompletionHandler<Response>() { @Override public Response onCompleted(Response response) throws Exception { int responseCode = response.getStatusCode(); if(responseCode != HttpURLConnection.HTTP_OK) { future.completeExceptionally(new GeoServerException(path, responseCode)); } else { future.complete(null); } return response; } @Override public void onThrowable(Throwable t){ future.completeExceptionally(new GeoServerException(path, t)); } }); return future; } private CompletableFuture<Void> put(String path, byte[] document) { return put(path, document, "text/xml"); } private CompletableFuture<Void> put(String path, byte[] document, String contentType) { log.debug("put {}", path); CompletableFuture<Void> future = new CompletableFuture<>(); asyncHttpClient.preparePut(path) .addHeader("Authorization", authorization) .addHeader("Content-type", contentType) .setBody(document) .execute(new AsyncCompletionHandler<Response>() { @Override public Response onCompleted(Response response) throws Exception { int responseCode = response.getStatusCode(); if(responseCode != HttpURLConnection.HTTP_OK) { future.completeExceptionally(new GeoServerException(path, responseCode)); } else { future.complete(null); } return response; } @Override public void onThrowable(Throwable t){ future.completeExceptionally(new GeoServerException(path, t)); } }); return future; } private CompletableFuture<Void> post(String path, byte[] document) { return post(path, document, "text/xml"); } private CompletableFuture<Void> post(String path, byte[] document, String contentType) { log.debug("posting {}", path); CompletableFuture<Void> future = new CompletableFuture<>(); asyncHttpClient.preparePost(path) .addHeader("Authorization", authorization) .addHeader("Content-type", contentType) .setBody(document) .execute(new AsyncCompletionHandler<Response>() { @Override public Response onCompleted(Response response) throws Exception { int responseCode = response.getStatusCode(); if(responseCode != HttpURLConnection.HTTP_CREATED) { future.completeExceptionally(new GeoServerException(path, responseCode)); } else { future.complete(null); } return response; } @Override public void onThrowable(Throwable t){ future.completeExceptionally(new GeoServerException(path, t)); } }); return future; } private String getServiceSettingsPath(Workspace workspace, ServiceType serviceType) { return restLocation + "services/" + serviceType.name().toLowerCase() + "/workspaces/" + workspace.getName() + "/settings"; } @Override public CompletableFuture<Void> putServiceSettings(Workspace workspace, ServiceType serviceType, ServiceSettings serviceSettings) { try { String serviceTypeName = serviceType.name().toLowerCase(); // we have to use the default settings as a template otherwise all kind of // essential settings are set to null, causing NPE when using the service. InputStream defaultServiceSettings = getClass().getResourceAsStream( "default-" + serviceTypeName + "-settings.xml"); Objects.requireNonNull(defaultServiceSettings); Document document = parse(defaultServiceSettings); XPath xpath = XPathFactory.newInstance().newXPath(); String title = serviceSettings.getTitle(); if(title != null) { Node titleNode = (Node)xpath.evaluate(serviceTypeName + "/title", document, XPathConstants.NODE); titleNode.setTextContent(title); } String abstr = serviceSettings.getAbstract(); if(abstr != null) { Node abstractNode = (Node)xpath.evaluate(serviceTypeName + "/abstrct", document, XPathConstants.NODE); abstractNode.setTextContent(abstr); } List<String> keywords = serviceSettings.getKeywords(); if(keywords != null) { Node keywordsNode = (Node)xpath.evaluate(serviceTypeName + "/keywords", document, XPathConstants.NODE); for(String keyword : keywords) { Node keywordNode = document.createElement("keyword"); keywordNode.appendChild(document.createTextNode(keyword)); keywordsNode.appendChild(keywordNode); } } return put(getServiceSettingsPath(workspace, serviceType), serialize(document)); } catch(Exception e) { return f.failed(e); } } @Override public CompletableFuture<Void> postWorkspace(Workspace workspace) { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); XMLOutputFactory of = XMLOutputFactory.newInstance(); XMLStreamWriter sw = of.createXMLStreamWriter(os); sw.writeStartDocument(); sw.writeStartElement("workspace"); sw.writeStartElement("name"); sw.writeCharacters(workspace.getName()); sw.writeEndElement(); sw.writeEndElement(); sw.writeEndDocument(); sw.close(); os.close(); return post(getWorkspacesPath(), os.toByteArray()); } catch(Exception e) { return f.failed(e); } } private String getWorkspacePath(String workspaceId) { return getWorkspacesPath() + "/" + workspaceId; } private String getWorkspacePath(Workspace workspace) { return getWorkspacePath(workspace.getName()); } private String getWorkspacesPath() { return restLocation + "workspaces"; } @Override public CompletableFuture<List<Workspace>> getWorkspaces() { CompletableFuture<List<Workspace>> future = new CompletableFuture<>(); get(getWorkspacesPath()).whenComplete((optionalDocument, t) -> { if(t != null) { future.completeExceptionally(t); } else { try { Document document = optionalDocument.get(); List<Workspace> retval = new ArrayList<>(); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList result = (NodeList)xpath.evaluate("/workspaces/workspace/name/text()", document, XPathConstants.NODESET); for(int i = 0; i < result.getLength(); i++) { Node n = result.item(i); retval.add(new Workspace(n.getTextContent())); } future.complete(retval); } catch(Exception e) { future.completeExceptionally(e); } } }); return future; } @Override public CompletableFuture<Optional<DataStore>> getDataStore(Workspace workspace, String dataStoreName) { CompletableFuture<Optional<DataStore>> future = new CompletableFuture<>(); get(getDataStorePath(workspace, dataStoreName)).whenComplete((optionalDocument, t) -> { if(t != null) { future.completeExceptionally(t); } else { try { if(optionalDocument.isPresent()) { Document document = optionalDocument.get(); XPath xpath = XPathFactory.newInstance().newXPath(); String name = (String)xpath.evaluate("/dataStore/name/text()", document, XPathConstants.STRING); Map<String, String> connectionParameters = new HashMap<>(); NodeList result = (NodeList)xpath.evaluate("/dataStore/connectionParameters/entry", document, XPathConstants.NODESET); for(int i = 0; i < result.getLength(); i++) { Node n = result.item(i); String key = n.getAttributes().getNamedItem("key").getNodeValue(); String value = n.getTextContent(); connectionParameters.put(key, value); } future.complete(Optional.of(new DataStore(name, connectionParameters))); } else { future.complete(Optional.empty()); } } catch(Exception e) { future.completeExceptionally(e); } } }); return future; } private String getDataStorePath(Workspace workspace, String dataStoreName) { return getDataStoresPath(workspace) + "/" + dataStoreName; } private <T> T optionalPresent(Optional<T> optional) { return optional.get(); } @Override public CompletableFuture<List<DataStore>> getDataStores(Workspace workspace) { CompletableFuture<List<CompletableFuture<DataStore>>> future = new CompletableFuture<>(); get(getDataStoresPath(workspace)).whenComplete((optionalDocument, t) -> { if(t != null) { future.completeExceptionally(t); } else { try { Document document = optionalDocument.get(); List<CompletableFuture<DataStore>> retval = new ArrayList<>(); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList result = (NodeList)xpath.evaluate("/dataStores/dataStore/name/text()", document, XPathConstants.NODESET); for(int i = 0; i < result.getLength(); i++) { Node n = result.item(i); retval.add(getDataStore(workspace, n.getTextContent()).thenApply(this::optionalPresent)); } future.complete(retval); } catch(Exception e) { future.completeExceptionally(e); } } }); return future.thenCompose(f::sequence); } @Override public CompletableFuture<Void> postDataStore(Workspace workspace, DataStore dataStore) { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); XMLOutputFactory of = XMLOutputFactory.newInstance(); XMLStreamWriter sw = of.createXMLStreamWriter(os); sw.writeStartDocument(); sw.writeStartElement("dataStore"); sw.writeStartElement("name"); sw.writeCharacters(dataStore.getName()); sw.writeEndElement(); sw.writeStartElement("connectionParameters"); for(Map.Entry<String, String> connectionParameter : dataStore.getConnectionParameters().entrySet()) { sw.writeStartElement(connectionParameter.getKey()); sw.writeCharacters(connectionParameter.getValue()); sw.writeEndElement(); } sw.writeEndElement(); sw.writeEndDocument(); sw.close(); os.close(); return post(getDataStoresPath(workspace), os.toByteArray()); } catch(Exception e) { return f.failed(e); } } private String getDataStoresPath(Workspace workspace) { return getWorkspacesPath() + "/" + workspace.getName() + "/datastores"; } private String getFeatureTypePath(Workspace workspace, DataStore dataStore, FeatureType featureType) { return getFeatureTypePath(workspace, dataStore, featureType.getName()); } private String getFeatureTypePath(Workspace workspace, DataStore dataStore, String featureTypeName) { return getFeatureTypesPath(workspace, dataStore) + "/" + featureTypeName; } private CompletableFuture<Optional<FeatureType>> getFeatureType(Workspace workspace, DataStore dataStore, String featureTypeName) { CompletableFuture<Optional<FeatureType>> future = new CompletableFuture<>(); get(getFeatureTypePath(workspace, dataStore, featureTypeName)).whenComplete((optionalDocument, t) -> { if(t != null) { future.completeExceptionally(t); } else { try { if(optionalDocument.isPresent()) { Document document = optionalDocument.get(); XPath xpath = XPathFactory.newInstance().newXPath(); String name = (String)xpath.evaluate("/featureType/name/text()", document, XPathConstants.STRING); String nativeName = (String)xpath.evaluate("/featureType/nativeName/text()", document, XPathConstants.STRING); String title = (String)xpath.evaluate("/featureType/title/text()", document, XPathConstants.STRING); String abstr = (String)xpath.evaluate("/featureType/abstract/text()", document, XPathConstants.STRING); List<Attribute> attributes = new ArrayList<>(); NodeList result = (NodeList)xpath.evaluate("/featureType/attributes/attribute", document, XPathConstants.NODESET); for(int i = 0; i < result.getLength(); i++) { Node n = result.item(i); String attributeName = xpath.evaluate("name/text()", n); attributes.add(new Attribute(attributeName)); } future.complete(Optional.of(new FeatureType(name, nativeName, title, abstr, Collections.unmodifiableList(attributes)))); } else { future.complete(Optional.empty()); } } catch(Exception e) { future.completeExceptionally(e); } } }); return future; } @Override public CompletableFuture<List<FeatureType>> getFeatureTypes(Workspace workspace, DataStore dataStore) { CompletableFuture<List<CompletableFuture<FeatureType>>> future = new CompletableFuture<>(); get(getFeatureTypesPath(workspace, dataStore)).whenComplete((optionalDocument, t) -> { if(t != null) { future.completeExceptionally(t); } else { try { Document document = optionalDocument.get(); List<CompletableFuture<FeatureType>> retval = new ArrayList<>(); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList result = (NodeList)xpath.evaluate("/featureTypes/featureType/name/text()", document, XPathConstants.NODESET); for(int i = 0; i < result.getLength(); i++) { Node n = result.item(i); retval.add(getFeatureType(workspace, dataStore, n.getTextContent()).thenApply(this::optionalPresent)); } future.complete(retval); } catch(Exception e) { future.completeExceptionally(e); } } }); return future.thenCompose(f::sequence); } @Override public CompletableFuture<Void> putFeatureType(Workspace workspace, DataStore dataStore, FeatureType featureType) { try { return put(getFeatureTypePath(workspace, dataStore, featureType), getFeatureTypeDocument(featureType)); } catch(Exception e) { return f.failed(e); } } private byte[] getFeatureTypeDocument(FeatureType featureType) throws XMLStreamException, IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); XMLOutputFactory of = XMLOutputFactory.newInstance(); XMLStreamWriter sw = of.createXMLStreamWriter(os); sw.writeStartDocument(); sw.writeStartElement("featureType"); sw.writeStartElement("name"); sw.writeCharacters(featureType.getName()); sw.writeEndElement(); String nativeName = featureType.getNativeName(); sw.writeStartElement("nativeName"); sw.writeCharacters(nativeName); sw.writeEndElement(); String title = featureType.getTitle(); if(title != null) { sw.writeStartElement("title"); sw.writeCharacters(title); sw.writeEndElement(); } String abstr = featureType.getAbstract(); if(abstr != null) { sw.writeStartElement("abstract"); sw.writeCharacters(abstr); sw.writeEndElement(); } sw.writeStartElement("enabled"); sw.writeCharacters("true"); sw.writeEndElement(); sw.writeEndElement(); sw.writeEndDocument(); sw.close(); os.close(); return os.toByteArray(); } @Override public CompletableFuture<Void> postFeatureType(Workspace workspace, DataStore dataStore, FeatureType featureType) { try { return post(getFeatureTypesPath(workspace, dataStore), getFeatureTypeDocument(featureType)); } catch(Exception e) { return f.failed(e); } } private String getFeatureTypesPath(Workspace workspace, DataStore dataStore) { return getDataStorePath(workspace, dataStore.getName()) + "/featuretypes"; } @Override public void close() throws IOException { asyncHttpClient.close(); } private String getLayerGroupPath(Workspace workspace, LayerGroup layerGroup) { return getLayerGroupPath(workspace, layerGroup.getName()); } private String getLayerGroupPath(Workspace workspace, String layerGroupName) { return getLayerGroupsPath(workspace) + "/" + layerGroupName; } private CompletableFuture<Optional<LayerGroup>> getLayerGroup(Workspace workspace, String layerGroupName) { CompletableFuture<Optional<LayerGroup>> future = new CompletableFuture<>(); get(getLayerGroupPath(workspace, layerGroupName)).whenComplete((optionalDocument, t) -> { if(t != null) { future.completeExceptionally(t); } else { try { if(optionalDocument.isPresent()) { Document document = optionalDocument.get(); List<LayerRef> layers = new ArrayList<>(); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList result = (NodeList)xpath.evaluate("/layerGroup/publishables/published", document, XPathConstants.NODESET); for(int i = 0; i < result.getLength(); i++) { Node n = result.item(i); String name = (String)xpath.evaluate("name/text()", n, XPathConstants.STRING); String type = (String)xpath.evaluate("@type", n, XPathConstants.STRING); switch(type) { case "layer": layers.add(new LayerRef(name, false)); break; case "layerGroup": layers.add(new LayerRef(name, true)); break; default: throw new IllegalArgumentException("unknown published type: " + type + ", name: " + name); } } String title = getStringValue((Node)xpath.evaluate("/layerGroup/title", document, XPathConstants.NODE)); String abstr = getStringValue((Node)xpath.evaluate("/layerGroup/abstractTxt", document, XPathConstants.NODE)); future.complete(Optional.of(new LayerGroup(layerGroupName, title, abstr, Collections.unmodifiableList(layers)))); } else { future.complete(Optional.empty()); } } catch(Exception e) { future.completeExceptionally(e); } } }); return future; } private String getLayerGroupsPath(Workspace workspace) { return getWorkspacesPath() + "/" + workspace.getName() + "/layergroups"; } @Override public CompletableFuture<List<LayerGroup>> getLayerGroups(Workspace workspace) { CompletableFuture<List<CompletableFuture<LayerGroup>>> future = new CompletableFuture<>(); get(getLayerGroupsPath(workspace)).whenComplete((optionalDocument, t) -> { if(t != null) { future.completeExceptionally(t); } else { try { Document document = optionalDocument.get(); List<CompletableFuture<LayerGroup>> retval = new ArrayList<>(); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList result = (NodeList)xpath.evaluate("/layerGroups/layerGroup/name/text()", document, XPathConstants.NODESET); for(int i = 0; i < result.getLength(); i++) { Node n = result.item(i); retval.add(getLayerGroup(workspace, n.getTextContent()).thenApply(this::optionalPresent)); } future.complete(retval); } catch(Exception e) { future.completeExceptionally(e); } } }); return future.thenCompose(f::sequence); } @Override public CompletableFuture<Void> putLayerGroup(Workspace workspace, LayerGroup layerGroup) { try { return put(getLayerGroupPath(workspace, layerGroup), getLayerGroupDocument(workspace, layerGroup)); } catch(Exception e) { return f.failed(e); } } @Override public CompletableFuture<Void> postLayerGroup(Workspace workspace, LayerGroup layerGroup) { try { return post(getLayerGroupsPath(workspace), getLayerGroupDocument(workspace, layerGroup)); } catch(Exception e) { return f.failed(e); } } private byte[] getLayerGroupDocument(Workspace workspace, LayerGroup layerGroup) throws FactoryConfigurationError, XMLStreamException, IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); XMLOutputFactory of = XMLOutputFactory.newInstance(); XMLStreamWriter sw = of.createXMLStreamWriter(os); sw.writeStartDocument(); sw.writeStartElement("layerGroup"); sw.writeStartElement("name"); sw.writeCharacters(layerGroup.getName()); sw.writeEndElement(); sw.writeStartElement("mode"); sw.writeCharacters("NAMED"); sw.writeEndElement(); String title = layerGroup.getTitle(); if(title != null) { sw.writeStartElement("title"); sw.writeCharacters(title); sw.writeEndElement(); } String abstr = layerGroup.getAbstract(); if(abstr != null) { sw.writeStartElement("abstractTxt"); sw.writeCharacters(abstr); sw.writeEndElement(); } sw.writeStartElement("publishables"); for(LayerRef layerRef : layerGroup.getLayers()) { sw.writeStartElement("published"); sw.writeAttribute("type", layerRef.isGroup() ? "layerGroup" : "layer"); sw.writeStartElement("name"); // layerGroup references without workspace prefix are not correctly resolved sw.writeCharacters(workspace.getName() + ":" + layerRef.getLayerName()); sw.writeEndElement(); sw.writeEndElement(); } sw.writeEndElement(); sw.writeEndElement(); sw.writeEndDocument(); sw.close(); os.close(); return os.toByteArray(); } @Override public CompletableFuture<Void> deleteDataStore(Workspace workspace, DataStore dataStore) { return delete(getDataStorePath(workspace, dataStore.getName()) + RECURSE); } @Override public CompletableFuture<Void> deleteFeatureType(Workspace workspace, DataStore dataStore, FeatureType featureType) { return delete(getFeatureTypePath(workspace, dataStore, featureType.getName()) + RECURSE); } @Override public CompletableFuture<Void> deleteLayerGroup(Workspace workspace, LayerGroup layerGroup) { return delete(getLayerGroupPath(workspace, layerGroup.getName())); } @Override public CompletableFuture<Void> deleteWorkspace(Workspace workspace) { return delete(getWorkspacePath(workspace) + RECURSE); } private String getStringValue(Node n) { if(n == null) { return null; } String retval = n.getTextContent(); if(retval.trim().isEmpty()) { return null; } return retval; } @Override public CompletableFuture<Optional<ServiceSettings>> getServiceSettings(Workspace workspace, ServiceType serviceType) { CompletableFuture<Optional<ServiceSettings>> future = new CompletableFuture<>(); get(getServiceSettingsPath(workspace, serviceType)).whenComplete((optionalDocument, t) -> { if(t != null) { future.completeExceptionally(t); } else { try { if(optionalDocument.isPresent()) { Document document = optionalDocument.get(); XPath xpath = XPathFactory.newInstance().newXPath(); String title = getStringValue((Node)xpath.evaluate(serviceType.name().toLowerCase() + "/title", document, XPathConstants.NODE)); String abstr = getStringValue((Node)xpath.evaluate(serviceType.name().toLowerCase() + "/abstrct", document, XPathConstants.NODE)); List<String> keywords = new ArrayList<>(); NodeList keywordNodes = (NodeList)xpath.evaluate(serviceType.name().toLowerCase() + "/keywords/string", document, XPathConstants.NODESET); if(keywordNodes != null && keywordNodes.getLength() > 0) { for(int i = 0; i < keywordNodes.getLength(); i++) { keywords.add(keywordNodes.item(i).getTextContent()); } } future.complete(Optional.of(new ServiceSettings(title, abstr, keywords))); } else { future.complete(Optional.empty()); } } catch(Exception e) { future.completeExceptionally(e); } } }); return future; } private String getWorkspaceSettingsPath(Workspace workspace) { return getWorkspacePath(workspace) + "/settings"; } @Override public CompletableFuture<WorkspaceSettings> getWorkspaceSettings(Workspace workspace) { CompletableFuture<WorkspaceSettings> future = new CompletableFuture<>(); get(getWorkspaceSettingsPath(workspace)).whenComplete((optionalDocument, t) -> { if(t != null) { future.completeExceptionally(t); } else { try { Document document = optionalDocument.get(); XPath xpath = XPathFactory.newInstance().newXPath(); String address = getStringValue((Node)xpath.evaluate("settings/contact/address", document, XPathConstants.NODE)); String city = getStringValue((Node)xpath.evaluate("settings/contact/addressCity", document, XPathConstants.NODE)); String country = getStringValue((Node)xpath.evaluate("settings/contact/addressCountry", document, XPathConstants.NODE)); String zipcode = getStringValue((Node)xpath.evaluate("settings/contact/addressPostalCode", document, XPathConstants.NODE)); String state = getStringValue((Node)xpath.evaluate("settings/contact/addressState", document, XPathConstants.NODE)); String addressType = getStringValue((Node)xpath.evaluate("settings/contact/addressType", document, XPathConstants.NODE)); String email = getStringValue((Node)xpath.evaluate("settings/contact/contactEmail", document, XPathConstants.NODE)); String fax = getStringValue((Node)xpath.evaluate("settings/contact/contactFacsimile", document, XPathConstants.NODE)); String organization = getStringValue((Node)xpath.evaluate("settings/contact/contactOrganization", document, XPathConstants.NODE)); String contact = getStringValue((Node)xpath.evaluate("settings/contact/contactPerson", document, XPathConstants.NODE)); String position = getStringValue((Node)xpath.evaluate("settings/contact/contactPosition", document, XPathConstants.NODE)); String telephone = getStringValue((Node)xpath.evaluate("settings/contact/contactVoice", document, XPathConstants.NODE)); future.complete(new WorkspaceSettings(contact, organization, position, addressType, address, city, state, zipcode, country, telephone, fax, email)); } catch(Exception e) { future.completeExceptionally(e); } } }); return future; } @Override public CompletableFuture<Void> putWorkspaceSettings(Workspace workspace, WorkspaceSettings workspaceSettings) { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); XMLOutputFactory of = XMLOutputFactory.newInstance(); XMLStreamWriter sw = of.createXMLStreamWriter(os); sw.writeStartDocument(); sw.writeStartElement("settings"); sw.writeStartElement("contact"); sw.writeStartElement("id"); sw.writeCharacters("contact"); sw.writeEndElement(); String address = workspaceSettings.getAddress(); if(address != null) { sw.writeStartElement("address"); sw.writeCharacters(address); sw.writeEndElement(); } String city = workspaceSettings.getCity(); if(city != null) { sw.writeStartElement("addressCity"); sw.writeCharacters(city); sw.writeEndElement(); } String country = workspaceSettings.getCountry(); if(country != null) { sw.writeStartElement("addressCountry"); sw.writeCharacters(country); sw.writeEndElement(); } String zipcode = workspaceSettings.getZipcode(); if(zipcode != null) { sw.writeStartElement("addressPostalCode"); sw.writeCharacters(zipcode); sw.writeEndElement(); } String state = workspaceSettings.getState(); if(state != null) { sw.writeStartElement("addressState"); sw.writeCharacters(state); sw.writeEndElement(); } String addressType = workspaceSettings.getAddressType(); if(addressType != null) { sw.writeStartElement("addressType"); sw.writeCharacters(addressType); sw.writeEndElement(); } String email = workspaceSettings.getEmail(); if(email != null) { sw.writeStartElement("contactEmail"); sw.writeCharacters(email); sw.writeEndElement(); } String fax = workspaceSettings.getFax(); if(fax != null) { sw.writeStartElement("contactFacsimile"); sw.writeCharacters(fax); sw.writeEndElement(); } String organization = workspaceSettings.getOrganization(); if(organization != null) { sw.writeStartElement("contactOrganization"); sw.writeCharacters(organization); sw.writeEndElement(); } String contact = workspaceSettings.getContact(); if(contact != null) { sw.writeStartElement("contactPerson"); sw.writeCharacters(contact); sw.writeEndElement(); } String position = workspaceSettings.getPosition(); if(position != null) { sw.writeStartElement("contactPosition"); sw.writeCharacters(position); sw.writeEndElement(); } String telephone = workspaceSettings.getTelephone(); if(telephone != null) { sw.writeStartElement("contactVoice"); sw.writeCharacters(telephone); sw.writeEndElement(); } sw.writeEndElement(); sw.writeEndElement(); sw.writeEndDocument(); sw.close(); return put(getWorkspaceSettingsPath(workspace), os.toByteArray()); } catch(Exception e) { return f.failed(e); } } @Override public CompletableFuture<Optional<Workspace>> getWorkspace(String workspaceId) { CompletableFuture<Optional<Workspace>> future = new CompletableFuture<>(); get(getWorkspacePath(workspaceId)).whenComplete((optionalDocument, t) -> { if(t != null) { future.completeExceptionally(t); } else { try { if(optionalDocument.isPresent()) { future.complete(Optional.of(new Workspace(workspaceId))); } else { future.complete(Optional.empty()); } } catch(Exception e) { future.completeExceptionally(e); } } }); return future; } private String getStylePath(Style style) { return getStylePath(style.getName()); } private String getStylePath(String styleId) { return getStylesPath() + "/" + styleId; } private String getStylesPath() { return restLocation + "styles"; } @Override public CompletableFuture<Optional<Style>> getStyle(String styleId) { CompletableFuture<Optional<Style>> future = new CompletableFuture<>(); CompletableFuture<String> fileNameFuture = new CompletableFuture<>(); fileNameFuture.thenAccept(fileName -> { // we use an alternative end-point here because the one in /rest // wrongly raises 404 in some cases. get(serviceLocation + "/styles/" + fileName, false, true).whenComplete((optionalDocument, t) -> { if(t != null) { future.completeExceptionally(t); } else { try { future.complete(Optional.of(new Style(styleId, optionalDocument.get()))); } catch(Exception e) { future.completeExceptionally(e); } } }); }); get(getStylePath(styleId)).whenComplete((optionalDocument, t) -> { if(t != null) { future.completeExceptionally(t); } else { try { if(optionalDocument.isPresent()) { Document document = optionalDocument.get(); XPath xpath = XPathFactory.newInstance().newXPath(); fileNameFuture.complete((String)xpath.evaluate("style/filename", document, XPathConstants.STRING)); } else { future.complete(Optional.empty()); } } catch(Exception e) { future.completeExceptionally(e); } } }); return future; } @Override public CompletableFuture<List<Style>> getStyles() { CompletableFuture<List<CompletableFuture<Style>>> future = new CompletableFuture<>(); get(getStylesPath()).whenComplete((optionalDocument, t) -> { if(t != null) { future.completeExceptionally(t); } else { try { List<CompletableFuture<Style>> retval = new ArrayList<>(); Document document = optionalDocument.get(); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList styleNameNodes = (NodeList)xpath.evaluate("styles/style/name", document, XPathConstants.NODESET); for(int i = 0; i < styleNameNodes.getLength(); i++) { Node styleNameNode = styleNameNodes.item(i); retval.add(getStyle(styleNameNode.getTextContent()).thenApply(this::optionalPresent)); } future.complete(retval); } catch(Exception e) { future.completeExceptionally(e); } } }); return future.thenCompose(f::sequence); } @Override public CompletableFuture<Void> postStyle(Style style) { try { Document sld = style.getSld(); return post(getStylesPath() + "?name=" + style.getName(), serialize(sld), getStyleContentType(sld)); } catch(Exception e) { return f.failed(e); } } @Override public CompletableFuture<Void> putStyle(Style style) { try { Document sld = style.getSld(); return put(getStylePath(style.getName()), serialize(sld), getStyleContentType(sld)); } catch(Exception e) { return f.failed(e); } } private String getStyleContentType(Document sld) { String contentType; Element root = sld.getDocumentElement(); if(root.getLocalName().equals("StyledLayerDescriptor")) { String version = root.getAttribute("version"); if("1.0.0".equals(version)) { contentType = "application/vnd.ogc.sld+xml"; } else if("1.1.0".equals(version)) { contentType = "application/vnd.ogc.se+xml"; } else { throw new IllegalStateException("expected: StyledLayerDescriptor[@version = '1.0.0' or @version = '1.1.0']"); } } else { throw new IllegalStateException("expected: StyledLayerDescriptor"); } return contentType; } private byte[] serialize(Document sld) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException { ByteArrayOutputStream os = new ByteArrayOutputStream(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(sld), new StreamResult(os)); return os.toByteArray(); } private Document parse(InputStream is) throws ParserConfigurationException, SAXException, IOException { return parse(is, false); } private Document parse(InputStream is, boolean namespaceAware) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(namespaceAware); DocumentBuilder db = dbf.newDocumentBuilder(); return db.parse(is); } private String getLayerPath(Workspace workspace, Layer layer) { return getLayerPath(workspace, layer.getName()); } private String getLayerPath(Workspace workspace, FeatureType featureType) { return getLayerPath(workspace, featureType.getName()); } private String getLayerPath(Workspace workspace, String name) { return restLocation + "layers/" + workspace.getName() + ":" + name; } public CompletableFuture<Layer> getLayer(Workspace workspace, FeatureType featureType) { CompletableFuture<Layer> future = new CompletableFuture<>(); get(getLayerPath(workspace, featureType)).whenComplete((optionalDocument, t) -> { if(t != null) { future.completeExceptionally(t); } else { try { Document document = optionalDocument.get(); XPath xpath = XPathFactory.newInstance().newXPath(); String defaultStyleName = (String)xpath.evaluate("layer/defaultStyle/name/text()", document, XPathConstants.STRING); StyleRef defaultStyle = new StyleRef(defaultStyleName); List<StyleRef> additionalStyles = new ArrayList<>(); NodeList additionalStyleNames = (NodeList)xpath.evaluate("layer/styles/style/name", document, XPathConstants.NODESET); for(int i = 0; i < additionalStyleNames.getLength(); i++) { additionalStyles.add(new StyleRef(additionalStyleNames.item(i).getTextContent())); } future.complete(new Layer(featureType.getName(), defaultStyle, additionalStyles)); } catch(Exception e) { future.completeExceptionally(e); } } }); return future; } public CompletableFuture<Void> putLayer(Workspace workspace, Layer layer) { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); XMLOutputFactory of = XMLOutputFactory.newInstance(); XMLStreamWriter sw = of.createXMLStreamWriter(os); sw.writeStartDocument(); sw.writeStartElement("layer"); sw.writeStartElement("name"); sw.writeCharacters(layer.getName()); sw.writeEndElement(); sw.writeStartElement("defaultStyle"); sw.writeStartElement("name"); sw.writeCharacters(layer.getDefaultStyle().getStyleName()); sw.writeEndElement(); sw.writeEndElement(); sw.writeStartElement("styles"); for(StyleRef style : layer.getAdditionalStyles()) { sw.writeStartElement("style"); sw.writeStartElement("name"); sw.writeCharacters(style.getStyleName()); sw.writeEndElement(); sw.writeEndElement(); } sw.writeEndElement(); sw.writeEndElement(); sw.writeEndDocument(); return put(getLayerPath(workspace, layer), os.toByteArray()); } catch(Exception e) { return f.failed(e); } } @Override public CompletableFuture<Void> deleteStyle(Style style) { return delete(getStylePath(style) + "?purge=true"); } }
package org.sindice.analytics.servlet; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.openrdf.http.protocol.Protocol; import org.sindice.analytics.backend.DGSQueryResultProcessor; import org.sindice.analytics.backend.DGSQueryResultProcessor.Context; import org.sindice.analytics.ranking.Label; import org.sindice.analytics.ranking.LabelsRanking; import org.sindice.analytics.ranking.LabelsRankingYAMLoader; import org.sindice.analytics.servlet.ResponseWriterFactory.ResponseType; import org.sindice.core.analytics.commons.summary.AnalyticsClassAttributes; import org.sindice.core.analytics.commons.summary.DataGraphSummaryVocab; import org.sindice.core.analytics.commons.summary.DatasetLabel; import org.sindice.core.sesame.backend.SesameBackend; import org.sindice.core.sesame.backend.SesameBackendException; import org.sindice.core.sesame.backend.SesameBackendFactory; import org.sindice.core.sesame.backend.SesameBackendFactory.BackendType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AssistedSparqlEditorServlet extends HttpServlet { private static final long serialVersionUID = 4137296200305461786L; private static final Logger logger = LoggerFactory .getLogger(AssistedSparqlEditorServlet.class); public static final String DGS_GRAPH = "dg"; public static final String DATA_REQUEST = "data"; private static final String DEFAULT_DATA_REQUEST = "DEFAULT"; private final List<LabelsRanking> labelsRankings = new ArrayList<LabelsRanking>(); private SesameBackend<Label, Context> dgsBackend = null; private int pagination; private int limit; @Override public void init(ServletConfig config) throws ServletException { super.init(config); logger.info("Intialized ASE Servlet"); // SPARQL endpoint with graph summary final BackendType backend = BackendType.valueOf((String) config.getServletContext().getAttribute(AssistedSparqlEditorListener.RECOMMENDER_WRAPPER + AssistedSparqlEditorListener.BACKEND)); final String[] backendArgs = (String[]) config.getServletContext().getAttribute(AssistedSparqlEditorListener.RECOMMENDER_WRAPPER + AssistedSparqlEditorListener.BACKEND_ARGS); // The path to the ranking configuration final String rankingConfigPath = (String) config.getServletContext().getAttribute(AssistedSparqlEditorListener.RECOMMENDER_WRAPPER + AssistedSparqlEditorListener.RANKING_CONFIGURATION); // The pagination value pagination = (Integer) config.getServletContext().getAttribute(AssistedSparqlEditorListener.RECOMMENDER_WRAPPER + AssistedSparqlEditorListener.PAGINATION); // The Limit of results to be retrieved limit = (Integer) config.getServletContext().getAttribute(AssistedSparqlEditorListener.RECOMMENDER_WRAPPER + AssistedSparqlEditorListener.LIMIT); // The ClassAttributes final String[] classAttributes = (String[]) config.getServletContext().getAttribute(AssistedSparqlEditorListener.RECOMMENDER_WRAPPER + AssistedSparqlEditorListener.CLASS_ATTRIBUTES); // Set the domain URI prefix DataGraphSummaryVocab.setDomainUriPrefix((String) config.getServletContext().getAttribute(AssistedSparqlEditorListener.RECOMMENDER_WRAPPER + AssistedSparqlEditorListener.DOMAIN_URI_PREFIX)); // Set the dataset label definition DataGraphSummaryVocab.setDatasetLabelDefinition(DatasetLabel.valueOf((String) config.getServletContext().getAttribute(AssistedSparqlEditorListener.RECOMMENDER_WRAPPER + AssistedSparqlEditorListener.DATASET_LABEL_DEF))); // Set the summary named graph DataGraphSummaryVocab.setGraphSummaryGraph((String) config.getServletContext().getAttribute(AssistedSparqlEditorListener.RECOMMENDER_WRAPPER + AssistedSparqlEditorListener.GRAPH_SUMMARY_GRAPH)); AnalyticsClassAttributes.initClassAttributes(classAttributes); try { final BufferedInputStream r = new BufferedInputStream(new FileInputStream(rankingConfigPath)); final LabelsRankingYAMLoader loader = new LabelsRankingYAMLoader(r); loader.load(); labelsRankings.addAll(loader.getConfigurations()); final DGSQueryResultProcessor qrp = new DGSQueryResultProcessor(); dgsBackend = SesameBackendFactory.getDgsBackend(backend, qrp, backendArgs); dgsBackend.initConnection(); logger.info("RankingConfiguration={} Backend={} BackendArgs={} ClassAttributes={} Pagination={} DomainUriPrefix={} DatasetLabelDef={} GraphSummaryGraph={} LIMIT={}", new Object[] { rankingConfigPath, backend, Arrays.toString(backendArgs), Arrays.toString(classAttributes), pagination, DataGraphSummaryVocab.DOMAIN_URI_PREFIX, DataGraphSummaryVocab.DATASET_LABEL_DEF, DataGraphSummaryVocab.GRAPH_SUMMARY_GRAPH, limit}); } catch (Exception e) { logger.error("Failed to start the DGS backend", e); } } @Override public void destroy() { logger.info("Destroy ASE Servlet"); try { for (LabelsRanking lr : labelsRankings) { lr.close(); } } catch (IOException e) { logger.error("Failed to release resources kept by the rankings: {}", e); } finally { if (dgsBackend != null) { try { dgsBackend.closeConnection(); } catch (SesameBackendException e) { logger.error("", e); } } } super.destroy(); } /** * Update the Graph name of the summary, where the data summary was * saved in */ @Override protected void doPut(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException { if (request.getParameter(DGS_GRAPH) != null) { DataGraphSummaryVocab.setGraphSummaryGraph(request.getParameter(DGS_GRAPH)); } else { DataGraphSummaryVocab.setGraphSummaryGraph(DataGraphSummaryVocab.DEFAULT_GSG); } logger.info("Using the summary: {}", DataGraphSummaryVocab.GRAPH_SUMMARY_GRAPH); } /** * Process request from editor, provides recommendations */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { getRecommendationAsJson(request, response); } /** * Process request from editor, provides recommendations */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { getRecommendationAsJson(request, response); } /** * Process auto-recommendation request * * @param request * @param response * @throws IOException */ private void getRecommendationAsJson(HttpServletRequest request, HttpServletResponse response) throws IOException { logger.info("\nBegin processing request"); final PrintWriter out = response.getWriter(); response.setContentType("application/json"); String res = computeResponse(request); out.print(res); out.flush(); out.close(); } private String computeResponse(HttpServletRequest request) throws IOException { String response = ""; String queryType = DEFAULT_DATA_REQUEST; if (request.getParameter(DATA_REQUEST) != null) { queryType = request.getParameter(DATA_REQUEST); } final ResponseWriter<?> responseWriter = ResponseWriterFactory.getResponseWriter(ResponseType.JSON); if (queryType.equalsIgnoreCase("autocomplete")) { // Check if user wants a context aware recommendation if (request.getParameter(Protocol.QUERY_PARAM_NAME) != null) { final String query = URLDecoder.decode(request.getParameter(Protocol.QUERY_PARAM_NAME), "UTF-8"); // Get recommendation response = (String) SparqlRecommender.run(dgsBackend, responseWriter, query, this.labelsRankings, pagination, limit); } } return response; } }
package org.gbif.registry.ws.resources; import com.google.common.base.CharMatcher; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Maps; import org.gbif.api.model.common.paging.Pageable; import org.gbif.api.model.common.paging.PagingRequest; import org.gbif.api.model.common.paging.PagingResponse; import org.gbif.api.model.registry.Comment; import org.gbif.api.model.registry.Contact; import org.gbif.api.model.registry.Endpoint; import org.gbif.api.model.registry.Identifier; import org.gbif.api.model.registry.MachineTag; import org.gbif.api.model.registry.NetworkEntity; import org.gbif.api.model.registry.Tag; import org.gbif.api.service.registry.NetworkEntityService; import org.gbif.api.vocabulary.IdentifierType; import org.gbif.api.vocabulary.TagName; import org.gbif.api.vocabulary.TagNamespace; import org.gbif.registry.events.ChangedComponentEvent; import org.gbif.registry.events.CreateEvent; import org.gbif.registry.events.DeleteEvent; import org.gbif.registry.events.EventManager; import org.gbif.registry.events.UpdateEvent; import org.gbif.registry.persistence.WithMyBatis; import org.gbif.registry.persistence.mapper.BaseNetworkEntityMapper; import org.gbif.registry.persistence.mapper.CommentMapper; import org.gbif.registry.persistence.mapper.ContactMapper; import org.gbif.registry.persistence.mapper.EndpointMapper; import org.gbif.registry.persistence.mapper.IdentifierMapper; import org.gbif.registry.persistence.mapper.MachineTagMapper; import org.gbif.registry.persistence.mapper.TagMapper; import org.gbif.registry.ws.Trim; import org.gbif.registry.ws.security.EditorAuthorizationService; import org.gbif.registry.ws.security.SecurityContextCheck; import org.gbif.registry.ws.security.UserRoles; import org.gbif.ws.WebApplicationException; import org.gbif.ws.server.interceptor.NullToNotFound; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.access.annotation.Secured; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkArgument; import static org.gbif.registry.ws.security.UserRoles.ADMIN_ROLE; import static org.gbif.registry.ws.security.UserRoles.APP_ROLE; import static org.gbif.registry.ws.security.UserRoles.EDITOR_ROLE; /** * Provides a skeleton implementation of the following. * <ul> * <li>Base CRUD operations for a network entity</li> * <li>Comment operations</li> * <li>Contact operations (in addition to BaseNetworkEntityResource)</li> * <li>Endpoint operations (in addition to BaseNetworkEntityResource)</li> * <li>Identifier operations (in addition to BaseNetworkEntityResource2)</li> * <li>MachineTag operations</li> * <li>Tag operations</li> * </ul> * * @param <T> The type of resource that is under CRUD */ @RequestMapping(path = "/", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public class BaseNetworkEntityResource<T extends NetworkEntity> implements NetworkEntityService<T> { private final BaseNetworkEntityMapper<T> mapper; private final CommentMapper commentMapper; private final MachineTagMapper machineTagMapper; private final TagMapper tagMapper; private final ContactMapper contactMapper; private final EndpointMapper endpointMapper; private final IdentifierMapper identifierMapper; private final EventManager eventManager; private final EditorAuthorizationService userAuthService; private final WithMyBatis withMyBatis; private final Class<T> objectClass; protected BaseNetworkEntityResource( BaseNetworkEntityMapper<T> mapper, CommentMapper commentMapper, ContactMapper contactMapper, EndpointMapper endpointMapper, IdentifierMapper identifierMapper, MachineTagMapper machineTagMapper, TagMapper tagMapper, Class<T> objectClass, EventManager eventManager, EditorAuthorizationService userAuthService, WithMyBatis withMyBatis) { this.mapper = mapper; this.commentMapper = commentMapper; this.machineTagMapper = machineTagMapper; this.tagMapper = tagMapper; this.contactMapper = contactMapper; this.endpointMapper = endpointMapper; this.identifierMapper = identifierMapper; this.objectClass = objectClass; this.eventManager = eventManager; this.userAuthService = userAuthService; this.withMyBatis = withMyBatis; } // TODO: 2019-08-26 validation // TODO: 2019-08-26 add APPLICATION_JAVASCRIPT type for all /** * This method ensures that the caller is authorized to perform the action and then adds the server * controlled fields for createdBy and modifiedBy. It then creates the entity. * * @param entity entity that extends NetworkEntity * @return key of entity created */ @RequestMapping(method = RequestMethod.POST) @Trim @Transactional @Secured({ADMIN_ROLE, EDITOR_ROLE}) public UUID createBase(@RequestBody @NotNull @Trim T entity) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final UserDetails principal = (UserDetails) authentication.getPrincipal(); // if not admin or app, verify rights if (!SecurityContextCheck.checkUserInRole(authentication, ADMIN_ROLE, APP_ROLE)) { boolean allowed = false; for (UUID entityKeyToBeAssessed : owningEntityKeys(entity)) { if (entityKeyToBeAssessed == null) { throw new WebApplicationException(HttpStatus.FORBIDDEN); } if (userAuthService.allowedToModifyEntity(principal, entityKeyToBeAssessed)) { allowed = true; break; } } if (!allowed) { throw new WebApplicationException(HttpStatus.FORBIDDEN); } } entity.setCreatedBy(principal.getUsername()); entity.setModifiedBy(principal.getUsername()); return create(entity); } // @Validate(groups = {PrePersist.class, Default.class}) @Override public UUID create(@Valid T entity) { withMyBatis.create(mapper, entity); eventManager.post(CreateEvent.newInstance(entity, objectClass)); return entity.getKey(); } /** * This method ensures that the caller is authorized to perform the action, and then deletes the entity. * </br> * Relax content-type to wildcard to allow angularjs. * * @param key key of entity to delete */ @DeleteMapping(value = "{key}", consumes = MediaType.ALL_VALUE) @Secured({ADMIN_ROLE, EDITOR_ROLE}) @Transactional public void deleteBase(@NotNull @PathVariable UUID key) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final UserDetails principal = (UserDetails) authentication.getPrincipal(); // the following lines allow to set the "modifiedBy" to the user who actually deletes the entity. // the api delete(UUID) should be changed eventually T objectToDelete = get(key); objectToDelete.setModifiedBy(principal.getUsername()); withMyBatis.update(mapper, objectToDelete); delete(key); } @Override public void delete(UUID key) { T objectToDelete = get(key); withMyBatis.delete(mapper, key); eventManager.post(DeleteEvent.newInstance(objectToDelete, objectClass)); } // @Validate(groups = {PostPersist.class, Default.class}) @NullToNotFound @Nullable @GetMapping(value = "{key}") @Override public T get(@NotNull @PathVariable UUID key) { return withMyBatis.get(mapper, key); } // we do a post not get cause we expect large numbers of keys to be sent @PostMapping("titles") @Override public Map<UUID, String> getTitles(@RequestBody Collection<UUID> keys) { Map<UUID, String> titles = Maps.newHashMap(); for (UUID key : keys) { titles.put(key, mapper.title(key)); } return titles; } @Override public PagingResponse<T> list(@Nullable Pageable page) { page = page == null ? new PagingRequest() : page; return withMyBatis.list(mapper, page); } @Override public PagingResponse<T> search(String query, @Nullable Pageable page) { page = page == null ? new PagingRequest() : page; // trim and handle null from given input String q = query != null ? Strings.emptyToNull(CharMatcher.WHITESPACE.trimFrom(query)) : query; return withMyBatis.search(mapper, q, page); } @Override public PagingResponse<T> listByIdentifier(IdentifierType type, String identifier, @Nullable Pageable page) { page = page == null ? new PagingRequest() : page; return withMyBatis.listByIdentifier(mapper, type, identifier, page); } @Override public PagingResponse<T> listByIdentifier(String identifier, @Nullable Pageable page) { return listByIdentifier(null, identifier, page); } /** * This method ensures that the path variable for the key matches the entity's key, ensures that the caller is * authorized to perform the action and then adds the server controlled field modifiedBy. * * @param key key of entity to update * @param entity entity that extends NetworkEntity */ @PutMapping(value = "{key}") @Trim @Transactional @Secured({ADMIN_ROLE, EDITOR_ROLE}) public void updateBase(@PathVariable UUID key, @RequestBody @NotNull @Trim T entity) { checkArgument(key.equals(entity.getKey()), "Provided entity must have the same key as the resource URL"); final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final UserDetails principal = (UserDetails) authentication.getPrincipal(); entity.setModifiedBy(principal.getUsername()); update(entity); } // @Validate(groups = {PostPersist.class, Default.class}) @Override public void update(@Valid T entity) { T oldEntity = get(entity.getKey()); withMyBatis.update(mapper, entity); // get complete entity with components populated, so subscribers of UpdateEvent can compare new and old entities T newEntity = get(entity.getKey()); eventManager.post(UpdateEvent.newInstance(newEntity, oldEntity, objectClass)); } /** * This method ensures that the caller is authorized to perform the action and then adds the server * controlled fields for createdBy and modifiedBy. * * @param targetEntityKey key of target entity to add comment to * @param comment Comment to add * @return key of Comment created */ @PostMapping(value = "{key}/comment") @Trim @Transactional @Secured({ADMIN_ROLE, EDITOR_ROLE, APP_ROLE}) public int addCommentBase(@NotNull @PathVariable("key") UUID targetEntityKey, @RequestBody @NotNull @Trim Comment comment) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final UserDetails principal = (UserDetails) authentication.getPrincipal(); comment.setCreatedBy(principal.getUsername()); comment.setModifiedBy(principal.getUsername()); return addComment(targetEntityKey, comment); } // @Validate(groups = {PrePersist.class, Default.class}) @Override public int addComment(UUID targetEntityKey, @Valid Comment comment) { int key = withMyBatis.addComment(commentMapper, mapper, targetEntityKey, comment); eventManager.post(ChangedComponentEvent.newInstance(targetEntityKey, objectClass, Comment.class)); return key; } /** * This method ensures that the caller is authorized to perform the action, and then deletes the Comment. * * @param targetEntityKey key of target entity to delete comment from * @param commentKey key of Comment to delete */ @DeleteMapping(value = "{key}/comment/{commentKey}", consumes = MediaType.ALL_VALUE) @Secured({ADMIN_ROLE, EDITOR_ROLE}) @Override public void deleteComment(@NotNull @PathVariable("key") UUID targetEntityKey, @PathVariable int commentKey) { withMyBatis.deleteComment(mapper, targetEntityKey, commentKey); eventManager.post(ChangedComponentEvent.newInstance(targetEntityKey, objectClass, Comment.class)); } @GetMapping(value = "{key}/comment") @Override public List<Comment> listComments(@NotNull @PathVariable("key") UUID targetEntityKey) { return withMyBatis.listComments(mapper, targetEntityKey); } /** * Adding most machineTags is restricted based on the namespace. * For some tags, it is restricted based on the editing role as usual. * * @param targetEntityKey key of target entity to add MachineTag to * @param machineTag MachineTag to add * @return key of MachineTag created */ @PostMapping(value = "{key}/machineTag") @Trim @Transactional public int addMachineTagBase(@PathVariable("key") UUID targetEntityKey, @RequestBody @NotNull @Trim MachineTag machineTag) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final UserDetails principal = (UserDetails) authentication.getPrincipal(); if (SecurityContextCheck.checkUserInRole(authentication, ADMIN_ROLE) || userAuthService.allowedToModifyNamespace(principal, machineTag.getNamespace()) || (SecurityContextCheck.checkUserInRole(authentication, EDITOR_ROLE) && TagNamespace.GBIF_DEFAULT_TERM.getNamespace().equals(machineTag.getNamespace()) && userAuthService.allowedToModifyDataset(principal, targetEntityKey)) ) { machineTag.setCreatedBy(principal.getUsername()); return addMachineTag(targetEntityKey, machineTag); } else { throw new WebApplicationException(HttpStatus.FORBIDDEN); } } // @Validate(groups = {PrePersist.class, Default.class}) @Override public int addMachineTag(UUID targetEntityKey, @Valid MachineTag machineTag) { return withMyBatis.addMachineTag(machineTagMapper, mapper, targetEntityKey, machineTag); } @Override public int addMachineTag(@NotNull UUID targetEntityKey, @NotNull String namespace, @NotNull String name, @NotNull String value) { MachineTag machineTag = new MachineTag(); machineTag.setNamespace(namespace); machineTag.setName(name); machineTag.setValue(value); return addMachineTag(targetEntityKey, machineTag); } @Override public int addMachineTag(@NotNull UUID targetEntityKey, @NotNull TagName tagName, @NotNull String value) { MachineTag machineTag = MachineTag.newInstance(tagName, value); return addMachineTag(targetEntityKey, machineTag); } /** * The webservice method to delete a machine tag. * Ensures that the caller is authorized to perform the action by looking at the namespace. */ public void deleteMachineTagByMachineTagKey(UUID targetEntityKey, int machineTagKey) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final UserDetails principal = (UserDetails) authentication.getPrincipal(); Optional<MachineTag> optMachineTag = withMyBatis.listMachineTags(mapper, targetEntityKey).stream() .filter(m -> m.getKey() == machineTagKey).findFirst(); if (optMachineTag.isPresent()) { MachineTag machineTag = optMachineTag.get(); if (SecurityContextCheck.checkUserInRole(authentication, ADMIN_ROLE) || userAuthService.allowedToModifyNamespace(principal, machineTag.getNamespace()) || (SecurityContextCheck.checkUserInRole(authentication, EDITOR_ROLE) && TagNamespace.GBIF_DEFAULT_TERM.getNamespace().equals(machineTag.getNamespace()) && userAuthService.allowedToModifyDataset(principal, targetEntityKey)) ) { deleteMachineTag(targetEntityKey, machineTagKey); } else { throw new WebApplicationException(HttpStatus.FORBIDDEN); } } else { throw new WebApplicationException(HttpStatus.NOT_FOUND); } } /** * Deletes the MachineTag according to interface without security restrictions. * * @param targetEntityKey key of target entity to delete MachineTag from * @param machineTagKey key of MachineTag to delete */ @Override public void deleteMachineTag(UUID targetEntityKey, int machineTagKey) { withMyBatis.deleteMachineTag(mapper, targetEntityKey, machineTagKey); } /** * The webservice method to delete all machine tag in a namespace. * Ensures that the caller is authorized to perform the action by looking at the namespace. */ public void deleteMachineTagsByNamespace(UUID targetEntityKey, String namespace) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final UserDetails principal = (UserDetails) authentication.getPrincipal(); if (!SecurityContextCheck.checkUserInRole(authentication, UserRoles.ADMIN_ROLE) && !userAuthService.allowedToModifyNamespace(principal, namespace)) { throw new WebApplicationException(HttpStatus.FORBIDDEN); } deleteMachineTags(targetEntityKey, namespace); } /** * It was added because of an ambiguity problem. * (Spring can't distinguish {key}/machineTag/{namespace} and {key}/machineTag/{machineTagKey:[0-9]+}) */ @DeleteMapping(value = "{key}/machineTag/{parameter}", consumes = MediaType.ALL_VALUE) public void deleteMachineTagsBase(@PathVariable("key") UUID targetEntityKey, @PathVariable String parameter) { if (Pattern.compile("[0-9]+").matcher(parameter).matches()) { deleteMachineTagByMachineTagKey(targetEntityKey, Integer.parseInt(parameter)); } else { deleteMachineTagsByNamespace(targetEntityKey, parameter); } } @Override public void deleteMachineTags(@NotNull UUID targetEntityKey, @NotNull TagNamespace tagNamespace) { deleteMachineTags(targetEntityKey, tagNamespace.getNamespace()); } @Override public void deleteMachineTags(@NotNull UUID targetEntityKey, @NotNull String namespace) { withMyBatis.deleteMachineTags(mapper, targetEntityKey, namespace, null); } /** * The webservice method to delete all machine tag of a particular name in a namespace. * Ensures that the caller is authorized to perform the action by looking at the namespace. */ @DeleteMapping(value = "{key}/machineTag/{namespace}/{name}", consumes = MediaType.ALL_VALUE) public void deleteMachineTagsBase(@PathVariable("key") UUID targetEntityKey, @PathVariable String namespace, @PathVariable String name) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final UserDetails principal = (UserDetails) authentication.getPrincipal(); if (!SecurityContextCheck.checkUserInRole(authentication, UserRoles.ADMIN_ROLE) && !userAuthService.allowedToModifyNamespace(principal, namespace)) { throw new WebApplicationException(HttpStatus.FORBIDDEN); } deleteMachineTags(targetEntityKey, namespace, name); } @Override public void deleteMachineTags(@NotNull UUID targetEntityKey, @NotNull TagName tagName) { deleteMachineTags(targetEntityKey, tagName.getNamespace().getNamespace(), tagName.getName()); } @Override public void deleteMachineTags(@NotNull UUID targetEntityKey, @NotNull String namespace, @NotNull String name) { withMyBatis.deleteMachineTags(mapper, targetEntityKey, namespace, name); } @GetMapping(value = "{key}/machineTag") @Override public List<MachineTag> listMachineTags(@PathVariable("key") UUID targetEntityKey) { return withMyBatis.listMachineTags(mapper, targetEntityKey); } @Override public PagingResponse<T> listByMachineTag(String namespace, @Nullable String name, @Nullable String value, @Nullable Pageable page) { page = page == null ? new PagingRequest() : page; return withMyBatis.listByMachineTag(mapper, namespace, name, value, page); } /** * This method ensures that the caller is authorized to perform the action and then adds the server * controlled fields for createdBy. * * @param targetEntityKey key of target entity to add Tag to * @param tag Tag to add * @return key of Tag created */ @PostMapping(value = "{key}/tag") @Secured({ADMIN_ROLE, EDITOR_ROLE}) public int addTagBase(@PathVariable("key") UUID targetEntityKey, @RequestBody @NotNull Tag tag) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final UserDetails principal = (UserDetails) authentication.getPrincipal(); tag.setCreatedBy(principal.getUsername()); return addTag(targetEntityKey, tag); } @Override public int addTag(@NotNull UUID targetEntityKey, @NotNull String value) { Tag tag = new Tag(); tag.setValue(value); return addTag(targetEntityKey, tag); } // @Validate(groups = {PrePersist.class, Default.class}) @Override public int addTag(UUID targetEntityKey, @Valid Tag tag) { int key = withMyBatis.addTag(tagMapper, mapper, targetEntityKey, tag); eventManager.post(ChangedComponentEvent.newInstance(targetEntityKey, objectClass, Tag.class)); return key; } /** * This method ensures that the caller is authorized to perform the action, and then deletes the Tag. * * @param targetEntityKey key of target entity to delete Tag from * @param tagKey key of Tag to delete */ @DeleteMapping(value = "{key}/tag/{tagKey}", consumes = MediaType.ALL_VALUE) @Secured({ADMIN_ROLE, EDITOR_ROLE}) @Override public void deleteTag(@PathVariable("key") UUID targetEntityKey, @PathVariable int tagKey) { withMyBatis.deleteTag(mapper, targetEntityKey, tagKey); eventManager.post(ChangedComponentEvent.newInstance(targetEntityKey, objectClass, Tag.class)); } @GetMapping(value = "{key}/tag") @Override public List<Tag> listTags(@PathVariable("key") UUID targetEntityKey, @RequestParam(value = "owner", required = false) String owner) { return withMyBatis.listTags(mapper, targetEntityKey, owner); } /** * This method ensures that the caller is authorized to perform the action and then adds the server * controlled fields for createdBy and modifiedBy. * * @param targetEntityKey key of target entity to add Contact to * @param contact Contact to add * @return key of Contact created */ @PostMapping(value = "{key}/contact") @Trim @Transactional @Secured({ADMIN_ROLE, EDITOR_ROLE, APP_ROLE}) public int addContactBase(@PathVariable("key") UUID targetEntityKey, @RequestBody @NotNull @Trim Contact contact) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final UserDetails principal = (UserDetails) authentication.getPrincipal(); contact.setCreatedBy(principal.getUsername()); contact.setModifiedBy(principal.getUsername()); return addContact(targetEntityKey, contact); } // @Validate(groups = {PrePersist.class, Default.class}) @Override public int addContact(UUID targetEntityKey, @Valid Contact contact) { int key = withMyBatis.addContact(contactMapper, mapper, targetEntityKey, contact); eventManager.post(ChangedComponentEvent.newInstance(targetEntityKey, objectClass, Contact.class)); return key; } /** * This method ensures that the caller is authorized to perform the action and then adds the server * controlled field for modifiedBy. * * @param targetEntityKey key of target entity to update contact * @param contactKey key of Contact to update * @param contact updated Contact */ @PutMapping("{key}/contact/{contactKey}") @Trim @Transactional @Secured({ADMIN_ROLE, EDITOR_ROLE}) public void updateContact(@PathVariable("key") UUID targetEntityKey, @PathVariable int contactKey, @RequestBody @NotNull @Trim Contact contact) { // for safety, and to match a nice RESTful URL structure Preconditions.checkArgument(Integer.valueOf(contactKey).equals(contact.getKey()), "Provided contact (key) does not match the path provided"); final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final UserDetails principal = (UserDetails) authentication.getPrincipal(); contact.setModifiedBy(principal.getUsername()); updateContact(targetEntityKey, contact); } // @Validate(groups = {PostPersist.class, Default.class}) @Override public void updateContact(UUID targetEntityKey, @Valid Contact contact) { withMyBatis.updateContact(contactMapper, mapper, targetEntityKey, contact); eventManager.post(ChangedComponentEvent.newInstance(targetEntityKey, objectClass, Contact.class)); } /** * This method ensures that the caller is authorized to perform the action. * * @param targetEntityKey key of target entity to delete Contact from * @param contactKey key of Contact to delete */ @DeleteMapping(value = "{key}/contact/{contactKey}", consumes = MediaType.ALL_VALUE) @Secured({ADMIN_ROLE, EDITOR_ROLE}) @Override public void deleteContact(@PathVariable("key") UUID targetEntityKey, @PathVariable int contactKey) { withMyBatis.deleteContact(mapper, targetEntityKey, contactKey); eventManager.post(ChangedComponentEvent.newInstance(targetEntityKey, objectClass, Contact.class)); } @GetMapping("{key}/contact") @Override public List<Contact> listContacts(@PathVariable("key") UUID targetEntityKey) { return withMyBatis.listContacts(mapper, targetEntityKey); } /** * This method ensures that the caller is authorized to perform the action and then adds the server * controlled fields for createdBy and modifiedBy. * * @param targetEntityKey key of target entity to add Endpoint to * @param endpoint Endpoint to add * @return key of Endpoint created */ @PostMapping("{key}/endpoint") @Trim @Transactional @Secured({ADMIN_ROLE, EDITOR_ROLE}) public int addEndpointBase(@PathVariable("key") UUID targetEntityKey, @RequestBody @NotNull @Trim Endpoint endpoint) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final UserDetails principal = (UserDetails) authentication.getPrincipal(); endpoint.setCreatedBy(principal.getUsername()); endpoint.setModifiedBy(principal.getUsername()); return addEndpoint(targetEntityKey, endpoint); } // @Validate(groups = {PrePersist.class, Default.class}) @Override public int addEndpoint(UUID targetEntityKey, @Valid Endpoint endpoint) { T oldEntity = get(targetEntityKey); int key = withMyBatis.addEndpoint(endpointMapper, mapper, targetEntityKey, endpoint, machineTagMapper); T newEntity = get(targetEntityKey); // posts an UpdateEvent instead of a ChangedComponentEvent, otherwise the crawler would have to start subscribing // to ChangedComponentEvent instead just to detect when an endpoint has been added to a Dataset eventManager.post(UpdateEvent.newInstance(newEntity, oldEntity, objectClass)); return key; } /** * This method ensures that the caller is authorized to perform the action, and then deletes the Endpoint. * * @param targetEntityKey key of target entity to delete Endpoint from * @param endpointKey key of Endpoint to delete */ @DeleteMapping(value = "{key}/endpoint/{endpointKey}", consumes = MediaType.ALL_VALUE) @Secured({ADMIN_ROLE, EDITOR_ROLE}) @Override public void deleteEndpoint(@PathVariable("key") UUID targetEntityKey, @PathVariable int endpointKey) { withMyBatis.deleteEndpoint(mapper, targetEntityKey, endpointKey); eventManager.post(ChangedComponentEvent.newInstance(targetEntityKey, objectClass, Endpoint.class)); } @GetMapping("{key}/endpoint") @Override public List<Endpoint> listEndpoints(@PathVariable("key") UUID targetEntityKey) { return withMyBatis.listEndpoints(mapper, targetEntityKey); } /** * This method ensures that the caller is authorized to perform the action and then adds the server * controlled field for createdBy. * * @param targetEntityKey key of target entity to add Identifier to * @param identifier Identifier to add * @return key of Identifier created */ @PostMapping("{key}/identifier") @Trim @Transactional @Secured({ADMIN_ROLE, EDITOR_ROLE}) public int addIdentifierBase(@PathVariable("key") UUID targetEntityKey, @RequestBody @NotNull @Trim Identifier identifier) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final UserDetails principal = (UserDetails) authentication.getPrincipal(); identifier.setCreatedBy(principal.getUsername()); return addIdentifier(targetEntityKey, identifier); } // @Validate(groups = {PrePersist.class, Default.class}) @Override public int addIdentifier(UUID targetEntityKey, @Valid Identifier identifier) { int key = withMyBatis.addIdentifier(identifierMapper, mapper, targetEntityKey, identifier); eventManager.post(ChangedComponentEvent.newInstance(targetEntityKey, objectClass, Identifier.class)); return key; } /** * This method ensures that the caller is authorized to perform the action, and then deletes the Identifier. * * @param targetEntityKey key of target entity to delete Identifier from * @param identifierKey key of Identifier to delete */ @DeleteMapping(value = "{key}/identifier/{identifierKey}", consumes = MediaType.ALL_VALUE) @Secured({ADMIN_ROLE, EDITOR_ROLE}) @Override public void deleteIdentifier(@PathVariable("key") UUID targetEntityKey, @PathVariable("identifierKey") int identifierKey) { withMyBatis.deleteIdentifier(mapper, targetEntityKey, identifierKey); eventManager.post(ChangedComponentEvent.newInstance(targetEntityKey, objectClass, Identifier.class)); } @GetMapping("{key}/identifier") @Override public List<Identifier> listIdentifiers(@PathVariable("key") UUID targetEntityKey) { return withMyBatis.listIdentifiers(mapper, targetEntityKey); } /** * Override this method to extract the entity key that governs security rights for creating. * If null is returned only admins are allowed to create new entities which is the default. */ protected List<UUID> owningEntityKeys(@NotNull T entity) { return new ArrayList<>(); } // TODO: 26/08/2019 move from here /** * Null safe builder to construct a paging response. * * @param page page to create response for, can be null */ protected <D> PagingResponse<D> pagingResponse(@Nullable Pageable page, Long count, List<D> result) { if (page == null) { // use default request page = new PagingRequest(); } return new PagingResponse<>(page, count, result); } }
package io.plumery.messaging.kafka; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.plumery.core.Event; import io.plumery.core.infrastructure.EventPublisher; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.StringSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Properties; public class KafkaEventPublisher implements EventPublisher { private static Logger LOG = LoggerFactory.getLogger(KafkaEventPublisher.class); private final KafkaProducer producer; private final ObjectMapper objectMapper; public KafkaEventPublisher(String zookeeper, ObjectMapper objectMapper) { Properties props = new Properties(); props.put("bootstrap.servers", zookeeper); props.put("key.serializer", StringSerializer.class); props.put("value.serializer", StringSerializer.class); this.producer = new KafkaProducer<>(props); this.objectMapper = objectMapper; } @Override public <T extends Event> void publish(String streamName, T event) { LOG.debug("Publishing event ["+event.getClass().getSimpleName()+"] for [" + streamName + "]"); String topic = streamName; String eventType = event.getClass().getSimpleName(); EventEnvelope envelope = new EventEnvelope(eventType, event); String value = serializeEnvelope(envelope); // -- the key of the record is an aggregate Id to ensure the order of the events for the same aggregate ProducerRecord<String, String> record = new ProducerRecord<>(topic, event.id.toString(), value); producer.send(record); } private String serializeEnvelope(EventEnvelope envelope) { String json; try { json = objectMapper.writeValueAsString(envelope); } catch (JsonProcessingException e) { throw new RuntimeException(e); } return json; } }
package net.ellitron.ldbcsnbimpls.interactive.torc.util; import net.ellitron.ldbcsnbimpls.interactive.core.SnbEntity; import net.ellitron.ldbcsnbimpls.interactive.core.SnbRelation; import net.ellitron.ldbcsnbimpls.interactive.torc.TorcEntity; import net.ellitron.torc.TorcGraph; import net.ellitron.torc.TorcVertex; import net.ellitron.torc.util.UInt128; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Graph; import org.docopt.Docopt; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.TimeZone; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.tinkerpop.gremlin.structure.VertexProperty; /** * A utility for loading dataset files generated by the LDBC SNB Data * Generator[1] into TorcDB[2]. * <p> * TODO:<br> * <ul> * <li>Make file searching more intelligent.</li> * </ul> * <p> * [1]: git@github.com:ldbc/ldbc_snb_datagen.git<br> * [2]: git@github.com:ellitron/torc.git<br> * * @author Jonathan Ellithorpe (jde@cs.stanford.edu) */ public class GraphLoader { private static final String doc = "GraphLoader: A utility for loading dataset files generated by the\n" + "LDBC SNB Data Generator into TorcDB. Nodes, props, and edges are\n" + "loaded separately using the \"nodes\", \"props\" or \"edges\"\n" + "command. Nodes must be loaded first before props or edges can be\n" + "loaded.\n" + "\n" + "Usage:\n" + " GraphLoader [options] nodes SOURCE\n" + " GraphLoader [options] props SOURCE\n" + " GraphLoader [options] edges SOURCE\n" + " GraphLoader (-h | --help)\n" + " GraphLoader --version\n" + "\n" + "Arguments:\n" + " SOURCE Directory containing SNB dataset files.\n" + "\n" + "Options:\n" + " --coordLoc=<loc> RAMCloud coordinator locator string\n" + " [default: tcp:host=127.0.0.1,port=12246].\n" + " --masters=<n> Number of RAMCloud master servers to use to\n" + " store the graph [default: 1].\n" + " --graphName=<g> The name to give the graph in RAMCloud\n" + " [default: graph].\n" + " --numLoaders=<n> The total number of loader instances loading\n" + " the graph in parallel [default: 1].\n" + " --loaderIdx=<n> Among numLoaders instance, which loader this\n" + " instance represents. Defines the partition of\n" + " the dataset this loader instance is responsible\n" + " for loading. Indexes start from 0.\n" + " [default: 0].\n" + " --numThreads=<n> The number of threads to use in this loader\n" + " instance.\n This loader's dataset partition is\n" + " divided up among this number of threads." + " [default: 1].\n" + " --txSize=<n> How many vertices/edges to load in a single\n" + " transaction. TorcDB transactions are buffered\n" + " locally before commit, and written in batch at\n" + " commit time. Setting this number appropriately\n" + " can therefore help to ammortize the RAMCloud\n" + " communication costs and increase loading\n" + " performance, although the right setting will\n" + " depend on system setup. [default: 128].\n" + " --txRetries=<r> The number of times to retry a failed\n" + " transaction before entering randomized backoff\n" + " mode. Transactions to RAMCloud may fail due to\n" + " timeouts, or sometimes conflicts on objects\n" + " (i.e. in the case of multithreaded loading).\n" + " [default: 10].\n" + " --txBackoff=<t> When a transaction has failed txRetries times\n" + " then the loader will wait a randomized amount\n" + " time in the range [0,t], and retry again. If\n" + " the transaction fails again, the time range is\n" + " doubled in size and the process is repeated.\n" + " When the transaction succeeds the time range is\n" + " reset to begin at [0,t] for future failures.\n" + " The units of this parameter is in milliseconds.\n" + " [default: 1000].\n" + " --splitSfx=<sf> The presence of this option indicates that the\n" + " dataset files have been split with each part\n" + " still containing the original file's header as\n" + " the first line. The value of this option is a\n" + " format string for the suffix used for the\n" + " parts. For example, .part%2d for part suffixes\n" + " that look like .part00, .part01, etc.\n The\n" + " presence of this option indicates that ALL\n" + " files have been split in this way. Also note\n" + " that this string must contain exactly 1 %d\n" + " somewhere in the string.\n" + " --reportInt=<i> Number of seconds between reporting status to\n" + " the screen. [default: 10].\n" + " --reportFmt=<s> Format options for status report output.\n" + " L - Total lines processed per second.\n" + " l - Per thread lines processed per second.\n" + " F - Total files processed.\n" + " f - Per thread files processed.\n" + " X - Total tx failures.\n" + " x - Per thread tx failures.\n" + " D - Total disk read bandwidth in MB/s.\n" + " d - Per thread disk read bandwidth in KB/s.\n" + " T - Total time elapsed.\n" + " [default: LFDT].\n" + " -h --help Show this screen.\n" + " --version Show version.\n" + "\n"; /** * Packs a unit of loading work for a loader thread to do. Includes a path to * the file to load, and what that file represents (either an SNB entity or * an SNB relation). */ private static class LoadUnit { private SnbEntity entity; private SnbRelation relation; private Path filePath; private boolean isProperties; /** * Constructor for LoadUnit. * * @param entity The entity this file pertains to. * @param filePath The path to the file. * @param isProperties Whether or not this is a file containing properties * for the entity. */ public LoadUnit(SnbEntity entity, Path filePath, boolean isProperties) { this.entity = entity; this.relation = null; this.filePath = filePath; this.isProperties = isProperties; } /** * Constructor for LoadUnit. * * @param relation The relations this file pertains to. * @param filePath The path to the file. */ public LoadUnit(SnbRelation relation, Path filePath) { this.entity = null; this.relation = relation; this.filePath = filePath; this.isProperties = false; } public boolean isEntity() { return entity != null; } public boolean isProperties() { return isProperties; } public boolean isRelation() { return relation != null; } public SnbEntity getSnbEntity() { return entity; } public SnbRelation getSnbRelation() { return relation; } public Path getFilePath() { return filePath; } } /** * A set of per-thread loading statistics. Each loader thread continually * updates these statistics, while a statistics reporting thread with a * reference to each ThreadStats instance in the system regularly prints * statistic summaries to the screen. */ private static class ThreadStats { /* * The total number of lines this thread has successfully processed and * loaded into the database. */ public long linesProcessed; /* * The total number of bytes this thread has read from disk. */ public long bytesReadFromDisk; /* * The total number of files this thread has successfully processed and * loaded into the database. */ public long filesProcessed; /* * The total number of files this thread has been given to process. */ public long totalFilesToProcess; /* * Number of times this thread has attempted to commit a transaction but * the transaction failed. */ public long txFailures; /** * Constructor. */ public ThreadStats() { this.linesProcessed = 0; this.bytesReadFromDisk = 0; this.filesProcessed = 0; this.totalFilesToProcess = 0; this.txFailures = 0; } /** * Copy constructor. * * @param stats ThreadStats object to copy. */ public ThreadStats(ThreadStats stats) { this.linesProcessed = stats.linesProcessed; this.bytesReadFromDisk = stats.bytesReadFromDisk; this.filesProcessed = stats.filesProcessed; this.totalFilesToProcess = stats.totalFilesToProcess; this.txFailures = stats.txFailures; } } /** * A loader thread which takes a set of files to load and loads them * sequentially. */ private static class LoaderThread implements Runnable { private final Graph graph; private final List<LoadUnit> loadList; private final int startIndex; private final int length; private final int txSize; private final int txRetries; private final int txBackoff; private final ThreadStats stats; /* * Used for parsing dates in the original dataset files output by the data * generator, and converting them to milliseconds since Jan. 1 9170. We * store dates in this form in TorcDB. */ private final SimpleDateFormat birthdayDateFormat; private final SimpleDateFormat creationDateDateFormat; /* * Used for generating random backoff times in the event of repeated * transaction failures. */ private final Random rand; /* * The maximum amount of time to sleep when experiencing failures. */ private final int MAX_SLEEP_TIME_MILLIS = 10000; /** * Constructor for LoaderThread. * * @param graph Graph into which to load the files. * @param loadList Master list of all files in the dataset. All loader * threads have a copy of this. * @param startIndex The index in the load list at which this thread's * loading work starts. * @param length The segment length in the load list for this thread. * @param txSize The number of lines to process within a single * transaction. * @param txRetries The maximum number of times to retry a failed * transaction before entering back-off mode. * @param txBackoff The time range, in milliseconds, in which to select a * random time to back-off in the case of txRetries transaction failures. * Time range is doubled upon repeated failures after backing off. * @param stats ThreadStats instance to update with loading statistics * info. */ public LoaderThread(Graph graph, List<LoadUnit> loadList, int startIndex, int length, int txSize, int txRetries, int txBackoff, ThreadStats stats) { this.graph = graph; this.loadList = loadList; this.startIndex = startIndex; this.length = length; this.txSize = txSize; this.txRetries = txRetries; this.txBackoff = txBackoff; this.stats = stats; this.birthdayDateFormat = new SimpleDateFormat("yyyy-MM-dd"); this.birthdayDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); this.creationDateDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); this.creationDateDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); this.rand = new Random(); } @Override public void run() { // Update this thread's total file load stat. stats.totalFilesToProcess = length; // Load every file in the range [startIndex, startIndex + length) for (int fIndex = startIndex; fIndex < startIndex + length; fIndex++) { LoadUnit loadUnit = loadList.get(fIndex); Path path = loadUnit.getFilePath(); BufferedReader inFile; try { inFile = Files.newBufferedReader(path, StandardCharsets.UTF_8); } catch (IOException ex) { throw new RuntimeException(String.format("Encountered error opening " + "file %s", path.getFileName())); } // First line of the file contains the column headers. String[] fieldNames; try { fieldNames = inFile.readLine().split("\\|"); } catch (IOException ex) { throw new RuntimeException(String.format("Encountered error reading " + "header line of file %s", path.getFileName())); } Consumer<List<String>> lineGobbler; if (loadUnit.isEntity()) { SnbEntity snbEntity = loadUnit.getSnbEntity(); long idSpace = TorcEntity.valueOf(snbEntity).idSpace; String vertexLabel = TorcEntity.valueOf(snbEntity).label; if (loadUnit.isProperties()) { lineGobbler = (List<String> lineBuffer) -> { for (int i = 0; i < lineBuffer.size(); i++) { String[] fieldValues = lineBuffer.get(i).split("\\|"); TorcVertex vertex = (TorcVertex) graph.vertices( new UInt128(idSpace, Long.decode(fieldValues[0]))) .next(); for (int j = 1; j < fieldValues.length; j++) { vertex.property(VertexProperty.Cardinality.list, fieldNames[j], fieldValues[j]); } } }; } else { lineGobbler = (List<String> lineBuffer) -> { for (int i = 0; i < lineBuffer.size(); i++) { /* * Here we parse the line into a map of the entity's * properties. Date-type fields (birthday, creationDate, ...) * need to be converted to the number of milliseconds since * January 1, 1970, 00:00:00 GMT. This is the format expected * to be returned for these fields by LDBC SNB benchmark * queries, although the format in the dataset files are things * like "1989-12-04" and "2010-03-17T23:32:10.447+0000". We * could do this conversion "live" during the benchmark, but * that would detract from the performance numbers' reflection * of true database performance since it would add to the * client-side query processing overhead. * * We also do special processing for array-type fields (emails, * speaks, ...), splitting the field value by the array * separator and creating a property for each of the elements. */ String[] fieldValues = lineBuffer.get(i).split("\\|"); Map<Object, Object> propMap = new HashMap<>(); for (int j = 0; j < fieldValues.length; j++) { try { if (fieldNames[j].equals("id")) { propMap.put(T.id, new UInt128(idSpace, Long.decode(fieldValues[j]))); } else if (fieldNames[j].equals("birthday")) { propMap.put(fieldNames[j], String.valueOf( birthdayDateFormat.parse(fieldValues[j]) .getTime())); } else if (fieldNames[j].equals("creationDate")) { propMap.put(fieldNames[j], String.valueOf( creationDateDateFormat.parse(fieldValues[j]) .getTime())); } else if (fieldNames[j].equals("joinDate")) { propMap.put(fieldNames[j], String.valueOf( creationDateDateFormat.parse(fieldValues[j]) .getTime())); } else if (fieldNames[j].equals("emails") || fieldNames[j].equals("speaks")) { String[] elements = fieldValues[j].split(";"); for (String elem : elements) { if (elem.length() != 0) { propMap.put(fieldNames[j], elem); } } } else { propMap.put(fieldNames[j], fieldValues[j]); } } catch (Exception ex) { throw new RuntimeException(String.format("Encountered " + "error processing field %s with value %s of line %d " + "in the line buffer. Line: \"%s\"", fieldNames[j], fieldValues[j], i, lineBuffer.get(i)), ex); } } // Don't forget to add the label! propMap.put(T.label, vertexLabel); List<Object> keyValues = new ArrayList<>(); propMap.forEach((key, val) -> { keyValues.add(key); keyValues.add(val); }); graph.addVertex(keyValues.toArray()); } }; } } else { SnbRelation snbRelation = loadUnit.getSnbRelation(); long tailIdSpace = TorcEntity.valueOf(snbRelation.tail).idSpace; long headIdSpace = TorcEntity.valueOf(snbRelation.head).idSpace; String edgeLabel = snbRelation.name; lineGobbler = (List<String> lineBuffer) -> { for (int i = 0; i < lineBuffer.size(); i++) { String[] fieldValues = lineBuffer.get(i).split("\\|"); TorcVertex tailVertex = (TorcVertex) graph.vertices( new UInt128(tailIdSpace, Long.decode(fieldValues[0]))) .next(); TorcVertex headVertex = (TorcVertex) graph.vertices( new UInt128(headIdSpace, Long.decode(fieldValues[1]))) .next(); Map<Object, Object> propMap = new HashMap<>(); for (int j = 2; j < fieldValues.length; j++) { try { if (fieldNames[j].equals("creationDate") || fieldNames[j].equals("joinDate")) { propMap.put(fieldNames[j], String.valueOf( creationDateDateFormat.parse(fieldValues[j]) .getTime())); } else { propMap.put(fieldNames[j], fieldValues[j]); } } catch (Exception ex) { throw new RuntimeException(String.format("Encountered " + "error processing field %s with value %s of line %d " + "in the line buffer. Line: \"%s\"", fieldNames[j], fieldValues[j], i, lineBuffer.get(i)), ex); } } List<Object> keyValues = new ArrayList<>(); propMap.forEach((key, val) -> { keyValues.add(key); keyValues.add(val); }); tailVertex.addEdge(edgeLabel, headVertex, keyValues.toArray()); /* * If this is not an undirected edge, then add the reverse edge * from head to tail. */ if (!snbRelation.directed) { headVertex.addEdge(edgeLabel, tailVertex, keyValues.toArray()); } } }; } // Keep track of what lines we're on in this file. long localLinesProcessed = 0; boolean hasLinesLeft = true; while (hasLinesLeft) { /* * Buffer txSize lines at a time from the input file and keep it * around until commit time. If the commit succeeds we can forget * about it, otherwise we'll use it again to retry the transaction. */ String line; List<String> lineBuffer = new ArrayList<>(txSize); try { while ((line = inFile.readLine()) != null) { lineBuffer.add(line); /* * Estimate the bytes we've read and add it to the * bytes-read-from-disk statistic. The file encoding is UTF-8, * which means ASCII characters are encoded with 1 byte, which * the vast majority of characters in the file ought to be. */ stats.bytesReadFromDisk += line.length(); if (lineBuffer.size() == txSize) { break; } } } catch (IOException ex) { throw new RuntimeException(String.format("Encountered error " + "reading lines of file %s", path.getFileName())); } // Catch when we've read all the lines in the file. if (line == null) { hasLinesLeft = false; } /* * Parse the lines in the buffer and write them into the database. If * the commit fails for any reason, retry the transaction up to * txRetries number of times. After that, enter multiplicative * backoff mode. */ int txFailCount = 0; int backoffMultiplier = 1; while (true) { try { lineGobbler.accept(lineBuffer); } catch (Exception ex) { throw new RuntimeException(String.format( "Encountered error processing lines in range [%d, %d] of " + "file %s", localLinesProcessed + 2, localLinesProcessed + 1 + lineBuffer.size(), path.getFileName()), ex); } try { graph.tx().commit(); localLinesProcessed += lineBuffer.size(); stats.linesProcessed += lineBuffer.size(); break; } catch (Exception e) { /* * The transaction failed due to either a conflict or a timeout. * In this case we want to retry the transaction, but only up to * the txRetries limit. */ txFailCount++; stats.txFailures++; if (txFailCount > txRetries) { try { int sleepTimeBound; if (backoffMultiplier * txBackoff < MAX_SLEEP_TIME_MILLIS) { sleepTimeBound = backoffMultiplier * txBackoff; backoffMultiplier *= 2; } else { sleepTimeBound = MAX_SLEEP_TIME_MILLIS; } int sleepTime = rand.nextInt(sleepTimeBound + 1); System.out.println(String.format("INFO: Thread %d " + "txFailCount reached %d on lines [%d, %d] of file %s. " + "Sleeping for %dms.", Thread.currentThread().getId(), txFailCount, localLinesProcessed + 2, localLinesProcessed + 1 + lineBuffer.size(), path.getFileName(), sleepTime)); Thread.sleep(sleepTime); } catch (InterruptedException ex) { // Our slumber has been cut short, most likely due to a // terminate signal. In this case we should terminate. try { inFile.close(); } catch (IOException ex1) { throw new RuntimeException(String.format("Encountered " + "error closing file %s", path.getFileName())); } return; } } } } } try { inFile.close(); } catch (IOException ex) { throw new RuntimeException(String.format("Encountered error closing " + "file %s", path.getFileName())); } stats.filesProcessed++; } } } /** * A thread which reports statistics on the loader threads in the system at a * set interval. This thread gets information on each thread via a shared * ThreadStats object with each thread. */ private static class StatsReporterThread implements Runnable { private List<ThreadStats> threadStats; private long reportInterval; private String formatString; /** * Constructor for StatsReporterThread. * * @param threadStats List of all the shared ThreadStats objects, one per * thread. * @param reportInterval Interval, in seconds, to report statistics to the * screen. */ public StatsReporterThread(List<ThreadStats> threadStats, long reportInterval, String formatString) { this.threadStats = threadStats; this.reportInterval = reportInterval; this.formatString = formatString; } @Override public void run() { try { // L - Total lines processed per second. // l - Per thread lines processed per second. // F - Total files processed per second. // f - Per thread files processed per second. // D - Total disk read bandwidth in MB/s. // d - Per thread disk read bandwidth in KB/s. // T - Total time elapsed. // Print the column headers. String colFormatStr = "%10s"; StringBuilder sb = new StringBuilder(); for (int i = 0; i < threadStats.size(); i++) { if (formatString.contains("l")) { sb.append(String.format(colFormatStr, i + ".l")); } if (formatString.contains("f")) { sb.append(String.format(colFormatStr, i + ".f")); } if (formatString.contains("x")) { sb.append(String.format(colFormatStr, i + ".x")); } if (formatString.contains("d")) { sb.append(String.format(colFormatStr, i + ".d")); } } if (formatString.contains("L")) { sb.append(String.format(colFormatStr, "L")); } if (formatString.contains("F")) { sb.append(String.format(colFormatStr, "F")); } if (formatString.contains("X")) { sb.append(String.format(colFormatStr, "X")); } if (formatString.contains("D")) { sb.append(String.format(colFormatStr, "D")); } if (formatString.contains("T")) { sb.append(String.format(colFormatStr, "T")); } String headerString = sb.toString(); System.out.println(headerString); // Capture the thread stats now before entering report loop. We'll use // this to start reporting diffs right away. List<ThreadStats> lastThreadStats = new ArrayList<>(); for (int i = 0; i < threadStats.size(); i++) { lastThreadStats.add(new ThreadStats(threadStats.get(i))); } long startTime = System.currentTimeMillis(); while (true) { Thread.sleep(reportInterval * 1000l); // Time elapsed since beginning loading. long timeElapsed = (System.currentTimeMillis() - startTime) / 1000l; sb = new StringBuilder(); long totalCurrLineRate = 0; long totalCurrByteRate = 0; long totalFilesProcessed = 0; long totalTxFailures = 0; long totalFilesToProcess = 0; for (int i = 0; i < threadStats.size(); i++) { ThreadStats lastStats = lastThreadStats.get(i); ThreadStats currStats = threadStats.get(i); long linesProcessed = currStats.linesProcessed - lastStats.linesProcessed; long bytesReadFromDisk = currStats.bytesReadFromDisk - lastStats.bytesReadFromDisk; long currLineRate = linesProcessed / reportInterval; long currByteRate = bytesReadFromDisk / reportInterval; if (formatString.contains("l")) { sb.append(String.format(colFormatStr, currLineRate)); } if (formatString.contains("f")) { sb.append(String.format(colFormatStr, String.format("(%d/%d)", currStats.filesProcessed, currStats.totalFilesToProcess))); } if (formatString.contains("x")) { sb.append(String.format(colFormatStr, currStats.txFailures)); } if (formatString.contains("d")) { sb.append(String.format(colFormatStr, (currByteRate / 1000l) + "KB/s")); } totalCurrLineRate += currLineRate; totalCurrByteRate += currByteRate; totalFilesProcessed += currStats.filesProcessed; totalTxFailures += currStats.txFailures; totalFilesToProcess += currStats.totalFilesToProcess; } if (formatString.contains("L")) { sb.append(String.format(colFormatStr, totalCurrLineRate)); } if (formatString.contains("F")) { sb.append(String.format(colFormatStr, String.format("(%d/%d)", totalFilesProcessed, totalFilesToProcess))); } if (formatString.contains("X")) { sb.append(String.format(colFormatStr, totalTxFailures)); } if (formatString.contains("D")) { sb.append(String.format(colFormatStr, (totalCurrByteRate / 1000000l) + "MB/s")); } if (formatString.contains("T")) { sb.append(String.format(colFormatStr, (timeElapsed / 60l) + "m")); } System.out.println(sb.toString()); lastThreadStats.clear(); for (int i = 0; i < threadStats.size(); i++) { lastThreadStats.add(new ThreadStats(threadStats.get(i))); } // Check if we are done loading. If so, exit. if (totalFilesProcessed == totalFilesToProcess) { break; } } } catch (InterruptedException ex) { // This is fine, we're probably being terminated, in which case we // should just go ahead and terminate. } } } public static void main(String[] args) throws FileNotFoundException, IOException, ParseException, InterruptedException { Map<String, Object> opts = new Docopt(doc).withVersion("GraphLoader 1.0").parse(args); int numLoaders = Integer.decode((String) opts.get("--numLoaders")); int loaderIdx = Integer.decode((String) opts.get("--loaderIdx")); int numThreads = Integer.decode((String) opts.get("--numThreads")); int txSize = Integer.decode((String) opts.get("--txSize")); int txRetries = Integer.decode((String) opts.get("--txRetries")); int txBackoff = Integer.decode((String) opts.get("--txBackoff")); long reportInterval = Long.decode((String) opts.get("--reportInt")); String formatString = (String) opts.get("--reportFmt"); String splitSuffix = (String) opts.get("--splitSfx"); String inputDir = (String) opts.get("SOURCE"); String command; if ((Boolean) opts.get("nodes")) { command = "nodes"; } else if ((Boolean) opts.get("props")) { command = "props"; } else { command = "edges"; } System.out.println(String.format( "GraphLoader: {coordLoc: %s, masters: %s, graphName: %s, " + "numLoaders: %d, loaderIdx: %d, numThreads: %d, txSize: %d, " + "txRetries: %d, txBackoff: %d, splitSfx: %s, reportFmt: %s, " + "inputDir: %s, command: %s}", (String) opts.get("--coordLoc"), (String) opts.get("--masters"), (String) opts.get("--graphName"), numLoaders, loaderIdx, numThreads, txSize, txRetries, txBackoff, splitSuffix, formatString, inputDir, command)); // Open a new TorcGraph with the supplied configuration. Map<String, String> config = new HashMap<>(); config.put(TorcGraph.CONFIG_COORD_LOCATOR, (String) opts.get("--coordLoc")); config.put(TorcGraph.CONFIG_GRAPH_NAME, (String) opts.get("--graphName")); config.put(TorcGraph.CONFIG_NUM_MASTER_SERVERS, (String) opts.get("--masters")); Graph graph = TorcGraph.open(config); /* * Construct a list of all the files that need to be loaded. If we are * loading nodes then this list will be a list of all the node files that * need to be loaded. Otherwise it will be a list of edge files. */ List<LoadUnit> loadList = new ArrayList<>(); if (command.equals("nodes")) { for (SnbEntity snbEntity : SnbEntity.values()) { String baseFileName = snbEntity.name + "_0_0.csv"; if (splitSuffix != null) { for (int i = 0;; i++) { String fileName = String.format("%s" + splitSuffix, baseFileName, i); File f = new File(inputDir + "/" + fileName); if (f.exists() && f.isFile()) { loadList.add(new LoadUnit(snbEntity, Paths.get(inputDir + "/" + fileName), false)); } else { if (i == 0) { System.out.println(String.format( "Missing file for %s nodes (%s)", snbEntity.name, fileName)); } else { System.out.println(String.format( "Found %d file parts for %s nodes", i, snbEntity.name)); } break; } } } else { File f = new File(inputDir + "/" + baseFileName); if (f.exists() && f.isFile()) { loadList.add(new LoadUnit(snbEntity, Paths.get(inputDir + "/" + baseFileName), false)); System.out.println(String.format("Found file for %s nodes (%s)", snbEntity.name, baseFileName)); } else { System.out.println(String.format("Missing file for %s nodes (%s)", snbEntity.name, baseFileName)); } } } System.out.println(String.format("Found %d total node files", loadList.size())); } else if (command.equals("props")) { loadList.add(new LoadUnit(SnbEntity.PERSON, Paths.get(inputDir + "/person_email_emailaddress_0_0.csv"), true)); System.out.println(String.format( "Found %d file parts for %s email properties", 1, SnbEntity.PERSON.name)); loadList.add(new LoadUnit(SnbEntity.PERSON, Paths.get(inputDir + "/person_speaks_language_0_0.csv"), true)); System.out.println(String.format( "Found %d file parts for %s speaks properties", 1, SnbEntity.PERSON.name)); System.out.println(String.format("Found %d total property files", loadList.size())); } else { for (SnbRelation snbRelation : SnbRelation.values()) { String baseFileName = String.format("%s_%s_%s_0_0.csv", snbRelation.tail.name, snbRelation.name, snbRelation.head.name); String edgeFormatStr; if (snbRelation.directed) { edgeFormatStr = "(%s)-[%s]->(%s)"; } else { edgeFormatStr = "(%s)-[%s]-(%s)"; } String edgeStr = String.format(edgeFormatStr, snbRelation.tail.name, snbRelation.name, snbRelation.head.name); if (splitSuffix != null) { for (int i = 0;; i++) { String fileName = String.format("%s" + splitSuffix, baseFileName, i); File f = new File(inputDir + "/" + fileName); if (f.exists() && f.isFile()) { loadList.add(new LoadUnit(snbRelation, Paths.get(inputDir + "/" + fileName))); } else { if (i == 0) { System.out.println(String.format( "Missing file for %s edges (%s)", edgeStr, fileName)); } else { System.out.println(String.format( "Found %d file parts for %s edges", i, edgeStr)); } break; } } } else { File f = new File(inputDir + "/" + baseFileName); if (f.exists() && f.isFile()) { loadList.add(new LoadUnit(snbRelation, Paths.get(inputDir + "/" + baseFileName))); System.out.println(String.format("Found file for %s edges (%s)", edgeStr, baseFileName)); } else { System.out.println(String.format("Missing file for %s edges (%s)", edgeStr, baseFileName)); } } } System.out.println(String.format("Found %d total edge files", loadList.size())); } /* * Calculate the segment of the list that this loader instance is * responsible for loading. */ int q = loadList.size() / numLoaders; int r = loadList.size() % numLoaders; int loadSize; int loadOffset; if (loaderIdx < r) { loadSize = q + 1; loadOffset = (q + 1) * loaderIdx; } else { loadSize = q; loadOffset = ((q + 1) * r) + (q * (loaderIdx - r)); } /* * Divvy up the load and start the threads. */ List<Thread> threads = new ArrayList<>(); List<ThreadStats> threadStats = new ArrayList<>(numThreads); for (int i = 0; i < numThreads; i++) { int qt = loadSize / numThreads; int rt = loadSize % numThreads; int threadLoadSize; int threadLoadOffset; if (i < rt) { threadLoadSize = qt + 1; threadLoadOffset = (qt + 1) * i; } else { threadLoadSize = qt; threadLoadOffset = ((qt + 1) * rt) + (qt * (i - rt)); } threadLoadOffset += loadOffset; ThreadStats stats = new ThreadStats(); threads.add(new Thread(new LoaderThread(graph, loadList, threadLoadOffset, threadLoadSize, txSize, txRetries, txBackoff, stats))); threads.get(i).start(); threadStats.add(stats); } /* * Start stats reporting thread. */ (new Thread(new StatsReporterThread(threadStats, reportInterval, formatString))).start(); /* * Join on all the loader threads. */ for (Thread thread : threads) { thread.join(); } } }
// copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // persons to whom the Software is furnished to do so, subject to the // notice shall be included in all copies or substantial portions of the // Software. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. package phasereditor.canvas.ui.shapes; import java.util.List; import org.eclipse.swt.graphics.RGB; import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.scene.effect.Blend; import javafx.scene.effect.BlendMode; import javafx.scene.effect.ColorInput; import javafx.scene.paint.Color; import javafx.scene.transform.Transform; import javafx.scene.transform.Translate; import phasereditor.assetpack.core.IAssetFrameModel; import phasereditor.assetpack.core.IAssetKey; import phasereditor.canvas.core.AnimationModel; import phasereditor.canvas.core.AssetSpriteModel; import phasereditor.canvas.core.BaseSpriteModel; import phasereditor.canvas.ui.editors.ObjectCanvas; import phasereditor.canvas.ui.editors.grid.PGridAnimationsProperty; import phasereditor.canvas.ui.editors.grid.PGridColorProperty; import phasereditor.canvas.ui.editors.grid.PGridModel; import phasereditor.canvas.ui.editors.grid.PGridNumberProperty; import phasereditor.canvas.ui.editors.grid.PGridSection; import phasereditor.canvas.ui.editors.grid.PGridStringProperty; import phasereditor.ui.ColorButtonSupport; /** * @author arian * */ public abstract class BaseSpriteControl<T extends BaseSpriteModel> extends BaseObjectControl<T> { private PGridNumberProperty _anchor_x_property; private PGridNumberProperty _anchor_y_property; private PGridColorProperty _tint_property; private PGridSection _spriteSection; public BaseSpriteControl(ObjectCanvas canvas, T model) { super(canvas, model); } @Override protected void updateTransforms(ObservableList<Transform> transforms) { super.updateTransforms(transforms); { // anchor double anchorX = getModel().getAnchorX(); double anchorY = getModel().getAnchorY(); double x = -getTextureWidth() * anchorX; double y = -getTextureHeight() * anchorY; Translate anchor = Transform.translate(x, y); transforms.add(anchor); } } @Override public void updateFromModel() { T model = getModel(); // update node of frame based sprites if (model instanceof AssetSpriteModel<?>) { IAssetKey key = ((AssetSpriteModel<?>) model).getAssetKey(); if (key != null && key instanceof IAssetFrameModel) { IAssetFrameModel frame = (IAssetFrameModel) key; if (getNode() instanceof FrameNode) { ((FrameNode) getNode()).updateContent(frame); } } } super.updateFromModel(); updateTint(); } protected void updateTint() { Node node = getNode(); String tint = getModel().getTint(); if (tint != null) { Blend multiply = new Blend(BlendMode.MULTIPLY); double width = getTextureWidth(); double height = getTextureHeight(); ColorInput value = new ColorInput(0, 0, width, height, Color.valueOf(tint)); multiply.setTopInput(value); Blend atop = new Blend(BlendMode.SRC_ATOP); atop.setTopInput(multiply); node.setEffect(atop); } } @Override protected void initPGridModel(PGridModel propModel) { super.initPGridModel(propModel); _spriteSection = new PGridSection("Sprite"); _anchor_x_property = new PGridNumberProperty(getId(), "anchor.x", help("Phaser.Sprite.anchor")) { @Override public Double getValue() { return Double.valueOf(getModel().getAnchorX()); } @Override public void setValue(Double value, boolean notify) { getModel().setAnchorX(value.doubleValue()); if (notify) { updateFromPropertyChange(); } } @Override public boolean isModified() { return getModel().getAnchorX() != 0; } }; _anchor_y_property = new PGridNumberProperty(getId(), "anchor.y", help("Phaser.Sprite.anchor")) { @Override public Double getValue() { return Double.valueOf(getModel().getAnchorY()); } @Override public void setValue(Double value, boolean notify) { getModel().setAnchorY(value.doubleValue()); if (notify) { updateFromPropertyChange(); } } @Override public boolean isModified() { return getModel().getAnchorY() != 0; } }; _tint_property = new PGridColorProperty(getId(), "tint", help("Phaser.Sprite.tint")) { @Override public void setValue(RGB value, boolean notify) { String tint; if (value == null) { tint = null; } else { tint = ColorButtonSupport.getHexString2(value); } getModel().setTint(tint); if (notify) { updateFromPropertyChange(); } } @Override public boolean isModified() { String tint = getModel().getTint(); return tint != null && !tint.equals("0xffffff"); } @Override public RGB getValue() { String tint = getModel().getTint(); if (tint == null) { return null; } Color c = Color.valueOf(tint); return new RGB((int) (c.getRed() * 255), (int) (c.getGreen() * 255), (int) (c.getBlue() * 255)); } }; _tint_property.setDefaultRGB(new RGB(255, 255, 255)); PGridAnimationsProperty animations_properties = new PGridAnimationsProperty(getId(), "animations", help("Phaser.Sprite.animations")) { @Override public void setValue(List<AnimationModel> value, boolean notify) { getModel().setAnimations(value); if (notify) { updateFromPropertyChange(); } } @Override public List<AnimationModel> getValue() { return getModel().getAnimations(); } @Override public boolean isModified() { return !getModel().getAnimations().isEmpty(); } @Override public IAssetKey getAssetKey() { if (getModel() instanceof AssetSpriteModel) { return ((AssetSpriteModel<?>) getModel()).getAssetKey(); } return null; } }; PGridStringProperty data_property = new PGridStringProperty(getId(), "data", help("Phaser.Sprite.data"), true) { @Override public boolean isModified() { String data = getModel().getData(); if (data == null) { return false; } return data.trim().length() > 0; } @Override public String getValue() { return getModel().getData(); } @Override public void setValue(String value, boolean notify) { getModel().setData(value); if (notify) { updateFromPropertyChange(); } } }; _spriteSection.add(_anchor_x_property); _spriteSection.add(_anchor_y_property); _spriteSection.add(_tint_property); _spriteSection.add(animations_properties); _spriteSection.add(data_property); propModel.getSections().add(_spriteSection); } protected PGridSection getSpriteSection() { return _spriteSection; } @Override public abstract double getTextureWidth(); @Override public abstract double getTextureHeight(); @Override public double getTextureLeft() { T model = getModel(); return model.getX() - getTextureWidth() * model.getAnchorX(); } @Override public double getTextureTop() { T model = getModel(); return model.getY() - getTextureHeight() * model.getAnchorY(); } @Override public double getTextureRight() { return getTextureLeft() + getTextureWidth(); } @Override public double getTextureBottom() { return getTextureTop() + getTextureHeight(); } }
package edu.iastate.cs.design.spec.stackexchange.request; import edu.iastate.cs.design.spec.stackexchange.objects.AnswerDTO; import edu.iastate.cs.design.spec.stackexchange.objects.QuestionDTO; import java.util.*; public class MockStackExchangeRequester implements IStackExchangeRequester { Map<QuestionDTO, List<AnswerDTO>> postMap; private int nextQuestionId; private int nextAnswerId; public MockStackExchangeRequester() { postMap = new HashMap<QuestionDTO, List<AnswerDTO>>(); nextQuestionId = 1; nextAnswerId = 1; } public QuestionDTO postQuestion(QuestionAddRequestData requestData) { QuestionDTO question = new QuestionDTO(requestData.getTitle(), requestData.getBody(), requestData.getTags(), nextQuestionId); postMap.put(question, new ArrayList<AnswerDTO>()); ++nextQuestionId; return question; } public List<AnswerDTO> getAnswersToQuestion(QuestionAnswersRequestData requestData) { QuestionDTO question = getQuestionByQuestionId(requestData.getId()); return postMap.get(question); } public AnswerDTO postAnswerToQuestion(AnswerQuestionRequestData requestData) { QuestionDTO question = getQuestionByQuestionId(requestData.getId()); // Will throw if question id didn't exist. Fine for the tests. AnswerDTO answer = new AnswerDTO(requestData.getBody(), nextAnswerId, question.getQuestionId()); List<AnswerDTO> answers = postMap.get(question); answers.add(answer); ++nextAnswerId; return answer; } private QuestionDTO getQuestionByQuestionId(int questionId) { for (QuestionDTO question : postMap.keySet()) { if (question.getQuestionId() == questionId) { return question; } } return null; } }
package sofia.internal.events; import java.util.List; import android.view.MotionEvent; /** * TODO document * * @author Tony Allevato * @version 2012.10.24 */ public class MotionEventDispatcher extends EventDispatcher { //~ Fields ................................................................ private MethodTransformer xyTransformer; //~ Constructors .......................................................... public MotionEventDispatcher(String method) { super(method); } //~ Protected methods ..................................................... @Override protected List<MethodTransformer> lookupTransformers( Object receiver, List<Class<?>> argTypes) { List<MethodTransformer> descriptors = super.lookupTransformers(receiver, argTypes); getXYTransformer().addIfSupportedBy(receiver, descriptors); return descriptors; } /** * Transforms an event with signature (MouseEvent event) to one with * signature (float x, float y). */ protected MethodTransformer getXYTransformer() { if (xyTransformer == null) { xyTransformer = new MethodTransformer(float.class, float.class) { protected Object[] transform(Object... args) { MotionEvent e = (MotionEvent) args[0]; return new Object[] { (float) e.getX(), (float) e.getY() }; } }; } return xyTransformer; } }
package is.heklapunch; import java.util.ArrayList; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TableLayout; public class OrganizeCreateActivity extends Activity { TableLayout station_table; SQLHandler handler; EditText stationNameField; EditText courseNameField; String stationName = ""; ArrayList<ArrayList<String>> stationList = new ArrayList<ArrayList<String>>(); int stationNumber = 1; Spinner courseSpinner; public CourseData[] courses; int selectedCourseID = -1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_organize_create); // create database object handler = new SQLHandler(this); courseNameField = (EditText) findViewById(R.id.editTextCourseName); stationNameField = (EditText) findViewById(R.id.EditTextStationName); // populate the spinner courses = handler.getCourseIDs(); if (courses != null) { courseSpinner = (Spinner) findViewById(R.id.spinner1); ArrayAdapter<CourseData> adapter = new ArrayAdapter<CourseData>( this, android.R.layout.simple_spinner_item, handler.getCourseIDs()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); courseSpinner.setAdapter(adapter); courseSpinner .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { CourseData data = courses[position]; selectedCourseID = Integer.valueOf(data.getValue()); } public void onNothingSelected(AdapterView<?> parent) { } }); } } public void createCourse(View view) { Intent intent = new Intent(this, OrganizeModifyActivity.class); Bundle b = new Bundle(); b.putInt("courseID", -1); intent.putExtras(b); startActivity(intent); finish(); } public void modifyCourse(View view) { Intent intent = new Intent(this, OrganizeModifyActivity.class); Bundle b = new Bundle(); b.putInt("courseID", selectedCourseID); intent.putExtras(b); startActivity(intent); finish(); } }
package gui; import com.googlecode.dex2jar.reader.DexFileReader; import parser.apk.APK; import parser.dex.DexClass; import parser.dex.DexFileAdapter; import utils.FileDrop; import utils.UtilLocal; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.*; import java.util.List; public class FeatureCode extends JPanel { final JTextArea stringList; JTree treePkg; public FeatureCode() { setLayout(new BorderLayout(0, 0)); final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitPane.setDividerLocation(250); add(splitPane, BorderLayout.CENTER); treePkg = new JTree(); treePkg.setRootVisible(false); treePkg.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); JScrollPane jScrollPaneLeft = new JScrollPane(treePkg); splitPane.setLeftComponent(jScrollPaneLeft); stringList = new JTextArea(); stringList.setText("\n" + "\n" + "\n" + " APK \n" + ""); JScrollPane jScrollPaneRight = new JScrollPane(stringList); jScrollPaneRight.setViewportView(stringList); splitPane.setRightComponent(jScrollPaneRight); new FileDrop(System.out, treePkg, /* dragBorder, */new FileDrop.Listener() { @Override public void filesDropped(java.io.File[] files) { createNodes(files); } }); treePkg.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent treeSelectionEvent) { JTree treeSource = (JTree) treeSelectionEvent.getSource(); TreePath[] treePaths = treeSource.getSelectionPaths(); if (treePaths == null) { return; } ArrayList<ClassNode> classNodes = new ArrayList<>(); stringList.setText(""); for (TreePath treePath : treePaths) { final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) treePath.getLastPathComponent(); if (treeNode.getUserObject() instanceof DexClass) { classNodes.add((ClassNode) treeNode); } else { classNodes.addAll(getClassNodes(treeNode)); } } stringList.append(getStrings(classNodes).replace("[<i>", "<i>").replace(", <i>", "<i>")); //get the current lead path final TreePath newPath = treeSelectionEvent.getNewLeadSelectionPath(); if (newPath == null) return; final DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) newPath.getLastPathComponent(); if (selectNode.getUserObject() instanceof DexFileReader) { final DexFileReader dexFile = (DexFileReader) selectNode.getUserObject(); System.out.println("dexFile.getClassSize : " + dexFile.getClassSize()); } else if (selectNode.getUserObject() instanceof DexClass) { DexClass classDefItem = (DexClass) selectNode.getUserObject(); StringBuilder sb = new StringBuilder(); List<String> strList = classDefItem.stringData; Collections.sort(strList); for (String str : strList) { sb.append("<i>").append(str).append("</i>").append('\n'); } stringList.setText(sb.toString()); } else { stringList.setText(getStrings(getClassNodes(selectNode)) .replace("[<i>", "<i>").replace(", <i>", "<i>")); } } }); } /** * @param parent * @param packageName * @return */ public static DefaultMutableTreeNode findOrAddNode(TreePath parent, String packageName) { final DefaultMutableTreeNode node = (DefaultMutableTreeNode) parent.getLastPathComponent(); for (final Enumeration e = node.children(); e.hasMoreElements(); ) { final DefaultMutableTreeNode mutableTreeNode = (DefaultMutableTreeNode) e.nextElement(); if (packageName.equals(mutableTreeNode.toString())) return mutableTreeNode; } final DefaultMutableTreeNode nodeCls = new DefaultMutableTreeNode(packageName); node.add(nodeCls); return nodeCls; } /** * * * @param selectNode * @return */ ArrayList<ClassNode> getClassNodes(DefaultMutableTreeNode selectNode) { ArrayList<ClassNode> classNodes = new ArrayList<>(); for (final Enumeration ee = selectNode.children(); ee.hasMoreElements(); ) { final DefaultMutableTreeNode n = (DefaultMutableTreeNode) ee.nextElement(); if (n.isLeaf()) { classNodes.add((ClassNode) n); } else { ArrayList<ClassNode> subClassNodes = getClassNodes(n); classNodes.addAll(subClassNodes); } } return classNodes; } /** * * * @param classNodes * @return */ private String getStrings(ArrayList<ClassNode> classNodes) { HashSet<String> hashSet = new HashSet<>(); for (ClassNode classNode : classNodes) { List<String> strList = classNode.dexClass.stringData; for (String str : strList) { hashSet.add("<i>" + str + "</i>" + '\n'); } } ArrayList<String> arrayList = new ArrayList<>(hashSet); Collections.sort(arrayList); return arrayList.toString(); } /** * * * @param files drop files... */ private void createNodes(File[] files) { final DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Files"); APK apk; // 1.parse files for (final File file : files) { DexFileReader dexFileReader; try { dexFileReader = new DexFileReader(file); } catch (IOException e) { e.printStackTrace(); continue; } DefaultMutableTreeNode fileNode = new FileNode(dexFileReader, file.getAbsolutePath()); rootNode.add(fileNode); // initialize class List, and sort them. final List<DexClass> classList = new ArrayList<>(); // final List<DexClass> classList = apk.getDexClasses(); // DexFileReader dexFileReader = apk.getDexFileReader(); try { dexFileReader.accept(new DexFileAdapter(classList), DexFileReader.SKIP_DEBUG | DexFileReader.SKIP_ANNOTATION); } catch (Exception e) { System.out.println("Accept Code Failed." + e.getMessage()); return; } //sort Collections.sort(classList, new ComparatorClass()); for (final DexClass dexClass : classList) { // com.pkg1.pkg2.cls; String className = dexClass.className; // com pkg1 pkg2 cls final String[] strings = className.substring(1, className.length() - 1).split("/"); if (UtilLocal.DEBUG) { System.out.print(className + " "); for (String name : strings) { System.out.print(name + " "); } System.out.println(); } int len = strings.length; DefaultMutableTreeNode pkgNode = fileNode; for (int i = 0; i < len - 1; i++) { pkgNode = findOrAddNode(new TreePath(pkgNode), strings[i]); } ClassNode classNode = new ClassNode(dexClass); pkgNode.add(classNode); } treePkg.setModel(new DefaultTreeModel(rootNode)); } } private class FileNode extends DefaultMutableTreeNode { String fileName; public FileNode(DexFileReader dexFileReader, String filePath) { super(dexFileReader, true); fileName = new File(filePath).getName(); } @Override public String toString() { return fileName; } } // class PackageNode { // String packageName; // PackageNode(String packageName) { // this.packageName = packageName; // @Override // public String toString() { // return packageName; class ClassNode extends DefaultMutableTreeNode { String className; DexClass dexClass; ClassNode(DexClass dexClass) { super(dexClass, true); final String[] strings = dexClass.className.substring (1, dexClass.className.length() - 1).split("/"); className = strings[strings.length - 1]; this.dexClass = dexClass; } @Override public String toString() { return className; } } /** * ClassDefItem */ public class ComparatorClass implements Comparator<DexClass> { @Override public int compare(DexClass arg0, DexClass arg1) { final String name0 = arg0.className; final String name1 = arg1.className; if (name0.contains("/")) { if (name1.contains("/")) { return name0.compareTo(name1); } else { return "".compareTo(name0); } } if (name1.contains("/")) { return name1.compareTo(""); } else { return name0.compareTo(name1); } } } }
package it.unimi.dsi.sux4j.mph; import it.unimi.dsi.Util; import it.unimi.dsi.bits.LongArrayBitVector; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntHeapIndirectPriorityQueue; import it.unimi.dsi.fastutil.longs.LongBigList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class Modulo3System { private final static boolean DEBUG = false; /** A modulo-3 equation. */ public static class Modulo3Equation { /** The constant term. */ protected int c; private final int numVars; protected final LongArrayBitVector bv; protected final long[] bits; private final LongBigList list; protected int coeff; private int firstVar; private int firstCoeff; private int wordIndex; private long word; public IntArrayList initialVars; private boolean isEmpty; /** Creates a new equation. * * @param c the constant term. */ public Modulo3Equation( final int c, final int numVars ){ this.c = c; this.bv = LongArrayBitVector.ofLength( numVars * 2 ); this.numVars = numVars; this.bits = bv.bits(); this.list = bv.asLongBigList( 2 ); this.firstVar = Integer.MAX_VALUE; this.initialVars = new IntArrayList(); this.isEmpty = true; } protected Modulo3Equation( final Modulo3Equation equation ){ this.c = equation.c; this.bv = equation.bv.copy(); this.bits = this.bv.bits(); this.numVars = equation.numVars; this.list = this.bv.asLongBigList( 2 ); this.firstVar = equation.firstVar; this.firstCoeff = equation.firstCoeff; this.initialVars = equation.initialVars; this.isEmpty = equation.isEmpty; } public Modulo3Equation add( final int index, final int value ) { if ( list.set( index, value ) != 0 ) throw new IllegalArgumentException(); initialVars.add( index ); if ( index < firstVar ) { firstVar = index; firstCoeff = value; } isEmpty = false; return this; } public Modulo3Equation add( final int index ) { return add( index, 1 ); } public int[] variables() { IntArrayList variables = new IntArrayList(); for( int var = firstVar(); var != Integer.MAX_VALUE; var = nextVar() ) variables.add( var ); return variables.toIntArray(); } public int[] coefficients() { IntArrayList coefficients = new IntArrayList(); for( int var = firstVar(); var != Integer.MAX_VALUE; var = nextVar() ) coefficients.add( coeff ); return coefficients.toIntArray(); } public Modulo3Equation eliminate( final Modulo3Equation equation, final int var ) { final int mul = this.list.get( var ) == equation.list.get( var ) ? 1 : 2; sub( equation, mul ); return this; //System.err.println( this + " - " + mul + " * " + equation + " => " + result ); //assert result.sub( equation, 3 - mul ).equals( this ) : result.sub( equation, 3 - mul ) + " != " + this; } protected final static long addMod3( final long x, final long y ) { // mask the high bit of each pair set iff the result of the // sum in that position is >= 3 // check if x is 2 and y is nonzero ... long mask = x & (y | (y << 1)); // ... or x is 1 and y is 2 mask |= (x << 1) & y; // clear the low bits mask &= 0x5555555555555555L << 1; // and turn 2s into 3s mask |= mask >> 1; return (x + y) - mask; } protected final static long subMod3( final long x, long y ) { // Change of sign y = ( y & 0x5555555555555555L ) << 1 | ( y & 0xAAAAAAAAAAAAAAAAL ) >>> 1; // mask the high bit of each pair set iff the result of the // sum in that position is >= 3 // check if x is 2 and y is nonzero ... long mask = x & ( y | (y << 1) ); // ... or x is 1 and y is 2 mask |= (x << 1) & y; // clear the low bits mask &= 0x5555555555555555L << 1; // and turn 2s into 3s mask |= mask >> 1; return (x + y) - mask; } public void setFirstVar() { if ( isEmpty ) firstVar = Integer.MAX_VALUE; else { int i = -1; while( bits[ ++i ] == 0 ); final int lsb = Long.numberOfTrailingZeros( bits[ i ] ) / 2; firstVar = lsb + 32 * i; firstCoeff = (int)( bits[ i ] >> lsb * 2 & 3 ); } } private final void addMod3( final LongArrayBitVector x, final LongArrayBitVector y ) { final long[] bx = x.bits(), by = y.bits(); boolean isNotEmpty = false; for( int i = (int)( ( x.length() + 63 ) / 64 ); i isNotEmpty |= ( bx[ i ] = addMod3( bx[ i ], by[ i ] ) ) != 0; isEmpty = ! isNotEmpty; } private final void subMod3( final LongArrayBitVector x, final LongArrayBitVector y ) { final long[] bx = x.bits(), by = y.bits(); boolean isNotEmpty = false; for( int i = (int)( ( x.length() + 63 ) / 64 ); i isNotEmpty |= ( bx[ i ] = subMod3( bx[ i ], by[ i ] ) ) != 0; isEmpty = ! isNotEmpty; } /** Subtract from this equation another equation multiplied by a provided constant. * * @param equation the subtrahend. * @param mul a multiplier that will be applied to the subtrahend. */ public void sub( final Modulo3Equation equation, final int mul ) { // Explicit multiplication tables to avoid modulo operators. if ( mul == 1 ) { c = ( c + 2 * equation.c ) % 3; subMod3( bv, equation.bv ); } else { c = ( c + equation.c ) % 3; addMod3( bv, equation.bv ); } } public int firstVar() { setFirstVar(); if ( firstVar == Integer.MAX_VALUE ) return Integer.MAX_VALUE; coeff = firstCoeff; wordIndex = firstVar / 32; word = bits[ wordIndex ]; assert firstVar == wordIndex * 32 + Long.numberOfTrailingZeros( word ) / 2; word &= word - 1; return firstVar; } public int nextVar() { while( word == 0 && ++wordIndex < bits.length ) word = bits[ wordIndex ]; if ( wordIndex == bits.length ) return Integer.MAX_VALUE; final int lsb = Long.numberOfTrailingZeros( word ); final int nextVar = wordIndex * 32 + lsb / 2; coeff = (int)( word >> ( lsb & ~1 ) & 3 ); word &= word - 1; return nextVar; } public boolean isUnsolvable() { return isEmpty && c != 0; } public boolean isIdentity() { return isEmpty && c == 0; } @Override public boolean equals( Object o ) { if ( ! ( o instanceof Modulo3Equation ) ) return false; final Modulo3Equation equation = (Modulo3Equation)o; return c == equation.c && bv.equals( equation.bv ); } public void normalized( final long[] result ) { final long[] bits = this.bits; // Drop coefficients for( int i = bits.length; i-- != 0; ) result[ i ] = ( bits[ i ] & 0x5555555555555555L ) | ( bits[ i ] & 0xAAAAAAAAAAAAAAAAL ) >>> 1; } public String toString() { StringBuilder b = new StringBuilder(); boolean someNonZero = false; for( int i = 0; i < list.size(); i++ ) { if ( list.getLong( i ) != 0 ) { if ( someNonZero ) b.append( " + " ); someNonZero = true; b.append( list.getLong( i ) == 1 ? "x" : "2x" ).append( '_' ).append( i ); } } if ( ! someNonZero ) b.append( '0' ); return b.append( " = " ).append( c ).toString(); } public Modulo3Equation copy() { return new Modulo3Equation( this ); } } private final ArrayList<Modulo3Equation> equations; private final int numVars; public Modulo3System( final int numVar ) { equations = new ArrayList<Modulo3Equation>(); this.numVars = numVar; } protected Modulo3System( ArrayList<Modulo3Equation> system, final int numVar ) { this.equations = system; this.numVars = numVar; } public Modulo3System copy() { ArrayList<Modulo3Equation> list = new ArrayList<Modulo3System.Modulo3Equation>( equations.size() ); for( Modulo3Equation equation: equations ) list.add( equation.copy() ); return new Modulo3System( list, numVars ); } @Override public String toString() { StringBuilder b = new StringBuilder(); for ( int i = 0; i < equations.size(); i++ ) b.append( equations.get( i ) ).append( '\n' ); return b.toString(); } public void add( Modulo3Equation equation ) { if ( equation.numVars != numVars ) throw new IllegalArgumentException( "The number of variables in the equation (" + equation.list.size() + ") does not match the number of variables of the system (" + numVars + ")" ); equations.add( equation ); } public boolean echelonForm() { main: for ( int i = 0; i < equations.size() - 1; i++ ) { assert equations.get( i ).firstVar != Integer.MAX_VALUE; for ( int j = i + 1; j < equations.size(); j++ ) { // Note that because of exchanges we cannot extract the first assignment Modulo3Equation eqJ = equations.get( j ); Modulo3Equation eqI = equations.get( i ); assert eqI.firstVar != Integer.MAX_VALUE; assert eqJ.firstVar != Integer.MAX_VALUE; final int firstVar = eqI.firstVar; if( firstVar == eqJ.firstVar ) { eqI.eliminate( eqJ, firstVar ); if ( eqI.isUnsolvable() ) return false; if ( eqI.isIdentity() ) continue main; eqI.setFirstVar(); } if ( eqI.firstVar > eqJ.firstVar ) Collections.swap( equations, i, j ); } } return true; } public boolean structuredGaussianElimination( final int[] solution ) { assert solution.length == numVars; LongArrayBitVector solutions = LongArrayBitVector.ofLength( numVars * 2 ); if ( ! structuredGaussianElimination( solutions ) ) return false; final LongBigList list = solutions.asLongBigList( 2 ); for( int i = solution.length; i-- != 0; ) solution[ i ] = (int)list.getLong( i ); return true; } public boolean structuredGaussianElimination( final LongArrayBitVector solution ) { assert solution.length() == numVars * 2; if ( DEBUG ) { System.err.println(); System.err.println( "====================" ); System.err.println(); System.err.println( this ); } final int numEquations = equations.size(); if ( numEquations == 0 ) return true; /* The weight of each variable, that is, the opposite of number of equations still * in the queue in which the variable appears. We use negative weights to have * variables of weight of maximum modulus at the top of the queue. */ final int weight[] = new int[ numVars ]; // For each variable, the equations still in the queue containing it. final IntArrayList[] varEquation = new IntArrayList[ numVars ]; // The priority of each equation still in the queue (the number of light variables). final int[] priority = new int[ numEquations ]; for( int i = 0; i < numEquations; i++ ) { final Modulo3Equation equation = equations.get( i ); // Initially, all variables are light. final int[] elements = equation.initialVars.elements(); for( int j = equation.initialVars.size(); j final int var = elements[ j ]; if ( varEquation[ var ] == null ) varEquation[ var ] = new IntArrayList( 8 ); weight[ var ] varEquation[ var ].add( i ); priority[ i ]++; } } final boolean[] isHeavy = new boolean[ numVars ]; IntHeapIndirectPriorityQueue variableQueue = new IntHeapIndirectPriorityQueue( weight, Util.identity( numVars ) ); // The equations that are neither dense, nor solved. IntHeapIndirectPriorityQueue equationQueue = new IntHeapIndirectPriorityQueue( priority, Util.identity( numEquations ) ); ArrayList<Modulo3Equation> dense = new ArrayList<Modulo3Equation>(); ArrayList<Modulo3Equation> solved = new ArrayList<Modulo3Equation>(); IntArrayList pivots = new IntArrayList(); final long[] normalized = new long[ equations.get( 0 ).bits.length ]; final long[] lightNormalized = new long[ normalized.length ]; Arrays.fill( lightNormalized, -1L ); while( ! equationQueue.isEmpty() ) { final int first = equationQueue.first(); // Index of the equation of minimum weight Modulo3Equation firstEquation = equations.get( first ); if ( DEBUG ) System.err.println( "Looking at equation " + first + " of priority " + priority[ first ] + " : " + firstEquation ); if ( priority[ first ] == 0 ) { equationQueue.dequeue(); if ( firstEquation.isUnsolvable() ) return false; if ( firstEquation.isIdentity() ) continue; /* This equation must be necessarily solved by standard Gaussian elimination. No updated * is needed, as all its variables are heavy. */ dense.add( firstEquation ); } else if ( priority[ first ] == 1 ) { equationQueue.dequeue(); /* This is solved (in terms of the heavy variables). Let's find the pivot, that is, * the only light variable. Note that we do not need to update varEquation[] of any variable, as they * are all either heavy (the non-pivot), or appearing only in this equation (the pivot). */ firstEquation.normalized( normalized ); for( int i = normalized.length; i-- != 0; ) normalized[ i ] &= lightNormalized[ i ]; int wordIndex = 0; while( ( normalized[ wordIndex ] & lightNormalized[ wordIndex ] ) == 0 ) wordIndex++; final int pivot = wordIndex * 32 + Long.numberOfTrailingZeros( normalized[ wordIndex ] & lightNormalized[ wordIndex ] ) / 2; // Record the light variable and the equation for computing it later. if ( DEBUG ) System.err.println( "Adding to solved variables x_" + pivot + " by equation " + firstEquation ); pivots.add( pivot ); solved.add( firstEquation ); variableQueue.remove( pivot ); // Pivots cannot become heavy // Now we need to eliminate the variable from all other equations containing it. final int[] elements = varEquation[ pivot ].elements(); for( int i = varEquation[ pivot ].size(); i final int equationIndex = elements[ i ]; if ( equationIndex == first ) continue; priority[ equationIndex ] equationQueue.changed( equationIndex ); final Modulo3Equation equation = equations.get( equationIndex ); if ( DEBUG ) System.err.print( "Replacing equation (" + equationIndex + ") " + equation + " with " ); equation.eliminate( firstEquation, pivot ); if ( DEBUG ) System.err.println( equation ); } } else { // Make another variable heavy final int var = variableQueue.dequeue(); isHeavy[ var ] = true; lightNormalized[ var / 32 ] ^= 1L << ( var % 32 ) * 2; if ( DEBUG ) { int numHeavy = 0; for( boolean b: isHeavy ) if ( b ) numHeavy++; System.err.println( "Making variable " + var + " of weight " + ( - weight[ var ] ) + " heavy (" + numHeavy + " heavy variables, " + equationQueue.size() + " equations to go)" ); } final int[] elements = varEquation[ var ].elements(); for( int i = varEquation[ var ].size(); i final int equationIndex = elements[ i ]; priority[ equationIndex ] equationQueue.changed( equationIndex ); } } } if ( DEBUG ) { int numHeavy = 0; for( boolean b: isHeavy ) if ( b ) numHeavy++; System.err.println( "Heavy variables: " + numHeavy + " (" + Util.format( numHeavy * 100 / numVars ) + "%)" ); System.err.println( "Dense equations: " + dense ); System.err.println( "Solved equations: " + solved ); System.err.println( "Pivots: " + pivots ); } Modulo3System denseSystem = new Modulo3System( dense, numVars ); if ( ! denseSystem.gaussianElimination( solution ) ) return false; // numVars >= denseSystem.numVars final long[] solutionBits = solution.bits(); final LongBigList solutionList = solution.asLongBigList( 2 ); if ( DEBUG ) System.err.println( "Solution (dense): " + solutionList ); for ( int i = solved.size(); i final Modulo3Equation equation = solved.get( i ); final int pivot = pivots.getInt( i ); assert solutionList.getLong( pivot ) == 0 : pivot; final int pivotCoefficient = (int)equation.list.getLong( pivot ); int sum = 0; final long[] bits = equation.bits; for( int j = solutionBits.length; j final long high = bits[ j ] & 0xAAAAAAAAAAAAAAAAL; final long low = bits[ j ] & 0x5555555555555555L; final long highShift = high >>> 1; // Make every 10 into a 11 and zero everything else long t = ( solutionBits[ j ] ^ ( high | highShift ) ) & ( bits[ j ] | highShift | low << 1 ); // Exchange ones with twos, and make 00 into 11 sum += Long.bitCount( t & 0xAAAAAAAAAAAAAAAAL ) * 2 + Long.bitCount( t & 0x5555555555555555L ); } sum = ( equation.c - sum ) % 3; if ( sum < 0 ) sum += 3; assert pivotCoefficient != -1; solutionList.set( pivot, sum == 0 ? 0 : pivotCoefficient == sum ? 1 : 2 ); } if ( DEBUG ) System.err.println( "Solution (all): " + solutionList ); return true; } public boolean gaussianElimination( final int[] solution ) { assert solution.length == numVars; LongArrayBitVector solutions = LongArrayBitVector.ofLength( numVars * 2 ); if ( ! gaussianElimination( solutions ) ) return false; final LongBigList list = solutions.asLongBigList( 2 ); for( int i = solution.length; i-- != 0; ) solution[ i ] = (int)list.getLong( i ); return true; } public boolean gaussianElimination( final LongArrayBitVector solution ) { assert solution.length() == numVars * 2; for ( Modulo3Equation equation: equations ) equation.setFirstVar(); if ( ! echelonForm() ) return false; final long[] solutionBits = solution.bits(); final LongBigList solutionList = solution.asLongBigList( 2 ); for ( int i = equations.size(); i final Modulo3Equation equation = equations.get( i ); if ( equation.isIdentity() ) continue; assert solutionList.getLong( equation.firstVar ) == 0 : equation.firstVar; int sum = 0; final long[] bits = equation.bits; for( int j = solutionBits.length; j final long high = bits[ j ] & 0xAAAAAAAAAAAAAAAAL; final long low = bits[ j ] & 0x5555555555555555L; final long highShift = high >>> 1; // Make every 10 into a 11 and zero everything else long t = ( solutionBits[ j ] ^ ( high | highShift ) ) & ( bits[ j ] | highShift | low << 1 ); // Exchange ones with twos, and make 00 into 11 sum += Long.bitCount( t & 0xAAAAAAAAAAAAAAAAL ) * 2 + Long.bitCount( t & 0x5555555555555555L ); } sum = ( equation.c - sum ) % 3; if ( sum < 0 ) sum += 3; solutionList.set( equation.firstVar, sum == 0 ? 0 : equation.firstCoeff == sum ? 1 : 2 ); } return true; } public int size() { return equations.size(); } public boolean check( final int solution[] ) { for( Modulo3Equation equation: equations ) { int sum = 0; for( int var = equation.firstVar(); var != Integer.MAX_VALUE; var = equation.nextVar() ) sum = ( sum + solution[ var ] * equation.coeff ) % 3; if ( equation.c != sum ) { // System.err.println( equation + " " + Arrays.toString( solution ) ); return false; } } return true; } }
package jade.core.messaging; import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; import java.util.Date; import jade.core.ServiceFinder; import jade.core.VerticalCommand; import jade.core.GenericCommand; import jade.core.Service; import jade.core.BaseService; import jade.core.ServiceException; import jade.core.Filter; import jade.core.Node; import jade.core.AgentContainerImpl; import jade.core.MainContainerImpl; import jade.core.CaseInsensitiveString; import jade.core.AID; import jade.core.ContainerID; import jade.core.Profile; import jade.core.Specifier; import jade.core.ProfileException; import jade.core.IMTPException; import jade.core.NotFoundException; import jade.core.UnreachableException; import jade.domain.FIPAAgentManagement.InternalError; import jade.domain.FIPAAgentManagement.Envelope; import jade.domain.FIPAAgentManagement.ReceivedObject; import jade.security.Authority; import jade.security.AgentPrincipal; import jade.security.PrivilegedExceptionAction; import jade.security.AuthException; import jade.lang.acl.ACLMessage; import jade.lang.acl.ACLCodec; import jade.lang.acl.StringACLCodec; import jade.mtp.MTP; import jade.mtp.MTPDescriptor; import jade.mtp.MTPException; import jade.mtp.InChannel; import jade.mtp.TransportAddress; import jade.util.leap.Iterator; import jade.util.leap.Map; import jade.util.leap.HashMap; import jade.util.leap.List; /** The JADE service to manage the message passing subsystem installed on the platform. @author Giovanni Rimassa - FRAMeTech s.r.l. */ public class MessagingService extends BaseService implements MessageManager.Channel { public static class UnknownACLEncodingException extends NotFoundException { UnknownACLEncodingException(String msg) { super(msg); } } // End of UnknownACLEncodingException class /** The name of this service. */ public static final String NAME = "Messaging"; /** This command name represents the action of sending an ACL message from an agent to another. */ public static final String SEND_MESSAGE = "Send-Message"; /** This command name represents the <code>install-mtp</code> action. */ public static final String INSTALL_MTP = "Install-MTP"; /** This command name represents the <code>uninstall-mtp</code> action. */ public static final String UNINSTALL_MTP = "Uninstall-MTP"; /** This command name represents the <code>set-platform-addresses</code> action. */ public static final String SET_PLATFORM_ADDRESSES = "Set-Platform-Addresses"; public static final String MAIN_SLICE = "Main-Container"; public MessagingService(AgentContainerImpl ac, Profile p) throws ProfileException { super(p); myContainer = ac; cachedSlices = new HashMap(); // Initialize its own ID String platformID = myContainer.getPlatformID(); accID = "fipa-mts://" + platformID + "/acc"; myMessageManager = new MessageManager(); myMessageManager.initialize(p, this); // Create a local slice localSlice = new ServiceComponent(); } public String getName() { return NAME; } public Class getHorizontalInterface() { return MessagingSlice.class; } public Slice getLocalSlice() { return localSlice; } public Filter getCommandFilter() { return localSlice; } /** Inner mix-in class for this service: this class receives commands through its <code>Filter</code> interface and serves them, coordinating with remote parts of this service through the <code>Slice</code> interface (that extends the <code>Service.Slice</code> interface). */ private class ServiceComponent implements Filter, MessagingSlice { public Iterator getAddresses() { return routes.getAddresses(); } // Entry point for the ACL message dispatching process public void deliverNow(ACLMessage msg, AID receiverID) throws UnreachableException, NotFoundException { try { MainContainerImpl impl = myContainer.getMain(); if(impl != null) { while(true) { // Directly use the GADT on the main container ContainerID cid = impl.getContainerID(receiverID); MessagingSlice targetSlice = (MessagingSlice)getSlice(cid.getName()); try { targetSlice.dispatchLocally(msg, receiverID); return; // Message dispatched } catch(NotFoundException nfe) { // The agent was found in he GADT, but not in the target LADT => try again } } } else { // Try first with the cached <AgentID;Container ID> pairs MessagingSlice cachedSlice = (MessagingSlice)cachedSlices.get(receiverID); if(cachedSlice != null) { // Cache hit :-) try { System.out.println(" cachedSlice.dispatchLocally(msg, receiverID); } catch(IMTPException imtpe) { cachedSlices.remove(receiverID); // Eliminate stale cache entry deliverUntilOK(msg, receiverID); } catch(NotFoundException nfe) { cachedSlices.remove(receiverID); // Eliminate stale cache entry deliverUntilOK(msg, receiverID); } } else { // Cache miss :-( System.out.println(" deliverUntilOK(msg, receiverID); } } } catch(IMTPException imtpe) { throw new UnreachableException("Unreachable network node", imtpe); } catch(ServiceException se) { throw new UnreachableException("Unreachable service slice:", se); } } private void deliverUntilOK(ACLMessage msg, AID receiverID) throws IMTPException, NotFoundException, ServiceException { boolean ok = false; do { MessagingSlice mainSlice = (MessagingSlice)getSlice(MAIN_SLICE); ContainerID cid = mainSlice.getAgentLocation(receiverID); MessagingSlice targetSlice = (MessagingSlice)getSlice(cid.getName()); try { targetSlice.dispatchLocally(msg, receiverID); System.out.println(" // On successful message dispatch, put the slice into the slice cache cachedSlices.put(receiverID, targetSlice); ok = true; } catch(NotFoundException nfe) { ok = false; // Stale proxy again, maybe the receiver is running around. Try again... } } while(!ok); } // Implementation of the Filter interface public void accept(VerticalCommand cmd) { // FIXME: Should set the exception somehow... try { String name = cmd.getName(); if(name.equals(SEND_MESSAGE)) { handleSendMessage(cmd); } if(name.equals(INSTALL_MTP)) { Object result = handleInstallMTP(cmd); cmd.setReturnValue(result); } else if(name.equals(UNINSTALL_MTP)) { handleUninstallMTP(cmd); } else if(name.equals(SET_PLATFORM_ADDRESSES)) { handleSetPlatformAddresses(cmd); } } catch(AuthException ae) { cmd.setReturnValue(ae); } catch(IMTPException imtpe) { imtpe.printStackTrace(); } catch(NotFoundException nfe) { nfe.printStackTrace(); } catch(ServiceException se) { se.printStackTrace(); } catch(MTPException mtpe) { mtpe.printStackTrace(); } } public void setBlocking(boolean newState) { // Do nothing. Blocking and Skipping not supported } public boolean isBlocking() { return false; // Blocking and Skipping not implemented } public void setSkipping(boolean newState) { // Do nothing. Blocking and Skipping not supported } public boolean isSkipping() { return false; // Blocking and Skipping not implemented } // Implementation of the Service.Slice interface public Service getService() { return MessagingService.this; } public Node getNode() throws ServiceException { try { return MessagingService.this.getLocalNode(); } catch(IMTPException imtpe) { throw new ServiceException("Problem in contacting the IMTP Manager", imtpe); } } // Implementation of the service-specific horizontal interface MessagingSlice public void dispatchLocally(ACLMessage msg, AID receiverID) throws IMTPException, NotFoundException { boolean found = myContainer.postMessageToLocalAgent(msg, receiverID); if(!found) { throw new NotFoundException("Messaging service slice failed to find " + receiverID); } } public void routeOut(ACLMessage msg, AID receiverID, String address) throws IMTPException, MTPException { RoutingTable.OutPort out = routes.lookup(address); if(out != null) out.route(msg, receiverID, address); else throw new MTPException("No suitable route found for address " + address + "."); } public ContainerID getAgentLocation(AID agentID) throws IMTPException, NotFoundException { MainContainerImpl impl = myContainer.getMain(); if(impl != null) { return impl.getContainerID(agentID); } else { // Do nothing for now, but could also have a local GADT copy, thus enabling e.g. Main Container replication return null; } } public MTPDescriptor installMTP(String address, String className) throws IMTPException, ServiceException, MTPException { try { // Create the MTP Class c = Class.forName(className); MTP proto = (MTP)c.newInstance(); InChannel.Dispatcher dispatcher = new InChannel.Dispatcher() { public void dispatchMessage(Envelope env, byte[] payload) { // To avoid message loops, make sure that the ID of this ACC does // not appear in a previous 'received' stamp ReceivedObject[] stamps = env.getStamps(); for(int i = 0; i < stamps.length; i++) { String id = stamps[i].getBy(); if(CaseInsensitiveString.equalsIgnoreCase(id, accID)) { System.out.println("ERROR: Message loop detected !!!"); System.out.println("Route is: "); for(int j = 0; j < stamps.length; j++) System.out.println("[" + j + "]" + stamps[j].getBy()); System.out.println("Message dispatch aborted."); return; } } // Put a 'received-object' stamp in the envelope ReceivedObject ro = new ReceivedObject(); ro.setBy(accID); ro.setDate(new Date()); env.setReceived(ro); // Decode the message, according to the 'acl-representation' slot String aclRepresentation = env.getAclRepresentation(); // Default to String representation if(aclRepresentation == null) aclRepresentation = StringACLCodec.NAME; ACLCodec codec = (ACLCodec)messageEncodings.get(aclRepresentation.toLowerCase()); if(codec == null) { System.out.println("Unknown ACL codec: " + aclRepresentation); return; } try { ACLMessage msg = codec.decode(payload); msg.setEnvelope(env); // If the 'sender' AID has no addresses, replace it with the // 'from' envelope slot AID sender = msg.getSender(); if(sender == null) { System.out.println("ERROR: Trying to dispatch a message with a null sender."); System.out.println("Aborting send operation..."); return; } Iterator itSender = sender.getAllAddresses(); if(!itSender.hasNext()) msg.setSender(env.getFrom()); Iterator it = env.getAllIntendedReceiver(); // If no 'intended-receiver' is present, use the 'to' slot (but // this should not happen). if(!it.hasNext()) it = env.getAllTo(); while(it.hasNext()) { AID receiver = (AID)it.next(); boolean found = myContainer.postMessageToLocalAgent(msg, receiver); if(!found) { myMessageManager.deliver(msg, receiver); } } } catch(ACLCodec.CodecException ce) { ce.printStackTrace(); } } }; if(address == null) { // Let the MTP choose the address TransportAddress ta = proto.activate(dispatcher); address = proto.addrToStr(ta); } else { // Convert the given string into a TransportAddress object and use it TransportAddress ta = proto.strToAddr(address); proto.activate(dispatcher, ta); } routes.addLocalMTP(address, proto); MTPDescriptor result = new MTPDescriptor(proto.getName(), new String[] {address}, proto.getSupportedProtocols()); MessagingSlice mainSlice = (MessagingSlice)getSlice(MAIN_SLICE); mainSlice.newMTP(result, myContainer.getID()); return result; } catch(ClassNotFoundException cnfe) { throw new MTPException("ERROR: The class " + className + " for the " + address + " MTP was not found"); } catch(InstantiationException ie) { throw new MTPException("The class " + className + " raised InstantiationException (see nested exception)", ie); } catch(IllegalAccessException iae) { throw new MTPException("The class " + className + " raised IllegalAccessException (see nested exception)", iae); } } public void uninstallMTP(String address) throws IMTPException, ServiceException, NotFoundException, MTPException { MTP proto = routes.removeLocalMTP(address); if(proto != null) { TransportAddress ta = proto.strToAddr(address); proto.deactivate(ta); MTPDescriptor desc = new MTPDescriptor(proto.getName(), new String[] {address}, proto.getSupportedProtocols()); MessagingSlice mainSlice = (MessagingSlice)getSlice(MAIN_SLICE); mainSlice.deadMTP(desc, myContainer.getID()); } else { throw new MTPException("No such address was found on this container: " + address); } } public void newMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException, ServiceException { MainContainerImpl impl = myContainer.getMain(); if(impl != null) { // Update the routing tables of all the other slices Slice[] slices = getAllSlices(); for(int i = 0; i < slices.length; i++) { try { MessagingSlice slice = (MessagingSlice)slices[i]; String sliceName = slice.getNode().getName(); if(!sliceName.equals(cid.getName())) { slice.addRoute(mtp, cid.getName()); } } catch(Throwable t) { // Re-throw allowed exceptions if(t instanceof IMTPException) { throw (IMTPException)t; } if(t instanceof ServiceException) { throw (ServiceException)t; } System.out.println(" } } impl.newMTP(mtp, cid); } else { // Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication } } public void deadMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException, ServiceException { MainContainerImpl impl = myContainer.getMain(); if(impl != null) { // Update the routing tables of all the other slices Slice[] slices = getAllSlices(); for(int i = 0; i < slices.length; i++) { try { MessagingSlice slice = (MessagingSlice)slices[i]; String sliceName = slice.getNode().getName(); if(!sliceName.equals(cid.getName())) { slice.removeRoute(mtp, cid.getName()); } } catch(Throwable t) { // Re-throw allowed exceptions if(t instanceof IMTPException) { throw (IMTPException)t; } if(t instanceof ServiceException) { throw (ServiceException)t; } System.out.println(" } } impl.deadMTP(mtp, cid); } else { // Do nothing for now, but could also route the command to the main slice, thus enabling e.g. AMS replication } } public void addRoute(MTPDescriptor mtp, String sliceName) throws IMTPException, ServiceException { MessagingSlice slice = (MessagingSlice)getSlice(sliceName); routes.addRemoteMTP(mtp, sliceName, slice); String[] addresses = mtp.getAddresses(); for(int i = 0; i < addresses.length; i++) { myContainer.addAddressToLocalAgents(addresses[i]); } } public void removeRoute(MTPDescriptor mtp, String sliceName) throws IMTPException, ServiceException { MessagingSlice slice = (MessagingSlice)getSlice(sliceName); routes.removeRemoteMTP(mtp, sliceName, slice); String[] addresses = mtp.getAddresses(); for(int i = 0; i < addresses.length; i++) { myContainer.removeAddressFromLocalAgents(addresses[i]); } } private RoutingTable routes = new RoutingTable(MessagingService.this); } // End of ServiceComponent class /** Activates the ACL codecs and MTPs as specified in the given <code>Profile</code> instance. @param myProfile The <code>Profile</code> instance containing the list of ACL codecs and MTPs to activate on this node. **/ public void activateProfile(Profile myProfile) { try { // Activate the default ACL String codec anyway ACLCodec stringCodec = new StringACLCodec(); messageEncodings.put(stringCodec.getName().toLowerCase(), stringCodec); // Codecs List l = myProfile.getSpecifiers(Profile.ACLCODECS); Iterator codecs = l.iterator(); while (codecs.hasNext()) { Specifier spec = (Specifier) codecs.next(); String className = spec.getClassName(); try{ Class c = Class.forName(className); ACLCodec codec = (ACLCodec)c.newInstance(); messageEncodings.put(codec.getName().toLowerCase(), codec); System.out.println("Installed "+ codec.getName()+ " ACLCodec implemented by " + className + "\n"); // FIXME: notify the AMS of the new Codec to update the APDescritption. } catch(ClassNotFoundException cnfe){ throw new jade.lang.acl.ACLCodec.CodecException("ERROR: The class " +className +" for the ACLCodec not found.", cnfe); } catch(InstantiationException ie) { throw new jade.lang.acl.ACLCodec.CodecException("The class " + className + " raised InstantiationException (see NestedException)", ie); } catch(IllegalAccessException iae) { throw new jade.lang.acl.ACLCodec.CodecException("The class " + className + " raised IllegalAccessException (see nested exception)", iae); } } // MTPs l = myProfile.getSpecifiers(Profile.MTPS); String fileName = myProfile.getParameter(Profile.FILE_DIR, "") + "MTPs-" + myContainer.getID().getName() + ".txt"; PrintWriter f = new PrintWriter(new FileWriter(fileName)); Iterator mtps = l.iterator(); while (mtps.hasNext()) { Specifier spec = (Specifier) mtps.next(); String className = spec.getClassName(); String addressURL = null; Object[] args = spec.getArgs(); if (args != null && args.length > 0) { addressURL = args[0].toString(); if(addressURL.equals("")) { addressURL = null; } } MTPDescriptor mtp = localSlice.installMTP(addressURL, className); String[] mtpAddrs = mtp.getAddresses(); f.println(mtpAddrs[0]); System.out.println(mtpAddrs[0]); } f.close(); } catch (ProfileException pe1) { System.out.println("Error reading MTPs/Codecs"); pe1.printStackTrace(); } catch(ServiceException se) { System.out.println("Error installing local MTPs"); se.printStackTrace(); } catch(jade.lang.acl.ACLCodec.CodecException ce) { System.out.println("Error installing ACL Codec"); ce.printStackTrace(); } catch(MTPException me) { System.out.println("Error installing MTP"); me.printStackTrace(); } catch(IOException ioe) { System.out.println("Error writing platform address"); ioe.printStackTrace(); } catch(IMTPException imtpe) { // Should never happen as this is a local call imtpe.printStackTrace(); } } public void deliverNow(ACLMessage msg, AID receiverID) throws UnreachableException { try { if(myContainer.livesHere(receiverID)) { localSlice.deliverNow(msg, receiverID); } else { // Dispatch it through the ACC Iterator addresses = receiverID.getAllAddresses(); while(addresses.hasNext()) { String address = (String)addresses.next(); try { forwardMessage(msg, receiverID, address); return; } catch(MTPException mtpe) { System.out.println("Bad address [" + address + "]: trying the next one..."); } } notifyFailureToSender(msg, receiverID, new InternalError("No valid address contained within the AID " + receiverID.getName())); } } catch(NotFoundException nfe) { // The receiver does not exist --> Send a FAILURE message notifyFailureToSender(msg, receiverID, new InternalError("Agent not found: " + nfe.getMessage())); } } private void forwardMessage(ACLMessage msg, AID receiver, String address) throws MTPException { AID aid = msg.getSender(); if(aid == null) { System.out.println("ERROR: null message sender. Aborting message dispatch..."); return; } // if has no address set, then adds the addresses of this platform if(!aid.getAllAddresses().hasNext()) addPlatformAddresses(aid); Iterator it1 = msg.getAllReceiver(); while(it1.hasNext()) { AID id = (AID)it1.next(); if(!id.getAllAddresses().hasNext()) addPlatformAddresses(id); } Iterator it2 = msg.getAllReplyTo(); while(it2.hasNext()) { AID id = (AID)it2.next(); if(!id.getAllAddresses().hasNext()) addPlatformAddresses(id); } try { localSlice.routeOut(msg, receiver, address); } catch(IMTPException imtpe) { throw new MTPException("Error during message routing", imtpe); } } /** * This method is used internally by the platform in order * to notify the sender of a message that a failure was reported by * the Message Transport Service. * Package scoped as it can be called by the MessageManager */ public void notifyFailureToSender(ACLMessage msg, AID receiver, InternalError ie) { //if (the sender is not the AMS and the performative is not FAILURE) if ( (msg.getSender()==null) || ((msg.getSender().equals(myContainer.getAMS())) && (msg.getPerformative()==ACLMessage.FAILURE))) // sanity check to avoid infinte loops return; // else send back a failure message final ACLMessage failure = msg.createReply(); failure.setPerformative(ACLMessage.FAILURE); //System.err.println(failure.toString()); final AID theAMS = myContainer.getAMS(); failure.setSender(theAMS); // FIXME: the content is not completely correct, but that should // also avoid creating wrong content // FIXME: the content should include the indication about the // receiver to wich dispatching failed. String content = "( (action " + msg.getSender().toString(); content = content + " ACLMessage ) " + ie.getMessage() + ")"; failure.setContent(content); try { Authority authority = myContainer.getAuthority(); authority.doPrivileged(new PrivilegedExceptionAction() { public Object run() { try { // FIXME: Having a custom code path for send failure notifications would be better... GenericCommand cmd = new GenericCommand(SEND_MESSAGE, NAME, ""); cmd.addParam(failure); cmd.addParam(theAMS); handleSendMessage(cmd); } catch (AuthException ae) { // it never happens if the policy file gives System.out.println( ae.getMessage() ); } return null; // nothing to return } }); } catch(Exception e) { // should be never thrown e.printStackTrace(); } } // Vertical command handler methods private void handleSendMessage(VerticalCommand cmd) throws AuthException { Object[] params = cmd.getParams(); ACLMessage msg = (ACLMessage)params[0]; AID sender = (AID)params[1]; // Set the sender unless already set try { if (msg.getSender().getName().length() < 1) msg.setSender(sender); } catch (NullPointerException e) { msg.setSender(sender); } AgentPrincipal target1 = myContainer.getAgentPrincipal(msg.getSender()); Authority authority = myContainer.getAuthority(); authority.checkAction(Authority.AGENT_SEND_AS, target1, null); AuthException lastException = null; // 26-Mar-2001. The receivers set into the Envelope of the message, // if present, must have precedence over those set into the ACLMessage. // If no :intended-receiver parameter is present in the Envelope, // then the :to parameter // is used to generate :intended-receiver field. // create an Iterator with all the receivers to which the message must be // delivered Iterator it = msg.getAllIntendedReceiver(); while (it.hasNext()) { AID dest = (AID)it.next(); try { AgentPrincipal target2 = myContainer.getAgentPrincipal(dest); authority.checkAction(Authority.AGENT_SEND_TO, target2, null); ACLMessage copy = (ACLMessage)msg.clone(); boolean found = myContainer.postMessageToLocalAgent(copy, dest); if(!found) { myMessageManager.deliver(copy, dest); } } catch (AuthException ae) { lastException = ae; notifyFailureToSender(msg, dest, new InternalError(ae.getMessage())); } } if(lastException != null) throw lastException; } private MTPDescriptor handleInstallMTP(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException, MTPException { Object[] params = cmd.getParams(); String address = (String)params[0]; ContainerID cid = (ContainerID)params[1]; String className = (String)params[2]; MessagingSlice targetSlice = (MessagingSlice)getSlice(cid.getName()); return targetSlice.installMTP(address, className); } private void handleUninstallMTP(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException, MTPException { Object[] params = cmd.getParams(); String address = (String)params[0]; ContainerID cid = (ContainerID)params[1]; MessagingSlice targetSlice = (MessagingSlice)getSlice(cid.getName()); targetSlice.uninstallMTP(address); } private void handleSetPlatformAddresses(VerticalCommand cmd) { Object[] params = cmd.getParams(); AID id = (AID)params[0]; id.clearAllAddresses(); addPlatformAddresses(id); } public void prepareEnvelope(ACLMessage msg, AID receiver) { Envelope env = msg.getEnvelope(); if(env == null) { msg.setDefaultEnvelope(); env = msg.getEnvelope(); } // If no 'to' slot is present, copy the 'to' slot from the // 'receiver' slot of the ACL message Iterator itTo = env.getAllTo(); if(!itTo.hasNext()) { Iterator itReceiver = msg.getAllReceiver(); while(itReceiver.hasNext()) env.addTo((AID)itReceiver.next()); } // If no 'from' slot is present, copy the 'from' slot from the // 'sender' slot of the ACL message AID from = env.getFrom(); if(from == null) { env.setFrom(msg.getSender()); } // Set the 'date' slot to 'now' if not present already Date d = env.getDate(); if(d == null) env.setDate(new Date()); // If no ACL representation is found, then default to String // representation String rep = env.getAclRepresentation(); if(rep == null) env.setAclRepresentation(StringACLCodec.NAME); // Write 'intended-receiver' slot as per 'FIPA Agent Message // Transport Service Specification': this ACC splits all // multicasts, since JADE has already split them in the // handleSend() method env.clearAllIntendedReceiver(); env.addIntendedReceiver(receiver); String comments = env.getComments(); if(comments == null) env.setComments(""); Long payloadLength = env.getPayloadLength(); if(payloadLength == null) env.setPayloadLength(new Long(-1)); String payloadEncoding = env.getPayloadEncoding(); if(payloadEncoding == null) env.setPayloadEncoding(""); } public byte[] encodeMessage(ACLMessage msg) throws NotFoundException { Envelope env = msg.getEnvelope(); String enc = env.getAclRepresentation(); if(enc != null) { // A Codec was selected ACLCodec codec =(ACLCodec)messageEncodings.get(enc.toLowerCase()); if(codec!=null) { // Supported Codec // FIXME: should verifY that the recevivers supports this Codec return codec.encode(msg); } else { // Unsupported Codec //FIXME: find the best according to the supported, the MTP (and the receivers Codec) throw new UnknownACLEncodingException("Unknown ACL encoding: " + enc + "."); } } else { // no codec indicated. //FIXME: find the better according to the supported Codec, the MTP (and the receiver codec) throw new UnknownACLEncodingException("No ACL encoding set."); } } /* * This method is called before preparing the Envelope of an outgoing message. * It checks for all the AIDs present in the message and adds the addresses, if not present **/ private void addPlatformAddresses(AID id) { Iterator it = localSlice.getAddresses(); while(it.hasNext()) { String addr = (String)it.next(); id.addAddresses(addr); } } // The concrete agent container, providing access to LADT, etc. private AgentContainerImpl myContainer; // The local slice for this service private ServiceComponent localSlice; // The cached AID -> MessagingSlice associations private Map cachedSlices; // The table of the locally installed ACL message encodings private Map messageEncodings = new HashMap(); // The platform ID, to be used in inter-platform dispatching private String accID; // The component managing asynchronous message delivery and retries private MessageManager myMessageManager; }
package jade.imtp.leap.nio; //#J2ME_EXCLUDE_FILE import jade.imtp.leap.ICPException; import jade.imtp.leap.JICP.*; import java.io.IOException; import java.io.EOFException; import java.io.ByteArrayOutputStream; import java.nio.*; import java.nio.channels.*; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.logging.Level; import java.util.logging.Logger; /** @author Giovanni Caire - TILAB */ public class NIOJICPConnection extends Connection { // type+info+session+recipient-length+recipient(255)+payload-length(4) public static final int MAX_HEADER_SIZE = 263; // TODO 5k, why? configurable? public static final int INITIAL_BUFFER_SIZE = 5120; // TODO 5k, why? configurable? public static final int INCREASE_STEP = 5120; private SocketChannel myChannel; private ByteBuffer socketData = ByteBuffer.allocateDirect(INITIAL_BUFFER_SIZE); private ByteBuffer payloadBuf = ByteBuffer.allocateDirect(INITIAL_BUFFER_SIZE); private byte type; private byte info; private byte sessionID; private String recipientID; private boolean headerReceived = false; private boolean closed = false; private List<BufferTransformerInfo> transformers = new LinkedList<BufferTransformerInfo>(); private static final Logger log = Logger.getLogger(NIOJICPConnection.class.getName()); public NIOJICPConnection() { } /** Read a JICPPacket from the connection. The method is synchronized since we reuse the same Buffer object for reading the packet header. It should be noted that the packet data may not be completely available when the embedded channel is ready for a READ operation. In that case a PacketIncompleteException is thrown to indicate that successive calls to this method must occur in order to fully read the packet. */ public final synchronized JICPPacket readPacket() throws IOException { read(); ByteBuffer jicpData = transformAfterRead(socketData); if (jicpData.hasRemaining()) { // JICP data actually available after transformations if (!headerReceived) { // Note that, since we require that a JICP-Header is never split, we // are sure that at least all header bytes are available //System.out.println("Read "+jicpData.remaining()+" bytes"); headerReceived = true; type = jicpData.get(); //System.out.println("type = "+type); info = jicpData.get(); //System.out.println("info = "+info); sessionID = -1; if ((info & JICPProtocol.SESSION_ID_PRESENT_INFO) != 0) { sessionID = jicpData.get(); //System.out.println("SessionID = "+sessionID); } if ((info & JICPProtocol.RECIPIENT_ID_PRESENT_INFO) != 0) { byte recipientIDLength = jicpData.get(); byte[] bb = new byte[recipientIDLength]; jicpData.get(bb); recipientID = new String(bb); //System.out.println("RecipientID = "+recipientID); } if ((info & JICPProtocol.DATA_PRESENT_INFO) != 0) { int b1 = (int) jicpData.get(); int b2 = (int) jicpData.get(); int payloadLength = ((b2 << 8) & 0x0000ff00) | (b1 & 0x000000ff); int b3 = (int) jicpData.get(); int b4 = (int) jicpData.get(); payloadLength |= ((b4 << 24) & 0xff000000) | ((b3 << 16) & 0x00ff0000); if (payloadLength > JICPPacket.MAX_SIZE) { throw new IOException("Packet size greater than maximum allowed size. " + payloadLength); } resizePayloadBuffer(payloadLength); // jicpData may already contain some payload bytes --> copy them into the payload buffer NIOHelper.copyAsMuchAsFits(payloadBuf, jicpData); if (payloadBuf.hasRemaining()) { // Payload not completely received. Wait for next round throw new PacketIncompleteException(); } else { return buildPacket(); } } else { return buildPacket(); } } else { // We are in the middle of reading the payload of a packet (the previous call to readPacket() resulted in a PacketIncompleteException) NIOHelper.copyAsMuchAsFits(payloadBuf, jicpData); if (payloadBuf.hasRemaining()) { // Payload not completely received. Wait for next round throw new PacketIncompleteException(); } else { return buildPacket(); } } } else { // No JICP data available at this round. Wait for next throw new PacketIncompleteException(); } } private void read() throws IOException { socketData.clear(); readFromChannel(socketData); while (!socketData.hasRemaining()) { // We read exactly how many bytes how socketData can contain. VERY likely there are // more bytes to read from the channel --> Enlarge socketData and read again socketData.flip(); socketData = NIOHelper.enlargeAndFillBuffer(socketData, INCREASE_STEP); try { readFromChannel(socketData); } catch (EOFException eofe) { // Return the bytes read so far break; } } socketData.flip(); if (log.isLoggable(Level.FINE)) log.fine(" } /** * reads data from the socket into a buffer * @param b * @return number of bytes read * @throws IOException */ private final int readFromChannel(ByteBuffer b) throws IOException { int n = myChannel.read(b); if (n == -1) { throw new EOFException("Channel closed"); } return n; } private ByteBuffer transformAfterRead(ByteBuffer incomingData) throws IOException { // Let BufferTransformers process incoming data ByteBuffer transformationInput = incomingData; ByteBuffer transformationOutput = transformationInput; for (ListIterator<BufferTransformerInfo> it = transformers.listIterator(transformers.size()); it.hasPrevious();) { BufferTransformerInfo info = it.previous(); BufferTransformer btf = info.getTransformer(); // In case there were unprocessed data at previous round, append them before the data to be processed at this round transformationInput = info.attachUnprocessedData(transformationInput); if (log.isLoggable(Level.FINER)) log.finer(" transformationOutput = btf.postprocessBufferRead(transformationInput); if (log.isLoggable(Level.FINER)) log.finer(" // In case the transformer did not process all input data, store unprocessed data for next round info.storeUnprocessedData(transformationInput); // Output of transformer N becomes input of transformer N-1 (transformers are scanned in reverse order when managing incoming data) transformationInput = transformationOutput; if (!transformationInput.hasRemaining() && it.hasPrevious()) { // No bytes for next transformation --> no need to continue scanning transformers break; } } return transformationOutput; } private void resizePayloadBuffer(int payloadLength) { if (payloadLength > payloadBuf.capacity()) { payloadBuf = NIOHelper.enlargeBuffer(payloadBuf, payloadLength - payloadBuf.capacity()); } else { payloadBuf.limit(payloadLength); } } private JICPPacket buildPacket() { payloadBuf.flip(); byte[] payload = new byte[payloadBuf.remaining()]; payloadBuf.get(payload, 0, payload.length); JICPPacket pkt = new JICPPacket(type, info, recipientID, payload); pkt.setSessionID(sessionID); // Reset internal fields to properly manage next JICP packet headerReceived = false; recipientID = null; payloadBuf.clear(); return pkt; } /** * Write a JICPPacket on the connection, first calls {@link #preprocessBufferToWrite(java.nio.ByteBuffer) }. * When the buffer returned by {@link #preprocessBufferToWrite(java.nio.ByteBuffer) }, no write will be performed. * @return number of application bytes written to the socket */ public final synchronized int writePacket(JICPPacket pkt) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); int n = pkt.writeTo(os); if (log.isLoggable(Level.FINE)) { log.fine("writePacket: number of bytes before preprocessing: " + n); } ByteBuffer toSend = ByteBuffer.wrap(os.toByteArray()); ByteBuffer bb = transformBeforeWrite(toSend); if (toSend.hasRemaining() && transformers.size() > 0) { // for direct JICPConnections the data from the packet are used directly // for subclasses the subsequent transformers must transform all data from the packet before sending throw new IOException("still need to transform: " + toSend.remaining()); } int totalWrited = 0; int totalToWrite = bb.remaining(); while (bb.hasRemaining()) { int toWrite = bb.remaining(); int writed = writeToChannel(bb); totalWrited += writed; if (log.isLoggable(Level.FINE)) { log.fine("writePacket: bytes written " + writed + ", needed to write: " + toWrite); } } if (log.isLoggable(Level.FINE)) { throw new IOException("writePacket: total bytes written " + totalWrited + ", total needed to write: " + totalToWrite); } return totalWrited; } private ByteBuffer transformBeforeWrite(ByteBuffer data) throws IOException { for (BufferTransformerInfo info : transformers) { BufferTransformer btf = info.getTransformer(); data = btf.preprocessBufferToWrite(data); } return data; } /** * writes data to the channel * @param bb * @return the number of bytes written to the channel * @throws IOException */ public final int writeToChannel(ByteBuffer bb) throws IOException { return myChannel.write(bb); } /** Close the connection */ public void close() throws IOException { closed = true; myChannel.close(); } // In some cases we may receive some data (often a socket closed by peer indication) while // closing the channel locally. Trying to read such data results in an Exception. To avoid printing // this Exception it is possible to check this method public boolean isClosed() { return closed; } public String getRemoteHost() { return myChannel.socket().getInetAddress().getHostAddress(); } /** * sets the channel for this connection * @param channel * @throws ICPException */ void init(SocketChannel channel) throws ICPException { this.myChannel = (SocketChannel) channel; } public void addBufferTransformer(BufferTransformer transformer) { transformers.add(new BufferTransformerInfo(transformer)); } /** * Inner class BufferTransformerInfo * This class keeps together a BufferTransformer and a ByteBuffer holding data already received * but not yet processed by that transformer. Such data will be used (together with newly received data) * at next transformation attempt */ private class BufferTransformerInfo { private BufferTransformer transformer; private ByteBuffer unprocessedData; BufferTransformerInfo(BufferTransformer transformer) { this.transformer = transformer; } BufferTransformer getTransformer() { return transformer; } public void storeUnprocessedData(ByteBuffer transformationInput) { if (transformationInput.hasRemaining()) { //System.out.println(" unprocessedData = ByteBuffer.allocateDirect(transformationInput.remaining()); NIOHelper.copyAsMuchAsFits(unprocessedData, transformationInput); unprocessedData.flip(); } else { // No un-processed data to store unprocessedData = null; } } public ByteBuffer attachUnprocessedData(ByteBuffer transformationInput) { ByteBuffer actualTransformationInput = transformationInput; if (unprocessedData != null && unprocessedData.hasRemaining()) { //System.out.println(" actualTransformationInput = NIOHelper.enlargeAndFillBuffer(unprocessedData, transformationInput.remaining()); NIOHelper.copyAsMuchAsFits(actualTransformationInput, transformationInput); actualTransformationInput.flip(); } return actualTransformationInput; } } // END of inner class BufferTransformerInfo }
package net.spy.memcached; import java.util.zip.CRC32; /** * Known hashing algorithms for locating a server for a key. */ public enum HashAlgorithm { /** * Native hash (String.hashCode()). */ NATIVE_HASH, /** * CRC32_HASH as used by the perl API. This will be more consistent both * across multiple API users as well as java versions, but is mostly likely * significantly slower. */ CRC32_HASH, FNV_HASH; private static final long FNV1_64_INIT = 0xcbf29ce484222325L; private static final long FNV_64_PRIME = 0x100000001b3L; /** * Compute the hash for the given key. * * @return a positive integer hash */ public long hash(String k) { long rv = 0; switch (this) { case NATIVE_HASH: rv = k.hashCode(); break; case CRC32_HASH: // return (crc32(shift) >> 16) & 0x7fff; CRC32 crc32 = new CRC32(); crc32.update(k.getBytes()); rv = (crc32.getValue() & 0xffffffff); rv = (rv >> 16) & 0x7fff; break; case FNV_HASH: // Thanks to pierre@demartines.com for the pointer rv = FNV1_64_INIT; int len = k.length(); for (int i = 0; i < len; i++) { rv *= FNV_64_PRIME; rv ^= k.charAt(i); } break; default: assert false; } return Math.abs(rv); } }
package org.orbeon.oxf.util; import java.io.File; public class SystemUtils { public static File getTemporaryDirectory() { return new File(System.getProperty("java.io.tmpdir")).getAbsoluteFile(); } /** * @param pth java.io.File.pathSeparator delimited path. * @return What you think. */ public static java.io.File[] pathToFiles( final String pth ) { final java.util.ArrayList pthArr = new java.util.ArrayList(); final java.util.StringTokenizer st = new java.util.StringTokenizer ( pth, java.io.File.pathSeparator ); while ( st.hasMoreTokens() ) { final String fnam = st.nextToken(); final java.io.File fil = new java.io.File( fnam ); pthArr.add( fil ); } final java.io.File[] ret = new java.io.File[ pthArr.size() ]; pthArr.toArray( ret ); return ret; } /** * @param trgt Receiver of path elements ( as java.io.File ) from pth. * @param pth java.io.File.pathSeparator delimited path. */ public static void gatherPaths( final java.util.Collection trgt, final String pth ) { final java.io.File[] files = pathToFiles( pth ); for ( int i = 0; i < files.length; i++ ) { trgt.add( files[ i ] ); } } /** * @param c Reciever of java.io.File's gathered from sun.boot.class.path elements * as well as the contents of the dirs named in java.ext.dirs. */ public static void gatherSystemPaths( java.util.Collection c ) { final String bootcp = System.getProperty( "sun.boot.class.path" ); gatherPaths( c, bootcp ); final String extDirProp = System.getProperty( "java.ext.dirs" ); final java.io.File[] extDirs = pathToFiles( extDirProp ); for ( int i = 0; i < extDirs.length; i++ ) { final java.io.File[] jars = extDirs[ i ].listFiles(); for ( int j = 0; j < jars.length; j++ ) { final java.io.File fil = jars[ j ]; final String fnam = fil.toString(); final int fnamLen = fnam.length(); if ( fnamLen < 5 ) continue; if ( fnam.regionMatches( true, fnamLen - 4, ".jar", 0, 4 ) ) { c.add( fil ); } else if ( fnam.regionMatches( true, fnamLen - 4, ".zip", 0, 4 ) ) { c.add( fil ); } } } } /** * Walks class loader hierarchy of clazz looking for instances of URLClassLoader. * For each found gets file urls and adds, converted, elements to the path. * Note that the more junior a class loader is the later in the path it's * contribution is. * @param clazz Class to try and build a classpath from. * @return java.io.File.pathSeparator delimited path. */ public static String pathFromLoaders( final Class clazz ) { final java.util.TreeSet sysPths = new java.util.TreeSet(); gatherSystemPaths( sysPths ); final StringBuffer sbuf = new StringBuffer(); final java.util.LinkedList urlLst = new java.util.LinkedList(); for ( ClassLoader cl = clazz.getClassLoader(); cl != null; cl = cl.getParent() ) { if ( !( cl instanceof java.net.URLClassLoader ) ) { continue; } final java.net.URLClassLoader ucl = ( java.net.URLClassLoader )cl; final java.net.URL[] urls = ucl.getURLs(); if ( urls == null ) continue; for ( int i = urls.length - 1; i > -1; i final java.net.URL url = urls[ i ]; final String prot = url.getProtocol(); if ( !"file".equalsIgnoreCase( prot ) ) continue; urlLst.addFirst( url ); } } for ( final java.util.Iterator itr = urlLst.iterator(); itr.hasNext(); ) { final java.net.URL url = ( java.net.URL )itr.next(); final String fnam = url.getFile(); final java.io.File fil = new java.io.File( fnam ); if ( sysPths.contains( fil ) ) continue; sbuf.append( fnam ); sbuf.append( java.io.File.pathSeparatorChar ); } final String ret = sbuf.toString(); return ret; } private SystemUtils() { // disallow instantiation } }
package ca.corefacility.bioinformatics.irida.config.workflow; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Profile; import org.springframework.core.env.Environment; import ca.corefacility.bioinformatics.irida.exceptions.WorkflowException; import ca.corefacility.bioinformatics.irida.model.workflow.RemoteWorkflow; import ca.corefacility.bioinformatics.irida.model.workflow.galaxy.phylogenomics.RemoteWorkflowPhylogenomics; import ca.corefacility.bioinformatics.irida.pipeline.upload.galaxy.GalaxyWorkflowService; import ca.corefacility.bioinformatics.irida.repositories.workflow.RemoteWorkflowRepository; import ca.corefacility.bioinformatics.irida.service.workflow.galaxy.phylogenomics.impl.RemoteWorkflowServicePhylogenomics; import com.github.jmchilton.blend4j.galaxy.WorkflowsClient; import com.github.jmchilton.blend4j.galaxy.beans.Workflow; /** * Configuration for loading up remote workflows. * * @author Aaron Petkau <aaron.petkau@phac-aspc.gc.ca> * */ @Configuration @Profile({ "dev", "prod", "it" }) public class RemoteWorkflowServiceConfig { private static final Logger logger = LoggerFactory.getLogger(RemoteWorkflowServiceConfig.class); private static final String DEFAULT_PHYLOGENOMICS_WORKFLOW_NAME = "SNPhyl Pipeline (imported from API)"; private static final String SEQUENCE_INPUT_LABEL = "sequence_reads"; private static final String REFERENCE_INPUT_LABEL = "reference"; private static final String DEFAULT_TREE_OUTPUT = "snp_tree.tre"; private static final String DEFAULT_MATRIX_OUTPUT = "snp_matrix.tsv"; private static final String DEFAULT_SNP_TABLE_OUTPUT = "snp_table.tsv"; @Autowired private Environment environment; @Autowired private RemoteWorkflowRepository remoteWorkflowRepository; @Autowired private GalaxyWorkflowService galaxyWorkflowService; /** * Create an instance of {@link RemoteWorkflow} and automatically install it * to the database (if necessary). This bean is intended to be run *before* * actual execution of a servlet, but *after* the database has been * populated. This duplicates what's done in * {@link InstallRemoteWorkflowPhylogenomics}. * * @param remoteWorkflowRepository * the workflow repository used to save the remote workflow. * @return an instance of the phylogenomics workflow. */ @Bean @Profile({ "dev", "prod" }) @DependsOn("springLiquibase") public RemoteWorkflowPhylogenomics remoteWorkflow(final RemoteWorkflowRepository remoteWorkflowRepository, final WorkflowsClient workflowClient, final GalaxyWorkflowService galaxyWorkflowService) { // figure out what the workflow ID is given the credentials that we have // in the workflow client try { final Optional<Workflow> workflowCheck = workflowClient.getWorkflows().stream() .filter(w -> w.getName().equals(DEFAULT_PHYLOGENOMICS_WORKFLOW_NAME)).findAny(); if (!workflowCheck.isPresent()) { logger.warn("Could not auto-configure SNVPhyl Workflow in Galaxy using workflow name [" + DEFAULT_PHYLOGENOMICS_WORKFLOW_NAME + "]. Is your Galaxy configured correctly?"); logger.warn("These are the pipeline names I *could* find:"); for (final Workflow w : workflowClient.getWorkflows()) { logger.warn("\t" + w.getName()); } return null; } // get the workflow checksum from // `GalaxyWorkflowService#getWorkflowChecksum` final String workflowId = workflowCheck.get().getId(); final String workflowChecksum = galaxyWorkflowService.getWorkflowChecksum(workflowId); // assume that we're using the default names for input labels and // output file names. final RemoteWorkflowPhylogenomics phylogenomicsWorkflow = new RemoteWorkflowPhylogenomics(workflowId, workflowChecksum, SEQUENCE_INPUT_LABEL, REFERENCE_INPUT_LABEL, DEFAULT_TREE_OUTPUT, DEFAULT_MATRIX_OUTPUT, DEFAULT_SNP_TABLE_OUTPUT); // return the instance that we persisted (even if nobody is going to // consume it). if (remoteWorkflowRepository.exists(workflowId)) { logger.info("Remote Phylogenomics Worklfow with id [" + workflowId + "] already configured, using existing configuration."); return (RemoteWorkflowPhylogenomics) remoteWorkflowRepository.findOne(workflowId); } else { logger.info("Configuring Remote Phylogenomics Workflow with id [" + workflowId + "]"); return remoteWorkflowRepository.save(phylogenomicsWorkflow); } } catch (Exception e) { logger.error("Could not connect to Galaxy. Not attempting to auto-configure workflow."); } return null; } /** * @return A RemoteWorkflowServicePhylogenomics with a correctly implemented * workflow. * @throws WorkflowException */ @Lazy @Bean public RemoteWorkflowServicePhylogenomics remoteWorkflowServicePhylogenomics( final RemoteWorkflowRepository remoteWorkflowRepository, final WorkflowsClient workflowClient, final GalaxyWorkflowService galaxyWorkflowService) throws WorkflowException { return new RemoteWorkflowServicePhylogenomics(remoteWorkflow(remoteWorkflowRepository, workflowClient, galaxyWorkflowService)); } }
package erogenousbeef.bigreactors.common.multiblock.tileentity; import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import cofh.api.energy.IEnergyHandler; import erogenousbeef.bigreactors.common.multiblock.interfaces.INeighborUpdatableEntity; import erogenousbeef.core.multiblock.MultiblockControllerBase; public class TileEntityReactorPowerTap extends TileEntityReactorPart implements IEnergyHandler, INeighborUpdatableEntity { IEnergyHandler rfNetwork; public TileEntityReactorPowerTap() { super(); rfNetwork = null; } @Override public void onNeighborBlockChange(World world, int x, int y, int z, Block neighborBlock) { if(isConnected()) { checkForConnections(world, x, y, z); } } @Override public void onNeighborTileChange(IBlockAccess world, int x, int y, int z, int neighborX, int neighborY, int neighborZ) { if(isConnected()) { checkForConnections(world, x, y, z); } } // IMultiblockPart @Override public void onAttached(MultiblockControllerBase newController) { super.onAttached(newController); checkForConnections(this.worldObj, xCoord, yCoord, zCoord); } @Override public void onMachineAssembled(MultiblockControllerBase multiblockControllerBase) { super.onMachineAssembled(multiblockControllerBase); checkForConnections(this.worldObj, xCoord, yCoord, zCoord); // Force a connection to the power taps this.notifyNeighborsOfTileChange(); } // Custom PowerTap methods /** * Check for a world connection, if we're assembled. * @param world * @param x * @param y * @param z */ protected void checkForConnections(IBlockAccess world, int x, int y, int z) { boolean wasConnected = (rfNetwork != null); ForgeDirection out = getOutwardsDir(); if(out == ForgeDirection.UNKNOWN) { wasConnected = false; rfNetwork = null; } else { // See if our adjacent non-reactor coordinate has a TE rfNetwork = null; TileEntity te = world.getTileEntity(x + out.offsetX, y + out.offsetY, z + out.offsetZ); if(!(te instanceof TileEntityReactorPowerTap)) { // Skip power taps, as they implement these APIs and we don't want to shit energy back and forth if(te instanceof IEnergyHandler) { rfNetwork = (IEnergyHandler)te; } } } boolean isConnected = (rfNetwork != null); if(wasConnected != isConnected) { worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); } } /** This will be called by the Reactor Controller when this tap should be providing power. * @return Power units remaining after consumption. */ public int onProvidePower(int units) { if(rfNetwork == null) { return units; } ForgeDirection approachDirection = getOutwardsDir().getOpposite(); int energyConsumed = rfNetwork.receiveEnergy(approachDirection, (int)units, false); units -= energyConsumed; return units; } // Thermal Expansion @Override public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { return 0; } @Override public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { if(!this.isConnected()) return 0; if(from == getOutwardsDir()) { return this.getReactorController().extractEnergy(from, maxExtract, simulate); } return 0; } @Override public boolean canConnectEnergy(ForgeDirection from) { return from == getOutwardsDir(); } @Override public int getEnergyStored(ForgeDirection from) { if(!this.isConnected()) return 0; return this.getReactorController().getEnergyStored(from); } @Override public int getMaxEnergyStored(ForgeDirection from) { if(!this.isConnected()) return 0; return this.getReactorController().getMaxEnergyStored(from); } public boolean hasEnergyConnection() { return rfNetwork != null; } }
package org.ppwcode.vernacular.persistence_III.dao.jpa; import javax.persistence.EntityManager; import org.ppwcode.util.exception_III.ProgrammingErrorHelpers; import org.toryt.annotations_I.Basic; import org.toryt.annotations_I.Expression; import org.toryt.annotations_I.MethodContract; /** * This Dao is meant to be used out of container. i.e. the entitymanager * will be programmatically created, instead of being injected by a container. * The JpaStatelessCrudDao must be configured with an entity manager using * a setter. * * Note that transaction control is still left out. It is at this * moment not decided whether the CRUD operation should run in its own transaction * or will be part of another transaction. * * Note that the rollbackOnly implementation can be provided since we will * use EntityTransactions in this application * * @author tmahieu * */ public class JpaOutOfContainerStatelessCrudDao extends JpaStatelessCrudDao { @Override @Basic public EntityManager getEntityManager() { return $entityManager; } @MethodContract( post=@Expression("entityManager == _entitymanager") ) public void setEntityManager(EntityManager entitymanager) { $entityManager = entitymanager; } private EntityManager $entityManager = null; /*</property>*/ @Override protected boolean getRollbackOnlyImpl() { // TODO Auto-generated method stub return getEntityManager().getTransaction().getRollbackOnly(); } @Override protected void rollbackOnlyPrecondition() throws AssertionError { ProgrammingErrorHelpers.dependency(getEntityManager(), "entityManager"); } @Override protected void setRollbackOnlyImpl() throws IllegalStateException { getEntityManager().getTransaction().setRollbackOnly(); } }
package com.marklogic.client.functionaltest; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.marklogic.client.DatabaseClient; import com.marklogic.client.DatabaseClientFactory; import com.marklogic.client.DatabaseClientFactory.Authentication; import com.marklogic.client.functionaltest.TestPOJOSpecialCharRead.SpecialArtifact; import com.marklogic.client.io.JacksonHandle; import com.marklogic.client.pojo.PojoPage; import com.marklogic.client.pojo.PojoQueryBuilder; import com.marklogic.client.pojo.PojoQueryDefinition; import com.marklogic.client.pojo.PojoRepository; import com.marklogic.client.pojo.annotation.GeospatialLatitude; import com.marklogic.client.pojo.annotation.GeospatialLongitude; import com.marklogic.client.pojo.annotation.GeospatialPathIndexProperty; import com.marklogic.client.pojo.annotation.Id; import com.marklogic.client.pojo.util.GenerateIndexConfig; import com.marklogic.client.query.QueryDefinition; public class TestPOJOQueryBuilderGeoQueries extends BasicJavaClientREST { private static String dbName = "TestPOJOQueryBuilderGeoQuerySearchDB"; private static String [] fNames = {"TestPOJOQueryBuilderGeoQuerySearchDB-1"}; private static String restServerName = "REST-Java-Client-API-Server"; private static int restPort = 8011; private DatabaseClient client ; @BeforeClass public static void setUpBeforeClass() throws Exception { // System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.wire", "debug"); System.out.println("In setup"); setupJavaRESTServer(dbName, fNames[0], restServerName,restPort); createAutomaticGeoIndex(); } @AfterClass public static void tearDownAfterClass() throws Exception { System.out.println("In tear down" ); tearDownJavaRESTServer(dbName, fNames, restServerName); } @Before public void setUp() throws Exception { client = DatabaseClientFactory.newClient("localhost", restPort, "rest-admin", "x", Authentication.DIGEST); } @After public void tearDown() throws Exception { // release client client.release(); } // public static class SpecialGeoArtifact { // public String name; // public long id; // private GeoCompany manufacturer; // private int inventory; // public long getId() { // return id; // public SpecialGeoArtifact setId(long id) { // this.id= id; return this; // public String getName() { // return name; // public SpecialGeoArtifact setName(String name) { // this.name = name; return this; // public GeoCompany getManufacturer() { // return manufacturer; // public SpecialGeoArtifact setManufacturer(GeoCompany manufacturer) { // this.manufacturer= manufacturer; return this; // public int getInventory() { // return inventory; // public SpecialGeoArtifact setInventory(int inventory) { // this.inventory= inventory; return this; //Issue 195 //public static class GeoCompany { // private String name; // private String state; // @GeospatialLatitude // public double latitude; // @GeospatialLongitude // public double longitude; //// @GeospatialPathIndexProperty // public String latlongPoint; // public String getName() { // return name; // public GeoCompany setName(String name) { // this.name = name; return this; // public String getState() { // return state; // public GeoCompany setState(String state) { // this.state = state; return this; // @GeospatialLatitude // public double getLatitude() { // return latitude; // public GeoCompany setLatitude(double latitude) { // this.latitude = latitude; return this; // public GeoCompany setLatLongPoint(String latlong) { // this.latlongPoint = latlong; return this; // public String getLatLongPoint(){ // return this.latlongPoint; // // @GeospatialLongitude // public double getLongitude() { // return longitude; // public GeoCompany setLongitude(double longitude) { // this.longitude = longitude; return this; public static void createAutomaticGeoIndex() throws Exception { boolean succeeded = false; File jsonFile = null; try { GenerateIndexConfig.main(new String[] { "-classes", "com.marklogic.client.functionaltest.GeoCompany", "-file", "TestAutomatedGeoPathRangeIndex.json" }); jsonFile = new File("TestAutomatedGeoPathRangeIndex.json"); ObjectMapper mapper = new ObjectMapper(); JsonNode jnode = mapper.readValue(jsonFile, JsonNode.class); if (!jnode.isNull()) { setPathRangeIndexInDatabase(dbName, jnode); succeeded = true; } else { assertTrue( "testArtifactIndexedOnString - No Json node available to insert into database", succeeded); } } catch (IOException e) { e.printStackTrace(); } finally { try { jsonFile.delete(); } catch (Exception e) { e.printStackTrace(); } } } public GeoSpecialArtifact getGeoArtifact(int counter){ GeoSpecialArtifact cogs = new GeoSpecialArtifact(); cogs.setId(counter); if( counter % 5 == 0){ cogs.setName("Cogs special"); if(counter % 2 ==0){ GeoCompany acme = new GeoCompany(); acme.setName("Acme special, Inc."); acme.setState("Reno"); acme.setLatitude(39.5272); acme.setLongitude(119.8219); acme.setLatLongPoint("39.5272 119.8219"); cogs.setManufacturer(acme); }else{ GeoCompany widgets = new GeoCompany(); widgets.setName("Widgets counter Inc."); widgets.setState("Las Vegas"); widgets.setLatitude(36.1215); widgets.setLongitude(115.1739); widgets.setLatLongPoint("36.1215 115.1739"); cogs.setManufacturer(widgets); } }else{ cogs.setName("Cogs "+counter); if(counter % 2 ==0){ GeoCompany acme = new GeoCompany(); acme.setName("Acme "+counter+", Inc."); acme.setState("Los Angles"); acme.setLatitude(34.0500); acme.setLongitude(118.2500); acme.setLatLongPoint("34.0500 118.2500"); cogs.setManufacturer(acme); }else{ GeoCompany widgets = new GeoCompany(); widgets.setName("Widgets "+counter+", Inc."); widgets.setState("San Fransisco"); widgets.setLatitude(37.7833); widgets.setLongitude(122.4167); widgets.setLatLongPoint("37.7833 122.4167"); cogs.setManufacturer(widgets); } } cogs.setInventory(1000+counter); return cogs; } public void validateArtifact(GeoSpecialArtifact art) { assertNotNull("Artifact object should never be Null",art); assertNotNull("Id should never be Null",art.id); assertTrue("Inventry is always greater than 1000", art.getInventory()>1000); } public void loadSimplePojos(PojoRepository products) { for(int i=1;i<111;i++){ if(i%2==0){ products.write(this.getGeoArtifact(i),"even","numbers"); } else { products.write(this.getGeoArtifact(i),"odd","numbers"); } } } // Below scenario is to test the geoPair -130 //This test is to verify GeoPair query works fine, // searching for lattitud and longitude of Reno @Test public void testPOJOGeoQuerySearchWithGeoPair() { PojoRepository<GeoSpecialArtifact,Long> products = client.newPojoRepository(GeoSpecialArtifact.class, Long.class); PojoPage<GeoSpecialArtifact> p; this.loadSimplePojos(products); PojoQueryBuilder qb = products.getQueryBuilder(); PojoQueryBuilder containerQb = qb.containerQueryBuilder("manufacturer",GeoCompany.class); PojoQueryDefinition qd =containerQb.geospatial(containerQb.geoPair("latitude", "longitude"),containerQb.circle(39.5272, 119.8219, 1)); JacksonHandle jh = new JacksonHandle(); products.setPageLength(5); p = products.search(qd, 1,jh); System.out.println(jh.get().toString()); assertEquals("total no of pages",3,p.getTotalPages()); System.out.println(jh.get().toString()); long pageNo=1,count=0; do{ count =0; p = products.search(qd,pageNo); while(p.hasNext()){ GeoSpecialArtifact a =p.next(); validateArtifact(a); assertTrue("Verifying document id is part of the search ids",a.getId()%5==0); assertEquals("Verifying Manufacurer is from state ","Reno",a.getManufacturer().getState()); count++; } assertEquals("Page size",count,p.size()); pageNo=pageNo+p.getPageSize(); }while(!p.isLastPage() && pageNo<=p.getTotalSize()); assertEquals("page number after the loop",3,p.getPageNumber()); assertEquals("total no of pages",3,p.getTotalPages()); assertEquals("page length from search handle",5,jh.get().path("page-length").asInt()); assertEquals("Total results from search handle",11,jh.get().path("total").asInt()); } // This test is to verify GeoProperty query works fine @Test public void testPOJOGeoQuerySearchWithGeoProperty() { PojoRepository<GeoSpecialArtifact,Long> products = client.newPojoRepository(GeoSpecialArtifact.class, Long.class); PojoPage<GeoSpecialArtifact> p; this.loadSimplePojos(products); PojoQueryBuilder qb = products.getQueryBuilder(); PojoQueryBuilder containerQb = qb.containerQueryBuilder("manufacturer",GeoCompany.class); PojoQueryDefinition qd =containerQb.filteredQuery(containerQb.geospatial(containerQb.geoPath("latlongPoint"),containerQb.circle(36.1215, 115.1739, 1))); JacksonHandle jh = new JacksonHandle(); products.setPageLength(5); p = products.search(qd, 1,jh); System.out.println(jh.get().toString()); long pageNo=1,count=0; do{ count =0; p = products.search(qd,pageNo); while(p.hasNext()){ GeoSpecialArtifact a =p.next(); validateArtifact(a); assertTrue("Verifying document id is part of the search ids",a.getId()%5==0); assertEquals("Verifying Manufacurer is from state ","Las Vegas",a.getManufacturer().getState()); count++; } assertEquals("Page size",count,p.size()); pageNo=pageNo+p.getPageSize(); }while(!p.isLastPage() && pageNo<=p.getTotalSize()); assertEquals("Total results from search handle",5,jh.get().path("results").size()); } //This test is to verify GeoPath query works fine, // searching for lattitud and longitude of Reno @Test public void testPOJOGeoQuerySearchWithGeoPath() { PojoRepository<GeoSpecialArtifact,Long> products = client.newPojoRepository(GeoSpecialArtifact.class, Long.class); PojoPage<GeoSpecialArtifact> p; this.loadSimplePojos(products); PojoQueryBuilder qb = products.getQueryBuilder(); PojoQueryBuilder containerQb = qb.containerQueryBuilder("manufacturer",GeoCompany.class); PojoQueryDefinition qd =containerQb.geospatial(containerQb.geoPath("latlongPoint"),containerQb.circle(34.0500, 118.2500, 1)); JacksonHandle jh = new JacksonHandle(); products.setPageLength(15); p = products.search(qd, 1,jh); System.out.println(jh.get().toString()); assertEquals("total no of pages",3,p.getTotalPages()); System.out.println(jh.get().toString()); long pageNo=1,count=0; do{ count =0; p = products.search(qd,pageNo); while(p.hasNext()){ GeoSpecialArtifact a =p.next(); validateArtifact(a); assertTrue("Verifying document id is part of the search ids",a.getId()%2==0); assertEquals("Verifying Manufacurer is from state ","Los Angles",a.getManufacturer().getState()); count++; } assertEquals("Page size",count,p.size()); pageNo=pageNo+p.getPageSize(); }while(!p.isLastPage() && pageNo<=p.getTotalSize()); assertEquals("page number after the loop",3,p.getPageNumber()); assertEquals("total no of pages",3,p.getTotalPages()); assertEquals("page length from search handle",15,jh.get().path("page-length").asInt()); assertEquals("Total results from search handle",44,jh.get().path("total").asInt()); } }
/* * UssdsimulatorView.java */ package org.mobicents.protocols.ss7.ussdsimulator; import java.util.logging.Level; import java.util.logging.Logger; import org.jdesktop.application.Action; import org.jdesktop.application.ResourceMap; import org.jdesktop.application.SingleFrameApplication; import org.jdesktop.application.FrameView; import org.jdesktop.application.TaskMonitor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Properties; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.swing.Timer; import javax.swing.Icon; import javax.swing.JDialog; import javax.swing.JFrame; import org.mobicents.protocols.ss7.map.MAPStackImpl; import org.mobicents.protocols.ss7.map.api.MAPApplicationContext; import org.mobicents.protocols.ss7.map.api.MAPDialog; import org.mobicents.protocols.ss7.map.api.MAPDialogListener; import org.mobicents.protocols.ss7.map.api.MAPException; import org.mobicents.protocols.ss7.map.api.MAPProvider; import org.mobicents.protocols.ss7.map.api.MAPServiceListener; import org.mobicents.protocols.ss7.map.api.MAPStack; import org.mobicents.protocols.ss7.map.api.dialog.AddressNature; import org.mobicents.protocols.ss7.map.api.dialog.AddressString; import org.mobicents.protocols.ss7.map.api.dialog.MAPAcceptInfo; import org.mobicents.protocols.ss7.map.api.dialog.MAPCloseInfo; import org.mobicents.protocols.ss7.map.api.dialog.MAPOpenInfo; import org.mobicents.protocols.ss7.map.api.dialog.MAPProviderAbortInfo; import org.mobicents.protocols.ss7.map.api.dialog.MAPRefuseInfo; import org.mobicents.protocols.ss7.map.api.dialog.MAPUserAbortInfo; import org.mobicents.protocols.ss7.map.api.dialog.NumberingPlan; import org.mobicents.protocols.ss7.map.api.service.supplementary.ProcessUnstructuredSSIndication; import org.mobicents.protocols.ss7.map.api.service.supplementary.USSDString; import org.mobicents.protocols.ss7.map.api.service.supplementary.UnstructuredSSIndication; import org.mobicents.protocols.ss7.sccp.impl.sctp.SccpSCTPProviderImpl; import org.mobicents.protocols.ss7.sccp.parameter.GlobalTitle; import org.mobicents.protocols.ss7.sccp.parameter.SccpAddress; import org.mobicents.protocols.ss7.stream.tcp.StartFailedException; import org.mobicents.protocols.ss7.ussdsimulator.mtp.USSDSimultorMtpProvider; /** * The application's main frame. */ public class UssdsimulatorView extends FrameView implements MAPDialogListener,MAPServiceListener{ public UssdsimulatorView(SingleFrameApplication app) { super(app); initComponents(); // status bar initialization - message timeout, idle icon and busy animation, etc ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { // statusMessageLabel.setText(""); } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate"); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]"); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; // statusAnimationLabel.setIcon(busyIcons[busyIconIndex]); } }); idleIcon = resourceMap.getIcon("StatusBar.idleIcon"); // statusAnimationLabel.setIcon(idleIcon); // progressBar.setVisible(false); // connecting action tasks to status bar via TaskMonitor TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { if (!busyIconTimer.isRunning()) { // statusAnimationLabel.setIcon(busyIcons[0]); busyIconIndex = 0; busyIconTimer.start(); } // progressBar.setVisible(true); // progressBar.setIndeterminate(true); } else if ("done".equals(propertyName)) { busyIconTimer.stop(); // statusAnimationLabel.setIcon(idleIcon); // progressBar.setVisible(false); // progressBar.setValue(0); } else if ("message".equals(propertyName)) { String text = (String)(evt.getNewValue()); // statusMessageLabel.setText((text == null) ? "" : text); messageTimer.restart(); } else if ("progress".equals(propertyName)) { int value = (Integer)(evt.getNewValue()); //progressBar.setVisible(true); //progressBar.setIndeterminate(false); //progressBar.setValue(value); } } }); //stupid net beans, can do that from GUI _field_peer_ip.setText("127.0.0.1"); enableKeyPad(false); } @Action public void showAboutBox() { if (aboutBox == null) { JFrame mainFrame = UssdsimulatorApp.getApplication().getMainFrame(); aboutBox = new UssdsimulatorAboutBox(mainFrame); aboutBox.setLocationRelativeTo(mainFrame); } UssdsimulatorApp.getApplication().show(aboutBox); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { mainPanel = new javax.swing.JPanel(); cell_keypad_master_panel = new javax.swing.JPanel(); cell_keypad_call_buttons_panel = new javax.swing.JPanel(); _keypad_button_call = new javax.swing.JButton(); _keypad_button_break = new javax.swing.JButton(); _keypad_button_1 = new javax.swing.JButton(); _keypad_button_2 = new javax.swing.JButton(); _keypad_button_3 = new javax.swing.JButton(); _keypad_button_4 = new javax.swing.JButton(); _keypad_button_5 = new javax.swing.JButton(); _keypad_button_6 = new javax.swing.JButton(); _keypad_button_7 = new javax.swing.JButton(); _keypad_button_8 = new javax.swing.JButton(); _keypad_button_9 = new javax.swing.JButton(); _keypad_button_star = new javax.swing.JButton(); _keypad_button_0 = new javax.swing.JButton(); _keypad_button_hash = new javax.swing.JButton(); _field_result_display = new java.awt.TextArea(); _field_punch_display = new java.awt.TextArea(); jSeparator1 = new javax.swing.JSeparator(); jSeparator2 = new javax.swing.JSeparator(); _label_peer_IP = new javax.swing.JLabel(); _label_peer_port = new javax.swing.JLabel(); _field_peer_port = new javax.swing.JTextField(); _button_open_server = new javax.swing.JButton(); _button_close_server = new javax.swing.JButton(); _field_peer_ip = new javax.swing.JTextField(); menuBar = new javax.swing.JMenuBar(); javax.swing.JMenu fileMenu = new javax.swing.JMenu(); javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem(); javax.swing.JMenu helpMenu = new javax.swing.JMenu(); javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem(); mainPanel.setName("mainPanel"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(org.mobicents.protocols.ss7.ussdsimulator.UssdsimulatorApp.class).getContext().getResourceMap(UssdsimulatorView.class); cell_keypad_master_panel.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, resourceMap.getColor("cell_keypad_master_panel.border.matteColor"))); // NOI18N cell_keypad_master_panel.setName("cell_keypad_master_panel"); // NOI18N cell_keypad_call_buttons_panel.setName("cell_keypad_call_buttons_panel"); // NOI18N _keypad_button_call.setText(resourceMap.getString("_keypad_button_call.text")); // NOI18N _keypad_button_call.setName("_keypad_button_call"); // NOI18N _keypad_button_call.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_callActionPerformed(evt); } }); _keypad_button_break.setText(resourceMap.getString("_keypad_button_break.text")); // NOI18N _keypad_button_break.setName("_keypad_button_break"); // NOI18N _keypad_button_break.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_breakActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout cell_keypad_call_buttons_panelLayout = new org.jdesktop.layout.GroupLayout(cell_keypad_call_buttons_panel); cell_keypad_call_buttons_panel.setLayout(cell_keypad_call_buttons_panelLayout); cell_keypad_call_buttons_panelLayout.setHorizontalGroup( cell_keypad_call_buttons_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(cell_keypad_call_buttons_panelLayout.createSequentialGroup() .addContainerGap() .add(_keypad_button_call) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 13, Short.MAX_VALUE) .add(_keypad_button_break) .addContainerGap()) ); cell_keypad_call_buttons_panelLayout.setVerticalGroup( cell_keypad_call_buttons_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, cell_keypad_call_buttons_panelLayout.createSequentialGroup() .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(cell_keypad_call_buttons_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_keypad_button_call) .add(_keypad_button_break)) .addContainerGap()) ); _keypad_button_1.setText(resourceMap.getString("_keypad_button_1.text")); // NOI18N _keypad_button_1.setName("_keypad_button_1"); // NOI18N _keypad_button_1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_1ActionPerformed(evt); } }); _keypad_button_2.setText(resourceMap.getString("_keypad_button_2.text")); // NOI18N _keypad_button_2.setName("_keypad_button_2"); // NOI18N _keypad_button_2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_2ActionPerformed(evt); } }); _keypad_button_3.setText(resourceMap.getString("_keypad_button_3.text")); // NOI18N _keypad_button_3.setName("_keypad_button_3"); // NOI18N _keypad_button_3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_3ActionPerformed(evt); } }); _keypad_button_4.setText(resourceMap.getString("_keypad_button_4.text")); // NOI18N _keypad_button_4.setName("_keypad_button_4"); // NOI18N _keypad_button_4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_4ActionPerformed(evt); } }); _keypad_button_5.setText(resourceMap.getString("_keypad_button_5.text")); // NOI18N _keypad_button_5.setName("_keypad_button_5"); // NOI18N _keypad_button_5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_5ActionPerformed(evt); } }); _keypad_button_6.setText(resourceMap.getString("_keypad_button_6.text")); // NOI18N _keypad_button_6.setName("_keypad_button_6"); // NOI18N _keypad_button_6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_6ActionPerformed(evt); } }); _keypad_button_7.setText(resourceMap.getString("_keypad_button_7.text")); // NOI18N _keypad_button_7.setName("_keypad_button_7"); // NOI18N _keypad_button_7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_7ActionPerformed(evt); } }); _keypad_button_8.setText(resourceMap.getString("_keypad_button_8.text")); // NOI18N _keypad_button_8.setName("_keypad_button_8"); // NOI18N _keypad_button_8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_8ActionPerformed(evt); } }); _keypad_button_9.setText(resourceMap.getString("_keypad_button_9.text")); // NOI18N _keypad_button_9.setName("_keypad_button_9"); // NOI18N _keypad_button_9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_9ActionPerformed(evt); } }); _keypad_button_star.setText(resourceMap.getString("_keypad_button_star.text")); // NOI18N _keypad_button_star.setName("_keypad_button_star"); // NOI18N _keypad_button_star.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_starActionPerformed(evt); } }); _keypad_button_0.setText(resourceMap.getString("_keypad_button_0.text")); // NOI18N _keypad_button_0.setName("_keypad_button_0"); // NOI18N _keypad_button_0.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_0ActionPerformed(evt); } }); _keypad_button_hash.setText(resourceMap.getString("_keypad_button_hash.text")); // NOI18N _keypad_button_hash.setName("_keypad_button_hash"); // NOI18N _keypad_button_hash.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_hashActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout cell_keypad_master_panelLayout = new org.jdesktop.layout.GroupLayout(cell_keypad_master_panel); cell_keypad_master_panel.setLayout(cell_keypad_master_panelLayout); cell_keypad_master_panelLayout.setHorizontalGroup( cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(cell_keypad_master_panelLayout.createSequentialGroup() .addContainerGap() .add(cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(cell_keypad_master_panelLayout.createSequentialGroup() .add(_keypad_button_4) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_5) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .add(cell_keypad_master_panelLayout.createSequentialGroup() .add(_keypad_button_7) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_8) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_9, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .add(cell_keypad_master_panelLayout.createSequentialGroup() .add(_keypad_button_star) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_0) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_hash)) .add(cell_keypad_call_buttons_panel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(cell_keypad_master_panelLayout.createSequentialGroup() .add(_keypad_button_1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_2) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); cell_keypad_master_panelLayout.setVerticalGroup( cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(cell_keypad_master_panelLayout.createSequentialGroup() .addContainerGap() .add(cell_keypad_call_buttons_panel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_keypad_button_1) .add(_keypad_button_2) .add(_keypad_button_3)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_keypad_button_4) .add(_keypad_button_5) .add(_keypad_button_6)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_keypad_button_7) .add(_keypad_button_8) .add(_keypad_button_9)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_keypad_button_star) .add(_keypad_button_0) .add(_keypad_button_hash)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); _field_result_display.setEditable(false); _field_result_display.setName("_field_result_display"); // NOI18N _field_punch_display.setName("_field_punch_display"); // NOI18N jSeparator1.setName("jSeparator1"); // NOI18N jSeparator2.setName("jSeparator2"); // NOI18N _label_peer_IP.setText(resourceMap.getString("_label_peer_IP.text")); // NOI18N _label_peer_IP.setName("_label_peer_IP"); // NOI18N _label_peer_port.setText(resourceMap.getString("_label_peer_port.text")); // NOI18N _label_peer_port.setName("_label_peer_port"); // NOI18N _field_peer_port.setText(resourceMap.getString("_field_peer_port.text")); // NOI18N _field_peer_port.setName("_field_peer_port"); // NOI18N _button_open_server.setText(resourceMap.getString("_button_open_server.text")); // NOI18N _button_open_server.setName("_button_open_server"); // NOI18N _button_open_server.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _button_open_serverActionPerformed(evt); } }); _button_close_server.setText(resourceMap.getString("_button_close_server.text")); // NOI18N _button_close_server.setEnabled(false); _button_close_server.setName("_button_close_server"); // NOI18N _button_close_server.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _button_close_serverActionPerformed(evt); } }); _field_peer_ip.setText(resourceMap.getString("_field_peer_ip.text")); // NOI18N _field_peer_ip.setName("_field_peer_ip"); // NOI18N org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel); mainPanel.setLayout(mainPanelLayout); mainPanelLayout.setHorizontalGroup( mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createSequentialGroup() .addContainerGap() .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createSequentialGroup() .add(_field_result_display, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 415, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(_field_punch_display, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 160, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(cell_keypad_master_panel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .add(mainPanelLayout.createSequentialGroup() .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false) .add(org.jdesktop.layout.GroupLayout.LEADING, mainPanelLayout.createSequentialGroup() .add(_label_peer_port) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_field_peer_port)) .add(org.jdesktop.layout.GroupLayout.LEADING, mainPanelLayout.createSequentialGroup() .add(_label_peer_IP) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_field_peer_ip, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 122, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(_button_close_server, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(_button_open_server, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE))) .add(jSeparator2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 602, Short.MAX_VALUE)) .add(103, 103, 103)) ); mainPanelLayout.setVerticalGroup( mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createSequentialGroup() .addContainerGap() .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createSequentialGroup() .add(cell_keypad_master_panel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createSequentialGroup() .add(80, 80, 80) .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(mainPanelLayout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(_field_punch_display, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 175, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))) .add(_field_result_display, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 370, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jSeparator2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(7, 7, 7) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_label_peer_IP) .add(_field_peer_ip, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(_button_open_server)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_label_peer_port) .add(_field_peer_port, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(_button_close_server)) .addContainerGap(17, Short.MAX_VALUE)) ); menuBar.setName("menuBar"); // NOI18N fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N fileMenu.setName("fileMenu"); // NOI18N javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(org.mobicents.protocols.ss7.ussdsimulator.UssdsimulatorApp.class).getContext().getActionMap(UssdsimulatorView.class, this); exitMenuItem.setAction(actionMap.get("quit")); // NOI18N exitMenuItem.setName("exitMenuItem"); // NOI18N fileMenu.add(exitMenuItem); menuBar.add(fileMenu); helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N helpMenu.setName("helpMenu"); // NOI18N aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N aboutMenuItem.setName("aboutMenuItem"); // NOI18N helpMenu.add(aboutMenuItem); menuBar.add(helpMenu); setComponent(mainPanel); setMenuBar(menuBar); }// </editor-fold>//GEN-END:initComponents private void _button_open_serverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__button_open_serverActionPerformed this._button_close_server.setEnabled(true); this._button_open_server.setEnabled(false); this.initSS7Future = this._EXECUTOR.schedule(new Runnable() { public void run() { try { initSS7(); } catch (Exception ex) { Logger.getLogger(UssdsimulatorView.class.getName()).log(Level.SEVERE, null, ex); resetServer(); _field_punch_display.setText("Failed to initiate connection."); onlyKeyPadContent = false; } if(!mtpLayer.isLinkUp()) { resetServer(); _field_punch_display.setText("Failed to initiate connection."); onlyKeyPadContent = false; }else { _field_punch_display.setText("Connected to RA."); onlyKeyPadContent = false; //init some fake addressses //create some fake addresses. peer1Address = sccpProvider.getSccpParameterFactory().getSccpAddress(); GlobalTitle gt = sccpProvider.getSccpParameterFactory().getGlobalTitle100(); //dont set more, until statics are defined! gt.setDigits("5557779"); peer1Address.setGlobalTitle(gt); peer1Address.setGlobalTitleIndicator(4);//for GT 100 peer2Address = sccpProvider.getSccpParameterFactory().getSccpAddress(); gt = sccpProvider.getSccpParameterFactory().getGlobalTitle100(); //dont set more, until statics are defined! gt.setDigits("5888879"); peer2Address.setGlobalTitle(gt); peer2Address.setGlobalTitleIndicator(4);//for GT 100 //map/ussd part mapUssdAppContext = MAPApplicationContext.networkUnstructuredSsContextV2; //fake data again //FIXME: Amit add proper comments. orgiReference = mapStack.getMAPProvider().getMapServiceFactory() .createAddressString(AddressNature.international_number, NumberingPlan.ISDN, "31628968300"); destReference = mapStack.getMAPProvider().getMapServiceFactory() .createAddressString(AddressNature.international_number, NumberingPlan.land_mobile, "204208300008002"); //we are done, lets enable keypad enableKeyPad(true); } } },0,TimeUnit.MICROSECONDS); }//GEN-LAST:event__button_open_serverActionPerformed private void _button_close_serverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__button_close_serverActionPerformed this.resetServer(); }//GEN-LAST:event__button_close_serverActionPerformed private void _keypad_button_callActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_callActionPerformed //here we make map call to peer :) MAPProvider mapProvider = this.mapStack.getMAPProvider(); //here, if no dialog exists its initial call :) String punchedText = this._field_punch_display.getText(); if (punchedText == null || punchedText.equals("")) { return; } USSDString ussdString = mapProvider.getMapServiceFactory().createUSSDString(punchedText); if (this.clientDialog == null) { try { this.clientDialog = mapProvider.createNewDialog(this.mapUssdAppContext, this.peer1Address, orgiReference, this.peer2Address, destReference); } catch (MAPException ex) { Logger.getLogger(UssdsimulatorView.class.getName()).log(Level.SEVERE, null, ex); this._field_punch_display.setText("Failed to create MAP dialog: " + ex); this.onlyKeyPadContent = false; return; } } try { AddressString msisdn = this.mapStack.getMAPProvider().getMapServiceFactory() .createAddressString(AddressNature.international_number, NumberingPlan.ISDN, "31628838002"); clientDialog.addProcessUnstructuredSSRequest((byte) 0x0F, ussdString,msisdn); clientDialog.send(); this._field_punch_display.setText(""); this._keypad_button_break.setEnabled(true); this._field_result_display.append("\n"); this._field_result_display.append(punchedText); } catch (MAPException ex) { Logger.getLogger(UssdsimulatorView.class.getName()).log(Level.SEVERE, null, ex); this._field_punch_display.setText("Failed to pass USSD request: " + ex); this.onlyKeyPadContent = false; return; } }//GEN-LAST:event__keypad_button_callActionPerformed private void _keypad_button_breakActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_breakActionPerformed //this is set once call should end if(this.clientDialog!=null) { try { this.clientDialog.close(true); } catch (MAPException ex) { Logger.getLogger(UssdsimulatorView.class.getName()).log(Level.SEVERE, null, ex); this._field_punch_display.setText("Failed to close MAP Dialog: " + ex); this.onlyKeyPadContent = false; } this._keypad_button_break.setEnabled(false); } }//GEN-LAST:event__keypad_button_breakActionPerformed private void _keypad_button_1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_1ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_1ActionPerformed private void _keypad_button_2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_2ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_2ActionPerformed private void _keypad_button_3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_3ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_3ActionPerformed private void _keypad_button_4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_4ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_4ActionPerformed private void _keypad_button_5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_5ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_5ActionPerformed private void _keypad_button_6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_6ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_6ActionPerformed private void _keypad_button_7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_7ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_7ActionPerformed private void _keypad_button_8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_8ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_8ActionPerformed private void _keypad_button_9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_9ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_9ActionPerformed private void _keypad_button_starActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_starActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_starActionPerformed private void _keypad_button_0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_0ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_0ActionPerformed private void _keypad_button_hashActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_hashActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_hashActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton _button_close_server; private javax.swing.JButton _button_open_server; private javax.swing.JTextField _field_peer_ip; private javax.swing.JTextField _field_peer_port; private java.awt.TextArea _field_punch_display; private java.awt.TextArea _field_result_display; private javax.swing.JButton _keypad_button_0; private javax.swing.JButton _keypad_button_1; private javax.swing.JButton _keypad_button_2; private javax.swing.JButton _keypad_button_3; private javax.swing.JButton _keypad_button_4; private javax.swing.JButton _keypad_button_5; private javax.swing.JButton _keypad_button_6; private javax.swing.JButton _keypad_button_7; private javax.swing.JButton _keypad_button_8; private javax.swing.JButton _keypad_button_9; private javax.swing.JButton _keypad_button_break; private javax.swing.JButton _keypad_button_call; private javax.swing.JButton _keypad_button_hash; private javax.swing.JButton _keypad_button_star; private javax.swing.JLabel _label_peer_IP; private javax.swing.JLabel _label_peer_port; private javax.swing.JPanel cell_keypad_call_buttons_panel; private javax.swing.JPanel cell_keypad_master_panel; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JPanel mainPanel; private javax.swing.JMenuBar menuBar; // End of variables declaration//GEN-END:variables private final Timer messageTimer; private final Timer busyIconTimer; private final Icon idleIcon; private final Icon[] busyIcons = new Icon[15]; private int busyIconIndex = 0; private JDialog aboutBox; private void enableKeyPad(boolean b) { this._keypad_button_1.setEnabled(b); this._keypad_button_2.setEnabled(b); this._keypad_button_3.setEnabled(b); this._keypad_button_4.setEnabled(b); this._keypad_button_5.setEnabled(b); this._keypad_button_6.setEnabled(b); this._keypad_button_7.setEnabled(b); this._keypad_button_8.setEnabled(b); this._keypad_button_9.setEnabled(b); this._keypad_button_0.setEnabled(b); this._keypad_button_star.setEnabled(b); this._keypad_button_hash.setEnabled(b); this._keypad_button_call.setEnabled(b); this._keypad_button_break.setEnabled(false); } private void keypadDigitPressed(ActionEvent evt) { if(!this.onlyKeyPadContent) { //clear this._field_punch_display.setText(""); this.onlyKeyPadContent = true; } this._field_punch_display.append(evt.getActionCommand()); } // async stuff // private ScheduledExecutorService _EXECUTOR = Executors.newScheduledThreadPool(2); private Future initSS7Future; // State stuff // private boolean onlyKeyPadContent = false; private SccpAddress peer1Address,peer2Address; private MAPApplicationContext mapUssdAppContext; private AddressString orgiReference,destReference; private MAPDialog clientDialog; // SS7 part // private Properties stackProperties; // private TCAPStack tcapStack; // private TCAPProvider tcapProvider; //this sucks... private SccpSCTPProviderImpl sccpProvider; private MAPStack mapStack; //this we have to create private USSDSimultorMtpProvider mtpLayer; //method to init stacks private void initSS7() throws Exception { this.stackProperties = new Properties(); //fake values; this.stackProperties.put("sccp.opc", "13150"); this.stackProperties.put("sccp.dpc", "31510"); this.stackProperties.put("sccp.sls", "0"); this.stackProperties.put("sccp.ssf", "3"); mtpLayer = new USSDSimultorMtpProvider(_field_peer_ip, _field_peer_port); mtpLayer.start(); long startTime = System.currentTimeMillis(); while(!mtpLayer.isLinkUp()) { Thread.currentThread().sleep(5000); if(startTime+20000<System.currentTimeMillis()) { break; } } if(!this.mtpLayer.isLinkUp()) { throw new StartFailedException(); } this.sccpProvider = new SccpSCTPProviderImpl(this.mtpLayer, stackProperties); this.mapStack = new MAPStackImpl(sccpProvider); this.mapStack.getMAPProvider().addMAPDialogListener(this); this.mapStack.getMAPProvider().addMAPServiceListener(this); //indicate linkup, since we mockup now, its done by hand. //this method is called by M3UserConnector! this.sccpProvider.linkUp(); } //FIXME: add proper dialog kill private void terminateSS7() { if(this.mtpLayer!=null) { this.mtpLayer.stop(); //this.mtpLayer = null; } } private void resetServer() { if(this.initSS7Future!=null) { this.initSS7Future.cancel(false); this.initSS7Future = null; } terminateSS7(); _button_close_server.setEnabled(false); _button_open_server.setEnabled(true); this.enableKeyPad(false); } public void onMAPAcceptInfo(MAPAcceptInfo arg0) { //throw new UnsupportedOperationException("Not supported yet."); } public void onMAPOpenInfo(MAPOpenInfo arg0) { //throw new UnsupportedOperationException("Not supported yet."); } public void onMAPCloseInfo(MAPCloseInfo close) { this._field_punch_display.setText("Dialog Closed"); this.onlyKeyPadContent = false; this.clientDialog = null; this._keypad_button_break.setEnabled(false); } public void onMAPProviderAbortInfo(MAPProviderAbortInfo arg0) { this._field_punch_display.setText("Dialog Aborted: "+arg0); this.onlyKeyPadContent = false; this.clientDialog = null; this._keypad_button_break.setEnabled(false); } public void onMAPRefuseInfo(MAPRefuseInfo arg0) { this._field_punch_display.setText("Dialog Refused: "+arg0); this.onlyKeyPadContent = false; this.clientDialog = null; this._keypad_button_break.setEnabled(false); } public void onMAPUserAbortInfo(MAPUserAbortInfo arg0) { this._field_punch_display.setText("Dialog UAborted: "+arg0); this.onlyKeyPadContent = false; this.clientDialog = null; this._keypad_button_break.setEnabled(false); } public void onProcessUnstructuredSSIndication(ProcessUnstructuredSSIndication arg0) { //we dont server requests. throw new UnsupportedOperationException("Not supported yet."); } public void onUnstructuredSSIndication(UnstructuredSSIndication ussdInditaion) { //here RA responds. USSDString string =ussdInditaion.getUSSDString(); this._field_result_display.setText(string.getString()); } }
package org.mwc.cmap.TimeController.views; import java.awt.Frame; import java.awt.event.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.*; import java.text.*; import java.util.*; import javax.swing.JPopupMenu; import junit.framework.TestCase; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.jface.action.*; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.*; import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.*; import org.eclipse.ui.*; import org.eclipse.ui.part.ViewPart; import org.mwc.cmap.TimeController.TimeControllerPlugin; import org.mwc.cmap.core.CorePlugin; import org.mwc.cmap.core.DataTypes.Temporal.*; import org.mwc.cmap.core.ui_support.PartMonitor; import org.mwc.debrief.core.editors.painters.*; import com.visutools.nav.bislider.BiSlider; import org.eclipse.swt.awt.*; import MWC.GUI.Properties.DateFormatPropertyEditor; import MWC.GenericData.*; import MWC.Utilities.Timer.TimerListener; /** * This sample class demonstrates how to plug-in a new workbench view. The view * shows data obtained from the model. The sample creates a dummy model on the * fly, but a real implementation would connect to the model available either in * this or another plug-in (e.g. the workspace). The view is connected to the * model using a content provider. * <p> * The view uses a label provider to define how model objects should be * presented in the view. Each view can present the same model objects using * different labels and icons, if needed. Alternatively, a single label provider * can be shared between views in order to ensure that objects of the same type * are presented in the same way everywhere. * <p> */ public class TimeController extends ViewPart implements ISelectionProvider, TimerListener { private PartMonitor _myPartMonitor; /** * the automatic timer we are using */ private MWC.Utilities.Timer.Timer _theTimer; /** * the editor the user is currently working with (assigned alongside the * time-provider object) */ protected IEditorPart _currentEditor; final private PropertyChangeListener _temporalListener = new NewTimeListener(); /** * the temporal dataset controlling the narrative entry currently displayed */ private TimeProvider _myTemporalDataset; /** * the "write" interface for the plot which tracks the narrative, where * avaialable */ private ControllableTime _controllableTime; /** * label showing the current time */ private Label _timeLabel; /** * the parent object for the time controller. It is at this level that we * enable/disable the controls */ private Composite _wholePanel; /** * the people listening to us */ private Vector _selectionListeners; /** * the thing we're currently displaying */ private ISelection _currentSelection; /** * and the preferences for time control */ private TimeControlProperties _myStepperProperties; /** * module to look after the limits of the slider */ SliderRangeManagement _slideManager = null; /** * the action which stores the current DTG as a bookmark */ private Action _setAsBookmarkAction; /** * This is a callback that will allow us to create the viewer and initialize * it. */ public void createPartControl(Composite parent) { // also sort out the slider conversion bits. We do it at the start, because // callbacks // created during initialisation may need to use/reset it _slideManager = new SliderRangeManagement() { public void setMinVal(int min) { _tNowSlider.setMinimum(min); } public void setMaxVal(int max) { _tNowSlider.setMaximum(max); } public void setTickSize(int small, int large, int drag) { _tNowSlider.setIncrement(small); _tNowSlider.setPageIncrement(large); } public void setEnabled(boolean val) { _tNowSlider.setEnabled(val); } }; // and fill in the interface buildInterface(parent); // of course though, we start off with the buttons not enabled _wholePanel.setEnabled(false); // and start listing for any part action setupListeners(); // ok we're all ready now. just try and see if the current part is valid _myPartMonitor.fireActivePart(getSite().getWorkbenchWindow().getActivePage()); // say that we're a selection provider getSite().setSelectionProvider(this); /** * the timer-related settings */ _theTimer = new MWC.Utilities.Timer.Timer(); _theTimer.stop(); _theTimer.setDelay(1000); _theTimer.addTimerListener(this); } /** * the slider control - remember it because we're always changing the limits, * etc */ private Scale _tNowSlider; /** * when the user clicks on us, we set our properties as a selection. Remember * the set of properties */ private StructuredSelection _propsAsSelection = null; protected TimeControlPreferences _myTimePreferences; /** * ok - put in our bits * * @param parent */ private void buildInterface(Composite parent) { // ok, draw our wonderful GUI. _wholePanel = new Composite(parent, SWT.BORDER); FillLayout onTop = new FillLayout(SWT.VERTICAL); _wholePanel.setLayout(onTop); // first create the button holder Composite _btnPanel = new Composite(_wholePanel, SWT.NONE); FillLayout btnFiller = new FillLayout(SWT.HORIZONTAL); btnFiller.marginHeight = 0; _btnPanel.setLayout(btnFiller); Button eBwd = new Button(_btnPanel, SWT.NONE); eBwd.addSelectionListener(new TimeButtonSelectionListener(false, null)); eBwd.setImage(TimeControllerPlugin.getImageDescriptor("icons/VCRBegin.gif") .createImage()); Button lBwd = new Button(_btnPanel, SWT.NONE); lBwd.setText("<<"); lBwd.setImage(TimeControllerPlugin.getImageDescriptor("icons/VCRRewind.gif") .createImage()); lBwd.addSelectionListener(new TimeButtonSelectionListener(false, new Boolean(true))); Button sBwd = new Button(_btnPanel, SWT.NONE); sBwd.setText("<"); sBwd.setImage(TimeControllerPlugin.getImageDescriptor("icons/VCRBack.gif") .createImage()); sBwd.addSelectionListener(new TimeButtonSelectionListener(false, new Boolean(false))); final Button play = new Button(_btnPanel, SWT.TOGGLE | SWT.NONE); play.setImage(TimeControllerPlugin.getImageDescriptor("icons/VCRPlay.gif") .createImage()); play.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { boolean playing = play.getSelection(); ImageDescriptor thisD; if (playing) { thisD = TimeControllerPlugin.getImageDescriptor("icons/VCRPause.gif"); startPlaying(); } else { thisD = TimeControllerPlugin.getImageDescriptor("icons/VCRPlay.gif"); stopPlaying(); } play.setImage(thisD.createImage()); } }); Button sFwd = new Button(_btnPanel, SWT.NONE); sFwd.setImage(TimeControllerPlugin.getImageDescriptor("icons/VCRForward.gif") .createImage()); sFwd.addSelectionListener(new TimeButtonSelectionListener(true, new Boolean(false))); Button lFwd = new Button(_btnPanel, SWT.NONE); lFwd.setImage(TimeControllerPlugin.getImageDescriptor("icons/VCRFastForward.gif") .createImage()); lFwd.addSelectionListener(new TimeButtonSelectionListener(true, new Boolean(true))); Button eFwd = new Button(_btnPanel, SWT.NONE); eFwd.setImage(TimeControllerPlugin.getImageDescriptor("icons/VCREnd.gif") .createImage()); eFwd.addSelectionListener(new TimeButtonSelectionListener(true, null)); // and the current time label Composite timeContainer = new Composite(_wholePanel, SWT.NONE); FillLayout timeFiller = new FillLayout(SWT.HORIZONTAL); timeContainer.setLayout(timeFiller); _timeLabel = new Label(timeContainer, SWT.NONE); _timeLabel.setAlignment(SWT.CENTER); _timeLabel.setText(" _timeLabel.setFont(new Font(Display.getDefault(), "OCR A Extended", 16, SWT.NONE)); _timeLabel.setForeground(new Color(Display.getDefault(), 33, 255, 22)); _timeLabel.setBackground(new Color(Display.getDefault(), 0, 0, 0)); // next create the time slider holder _tNowSlider = new Scale(_wholePanel, SWT.NONE); _tNowSlider.setMinimum(0); _tNowSlider.setMaximum(100); _tNowSlider.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { int index = _tNowSlider.getSelection(); HiResDate newDTG = _slideManager.fromSliderUnits(index, _myTemporalDataset .getPeriod().getStartDTG()); fireNewTime(newDTG); } public void widgetDefaultSelected(SelectionEvent e) { } }); _wholePanel.addListener(SWT.MouseWheel, new WheelMovedEvent()); /* * the next bit is a fudge (taken from "How to scroll a canvas" on Eclipse * newsgroups */ _wholePanel.addListener(SWT.MouseDown, new Listener() { public void handleEvent(Event event) { Control focus = event.display.getFocusControl(); while (focus != null) { focus = focus.getParent(); } _wholePanel.setFocus(); } }); // try and put in a bi-slider Composite sliderContainer = new Composite(_wholePanel, SWT.EMBEDDED); java.awt.Frame sliderFrame = SWT_AWT.new_Frame(sliderContainer); final BiSlider bi = new BiSlider(); sliderFrame.add(bi); bi.setVisible(true); bi.setMinimumValue(-193); bi.setMaximumValue(227); bi.setSegmentSize(20); bi.setMinimumColor(java.awt.Color.GRAY); bi.setMaximumColor(java.awt.Color.GRAY); bi.setUnit(""); bi.setPrecise(true); final JPopupMenu JPopupMenu1 = bi.createPopupMenu(); bi.addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent MouseEvent_Arg){ if (MouseEvent_Arg.getButton()==MouseEvent.BUTTON3){ JPopupMenu1.show(bi, MouseEvent_Arg.getX(), MouseEvent_Arg.getY()); } } }); } protected void stopPlaying() { _theTimer.stop(); } /** * ok, start auto-stepping forward through the serial */ protected void startPlaying() { // hey - set a practical minimum step size, 1/4 second is a fair start point final long delayToUse = Math.max(_myStepperProperties.getAutoInterval().getMillis(), 250); // ok - make sure the time has the right time _theTimer.setDelay(delayToUse); _theTimer.start(); } public void onTime(ActionEvent event) { // temporarily remove ourselves, to prevent being called twice _theTimer.removeTimerListener(this); // catch any exceptions raised here, it doesn't really // matter if we miss a time step try { // pass the step operation on to our parent processClick(Boolean.FALSE, true); } catch (Exception e) { CorePlugin.logError(Status.ERROR, "Error on auto-time stepping", e); } // register ourselves as a time again _theTimer.addTimerListener(this); } private final class NewTimeListener implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent event) { // see if it's the time or the period which // has changed if (event.getPropertyName().equals(TimeProvider.TIME_CHANGED_PROPERTY_NAME)) { // ok, use the new time HiResDate newDTG = (HiResDate) event.getNewValue(); timeUpdated(newDTG); } else if (event.getPropertyName().equals(TimeProvider.PERIOD_CHANGED_PROPERTY_NAME)) { TimePeriod newPeriod = (TimePeriod) event.getNewValue(); _slideManager.resetRange(newPeriod.getStartDTG(), newPeriod.getEndDTG()); } // also double-check if it's time to enable our interface checkTimeEnabled(); } } private class TimeButtonSelectionListener implements SelectionListener { private boolean _fwd; private Boolean _large; public TimeButtonSelectionListener(boolean fwd, Boolean large) { _fwd = fwd; _large = large; } public void widgetSelected(SelectionEvent e) { processClick(_large, _fwd); } public void widgetDefaultSelected(SelectionEvent e) { } } private void processClick(Boolean large, boolean fwd) { // check that we have a current time (on initialisation some plots may not // contain data) HiResDate tNow = _myTemporalDataset.getTime(); if (tNow != null) { // yup, time is there. work with it baby long micros = tNow.getMicros(); // right, special case for when user wants to go straight to the end - in // which // case there is a zero in the scale if (large == null) { // right, fwd or bwd if (fwd) micros = _myTemporalDataset.getPeriod().getEndDTG().getMicros(); else micros = _myTemporalDataset.getPeriod().getStartDTG().getMicros(); } else { long size; // normal processing.. if (large.booleanValue()) { // do large step size = (long) _myStepperProperties.getLargeStep().getValueIn( Duration.MICROSECONDS); } else { // and the small size step size = (long) _myStepperProperties.getSmallStep().getValueIn( Duration.MICROSECONDS); } // right, either move forwards or backwards. if (fwd) micros += size; else micros -= size; } HiResDate newDTG = new HiResDate(0, micros); // find the extent of the current dataset TimePeriod timeP = _myTemporalDataset.getPeriod(); // do we represent a valid time? if (timeP.contains(newDTG)) { // yes, fire the new DTG fireNewTime(newDTG); } } } private void fireNewTime(HiResDate dtg) { _controllableTime.setTime(this, dtg); } private void setupListeners() { // try to add ourselves to listen out for page changes // getSite().getWorkbenchWindow().getPartService().addPartListener(this); _myPartMonitor = new PartMonitor(getSite().getWorkbenchWindow().getPartService()); _myPartMonitor.addPartListener(TimeProvider.class, PartMonitor.OPENED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // implementation here. // TimeProvider thisTemporalDataset = (TimeProvider) part; // thisTemporalDataset.addListener(_temporalListener, // TimeProvider.TIME_CHANGED_PROPERTY_NAME); } }); _myPartMonitor.addPartListener(TimeProvider.class, PartMonitor.ACTIVATED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { if (_myTemporalDataset != part) { // ok, stop listening to the old one if (_myTemporalDataset != null) _myTemporalDataset.removeListener(_temporalListener, TimeProvider.TIME_CHANGED_PROPERTY_NAME); // implementation here. _myTemporalDataset = (TimeProvider) part; // and start listening to the new one _myTemporalDataset.addListener(_temporalListener, TimeProvider.TIME_CHANGED_PROPERTY_NAME); // also configure for the current time HiResDate newDTG = _myTemporalDataset.getTime(); timeUpdated(newDTG); // and initialise the current time TimePeriod firstDTG = _myTemporalDataset.getPeriod(); if (firstDTG != null) { _slideManager.resetRange(firstDTG.getStartDTG(), firstDTG.getEndDTG()); } checkTimeEnabled(); // hmm, do we want to store this part? _currentEditor = (IEditorPart) parentPart; } } }); _myPartMonitor.addPartListener(TimeProvider.class, PartMonitor.CLOSED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // ok, stop listening to this object (just in case we were, anyway). _myTemporalDataset.removeListener(_temporalListener, TimeProvider.TIME_CHANGED_PROPERTY_NAME); // was it our one? if (_myTemporalDataset == part) { _myTemporalDataset = null; } // and sort out whether we should be active or not. checkTimeEnabled(); } }); // _myPartMonitor.addPartListener(TimeProvider.class, PartMonitor.CLOSED, // new PartMonitor.ICallback() // public void eventTriggered(String type, Object part, IWorkbenchPart // parentPart) // // are we still listening? // if (_myTemporalDataset != null) // _myTemporalDataset.removeListener(_temporalListener, // TimeProvider.TIME_CHANGED_PROPERTY_NAME); // _myTemporalDataset = null; // checkTimeEnabled(); _myPartMonitor.addPartListener(ControllableTime.class, PartMonitor.ACTIVATED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // implementation here. ControllableTime ct = (ControllableTime) part; _controllableTime = ct; checkTimeEnabled(); } }); _myPartMonitor.addPartListener(ControllableTime.class, PartMonitor.CLOSED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { _controllableTime = null; checkTimeEnabled(); } }); _myPartMonitor.addPartListener(LayerPainterManager.class, PartMonitor.ACTIVATED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // ok, insert the painter mode actions, together with our standard // ones populateDropDownList((LayerPainterManager) part); } }); _myPartMonitor.addPartListener(LayerPainterManager.class, PartMonitor.CLOSED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // _painterSelector.getCombo().setEnabled(false); // _myLayerPainterManager = null; } }); _myPartMonitor.addPartListener(TimeControlPreferences.class, PartMonitor.ACTIVATED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // just check we're not already managing this plot if (part != _myStepperProperties) { // ok, ignore the old one, if we have one if (_myStepperProperties != null) { _myStepperProperties.removePropertyChangeListener(_myDateFormatListener); _myStepperProperties = null; } _myStepperProperties = (TimeControlProperties) part; if (_myDateFormatListener == null) _myDateFormatListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { // right, see if the user is changing the DTG format if (evt.getPropertyName().equals(TimeControlProperties.DTG_FORMAT_ID)) { // ok, refresh the DTG String newVal = getFormattedDate(_myTemporalDataset.getTime()); _timeLabel.setText(newVal); } } }; // also, listen out for changes in the DTG formatter _myStepperProperties.addPropertyChangeListener(_myDateFormatListener); } } }); _myPartMonitor.addPartListener(TimeControlPreferences.class, PartMonitor.DEACTIVATED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { } }); } private PropertyChangeListener _myDateFormatListener = null; /** * convenience method to make the panel enabled if we have a time controller * and a valid time */ private void checkTimeEnabled() { boolean enable = false; if (_myTemporalDataset != null) { if ((_controllableTime != null) && (_myTemporalDataset.getTime() != null)) enable = true; } final boolean finalEnabled = enable; Display.getDefault().asyncExec(new Runnable() { public void run() { if (!_wholePanel.isDisposed()) { // aaah, if we're clearing the panel, set the text to "pending" if (!finalEnabled) { _timeLabel.setText(" } _wholePanel.setEnabled(finalEnabled); } } }); } /* * (non-Javadoc) * * @see org.eclipse.ui.part.WorkbenchPart#dispose() */ public void dispose() { super.dispose(); // and stop listening for part activity _myPartMonitor.dispose(getSite().getWorkbenchWindow().getPartService()); // also stop listening for time events if (_myTemporalDataset != null) { _myTemporalDataset.removeListener(_temporalListener, TimeProvider.TIME_CHANGED_PROPERTY_NAME); } } /** * Passing the focus request to the viewer's control. */ public void setFocus() { // get the editable thingy if (_propsAsSelection == null) _propsAsSelection = new StructuredSelection(_myStepperProperties); fireSelectionChanged(_propsAsSelection); _propsAsSelection = null; } // temporal data management /** * the data we are looking at has updated. If we're set to follow that time, * update ourselves */ private void timeUpdated(final HiResDate newDTG) { if (newDTG != null) { if (!_timeLabel.isDisposed()) { // updating the text items has to be done in the UI thread. make it so Display.getDefault().asyncExec(new Runnable() { public void run() { // display the correct time. String newVal = getFormattedDate(newDTG); _timeLabel.setText(newVal); // there's a (slim) chance that the temp dataset has already been // cleared, or // hasn't been caught yet. just check we still know about it if (_myTemporalDataset != null) { TimePeriod dataPeriod = _myTemporalDataset.getPeriod(); if (dataPeriod != null) { int newIndex = _slideManager.toSliderUnits(newDTG, dataPeriod .getStartDTG()); _tNowSlider.setSelection(newIndex); } } } }); } } else { System.out.println("null DTG received by time controller"); } } private String getFormattedDate(HiResDate newDTG) { String newVal = "n/a"; // hmm, we may have heard about the new date before hearing about the // plot's stepper properties. check they arrived if (_myStepperProperties != null) { String dateFormat = _myStepperProperties.getDTGFormat(); // store.getString(PreferenceConstants.P_STRING); try { newVal = toStringHiRes(newDTG, dateFormat); } catch (IllegalArgumentException e) { System.err.println("Invalid date format in preferences"); } } return newVal; } public static String toStringHiRes(HiResDate time, String pattern) throws IllegalArgumentException { // so, have a look at the data long micros = time.getMicros(); // long wholeSeconds = micros / 1000000; StringBuffer res = new StringBuffer(); java.util.Date theTime = new java.util.Date(micros / 1000); SimpleDateFormat selectedFormat = new SimpleDateFormat(pattern); selectedFormat.setTimeZone(TimeZone.getTimeZone("GMT")); res.append(selectedFormat.format(theTime)); DecimalFormat microsFormat = new DecimalFormat("000000"); DecimalFormat millisFormat = new DecimalFormat("000"); // do we have micros? if (micros % 1000 > 0) { // yes res.append("."); res.append(microsFormat.format(micros % 1000000)); } else { // do we have millis? if (micros % 1000000 > 0) { // yes, convert the value to millis long millis = micros = (micros % 1000000) / 1000; res.append("."); res.append(millisFormat.format(millis)); } else { // just use the normal output } } return res.toString(); } public static class TestTimeController extends TestCase { private int _min, _max, _smallTick, _largeTick, _dragSize; private boolean _enabled; public void testSliderScales() { SliderRangeManagement range = new SliderRangeManagement() { public void setMinVal(int min) { _min = min; } public void setMaxVal(int max) { _max = max; } public void setTickSize(int small, int large, int drag) { _smallTick = small; _largeTick = large; _dragSize = drag; } public void setEnabled(boolean val) { _enabled = val; } }; // initialise our testing values _min = _max = _smallTick = _largeTick = -1; _enabled = false; HiResDate starter = new HiResDate(0, 100); HiResDate ender = new HiResDate(0, 200); range.resetRange(starter, ender); assertEquals("min val set", 0, _min); assertEquals("max val set", 100, _max); assertEquals("sml tick set", 10000, _smallTick); assertEquals("drag size set", 500, _dragSize); assertEquals("large tick set", 100000, _largeTick); assertTrue("slider should be enabled", _enabled); // ok, see how the transfer goes HiResDate newToSlider = new HiResDate(0, 130); int res = range.toSliderUnits(newToSlider, starter); assertEquals("correct to slider units", 30, res); // and backwards newToSlider = range.fromSliderUnits(res, starter); assertEquals("correct from slider units", 130, newToSlider.getMicros()); // right, now back to millis Date starterD = new Date(2005, 3, 3, 12, 1, 1); Date enderD = new Date(2005, 3, 12, 12, 1, 1); starter = new HiResDate(starterD.getTime()); ender = new HiResDate(enderD.getTime()); range.resetRange(starter, ender); long diff = (enderD.getTime() - starterD.getTime()) / 1000; assertEquals("correct range in secs", diff, _max); assertEquals("sml tick set", 60, _smallTick); assertEquals("large tick set", 600, _largeTick); } } private class WheelMovedEvent implements Listener { public void handleEvent(Event event) { int count = event.count; boolean fwd; Boolean large = new Boolean(false); // is the control button down? int keys = event.stateMask; if ((keys & SWT.SHIFT) != 0) large = new Boolean(true); if (count < 0) fwd = true; else fwd = false; processClick(large, fwd); } } public void addSelectionChangedListener(ISelectionChangedListener listener) { if (_selectionListeners == null) _selectionListeners = new Vector(0, 1); // see if we don't already contain it.. if (!_selectionListeners.contains(listener)) _selectionListeners.add(listener); } public ISelection getSelection() { return _currentSelection; } public void removeSelectionChangedListener(ISelectionChangedListener listener) { _selectionListeners.remove(listener); } public void setSelection(ISelection selection) { _currentSelection = selection; } protected void fireSelectionChanged(ISelection sel) { // just double-check that we're not already processing this if (sel != _currentSelection) { _currentSelection = sel; if (_selectionListeners != null) { SelectionChangedEvent sEvent = new SelectionChangedEvent(this, sel); for (Iterator stepper = _selectionListeners.iterator(); stepper.hasNext();) { ISelectionChangedListener thisL = (ISelectionChangedListener) stepper.next(); if (thisL != null) { thisL.selectionChanged(sEvent); } } } } } /** * ok - put in the stepper mode buttons - and any others we think of. */ private void populateDropDownList(final LayerPainterManager myLayerPainterManager) { // clear the list final IMenuManager menuManager = getViewSite().getActionBars().getMenuManager(); final IToolBarManager toolManager = getViewSite().getActionBars().getToolBarManager(); // ok, remove the existing items menuManager.removeAll(); toolManager.removeAll(); // ok, what are the painters we know about TemporalLayerPainter[] list = myLayerPainterManager.getList(); // add the items for (int i = 0; i < list.length; i++) { // ok, next painter final TemporalLayerPainter painter = list[i]; // create an action for it Action thisOne = new Action(painter.toString(), Action.AS_RADIO_BUTTON) { public void runWithEvent(Event event) { myLayerPainterManager.setCurrentPainter(painter); } }; // hmm, and see if this is our current painter if (painter.getName().equals(myLayerPainterManager.getCurrentPainter().getName())) { thisOne.setChecked(true); } // and store it on both menus menuManager.add(thisOne); toolManager.add(thisOne); } // ok, let's have a separator menuManager.add(new Separator()); // ok, second menu for the DTG formats MenuManager formatMenu = new MenuManager("DTG Format"); // and store it menuManager.add(formatMenu); // and now the date formats String[] formats = DateFormatPropertyEditor.getTagList(); for (int i = 0; i < formats.length; i++) { final String thisFormat = formats[i]; // the properties manager is expecting the integer index of the new // format, not the string value. // so store it as an integer index final Integer thisIndex = new Integer(i); // and create a new action to represent the change Action newFormat = new Action(thisFormat, Action.AS_RADIO_BUTTON) { public void run() { super.run(); _myStepperProperties.setPropertyValue(TimeControlProperties.DTG_FORMAT_ID, thisIndex); } }; formatMenu.add(newFormat); } // lastly the add-bookmark item _setAsBookmarkAction = new Action("Add DTG as bookmark", Action.AS_PUSH_BUTTON) { public void runWithEvent(Event event) { addMarker(); } }; menuManager.add(_setAsBookmarkAction); // ok - get the action bars to re-populate themselves, otherwise we don't // see our changes getViewSite().getActionBars().updateActionBars(); } protected void addMarker() { try { // right, do we have an editor with a file? IEditorInput input = _currentEditor.getEditorInput(); if (input instanceof IFileEditorInput) { // aaah, and is there a file present? IFileEditorInput ife = (IFileEditorInput) input; IResource file = ife.getFile(); String currentText = _timeLabel.getText(); long tNow = _myTemporalDataset.getTime().getMicros(); if (file != null) { // yup, get the description InputDialog inputD = new InputDialog(getViewSite().getShell(), "Add bookmark at this DTG", "Enter description of this bookmark", currentText, null); inputD.open(); String content = inputD.getValue(); if (content != null) { IMarker marker = file.createMarker(IMarker.BOOKMARK); Map attributes = new HashMap(4); attributes.put(IMarker.MESSAGE, content); attributes.put(IMarker.LOCATION, currentText); attributes.put(IMarker.LINE_NUMBER, "" + tNow); attributes.put(IMarker.USER_EDITABLE, Boolean.FALSE); marker.setAttributes(attributes); } } } } catch (CoreException e) { e.printStackTrace(); } } // AND PROPERTY EDITORS FOR THE }
package org.wildfly.extension.undertow.deployment; import io.undertow.Handlers; import io.undertow.jsp.JspFileHandler; import io.undertow.jsp.JspServletBuilder; import io.undertow.predicate.Predicate; import io.undertow.security.api.AuthenticationMechanism; import io.undertow.security.api.AuthenticationMode; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.builder.PredicatedHandler; import io.undertow.server.handlers.resource.CachingResourceManager; import io.undertow.server.handlers.resource.FileResourceManager; import io.undertow.server.handlers.resource.ResourceManager; import io.undertow.server.session.SecureRandomSessionIdGenerator; import io.undertow.servlet.ServletExtension; import io.undertow.servlet.Servlets; import io.undertow.servlet.api.AuthMethodConfig; import io.undertow.servlet.api.ClassIntrospecter; import io.undertow.servlet.api.ConfidentialPortManager; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.ErrorPage; import io.undertow.servlet.api.FilterInfo; import io.undertow.servlet.api.HttpMethodSecurityInfo; import io.undertow.servlet.api.InstanceFactory; import io.undertow.servlet.api.InstanceHandle; import io.undertow.servlet.api.ListenerInfo; import io.undertow.servlet.api.LoginConfig; import io.undertow.servlet.api.MimeMapping; import io.undertow.servlet.api.SecurityConstraint; import io.undertow.servlet.api.ServletContainerInitializerInfo; import io.undertow.servlet.api.ServletInfo; import io.undertow.servlet.api.ServletSecurityInfo; import io.undertow.servlet.api.ServletSessionConfig; import io.undertow.servlet.api.SessionManagerFactory; import io.undertow.servlet.api.ThreadSetupHandler; import io.undertow.servlet.api.WebResourceCollection; import io.undertow.servlet.handlers.DefaultServlet; import io.undertow.servlet.handlers.ServletPathMatches; import io.undertow.servlet.util.ImmediateInstanceFactory; import io.undertow.websockets.extensions.PerMessageDeflateHandshake; import io.undertow.websockets.jsr.ServerWebSocketContainer; import io.undertow.websockets.jsr.WebSocketDeploymentInfo; import org.apache.jasper.deploy.FunctionInfo; import org.apache.jasper.deploy.JspPropertyGroup; import org.apache.jasper.deploy.TagAttributeInfo; import org.apache.jasper.deploy.TagFileInfo; import org.apache.jasper.deploy.TagInfo; import org.apache.jasper.deploy.TagLibraryInfo; import org.apache.jasper.deploy.TagLibraryValidatorInfo; import org.apache.jasper.deploy.TagVariableInfo; import org.apache.jasper.servlet.JspServlet; import org.jboss.annotation.javaee.Icon; import org.jboss.as.ee.component.ComponentRegistry; import org.jboss.as.naming.ManagedReference; import org.jboss.as.naming.ManagedReferenceFactory; import org.jboss.as.security.plugins.SecurityDomainContext; import org.jboss.as.server.deployment.SetupAction; import org.jboss.as.server.suspend.ServerActivity; import org.jboss.as.server.suspend.ServerActivityCallback; import org.jboss.as.server.suspend.SuspendController; import org.jboss.as.web.common.ExpressionFactoryWrapper; import org.jboss.as.web.common.ServletContextAttribute; import org.jboss.as.web.common.WebInjectionContainer; import org.jboss.as.web.session.SessionIdentifierCodec; import org.jboss.metadata.javaee.spec.DescriptionGroupMetaData; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.javaee.spec.SecurityRoleRefMetaData; import org.jboss.metadata.web.jboss.JBossServletMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.metadata.web.spec.AttributeMetaData; import org.jboss.metadata.web.spec.CookieConfigMetaData; import org.jboss.metadata.web.spec.DispatcherType; import org.jboss.metadata.web.spec.EmptyRoleSemanticType; import org.jboss.metadata.web.spec.ErrorPageMetaData; import org.jboss.metadata.web.spec.FilterMappingMetaData; import org.jboss.metadata.web.spec.FilterMetaData; import org.jboss.metadata.web.spec.FunctionMetaData; import org.jboss.metadata.web.spec.HttpMethodConstraintMetaData; import org.jboss.metadata.web.spec.JspConfigMetaData; import org.jboss.metadata.web.spec.JspPropertyGroupMetaData; import org.jboss.metadata.web.spec.ListenerMetaData; import org.jboss.metadata.web.spec.LocaleEncodingMetaData; import org.jboss.metadata.web.spec.LoginConfigMetaData; import org.jboss.metadata.web.spec.MimeMappingMetaData; import org.jboss.metadata.web.spec.MultipartConfigMetaData; import org.jboss.metadata.web.spec.SecurityConstraintMetaData; import org.jboss.metadata.web.spec.ServletMappingMetaData; import org.jboss.metadata.web.spec.SessionConfigMetaData; import org.jboss.metadata.web.spec.SessionTrackingModeType; import org.jboss.metadata.web.spec.TagFileMetaData; import org.jboss.metadata.web.spec.TagMetaData; import org.jboss.metadata.web.spec.TldMetaData; import org.jboss.metadata.web.spec.TransportGuaranteeType; import org.jboss.metadata.web.spec.VariableMetaData; import org.jboss.metadata.web.spec.WebResourceCollectionMetaData; import org.jboss.modules.Module; import org.jboss.msc.inject.Injector; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; import org.jboss.security.audit.AuditManager; import org.jboss.security.auth.login.JASPIAuthenticationInfo; import org.jboss.security.authorization.config.AuthorizationModuleEntry; import org.jboss.security.authorization.modules.JACCAuthorizationModule; import org.jboss.security.config.ApplicationPolicy; import org.jboss.security.config.AuthorizationInfo; import org.jboss.security.config.SecurityConfiguration; import org.jboss.vfs.VirtualFile; import org.wildfly.extension.requestcontroller.ControlPoint; import org.wildfly.extension.undertow.Host; import org.wildfly.extension.undertow.JSPConfig; import org.wildfly.extension.undertow.ServletContainerService; import org.wildfly.extension.undertow.SessionCookieConfig; import org.wildfly.extension.undertow.SingleSignOnService; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.wildfly.extension.undertow.UndertowService; import org.wildfly.extension.undertow.ApplicationSecurityDomainDefinition.Registration; import org.wildfly.extension.undertow.security.AuditNotificationReceiver; import org.wildfly.extension.undertow.security.JAASIdentityManagerImpl; import org.wildfly.extension.undertow.security.JbossAuthorizationManager; import org.wildfly.extension.undertow.security.LogoutNotificationReceiver; import org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor; import org.wildfly.extension.undertow.security.SecurityContextAssociationHandler; import org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction; import org.wildfly.extension.undertow.security.jacc.JACCAuthorizationManager; import org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler; import org.wildfly.extension.undertow.security.jaspi.JASPICAuthenticationMechanism; import org.wildfly.extension.undertow.security.jaspi.JASPICSecureResponseHandler; import org.wildfly.extension.undertow.security.jaspi.JASPICSecurityContextFactory; import org.wildfly.extension.undertow.session.CodecSessionConfigWrapper; import org.wildfly.extension.undertow.session.SharedSessionManagerConfig; import org.xnio.IoUtils; import javax.servlet.Filter; import javax.servlet.Servlet; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.SessionTrackingMode; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EventListener; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import org.jboss.security.AuthenticationManager; import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.AUTHENTICATE; import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.DENY; import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.PERMIT; import org.jboss.as.server.ServerEnvironment; import org.jboss.security.authentication.JBossCachedAuthenticationManager; /** * Service that builds up the undertow metadata. * * @author Stuart Douglas */ public class UndertowDeploymentInfoService implements Service<DeploymentInfo> { public static final ServiceName SERVICE_NAME = ServiceName.of("UndertowDeploymentInfoService"); public static final String DEFAULT_SERVLET_NAME = "default"; public static final String OLD_URI_PREFIX = "http://java.sun.com"; public static final String NEW_URI_PREFIX = "http://xmlns.jcp.org"; public static final String UNDERTOW = "undertow"; private DeploymentInfo deploymentInfo; private Registration registration; private final JBossWebMetaData mergedMetaData; private final String deploymentName; private final TldsMetaData tldsMetaData; private final List<TldMetaData> sharedTlds; private final Module module; private final ScisMetaData scisMetaData; private final VirtualFile deploymentRoot; private final String jaccContextId; private final String securityDomain; private final List<ServletContextAttribute> attributes; private final String contextPath; private final List<SetupAction> setupActions; private final Set<VirtualFile> overlays; private final List<ExpressionFactoryWrapper> expressionFactoryWrappers; private final List<PredicatedHandler> predicatedHandlers; private final List<HandlerWrapper> initialHandlerChainWrappers; private final List<HandlerWrapper> innerHandlerChainWrappers; private final List<HandlerWrapper> outerHandlerChainWrappers; private final List<ThreadSetupHandler> threadSetupActions; private final List<ServletExtension> servletExtensions; private final SharedSessionManagerConfig sharedSessionManagerConfig; private final boolean explodedDeployment; private final InjectedValue<UndertowService> undertowService = new InjectedValue<>(); private final InjectedValue<SessionManagerFactory> sessionManagerFactory = new InjectedValue<>(); private final InjectedValue<SessionIdentifierCodec> sessionIdentifierCodec = new InjectedValue<>(); private final InjectedValue<SecurityDomainContext> securityDomainContextValue = new InjectedValue<SecurityDomainContext>(); private final InjectedValue<ServletContainerService> container = new InjectedValue<>(); private final InjectedValue<ComponentRegistry> componentRegistryInjectedValue = new InjectedValue<>(); private final InjectedValue<Host> host = new InjectedValue<>(); private final InjectedValue<ControlPoint> controlPointInjectedValue = new InjectedValue<>(); private final InjectedValue<SuspendController> suspendControllerInjectedValue = new InjectedValue<>(); private final InjectedValue<ServerEnvironment> serverEnvironmentInjectedValue = new InjectedValue<>(); private final Map<String, InjectedValue<Executor>> executorsByName = new HashMap<String, InjectedValue<Executor>>(); private final WebSocketDeploymentInfo webSocketDeploymentInfo; private final File tempDir; private final List<File> externalResources; private final InjectedValue<Function> securityFunction = new InjectedValue<>(); private final List<Predicate> allowSuspendedRequests; private UndertowDeploymentInfoService(final JBossWebMetaData mergedMetaData, final String deploymentName, final TldsMetaData tldsMetaData, final List<TldMetaData> sharedTlds, final Module module, final ScisMetaData scisMetaData, final VirtualFile deploymentRoot, final String jaccContextId, final String securityDomain, final List<ServletContextAttribute> attributes, final String contextPath, final List<SetupAction> setupActions, final Set<VirtualFile> overlays, final List<ExpressionFactoryWrapper> expressionFactoryWrappers, List<PredicatedHandler> predicatedHandlers, List<HandlerWrapper> initialHandlerChainWrappers, List<HandlerWrapper> innerHandlerChainWrappers, List<HandlerWrapper> outerHandlerChainWrappers, List<ThreadSetupHandler> threadSetupActions, boolean explodedDeployment, List<ServletExtension> servletExtensions, SharedSessionManagerConfig sharedSessionManagerConfig, WebSocketDeploymentInfo webSocketDeploymentInfo, File tempDir, List<File> externalResources, List<Predicate> allowSuspendedRequests) { this.mergedMetaData = mergedMetaData; this.deploymentName = deploymentName; this.tldsMetaData = tldsMetaData; this.sharedTlds = sharedTlds; this.module = module; this.scisMetaData = scisMetaData; this.deploymentRoot = deploymentRoot; this.jaccContextId = jaccContextId; this.securityDomain = securityDomain; this.attributes = attributes; this.contextPath = contextPath; this.setupActions = setupActions; this.overlays = overlays; this.expressionFactoryWrappers = expressionFactoryWrappers; this.predicatedHandlers = predicatedHandlers; this.initialHandlerChainWrappers = initialHandlerChainWrappers; this.innerHandlerChainWrappers = innerHandlerChainWrappers; this.outerHandlerChainWrappers = outerHandlerChainWrappers; this.threadSetupActions = threadSetupActions; this.explodedDeployment = explodedDeployment; this.servletExtensions = servletExtensions; this.sharedSessionManagerConfig = sharedSessionManagerConfig; this.webSocketDeploymentInfo = webSocketDeploymentInfo; this.tempDir = tempDir; this.externalResources = externalResources; this.allowSuspendedRequests = allowSuspendedRequests; } @Override public synchronized void start(final StartContext startContext) throws StartException { ClassLoader oldTccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(module.getClassLoader()); DeploymentInfo deploymentInfo = createServletConfig(); deploymentInfo.setConfidentialPortManager(getConfidentialPortManager()); handleDistributable(deploymentInfo); if (securityFunction.getOptionalValue() == null) { handleIdentityManager(deploymentInfo); handleJASPIMechanism(deploymentInfo); handleJACCAuthorization(deploymentInfo); handleAuthManagerLogout(deploymentInfo, mergedMetaData); if(mergedMetaData.isUseJBossAuthorization()) { deploymentInfo.setAuthorizationManager(new JbossAuthorizationManager(deploymentInfo.getAuthorizationManager())); } } handleAdditionalAuthenticationMechanisms(deploymentInfo); SessionConfigMetaData sessionConfig = mergedMetaData.getSessionConfig(); if(sharedSessionManagerConfig != null && sharedSessionManagerConfig.getSessionConfig() != null) { sessionConfig = sharedSessionManagerConfig.getSessionConfig(); } ServletSessionConfig config = null; //default session config SessionCookieConfig defaultSessionConfig = container.getValue().getSessionCookieConfig(); if (defaultSessionConfig != null) { config = new ServletSessionConfig(); if (defaultSessionConfig.getName() != null) { config.setName(defaultSessionConfig.getName()); } if (defaultSessionConfig.getDomain() != null) { config.setDomain(defaultSessionConfig.getDomain()); } if (defaultSessionConfig.getHttpOnly() != null) { config.setHttpOnly(defaultSessionConfig.getHttpOnly()); } if (defaultSessionConfig.getSecure() != null) { config.setSecure(defaultSessionConfig.getSecure()); } if (defaultSessionConfig.getMaxAge() != null) { config.setMaxAge(defaultSessionConfig.getMaxAge()); } if (defaultSessionConfig.getComment() != null) { config.setComment(defaultSessionConfig.getComment()); } } SecureRandomSessionIdGenerator sessionIdGenerator = new SecureRandomSessionIdGenerator(); sessionIdGenerator.setLength(container.getValue().getSessionIdLength()); deploymentInfo.setSessionIdGenerator(sessionIdGenerator); boolean sessionTimeoutSet = false; if (sessionConfig != null) { if (sessionConfig.getSessionTimeoutSet()) { deploymentInfo.setDefaultSessionTimeout(sessionConfig.getSessionTimeout() * 60); sessionTimeoutSet = true; } CookieConfigMetaData cookieConfig = sessionConfig.getCookieConfig(); if (config == null) { config = new ServletSessionConfig(); } if (cookieConfig != null) { if (cookieConfig.getName() != null) { config.setName(cookieConfig.getName()); } if (cookieConfig.getDomain() != null) { config.setDomain(cookieConfig.getDomain()); } if (cookieConfig.getComment() != null) { config.setComment(cookieConfig.getComment()); } config.setSecure(cookieConfig.getSecure()); config.setPath(cookieConfig.getPath()); config.setMaxAge(cookieConfig.getMaxAge()); config.setHttpOnly(cookieConfig.getHttpOnly()); } List<SessionTrackingModeType> modes = sessionConfig.getSessionTrackingModes(); if (modes != null && !modes.isEmpty()) { final Set<SessionTrackingMode> trackingModes = new HashSet<>(); for (SessionTrackingModeType mode : modes) { switch (mode) { case COOKIE: trackingModes.add(SessionTrackingMode.COOKIE); break; case SSL: trackingModes.add(SessionTrackingMode.SSL); break; case URL: trackingModes.add(SessionTrackingMode.URL); break; } } config.setSessionTrackingModes(trackingModes); } } if(!sessionTimeoutSet) { deploymentInfo.setDefaultSessionTimeout(container.getValue().getDefaultSessionTimeout() * 60); } if (config != null) { deploymentInfo.setServletSessionConfig(config); } for (final SetupAction action : setupActions) { deploymentInfo.addThreadSetupAction(new UndertowThreadSetupAction(action)); } if (initialHandlerChainWrappers != null) { for (HandlerWrapper handlerWrapper : initialHandlerChainWrappers) { deploymentInfo.addInitialHandlerChainWrapper(handlerWrapper); } } if (innerHandlerChainWrappers != null) { for (HandlerWrapper handlerWrapper : innerHandlerChainWrappers) { deploymentInfo.addInnerHandlerChainWrapper(handlerWrapper); } } if (outerHandlerChainWrappers != null) { for (HandlerWrapper handlerWrapper : outerHandlerChainWrappers) { deploymentInfo.addOuterHandlerChainWrapper(handlerWrapper); } } if (threadSetupActions != null) { for (ThreadSetupHandler threadSetupAction : threadSetupActions) { deploymentInfo.addThreadSetupAction(threadSetupAction); } } deploymentInfo.setServerName(serverEnvironmentInjectedValue.getValue().getProductConfig().getPrettyVersionString()); if (undertowService.getValue().isStatisticsEnabled()) { deploymentInfo.setMetricsCollector(new UndertowMetricsCollector()); } ControlPoint controlPoint = controlPointInjectedValue.getOptionalValue(); if (controlPoint != null) { deploymentInfo.addOuterHandlerChainWrapper(GlobalRequestControllerHandler.wrapper(controlPoint, allowSuspendedRequests)); } container.getValue().getAuthenticationMechanisms().entrySet().forEach(e -> deploymentInfo.addAuthenticationMechanism(e.getKey(), e.getValue())); deploymentInfo.setUseCachedAuthenticationMechanism(!deploymentInfo.getAuthenticationMechanisms().containsKey(SingleSignOnService.AUTHENTICATION_MECHANISM_NAME)); this.deploymentInfo = deploymentInfo; } finally { Thread.currentThread().setContextClassLoader(oldTccl); } } private void handleAuthManagerLogout(DeploymentInfo deploymentInfo, JBossWebMetaData mergedMetaData) { if(securityDomain == null) { return; } AuthenticationManager manager = securityDomainContextValue.getValue().getAuthenticationManager(); deploymentInfo.addNotificationReceiver(new LogoutNotificationReceiver(manager, securityDomain)); if(mergedMetaData.isFlushOnSessionInvalidation()) { LogoutSessionListener listener = new LogoutSessionListener(manager); deploymentInfo.addListener(Servlets.listener(LogoutSessionListener.class, new ImmediateInstanceFactory<EventListener>(listener))); } } @Override public synchronized void stop(final StopContext stopContext) { IoUtils.safeClose(this.deploymentInfo.getResourceManager()); if (securityDomain != null && securityFunction.getOptionalValue() == null) { AuthenticationManager authManager = securityDomainContextValue.getValue().getAuthenticationManager(); if (authManager != null && authManager instanceof JBossCachedAuthenticationManager) { ((JBossCachedAuthenticationManager) authManager).releaseModuleEntries(module.getClassLoader()); } } this.deploymentInfo.setConfidentialPortManager(null); this.deploymentInfo = null; if (registration != null) { registration.cancel(); } } @Override public synchronized DeploymentInfo getValue() throws IllegalStateException, IllegalArgumentException { return deploymentInfo; } /** * <p>Adds to the deployment the {@link org.wildfly.extension.undertow.security.jaspi.JASPICAuthenticationMechanism}, if necessary. The handler will be added if the security domain * is configured with JASPI authentication.</p> * * @param deploymentInfo */ private void handleJASPIMechanism(final DeploymentInfo deploymentInfo) { if(securityDomain == null) { return; } ApplicationPolicy applicationPolicy = SecurityConfiguration.getApplicationPolicy(this.securityDomain); if (applicationPolicy != null && JASPIAuthenticationInfo.class.isInstance(applicationPolicy.getAuthenticationInfo())) { String authMethod = null; LoginConfig loginConfig = deploymentInfo.getLoginConfig(); if (loginConfig != null && loginConfig.getAuthMethods().size() > 0) { authMethod = loginConfig.getAuthMethods().get(0).getName(); } deploymentInfo.setJaspiAuthenticationMechanism(new JASPICAuthenticationMechanism(securityDomain, authMethod)); deploymentInfo.setSecurityContextFactory(new JASPICSecurityContextFactory(this.securityDomain)); deploymentInfo.addOuterHandlerChainWrapper(next -> new JASPICSecureResponseHandler(next)); } } /** * <p> * Sets the {@link JACCAuthorizationManager} in the specified {@link DeploymentInfo} if the webapp security domain * has defined a JACC authorization module. * </p> * * @param deploymentInfo the {@link DeploymentInfo} instance. */ private void handleJACCAuthorization(final DeploymentInfo deploymentInfo) { if(securityDomain == null) { return; } // TODO make the authorization manager implementation configurable in Undertow or jboss-web.xml ApplicationPolicy applicationPolicy = SecurityConfiguration.getApplicationPolicy(this.securityDomain); if (applicationPolicy != null) { AuthorizationInfo authzInfo = applicationPolicy.getAuthorizationInfo(); if (authzInfo != null) { for (AuthorizationModuleEntry entry : authzInfo.getModuleEntries()) { if (JACCAuthorizationModule.class.getName().equals(entry.getPolicyModuleName())) { deploymentInfo.setAuthorizationManager(new JACCAuthorizationManager()); break; } } } } } private void handleAdditionalAuthenticationMechanisms(final DeploymentInfo deploymentInfo) { for (Map.Entry<String, AuthenticationMechanism> am : host.getValue().getAdditionalAuthenticationMechanisms().entrySet()) { deploymentInfo.addFirstAuthenticationMechanism(am.getKey(), am.getValue()); } } private void handleIdentityManager(final DeploymentInfo deploymentInfo) { if(securityDomain != null) { SecurityDomainContext sdc = securityDomainContextValue.getValue(); deploymentInfo.setIdentityManager(new JAASIdentityManagerImpl(sdc)); AuditManager auditManager = sdc.getAuditManager(); if (auditManager != null && !mergedMetaData.isDisableAudit()) { deploymentInfo.addNotificationReceiver(new AuditNotificationReceiver(auditManager)); } } } private ConfidentialPortManager getConfidentialPortManager() { return new ConfidentialPortManager() { @Override public int getConfidentialPort(HttpServerExchange exchange) { int port = exchange.getConnection().getLocalAddress(InetSocketAddress.class).getPort(); if (port<0){ UndertowLogger.ROOT_LOGGER.debugf("Confidential port not defined for port %s", port); } return host.getValue().getServer().getValue().lookupSecurePort(port); } }; } private void handleDistributable(final DeploymentInfo deploymentInfo) { SessionManagerFactory managerFactory = this.sessionManagerFactory.getOptionalValue(); if (managerFactory != null) { deploymentInfo.setSessionManagerFactory(managerFactory); } SessionIdentifierCodec codec = this.sessionIdentifierCodec.getOptionalValue(); if (codec != null) { deploymentInfo.setSessionConfigWrapper(new CodecSessionConfigWrapper(codec)); } } /* This is to address WFLY-1894 but should probably be moved to some other place. */ private String resolveContextPath() { if (deploymentName.equals(host.getValue().getDefaultWebModule())) { return "/"; } else { return contextPath; } } private DeploymentInfo createServletConfig() throws StartException { final ComponentRegistry componentRegistry = componentRegistryInjectedValue.getValue(); try { if (!mergedMetaData.isMetadataComplete()) { mergedMetaData.resolveAnnotations(); } mergedMetaData.resolveRunAs(); final DeploymentInfo d = new DeploymentInfo(); d.setContextPath(resolveContextPath()); if (mergedMetaData.getDescriptionGroup() != null) { d.setDisplayName(mergedMetaData.getDescriptionGroup().getDisplayName()); } d.setDeploymentName(deploymentName); d.setHostName(host.getValue().getName()); final ServletContainerService servletContainer = container.getValue(); try { //TODO: make the caching limits configurable List<String> externalOverlays = mergedMetaData.getOverlays(); ResourceManager resourceManager = new ServletResourceManager(deploymentRoot, overlays, explodedDeployment, mergedMetaData.isSymbolicLinkingEnabled(), servletContainer.isDisableFileWatchService(), externalOverlays); resourceManager = new CachingResourceManager(100, 10 * 1024 * 1024, servletContainer.getBufferCache(), resourceManager, explodedDeployment ? 2000 : -1); if(externalResources != null && !externalResources.isEmpty()) { //TODO: we don't cache external deployments, as they are intended for development use //should be make this configurable or something? List<ResourceManager> delegates = new ArrayList<>(); for(File resource : externalResources) { delegates.add(new FileResourceManager(resource.getCanonicalFile(), 1024, true, mergedMetaData.isSymbolicLinkingEnabled(), "/")); } delegates.add(resourceManager); resourceManager = new DelegatingResourceManager(delegates); } d.setResourceManager(resourceManager); } catch (IOException e) { throw new StartException(e); } d.setTempDir(tempDir); d.setClassLoader(module.getClassLoader()); final String servletVersion = mergedMetaData.getServletVersion(); if (servletVersion != null) { d.setMajorVersion(Integer.parseInt(servletVersion.charAt(0) + "")); d.setMinorVersion(Integer.parseInt(servletVersion.charAt(2) + "")); } else { d.setMajorVersion(3); d.setMinorVersion(1); } //in most cases flush just hurts performance for no good reason d.setIgnoreFlush(servletContainer.isIgnoreFlush()); //controls initialization of filters on start of application d.setEagerFilterInit(servletContainer.isEagerFilterInit()); d.setAllowNonStandardWrappers(servletContainer.isAllowNonStandardWrappers()); d.setServletStackTraces(servletContainer.getStackTraces()); d.setDisableCachingForSecuredPages(servletContainer.isDisableCachingForSecuredPages()); if (servletContainer.getSessionPersistenceManager() != null) { d.setSessionPersistenceManager(servletContainer.getSessionPersistenceManager()); } //for 2.2 apps we do not require a leading / in path mappings boolean is22OrOlder; if (d.getMajorVersion() == 1) { is22OrOlder = true; } else if (d.getMajorVersion() == 2) { is22OrOlder = d.getMinorVersion() < 3; } else { is22OrOlder = false; } JSPConfig jspConfig = servletContainer.getJspConfig(); final Set<String> seenMappings = new HashSet<>(); HashMap<String, TagLibraryInfo> tldInfo = createTldsInfo(tldsMetaData, sharedTlds); //default JSP servlet final ServletInfo jspServlet = jspConfig != null ? jspConfig.createJSPServletInfo() : null; if (jspServlet != null) { //this would be null if jsp support is disabled HashMap<String, JspPropertyGroup> propertyGroups = createJspConfig(mergedMetaData); JspServletBuilder.setupDeployment(d, propertyGroups, tldInfo, new UndertowJSPInstanceManager(new WebInjectionContainer(module.getClassLoader(), componentRegistryInjectedValue.getValue()))); if (mergedMetaData.getJspConfig() != null) { Collection<JspPropertyGroup> values = new LinkedHashSet<>(propertyGroups.values()); d.setJspConfigDescriptor(new JspConfigDescriptorImpl(tldInfo.values(), values)); } d.addServlet(jspServlet); final Set<String> jspPropertyGroupMappings = propertyGroups.keySet(); for (final String mapping : jspPropertyGroupMappings) { if(!jspServlet.getMappings().contains(mapping)) { jspServlet.addMapping(mapping); } } seenMappings.addAll(jspPropertyGroupMappings); //setup JSP application context initializing listener d.addListener(new ListenerInfo(JspInitializationListener.class)); d.addServletContextAttribute(JspInitializationListener.CONTEXT_KEY, expressionFactoryWrappers); } d.setClassIntrospecter(new ComponentClassIntrospector(componentRegistry)); final Map<String, List<ServletMappingMetaData>> servletMappings = new HashMap<>(); if (mergedMetaData.getExecutorName() != null) { d.setExecutor(executorsByName.get(mergedMetaData.getExecutorName()).getValue()); } Boolean proactiveAuthentication = mergedMetaData.getProactiveAuthentication(); if(proactiveAuthentication == null) { proactiveAuthentication = container.getValue().isProactiveAuth(); } d.setAuthenticationMode(proactiveAuthentication ? AuthenticationMode.PRO_ACTIVE : AuthenticationMode.CONSTRAINT_DRIVEN); if (servletExtensions != null) { for (ServletExtension extension : servletExtensions) { d.addServletExtension(extension); } } if (mergedMetaData.getServletMappings() != null) { for (final ServletMappingMetaData mapping : mergedMetaData.getServletMappings()) { List<ServletMappingMetaData> list = servletMappings.get(mapping.getServletName()); if (list == null) { servletMappings.put(mapping.getServletName(), list = new ArrayList<>()); } list.add(mapping); } } if (jspServlet != null) { jspServlet.addHandlerChainWrapper(JspFileHandler.jspFileHandlerWrapper(null)); // we need to clear the file attribute if it is set (WFLY-4106) List<ServletMappingMetaData> list = servletMappings.get(jspServlet.getName()); if(list != null && ! list.isEmpty()) { for (final ServletMappingMetaData mapping : list) { for(String urlPattern : mapping.getUrlPatterns()) { jspServlet.addMapping(urlPattern); } seenMappings.addAll(mapping.getUrlPatterns()); } } } final List<JBossServletMetaData> servlets = new ArrayList<JBossServletMetaData>(); for (JBossServletMetaData servlet : mergedMetaData.getServlets()) { servlets.add(servlet); } for (final JBossServletMetaData servlet : mergedMetaData.getServlets()) { final ServletInfo s; if (servlet.getJspFile() != null) { s = new ServletInfo(servlet.getName(), JspServlet.class); s.addHandlerChainWrapper(JspFileHandler.jspFileHandlerWrapper(servlet.getJspFile())); } else { if (servlet.getServletClass() == null) { if(DEFAULT_SERVLET_NAME.equals(servlet.getName())) { s = new ServletInfo(servlet.getName(), DefaultServlet.class); } else { throw UndertowLogger.ROOT_LOGGER.servletClassNotDefined(servlet.getServletName()); } } else { Class<? extends Servlet> servletClass = (Class<? extends Servlet>) module.getClassLoader().loadClass(servlet.getServletClass()); ManagedReferenceFactory creator = componentRegistry.createInstanceFactory(servletClass); if (creator != null) { InstanceFactory<Servlet> factory = createInstanceFactory(creator); s = new ServletInfo(servlet.getName(), servletClass, factory); } else { s = new ServletInfo(servlet.getName(), servletClass); } } } s.setAsyncSupported(servlet.isAsyncSupported()) .setJspFile(servlet.getJspFile()) .setEnabled(servlet.isEnabled()); if (servlet.getRunAs() != null) { s.setRunAs(servlet.getRunAs().getRoleName()); } if (servlet.getLoadOnStartupSet()) {//todo why not cleanup api and just use int everywhere s.setLoadOnStartup(servlet.getLoadOnStartupInt()); } if (servlet.getExecutorName() != null) { s.setExecutor(executorsByName.get(servlet.getExecutorName()).getValue()); } handleServletMappings(is22OrOlder, seenMappings, servletMappings, s); if (servlet.getInitParam() != null) { for (ParamValueMetaData initParam : servlet.getInitParam()) { if (!s.getInitParams().containsKey(initParam.getParamName())) { s.addInitParam(initParam.getParamName(), initParam.getParamValue()); } } } if (servlet.getServletSecurity() != null) { ServletSecurityInfo securityInfo = new ServletSecurityInfo(); s.setServletSecurityInfo(securityInfo); securityInfo.setEmptyRoleSemantic(servlet.getServletSecurity().getEmptyRoleSemantic() == EmptyRoleSemanticType.DENY ? DENY : PERMIT) .setTransportGuaranteeType(transportGuaranteeType(servlet.getServletSecurity().getTransportGuarantee())) .addRolesAllowed(servlet.getServletSecurity().getRolesAllowed()); if (servlet.getServletSecurity().getHttpMethodConstraints() != null) { for (HttpMethodConstraintMetaData method : servlet.getServletSecurity().getHttpMethodConstraints()) { securityInfo.addHttpMethodSecurityInfo( new HttpMethodSecurityInfo() .setEmptyRoleSemantic(method.getEmptyRoleSemantic() == EmptyRoleSemanticType.DENY ? DENY : PERMIT) .setTransportGuaranteeType(transportGuaranteeType(method.getTransportGuarantee())) .addRolesAllowed(method.getRolesAllowed()) .setMethod(method.getMethod())); } } } if (servlet.getSecurityRoleRefs() != null) { for (final SecurityRoleRefMetaData ref : servlet.getSecurityRoleRefs()) { s.addSecurityRoleRef(ref.getRoleName(), ref.getRoleLink()); } } if (servlet.getMultipartConfig() != null) { MultipartConfigMetaData mp = servlet.getMultipartConfig(); s.setMultipartConfig(Servlets.multipartConfig(mp.getLocation(), mp.getMaxFileSize(), mp.getMaxRequestSize(), mp.getFileSizeThreshold())); } d.addServlet(s); } if(jspServlet != null) { if(!seenMappings.contains("*.jsp")) { jspServlet.addMapping("*.jsp"); } if(!seenMappings.contains("*.jspx")) { jspServlet.addMapping("*.jspx"); } } //we explicitly add the default servlet, to allow it to be mapped if (!mergedMetaData.getServlets().containsKey(ServletPathMatches.DEFAULT_SERVLET_NAME)) { ServletInfo defaultServlet = Servlets.servlet(DEFAULT_SERVLET_NAME, DefaultServlet.class); handleServletMappings(is22OrOlder, seenMappings, servletMappings, defaultServlet); d.addServlet(defaultServlet); } if(servletContainer.getDirectoryListingEnabled() != null) { ServletInfo defaultServlet = d.getServlets().get(DEFAULT_SERVLET_NAME); defaultServlet.addInitParam(DefaultServlet.DIRECTORY_LISTING, servletContainer.getDirectoryListingEnabled().toString()); } if (mergedMetaData.getFilters() != null) { for (final FilterMetaData filter : mergedMetaData.getFilters()) { Class<? extends Filter> filterClass = (Class<? extends Filter>) module.getClassLoader().loadClass(filter.getFilterClass()); ManagedReferenceFactory creator = componentRegistry.createInstanceFactory(filterClass); FilterInfo f; if (creator != null) { InstanceFactory<Filter> instanceFactory = createInstanceFactory(creator); f = new FilterInfo(filter.getName(), filterClass, instanceFactory); } else { f = new FilterInfo(filter.getName(), filterClass); } f.setAsyncSupported(filter.isAsyncSupported()); d.addFilter(f); if (filter.getInitParam() != null) { for (ParamValueMetaData initParam : filter.getInitParam()) { f.addInitParam(initParam.getParamName(), initParam.getParamValue()); } } } } if (mergedMetaData.getFilterMappings() != null) { for (final FilterMappingMetaData mapping : mergedMetaData.getFilterMappings()) { if (mapping.getUrlPatterns() != null) { for (String url : mapping.getUrlPatterns()) { if (is22OrOlder && !url.startsWith("*") && !url.startsWith("/")) { url = "/" + url; } if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) { for (DispatcherType dispatcher : mapping.getDispatchers()) { d.addFilterUrlMapping(mapping.getFilterName(), url, javax.servlet.DispatcherType.valueOf(dispatcher.name())); } } else { d.addFilterUrlMapping(mapping.getFilterName(), url, javax.servlet.DispatcherType.REQUEST); } } } if (mapping.getServletNames() != null) { for (String servletName : mapping.getServletNames()) { if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) { for (DispatcherType dispatcher : mapping.getDispatchers()) { d.addFilterServletNameMapping(mapping.getFilterName(), servletName, javax.servlet.DispatcherType.valueOf(dispatcher.name())); } } else { d.addFilterServletNameMapping(mapping.getFilterName(), servletName, javax.servlet.DispatcherType.REQUEST); } } } } } if (scisMetaData != null && scisMetaData.getHandlesTypes() != null) { for (final ServletContainerInitializer sci : scisMetaData.getScis()) { final ImmediateInstanceFactory<ServletContainerInitializer> instanceFactory = new ImmediateInstanceFactory<>(sci); d.addServletContainerInitalizer(new ServletContainerInitializerInfo(sci.getClass(), instanceFactory, scisMetaData.getHandlesTypes().get(sci))); } } if (mergedMetaData.getListeners() != null) { for (ListenerMetaData listener : mergedMetaData.getListeners()) { addListener(module.getClassLoader(), componentRegistry, d, listener); } } if (mergedMetaData.getContextParams() != null) { for (ParamValueMetaData param : mergedMetaData.getContextParams()) { d.addInitParameter(param.getParamName(), param.getParamValue()); } } if (mergedMetaData.getWelcomeFileList() != null && mergedMetaData.getWelcomeFileList().getWelcomeFiles() != null) { List<String> welcomeFiles = mergedMetaData.getWelcomeFileList().getWelcomeFiles(); for (String file : welcomeFiles) { if (file.startsWith("/")) { d.addWelcomePages(file.substring(1)); } else { d.addWelcomePages(file); } } } else { d.addWelcomePages("index.html", "index.htm", "index.jsp"); } d.addWelcomePages(servletContainer.getWelcomeFiles()); if (mergedMetaData.getErrorPages() != null) { for (final ErrorPageMetaData page : mergedMetaData.getErrorPages()) { final ErrorPage errorPage; if (page.getExceptionType() != null && !page.getExceptionType().isEmpty()) { errorPage = new ErrorPage(page.getLocation(), (Class<? extends Throwable>) module.getClassLoader().loadClass(page.getExceptionType())); } else if (page.getErrorCode() != null && !page.getErrorCode().isEmpty()) { errorPage = new ErrorPage(page.getLocation(), Integer.parseInt(page.getErrorCode())); } else { errorPage = new ErrorPage(page.getLocation()); } d.addErrorPages(errorPage); } } for(Map.Entry<String, String> entry : servletContainer.getMimeMappings().entrySet()) { d.addMimeMapping(new MimeMapping(entry.getKey(), entry.getValue())); } if (mergedMetaData.getMimeMappings() != null) { for (final MimeMappingMetaData mapping : mergedMetaData.getMimeMappings()) { d.addMimeMapping(new MimeMapping(mapping.getExtension(), mapping.getMimeType())); } } d.setDenyUncoveredHttpMethods(mergedMetaData.getDenyUncoveredHttpMethods() != null); Set<String> securityRoleNames = mergedMetaData.getSecurityRoleNames(); if (mergedMetaData.getSecurityConstraints() != null) { for (SecurityConstraintMetaData constraint : mergedMetaData.getSecurityConstraints()) { SecurityConstraint securityConstraint = new SecurityConstraint() .setTransportGuaranteeType(transportGuaranteeType(constraint.getTransportGuarantee())); List<String> roleNames = constraint.getRoleNames(); if (constraint.getAuthConstraint() == null) { // no auth constraint means we permit the empty roles securityConstraint.setEmptyRoleSemantic(PERMIT); } else if (roleNames.size() == 1 && roleNames.contains("*") && securityRoleNames.contains("*")) { // AS7-6932 - Trying to do a * to * mapping which JBossWeb passed through, for Undertow enable // authentication only mode. // TODO - AS7-6933 - Revisit workaround added to allow switching between JBoss Web and Undertow. securityConstraint.setEmptyRoleSemantic(AUTHENTICATE); } else { securityConstraint.addRolesAllowed(roleNames); } if (constraint.getResourceCollections() != null) { for (final WebResourceCollectionMetaData resourceCollection : constraint.getResourceCollections()) { securityConstraint.addWebResourceCollection(new WebResourceCollection() .addHttpMethods(resourceCollection.getHttpMethods()) .addHttpMethodOmissions(resourceCollection.getHttpMethodOmissions()) .addUrlPatterns(resourceCollection.getUrlPatterns())); } } d.addSecurityConstraint(securityConstraint); } } final LoginConfigMetaData loginConfig = mergedMetaData.getLoginConfig(); if (loginConfig != null) { List<AuthMethodConfig> authMethod = authMethod(loginConfig.getAuthMethod()); if (loginConfig.getFormLoginConfig() != null) { d.setLoginConfig(new LoginConfig(loginConfig.getRealmName(), loginConfig.getFormLoginConfig().getLoginPage(), loginConfig.getFormLoginConfig().getErrorPage())); } else { d.setLoginConfig(new LoginConfig(loginConfig.getRealmName())); } for (AuthMethodConfig method : authMethod) { d.getLoginConfig().addLastAuthMethod(method); } } d.addSecurityRoles(mergedMetaData.getSecurityRoleNames()); Map<String, Set<String>> principalVersusRolesMap = mergedMetaData.getPrincipalVersusRolesMap(); Function<DeploymentInfo, Registration> securityFunction = this.securityFunction.getOptionalValue(); if (securityFunction != null) { registration = securityFunction.apply(d); d.addOuterHandlerChainWrapper(JACCContextIdHandler.wrapper(jaccContextId)); if(mergedMetaData.isUseJBossAuthorization()) { UndertowLogger.ROOT_LOGGER.configurationOptionIgnoredWhenUsingElytron("use-jboss-authorization"); } } else { if (securityDomain != null) { d.addThreadSetupAction(new SecurityContextThreadSetupAction(securityDomain, securityDomainContextValue.getValue(), principalVersusRolesMap)); d.addInnerHandlerChainWrapper(SecurityContextAssociationHandler.wrapper(mergedMetaData.getRunAsIdentity())); d.addOuterHandlerChainWrapper(JACCContextIdHandler.wrapper(jaccContextId)); d.addLifecycleInterceptor(new RunAsLifecycleInterceptor(mergedMetaData.getRunAsIdentity())); } } if (principalVersusRolesMap != null) { for (Map.Entry<String, Set<String>> entry : principalVersusRolesMap.entrySet()) { d.addPrincipalVsRoleMappings(entry.getKey(), entry.getValue()); } } // Setup an deployer configured ServletContext attributes if(attributes != null) { for (ServletContextAttribute attribute : attributes) { d.addServletContextAttribute(attribute.getName(), attribute.getValue()); } } //now setup websockets if they are enabled if(servletContainer.isWebsocketsEnabled() && webSocketDeploymentInfo != null) { webSocketDeploymentInfo.setBuffers(servletContainer.getWebsocketsBufferPool().getValue()); webSocketDeploymentInfo.setWorker(servletContainer.getWebsocketsWorker().getValue()); webSocketDeploymentInfo.setDispatchToWorkerThread(servletContainer.isDispatchWebsocketInvocationToWorker()); if(servletContainer.isPerMessageDeflate()) { PerMessageDeflateHandshake perMessageDeflate = new PerMessageDeflateHandshake(false, servletContainer.getDeflaterLevel()); webSocketDeploymentInfo.addExtension(perMessageDeflate); } final AtomicReference<ServerActivity> serverActivity = new AtomicReference<>(); webSocketDeploymentInfo.addListener(wsc -> { serverActivity.set(new ServerActivity() { @Override public void preSuspend(ServerActivityCallback listener) { listener.done(); } @Override public void suspended(final ServerActivityCallback listener) { if(wsc.getConfiguredServerEndpoints().isEmpty()) { //TODO: remove this once undertow bug fix is upstream listener.done(); return; } wsc.pause(new ServerWebSocketContainer.PauseListener() { @Override public void paused() { listener.done(); } @Override public void resumed() { } }); } @Override public void resume() { wsc.resume(); } }); suspendControllerInjectedValue.getValue().registerActivity(serverActivity.get()); }); ServletContextListener sl = new ServletContextListener() { @Override public void contextInitialized(ServletContextEvent sce) {} @Override public void contextDestroyed(ServletContextEvent sce) { final ServerActivity activity = serverActivity.get(); if(activity != null) { suspendControllerInjectedValue.getValue().unRegisterActivity(activity); } } }; d.addListener(new ListenerInfo(sl.getClass(), new ImmediateInstanceFactory<EventListener>(sl))); d.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSocketDeploymentInfo); } if (mergedMetaData.getLocalEncodings() != null && mergedMetaData.getLocalEncodings().getMappings() != null) { for (LocaleEncodingMetaData locale : mergedMetaData.getLocalEncodings().getMappings()) { d.addLocaleCharsetMapping(locale.getLocale(), locale.getEncoding()); } } if (predicatedHandlers != null && !predicatedHandlers.isEmpty()) { d.addOuterHandlerChainWrapper(new RewriteCorrectingHandlerWrappers.PostWrapper()); d.addOuterHandlerChainWrapper(new HandlerWrapper() { @Override public HttpHandler wrap(HttpHandler handler) { if (predicatedHandlers.size() == 1) { PredicatedHandler ph = predicatedHandlers.get(0); return Handlers.predicate(ph.getPredicate(), ph.getHandler().wrap(handler), handler); } else { return Handlers.predicates(predicatedHandlers, handler); } } }); d.addOuterHandlerChainWrapper(new RewriteCorrectingHandlerWrappers.PreWrapper()); } if (mergedMetaData.getDefaultEncoding() != null) { d.setDefaultEncoding(mergedMetaData.getDefaultEncoding()); } else if (servletContainer.getDefaultEncoding() != null) { d.setDefaultEncoding(servletContainer.getDefaultEncoding()); } d.setCrawlerSessionManagerConfig(servletContainer.getCrawlerSessionManagerConfig()); return d; } catch (ClassNotFoundException e) { throw new StartException(e); } } private void handleServletMappings(boolean is22OrOlder, Set<String> seenMappings, Map<String, List<ServletMappingMetaData>> servletMappings, ServletInfo s) { List<ServletMappingMetaData> mappings = servletMappings.get(s.getName()); if (mappings != null) { for (ServletMappingMetaData mapping : mappings) { for (String pattern : mapping.getUrlPatterns()) { if (is22OrOlder && !pattern.startsWith("*") && !pattern.startsWith("/")) { pattern = "/" + pattern; } if (!seenMappings.contains(pattern)) { s.addMapping(pattern); seenMappings.add(pattern); } } } } } /** * Convert the authentication method name from the format specified in the web.xml to the format used by * {@link javax.servlet.http.HttpServletRequest}. * <p/> * If the auth method is not recognised then it is returned as-is. * * @return The converted auth method. * @throws NullPointerException if no configuredMethod is supplied. */ private static List<AuthMethodConfig> authMethod(String configuredMethod) { if (configuredMethod == null) { return Collections.singletonList(new AuthMethodConfig(HttpServletRequest.BASIC_AUTH)); } return AuthMethodParser.parse(configuredMethod, Collections.singletonMap("CLIENT-CERT", HttpServletRequest.CLIENT_CERT_AUTH)); } private static io.undertow.servlet.api.TransportGuaranteeType transportGuaranteeType(final TransportGuaranteeType type) { if (type == null) { return io.undertow.servlet.api.TransportGuaranteeType.NONE; } switch (type) { case CONFIDENTIAL: return io.undertow.servlet.api.TransportGuaranteeType.CONFIDENTIAL; case INTEGRAL: return io.undertow.servlet.api.TransportGuaranteeType.INTEGRAL; case NONE: return io.undertow.servlet.api.TransportGuaranteeType.NONE; } throw new RuntimeException("UNREACHABLE"); } private static HashMap<String, JspPropertyGroup> createJspConfig(JBossWebMetaData metaData) { final HashMap<String, JspPropertyGroup> result = new HashMap<>(); // JSP Config JspConfigMetaData config = metaData.getJspConfig(); if (config != null) { // JSP Property groups List<JspPropertyGroupMetaData> groups = config.getPropertyGroups(); if (groups != null) { for (JspPropertyGroupMetaData group : groups) { org.apache.jasper.deploy.JspPropertyGroup jspPropertyGroup = new org.apache.jasper.deploy.JspPropertyGroup(); for (String pattern : group.getUrlPatterns()) { jspPropertyGroup.addUrlPattern(pattern); } jspPropertyGroup.setElIgnored(group.getElIgnored()); jspPropertyGroup.setPageEncoding(group.getPageEncoding()); jspPropertyGroup.setScriptingInvalid(group.getScriptingInvalid()); jspPropertyGroup.setIsXml(group.getIsXml()); if (group.getIncludePreludes() != null) { for (String includePrelude : group.getIncludePreludes()) { jspPropertyGroup.addIncludePrelude(includePrelude); } } if (group.getIncludeCodas() != null) { for (String includeCoda : group.getIncludeCodas()) { jspPropertyGroup.addIncludeCoda(includeCoda); } } jspPropertyGroup.setDeferredSyntaxAllowedAsLiteral(group.getDeferredSyntaxAllowedAsLiteral()); jspPropertyGroup.setTrimDirectiveWhitespaces(group.getTrimDirectiveWhitespaces()); jspPropertyGroup.setDefaultContentType(group.getDefaultContentType()); jspPropertyGroup.setBuffer(group.getBuffer()); jspPropertyGroup.setErrorOnUndeclaredNamespace(group.getErrorOnUndeclaredNamespace()); for (String pattern : jspPropertyGroup.getUrlPatterns()) { // Split off the groups to individual mappings result.put(pattern, jspPropertyGroup); } } } } //it looks like jasper needs these in order of least specified to most specific final LinkedHashMap<String, JspPropertyGroup> ret = new LinkedHashMap<>(); final ArrayList<String> paths = new ArrayList<>(result.keySet()); Collections.sort(paths, new Comparator<String>() { @Override public int compare(final String o1, final String o2) { return o1.length() - o2.length(); } }); for (String path : paths) { ret.put(path, result.get(path)); } return ret; } private static HashMap<String, TagLibraryInfo> createTldsInfo(final TldsMetaData tldsMetaData, List<TldMetaData> sharedTlds) throws ClassNotFoundException { final HashMap<String, TagLibraryInfo> ret = new HashMap<>(); if (tldsMetaData != null) { if (tldsMetaData.getTlds() != null) { for (Map.Entry<String, TldMetaData> tld : tldsMetaData.getTlds().entrySet()) { createTldInfo(tld.getKey(), tld.getValue(), ret); } } if (sharedTlds != null) { for (TldMetaData metaData : sharedTlds) { createTldInfo(null, metaData, ret); } } } //we also register them under the new namespaces for (String k : new HashSet<>(ret.keySet())) { if (k != null) { if (k.startsWith(OLD_URI_PREFIX)) { String newUri = k.replace(OLD_URI_PREFIX, NEW_URI_PREFIX); ret.put(newUri, ret.get(k)); } } } return ret; } private static TagLibraryInfo createTldInfo(final String location, final TldMetaData tldMetaData, final HashMap<String, TagLibraryInfo> ret) throws ClassNotFoundException { String relativeLocation = location; String jarPath = null; if (relativeLocation != null && relativeLocation.startsWith("/WEB-INF/lib/")) { int pos = relativeLocation.indexOf('/', "/WEB-INF/lib/".length()); if (pos > 0) { jarPath = relativeLocation.substring(pos); if (jarPath.startsWith("/")) { jarPath = jarPath.substring(1); } relativeLocation = relativeLocation.substring(0, pos); } } TagLibraryInfo tagLibraryInfo = new TagLibraryInfo(); tagLibraryInfo.setTlibversion(tldMetaData.getTlibVersion()); if (tldMetaData.getJspVersion() == null) { tagLibraryInfo.setJspversion(tldMetaData.getVersion()); } else { tagLibraryInfo.setJspversion(tldMetaData.getJspVersion()); } tagLibraryInfo.setShortname(tldMetaData.getShortName()); tagLibraryInfo.setUri(tldMetaData.getUri()); if (tldMetaData.getDescriptionGroup() != null) { tagLibraryInfo.setInfo(tldMetaData.getDescriptionGroup().getDescription()); } // Validator if (tldMetaData.getValidator() != null) { TagLibraryValidatorInfo tagLibraryValidatorInfo = new TagLibraryValidatorInfo(); tagLibraryValidatorInfo.setValidatorClass(tldMetaData.getValidator().getValidatorClass()); if (tldMetaData.getValidator().getInitParams() != null) { for (ParamValueMetaData paramValueMetaData : tldMetaData.getValidator().getInitParams()) { tagLibraryValidatorInfo.addInitParam(paramValueMetaData.getParamName(), paramValueMetaData.getParamValue()); } } tagLibraryInfo.setValidator(tagLibraryValidatorInfo); } // Tag if (tldMetaData.getTags() != null) { for (TagMetaData tagMetaData : tldMetaData.getTags()) { TagInfo tagInfo = new TagInfo(); tagInfo.setTagName(tagMetaData.getName()); tagInfo.setTagClassName(tagMetaData.getTagClass()); tagInfo.setTagExtraInfo(tagMetaData.getTeiClass()); if (tagMetaData.getBodyContent() != null) { tagInfo.setBodyContent(tagMetaData.getBodyContent().toString()); } tagInfo.setDynamicAttributes(tagMetaData.getDynamicAttributes()); // Description group if (tagMetaData.getDescriptionGroup() != null) { DescriptionGroupMetaData descriptionGroup = tagMetaData.getDescriptionGroup(); if (descriptionGroup.getIcons() != null && descriptionGroup.getIcons().value() != null && (descriptionGroup.getIcons().value().length > 0)) { Icon icon = descriptionGroup.getIcons().value()[0]; tagInfo.setLargeIcon(icon.largeIcon()); tagInfo.setSmallIcon(icon.smallIcon()); } tagInfo.setInfoString(descriptionGroup.getDescription()); tagInfo.setDisplayName(descriptionGroup.getDisplayName()); } // Variable if (tagMetaData.getVariables() != null) { for (VariableMetaData variableMetaData : tagMetaData.getVariables()) { TagVariableInfo tagVariableInfo = new TagVariableInfo(); tagVariableInfo.setNameGiven(variableMetaData.getNameGiven()); tagVariableInfo.setNameFromAttribute(variableMetaData.getNameFromAttribute()); tagVariableInfo.setClassName(variableMetaData.getVariableClass()); tagVariableInfo.setDeclare(variableMetaData.getDeclare()); if (variableMetaData.getScope() != null) { tagVariableInfo.setScope(variableMetaData.getScope().toString()); } tagInfo.addTagVariableInfo(tagVariableInfo); } } // Attribute if (tagMetaData.getAttributes() != null) { for (AttributeMetaData attributeMetaData : tagMetaData.getAttributes()) { TagAttributeInfo tagAttributeInfo = new TagAttributeInfo(); tagAttributeInfo.setName(attributeMetaData.getName()); tagAttributeInfo.setType(attributeMetaData.getType()); tagAttributeInfo.setReqTime(attributeMetaData.getRtexprvalue()); tagAttributeInfo.setRequired(attributeMetaData.getRequired()); tagAttributeInfo.setFragment(attributeMetaData.getFragment()); if (attributeMetaData.getDeferredValue() != null) { tagAttributeInfo.setDeferredValue("true"); tagAttributeInfo.setExpectedTypeName(attributeMetaData.getDeferredValue().getType()); } else { tagAttributeInfo.setDeferredValue("false"); } if (attributeMetaData.getDeferredMethod() != null) { tagAttributeInfo.setDeferredMethod("true"); tagAttributeInfo.setMethodSignature(attributeMetaData.getDeferredMethod().getMethodSignature()); } else { tagAttributeInfo.setDeferredMethod("false"); } tagInfo.addTagAttributeInfo(tagAttributeInfo); } } tagLibraryInfo.addTagInfo(tagInfo); } } // Tag files if (tldMetaData.getTagFiles() != null) { for (TagFileMetaData tagFileMetaData : tldMetaData.getTagFiles()) { TagFileInfo tagFileInfo = new TagFileInfo(); tagFileInfo.setName(tagFileMetaData.getName()); tagFileInfo.setPath(tagFileMetaData.getPath()); tagLibraryInfo.addTagFileInfo(tagFileInfo); } } // Function if (tldMetaData.getFunctions() != null) { for (FunctionMetaData functionMetaData : tldMetaData.getFunctions()) { FunctionInfo functionInfo = new FunctionInfo(); functionInfo.setName(functionMetaData.getName()); functionInfo.setFunctionClass(functionMetaData.getFunctionClass()); functionInfo.setFunctionSignature(functionMetaData.getFunctionSignature()); tagLibraryInfo.addFunctionInfo(functionInfo); } } if (jarPath == null && relativeLocation == null) { if (!ret.containsKey(tagLibraryInfo.getUri())) { ret.put(tagLibraryInfo.getUri(), tagLibraryInfo); } } else if (jarPath == null) { tagLibraryInfo.setLocation(""); tagLibraryInfo.setPath(relativeLocation); if (!ret.containsKey(tagLibraryInfo.getUri())) { ret.put(tagLibraryInfo.getUri(), tagLibraryInfo); } ret.put(relativeLocation, tagLibraryInfo); } else { tagLibraryInfo.setLocation(relativeLocation); tagLibraryInfo.setPath(jarPath); if (!ret.containsKey(tagLibraryInfo.getUri())) { ret.put(tagLibraryInfo.getUri(), tagLibraryInfo); } if (jarPath.equals("META-INF/taglib.tld")) { ret.put(relativeLocation, tagLibraryInfo); } } return tagLibraryInfo; } private static void addListener(final ClassLoader classLoader, final ComponentRegistry components, final DeploymentInfo d, final ListenerMetaData listener) throws ClassNotFoundException { ListenerInfo l; final Class<? extends EventListener> listenerClass = (Class<? extends EventListener>) classLoader.loadClass(listener.getListenerClass()); ManagedReferenceFactory creator = components.createInstanceFactory(listenerClass); if (creator != null) { InstanceFactory<EventListener> factory = createInstanceFactory(creator); l = new ListenerInfo(listenerClass, factory); } else { l = new ListenerInfo(listenerClass); } d.addListener(l); } private static <T> InstanceFactory<T> createInstanceFactory(final ManagedReferenceFactory creator) { return new InstanceFactory<T>() { @Override public InstanceHandle<T> createInstance() throws InstantiationException { final ManagedReference instance = creator.getReference(); return new InstanceHandle<T>() { @Override public T getInstance() { return (T) instance.getInstance(); } @Override public void release() { instance.release(); } }; } }; } public void addInjectedExecutor(final String name, final InjectedValue<Executor> injected) { executorsByName.put(name, injected); } public InjectedValue<ServletContainerService> getContainer() { return container; } public InjectedValue<SecurityDomainContext> getSecurityDomainContextValue() { return securityDomainContextValue; } public Injector<SessionManagerFactory> getSessionManagerFactoryInjector() { return this.sessionManagerFactory; } public Injector<SessionIdentifierCodec> getSessionIdentifierCodecInjector() { return this.sessionIdentifierCodec; } public InjectedValue<UndertowService> getUndertowService() { return undertowService; } public InjectedValue<ControlPoint> getControlPointInjectedValue() { return controlPointInjectedValue; } public InjectedValue<ComponentRegistry> getComponentRegistryInjectedValue() { return componentRegistryInjectedValue; } public InjectedValue<SuspendController> getSuspendControllerInjectedValue() { return suspendControllerInjectedValue; } public InjectedValue<ServerEnvironment> getServerEnvironmentInjectedValue() { return serverEnvironmentInjectedValue; } public Injector<Function> getSecurityFunctionInjector() { return securityFunction; } public InjectedValue<Host> getHost() { return host; } private static class ComponentClassIntrospector implements ClassIntrospecter { private final ComponentRegistry componentRegistry; public ComponentClassIntrospector(final ComponentRegistry componentRegistry) { this.componentRegistry = componentRegistry; } @Override public <T> InstanceFactory<T> createInstanceFactory(final Class<T> clazz) throws NoSuchMethodException { final ManagedReferenceFactory component = componentRegistry.createInstanceFactory(clazz); return new ManagedReferenceInstanceFactory<>(component); } } private static class ManagedReferenceInstanceFactory<T> implements InstanceFactory<T> { private final ManagedReferenceFactory component; public ManagedReferenceInstanceFactory(final ManagedReferenceFactory component) { this.component = component; } @Override public InstanceHandle<T> createInstance() throws InstantiationException { final ManagedReference reference = component.getReference(); return new InstanceHandle<T>() { @Override public T getInstance() { return (T) reference.getInstance(); } @Override public void release() { reference.release(); } }; } } public static Builder builder() { return new Builder(); } public static class Builder { private JBossWebMetaData mergedMetaData; private String deploymentName; private TldsMetaData tldsMetaData; private List<TldMetaData> sharedTlds; private Module module; private ScisMetaData scisMetaData; private VirtualFile deploymentRoot; private String jaccContextId; private List<ServletContextAttribute> attributes; private String contextPath; private String securityDomain; private List<SetupAction> setupActions; private Set<VirtualFile> overlays; private List<ExpressionFactoryWrapper> expressionFactoryWrappers; private List<PredicatedHandler> predicatedHandlers; private List<HandlerWrapper> initialHandlerChainWrappers; private List<HandlerWrapper> innerHandlerChainWrappers; private List<HandlerWrapper> outerHandlerChainWrappers; private List<ThreadSetupHandler> threadSetupActions; private List<ServletExtension> servletExtensions; private SharedSessionManagerConfig sharedSessionManagerConfig; private boolean explodedDeployment; private WebSocketDeploymentInfo webSocketDeploymentInfo; private File tempDir; private List<File> externalResources; List<Predicate> allowSuspendedRequests; Builder setMergedMetaData(final JBossWebMetaData mergedMetaData) { this.mergedMetaData = mergedMetaData; return this; } public Builder setDeploymentName(final String deploymentName) { this.deploymentName = deploymentName; return this; } public Builder setTldsMetaData(final TldsMetaData tldsMetaData) { this.tldsMetaData = tldsMetaData; return this; } public Builder setSharedTlds(final List<TldMetaData> sharedTlds) { this.sharedTlds = sharedTlds; return this; } public Builder setModule(final Module module) { this.module = module; return this; } public Builder setScisMetaData(final ScisMetaData scisMetaData) { this.scisMetaData = scisMetaData; return this; } public Builder setDeploymentRoot(final VirtualFile deploymentRoot) { this.deploymentRoot = deploymentRoot; return this; } public Builder setJaccContextId(final String jaccContextId) { this.jaccContextId = jaccContextId; return this; } public Builder setAttributes(final List<ServletContextAttribute> attributes) { this.attributes = attributes; return this; } public Builder setContextPath(final String contextPath) { this.contextPath = contextPath; return this; } public Builder setSetupActions(final List<SetupAction> setupActions) { this.setupActions = setupActions; return this; } public Builder setSecurityDomain(final String securityDomain) { this.securityDomain = securityDomain; return this; } public Builder setOverlays(final Set<VirtualFile> overlays) { this.overlays = overlays; return this; } public Builder setExpressionFactoryWrappers(final List<ExpressionFactoryWrapper> expressionFactoryWrappers) { this.expressionFactoryWrappers = expressionFactoryWrappers; return this; } public Builder setPredicatedHandlers(List<PredicatedHandler> predicatedHandlers) { this.predicatedHandlers = predicatedHandlers; return this; } public Builder setInitialHandlerChainWrappers(List<HandlerWrapper> initialHandlerChainWrappers) { this.initialHandlerChainWrappers = initialHandlerChainWrappers; return this; } public Builder setInnerHandlerChainWrappers(List<HandlerWrapper> innerHandlerChainWrappers) { this.innerHandlerChainWrappers = innerHandlerChainWrappers; return this; } public Builder setOuterHandlerChainWrappers(List<HandlerWrapper> outerHandlerChainWrappers) { this.outerHandlerChainWrappers = outerHandlerChainWrappers; return this; } public Builder setThreadSetupActions(List<ThreadSetupHandler> threadSetupActions) { this.threadSetupActions = threadSetupActions; return this; } public Builder setExplodedDeployment(boolean explodedDeployment) { this.explodedDeployment = explodedDeployment; return this; } public List<ServletExtension> getServletExtensions() { return servletExtensions; } public Builder setServletExtensions(List<ServletExtension> servletExtensions) { this.servletExtensions = servletExtensions; return this; } public Builder setSharedSessionManagerConfig(SharedSessionManagerConfig sharedSessionManagerConfig) { this.sharedSessionManagerConfig = sharedSessionManagerConfig; return this; } public Builder setWebSocketDeploymentInfo(WebSocketDeploymentInfo webSocketDeploymentInfo) { this.webSocketDeploymentInfo = webSocketDeploymentInfo; return this; } public File getTempDir() { return tempDir; } public Builder setTempDir(File tempDir) { this.tempDir = tempDir; return this; } public Builder setAllowSuspendedRequests(List<Predicate> allowSuspendedRequests) { this.allowSuspendedRequests = allowSuspendedRequests; return this; } public Builder setExternalResources(List<File> externalResources) { this.externalResources = externalResources; return this; } public UndertowDeploymentInfoService createUndertowDeploymentInfoService() { return new UndertowDeploymentInfoService(mergedMetaData, deploymentName, tldsMetaData, sharedTlds, module, scisMetaData, deploymentRoot, jaccContextId, securityDomain, attributes, contextPath, setupActions, overlays, expressionFactoryWrappers, predicatedHandlers, initialHandlerChainWrappers, innerHandlerChainWrappers, outerHandlerChainWrappers, threadSetupActions, explodedDeployment, servletExtensions, sharedSessionManagerConfig, webSocketDeploymentInfo, tempDir, externalResources, allowSuspendedRequests); } } private static class UndertowThreadSetupAction implements ThreadSetupHandler { private final SetupAction action; private UndertowThreadSetupAction(SetupAction action) { this.action = action; } @Override public <T, C> Action<T, C> create(Action<T, C> action) { return (exchange, context) -> { UndertowThreadSetupAction.this.action.setup(Collections.emptyMap()); try { return action.call(exchange, context); } finally { UndertowThreadSetupAction.this.action.teardown(Collections.emptyMap()); } }; } } }
package com.frankwu.nmea; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.Observable; import java.util.Observer; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; public class GgaNmeaCodecTest { @Test public void decodeValidMessage() { GgaNmeaCodec codec = new GgaNmeaCodec(); codec.addObserver(new Observer() { @Override public void update(Observable o, Object arg) { System.out.println(arg); } } ); Observer mockObserver = mock(Observer.class); codec.addObserver(mockObserver); String content = "$GPGGA,092750.000,5321.6802,N,00630.3372,W,1,8,1.03,61.7,M,55.2,M,,*76\r\n"; codec.decode(content); content = "$GPGGA,092751.000,5321.6802,N,00630.3371,W,1,8,1.03,61.7,M,55.3,M,,*75\r\n"; codec.decode(content); content = "$GPGGA,092204.999,4250.5589,S,14718.5084,E,1,04,24.4,19.7,M,,,,0000*1F\r\n"; codec.decode(content); verify(mockObserver, times(3)).update(eq(codec), any()); } @Test public void encode() { final GgaNmeaCodec codec = new GgaNmeaCodec(); final String content = "$GPGGA,092750.000,5321.6802,N,00630.3372,W,1,8,1.03,61.7,M,55.2,M,,*76\r\n"; codec.addObserver(new Observer() { @Override public void update(Observable o, Object arg) { AbstractNmeaObject obj = (AbstractNmeaObject) arg; List<String> contents = codec.encode(obj); assertEquals(Arrays.asList(content), contents); } }); codec.decode(content); } }
package net.echinopsii.ariane.community.core.mapping.wat.rest.ds.domain; import net.echinopsii.ariane.community.core.mapping.ds.MappingDSException; import net.echinopsii.ariane.community.core.mapping.ds.domain.Container; import net.echinopsii.ariane.community.core.mapping.ds.domain.Endpoint; import net.echinopsii.ariane.community.core.mapping.ds.domain.Node; import net.echinopsii.ariane.community.core.mapping.ds.json.PropertiesJSON; import net.echinopsii.ariane.community.core.mapping.ds.service.MappingSce; import net.echinopsii.ariane.community.core.mapping.wat.MappingBootstrap; import net.echinopsii.ariane.community.core.mapping.ds.json.domain.NodeJSON; import net.echinopsii.ariane.community.core.mapping.ds.json.domain.NodeJSON.JSONDeserializedNode; import net.echinopsii.ariane.community.core.mapping.ds.json.ToolBox; import net.echinopsii.ariane.community.core.mapping.wat.rest.ds.JSONDeserializationResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.*; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.*; @Path("/mapping/domain/nodes") public class NodeEndpoint { private static final Logger log = LoggerFactory.getLogger(NodeEndpoint.class); public static JSONDeserializationResponse jsonFriendlyToMappingFriendly(JSONDeserializedNode jsonDeserializedNode) throws MappingDSException { JSONDeserializationResponse ret = new JSONDeserializationResponse(); // DETECT POTENTIAL QUERIES ERROR FIRST Container reqNodeContainer = null; Node reqNodeParentNode = null; List<Node> reqNodeChildNodes = new ArrayList<>(); List<Node> reqNodeTwinNodes = new ArrayList<>(); List<Endpoint> reqNodeEndpoints = new ArrayList<>(); HashMap<String, Object> reqProperties = new HashMap<>(); if (jsonDeserializedNode.getNodeContainerID()!=0) { reqNodeContainer = (Container) MappingBootstrap.getMappingSce().getContainerSce().getContainer(jsonDeserializedNode.getNodeContainerID()); if (reqNodeContainer == null) ret.setErrorMessage("Request Error : container with provided ID " + jsonDeserializedNode.getNodeContainerID() + " was not found."); } if (ret.getErrorMessage() == null && jsonDeserializedNode.getNodeParentNodeID()!=0) { reqNodeParentNode = (Node) MappingBootstrap.getMappingSce().getNodeSce().getNode(jsonDeserializedNode.getNodeParentNodeID()); if (reqNodeParentNode == null) ret.setErrorMessage("Request Error : parent node with provided ID " + jsonDeserializedNode.getNodeParentNodeID() + " was not found."); } if (ret.getErrorMessage() == null && jsonDeserializedNode.getNodeChildNodesID()!=null && jsonDeserializedNode.getNodeChildNodesID().size() > 0 ) { for (long id : jsonDeserializedNode.getNodeChildNodesID()) { Node childNode = MappingBootstrap.getMappingSce().getNodeSce().getNode(id); if (childNode != null) reqNodeChildNodes.add(childNode); else { ret.setErrorMessage("Request Error : child node with provided ID " + id + " was not found."); break; } } } if (ret.getErrorMessage() == null && jsonDeserializedNode.getNodeTwinNodesID()!=null && jsonDeserializedNode.getNodeTwinNodesID().size() > 0 ) { for (long id : jsonDeserializedNode.getNodeTwinNodesID()) { Node twinNode = MappingBootstrap.getMappingSce().getNodeSce().getNode(id); if (twinNode != null) reqNodeTwinNodes.add(twinNode); else { ret.setErrorMessage("Request Error : twin node with provided ID " + id + " was not found."); break; } } } if (ret.getErrorMessage() == null && jsonDeserializedNode.getNodeEndpointsID()!=null && jsonDeserializedNode.getNodeEndpointsID().size() > 0) { for (long id : jsonDeserializedNode.getNodeTwinNodesID()) { Endpoint endpoint = MappingBootstrap.getMappingSce().getEndpointSce().getEndpoint(id); if (endpoint != null) reqNodeEndpoints.add(endpoint); else { ret.setErrorMessage("Request Error : endpoint with provided ID " + id + " was not found."); break; } } } if (ret.getErrorMessage() == null && jsonDeserializedNode.getNodeProperties()!=null && jsonDeserializedNode.getNodeProperties().size() > 0) { for (PropertiesJSON.JSONDeserializedProperty deserializedProperty : jsonDeserializedNode.getNodeProperties()) { try { Object oValue = ToolBox.extractPropertyObjectValueFromString(deserializedProperty.getPropertyValue(), deserializedProperty.getPropertyType()); reqProperties.put(deserializedProperty.getPropertyName(), oValue); } catch (Exception e) { e.printStackTrace(); ret.setErrorMessage("Request Error : invalid property " + deserializedProperty.getPropertyName() + "."); break; } } } // LOOK IF NODE MAYBE UPDATED OR CREATED Node deserializedNode = null; if (ret.getErrorMessage() == null && jsonDeserializedNode.getNodeID() != 0) { deserializedNode = (Node) MappingBootstrap.getMappingSce().getNodeSce().getNode(jsonDeserializedNode.getNodeID()); if (deserializedNode == null) ret.setErrorMessage("Request Error : node with provided ID " + jsonDeserializedNode.getNodeID() + " was not found."); } if (ret.getErrorMessage() == null && deserializedNode == null && reqNodeContainer != null && jsonDeserializedNode.getNodeName() != null) deserializedNode = (Node) MappingBootstrap.getMappingSce().getNodeByName(reqNodeContainer, jsonDeserializedNode.getNodeName()); // APPLY REQ IF NO ERRORS if (ret.getErrorMessage() == null) { String reqNodeName = jsonDeserializedNode.getNodeName(); long reqContainerID = jsonDeserializedNode.getNodeContainerID(); long reqParentNodeID = jsonDeserializedNode.getNodeParentNodeID(); if (deserializedNode == null) deserializedNode = MappingBootstrap.getMappingSce().getNodeSce().createNode(reqNodeName, reqContainerID, reqParentNodeID); else { if (reqNodeName != null) deserializedNode.setNodeName(reqNodeName); if (reqNodeContainer != null) deserializedNode.setNodeContainer(reqNodeContainer); if (reqNodeParentNode != null) deserializedNode.setNodeParentNode(reqNodeParentNode); } if (jsonDeserializedNode.getNodeChildNodesID()!=null) { List<Node> childNodesToDelete = new ArrayList<>(); for (Node existingChildNode : deserializedNode.getNodeChildNodes()) if (!reqNodeChildNodes.contains(existingChildNode)) childNodesToDelete.add(existingChildNode); for (Node childNodeToDelete : childNodesToDelete) deserializedNode.removeNodeChildNode(childNodeToDelete); for (Node childNodeReq : reqNodeChildNodes) deserializedNode.addNodeChildNode(childNodeReq); } if (jsonDeserializedNode.getNodeTwinNodesID()!=null) { List<Node> twinNodesToDelete = new ArrayList<>(); for (Node existingTwinNode : deserializedNode.getTwinNodes()) if (!reqNodeTwinNodes.contains(existingTwinNode)) twinNodesToDelete.add(existingTwinNode); for (Node twinNodeToDelete : twinNodesToDelete) { deserializedNode.removeTwinNode(twinNodeToDelete); twinNodeToDelete.removeTwinNode(deserializedNode); } for (Node twinNodeReq : reqNodeTwinNodes) { deserializedNode.addTwinNode(twinNodeReq); twinNodeReq.addTwinNode(deserializedNode); } } if (jsonDeserializedNode.getNodeEndpointsID()!=null) { List<Endpoint> endpointsToDelete = new ArrayList<>(); for (Endpoint existingEndpoint : deserializedNode.getNodeEndpoints()) if (!reqNodeEndpoints.contains(existingEndpoint)) endpointsToDelete.add(existingEndpoint); for (Endpoint endpointToDelete : endpointsToDelete) deserializedNode.removeEndpoint(endpointToDelete); for (Endpoint endpointReq : reqNodeEndpoints) deserializedNode.addEnpoint(endpointReq); } if (jsonDeserializedNode.getNodeProperties()!=null) { if (deserializedNode.getNodeProperties()!=null) { List<String> propertiesToDelete = new ArrayList<>(); for (String propertyKey : deserializedNode.getNodeProperties().keySet()) if (!reqProperties.containsKey(propertyKey)) propertiesToDelete.add(propertyKey); for (String propertyToDelete : propertiesToDelete) deserializedNode.removeNodeProperty(propertyToDelete); } for (String propertyKey : reqProperties.keySet()) deserializedNode.addNodeProperty(propertyKey, reqProperties.get(propertyKey)); } ret.setDeserializedObject(deserializedNode); } return ret; } @GET @Path("/{param:[0-9][0-9]*}") public Response displayNode(@PathParam("param") long id) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] get node : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id}); if (subject.hasRole("mappingreader") || subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:read") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { Node node = (Node) MappingBootstrap.getMappingSce().getNodeSce().getNode(id); if (node != null) { try { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); NodeJSON.oneNode2JSON(node, outStream); String result = ToolBox.getOuputStreamContent(outStream, "UTF-8"); return Response.status(Status.OK).entity(result).build(); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); String result = e.getMessage(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build(); } } else { return Response.status(Status.NOT_FOUND).entity("Node with id " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to read mapping db. Contact your administrator.").build(); } } @GET public Response displayAllNodes() { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] get nodes", new Object[]{Thread.currentThread().getId(), subject.getPrincipal()}); if (subject.hasRole("mappingreader") || subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:read") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { String result = ""; ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { NodeJSON.manyNodes2JSON((HashSet<Node>) MappingBootstrap.getMappingSce().getNodeSce().getNodes(null), outStream); result = ToolBox.getOuputStreamContent(outStream, "UTF-8"); return Response.status(Status.OK).entity(result).build(); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); result = e.getMessage(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to read mapping db. Contact your administrator.").build(); } } @GET @Path("/get") public Response getNode(@QueryParam("endpointURL") String endpointURL, @QueryParam("ID")long id) { if (id != 0) { return displayNode(id); } else if (endpointURL!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] get node: {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), endpointURL}); if (subject.hasRole("mappingreader") || subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:read") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { Node node = (Node) MappingBootstrap.getMappingSce().getNodeSce().getNode(endpointURL); if (node != null) { try { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); NodeJSON.oneNode2JSON(node, outStream); String result = ToolBox.getOuputStreamContent(outStream, "UTF-8"); return Response.status(Status.OK).entity(result).build(); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); String result = e.getMessage(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build(); } } else { return Response.status(Status.NOT_FOUND).entity("Node with id " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to read mapping db. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("MappingDSLRegistryRequest error: name and id are not defined. You must define one of these parameters").build(); } } @GET @Path("/find") public Response findNodes(@QueryParam("selector") String selector) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] find node: {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), selector}); if (subject.hasRole("mappingreader") || subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:read") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { HashSet<Node> nodes = (HashSet<Node>) MappingBootstrap.getMappingSce().getNodeSce().getNodes(selector); if (nodes != null && nodes.size() > 0) { String result = ""; ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { NodeJSON.manyNodes2JSON(nodes, outStream); result = ToolBox.getOuputStreamContent(outStream, "UTF-8"); return Response.status(Status.OK).entity(result).build(); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); result = e.getMessage(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build(); } } else { return Response.status(Status.NOT_FOUND).entity("No node matching with selector ('"+selector+"') found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to read mapping db. Contact your administrator.").build(); } } @GET @Path("/create") public Response createNode(@QueryParam("name")String nodeName, @QueryParam("containerID")long containerID, @QueryParam("parentNodeID")long parentNodeID) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] create node : ({},{},{},{})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), nodeName, containerID, parentNodeID}); if (subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:write") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { try { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); Node node = MappingBootstrap.getMappingSce().getNodeSce().createNode(nodeName, containerID, parentNodeID); try { NodeJSON.oneNode2JSON(node, outStream); String result = ToolBox.getOuputStreamContent(outStream, "UTF-8"); return Response.status(Status.OK).entity(result).build(); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); String result = e.getMessage(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build(); } } catch (MappingDSException e) { log.error(e.getMessage()); e.printStackTrace(); String result = e.getMessage(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to write on mapping db. Contact your administrator.").build(); } } @POST public Response postNode(@QueryParam("payload") String payload) throws IOException { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] create or update node : ({})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), payload}); if (subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:write") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { if (payload != null) { try { Response ret; JSONDeserializationResponse deserializationResponse = jsonFriendlyToMappingFriendly(NodeJSON.JSON2Node(payload)); if (deserializationResponse.getErrorMessage()!=null) { String result = deserializationResponse.getErrorMessage(); ret = Response.status(Status.BAD_REQUEST).entity(result).build(); } else if (deserializationResponse.getDeserializedObject()!=null) { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); NodeJSON.oneNode2JSON((Node)deserializationResponse.getDeserializedObject(), outStream); String result = ToolBox.getOuputStreamContent(outStream, "UTF-8"); ret = Response.status(Status.OK).entity(result).build(); } else { String result = "ERROR while deserializing !"; ret = Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build(); } return ret ; } catch (MappingDSException e) { log.error(e.getMessage()); e.printStackTrace(); String result = e.getMessage(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build(); } } else { return Response.status(Status.BAD_REQUEST).entity("No payload attached to this POST").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to write on mapping db. Contact your administrator.").build(); } } @GET @Path("/delete") public Response deleteNode(@QueryParam("ID")long nodeID) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] delete node : ({})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), nodeID}); if (subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:write") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { MappingSce mapping = MappingBootstrap.getMappingSce(); try { mapping.getNodeSce().deleteNode(nodeID); return Response.status(Status.OK).entity("Node (" + nodeID + ") successfully deleted.").build(); } catch (MappingDSException e) { log.error(e.getMessage()); e.printStackTrace(); String result = e.getMessage(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to write on mapping db. Contact your administrator.").build(); } } @GET @Path("/update/name") public Response setNodeName(@QueryParam("ID")long id, @QueryParam("name")String name) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update node name : ({},{})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, name}); if (subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:write") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { Node node = MappingBootstrap.getMappingSce().getNodeSce().getNode(id); if (node != null) { node.setNodeName(name); return Response.status(Status.OK).entity("Node (" + id + ") name successfully updated to " + name + ".").build(); } else { return Response.status(Status.NOT_FOUND).entity("Error while updating node (" + id + ") name " + name + " : node " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to write on mapping db. Contact your administrator.").build(); } } @GET @Path("/update/container") public Response setNodeContainer(@QueryParam("ID")long id, @QueryParam("containerID")long containerID) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update node container : ({},{})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, containerID}); if (subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:write") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { Node node = MappingBootstrap.getMappingSce().getNodeSce().getNode(id); if (node != null) { Container container = MappingBootstrap.getMappingSce().getContainerSce().getContainer(containerID); if (container != null) { node.setNodeContainer(container); return Response.status(Status.OK).entity("Node (" + id + ") container successfully updated to " + containerID + ".").build(); } else { return Response.status(Status.NOT_FOUND).entity("Error while updating node (" + id + ") container " + containerID + " : container " + containerID + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Error while updating node (" + id + ") container " + containerID + " : node " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to write on mapping db. Contact your administrator.").build(); } } @GET @Path("/update/parentNode") public Response setNodeParentNode(@QueryParam("ID")long id, @QueryParam("parentNodeID")long parentNodeID) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update node parent node : ({},{})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, parentNodeID}); if (subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:write") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { Node node = MappingBootstrap.getMappingSce().getNodeSce().getNode(id); if (node != null) { Node parentNode = MappingBootstrap.getMappingSce().getNodeSce().getNode(id); if (parentNode != null) { node.setNodeParentNode(parentNode); return Response.status(Status.OK).entity("Node (" + parentNodeID + ") parent node successfully updated to " + parentNodeID + ".").build(); } else { return Response.status(Status.NOT_FOUND).entity("Error while updating node (" + id + ") parent node " + parentNodeID + " : parent node " + parentNodeID + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Error while updating node (" + id + ") parent node " + parentNodeID + " : node " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to write on mapping db. Contact your administrator.").build(); } } @GET @Path("/update/childNodes/add") public Response addNodeChildNode(@QueryParam("ID")long id, @QueryParam("childNodeID") long childNodeID) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] add node child node : ({},{})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, childNodeID}); if (subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:write") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { Node node = MappingBootstrap.getMappingSce().getNodeSce().getNode(id); if (node != null) { Node childNode = MappingBootstrap.getMappingSce().getNodeSce().getNode(childNodeID); if (childNode != null) { node.addNodeChildNode(childNode); return Response.status(Status.OK).entity("Child node (" + childNodeID + ") successfully added to node " + id + ".").build(); } else { return Response.status(Status.NOT_FOUND).entity("Error while adding child node " + childNodeID + " to node " + id + " : child node " + childNodeID + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Error while adding child node " + childNodeID + " to node " + id + " : node " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to write on mapping db. Contact your administrator.").build(); } } @GET @Path("/update/childNodes/delete") public Response deleteNodeChildNode(@QueryParam("ID")long id, @QueryParam("childNodeID") long childNodeID) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] delete node child node : ({},{})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, childNodeID}); if (subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:write") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { Node node = MappingBootstrap.getMappingSce().getNodeSce().getNode(id); if (node != null) { Node childNode = MappingBootstrap.getMappingSce().getNodeSce().getNode(childNodeID); if (childNode != null) { node.removeNodeChildNode(childNode); return Response.status(Status.OK).entity("Child node (" + childNodeID + ") successfully deleted from node " + id + ".").build(); } else { return Response.status(Status.NOT_FOUND).entity("Error while deleting child node " + childNodeID + " from node " + id + " : child node " + childNodeID + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Error while deleting child node " + childNodeID + " from node " + id + " : node " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to write on mapping db. Contact your administrator.").build(); } } @GET @Path("/update/twinNodes/add") public Response addNodeTwinNode(@QueryParam("ID")long id, @QueryParam("twinNodeID") long twinNodeID) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] add node twin node : ({},{})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, twinNodeID}); if (subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:write") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { Node node = MappingBootstrap.getMappingSce().getNodeSce().getNode(id); if (node != null) { Node twinNode = MappingBootstrap.getMappingSce().getNodeSce().getNode(twinNodeID); if (twinNode != null) { node.addTwinNode(twinNode); twinNode.addTwinNode(node); return Response.status(Status.OK).entity("Twin node (" + twinNodeID + ") successfully added to node " + id + ".").build(); } else { return Response.status(Status.NOT_FOUND).entity("Error while adding twin node " + twinNodeID + " to node " + id + " : twin node " + twinNodeID + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Error while adding twin node " + twinNodeID + " to node " + id + " : node " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to write on mapping db. Contact your administrator.").build(); } } @GET @Path("/update/twinNodes/delete") public Response deleteNodeTwinNode(@QueryParam("ID")long id, @QueryParam("twinNodeID") long twinNodeID) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] delete node twin node : ({},{})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, twinNodeID}); if (subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:write") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { Node node = MappingBootstrap.getMappingSce().getNodeSce().getNode(id); if (node != null) { Node twinNode = MappingBootstrap.getMappingSce().getNodeSce().getNode(twinNodeID); if (twinNode != null) { node.removeTwinNode(twinNode); twinNode.removeTwinNode(node); return Response.status(Status.OK).entity("Twin node (" + twinNodeID + ") successfully deleted from node " + id + ".").build(); } else { return Response.status(Status.NOT_FOUND).entity("Error while deleting twin node " + twinNodeID + " from node " + id + " : twin node " + twinNodeID + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Error while deleting twin node " + twinNodeID + " from node " + id + " : node " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to write on mapping db. Contact your administrator.").build(); } } @GET @Path("/update/endpoints/add") public Response addNodeEndpoint(@QueryParam("ID")long id, @QueryParam("endpointID") long endpointID) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] add node endpoint : ({},{})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, endpointID}); if (subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:write") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { Node node = MappingBootstrap.getMappingSce().getNodeSce().getNode(id); if (node != null) { Endpoint endpoint = MappingBootstrap.getMappingSce().getEndpointSce().getEndpoint(endpointID); if (endpoint != null) { node.addEnpoint(endpoint); return Response.status(Status.OK).entity("Endpoint (" + endpointID + ") successfully added to node " + id + ".").build(); } else { return Response.status(Status.NOT_FOUND).entity("Error while adding endpoint " + endpointID + " to node " + id + " : node " + id + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Error while adding endpoint " + endpointID + " to node " + id + " : node " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to write on mapping db. Contact your administrator.").build(); } } @GET @Path("/update/endpoints/delete") public Response deleteNodeEndpoint(@QueryParam("ID")long id, @QueryParam("endpointID") long endpointID) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] delete node endpoint : ({},{})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, endpointID}); if (subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:write") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { Node node = MappingBootstrap.getMappingSce().getNodeSce().getNode(id); if (node != null) { Endpoint endpoint = MappingBootstrap.getMappingSce().getEndpointSce().getEndpoint(endpointID); if (endpoint != null) { node.removeEndpoint(endpoint); return Response.status(Status.OK).entity("Endpoint (" + endpointID + ") successfully deleted from node " + id + ".").build(); } else { return Response.status(Status.NOT_FOUND).entity("Error while deleting endpoint " + endpointID + " from node " + id + " : node " + id + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Error while deleting endpoint " + endpointID + " from node : node " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to write on mapping db. Contact your administrator.").build(); } } @GET @Path("/update/properties/add") public Response addNodeProperty(@QueryParam("ID")long id, @QueryParam("propertyName") String name, @QueryParam("propertyValue") String value, @DefaultValue("String") @QueryParam("propertyType") String type) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update node by adding a property : ({},({},{},{}))", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, name, value, type}); if (subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:write") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { Node node = MappingBootstrap.getMappingSce().getNodeSce().getNode(id); if (node != null) { Object oValue; try { oValue = ToolBox.extractPropertyObjectValueFromString(value, type); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); String result = e.getMessage(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build(); } node.addNodeProperty(name, oValue); return Response.status(Status.OK).entity("Property (" + name + "," + value + ") successfully added to node " + id + ".").build(); } else { return Response.status(Status.NOT_FOUND).entity("Error while adding property " + name + " to node " + id + " : node " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to write on mapping db. Contact your administrator.").build(); } } @GET @Path("/update/properties/delete") public Response deleteNodeProperty(@QueryParam("ID")long id, @QueryParam("propertyName") String name) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update node by removing a property : ({},{})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, name}); if (subject.hasRole("mappinginjector") || subject.isPermitted("mappingDB:write") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { Node node = MappingBootstrap.getMappingSce().getNodeSce().getNode(id); if (node != null) { node.removeNodeProperty(name); return Response.status(Status.OK).entity("Property (" + name + ") successfully deleted from node " + id + ".").build(); } else { return Response.status(Status.NOT_FOUND).entity("Error while adding property " + name + " from node " + id + " : node " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to write on mapping db. Contact your administrator.").build(); } } }
package com.zabawaba.reflector; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.util.HashSet; import org.junit.Test; import com.zabawaba.reflector.classes.Empty; import com.zabawaba.reflector.classes.SampleOne; public class FieldsTest { @Test public void testGet() throws NoSuchFieldException { SampleOne sample = new SampleOne(); ReflectorField field = Fields.forObj(sample).get("field1"); assertNotNull(field); } @Test(expected=NoSuchFieldException.class) public void testGet_MissingField() throws NoSuchFieldException { SampleOne sample = new SampleOne(); Fields.forObj(sample).get("i_don't_exist"); fail("should have through exception"); } @Test public void testForObj() { SampleOne sample = new SampleOne(); Fields f = Fields.forObj(sample); assertNotNull(f); } /* * TODO: figure out why this test messes up cobertura reporting * * @Test * public void testGetFieldValue_SecurityManager() { * SampleOne sample = new SampleOne(); * System.err.close(); * System.setSecurityManager(new SecurityManager()); * Object value = ReflectionUtil.getFieldValue(sample, "field3"); * assertNull(value); *} */ @Test public void testList() { HashSet<ReflectorField> fields = Fields.forObj(new SampleOne()).list(); assertEquals(3, fields.size()); } @Test public void testList_NoFieldsOnClass() { HashSet<ReflectorField> fields = Fields.forObj(new Empty()).list(); // there are 0 fields in the object class assertEquals(0, fields.size()); } @Test public void testListWithFilter() { HashSet<ReflectorField> fields = Fields.forObj(new SampleOne()).list(Fields.PUBLIC_FIELDS); assertEquals(2, fields.size()); } @Test public void tesListWithFilter_NullFilter() { HashSet<ReflectorField> fields = Fields.forObj(new SampleOne()).list(null); assertEquals(3, fields.size()); } }
package application; import java.io.File; import java.io.InputStream; import java.util.ResourceBundle; import configuration.ErrorCheck; import configuration.Parser; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.stage.FileChooser; import javafx.stage.Stage; /** * Creates the GUI * @author Andrew Sun * */ public class GUI { private static final int NUM_BUTTONS = 3; private static final int HELP_BUTTON = 0; private static final int TURTLE_BUTTON = 1; //private static final int OPEN_FILE_BUTTON = 2; private static final int HBOX_SPACING = 20; private static final int STAGE_HEIGHT = 800; private static final int STAGE_WIDTH = 1200; private static final int VIEW_HEIGHT = 700; private static final int VIEW_WIDTH = 900; // Cut down instance variables // Think about seperating classes private TextField commandsField; private ListView<String> prevCommands; private static final ObservableList<String> myCommandsList = FXCollections.observableArrayList(); private static final ObservableList<String> myLanguageNames = FXCollections.observableArrayList(); private BorderPane myBorders; private View myView; private Scene myScene; private Button[] myButtons; private String[] myButtonNames; private ResourceBundle myLabels, myCurrentBundle; private HBox mainHBox; private Parser myParser; private File myTurtleFilePath; private ErrorCheck myErrorCheck; private final ColorPicker penColor = new ColorPicker(); private final ColorPicker backgroundColor = new ColorPicker(); public GUI(){ myLabels = ResourceBundle.getBundle("buttons"); myButtonNames = new String[] {"help", "turtleimage", "openfile"}; myLanguageNames.addAll(new String[] {"English", "Chinese", "French", "German", "Italian", "Japanese", "Korean", "Portuguese", "Russian", "Spanish"}); myButtons = new Button[NUM_BUTTONS]; myBorders = new BorderPane(); myParser = new Parser(); // default values penColor.setValue(Color.BLACK); backgroundColor.setValue(Color.WHITE); } /** * Initializes the GUI and returns a scene to the Main method. * @param s * @return Scene */ public Scene initialize(Stage s){ System.out.println(" gui initialize"); initializeView(); initializeTextField(); initializeCommandsHistory(); initializeButtons(); myScene = new Scene(myBorders, STAGE_WIDTH, STAGE_HEIGHT); return myScene; } /** * Creates the Color Buttons, normal buttons, and language selection buttons */ private void initializeButtons(){ // Creates HBox for button alignment mainHBox = new HBox(); mainHBox.setSpacing(HBOX_SPACING); mainHBox.setAlignment(Pos.CENTER); String buttonStyle = "-fx-font: 14 georgia; -fx-text-fill: black; -fx-effect: dropshadow( three-pass-box , rgba(0,0,0,0.6) , 5, 0.0 , 0 , 1 ); -fx-border-width: 2 2 2 2; -fx-border-color: #006652; -fx-background-color: white;"; // Creates ColorPicker buttons penColor.setStyle(buttonStyle); penColor.setOnAction(e -> myView.setColor(penColor.getValue())); backgroundColor.setStyle(buttonStyle); backgroundColor.setOnAction(e -> myView.setBackgroundColor(backgroundColor.getValue())); mainHBox.getChildren().addAll(penColor, backgroundColor); // Creates normal buttons for (int i = 0; i < NUM_BUTTONS; i++){ Button b = new Button(myLabels.getString(myButtonNames[i])); b.setStyle(buttonStyle); myButtons[i] = b; b.setOnMousePressed(e -> mouseDown(b)); b.setOnMouseReleased(e -> mouseUp(b)); mainHBox.getChildren().add(b); } myButtons[TURTLE_BUTTON].setOnMouseClicked(e -> chooseTurtleImage()); myButtons[HELP_BUTTON].setOnMouseClicked(e -> launchHelpPage()); // Creates languages buttons ComboBox<String> langBox = new ComboBox<String>(); langBox.setItems(myLanguageNames); langBox.setStyle(buttonStyle); langBox.setValue("English"); // TODO: set on changed properties langBox.valueProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> ov, String t, String t1) { myCurrentBundle = ResourceBundle.getBundle("resources.languages." + t1); } }); mainHBox.getChildren().add(langBox); myBorders.setTop(mainHBox); } /** * Launches a help page to go to SLogo Help Page */ private void launchHelpPage() { WebPopUp helpPage = new WebPopUp(); try { helpPage.start(new Stage()); } catch (Exception e) { e.printStackTrace(); } } /** * Prompts user to choose an image file. */ private void chooseTurtleImage() { FileChooser fileChooser = new FileChooser(); FileChooser.ExtensionFilter jpgFilter = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG"); FileChooser.ExtensionFilter pngFilter = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG"); fileChooser.getExtensionFilters().addAll(jpgFilter, pngFilter); myTurtleFilePath = fileChooser.showOpenDialog(null); myView.updateTurtleImage(myTurtleFilePath); } /** * Initializes view */ private void initializeView() { System.out.println(" gui initialize view"); myView = new View(VIEW_WIDTH, VIEW_HEIGHT); myBorders.setCenter(myView); } /** * Initializes commands history */ private void initializeCommandsHistory() { System.out.println(" gui initialize ch"); prevCommands = new ListView<String>(myCommandsList); myBorders.setRight(prevCommands); } /** * Initializes text field for user to enter commands */ private void initializeTextField() { System.out.println(" gui initialize tf"); // TODO pass in string to parser myErrorCheck = new ErrorCheck(); commandsField = new TextField(); commandsField.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent t) { if (t.getCode() == KeyCode.ENTER){ if(myErrorCheck.validateInput(commandsField.getText())){ myParser.parse(commandsField.getText()); } else{ System.out.println("error!"); } myCommandsList.add(commandsField.getText()); commandsField.clear(); } } }); myBorders.setBottom(commandsField); } /** * added button styles * @author anika, edited by Andrew * @param b */ private void mouseDown(Button b) { b.setStyle("-fx-font: 14 georgia; -fx-text-fill: #CC0000; -fx-effect: dropshadow( three-pass-box , rgba(0,0,0,0.6) ,.5, 0.0 , 0 , 1 ); -fx-border-width: 2 2 2 2; -fx-border-color: white; -fx-background-color: black;"); } private void mouseUp(Button b) { b.setStyle("-fx-font: 14 georgia; -fx-text-fill: black; -fx-effect: dropshadow( three-pass-box , rgba(0,0,0,0.6) , 5, 0.0 , 0 , 1 ); -fx-border-width: 2 2 2 2; -fx-border-color: #006652; -fx-background-color: white;"); } public View getView(){ return myView; } }
package edu.cornell.mannlib.vitro.webapp.controller.accounts.user; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.cornell.mannlib.vedit.beans.LoginStatusBean; import edu.cornell.mannlib.vitro.webapp.auth.policy.PolicyHelper; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.usepages.ManageOwnProxies; import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.SelfEditingConfiguration; import edu.cornell.mannlib.vitro.webapp.beans.UserAccount; import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.accounts.UserAccountsPage; import edu.cornell.mannlib.vitro.webapp.controller.accounts.admin.UserAccountsEditPage; import edu.cornell.mannlib.vitro.webapp.controller.authenticate.Authenticator; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; /** * Handle the "My Account" form display and submission. */ public class UserAccountsMyAccountPage extends UserAccountsPage { private static final Log log = LogFactory .getLog(UserAccountsEditPage.class); private static final String PARAMETER_SUBMIT = "submitMyAccount"; private static final String PARAMETER_EMAIL_ADDRESS = "emailAddress"; private static final String PARAMETER_FIRST_NAME = "firstName"; private static final String PARAMETER_LAST_NAME = "lastName"; private static final String PARAMETER_PROXY_URI = "proxyUri"; private static final String ERROR_NO_EMAIL = "errorEmailIsEmpty"; private static final String ERROR_EMAIL_IN_USE = "errorEmailInUse"; private static final String ERROR_EMAIL_INVALID_FORMAT = "errorEmailInvalidFormat"; private static final String ERROR_NO_FIRST_NAME = "errorFirstNameIsEmpty"; private static final String ERROR_NO_LAST_NAME = "errorLastNameIsEmpty"; private static final String TEMPLATE_NAME = "userAccounts-myAccount.ftl"; private static final String PROPERTY_PROFILE_TYPES = "proxy.eligibleTypeList"; private final UserAccountsMyAccountPageStrategy strategy; private final UserAccount userAccount; /* The request parameters */ private boolean submit; private String emailAddress = ""; private String firstName = ""; private String lastName = ""; private List<String> proxyUris = new ArrayList<String>(); /** The result of validating a "submit" request. */ private String errorCode = ""; /** The result of updating the account. */ private String confirmationCode = ""; public UserAccountsMyAccountPage(VitroRequest vreq) { super(vreq); this.userAccount = LoginStatusBean.getCurrentUser(vreq); this.strategy = UserAccountsMyAccountPageStrategy.getInstance(vreq, this, isExternalAccount()); parseRequestParameters(); if (isSubmit()) { validateParameters(); } } public UserAccount getUserAccount() { return userAccount; } private void parseRequestParameters() { submit = isFlagOnRequest(PARAMETER_SUBMIT); emailAddress = getStringParameter(PARAMETER_EMAIL_ADDRESS, ""); firstName = getStringParameter(PARAMETER_FIRST_NAME, ""); lastName = getStringParameter(PARAMETER_LAST_NAME, ""); proxyUris = getStringParameters(PARAMETER_PROXY_URI); strategy.parseAdditionalParameters(); } public boolean isSubmit() { return submit; } private void validateParameters() { if (emailAddress.isEmpty()) { errorCode = ERROR_NO_EMAIL; } else if (emailIsChanged() && isEmailInUse()) { errorCode = ERROR_EMAIL_IN_USE; } else if (!isEmailValidFormat()) { errorCode = ERROR_EMAIL_INVALID_FORMAT; } else if (firstName.isEmpty()) { errorCode = ERROR_NO_FIRST_NAME; } else if (lastName.isEmpty()) { errorCode = ERROR_NO_LAST_NAME; } else { errorCode = strategy.additionalValidations(); } } private boolean emailIsChanged() { return !emailAddress.equals(userAccount.getEmailAddress()); } private boolean isEmailInUse() { return userAccountsDao.getUserAccountByEmail(emailAddress) != null; } private boolean isEmailValidFormat() { return Authenticator.isValidEmailAddress(emailAddress); } public boolean isValid() { return errorCode.isEmpty(); } private boolean isExternalAccount() { return LoginStatusBean.getBean(vreq).hasExternalAuthentication(); } public final ResponseValues showPage() { Map<String, Object> body = new HashMap<String, Object>(); if (isSubmit()) { body.put("emailAddress", emailAddress); body.put("firstName", firstName); body.put("lastName", lastName); body.put("proxies", buildOngoingProxyList()); } else { body.put("emailAddress", userAccount.getEmailAddress()); body.put("firstName", userAccount.getFirstName()); body.put("lastName", userAccount.getLastName()); body.put("proxies", buildOriginalProxyList()); } body.put("formUrls", buildUrlsMap()); body.put("myAccountUri", userAccount.getUri()); body.put("profileTypes", buildProfileTypesString()); // Could I do this without exposing this mechanism? But how to search // for an associated profile in AJAX? body.put("matchingProperty", SelfEditingConfiguration.getBean(vreq) .getMatchingPropertyUri()); if (userAccount.isExternalAuthOnly()) { body.put("externalAuthOnly", Boolean.TRUE); } if (!errorCode.isEmpty()) { body.put(errorCode, Boolean.TRUE); } if (!confirmationCode.isEmpty()) { body.put(confirmationCode, Boolean.TRUE); } if (isProxyPanelAuthorized()) { body.put("showProxyPanel", Boolean.TRUE); } strategy.addMoreBodyValues(body); return new TemplateResponseValues(TEMPLATE_NAME, body); } private String buildProfileTypesString() { return ConfigurationProperties.getBean(vreq).getProperty( PROPERTY_PROFILE_TYPES, "http://www.w3.org/2002/07/owl#Thing"); } public void updateAccount() { userAccount.setEmailAddress(emailAddress); userAccount.setFirstName(firstName); userAccount.setLastName(lastName); Individual profilePage = getProfilePage(userAccount); if (profilePage != null) { userAccountsDao.setProxyAccountsOnProfile(profilePage.getURI(), proxyUris); } strategy.setAdditionalProperties(userAccount); userAccountsDao.updateUserAccount(userAccount); strategy.notifyUser(); confirmationCode = strategy.getConfirmationCode(); } boolean isProxyPanelAuthorized() { return PolicyHelper .isAuthorizedForActions(vreq, new ManageOwnProxies()) && (getProfilePage(userAccount) != null); } boolean isExternalAuthOnly() { return (userAccount != null) && userAccount.isExternalAuthOnly(); } private List<ProxyInfo> buildOngoingProxyList() { List<UserAccount> proxyUsers = new ArrayList<UserAccount>(); for (String proxyUri : proxyUris) { UserAccount proxyUser = userAccountsDao .getUserAccountByUri(proxyUri); if (proxyUser == null) { log.warn("No UserAccount found for proxyUri: " + proxyUri); } else { proxyUsers.add(proxyUser); } } return buildProxyListFromUserAccounts(proxyUsers); } private List<ProxyInfo> buildOriginalProxyList() { Collection<UserAccount> proxyUsers; Individual profilePage = getProfilePage(userAccount); if (profilePage == null) { log.debug("no profile page"); proxyUsers = Collections.emptyList(); } else { String uri = profilePage.getURI(); log.debug("profile page at " + uri); proxyUsers = userAccountsDao.getUserAccountsWhoProxyForPage(uri); if (log.isDebugEnabled()) { log.debug(getUrisFromUserAccounts(proxyUsers)); } } return buildProxyListFromUserAccounts(proxyUsers); } private Individual getProfilePage(UserAccount ua) { SelfEditingConfiguration sec = SelfEditingConfiguration.getBean(vreq); List<Individual> profilePages = sec .getAssociatedIndividuals(indDao, ua); if (profilePages.isEmpty()) { return null; } else { return profilePages.get(0); } } private List<ProxyInfo> buildProxyListFromUserAccounts( Collection<UserAccount> proxyUsers) { List<ProxyInfo> proxyInfos = new ArrayList<ProxyInfo>(); for (UserAccount proxyUser : proxyUsers) { proxyInfos.add(assembleProxyInfoForUser(proxyUser)); } return proxyInfos; } private ProxyInfo assembleProxyInfoForUser(UserAccount proxyUser) { String userUri = proxyUser.getUri(); String label = assembleUserAccountLabel(proxyUser); String classLabel = ""; String imageUrl = ""; // Does this user have a profile? Can we get better info? Individual proxyProfilePage = getProfilePage(proxyUser); if (proxyProfilePage != null) { String thumbUrl = proxyProfilePage.getThumbUrl(); if ((thumbUrl != null) && (!thumbUrl.isEmpty())) { imageUrl = UrlBuilder.getUrl(thumbUrl); } classLabel = getMostSpecificTypeLabel(proxyProfilePage.getURI()); } return new ProxyInfo(userUri, label, classLabel, imageUrl); } private String assembleUserAccountLabel(UserAccount ua) { String last = ua.getLastName(); String first = ua.getFirstName(); if (last.isEmpty()) { return first; } else if (first.isEmpty()) { return last; } else { return last + ", " + first; } } private String getMostSpecificTypeLabel(String uri) { Map<String, String> types = opsDao .getMostSpecificTypesInClassgroupsForIndividual(uri); if (types.isEmpty()) { return ""; } else { return types.values().iterator().next(); } } private List<String> getUrisFromUserAccounts( Collection<UserAccount> proxyUsers) { List<String> list = new ArrayList<String>(); for (UserAccount u : proxyUsers) { list.add(u.getUri()); } return list; } public static class ProxyInfo { private final String uri; private final String label; private final String classLabel; private final String imageUrl; public ProxyInfo(String uri, String label, String classLabel, String imageUrl) { this.uri = uri; this.label = label; this.classLabel = classLabel; this.imageUrl = imageUrl; } public String getUri() { return uri; } public String getLabel() { return label; } public String getClassLabel() { return classLabel; } public String getImageUrl() { return imageUrl; } } }
package de.retest.recheck; import static de.retest.recheck.Properties.TEST_REPORT_FILE_EXTENSION; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.endsWith; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.doThrow; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.support.membermodification.MemberMatcher.method; import java.awt.HeadlessException; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import de.retest.recheck.persistence.FileNamer; import de.retest.recheck.ui.DefaultValueFinder; import de.retest.recheck.ui.descriptors.IdentifyingAttributes; import de.retest.recheck.ui.descriptors.RootElement; @RunWith( PowerMockRunner.class ) @PrepareForTest( Rehub.class ) public class RecheckImplTest { @Rule TemporaryFolder temp = new TemporaryFolder(); @Test public void using_strange_stepText_should_be_normalized() throws Exception { final FileNamerStrategy fileNamerStrategy = spy( new MavenConformFileNamerStrategy() ); final RecheckOptions opts = RecheckOptions.builder() .fileNamerStrategy( fileNamerStrategy ) .build(); final Recheck cut = new RecheckImpl( opts ); final RecheckAdapter adapter = mock( RecheckAdapter.class ); try { cut.check( mock( Object.class ), adapter, "!@#%$^&)te}{:|\\\":xt!(@*$" ); } catch ( final Exception e ) { // Ignore Exceptions, fear AssertionErrors... } verify( fileNamerStrategy ).createFileNamer( eq( fileNamerStrategy.getTestClassName() ) ); verify( fileNamerStrategy ).createFileNamer( endsWith( ".!@ } @Test public void test_class_name_should_be_default_result_file_name() throws Exception { final String suiteName = getClass().getName(); final RecheckImpl cut = new RecheckImpl(); final String resultFileName = cut.getResultFile().getName(); assertThat( resultFileName ).isEqualTo( suiteName + TEST_REPORT_FILE_EXTENSION ); } @Test public void exec_suite_name_should_be_used_for_result_file_name() throws Exception { final String suiteName = "FooBar"; final RecheckOptions opts = RecheckOptions.builder() .suiteName( suiteName ) .build(); final RecheckImpl cut = new RecheckImpl( opts ); final String resultFileName = cut.getResultFile().getName(); assertThat( resultFileName ).isEqualTo( suiteName + TEST_REPORT_FILE_EXTENSION ); } @Test public void calling_check_without_startTest_should_work() throws Exception { final Path root = temp.newFolder().toPath(); final RecheckOptions opts = RecheckOptions.builder() .fileNamerStrategy( new WithinTempDirectoryFileNamerStrategy( root ) ) .build(); final Recheck cut = new RecheckImpl( opts ); cut.check( "String", new DummyStringRecheckAdapter(), "step" ); } @Test public void calling_with_no_GM_should_produce_better_error_msg() throws Exception { final Path root = temp.newFolder().toPath(); final RecheckOptions opts = RecheckOptions.builder() .fileNamerStrategy( new WithinTempDirectoryFileNamerStrategy( root ) ) .build(); final Recheck cut = new RecheckImpl( opts ); final RootElement rootElement = mock( RootElement.class ); when( rootElement.getIdentifyingAttributes() ).thenReturn( mock( IdentifyingAttributes.class ) ); final RecheckAdapter adapter = mock( RecheckAdapter.class ); when( adapter.canCheck( any() ) ).thenReturn( true ); when( adapter.convert( any() ) ).thenReturn( Collections.singleton( rootElement ) ); cut.startTest( "some-test" ); cut.check( "to-verify", adapter, "some-step" ); final String goldenMasterName = "SomeTestClass/some-test.some-step.recheck"; assertThatThrownBy( cut::capTest ) .isExactlyInstanceOf( AssertionError.class ) .hasMessageStartingWith( "'SomeTestClass': " + NoGoldenMasterActionReplayResult.MSG_LONG ) .hasMessageEndingWith( goldenMasterName ); } @Test public void headless_no_key_should_result_in_AssertionError() throws Exception { final RecheckOptions opts = RecheckOptions.builder() .enableReportUpload() .build(); mockStatic( Rehub.class ); doThrow( new HeadlessException() ).when( Rehub.class, method( Rehub.class, "init" ) ).withNoArguments(); assertThatThrownBy( () -> new RecheckImpl( opts ) ).isExactlyInstanceOf( AssertionError.class ); } private static class DummyStringRecheckAdapter implements RecheckAdapter { @Override public DefaultValueFinder getDefaultValueFinder() { return null; } @Override public Set<RootElement> convert( final Object arg0 ) { final IdentifyingAttributes identifyingAttributes = mock( IdentifyingAttributes.class ); final RootElement rootElement = mock( RootElement.class ); when( rootElement.getIdentifyingAttributes() ).thenReturn( identifyingAttributes ); return Collections.singleton( rootElement ); } @Override public boolean canCheck( final Object arg0 ) { return false; } } private static class WithinTempDirectoryFileNamerStrategy implements FileNamerStrategy { private final Path root; public WithinTempDirectoryFileNamerStrategy( final Path root ) throws IOException { this.root = root; } @Override public FileNamer createFileNamer( final String... baseNames ) { return new FileNamer() { @Override public File getFile( final String extension ) { return resolveRoot( baseNames, extension ); } @Override public File getResultFile( final String extension ) { return resolveRoot( baseNames, extension ); } }; } private File resolveRoot( final String[] baseNames, final String extension ) { final int last = baseNames.length - 1; final List<String> list = new ArrayList<>( Arrays.asList( baseNames ) ); list.set( last, baseNames[last] + extension ); Path path = root; for ( final String sub : list ) { path = path.resolve( sub ); } return path.toFile(); } @Override public String getTestClassName() { return "SomeTestClass"; } @Override public String getTestMethodName() { return "someTestMethod"; } } }
package hm.binkley.util; import com.google.inject.AbstractModule; import com.google.inject.Key; import com.google.inject.TypeLiteral; import org.junit.Test; import org.kohsuke.MetaInfServices; import javax.inject.Inject; import java.util.HashSet; import java.util.Set; import static com.google.inject.Guice.createInjector; import static com.google.inject.name.Names.named; import static hm.binkley.util.ServiceBinder.with; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /** * {@code ServiceBinderTest} tests {@link ServiceBinder}. * * @author <a href="mailto:binkley@alumni.rice.edu">B. K. Oxley (binkley)</a> * @todo Needs documentation. */ public class ServiceBinderTest { @Test public void shouldBindServices() { final Set<Class<? extends Bob>> found = new HashSet<Class<? extends Bob>>(); for (final Bob bob : createInjector(new TestModule()) .getInstance(Key.get(new TypeLiteral<Set<Bob>>() {}))) found.add(bob.getClass()); final Set<Class<? extends Bob>> expected = new HashSet<Class<? extends Bob>>(); expected.add(Fred.class); expected.add(Nancy.class); assertThat(found, is(equalTo(expected))); } @Test public void shouldInjectServices() { assertThat(createInjector(new TestModule()).getInstance(Nancy.class).test, is(equalTo(this))); } public interface Bob {} @MetaInfServices public static final class Fred implements Bob {} @MetaInfServices public static final class Nancy implements Bob { private final ServiceBinderTest test; @Inject public Nancy(final ServiceBinderTest test) { this.test = test; } } public final class TestModule extends AbstractModule { @Override protected void configure() { bindConstant().annotatedWith(named("cat-name")).to("Felix"); bind(ServiceBinderTest.class).toInstance(ServiceBinderTest.this); with(binder()).bind(Bob.class, Bob.class.getClassLoader()); } } }
package org.neo4j.gis.spatial; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; import org.geotools.data.shapefile.shp.ShapefileException; import org.neo4j.gis.spatial.osm.OSMImporter; import org.neo4j.gis.spatial.query.SearchIntersect; import com.vividsolutions.jts.geom.Envelope; /** * Test cases for initial version of Neo4j-Spatial. This was converted directly from Davide * Savazzi's console applications: ShapefileImporter, Test, Test2 and Test3. * * @author Davide Savazzi * @author Craig Taverner */ public class TestSpatial extends Neo4jTestCase { private final String SHP_DIR = "target/shp"; private final String OSM_DIR = "target/osm"; private enum DataFormat { SHP("ESRI Shapefile"), OSM("OpenStreetMap"); private String description; DataFormat(String description) { this.description = description; } public String toString() { return description; } } /** * This class represents mock objects for representing geometries in simple form in memory for * testing against real geometries. We have a few hard-coded test geometries we expect to find * stored in predictable ways in the test database. Currently we only test for bounding box so * this class only contains that information. * * @author craig * @since 1.0.0 */ private static class TestGeometry { private Integer id; private String name; private String comments; Envelope bounds; public TestGeometry(Integer id, String name, String comments, String bounds) { this.id = id; this.name = name == null ? "" : name; this.comments = comments; float bf[] = new float[4]; int bi = 0; for (String bound : bounds.replaceAll("[\\(\\)\\s]+", "").split(",")) { bf[bi++] = Float.parseFloat(bound); } this.bounds = new Envelope(bf[0], bf[2], bf[1], bf[3]); } public String toString() { return (name.length() > 0 ? name : "ID[" + id + "]") + (comments == null || comments.length() < 1 ? "" : " (" + comments + ")"); } public boolean inOrIntersects(Envelope env) { return env.intersects(bounds); } } private static final ArrayList<String> layers = new ArrayList<String>(); private static final HashMap<String, ArrayList<TestGeometry>> layerTestGeometries = new HashMap<String, ArrayList<TestGeometry>>(); private static final HashMap<String, DataFormat> layerTestFormats = new HashMap<String, DataFormat>(); private static String spatialTestMode; static { // TODO: Rather load this from a configuration file, properties file or JRuby test code addTestLayer("sweden.osm", DataFormat.OSM); addTestLayer("sweden.osm.administrative", DataFormat.OSM); // TODO: Rather load this from a configuration file, properties file or JRuby test code addTestLayer("sweden_administrative", DataFormat.SHP); addTestGeometry(1055, "Söderåsens nationalpark", "near top edge", "(13.167721,56.002416), (13.289724,56.047099)"); addTestGeometry(1067, "", "inside", "(13.2122907,55.6969478), (13.5614499,55.7835819)"); addTestGeometry(943, "", "crosses left edge", "(12.9120438,55.8253138), (13.0501381,55.8484289)"); addTestGeometry(884, "", "outside left", "(12.7492433,55.9269403), (12.9503304,55.964951)"); addTestGeometry(1362, "", "crosses top right", "(13.7453871,55.9483067), (14.0084487,56.1538786)"); addTestGeometry(1521, "", "outside right", "(14.0762394,55.4889569), (14.1869043,55.7592587)"); addTestGeometry(1184, "", "outside above", "(13.4215555,56.109138), (13.4683671,56.2681347)"); addTestLayer("sweden_natural", DataFormat.SHP); addTestGeometry(208, "Bokskogen", "", "(13.1935576,55.5324763), (13.2710125,55.5657891)"); addTestGeometry(6110, "Pålsjö skog", "", "(12.6744031,56.0636946), (12.6934147,56.0771857)"); addTestGeometry(647, "Dalby söderskog", "", "(13.32406,55.671652), (13.336948,55.679243)"); addTestLayer("sweden_water", DataFormat.SHP); addTestGeometry(9548, "Yddingesjön", "", "(13.23564,55.5360264), (13.2676649,55.5558856)"); addTestGeometry(10494, "Finjasjön", "", "(13.6718979,56.1157516), (13.7398759,56.1566911)"); addTestLayer("sweden_highway", DataFormat.SHP); addTestGeometry(58904, "Holmeja byväg", "", "(13.2819022,55.5561414), (13.2820848,55.5575418)"); addTestGeometry(45305, "Yttre RIngvägen", "", "(12.9827334,55.5473645), (13.0118313,55.5480455)"); addTestGeometry(43536, "Yttre RIngvägen", "", "(12.9412071,55.5564264), (12.9422181,55.5571701)"); } private static void addTestLayer(String layer, DataFormat format) { layers.add(layer); layerTestFormats.put(layer, format); layerTestGeometries.put(layer, new ArrayList<TestGeometry>()); } private static void addTestGeometry(Integer id, String name, String comments, String bounds) { String layer = layers.get(layers.size() - 1); ArrayList<TestGeometry> geoms = layerTestGeometries.get(layer); geoms.add(new TestGeometry(id, name, comments, bounds)); } public TestSpatial(String name) { setName(name); } public static Test suite() { spatialTestMode = System.getProperty("spatial.test.mode"); deleteDatabase(); TestSuite suite = new TestSuite(); // suite.addTest(new TestSpatial("testSpatialIndex")); // TODO: Split different layers to different test cases here for nicer control and // visibility String[] layersToTest = null; if (spatialTestMode != null && spatialTestMode.equals("long")) { // Very long running tests layersToTest = new String[] {"sweden.osm", "sweden.osm.administrative", "sweden_administrative", "sweden_natural", "sweden_water", "sweden_highway"}; } else if (spatialTestMode != null && spatialTestMode.equals("short")) { // Tests used for a quick check layersToTest = new String[] {"sweden_administrative"}; } else if (spatialTestMode != null && spatialTestMode.equals("dev")) { // Tests relevant to current development layersToTest = new String[] {"sweden.osm.administrative", "sweden_administrative"}; //layersToTest = new String[] {"sweden_administrative"}; } else { // Tests to run by default for regression (not too long running, and should always pass) layersToTest = new String[] {"sweden.osm.administrative", "sweden_administrative", "sweden_natural", "sweden_water"}; } for (final String layerName : layersToTest) { suite.addTest(new TestSpatial("Test Import of "+layerName) { public void runTest() { try { testImport(layerName); } catch (Exception e) { // assertTrue("Failed to run import test due to exception: " + e, false); throw new RuntimeException(e.getMessage(), e); } } }); suite.addTest(new TestSpatial("Test Spatial Index on "+layerName) { public void runTest() { try { testSpatialIndex(layerName); } catch (Exception e) { // assertTrue("Failed to run import test due to exception: " + e, false); throw new RuntimeException(e.getMessage(), e); } } }); } System.out.println("This suite has " + suite.testCount() + " tests"); for (int i = 0; i < suite.testCount(); i++) { System.out.println("\t" + suite.testAt(i).toString()); } return suite; } public void testBlank() { } protected void setUp() throws Exception { super.setUp(false, false, false); } protected void testImport(String layerName) throws Exception { long start = System.currentTimeMillis(); System.out.println("\n===========\n=========== Import Test: " + layerName + "\n==========="); SpatialDatabaseService spatialService = new SpatialDatabaseService(graphDb()); Layer layer = spatialService.getLayer(layerName); if (layer == null || layer.getIndex() == null || layer.getIndex().count() < 1) { switch (TestSpatial.layerTestFormats.get(layerName)) { case SHP: loadTestShpData(layerName, 1000); break; case OSM: loadTestOsmData(layerName, 1000); break; default: System.err.println("Unknown format: " + layerTestFormats.get(layerName)); } } System.out.println("Total time for load: " + 1.0 * (System.currentTimeMillis() - start) / 1000.0 + "s"); } private void loadTestShpData(String layerName, int commitInterval) throws ShapefileException, FileNotFoundException, IOException { String shpPath = SHP_DIR + File.separator + layerName; System.out.println("\n=== Loading layer " + layerName + " from " + shpPath + " ==="); ShapefileImporter importer = new ShapefileImporter(graphDb(), new NullListener(), commitInterval); importer.importFile(shpPath, layerName); } private void loadTestOsmData(String layerName, int commitInterval) throws Exception { String osmPath = OSM_DIR + File.separator + layerName; System.out.println("\n=== Loading layer " + layerName + " from " + osmPath + " ==="); reActivateDatabase(false, true, false); OSMImporter importer = new OSMImporter(layerName); importer.importFile(getBatchInserter(), osmPath); reActivateDatabase(false, false, false); importer.reIndex(graphDb(), commitInterval); } public void testSpatialIndex(String layerName) { System.out.println("\n=== Spatial Index Test: " + layerName + " ==="); long start = System.currentTimeMillis(); doTestSpatialIndex(layerName); System.out.println("Total time for index test: " + 1.0 * (System.currentTimeMillis() - start) / 1000.0 + "s"); } private void doTestSpatialIndex(String layerName) { SpatialDatabaseService spatialService = new SpatialDatabaseService(graphDb()); Layer layer = spatialService.getLayer(layerName); if (layer == null || layer.getIndex() == null || layer.getIndex().count() < 1) { System.out.println("Layer not loaded: " + layerName); return; } ((RTreeIndex)layer.getIndex()).warmUp(); SpatialIndexReader fakeIndex = new SpatialIndexPerformanceProxy(new FakeIndex(layer)); SpatialIndexReader rtreeIndex = new SpatialIndexPerformanceProxy(layer.getIndex()); System.out.println("FakeIndex bounds: " + fakeIndex.getLayerBoundingBox()); System.out.println("RTreeIndex bounds: " + rtreeIndex.getLayerBoundingBox()); System.out.println("FakeIndex count: " + fakeIndex.count()); System.out.println("RTreeIndex count: " + rtreeIndex.count()); // Bounds for sweden_administrative: 11.1194502 : 24.1585511, 55.3550515 : 69.0600767 Envelope bbox = new Envelope(13.0, 14.00, 55.0, 56.0); // Envelope bbox = new Envelope(7, 10, 37, 40); System.out.println("Displaying test geometries for layer '" + layerName + "'"); for (TestGeometry testData : layerTestGeometries.get(layerName)) { System.out.println("\tGeometry: " + testData.toString() + " " + (testData.inOrIntersects(bbox) ? "is" : "is NOT") + " inside search region"); } Search searchQuery = new SearchIntersect(layer.getGeometryFactory().toGeometry(bbox)); for (SpatialIndexReader index : new SpatialIndexReader[] {fakeIndex, rtreeIndex}) { ArrayList<TestGeometry> foundData = new ArrayList<TestGeometry>(); index.executeSearch(searchQuery); List<SpatialDatabaseRecord> results = searchQuery.getResults(); System.out.println("\tIndex[" + index.getClass() + "] found results: " + results.size()); int ri = 0; for (SpatialDatabaseRecord r : results) { if (ri++ < 10) { StringBuffer props = new StringBuffer(); for (String prop : r.getPropertyNames()) { if(props.length()>0) props.append(", "); props.append(prop + ": " + r.getProperty(prop)); } System.out.println("\tRTreeIndex result[" + ri + "]: " + r.getId() + ":" + r.getType() + " - " + r.toString() + ": PROPS["+props+"]"); } else if (ri == 10) { System.out.println("\t.. and " + (results.size() - ri) + " more .."); } String name = (String)r.getProperty("NAME"); Integer id = (Integer)r.getProperty("ID"); if (name != null && name.length() > 0 || id != null) { for (TestGeometry testData : layerTestGeometries.get(layerName)) { if ((name != null && name.length()>0 && testData.name.equals(name)) || (id != null && testData.id.equals(id))) { System.out.println("\tFound match in test data: test[" + testData + "] == result[" + r + "]"); foundData.add(testData); } } } else { System.err.println("\tNo name or id in RTreeIndex result: " + r.getId() + ":" + r.getType() + " - " + r.toString()); } } System.out.println("Found " + foundData.size() + " test datasets in region[" + bbox + "]"); for (TestGeometry testData : foundData) { System.out.println("\t" + testData + ": " + testData.bounds); } System.out.println("Verifying results for " + layerTestGeometries.size() + " test datasets in region[" + bbox + "]"); for (TestGeometry testData : layerTestGeometries.get(layerName)) { System.out.println("\t" + testData + ": " + testData.bounds); String error = "Incorrect test result: test[" + testData + "] not found by search inside region[" + bbox + "]"; if (testData.inOrIntersects(bbox) && !foundData.contains(testData)) { System.out.println(error); assertTrue(error, false); } } } } }
package org.robolectric.shadows; import android.app.Activity; import android.content.res.TypedArray; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.widget.Button; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.R; import org.robolectric.Robolectric; import org.robolectric.TestRunners; import org.robolectric.res.ResName; import org.robolectric.res.ResourceLoader; import org.robolectric.res.Style; import org.robolectric.util.TestUtil; import static org.fest.assertions.api.Assertions.assertThat; import static org.robolectric.Robolectric.shadowOf; @RunWith(TestRunners.WithDefaults.class) public class ThemeTest { @Test public void whenExplicitlySetOnActivity_activityGetsThemeFromActivityInManifest() throws Exception { TestActivity activity = new TestActivity(); activity.setTheme(R.style.Theme_Robolectric); shadowOf(activity).callOnCreate(null); Button theButton = (Button) activity.findViewById(R.id.button); assertThat(theButton.getBackground()).isEqualTo(new ColorDrawable(0xff00ff00)); } @Test public void whenSetOnActivityInManifest_activityGetsThemeFromActivityInManifest() throws Exception { TestActivity activity = Robolectric.buildActivity(TestActivity.class).create().get(); Button theButton = (Button) activity.findViewById(R.id.button); assertThat(theButton.getBackground()).isEqualTo(new ColorDrawable(0xff00ff00)); } @Test public void whenNotSetOnActivityInManifest_activityGetsThemeFromApplicationInManifest() throws Exception { TestActivity activity = Robolectric.buildActivity(TestActivityWithAnotherTheme.class).create().get(); Button theButton = (Button) activity.findViewById(R.id.button); assertThat(theButton.getBackground()).isEqualTo(new ColorDrawable(0xffff0000)); } @Test public void shouldResolveReferencesThatStartWithAQuestionMark() throws Exception { TestActivity activity = Robolectric.buildActivity(TestActivityWithAnotherTheme.class).create().get(); Button theButton = (Button) activity.findViewById(R.id.button); assertThat(theButton.getMinWidth()).isEqualTo(42); // via AnotherTheme.Button -> logoWidth and logoHeight // assertThat(theButton.getMinHeight()).isEqualTo(42); todo 2.0-cleanup } @Test public void shouldLookUpStylesFromStyleResId() throws Exception { TestActivity activity = Robolectric.buildActivity(TestActivityWithAnotherTheme.class).create().get(); TypedArray a = activity.obtainStyledAttributes(null, R.styleable.CustomView, 0, R.style.MyCustomView); boolean enabled = a.getBoolean(R.styleable.CustomView_aspectRatioEnabled, false); assertThat(enabled).isTrue(); } @Test public void shouldInheritThemeValuesFromImplicitParents() throws Exception { TestActivity activity = Robolectric.buildActivity(TestActivityWithAnotherTheme.class).create().get(); ResourceLoader resourceLoader = Robolectric.shadowOf(activity.getResources()).getResourceLoader(); Style style = ShadowAssetManager.resolveStyle(resourceLoader, new ResName(TestUtil.TEST_PACKAGE, "style", "Widget.AnotherTheme.Button.Blarf"), ""); assertThat(style.getAttrValue(new ResName("android", "attr", "background")).value) .isEqualTo("#ffff0000"); } // @Test public void shouldPerformFastly() throws Exception { // TestActivity activity = Robolectric.buildActivity(TestActivityWithAnotherTheme.class).create().get(); // Class type = type("com.android.internal.R$styleable").withClassLoader(TestActivity.class.getClassLoader()).load(); // int[] styleableIds = field("TextView").ofType(int[].class).in(type).get(); // // once for warm-up // long start = System.currentTimeMillis(); // activity.obtainStyledAttributes(null, styleableIds, 0, R.style.MyCustomView); // System.out.println(String.format("Warm-up took %4dms", System.currentTimeMillis() - start)); // start = System.currentTimeMillis(); // int count = 5000; // for (int i = 0; i < count; i++) { // activity.obtainStyledAttributes(null, styleableIds, 0, R.style.MyCustomView); // System.out.println(String.format("Took %4.1fms", (System.currentTimeMillis() - start) / ((float) count))); public static class TestActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.styles_button_layout); } } public static class TestActivityWithAnotherTheme extends TestActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.styles_button_layout); } } }
package org.jdesktop.swingx; import java.util.Calendar; import java.util.logging.Logger; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFormattedTextField; import javax.swing.JPanel; /** * Known issues of <code>JXDatePicker</code>. * * @author Jeanette Winzenburg */ public class JXDatePickerIssues extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(JXDatePickerIssues.class .getName()); public static void main(String[] args) { // setSystemLF(true); JXDatePickerIssues test = new JXDatePickerIssues(); try { test.runInteractiveTests(); // test.runInteractiveTests(".*Show.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } private Calendar calendar; /** * Issue #565-swingx: occasionally, the popup isn't closed. * to reproduce: open the picker's popup then click into * the comboBox. All is well if click into the textfield. * */ public void interactiveClosePopup() { JXDatePicker picker = new JXDatePicker(); JComboBox box = new JComboBox(new String[] {"one", "twos"}); box.setEditable(true); JComponent panel = new JPanel(); panel.add(picker); panel.add(box); JXFrame frame = showInFrame(panel, "closed?"); // JXRootPane eats esc frame.getRootPaneExt().getActionMap().remove("esc-action"); } /** * Issue #566-swingx: JXRootPane eats picker's popup esc. * to reproduce: open the picker's popup the press esc - * not closed. Same with combo is working. * */ public void interactiveXRootPaneEatsEscape() { JXDatePicker picker = new JXDatePicker(); JComboBox box = new JComboBox(new String[] {"one", "twos"}); box.setEditable(true); JComponent panel = new JPanel(); panel.add(picker); panel.add(box); @SuppressWarnings("unused") JXFrame frame = showInFrame(panel, "closed?"); // JXRootPane eats esc // frame.getRootPaneExt().getActionMap().remove("esc-action"); } /** * compare JFormattedTextField and JXDatePicker pref. * date is slightly cut. Looks like an issue * of the formattedTextField. */ public void interactivePrefSize() { // ListSelectionModel l; // TreeSelectionModel t; JXDatePicker picker = new JXDatePicker(); JFormattedTextField field = new JFormattedTextField(new JXDatePickerFormatter()); field.setValue(picker.getDate()); JComponent panel = new JPanel(); panel.add(picker); panel.add(field); JXFrame frame = showInFrame(panel, "compare pref width"); // JXRootPane eats esc frame.getRootPaneExt().getActionMap().remove("esc-action"); } /** * visual testing of selection constraints: upper/lower bounds. * * Issue #567-swingx: * clicking into a unselectable in the popup clears the * selection - should revert to the last valid selection. */ public void interactiveBounds() { JXDatePicker picker = new JXDatePicker(); calendar.add(Calendar.DAY_OF_MONTH, 10); // access the model directly requires to "clean" the date picker.getMonthView().setUpperBound(calendar.getTimeInMillis()); calendar.add(Calendar.DAY_OF_MONTH, - 20); picker.getMonthView().setLowerBound(calendar.getTimeInMillis()); JXFrame frame = showInFrame(picker, "lower/upper bounds"); frame.pack(); } /** * test that selectionListener is uninstalled. * * Hmm ... missing api or overshooting? */ public void testSelectionListening() { // JXMonthView monthView = new JXMonthView(); // int selectionListenerCount = monthView.getSelectionModel()).getListeners().length; // JXDatePicker picker = new JXDatePicker(); // assertEquals("ui must have installed one listener", selectionListenerCount + 1, // picker.getMonthView().getSelectionModel().getListeners().length); // picker.getUI().uninstallUI(picker); // assertEquals("", selectionListenerCount, // picker.getMonthView().getSelectionModel().getListeners().length); } @Override protected void setUp() throws Exception { calendar = Calendar.getInstance(); } }
/** * This is a combination of our type checker tests. It should cover most * type-valid constructs of our extended language. * * @author Elvis Stansvik <elvstone@gmail.com> */ //EXT:LONG //EXT:IWE //EXT:NBD //EXT:CLE //EXT:CGT //EXT:CGE //EXT:CEQ //EXT:CNE //EXT:BDJ class TypeCheckTest { public static void main(String[] args) { int i; int[] ia; long l; long[] la; boolean b; A cA; A cA1; A cA2; B cB; C cC; // Assignment + new instance/array. i = 42; ia = new int[42]; l = 42; l = 42L; la = new long[42]; b = true; cA = new A(); cA1 = new A(); cA2 = new A(); cB = new B(); cC = new C(); // Operator + i = i + i; l = i + l; l = l + i; l = l + l; // Operator - i = i - i; l = l - i; l = l - l; // Operator * i = i * i; l = i * l; l = l * i; l = l * l; // Operator == if (i == i) {} if (i == l) {} if (ia == ia) {} if (l == i) {} if (l == l) {} if (la == la) {} if (b == b) {} if (cA1 == cA2) {} // Operator != if (i != i) {} if (i != l) {} if (ia != ia) {} if (l != i) {} if (l != l) {} if (la != la) {} if (b != b) {} if (cA != cA) {} // Operator < if (i < i) {} if (i < l) {} if (l < i) {} if (l < l) {} // Operator <= if (i <= i) {} if (i <= l) {} if (l <= i) {} if (l <= l) {} // Operator >= if (i >= i) {} if (i >= l) {} if (l >= i) {} if (l >= l) {} // Operator > if (i > i) {} if (i > l) {} if (l > i) {} if (l > l) {} // Operator &&, || and ! if (b && b) {} if (b || b) {} if (!b) {} // Array access i = ia[i]; l = ia[i]; l = la[i]; // Array assignment ia[i] = i; la[i] = l; la[i] = i; // Array length i = ia.length; i = la.length; // if, if/else and while if (b) { b = false; if (b) b = true; } if (b) { b = false; b = true; } else { b = true; b = false; } if (b) b = false; else if (b) b = true; else b = false; while (b) {} // Integer literals i = 0; i = 42; i = 2147483647; l = 0; l = 42; l = 9223372036854775807l; l = 9223372036854775807L; // Method invocation i = cC.f_i(i); i = cC.f_ia(ia); i = cC.f_l(i); i = cC.f_l(l); i = cC.f_la(la); i = cC.f_b(b); i = cC.f_A(cA); i = cC.f_all(i, ia, l, la, b, cA); // println System.out.println(i); System.out.println(l); } } class A { int r; int a; public int f(int b) { // Variable visibility int c; c = 0; { int d; d = 0; { int e; e = 0; r = a; r = b; r = c; r = d; r = e; } r = a; r = b; r = c; r = d; } r = a; r = b; r = c; return r; } } class B { // Check return type compatibility. public int f1() { return 42; } public int[] f2() { return new int[42]; } public long f3() { return 42; } public long f4() { return 42L; } public long[] f5() { return new long[42]; } public boolean f6() { return true; } public A f7() { return new A(); } } class C { // Methods invoked from TypeCheckTest. public int f_i(int a) { return 1; } public int f_ia(int[] a) { return 1; } public int f_l(long a) { return 1; } public int f_la(long[] a) { return 1; } public int f_b(boolean a) { return 1; } public int f_A(A a) { return 1; } public int f_all(int a, int[] b, long c, long[] d, boolean e, A f) { return 1; } }
package wicket.util.lang; import java.io.Serializable; import wicket.WicketTestCase; import wicket.markup.html.form.TextField; import wicket.model.Model; import wicket.model.PropertyModel; /** * Tests the Objects class. * * @author Martijn Dashorst */ public class ObjectsTest extends WicketTestCase { public ObjectsTest(String name) { super(name); } /** * Test method for 'wicket.util.lang.Objects.equal(Object, Object)' */ public void testEqual() { Object object = new Object(); assertTrue(Objects.equal(object, object)); assertFalse(Objects.equal(null, object)); assertFalse(Objects.equal(object, null)); assertTrue(Objects.equal(null, null)); assertFalse(Objects.equal(new Object(), new Object())); assertTrue(Objects.equal(new Integer(1), new Integer(1))); assertFalse(Objects.equal("1", new Integer(1))); assertFalse(Objects.equal(new Integer(1), "1")); assertTrue(Objects.equal("1", new Integer(1).toString())); assertTrue(Objects.equal(new Integer(1).toString(), "1")); } /** * Test method for 'wicket.util.lang.Objects.clone(Object)' */ public void testCloneNull() { Object clone = Objects.clone(null); assertEquals(null, clone); } /** * Test method for 'wicket.util.lang.Objects.clone(Object)' */ public void testCloneString() { String cloneMe = "Mini-me"; Object clone = Objects.clone(cloneMe); assertEquals(cloneMe, clone); assertNotSame(cloneMe, clone); } /** * Test method for 'wicket.util.lang.Objects.clone(Object)' */ public void testCloneObject() { Object cloneMe = new Object(); try { Objects.clone(cloneMe); fail("Exception expected"); } catch (RuntimeException e) { assertTrue(true); } } /** * Test method for component cloning */ public void testComponentClone() { PropertyModel pm = new PropertyModel(new TextField("test", new Model("test")),"modelObject"); PropertyModel pm2= (PropertyModel)Objects.clone(pm); assertTrue(pm.getObject(null) == pm2.getObject(null)); } /** * Test method for 'wicket.util.lang.Objects.clone(Object)' */ public void testCloneCloneObject() { CloneObject cloneMe = new CloneObject(); cloneMe.nr = 1; Object clone = Objects.clone(cloneMe); assertEquals(cloneMe, clone); assertNotSame(cloneMe, clone); } /** * Used for testing the clone function. */ private static final class CloneObject implements Serializable { private static final long serialVersionUID = 1L; /** * int for testing equality. */ private int nr; /** * @see Object#equals(java.lang.Object) */ public boolean equals(Object o) { CloneObject other = (CloneObject)o; return other.nr == nr; } } }
package uk.ac.ed.inf.Metabolic.ndomAPI; public interface IModelObject { public String getId(); public String getName(); public String getASCIIName(); public String getDescription(); public String getDetailedDescription(); }
package uk.co.eluinhost.ultrahardcore; import org.bukkit.Bukkit; import org.bukkit.command.PluginCommand; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.serialization.ConfigurationSerialization; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; import uk.co.eluinhost.commands.CommandHandler; import uk.co.eluinhost.ultrahardcore.commands.ClearInventoryCommand; import uk.co.eluinhost.ultrahardcore.commands.FeatureCommand; import uk.co.eluinhost.ultrahardcore.commands.HealCommand; import uk.co.eluinhost.ultrahardcore.commands.TPCommand; import uk.co.eluinhost.ultrahardcore.config.ConfigManager; import uk.co.eluinhost.ultrahardcore.config.ConfigNodes; import uk.co.eluinhost.ultrahardcore.exceptions.features.FeatureIDConflictException; import uk.co.eluinhost.ultrahardcore.exceptions.features.InvalidFeatureIDException; import uk.co.eluinhost.ultrahardcore.exceptions.scatter.ScatterTypeConflictException; import uk.co.eluinhost.ultrahardcore.features.FeatureManager; import uk.co.eluinhost.ultrahardcore.features.anonchat.AnonChatFeature; import uk.co.eluinhost.ultrahardcore.features.deathbans.DeathBan; import uk.co.eluinhost.ultrahardcore.features.deathbans.DeathBansFeature; import uk.co.eluinhost.ultrahardcore.features.deathdrops.DeathDropsFeature; import uk.co.eluinhost.ultrahardcore.features.deathlightning.DeathLightningFeature; import uk.co.eluinhost.ultrahardcore.features.deathmessages.DeathMessagesFeature; import uk.co.eluinhost.ultrahardcore.features.enderpearls.EnderpearlsFeature; import uk.co.eluinhost.ultrahardcore.features.footprints.FootprintFeature; import uk.co.eluinhost.ultrahardcore.features.ghastdrops.GhastDropsFeature; import uk.co.eluinhost.ultrahardcore.features.goldenheads.GoldenHeadsFeature; import uk.co.eluinhost.ultrahardcore.features.hardcorehearts.HardcoreHeartsFeature; import uk.co.eluinhost.ultrahardcore.features.nether.NetherFeature; import uk.co.eluinhost.ultrahardcore.features.playerheads.PlayerHeadsFeature; import uk.co.eluinhost.ultrahardcore.features.playerlist.PlayerListFeature; import uk.co.eluinhost.ultrahardcore.features.portals.PortalsFeature; import uk.co.eluinhost.ultrahardcore.features.potionnerfs.PotionNerfsFeature; import uk.co.eluinhost.ultrahardcore.features.recipes.RecipeFeature; import uk.co.eluinhost.ultrahardcore.features.regen.RegenFeature; import uk.co.eluinhost.ultrahardcore.features.witchspawns.WitchSpawnsFeature; import uk.co.eluinhost.ultrahardcore.metrics.MetricsLite; import uk.co.eluinhost.ultrahardcore.scatter.ScatterManager; import uk.co.eluinhost.ultrahardcore.scatter.types.EvenCircumferenceType; import uk.co.eluinhost.ultrahardcore.scatter.types.RandomCircularType; import uk.co.eluinhost.ultrahardcore.scatter.types.RandomSquareType; import java.io.IOException; import java.util.logging.Logger; /** * UltraHardcore * <p/> * Main plugin class, init * * @author ghowden */ public class UltraHardcore extends JavaPlugin implements Listener { /** * @return the current instance of the plugin */ public static UltraHardcore getInstance() { return (UltraHardcore) Bukkit.getServer().getPluginManager().getPlugin("UltraHardcore"); } //When the plugin gets started @Override public void onEnable() { //register deathbans for serilization ConfigurationSerialization.registerClass(DeathBan.class); //register the bungeecord plugin channel getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); //load all the configs loadDefaultConfigurations(); //load all the features loadDefaultFeatures(); //load all the scatter types loadDefaultScatterTypes(); //load all the commands loadDefaultCommands(); //Load all the metric infos try { MetricsLite met = new MetricsLite(this); met.start(); } catch (IOException ignored) { } } /** * Load all the default commands */ private void loadDefaultCommands() { CommandHandler commandHandler = CommandHandler.getInstance(); Class[] classes = { HealCommand.class, ClearInventoryCommand.class, TPCommand.class, FeatureCommand.class }; for(Class clazz : classes){ try { commandHandler.registerCommands(clazz); } catch (@SuppressWarnings("OverlyBroadCatchBlock") Exception e) { e.printStackTrace(); } } String[] baseCommands = { "heal", "feed", "tpp", "ci", "ciself", "deathban", "randomteams", "clearteams", "listteams", "createteam", "removeteam", "jointeam", "leaveteam", "emptyteams", "scatter", "freeze", "feature", "generateborder", "givedrops", "timer" }; for(String com : baseCommands){ setExecutor(com); } } /** * Set the command name given's executor to our command handler * @param commandName the command name * TODO this should be in the command framework */ private void setExecutor(String commandName) { CommandHandler handler = CommandHandler.getInstance(); PluginCommand pc = getCommand(commandName); if (pc == null) { getLogger().warning("Plugin failed to register the command " + commandName + ", is the command already taken?"); } else { pc.setExecutor(handler); pc.setTabCompleter(handler); } } /** * Load all the default features into the feature manager */ @SuppressWarnings("OverlyCoupledMethod") public static void loadDefaultFeatures() { Logger log = Bukkit.getLogger(); log.info("Loading UHC feature modules..."); //Load the default features with settings in config FeatureManager featureManager = FeatureManager.getInstance(); FileConfiguration config = ConfigManager.getInstance().getConfig(); try { featureManager.addFeature(new DeathLightningFeature(), config.getBoolean(ConfigNodes.DEATH_LIGHTNING)); featureManager.addFeature(new EnderpearlsFeature(), config.getBoolean(ConfigNodes.NO_ENDERPEARL_DAMAGE)); featureManager.addFeature(new GhastDropsFeature(), config.getBoolean(ConfigNodes.GHAST_DROP_CHANGES)); featureManager.addFeature(new PlayerHeadsFeature(), config.getBoolean(ConfigNodes.DROP_PLAYER_HEAD)); featureManager.addFeature(new PlayerListFeature(), config.getBoolean(ConfigNodes.PLAYER_LIST_HEALTH)); featureManager.addFeature(new RecipeFeature(), config.getBoolean(ConfigNodes.RECIPE_CHANGES)); featureManager.addFeature(new RegenFeature(), config.getBoolean(ConfigNodes.NO_HEALTH_REGEN)); featureManager.addFeature(new DeathMessagesFeature(), config.getBoolean(ConfigNodes.DEATH_MESSAGES_ENABLED)); featureManager.addFeature(new DeathDropsFeature(), config.getBoolean(ConfigNodes.DEATH_DROPS_ENABLED)); featureManager.addFeature(new AnonChatFeature(), config.getBoolean(ConfigNodes.ANON_CHAT_ENABLED)); featureManager.addFeature(new GoldenHeadsFeature(), config.getBoolean(ConfigNodes.GOLDEN_HEADS_ENABLED)); featureManager.addFeature(new DeathBansFeature(), config.getBoolean(ConfigNodes.DEATH_BANS_ENABLED)); featureManager.addFeature(new PotionNerfsFeature(), config.getBoolean(ConfigNodes.POTION_NERFS_ENABLED)); featureManager.addFeature(new NetherFeature(), config.getBoolean(ConfigNodes.NETHER_DISABLE_ENABELD)); featureManager.addFeature(new WitchSpawnsFeature(), config.getBoolean(ConfigNodes.WITCH_SPAWNS_ENABLED)); featureManager.addFeature(new PortalsFeature(), config.getBoolean(ConfigNodes.PORTAL_RANGES_ENABLED)); //load the protocollib features last featureManager.addFeature(new HardcoreHeartsFeature(), config.getBoolean(ConfigNodes.HARDCORE_HEARTS_ENABLED)); featureManager.addFeature(new FootprintFeature(), config.getBoolean(ConfigNodes.FOOTPRINTS_ENABLED)); } catch (FeatureIDConflictException ignored) { log.severe("A default UHC Feature ID is conflicting, this should never happen!"); } catch (InvalidFeatureIDException ignored) { log.severe("A default UHC feature ID is invalid, this should never happen!"); } catch (NoClassDefFoundError ignored) { log.severe("Couldn't find protocollib for related features, skipping them all."); } } /** * Add the default config files */ public static void loadDefaultConfigurations(){ ConfigManager configManager = ConfigManager.getInstance(); configManager.addConfiguration("main", ConfigManager.getFromFile("main.yml", true)); configManager.addConfiguration("bans", ConfigManager.getFromFile("bans.yml", true)); } /** * Load the default scatter types */ public static void loadDefaultScatterTypes(){ ScatterManager scatterManager = ScatterManager.getInstance(); try { scatterManager.addScatterType(new EvenCircumferenceType()); scatterManager.addScatterType(new RandomCircularType()); scatterManager.addScatterType(new RandomSquareType()); } catch (ScatterTypeConflictException ignored) { Bukkit.getLogger().severe("Conflict error when loading default scatter types!"); } } }
package weave.servlets; import static weave.config.WeaveConfig.getConnectionConfig; import static weave.config.WeaveConfig.getDataConfig; import static weave.config.WeaveConfig.initWeaveConfig; import java.rmi.RemoteException; import java.security.InvalidParameterException; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpSession; import org.postgis.Geometry; import org.postgis.PGgeometry; import org.postgis.Point; import weave.beans.AttributeColumnData; import weave.beans.GeometryStreamMetadata; import weave.beans.PGGeom; import weave.beans.TableData; import weave.beans.WeaveJsonDataSet; import weave.beans.WeaveRecordList; import weave.config.ConnectionConfig.ConnectionInfo; import weave.config.ConnectionConfig.WeaveAuthenticationException; import weave.config.ConnectionConfig; import weave.config.DataConfig; import weave.config.WeaveConfig; import weave.config.DataConfig.DataEntity; import weave.config.DataConfig.DataEntityMetadata; import weave.config.DataConfig.DataEntityWithRelationships; import weave.config.DataConfig.DataType; import weave.config.DataConfig.EntityHierarchyInfo; import weave.config.DataConfig.EntityType; import weave.config.DataConfig.PrivateMetadata; import weave.config.DataConfig.PublicMetadata; import weave.config.WeaveContextParams; import weave.geometrystream.SQLGeometryStreamReader; import weave.utils.CSVParser; import weave.utils.ListUtils; import weave.utils.MapUtils; import weave.utils.SQLResult; import weave.utils.SQLUtils; import weave.utils.SQLUtils.WhereClause; import weave.utils.SQLUtils.WhereClause.ColumnFilter; import weave.utils.SQLUtils.WhereClause.NestedColumnFilters; import weave.utils.Strings; /** * This class connects to a database and gets data * uses xml configuration file to get connection/query info * * @author Andy Dufilie */ public class DataService extends WeaveServlet implements IWeaveEntityService { private static final long serialVersionUID = 1L; public static final int MAX_COLUMN_REQUEST_COUNT = 100; public DataService() { } public void init(ServletConfig config) throws ServletException { super.init(config); initWeaveConfig(WeaveContextParams.getInstance(config.getServletContext())); } public void destroy() { SQLUtils.staticCleanup(); } // Authentication private static final String SESSION_USERNAME = "DataService.user"; private static final String SESSION_PASSWORD = "DataService.pass"; /** * @param user * @param password * @return true if the user has superuser privileges. * @throws RemoteException If authentication fails. */ public void authenticate(String username, String password) throws RemoteException { ConnectionConfig connConfig = getConnectionConfig(); ConnectionInfo info = connConfig.getConnectionInfo(ConnectionInfo.DIRECTORY_SERVICE, username, password); if (info == null) throw new RemoteException("Incorrect username or password"); HttpSession session = getServletRequestInfo().request.getSession(true); session.setAttribute(SESSION_USERNAME, username); session.setAttribute(SESSION_PASSWORD, password); } /** * Gets static, read-only connection from a ConnectionInfo object using pass-through authentication if necessary. * @param connInfo * @return * @throws RemoteException */ private Connection getStaticReadOnlyConnection(ConnectionInfo connInfo) throws RemoteException { if (connInfo.requiresAuthentication()) { HttpSession session = getServletRequestInfo().request.getSession(true); String user = (String)session.getAttribute(SESSION_USERNAME); String pass = (String)session.getAttribute(SESSION_PASSWORD); connInfo = getConnectionConfig().getConnectionInfo(connInfo.name, user, pass); if (connInfo == null) throw new WeaveAuthenticationException("Incorrect username or password"); } return connInfo.getStaticReadOnlyConnection(); } // helper functions private DataEntity getColumnEntity(int columnId) throws RemoteException { DataEntity entity = getDataConfig().getEntity(columnId); if (entity == null) throw new RemoteException("No column with id " + columnId); String entityType = entity.publicMetadata.get(PublicMetadata.ENTITYTYPE); if (!Strings.equal(entityType, EntityType.COLUMN)) throw new RemoteException(String.format("Entity with id=%s is not a column (entityType: %s)", columnId, entityType)); return entity; } private void assertColumnHasPrivateMetadata(DataEntity columnEntity, String ... fields) throws RemoteException { for (String field : fields) { if (Strings.isEmpty(columnEntity.privateMetadata.get(field))) { String dataType = columnEntity.publicMetadata.get(PublicMetadata.DATATYPE); String description = (dataType != null && dataType.equals(DataType.GEOMETRY)) ? "Geometry column" : "Column"; throw new RemoteException(String.format("%s %s is missing private metadata %s", description, columnEntity.id, field)); } } } private boolean assertStreamingGeometryColumn(DataEntity entity, boolean throwException) throws RemoteException { try { String dataType = entity.publicMetadata.get(PublicMetadata.DATATYPE); if (dataType == null || !dataType.equals(DataType.GEOMETRY)) throw new RemoteException(String.format("Column %s dataType is %s, not %s", entity.id, dataType, DataType.GEOMETRY)); assertColumnHasPrivateMetadata(entity, PrivateMetadata.CONNECTION, PrivateMetadata.SQLSCHEMA, PrivateMetadata.SQLTABLEPREFIX); return true; } catch (RemoteException e) { if (throwException) throw e; return false; } } // Server info public Map<String,Object> getServerInfo() throws RemoteException { ConnectionConfig connConfig = getConnectionConfig(); HttpSession session = getServletRequestInfo().request.getSession(true); String username = (String)session.getAttribute(SESSION_USERNAME); return MapUtils.fromPairs( "version", WeaveConfig.getVersion(), "authenticatedUser", username, "hasDirectoryService", connConfig.getConnectionInfo(ConnectionInfo.DIRECTORY_SERVICE) != null, "idFields", connConfig.getDatabaseConfigInfo().idFields ); } // DataEntity info public EntityHierarchyInfo[] getHierarchyInfo(Map<String,String> publicMetadata) throws RemoteException { return getDataConfig().getEntityHierarchyInfo(publicMetadata); } public DataEntityWithRelationships[] getEntities(int[] ids) throws RemoteException { if (ids.length > DataConfig.MAX_ENTITY_REQUEST_COUNT) throw new RemoteException(String.format("You cannot request more than %s entities at a time.", DataConfig.MAX_ENTITY_REQUEST_COUNT)); // prevent user from receiving private metadata return getDataConfig().getEntitiesWithRelationships(ids, false); } public int[] findEntityIds(Map<String,String> publicMetadata, String[] wildcardFields) throws RemoteException { int[] ids = ListUtils.toIntArray( getDataConfig().searchPublicMetadata(publicMetadata, wildcardFields) ); Arrays.sort(ids); return ids; } public String[] findPublicFieldValues(String fieldName, String valueSearch) throws RemoteException { throw new RemoteException("Not implemented yet"); } // Columns private static ConnectionInfo getColumnConnectionInfo(DataEntity entity) throws RemoteException { String connName = entity.privateMetadata.get(PrivateMetadata.CONNECTION); ConnectionConfig connConfig = getConnectionConfig(); ConnectionInfo connInfo = connConfig.getConnectionInfo(connName); if (connInfo == null) { String title = entity.publicMetadata.get(PublicMetadata.TITLE); throw new RemoteException(String.format("Connection named '%s' associated with column #%s (%s) no longer exists", connName, entity.id, title)); } return connInfo; } /** * This retrieves the data and the public metadata for a single attribute column. * @param columnId Either an entity ID (int) or a Map specifying public metadata values that uniquely identify a column. * @param minParam Used for filtering numeric data * @param maxParam Used for filtering numeric data * @param sqlParams Specifies parameters to be used in place of '?' placeholders that appear in the SQL query for the column. * @return The column data. * @throws RemoteException */ @SuppressWarnings("unchecked") public AttributeColumnData getColumn(Object columnId, double minParam, double maxParam, Object[] sqlParams) throws RemoteException { DataEntity entity = null; if (columnId instanceof Map) { @SuppressWarnings({ "rawtypes" }) Map metadata = (Map)columnId; metadata.put(PublicMetadata.ENTITYTYPE, EntityType.COLUMN); int[] ids = findEntityIds(metadata, null); if (ids.length == 0) throw new RemoteException("No column with id " + columnId); if (ids.length > 1) throw new RemoteException(String.format( "The specified metadata does not uniquely identify a column (%s matching columns found): %s", ids.length, columnId )); entity = getColumnEntity(ids[0]); } else { columnId = cast(columnId, Integer.class); entity = getColumnEntity((Integer)columnId); } // if it's a geometry column, just return the metadata if (assertStreamingGeometryColumn(entity, false)) { GeometryStreamMetadata gsm = (GeometryStreamMetadata) getGeometryData(entity, GeomStreamComponent.TILE_DESCRIPTORS, null); AttributeColumnData result = new AttributeColumnData(); result.id = entity.id; result.metadata = entity.publicMetadata; result.metadataTileDescriptors = gsm.metadataTileDescriptors; result.geometryTileDescriptors = gsm.geometryTileDescriptors; return result; } //TODO - check if entity is a table String query = entity.privateMetadata.get(PrivateMetadata.SQLQUERY); int tableId = DataConfig.NULL; String tableField = null; if (Strings.isEmpty(query)) { String entityType = entity.publicMetadata.get(PublicMetadata.ENTITYTYPE); tableField = entity.privateMetadata.get(PrivateMetadata.SQLCOLUMN); if (!Strings.equal(entityType, EntityType.COLUMN)) throw new RemoteException(String.format("Entity %s has no sqlQuery and is not a column (entityType=%s)", entity.id, entityType)); if (Strings.isEmpty(tableField)) throw new RemoteException(String.format("Entity %s has no sqlQuery and no sqlColumn private metadata", entity.id)); // if there's no query, the query lives in the table entity instead of the column entity DataConfig config = getDataConfig(); List<Integer> parentIds = config.getParentIds(entity.id); Map<Integer, String> idToType = config.getEntityTypes(parentIds); for (int id : parentIds) { if (Strings.equal(idToType.get(id), EntityType.TABLE)) { tableId = id; break; } } } String dataType = entity.publicMetadata.get(PublicMetadata.DATATYPE); ConnectionInfo connInfo = getColumnConnectionInfo(entity); List<String> keys = null; List<Double> numericData = null; List<String> stringData = null; List<Object> thirdColumn = null; // hack for dimension slider format List<PGGeom> geometricData = null; if (!Strings.isEmpty(query)) { keys = new ArrayList<String>(); ////// begin MIN/MAX code // use config min,max or param min,max to filter the data double minValue = Double.NaN; double maxValue = Double.NaN; // server min,max values take priority over user-specified params if (entity.publicMetadata.containsKey(PublicMetadata.MIN)) { try { minValue = Double.parseDouble(entity.publicMetadata.get(PublicMetadata.MIN)); } catch (Exception e) { } } else { minValue = minParam; } if (entity.publicMetadata.containsKey(PublicMetadata.MAX)) { try { maxValue = Double.parseDouble(entity.publicMetadata.get(PublicMetadata.MAX)); } catch (Exception e) { } } else { maxValue = maxParam; } if (Double.isNaN(minValue)) minValue = Double.NEGATIVE_INFINITY; if (Double.isNaN(maxValue)) maxValue = Double.POSITIVE_INFINITY; ////// end MIN/MAX code try { Connection conn = getStaticReadOnlyConnection(connInfo); // use default sqlParams if not specified by query params if (sqlParams == null || sqlParams.length == 0) { String sqlParamsString = entity.privateMetadata.get(PrivateMetadata.SQLPARAMS); sqlParams = CSVParser.defaultParser.parseCSVRow(sqlParamsString, true); } SQLResult result = SQLUtils.getResultFromQuery(conn, query, sqlParams, false); // if dataType is defined in the config file, use that value. // otherwise, derive it from the sql result. if (Strings.isEmpty(dataType)) { dataType = DataType.fromSQLType(result.columnTypes[1]); entity.publicMetadata.put(PublicMetadata.DATATYPE, dataType); // fill in missing metadata for the client } if (dataType.equalsIgnoreCase(DataType.NUMBER)) // special case: "number" => Double { numericData = new LinkedList<Double>(); } else if (dataType.equalsIgnoreCase(DataType.GEOMETRY)) { geometricData = new LinkedList<PGGeom>(); } else { stringData = new LinkedList<String>(); } // hack for dimension slider format if (result.columnTypes.length == 3) thirdColumn = new LinkedList<Object>(); Object keyObj, dataObj; double value; for (int i = 0; i < result.rows.length; i++) { keyObj = result.rows[i][0]; if (keyObj == null) continue; dataObj = result.rows[i][1]; if (dataObj == null) continue; if (numericData != null) { try { if (dataObj instanceof String) dataObj = Double.parseDouble((String)dataObj); value = ((Number)dataObj).doubleValue(); } catch (Exception e) { continue; } // filter the data based on the min,max values if (minValue <= value && value <= maxValue) numericData.add(value); else continue; } else if (geometricData != null) { // The dataObj must be cast to PGgeometry before an individual Geometry can be extracted. if (!(dataObj instanceof PGgeometry)) continue; Geometry geom = ((PGgeometry) dataObj).getGeometry(); int numPoints = geom.numPoints(); // Create PGGeom Bean here and fill it up! PGGeom bean = new PGGeom(); bean.type = geom.getType(); bean.xyCoords = new double[numPoints * 2]; for (int j = 0; j < numPoints; j++) { Point pt = geom.getPoint(j); bean.xyCoords[j * 2] = pt.x; bean.xyCoords[j * 2 + 1] = pt.y; } geometricData.add(bean); } else { stringData.add(dataObj.toString()); } // if we got here, it means a data value was added, so add the corresponding key keys.add(keyObj.toString()); // hack for dimension slider format if (thirdColumn != null) thirdColumn.add(result.rows[i][2]); } } catch (SQLException e) { System.err.println(query); e.printStackTrace(); throw new RemoteException(String.format("Unable to retrieve data for column %s", columnId)); } catch (NullPointerException e) { e.printStackTrace(); throw new RemoteException("Unexpected error", e); } } AttributeColumnData result = new AttributeColumnData(); result.id = entity.id; result.tableId = tableId; result.tableField = tableField; result.metadata = entity.publicMetadata; if (keys != null) result.keys = keys.toArray(new String[keys.size()]); if (numericData != null) result.data = numericData.toArray(); else if (geometricData != null) result.data = geometricData.toArray(); else if (stringData != null) result.data = stringData.toArray(); // hack for dimension slider if (thirdColumn != null) result.thirdColumn = thirdColumn.toArray(); return result; } public TableData getTable(int id, Object[] sqlParams) throws RemoteException { DataEntity entity = getDataConfig().getEntity(id); ConnectionInfo connInfo = getColumnConnectionInfo(entity); String query = entity.privateMetadata.get(PrivateMetadata.SQLQUERY); Map<String, Object[]> data = new HashMap<String, Object[]>(); try { Connection conn = getStaticReadOnlyConnection(connInfo); // use default sqlParams if not specified by query params if (sqlParams == null || sqlParams.length == 0) { String sqlParamsString = entity.privateMetadata.get(PrivateMetadata.SQLPARAMS); sqlParams = CSVParser.defaultParser.parseCSVRow(sqlParamsString, true); } SQLResult result = SQLUtils.getResultFromQuery(conn, query, sqlParams, false); // transpose int iColCount = result.columnNames.length; int iRowCount = result.rows.length; for (int iCol = 0; iCol < iColCount; iCol++) { Object[] column = new Object[result.rows.length]; for (int iRow = 0; iRow < iRowCount; iRow++) column[iRow] = result.rows[iRow][iCol]; data.put(result.columnNames[iCol], column); } } catch (SQLException e) { System.err.println(query); e.printStackTrace(); throw new RemoteException(String.format("Unable to retrieve data for table %s", id)); } catch (NullPointerException e) { e.printStackTrace(); throw new RemoteException("Unexpected error", e); } TableData result = new TableData(); result.id = id; result.keyColumn = entity.privateMetadata.get(PrivateMetadata.SQLKEYCOLUMN); result.columns = data; return result; } /** * This function is intended for use with JsonRPC calls. * @param columnIds A list of column IDs. * @return A WeaveJsonDataSet containing all the data from the columns. * @throws RemoteException */ public WeaveJsonDataSet getDataSet(int[] columnIds) throws RemoteException { if (columnIds == null) columnIds = new int[0]; if (columnIds.length > MAX_COLUMN_REQUEST_COUNT) throw new RemoteException(String.format("You cannot request more than %s columns at a time.", MAX_COLUMN_REQUEST_COUNT)); WeaveJsonDataSet result = new WeaveJsonDataSet(); for (Integer columnId : columnIds) { try { AttributeColumnData columnData = getColumn(columnId, Double.NaN, Double.NaN, null); result.addColumnData(columnData); } catch (RemoteException e) { e.printStackTrace(); } } return result; } // geometry columns public byte[] getGeometryStreamMetadataTiles(int columnId, int[] tileIDs) throws RemoteException { DataEntity entity = getColumnEntity(columnId); if (tileIDs == null || tileIDs.length == 0) throw new RemoteException("At least one tileID must be specified."); return (byte[]) getGeometryData(entity, GeomStreamComponent.METADATA_TILES, tileIDs); } public byte[] getGeometryStreamGeometryTiles(int columnId, int[] tileIDs) throws RemoteException { DataEntity entity = getColumnEntity(columnId); if (tileIDs == null || tileIDs.length == 0) throw new RemoteException("At least one tileID must be specified."); return (byte[]) getGeometryData(entity, GeomStreamComponent.GEOMETRY_TILES, tileIDs); } private static enum GeomStreamComponent { TILE_DESCRIPTORS, METADATA_TILES, GEOMETRY_TILES }; private Object getGeometryData(DataEntity entity, GeomStreamComponent component, int[] tileIDs) throws RemoteException { assertStreamingGeometryColumn(entity, true); Connection conn = getStaticReadOnlyConnection(getColumnConnectionInfo(entity)); String schema = entity.privateMetadata.get(PrivateMetadata.SQLSCHEMA); String tablePrefix = entity.privateMetadata.get(PrivateMetadata.SQLTABLEPREFIX); try { switch (component) { case TILE_DESCRIPTORS: GeometryStreamMetadata result = new GeometryStreamMetadata(); result.metadataTileDescriptors = SQLGeometryStreamReader.getMetadataTileDescriptors(conn, schema, tablePrefix); result.geometryTileDescriptors = SQLGeometryStreamReader.getGeometryTileDescriptors(conn, schema, tablePrefix); return result; case METADATA_TILES: return SQLGeometryStreamReader.getMetadataTiles(conn, schema, tablePrefix, tileIDs); case GEOMETRY_TILES: return SQLGeometryStreamReader.getGeometryTiles(conn, schema, tablePrefix, tileIDs); default: throw new InvalidParameterException("Invalid GeometryStreamComponent param."); } } catch (Exception e) { e.printStackTrace(); throw new RemoteException(String.format("Unable to read geometry data (id=%s)", entity.id)); } } // Row query public WeaveRecordList getRows(String keyType, String[] keysArray) throws RemoteException { DataConfig dataConfig = getDataConfig(); DataEntityMetadata params = new DataEntityMetadata(); params.setPublicValues( PublicMetadata.ENTITYTYPE, EntityType.COLUMN, PublicMetadata.KEYTYPE, keyType ); List<Integer> columnIds = new ArrayList<Integer>( dataConfig.searchPublicMetadata(params.publicMetadata, null) ); if (columnIds.size() > MAX_COLUMN_REQUEST_COUNT) columnIds = columnIds.subList(0, MAX_COLUMN_REQUEST_COUNT); return DataService.getFilteredRows(ListUtils.toIntArray(columnIds), null, keysArray); } /** * Gets all column IDs referenced by this object and its nested objects. */ private static Collection<Integer> getReferencedColumnIds(NestedColumnFilters filters) { Set<Integer> ids = new HashSet<Integer>(); if (filters.cond != null) ids.add(((Number)filters.cond.f).intValue()); else for (NestedColumnFilters nested : (filters.and != null ? filters.and : filters.or)) ids.addAll(getReferencedColumnIds(nested)); return ids; } /** * Converts nested ColumnFilter.f values from a column ID to the corresponding SQL field name. * @param filters * @param entities * @return A copy of filters with field names in place of the column IDs. * @see ColumnFilter#f */ private static NestedColumnFilters convertColumnIdsToFieldNames(NestedColumnFilters filters, Map<Integer, DataEntity> entities) { if (filters == null) return null; NestedColumnFilters result = new NestedColumnFilters(); if (filters.cond != null) { result.cond = new ColumnFilter(); result.cond.v = filters.cond.v; result.cond.r = filters.cond.r; result.cond.f = entities.get(((Number)filters.cond.f).intValue()).privateMetadata.get(PrivateMetadata.SQLCOLUMN); } else { NestedColumnFilters[] in = (filters.and != null ? filters.and : filters.or); NestedColumnFilters[] out = new NestedColumnFilters[in.length]; for (int i = 0; i < in.length; i++) out[i] = convertColumnIdsToFieldNames(in[i], entities); if (filters.and == in) result.and = out; else result.or = out; } return result; } private static SQLResult getFilteredRowsFromSQL(Connection conn, String schema, String table, int[] columns, NestedColumnFilters filters, Map<Integer,DataEntity> entities) throws SQLException { String[] quotedFields = new String[columns.length]; for (int i = 0; i < columns.length; i++) quotedFields[i] = SQLUtils.quoteSymbol(conn, entities.get(columns[i]).privateMetadata.get(PrivateMetadata.SQLCOLUMN)); WhereClause<Object> where = WhereClause.fromFilters(conn, convertColumnIdsToFieldNames(filters, entities)); String query = String.format( "SELECT %s FROM %s %s", Strings.join(",", quotedFields), SQLUtils.quoteSchemaTable(conn, schema, table), where.clause ); return SQLUtils.getResultFromQuery(conn, query, where.params.toArray(), false); } @SuppressWarnings("unchecked") public static WeaveRecordList getFilteredRows(int[] columns, NestedColumnFilters filters, String[] keysArray) throws RemoteException { if (columns == null || columns.length == 0) throw new RemoteException("At least one column must be specified."); if (filters != null) filters.assertValid(); DataConfig dataConfig = getDataConfig(); WeaveRecordList result = new WeaveRecordList(); Map<Integer, DataEntity> entityLookup = new HashMap<Integer, DataEntity>(); { // get all column IDs whether or not they are to be selected. Set<Integer> allColumnIds = new HashSet<Integer>(); if (filters != null) allColumnIds.addAll(getReferencedColumnIds(filters)); for (int id : columns) allColumnIds.add(id); // get all corresponding entities for (DataEntity entity : dataConfig.getEntities(allColumnIds, true)) entityLookup.put(entity.id, entity); // check for missing columns for (int id : allColumnIds) if (entityLookup.get(id) == null) throw new RemoteException("No column with ID=" + id); // provide public metadata in the same order as the selected columns result.attributeColumnMetadata = new Map[columns.length]; for (int i = 0; i < columns.length; i++) result.attributeColumnMetadata[i] = entityLookup.get(columns[i]).publicMetadata; } String keyType = result.attributeColumnMetadata[0].get(PublicMetadata.KEYTYPE); // make sure all columns have same keyType for (int i = 1; i < columns.length; i++) if (!Strings.equal(keyType, result.attributeColumnMetadata[i].get(PublicMetadata.KEYTYPE))) throw new RemoteException("Specified columns must all have same keyType."); if (keysArray == null) { boolean canGenerateSQL = true; // check to see if all the columns are from the same SQL table. String connection = null; String sqlSchema = null; String sqlTable = null; for (DataEntity entity : entityLookup.values()) { String c = entity.privateMetadata.get(PrivateMetadata.CONNECTION); String s = entity.privateMetadata.get(PrivateMetadata.SQLSCHEMA); String t = entity.privateMetadata.get(PrivateMetadata.SQLTABLE); if (connection == null) connection = c; if (sqlSchema == null) sqlSchema = s; if (sqlTable == null) sqlTable = t; if (!Strings.equal(connection, c) || !Strings.equal(sqlSchema, s) || !Strings.equal(sqlTable, t)) { canGenerateSQL = false; break; } } if (canGenerateSQL) { Connection conn = getColumnConnectionInfo(entityLookup.get(columns[0])).getStaticReadOnlyConnection(); try { result.recordData = getFilteredRowsFromSQL(conn, sqlSchema, sqlTable, columns, filters, entityLookup).rows; } catch (SQLException e) { throw new RemoteException("getFilteredRows() failed.", e); } } } if (result.recordData == null) { throw new Error("Selecting across tables is not supported yet."); /* HashMap<String,Object[]> data = new HashMap<String,Object[]>(); if (keysArray != null) for (String key : keysArray) data.put(key, new Object[entities.length]); for (int colIndex = 0; colIndex < entities.length; colIndex++) { Object[] filters = fcrs[colIndex].filters; DataEntity info = entities[colIndex]; String sqlQuery = info.privateMetadata.get(PrivateMetadata.SQLQUERY); String sqlParams = info.privateMetadata.get(PrivateMetadata.SQLPARAMS); //if (dataWithKeysQuery.length() == 0) // throw new RemoteException(String.format("No SQL query is associated with column \"%s\" in dataTable \"%s\"", attributeColumnName, dataTableName)); String dataType = info.publicMetadata.get(PublicMetadata.DATATYPE); // use config min,max or param min,max to filter the data String infoMinStr = info.publicMetadata.get(PublicMetadata.MIN); String infoMaxStr = info.publicMetadata.get(PublicMetadata.MAX); double minValue = Double.NEGATIVE_INFINITY; double maxValue = Double.POSITIVE_INFINITY; // first try parsing config min,max values try { minValue = Double.parseDouble(infoMinStr); } catch (Exception e) { } try { maxValue = Double.parseDouble(infoMaxStr); } catch (Exception e) { } // override config min,max with param values if given // * columnInfoArray = config.getDataEntity(params); // * for each info in columnInfoArray // * get sql data // * for each row in sql data // * if key is in keys array, // * add this value to the result // * return result try { //timer.start(); boolean errorReported = false; Connection conn = getColumnConnectionInfo(info).getStaticReadOnlyConnection(); String[] sqlParamsArray = null; if (sqlParams != null && sqlParams.length() > 0) sqlParamsArray = CSVParser.defaultParser.parseCSV(sqlParams, true)[0]; SQLResult sqlResult = SQLUtils.getResultFromQuery(conn, sqlQuery, sqlParamsArray, false); //timer.lap("get row set"); // if dataType is defined in the config file, use that value. // otherwise, derive it from the sql result. if (Strings.isEmpty(dataType)) dataType = DataType.fromSQLType(sqlResult.columnTypes[1]); boolean isNumeric = dataType != null && dataType.equalsIgnoreCase(DataType.NUMBER); Object keyObj, dataObj; for (int iRow = 0; iRow < sqlResult.rows.length; iRow++) { keyObj = sqlResult.rows[iRow][0]; dataObj = sqlResult.rows[iRow][1]; if (keyObj == null || dataObj == null) continue; keyObj = keyObj.toString(); if (data.containsKey(keyObj)) { // if row has been set to null, skip if (data.get(keyObj) == null) continue; } else { // if keys are specified and row is not present, skip if (keysArray != null) continue; } try { boolean passedFilters = true; // convert the data to the appropriate type, then filter by value if (isNumeric) { if (dataObj instanceof Number) // TEMPORARY SOLUTION - FIX ME { double doubleValue = ((Number)dataObj).doubleValue(); // filter the data based on the min,max values if (minValue <= doubleValue && doubleValue <= maxValue) { // filter the value if (filters != null) { passedFilters = false; for (Object range : filters) { Number min = (Number)((Object[])range)[0]; Number max = (Number)((Object[])range)[1]; if (min.doubleValue() <= doubleValue && doubleValue <= max.doubleValue()) { passedFilters = true; break; } } } } else passedFilters = false; } else passedFilters = false; } else { String stringValue = dataObj.toString(); dataObj = stringValue; // filter the value if (filters != null) { passedFilters = false; for (Object filter : filters) { if (filter.equals(stringValue)) { passedFilters = true; break; } } } } Object[] row = data.get(keyObj); if (passedFilters) { // add existing row if it has not been added yet if (!data.containsKey(keyObj)) { for (int i = 0; i < colIndex; i++) { Object[] prevFilters = fcrs[i].filters; if (prevFilters != null) { passedFilters = false; break; } } if (passedFilters) row = new Object[entities.length]; data.put((String)keyObj, row); } if (row != null) row[colIndex] = dataObj; } else { // remove existing row if value did not pass filters if (row != null || !data.containsKey(keyObj)) data.put((String)keyObj, null); } } catch (Exception e) { if (!errorReported) { errorReported = true; e.printStackTrace(); } } } } catch (SQLException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); throw new RemoteException(e.getMessage()); } } if (keysArray == null) { List<String> keys = new LinkedList<String>(); for (Entry<String,Object[]> entry : data.entrySet()) if (entry.getValue() != null) keys.add(entry.getKey()); keysArray = keys.toArray(new String[keys.size()]); } Object[][] rows = new Object[keysArray.length][]; for (int iKey = 0; iKey < keysArray.length; iKey++) rows[iKey] = data.get(keysArray[iKey]); result.recordData = rows; */ } result.keyType = keyType; result.recordKeys = keysArray; return result; } // backwards compatibility /** * Use getHierarchyInfo() instead. This function is provided for backwards compatibility only. * @deprecated */ @Deprecated public EntityHierarchyInfo[] getDataTableList() throws RemoteException { return getDataConfig().getEntityHierarchyInfo(MapUtils.<String,String>fromPairs(PublicMetadata.ENTITYTYPE, EntityType.TABLE)); } /** * Use getEntities() instead. This function is provided for backwards compatibility only. * @deprecated */ @Deprecated public int[] getEntityChildIds(int parentId) throws RemoteException { return ListUtils.toIntArray( getDataConfig().getChildIds(parentId) ); } /** * Use getEntities() instead. This function is provided for backwards compatibility only. * @deprecated */ @Deprecated public int[] getParents(int childId) throws RemoteException { int[] ids = ListUtils.toIntArray( getDataConfig().getParentIds(childId) ); Arrays.sort(ids); return ids; } /** * Use findEntityIds() instead. This function is provided for backwards compatibility only. * @deprecated */ @Deprecated public int[] getEntityIdsByMetadata(Map<String,String> publicMetadata, int entityType) throws RemoteException { publicMetadata.put(PublicMetadata.ENTITYTYPE, EntityType.fromInt(entityType)); return findEntityIds(publicMetadata, null); } /** * Use getEntities() instead. This function is provided for backwards compatibility only. * @deprecated */ @Deprecated public DataEntity[] getEntitiesById(int[] ids) throws RemoteException { return getEntities(ids); } /** * @param metadata The metadata query. * @return The id of the matching column. * @throws RemoteException Thrown if the metadata query does not match exactly one column. */ @Deprecated public AttributeColumnData getColumnFromMetadata(Map<String, String> metadata) throws RemoteException { if (metadata == null || metadata.size() == 0) throw new RemoteException("No metadata query parameters specified."); metadata.put(PublicMetadata.ENTITYTYPE, EntityType.COLUMN); final String DATATABLE = "dataTable"; final String NAME = "name"; // exclude these parameters from the query if (metadata.containsKey(NAME)) metadata.remove(PublicMetadata.TITLE); String minStr = metadata.remove(PublicMetadata.MIN); String maxStr = metadata.remove(PublicMetadata.MAX); String paramsStr = metadata.remove(PrivateMetadata.SQLPARAMS); DataConfig dataConfig = getDataConfig(); Collection<Integer> ids = dataConfig.searchPublicMetadata(metadata, null); // attempt recovery for backwards compatibility if (ids.size() == 0) { if (metadata.containsKey(DATATABLE) && metadata.containsKey(NAME)) { // try to find columns sqlTable==dataTable and sqlColumn=name Map<String,String> privateMetadata = new HashMap<String,String>(); String sqlTable = metadata.get(DATATABLE); String sqlColumn = metadata.get(NAME); for (int i = 0; i < 2; i++) { if (i == 1) sqlTable = sqlTable.toLowerCase(); privateMetadata.put(PrivateMetadata.SQLTABLE, sqlTable); privateMetadata.put(PrivateMetadata.SQLCOLUMN, sqlColumn); ids = dataConfig.searchPrivateMetadata(privateMetadata, null); if (ids.size() > 0) break; } } else if (metadata.containsKey(NAME) && Strings.equal(metadata.get(PublicMetadata.DATATYPE), DataType.GEOMETRY)) { metadata.put(PublicMetadata.TITLE, metadata.remove(NAME)); ids = dataConfig.searchPublicMetadata(metadata, null); } if (ids.size() == 0) throw new RemoteException("No column matches metadata query: " + metadata); } // warning if more than one column if (ids.size() > 1) { String message = String.format( "WARNING: Multiple columns (%s) match metadata query: %s", ids.size(), metadata ); System.err.println(message); //throw new RemoteException(message); } // return first column int id = ListUtils.getFirstSortedItem(ids, DataConfig.NULL); double min = Double.NaN, max = Double.NaN; try { min = (Double)cast(minStr, double.class); } catch (Throwable t) { } try { max = (Double)cast(maxStr, double.class); } catch (Throwable t) { } String[] sqlParams = CSVParser.defaultParser.parseCSVRow(paramsStr, true); return getColumn(id, min, max, sqlParams); } }
package protocolsupport.injector; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandler; import java.util.List; import net.minecraft.server.v1_8_R3.ChatComponentText; import net.minecraft.server.v1_8_R3.MinecraftServer; import net.minecraft.server.v1_8_R3.NetworkManager; import net.minecraft.server.v1_8_R3.ServerConnection; import protocolsupport.protocol.core.ServerConnectionChannel; import protocolsupport.utils.Utils; public class NettyInjector { @SuppressWarnings("unchecked") public static void inject() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { ServerConnection serverConnection = MinecraftServer.getServer().getServerConnection(); List<NetworkManager> networkManagersList = ((List<NetworkManager>) Utils.setAccessible(serverConnection.getClass().getDeclaredField("h")).get(serverConnection)); Channel channel = ((List<ChannelFuture>) Utils.setAccessible(serverConnection.getClass().getDeclaredField("g")).get(serverConnection)).get(0).channel(); ChannelHandler serverHandler = channel.pipeline().first(); Utils.setAccessible(serverHandler.getClass().getDeclaredField("childHandler")).set(serverHandler, new ServerConnectionChannel(networkManagersList)); synchronized (networkManagersList) { for (NetworkManager nm : networkManagersList) { nm.close(new ChatComponentText("ProtocolSupport channel reset")); } } } }
package railo.runtime.type; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.net.URL; import java.sql.Blob; import java.sql.Clob; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.Ref; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.Arrays; import java.util.Calendar; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import railo.commons.db.DBUtil; import railo.commons.io.IOUtil; import railo.commons.lang.SizeOf; import railo.commons.lang.StringUtil; import railo.commons.sql.SQLUtil; import railo.loader.engine.CFMLEngineFactory; import railo.runtime.PageContext; import railo.runtime.converter.ScriptConverter; import railo.runtime.db.CFTypes; import railo.runtime.db.DataSource; import railo.runtime.db.DataSourceUtil; import railo.runtime.db.DatasourceConnection; import railo.runtime.db.DatasourceConnectionImpl; import railo.runtime.db.DatasourceConnectionPro; import railo.runtime.db.SQL; import railo.runtime.db.SQLCaster; import railo.runtime.db.SQLItem; import railo.runtime.dump.DumpData; import railo.runtime.dump.DumpProperties; import railo.runtime.dump.DumpRow; import railo.runtime.dump.DumpTable; import railo.runtime.dump.DumpTablePro; import railo.runtime.dump.DumpUtil; import railo.runtime.dump.SimpleDumpData; import railo.runtime.engine.ThreadLocalPageContext; import railo.runtime.exp.ApplicationException; import railo.runtime.exp.DatabaseException; import railo.runtime.exp.ExpressionException; import railo.runtime.exp.PageException; import railo.runtime.exp.PageRuntimeException; import railo.runtime.functions.arrays.ArrayFind; import railo.runtime.interpreter.CFMLExpressionInterpreter; import railo.runtime.op.Caster; import railo.runtime.op.Decision; import railo.runtime.op.ThreadLocalDuplication; import railo.runtime.op.date.DateCaster; import railo.runtime.query.caster.Cast; import railo.runtime.reflection.Reflector; import railo.runtime.timer.Stopwatch; import railo.runtime.type.comparator.NumberSortRegisterComparator; import railo.runtime.type.comparator.SortRegister; import railo.runtime.type.comparator.SortRegisterComparator; import railo.runtime.type.dt.DateTime; import railo.runtime.type.dt.DateTimeImpl; import railo.runtime.type.it.CollectionIterator; import railo.runtime.type.it.KeyIterator; import railo.runtime.type.sql.BlobImpl; import railo.runtime.type.sql.ClobImpl; import railo.runtime.type.util.ArrayUtil; import railo.runtime.type.util.CollectionUtil; /** * implementation of the query interface */ public class QueryImpl implements QueryPro,Objects,Sizeable { private static final long serialVersionUID = 1035795427320192551L; /** * @return the template */ public String getTemplate() { return template; } public static final Collection.Key COLUMNS = KeyImpl.intern("COLUMNS"); public static final Collection.Key SQL = KeyImpl.intern("SQL"); public static final Collection.Key EXECUTION_TIME = KeyImpl.intern("executionTime"); public static final Collection.Key RECORDCOUNT = KeyImpl.intern("RECORDCOUNT"); public static final Collection.Key CACHED = KeyImpl.intern("cached"); public static final Collection.Key COLUMNLIST = KeyImpl.intern("COLUMNLIST"); public static final Collection.Key CURRENTROW = KeyImpl.intern("CURRENTROW"); public static final Collection.Key IDENTITYCOL = KeyImpl.intern("IDENTITYCOL"); public static final Collection.Key GENERATED_KEYS = KeyImpl.intern("GENERATED_KEYS"); //private static int count=0; private QueryColumnImpl[] columns; private Collection.Key[] columnNames; private SQL sql; private ArrayInt arrCurrentRow=new ArrayInt(); private int recordcount=0; private int columncount; private long exeTime=0; private boolean isCached=false; private String name; private int updateCount; private QueryImpl generatedKeys; private String template; /** * @return return execution time to get query */ public int executionTime() { return (int) exeTime; } /** * create a QueryImpl from a SQL Resultset * @param result SQL Resultset * @param maxrow * @param name * @throws PageException */ public QueryImpl(ResultSet result, int maxrow, String name) throws PageException { this.name=name; Stopwatch stopwatch=new Stopwatch(); stopwatch.start(); try { fillResult(null,result,maxrow,false,false); } catch (SQLException e) { throw new DatabaseException(e,null); } catch (IOException e) { throw Caster.toPageException(e); } exeTime=stopwatch.time(); } /** * Constructor of the class * only for internal usage (cloning/deserialize) */ public QueryImpl() { } public QueryImpl(ResultSet result, String name) throws PageException { this.name=name; try { fillResult(null,result,-1,true,false); } catch (SQLException e) { throw new DatabaseException(e,null); } catch (Exception e) { throw Caster.toPageException(e); } } /** * constructor of the class, to generate a resultset from a sql query * @param dc Connection to a database * @param name * @param sql sql to execute * @param maxrow maxrow for the resultset * @throws PageException */ public QueryImpl(DatasourceConnection dc,SQL sql,int maxrow, int fetchsize,int timeout, String name) throws PageException { this(dc, sql, maxrow, fetchsize, timeout, name,null,false); } public QueryImpl(DatasourceConnection dc,SQL sql,int maxrow, int fetchsize,int timeout, String name,String template) throws PageException { this(dc, sql, maxrow, fetchsize, timeout, name,template,false); } public QueryImpl(DatasourceConnection dc,SQL sql,int maxrow, int fetchsize,int timeout, String name,String template,boolean createUpdateData) throws PageException { this.name=name; this.template=template; this.sql=sql; //ResultSet result=null; Statement stat=null; // check SQL Restrictions if(dc.getDatasource().hasSQLRestriction()) { checkSQLRestriction(dc,sql); } // check if datasource support Generated Keys boolean createGeneratedKeys=createUpdateData; if(createUpdateData){ DatasourceConnectionImpl dci=(DatasourceConnectionImpl) dc; dci.supportsGetGeneratedKeys(); if(!dci.supportsGetGeneratedKeys())createGeneratedKeys=false; } Stopwatch stopwatch=new Stopwatch(); stopwatch.start(); boolean hasResult=false; boolean closeStatement=true; try { SQLItem[] items=sql.getItems(); if(items.length==0) { stat=dc.getConnection().createStatement(); setAttributes(stat,maxrow,fetchsize,timeout); // some driver do not support second argument hasResult=createGeneratedKeys?stat.execute(sql.getSQLString(),Statement.RETURN_GENERATED_KEYS):stat.execute(sql.getSQLString()); } else { // some driver do not support second argument PreparedStatement preStat = ((DatasourceConnectionPro)dc).getPreparedStatement(sql, createGeneratedKeys); closeStatement=false; stat=preStat; setAttributes(preStat,maxrow,fetchsize,timeout); setItems(preStat,items); hasResult=preStat.execute(); } int uc; ResultSet res; do { if(hasResult) { res=stat.getResultSet(); if(fillResult(dc,res, maxrow, true,createGeneratedKeys))break; } else if((uc=setUpdateCount(stat))!=-1){ if(uc>0 && createGeneratedKeys)setGeneratedKeys(dc, stat); } else break; hasResult=stat.getMoreResults(Statement.CLOSE_CURRENT_RESULT); } while(true); } catch (SQLException e) { throw new DatabaseException(e,sql,dc); } catch (Throwable e) { throw Caster.toPageException(e); } finally { if(closeStatement)DBUtil.closeEL(stat); } exeTime=stopwatch.time(); } private int setUpdateCount(Statement stat) { try{ int uc=stat.getUpdateCount(); if(uc>-1){ updateCount+=uc; return uc; } } catch(Throwable t){} return -1; } private boolean setGeneratedKeys(DatasourceConnection dc,Statement stat) { try{ ResultSet rs = stat.getGeneratedKeys(); setGeneratedKeys(dc, rs); return true; } catch(Throwable t) { return false; } } private void setGeneratedKeys(DatasourceConnection dc,ResultSet rs) throws PageException { generatedKeys=new QueryImpl(rs,""); if(DataSourceUtil.isMSSQL(dc)) generatedKeys.renameEL(GENERATED_KEYS,IDENTITYCOL); } /*private void setUpdateData(Statement stat, boolean createGeneratedKeys, boolean createUpdateCount) { // update Count if(createUpdateCount){ try{ updateCount=stat.getUpdateCount(); } catch(Throwable t){ t.printStackTrace(); } } // generated keys if(createGeneratedKeys){ try{ ResultSet rs = stat.getGeneratedKeys(); generatedKeys=new QueryImpl(rs,""); } catch(Throwable t){ t.printStackTrace(); } } }*/ private void setItems(PreparedStatement preStat, SQLItem[] items) throws DatabaseException, PageException, SQLException { for(int i=0;i<items.length;i++) { SQLCaster.setValue(preStat,i+1,items[i]); } } public int getUpdateCount() { return updateCount; } public Query getGeneratedKeys() { return generatedKeys; } private void setAttributes(Statement stat,int maxrow, int fetchsize,int timeout) throws SQLException { if(maxrow>-1) stat.setMaxRows(maxrow); if(fetchsize>0)stat.setFetchSize(fetchsize); if(timeout>0)stat.setQueryTimeout(timeout); } private ResultSet getResultSetEL(Statement stat) { try { return stat.getResultSet(); } catch(SQLException sqle) { return null; } } /** * check if there is a sql restriction * @param ds * @param sql * @throws PageException */ private static void checkSQLRestriction(DatasourceConnection dc, SQL sql) throws PageException { Array sqlparts = List.listToArrayRemoveEmpty( SQLUtil.removeLiterals(sql.getSQLString()) ," \t"+System.getProperty("line.separator")); //print.ln(List.toStringArray(sqlparts)); DataSource ds = dc.getDatasource(); if(!ds.hasAllow(DataSource.ALLOW_ALTER)) checkSQLRestriction(dc,"alter",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_CREATE)) checkSQLRestriction(dc,"create",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_DELETE)) checkSQLRestriction(dc,"delete",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_DROP)) checkSQLRestriction(dc,"drop",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_GRANT)) checkSQLRestriction(dc,"grant",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_INSERT)) checkSQLRestriction(dc,"insert",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_REVOKE)) checkSQLRestriction(dc,"revoke",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_SELECT)) checkSQLRestriction(dc,"select",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_UPDATE)) checkSQLRestriction(dc,"update",sqlparts,sql); } private static void checkSQLRestriction(DatasourceConnection dc, String keyword, Array sqlparts, SQL sql) throws PageException { if(ArrayFind.find(sqlparts,keyword,false)>0) { throw new DatabaseException("access denied to execute \""+StringUtil.ucFirst(keyword)+"\" SQL statment for datasource "+dc.getDatasource().getName(),null,sql,dc); } } private boolean fillResult(DatasourceConnection dc, ResultSet result, int maxrow, boolean closeResult,boolean createGeneratedKeys) throws SQLException, IOException, PageException { if(result==null) return false; recordcount=0; ResultSetMetaData meta = result.getMetaData(); columncount=meta.getColumnCount(); // set header arrays Collection.Key[] tmpColumnNames = new Collection.Key[columncount]; int count=0; Collection.Key key; String columnName; for(int i=0;i<columncount;i++) { columnName=meta.getColumnName(i+1); if(StringUtil.isEmpty(columnName))columnName="column_"+i; key=KeyImpl.init(columnName); int index=getIndexFrom(tmpColumnNames,key,0,i); if(index==-1) { tmpColumnNames[i]=key; count++; } } columncount=count; columnNames=new Collection.Key[columncount]; columns=new QueryColumnImpl[columncount]; Cast[] casts = new Cast[columncount]; // get all used ints int[] usedColumns=new int[columncount]; count=0; for(int i=0;i<tmpColumnNames.length;i++) { if(tmpColumnNames[i]!=null) { usedColumns[count++]=i; } } // set used column names int[] types=new int[columns.length]; for(int i=0;i<usedColumns.length;i++) { columnNames[i]=tmpColumnNames[usedColumns[i]]; columns[i]=new QueryColumnImpl(this,columnNames[i],types[i]=meta.getColumnType(usedColumns[i]+1)); if(types[i]==Types.TIMESTAMP) casts[i]=Cast.TIMESTAMP; else if(types[i]==Types.TIME) casts[i]=Cast.TIME; else if(types[i]==Types.DATE) casts[i]=Cast.DATE; else if(types[i]==Types.CLOB) casts[i]=Cast.CLOB; else if(types[i]==Types.BLOB) casts[i]=Cast.BLOB; else if(types[i]==Types.BIT) casts[i]=Cast.BIT; else if(types[i]==Types.ARRAY) casts[i]=Cast.ARRAY; //else if(types[i]==Types.TINYINT) casts[i]=Cast.ARRAY; else if(types[i]==CFTypes.OPAQUE){ if(SQLUtil.isOracle(result.getStatement().getConnection())) casts[i]=Cast.ORACLE_OPAQUE; else casts[i]=Cast.OTHER; } else casts[i]=Cast.OTHER; } if(createGeneratedKeys && columncount==1 && columnNames[0].equals(GENERATED_KEYS) && dc!=null && DataSourceUtil.isMSSQLDriver(dc)) { columncount=0; columnNames=null; columns=null; setGeneratedKeys(dc, result); return false; } // fill data //Object o; while(result.next()) { if(maxrow>-1 && recordcount>=maxrow) { break; } for(int i=0;i<usedColumns.length;i++) { columns[i].add(casts[i].toCFType(types[i], result, usedColumns[i]+1)); } ++recordcount; } if(closeResult)result.close(); return true; } private Object toBytes(Blob blob) throws IOException, SQLException { return IOUtil.toBytes((blob).getBinaryStream()); } private static Object toString(Clob clob) throws IOException, SQLException { return IOUtil.toString(clob.getCharacterStream()); } private int getIndexFrom(Collection.Key[] tmpColumnNames, Collection.Key key, int from, int to) { for(int i=from;i<to;i++) { if(tmpColumnNames[i]!=null && tmpColumnNames[i].equalsIgnoreCase(key))return i; } return -1; } /** * constructor of the class, to generate a empty resultset (no database execution) * @param strColumns columns for the resultset * @param rowNumber count of rows to generate (empty fields) * @param name */ public QueryImpl(String[] strColumns, int rowNumber,String name) { this.name=name; columncount=strColumns.length; recordcount=rowNumber; columnNames=new Collection.Key[columncount]; columns=new QueryColumnImpl[columncount]; for(int i=0;i<strColumns.length;i++) { columnNames[i]=KeyImpl.init(strColumns[i].trim()); columns[i]=new QueryColumnImpl(this,columnNames[i],Types.OTHER,recordcount); } } /** * constructor of the class, to generate a empty resultset (no database execution) * @param strColumns columns for the resultset * @param rowNumber count of rows to generate (empty fields) * @param name */ public QueryImpl(Collection.Key[] columnKeys, int rowNumber,String name) { this.name=name; columncount=columnKeys.length; recordcount=rowNumber; columnNames=new Collection.Key[columncount]; columns=new QueryColumnImpl[columncount]; for(int i=0;i<columnKeys.length;i++) { columnNames[i]=columnKeys[i]; columns[i]=new QueryColumnImpl(this,columnNames[i],Types.OTHER,recordcount); } } /** * constructor of the class, to generate a empty resultset (no database execution) * @param strColumns columns for the resultset * @param strTypes array of the types * @param rowNumber count of rows to generate (empty fields) * @param name * @throws DatabaseException */ public QueryImpl(String[] strColumns, String[] strTypes, int rowNumber, String name) throws DatabaseException { this.name=name; columncount=strColumns.length; if(strTypes.length!=columncount) throw new DatabaseException("columns and types has not the same count",null,null,null); recordcount=rowNumber; columnNames=new Collection.Key[columncount]; columns=new QueryColumnImpl[columncount]; for(int i=0;i<strColumns.length;i++) { columnNames[i]=KeyImpl.init(strColumns[i].trim()); columns[i]=new QueryColumnImpl(this,columnNames[i],SQLCaster.toIntType(strTypes[i]),recordcount); } } /** * constructor of the class, to generate a empty resultset (no database execution) * @param strColumns columns for the resultset * @param strTypes array of the types * @param rowNumber count of rows to generate (empty fields) * @param name * @throws DatabaseException */ public QueryImpl(Collection.Key[] columnNames, String[] strTypes, int rowNumber, String name) throws DatabaseException { this.name=name; this.columnNames=columnNames; columncount=columnNames.length; if(strTypes.length!=columncount) throw new DatabaseException("columns and types has not the same count",null,null,null); recordcount=rowNumber; columns=new QueryColumnImpl[columncount]; for(int i=0;i<columnNames.length;i++) { columns[i]=new QueryColumnImpl(this,columnNames[i],SQLCaster.toIntType(strTypes[i]),recordcount); } } /** * constructor of the class, to generate a empty resultset (no database execution) * @param arrColumns columns for the resultset * @param rowNumber count of rows to generate (empty fields) * @param name */ public QueryImpl(Array arrColumns, int rowNumber, String name) { this.name=name; columncount=arrColumns.size(); recordcount=rowNumber; columnNames=new Collection.Key[columncount]; columns=new QueryColumnImpl[columncount]; for(int i=0;i<columncount;i++) { columnNames[i]=KeyImpl.init(arrColumns.get(i+1,"").toString().trim()); columns[i]=new QueryColumnImpl(this,columnNames[i],Types.OTHER,recordcount); } } /** * constructor of the class, to generate a empty resultset (no database execution) * @param arrColumns columns for the resultset * @param arrTypes type of the columns * @param rowNumber count of rows to generate (empty fields) * @param name * @throws PageException */ public QueryImpl(Array arrColumns, Array arrTypes, int rowNumber, String name) throws PageException { this.name=name; columncount=arrColumns.size(); if(arrTypes.size()!=columncount) throw new DatabaseException("columns and types has not the same count",null,null,null); recordcount=rowNumber; columnNames=new Collection.Key[columncount]; columns=new QueryColumnImpl[columncount]; for(int i=0;i<columncount;i++) { columnNames[i]=KeyImpl.init(arrColumns.get(i+1,"").toString().trim()); columns[i]=new QueryColumnImpl(this,columnNames[i],SQLCaster.toIntType(Caster.toString(arrTypes.get(i+1,""))),recordcount); } } /** * constructor of the class * @param columnNames columns definition as String Array * @param arrColumns values * @param name * @throws DatabaseException */ public QueryImpl(String[] strColumnNames, Array[] arrColumns, String name) throws DatabaseException { this(_toKeys(strColumnNames),arrColumns,name); } private static Collection.Key[] _toKeys(String[] strColumnNames) { Collection.Key[] columnNames=new Collection.Key[strColumnNames.length]; for(int i=0 ;i<columnNames.length;i++) { columnNames[i]=KeyImpl.init(strColumnNames[i].trim()); } return columnNames; } private static String[] _toStringKeys(Collection.Key[] columnNames) { String[] strColumnNames=new String[columnNames.length]; for(int i=0 ;i<strColumnNames.length;i++) { strColumnNames[i]=columnNames[i].getString(); } return strColumnNames; } /*public QueryImpl(Collection.Key[] columnNames, QueryColumn[] columns, String name,long exeTime, boolean isCached,SQL sql) throws DatabaseException { this.columnNames=columnNames; this.columns=columns; this.exeTime=exeTime; this.isCached=isCached; this.name=name; this.columncount=columnNames.length; this.recordcount=columns.length==0?0:columns[0].size(); this.sql=sql; }*/ public QueryImpl(Collection.Key[] columnNames, Array[] arrColumns, String name) throws DatabaseException { this.name=name; if(columnNames.length!=arrColumns.length) throw new DatabaseException("invalid parameter for query, not the same count from names and columns","names:"+columnNames.length+";columns:"+arrColumns.length,null,null,null); int len=0; columns=new QueryColumnImpl[arrColumns.length]; if(arrColumns.length>0) { // test columns len=arrColumns[0].size(); for(int i=0;i<arrColumns.length;i++) { if(arrColumns[i].size()!=len) throw new DatabaseException("invalid parameter for query, all columns must have the same size","column[1]:"+len+"<>column["+(i+1)+"]:"+arrColumns[i].size(),null,null,null); //columns[i]=new QueryColumnTypeFlex(arrColumns[i]); columns[i]=new QueryColumnImpl(this,columnNames[i],arrColumns[i],Types.OTHER); } // test keys Map testMap=new HashMap(); for(int i=0 ;i<columnNames.length;i++) { if(!Decision.isSimpleVariableName(columnNames[i])) throw new DatabaseException("invalid column name ["+columnNames[i]+"] for query", "column names must start with a letter and can be followed by letters numbers and underscores [_]. RegExp:[a-zA-Z][a-zA-Z0-9_]*",null,null,null); if(testMap.containsKey(columnNames[i].getLowerString())) throw new DatabaseException("invalid parameter for query, ambiguous column name "+columnNames[i],"columnNames: "+List.arrayToListTrim( _toStringKeys(columnNames),","),null,null,null); testMap.put(columnNames[i].getLowerString(),"set"); } } columncount=columns.length; recordcount=len; this.columnNames=columnNames; } /** * constructor of the class * @param columnList * @param data * @param name */ public QueryImpl(String[] strColumnList, Object[][] data,String name) { this(toCollKeyArr(strColumnList),data.length,name); for(int iRow=0;iRow<data.length;iRow++) { Object[] row=data[iRow]; for(int iCol=0;iCol<row.length;iCol++) { //print.ln(columnList[iCol]+":"+iRow+"="+row[iCol]); setAtEL(columnNames[iCol],iRow+1,row[iCol]); } } } private static Collection.Key[] toCollKeyArr(String[] strColumnList) { Collection.Key[] columnList=new Collection.Key[strColumnList.length]; for(int i=0 ;i<columnList.length;i++) { columnList[i]=KeyImpl.init(strColumnList[i].trim()); } return columnList; } /** * @see railo.runtime.type.Collection#size() */ public int size() { return columncount; } /** * @see railo.runtime.type.Collection#keys() */ public Collection.Key[] keys() { return columnNames; } /** * @see railo.runtime.type.Collection#keysAsString() */ public String[] keysAsString() { return toString(columnNames); } private String[] toString(Collection.Key[] keys) { if(keys==null) return new String[0]; String[] strKeys=new String[keys.length]; for(int i=0 ;i<columns.length;i++) { strKeys[i]=keys[i].getString(); } return strKeys; } /** * @see railo.runtime.type.Collection#removeEL(java.lang.String) */ public synchronized Object removeEL(String key) { return setEL(key,null); /*int index=getIndexFromKey(key); if(index!=-1) _removeEL(index); return null;*/ } /** * @see railo.runtime.type.Collection#removeEL(railo.runtime.type.Collection.Key) */ public Object removeEL(Collection.Key key) { return setEL(key,null); /*int index=getIndexFromKey(key); if(index!=-1) return _removeEL(index); return null;*/ } /*private QueryColumn _removeEL(int index) { QueryColumnImpl[] qc=new QueryColumnImpl[--columncount]; Collection.Key[] names=new Collection.Key[columncount]; int count=0; QueryColumn removed=null; for(int i=0;i<columns.length;i++) { if(index!=i){ names[count]=columnNames[i]; qc[count++]=columns[i]; } else { removed=columns[i]; } } columnNames=names; columns=qc; return removed; }*/ /** * @see railo.runtime.type.Collection#remove(java.lang.String) */ public synchronized Object remove(String key) throws PageException { return set(key,null); /*int index=getIndexFromKey(key); if(index!=-1) return _removeEL(index); throw new ExpressionException("can't remove column with name ["+key+"], column doesn't exist");*/ } /** * @throws PageException * @see railo.runtime.type.Collection#remove(railo.runtime.type.Collection.Key) */ public Object remove(Collection.Key key) throws PageException { return set(key,null); /*int index=getIndexFromKey(key); if(index!=-1) return _removeEL(index); throw new ExpressionException("can't remove column with name ["+key+"], column doesn't exist");*/ } /** * @see railo.runtime.type.Collection#clear() */ public void clear() { for(int i=0;i<columns.length;i++) { columns[i].clear(); } recordcount=0; //columns=new QueryColumnImpl[0]; //columnNames=new Collection.Key[0]; //columncount=0; } /** * * @see railo.runtime.type.Collection#get(java.lang.String, java.lang.Object) */ public Object get(String key, Object defaultValue) { return getAt(key, arrCurrentRow.get(getPid(), 1), defaultValue); } //private static int pidc=0; private int getPid() { PageContext pc = ThreadLocalPageContext.get(); if(pc==null) { pc=CFMLEngineFactory.getInstance().getThreadPageContext(); if(pc==null)throw new RuntimeException("cannot get pid for current thread"); } return pc.getId(); } /** * * @see railo.runtime.type.Collection#get(railo.runtime.type.Collection.Key, java.lang.Object) */ public Object get(Collection.Key key, Object defaultValue) { return getAt(key, arrCurrentRow.get(getPid(), 1), defaultValue); } /** * @see railo.runtime.type.Collection#get(java.lang.String) */ public Object get(String key) throws PageException { return getAt(key, arrCurrentRow.get(getPid(), 1) ); } /** * @see railo.runtime.type.Collection#get(railo.runtime.type.Collection.Key) */ public Object get(Collection.Key key) throws PageException { return getAt(key, arrCurrentRow.get(getPid(), 1) ); } /** * * @see railo.runtime.type.Query#getAt(java.lang.String, int, java.lang.Object) */ public Object getAt(String key, int row, Object defaultValue) { int index=getIndexFromKey(key); if(index!=-1) { return columns[index].get(row,defaultValue); } if(key.length()>0) { char c=key.charAt(0); if(c=='r' || c=='R') { if(key.equalsIgnoreCase("recordcount")) return new Double(getRecordcount()); } if(c=='c' || c=='C') { if(key.equalsIgnoreCase("currentrow")) return new Double(row); else if(key.equalsIgnoreCase("columnlist")) return getColumnlist(true); } } return null; } public Object getAt(Collection.Key key, int row, Object defaultValue) { int index=getIndexFromKey(key); if(index!=-1) { return columns[index].get(row,defaultValue); } if(key.getString().length()>0) { char c=key.lowerCharAt(0); if(c=='r') { if(key.equals(RECORDCOUNT)) return new Double(getRecordcount()); } else if(c=='c') { if(key.equals(CURRENTROW)) return new Double(row); else if(key.equals(COLUMNLIST)) return getColumnlist(true); } } return null; } /** * @see railo.runtime.type.Query#getAt(java.lang.String, int) */ public Object getAt(String key, int row) throws PageException { //print.err("str:"+key); int index=getIndexFromKey(key); if(index!=-1) { return columns[index].get(row); } if(key.length()>0){ char c=key.charAt(0); if(c=='r' || c=='R') { if(key.equalsIgnoreCase("recordcount")) return new Double(getRecordcount()); } else if(c=='c' || c=='C') { if(key.equalsIgnoreCase("currentrow")) return new Double(row); else if(key.equalsIgnoreCase("columnlist")) return getColumnlist(true); } } throw new DatabaseException("column ["+key+"] not found in query, columns are ["+getColumnlist(false)+"]",null,sql,null); } /** * @see railo.runtime.type.Query#getAt(railo.runtime.type.Collection.Key, int) */ public Object getAt(Collection.Key key, int row) throws PageException { int index=getIndexFromKey(key); if(index!=-1) { return columns[index].get(row); } if(key.getString().length()>0) { char c=key.lowerCharAt(0); if(c=='r') { if(key.equals(RECORDCOUNT)) return new Double(getRecordcount()); } else if(c=='c') { if(key.equals(CURRENTROW)) return new Double(row); else if(key.equals(COLUMNLIST)) return getColumnlist(true); } } throw new DatabaseException("column ["+key+"] not found in query, columns are ["+getColumnlist(false)+"]",null,sql,null); } /** * @see railo.runtime.type.Query#removeRow(int) */ public synchronized int removeRow(int row) throws PageException { //disconnectCache(); for(int i=0;i<columns.length;i++) { columns[i].removeRow(row); } return --recordcount; } /** * @see railo.runtime.type.Query#removeRowEL(int) */ public int removeRowEL(int row) { //disconnectCache(); try { return removeRow(row); } catch (PageException e) { return recordcount; } } /** * @see railo.runtime.type.Query#removeColumn(java.lang.String) */ public QueryColumn removeColumn(String key) throws DatabaseException { //disconnectCache(); QueryColumn removed = removeColumnEL(key); if(removed==null) { if(key.equalsIgnoreCase("recordcount") || key.equalsIgnoreCase("currentrow") || key.equalsIgnoreCase("columnlist")) throw new DatabaseException("can't remove "+key+" this is not a row","existing rows are ["+getColumnlist(false)+"]",null,null,null); throw new DatabaseException("can't remove row ["+key+"], this row doesn't exist", "existing rows are ["+getColumnlist(false)+"]",null,null,null); } return removed; } /** * @see railo.runtime.type.Query#removeColumn(railo.runtime.type.Collection.Key) */ public QueryColumn removeColumn(Collection.Key key) throws PageException { //disconnectCache(); QueryColumn removed = removeColumnEL(key); if(removed==null) { if(key.equals(RECORDCOUNT) || key.equals(CURRENTROW) || key.equals(COLUMNLIST)) throw new DatabaseException("can't remove "+key+" this is not a row","existing rows are ["+getColumnlist(false)+"]",null,null,null); throw new DatabaseException("can't remove row ["+key+"], this row doesn't exist", "existing rows are ["+getColumnlist(false)+"]",null,null,null); } return removed; } /** * @see railo.runtime.type.Query#removeColumnEL(java.lang.String) */ public synchronized QueryColumn removeColumnEL(String key) { //disconnectCache(); int index=getIndexFromKey(key); if(index!=-1) { int current=0; QueryColumn removed=null; Collection.Key[] newColumnNames=new Collection.Key[columnNames.length-1]; QueryColumnImpl[] newColumns=new QueryColumnImpl[columns.length-1]; for(int i=0;i<columns.length;i++) { if(i==index) { removed=columns[i]; } else { newColumnNames[current]=columnNames[i]; newColumns[current++]=columns[i]; } } columnNames=newColumnNames; columns=newColumns; columncount return removed; } return null; } public QueryColumn removeColumnEL(Collection.Key key) { //disconnectCache(); int index=getIndexFromKey(key); if(index!=-1) { int current=0; QueryColumn removed=null; Collection.Key[] newColumnNames=new Collection.Key[columnNames.length-1]; QueryColumnImpl[] newColumns=new QueryColumnImpl[columns.length-1]; for(int i=0;i<columns.length;i++) { if(i==index) { removed=columns[i]; } else { newColumnNames[current]=columnNames[i]; newColumns[current++]=columns[i]; } } columnNames=newColumnNames; columns=newColumns; columncount return removed; } return null; } /** * @see railo.runtime.type.Collection#setEL(java.lang.String, java.lang.Object) */ public Object setEL(String key, Object value) { return setAtEL(key, arrCurrentRow.get(getPid(), 1), value); } /** * @see railo.runtime.type.Collection#setEL(railo.runtime.type.Collection.Key, java.lang.Object) */ public Object setEL(Collection.Key key, Object value) { return setAtEL(key, arrCurrentRow.get(getPid(), 1), value); } /** * @see railo.runtime.type.Collection#set(java.lang.String, java.lang.Object) */ public Object set(String key, Object value) throws PageException { return setAt(key, arrCurrentRow.get(getPid(), 1), value); } /** * @see railo.runtime.type.Collection#set(railo.runtime.type.Collection.Key, java.lang.Object) */ public Object set(Collection.Key key, Object value) throws PageException { return setAt(key, arrCurrentRow.get(getPid(), 1), value); } /** * @see railo.runtime.type.Query#setAt(java.lang.String, int, java.lang.Object) */ public Object setAt(String key,int row, Object value) throws PageException { //disconnectCache(); int index=getIndexFromKey(key); if(index!=-1) { return columns[index].set(row,value); } throw new DatabaseException("column ["+key+"] does not exist","columns are ["+getColumnlist(false)+"]",null,sql,null); } public Object setAt(Collection.Key key, int row, Object value) throws PageException { //disconnectCache(); int index=getIndexFromKey(key); if(index!=-1) { return columns[index].set(row,value); } throw new DatabaseException("column ["+key+"] does not exist","columns are ["+getColumnlist(false)+"]",null,sql,null); } /** * @see railo.runtime.type.Query#setAtEL(java.lang.String, int, java.lang.Object) */ public Object setAtEL(String key,int row, Object value) { //disconnectCache(); int index=getIndexFromKey(key); if(index!=-1) { return columns[index].setEL(row,value); } return null; } public Object setAtEL(Collection.Key key, int row, Object value) { //disconnectCache(); int index=getIndexFromKey(key); if(index!=-1) { return columns[index].setEL(row,value); } return null; } /** * @see railo.runtime.type.Iterator#next() */ public boolean next() { return next(getPid()); } /** * @see railo.runtime.type.Iterator#next(int) */ public boolean next(int pid) { if(recordcount>=(arrCurrentRow.set(pid,arrCurrentRow.get(pid,0)+1))) { return true; } arrCurrentRow.set(pid,0); return false; } /** * @see railo.runtime.type.Iterator#reset() */ public void reset() { reset(getPid()); } public void reset(int pid) { arrCurrentRow.set(pid,0); } /** * @see railo.runtime.type.Iterator#getRecordcount() */ public int getRecordcount() { return recordcount; } /** * @see railo.runtime.type.Iterator#getCurrentrow() * FUTURE set this to deprectaed */ public int getCurrentrow() { return getCurrentrow(getPid()); } /** * @see railo.runtime.type.QueryPro#getCurrentrow(int) */ public int getCurrentrow(int pid) { return arrCurrentRow.get(pid,1); } /** * return a string list of all columns * @return string list */ public String getColumnlist(boolean upperCase) { StringBuffer sb=new StringBuffer(); for(int i=0;i<columnNames.length;i++) { if(i>0)sb.append(','); sb.append(upperCase?columnNames[i].getString().toUpperCase():columnNames[i].getString());// FUTURE getUpperString } return sb.toString(); } public String getColumnlist() { return getColumnlist(true); } /** * @deprecated use instead go(int,int) * @see railo.runtime.type.Iterator#go(int) */ public boolean go(int index) { return go(index,getPid()); } public boolean go(int index, int pid) { if(index>0 && index<=recordcount) { arrCurrentRow.set(pid, index); return true; } arrCurrentRow.set(pid, 0); return false; } /** * @see railo.runtime.type.Iterator#isEmpty() */ public boolean isEmpty() { return recordcount+columncount==0; } /** * @see railo.runtime.dump.Dumpable#toDumpData(railo.runtime.PageContext, int) */ public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) { maxlevel String[] keys=keysAsString(); DumpData[] heads=new DumpData[keys.length+1]; //int tmp=1; heads[0]=new SimpleDumpData(""); for(int i=0;i<keys.length;i++) { heads[i+1]=new SimpleDumpData(keys[i]); } StringBuilder comment=new StringBuilder(); //table.appendRow(1, new SimpleDumpData("SQL"), new SimpleDumpData(sql.toString())); if(!StringUtil.isEmpty(template)) comment.append("Template:").append(template).append("\n"); //table.appendRow(1, new SimpleDumpData("Template"), new SimpleDumpData(template)); comment.append("Execution Time (ms):").append(Caster.toString(exeTime)).append("\n"); comment.append("Recordcount:").append(Caster.toString(getRecordcount())).append("\n"); comment.append("Cached:").append(isCached()?"Yes\n":"No\n"); if(sql!=null) comment.append("SQL:").append("\n").append(StringUtil.suppressWhiteSpace(sql.toString().trim())).append("\n"); //table.appendRow(1, new SimpleDumpData("Execution Time (ms)"), new SimpleDumpData(exeTime)); //table.appendRow(1, new SimpleDumpData("recordcount"), new SimpleDumpData(getRecordcount())); //table.appendRow(1, new SimpleDumpData("cached"), new SimpleDumpData(isCached()?"Yes":"No")); DumpTable recs=new DumpTablePro("query","#cc99cc","#ffccff","#000000"); recs.setTitle("Query"); if(dp.getMetainfo())recs.setComment(comment.toString()); recs.appendRow(new DumpRow(-1,heads)); // body DumpData[] items; for(int i=0;i<recordcount;i++) { items=new DumpData[columncount+1]; items[0]=new SimpleDumpData(i+1); for(int y=0;y<keys.length;y++) { try { Object o=getAt(keys[y],i+1); if(o instanceof String)items[y+1]=new SimpleDumpData(o.toString()); else if(o instanceof Number) items[y+1]=new SimpleDumpData(Caster.toString(((Number)o).doubleValue())); else if(o instanceof Boolean) items[y+1]=new SimpleDumpData(((Boolean)o).booleanValue()); else if(o instanceof Date) items[y+1]=new SimpleDumpData(Caster.toString(o)); else if(o instanceof Clob) items[y+1]=new SimpleDumpData(Caster.toString(o)); else items[y+1]=DumpUtil.toDumpData(o, pageContext,maxlevel,dp); } catch (PageException e) { items[y+1]=new SimpleDumpData("[empty]"); } } recs.appendRow(new DumpRow(1,items)); } if(!dp.getMetainfo()) return recs; //table.appendRow(1, new SimpleDumpData("result"), recs); return recs; } /** * sorts a query by a column * @param column colun to sort * @throws PageException */ public void sort(String column) throws PageException { sort(column,Query.ORDER_ASC); } /** * @see railo.runtime.type.Query#sort(railo.runtime.type.Collection.Key) */ public void sort(Collection.Key column) throws PageException { sort(column,Query.ORDER_ASC); } /** * sorts a query by a column * @param strColumn column to sort * @param order sort type (Query.ORDER_ASC or Query.ORDER_DESC) * @throws PageException */ public synchronized void sort(String strColumn, int order) throws PageException { //disconnectCache(); sort(getColumn(strColumn),order); } /** * @see railo.runtime.type.Query#sort(railo.runtime.type.Collection.Key, int) */ public synchronized void sort(Collection.Key keyColumn, int order) throws PageException { //disconnectCache(); sort(getColumn(keyColumn),order); } private void sort(QueryColumn column, int order) throws PageException { int type = column.getType(); SortRegister[] arr= ArrayUtil.toSortRegisterArray(column); Arrays.sort(arr, ( type==Types.BIGINT || type==Types.BIT || type==Types.INTEGER || type==Types.SMALLINT || type==Types.TINYINT || type==Types.DECIMAL || type==Types.DOUBLE || type==Types.NUMERIC || type==Types.REAL)? (Comparator)new NumberSortRegisterComparator(order==ORDER_ASC):(Comparator)new SortRegisterComparator(order==ORDER_ASC,true) ); for(int i=0;i<columns.length;i++) { column=columns[i]; int len=column.size(); QueryColumnImpl newCol=new QueryColumnImpl(this,columnNames[i],columns[i].getType(),len); for(int y=1;y<=len;y++) { newCol.set(y,column.get(arr[y-1].getOldPosition()+1)); } columns[i]=newCol; } } /** * @see railo.runtime.type.Query#addRow(int) */ public synchronized boolean addRow(int count) { //disconnectCache(); for(int i=0;i<columns.length;i++) { QueryColumnImpl column = columns[i]; column.addRow(count); } recordcount+=count; return true; } /** * @see railo.runtime.type.Query#addColumn(java.lang.String, railo.runtime.type.Array) */ public boolean addColumn(String columnName, Array content) throws DatabaseException { return addColumn(columnName,content,Types.OTHER); } public boolean addColumn(Collection.Key columnName, Array content) throws PageException { return addColumn(columnName,content,Types.OTHER); } /** * @throws DatabaseException * @see railo.runtime.type.Query#addColumn(java.lang.String, railo.runtime.type.Array, int) */ public synchronized boolean addColumn(String columnName, Array content, int type) throws DatabaseException { return addColumn(KeyImpl.init(columnName.trim()), content, type); } /** * @see railo.runtime.type.Query#addColumn(railo.runtime.type.Collection.Key, railo.runtime.type.Array, int) */ public boolean addColumn(Collection.Key columnName, Array content, int type) throws DatabaseException { //disconnectCache(); // TODO Meta type content=(Array) content.duplicate(false); if(getIndexFromKey(columnName)!=-1) throw new DatabaseException("column name ["+columnName.getString()+"] already exist",null,sql,null); if(content.size()!=getRecordcount()) { //throw new DatabaseException("array for the new column has not the same size like the query (arrayLen!=query.recordcount)"); if(content.size()>getRecordcount()) addRow(content.size()-getRecordcount()); else content.setEL(getRecordcount(),""); } QueryColumnImpl[] newColumns=new QueryColumnImpl[columns.length+1]; Collection.Key[] newColumnNames=new Collection.Key[columns.length+1]; for(int i=0;i<columns.length;i++) { newColumns[i]=columns[i]; newColumnNames[i]=columnNames[i]; } newColumns[columns.length]=new QueryColumnImpl(this,columnName,content,type ); newColumnNames[columns.length]=columnName; columns=newColumns; columnNames=newColumnNames; columncount++; return true; } /* * * if this query is still connected with cache (same query also in cache) * it will disconnetd from cache (clone object and add clone to cache) */ //protected void disconnectCache() {} /** * @see railo.runtime.type.Query#clone() */ public Object clone() { return cloneQuery(true); } /** * @see railo.runtime.type.Collection#duplicate(boolean) */ public Collection duplicate(boolean deepCopy) { return cloneQuery(true); } /** * @return clones the query object */ public QueryImpl cloneQuery(boolean deepCopy) { QueryImpl newResult=new QueryImpl(); ThreadLocalDuplication.set(this, newResult); try{ if(columnNames!=null){ newResult.columnNames=new Collection.Key[columnNames.length]; newResult.columns=new QueryColumnImpl[columnNames.length]; for(int i=0;i<columnNames.length;i++) { newResult.columnNames[i]=columnNames[i]; newResult.columns[i]=columns[i].cloneColumn(newResult,deepCopy); } } newResult.sql=sql; newResult.template=template; newResult.recordcount=recordcount; newResult.columncount=columncount; newResult.isCached=isCached; newResult.name=name; newResult.exeTime=exeTime; newResult.updateCount=updateCount; if(generatedKeys!=null)newResult.generatedKeys=generatedKeys.cloneQuery(false); return newResult; } finally { ThreadLocalDuplication.remove(this); } } /** * @see railo.runtime.type.Query#getTypes() */ public synchronized int[] getTypes() { int[] types=new int[columns.length]; for(int i=0;i<columns.length;i++) { types[i]=columns[i].getType(); } return types; } /** * @see railo.runtime.type.Query#getTypesAsMap() */ public synchronized Map getTypesAsMap() { Map map=new HashMap(); for(int i=0;i<columns.length;i++) { map.put(columnNames[i],columns[i].getTypeAsString()); } return map; } /** * @see railo.runtime.type.Query#getColumn(java.lang.String) */ public QueryColumn getColumn(String key) throws DatabaseException { return getColumn(KeyImpl.init(key.trim())); } /** * @see railo.runtime.type.Query#getColumn(railo.runtime.type.Collection.Key) */ public QueryColumn getColumn(Collection.Key key) throws DatabaseException { int index=getIndexFromKey(key); if(index!=-1) return columns[index]; if(key.getString().length()>0) { char c=key.lowerCharAt(0); if(c=='r') { if(key.equals(RECORDCOUNT)) return new QueryColumnRef(this,key,Types.INTEGER); } if(c=='c') { if(key.equals(CURRENTROW)) return new QueryColumnRef(this,key,Types.INTEGER); else if(key.equals(COLUMNLIST)) return new QueryColumnRef(this,key,Types.INTEGER); } } throw new DatabaseException("key ["+key.getString()+"] not found in query, columns are ["+getColumnlist(false)+"]",null,sql,null); } private void renameEL(Collection.Key src, Collection.Key trg) { int index=getIndexFromKey(src); if(index!=-1){ columnNames[index]=trg; columns[index].setKey(trg); } } public synchronized void rename(Collection.Key columnName,Collection.Key newColumnName) throws ExpressionException { int index=getIndexFromKey(columnName); if(index==-1) throw new ExpressionException("invalid column name definitions"); columnNames[index]=newColumnName; columns[index].setKey(newColumnName); } /** * * @see railo.runtime.type.Query#getColumn(java.lang.String, railo.runtime.type.QueryColumn) */ public QueryColumn getColumn(String key, QueryColumn defaultValue) { return getColumn(KeyImpl.init(key.trim()),defaultValue); } /** * @see railo.runtime.type.Query#getColumn(railo.runtime.type.Collection.Key, railo.runtime.type.QueryColumn) */ public QueryColumn getColumn(Collection.Key key, QueryColumn defaultValue) { int index=getIndexFromKey(key); if(index!=-1) return columns[index]; if(key.getString().length()>0) {//FUTURE add length method to Key Interface char c=key.lowerCharAt(0); if(c=='r') { if(key.equals(RECORDCOUNT)) return new QueryColumnRef(this,key,Types.INTEGER); } if(c=='c') { if(key.equals(CURRENTROW)) return new QueryColumnRef(this,key,Types.INTEGER); else if(key.equals(COLUMNLIST)) return new QueryColumnRef(this,key,Types.INTEGER); } } return defaultValue; } /** * @see java.lang.Object#toString() */ public String toString() { String[] keys=keysAsString(); StringBuffer sb=new StringBuffer(); sb.append("Query\n"); sb.append(" if(sql!=null) { sb.append(sql+"\n"); sb.append(" } if(exeTime>0) { sb.append("Execution Time: "+exeTime+"\n"); sb.append(" } sb.append("Recordcount: "+getRecordcount()+"\n"); sb.append(" String trenner=""; for(int i=0;i<keys.length;i++) { trenner+="+ } trenner+="+\n"; sb.append(trenner); // Header for(int i=0;i<keys.length;i++) { sb.append(getToStringField(keys[i])); } sb.append("|\n"); sb.append(trenner); sb.append(trenner); // body for(int i=0;i<recordcount;i++) { for(int y=0;y<keys.length;y++) { try { Object o=getAt(keys[y],i+1); if(o instanceof String)sb.append(getToStringField(o.toString())); else if(o instanceof Number) sb.append(getToStringField(Caster.toString(((Number)o).doubleValue()))); else if(o instanceof Clob) sb.append(getToStringField(Caster.toString(o))); else sb.append(getToStringField(o.toString())); } catch (PageException e) { sb.append(getToStringField("[empty]")); } } sb.append("|\n"); sb.append(trenner); } return sb.toString(); } private String getToStringField(String str) { if(str==null) return "| "; else if(str.length()<21) { String s="|"+str; for(int i=str.length();i<21;i++)s+=" "; return s; } else if(str.length()==21) return "|"+str; else return "|"+str.substring(0,18)+"..."; } /** * * @param type * @return return String represetation of a Type from int type */ public static String getColumTypeName(int type) { switch(type) { case Types.ARRAY: return "OBJECT"; case Types.BIGINT: return "BIGINT"; case Types.BINARY: return "BINARY"; case Types.BIT: return "BIT"; case Types.BLOB: return "OBJECT"; case Types.BOOLEAN: return "BOOLEAN"; case Types.CHAR: return "CHAR"; case Types.NCHAR: return "NCHAR"; case Types.CLOB: return "OBJECT"; case Types.NCLOB: return "OBJECT"; case Types.DATALINK: return "OBJECT"; case Types.DATE: return "DATE"; case Types.DECIMAL: return "DECIMAL"; case Types.DISTINCT: return "OBJECT"; case Types.DOUBLE: return "DOUBLE"; case Types.FLOAT: return "DOUBLE"; case Types.INTEGER: return "INTEGER"; case Types.JAVA_OBJECT: return "OBJECT"; case Types.LONGVARBINARY: return "LONGVARBINARY"; case Types.LONGVARCHAR: return "LONGVARCHAR"; case Types.NULL: return "OBJECT"; case Types.NUMERIC: return "NUMERIC"; case Types.OTHER: return "OBJECT"; case Types.REAL: return "REAL"; case Types.REF: return "OBJECT"; case Types.SMALLINT: return "SMALLINT"; case Types.STRUCT: return "OBJECT"; case Types.TIME: return "TIME"; case Types.TIMESTAMP: return "TIMESTAMP"; case Types.TINYINT: return "TINYINT"; case Types.VARBINARY: return "VARBINARY"; case Types.NVARCHAR: return "NVARCHAR"; case Types.VARCHAR: return "VARCHAR"; default : return "VARCHAR"; } } private int getIndexFromKey(String key) { String lc = StringUtil.toLowerCase(key); for(int i=0;i<columnNames.length;i++) { if(columnNames[i].getLowerString().equals(lc)) return i; } return -1; } private int getIndexFromKey(Collection.Key key) { for(int i=0;i<columnNames.length;i++) { if(columnNames[i].equalsIgnoreCase(key)) return i; } return -1; } /** * @see railo.runtime.type.Query#setExecutionTime(long) */ public void setExecutionTime(long exeTime) { this.exeTime=exeTime; } /** * @param maxrows * @return has cutted or not */ public synchronized boolean cutRowsTo(int maxrows) { //disconnectCache(); if(maxrows>-1 && maxrows<getRecordcount()) { for(int i=0;i<columns.length;i++) { QueryColumn column = columns[i]; column.cutRowsTo(maxrows); } recordcount=maxrows; return true; } return false; } /** * @see railo.runtime.type.Query#setCached(boolean) */ public void setCached(boolean isCached) { this.isCached=isCached; } /** * @see railo.runtime.type.Query#isCached() */ public boolean isCached() { return isCached; } /** * @see com.allaire.cfx.Query#addRow() */ public int addRow() { addRow(1); return getRecordcount(); } public Key getColumnName(int columnIndex) { Key[] keys = keys(); if(columnIndex<1 || columnIndex>keys.length) return null; return keys[columnIndex-1]; } /** * @see com.allaire.cfx.Query#getColumnIndex(java.lang.String) */ public int getColumnIndex(String coulmnName) { String[] keys = keysAsString(); for(int i=0;i<keys.length;i++) { if(keys[i].equalsIgnoreCase(coulmnName)) return i+1; } return -1; } /** * @see com.allaire.cfx.Query#getColumns() */ public String[] getColumns() { return getColumnNamesAsString(); } /** * @see railo.runtime.type.QueryPro#getColumnNames() */ public Collection.Key[] getColumnNames() { Collection.Key[] keys = keys(); Collection.Key[] rtn=new Collection.Key[keys.length]; System.arraycopy(keys,0,rtn,0,keys.length); return rtn; } public void setColumnNames(Collection.Key[] trg) throws PageException { columncount=trg.length; Collection.Key[] src = keys(); // target < source if(trg.length<src.length){ this.columnNames=new Collection.Key[trg.length]; QueryColumnImpl[] tmp=new QueryColumnImpl[trg.length]; for(int i=0;i<trg.length;i++){ this.columnNames[i]=trg[i]; tmp[i]=this.columns[i]; tmp[i].setKey(trg[i]); } this.columns=tmp; return; } if(trg.length>src.length){ int recordcount=getRecordcount(); for(int i=src.length;i<trg.length;i++){ Array arr=new ArrayImpl(); for(int r=1;r<=recordcount;r++){ arr.setE(i,""); } addColumn(trg[i], arr); } src = keys(); } for(int i=0;i<trg.length;i++){ this.columnNames[i]=trg[i]; this.columns[i].setKey(trg[i]); } } /** * @see railo.runtime.type.QueryPro#getColumnNamesAsString() */ public String[] getColumnNamesAsString() { String[] keys = keysAsString(); String[] rtn=new String[keys.length]; System.arraycopy(keys,0,rtn,0,keys.length); return rtn; } /** * @see com.allaire.cfx.Query#getData(int, int) */ public String getData(int row, int col) throws IndexOutOfBoundsException { String[] keys = keysAsString(); if(col<1 || col>keys.length) { new IndexOutOfBoundsException("invalid column index to retrieve Data from query, valid index goes from 1 to "+keys.length); } Object o=getAt(keys[col-1],row,null); if(o==null) throw new IndexOutOfBoundsException("invalid row index to retrieve Data from query, valid index goes from 1 to "+getRecordcount()); return Caster.toString( o,"" ); } /** * @see com.allaire.cfx.Query#getName() */ public String getName() { return this.name; } /** * @see com.allaire.cfx.Query#getRowCount() */ public int getRowCount() { return getRecordcount(); } /** * @see com.allaire.cfx.Query#setData(int, int, java.lang.String) */ public void setData(int row, int col, String value) throws IndexOutOfBoundsException { String[] keys = keysAsString(); if(col<1 || col>keys.length) { new IndexOutOfBoundsException("invalid column index to retrieve Data from query, valid index goes from 1 to "+keys.length); } try { setAt(keys[col-1],row,value); } catch (PageException e) { throw new IndexOutOfBoundsException("invalid row index to retrieve Data from query, valid index goes from 1 to "+getRecordcount()); } } /** * @see railo.runtime.type.Collection#containsKey(java.lang.String) */ public boolean containsKey(String key) { return getColumn(key,null)!=null; } /** * * @see railo.runtime.type.Collection#containsKey(railo.runtime.type.Collection.Key) */ public boolean containsKey(Collection.Key key) { return getColumn(key,null)!=null; } /** * @see railo.runtime.op.Castable#castToString() */ public String castToString() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Query to String", "Use Build-In-Function \"serialize(Query):String\" to create a String from Query"); } /** * @see railo.runtime.op.Castable#castToString(java.lang.String) */ public String castToString(String defaultValue) { return defaultValue; } /** * @see railo.runtime.op.Castable#castToBooleanValue() */ public boolean castToBooleanValue() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Query to a boolean value"); } /** * @see railo.runtime.op.Castable#castToBoolean(java.lang.Boolean) */ public Boolean castToBoolean(Boolean defaultValue) { return defaultValue; } /** * @see railo.runtime.op.Castable#castToDoubleValue() */ public double castToDoubleValue() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Query to a number value"); } /** * @see railo.runtime.op.Castable#castToDoubleValue(double) */ public double castToDoubleValue(double defaultValue) { return defaultValue; } /** * @see railo.runtime.op.Castable#castToDateTime() */ public DateTime castToDateTime() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Query to a Date"); } /** * @see railo.runtime.op.Castable#castToDateTime(railo.runtime.type.dt.DateTime) */ public DateTime castToDateTime(DateTime defaultValue) { return defaultValue; } /** * @see railo.runtime.op.Castable#compare(boolean) */ public int compareTo(boolean b) throws ExpressionException { throw new ExpressionException("can't compare Complex Object Type Query with a boolean value"); } /** * @see railo.runtime.op.Castable#compareTo(railo.runtime.type.dt.DateTime) */ public int compareTo(DateTime dt) throws PageException { throw new ExpressionException("can't compare Complex Object Type Query with a DateTime Object"); } /** * @see railo.runtime.op.Castable#compareTo(double) */ public int compareTo(double d) throws PageException { throw new ExpressionException("can't compare Complex Object Type Query with a numeric value"); } /** * @see railo.runtime.op.Castable#compareTo(java.lang.String) */ public int compareTo(String str) throws PageException { throw new ExpressionException("can't compare Complex Object Type Query with a String"); } public synchronized Array getMetaDataSimple() { Array cols=new ArrayImpl(); Struct column; for(int i=0;i<columns.length;i++) { column=new StructImpl(); column.setEL("name",columnNames[i].getString()); column.setEL("isCaseSensitive",Boolean.FALSE); column.setEL("typeName",columns[i].getTypeAsString()); cols.appendEL(column); } return cols; } public synchronized Struct _getMetaData() { Struct cols=new StructImpl(); for(int i=0;i<columns.length;i++) { cols.setEL(columnNames[i],columns[i].getTypeAsString()); } Struct sct=new StructImpl(); sct.setEL(KeyImpl.NAME_UC,getName()); sct.setEL(COLUMNS,cols); sct.setEL(SQL,sql==null?"":sql.toString()); sct.setEL(EXECUTION_TIME,new Double(exeTime)); sct.setEL(RECORDCOUNT,new Double(getRowCount())); sct.setEL(CACHED,Caster.toBoolean(isCached())); return sct; } /** * @return the sql */ public SQL getSql() { return sql; } /** * @param sql the sql to set */ public void setSql(SQL sql) { this.sql = sql; } /** * @see java.sql.ResultSet#getObject(java.lang.String) */ public Object getObject(String columnName) throws SQLException { int currentrow; if((currentrow=arrCurrentRow.get(getPid(),0))==0) return null; try { return getAt(columnName,currentrow); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getObject(int) */ public Object getObject(int columnIndex) throws SQLException { if(columnIndex>0 && columnIndex<=columncount) return getObject(this.columnNames[columnIndex-1].getString()); return null; } /** * @see java.sql.ResultSet#getString(int) */ public String getString(int columnIndex) throws SQLException { Object rtn = getObject(columnIndex); if(rtn==null)return null; if(Decision.isCastableToString(rtn)) return Caster.toString(rtn,null); throw new SQLException("can't cast value to string"); } /** * @see java.sql.ResultSet#getString(java.lang.String) */ public String getString(String columnName) throws SQLException { Object rtn = getObject(columnName); if(rtn==null)return null; if(Decision.isCastableToString(rtn)) return Caster.toString(rtn,null); throw new SQLException("can't cast value to string"); } /** * @see java.sql.ResultSet#getBoolean(int) */ public boolean getBoolean(int columnIndex) throws SQLException { Object rtn = getObject(columnIndex); if(rtn==null)return false; if(rtn!=null && Decision.isCastableToBoolean(rtn)) return Caster.toBooleanValue(rtn,false); throw new SQLException("can't cast value to boolean"); } /** * @see java.sql.ResultSet#getBoolean(java.lang.String) */ public boolean getBoolean(String columnName) throws SQLException { Object rtn = getObject(columnName); if(rtn==null)return false; if(rtn!=null && Decision.isCastableToBoolean(rtn)) return Caster.toBooleanValue(rtn,false); throw new SQLException("can't cast value to boolean"); } /** * * @see railo.runtime.type.Objects#call(railo.runtime.PageContext, java.lang.String, java.lang.Object[]) */ public Object call(PageContext pc, String methodName, Object[] arguments) throws PageException { return Reflector.callMethod(this,methodName,arguments); } /** * * @see railo.runtime.type.Objects#call(railo.runtime.PageContext, railo.runtime.type.Collection.Key, java.lang.Object[]) */ public Object call(PageContext pc, Key methodName, Object[] arguments) throws PageException { return Reflector.callMethod(this,methodName,arguments); } /** * * @see railo.runtime.type.Objects#callWithNamedValues(railo.runtime.PageContext, java.lang.String, railo.runtime.type.Struct) */ public Object callWithNamedValues(PageContext pc, String methodName,Struct args) throws PageException { throw new ExpressionException("No matching Method/Function ["+methodName+"] for call with named arguments found"); } /** * @see railo.runtime.type.Objects#callWithNamedValues(railo.runtime.PageContext, railo.runtime.type.Collection.Key, railo.runtime.type.Struct) */ public Object callWithNamedValues(PageContext pc, Key methodName, Struct args) throws PageException { throw new ExpressionException("No matching Method/Function ["+methodName.getString()+"] for call with named arguments found"); } /** * @see railo.runtime.type.Objects#get(railo.runtime.PageContext, java.lang.String, java.lang.Object) */ public Object get(PageContext pc, String key, Object defaultValue) { return getAt(key,arrCurrentRow.get(pc.getId(),1),defaultValue); } /** * @see railo.runtime.type.Objects#get(railo.runtime.PageContext, railo.runtime.type.Collection.Key, java.lang.Object) */ public Object get(PageContext pc, Key key, Object defaultValue) { return getAt(key,arrCurrentRow.get( pc.getId(),1),defaultValue); } /** * @see railo.runtime.type.Objects#get(railo.runtime.PageContext, java.lang.String) */ public Object get(PageContext pc, String key) throws PageException { return getAt(key,arrCurrentRow.get(pc.getId(),1)); } /** * @see railo.runtime.type.Objects#get(railo.runtime.PageContext, railo.runtime.type.Collection.Key) */ public Object get(PageContext pc, Key key) throws PageException { return getAt(key,arrCurrentRow.get(pc.getId(),1)); } /** * @see railo.runtime.type.Objects#isInitalized() */ public boolean isInitalized() { return true; } /** * @see railo.runtime.type.Objects#set(railo.runtime.PageContext, java.lang.String, java.lang.Object) */ public Object set(PageContext pc, String propertyName, Object value) throws PageException { return setAt(propertyName,arrCurrentRow.get(pc.getId(),1),value); } /** * @see railo.runtime.type.Objects#set(railo.runtime.PageContext, railo.runtime.type.Collection.Key, java.lang.Object) */ public Object set(PageContext pc, Key propertyName, Object value) throws PageException { return setAt(propertyName,arrCurrentRow.get(pc.getId(),1),value); } /** * @see railo.runtime.type.Objects#setEL(railo.runtime.PageContext, java.lang.String, java.lang.Object) */ public Object setEL(PageContext pc, String propertyName, Object value) { return setAtEL(propertyName,arrCurrentRow.get(pc.getId(),1),value); } /** * @see railo.runtime.type.Objects#setEL(railo.runtime.PageContext, railo.runtime.type.Collection.Key, java.lang.Object) */ public Object setEL(PageContext pc, Key propertyName, Object value) { return setAtEL(propertyName,arrCurrentRow.get(pc.getId(),1),value); } /** * @see java.sql.ResultSet#wasNull() */ public boolean wasNull() { throw new PageRuntimeException(new ApplicationException("method [wasNull] is not supported")); } /** * @see java.sql.ResultSet#absolute(int) */ public boolean absolute(int row) throws SQLException { if(recordcount==0) { if(row!=0) throw new SQLException("invalid row ["+row+"], query is Empty"); return false; } //row=row%recordcount; if(row>0) arrCurrentRow.set(getPid(),row); else arrCurrentRow.set(getPid(),(recordcount+1)+row); return true; } /** * @see java.sql.ResultSet#afterLast() */ public void afterLast() throws SQLException { arrCurrentRow.set(getPid(),recordcount+1); } /** * @see java.sql.ResultSet#beforeFirst() */ public void beforeFirst() throws SQLException { arrCurrentRow.set(getPid(),0); } /** * @see java.sql.ResultSet#cancelRowUpdates() */ public void cancelRowUpdates() throws SQLException { // ignored } /** * @see java.sql.ResultSet#clearWarnings() */ public void clearWarnings() throws SQLException { // ignored } /** * @see java.sql.ResultSet#close() */ public void close() throws SQLException { // ignored } /** * @see java.sql.ResultSet#deleteRow() */ public void deleteRow() throws SQLException { try { removeRow(arrCurrentRow.get(getPid())); } catch (Exception e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#findColumn(java.lang.String) */ public int findColumn(String columnName) throws SQLException { int index= getColumnIndex(columnName); if(index==-1) throw new SQLException("invald column definitions ["+columnName+"]"); return index; } /** * @see java.sql.ResultSet#first() */ public boolean first() throws SQLException { return absolute(1); } public java.sql.Array getArray(int i) throws SQLException { throw new SQLException("method is not implemented"); } public java.sql.Array getArray(String colName) throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getAsciiStream(int) */ public InputStream getAsciiStream(int columnIndex) throws SQLException { String res = getString(columnIndex); if(res==null)return null; return new ByteArrayInputStream(res.getBytes()); } /** * @see java.sql.ResultSet#getAsciiStream(java.lang.String) */ public InputStream getAsciiStream(String columnName) throws SQLException { String res = getString(columnName); if(res==null)return null; return new ByteArrayInputStream(res.getBytes()); } /** * @see java.sql.ResultSet#getBigDecimal(int) */ public BigDecimal getBigDecimal(int columnIndex) throws SQLException { return new BigDecimal(getDouble(columnIndex)); } /** * @see java.sql.ResultSet#getBigDecimal(java.lang.String) */ public BigDecimal getBigDecimal(String columnName) throws SQLException { return new BigDecimal(getDouble(columnName)); } /** * @see java.sql.ResultSet#getBigDecimal(int, int) */ public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { return new BigDecimal(getDouble(columnIndex)); } /** * @see java.sql.ResultSet#getBigDecimal(java.lang.String, int) */ public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException { return new BigDecimal(getDouble(columnName)); } /** * @see java.sql.ResultSet#getBinaryStream(int) */ public InputStream getBinaryStream(int columnIndex) throws SQLException { Object obj = getObject(columnIndex); if(obj==null)return null; try { return Caster.toBinaryStream(obj); } catch (Exception e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getBinaryStream(java.lang.String) */ public InputStream getBinaryStream(String columnName) throws SQLException { Object obj = getObject(columnName); if(obj==null)return null; try { return Caster.toBinaryStream(obj); } catch (Exception e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getBlob(int) */ public Blob getBlob(int i) throws SQLException { byte[] bytes = getBytes(i); if(bytes==null) return null; try { return BlobImpl.toBlob(bytes); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getBlob(java.lang.String) */ public Blob getBlob(String colName) throws SQLException { byte[] bytes = getBytes(colName); if(bytes==null) return null; try { return BlobImpl.toBlob(bytes); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getByte(int) */ public byte getByte(int columnIndex) throws SQLException { Object obj = getObject(columnIndex); if(obj==null) return (byte)0; try { return Caster.toByteValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getByte(java.lang.String) */ public byte getByte(String columnName) throws SQLException { Object obj = getObject(columnName); if(obj==null) return (byte)0; try { return Caster.toByteValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getBytes(int) */ public byte[] getBytes(int columnIndex) throws SQLException { Object obj = getObject(columnIndex); if(obj==null) return null; try { return Caster.toBytes(obj); } catch (Exception e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getBytes(java.lang.String) */ public byte[] getBytes(String columnName) throws SQLException { Object obj = getObject(columnName); if(obj==null) return null; try { return Caster.toBytes(obj); } catch (Exception e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getCharacterStream(int) */ public Reader getCharacterStream(int columnIndex) throws SQLException { String str=getString(columnIndex); if(str==null) return null; return new StringReader(str); } /** * @see java.sql.ResultSet#getCharacterStream(java.lang.String) */ public Reader getCharacterStream(String columnName) throws SQLException { String str=getString(columnName); if(str==null) return null; return new StringReader(str); } /** * @see java.sql.ResultSet#getClob(int) */ public Clob getClob(int i) throws SQLException { String str=getString(i); if(str==null) return null; return ClobImpl.toClob(str); } /** * @see java.sql.ResultSet#getClob(java.lang.String) */ public Clob getClob(String colName) throws SQLException { String str=getString(colName); if(str==null) return null; return ClobImpl.toClob(str); } /** * @see java.sql.ResultSet#getConcurrency() */ public int getConcurrency() throws SQLException { return 0; } /** * @see java.sql.ResultSet#getCursorName() */ public String getCursorName() throws SQLException { return null; } /** * @see java.sql.ResultSet#getDate(int) */ public java.sql.Date getDate(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return null; try { return new java.sql.Date(Caster.toDate(obj, false, null).getTime()); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getDate(java.lang.String) */ public java.sql.Date getDate(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return null; try { return new java.sql.Date(Caster.toDate(obj, false, null).getTime()); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getDate(int, java.util.Calendar) */ public java.sql.Date getDate(int columnIndex, Calendar cal)throws SQLException { return getDate(columnIndex); // TODO impl } /** * @see java.sql.ResultSet#getDate(java.lang.String, java.util.Calendar) */ public java.sql.Date getDate(String columnName, Calendar cal) throws SQLException { return getDate(columnName);// TODO impl } /** * @see java.sql.ResultSet#getDouble(int) */ public double getDouble(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return 0; try { return Caster.toDoubleValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getDouble(java.lang.String) */ public double getDouble(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return 0; try { return Caster.toDoubleValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getFetchDirection() */ public int getFetchDirection() throws SQLException { return 1000; } /** * @see java.sql.ResultSet#getFetchSize() */ public int getFetchSize() throws SQLException { return 0; } /** * @see java.sql.ResultSet#getFloat(int) */ public float getFloat(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return 0; try { return Caster.toFloatValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getFloat(java.lang.String) */ public float getFloat(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return 0; try { return Caster.toFloatValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getInt(int) */ public int getInt(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return 0; try { return Caster.toIntValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getInt(java.lang.String) */ public int getInt(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return 0; try { return Caster.toIntValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getLong(int) */ public long getLong(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return 0; try { return Caster.toLongValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getLong(java.lang.String) */ public long getLong(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return 0; try { return Caster.toLongValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getObject(int, java.util.Map) */ public Object getObject(int i, Map map) throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getObject(java.lang.String, java.util.Map) */ public Object getObject(String colName, Map map) throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getRef(int) */ public Ref getRef(int i) throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getRef(java.lang.String) */ public Ref getRef(String colName) throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getRow() */ public int getRow() throws SQLException { return arrCurrentRow.get(getPid(),0); } /** * @see java.sql.ResultSet#getShort(int) */ public short getShort(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return 0; try { return Caster.toShortValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getShort(java.lang.String) */ public short getShort(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return 0; try { return Caster.toShortValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } public Statement getStatement() throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getTime(int) */ public Time getTime(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return null; try { return new Time(DateCaster.toTime(null, obj).getTime()); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getTime(java.lang.String) */ public Time getTime(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return null; try { return new Time(DateCaster.toTime(null, obj).getTime()); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getTime(int, java.util.Calendar) */ public Time getTime(int columnIndex, Calendar cal) throws SQLException { return getTime(columnIndex);// TODO impl } /** * @see java.sql.ResultSet#getTime(java.lang.String, java.util.Calendar) */ public Time getTime(String columnName, Calendar cal) throws SQLException { return getTime(columnName);// TODO impl } /** * @see java.sql.ResultSet#getTimestamp(int) */ public Timestamp getTimestamp(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return null; try { return new Timestamp(DateCaster.toTime(null, obj).getTime()); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getTimestamp(java.lang.String) */ public Timestamp getTimestamp(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return null; try { return new Timestamp(DateCaster.toTime(null, obj).getTime()); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getTimestamp(int, java.util.Calendar) */ public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { return getTimestamp(columnIndex);// TODO impl } /** * @see java.sql.ResultSet#getTimestamp(java.lang.String, java.util.Calendar) */ public Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException { return getTimestamp(columnName);// TODO impl } /** * @see java.sql.ResultSet#getType() */ public int getType() throws SQLException { return 0; } /** * @see java.sql.ResultSet#getURL(int) */ public URL getURL(int columnIndex) throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getURL(java.lang.String) */ public URL getURL(String columnName) throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getUnicodeStream(int) */ public InputStream getUnicodeStream(int columnIndex) throws SQLException { String str=getString(columnIndex); if(str==null) return null; try { return new ByteArrayInputStream(str.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getUnicodeStream(java.lang.String) */ public InputStream getUnicodeStream(String columnName) throws SQLException { String str=getString(columnName); if(str==null) return null; try { return new ByteArrayInputStream(str.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getWarnings() */ public SQLWarning getWarnings() throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#insertRow() */ public void insertRow() throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#isAfterLast() */ public boolean isAfterLast() throws SQLException { return getCurrentrow()>recordcount; } /** * @see java.sql.ResultSet#isBeforeFirst() */ public boolean isBeforeFirst() throws SQLException { return arrCurrentRow.get(getPid(),0)==0; } /** * @see java.sql.ResultSet#isFirst() */ public boolean isFirst() throws SQLException { return arrCurrentRow.get(getPid(),0)==1; } public boolean isLast() throws SQLException { return arrCurrentRow.get(getPid(),0)==recordcount; } public boolean last() throws SQLException { return absolute(recordcount); } public void moveToCurrentRow() throws SQLException { // ignore } public void moveToInsertRow() throws SQLException { // ignore } public boolean previous() { return previous(getPid()); } public boolean previous(int pid) { if(0<(arrCurrentRow.set(pid,arrCurrentRow.get(pid,0)-1))) { return true; } arrCurrentRow.set(pid,0); return false; } public void refreshRow() throws SQLException { // ignore } /** * @see java.sql.ResultSet#relative(int) */ public boolean relative(int rows) throws SQLException { return absolute(getRow()+rows); } /** * @see java.sql.ResultSet#rowDeleted() */ public boolean rowDeleted() throws SQLException { return false; } /** * @see java.sql.ResultSet#rowInserted() */ public boolean rowInserted() throws SQLException { return false; } /** * @see java.sql.ResultSet#rowUpdated() */ public boolean rowUpdated() throws SQLException { return false; } public void setFetchDirection(int direction) throws SQLException { // ignore } public void setFetchSize(int rows) throws SQLException { // ignore } /** * @see java.sql.ResultSet#updateArray(int, java.sql.Array) */ public void updateArray(int columnIndex, java.sql.Array x)throws SQLException { updateObject(columnIndex, x.getArray()); } /** * @see java.sql.ResultSet#updateArray(java.lang.String, java.sql.Array) */ public void updateArray(String columnName, java.sql.Array x)throws SQLException { updateObject(columnName, x.getArray()); } /** * @see java.sql.ResultSet#updateAsciiStream(int, java.io.InputStream, int) */ public void updateAsciiStream(int columnIndex, InputStream x, int length)throws SQLException { updateBinaryStream(columnIndex, x, length); } /** * @see java.sql.ResultSet#updateAsciiStream(java.lang.String, java.io.InputStream, int) */ public void updateAsciiStream(String columnName, InputStream x, int length)throws SQLException { updateBinaryStream(columnName, x, length); } /** * @see java.sql.ResultSet#updateBigDecimal(int, java.math.BigDecimal) */ public void updateBigDecimal(int columnIndex, BigDecimal x)throws SQLException { updateObject(columnIndex, x.toString()); } /** * @see java.sql.ResultSet#updateBigDecimal(java.lang.String, java.math.BigDecimal) */ public void updateBigDecimal(String columnName, BigDecimal x) throws SQLException { updateObject(columnName, x.toString()); } /** * @see java.sql.ResultSet#updateBinaryStream(int, java.io.InputStream, int) */ public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException { try { updateObject(columnIndex, IOUtil.toBytesMax(x, length)); } catch (IOException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateBinaryStream(java.lang.String, java.io.InputStream, int) */ public void updateBinaryStream(String columnName, InputStream x, int length) throws SQLException { try { updateObject(columnName, IOUtil.toBytesMax(x, length)); } catch (IOException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateBlob(int, java.sql.Blob) */ public void updateBlob(int columnIndex, Blob x) throws SQLException { try { updateObject(columnIndex, toBytes(x)); } catch (IOException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateBlob(java.lang.String, java.sql.Blob) */ public void updateBlob(String columnName, Blob x) throws SQLException { try { updateObject(columnName, toBytes(x)); } catch (IOException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateBoolean(int, boolean) */ public void updateBoolean(int columnIndex, boolean x) throws SQLException { updateObject(columnIndex, Caster.toBoolean(x)); } /** * @see java.sql.ResultSet#updateBoolean(java.lang.String, boolean) */ public void updateBoolean(String columnName, boolean x) throws SQLException { updateObject(columnName, Caster.toBoolean(x)); } /** * @see java.sql.ResultSet#updateByte(int, byte) */ public void updateByte(int columnIndex, byte x) throws SQLException { updateObject(columnIndex, new Byte(x)); } /** * @see java.sql.ResultSet#updateByte(java.lang.String, byte) */ public void updateByte(String columnName, byte x) throws SQLException { updateObject(columnName, new Byte(x)); } /** * @see java.sql.ResultSet#updateBytes(int, byte[]) */ public void updateBytes(int columnIndex, byte[] x) throws SQLException { updateObject(columnIndex, x); } /** * @see java.sql.ResultSet#updateBytes(java.lang.String, byte[]) */ public void updateBytes(String columnName, byte[] x) throws SQLException { updateObject(columnName, x); } /** * @see java.sql.ResultSet#updateCharacterStream(int, java.io.Reader, int) */ public void updateCharacterStream(int columnIndex, Reader reader, int length)throws SQLException { try { updateObject(columnIndex, IOUtil.toString(reader)); } catch (Exception e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateCharacterStream(java.lang.String, java.io.Reader, int) */ public void updateCharacterStream(String columnName, Reader reader,int length) throws SQLException { try { updateObject(columnName, IOUtil.toString(reader)); } catch (Exception e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateClob(int, java.sql.Clob) */ public void updateClob(int columnIndex, Clob x) throws SQLException { try { updateObject(columnIndex, toString(x)); } catch (IOException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateClob(java.lang.String, java.sql.Clob) */ public void updateClob(String columnName, Clob x) throws SQLException { try { updateObject(columnName, toString(x)); } catch (IOException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateDate(int, java.sql.Date) */ public void updateDate(int columnIndex, java.sql.Date x)throws SQLException { updateObject(columnIndex, Caster.toDate(x, false, null, null)); } /** * @see java.sql.ResultSet#updateDate(java.lang.String, java.sql.Date) */ public void updateDate(String columnName, java.sql.Date x)throws SQLException { updateObject(columnName, Caster.toDate(x, false, null, null)); } /** * @see java.sql.ResultSet#updateDouble(int, double) */ public void updateDouble(int columnIndex, double x) throws SQLException { updateObject(columnIndex, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateDouble(java.lang.String, double) */ public void updateDouble(String columnName, double x) throws SQLException { updateObject(columnName, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateFloat(int, float) */ public void updateFloat(int columnIndex, float x) throws SQLException { updateObject(columnIndex, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateFloat(java.lang.String, float) */ public void updateFloat(String columnName, float x) throws SQLException { updateObject(columnName, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateInt(int, int) */ public void updateInt(int columnIndex, int x) throws SQLException { updateObject(columnIndex, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateInt(java.lang.String, int) */ public void updateInt(String columnName, int x) throws SQLException { updateObject(columnName, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateLong(int, long) */ public void updateLong(int columnIndex, long x) throws SQLException { updateObject(columnIndex, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateLong(java.lang.String, long) */ public void updateLong(String columnName, long x) throws SQLException { updateObject(columnName, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateNull(int) */ public void updateNull(int columnIndex) throws SQLException { updateObject(columnIndex, null); } /** * @see java.sql.ResultSet#updateNull(java.lang.String) */ public void updateNull(String columnName) throws SQLException { updateObject(columnName, null); } /** * @see java.sql.ResultSet#updateObject(int, java.lang.Object) */ public void updateObject(int columnIndex, Object x) throws SQLException { try { set(getColumnName(columnIndex), x); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateObject(java.lang.String, java.lang.Object) */ public void updateObject(String columnName, Object x) throws SQLException { try { set(KeyImpl.init(columnName), x); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateObject(int, java.lang.Object, int) */ public void updateObject(int columnIndex, Object x, int scale)throws SQLException { updateObject(columnIndex, x); } /** * @see java.sql.ResultSet#updateObject(java.lang.String, java.lang.Object, int) */ public void updateObject(String columnName, Object x, int scale)throws SQLException { updateObject(columnName, x); } /** * @see java.sql.ResultSet#updateRef(int, java.sql.Ref) */ public void updateRef(int columnIndex, Ref x) throws SQLException { updateObject(columnIndex, x.getObject()); } /** * @see java.sql.ResultSet#updateRef(java.lang.String, java.sql.Ref) */ public void updateRef(String columnName, Ref x) throws SQLException { updateObject(columnName, x.getObject()); } public void updateRow() throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#updateShort(int, short) */ public void updateShort(int columnIndex, short x) throws SQLException { updateObject(columnIndex, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateShort(java.lang.String, short) */ public void updateShort(String columnName, short x) throws SQLException { updateObject(columnName, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateString(int, java.lang.String) */ public void updateString(int columnIndex, String x) throws SQLException { updateObject(columnIndex, x); } /** * @see java.sql.ResultSet#updateString(java.lang.String, java.lang.String) */ public void updateString(String columnName, String x) throws SQLException { updateObject(columnName, x); } /** * @see java.sql.ResultSet#updateTime(int, java.sql.Time) */ public void updateTime(int columnIndex, Time x) throws SQLException { updateObject(columnIndex, new DateTimeImpl(x.getTime(),false)); } /** * @see java.sql.ResultSet#updateTime(java.lang.String, java.sql.Time) */ public void updateTime(String columnName, Time x) throws SQLException { updateObject(columnName, new DateTimeImpl(x.getTime(),false)); } /** * @see java.sql.ResultSet#updateTimestamp(int, java.sql.Timestamp) */ public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { updateObject(columnIndex, new DateTimeImpl(x.getTime(),false)); } /** * @see java.sql.ResultSet#updateTimestamp(java.lang.String, java.sql.Timestamp) */ public void updateTimestamp(String columnName, Timestamp x) throws SQLException { updateObject(columnName, new DateTimeImpl(x.getTime(),false)); } public ResultSetMetaData getMetaData() throws SQLException { throw new SQLException("method is not implemented"); } /** * @see railo.runtime.type.Collection#keyIterator() */ public Iterator keyIterator() { return new KeyIterator(keys()); } /** * @see railo.runtime.type.Iteratorable#iterator() */ public Iterator iterator() { return keyIterator(); } public Iterator valueIterator() { return new CollectionIterator(keys(),this); } public void readExternal(ObjectInput in) throws IOException { try { QueryImpl other=(QueryImpl) new CFMLExpressionInterpreter().interpret(ThreadLocalPageContext.get(),in.readUTF()); this.arrCurrentRow=other.arrCurrentRow; this.columncount=other.columncount; this.columnNames=other.columnNames; this.columns=other.columns; this.exeTime=other.exeTime; this.generatedKeys=other.generatedKeys; this.isCached=other.isCached; this.name=other.name; this.recordcount=other.recordcount; this.sql=other.sql; this.updateCount=other.updateCount; } catch (PageException e) { throw new IOException(e.getMessage()); } } public void writeExternal(ObjectOutput out) { try { out.writeUTF(new ScriptConverter().serialize(this)); } catch (Throwable t) {} } /** * @see railo.runtime.type.Sizeable#sizeOf() */ public long sizeOf(){ long size=SizeOf.size(this.exeTime)+ SizeOf.size(this.isCached)+ SizeOf.size(this.arrCurrentRow)+ SizeOf.size(this.columncount)+ SizeOf.size(this.generatedKeys)+ SizeOf.size(this.name)+ SizeOf.size(this.recordcount)+ SizeOf.size(this.sql)+ SizeOf.size(this.template)+ SizeOf.size(this.updateCount); for(int i=0;i<columns.length;i++){ size+=this.columns[i].sizeOf(); } return size; } public boolean equals(Object obj){ if(!(obj instanceof Collection)) return false; return CollectionUtil.equals(this,(Collection)obj); } public int getHoldability() throws SQLException { throw notSupported(); } public boolean isClosed() throws SQLException { return false; } public void updateNString(int columnIndex, String nString)throws SQLException { updateString(columnIndex, nString); } public void updateNString(String columnLabel, String nString)throws SQLException { updateString(columnLabel, nString); } public String getNString(int columnIndex) throws SQLException { return getString(columnIndex); } public String getNString(String columnLabel) throws SQLException { return getString(columnLabel); } public Reader getNCharacterStream(int columnIndex) throws SQLException { return getCharacterStream(columnIndex); } public Reader getNCharacterStream(String columnLabel) throws SQLException { return getCharacterStream(columnLabel); } public void updateNCharacterStream(int columnIndex, Reader x, long length)throws SQLException { updateCharacterStream(columnIndex, x, length); } public void updateNCharacterStream(String columnLabel, Reader reader,long length) throws SQLException { throw notSupported(); } public void updateAsciiStream(int columnIndex, InputStream x, long length)throws SQLException { throw notSupported(); } public void updateBinaryStream(int columnIndex, InputStream x, long length)throws SQLException { throw notSupported(); } public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException { throw notSupported(); } public void updateAsciiStream(String columnLabel, InputStream x, long length)throws SQLException { throw notSupported(); } public void updateBinaryStream(String columnLabel, InputStream x,long length) throws SQLException { throw notSupported(); } public void updateCharacterStream(String columnLabel, Reader reader,long length) throws SQLException { throw notSupported(); } public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException { throw notSupported(); } public void updateBlob(String columnLabel, InputStream inputStream,long length) throws SQLException { throw notSupported(); } public void updateClob(int columnIndex, Reader reader, long length) throws SQLException { throw notSupported(); } public void updateClob(String columnLabel, Reader reader, long length) throws SQLException { throw notSupported(); } public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException { updateClob(columnIndex, reader, length); } public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException { updateClob(columnLabel, reader,length); } public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException { updateCharacterStream(columnIndex, x); } public void updateNCharacterStream(String columnLabel, Reader reader)throws SQLException { throw notSupported(); } public void updateAsciiStream(int columnIndex, InputStream x)throws SQLException { throw notSupported(); } public void updateBinaryStream(int columnIndex, InputStream x)throws SQLException { throw notSupported(); } public void updateCharacterStream(int columnIndex, Reader x) throws SQLException { throw notSupported(); } public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException { throw notSupported(); } public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException { throw notSupported(); } public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException { throw notSupported(); } public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException { throw notSupported(); } public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException { throw notSupported(); } public void updateClob(int columnIndex, Reader reader) throws SQLException { throw notSupported(); } public void updateClob(String columnLabel, Reader reader) throws SQLException { throw notSupported(); } public void updateNClob(int columnIndex, Reader reader) throws SQLException { updateClob(columnIndex, reader); } public void updateNClob(String columnLabel, Reader reader) throws SQLException { updateClob(columnLabel, reader); } public <T> T unwrap(Class<T> iface) throws SQLException { throw notSupported(); } public boolean isWrapperFor(Class<?> iface) throws SQLException { throw notSupported(); } //JDK6: uncomment this for compiling with JDK6 public void updateNClob(int columnIndex, NClob nClob) throws SQLException { throw notSupported(); } public void updateNClob(String columnLabel, NClob nClob) throws SQLException { throw notSupported(); } public NClob getNClob(int columnIndex) throws SQLException { throw notSupported(); } public NClob getNClob(String columnLabel) throws SQLException { throw notSupported(); } public SQLXML getSQLXML(int columnIndex) throws SQLException { throw notSupported(); } public SQLXML getSQLXML(String columnLabel) throws SQLException { throw notSupported(); } public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException { throw notSupported(); } public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException { throw notSupported(); } public RowId getRowId(int columnIndex) throws SQLException { throw notSupported(); } public RowId getRowId(String columnLabel) throws SQLException { throw notSupported(); } public void updateRowId(int columnIndex, RowId x) throws SQLException { throw notSupported(); } public void updateRowId(String columnLabel, RowId x) throws SQLException { throw notSupported(); } private SQLException notSupported() { return new SQLException("this feature is not supported"); } private RuntimeException notSupportedEL() { return new RuntimeException(new SQLException("this feature is not supported")); } }
package net.sf.taverna.t2.workflowmodel.processor.iteration; import java.util.HashMap; import java.util.Map; import net.sf.taverna.t2.invocation.Completion; import net.sf.taverna.t2.invocation.TreeCache; import net.sf.taverna.t2.reference.T2Reference; import net.sf.taverna.t2.workflowmodel.processor.activity.Job; /** * The dot product matches jobs by index array, when a job is received a job is * emited if and only if the index array of the new job is matched exactly by * index arrays of one job in each other input index. * * @author Tom Oinn * */ public class DotProduct extends CompletionHandlingAbstractIterationStrategyNode { Map<String, TreeCache[]> ownerToCache = new HashMap<String, TreeCache[]>(); @Override public synchronized void innerReceiveJob(int inputIndex, Job newJob) { if (getChildCount() == 1) { // if there's only one input there's nothing to do here so push the // job through pushJob(newJob); return; } String owningProcess = newJob.getOwningProcess(); if (!ownerToCache.containsKey(owningProcess)) { TreeCache[] caches = new TreeCache[getChildCount()]; for (int i = 0; i < getChildCount(); i++) { caches[i] = new TreeCache(); } ownerToCache.put(owningProcess, caches); } // Firstly store the new job in the cache, this isn't optimal but is // safe for now - we can make this more efficient by doing the // comparison first and only storing the job if required TreeCache[] caches = ownerToCache.get(owningProcess); caches[inputIndex].insertJob(newJob); int[] indexArray = newJob.getIndex(); boolean foundMatch = true; Map<String, T2Reference> newDataMap = new HashMap<String, T2Reference>(); for (TreeCache cache : caches) { if (cache.containsLocation(indexArray)) { newDataMap.putAll(cache.get(indexArray).getData()); } else { foundMatch = false; } } if (foundMatch) { Job j = new Job(owningProcess, indexArray, newDataMap, newJob .getContext()); // Remove all copies of the job with this index from the cache, // we'll never use it // again and it pays to be tidy for (TreeCache cache : caches) { cache.cut(indexArray); } pushJob(j); } } /** * Delegate to the superclass to propogate completion events if and only if * the completion event is a final one. We can potentially implement finer * grained logic here in the future. */ @Override public synchronized void innerReceiveCompletion(int inputIndex, Completion completion) { // Do nothing, let the superclass handle final completion events, ignore // others for now (although in theory we should be able to do better // than this really) } @Override protected synchronized void cleanUp(String owningProcess) { ownerToCache.remove(owningProcess); } public int getIterationDepth(Map<String, Integer> inputDepths) throws IterationTypeMismatchException { // Check that all input depths are the same if (isLeaf()) { // No children! throw new IterationTypeMismatchException("Dot product with no children"); } int depth = getChildAt(0).getIterationDepth(inputDepths); for (IterationStrategyNode childNode : getChildren()) { if (childNode.getIterationDepth(inputDepths) != depth) { throw new IterationTypeMismatchException( "Mismatched input types for dot product node"); } } return depth; } }
package org.opendaylight.yangtools.yang.model.util.type; import static java.util.Objects.requireNonNull; import com.google.common.collect.ImmutableList; import java.util.Collection; import org.eclipse.jdt.annotation.NonNull; import org.opendaylight.yangtools.concepts.Builder; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.opendaylight.yangtools.yang.model.api.TypeDefinition; import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode; public abstract class TypeBuilder<T extends TypeDefinition<T>> implements Builder<T> { private final ImmutableList.Builder<UnknownSchemaNode> unknownSchemaNodes = ImmutableList.builder(); private final @NonNull SchemaPath path; private final T baseType; TypeBuilder(final T baseType, final SchemaPath path) { this.path = requireNonNull(path); this.baseType = baseType; } final T getBaseType() { return baseType; } final @NonNull SchemaPath getPath() { return path; } final @NonNull Collection<? extends UnknownSchemaNode> getUnknownSchemaNodes() { return unknownSchemaNodes.build(); } public final void addUnknownSchemaNode(final @NonNull UnknownSchemaNode node) { unknownSchemaNodes.add(node); } }
package com.afollestad.silk.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import com.afollestad.silk.caching.SilkComparable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * A BaseAdapter wrapper that makes creating list adapters easier. Contains various convenience methods and handles * recycling views on its own. * * @param <ItemType> The type of items held in the adapter. * @author Aidan Follestad (afollestad) */ public abstract class SilkAdapter<ItemType extends SilkComparable> extends BaseAdapter implements ScrollStatePersister { private final Context context; private final List<ItemType> items; private boolean isChanged = false; private int mScrollState = AbsListView.OnScrollListener.SCROLL_STATE_IDLE; public SilkAdapter(Context context) { this.context = context; this.items = new ArrayList<ItemType>(); } /** * Called to get the layout of a view being inflated by the SilkAdapter. The inheriting adapter class must return * the layout for list items, this should always be the same value unless you have multiple view types. * <p/> * If you override {#getItemViewType} and/or {#getViewTypeCount}, the parameter to this method will be filled with * the item type at the index of the item view being inflated. Otherwise, it can be ignored. */ protected abstract int getLayout(int index, int type); /** * Called when a list item view is inflated and the inheriting adapter must fill in views in the inflated layout. * The second parameter ('recycled') should be returned at the end of the method. * * @param index The index of the inflated view. * @param recycled The layout with views to be filled (e.g. text views). * @param item The item at the current index of the adapter. */ public abstract View onViewCreated(int index, View recycled, ItemType item); /** * Gets the context passed in the constructor, that's used for inflating views. */ protected final Context getContext() { return context; } /** * Adds an item at a specific index inside the adapter. */ public void add(int index, ItemType toAdd) { isChanged = true; this.items.add(index, toAdd); notifyDataSetChanged(); } /** * Adds a list of items to the adapter and notifies the attached Listview. * * @param index The index to begin adding items at (inserted starting here). * @param toAdd The items to add. */ public final void add(int index, List<ItemType> toAdd) { for (ItemType aToAdd : toAdd) { add(index, aToAdd); index++; } } /** * Adds a single item to the adapter and notifies the attached ListView. */ public void add(ItemType toAdd) { isChanged = true; this.items.add(toAdd); notifyDataSetChanged(); } /** * Adds an array of items to the adapter and notifies the attached ListView. */ public final void add(ItemType[] toAdd) { add(new ArrayList<ItemType>(Arrays.asList(toAdd))); } /** * Adds a list of items to the adapter and notifies the attached Listview. */ public final void add(List<ItemType> toAdd) { isChanged = true; for (ItemType item : toAdd) add(item); } /** * Updates a single item in the adapter using isSame() from SilkComparable. Once the filter finds the item, the loop is broken * so you cannot update multiple items with a single call. * <p/> * If the item is not found, it will be added to the adapter. * * @return True if the item was updated. */ public boolean update(ItemType toUpdate) { return update(toUpdate, true); } /** * Updates a single item in the adapter using isSame() from SilkComparable. Once the filter finds the item, the loop is broken * so you cannot update multiple items with a single call. * * @param addIfNotFound Whether or not the item will be added if it's not found. * @return True if the item was updated or added. */ public boolean update(ItemType toUpdate, boolean addIfNotFound) { boolean found = false; for (int i = 0; i < items.size(); i++) { if (toUpdate.equalTo(items.get(i))) { items.set(i, toUpdate); found = true; break; } } if (found) return true; else if (addIfNotFound) { add(toUpdate); return true; } return false; } /** * Sets the items in the adapter (clears any previous ones before adding) and notifies the attached ListView. */ public final void set(ItemType[] toSet) { set(new ArrayList<ItemType>(Arrays.asList(toSet))); } /** * Sets the items in the adapter (clears any previous ones before adding) and notifies the attached ListView. */ public final void set(List<ItemType> toSet) { isChanged = true; this.items.clear(); for (ItemType item : toSet) add(item); } /** * Checks whether or not the adapter contains an item based on the adapter's inherited Filter. */ public final boolean contains(ItemType item) { for (int i = 0; i < getCount(); i++) { ItemType curItem = getItem(i); if (item.equalTo(curItem)) return true; } return false; } /** * Removes an item from the list by its index. */ public void remove(int index) { isChanged = true; this.items.remove(index); notifyDataSetChanged(); } /** * Removes a single item in the adapter using isSame() from SilkComparable. Once the filter finds the item, the loop is broken * so you cannot remove multiple items with a single call. */ public void remove(ItemType toRemove) { for (int i = 0; i < items.size(); i++) { if (toRemove.equalTo(items.get(i))) { this.remove(i); break; } } } /** * Removes an array of items from the adapter, uses isSame() from SilkComparable to find the items. */ public final void remove(ItemType[] toRemove) { for (ItemType item : toRemove) remove(item); } /** * Clears all items from the adapter and notifies the attached ListView. */ public void clear() { isChanged = true; this.items.clear(); notifyDataSetChanged(); } /** * Gets a list of all items in the adapter. */ public final List<ItemType> getItems() { return items; } @Override public int getCount() { return items.size(); } @Override public ItemType getItem(int i) { return items.get(i); } @Override public long getItemId(int i) { long id = getItemId(getItem(i)); if (id < 0) id = i; return id; } public abstract long getItemId(ItemType item); /** * @deprecated Override {@link #onViewCreated(int, android.view.View, com.afollestad.silk.caching.SilkComparable)} instead. */ @Override public View getView(int i, View view, ViewGroup viewGroup) { if (view == null) { int type = getItemViewType(i); view = LayoutInflater.from(context).inflate(getLayout(i, type), null); } return onViewCreated(i, view, getItem(i)); } /** * Resets the changed state of the adapter, indicating that the adapter has not been changed. Every call * to a mutator method (e.g. add, set, remove, clear) will set it back to true. */ public void resetChanged() { isChanged = false; } /** * Marks the adapter as changed. */ public void markChanged() { isChanged = true; } /** * Gets whether or not the adapter has been changed since the last time {#resetChanged} was called. */ public final boolean isChanged() { return isChanged; } /** * Gets the scroll state set by a {@link com.afollestad.silk.views.list.SilkListView}. */ @Override public final int getScrollState() { return mScrollState; } /** * Used by the {@link com.afollestad.silk.views.list.SilkListView} to update the adapter with its scroll state. */ @Override public final void setScrollState(int state) { mScrollState = state; } }
package liquibase.util; import java.io.File; import java.io.IOException; public class FileUtil { /** * Schedule a file to be deleted when JVM exits. * If file is directory delete it and all sub-directories. */ public static void forceDeleteOnExit(final File file) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { FileUtil.deleteDirectory(file); } catch (IOException e) { e.printStackTrace(); } } }); } /** * Recursively schedule directory for deletion on JVM exit. */ private static void deleteDirectory(final File directory) throws IOException { if (!directory.exists()) { return; } cleanDirectory(directory); if (!directory.delete()) { throw new IOException("Cannot delete " + directory.getAbsolutePath()); } } /** * Clean a directory without deleting it. */ private static void cleanDirectory(final File directory) throws IOException { if (!directory.exists()) { return; } if (!directory.isDirectory()) { return; } IOException exception = null; final File[] files = directory.listFiles(); if (files != null) { for (final File file : files) { try { cleanDirectory(file); if (!file.delete()) { throw new IOException("Cannot delete " + file.getAbsolutePath()); } } catch (final IOException ioe) { exception = ioe; } } } if (null != exception) { throw exception; } } }
package mil.nga.giat.mage; import android.Manifest; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.design.widget.NavigationView; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.content.ContextCompat; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AlertDialog; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import dagger.android.support.DaggerAppCompatActivity; import mil.nga.geopackage.validate.GeoPackageValidate; import mil.nga.giat.mage.cache.GeoPackageCacheUtils; import mil.nga.giat.mage.event.ChangeEventActivity; import mil.nga.giat.mage.event.EventActivity; import mil.nga.giat.mage.glide.GlideApp; import mil.nga.giat.mage.glide.model.Avatar; import mil.nga.giat.mage.help.HelpActivity; import mil.nga.giat.mage.login.LoginActivity; import mil.nga.giat.mage.map.MapFragment; import mil.nga.giat.mage.map.cache.CacheProvider; import mil.nga.giat.mage.newsfeed.ObservationFeedFragment; import mil.nga.giat.mage.newsfeed.PeopleFeedFragment; import mil.nga.giat.mage.preferences.GeneralPreferencesActivity; import mil.nga.giat.mage.profile.ProfileActivity; import mil.nga.giat.mage.sdk.datastore.DaoStore; import mil.nga.giat.mage.sdk.datastore.user.Event; import mil.nga.giat.mage.sdk.datastore.user.EventHelper; import mil.nga.giat.mage.sdk.datastore.user.User; import mil.nga.giat.mage.sdk.datastore.user.UserHelper; import mil.nga.giat.mage.sdk.exceptions.EventException; import mil.nga.giat.mage.sdk.exceptions.UserException; import mil.nga.giat.mage.sdk.utils.MediaUtility; /** * This is the Activity that holds other fragments. Map, feeds, etc. It * starts and stops much of the context. It also contains menus . * */ public class LandingActivity extends DaggerAppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { /** * Extra key for storing the local file path used to launch MAGE */ public static final String EXTRA_OPEN_FILE_PATH = "extra_open_file_path"; private static final String BOTTOM_NAVIGATION_ITEM = "BOTTOM_NAVIGATION_ITEM"; private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 100; private static final int PERMISSIONS_REQUEST_ACCESS_STORAGE= 200; private static final int PERMISSIONS_REQUEST_OPEN_FILE = 300; private static final int PERMISSIONS_REQUEST_FOREGROUND_SERVICE = 400; private static final int AUTHENTICATE_REQUEST = 500; private static final int CHANGE_EVENT_REQUEST = 600; @Inject protected MageApplication application; private int currentNightMode; private static final String LOG_NAME = LandingActivity.class.getName(); private NavigationView navigationView; private DrawerLayout drawerLayout; private BottomNavigationView bottomNavigationView; private List<Fragment> bottomNavigationFragments = new ArrayList<>(); private boolean locationPermissionGranted = false; private Uri openUri; private String openPath; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_landing); drawerLayout = findViewById(R.id.drawer_layout); navigationView = findViewById(R.id.navigation); navigationView.setNavigationItemSelectedListener(this); currentNightMode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK; bottomNavigationFragments.add(new MapFragment()); bottomNavigationFragments.add(new ObservationFeedFragment()); bottomNavigationFragments.add(new PeopleFeedFragment()); // TODO investigate moving this call // its here because this is the first activity started after login and it ensures // the user has selected an event. However there are other instances that could // bring the user back to this activity in which this has already been called, // i.e. after TokenExpiredActivity. application.onLogin(); CacheProvider.getInstance(getApplicationContext()).refreshTileOverlays(); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); setTitle(); setRecentsEvents(); locationPermissionGranted = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; if (locationPermissionGranted) { if (shouldReportLocation()) { application.startLocationService(); } } else { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { new AlertDialog.Builder(LandingActivity.this, R.style.AppCompatAlertDialogStyle) .setTitle(R.string.location_access_rational_title) .setMessage(R.string.location_access_rational_message) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(LandingActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); } }) .create() .show(); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); } } getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp); getSupportActionBar().setDisplayHomeAsUpEnabled(true); View headerView = navigationView.getHeaderView(0); headerView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onNavigationItemSelected(navigationView.getMenu().findItem(R.id.profile_navigation)); } }); // Check if MAGE was launched with a local file openPath = getIntent().getStringExtra(EXTRA_OPEN_FILE_PATH); if (openPath != null) { if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle) .setTitle(R.string.cache_access_rational_title) .setMessage(R.string.cache_access_rational_message) .setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(LandingActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_OPEN_FILE); } }) .show(); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_OPEN_FILE); } } else { // Else, store the path to pass to further intents handleOpenFilePath(); } } bottomNavigationView = findViewById(R.id.bottom_navigation); bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switchBottomNavigationFragment(item); return true; } }); MenuItem menuItem = bottomNavigationView.getMenu().findItem(R.id.map_tab); if (savedInstanceState != null) { int item = savedInstanceState.getInt(BOTTOM_NAVIGATION_ITEM); menuItem = bottomNavigationView.getMenu().findItem(item); } switchBottomNavigationFragment(menuItem); } @Override protected void onResume() { super.onResume(); View headerView = navigationView.getHeaderView(0); try { final ImageView avatarImageView = headerView.findViewById(R.id.avatar_image_view); User user = UserHelper.getInstance(getApplicationContext()).readCurrentUser(); GlideApp.with(this) .load(Avatar.Companion.forUser(user)) .circleCrop() .fallback(R.drawable.ic_account_circle_white_48dp) .error(R.drawable.ic_account_circle_white_48dp) .into(avatarImageView); TextView displayName = headerView.findViewById(R.id.display_name); displayName.setText(user.getDisplayName()); TextView email = headerView.findViewById(R.id.email); email.setText(user.getEmail()); email.setVisibility(StringUtils.isNoneBlank(user.getEmail()) ? View.VISIBLE : View.GONE); } catch (UserException e) { Log.e(LOG_NAME, "Error pulling current user from the database", e); } // This activity is 'singleTop' and as such will not recreate itself based on a uiMode configuration change. // Force this by check if the uiMode has changed. int nightMode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK; if (nightMode != currentNightMode) { recreate(); } if (shouldReportLocation() && locationPermissionGranted != (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)) { locationPermissionGranted = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; application.startLocationService(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(BOTTOM_NAVIGATION_ITEM, bottomNavigationView.getSelectedItemId()); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: { locationPermissionGranted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED; if (shouldReportLocation()) { application.startLocationService(); } break; } case PERMISSIONS_REQUEST_ACCESS_STORAGE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { CacheProvider.getInstance(getApplicationContext()).refreshTileOverlays(); } break; } case PERMISSIONS_REQUEST_OPEN_FILE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { handleOpenFilePath(); } else { if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { // User denied storage with never ask again. Since they will get here // by opening a cache into MAGE, give them a dialog that will // by opening a cache into MAGE, give them a dialog that will showDisabledPermissionsDialog( getResources().getString(R.string.cache_access_title), getResources().getString(R.string.cache_access_message)); } } break; } } } private void setTitle() { Event event = EventHelper.getInstance(getApplicationContext()).getCurrentEvent(); getSupportActionBar().setTitle(event.getName()); } private void setRecentsEvents() { Menu menu = navigationView.getMenu(); Menu recentEventsMenu = menu.findItem(R.id.recents_events_item).getSubMenu(); recentEventsMenu.removeGroup(R.id.events_group); EventHelper eventHelper = EventHelper.getInstance(getApplicationContext()); try { final Event currentEvent = eventHelper.getCurrentEvent(); menu.findItem(R.id.event_navigation).setTitle(currentEvent.getName()).setActionView(R.layout.navigation_item_info); Iterable<Event> recentEvents = Iterables.filter(eventHelper.getRecentEvents(), new Predicate<Event>() { @Override public boolean apply(Event event) { return !event.getRemoteId().equals(currentEvent.getRemoteId()); } }); int i = 1; for (final Event event : recentEvents) { MenuItem item = recentEventsMenu .add(R.id.events_group, Menu.NONE, i++, event.getName()) .setIcon(R.drawable.ic_restore_black_24dp); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { drawerLayout.closeDrawer(GravityCompat.START); Intent intent = new Intent(LandingActivity.this, ChangeEventActivity.class); intent.putExtra(ChangeEventActivity.EVENT_ID_EXTRA, event.getId()); startActivityForResult(intent, CHANGE_EVENT_REQUEST); return true; } }); } MenuItem item = recentEventsMenu .add(R.id.events_group, Menu.NONE, i, "More Events") .setIcon(R.drawable.ic_event_note_white_24dp); item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { drawerLayout.closeDrawer(GravityCompat.START); Intent intent = new Intent(LandingActivity.this, ChangeEventActivity.class); startActivityForResult(intent, CHANGE_EVENT_REQUEST); return true; } }); } catch (EventException e) { e.printStackTrace(); } } private void showDisabledPermissionsDialog(String title, String message) { new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle) .setTitle(title) .setMessage(message) .setPositiveButton(R.string.settings, new Dialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.fromParts("package", getApplicationContext().getPackageName(), null)); startActivity(intent); } }) .setNegativeButton(android.R.string.cancel, null) .show(); } private boolean shouldReportLocation() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); return preferences.getBoolean(getString(R.string.reportLocationKey), getResources().getBoolean(R.bool.reportLocationDefaultValue)); } @Override public boolean onNavigationItemSelected(MenuItem menuItem) { drawerLayout.closeDrawer(GravityCompat.START); switch (menuItem.getItemId()) { case R.id.event_navigation: { Event event = EventHelper.getInstance(getApplicationContext()).getCurrentEvent(); Intent intent = new Intent(LandingActivity.this, EventActivity.class); intent.putExtra(EventActivity.Companion.getEVENT_ID_EXTRA(), event.getId()); startActivityForResult(intent, CHANGE_EVENT_REQUEST); break; } case R.id.profile_navigation: { Intent intent = new Intent(this, ProfileActivity.class); startActivity(intent); break; } case R.id.settings_navigation: { Intent intent = new Intent(this, GeneralPreferencesActivity.class); startActivity(intent); break; } case R.id.help_navigation: { Intent intent = new Intent(this, HelpActivity.class); startActivity(intent); break; } case R.id.logout_navigation: { application.onLogout(true, new MageApplication.OnLogoutListener() { @Override public void onLogout() { Intent intent = new Intent(getApplicationContext(), LoginActivity.class); startActivity(intent); finish(); } }); break; } } return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: drawerLayout.openDrawer(GravityCompat.START); break; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CHANGE_EVENT_REQUEST) { if (resultCode == RESULT_OK) { setTitle(); setRecentsEvents(); } } } private void switchBottomNavigationFragment(MenuItem item) { Fragment fragment = null; switch (item.getItemId()) { case R.id.map_tab: fragment = bottomNavigationFragments.get(0); break; case R.id.observations_tab: fragment = bottomNavigationFragments.get(1); break; case R.id.people_tab: fragment = bottomNavigationFragments.get(2); break; } if (fragment != null) { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.navigation_content, fragment).commit(); } } /** * Handle opening the file path that MAGE was launched with */ private void handleOpenFilePath() { File cacheFile = new File(openPath); // Handle GeoPackage files by linking them to their current location if (GeoPackageValidate.hasGeoPackageExtension(cacheFile)) { String cacheName = GeoPackageCacheUtils.importGeoPackage(this, cacheFile); if (cacheName != null) { CacheProvider.getInstance(getApplicationContext()).enableAndRefreshTileOverlays(cacheName); } } } public static void deleteAllData(Context context) { DaoStore.getInstance(context).resetDatabase(); PreferenceManager.getDefaultSharedPreferences(context).edit().clear().commit(); deleteDir(MediaUtility.getMediaStageDirectory(context)); clearApplicationData(context); } public static void clearApplicationData(Context context) { File cache = context.getCacheDir(); File appDir = new File(cache.getParent()); if (appDir.exists()) { String[] children = appDir.list(); for (String s : children) { if (!s.equals("lib") && !s.equals("databases")) { File f = new File(appDir, s); Log.d(LOG_NAME, "Deleting " + f.getAbsolutePath()); deleteDir(f); } } } deleteDir(MediaUtility.getMediaStageDirectory(context)); } public static boolean deleteDir(File dir) { if (dir != null && dir.isDirectory()) { String[] children = dir.list(); for (String kid : children) { boolean success = deleteDir(new File(dir, kid)); if (!success) { return false; } } } if (dir == null) { return true; } return dir.delete(); } }
package cgeo.geocaching.utils; import cgeo.geocaching.BuildConfig; public class BranchDetectionHelper { // should contain the version name of the last feature release public static final String FEATURE_VERSION_NAME = "2021.11.16-RC"; private BranchDetectionHelper() { // utility class } /** * @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy) */ @SuppressWarnings("ConstantConditions") // BUILD_TYPE is detected as constant but can change depending on the build configuration public static boolean isProductionBuild() { return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly")); } }
package com.zeyad.genericusecase.domain.interactors; import android.content.Context; import android.database.sqlite.SQLiteOpenHelper; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import com.zeyad.genericusecase.Config; import com.zeyad.genericusecase.data.mappers.EntityDataMapper; import com.zeyad.genericusecase.data.mappers.EntityMapper; import com.zeyad.genericusecase.data.network.ApiConnectionFactory; import com.zeyad.genericusecase.data.utils.EntityMapperUtil; import com.zeyad.genericusecase.data.utils.IEntityMapperUtil; import com.zeyad.genericusecase.data.utils.Utils; public class GenericUseCaseFactory { private static IGenericUseCase sGenericUseCase; public static IGenericUseCase getInstance() { return sGenericUseCase; } /** * initializes the Generic Use Case with given context without a DB option. * * @param context context of activity/application */ public static void initWithoutDB(@NonNull Context context) { Config.init(context); Config.getInstance().setPrefFileName("com.generic.use.case.PREFS"); ApiConnectionFactory.init(); GenericUseCase.initWithoutDB(new EntityMapperUtil() { @NonNull @Override public EntityMapper getDataMapper(Class dataClass) { return new EntityDataMapper(); } }); sGenericUseCase = GenericUseCase.getInstance(); } /** * initializes the Generic Use Case with Realm given context. * * @param context context of activity/application * @param entityMapper */ public static void initWithRealm(@NonNull Context context, @Nullable IEntityMapperUtil entityMapper) { initCore(context, null, entityMapper); sGenericUseCase = GenericUseCase.getInstance(); } /** * initializes the Generic Use Case with SQLBrite given context. * * @param context context of application */ public static void initWithSQLBrite(@NonNull Context context, @NonNull SQLiteOpenHelper sqLiteOpenHelper) { initCore(context, sqLiteOpenHelper, null); sGenericUseCase = GenericUseCase.getInstance(); } static void initCore(@NonNull Context context, SQLiteOpenHelper sqLiteOpenHelper, @Nullable IEntityMapperUtil entityMapper) { if (!Utils.doesContextBelongsToApplication(context)) throw new IllegalArgumentException("Context should be application context only."); Config.init(context); Config.getInstance().setPrefFileName("com.generic.use.case.PREFS"); ApiConnectionFactory.init(); if (entityMapper == null) entityMapper = new EntityMapperUtil() { @NonNull @Override public EntityMapper getDataMapper(Class dataClass) { return new EntityDataMapper(); } }; if (sqLiteOpenHelper == null) GenericUseCase.initWithRealm(entityMapper); else GenericUseCase.initWithSQLBrite(sqLiteOpenHelper, entityMapper); } /** * This method is meant for test purposes only. Use other versions of initRealm for production code. * * @param genericUseCase mocked generic use(expected) or any IGenericUseCase implementation */ @VisibleForTesting private static void init(IGenericUseCase genericUseCase) { sGenericUseCase = genericUseCase; } }
package org.swows.web; import java.io.BufferedReader; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.swows.graph.DynamicDatasetMap; import org.swows.graph.EventCachingGraph; import org.swows.graph.events.DynamicGraph; import org.swows.graph.events.DynamicGraphFromGraph; import org.swows.producer.DataflowProducer; import org.swows.runnable.RunnableContext; import org.swows.runnable.RunnableContextFactory; import org.swows.vocabulary.DOMEvents; import org.swows.vocabulary.SWI; import org.swows.xmlinrdf.DocumentReceiver; import org.swows.xmlinrdf.DomDecoder; import org.swows.xmlinrdf.EventManager; import org.w3c.dom.Attr; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.events.Event; import org.w3c.dom.events.EventListener; import org.w3c.dom.events.EventTarget; import org.w3c.dom.events.MutationEvent; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSOutput; import org.w3c.dom.ls.LSSerializer; import com.hp.hpl.jena.graph.Graph; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.NodeFactory; public class WebApp implements EventManager { private EventCachingGraph cachingGraph = null; private boolean docLoadedOnClient = false; private Document document = null; // private boolean docToBeRealoaded = false; private DOMImplementation domImpl; private final WebInput webInput = new WebInput(); private static final Logger logger = Logger.getLogger(WebApp.class); private static final String JS_CALLBACK_FUNCTION_NAME = "swowsEvent"; // private static final String JS_CALLBACK_BODY = // "var reqTxt = '" + // "@prefix evt: <http://www.swows.org/2013/07/xml-dom-events // "_:newEvent a evt:Event; '; " + //// "for (var i = 0; i < evt.length; i++) { " + //// "reqText += '<' + evt[i] + '>'; " + // "reqTxt += '" + // "evt:target <' + tn(evt.target).getAttribute('resource') + '>; " + // "evt:currentTarget <' + tn(evt.currentTarget).getAttribute('resource') + '>; " + // "evt:type \"' + evt.type + '\".'; " + // "var req = new XMLHttpRequest(); req.open('POST','',false); " + // "req.send(reqTxt); " + //// "alert(req.responseText); " + // "eval(req.responseText); "; private String jsCallbackBody; private static final String JS_TARGET_CB_FUNCTION = "var evtQueue = []; " + "var evtsByTargetAndType = {}; " + "var addEvtToQueue = function (evt) { " + "var evtsByType = evtsByTargetAndType[evt.target]; " + "if (evtsByType) { " + "var prevEvt = evtsByType[evt.type]; " + "} else { " + "var evtsByType = []; " + "evtsByTargetAndType[evt.target] = evtsByType; " + "}; " + "if (prevEvt) { " + "evtQueue[evtQueue.indexOf(prevEvt)] = evt; " + "} else { " + "evtQueue.push(evt); " + "}; " + "evtsByType[evt.type] = evt; " + "}; " + "var evtFromQueue = function (evt) { " + "var evt = evtQueue.shift(); " + "var evtsByType = evtsByTargetAndType[evt.target]; " + "delete evtsByType[evt.type]; " + "if (evtsByType.length == 0) delete evtsByTargetAndType[evt.target]; " + "return evt; " + "}; " + "var tn = function (t) { return t.correspondingUseElement ? t.correspondingUseElement : t; }; " + "var res = function (obj) { " + "switch(typeof obj) { " + "case 'boolean': " + "case 'number': " + "return obj; " + "case 'string': " + "case 'xml': " + "return '\"' + obj + '\"'; " + "case 'object': " + "return (obj instanceof Node) " + "? ( '<' + obj.getAttribute('resource') + '>' ) " + ": ( (obj instanceof Number || obj instanceof Boolean) " + "? obj " + ": ( (obj instanceof String) " + "? ('\"' + obj + '\"') " + ": ( (obj instanceof Object) " + "? ('\"' + obj + '\"') " + // "? ('[ ' + predList(obj) + ' ]') " + ": ('\"' + obj + '\"') ) ) ) ; " + "default: " + "return '\"' + obj + '\"'; " + "} " + "}; " + "var predList = function (obj) { " + "return Object.keys(obj) " + ".filter(function(k) {return !(obj[k] == undefined);}) " + ".map(function(k) { return 'evt:' + k + ' ' + res(tn(obj[k])) + ' '; }).join('; '); " + "}; "; private static final String CHARACTER_ENCODING = "utf-8"; private static final String JS_CONTENT_TYPE = "application/javascript"; // private StringBuffer clientCommandsCache = null; private StringBuffer clientAddCommandsCache = null; private StringBuffer clientChangeCommandsCache = null; private StringBuffer clientRemoveCommandsCache = null; private static final int CLIENT_COMMANDS_CACHE_CAPACITY = 256; private static final String CLIENT_COMMANDS_SEP = ";"; private int newNodeCount = 0; private Map<org.w3c.dom.Node, Integer> newNodeIds; private void resetCommandSet() { clientAddCommandsCache = null; clientChangeCommandsCache = null; clientRemoveCommandsCache = null; newNodeCount = 0; newNodeIds = null; } private String newNode2varName(org.w3c.dom.Node node) { if (newNodeIds == null) newNodeIds = new HashMap<org.w3c.dom.Node, Integer>(); Integer nodeId = newNodeIds.get(node); if (nodeId == null) { nodeId = newNodeCount++; newNodeIds.put(node, nodeId); } return "newNode_" + nodeId; } private String node2varName(org.w3c.dom.Node node) { if (newNodeIds == null) return null; Integer nodeId = newNodeIds.get(node); if (nodeId == null) return null; return "newNode_" + nodeId; } // TODO: it would be possible useful to use deflate/inflate for client server communication // Maybe for http is possible to use browser native decompression // private void addClientCommand(String command) { // if (command != null) { // if (clientCommandsCache == null) // clientCommandsCache = // new StringBuffer(CLIENT_COMMANDS_CACHE_CAPACITY); // clientCommandsCache.append(command); // clientCommandsCache.append(CLIENT_COMMANDS_SEP); private void addClientAddCommand(String command) { if (command != null) { if (clientAddCommandsCache == null) clientAddCommandsCache = new StringBuffer(CLIENT_COMMANDS_CACHE_CAPACITY); clientAddCommandsCache.append(command); clientAddCommandsCache.append(CLIENT_COMMANDS_SEP); } } private void addClientChangeCommand(String command) { if (command != null) { if (clientChangeCommandsCache == null) clientChangeCommandsCache = new StringBuffer(CLIENT_COMMANDS_CACHE_CAPACITY); clientChangeCommandsCache.append(command); clientChangeCommandsCache.append(CLIENT_COMMANDS_SEP); } } private void addClientRemoveCommand(String command) { if (command != null) { if (clientRemoveCommandsCache == null) clientRemoveCommandsCache = new StringBuffer(CLIENT_COMMANDS_CACHE_CAPACITY); clientRemoveCommandsCache.append(command); clientRemoveCommandsCache.append(CLIENT_COMMANDS_SEP); } } private void addDOMListeners() { logger.debug("Started registering DOM mutation listeners"); // ((EventTarget) xmlDoc) // .addEventListener( // "DOMSubtreeModified", // domGenericEventListener, // false); ((EventTarget) document) .addEventListener( "DOMNodeInserted", new EventListener() { public void handleEvent(Event event) { logger.debug("DOMNodeInserted event"); addNodeInsert((MutationEvent) event); } }, false); ((EventTarget) document) .addEventListener( "DOMNodeRemoved", new EventListener() { public void handleEvent(Event event) { logger.debug("DOMNodeRemoved event"); addNodeRemoval((MutationEvent) event); } }, false); ((EventTarget) document) .addEventListener( "DOMNodeRemovedFromDocument", new EventListener() { public void handleEvent(Event event) { logger.debug("DOMNodeRemovedFromDocument event"); addNodeRemovalFromDoc((MutationEvent) event); } }, false); ((EventTarget) document) .addEventListener( "DOMNodeInsertedIntoDocument", new EventListener() { public void handleEvent(Event event) { logger.debug("DOMNodeInsertedIntoDocument event"); addNodeCreation((MutationEvent) event); } }, false); ((EventTarget) document) .addEventListener( "DOMAttrModified", new EventListener() { public void handleEvent(Event event) { logger.trace("DOMAttrModified event of type " + ((MutationEvent) event).getAttrChange()); addAttrModify((MutationEvent) event); } }, false); ((EventTarget) document) .addEventListener( "DOMCharacterDataModified", new EventListener() { public void handleEvent(Event event) { logger.trace("DOMCharacterDataModified event"); addCharacterDataModify((MutationEvent) event); } }, false); logger.debug("Ended registering DOM mutation listeners"); } private void setOnload(String onloadBody) { Element docElem = document.getDocumentElement(); if ( docElem.getNodeName().equals("html") || docElem.getLocalName().equals("html") ) ((Element) docElem.getLastChild()).setAttribute("onload", onloadBody); // ((Element) docElem.getElementsByTagName("body").item(0)).setAttribute("onload", onloadBody); if ( docElem.getNodeName().equals("svg") || docElem.getLocalName().equals("svg") ) docElem.setAttribute("onload", onloadBody); } private void setDocument(Document newDocument) { document = newDocument; // setOnload( JS_TARGET_CB_FUNCTION + "var " + JS_CALLBACK_FUNCTION_NAME + " = function (evt) { " + jsCallbackBody +" }; " + genAddEventListeners() ); setOnload( JS_TARGET_CB_FUNCTION + JS_CALLBACK_FUNCTION_NAME + " = function (evt) { " + jsCallbackBody +" }; " + genAddEventListeners() ); // setOnload( JS_TARGET_CB_FUNCTION + "function " + JS_CALLBACK_FUNCTION_NAME + "(evt) { " + jsCallbackBody +" }; " + genAddEventListeners() ); addDOMListeners(); } public WebApp( Graph dataflowGraph, String requestURL ) { jsCallbackBody = "var reqTxt = '" + "@prefix evt: <" + DOMEvents.getURI() + "> . " + "_:newEvent a evt:Event; '; " + "reqTxt += predList(evt) + ' .'; " + "var req = new XMLHttpRequest(); req.open('POST','" + requestURL + "',false); " + "req.send(reqTxt); " + "eval(req.responseText); "; RunnableContextFactory.setDefaultRunnableContext(new RunnableContext() { public synchronized void run(final Runnable runnable) { // try { // while (!docLoadedOnClient || cachingGraph == null) Thread.yield(); // final long start = System.currentTimeMillis(); runnable.run(); // long afterCascade = System.currentTimeMillis(); // System.out.println( // "RDF envent cascade executed in " // + (afterCascade - runEntered) + "ms" ); cachingGraph.sendEvents(); // long afterSvgDom = System.currentTimeMillis(); // System.out.println( // "SVG DOM updated in " // + (afterSvgDom - afterCascade) + "ms" ); // long runFinished = System.currentTimeMillis(); // System.out.println( // "SVG updated and repainted in " // + (runFinished - start + "ms" ) ); if (!docLoadedOnClient) { askForReload(); } // } catch(InterruptedException e) { // throw new RuntimeException(e); } }); // final WebInput webInput = new WebInput(); // final SystemTime systemTime = new SystemTime(); final DynamicDatasetMap inputDatasetGraph = new DynamicDatasetMap(webInput.getGraph()); inputDatasetGraph.addGraph(NodeFactory.createURI(SWI.getURI() + "mouseEvents"), webInput.getGraph()); DataflowProducer applyOps = new DataflowProducer(new DynamicGraphFromGraph(dataflowGraph), inputDatasetGraph); DynamicGraph outputGraph = applyOps.createGraph(inputDatasetGraph); cachingGraph = new EventCachingGraph(outputGraph); // cachingGraph = new EventCachingGraph( new LoggingGraph(outputGraph, Logger.getRootLogger(), true, true) ); try { domImpl = (DOMImplementationRegistry.newInstance().getDOMImplementation("XML 3.0 +MutationEvents 2.0") != null) ? DOMImplementationRegistry.newInstance().getDOMImplementation("XML 3.0 +MutationEvents 2.0") : domImpl; logger.debug("Loaded DOM implementation: " + domImpl); // logger.debug("XML DOM Level 1: " + domImpl.hasFeature("XML", "1.0")); // logger.debug("XML DOM Level 2: " + domImpl.hasFeature("XML", "2.0")); // logger.debug("XML DOM Level 3: " + domImpl.hasFeature("XML", "3.0")); // logger.debug("Core DOM Level 1: " + domImpl.hasFeature("Core", "1.0")); // logger.debug("Core DOM Level 2: " + domImpl.hasFeature("Core", "2.0")); // logger.debug("Core DOM Level 3: " + domImpl.hasFeature("Core", "3.0")); // logger.debug("Events DOM Level 1: " + domImpl.hasFeature("+Events", "1.0")); // logger.debug("Events DOM Level 2: " + domImpl.hasFeature("+Events", "2.0")); // logger.debug("Events DOM Level 3: " + domImpl.hasFeature("+Events", "3.0")); // logger.debug("MutationEvents DOM Level 1: " + domImpl.hasFeature("+MutationEvents", "1.0")); // logger.debug("MutationEvents DOM Level 2: " + domImpl.hasFeature("+MutationEvents", "2.0")); // logger.debug("MutationEvents DOM Level 3: " + domImpl.hasFeature("+MutationEvents", "3.0")); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (ClassCastException e) { throw new RuntimeException(e); } // Set<DomEventListener> domEventListenerSet = new HashSet <DomEventListener>(); // domEventListenerSet.add(mouseInput); // Map<String,Set<DomEventListener>> domEventListeners = new HashMap <String,Set<DomEventListener>>(); // domEventListeners.put("click", domEventListenerSet); // domEventListeners.put("mousedown", domEventListenerSet); // domEventListeners.put("mouseup", domEventListenerSet); setDocument( DomDecoder.decodeOne( cachingGraph, // outputGraph, // new LoggingGraph(cachingGraph, Logger.getRootLogger(), true, true), domImpl /*, new RunnableContext() { @Override public void run(Runnable runnable) { try { batikRunnableQueue.invokeAndWait(runnable); } catch(InterruptedException e) { throw new RuntimeException(e); } } } */, new DocumentReceiver() { // (new Thread() { // public void run() { // while (true) { // while (newDocument == null) yield(); // RunnableQueue runnableQueue = batikRunnableQueue; // runnableQueue.suspendExecution(true); // batikRunnableQueue = null; //// batikRunnableQueue.getThread().halt(); //// batikRunnableQueue = null; // svgCanvas.setDocument(newDocument); // newDocument = null; // batikRunnableQueue.resumeExecution(); // }).start(); // private Document newDocument = null; public void sendDocument(Document doc) { setDocument(doc); docLoadedOnClient = false; } }, // domEventListeners, this)); // TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Transformer transformer; // try { // transformer = transformerFactory.newTransformer(); // DOMSource source = new DOMSource(xmlDoc); // StreamResult result = new StreamResult(System.out); // transformer.transform(source, result); // } catch (TransformerException e) { // e.printStackTrace(); } private void askForReload() { // TODO Auto-generated method stub } private String clientNodeIdentifier(org.w3c.dom.Node node) { String varName = node2varName(node); if (varName != null) return varName; if (node instanceof Element) { Element element = (Element) node; NamedNodeMap attrs = element.getAttributes(); for (int attrIndex = 0; attrIndex < attrs.getLength(); attrIndex++ ) { Attr attr = (Attr) attrs.item(attrIndex); if (attr.isId() || attr.getName().equalsIgnoreCase("id") // TODO: delete this two lines of workaround and find better way to manage id attrs || attr.getName().equals("xml:id") ) return "document.getElementById('" + attr.getValue() + "')"; } } org.w3c.dom.Node parent = node.getParentNode(); if (parent instanceof Document) return "document.documentElement"; int childIndex = 0; for (org.w3c.dom.Node currNode = node; currNode != parent.getFirstChild(); currNode = currNode.getPreviousSibling()) childIndex++; return clientNodeIdentifier(parent) + ".childNodes[" + childIndex + "]"; } Map<org.w3c.dom.Node, Set<String>> listenedNodeAndTypes = new HashMap<org.w3c.dom.Node, Set<String>>(); private String genAddEventListener( org.w3c.dom.Node target, String type, boolean useCapture) { if (target instanceof Element) { return clientNodeIdentifier(target) + ".addEventListener( '" + type + "', " + JS_CALLBACK_FUNCTION_NAME + ", " + useCapture + " )"; } return ""; } private String genAddEventListeners(org.w3c.dom.Node target) { StringBuffer buffer = new StringBuffer(CLIENT_COMMANDS_CACHE_CAPACITY); for (String type : listenedNodeAndTypes.get(target)) buffer .append( genAddEventListener(target, type, false) ) .append( CLIENT_COMMANDS_SEP ); // TODO: manage useCapture if to be used at all return buffer.toString(); } private String genAddEventListeners() { StringBuffer buffer = new StringBuffer(CLIENT_COMMANDS_CACHE_CAPACITY); for (org.w3c.dom.Node target : listenedNodeAndTypes.keySet()) for (String type : listenedNodeAndTypes.get(target)) buffer .append( genAddEventListener(target, type, false) ) .append( CLIENT_COMMANDS_SEP ); // TODO: manage useCapture if to be used at all return buffer.toString(); } public void addEventListener( Node targetNode, org.w3c.dom.Node target, String type, EventListener listener, boolean useCapture) { // ((Element) target).setAttribute("on" + type, JS_CALLBACK); logger.trace("addEventListener() called"); Set<String> listenedTypesForTarget = listenedNodeAndTypes.get(target); if (listenedTypesForTarget == null) { listenedTypesForTarget = new HashSet<String>(); listenedNodeAndTypes.put(target, listenedTypesForTarget); } listenedTypesForTarget.add(type); if (docLoadedOnClient) { // String clientNodeId = clientNodeIdentifier(target); // if (clientNodeId != null) { // addClientCommand( genAddEventListener(target, type, useCapture) ); // } else { logger.trace("setting attribute on" + type + ":" + JS_CALLBACK_FUNCTION_NAME + "(event)"); ((Element) target).setAttribute("on" + type, JS_CALLBACK_FUNCTION_NAME + "(event)"); } } private void addAttrModify(MutationEvent event) { if (!docLoadedOnClient) return; String elemId = clientNodeIdentifier((org.w3c.dom.Node) event.getTarget()); String nsURI = event.getRelatedNode().getNamespaceURI(); String cmd = null; switch(event.getAttrChange()) { case MutationEvent.ADDITION : case MutationEvent.MODIFICATION : if (nsURI != null) cmd = elemId + ".setAttributeNS('" + nsURI + "','" + event.getAttrName() + "','" + stringEncode(event.getNewValue()) + "')"; else cmd = elemId + ".setAttribute('" + event.getAttrName() + "','" + stringEncode(event.getNewValue()) + "')"; break; case MutationEvent.REMOVAL : if (nsURI != null) cmd = elemId + ".removeAttributeNS('" + nsURI + "','" + event.getAttrName() + "')"; else cmd = elemId + ".removeAttribute('" + event.getAttrName() + "')"; break; } if (cmd != null) addClientChangeCommand( cmd ); } private void addCharacterDataModify(MutationEvent event) { if (!docLoadedOnClient) return; String elemId = clientNodeIdentifier((org.w3c.dom.Node) event.getTarget()); String cmd = null; cmd = elemId + ".nodeValue = '" + stringEncode(((MutationEvent) event).getNewValue()) + "'"; if (cmd != null) addClientChangeCommand( cmd ); } private void addNodeCreation(MutationEvent event) { if (!docLoadedOnClient) return; org.w3c.dom.Node newNode = (org.w3c.dom.Node) event.getTarget(); String nsURI = newNode.getNamespaceURI(); String cmd = null; switch(newNode.getNodeType()) { case(org.w3c.dom.Node.ATTRIBUTE_NODE) : if (nsURI != null) cmd = "var " + newNode2varName(newNode) + " = document.createAttributeNS('" + nsURI + "','" + newNode.getNodeName() + "')"; else cmd = "var " + newNode2varName(newNode) + " = document.createAttribute('" + newNode.getNodeName() + "')"; break; case(org.w3c.dom.Node.ELEMENT_NODE) : if (nsURI != null) cmd = "var " + newNode2varName(newNode) + " = document.createElementNS('" + nsURI + "','" + newNode.getNodeName() + "')"; else cmd = "var " + newNode2varName(newNode) + " = document.createElement('" + newNode.getNodeName() + "')"; break; case(org.w3c.dom.Node.TEXT_NODE) : cmd = "var " + newNode2varName(newNode) + " = document.createText('" + stringEncode(newNode.getNodeValue()) + "')"; break; case(org.w3c.dom.Node.DOCUMENT_FRAGMENT_NODE) : cmd = "var " + newNode2varName(newNode) + " = document.createDocumentFragment()"; break; case(org.w3c.dom.Node.COMMENT_NODE) : cmd = "var " + newNode2varName(newNode) + " = document.createComment('" + stringEncode(newNode.getNodeValue()) + "')"; break; } if (cmd != null) addClientAddCommand( cmd ); } private String stringEncode(String inputString) { return inputString.replace("'", "\\'"); } private String addCompleteNodeCreation(org.w3c.dom.Node newNode) { String varName = node2varName(newNode); if (varName != null) return varName; String nsURI = newNode.getNamespaceURI(); String cmd = null; varName = newNode2varName(newNode); switch(newNode.getNodeType()) { case(org.w3c.dom.Node.ATTRIBUTE_NODE) : if (nsURI != null) cmd = "var " + varName + " = document.createAttributeNS('" + nsURI + "','" + newNode.getNodeName() + "')"; else cmd = "var " + varName + " = document.createAttribute('" + newNode.getNodeName() + "')"; break; case(org.w3c.dom.Node.ELEMENT_NODE) : if (nsURI != null) cmd = "var " + varName + " = document.createElementNS('" + nsURI + "','" + newNode.getNodeName() + "')"; else cmd = "var " + varName + " = document.createElement('" + newNode.getNodeName() + "')"; NamedNodeMap attrMap = newNode.getAttributes(); for (int attrIndex = 0; attrIndex < attrMap.getLength(); attrIndex++) { Attr attr = (Attr) attrMap.item(attrIndex); String attrNsURI = attr.getNamespaceURI(); if (attrNsURI != null) cmd += "; " + varName + ".setAttributeNS('" + attrNsURI + "','" + attr.getName() + "','" + stringEncode(attr.getValue()) + "')"; else cmd += "; " + varName + ".setAttribute('" + attr.getName() + "','" + stringEncode(attr.getValue()) + "')"; } NodeList children = newNode.getChildNodes(); for (int childIndex = 0; childIndex < children.getLength(); childIndex++) { org.w3c.dom.Node child = children.item(childIndex); cmd += "; " + varName + ".appendChild(" + addCompleteNodeCreation(child) + ")"; } // NodeList children = newNode.getChildNodes(); // for (int childIndex = 0; childIndex < children.getLength(); childIndex++) { if (listenedNodeAndTypes.containsKey(newNode)) cmd += "; " + genAddEventListeners(newNode); break; case(org.w3c.dom.Node.TEXT_NODE) : cmd = "var " + varName + " = document.createTextNode('" + stringEncode(newNode.getNodeValue()) + "')"; break; case(org.w3c.dom.Node.DOCUMENT_FRAGMENT_NODE) : cmd = "var " + varName + " = document.createDocumentFragment()"; break; case(org.w3c.dom.Node.COMMENT_NODE) : cmd = "var " + varName + " = document.createComment('" + stringEncode(newNode.getNodeValue()) + "')"; break; } if (cmd != null) addClientAddCommand( cmd ); return varName; } private void addNodeRemovalFromDoc(MutationEvent event) { } private void addNodeInsert(MutationEvent event) { if (!docLoadedOnClient) return; org.w3c.dom.Node node = (org.w3c.dom.Node) event.getTarget(); org.w3c.dom.Node parentNode = (org.w3c.dom.Node) event.getRelatedNode(); org.w3c.dom.Node nextSibling = node.getNextSibling(); addClientAddCommand( clientNodeIdentifier(parentNode) + ( (nextSibling != null) ? ".insertBefore(" + addCompleteNodeCreation(node) + "," + clientNodeIdentifier(nextSibling) + ")" : ".appendChild(" + addCompleteNodeCreation(node) + ")" ) ); } private void addNodeRemoval(MutationEvent event) { if (!docLoadedOnClient) return; org.w3c.dom.Node childNode = (org.w3c.dom.Node) event.getTarget(); org.w3c.dom.Node parentNode = (org.w3c.dom.Node) event.getRelatedNode(); addClientAddCommand(clientNodeIdentifier(parentNode) + ".removeChild(" + clientNodeIdentifier(childNode) + ")"); } public void removeEventListener( Node targetNode, org.w3c.dom.Node target, String type, EventListener listener, boolean useCapture) { Set<String> listenedTypesForTarget = listenedNodeAndTypes.get(target); if (listenedTypesForTarget != null) { listenedTypesForTarget.remove(type); if (listenedTypesForTarget.isEmpty()) listenedNodeAndTypes.remove(target); } // if (target instanceof Element) { // ((Element) target).removeAttribute("on" + type); if (docLoadedOnClient) addClientRemoveCommand( clientNodeIdentifier(target) + ".removeEventListener( '" + type + "', " + JS_CALLBACK_FUNCTION_NAME + ", " + useCapture + " )"); } private String getContentType() { Element docElem = document.getDocumentElement(); if ( docElem.getNodeName().equals("html") || docElem.getLocalName().equals("html") ) return "text/html"; if ( docElem.getNodeName().equals("svg") || docElem.getLocalName().equals("svg") ) return "image/svg+xml"; return "application/xml"; } private void sendEntireDocument(HttpServletResponse response) throws IOException { response.setContentType(getContentType()); // response.setContentType("text/html"); OutputStream out = response.getOutputStream(); DOMImplementationLS feature = (DOMImplementationLS) domImpl.getFeature("LS", "3.0"); LSSerializer serializer = feature.createLSSerializer(); LSOutput output = feature.createLSOutput(); output.setByteStream(out); serializer.write(document, output); docLoadedOnClient = true; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { sendEntireDocument(response); } public synchronized void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(JS_CONTENT_TYPE); response.setCharacterEncoding(CHARACTER_ENCODING); // response.setContentType("text/html"); OutputStream out = response.getOutputStream(); Writer writer = new OutputStreamWriter(out,CHARACTER_ENCODING); BufferedReader eventReader = request.getReader(); StringBuffer eventSB = new StringBuffer(); while (true) { String eventLine = eventReader.readLine(); if (eventLine == null) break; eventSB.append(eventLine); } webInput.handleEvent(eventSB.toString()); if (clientRemoveCommandsCache != null) writer.write(clientRemoveCommandsCache.toString()); if (clientChangeCommandsCache != null) writer.write(clientChangeCommandsCache.toString()); if (clientAddCommandsCache != null) writer.write(clientAddCommandsCache.toString()); resetCommandSet(); writer.flush(); // copying input to output just to test it //writer.write(eventSB.toString()); // writer.flush(); } // public Document getDocument() { // return document; }
package org.nick.wwwjdic.ocr; import static org.nick.wwwjdic.WwwjdicPreferences.ACRA_DEBUG; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import org.acra.ACRA; import org.nick.wwwjdic.Activities; import org.nick.wwwjdic.DictionaryResultList; import org.nick.wwwjdic.ExamplesResultList; import org.nick.wwwjdic.KanjiResultList; import org.nick.wwwjdic.R; import org.nick.wwwjdic.WebServiceBackedActivity; import org.nick.wwwjdic.Wwwjdic; import org.nick.wwwjdic.WwwjdicPreferences; import org.nick.wwwjdic.model.SearchCriteria; import org.nick.wwwjdic.ocr.crop.CropImage; import org.nick.wwwjdic.utils.Analytics; import org.nick.wwwjdic.utils.Dialogs; import org.nick.wwwjdic.utils.MediaScannerWrapper; import org.nick.wwwjdic.utils.UIUtils; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Canvas; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.hardware.Camera; import android.hardware.Camera.Size; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.support.v4.view.MenuItem; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; public class OcrActivity extends WebServiceBackedActivity implements SurfaceHolder.Callback, OnClickListener, OnTouchListener, OnCheckedChangeListener { private static final String TAG = OcrActivity.class.getSimpleName(); // kind of arbitrary, but OCR seems to work fine with this, and we need to // keep picture size small for faster recognition private static final int MIN_PIXELS = 320 * 480; private static final int MAX_PIXELS = 640 * 480; private static final String IMAGE_CAPTURE_URI_KEY = "ocr.imageCaptureUri"; private static final int CROP_REQUEST_CODE = 1; private static final int SELECT_IMAGE_REQUEST_CODE = 2; private Camera camera; private Size previewSize; private Size pictureSize; private boolean isPreviewRunning = false; private SurfaceView surfaceView; private SurfaceHolder surfaceHolder; private Uri imageCaptureUri; private boolean autoFocusInProgress = false; private static final int AUTO_FOCUS = 1; protected static final int OCRRED_TEXT = 2; public static final int PICTURE_TAKEN = 3; private TextView ocrredTextView; private Button dictSearchButton; private Button kanjidictSearchButton; private Button exampleSearchButton; private Button pickImageButton; private ToggleButton flashToggle; private boolean supportsFlash = false; @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); super.onCreate(savedInstanceState); } @Override protected void activityOnCreate(Bundle icicle) { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (!UIUtils.isHoneycombTablet(this)) { requestWindowFeature(Window.FEATURE_NO_TITLE); } window.setFormat(PixelFormat.TRANSLUCENT); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setContentView(R.layout.ocr); surfaceView = (SurfaceView) findViewById(R.id.capture_surface); camera = CameraHolder.getInstance().tryOpen(); if (camera == null) { Dialogs.createFinishActivityAlertDialog(this, R.string.camera_in_use_title, R.string.camera_in_use_message).show(); return; } surfaceView.setOnTouchListener(this); surfaceHolder = surfaceView.getHolder(); surfaceHolder.addCallback(this); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); ocrredTextView = (TextView) findViewById(R.id.ocrredText); ocrredTextView.setTextSize(30f); dictSearchButton = (Button) findViewById(R.id.send_to_dict); dictSearchButton.setOnClickListener(this); kanjidictSearchButton = (Button) findViewById(R.id.send_to_kanjidict); kanjidictSearchButton.setOnClickListener(this); exampleSearchButton = (Button) findViewById(R.id.send_to_example_search); exampleSearchButton.setOnClickListener(this); toggleSearchButtons(false); pickImageButton = (Button) findViewById(R.id.pick_image); pickImageButton.setOnClickListener(this); flashToggle = (ToggleButton) findViewById(R.id.auto_flash_toggle); flashToggle.setOnCheckedChangeListener(this); if (icicle != null) { imageCaptureUri = icicle.getParcelable(IMAGE_CAPTURE_URI_KEY); } surfaceView.requestFocus(); } @Override protected void onDestroy() { super.onDestroy(); closeCamera(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(IMAGE_CAPTURE_URI_KEY, imageCaptureUri); } @Override protected void onStart() { super.onStart(); Analytics.startSession(this); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled( UIUtils.isHoneycombTablet(this)); } } @Override protected void onStop() { super.onStop(); Analytics.endSession(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Activities.home(this); return true; default: // do nothing } return super.onOptionsItemSelected(item); } private void toggleSearchButtons(boolean enabled) { dictSearchButton.setEnabled(enabled); kanjidictSearchButton.setEnabled(enabled); exampleSearchButton.setEnabled(enabled); } void autoFocus() { try { autoFocusInProgress = false; // if camera is closed, ignore if (camera == null) { return; } imageCaptureUri = createTempFile(); if (imageCaptureUri == null) { Toast t = Toast.makeText(OcrActivity.this, R.string.sd_file_create_failed, Toast.LENGTH_SHORT); t.show(); return; } final ImageCaptureCallback captureCb = new ImageCaptureCallback( getContentResolver().openOutputStream(imageCaptureUri), handler); camera.takePicture(null, null, captureCb); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); deleteTempFile(); if (ACRA_DEBUG) { ACRA.getErrorReporter().handleSilentException(e); } Toast.makeText(OcrActivity.this, R.string.image_capture_failed, Toast.LENGTH_SHORT).show(); } } void autoFocusFailed() { autoFocusInProgress = false; Toast t = Toast.makeText(OcrActivity.this, R.string.af_failed, Toast.LENGTH_SHORT); t.show(); } void ocrSuccess(String ocrredText) { ocrredTextView.setTextSize(30f); ocrredTextView.setText(ocrredText); toggleSearchButtons(true); } void ocrFailed() { Toast t = Toast.makeText(this, R.string.ocr_failed, Toast.LENGTH_SHORT); t.show(); } public static class OcrHandler extends WsResultHandler { public OcrHandler(OcrActivity ocrActivity) { super(ocrActivity); } @Override public void handleMessage(Message msg) { OcrActivity ocrActivity = (OcrActivity) activity; if (activity == null) { return; } switch (msg.what) { case AUTO_FOCUS: if (msg.arg1 == 1) { ocrActivity.autoFocus(); } else { ocrActivity.autoFocusFailed(); } break; case OCRRED_TEXT: ocrActivity.dismissProgressDialog(); int success = msg.arg1; if (success == 1) { String ocrredText = (String) msg.obj; ocrActivity.ocrSuccess(ocrredText); } else { ocrActivity.ocrFailed(); } break; case PICTURE_TAKEN: ocrActivity.crop(); break; default: super.handleMessage(msg); } } } protected WsResultHandler createHandler() { return new OcrHandler(this); } class OcrTask implements Runnable { private Bitmap bitmap; private Handler handler; public OcrTask(Bitmap b, Handler h) { bitmap = b; handler = h; } @Override public void run() { try { WeOcrClient client = new WeOcrClient( WwwjdicPreferences.getWeocrUrl(OcrActivity.this), WwwjdicPreferences.getWeocrTimeout(OcrActivity.this)); String ocredText = client.sendLineOcrRequest(bitmap); Log.d(TAG, "OCR result: " + ocredText); if (ocredText != null && !"".equals(ocredText)) { Message msg = handler.obtainMessage(OCRRED_TEXT, 1, 0); msg.obj = ocredText; handler.sendMessage(msg); } else { Log.d("TAG", "OCR failed: empty string returned"); Message msg = handler.obtainMessage(OCRRED_TEXT, 0, 0); handler.sendMessage(msg); } } catch (Exception e) { Log.e("TAG", "OCR failed", e); Message msg = handler.obtainMessage(OCRRED_TEXT, 0, 0); handler.sendMessage(msg); } } } Camera.PictureCallback pictureCallbackRaw = new Camera.PictureCallback() { public void onPictureTaken(byte[] data, Camera c) { OcrActivity.this.camera.startPreview(); } }; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { return super.onKeyDown(keyCode, event); } if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { Analytics.event("ocrTake", this); requestAutoFocus(); } return false; } private void crop() { try { if (!tempFileExists()) { String path = ""; if (imageCaptureUri != null) { path = new File(imageCaptureUri.getPath()) .getAbsolutePath(); } Log.w(TAG, "temp file does not exist: " + path); Toast.makeText( this, getResources().getString(R.string.read_picture_error, path), Toast.LENGTH_SHORT).show(); } callCropper(imageCaptureUri); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); Toast t = Toast.makeText(OcrActivity.this, R.string.cant_start_cropper, Toast.LENGTH_SHORT); t.show(); } } private void callCropper(Uri imageUri) { Intent intent = new Intent(this, CropImage.class); Bundle extras = new Bundle(); // if we want to scale // extras.putInt("outputX", 200); // extras.putInt("outputY", 200); // extras.putBoolean("scale", true); intent.setDataAndType(imageUri, "image/jpeg"); intent.putExtras(extras); startActivityForResult(intent, CROP_REQUEST_CODE); } private void requestAutoFocus() { if (autoFocusInProgress) { return; } autoFocusInProgress = true; try { camera.autoFocus(new Camera.AutoFocusCallback() { @Override public void onAutoFocus(boolean success, Camera camera) { sendAutoFocusResultMessage(success); } }); } catch (RuntimeException e) { Log.e(TAG, "auto focusFailed: " + e.getMessage(), e); sendAutoFocusResultMessage(false); } finally { toggleSearchButtons(false); ocrredTextView.setText(""); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CROP_REQUEST_CODE) { deleteTempFile(); if (resultCode == RESULT_OK) { Bitmap cropped = (Bitmap) data.getExtras() .getParcelable("data"); try { if (WwwjdicPreferences.isDumpCroppedImages(this)) { dumpBitmap(cropped, "cropped-color.jpg"); } Bitmap blackAndWhiteBitmap = convertToGrayscale(cropped); if (WwwjdicPreferences.isDumpCroppedImages(this)) { dumpBitmap(blackAndWhiteBitmap, "cropped.jpg"); } Analytics.event("ocr", this); OcrTask task = new OcrTask(blackAndWhiteBitmap, handler); String message = getResources().getString( R.string.doing_ocr); submitWsTask(task, message); } catch (Exception e) { throw new RuntimeException(e); } } else if (resultCode == RESULT_CANCELED) { Toast t = Toast.makeText(this, R.string.cancelled, Toast.LENGTH_SHORT); t.show(); } } else if (requestCode == SELECT_IMAGE_REQUEST_CODE) { if (resultCode == RESULT_OK) { Uri selectedImageUri = data.getData(); callCropper(selectedImageUri); } } } private void deleteTempFile() { if (imageCaptureUri == null) { return; } File f = new File(imageCaptureUri.getPath()); if (f.exists()) { boolean deleted = f.delete(); Log.d(TAG, "deleted: " + deleted); } } private boolean tempFileExists() { if (imageCaptureUri == null) { return false; } File f = new File(imageCaptureUri.getPath()); return f.exists(); } private Bitmap convertToGrayscale(Bitmap bitmap) { ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.setSaturation(0); Paint paint = new Paint(); ColorMatrixColorFilter cmcf = new ColorMatrixColorFilter(colorMatrix); paint.setColorFilter(cmcf); Bitmap result = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.RGB_565); Canvas drawingCanvas = new Canvas(result); Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); Rect dst = new Rect(src); drawingCanvas.drawBitmap(bitmap, src, dst, paint); return result; } private void dumpBitmap(Bitmap bitmap, String filename) { try { File sdDir = Environment.getExternalStorageDirectory(); File wwwjdicDir = new File(sdDir.getAbsolutePath() + "/wwwjdic"); if (!wwwjdicDir.exists()) { wwwjdicDir.mkdir(); } if (!wwwjdicDir.canWrite()) { return; } File imageFile = new File(wwwjdicDir, filename); FileOutputStream out = new FileOutputStream( imageFile.getAbsolutePath()); bitmap.compress(CompressFormat.JPEG, 90, out); out.flush(); out.close(); if (UIUtils.isFroyo()) { MediaScannerWrapper.scanFile(this, filename); } } catch (IOException e) { throw new RuntimeException(e); } } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { Log.d(TAG, String.format("surface changed: w=%d; h=%d)", w, h)); if (holder.getSurface() == null) { Log.d(TAG, "holder.getSurface() == null"); return; } if (holder != surfaceHolder) { return; } // camera is null if in use. in that case we finish(), // so just ignore it if (camera == null) { return; } // it seems surfaceChanged is sometimes called twice: // once with SCREEN_ORIENTATION_PORTRAIT and once with // SCREEN_ORIENTATION_LANDSCAPE. At least on a Sapphire with // CyanogenMod. Calling setPreviewSize with wrong width and // height leads to a FC, so skip it. if (w < h) { return; } if (isPreviewRunning) { stopPreview(); } try { Camera.Parameters p = camera.getParameters(); if (previewSize != null) { Log.d(TAG, String.format("previewSize: w=%d; h=%d", previewSize.width, previewSize.height)); p.setPreviewSize(previewSize.width, previewSize.height); } else { int previewWidth = (w >> 3) << 3; int previewHeight = (h >> 3) << 3; Log.d(TAG, String.format("previewSize: w=%d; h=%d", previewWidth, previewHeight)); p.setPreviewSize(previewWidth, previewHeight); } if (pictureSize != null) { Log.d(TAG, String.format("pictureSize: w=%d; h=%d", pictureSize.width, pictureSize.height)); p.setPictureSize(pictureSize.width, pictureSize.height); } else { int pictureWidth = (w >> 3) << 3; int pictureHeight = (h >> 3) << 3; Log.d(TAG, String.format("pictureSize: w=%d; h=%d", pictureWidth, pictureHeight)); p.setPictureSize(pictureWidth, pictureHeight); } if (supportsFlash) { CameraHolder.getInstance().toggleFlash(flashToggle.isChecked(), p); } camera.setParameters(p); camera.setPreviewDisplay(holder); startPreview(); } catch (Exception e) { Log.e(TAG, "error initializing camera: " + e.getMessage(), e); if (ACRA_DEBUG) { ACRA.getErrorReporter().handleSilentException(e); } Dialogs.createErrorDialog(this, R.string.ocr_error).show(); } } private void startPreview() { if (isPreviewRunning) { stopPreview(); } try { Log.v(TAG, "startPreview"); camera.startPreview(); } catch (Throwable ex) { closeCamera(); throw new RuntimeException("startPreview failed", ex); } isPreviewRunning = true; } public void surfaceCreated(SurfaceHolder holder) { Log.d(TAG, "surfaceCreated"); if (camera == null) { camera = CameraHolder.getInstance().tryOpen(); if (camera == null) { Dialogs.createFinishActivityAlertDialog(this, R.string.camera_in_use_title, R.string.camera_in_use_message).show(); return; } } Camera.Parameters params = camera.getParameters(); List<Size> supportedPreviewSizes = CameraHolder.getInstance() .getSupportedPreviewSizes(params); if (supportedPreviewSizes != null) { Log.d(TAG, "supported preview sizes"); for (Size s : supportedPreviewSizes) { Log.d(TAG, String.format("%dx%d", s.width, s.height)); } } List<Size> supportedPictueSizes = CameraHolder.getInstance() .getSupportedPictureSizes(params); if (supportedPictueSizes != null) { Log.d(TAG, "supported picture sizes:"); for (Size s : supportedPictueSizes) { Log.d(TAG, String.format("%dx%d", s.width, s.height)); } } supportsFlash = CameraHolder.getInstance().supportsFlash(params); try { if (supportedPreviewSizes != null && !supportedPreviewSizes.isEmpty()) { previewSize = getOptimalPreviewSize(supportedPreviewSizes); Log.d(TAG, String.format("preview width: %d; height: %d", previewSize.width, previewSize.height)); params.setPreviewSize(previewSize.width, previewSize.height); camera.setParameters(params); } if (supportedPictueSizes != null && !supportedPictueSizes.isEmpty()) { pictureSize = getOptimalPictureSize(supportedPictueSizes); Log.d(TAG, String.format("picture width: %d; height: %d", pictureSize.width, pictureSize.height)); } flashToggle.setEnabled(supportsFlash); camera.setPreviewDisplay(holder); } catch (Exception e) { Log.e(TAG, "error initializing camera: " + e.getMessage(), e); if (ACRA_DEBUG) { ACRA.getErrorReporter().handleSilentException(e); } Dialogs.createErrorDialog(this, R.string.ocr_error).show(); } } private Size getOptimalPictureSize(List<Size> supportedPictueSizes) { Size result = supportedPictueSizes.get(supportedPictueSizes.size() - 1); for (Size s : supportedPictueSizes) { int pixels = s.width * s.height; if (pixels >= MIN_PIXELS && pixels <= MAX_PIXELS) { return s; } } return result; } private Size getOptimalPreviewSize(List<Size> sizes) { WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); int targetHeight = windowManager.getDefaultDisplay().getHeight(); int targetWidth = windowManager.getDefaultDisplay().getWidth(); Size result = null; double diff = Double.MAX_VALUE; for (Size size : sizes) { double newDiff = Math.abs(size.width - targetWidth) + Math.abs(size.height - targetHeight); if (newDiff == 0) { result = size; break; } else if (newDiff < diff) { diff = newDiff; result = size; } } return result; } public void surfaceDestroyed(SurfaceHolder holder) { stopPreview(); closeCamera(); } private void stopPreview() { if (camera != null && isPreviewRunning) { camera.stopPreview(); } isPreviewRunning = false; } private void closeCamera() { if (camera != null) { CameraHolder.getInstance().release(); camera = null; isPreviewRunning = false; } } @Override public void onClick(View v) { TextView t = (TextView) findViewById(R.id.ocrredText); String key = t.getText().toString(); boolean isDirectSearch = WwwjdicPreferences.isDirectSearch(this); SearchCriteria criteria = null; Intent intent = new Intent(this, Wwwjdic.class); Bundle extras = new Bundle(); if (v.getId() == R.id.send_to_dict) { if (isDirectSearch) { criteria = SearchCriteria.createForDictionaryDefault(key); intent = new Intent(this, DictionaryResultList.class); } else { extras.putInt(Wwwjdic.EXTRA_SEARCH_TYPE, SearchCriteria.CRITERIA_TYPE_DICT); } } else if (v.getId() == R.id.send_to_kanjidict) { if (isDirectSearch) { criteria = SearchCriteria.createForKanjiOrReading(key); intent = new Intent(this, KanjiResultList.class); } else { extras.putInt(Wwwjdic.EXTRA_SEARCH_TYPE, SearchCriteria.CRITERIA_TYPE_KANJI); } } else if (v.getId() == R.id.send_to_example_search) { if (isDirectSearch) { criteria = SearchCriteria.createForExampleSearchDefault(key); intent = new Intent(this, ExamplesResultList.class); } else { extras.putInt(Wwwjdic.EXTRA_SEARCH_TYPE, SearchCriteria.CRITERIA_TYPE_EXAMPLES); } } else if (v.getId() == R.id.pick_image) { intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE);
package pt.fccn.saw.selenium; import java.net.URL; import java.util.concurrent.TimeUnit; import java.util.NoSuchElementException; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.By; import org.openqa.selenium.remote.*; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; /** * The base class for tests using WebDriver to test specific browsers. * This test read system properties to know which browser to test or, * if tests are te be run remotely, it also read login information and * the browser, browser version and OS combination to be used. * * The WebDriver tests provide the more precise results without the * restrictions present in selenium due to browers' security models. */ public class WebDriverTestBase{ protected static WebDriver driver; protected static String testURL; protected static String browserVersion; protected static String titleOfFirstResult; protected static String pre_prod="preprod"; //protected static String pre_prod="p24"; protected static boolean Ispre_prod=false; /** * Start and setup a WebDriver. * This method first check if we want a local or remote WebDriver. * If a local WebDriver is desired, it initialize the correct one. * If a remote WebDriver is desired, it configures and initialize it. * * This method is run only once per test class so we prevent the * overhead of initialization for each test. */ @BeforeClass public static void setUp() throws Exception { // Read system properties. String username = System.getProperty("test.remote.access.user"); String apiKey = System.getProperty("test.remote.access.key"); String browser = System.getProperty("test.browser", "*firefox"); String os = System.getProperty("test.os", "windows"); browserVersion = System.getProperty("test.browser.version", "16"); String projectName = System.getProperty("test.project.name"); testURL = System.getProperty("test.url"); //Decide which environment to choose // Decide if tests are to be run locally or remotely if(username == null || apiKey == null) { System.out.println("Run test localy"); driver = selectLocalBrowser(browser); } else { System.out.println("Run test in saucelabs NOW"); //parameterCleanupForRemote(browser, browserVersion); String browSersToTesJSON = System.getenv("SAUCE_ONDEMAND_BROWSERS"); System.out.println("browsers " + browSersToTesJSON); DesiredCapabilities capabillities = new DesiredCapabilities(); capabillities.setBrowserName(System.getenv("SELENIUM_BROWSER")); capabillities.setVersion(System.getenv("SELENIUM_VERSION")); capabillities.setCapability(CapabilityType.PLATFORM, System.getenv("SELENIUM_PLATFORM")); driver = new RemoteWebDriver( new URL("http://"+ username +":"+ apiKey +"@ondemand.saucelabs.com:80/wd/hub"), capabillities); } // Set the default time to wait for an element to appear in a webpage. driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS); } /** * This method is run before each test. * It sets the browsers to the starting test url */ @Before public void preTest() { driver.get( testURL ); } /** * Releases the resources used for the tests, i.e., * It closes the WebDriver. */ @AfterClass public static void tearDown() throws Exception { driver.quit(); } /** * Creates a Local WebDriver given a string with the web browser name. * * @param browser The browser name for the WebDriver initialization * @return The initialized Local WebDriver */ private static WebDriver selectLocalBrowser(String browser) throws java.net.MalformedURLException{ WebDriver driver = null; if (browser.contains("firefox")) { driver = new FirefoxDriver(); } else if (browser.contains("iexplorer")) { driver = new InternetExplorerDriver(); } else if (browser.contains("chrome")) { //DesiredCapabilities capabilities = DesiredCapabilities.chrome(); //capabilities.setCapability("chrome.binary", "/usr/lib/chromium-browser/chromium-browser"); //driver = new ChromeDriver(capabilities); driver = new ChromeDriver(); } else if (browser.contains("opera")) { driver = new OperaDriver(); } else if (browser.contains("remote-chrome")) { DesiredCapabilities capabilities = DesiredCapabilities.chrome(); driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities); } else if (browser.contains("remote-firefox")) { DesiredCapabilities capabilities = DesiredCapabilities.firefox(); driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities); driver.get("http: } else { // OH NOEZ! I DOAN HAZ DAT BROWSR! System.err.println("Cannot find suitable browser driver for ["+ browser +"]"); } return driver; } /** * Gets a suitable Platform object given a OS/Platform string.. * * @param platformString The given string for the OS/Platform to use * @return The Platform object that represent the requested OS/Platform */ private static Platform selectPlatform(String platformString) { Platform platform = null; if (platformString.contains("Windows")) { if (platformString.contains("2008")) { platform = Platform.VISTA; } else { platform = Platform.XP; } } else if (platformString.toLowerCase().equals("linux")){ platform = Platform.LINUX; } else { System.err.println("Cannot find a suitable platform/OS for ["+ platformString +"]"); } return platform; } /** * Miscellaneous cleaning for browser and browser's version strings. * @param browser The browser string to clean * @param browserVersion The browser version string to clean */ private static void parameterCleanupForRemote(String browser, String browserVersion) { // Selenium1 likes to prepend a "*" to browser string. if (browser.startsWith("*")) { browser = browser.substring(1); } // SauceLabs doesn't use version numbering for Google Chrome due to // the fast release schedule of that browser. if (browser.contains("googlechrome")) { browserVersion = ""; } } /** * Utility class to obtain the Class name in a static context. */ public static class CurrentClassGetter extends SecurityManager { public String getClassName() { return getClassContext()[1].getName(); } } /** * Checks if an element is present in the page */ protected boolean isElementPresent(By by) { try { driver.findElement(by); return true; } catch (NoSuchElementException e) { return false; } } }
package pt.webdetails.cda.exporter; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import javax.swing.table.TableModel; import org.apache.axis2.databinding.types.xsd.Decimal; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; public class XmlExporter extends AbstractExporter { public XmlExporter(HashMap <String,String> extraSettings) { super(); } public void export(final OutputStream out, final TableModel tableModel) throws ExporterException { final Document document = DocumentHelper.createDocument(); // Generate metadata final Element root = document.addElement("CdaExport"); final Element metadata = root.addElement("MetaData"); final int columnCount = tableModel.getColumnCount(); final int rowCount = tableModel.getRowCount(); for (int i = 0; i < columnCount; i++) { final Element columnInfo = metadata.addElement("ColumnMetaData"); columnInfo.addAttribute("index", (String.valueOf(i))); columnInfo.addAttribute("type", getColType(tableModel.getColumnClass(i))); columnInfo.addAttribute("name", tableModel.getColumnName(i)); } final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US); final Element resultSet = root.addElement("ResultSet"); for (int rowIdx = 0; rowIdx < rowCount; rowIdx++) { final Element row = resultSet.addElement("Row"); for (int colIdx = 0; colIdx < columnCount; colIdx++) { final Element col = row.addElement("Col"); final Object value = tableModel.getValueAt(rowIdx, colIdx); if (value instanceof Date) { col.setText(format.format(value)); } else if (value != null) { // numbers can be safely converted via toString, as they use a well-defined format there col.setText(value.toString()); } else{ col.addAttribute("isNull","true"); } } } try { final Writer writer = new BufferedWriter(new OutputStreamWriter(out)); document.setXMLEncoding("UTF-8"); document.write(writer); writer.flush(); } catch (IOException e) { throw new ExporterException("IO Exception converting to utf-8", e); } } public String getMimeType() { return "text/xml"; } public String getAttachmentName() { // No attachment required return null; } }
package io.car.server.rest; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import com.google.inject.Inject; import com.google.inject.Provider; import io.car.server.core.User; import io.car.server.core.UserService; import io.car.server.core.exception.UserNotFoundException; import io.car.server.rest.auth.AuthConstants; /** * @author Christian Autermann <c.autermann@52north.org> */ public abstract class AbstractResource { private Provider<SecurityContext> securityContext; private Provider<UserService> service; private Provider<UriInfo> uriInfo; private Provider<ResourceFactory> resourceFactory; protected boolean canModifyUser(User user) { return getSecurityContext().isUserInRole(AuthConstants.ADMIN_ROLE) || (getSecurityContext().getUserPrincipal() != null && getSecurityContext().getUserPrincipal().getName().equals(user.getName())); } public SecurityContext getSecurityContext() { return securityContext.get(); } public UriInfo getUriInfo() { return uriInfo.get(); } public UserService getUserService() { return service.get(); } public ResourceFactory getResourceFactory() { return resourceFactory.get(); } protected User getCurrentUser() throws UserNotFoundException { return getUserService().getUser(getSecurityContext().getUserPrincipal().getName()); } @Inject public void setSecurityContext(Provider<SecurityContext> securityContext) { this.securityContext = securityContext; } @Inject public void setUriInfo(Provider<UriInfo> uriInfo) { this.uriInfo = uriInfo; } @Inject public void setUserService(Provider<UserService> service) { this.service = service; } @Inject public void setResourceFactory(Provider<ResourceFactory> resourceFactory) { this.resourceFactory = resourceFactory; } }
package io.bigio.util; import io.bigio.Parameters; import io.netty.util.NetUtil; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.SocketException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A utility class providing network tools. * * @author Andy Trimble */ public class NetworkUtil { private static final Logger LOG = LoggerFactory.getLogger(NetworkUtil.class); private static final String NETWORK_INTERFACE_PROPETY = "io.bigio.network"; private static NetworkInterface nic = null; private static InetAddress inetAddress = null; private static String ip; private static final int START_PORT = 32768; private static final int END_PORT = 65536; private static final int NUM_CANDIDATES = END_PORT - START_PORT; private static final List<Integer> PORTS = new ArrayList<>(); private static Iterator<Integer> portIterator; static { for (int i = START_PORT; i < END_PORT; i ++) { PORTS.add(i); } Collections.shuffle(PORTS); } /** * Get the IP address of this instance. * * @return the IP address associated with the selected network interface */ public static String getIp() { if(nic == null) { findNIC(); } return ip; } /** * Get the configured network interface. * * @return the network interface this member is using */ public static NetworkInterface getNetworkInterface() { if(nic == null) { findNIC(); } return nic; } /** * Get the InetAddress object. * * @return the InetAddress object */ public static InetAddress getInetAddress() { if(nic == null) { findNIC(); } return inetAddress; } /** * Get a random unused port between START_PORT and END_PORT. * * @return a random unused port */ public static int getFreePort() { for (int i = 0; i < NUM_CANDIDATES; i ++) { int port = nextCandidatePort(); try { // Ensure it is possible to bind on both wildcard and loopback. ServerSocket ss; ss = new ServerSocket(); ss.setReuseAddress(false); ss.bind(new InetSocketAddress(port)); ss.close(); ss = new ServerSocket(); ss.setReuseAddress(false); ss.bind(new InetSocketAddress(NetUtil.LOCALHOST, port)); ss.close(); return port; } catch (IOException e) { // ignore } } throw new RuntimeException("unable to find a free port"); } private static int nextCandidatePort() { if (portIterator == null || !portIterator.hasNext()) { portIterator = PORTS.iterator(); } return portIterator.next(); } private static void findNIC() { try { String networkInterfaceName = Parameters.INSTANCE.getProperty(NETWORK_INTERFACE_PROPETY); if(networkInterfaceName == null || "".equals(networkInterfaceName)) { switch(Parameters.INSTANCE.currentOS()) { case WIN_64: case WIN_32: networkInterfaceName = "lo"; break; case LINUX_64: case LINUX_32: networkInterfaceName = "eth0"; break; case MAC_64: case MAC_32: networkInterfaceName = "en0"; break; default: LOG.error("Cannot determine operating system. Cluster cannot form."); } } else { networkInterfaceName = networkInterfaceName.trim(); } nic = NetworkInterface.getByName(networkInterfaceName); if(nic != null && !nic.isUp()) { LOG.error("Selected network interface '" + networkInterfaceName + "' is down. Please select an alternate network " + "interface using the property 'io.bigio.network' in your " + "configuration file (ex. io.bigio.network=eth0). For " + "a list of available interfaces, type 'net' into the shell."); } if(nic != null) { Enumeration e = nic.getInetAddresses(); while(e.hasMoreElements()) { InetAddress i = (InetAddress) e.nextElement(); String address = i.getHostAddress(); if(!address.contains(":")) { inetAddress = i; ip = address; break; } } } else { LOG.error("Selected network interface '" + networkInterfaceName + "' cannot be found. Please select an alternate network " + "interface using the property 'io.bigio.network' in your " + "configuration file (ex. io.bigio.network=eth0). For " + "a list of available interfaces, type 'net' into the shell."); } } catch(SocketException ex) { LOG.error("Unable to determine IP address", ex); nic = null; } } }
package jscenegraph.database.inventor; import java.text.DateFormat; import java.time.Instant; import java.util.Date; import java.util.Formatter; import java.util.Locale; import jscenegraph.port.Mutable; import net.sourceforge.jpcap.util.Timeval; //! Class for representation of a time. /*! \class SbTime \ingroup Basics This class represents and performs operations on time. Operations may be done in seconds, seconds and microseconds, or using a <tt>struct timeval</tt> (defined in <em>/usr/include/sys/time.h</em>). \par See Also \par cftime */ /** * @author Yves Boyadjian * */ public class SbTime implements Mutable { private Timeval t; // Default constructor. public SbTime() { t = new Timeval(0, 0); } // Constructor taking seconds. public SbTime(double sec) { if (sec >= 0) { long tv_sec = (long) (sec); int tv_usec = (int) (0.5 + (sec - tv_sec) * 1000000.0); t = new Timeval(tv_sec, tv_usec); } else this.copyFrom((new SbTime(-sec)).operator_minus()); } // Constructor taking seconds + microseconds. public SbTime(long sec, int usec) { t = new Timeval(sec, usec); } // java port public SbTime(SbTime src) { t = new Timeval(src.t.getSeconds(), src.t.getMicroSeconds()); } // Get a zero time. public static SbTime zero() { return new SbTime(0, 0); } // Get the current time (seconds since Jan 1, 1970). public static SbTime getTimeOfDay() { Instant now = Instant.now(); long sec = now.getEpochSecond(); int nanos = now.getNano(); int usec = nanos / 1000; return new SbTime(sec, usec); } // Description: // Sets to the current time. // Use: public public void setToTimeOfDay() { // #ifdef WIN32 this.copyFrom(SbTime.getTimeOfDay()); // #else // if (-1 == gettimeofday(&t, NULL)) // perror("gettimeofday"); // #endif } // ! Get time in seconds as a double public double getValue() { return (double) t.getSeconds() + (double) t.getMicroSeconds() / 1000000.0; } // ! Get time in milliseconds (for Xt). public long getMsecValue() // System long { return t.getSeconds() * 1000 + t.getMicroSeconds() / 1000; } // ! Equality operators. public boolean operator_not_equal(final SbTime tm) { return !(this.operator_equal(tm)); } // comparison operator public boolean operator_equal(SbTime other) { return t.compareTo(other.t) == 0; } // add operator (java port) public SbTime operator_add(SbTime t1) { long tm_sec = t.getSeconds() + t1.t.getSeconds(); long tm_usec = (long) t.getMicroSeconds() + t1.t.getMicroSeconds(); if (tm_usec >= 1000000) { tm_sec += 1; tm_usec -= 1000000; } SbTime tm = new SbTime(tm_sec, (int) tm_usec); return tm; } public boolean operator_less_or_equals(SbTime tm) { int comparison = t.compareTo(tm.t); // java port return comparison <= 0; } // Unary negation. public SbTime operator_minus() { return (t.getMicroSeconds() == 0) ? new SbTime(-t.getSeconds(), 0) : new SbTime(-t.getSeconds() - 1, 1000000 - t.getMicroSeconds()); } // Description: // Use: public public SbTime operator_minus(final SbTime t1) { final SbTime t0 = this; long sec; long usec; // System long sec = t0.t.getSeconds() - t1.t.getSeconds(); usec = t0.t.getMicroSeconds() - t1.t.getMicroSeconds(); while (usec < 0 && sec > 0) { usec += 1000000; sec -= 1; } return new SbTime(sec, (int) usec); } // ! division by another time public double operator_div(final SbTime tm) { return getValue() / tm.getValue(); } // Description: // Use: public public SbTime operator_mul(double s) { final SbTime tm = this; return new SbTime(tm.getValue() * s); } @Override public void copyFrom(Object other) { SbTime otherTime = (SbTime) other; t = otherTime.t; } // ! Set time from milliseconds. public void setMsecValue(long msec) // System long { t = new Timeval(msec / 1000, (int) (1000 * (msec % 1000))); } // ! Convert to a string. The default format is seconds with 3 digits of // fraction // ! precision. \p fmt is a character string that consists of field // descriptors and // ! text characters, in a manner analogous to cftime (3C) and printf (3S). // ! Each field descriptor consists of a % character followed by another // character // ! which specifies the replacement for the field descriptor. All other // characters // ! are copied from \p fmt into the result. The following field descriptors // are // ! supported: // ! \code // ! % the `%' character // ! D total number of days // ! H total number of hours // ! M total number of minutes // ! S total number of seconds // ! I total number of milliseconds // ! U total number of microseconds // ! h hours remaining after the days (00-23) // ! m minutes remaining after the hours (00-59) // ! s seconds remaining after the minutes (00-59) // ! i milliseconds remaining after the seconds (000-999) // ! u microseconds remaining after the seconds (000000-999999) // ! \endcode // ! The uppercase descriptors are formatted with a leading `em' for // negative // ! times; the lowercase descriptors are formatted fixed width, with // leading // ! zeros. For example, a reasonable format string might be // ! "elapsedtime:%Mminutes,%sseconds". The default value of \p fmt, // ! "%S.%i", formats the time as seconds with 3 digits of fractional // precision. // java port // Description: // Converts to a formatted string. The format string supports the following: // %% the '%' character // %D total number of days // %H total number of hours // %M total number of minutes // %S total number of seconds // %I total number of milliseconds // %U total number of microseconds // %h 00-23 hours remaining after the days // %m 00-59 minutes remaining after the hours // %s 00-59 seconds remaining after the minutes // %i 000-999 milliseconds remaining after the seconds // %u 000000-999999 microseconds remaining after the seconds // uppercase descriptors are formatted with a leading '-' for negative times // lowercase descriptors are formatted fixed width with leading zeros // Use: public public String format() { return format("%S.%i"); } public String format(String fmtStr) { boolean negative; Timeval tv; // turn into sign-magnitude form if (t.getSeconds() >= 0) { negative = false; tv = t; } else { negative = true; tv = this.operator_minus().t; } // first calculate total durations int tday = (int) (tv.getSeconds() / (60 * 60 * 24)); int thour = (int) (tv.getSeconds() / (60 * 60)); int tmin = (int) (tv.getSeconds() / 60); int tsec = (int) (tv.getSeconds()); int tmilli = (int) (1000 * tv.getSeconds() + tv.getMicroSeconds() / 1000); int tmicro = (int) (1000000 * tv.getSeconds() + tv.getMicroSeconds()); // then calculate remaining durations int rhour = thour - 24 * tday; int rmin = tmin - 60 * thour; int rsec = tsec - 60 * tmin; int rmilli = tmilli - 1000 * tsec; int rmicro = tmicro - 1000000 * tsec; char[] buf = new char[200]; int s = 0; int fmt = 0; for (; fmt < fmtStr.length(); fmt++) { if (fmtStr.charAt(fmt) != '%') { buf[s] = fmtStr.charAt(fmt); s++; } else { fmt++; switch (fmtStr.charAt(fmt)) { case 0: fmt--; // trailing '%' in format string break; case '%': buf[s] = '%'; // "%%" in format string s++; break; case 'D': if (negative) { buf[s] = '-'; s++; } s += sprintf(s, "%ld", tday, buf); break; case 'H': if (negative) { buf[s] = '-'; s++; } s += sprintf(s, "%ld", thour, buf); break; case 'M': if (negative) { buf[s] = '-'; s++; } s += sprintf(s, "%ld", tmin, buf); break; case 'S': if (negative) { buf[s] = '-'; s++; } s += sprintf(s, "%ld", tsec, buf); break; case 'I': if (negative) { buf[s] = '-'; s++; } s += sprintf(s, "%ld", tmilli, buf); break; case 'U': if (negative) { buf[s] = '-'; s++; } s += sprintf(s, "%ld", tmicro, buf); break; case 'h': s += sprintf(s, "%.2ld", rhour, buf); break; case 'm': s += sprintf(s, "%.2ld", rmin, buf); break; case 's': s += sprintf(s, "%.2ld", rsec, buf); break; case 'i': s += sprintf(s, "%.3ld", rmilli, buf); break; case 'u': s += sprintf(s, "%.6ld", rmicro, buf); break; default: buf[s] = '%'; s++; // echo any bad '%?' buf[s] = fmtStr.charAt(fmt); s++; // specifier } } if (s >= buf.length - 7) // don't overshoot the buffer break; } buf[s] = 0; return new String(buf); } private int sprintf(final int s, String format, int value, char[] buf) { String result = String.format(format, value); int len = result.length(); int sc = s; for (int i = 0; i < len; i++) { char c = result.charAt(i); buf[sc] = c; sc++; } return sc - s; } // ! Convert to a date string, interpreting the time as seconds since // ! Jan 1, 1970. The default format gives "Tuesday, 01/26/93 11:23:41 AM". // ! See the cftime() reference page for explanation of the format string. // Description: // Formats as an absolute date/time, using unix "strftime" mechanism. // Use: public // java port public String formatDate() { return formatDate("%tA, %tD %tr"); } public String formatDate(String fmt) { String buf; Date date = t.getDate(); // strftime(buf, sizeof(buf), fmt, localtime(&seconds)); Formatter formatter = new Formatter(Locale.US); buf = formatter.format(fmt, date, date, date).toString(); formatter.close(); return buf; } // ! Set time from a double (in seconds). public void setValue(double sec) { long tv_sec = (long) (sec); int tv_usec = (int) ((sec - tv_sec) * 1000000.0); t = new Timeval(tv_sec, tv_usec); } }
package org.jpos.ee; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.List; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Base64; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.ObjectNotFoundException; import org.hibernate.criterion.Restrictions; import org.jpos.iso.ISOUtil; import org.jpos.security.SystemSeed; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; /** * @author Alejandro Revilla */ public class UserManager { DB db; VERSION version; public UserManager (DB db) { super (); this.db = db; version = VERSION.ZERO; } public UserManager (DB db, VERSION version) { super (); this.db = db; this.version = version; } /** * @return all users * @throws HibernateException on low level hibernate related exception */ public List findAll () throws HibernateException { return db.session().createCriteria (User.class) .add (Restrictions.eq ("deleted", Boolean.FALSE)) .list(); } public User getUserByNick (String nick) throws HibernateException { return getUserByNick(nick, false); } public User getUserByNick (String nick, boolean includeDeleted) throws HibernateException { try { Criteria crit = db.session().createCriteria (User.class) .add (Restrictions.eq ("nick", nick)); if (!includeDeleted) crit = crit.add (Restrictions.eq ("deleted", Boolean.FALSE)); return (User) crit.uniqueResult(); } catch (ObjectNotFoundException ignored) { } return null; } /** * @param nick name. * @param pass hash * @return the user * @throws BLException if invalid user/pass * @throws HibernateException on low level hibernate related exception */ public User getUserByNick (String nick, String pass) throws HibernateException, BLException { User u = getUserByNick(nick); assertNotNull (u, "User does not exist"); assertTrue(checkPassword(u, pass), "Invalid password"); return u; } public boolean checkPassword (User u, String clearpass) throws HibernateException, BLException { assertNotNull(clearpass, "Invalid pass"); String passwordHash = u.getPassword(); assertNotNull(passwordHash, "Password is null"); VERSION v = VERSION.getVersion(passwordHash); assertTrue(v != VERSION.UNKNOWN, "Unknown password"); switch (v.getVersion()) { case (byte) 0: return (passwordHash.equals(getV0Hash(u.getId(), clearpass))); case (byte) 1: byte[] b = Base64.decode(passwordHash); byte[] salt = new byte[VERSION.ONE.getSalt().length]; byte[] clientSalt = new byte[VERSION.ONE.getSalt().length]; System.arraycopy (b, 1, salt, 0, salt.length); System.arraycopy(b, 1 + salt.length, clientSalt, 0, clientSalt.length); clearpass = clearpass.startsWith("v1:") ? clearpass.substring(3) : upgradeClearPassword(clearpass, clientSalt); String computedPasswordHash = genV1Hash(clearpass, VERSION.ONE.getSalt(salt), clientSalt); return computedPasswordHash.equals(u.getPassword()); } return false; } /** * @param u the user * @param clearpass new password in clear * @return true if password is in PasswordHistory */ public boolean checkNewPassword (User u, String clearpass) { // TODO - we need to reuse client hash in order to check duplicates String newHash = getV0Hash(u.getId(), clearpass); if (newHash.equals(u.getPassword())) return false; for (PasswordHistory p : u.getPasswordhistory()) { if (p.getValue().equals(newHash)) return false; } return true; } public void setPassword(User u, String clearpass) throws BLException { setPassword(u, clearpass, null); } public void setPassword (User u, String clearpass, User author) throws BLException { if (u.getPassword() != null) u.addPasswordHistoryValue(u.getPassword()); switch (version) { case ZERO: setV0Password(u, clearpass); break; case ONE: setV1Password (u, clearpass); break; } RevisionManager revmgr = new RevisionManager(db); if (author == null) author = u; revmgr.createRevision (author, "user." + u.getId(), "Password changed"); db.session().saveOrUpdate(u); } // VERSION ZERO IMPLEMENTATION private static String getV0Hash (long id, String pass) { String hash = null; try { MessageDigest md = MessageDigest.getInstance ("SHA"); md.update (Long.toString(id,16).getBytes()); hash = ISOUtil.hexString ( md.digest (pass.getBytes()) ).toLowerCase(); } catch (NoSuchAlgorithmException e) { // should never happen } return hash; } private void setV0Password (User u, String clearpass) { u.setPassword(getV0Hash(u.getId(), clearpass)); } // VERSION ONE IMPLEMENTATION private String upgradeClearPassword (String clearpass, byte[] salt) { return ISOUtil.hexString(genV1ClientHash(clearpass, salt)); } private byte[] genSalt(int l) { SecureRandom sr; try { sr = SecureRandom.getInstance("SHA1PRNG"); byte[] salt = new byte[l]; sr.nextBytes(salt); return salt; } catch (NoSuchAlgorithmException ignored) { // Should never happen, SHA1PRNG is a supported algorithm } return null; } public boolean upgradePassword (User u, String clearpass) throws HibernateException, BLException { assertNotNull(clearpass, "Invalid pass"); String passwordHash = u.getPassword(); assertNotNull(passwordHash, "Password is null"); VERSION v = VERSION.getVersion(passwordHash); if (v == VERSION.ZERO && passwordHash.equals(getV0Hash(u.getId(), clearpass))) { setV1Password(u, clearpass); return true; } return false; } private void setV1Password (User u, String pass) throws BLException { assertNotNull(pass, "Invalid password"); byte[] clientSalt; byte[] serverSalt = genSalt(VERSION.ONE.getSalt().length); if (pass.startsWith("v1:")) { byte[] b = Base64.decode(u.getPassword()); clientSalt = new byte[VERSION.ONE.getSalt().length]; System.arraycopy (b, 1+clientSalt.length, clientSalt, 0, clientSalt.length); pass = pass.substring(3); } else { clientSalt = genSalt(VERSION.ONE.getSalt().length); pass = upgradeClearPassword(pass, clientSalt); } u.setPassword(genV1Hash(pass, serverSalt, clientSalt)); } private String genV1Hash(String password, byte[] salt, byte[] clientSalt) throws BLException { try { SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); int iterations = VERSION.ONE.getIterations(); PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, 2048); return org.bouncycastle.util.encoders.Base64.toBase64String( Arrays.concatenate( new byte[]{VERSION.ONE.getVersion()}, VERSION.ONE.getSalt(salt), clientSalt, skf.generateSecret(spec).getEncoded()) ); } catch (Exception e) { throw new BLException (e.getLocalizedMessage()); } } private byte[] genV1ClientHash (String clearpass, byte[] seed) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); int iterations = VERSION.ONE.getIterations(); byte[] passAsBytes = clearpass.getBytes(StandardCharsets.UTF_8); for (int i=0; i<iterations; i++) { if (i % 7 == 0) md.update(seed); md.update(passAsBytes); } return md.digest(); } catch (NoSuchAlgorithmException e) { // should never happen, SHA-256 is a supported algorithm } return null; } // HELPER METHODS protected void assertNotNull (Object obj, String error) throws BLException { if (obj == null) throw new BLException (error); } protected void assertTrue (boolean condition, String error) throws BLException { if (!condition) throw new BLException (error); } public enum VERSION { UNKNOWN((byte)0xFF, 0, 0, 0, null), ZERO((byte)0, 0, 160, 40, null), ONE((byte) 1,100000,2048, 388, Base64.decode("K7f2dgQQHK5CW6Wz+CscUA==")); private byte version; private int iterations; private int keylength; private int encodedLength; private byte[] salt; VERSION(byte version, int iterations, int keylength, int encodedLength, byte[] salt) { this.version = version; this.iterations = iterations; this.keylength = keylength; this.encodedLength = encodedLength; this.salt = salt; } public byte getVersion() { return version; } public int getIterations() { return iterations; } public int getKeylength() { return keylength; } public int getEncodedLength() { return encodedLength; } public byte[] getSalt() { return ISOUtil.xor(salt, SystemSeed.getSeed(salt.length, salt.length)); } public byte[] getSalt(byte[] salt) { return ISOUtil.xor(salt, getSalt()); } public static VERSION getVersion (String hash) { for (VERSION v : VERSION.values()) { if (v.getEncodedLength() == hash.length()) return v; if (v != UNKNOWN && v != ZERO) { byte[] b = Base64.decode(hash); if (b[0] == v.getVersion()) return v; } } return UNKNOWN; } } }
import java.io.*; import java.util.Vector; public class SubscribedNewsgroups { private static NewsGroup[] allSubscribed = null; private static boolean windows = false; public static void main( String[] args ) { // Test the class SubscribedNewsgroups subscribed = new SubscribedNewsgroups(); NewsGroup allGroups[] = subscribed.getNewsGroups(); if( allGroups == null ) { System.out.println("Could not find subscribed newsgroups from mozilla/netscape mailrc files"); } else { for( int i=0; i < allGroups.length; i++ ) { System.out.println( "Hostname is: " + allGroups[i].getHostName() + " Newsgroup is: " + allGroups[i].getNewsgroupName() ); } } } // Only public method of the class // Returns and array of unique NewsGroup objects public NewsGroup[] getNewsGroups() { windows = false; if( System.getProperty( "os.name" ).indexOf( "Windows" ) != -1 ) { windows = true; } String mozillaHome = ""; if( windows ) { mozillaHome = System.getProperty( "user.home" ) + System.getProperty( "file.separator" ) + "Application Data" + System.getProperty( "file.separator" ) + "Mozilla" + System.getProperty( "file.separator" ) + "Profiles"; //System.out.println( "Windows mozilla path: " + mozillaHome ); } else { mozillaHome = System.getProperty( "user.home" ) + System.getProperty( "file.separator" ) + ".mozilla"; //System.out.println( "Unix/Linux mozilla path: " + mozillaHome ); } if( !new File( mozillaHome ).isDirectory() ) { //System.out.println("Could not find .mozilla directory"); return null; } //System.out.println(".mozilla directory found"); // Get all the profiles belonging to the user File profiles[] = findProfiles( new File ( mozillaHome ) ); if( profiles.length < 1 ) { //System.out.println("Could not find Profiles"); return null; } //System.out.println("Profiles found"); // Get the News directory for each profile File allNewsDirs[] = new File[ profiles.length ]; for( int i=0; i < profiles.length; i++ ) { File newsDir = findNewsDir( profiles[i] ); allNewsDirs[i] = newsDir; //System.out.println( "News is at: " + newsDir.getPath() ); } // Check that at least one News directory exists and remove nulls boolean newsFound = false; //Vector nonNullNews = new Vector(); for( int i=0; i < allNewsDirs.length; i++ ) { if( allNewsDirs[i] != null ) { newsFound = true; break; } } if( !newsFound ) { //System.out.println("Could not find News directory"); return null; } //System.out.println("News directory found"); // Get all the mailrc files for each News directory File allMailrcs[] = findMailrcFiles( allNewsDirs ); if( allMailrcs == null ) { //System.out.println("Could not find mailrc files"); return null; } //System.out.println("mailrc files found"); Vector subscribed = new Vector(); // Get the newsgroups in each mailrc file for( int i=0; i < allMailrcs.length; i++ ) { File mailrc = (File) allMailrcs[i]; NewsGroup newsgroup[] = findNewsgroups( mailrc ); //if the Newsgroup has not already been added to the list for( int j=0; j < newsgroup.length; j++ ) { // if newsgroup is unique then add to the list if( !listed( newsgroup[j], subscribed ) ) { subscribed.addElement( newsgroup[j] ); } } } // Copy all unique Newsgroups into the global array allSubscribed = new NewsGroup[ subscribed.size() ]; subscribed.copyInto( allSubscribed ); // Test that at least one subscribed newsgroup has been found if( allSubscribed.length < 1 ) { //System.out.println("Could not find Subscribed newsgroups "); return null; } //System.out.println("Subscribed newsgroups found"); return allSubscribed; } // Tests if the NewsGroup object has already been listed by another mailrc file private static boolean listed( NewsGroup newsgroup, Vector uniqueSubscription ) { for(int i=0; i < uniqueSubscription.size(); i++) { NewsGroup tempGroup = (NewsGroup) uniqueSubscription.elementAt(i); // Test for duplication if(newsgroup.getHostName().equalsIgnoreCase( tempGroup.getHostName()) && newsgroup.getNewsgroupName().equalsIgnoreCase( tempGroup.getNewsgroupName() ) ) return true; } return false; } // Finds all the NewsGroups in an individual mailrc file private static NewsGroup[] findNewsgroups(File mailrcfile ) { String hostname = ""; String newsgroup = ""; NewsGroup mailrcNewsGroups[] = null; //Retrieve name of news host/server from file name //Sequentially access each of the newsgroups //If the newsgroup is not already contained in the global NewsGroup[] array then add it String filename = mailrcfile.getPath(); if( windows ) { // Windows format "staroffice-news.germany.sun.com.rc" int hostNameStart = filename.lastIndexOf("\\") + 1; int hostNameEnd = filename.indexOf(".rc"); hostname = filename.substring( hostNameStart, hostNameEnd ); } else { // Unix/Linux format "newsrc-staroffice-news.germany.sun.com" int hostNameStart = filename.indexOf("-") + 1; hostname = filename.substring( hostNameStart, filename.length() ); } // Assumes the content format in Window is the same as Unix/Linux (unknown at the moment) // i.e. a list of newsgroups each ending with a ":" LineNumberReader in = null; try { in = new LineNumberReader( new FileReader( mailrcfile ) ); Vector groups = new Vector(); String inString = ""; int line = 0; while( inString != null ) { in.setLineNumber( line ); inString = in.readLine(); line++; if( inString != null ) { int newsgroupEnd = inString.indexOf(":"); newsgroup = inString.substring( 0, newsgroupEnd ); NewsGroup group = new NewsGroup( hostname, newsgroup ); groups.addElement( group ); } } mailrcNewsGroups = new NewsGroup[ groups.size() ]; groups.copyInto(mailrcNewsGroups); in.close(); } catch( IOException ioe ) { ioe.printStackTrace(); } return mailrcNewsGroups; } // Finds all the mailrc files for all the given News directories private static File[] findMailrcFiles(File[] newsDirs) { Vector allFiles = new Vector(); for( int i=0; i < newsDirs.length; i++ ) { //System.out.println( "Finding mailrc for: " + newsDirs[i] ); if( newsDirs[i] != null ) { File mailrcFiles[] = newsDirs[i].listFiles( new VersionFilter() ); //System.out.println( "Number found: " + mailrcFiles.length ); for( int j=0; j < mailrcFiles.length; j++ ) { //System.out.println( "This mailrc was found: " + mailrcFiles[j] ); allFiles.addElement( mailrcFiles[j] ); } } } File allMailrcFiles[] = new File[ allFiles.size() ]; allFiles.copyInto(allMailrcFiles); //System.out.println( "number of mailrcs in total: " + allMailrcFiles.length ); if( allMailrcFiles.length == 0 ) { //System.out.println( "Returning null"); return null; } //System.out.println( "Returning an File array containing mailrcs"); return allMailrcFiles; } // Finds all profiles belonging to one user (can be more than one) private static File[] findProfiles(File start) { // Get all files and directories in .mozilla File allFiles[] = start.listFiles(); File[] dirs = new File[allFiles.length]; int dirCounter = 0; // Remove files leaving directories only for(int i=0; i < allFiles.length; i++ ) { if(allFiles[i].isDirectory()) { dirs[dirCounter] = allFiles[i]; dirCounter++; } } // Add each directory to a user profile array File[] profileDirs = new File[dirCounter]; for( int i=0; i < dirCounter; i++ ) { profileDirs[i] = dirs[i]; } // return a File array containing the profile dirs return profileDirs; } // Recursively searches for the News directory for a given profile directory private static File findNewsDir(File start) { File mailrcFile = null; // File array containing all matches for the version filter ("News") File files[] = start.listFiles(new VersionFilter()); // If the array is empty then no matches were found if (files.length == 0) { // File array of all the directories in File start File dirs[] = start.listFiles(new DirFilter()); // for each of the directories check for a match for (int i=0; i< dirs.length; i++) { mailrcFile = findNewsDir(dirs[i]); if (mailrcFile != null) { // break the for loop break; } } } else { mailrcFile = files[0]; } // return a File representing the News dir in a profile return mailrcFile; } } class DirFilter implements FileFilter { public boolean accept(File aFile) { return aFile.isDirectory(); } } class VersionFilter implements FileFilter { public boolean accept(File aFile) { if( System.getProperty( "os.name" ).indexOf( "Windows" ) != -1 ) { if (aFile.getName().compareToIgnoreCase("News") == 0 || aFile.getName().indexOf(".rc") != -1 ) { return true; } } else { if (aFile.getName().compareToIgnoreCase("News") == 0 || aFile.getName().indexOf("newsrc") != -1 ) { return true; } } return false; } }
package com.cube.storm; import android.content.Context; import android.support.annotation.NonNull; import com.cube.storm.ui.controller.downloader.StormSchemeHandler; import com.cube.storm.ui.data.ContentSize; import com.cube.storm.ui.lib.factory.FileFactory; import com.cube.storm.ui.lib.factory.IntentFactory; import com.cube.storm.ui.lib.factory.ViewFactory; import com.cube.storm.ui.lib.handler.LinkHandler; import com.cube.storm.ui.lib.parser.ViewBuilder; import com.cube.storm.ui.lib.parser.ViewProcessor; import com.cube.storm.ui.lib.processor.TextProcessor; import com.cube.storm.ui.lib.resolver.AppResolver; import com.cube.storm.ui.lib.spec.DividerSpec; import com.cube.storm.ui.lib.spec.ListDividerSpec; import com.cube.storm.ui.model.App; import com.cube.storm.ui.model.Model; import com.cube.storm.ui.model.list.ListItem; import com.cube.storm.ui.model.list.collection.CollectionItem; import com.cube.storm.ui.model.page.Page; import com.cube.storm.ui.model.property.LinkProperty; import com.cube.storm.ui.model.property.TextProperty; import com.cube.storm.util.lib.processor.Processor; import com.cube.storm.util.lib.resolver.AssetsResolver; import com.cube.storm.util.lib.resolver.FileResolver; import com.cube.storm.util.lib.resolver.Resolver; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import java.lang.reflect.Type; import java.util.LinkedHashMap; import java.util.Map; import lombok.Getter; import lombok.Setter; /** * This is the entry point class of the library. To enable the use of the library, you must instantiate * a new {@link UiSettings.Builder} object in your {@link android.app.Application} singleton class. * * This class should not be directly instantiated. * * @author Callum Taylor * @project LightningUi */ public class UiSettings { /** * The singleton instance of the settings */ private static UiSettings instance; public static UiSettings getInstance() { if (instance == null) { throw new IllegalAccessError("You must build the Ui settings object first using UiSettings$Builder"); } return instance; } /** * Default private constructor */ private UiSettings(){} /** * App data for the content */ @Getter private App app; /** * The intent factory instance of the module. This is the instance that will be used to resolve * every activity/fragment for a storm page/Uri */ @Getter @Setter private IntentFactory intentFactory; /** * The view factory instance of the module. This is the instance that will be used to resolve * models and holders for a specific view */ @Getter @Setter private ViewFactory viewFactory; /** * Factory class responsible for loading a file from disk based on its Uri */ @Getter @Setter private FileFactory fileFactory; /** * The view processor map used by {@link com.cube.storm.ui.lib.parser.ViewBuilder}. Use {@link com.cube.storm.UiSettings.Builder#registerType(Type, com.cube.storm.ui.lib.parser.ViewProcessor)} to * override the processor used to match models with json class names */ @Getter @Setter private Map<Type, ViewProcessor> viewProcessors = new LinkedHashMap<Type, ViewProcessor>(0); /** * Image loader which is used when displaying images in the list */ @Getter @Setter private ImageLoader imageLoader = ImageLoader.getInstance(); /** * The density to use when loading images */ @Getter @Setter private ContentSize contentSize; /** * The handler used when a link is triggered */ @Getter @Setter private LinkHandler linkHandler; /** * The gson builder class used to build all of the storm objects from json/string/binary */ @Getter @Setter private ViewBuilder viewBuilder; /** * Processor class used to process strings as part of {@link com.cube.storm.ui.model.property.TextProperty} */ @Getter @Setter private Processor<TextProperty, String> textProcessor; /** * Uri resolver used to load a file based on it's protocol. You should not need to use this instance * directly to load a file, instead use {@link com.cube.storm.ui.lib.factory.FileFactory} which uses this * to resolve a file and load it. Only use this if you want to load a specific scheme */ @Getter @Setter private Map<String, Resolver> uriResolvers = new LinkedHashMap<String, Resolver>(2); /** * Default divider spec to use in {@link com.cube.storm.ui.controller.adapter.StormListAdapter} */ @Getter @Setter private DividerSpec dividerSpec; /** * Sets the app model of the content * * @param app The new app model */ public void setApp(@NonNull App app) { this.app = app; } /** * The builder class for {@link com.cube.storm.UiSettings}. Use this to create a new {@link com.cube.storm.UiSettings} instance * with the customised properties specific for your project. * * Call {@link #build()} to build the settings object. */ public static class Builder { /** * The temporary instance of the {@link UiSettings} object. */ private UiSettings construct; private Context context; /** * Default constructor */ public Builder(Context context) { this.construct = new UiSettings(); this.context = context.getApplicationContext(); intentFactory(new IntentFactory(){}); viewFactory(new ViewFactory(){}); fileFactory(new FileFactory(){}); imageLoaderConfiguration(new ImageLoaderConfiguration.Builder(this.context)); linkHandler(new LinkHandler()); textProcessor(new TextProcessor()); contentSize(ContentSize.MEDIUM); ViewProcessor<? extends Model> baseProcessor = new ViewProcessor<Model>() { @Override public Class<? extends Model> getClassFromName(String name) { return UiSettings.getInstance().getViewFactory().getModelForView(name); } }; registerType(Page.class, baseProcessor); registerType(ListItem.class, baseProcessor); registerType(CollectionItem.class, baseProcessor); registerType(LinkProperty.class, baseProcessor); registerUriResolver("file", new FileResolver()); registerUriResolver("assets", new AssetsResolver(this.context)); registerUriResolver("app", new AppResolver(this.context)); viewBuilder(new ViewBuilder(){}); dividerSpec(new ListDividerSpec()); } /** * Sets the default {@link com.cube.storm.ui.lib.spec.DividerSpec} for the list adapter to use when layout out its children * * @param spec The new divider spec to use by default * * @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining */ public Builder dividerSpec(DividerSpec spec) { construct.dividerSpec = spec; return this; } /** * Sets the default {@link com.cube.storm.ui.lib.factory.IntentFactory} for the module * * @param intentFactory The new {@link com.cube.storm.ui.lib.factory.IntentFactory} * * @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining */ public Builder intentFactory(IntentFactory intentFactory) { construct.intentFactory = intentFactory; return this; } /** * Sets the default {@link com.cube.storm.ui.lib.factory.ViewFactory} for the module * * @param viewFactory The new {@link com.cube.storm.ui.lib.factory.ViewFactory} * * @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining */ public Builder viewFactory(ViewFactory viewFactory) { construct.viewFactory = viewFactory; return this; } /** * Sets the default {@link com.cube.storm.ui.lib.factory.FileFactory} for the module * * @param fileFactory The new {@link com.cube.storm.ui.lib.factory.FileFactory} * * @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining */ public Builder fileFactory(FileFactory fileFactory) { construct.fileFactory = fileFactory; return this; } /** * Sets the default image loader configuration. * * Note: The ImageDownloader set in the builder is overriden by this method to allow the use * of {@link #getUriResolvers()} to resolve the uris for loading images. Use {@link #registerUriResolver(String, com.cube.storm.util.lib.resolver.Resolver)} * to register any additional custom uris you wish to override. * * TODO: Find a better way to allow users to use their own imagedownloader, we should not be blocking this config * * @param configuration The new configuration for the image loader * * @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining */ public Builder imageLoaderConfiguration(ImageLoaderConfiguration.Builder configuration) { if (construct.imageLoader.isInited()) { construct.imageLoader.destroy(); } construct.imageLoader.init(configuration.build()); return this; } /** * Sets the default {@link com.cube.storm.ui.data.ContentSize} for the module * * @param contentSize The new {@link com.cube.storm.ui.data.ContentSize} * * @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining */ public Builder contentSize(ContentSize contentSize) { construct.contentSize = contentSize; return this; } /** * Sets the default {@link com.cube.storm.ui.lib.handler.LinkHandler} for the module * * @param linkHandler The new {@link com.cube.storm.ui.lib.handler.LinkHandler} * * @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining */ public Builder linkHandler(LinkHandler linkHandler) { construct.linkHandler = linkHandler; return this; } /** * Sets the default {@link com.cube.storm.ui.lib.parser.ViewBuilder} for the module * * @param viewBuilder The new {@link com.cube.storm.ui.lib.parser.ViewBuilder} * * @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining */ public Builder viewBuilder(ViewBuilder viewBuilder) { construct.viewBuilder = viewBuilder; return this; } /** * Sets the default {@link com.cube.storm.util.lib.processor.Processor} for the module * * @param textProcessor The new {@link com.cube.storm.util.lib.processor.Processor} * * @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining */ public Builder textProcessor(Processor<TextProperty, String> textProcessor) { construct.textProcessor = textProcessor; return this; } /** * Registers a deserializer type for a class instance. Use this method to override what processor * gets used for a specific view type. * * @param instanceClass The class to register for deserialization * @param deserializer The processor class * * @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining */ public Builder registerType(Type instanceClass, ViewProcessor deserializer) { construct.viewProcessors.put(instanceClass, deserializer); return this; } /** * Registers a uri resolver to use in the {@link com.cube.storm.ui.lib.factory.FileFactory} * * @param protocol The string protocol to register * @param resolver The resolver to use for the registered protocol * * @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining */ public Builder registerUriResolver(String protocol, Resolver resolver) { construct.uriResolvers.put(protocol, resolver); ImageLoader.getInstance().registerSchemeHandler(protocol, new StormSchemeHandler()); return this; } /** * Registers a uri resolvers * * @param resolvers The map of resolvers to register * * @return The {@link com.cube.storm.UiSettings.Builder} instance for chaining */ public Builder registerUriResolver(Map<String, Resolver> resolvers) { construct.uriResolvers.putAll(resolvers); for (String protocol : resolvers.keySet()) { ImageLoader.getInstance().registerSchemeHandler(protocol, new StormSchemeHandler()); } return this; } /** * Builds the final settings object and sets its instance. Use {@link #getInstance()} to retrieve the settings * instance. * * @return The newly set {@link com.cube.storm.UiSettings} instance */ public UiSettings build() { return (UiSettings.instance = construct); } } }
package com.mancj.slideup; import android.animation.Animator; import android.animation.TimeInterpolator; import android.animation.ValueAnimator; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import android.view.animation.DecelerateInterpolator; import android.view.inputmethod.InputMethodManager; import java.io.Serializable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static android.view.Gravity.BOTTOM; import static android.view.Gravity.END; import static android.view.Gravity.START; import static android.view.Gravity.TOP; import static android.view.View.GONE; import static android.view.View.VISIBLE; import static com.mancj.slideup.SlideUp.State.HIDDEN; import static com.mancj.slideup.SlideUp.State.SHOWED; public class SlideUp<T extends View> implements View.OnTouchListener, ValueAnimator.AnimatorUpdateListener, Animator.AnimatorListener { private final static String TAG = "SlideUp"; private final static String KEY_START_GRAVITY = TAG + "_start_gravity"; private final static String KEY_DEBUG = TAG + "_debug"; private final static String KEY_TOUCHABLE_AREA = TAG + "_touchable_area"; private final static String KEY_STATE = TAG + "_state"; private final static String KEY_AUTO_SLIDE_DURATION = TAG + "_auto_slide_duration"; private final static String KEY_HIDE_SOFT_INPUT = TAG + "_hide_soft_input"; /** * <p>Available start states</p> * */ public enum State implements Parcelable, Serializable { /** * State hidden is equal {@link View#GONE} * */ HIDDEN, /** * State showed is equal {@link View#VISIBLE} * */ SHOWED; @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(ordinal()); } @Override public int describeContents() { return 0; } public static final Creator<State> CREATOR = new Creator<State>() { @Override public State createFromParcel(Parcel in) { return State.values()[in.readInt()]; } @Override public State[] newArray(int size) { return new State[size]; } }; } @IntDef(value = {START, END, TOP, BOTTOM}) @Retention(RetentionPolicy.SOURCE) private @interface StartVector{} private State startState; private State currentState; private T sliderView; private float touchableArea; private int autoSlideDuration; private List<Listener> listeners; private ValueAnimator valueAnimator; private float slideAnimationTo; private float startPositionY; private float startPositionX; private float viewStartPositionY; private float viewStartPositionX; private boolean canSlide = true; private float density; private float maxSlidePosition; private float viewHeight; private float viewWidth; private boolean hideKeyboard; private TimeInterpolator interpolator; private boolean gesturesEnabled; private boolean isRTL; private int startGravity; private boolean debug; /** * <p>Interface to listen to all handled events taking place in the slider</p> * */ public interface Listener { /** * @param percent percents of complete slide <b color="#FFEE58">(100 = HIDDEN, 0 = SHOWED)</b> * */ void onSlide(float percent); /** * @param visibility (<b>GONE</b> or <b>VISIBLE</b>) * */ void onVisibilityChanged(int visibility); } /** * <p>Adapter for {@link Listener}. With it you can use all, some single, or none method from Listener</p> * */ public static class ListenerAdapter implements Listener { public void onSlide(float percent){} public void onVisibilityChanged(int visibility){} } /** * <p>Default constructor for SlideUp</p> * */ public final static class Builder<T extends View>{ private T sliderView; private float density; private float touchableArea; private boolean isRTL; private State startState = HIDDEN; private List<Listener> listeners = new ArrayList<>(); private boolean debug = false; private int autoSlideDuration = 300; private int startGravity = BOTTOM; private boolean gesturesEnabled = true; private boolean hideKeyboard = false; private TimeInterpolator interpolator = new DecelerateInterpolator(); /** * <p>Construct a SlideUp by passing the view or his child to use for the generation</p> * */ public Builder(@NonNull T sliderView){ this.sliderView = sliderView; density = sliderView.getResources().getDisplayMetrics().density; isRTL = sliderView.getResources().getBoolean(R.bool.is_right_to_left); touchableArea = 300 * density; } /** * <p>Define a start state on screen</p> * * @param startState <b>(default - <b color="#FFEE58">{@link State#HIDDEN}</b>)</b> * */ public Builder withStartState(@NonNull State startState){ this.startState = startState; return this; } /** * <p>Define a start gravity, <b>this parameter affects the motion vector slider</b></p> * * @param gravity <b>(default - <b color="#FFEE58">{@link android.view.Gravity#BOTTOM}</b>)</b> * */ public Builder withStartGravity(@StartVector int gravity){ startGravity = gravity; return this; } /** * <p>Define a {@link Listener} for this SlideUp</p> * * @param listeners {@link List} of listeners * */ public Builder withListeners(@NonNull List<Listener> listeners){ this.listeners = listeners; return this; } /** * <p>Define a {@link Listener} for this SlideUp</p> * * @param listeners array of listeners * */ public Builder withListeners(@NonNull Listener... listeners){ List<Listener> listeners_list = new ArrayList<>(); Collections.addAll(listeners_list, listeners); return withListeners(listeners_list); } /** * <p>Turning on/off debug logging for all handled events</p> * * @param enabled <b>(default - <b color="#FFEE58">false</b>)</b> * */ public Builder withLoggingEnabled(boolean enabled){ debug = enabled; return this; } /** * <p>Define duration of animation (whenever you use {@link #hide()} or {@link #show()} methods)</p> * * @param duration <b>(default - <b color="#FFEE58">300</b>)</b> * */ public Builder withAutoSlideDuration(int duration){ autoSlideDuration = duration; return this; } /** * <p>Define touchable area <b>(in dp)</b> for interaction</p> * * @param area <b>(default - <b color="#FFEE58">300dp</b>)</b> * */ public Builder withTouchableArea(float area){ touchableArea = area * density; return this; } /** * <p>Turning on/off sliding on touch event</p> * * @param enabled <b>(default - <b color="#FFEE58">true</b>)</b> * */ public Builder withGesturesEnabled(boolean enabled){ gesturesEnabled = enabled; return this; } /** * <p>Define behavior of soft input</p> * * @param hide <b>(default - <b color="#FFEE58">false</b>)</b> * */ public Builder withHideSoftInputWhenDisplayed(boolean hide){ hideKeyboard = hide; return this; } /** * <p>Define interpolator for animation (whenever you use {@link #hide()} or {@link #show()} methods)</p> * * @param interpolator <b>(default - <b color="#FFEE58">Decelerate interpolator</b>)</b> * */ public Builder withInterpolator(TimeInterpolator interpolator){ this.interpolator = interpolator; return this; } /** * <p> * <b color="#FFEE58">IMPORTANT:</b> * If you want to restore saved parameters, place this method at the end of builder * </p> * @param savedState parameters will be restored from this bundle, if it contains them * */ public Builder withSavedState(@Nullable Bundle savedState){ restoreParams(savedState); return this; } /** * <p>Build the SlideUp and add behavior to view</p> * */ public SlideUp<T> build(){ return new SlideUp<>(this); } /** * <p>Trying restore saved state</p> * */ private void restoreParams(@Nullable Bundle savedState){ if (savedState == null) return; if (savedState.getParcelable(KEY_STATE) != null) startState = savedState.getParcelable(KEY_STATE); startGravity = savedState.getInt(KEY_START_GRAVITY, startGravity); debug = savedState.getBoolean(KEY_DEBUG, debug); touchableArea = savedState.getFloat(KEY_TOUCHABLE_AREA, touchableArea) * density; autoSlideDuration = savedState.getInt(KEY_AUTO_SLIDE_DURATION, autoSlideDuration); hideKeyboard = savedState.getBoolean(KEY_HIDE_SOFT_INPUT, hideKeyboard); } } /** * <p>Trying hide soft input from window</p> * * @see InputMethodManager#hideSoftInputFromWindow(IBinder, int) * */ public void hideSoftInput(){ ((InputMethodManager) sliderView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(sliderView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } /** * <p>Trying show soft input to window</p> * * @see InputMethodManager#showSoftInput(View, int) * */ public void showSoftInput(){ ((InputMethodManager) sliderView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)) .showSoftInput(sliderView, 0); } private SlideUp(Builder<T> builder){ startGravity = builder.startGravity; listeners = builder.listeners; sliderView = builder.sliderView; startState = builder.startState; density = builder.density; touchableArea = builder.touchableArea; autoSlideDuration = builder.autoSlideDuration; debug = builder.debug; isRTL = builder.isRTL; gesturesEnabled = builder.gesturesEnabled; hideKeyboard = builder.hideKeyboard; interpolator = builder.interpolator; init(); } private void init() { sliderView.setOnTouchListener(this); createAnimation(); sliderView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { viewHeight = sliderView.getHeight(); viewWidth = sliderView.getWidth(); switch (startGravity){ case TOP: sliderView.setPivotY(viewHeight); break; case BOTTOM: sliderView.setPivotY(0); break; case START: sliderView.setPivotX(0); break; case END: sliderView.setPivotX(viewWidth); break; } updateToCurrentState(); ViewTreeObserver observer = sliderView.getViewTreeObserver(); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) { observer.removeGlobalOnLayoutListener(this); } else { observer.removeOnGlobalLayoutListener(this); } } }); updateToCurrentState(); } private void updateToCurrentState() { switch (startState){ case HIDDEN: hideImmediately(); break; case SHOWED: showImmediately(); break; } } /** * <p>Returns the visibility status for this view.</p> * * @return true if view have status {@link View#VISIBLE} */ public boolean isVisible(){ return sliderView.getVisibility() == VISIBLE; } /** * <p>Add Listener which will be used in combination with this SlideUp</p> * */ public void addSlideListener(@NonNull Listener listener){ listeners.add(listener); } /** * <p>Remove Listener which was used in combination with this SlideUp</p> * */ public void removeSlideListener(@NonNull Listener listener){ listeners.remove(listener); } /** * <p>Returns typed view which was used as slider</p> * */ public T getSliderView() { return sliderView; } /** * <p>Set duration of animation (whenever you use {@link #hide()} or {@link #show()} methods)</p> * * @param autoSlideDuration <b>(default - <b color="#FFEE58">300</b>)</b> * */ public void setAutoSlideDuration(int autoSlideDuration) { this.autoSlideDuration = autoSlideDuration; } /** * <p>Returns duration of animation (whenever you use {@link #hide()} or {@link #show()} methods)</p> * */ public float getAutoSlideDuration(){ return this.autoSlideDuration; } /** * <p>Set touchable area <b>(in dp)</b> for interaction</p> * * @param touchableArea <b>(default - <b color="#FFEE58">300dp</b>)</b> * */ public void setTouchableArea(float touchableArea) { this.touchableArea = touchableArea * density; } /** * <p>Returns touchable area <b>(in dp)</b> for interaction</p> * */ public float getTouchableArea() { return this.touchableArea / density; } /** * <p>Returns running status of animation</p> * * @return true if animation is running * */ public boolean isAnimationRunning(){ return valueAnimator != null && valueAnimator.isRunning(); } /** * <p>Show view with animation</p> * */ public void show(){ show(false); } /** * <p>Hide view with animation</p> * */ public void hide(){ hide(false); } /** * <p>Hide view without animation</p> * */ public void hideImmediately() { hide(true); } /** * <p>Show view without animation</p> * */ public void showImmediately() { show(true); } /** * <p>Turning on/off debug logging</p> * * @param enabled <b>(default - <b color="#FFEE58">false</b>)</b> * */ public void setLoggingEnabled(boolean enabled){ debug = enabled; } /** * <p>Returns current status of debug logging</p> * */ public boolean isLoggingEnabled(){ return debug; } /** * <p>Turning on/off gestures</p> * * @param enabled <b>(default - <b color="#FFEE58">true</b>)</b> * */ public void setGesturesEnabled(boolean enabled) { this.gesturesEnabled = enabled; } /** * <p>Returns current status of gestures</p> * */ public boolean isGesturesEnabled() { return gesturesEnabled; } /** * <p>Returns current interpolator</p> * */ public TimeInterpolator getInterpolator() { return interpolator; } /** * <p>Returns gravity which used in combination with this SlideUp</p> * */ @StartVector public int getStartGravity() { return startGravity; } /** * <p>Sets interpolator for animation (whenever you use {@link #hide()} or {@link #show()} methods)</p> * * @param interpolator <b>(default - <b color="#FFEE58">DecelerateInterpolator</b>)</b> * */ public void setInterpolator(TimeInterpolator interpolator) { valueAnimator.setInterpolator(this.interpolator = interpolator); } /** * <p>Returns current behavior of soft input</p> * */ public boolean isHideKeyboardWhenDisplayed() { return hideKeyboard; } /** * <p>Sets behavior of soft input</p> * * @param hide <b>(default - <b color="#FFEE58">false</b>)</b> * */ public void setHideKeyboardWhenDisplayed(boolean hide) { hideKeyboard = hide; } /** * <p>Saving current parameters of SlideUp</p> * * @return {@link Bundle} with saved parameters of SlideUp * */ public Bundle onSaveInstanceState(@Nullable Bundle savedState){ if (savedState == null) savedState = Bundle.EMPTY; savedState.putInt(KEY_START_GRAVITY, startGravity); savedState.putBoolean(KEY_DEBUG, debug); savedState.putFloat(KEY_TOUCHABLE_AREA, touchableArea / density); savedState.putParcelable(KEY_STATE, currentState); savedState.putInt(KEY_AUTO_SLIDE_DURATION, autoSlideDuration); savedState.putBoolean(KEY_HIDE_SOFT_INPUT, hideKeyboard); return savedState; } private void hide(boolean immediately) { switch (startGravity){ case TOP: if (immediately){ if (sliderView.getHeight() > 0){ sliderView.setTranslationY(viewHeight); sliderView.setVisibility(GONE); notifyVisibilityChanged(GONE); }else { startState = HIDDEN; } }else { this.slideAnimationTo = sliderView.getHeight(); valueAnimator.setFloatValues(sliderView.getTranslationY(), slideAnimationTo); valueAnimator.start(); } break; case BOTTOM: if (immediately){ if (sliderView.getHeight() > 0){ sliderView.setTranslationY(-viewHeight); sliderView.setVisibility(GONE); notifyVisibilityChanged(GONE); }else { startState = HIDDEN; } }else { this.slideAnimationTo = -sliderView.getHeight(); valueAnimator.setFloatValues(sliderView.getTranslationY(), slideAnimationTo); valueAnimator.start(); } break; case START: if (immediately){ if (sliderView.getWidth() > 0){ sliderView.setTranslationX(viewWidth); sliderView.setVisibility(GONE); notifyVisibilityChanged(GONE); }else { startState = HIDDEN; } }else { this.slideAnimationTo = sliderView.getWidth(); valueAnimator.setFloatValues(sliderView.getTranslationX(), slideAnimationTo); valueAnimator.start(); } break; case END: if (immediately){ if (sliderView.getWidth() > 0){ sliderView.setTranslationX(-viewWidth); sliderView.setVisibility(GONE); notifyVisibilityChanged(GONE); }else { startState = HIDDEN; } }else { this.slideAnimationTo = -sliderView.getHeight(); valueAnimator.setFloatValues(sliderView.getTranslationX(), slideAnimationTo); valueAnimator.start(); } break; } } private void show(boolean immediately){ switch (startGravity) { case TOP: case BOTTOM: if (immediately){ if (sliderView.getHeight() > 0){ sliderView.setTranslationY(0); sliderView.setVisibility(VISIBLE); notifyVisibilityChanged(VISIBLE); }else { startState = SHOWED; } }else { this.slideAnimationTo = 0; valueAnimator.setFloatValues(viewHeight, slideAnimationTo); valueAnimator.start(); } break; case START: case END: if (immediately){ if (sliderView.getWidth() > 0){ sliderView.setTranslationX(0); sliderView.setVisibility(VISIBLE); notifyVisibilityChanged(VISIBLE); }else { startState = SHOWED; } }else { this.slideAnimationTo = 0; valueAnimator.setFloatValues(viewWidth, slideAnimationTo); valueAnimator.start(); } break; } } private void createAnimation(){ valueAnimator = ValueAnimator.ofFloat(); valueAnimator.setDuration(autoSlideDuration); valueAnimator.setInterpolator(interpolator); valueAnimator.addUpdateListener(this); valueAnimator.addListener(this); } @Override public final boolean onTouch(View v, MotionEvent event) { if (!gesturesEnabled) return false; if (isAnimationRunning()) return false; switch (startGravity){ case TOP: return onTouchUpToDown(event); case BOTTOM: return onTouchDownToUp(event); case START: return onTouchStartToEnd(event); case END: return onTouchEndToStart(event); default: e("onTouchListener", "(onTouch)", "You are using not supportable gravity"); return false; } } private boolean onTouchEndToStart(MotionEvent event){ float touchedArea = event.getRawX() - getEnd(); switch (event.getActionMasked()){ case MotionEvent.ACTION_DOWN: viewWidth = sliderView.getWidth(); startPositionX = event.getRawX(); viewStartPositionX = sliderView.getTranslationX(); if (touchableArea < touchedArea){ canSlide = false; } break; case MotionEvent.ACTION_MOVE: float difference = event.getRawX() - startPositionX; float moveTo = viewStartPositionX + difference; float percents = moveTo * 100 / sliderView.getWidth(); if (moveTo > 0 && canSlide){ notifyPercentChanged(percents); sliderView.setTranslationX(moveTo); } if (event.getRawX() > maxSlidePosition) { maxSlidePosition = event.getRawX(); } break; case MotionEvent.ACTION_UP: float slideAnimationFrom = sliderView.getTranslationX(); if (slideAnimationFrom == viewStartPositionX) return false; boolean mustShow = maxSlidePosition > event.getRawX(); boolean scrollableAreaConsumed = sliderView.getTranslationX() > sliderView.getWidth() / 5; if (scrollableAreaConsumed && !mustShow){ slideAnimationTo = sliderView.getWidth(); }else { slideAnimationTo = 0; } valueAnimator.setFloatValues(slideAnimationFrom, slideAnimationTo); valueAnimator.start(); canSlide = true; maxSlidePosition = 0; break; } return true; } private boolean onTouchStartToEnd(MotionEvent event){ float touchedArea = getEnd() - event.getRawX(); switch (event.getActionMasked()){ case MotionEvent.ACTION_DOWN: maxSlidePosition = viewWidth; viewWidth = sliderView.getWidth(); startPositionX = event.getRawX(); viewStartPositionX = sliderView.getTranslationX(); if (touchableArea < touchedArea){ canSlide = false; } break; case MotionEvent.ACTION_MOVE: float difference = event.getRawX() - startPositionX; float moveTo = viewStartPositionX + difference; float percents = moveTo * 100 / -sliderView.getWidth(); if (moveTo < 0 && canSlide){ notifyPercentChanged(percents); sliderView.setTranslationX(moveTo); } if (event.getRawX() < maxSlidePosition) { maxSlidePosition = event.getRawX(); } break; case MotionEvent.ACTION_UP: float slideAnimationFrom = -sliderView.getTranslationX(); if (slideAnimationFrom == viewStartPositionX) return false; boolean mustShow = maxSlidePosition < event.getRawX(); boolean scrollableAreaConsumed = sliderView.getTranslationX() < -sliderView.getHeight() / 5; if (scrollableAreaConsumed && !mustShow){ slideAnimationTo = sliderView.getWidth(); }else { slideAnimationTo = 0; } valueAnimator.setFloatValues(slideAnimationFrom, slideAnimationTo); valueAnimator.start(); canSlide = true; maxSlidePosition = 0; break; } return true; } private boolean onTouchDownToUp(MotionEvent event){ float touchedArea = event.getRawY() - sliderView.getTop(); switch (event.getActionMasked()){ case MotionEvent.ACTION_DOWN: viewHeight = sliderView.getHeight(); startPositionY = event.getRawY(); viewStartPositionY = sliderView.getTranslationY(); if (touchableArea < touchedArea){ canSlide = false; } break; case MotionEvent.ACTION_MOVE: float difference = event.getRawY() - startPositionY; float moveTo = viewStartPositionY + difference; float percents = moveTo * 100 / sliderView.getHeight(); if (moveTo > 0 && canSlide){ notifyPercentChanged(percents); sliderView.setTranslationY(moveTo); } if (event.getRawY() > maxSlidePosition) { maxSlidePosition = event.getRawY(); } break; case MotionEvent.ACTION_UP: float slideAnimationFrom = sliderView.getTranslationY(); if (slideAnimationFrom == viewStartPositionY) return false; boolean mustShow = maxSlidePosition > event.getRawY(); boolean scrollableAreaConsumed = sliderView.getTranslationY() > sliderView.getHeight() / 5; if (scrollableAreaConsumed && !mustShow){ slideAnimationTo = sliderView.getHeight(); }else { slideAnimationTo = 0; } valueAnimator.setFloatValues(slideAnimationFrom, slideAnimationTo); valueAnimator.start(); canSlide = true; maxSlidePosition = 0; break; } return true; } private boolean onTouchUpToDown(MotionEvent event){ float touchedArea = event.getRawY() - sliderView.getBottom(); switch (event.getActionMasked()){ case MotionEvent.ACTION_DOWN: viewHeight = sliderView.getHeight(); startPositionY = event.getRawY(); viewStartPositionY = sliderView.getTranslationY(); maxSlidePosition = viewHeight; if (touchableArea < touchedArea){ canSlide = false; } break; case MotionEvent.ACTION_MOVE: float difference = event.getRawY() - startPositionY; float moveTo = viewStartPositionY + difference; float percents = moveTo * 100 / -sliderView.getHeight(); if (moveTo < 0 && canSlide){ notifyPercentChanged(percents); sliderView.setTranslationY(moveTo); } if (event.getRawY() < maxSlidePosition) { maxSlidePosition = event.getRawY(); } break; case MotionEvent.ACTION_UP: float slideAnimationFrom = -sliderView.getTranslationY(); if (slideAnimationFrom == viewStartPositionY) return false; boolean mustShow = maxSlidePosition < event.getRawY(); boolean scrollableAreaConsumed = sliderView.getTranslationY() < -sliderView.getHeight() / 5; if (scrollableAreaConsumed && !mustShow){ slideAnimationTo = sliderView.getHeight() + sliderView.getTop(); }else { slideAnimationTo = 0; } valueAnimator.setFloatValues(slideAnimationFrom, slideAnimationTo); valueAnimator.start(); canSlide = true; maxSlidePosition = 0; break; } return true; } @Override public final void onAnimationUpdate(ValueAnimator animation) { float value = (float) animation.getAnimatedValue(); switch (startGravity){ case TOP: onAnimationUpdateUpToDown(value); break; case BOTTOM: onAnimationUpdateDownToUp(value); break; case START: onAnimationUpdateStartToEnd(value); break; case END: onAnimationUpdateEndToStart(value); break; } } private void onAnimationUpdateUpToDown(float value){ sliderView.setTranslationY(-value); float visibleDistance = sliderView.getTop() - sliderView.getY(); float percents = (visibleDistance) * 100 / viewHeight; notifyPercentChanged(percents); } private void onAnimationUpdateDownToUp(float value){ sliderView.setTranslationY(value); float visibleDistance = sliderView.getY() - sliderView.getTop(); float percents = (visibleDistance) * 100 / viewHeight; notifyPercentChanged(percents); } private void onAnimationUpdateStartToEnd(float value){ sliderView.setTranslationX(-value); float visibleDistance = sliderView.getX() - getStart(); float percents = (visibleDistance) * 100 / -viewWidth; notifyPercentChanged(percents); } private void onAnimationUpdateEndToStart(float value){ sliderView.setTranslationX(value); float visibleDistance = sliderView.getX() - getStart(); float percents = (visibleDistance) * 100 / viewWidth; notifyPercentChanged(percents); } private int getStart(){ if (isRTL){ return sliderView.getRight(); }else { return sliderView.getLeft(); } } private int getEnd(){ if (isRTL){ return sliderView.getLeft(); }else { return sliderView.getRight(); } } private void notifyPercentChanged(float percent){ percent = percent > 100 ? 100 : percent; percent = percent < 0 ? 0 : percent; if (slideAnimationTo == 0 && hideKeyboard) hideSoftInput(); if (listeners != null && !listeners.isEmpty()){ for (int i = 0; i < listeners.size(); i++) { Listener l = listeners.get(i); if (l != null){ l.onSlide(percent); d("Listener(" + i + ")", "(onSlide)", "value = " + percent); }else { e("Listener(" + i + ")", "(onSlide)", "Listener is null, skip notify for him..."); } } } } private void notifyVisibilityChanged(int visibility){ if (listeners != null && !listeners.isEmpty()){ for (int i = 0; i < listeners.size(); i++) { Listener l = listeners.get(i); if (l != null) { l.onVisibilityChanged(visibility); d("Listener(" + i + ")", "(onVisibilityChanged)", "value = " + (visibility == VISIBLE ? "VISIBLE" : visibility == GONE ? "GONE" : visibility)); }else { e("Listener(" + i + ")", "(onVisibilityChanged)", "Listener is null, skip notify for him..."); } } } switch (visibility){ case VISIBLE: currentState = SHOWED; break; case GONE: currentState = HIDDEN; break; } } @Override public final void onAnimationStart(Animator animator) { if (sliderView.getVisibility() != VISIBLE) { sliderView.setVisibility(VISIBLE); notifyVisibilityChanged(VISIBLE); } } @Override public final void onAnimationEnd(Animator animator) { if (slideAnimationTo != 0){ if (sliderView.getVisibility() != GONE) { sliderView.setVisibility(GONE); notifyVisibilityChanged(GONE); } } } @Override public final void onAnimationCancel(Animator animator) {} @Override public final void onAnimationRepeat(Animator animator) {} private void e(String listener, String method, String message){ if (debug) Log.e(TAG, String.format("%1$-15s %2$-23s %3$s", listener, method, message)); } private void d(String listener, String method, String value){ if (debug) Log.d(TAG, String.format("%1$-15s %2$-23s %3$s", listener, method, value)); } }
package com.codahale.metrics; /** * An abstraction for how time passes. It is passed to {@link Timer} to track * timing. */ public abstract class Clock { /** * Returns the current time tick. * * @return time tick in nanoseconds */ public abstract long getTick(); /** * Returns the current time in milliseconds. * * @return time in milliseconds */ public long getTime() { return System.currentTimeMillis(); } private static final Clock DEFAULT = new UserTimeClock(); /** * The default clock to use. * * @return the default {@link Clock} instance * * @see Clock.UserTimeClock */ public static Clock defaultClock() { return DEFAULT; } /** * A clock implementation which returns the current time in epoch * nanoseconds. */ public static class UserTimeClock extends Clock { @Override public long getTick() { return System.currentTimeMillis() * 1000000; } } }
package com.fastdtw.timeseries; import java.util.ArrayList; import java.util.List; public class PAA implements TimeSeries { private int[] aggPtSize; private final int originalLength; private final TimeSeries base; public PAA(TimeSeries ts, int shrunkSize) { validate(ts, shrunkSize); List<String> labels = new ArrayList<String>(ts.getLabels()); List<Double> timeReadings = new ArrayList<Double>(); List<TimeSeriesPoint> points = new ArrayList<TimeSeriesPoint>(); // Initialize private data. this.originalLength = ts.size(); this.aggPtSize = new int[shrunkSize]; // Determine the size of each sampled point. (may be a fraction) final double reducedPtSize = (double) ts.size() / (double) shrunkSize; // Variables that keep track of the range of points being averaged into // a single point. int ptToReadFrom = 0; int ptToReadTo; // Keep averaging ranges of points into aggregate points until all of // the data is averaged. while (ptToReadFrom < ts.size()) { // determine end of current range ptToReadTo = (int) Math.round(reducedPtSize * (timeReadings.size() + 1)) - 1; final int ptsToRead = ptToReadTo - ptToReadFrom + 1; // Keep track of the sum of all the values being averaged to create // a single point. double timeSum = 0.0; final double[] measurementSums = new double[ts.numOfDimensions()]; // Sum all of the values over the range ptToReadFrom...ptToReadFrom. for (int pt = ptToReadFrom; pt <= ptToReadTo; pt++) { final double[] currentPoint = ts.getMeasurementVector(pt); timeSum += ts.getTimeAtNthPoint(pt); for (int dim = 0; dim < ts.numOfDimensions(); dim++) measurementSums[dim] += currentPoint[dim]; } // end for loop // Determine the average value over the range // ptToReadFrom...ptToReadFrom. timeSum = timeSum / ptsToRead; for (int dim = 0; dim < ts.numOfDimensions(); dim++) // find the average of each measurement measurementSums[dim] = measurementSums[dim] / ptsToRead; // Add the computed average value to the aggregate approximation. this.aggPtSize[timeReadings.size()] = ptsToRead; timeReadings.add(timeSum); points.add(new TimeSeriesPoint(measurementSums)); ptToReadFrom = ptToReadTo + 1; // next window of points to average // startw where the last window ended } base = new TimeSeriesBase(labels, timeReadings, points); } private static int validate(TimeSeries ts, int shrunkSize) { if (shrunkSize > ts.size()) throw new RuntimeException( "ERROR: The size of an aggregate representation may not be largerr than the \n" + "original time series (shrunkSize=" + shrunkSize + " , origSize=" + ts.size() + ")."); if (shrunkSize <= 0) throw new RuntimeException( "ERROR: The size of an aggregate representation must be greater than zero and \n" + "no larger than the original time series."); return shrunkSize; } public int aggregatePtSize(int ptIndex) { return aggPtSize[ptIndex]; } public String toString() { return "(" + this.originalLength + " point time series represented as " + this.size() + " points)\n" + super.toString(); } @Override public int size() { return base.size(); } @Override public int numOfDimensions() { return base.numOfDimensions(); } @Override public double getTimeAtNthPoint(int n) { return base.getTimeAtNthPoint(n); } @Override public List<String> getLabels() { return base.getLabels(); } @Override public double getMeasurement(int pointIndex, int valueIndex) { return base.getMeasurement(pointIndex, valueIndex); } @Override public double getMeasurement(int pointIndex, String valueLabel) { return base.getMeasurement(pointIndex, valueLabel); } @Override public double[] getMeasurementVector(int pointIndex) { return base.getMeasurementVector(pointIndex); } } // end class PAA
package com.google.sps.data; import java.util.ArrayList; import java.util.List; // Class representing a Recipe public class Recipe { private ArrayList<String> ingredients; private ArrayList<String> steps; private ArrayList<String> tags; private String authorID; private String description; private String imageBlobKey; private String recipeName; private int popularity; private long id; public Recipe(long id, String recipeName, String imageBlobKey, String description, ArrayList<String> tags, ArrayList<String> ingredients, ArrayList<String> steps, int popularity) { this.id = id; this.recipeName = recipeName; this.imageBlobKey = imageBlobKey; this.tags = tags; this.description = description; this.ingredients = ingredients; this.steps = steps; this.popularity = popularity; } // haven't implemented yet public void setAuthorId(String id) { authorID = id; } public long getId() { return id; } public void increasePopularity() { popularity++; } public void decreasePopularity() { popularity } }
package com.java.utils; import com.java.IConverter; import com.java.exception.ConverterException; import com.java.regex.RegexValidation; public class DoubleUtils implements IConverter<Double> { private static DoubleUtils instance = new DoubleUtils(); private DoubleUtils() {} public static DoubleUtils getInstance() { return instance; } /** * Method responsible for converting the String value reported in Integer * * <br /><br /> * * @param Value (String) value to be converted into Integer * @return (Double) Double value transformed into * @throws ConverterException If an error occurs in the conversion. */ public Double convert(String value) throws ConverterException { Double newDouble = null; if (value != null && !value.equals("")) { try { newDouble = new Double(value); } catch(Exception e) { try { newDouble = new Double(value.replace(".", "").replace(",", ".")); } catch(Exception f) { throw new ConverterException(this.getClass(), f); } } } return newDouble; } /** * Checks if the String contains only numbers * * <br /><br /> * * Remember: * <ul> * <li><code>The string must contain only numbers</code></li> * </ul> * * @param value (String) string to check * @return (boolean) true if the string has only number, and false otherwise * @see com.java.regex.RegexValidation.OnlyNumbers() */ public static boolean isOnlyNumber(String value) { boolean ret = false; if (!StringUtils.isBlank(value)) { ret = value.matches(RegexValidation.OnlyNumbersFloats.expression()); } return ret; } /** * Check if the string is empty * * <br /><br /> * * Examples: * <ul> * <li><code>" " == false</code></li> * <li><code>"" == true</code></li> * <li><code>"0" == true</code></li> * <li><code>"0.1" == false</code></li> * <li><code>"0.01" == false</code></li> * <li><code>"0.001" == false</code></li> * <li><code>"1" == false</code></li> * </ul> * * @param value (String) string to check * @return (boolean) true to empty string and false otherwise * @see com.java.utils.StringUtils.isBlank(String) */ public static boolean isBlank(String value) { boolean isBlank = StringUtils.isBlank(value); if (!isBlank) { if (isOnlyNumber(value)) { isBlank = isZero(value); } } return isBlank; } public static boolean isZero(String value) { Double d = DoubleUtils.getInstance().convert(value); return Double.compare(d, Double.valueOf(0.0)) <= 0; } public static boolean isZero(double value) { return Double.compare(value, Double.valueOf(0.0)) <= 0; } public static double round(double round, int decimal, int ceilOrFloor) { round *= (Math.pow(10, decimal)); if (ceilOrFloor == 0) { round = Math.ceil(round); } else { round = Math.floor(round); } round /= (Math.pow(10, decimal)); return round; } }
package com.nerodesk.om.aws; import com.amazonaws.services.s3.model.ObjectMetadata; import com.jcabi.log.Logger; import com.jcabi.manifests.Manifests; import com.jcabi.s3.Bucket; import com.jcabi.s3.Ocket; import com.nerodesk.om.Attributes; import com.nerodesk.om.Doc; import com.nerodesk.om.Friends; import com.rosaloves.bitlyj.Bitly; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.validation.constraints.NotNull; import lombok.EqualsAndHashCode; import org.takes.misc.Href; /** * AWS-based version of Doc. * * @author Yegor Bugayenko (yegor@teamed.io) * @version $Id$ * @since 0.2 * @todo #101:30min Methods size, type and created have to replaced with correct * implementation. Size should give number of bytes of the document, type * should be MIME type of the document, created should be a timestamp when the * document was created. */ @EqualsAndHashCode(of = { "bucket", "user", "label" }) final class AwsDoc implements Doc { /** * Header with a list of friends. */ public static final String HEADER = "x-ndk-redirect"; /** * Bucket. */ private final transient Bucket bucket; /** * URN of the user. */ private final transient String user; /** * Doc name. */ private final transient String label; /** * Ctor. * @param bkt Bucket * @param urn URN of the user * @param doc Name of document */ AwsDoc(final Bucket bkt, final String urn, final String doc) { this.bucket = bkt; this.user = urn; this.label = doc; } @Override public boolean exists() throws IOException { return this.ocket().exists(); } @Override public void delete() throws IOException { this.bucket.remove(this.ocket().key()); } @Override public Friends friends() { return new AwsFriends(this.bucket, this.user, this.label); } @Override public void read(@NotNull final OutputStream output) throws IOException { Ocket ocket = this.ocket(); final String redir = ocket.meta().getUserMetaDataOf(AwsDoc.HEADER); if (redir != null) { ocket = this.bucket.ocket(redir); } ocket.read(output); Logger.info(this, "%s read", ocket); } @Override public void write(final InputStream input, final long size) throws IOException { final Ocket ocket = this.ocket(); if (ocket.exists() && ocket.meta().getUserMetaDataOf(AwsDoc.HEADER) != null) { throw new IllegalStateException("you can't write to this doc"); } final ObjectMetadata meta = new ObjectMetadata(); if (size > 0) { meta.setContentLength(size); } ocket.write(input, meta); Logger.info(this, "%d bytes saved to %s", size, ocket.key()); } @Override public String shortUrl() { return Bitly .as( Manifests.read("Nerodesk-BitlyId"), Manifests.read("Nerodesk-BitlyKey") ) .call( Bitly.shorten( new Href("http://beta.nerodesk.com/doc/read") .with("file", this.label).toString() ) ) .getShortUrl(); } @Override public Attributes attributes() throws IOException { return new AwsAttributes(); } /** * Ocket. * @return Key */ private Ocket ocket() { return this.bucket.ocket( String.format("%s/%s", this.user, this.label) ); } }
package com.tagadvance.sudoku; import java.io.IOException; import com.tagadvance.sudoku.SudokuBuilder.SudokuFactory; public class Main { public static void main(String[] args) throws UnsolvableException, IOException, InterruptedException { SudokuFactory<Integer> factory = SudokuBuilder.newBuilder().createClassicSudokuFactory(); Sudoku<Integer> sudoku = factory.createSudoku(); Grid<Integer> grid = factory.createEmptyGrid(); SudokuParser<Integer> parser = new IntegerSudokuParser(); String puzzle = "?????64?9?3?2???1???6?7?????7???2??5?4?????2?9??6???3?????9?1???9???3?7?3?54?????"; parser.populateSudokuFromString(grid, puzzle); System.out.println(grid); System.out.println(); SudokuSolver solver = new SimpleSudokuSolver(); Grid<Integer> result = solver.solve(sudoku, grid); System.out.println(result); System.out.println("**********"); } }
package crazypants.enderio; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.lang.reflect.Field; import java.util.List; import crazypants.enderio.entity.SkeletonHandler; import net.minecraft.block.material.Material; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.WeightedRandomChestContent; import net.minecraftforge.common.ChestGenHooks; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import com.google.common.collect.ImmutableList; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLLoadCompleteEvent; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLInterModComms; import cpw.mods.fml.common.event.FMLInterModComms.IMCEvent; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartedEvent; import cpw.mods.fml.common.event.FMLServerStoppedEvent; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.relauncher.Side; import crazypants.enderio.api.IMC; import crazypants.enderio.block.BlockDarkSteelAnvil; import crazypants.enderio.block.BlockDarkSteelLadder; import crazypants.enderio.block.BlockDarkSteelPressurePlate; import crazypants.enderio.block.BlockReinforcedObsidian; import crazypants.enderio.conduit.BlockConduitBundle; import crazypants.enderio.conduit.ConduitRecipes; import crazypants.enderio.conduit.facade.BlockConduitFacade; import crazypants.enderio.conduit.facade.ItemConduitFacade; import crazypants.enderio.conduit.gas.ItemGasConduit; import crazypants.enderio.conduit.geom.ConduitGeometryUtil; import crazypants.enderio.conduit.item.ItemExtractSpeedUpgrade; import crazypants.enderio.conduit.item.ItemItemConduit; import crazypants.enderio.conduit.item.filter.ItemBasicItemFilter; import crazypants.enderio.conduit.item.filter.ItemExistingItemFilter; import crazypants.enderio.conduit.item.filter.ItemModItemFilter; import crazypants.enderio.conduit.item.filter.ItemPowerItemFilter; import crazypants.enderio.conduit.liquid.ItemLiquidConduit; import crazypants.enderio.conduit.me.ItemMEConduit; import crazypants.enderio.conduit.power.ItemPowerConduit; import crazypants.enderio.conduit.redstone.ConduitBundledRedstoneProvider; import crazypants.enderio.conduit.redstone.InsulatedRedstoneConduit; import crazypants.enderio.conduit.redstone.ItemRedstoneConduit; import crazypants.enderio.config.Config; import crazypants.enderio.enchantment.Enchantments; import crazypants.enderio.enderface.BlockEnderIO; import crazypants.enderio.enderface.EnderfaceRecipes; import crazypants.enderio.enderface.ItemEnderface; import crazypants.enderio.fluid.BlockFluidEio; import crazypants.enderio.fluid.FluidFuelRegister; import crazypants.enderio.fluid.Fluids; import crazypants.enderio.fluid.ItemBucketEio; import crazypants.enderio.item.ItemConduitProbe; import crazypants.enderio.item.ItemMagnet; import crazypants.enderio.item.ItemRecipes; import crazypants.enderio.item.ItemSoulVessel; import crazypants.enderio.item.ItemYetaWrench; import crazypants.enderio.item.darksteel.DarkSteelItems; import crazypants.enderio.item.darksteel.SoundEntity; import crazypants.enderio.item.skull.BlockEndermanSkull; import crazypants.enderio.machine.MachineRecipes; import crazypants.enderio.machine.PacketRedstoneMode; import crazypants.enderio.machine.alloy.AlloyRecipeManager; import crazypants.enderio.machine.alloy.BlockAlloySmelter; import crazypants.enderio.machine.attractor.BlockAttractor; import crazypants.enderio.machine.buffer.BlockBuffer; import crazypants.enderio.machine.capbank.BlockCapBank; import crazypants.enderio.machine.crafter.BlockCrafter; import crazypants.enderio.machine.crusher.BlockCrusher; import crazypants.enderio.machine.crusher.CrusherRecipeManager; import crazypants.enderio.machine.enchanter.BlockEnchanter; import crazypants.enderio.machine.enchanter.EnchanterRecipeManager; import crazypants.enderio.machine.farm.BlockFarmStation; import crazypants.enderio.machine.farm.FarmersRegistry; import crazypants.enderio.machine.generator.combustion.BlockCombustionGenerator; import crazypants.enderio.machine.generator.stirling.BlockStirlingGenerator; import crazypants.enderio.machine.generator.zombie.BlockZombieGenerator; import crazypants.enderio.machine.hypercube.BlockHyperCube; import crazypants.enderio.machine.hypercube.HyperCubeRegister; import crazypants.enderio.machine.killera.BlockKillerJoe; import crazypants.enderio.machine.light.BlockElectricLight; import crazypants.enderio.machine.light.BlockLightNode; import crazypants.enderio.machine.monitor.BlockPowerMonitor; import crazypants.enderio.machine.painter.BlockPaintedCarpet; import crazypants.enderio.machine.painter.BlockPaintedFence; import crazypants.enderio.machine.painter.BlockPaintedFenceGate; import crazypants.enderio.machine.painter.BlockPaintedGlowstone; import crazypants.enderio.machine.painter.BlockPaintedSlab; import crazypants.enderio.machine.painter.BlockPaintedStair; import crazypants.enderio.machine.painter.BlockPaintedWall; import crazypants.enderio.machine.painter.BlockPainter; import crazypants.enderio.machine.painter.PaintSourceValidator; import crazypants.enderio.machine.power.BlockCapacitorBank; import crazypants.enderio.machine.ranged.RangeEntity; import crazypants.enderio.machine.reservoir.BlockReservoir; import crazypants.enderio.machine.slicensplice.BlockSliceAndSplice; import crazypants.enderio.machine.slicensplice.SliceAndSpliceRecipeManager; import crazypants.enderio.machine.solar.BlockSolarPanel; import crazypants.enderio.machine.soul.BlockSoulBinder; import crazypants.enderio.machine.soul.SoulBinderRecipeManager; import crazypants.enderio.machine.spawner.BlockPoweredSpawner; import crazypants.enderio.machine.spawner.ItemBrokenSpawner; import crazypants.enderio.machine.spawner.PoweredSpawnerConfig; import crazypants.enderio.machine.spawnguard.BlockSpawnGuard; import crazypants.enderio.machine.tank.BlockTank; import crazypants.enderio.machine.transceiver.BlockTransceiver; import crazypants.enderio.machine.transceiver.ServerChannelRegister; import crazypants.enderio.machine.vacuum.BlockVacuumChest; import crazypants.enderio.machine.vat.BlockVat; import crazypants.enderio.machine.vat.VatRecipeManager; import crazypants.enderio.machine.wireless.BlockWirelessCharger; import crazypants.enderio.machine.xp.BlockExperienceObelisk; import crazypants.enderio.machine.xp.ItemXpTransfer; import crazypants.enderio.material.Alloy; import crazypants.enderio.material.BlockDarkIronBars; import crazypants.enderio.material.BlockFusedQuartz; import crazypants.enderio.material.BlockIngotStorage; import crazypants.enderio.material.ItemAlloy; import crazypants.enderio.material.ItemCapacitor; import crazypants.enderio.material.ItemFrankenSkull; import crazypants.enderio.material.ItemFusedQuartzFrame; import crazypants.enderio.material.ItemMachinePart; import crazypants.enderio.material.ItemMaterial; import crazypants.enderio.material.ItemPowderIngot; import crazypants.enderio.material.MaterialRecipes; import crazypants.enderio.material.OreDictionaryPreferences; import crazypants.enderio.network.MessageTileNBT; import crazypants.enderio.network.PacketHandler; import crazypants.enderio.rail.BlockEnderRail; import crazypants.enderio.teleport.BlockTravelAnchor; import crazypants.enderio.teleport.ItemTravelStaff; import crazypants.enderio.teleport.TeleportRecipes; import crazypants.enderio.teleport.TravelController; import crazypants.util.EntityUtil; import static crazypants.enderio.EnderIO.MODID; import static crazypants.enderio.EnderIO.MOD_NAME; import static crazypants.enderio.EnderIO.VERSION; @Mod(modid = MODID, name = MOD_NAME, version = VERSION, dependencies = "required-after:Forge@10.13.2.1234,);after:MineFactoryReloaded", guiFactory = "crazypants.enderio.config.ConfigFactoryEIO") public class EnderIO { public static final String MODID = "EnderIO"; public static final String MOD_NAME = "Ender IO"; public static final String VERSION = "@VERSION@"; @Instance(MODID) public static EnderIO instance; @SidedProxy(clientSide = "crazypants.enderio.ClientProxy", serverSide = "crazypants.enderio.CommonProxy") public static CommonProxy proxy; public static final PacketHandler packetPipeline = new PacketHandler(); public static GuiHandler guiHandler = new GuiHandler(); // Materials public static ItemCapacitor itemBasicCapacitor; public static ItemAlloy itemAlloy; public static BlockFusedQuartz blockFusedQuartz; public static ItemFusedQuartzFrame itemFusedQuartzFrame; public static ItemMachinePart itemMachinePart; public static ItemPowderIngot itemPowderIngot; public static ItemMaterial itemMaterial; public static BlockIngotStorage blockIngotStorage; public static BlockDarkIronBars blockDarkIronBars; // Enderface public static BlockEnderIO blockEnderIo; public static ItemEnderface itemEnderface; //Teleporting public static BlockTravelAnchor blockTravelPlatform; public static ItemTravelStaff itemTravelStaff; // Painter public static BlockPainter blockPainter; public static BlockPaintedFence blockPaintedFence; public static BlockPaintedFenceGate blockPaintedFenceGate; public static BlockPaintedWall blockPaintedWall; public static BlockPaintedStair blockPaintedStair; public static BlockPaintedSlab blockPaintedSlab; public static BlockPaintedSlab blockPaintedDoubleSlab; public static BlockPaintedGlowstone blockPaintedGlowstone; public static BlockPaintedCarpet blockPaintedCarpet; // Conduits public static BlockConduitBundle blockConduitBundle; public static BlockConduitFacade blockConduitFacade; public static ItemConduitFacade itemConduitFacade; public static ItemRedstoneConduit itemRedstoneConduit; public static ItemPowerConduit itemPowerConduit; public static ItemLiquidConduit itemLiquidConduit; public static ItemItemConduit itemItemConduit; public static ItemGasConduit itemGasConduit; public static ItemMEConduit itemMEConduit; public static ItemBasicItemFilter itemBasicFilterUpgrade; public static ItemExistingItemFilter itemExistingItemFilter; public static ItemModItemFilter itemModItemFilter; public static ItemPowerItemFilter itemPowerItemFilter; public static ItemExtractSpeedUpgrade itemExtractSpeedUpgrade; // Machines public static BlockStirlingGenerator blockStirlingGenerator; public static BlockCombustionGenerator blockCombustionGenerator; public static BlockZombieGenerator blockZombieGenerator; public static BlockSolarPanel blockSolarPanel; public static BlockReservoir blockReservoir; public static BlockAlloySmelter blockAlloySmelter; public static BlockCapacitorBank blockCapacitorBank; public static BlockCapBank blockCapBank; public static BlockWirelessCharger blockWirelessCharger; public static BlockCrusher blockCrusher; public static BlockHyperCube blockHyperCube; public static BlockPowerMonitor blockPowerMonitor; public static BlockVat blockVat; public static BlockFarmStation blockFarmStation; public static BlockTank blockTank; public static BlockCrafter blockCrafter; public static BlockPoweredSpawner blockPoweredSpawner; public static ItemBrokenSpawner itemBrokenSpawner; public static BlockSliceAndSplice blockSliceAndSplice; public static BlockSoulBinder blockSoulFuser; public static BlockAttractor blockAttractor; public static BlockSpawnGuard blockSpawnGuard; public static BlockExperienceObelisk blockExperianceOblisk; public static BlockTransceiver blockTransceiver; public static BlockBuffer blockBuffer; public static BlockKillerJoe blockKillerJoe; public static BlockEnchanter blockEnchanter; public static BlockElectricLight blockElectricLight; public static BlockLightNode blockLightNode; //Blocks public static BlockDarkSteelPressurePlate blockDarkSteelPressurePlate; public static BlockDarkSteelAnvil blockDarkSteelAnvil; public static BlockDarkSteelLadder blockDarkSteelLadder; public static BlockEndermanSkull blockEndermanSkull; public static BlockReinforcedObsidian blockReinforcedObsidian; public static BlockEnderRail blockEnderRail; //Fluids public static Fluid fluidNutrientDistillation; public static BlockFluidEio blockNutrientDistillation; public static ItemBucketEio itemBucketNutrientDistillation; public static Fluid fluidHootch; public static BlockFluidEio blockHootch; public static ItemBucketEio itemBucketHootch; public static Fluid fluidRocketFuel; public static BlockFluidEio blockRocketFuel; public static ItemBucketEio itemBucketRocketFuel; public static Fluid fluidFireWater; public static BlockFluidEio blockFireWater; public static ItemBucketEio itemBucketFireWater; //Open block compatable liquid XP public static Fluid fluidXpJuice; public static ItemBucketEio itemBucketXpJuice; // Items public static ItemYetaWrench itemYetaWench; public static ItemConduitProbe itemConduitProbe; public static ItemMagnet itemMagnet; public static ItemXpTransfer itemXpTransfer; public static ItemSoulVessel itemSoulVessel; public static ItemFrankenSkull itemFrankenSkull; public static BlockVacuumChest blockVacuumChest; @EventHandler public void preInit(FMLPreInitializationEvent event) { Config.load(event); ConduitGeometryUtil.setupBounds((float) Config.conduitScale); blockStirlingGenerator = BlockStirlingGenerator.create(); blockCombustionGenerator = BlockCombustionGenerator.create(); blockZombieGenerator = BlockZombieGenerator.create(); blockSolarPanel = BlockSolarPanel.create(); blockCrusher = BlockCrusher.create(); blockAlloySmelter = BlockAlloySmelter.create(); blockCapacitorBank = BlockCapacitorBank.create(); blockCapBank = BlockCapBank.create(); blockPainter = BlockPainter.create(); blockPaintedFence = BlockPaintedFence.create(); blockPaintedFenceGate = BlockPaintedFenceGate.create(); blockPaintedWall = BlockPaintedWall.create(); blockPaintedStair = BlockPaintedStair.create(); blockPaintedSlab = new BlockPaintedSlab(false); blockPaintedDoubleSlab = new BlockPaintedSlab(true); blockPaintedSlab.init(); blockPaintedDoubleSlab.init(); blockCrafter = BlockCrafter.create(); blockPaintedGlowstone = BlockPaintedGlowstone.create(); blockPaintedCarpet = BlockPaintedCarpet.create(); blockVat = BlockVat.create(); blockPowerMonitor = BlockPowerMonitor.create(); blockFarmStation = BlockFarmStation.create(); blockWirelessCharger = BlockWirelessCharger.create(); blockHyperCube = BlockHyperCube.create(); blockTank = BlockTank.create(); blockReservoir = BlockReservoir.create(); blockVacuumChest = BlockVacuumChest.create(); blockTransceiver = BlockTransceiver.create(); blockBuffer = BlockBuffer.create(); blockEnderIo = BlockEnderIO.create(); blockTravelPlatform = BlockTravelAnchor.create(); blockSliceAndSplice = BlockSliceAndSplice.create(); blockSoulFuser = BlockSoulBinder.create(); blockPoweredSpawner = BlockPoweredSpawner.create(); blockKillerJoe = BlockKillerJoe.create(); blockAttractor = BlockAttractor.create(); blockSpawnGuard = BlockSpawnGuard.create(); blockExperianceOblisk = BlockExperienceObelisk.create(); blockEnchanter = BlockEnchanter.create(); blockDarkSteelPressurePlate = BlockDarkSteelPressurePlate.create(); blockDarkSteelAnvil = BlockDarkSteelAnvil.create(); blockDarkSteelLadder = BlockDarkSteelLadder.create(); blockElectricLight = BlockElectricLight.create(); blockLightNode = BlockLightNode.create(); blockReinforcedObsidian = BlockReinforcedObsidian.create(); blockFusedQuartz = BlockFusedQuartz.create(); itemFusedQuartzFrame = ItemFusedQuartzFrame.create(); blockEnderRail = BlockEnderRail.create(); blockConduitBundle = BlockConduitBundle.create(); blockConduitFacade = BlockConduitFacade.create(); itemConduitFacade = ItemConduitFacade.create(); itemBrokenSpawner = ItemBrokenSpawner.create(); blockEndermanSkull = BlockEndermanSkull.create(); itemFrankenSkull = ItemFrankenSkull.create(); itemRedstoneConduit = ItemRedstoneConduit.create(); itemPowerConduit = ItemPowerConduit.create(); itemLiquidConduit = ItemLiquidConduit.create(); itemItemConduit = ItemItemConduit.create(); itemGasConduit = ItemGasConduit.create(); itemMEConduit = ItemMEConduit.create(); itemBasicFilterUpgrade = ItemBasicItemFilter.create(); itemExistingItemFilter = ItemExistingItemFilter.create(); itemModItemFilter = ItemModItemFilter.create(); itemPowerItemFilter = ItemPowerItemFilter.create(); itemExtractSpeedUpgrade = ItemExtractSpeedUpgrade.create(); itemBasicCapacitor = ItemCapacitor.create(); itemMachinePart = ItemMachinePart.create(); itemMaterial = ItemMaterial.create(); itemAlloy = ItemAlloy.create(); itemPowderIngot = ItemPowderIngot.create(); registerFluids(); itemYetaWench = ItemYetaWrench.create(); itemEnderface = ItemEnderface.create(); itemTravelStaff = ItemTravelStaff.create(); itemConduitProbe = ItemConduitProbe.create(); itemMagnet = ItemMagnet.create(); itemXpTransfer = ItemXpTransfer.create(); itemSoulVessel = ItemSoulVessel.create(); blockIngotStorage = BlockIngotStorage.create(); blockDarkIronBars = BlockDarkIronBars.create(); DarkSteelItems.createDarkSteelArmorItems(); int entityID = EntityRegistry.findGlobalUniqueEntityId(); EntityRegistry.registerGlobalEntityID(SoundEntity.class, "soundEntity", entityID); EntityRegistry.registerModEntity(SoundEntity.class, "soundEntity", entityID, this, 0, 0, false); entityID = EntityRegistry.findGlobalUniqueEntityId(); EntityRegistry.registerGlobalEntityID(RangeEntity.class, "rangeEntity", entityID); EntityRegistry.registerModEntity(RangeEntity.class, "rangeEntity", entityID, this, 0, 0, false); FMLInterModComms.sendMessage("Waila", "register", "crazypants.enderio.waila.WailaCompat.load"); MaterialRecipes.registerOresInDictionary(); } private void registerFluids() { Fluid f = new Fluid(Fluids.NUTRIENT_DISTILLATION_NAME).setDensity(1500).setViscosity(3000); FluidRegistry.registerFluid(f); fluidNutrientDistillation = FluidRegistry.getFluid(f.getName()); blockNutrientDistillation = BlockFluidEio.create(fluidNutrientDistillation, Material.water); f = new Fluid(Fluids.HOOTCH_NAME).setDensity(900).setViscosity(1000); FluidRegistry.registerFluid(f); fluidHootch = FluidRegistry.getFluid(f.getName()); blockHootch = BlockFluidEio.create(fluidHootch, Material.water); FluidFuelRegister.instance.addFuel(f, Config.hootchPowerPerCycleRF, Config.hootchPowerTotalBurnTime); FMLInterModComms.sendMessage("Railcraft", "boiler-fuel-liquid", Fluids.HOOTCH_NAME + "@" + (Config.hootchPowerPerCycleRF / 10 * Config.hootchPowerTotalBurnTime)); f = new Fluid(Fluids.ROCKET_FUEL_NAME).setDensity(900).setViscosity(1000); FluidRegistry.registerFluid(f); fluidRocketFuel = FluidRegistry.getFluid(f.getName()); blockRocketFuel = BlockFluidEio.create(fluidRocketFuel, Material.water); FluidFuelRegister.instance.addFuel(f, Config.rocketFuelPowerPerCycleRF, Config.rocketFuelPowerTotalBurnTime); FMLInterModComms.sendMessage("Railcraft", "boiler-fuel-liquid", Fluids.ROCKET_FUEL_NAME + "@" + (Config.rocketFuelPowerPerCycleRF / 10 * Config.rocketFuelPowerTotalBurnTime)); f = new Fluid(Fluids.FIRE_WATER_NAME).setDensity(900).setViscosity(1000); FluidRegistry.registerFluid(f); fluidFireWater = FluidRegistry.getFluid(f.getName()); blockFireWater = BlockFluidEio.create(fluidFireWater, Material.lava); FluidFuelRegister.instance.addFuel(f, Config.fireWaterPowerPerCycleRF, Config.fireWaterPowerTotalBurnTime); FMLInterModComms.sendMessage("Railcraft", "boiler-fuel-liquid", Fluids.FIRE_WATER_NAME + "@" + (Config.fireWaterPowerPerCycleRF / 10 * Config.fireWaterPowerTotalBurnTime)); if(!Loader.isModLoaded("OpenBlocks")) { Log.info("XP Juice registered by Ender IO."); fluidXpJuice = new Fluid(Config.xpJuiceName).setLuminosity(10).setDensity(800).setViscosity(1500).setUnlocalizedName("eio.xpjuice"); FluidRegistry.registerFluid(fluidXpJuice); itemBucketXpJuice = ItemBucketEio.create(fluidXpJuice); } else { Log.info("XP Juice regististration left to Open Blocks."); } itemBucketNutrientDistillation = ItemBucketEio.create(fluidNutrientDistillation); itemBucketHootch = ItemBucketEio.create(fluidHootch); itemBucketRocketFuel = ItemBucketEio.create(fluidRocketFuel); itemBucketFireWater = ItemBucketEio.create(fluidFireWater); } @EventHandler public void load(FMLInitializationEvent event) { instance = this; PacketHandler.INSTANCE.registerMessage(MessageTileNBT.class, MessageTileNBT.class, PacketHandler.nextID(), Side.SERVER); PacketHandler.INSTANCE.registerMessage(PacketRedstoneMode.class, PacketRedstoneMode.class, PacketHandler.nextID(), Side.SERVER); NetworkRegistry.INSTANCE.registerGuiHandler(this, guiHandler); MinecraftForge.EVENT_BUS.register(this); //Register Custom Dungeon Loot here if(Config.lootDarkSteel) { ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem( new WeightedRandomChestContent(new ItemStack(EnderIO.itemAlloy, 1, Alloy.DARK_STEEL.ordinal()), 1, 3, 15)); } if(Config.lootItemConduitProbe) { ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(EnderIO.itemConduitProbe, 1, 0), 1, 1, 10)); } if(Config.lootQuartz) { ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(Items.quartz), 3, 16, 20)); } if(Config.lootNetherWart) { ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(Items.nether_wart), 1, 4, 10)); } if(Config.lootEnderPearl) { ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(Items.ender_pearl), 1, 2, 30)); } if(Config.lootElectricSteel) { ChestGenHooks.getInfo(ChestGenHooks.VILLAGE_BLACKSMITH).addItem( new WeightedRandomChestContent(new ItemStack(EnderIO.itemAlloy, 1, Alloy.ELECTRICAL_STEEL.ordinal()), 2, 6, 20)); } if(Config.lootRedstoneAlloy) { ChestGenHooks.getInfo(ChestGenHooks.VILLAGE_BLACKSMITH).addItem( new WeightedRandomChestContent(new ItemStack(EnderIO.itemAlloy, 1, Alloy.REDSTONE_ALLOY.ordinal()), 3, 6, 35)); } if(Config.lootDarkSteel) { ChestGenHooks.getInfo(ChestGenHooks.VILLAGE_BLACKSMITH).addItem( new WeightedRandomChestContent(new ItemStack(EnderIO.itemAlloy, 1, Alloy.DARK_STEEL.ordinal()), 3, 6, 35)); } if(Config.lootPhasedIron) { ChestGenHooks.getInfo(ChestGenHooks.VILLAGE_BLACKSMITH).addItem( new WeightedRandomChestContent(new ItemStack(EnderIO.itemAlloy, 1, Alloy.PHASED_IRON.ordinal()), 1, 2, 10)); } if(Config.lootPhasedGold) { ChestGenHooks.getInfo(ChestGenHooks.VILLAGE_BLACKSMITH).addItem( new WeightedRandomChestContent(new ItemStack(EnderIO.itemAlloy, 1, Alloy.PHASED_GOLD.ordinal()), 1, 2, 5)); } if(Config.lootTravelStaff) { ItemStack staff = new ItemStack(EnderIO.itemTravelStaff, 1, 0); ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(staff, 1, 1, 3)); ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_CHEST).addItem(new WeightedRandomChestContent(staff, 1, 1, 3)); } DarkSteelItems.addLoot(); if(Loader.isModLoaded("ComputerCraft")) { ConduitBundledRedstoneProvider.register(); } if(Config.replaceWitherSkeletons) { SkeletonHandler.registerSkeleton(this); } EnderfaceRecipes.addRecipes(); MaterialRecipes.addRecipes(); ConduitRecipes.addRecipes(); MachineRecipes.addRecipes(); ItemRecipes.addRecipes(); TeleportRecipes.addRecipes(); proxy.load(); } @EventHandler public void postInit(FMLPostInitializationEvent event) { Config.postInit(); //Regsiter the enchants Enchantments.getInstance(); MaterialRecipes.registerDependantOresInDictionary(); //This must be loaded before parsing the recipes so we get the preferred outputs OreDictionaryPreferences.loadConfig(); MaterialRecipes.addOreDictionaryRecipes(); MachineRecipes.addOreDictionaryRecipes(); ItemRecipes.addOreDictionaryRecipes(); CrusherRecipeManager.getInstance().loadRecipesFromConfig(); AlloyRecipeManager.getInstance().loadRecipesFromConfig(); SliceAndSpliceRecipeManager.getInstance().loadRecipesFromConfig(); VatRecipeManager.getInstance().loadRecipesFromConfig(); EnchanterRecipeManager.getInstance().loadRecipesFromConfig(); FarmersRegistry.addFarmers(); SoulBinderRecipeManager.getInstance().addDefaultRecipes(); PaintSourceValidator.instance.loadConfig(); if(fluidXpJuice == null) { //should have been registered by open blocks fluidXpJuice = FluidRegistry.getFluid(getXPJuiceName()); if(fluidXpJuice == null) { Log.error("Liquid XP Juice registration left to open blocks but could not be found."); } } if(Config.dumpMobNames) { File dumpFile = new File(Config.configDirectory, "mobTypes.txt"); List<String> names = EntityUtil.getAllRegisteredMobNames(false); try { BufferedWriter br = new BufferedWriter(new FileWriter(dumpFile, false)); for (String name : names) { br.append(name); br.newLine(); } br.flush(); br.close(); } catch (Exception e) { Log.error("Could not write mob types file: " + e); } } addModIntegration(); } @EventHandler public void loadComplete(FMLLoadCompleteEvent event) { processImc(FMLInterModComms.fetchRuntimeMessages(this)); //Some mods send IMCs during PostInit, so we catch them here. } private static String getXPJuiceName() { String openBlocksXPJuiceName = null; try { Field getField = Class.forName("openblocks.Config").getField("xpFluidId"); openBlocksXPJuiceName = (String) getField.get(null); }catch(Exception e) { } if(openBlocksXPJuiceName != null && !Config.xpJuiceName.equals(openBlocksXPJuiceName)) { Log.info("Overwriting XP Juice name with '" + openBlocksXPJuiceName + "' taken from OpenBlocks' config"); return openBlocksXPJuiceName; } return Config.xpJuiceName; } private void addModIntegration() { if(Loader.isModLoaded("TConstruct")) { try { Class<?> ttClass = Class.forName("tconstruct.tools.TinkerTools"); Field modFluxF = ttClass.getField("modFlux"); Object modFluxInst = modFluxF.get(null); Class<?> modFluxClass = Class.forName("tconstruct.modifiers.tools.ModFlux"); Field batteriesField = modFluxClass.getField("batteries"); List<ItemStack> batteries = (List<ItemStack>) batteriesField.get(modFluxInst); batteries.add(new ItemStack(blockCapBank)); Log.info("Registered Capacitor Banks as Tinkers Construct Flux Upgrades"); } catch (Exception e) { //Doesn't matter if it didnt work Log.info("Failed to registered Capacitor Banks as Tinkers Construct Flux Upgrades"); } } } @EventHandler public void onImc(IMCEvent evt) { processImc(evt.getMessages()); } private void processImc(ImmutableList<IMCMessage> messages) { for (IMCMessage msg : messages) { String key = msg.key; try { if(msg.isStringMessage()) { String value = msg.getStringValue(); if(IMC.VAT_RECIPE.equals(key)) { VatRecipeManager.getInstance().addCustomRecipes(value); } else if(IMC.SAG_RECIPE.equals(key)) { CrusherRecipeManager.getInstance().addCustomRecipes(value); } else if(IMC.ALLOY_RECIPE.equals(key)) { AlloyRecipeManager.getInstance().addCustomRecipes(value); } else if(IMC.POWERED_SPAWNER_BLACKLIST_ADD.equals(key)) { PoweredSpawnerConfig.getInstance().addToBlacklist(value); } else if(IMC.TELEPORT_BLACKLIST_ADD.equals(key)) { TravelController.instance.addBlockToBlinkBlackList(value); } else if(IMC.SOUL_VIAL_BLACKLIST.equals(key) && itemSoulVessel != null) { itemSoulVessel.addEntityToBlackList(value); } else if(IMC.ENCHANTER_RECIPE.equals(key)) { EnchanterRecipeManager.getInstance().addCustomRecipes(value); } else if(IMC.SLINE_N_SPLICE_RECIPE.equals(key)) { SliceAndSpliceRecipeManager.getInstance().addCustomRecipes(key); } } else if(msg.isNBTMessage()) { if(IMC.SOUL_BINDER_RECIPE.equals(key)) { SoulBinderRecipeManager.getInstance().addRecipeFromNBT(msg.getNBTValue()); } else if(IMC.POWERED_SPAWNER_COST_MULTIPLIER.equals(key)) { PoweredSpawnerConfig.getInstance().addEntityCostFromNBT(msg.getNBTValue()); } else if(IMC.FLUID_FUEL_ADD.equals(key)) { FluidFuelRegister.instance.addFuel(msg.getNBTValue()); } else if(IMC.FLUID_COOLANT_ADD.equals(key)) { FluidFuelRegister.instance.addCoolant(msg.getNBTValue()); } else if(IMC.REDSTONE_CONNECTABLE_ADD.equals(key)) { InsulatedRedstoneConduit.addConnectableBlock(msg.getNBTValue()); } } else if(msg.isItemStackMessage()) { if(IMC.PAINTER_WHITELIST_ADD.equals(key)) { PaintSourceValidator.instance.addToWhitelist(msg.getItemStackValue()); } else if(IMC.PAINTER_BLACKLIST_ADD.equals(key)) { PaintSourceValidator.instance.addToBlacklist(msg.getItemStackValue()); } } } catch (Exception e) { Log.error("Error occured handling IMC message " + key + " from " + msg.getSender()); } } } @EventHandler public void serverStarted(FMLServerStartedEvent event) { HyperCubeRegister.load(); ServerChannelRegister.load(); } @EventHandler public void serverStopped(FMLServerStoppedEvent event) { HyperCubeRegister.unload(); ServerChannelRegister.store(); } }
package edu.mines.jtk.dsp; import static edu.mines.jtk.util.ArrayMath.*; import edu.mines.jtk.util.Check; /** * Sampling of one variable. * <p> * Samplings are often used to represent independent variables for sampled * functions. They describe the values at which a function is sampled. For * efficiency, and to guarantee a unique mapping from sample value to * function value, we restrict samplings to be strictly increasing. In other * words, no two samples have equal value, and sample values increase with * increasing sample index. * <p> * Samplings are either uniform or non-uniform. Uniform samplings are * represented by a sample count n, a sampling interval d, and a first * sample value f. Non-uniform samplings are represented by an array of * sample values. * <p> * All sample values are computed and stored in <em>double precision</em>. * This double precision can be especially important in uniform samplings, * where the sampling interval d and first sample value f may be used to * compute values for thousands of samples, in loops like this one: * <pre><code> * int n = sampling.getCount(); * double d = sampling.getDelta(); * double f = sampling.getFirst(); * double v = f; * for (int i=0; i&lt;n; ++i,v+=d) { * // some calculation that uses the sample value v * } * </code></pre> * In each iteration of the loop above, the sample value v is computed by * accumulating the sampling interval d. This computation is fast, but it * also yields rounding error that can grow quadratically with the number * of samples n. If v were computed in single (float) precision, then this * rounding error could exceed the sampling interval d for as few as * n=10,000 samples. * <p> * If accumulating in double precision is insufficient, a more accurate * and more costly way to compute sample values is as follows: * <pre><code> * // ... * double v = f; * for (int i=0; i&lt;n; ++i,v=f+i*d) { * // some calculation that uses the sample value v * } * </code></pre> * With this computation of sample values, rounding errors can grow only * linearly with the number of samples n. * <p> * Two samplings are considered equivalent if their sample values differ * by no more than the <em>sampling tolerance</em>. This tolerance may be * specified, as a fraction of the sampling interval, when a sampling is * constructed. Alternatively, a default tolerance may be used. When * comparing two samplings, the smaller of their tolerances is used. * <p> * A sampling is immutable. New samplings can be constructed by applying * various transformations (e.g., shifting) to an existing sampling, but * an existing sampling cannot be changed. Therefore, multiple sampled * functions can safely share the same sampling. * * @author Dave Hale, Colorado School of Mines * @version 2005.03.11 */ public class Sampling { /** * A default fraction used to test for equivalent sample values. * By default, if the difference between two sample values does not * exceed this fraction of the sampling interval, then those values * are considered equivalent. This default is used when a tolerance * is not specified explicitly when a sampling is constructed. */ public static final double DEFAULT_TOLERANCE = 1.0e-6; /** * Constructs a uniform sampling with specified count. The sampling * interval (delta) is 1.0, and the first sample value is 0.0. * @param n the number (count) of samples; must be positive. */ public Sampling(int n) { this(n,1.0,0.0); } /** * Constructs a uniform sampling with specified parameters. * @param n the number (count) of samples; must be positive. * @param d the sampling interval (delta); must be positive. * @param f the first sample value. */ public Sampling(int n, double d, double f) { this(n,d,f,DEFAULT_TOLERANCE); } /** * Constructs a sampling with specified parameters. * @param n the number (count) of samples; must be positive. * @param d the sampling interval (delta); must be positive. * @param f the first sample value. * @param t the sampling tolerance, expressed as fraction of delta. */ public Sampling(int n, double d, double f, double t) { Check.argument(n>0,"n>0"); Check.argument(d>0.0,"d>0.0"); _n = n; _d = d; _di = 1.0/d; _f = f; _v = null; _t = t; _td = _t*_d; } /** * Constructs a sampling from the specified array of values. The values * must be strictly increasing. * <p> * The constructed sampling may or may not be uniform, depending on the * specified values and default sampling tolerance. If uniform (to within * the default tolerance), then the array of values is discarded, and the * sampling is represented by the count, sampling interval, and first * sample value. * @param v the array of sampling values; must have non-zero length. */ public Sampling(double[] v) { this(v,DEFAULT_TOLERANCE); } /** * Constructs a sampling from the specified array of values and tolerance. * The values must be strictly increasing. * <p> * The constructed sampling may or may not be uniform, depending on the * specified values and tolerance. If uniform (to within the specified * tolerance), then the array of values is discarded, and the sampling is * represented by the count, sampling interval, and first sample value. * @param v the array of sampling values; must have non-zero length. * @param t the sampling tolerance, expressed as fraction of delta. */ public Sampling(double[] v, double t) { Check.argument(v.length>0,"v.length>0"); Check.argument(isIncreasing(v),"v is increasing"); _n = v.length; _d = (_n<2)?1.0:(v[_n-1]-v[0])/(_n-1); _di = 1.0/_d; _f = v[0]; _t = t; _td = _t*_d; boolean uniform = true; for (int i=0; i<_n && uniform; ++i) { double vi = _f+i*_d; if (!almostEqual(v[i],vi,_td)) uniform = false; } _v = (uniform)?null: copy(v); } /** * Gets the number of samples. * @return the number of samples. */ public int getCount() { return _n; } /** * Gets the sampling interval. If not uniformly sampled, the sampling * interval is the average difference between sample values. * @return the sampling interval; 1.0, if fewer than two samples. */ public double getDelta() { return _d; } /** * Gets the first sample value. * @return the first sample value. */ public double getFirst() { return _f; } /** * Gets the last sample value. * @return the last sample value. */ public double getLast() { return (_v!=null)?_v[_n-1]:_f+(_n-1)*_d; } /** * Gets the sample value with specified index. * @param i the index. * @return the sample value. */ public double getValue(int i) { Check.index(_n,i); return value(i); } /** * Gets the sample values. If this sampling was constructed with an array * of sample values, then the returned values are equivalent (equal to * within the sampling tolerance) to the values in that array. * @return the sample values; returned by copy, not by reference. */ public double[] getValues() { double[] v; if (_v!=null) { v = copy(_v); } else { v = new double[_n]; for (int i=0; i<_n; ++i) v[i] = _f+i*_d; } return v; } /** * Determines whether this sampling is uniform. A sampling is uniform * if its values can be computed, to within the sampling tolerance, by * the expression v = f+i*d, for sampling indices i = 0, 1, ..., n-1. * Samplings with only one sample are considered to be uniform. * <p> * Note that, by this definition, samplings constructed with an array * of sample values may or may not be uniform. * @return true, if uniform; false, otherwise. */ public boolean isUniform() { return _v==null; } /** * Determines whether this sampling is equivalent to the specified sampling. * Two samplings are equivalent if each of their sample values differs by * no more than the sampling tolerance. * @param s the sampling to compare to this sampling. * @return true, if equivalent; false, otherwise. */ public boolean isEquivalentTo(Sampling s) { Sampling t = this; if (t.isUniform()!=s.isUniform()) return false; if (t.isUniform()) { if (t.getCount()!=s.getCount()) return false; double tiny = tinyWith(s); double tf = t.getFirst(); double tl = t.getLast(); double sf = s.getFirst(); double sl = s.getLast(); return almostEqual(tf,sf,tiny) && almostEqual(tl,sl,tiny); } else { double tiny = tinyWith(s); for (int i=0; i<_n; ++i) { if (!almostEqual(_v[i],s.value(i),tiny)) return false; } return true; } } /** * Determines whether this sampling is compatible with the specified sampling. * Two samplings are incompatible if their ranges of sample values overlap, * but not all values in the overlapping parts are equivalent. Otherwise, * they are compatible. * @param s the sampling to compare to this sampling. * @return true, if compatible; false, otherwise. */ public boolean isCompatible(Sampling s) { Sampling t = this; int nt = t.getCount(); int ns = s.getCount(); double tf = t.getFirst(); double sf = s.getFirst(); double tl = t.getLast(); double sl = s.getLast(); int it = 0; int is = 0; int jt = nt-1; int js = ns-1; if (tl<sf) { return true; } else if (sl<tf) { return true; } else { if (tf<sf) { it = t.indexOf(sf); } else { is = s.indexOf(tf); } if (it<0 || is<0) return false; if (tl<sl) { js = s.indexOf(tl); } else { jt = t.indexOf(sl); } if (jt<0 || js<0) return false; int mt = 1+jt-it; int ms = 1+js-is; if (mt!=ms) return false; if (!t.isUniform() || !s.isUniform()) { double tiny = tinyWith(s); for (jt=it,js=is; jt!=mt; ++jt,++js) { if (!almostEqual(t.value(jt),s.value(js),tiny)) return false; } } return true; } } /** * Returns the index of the sample with specified value. If this * sampling has a sample value that equals (to within the sampling * tolerance) the specified value, then this method returns the * index of that sample. Otherwise, this method returns -1. * @param x the value. * @return the index of the matching sample; -1, if none. */ public int indexOf(double x) { int i = -1; if (isUniform()) { int j = (int)Math.round((x-_f)/_d); if (0<=j && j<_n && almostEqual(x,_f+j*_d,_td)) i = j; } else { int j = binarySearch(_v,x); if (0<=j) { i = j; } else { j = -(j+1); if (j>0 && almostEqual(x,_v[j-1],_td)) { i = j-1; } else if (j<_n && almostEqual(x,_v[j],_td)) { i = j; } } } return i; } /** * Returns the index of the sample nearest to the specified value. * @param x the value. * @return the index of the nearest sample. */ public int indexOfNearest(double x) { int i; if (isUniform()) { i = (int)Math.round((x-_f)/_d); if (i<0) i = 0; if (i>=_n) i = _n-1; } else { i = binarySearch(_v,x); if (i<0) { i = -(i+1); if (i==_n) { i = _n-1; } else if (i>0 && Math.abs(x-_v[i-1])<Math.abs(x-_v[i])) { --i; } } } return i; } /** * Returns the value of the sample nearest to the specified value. * @param x the value. * @return the value of the nearest sample. */ public double valueOfNearest(double x) { return getValue(indexOfNearest(x)); } /** * Determines whether the specified index is in the bounds of this sampling. * An index is in bounds if in the range [0,count-1] of the first and last * sample indices. * @param i the index. * @return true, if in bounds; false, otherwise. */ public boolean isInBounds(int i) { return 0<=i && i<_n; } /** * Determines whether the specified value is in the bounds of this sampling. * A value is in bounds if in the range [first,last] defined by the first * and last sample values. * @param x the value. * @return true, if in bounds; false, otherwise. */ public boolean isInBounds(double x) { return getFirst()<=x && x<=getLast(); } /** * Determines whether the specified value is in the bounds of this sampling, * which is assumed to be uniform. A value is in bounds if in the range * [first-0.5*delta,last+0.5*delta] defined by the first and last sample * values and the sampling interval delta. In effect, this method extends * the bounds of this sampling by one-half sample when testing the value. * @param x the value. * @return true, if in bounds; false, otherwise. */ public boolean isInBoundsExtended(double x) { Check.state(isUniform(),"sampling is uniform"); double dhalf = 0.5*_d; return getFirst()-dhalf<=x && x<=getLast()+dhalf; } /** * Gets the value for the specified index, assuming uniform sampling. * The index and the returned value need not be in the bounds of this * sampling, which must be uniform. That is, the specified index may be * less than zero or greater than or equal to the number of samples. * @param i the index. * @return the value. */ public double getValueExtended(int i) { Check.state(isUniform(),"sampling is uniform"); return _f+i*_d; } /** * Returns the index of the sample nearest the specified value, assuming * uniform sampling. The value and the returned index need not be in the * bounds of this sampling, which must be uniform. Specifically, the * returned index may be less than zero or greater than or equal to the * number of samples. * @param x the value. */ public int indexOfNearestExtended(double x) { Check.state(isUniform(),"sampling is uniform"); return (int)Math.round((x-_f)/_d); } /** * Returns the index of the floor (sample before or at) of the specified value, * assuming uniform sampling. The value and the returned index need not be in * in the bounds of this sampling, which must be uniform. Specifically, the * returned index may be less than zero or greater than or equal to the * number of samples. * @param x the value. */ public int indexOfFloorExtended(double x) { Check.state(isUniform(),"sampling is uniform"); double d = x-_f; return (d<0.0)?(int)Math.round((d*_di)-0.5):(int)(d*_di); } /** * Returns the fraction of an index (0.0 to 1.0) from the floor to the specified value, * assuming uniform sampling. The value need not be in in the bounds of this sampling, which * must be uniform. * @param x the value. * @param floorIndex the index of the floor, as returned from indexOfFloorExtended(x). */ public double remainderOfFloorExtended(double x, int floorIndex) { Check.state(isUniform(),"sampling is uniform"); double c = _f+(double)floorIndex*_d; return (x-c)*_di; } /** * Returns the value of the sample nearest to the specified value, * assuming uniform sampling. The specified and returned values need * not be in the bounds of this sampling, which must be uniform. * @param x the value. * @return the value of the nearest sample. */ public double valueOfNearestExtended(double x) { return getValueExtended(indexOfNearestExtended(x)); } /** * Determines the overlap between this sampling and the specified sampling. * Both the specified sampling and this sampling represent a first-to-last * range of sample values. The overlap is a contiguous set of samples that * have values that are equal, to within the minimum sampling tolerance of * the two samplings. This set is represented by an array of three ints, * {n,it,is}, where n is the number of overlapping samples, and it and is * denote the indices of the first samples in the overlapping parts of this * sampling (t) and the specified sampling (s). There exist three cases. * <ul><li> * The ranges of sample values overlap, and all values in the overlapping * parts are equivalent. In this case, the two samplings are compatible; * and this method returns the array {n,it,is}, as described * above. * </li><li> * The ranges of sample values in the two samplings do not overlap. * In this case, the two samplings are compatible; and this method * returns either {0,nt,0} or {0,0,ns}, depending on whether all * sample values in this sampling are less than or greater than * those in the specified sampling, respectively. * </li><li> * The ranges of sample values overlap, but not all values in the * overlapping parts are equivalent. In this case, the two samplings * are incompatible; and this method returns null. * </li></ul> * @param s the sampling to compare with this sampling. * @return the array {n,it,is} that describes the overlap; null, if * the specified sampling is incompatible with this sampling. */ public int[] overlapWith(Sampling s) { Sampling t = this; int nt = t.getCount(); int ns = s.getCount(); double tf = t.getFirst(); double sf = s.getFirst(); double tl = t.getLast(); double sl = s.getLast(); int it = 0; int is = 0; int jt = nt-1; int js = ns-1; if (tl<sf) { return new int[]{0,nt,0}; } else if (sl<tf) { return new int[]{0,0,ns}; } else { if (tf<sf) { it = t.indexOf(sf); } else { is = s.indexOf(tf); } if (it<0 || is<0) return null; if (tl<sl) { js = s.indexOf(tl); } else { jt = t.indexOf(sl); } if (jt<0 || js<0) return null; int mt = 1+jt-it; int ms = 1+js-is; if (mt!=ms) return null; if (!t.isUniform() || !s.isUniform()) { double tiny = tinyWith(s); for (jt=it,js=is; jt!=mt; ++jt,++js) { if (!almostEqual(t.value(jt),s.value(js),tiny)) return null; } } return new int[]{mt,it,is}; } } /** * Returns the union of this sampling with the specified sampling. This * union is possible if and only if the two samplings are compatible. * <p> * If the two samplings do not overlap, this method does not create * samples within any gap that may exist between them. In other words, * the number of samples in the sampling returned is exactly nt+ns-n, * where nt is the number of samples in this sampling, ns is the number * of samples in the specified sampling, and n is the number of samples * with equivalent values in any overlapping parts of the two samplings. * If the samplings do not overlap, then n = 0. One consequence of this * behavior is that the union of two uniform samplings with the same * sampling interval may be non-uniform. * <p> * This method returns a new sampling; it does not modify this sampling. * @see #overlapWith(Sampling) * @param s the sampling to merge with this sampling. * @return the merged sampling; null, if no merge is possible. */ public Sampling mergeWith(Sampling s) { Sampling t = this; int[] overlap = t.overlapWith(s); if (overlap==null) return null; int n = overlap[0]; int it = overlap[1]; int is = overlap[2]; int nt = t.getCount(); int ns = s.getCount(); int nm = nt+ns-n; if (n>0 && t.isUniform() && s.isUniform()) { double dm = t.getDelta(); double fm = (it==0)?s.getFirst():t.getFirst(); return new Sampling(nm,dm,fm); } else { double[] vm = new double[nm]; int jm = 0; for (int jt=0; jt<it; ++jt) vm[jm++] = t.value(jt); for (int js=0; js<is; ++js) vm[jm++] = s.value(js); for (int jt=it; jt<it+n; ++jt) vm[jm++] = t.value(jt); for (int jt=it+n; jt<nt; ++jt) vm[jm++] = t.value(jt); for (int js=is+n; js<ns; ++js) vm[jm++] = s.value(js); return new Sampling(vm); } } /** * Shifts this sampling. * <p> * This method returns a new sampling; it does not modify this sampling. * @param s the value (shift) to add to this sampling's values. * @return the new sampling. */ public Sampling shift(double s) { if (_v==null) { return new Sampling(_n,_d,_f+s,_t); } else { double[] v = new double[_n]; for (int i=0; i<_n; ++i) v[i] = _v[i]+s; return new Sampling(v,_t); } } /** * Prepends samples to this sampling. * If this sampling is not uniform, prepended sample values are computed * to preserve the average difference between adjacent sample values. * <p> * This method returns a new sampling; it does not modify this sampling. * @param m the number of new samples prepended to this sampling. * @return the new sampling. */ public Sampling prepend(int m) { int n = _n+m; double f = _f-m*_d; if (_v==null) { return new Sampling(n,_d,f,_t); } else { double[] v = new double[n]; for (int i=0; i<m; ++i) v[i] = f+i*_d; for (int i=m; i<n; ++i) v[i] = _v[i-m]; return new Sampling(v,_t); } } /** * Appends samples to this sampling. * If this sampling is not uniform, appended sample values are computed * to preserve the average difference between adjacent sample values. * <p> * This method returns a new sampling; it does not modify this sampling. * @param m the number of new samples appended to this sampling. * @return the new sampling. */ public Sampling append(int m) { int n = _n+m; if (_v==null) { return new Sampling(n,_d,_f,_t); } else { double[] v = new double[n]; for (int i=0; i<_n; ++i) v[i] = _v[i]; for (int i=_n; i<n; ++i) v[i] = _f+i*_d; return new Sampling(v,_t); } } /** * Decimates this sampling. Beginning with the first sample, keeps only * every m'th sample, while discarding the others in this sampling. If * this sampling has n values, the new sampling will have 1+(n-1)/m values. * <p> * This method returns a new sampling; it does not modify this sampling. * @param m the factor by which to decimate; must be positive. * @return the new sampling. */ public Sampling decimate(int m) { Check.argument(m>0,"m>0"); int n = 1+(_n-1)/m; if (_v==null) { return new Sampling(n,m*_d,_f,_t); } else { double[] v = new double[n]; for (int i=0,j=0; i<n; ++i,j+=m) v[i] = _v[j]; return new Sampling(v,_t); } } /** * Interpolates this sampling. Inserts m-1 evenly spaced samples between * each of the samples in this sampling. If this sampling has n values, * the new sampling will have 1+(n-1)*m values. * <p> * This method returns a new sampling; it does not modify this sampling. * @param m the factor by which to interpolate. * @return the new sampling. */ public Sampling interpolate(int m) { Check.argument(m>0,"m>0"); int n = _n+(_n-1)*(m-1); if (_v==null) { return new Sampling(n,_d/m,_f,_t); } else { double[] v = new double[n]; v[0] = _v[0]; for (int i=1,j=m; i<_n; ++i,j+=m) { v[j] = _v[i]; double dk = (v[j]-v[j-m])/m; double vk = v[j-m]; for (int k=j-m+1; k<j; ++k,vk+=dk) v[k] = vk; } return new Sampling(v,_t); } } // private private int _n; // number of samples private double _d; // sampling interval private double _di; // inverse of sampling interval (1/_d). Cached to minimize float divides. private double _f; // value of first sample private double[] _v; // array[n] of sample values; null, if uniform private double _t; // sampling tolerance, as a fraction of _d private double _td; // sampling tolerance _t multiplied by _d private double value(int i) { return (_v!=null)?_v[i]:_f+i*_d; } private boolean almostEqual(double v1, double v2, double tiny) { double diff = v1-v2; return (diff<0.0)?-diff<tiny:diff<tiny; } private double tinyWith(Sampling s) { return (_td<s._td)?_td:s._td; } }
package gl8080.qiitabk.domain; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown=true) public class Item { private final String id; private final String title; private final String text; public Item( @JsonProperty("id") String id, @JsonProperty("title") String title, @JsonProperty("body") String text) { Objects.requireNonNull(id); Objects.requireNonNull(title); this.id = id; this.title = title; this.text = text; } public String getId() { return id; } public String getTitle() { return title; } public String getText() { return text; } @Override public String toString() { return "Item [id=" + id + ", title=" + title + ", text=<...>]"; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Item)) return false; Item other = (Item)o; return this.id.equals(other.id); } @Override public int hashCode() { return this.id.hashCode(); } private static final Pattern IMAGE_PATTERN = Pattern.compile("!\\[[^]]*]\\(([^) ]+)\\)"); public List<Image> getImageList() { Matcher matcher = IMAGE_PATTERN.matcher(this.text); List<Image> list = new ArrayList<>(); while (matcher.find()) { String url = matcher.group(1); list.add(new Image(url)); } return list; } }
package io.measures.passage; import com.google.common.base.Joiner; import io.measures.passage.geometry.Model3D; import io.measures.passage.geometry.Point2D; import io.measures.passage.geometry.Projectable2D; import io.measures.passage.geometry.Projectable3D; import io.measures.passage.geometry.SphericalPoint; import io.measures.passage.geometry.Triangle3D; import processing.core.PApplet; import processing.core.PGraphics; import processing.core.PImage; import processing.event.KeyEvent; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Sketch * @author Dietrich Featherston */ public class Sketch extends PApplet { protected final long startedAt = System.currentTimeMillis()/1000L; protected final String homeDir; protected final String baseDataDir; protected static final Joiner pathJoiner = Joiner.on(File.separatorChar); public final int slate = color(50); public final int gray = color(180); public final int yellow = color(255, 255, 1); public final int pink = color(255, 46, 112); public final int teal = color(85, 195, 194); public final int nak = color(0, 170, 255); public final int blue = color(49, 130, 189); public final int darkblue = color(49, 130, 189); public final int lightblue = color(222, 235, 247); public final int redorange = color(240, 59, 32); private PGraphics paperGraphics; protected boolean recordPdf = false; protected long pdfTime = 0L; private boolean saveAnimation = false; private int numAnimationFrames = 100; public Sketch() { String homeDir = getParameter("PASSAGE_HOME"); String userDir = System.getProperty("user.dir"); if(homeDir == null) { homeDir = userDir; } this.homeDir = homeDir; baseDataDir = getParameter("PASSAGE_DATA") == null ? homeDir : getParameter("PASSAGE_DATA"); // ensure the snapshot directory exists new File(getSnapshotDir()).mkdirs(); // ensure the data dir exists new File(getDataDir()).mkdirs(); } public void initSize(String type) { size(getTargetWidth(), getTargetHeight(), type); } public int getTargetWidth() { return 1280; } public int getTargetHeight() { return 720; } public float getAspectRatio() { return (float)getTargetWidth() / (float)getTargetHeight(); } public void saveAnimation() { this.saveAnimation = true; } public void animationFrames(int n) { numAnimationFrames = n; } @Override public final void draw() { beforeFrame(); try { renderFrame(); } catch(Exception e) { println(e.getMessage()); } finally { afterFrame(); } } public void beforeFrame() { if(recordPdf) { beginRaw(PDF, getSnapshotPath("vector-" + pdfTime + ".pdf")); } } public void renderFrame() { println("ERROR - sketch renderFrame() not implemented"); noLoop(); } public void afterFrame() { if(recordPdf) { endRaw(); recordPdf = false; } if(saveAnimation) { saveFrame(getSnapshotPath("frames-" + startedAt + "/frame- if(frameCount >= numAnimationFrames) { exit(); } } } public int darker(int c) { return color(round(red(c)*0.6f), round(green(c)*0.6f), round(blue(c)*0.6f)); } public int lighter(int c) { return color( constrain(round(red(c)*1.1f), 0, 255), constrain(round(green(c)*1.1f), 0, 255), constrain(round(blue(c)*1.1f), 0, 255)); } public void point(Projectable2D p) { point(p.x(), p.y()); } public void points(Iterable<? extends Projectable2D> points) { for(Projectable2D p : points) { point(p); } } public void point(Projectable3D p) { point(p.x(), p.y(), p.z()); } public void vertex(Projectable3D p) { vertex(p.x(), p.y(), p.z()); } public void vertex(Projectable2D p) { vertex(p.x(), p.y()); } public void line(Projectable3D a, Projectable3D b) { line(a.x(), a.y(), a.z(), b.x(), b.y(), b.z()); } public void line(Projectable2D a, Projectable2D b) { line(a.x(), a.y(), b.x(), b.y()); } public void renderModel(Model3D model) { beginShape(TRIANGLES); for(Triangle3D t : model.getTriangles()) { vertex(t.a()); vertex(t.b()); vertex(t.c()); } endShape(); } public void triangle(Triangle3D t) { beginShape(TRIANGLE); vertex(t.a()); vertex(t.b()); vertex(t.c()); endShape(); } public void translate(Projectable2D p) { translate(p.x(), p.y()); } public void translate(Projectable3D p) { translate(p.x(), p.y(), p.z()); } public void translateNormal(SphericalPoint p) { rotateZ(p.phi()); rotateY(p.theta()); translate(0, 0, p.r()); } public static float dist(Projectable2D a, Projectable2D b) { return dist(a.x(), a.y(), b.x(), b.y()); } public static float dist(Projectable3D a, Projectable3D b) { return dist(a.x(), a.y(), a.z(), b.x(), b.y(), b.z()); } public float noiseZ(float noiseScale, float x, float y, float z) { return noise(noiseScale*(x+10000), noiseScale*(y+10000), noiseScale*(z+10000)); } @Override public void keyPressed(KeyEvent e) { super.keyPressed(); if(key == ' ') { // snapshot raster graphics + code snapshot(); } else if(key == 'p') { // snapshot a pdf + code recordPdf = true; pdfTime = now(); snapshotCode(pdfTime); } } public long now() { return System.currentTimeMillis()/1000; } public void snapshot() { long time = now(); snapshotCode(time); snapshotFrame(time); } public void snapshotCode() { snapshotCode(now()); } public void snapshotCode(long time) { println("taking code snapshot"); copyFile(getSketchSourceFile(), getSnapshotPath("code-" + time + ".java")); } public void snapshotFrame() { snapshotFrame(now()); } public void snapshotFrame(long time) { println("taking raster snapshot"); saveFrame(getSnapshotPath("raster-" + time + ".jpg")); } // todo - compatibility public void copyFile(String from, String to) { try { String command = "cp " + from + " " + to; Process p = Runtime.getRuntime().exec(command); copy(p.getInputStream(), System.out); copy(p.getErrorStream(), System.err); } catch(Exception ignored) { println(ignored.getMessage()); ignored.printStackTrace(); } } public void copy(InputStream in, OutputStream out) throws IOException { while (true) { int c = in.read(); if (c == -1) break; out.write((char)c); } } public String getSketchSourceFile() { return pathJoiner.join(getSketchSourcePath(), getSketchPathComponent() + ".java"); } private String getSketchSourcePath() { return pathJoiner.join(homeDir, "src/main/java"); } public String getSketchPathComponent() { return this.getClass().getName().replace('.', File.separatorChar); } /** * @return the directory to which progress artifacts should be saved */ public String getSnapshotDir() { return pathJoiner.join(baseDataDir, getSketchPathComponent(), "snapshots"); } public String getSnapshotPath(String name) { return pathJoiner.join(getSnapshotDir(), name); } public String getDataDir() { return pathJoiner.join(baseDataDir, getSketchPathComponent(), "data"); } public String getDataPath(String name) { return pathJoiner.join(getDataDir(), name); } public String getHomeDir() { return homeDir; } public String getHomePath(String name) { return pathJoiner.join(getHomeDir(), name); } public static void fit(PImage img, int maxWidth, int maxHeight) { // oblig image resizing to fit in our space float imgratio = (float)img.width / (float)img.height; if(img.width > img.height) { img.resize(round(imgratio * maxHeight), maxHeight); } else { img.resize(maxWidth, round(maxWidth/imgratio)); } } @Override public File dataFile(String where) { File why = new File(where); if (why.isAbsolute()) return why; File sketchSpecificFile = new File(getDataPath(where)); if(sketchSpecificFile.exists()) { return sketchSpecificFile; } else { File f = new File(pathJoiner.join(baseDataDir, "data", where)); if(f.exists()) { return f; } } return why; } @Override public String getParameter(String name) { return System.getenv(name); } public void printenv() { System.out.println("sketch name: " + this.getClass().getName()); System.out.println("PASSAGE_HOME=" + homeDir); System.out.println("PASSAGE_DATA=" + baseDataDir); System.out.println("sketch-specific path = " + getSketchPathComponent()); System.out.println("sketch source = " + getSketchSourcePath()); System.out.println("sketch source file = " + getSketchSourceFile()); System.out.println("snapshot dir = " + getSnapshotDir()); } public void oldPaperBackground() { if(paperGraphics == null) { int center = color(252, 243, 211); int edge = color(245, 222, 191); PGraphics g = createGraphics(10, 10); g.beginDraw(); g.noStroke(); g.background(edge); g.fill(center); g.ellipse(g.width/2, g.height/2, g.width*0.8f, g.height*0.8f); g.filter(BLUR, 2); g.endDraw(); /* g.filter(BLUR, width/30); g.filter(BLUR, width/30); g.filter(BLUR, width/30); */ paperGraphics = g; } } }
package ml.duncte123.skybot; import ch.qos.logback.classic.Logger; import com.sedmelluq.discord.lavaplayer.jdaudp.NativeAudioSendFactory; import ml.duncte123.skybot.utils.AirUtils; import ml.duncte123.skybot.utils.GuildSettingsUtils; import ml.duncte123.skybot.utils.HelpEmbeds; import ml.duncte123.skybot.utils.Settings; import net.dv8tion.jda.bot.sharding.DefaultShardManagerBuilder; import org.apache.commons.lang3.time.DateUtils; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; /** * NOTE TO SELF String.format("%#s", userObject) */ public class SkyBot { /** * This is our main method * @param args The args passed in while running the bot * @throws Exception When you mess something up * @deprecated Because I can lol */ @Deprecated public static void main(String... args) throws Exception { //Set the logger to only info by default Logger l = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); l.setLevel(ch.qos.logback.classic.Level.INFO); //Set the value for other classes to use boolean useDatabase = AirUtils.nonsqlite; if(useDatabase) { //Don't try to connect if we don't want to if (!AirUtils.db.connManager.hasSettings()) { AirUtils.log(Settings.defaultName + "Main", Level.ERROR, "Can't load database settings. ABORTING!!!!!"); System.exit(-2); return; } if (!AirUtils.db.isConnected()) { AirUtils.log(Settings.defaultName + "Main", Level.ERROR, "Can't connect to database. ABORTING!!!!!"); System.exit(-3); return; } } else { int startIn = 5; AirUtils.logger.warn("Using SQLite as the database"); AirUtils.logger.warn("Please note that is is not recommended and can break some features."); AirUtils.logger.warn("Please report bugs on GitHub (https://github.com/duncte123/SkyBot/issues)"); Thread.sleep(DateUtils.MILLIS_PER_SECOND * startIn); } //Load the settings before loading the bot GuildSettingsUtils.loadAllSettings(); //Load the tags AirUtils.loadAllTags(); //Set the token to a string String token = AirUtils.config.getString("discord.token", "Your Bot Token"); //But this time we are going to shard it int TOTAL_SHARDS = AirUtils.config.getInt("discord.totalShards", 1); //Set up sharding for the bot new DefaultShardManagerBuilder() .addEventListeners(new BotListener()) //event.getJDA().getRegisteredListeners().get(0) .setAudioSendFactory(new NativeAudioSendFactory()) .setShardsTotal(TOTAL_SHARDS) //.setGameProvider(shardId -> Game.of(Settings.prefix + "help | Shard #" + (shardId + 1))) .setToken(token) .buildAsync(); //Load all the commands for the help embed last HelpEmbeds.init(); } }
package mods.ocminecart; import mods.ocminecart.common.CommonProxy; import mods.ocminecart.common.items.ModItems; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraftforge.common.config.Configuration; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; @Mod(modid = OCMinecart.MODID, name=OCMinecart.NAME, version=OCMinecart.VERSION, dependencies = "required-after:OpenComputers@[1.5.14,); after:Waile@[1.5.8a,)") public class OCMinecart { public static final String MODID = "ocminecart"; public static final String VERSION = "0.4-alpha"; public static final String NAME = "OC-Minecarts"; @Instance(OCMinecart.MODID) public static OCMinecart instance; public static Logger logger = LogManager.getLogger(OCMinecart.NAME); @SidedProxy(serverSide="mods.ocminecart.common.CommonProxy", clientSide="mods.ocminecart.client.ClientProxy") public static CommonProxy proxy; public static Configuration config; public static CreativeTabs itemGroup = new CreativeTabs(OCMinecart.MODID+".modtab"){ @Override public Item getTabIconItem() { return ModItems.item_ComputerCartCase; } }; //public static CreativeTabs itemGroup = li.cil.oc.api.CreativeTab.instance; @EventHandler public void preInit(FMLPreInitializationEvent event){ config = new Configuration(event.getSuggestedConfigurationFile()); Settings.init(); proxy.preInit(); } @EventHandler public void Init(FMLInitializationEvent event){ logModApis(); proxy.init(); } @EventHandler public void postInit(FMLPostInitializationEvent event){ proxy.postInit(); } private void logModApis(){ if(Loader.isModLoaded("appliedenergistics2")) OCMinecart.logger.info("Found Mod: AE2"); if(Loader.isModLoaded("NotEnoughItems")) OCMinecart.logger.info("Found Mod: NEI"); if(Loader.isModLoaded("Waila")) OCMinecart.logger.info("Found Mod: WAILA"); if(Loader.isModLoaded("Railcraft")) OCMinecart.logger.info("Found Mod: Railcraft"); } }
package net.apnic.rdapd.autnum; import java.io.Serializable; public class ASN implements Comparable<ASN>, Serializable { public static final long MAX_ASN = 0xFFFFFFFFL; public static final long MIN_ASN = 0x1L; private final long asn; public ASN(long asn) { if(asn < MIN_ASN || asn > MAX_ASN) { throw new IllegalArgumentException( String.format("invalid ASN value must be in the range %d - %d", MIN_ASN, MAX_ASN)); } this.asn = asn; } @Override public int compareTo(ASN o) { if(getASN() == o.getASN()) { return 0; } return getASN() < o.getASN() ? -1 : 1; } @Override public boolean equals(Object other) { return other != null && other instanceof ASN && getASN() == ((ASN)other).getASN(); } public long getASN() { return asn; } @Override public int hashCode() { return Long.valueOf(getASN()).hashCode(); } public static ASN valueOf(long asn) { return new ASN(asn); } }
package net.trustyuri.rdf; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URISyntaxException; import java.util.Map; import java.util.zip.GZIPOutputStream; import net.trustyuri.TrustyUriException; import net.trustyuri.TrustyUriResource; import net.trustyuri.TrustyUriUtils; import org.openrdf.OpenRDFException; import org.openrdf.model.BNode; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.impl.URIImpl; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandler; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParser; import org.openrdf.rio.RDFWriter; import org.openrdf.rio.Rio; import org.openrdf.rio.helpers.RDFaParserSettings; public class RdfUtils { public static final char bnodeChar = '_'; public static final char preAcChar = '.'; public static final char postAcChar = ' public static final char postAcFallbackChar = '.'; private RdfUtils() {} // no instances allowed public static String getTrustyUriString(URI baseUri, String artifactCode, String suffix) { String s = expandBaseUri(baseUri) + artifactCode; if (suffix != null) { suffix = suffix.replace(" if (suffix.startsWith(bnodeChar + "")) { // Duplicate bnode character for escaping: s += getPostAcChar(baseUri) + bnodeChar + suffix; } else { s += getPostAcChar(baseUri) + suffix; } } return s; } public static String getTrustyUriString(URI baseUri, String artifactCode) { return getTrustyUriString(baseUri, artifactCode, null); } public static URI getTrustyUri(URI baseUri, String artifactCode, String suffix) { if (baseUri == null) return null; return new URIImpl(getTrustyUriString(baseUri, artifactCode, suffix)); } public static URI getTrustyUri(URI baseUri, String artifactCode) { if (baseUri == null) return null; return new URIImpl(getTrustyUriString(baseUri, artifactCode, null)); } public static URI getPreUri(Resource resource, URI baseUri, Map<String,Integer> bnodeMap, boolean frozen) { if (resource == null) { throw new RuntimeException("Resource is null"); } else if (resource instanceof URI) { URI plainUri = (URI) resource; checkUri(plainUri); // TODO Add option to disable suffixes appended to trusty URIs String suffix = getSuffix(plainUri, baseUri); if (suffix == null && !plainUri.equals(baseUri)) { return plainUri; } else if (frozen) { return null; } else if (TrustyUriUtils.isPotentialTrustyUri(plainUri)) { return plainUri; } else { return getTrustyUri(baseUri, " ", suffix); } } else { if (frozen) { return null; } else { return getSkolemizedUri((BNode) resource, baseUri, bnodeMap); } } } public static void checkUri(URI uri) { try { // Raise error if not well-formed new java.net.URI(uri.stringValue()); } catch (URISyntaxException ex) { throw new RuntimeException("Malformed URI: " + uri.stringValue(), ex); } } public static char getPostAcChar(URI baseUri) { if (baseUri.stringValue().contains(" return postAcFallbackChar; } return postAcChar; } private static URI getSkolemizedUri(BNode bnode, URI baseUri, Map<String,Integer> bnodeMap) { int n = getBlankNodeNumber(bnode, bnodeMap); return new URIImpl(expandBaseUri(baseUri) + " " + getPostAcChar(baseUri) + bnodeChar + n); } private static String getSuffix(URI plainUri, URI baseUri) { if (baseUri == null) return null; String b = baseUri.toString(); String p = plainUri.toString(); if (p.equals(b)) { return null; } else if (p.startsWith(b)) { return p.substring(b.length()); } else { return null; } } public static String normalize(URI uri, String artifactCode) { String s = uri.toString(); if (s.indexOf('\n') > -1 || s.indexOf('\t') > -1) { throw new RuntimeException("Newline or tab character in URI: " + s); } if (artifactCode == null) return s; return s.replace(artifactCode, " "); } private static int getBlankNodeNumber(BNode blankNode, Map<String,Integer> bnodeMap) { String id = blankNode.getID(); Integer n = bnodeMap.get(id); if (n == null) { n = bnodeMap.size()+1; bnodeMap.put(id, n); } return n; } private static String expandBaseUri(URI baseUri) { String s = baseUri.toString(); if (s.matches(".*[A-Za-z0-9\\-_]")) { s += preAcChar; } return s; } public static RdfFileContent load(InputStream in, RDFFormat format) throws IOException, TrustyUriException { RDFParser p = getParser(format); RdfFileContent content = new RdfFileContent(format); p.setRDFHandler(content); try { p.parse(in, ""); } catch (OpenRDFException ex) { throw new TrustyUriException(ex); } in.close(); return content; } public static RDFParser getParser(RDFFormat format) { RDFParser p = Rio.createParser(format); p.getParserConfig().set(RDFaParserSettings.FAIL_ON_RDFA_UNDEFINED_PREFIXES, true); return p; } public static RdfFileContent load(TrustyUriResource r) throws IOException, TrustyUriException { return load(r.getInputStream(), r.getFormat(RDFFormat.TURTLE)); } public static void fixTrustyRdf(File file) throws IOException, TrustyUriException { TrustyUriResource r = new TrustyUriResource(file); RdfFileContent content = RdfUtils.load(r); String oldArtifactCode = r.getArtifactCode(); content = RdfPreprocessor.run(content, oldArtifactCode); String newArtifactCode = createArtifactCode(content, oldArtifactCode.startsWith("RB")); content = processNamespaces(content, oldArtifactCode, newArtifactCode); OutputStream out; String filename = r.getFilename().replace(oldArtifactCode, newArtifactCode); if (filename.matches(".*\\.(gz|gzip)")) { out = new GZIPOutputStream(new FileOutputStream(new File("fixed." + filename))); } else { out = new FileOutputStream(new File("fixed." + filename)); } RDFWriter writer = Rio.createWriter(r.getFormat(RDFFormat.TRIG), out); TransformRdf.transformPreprocessed(content, null, writer); } public static void fixTrustyRdf(RdfFileContent content, String oldArtifactCode, RDFHandler writer) throws TrustyUriException { content = RdfPreprocessor.run(content, oldArtifactCode); String newArtifactCode = createArtifactCode(content, oldArtifactCode.startsWith("RB")); content = processNamespaces(content, oldArtifactCode, newArtifactCode); TransformRdf.transformPreprocessed(content, null, writer); } private static String createArtifactCode(RdfFileContent preprocessedContent, boolean graphModule) throws TrustyUriException { if (graphModule) { return RdfHasher.makeGraphArtifactCode(preprocessedContent.getStatements()); } else { return RdfHasher.makeArtifactCode(preprocessedContent.getStatements()); } } private static RdfFileContent processNamespaces(RdfFileContent content, String oldArtifactCode, String newArtifactCode) { try { RdfFileContent contentOut = new RdfFileContent(content.getOriginalFormat()); content.propagate(new NamespaceProcessor(oldArtifactCode, newArtifactCode, contentOut)); return contentOut; } catch (RDFHandlerException ex) { ex.printStackTrace(); } return content; } private static class NamespaceProcessor implements RDFHandler { private RDFHandler handler; private String oldArtifactCode, newArtifactCode; public NamespaceProcessor(String oldArtifactCode, String newArtifactCode, RDFHandler handler) { this.handler = handler; this.oldArtifactCode = oldArtifactCode; this.newArtifactCode = newArtifactCode; } @Override public void startRDF() throws RDFHandlerException { handler.startRDF(); } @Override public void endRDF() throws RDFHandlerException { handler.endRDF(); } @Override public void handleNamespace(String prefix, String uri) throws RDFHandlerException { handler.handleNamespace(prefix, uri.replace(oldArtifactCode, newArtifactCode)); } @Override public void handleStatement(Statement st) throws RDFHandlerException { handler.handleStatement(st); } @Override public void handleComment(String comment) throws RDFHandlerException { handler.handleComment(comment); } } }
package org.btc4j.client; import java.io.File; import java.math.BigDecimal; import java.util.List; import java.util.Map; import org.btc4j.core.BtcAccount; import org.btc4j.core.BtcAddedNode; import org.btc4j.core.BtcAddress; import org.btc4j.core.BtcApi; import org.btc4j.core.BtcBlock; import org.btc4j.core.BtcException; import org.btc4j.core.BtcLastBlock; import org.btc4j.core.BtcMiningInfo; import org.btc4j.core.BtcMultiSignatureAddress; import org.btc4j.core.BtcNode; import org.btc4j.core.BtcPeer; import org.btc4j.core.BtcInfo; import org.btc4j.core.BtcRawTransaction; import org.btc4j.core.BtcTransaction; import org.btc4j.core.BtcTransactionOutputSet; public class BtcClient implements BtcApi { @Override public String addMultiSignatureAddress(long required, List<String> keys, String account) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void addNode(String node, BtcNode.Operation operation) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void backupWallet(File destination) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcMultiSignatureAddress createMultiSignatureAddress(long required, List<String> keys) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String createRawTransaction(List<Object> transactionIds, List<Object> addresses) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcRawTransaction decodeRawTransaction(String hex) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String dumpPrivateKey(String address) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String getAccount(String address) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String getAccountAddress(String account) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<BtcAddedNode> getAddedNodeInformation(boolean dns, String node) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<String> getAddressesByAccount(String account) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BigDecimal getBalance(String account, long minConfirms) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcBlock getBlock(String hash) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public long getBlockCount() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String getBlockHash(long index) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String getBlockTemplate(String params) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public long getConnectionCount() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BigDecimal getDifficulty() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public boolean getGenerate() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public long getHashesPerSecond() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcInfo getInformation() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcMiningInfo getMiningInformation() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String getNewAddress(String account) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<BtcPeer> getPeerInformation() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<String> getRawMemoryPool() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcRawTransaction getRawTransaction(String transactionId, boolean verbose) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BigDecimal getReceivedByAccount(String account, long minConfirms) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BigDecimal getReceivedByAddress(String address, long minConfirms) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcTransaction getTransaction(String transactionId) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String getTransactionOutput(String transactionId, long index, boolean includeMemoryPool) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcTransactionOutputSet getTransactionOutputSetInformation() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String getWork(String data) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } public String help() throws BtcException { return help(""); } public String help(String command) throws BtcException { return "Bitcoin Client not yet implemented"; } @Override public String importPrivateKey(String privateKey, String label, boolean rescan) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void keyPoolRefill() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public Map<String, BtcAccount> listAccounts(long minConfirms) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<BtcAddress> listAddressGroupings() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<String> listLockUnspent() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<BtcAccount> listReceivedByAccount(long minConfirms, boolean includeEmpty) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<BtcAddress> listReceivedByAddress(long minConfirms, boolean includeEmpty) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcLastBlock listSinceBlock(String blockHash, long targetConfirms) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<BtcTransaction> listTransactions(String account, long count, long from) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<String> listUnspent(long minConfirms, long maxConfirms) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void lockUnspent(boolean unlock, List<Object> outputs) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public boolean move(String account, String toAccount, BigDecimal amount, long minConfirms, String comment) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String sendFrom(String account, String address, BigDecimal amount, long minConfirms, String comment, String commentTo) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String sendMany(String account, Map<String, BigDecimal> amounts, long minConfirms, String comment) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void sendRawTransaction(String transactionId) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String sendToAddress(String address, BigDecimal amount, String comment, String commentTo) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void setAccount(String address, String account) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void setGenerate(boolean generate, long generateProcessorsLimit) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public boolean setTransactionFee(BigDecimal amount) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String signMessage(String address, String message) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void signRawTransaction(String transactionId, List<Object> signatures, List<String> keys) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } public String stop() throws BtcException { return "Stopping Bitcoin Client"; } @Override public void submitBlock(String data, List<Object> params) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcAddress validateAddress(String address) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public boolean verifyMessage(String address, String signature, String message) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void walletLock() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void walletPassphrase(String passphrase, long timeout) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void walletPassphraseChange(String passphrase, String newPassphrase) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } }
package org.htwkvisu.gui; import javafx.geometry.BoundingBox; import javafx.geometry.Point2D; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.CheckBox; import javafx.scene.image.PixelWriter; import javafx.scene.paint.Color; import org.htwkvisu.gui.interpolate.InterpolateConfig; import org.htwkvisu.org.IMapDrawable; import org.htwkvisu.org.pois.NormalizedColorCalculator; import org.htwkvisu.org.pois.ScoringCalculator; import org.htwkvisu.utils.MathUtils; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * Canvas for map. */ public class MapCanvas extends BasicCanvas { private Point2D mapCenter = new Point2D(50.832222, 12.92416666); //Chemnitz private GraphicsContext gc = getGraphicsContext2D(); private double widthDistance = 0; private double heightDistance = 0; private CheckBox colorModeCheckBox; private Grid grid = new Grid(this); public static final Point2D CITY_LEIPZIG = new Point2D(51.340333, 12.37475); /** * Construct and init canvas */ public MapCanvas(ScoringConfig config) { super(config); // add test cities addDrawableElement(new City(CITY_LEIPZIG, "Leipzig", 0)); addDrawableElement(new City(new Point2D(51.049259, 13.73836112), "Dresden", 0)); addDrawableElement(new City(new Point2D(50.832222, 12.92416666), "Chemnitz", 0)); addDrawableElement(new City(new Point2D(50.718888, 12.492222), "Zwickau", 0)); } @Override protected void drawInfo() { gc.setFill(Color.GRAY); gc.fillText("Center: " + MathUtils.roundToDecimalsAsString(mapCenter.getX(), 5) + " " + MathUtils.roundToDecimalsAsString(mapCenter.getY(), 5), 10, 20); gc.fillText("Distance: " + MathUtils.roundToDecimalsAsString(widthDistance, 3) + " km x " + MathUtils.roundToDecimalsAsString(heightDistance, 3) + " km", 10, 40); gc.fillText("Scale: " + MathUtils.roundToDecimalsAsString(scale, 2), 10, 60); gc.fillText("Bounds: " + getCoordsBoundsAsString(), 10, 80); } @Override public void drawScoringValues() { // get sample points for canvas List<Point2D> gridPoints = calculateGrid(); Color[] cols = new Color[gridPoints.size()]; boolean useNorm = colorModeCheckBox != null && colorModeCheckBox.isSelected(); NormalizedColorCalculator norm = new NormalizedColorCalculator(this, useNorm); final int pixelDensity = config.getSamplingPixelDensity(); final int xSize = grid.getxSize(); final int ySize = grid.getySize(); // calculate values IntStream.range(0, ySize).parallel().forEach(y -> { IntStream.range(0, xSize).forEach(x -> { final int index = y * xSize + x; Point2D pt = gridPoints.get(index); cols[index] = norm.calculateColor(pt); }); }); Color[][] screen = new Color[pixelDensity * xSize][pixelDensity * ySize]; IntStream.range(0, (ySize - 1)).parallel().forEach(y -> { IntStream.range(0, (xSize - 1)).forEach(x -> { for (int xStep = 0; xStep < pixelDensity; xStep++) { for (int yStep = 0; yStep < pixelDensity; yStep++) { float xNorm = (float) xStep / pixelDensity; float yNorm = (float) yStep / pixelDensity; screen[x * pixelDensity + xStep][y * pixelDensity + yStep] = config.getInterpolationMode().interpolateColor( new InterpolateConfig(cols, xSize, cols.length / xSize, x, y, xNorm, 1 - yNorm)); } } }); }); // draw linear interpolated values /*PixelWriter pxWriter = gc.getPixelWriter(); for (int y = 0; y < ySize - 1; y++) { for (int x = 0; x < xSize - 1; x++) { Point2D pt = gridPoints.get(y * xSize + x); Point2D pixelPos = transferCoordinateToPixel(pt); for (int xStep = 0; xStep < pixelDensity; xStep++) { for (int yStep = 0; yStep < pixelDensity; yStep++) { float xNorm = (float) xStep / pixelDensity; float yNorm = (float) yStep / pixelDensity; final Color lerpedCol = config.getInterpolationMode().interpolateColor( new InterpolateConfig(cols, xSize, cols.length / xSize, x, y, xNorm, yNorm)); pxWriter.setColor((int) pixelPos.getX() + xStep, (int) pixelPos.getY() + yStep, lerpedCol); } } } }*/ PixelWriter pxWriter = gc.getPixelWriter(); for (int x = 0; x < (xSize - 1) * pixelDensity; x++) { for (int y = 0; y < (ySize - 1) * pixelDensity; y++) { pxWriter.setColor(x, (ySize - 1) * pixelDensity - y, screen[x][y]); } } } @Override public void drawGrid() { double northPos; double eastPos; gc.setStroke(Color.BLACK); // Latitude double x = coordsBounds.getMinX(); while (x < coordsBounds.getMaxX()) { double fullVal = Math.ceil(x); northPos = transferCoordinateToPixel(new Point2D(fullVal, Math.ceil(x))).getY(); gc.strokeLine(0, northPos, tmpWidth, northPos); gc.fillText(MathUtils.roundToDecimalsAsString(fullVal, 0), 10, northPos - 10); x++; } // Longitude double y = coordsBounds.getMinY(); while (y < coordsBounds.getMaxY()) { double fullVal = Math.ceil(y); eastPos = transferCoordinateToPixel(new Point2D(Math.ceil(y), fullVal)).getX(); gc.strokeLine(eastPos, 0, eastPos, tmpHeight); gc.fillText(MathUtils.roundToDecimalsAsString(fullVal, 0), eastPos + 10, tmpHeight - 10); y++; } } @Override public void addDrawableElement(IMapDrawable elem) { if (elem == null) { throw new IllegalArgumentException("No valid element!"); } drawables.add(elem); } private void drawPOIS() { ScoringCalculator.generateEnabled().forEach(a -> a.draw(gc, this)); } @Override public void drawElements() { List<IMapDrawable> toDraw = drawables.parallelStream() .filter(p -> !isInDragMode() || p.showDuringGrab()) .filter(p -> p.getMinDrawScale() < scale) .filter(p -> coordsBounds.contains(p.getCoordinates())) .collect(Collectors.toList()); for (IMapDrawable elem : toDraw) { elem.draw(this.gc, this); } } @Override public void centerView(Point2D center) { if (center != null) { mapCenter = center; } else { mapCenter = CITY_LEIPZIG; } redraw(); } @Override public Point2D getCenter() { return mapCenter; } @Override public void redraw() { //long tStart = System.currentTimeMillis(); tmpWidth = getWidth(); tmpHeight = getHeight(); double coveredWidth = tmpWidth / scale; double coveredHeight = tmpHeight / scale; coordsBounds = new BoundingBox(mapCenter.getX() - coveredHeight / 2, mapCenter.getY() - coveredWidth / 2, coveredHeight, coveredWidth); heightDistance = MathUtils.convertUnitsToKilometres(coordsBounds.getWidth()); widthDistance = MathUtils.convertUnitsToKilometres(coordsBounds.getHeight()); // clear view gc.clearRect(0, 0, tmpWidth, tmpHeight); // draw map content if (!isInDragMode()) { drawScoringValues(); } drawInfo(); drawGrid(); drawPOIS(); //TODO: Draw elements count drawElements(); //Logger.getGlobal().info("Redraw took " + (System.currentTimeMillis() - tStart) + " ms"); } @Override public Point2D transferCoordinateToPixel(Point2D p) { return new Point2D((p.getY() - mapCenter.getY()) * scale + tmpWidth / 2, ((mapCenter.getX() - p.getX()) * scale + tmpHeight / 2)); } @Override public Point2D transferPixelToCoordinate(double x, double y) { return new Point2D(coordsBounds.getMaxX() - (y / tmpHeight) * coordsBounds.getWidth(), coordsBounds.getMinY() + (x / tmpWidth) * coordsBounds.getHeight()); } public int calculateMaxScore() { List<Point2D> gridPoints = calculateGrid(); double score = 0.0; double tmp = 0.0; for (Point2D point : gridPoints) { tmp = ScoringCalculator.calculateEnabledScoreValue(point); if (score < tmp) { score = tmp; } } return (int) score; } public List<Point2D> calculateGrid() { return grid.calcGridPoints(config.getSamplingPixelDensity()); } public void setColorModeCheckBox(CheckBox colorModeCheckBox) { this.colorModeCheckBox = colorModeCheckBox; } public CheckBox getColorModeCheckBox() { return colorModeCheckBox; } }
package org.jboss.virtual; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.zip.ZipFile; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; import org.jboss.logging.Logger; import org.jboss.util.collection.CollectionsFactory; /** * VFS Utilities * * @author <a href="adrian@jboss.com">Adrian Brock</a> * @author <a href="ales.justin@jboss.com">Ales Justin</a> * @version $Revision: 1.1 $ */ public class VFSUtils { /** The log */ private static final Logger log = Logger.getLogger(VFSUtils.class); /** The default encoding */ private static final String DEFAULT_ENCODING = "UTF-8"; /** * Constant representing the URL file protocol */ public static final String FILE_PROTOCOL = "file"; /** Standard separator for JAR URL */ public static final String JAR_URL_SEPARATOR = "!/"; /** The default buffer size to use for copies */ public static final int DEFAULT_BUFFER_SIZE = 65536; private VFSUtils() { } public static String getPathsString(Collection<VirtualFile> paths) { if (paths == null) throw new IllegalArgumentException("Null paths"); StringBuilder buffer = new StringBuilder(); boolean first = true; for (VirtualFile path : paths) { if (path == null) throw new IllegalArgumentException("Null path in " + paths); if (first == false) buffer.append(':'); else first = false; buffer.append(path.getPathName()); } if (first == true) buffer.append("<empty>"); return buffer.toString(); } public static void addManifestLocations(VirtualFile file, List<VirtualFile> paths) throws IOException { if (file == null) throw new IllegalArgumentException("Null file"); if (paths == null) throw new IllegalArgumentException("Null paths"); boolean trace = log.isTraceEnabled(); Manifest manifest = getManifest(file); if (manifest == null) return; Attributes mainAttributes = manifest.getMainAttributes(); String classPath = mainAttributes.getValue(Attributes.Name.CLASS_PATH); if (classPath == null) { if (trace) log.trace("Manifest has no Class-Path for " + file.getPathName()); return; } VirtualFile parent = file.getParent(); if (parent == null) { log.debug(file + " has no parent."); return; } if (trace) log.trace("Parsing Class-Path: " + classPath + " for " + file.getName() + " parent=" + parent.getName()); StringTokenizer tokenizer = new StringTokenizer(classPath); while (tokenizer.hasMoreTokens()) { String path = tokenizer.nextToken(); try { VirtualFile vf = parent.getChild(path); if(vf != null) { if(paths.contains(vf) == false) { paths.add(vf); // Recursively process the jar addManifestLocations(vf, paths); } else if (trace) log.trace(vf.getName() + " from manifiest is already in the classpath " + paths); } else if (trace) log.trace("Unable to find " + path + " from " + parent.getName()); } catch (IOException e) { log.debug("Manifest Class-Path entry " + path + " ignored for " + file.getPathName() + " reason=" + e); } } } public static Manifest getManifest(VirtualFile archive) throws IOException { if (archive == null) throw new IllegalArgumentException("Null archive"); VirtualFile manifest = archive.getChild(JarFile.MANIFEST_NAME); if (manifest == null) { if (log.isTraceEnabled()) log.trace("Can't find manifest for " + archive.getPathName()); return null; } return readManifest(manifest); } /** * Read the manifest from given manifest VirtualFile. * * @param manifest the VF to read from * @return JAR's manifest * @throws IOException if problems while opening VF stream occur */ public static Manifest readManifest(VirtualFile manifest) throws IOException { if (manifest == null) throw new IllegalArgumentException("Null manifest file"); InputStream stream = manifest.openStream(); try { return new Manifest(stream); } finally { safeClose(stream); } } public static String fixName(String name) { if (name == null) throw new IllegalArgumentException("Null name"); int length = name.length(); if (length <= 1) return name; if (name.charAt(length-1) == '/') return name.substring(0, length-1); return name; } /** * Decode the path with UTF-8 encoding.. * * @param path the path to decode * @return decoded path */ public static String decode(String path) { return decode(path, DEFAULT_ENCODING); } /** * Decode the path. * * @param path the path to decode * @param encoding the encodeing * @return decoded path */ public static String decode(String path, String encoding) { try { return URLDecoder.decode(path, encoding); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Cannot decode: " + path + " [" + encoding + "]", e); } } /** * Get the name. * * @param uri the uri * @return name from uri's path */ public static String getName(URI uri) { if (uri == null) throw new IllegalArgumentException("Null uri"); String name = uri.getPath(); if( name != null ) { // TODO: Not correct for certain uris like jar:...!/ int lastSlash = name.lastIndexOf('/'); if( lastSlash > 0 ) name = name.substring(lastSlash+1); } return name; } /** * Take a URL.getQuery string and parse it into name=value pairs * * @param query Possibly empty/null url query string * @return String[] for the name/value pairs in the query. May be empty but never null. */ public static Map<String, String> parseURLQuery(String query) { Map<String, String> pairsMap = CollectionsFactory.createLazyMap(); if(query != null) { StringTokenizer tokenizer = new StringTokenizer(query, "=&"); while(tokenizer.hasMoreTokens()) { String name = tokenizer.nextToken(); String value = tokenizer.nextToken(); pairsMap.put(name, value); } } return pairsMap; } /** * Deal with urls that may include spaces. * * @param url the url * @return uri the uri * @throws URISyntaxException for any error */ public static URI toURI(URL url) throws URISyntaxException { if (url == null) throw new IllegalArgumentException("Null url"); try { return url.toURI(); } catch (URISyntaxException e) { String urispec = url.toExternalForm(); // Escape percent sign and spaces urispec = urispec.replaceAll("%", "%25"); urispec = urispec.replaceAll(" ", "%20"); return new URI(urispec); } } /** * Ensure the url is convertible to URI by encoding spaces and percent characters if necessary * * @param url to be sanitized * @return sanitized URL * @throws URISyntaxException if URI conversion can't be fixed * @throws MalformedURLException if an error occurs */ public static URL sanitizeURL(URL url) throws URISyntaxException, MalformedURLException { return toURI(url).toURL(); } /** * Copy input stream to output stream and close them both * * @param is input stream * @param os output stream * @throws IOException for any error */ public static void copyStreamAndClose(InputStream is, OutputStream os) throws IOException { copyStreamAndClose(is, os, DEFAULT_BUFFER_SIZE); } /** * Copy input stream to output stream and close them both * * @param is input stream * @param os output stream * @param bufferSize the buffer size to use * @throws IOException for any error */ public static void copyStreamAndClose(InputStream is, OutputStream os, int bufferSize) throws IOException { try { copyStream(is, os, bufferSize); // throw an exception if the close fails since some data might be lost is.close(); os.close(); } finally { // ...but still guarantee that they're both closed safeClose(is); safeClose(os); } } /** * Copy input stream to output stream without closing streams. * Flushes output stream when done. * * @param is input stream * @param os output stream * @throws IOException for any error */ public static void copyStream(InputStream is, OutputStream os) throws IOException { copyStream(is, os, DEFAULT_BUFFER_SIZE); } /** * Copy input stream to output stream without closing streams. * Flushes output stream when done. * * @param is input stream * @param os output stream * @param bufferSize the buffer size to use * @throws IOException for any error */ public static void copyStream(InputStream is, OutputStream os, int bufferSize) throws IOException { if (is == null) throw new IllegalArgumentException("input stream is null"); if (os == null) throw new IllegalArgumentException("output stream is null"); byte [] buff = new byte[bufferSize]; int rc; while ((rc = is.read(buff)) != -1) os.write(buff, 0, rc); os.flush(); } /** * Write the given bytes to the given virtual file, replacing its current contents (if any) or creating a new * file if one does not exist. * * @param virtualFile the virtual file to write * @param bytes the bytes * @throws IOException if an error occurs */ public static void writeFile(VirtualFile virtualFile, byte[] bytes) throws IOException { final File file = virtualFile.getPhysicalFile(); file.getParentFile().mkdirs(); final FileOutputStream fos = new FileOutputStream(file); try { fos.write(bytes); fos.close(); } finally { safeClose(fos); } } /** * Get the virtual URL for a virtual file. This URL can be used to access the virtual file; however, taking the * file part of the URL and attempting to use it with the {@link java.io.File} class may fail if the file is not * present on the physical filesystem, and in general should not be attempted. * * @param file the virtual file * @return the URL * @throws MalformedURLException if the file cannot be coerced into a URL for some reason */ public static URL getVirtualURL(VirtualFile file) throws MalformedURLException { // todo: specify the URL handler directly as a minor optimization return new URL("file", "", -1, file.getPathName(true)); } /** * Get the virtual URI for a virtual file. * * @param file the virtual file * @return the URI * @throws URISyntaxException if the file cannot be coerced into a URI for some reason */ public static URI getVirtualURI(VirtualFile file) throws URISyntaxException { return new URI("file", "", file.getPathName(true), null); } /** * Get a physical URL for a virtual file. See the warnings on the {@link VirtualFile#getPhysicalFile()} method * before using this method. * * @param file the virtual file * @return the physical file URL * @throws IOException if an I/O error occurs getting the physical file */ public static URL getPhysicalURL(VirtualFile file) throws IOException { return getPhysicalURI(file).toURL(); } /** * Get a physical URI for a virtual file. See the warnings on the {@link VirtualFile#getPhysicalFile()} method * before using this method. * * @param file the virtual file * @return the physical file URL * @throws IOException if an I/O error occurs getting the physical file */ public static URI getPhysicalURI(VirtualFile file) throws IOException { return file.getPhysicalFile().toURI(); } /** * Safely close some resource without throwing an exception. Any exception will be logged at TRACE level. * * @param c the resource */ public static void safeClose(final Closeable c) { if (c != null) try { c.close(); } catch (Exception e) { log.trace("Failed to close resource", e); } } /** * Safely close some resources without throwing an exception. Any exception will be logged at TRACE level. * * @param ci the resources */ public static void safeClose(final Iterable<? extends Closeable> ci) { if (ci != null) for (Closeable closeable : ci) { safeClose(closeable); } } /** * Safely close some resource without throwing an exception. Any exception will be logged at TRACE level. * * @param zipFile the resource */ public static void safeClose(final ZipFile zipFile) { if (zipFile != null) try { zipFile.close(); } catch (Exception e) { log.trace("Failed to close resource", e); } } /** * Attempt to recursively delete a real file. * * @param root the real file to delete * @return {@code true} if the file was deleted */ public static boolean recursiveDelete(File root) { boolean ok = true; if (root.isDirectory()) { final File[] files = root.listFiles(); for (File file : files) { ok &= recursiveDelete(file); } return ok && (root.delete() || ! root.exists()); } else { ok &= root.delete() || ! root.exists(); } return ok; } }
package org.nutz.pay.bean.biz; public class Dict { public static String UMS_WEBPAY_API_GET_GATEWAY = "https://qr.chinaums.com/netpay-portal/webpay/pay.do"; public static String UMS_WEBPAY_API_GET_DEV_GATEWAY = "https://qr-test2.chinaums.com/netpay-portal/webpay/pay.do"; public static String UMS_WEBPAY_API_POST_GATEWAY = "https://qr.chinaums.com/netpay-route-server/api/"; public static String UMS_WEBPAY_API_POST_DEV_GATEWAY = "https://qr-test2.chinaums.com/netpay-route-server/api/"; public static String UMS_QR_API_POST_GATEWAY = "https://qr.chinaums.com/bills/qrCode.do"; public static String UMS_QR_API_POST_DEV_GATEWAY = "https://qr-test2.chinaums.com/bills/qrCode.do"; public static final String DATE_FORMART_FULL = "yyyy-MM-dd HH:mm:ss"; public static final String DATE_FORMART = "yyyy-MM-dd"; public static String MSGTYPE_WXPAY_JSPAY = "WXPay.jsPay"; public static String MSGTYPE_TRADE_JSPAY = "trade.jsPay"; public static String MSGTYPE_QMF_JSPAY = "qmf.jspay"; public static String MSGTYPE_QMF_WEBPAY = "qmf.webPay"; public static String MSGTYPE_ACP_JSPAY = "acp.jsPay"; public static String MSGTYPE_WX_UNIFIEDORDER = "wx.unifiedOrder"; /** * MD5 */ public static String SIGNTYPE_MD5 = "MD5"; /** * SHA256 */ public static String SIGNTYPE_SHA256 = "SHA256"; public static String CERTTYPE_IDENTITY_CARD = "IDENTITY_CARD"; public static String CERTTYPE_PASSPORT = "PASSPORT"; public static String CERTTYPE_OFFICER_CARD = "OFFICER_CARD"; public static String CERTTYPE_SOLDIER_CARD = "SOLDIER_CARD"; public static String CERTTYPE_HUKOU = "HUKOU"; }
// File path shortening code adapted from: package org.scijava.util; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Useful methods for working with file paths. * * @author Johannes Schindelin * @author Curtis Rueden * @author Grant Harris */ public final class FileUtils { public static final int DEFAULT_SHORTENER_THRESHOLD = 4; public static final String SHORTENER_BACKSLASH_REGEX = "\\\\"; public static final String SHORTENER_SLASH_REGEX = "/"; public static final String SHORTENER_BACKSLASH = "\\"; public static final String SHORTENER_SLASH = "/"; public static final String SHORTENER_ELLIPSE = "..."; private FileUtils() { // prevent instantiation of utility class } /** * Gets the absolute path to the given file, with the directory separator * standardized to forward slash, like most platforms use. * * @param file The file whose path will be obtained and standardized. * @return The file's standardized absolute path. */ public static String getPath(final File file) { final String path = file.getAbsolutePath(); final String slash = System.getProperty("file.separator"); return getPath(path, slash); } /** * Gets a standardized path based on the given one, with the directory * separator standardized from the specific separator to forward slash, like * most platforms use. * * @param path The path to standardize. * @param separator The directory separator to be standardized. * @return The standardized path. */ public static String getPath(final String path, final String separator) { // NB: Standardize directory separator (i.e., avoid Windows nonsense!). return path.replaceAll(Pattern.quote(separator), "/"); } /** * Extracts the file extension from a file. * * @param file the file object * @return the file extension (excluding the dot), or the empty string when * the file name does not contain dots */ public static String getExtension(final File file) { final String name = file.getName(); final int dot = name.lastIndexOf('.'); if (dot < 0) return ""; return name.substring(dot + 1); } /** * Extracts the file extension from a file path. * * @param path the path to the file (relative or absolute) * @return the file extension (excluding the dot), or the empty string when * the file name does not contain dots */ public static String getExtension(final String path) { return getExtension(new File(path)); } /** * A regular expression to match filenames containing version information. * <p> * This is kept synchronized with {@code imagej.updater.core.FileObject}. * </p> */ private final static Pattern versionPattern = Pattern .compile("(.+?)(-\\d+(\\.\\d+|\\d{7})+[a-z]?\\d?(-[A-Za-z0-9.]+?|\\.GA)*?)?((-(swing|swt|shaded|sources|javadoc|native))?(\\.jar(-[a-z]*)?))"); public static String stripFilenameVersion(final String filename) { final Matcher matcher = versionPattern.matcher(filename); if (!matcher.matches()) return filename; return matcher.group(1) + matcher.group(5); } /** * Lists all versions of a given (possibly versioned) file name. * * @param directory the directory to scan * @param filename the file name to use * @return the list of matches */ public static File[] getAllVersions(final File directory, final String filename) { final Matcher matcher = versionPattern.matcher(filename); if (!matcher.matches()) { final File file = new File(directory, filename); return file.exists() ? new File[] { file } : null; } final String baseName = matcher.group(1); final String classifier = matcher.group(6); return directory.listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String name) { if (!name.startsWith(baseName)) return false; final Matcher matcher2 = versionPattern.matcher(name); return matcher2.matches() && baseName.equals(matcher2.group(1)) && equals(classifier, matcher2.group(6)); } private boolean equals(final String a, final String b) { if (a == null) { return b == null; } return a.equals(b); } }); } public static File urlToFile(final URL url) { return url == null ? null : urlToFile(url.toString()); } public static File urlToFile(final String url) { String path = url; if (path.startsWith("jar:")) { // remove "jar:" prefix and "!/" suffix final int index = path.indexOf("!/"); path = path.substring(4, index); } try { return new File(new URL(path).toURI()); } catch (final MalformedURLException e) { // NB: URL is not completely well-formed. } catch (final URISyntaxException e) { // NB: URL is not completely well-formed. } if (path.startsWith("file:")) { // pass through the URL as-is, minus "file:" prefix path = path.substring(5); return new File(path); } throw new IllegalArgumentException("Invalid URL: " + url); } /** * Shortens the path to a maximum of 4 path elements. * * @param path the path to the file (relative or absolute) * @return shortened path */ public static String shortenPath(final String path) { return shortenPath(path, DEFAULT_SHORTENER_THRESHOLD); } /** * Shortens the path based on the given maximum number of path elements. E.g., * "C:/1/2/test.txt" returns "C:/1/.../test.txt" if threshold is 1. * * @param path the path to the file (relative or absolute) * @param threshold the number of directories to keep unshortened * @return shortened path */ public static String shortenPath(final String path, final int threshold) { String regex = SHORTENER_BACKSLASH_REGEX; String sep = SHORTENER_BACKSLASH; if (path.indexOf("/") > 0) { regex = SHORTENER_SLASH_REGEX; sep = SHORTENER_SLASH; } String pathtemp[] = path.split(regex); // remove empty elements int elem = 0; { final String newtemp[] = new String[pathtemp.length]; int j = 0; for (int i = 0; i < pathtemp.length; i++) { if (!pathtemp[i].equals("")) { newtemp[j++] = pathtemp[i]; elem++; } } pathtemp = newtemp; } if (elem > threshold) { final StringBuilder sb = new StringBuilder(); int index = 0; // drive or protocol final int pos2dots = path.indexOf(":"); if (pos2dots > 0) { // case c:\ c:/ etc. sb.append(path.substring(0, pos2dots + 2)); index++; if (path.indexOf(":/") > 0 && pathtemp[0].length() > 2) { sb.append(SHORTENER_SLASH); } } else { final boolean isUNC = path.substring(0, 2).equals(SHORTENER_BACKSLASH_REGEX); if (isUNC) { sb.append(SHORTENER_BACKSLASH).append(SHORTENER_BACKSLASH); } } for (; index <= threshold; index++) { sb.append(pathtemp[index]).append(sep); } if (index == (elem - 1)) { sb.append(pathtemp[elem - 1]); } else { sb.append(SHORTENER_ELLIPSE).append(sep).append(pathtemp[elem - 1]); } return sb.toString(); } return path; } /** * Compacts a path into a given number of characters. The result is similar to * the Win32 API PathCompactPathExA. * * @param path the path to the file (relative or absolute) * @param limit the number of characters to which the path should be limited * @return shortened path */ public static String limitPath(final String path, final int limit) { if (path.length() <= limit) return path; final char shortPathArray[] = new char[limit]; final char pathArray[] = path.toCharArray(); final char ellipseArray[] = SHORTENER_ELLIPSE.toCharArray(); final int pathindex = pathArray.length - 1; final int shortpathindex = limit - 1; // fill the array from the end int i = 0; for (; i < limit; i++) { if (pathArray[pathindex - i] != '/' && pathArray[pathindex - i] != '\\') { shortPathArray[shortpathindex - i] = pathArray[pathindex - i]; } else { break; } } // check how much space is left final int free = limit - i; if (free < SHORTENER_ELLIPSE.length()) { // fill the beginning with ellipse for (int j = 0; j < ellipseArray.length; j++) { shortPathArray[j] = ellipseArray[j]; } } else { // fill the beginning with path and leave room for the ellipse int j = 0; for (; j + ellipseArray.length < free; j++) { shortPathArray[j] = pathArray[j]; } // ... add the ellipse for (int k = 0; j + k < free; k++) { shortPathArray[j + k] = ellipseArray[k]; } } return new String(shortPathArray); } /** * Creates a temporary directory. * <p> * Since there is no atomic operation to do that, we create a temporary file, * delete it and create a directory in its place. To avoid race conditions, we * use the optimistic approach: if the directory cannot be created, we try to * obtain a new temporary file rather than erroring out. * </p> * <p> * It is the caller's responsibility to make sure that the directory is * deleted. * </p> * * @param prefix The prefix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @param suffix The suffix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @return An abstract pathname denoting a newly-created empty directory * @throws IOException */ public static File createTemporaryDirectory(final String prefix, final String suffix) throws IOException { return createTemporaryDirectory(prefix, suffix, null); } /** * Creates a temporary directory. * <p> * Since there is no atomic operation to do that, we create a temporary file, * delete it and create a directory in its place. To avoid race conditions, we * use the optimistic approach: if the directory cannot be created, we try to * obtain a new temporary file rather than erroring out. * </p> * <p> * It is the caller's responsibility to make sure that the directory is * deleted. * </p> * * @param prefix The prefix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @param suffix The suffix string to be used in generating the file's name; * see {@link File#createTempFile(String, String, File)} * @param directory The directory in which the file is to be created, or null * if the default temporary-file directory is to be used * @return: An abstract pathname denoting a newly-created empty directory * @throws IOException */ public static File createTemporaryDirectory(final String prefix, final String suffix, final File directory) throws IOException { for (int counter = 0; counter < 10; counter++) { final File file = File.createTempFile(prefix, suffix, directory); if (!file.delete()) { throw new IOException("Could not delete file " + file); } // in case of a race condition, just try again if (file.mkdir()) return file; } throw new IOException( "Could not create temporary directory (too many race conditions?)"); } /** * Deletes a directory recursively. * * @param directory The directory to delete. * @return whether it succeeded (see also {@link File#delete()}) */ public static boolean deleteRecursively(final File directory) { if (directory == null) return true; final File[] list = directory.listFiles(); if (list == null) return true; for (final File file : list) { if (file.isFile()) { if (!file.delete()) return false; } else if (file.isDirectory()) { if (!deleteRecursively(file)) return false; } } return directory.delete(); } /** * Recursively lists the contents of the referenced directory. Directories are * excluded from the result. Supported protocols include {@code file} and * {@code jar}. * * @param directory The directory whose contents should be listed. * @return A collection of {@link URL}s representing the directory's contents. * @see #listContents(URL, boolean, boolean) */ public static Collection<URL> listContents(final URL directory) { return listContents(directory, true, true); } /** * Lists all contents of the referenced directory. Supported protocols include * {@code file} and {@code jar}. * * @param directory The directory whose contents should be listed. * @param recurse Whether to list contents recursively, as opposed to only the * directory's direct contents. * @param filesOnly Whether to exclude directories in the resulting collection * of contents. * @return A collection of {@link URL}s representing the directory's contents. */ public static Collection<URL> listContents(final URL directory, final boolean recurse, final boolean filesOnly) { return appendContents(new ArrayList<URL>(), directory, recurse, filesOnly); } /** * Recursively adds contents from the referenced directory to an existing * collection. Directories are excluded from the result. Supported protocols * include {@code file} and {@code jar}. * * @param result The collection to which contents should be added. * @param directory The directory whose contents should be listed. * @return A collection of {@link URL}s representing the directory's contents. * @see #appendContents(Collection, URL, boolean, boolean) */ public static Collection<URL> appendContents(final Collection<URL> result, final URL directory) { return appendContents(result, directory, true, true); } /** * Add contents from the referenced directory to an existing collection. * Supported protocols include {@code file} and {@code jar}. * * @param result The collection to which contents should be added. * @param directory The directory whose contents should be listed. * @param recurse Whether to append contents recursively, as opposed to only * the directory's direct contents. * @param filesOnly Whether to exclude directories in the resulting collection * of contents. * @return A collection of {@link URL}s representing the directory's contents. */ public static Collection<URL> appendContents(final Collection<URL> result, final URL directory, final boolean recurse, final boolean filesOnly) { if (directory == null) return result; // nothing to append final String protocol = directory.getProtocol(); if (protocol.equals("file")) { final File dir = urlToFile(directory); final File[] list = dir.listFiles(); if (list != null) { for (final File file : list) { try { if (!filesOnly || file.isFile()) { result.add(file.toURI().toURL()); } if (recurse && file.isDirectory()) { appendContents(result, file.toURI().toURL(), recurse, filesOnly); } } catch (final MalformedURLException e) { e.printStackTrace(); } } } } else if (protocol.equals("jar")) { try { final String url = directory.toString(); final int bang = url.indexOf("!/"); if (bang < 0) return result; final String prefix = url.substring(bang + 2); final String baseURL = url.substring(0, bang + 2); final JarURLConnection connection = (JarURLConnection) new URL(baseURL).openConnection(); final JarFile jar = connection.getJarFile(); for (final JarEntry entry : new IteratorPlus<JarEntry>(jar.entries())) { final String urlEncoded = new URI(null, null, entry.getName(), null).toString(); if (urlEncoded.length() > prefix.length() && // omit directory itself urlEncoded.startsWith(prefix)) { if (filesOnly && urlEncoded.endsWith("/")) { // URL is directory; exclude it continue; } if (!recurse) { // check whether this URL is a *direct* child of the directory final int slash = urlEncoded.indexOf("/", prefix.length()); if (slash >= 0 && slash != urlEncoded.length() - 1) { // not a direct child continue; } } result.add(new URL(baseURL + urlEncoded)); } } jar.close(); } catch (final IOException e) { e.printStackTrace(); } catch (final URISyntaxException e) { throw new IllegalArgumentException(e); } } return result; } // -- Deprecated methods -- /** * Returns the {@link Matcher} object dissecting a versioned file name. * * @param filename the file name * @return the {@link Matcher} object * @deprecated see {@link #stripFilenameVersion(String)} */ @Deprecated public static Matcher matchVersionedFilename(final String filename) { return versionPattern.matcher(filename); } }
package seedu.jobs.model.task; import java.util.Optional; import seedu.jobs.commons.exceptions.IllegalValueException; /** * Represents a Task's time signature in JOBS. Guarantees: immutable; is valid * as declared in {@link #isValidTime(String)} */ public class Time { public static final String MESSAGE_TIME_CONSTRAINT = "Time should always follow the dd/mm/yy hh:mm format"; public static final String TIME_VALIDATION_REGEX = "^[0-3]*[0-9]/[0-3]*[0-9]/(?:[0-9][0-9])?[0-9][0-9]\\s+(0*[1-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])"; public static final String DEFAULT_TIME = ""; public String value; public Time(Optional<String> startTime) throws IllegalValueException { if (!startTime.isPresent()) { this.value = DEFAULT_TIME; } else { if(startTime.get().equals("")){ this.value = DEFAULT_TIME; } else if (!isValidTime(startTime.get())) { throw new IllegalValueException(MESSAGE_TIME_CONSTRAINT); } else{ this.value = startTime.get(); } } } /** * Returns true if a given string is in valid time format */ public static boolean isValidTime(String test) { return test.matches(TIME_VALIDATION_REGEX); } @Override public String toString() { return this.value; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Time // instanceof handles nulls && this.value.equals(((Time) other).value)); // state // check } @Override public int hashCode() { return value.hashCode(); } }
package techreborn.init; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraftforge.common.ForgeModContainer; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.UniversalBucket; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.oredict.OreDictionary; import reborncore.api.recipe.RecipeHandler; import reborncore.common.registration.RebornRegistry; import reborncore.common.util.ItemUtils; import reborncore.common.util.OreUtil; import reborncore.common.util.RebornCraftingHelper; import reborncore.common.util.StringUtils; import techreborn.Core; import techreborn.api.reactor.FusionReactorRecipe; import techreborn.api.reactor.FusionReactorRecipeHelper; import techreborn.api.recipe.machines.*; import techreborn.blocks.BlockMachineFrames; import techreborn.blocks.BlockOre; import techreborn.compat.CompatManager; import techreborn.config.ConfigTechReborn; import techreborn.init.recipes.*; import techreborn.items.*; import techreborn.lib.ModInfo; import java.util.Iterator; import java.util.Map; import static techreborn.utils.OreDictUtils.getDictData; import static techreborn.utils.OreDictUtils.getDictOreOrEmpty; import static techreborn.utils.OreDictUtils.isDictPrefixed; import static techreborn.utils.OreDictUtils.joinDictName; @RebornRegistry(modID = ModInfo.MOD_ID) public class ModRecipes { public static void init() { //Gonna rescan to make sure we have an uptodate list OreUtil.scanForOres(); //Done again incase we loaded before QuantumStorage CompatManager.isQuantumStorageLoaded = Loader.isModLoaded("quantumstorage"); CraftingTableRecipes.init(); SmeltingRecipes.init(); ExtractorRecipes.init(); RollingMachineRecipes.init(); FluidGeneratorRecipes.init(); IndustrialGrinderRecipes.init(); IndustrialCentrifugeRecipes.init(); IndustrialElectrolyzerRecipes.init(); ImplosionCompressorRecipes.init(); ScrapboxRecipes.init(); addGeneralShapedRecipes(); addMachineRecipes(); addAlloySmelterRecipes(); addChemicalReactorRecipes(); addBlastFurnaceRecipes(); addVacuumFreezerRecipes(); addReactorRecipes(); addIc2Recipes(); addGrinderRecipes(); addCompressorRecipes(); } public static void postInit() { if (ConfigTechReborn.disableRailcraftSteelNuggetRecipe) { Iterator iterator = FurnaceRecipes.instance().getSmeltingList().entrySet().iterator(); Map.Entry entry; while (iterator.hasNext()) { entry = (Map.Entry) iterator.next(); if (entry.getValue() instanceof ItemStack && entry.getKey() instanceof ItemStack) { ItemStack input = (ItemStack) entry.getKey(); ItemStack output = (ItemStack) entry.getValue(); if (ItemUtils.isInputEqual("nuggetSteel", output, true, true, false) && ItemUtils.isInputEqual("nuggetIron", input, true, true, false)) { Core.logHelper.info("Removing a steelnugget smelting recipe"); iterator.remove(); } } } } IndustrialSawmillRecipes.init(); } private static void addCompressorRecipes() { RecipeHandler.addRecipe(new CompressorRecipe(ItemIngots.getIngotByName("advanced_alloy"), ItemPlates.getPlateByName("advanced_alloy"), 400, 20)); RecipeHandler.addRecipe( new CompressorRecipe(IC2Duplicates.CARBON_MESH.getStackBasedOnConfig(), ItemPlates.getPlateByName("carbon"), 400, 2)); for (String ore : OreUtil.oreNames) { if (ore.equals("iridium")) { continue; } if (OreUtil.doesOreExistAndValid("plate" + OreUtil.capitalizeFirstLetter(ore)) && OreUtil.doesOreExistAndValid("ingot" + OreUtil.capitalizeFirstLetter(ore))) { RecipeHandler.addRecipe( new CompressorRecipe(OreUtil.getStackFromName("ingot" + OreUtil.capitalizeFirstLetter(ore), 1), OreUtil.getStackFromName("plate" + OreUtil.capitalizeFirstLetter(ore), 1), 300, 4)); } if (OreUtil.doesOreExistAndValid("plate" + OreUtil.capitalizeFirstLetter(ore)) && OreUtil.doesOreExistAndValid("gem" + OreUtil.capitalizeFirstLetter(ore))) { RecipeHandler.addRecipe( new CompressorRecipe(OreUtil.getStackFromName("gem" + OreUtil.capitalizeFirstLetter(ore), 9), OreUtil.getStackFromName("plate" + OreUtil.capitalizeFirstLetter(ore), 1), 300, 4)); } if (OreUtil.hasPlate(ore) && OreUtil.hasBlock(ore)) { RecipeHandler.addRecipe( new CompressorRecipe(OreUtil.getStackFromName("block" + OreUtil.capitalizeFirstLetter(ore), 1), OreUtil.getStackFromName("plate" + OreUtil.capitalizeFirstLetter(ore), 9), 300, 4)); } } RecipeHandler.addRecipe( new CompressorRecipe(OreUtil.getStackFromName("plankWood", 1), OreUtil.getStackFromName("plateWood", 1), 300, 4)); RecipeHandler.addRecipe( new CompressorRecipe(OreUtil.getStackFromName("dustLazurite", 8), OreUtil.getStackFromName("plateLazurite", 1), 300, 4)); } static void addGrinderRecipes() { // Vanilla int eutick = 2; int ticktime = 300; RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Items.BONE), new ItemStack(Items.DYE, 6, 15), 170, 19)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Blocks.COBBLESTONE), new ItemStack(Blocks.SAND), 230, 23)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Blocks.GRAVEL), new ItemStack(Items.FLINT), 200, 20)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Blocks.GLOWSTONE), ItemDusts.getDustByName("glowstone", 4), 220, 21)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Blocks.NETHERRACK), ItemDusts.getDustByName("netherrack"), 300, 27)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Items.COAL), ItemDusts.getDustByName("coal"), 300, 27)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(net.minecraft.init.Items.CLAY_BALL), ItemDusts.getDustByName("clay"), 200, 18)); for (String oreDictionaryName : OreDictionary.getOreNames()) { if (isDictPrefixed(oreDictionaryName, "ore", "gem", "ingot")) { ItemStack oreStack = getDictOreOrEmpty(oreDictionaryName, 1); String[] data = getDictData(oreDictionaryName); //High-level ores shouldn't grind here if (data[0].equals("ore") && ( data[1].equals("tungsten") || data[1].equals("titanium") || data[1].equals("aluminium") || data[1].equals("iridium") || data[1].equals("saltpeter")) || oreStack == ItemStack.EMPTY) continue; boolean ore = data[0].equals("ore"); Core.logHelper.debug("Ore: " + data[1]); ItemStack dust = getDictOreOrEmpty(joinDictName("dust", data[1]), ore ? 2 : 1); if (dust == ItemStack.EMPTY || dust.getItem() == null) { continue; } dust = dust.copy(); if (ore) { dust.setCount(2); } RecipeHandler.addRecipe(new GrinderRecipe(oreStack, dust, ore ? 270 : 200, ore ? 31 : 22)); } } RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Items.COAL), ItemDusts.getDustByName("coal"), 120, 10)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Blocks.END_STONE), ItemDusts.getDustByName("endstone"), 300, 16)); } static void addReactorRecipes() { FusionReactorRecipeHelper.registerRecipe( new FusionReactorRecipe(ItemCells.getCellByName("helium3"), ItemCells.getCellByName("deuterium"), ItemCells.getCellByName("heliumplasma"), 40000000, 32768, 1024)); FusionReactorRecipeHelper.registerRecipe( new FusionReactorRecipe(ItemCells.getCellByName("tritium"), ItemCells.getCellByName("deuterium"), ItemCells.getCellByName("helium3"), 60000000, 32768, 2048)); FusionReactorRecipeHelper.registerRecipe( new FusionReactorRecipe(ItemCells.getCellByName("wolframium"), ItemCells.getCellByName("Berylium"), ItemDusts.getDustByName("platinum"), 80000000, -2048, 1024)); FusionReactorRecipeHelper.registerRecipe( new FusionReactorRecipe(ItemCells.getCellByName("wolframium"), ItemCells.getCellByName("lithium"), BlockOre.getOreByName("iridium"), 90000000, -2048, 1024)); } static void addGeneralShapedRecipes() { RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.CLOAKING_DEVICE), "CIC", "IOI", "CIC", 'C', "ingotChrome", 'I', "plateIridium", 'O', new ItemStack(ModItems.LAPOTRONIC_ORB)); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.TREE_TAP), " S ", "PPP", "P ", 'S', "stickWood", 'P', "plankWood"); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.ROCK_CUTTER), "DT ", "DT ", "DCB", 'D', "dustDiamond", 'T', "ingotTitanium", 'C', "circuitBasic", 'B', new ItemStack(ModItems.RE_BATTERY)); for (String part : ItemParts.types) { if (part.endsWith("Gear")) { RebornCraftingHelper.addShapedOreRecipe(ItemParts.getPartByName(part), " O ", "OIO", " O ", 'I', new ItemStack(Items.IRON_INGOT), 'O', "ingot" + StringUtils.toFirstCapital(part.replace("Gear", ""))); } } RebornCraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("heliumCoolantSimple"), " T ", "TCT", " T ", 'T', "ingotTin", 'C', ItemCells.getCellByName("helium", 1)); RebornCraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("HeliumCoolantTriple"), "TTT", "CCC", "TTT", 'T', "ingotTin", 'C', ItemParts.getPartByName("heliumCoolantSimple")); RebornCraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("HeliumCoolantSix"), "THT", "TCT", "THT", 'T', "ingotTin", 'C', "ingotCopper", 'H', ItemParts.getPartByName("HeliumCoolantTriple")); RebornCraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("NaKCoolantTriple"), "TTT", "CCC", "TTT", 'T', "ingotTin", 'C', ItemParts.getPartByName("NaKCoolantSimple")); RebornCraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("NaKCoolantSix"), "THT", "TCT", "THT", 'T', "ingotTin", 'C', "ingotCopper", 'H', ItemParts.getPartByName("NaKCoolantTriple")); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.ADJUSTABLE_SU), "LLL", "LCL", "LLL", 'L', new ItemStack(ModItems.LAPOTRONIC_ORB), 'C', new ItemStack(ModItems.ENERGY_CRYSTAL)); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.INTERDIMENSIONAL_SU), "PAP", "ACA", "PAP", 'P', "plateIridium", 'C', new ItemStack(Blocks.ENDER_CHEST), 'A', new ItemStack(ModBlocks.ADJUSTABLE_SU)); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.FUSION_CONTROL_COMPUTER), "CCC", "PTP", "CCC", 'P', new ItemStack(ModItems.ENERGY_CRYSTAL), 'T', new ItemStack(ModBlocks.FUSION_COIL), 'C', "circuitMaster"); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.LIGHTNING_ROD), "CAC", "ACA", "CAC", 'A', new ItemStack(ModBlocks.MACHINE_CASINGS, 1, 2), 'C', "circuitMaster"); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.FUSION_COIL), "CSC", "NAN", "CRC", 'A', new ItemStack(ModBlocks.MACHINE_CASINGS, 1, 2), 'N', ItemParts.getPartByName("nichromeHeatingCoil"), 'C', "circuitMaster", 'S', ItemParts.getPartByName("superConductor"), 'R', ItemParts.getPartByName("iridiumNeutronReflector")); RebornCraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("iridiumNeutronReflector"), "PPP", "PIP", "PPP", 'P', ItemParts.getPartByName("thickNeutronReflector"), 'I', "ingotIridium"); RebornCraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("thickNeutronReflector"), " P ", "PCP", " P ", 'P', ItemParts.getPartByName("neutronReflector"), 'C', ItemCells.getCellByName("Berylium")); RebornCraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("neutronReflector"), "TCT", "CPC", "TCT", 'T', "dustTin", 'C', "dustCoal", 'P', "plateCopper"); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.SCRAP_BOX), "SSS", "SSS", "SSS", 'S', ItemParts.getPartByName("scrap")); if (!IC2Duplicates.deduplicate()) { RebornCraftingHelper.addShapedOreRecipe(ItemUpgrades.getUpgradeByName("Overclock"), "TTT", "WCW", 'T', ItemParts.getPartByName("CoolantSimple"), 'W', IC2Duplicates.CABLE_ICOPPER.getStackBasedOnConfig(), 'C', "circuitBasic"); RebornCraftingHelper.addShapedOreRecipe(ItemUpgrades.getUpgradeByName("Overclock", 2), " T ", "WCW", 'T', ItemParts.getPartByName("heliumCoolantSimple"), 'W', IC2Duplicates.CABLE_ICOPPER.getStackBasedOnConfig(), 'C', "circuitBasic"); RebornCraftingHelper.addShapedOreRecipe(ItemUpgrades.getUpgradeByName("Overclock", 2), " T ", "WCW", 'T', ItemParts.getPartByName("NaKCoolantSimple"), 'W', IC2Duplicates.CABLE_ICOPPER.getStackBasedOnConfig(), 'C', "circuitBasic"); RebornCraftingHelper.addShapedOreRecipe(ItemUpgrades.getUpgradeByName("transformer"), "GGG", "WTW", "GCG", 'G', "blockGlass", 'W', IC2Duplicates.CABLE_IGOLD.getStackBasedOnConfig(), 'C', "circuitBasic", 'T', IC2Duplicates.MVT.getStackBasedOnConfig()); } RebornCraftingHelper.addShapedOreRecipe(ItemUpgrades.getUpgradeByName("energy_storage"), "PPP", "WBW", "PCP", 'P', "plankWood", 'W', IC2Duplicates.CABLE_ICOPPER.getStackBasedOnConfig(), 'C', "circuitBasic", 'B', ModItems.RE_BATTERY); RebornCraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("CoolantSimple"), " T ", "TWT", " T ", 'T', "ingotTin", 'W', "containerWater"); RebornCraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("CoolantTriple"), "TTT", "CCC", "TTT", 'T', "ingotTin", 'C', ItemParts.getPartByName("CoolantSimple")); RebornCraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("CoolantSix"), "TCT", "TPT", "TCT", 'T', "ingotTin", 'C', ItemParts.getPartByName("CoolantTriple"), 'P', "plateCopper"); RebornCraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("NaKCoolantSimple"), "TST", "PCP", "TST", 'T', "ingotTin", 'C', ItemParts.getPartByName("CoolantSimple"), 'S', ItemCells.getCellByName("sodium"), 'P', ItemCells.getCellByName("potassium")); RebornCraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("NaKCoolantSimple"), "TPT", "SCS", "TPT", 'T', "ingotTin", 'C', ItemParts.getPartByName("CoolantSimple"), 'S', ItemCells.getCellByName("sodium"), 'P', ItemCells.getCellByName("potassium")); RebornCraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("dataControlCircuit"), "ADA", "DID", "ADA", 'I', "ingotIridium", 'A', "circuitAdvanced", 'D', ItemParts.getPartByName("dataStorageCircuit")); RebornCraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("dataOrb"), "DDD", "DSD", "DDD", 'D', ItemParts.getPartByName("dataStorageCircuit"), 'S', ItemParts.getPartByName("dataStorageCircuit")); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.ELECTRIC_TREE_TAP), "TB", " ", 'T', new ItemStack(ModItems.TREE_TAP), 'B', new ItemStack(ModItems.RE_BATTERY)); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.NANOSABER), "DC ", "DC ", "GLG", 'L', new ItemStack(ModItems.LAPOTRONIC_CRYSTAL), 'C', "plateCarbon", 'D', "plateDiamond", 'G', ItemDustsSmall.getSmallDustByName("glowstone")); RebornCraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("diamondGrindingHead", 2), "TST", "SBS", "TST", 'T', "plateDiamond", 'S', "plateSteel", 'B', "blockDiamond"); RebornCraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("coolantSimple", 2), " T ", "TWT", " T ", 'T', "ingotTin", 'W', new ItemStack(Items.WATER_BUCKET)); Core.logHelper.info("Shapped Recipes Added"); } static void addMachineRecipes() { if (!CompatManager.isQuantumStorageLoaded) { RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.QUANTUM_TANK), "EPE", "PCP", "EPE", 'P', "ingotPlatinum", 'E', "circuitAdvanced", 'C', ModBlocks.QUANTUM_CHEST); } RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.DIGITAL_CHEST), "PPP", "PDP", "PCP", 'P', "plateAluminum", 'D', ItemParts.getPartByName("dataOrb"), 'C', ItemParts.getPartByName("computerMonitor")); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.DIGITAL_CHEST), "PPP", "PDP", "PCP", 'P', "plateSteel", 'D', ItemParts.getPartByName("dataOrb"), 'C', ItemParts.getPartByName("computerMonitor")); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.ALLOY_SMELTER), " C ", "FMF", " ", 'C', "circuitBasic", 'F', IC2Duplicates.ELECTRICAL_FURNACE.getStackBasedOnConfig(), 'M', BlockMachineFrames.getFrameByName("machine", 1)); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.LSU_STORAGE), "LLL", "LCL", "LLL", 'L', "blockLapis", 'C', "circuitBasic"); RecipeHandler.addRecipe(new VacuumFreezerRecipe(ItemIngots.getIngotByName("hot_tungstensteel"), ItemIngots.getIngotByName("tungstensteel"), 440, 128)); RecipeHandler.addRecipe(new VacuumFreezerRecipe(ItemCells.getCellByName("heliumplasma"), ItemCells.getCellByName("helium"), 440, 128)); RecipeHandler.addRecipe( new VacuumFreezerRecipe(ItemCells.getCellByName("water"), ItemCells.getCellByName("cell"), 60, 128)); } static void addVacuumFreezerRecipes() { RecipeHandler.addRecipe(new VacuumFreezerRecipe( new ItemStack(Blocks.ICE, 2), new ItemStack(Blocks.PACKED_ICE), 60, 100 )); RecipeHandler.addRecipe(new VacuumFreezerRecipe( ItemIngots.getIngotByName("hot_tungstensteel"), ItemIngots.getIngotByName("tungstensteel"), 440, 120)); RecipeHandler.addRecipe(new VacuumFreezerRecipe( ItemCells.getCellByName("heliumplasma"), ItemCells.getCellByName("helium"), 440, 128)); RecipeHandler.addRecipe( new VacuumFreezerRecipe( ItemCells.getCellByName("water"), ItemCells.getCellByName("cell"), 60, 87)); } static void addAlloySmelterRecipes() { // Bronze RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemIngots.getIngotByName("copper", 3), ItemIngots.getIngotByName("tin", 1), ItemIngots.getIngotByName("bronze", 4), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemIngots.getIngotByName("copper", 3), ItemDusts.getDustByName("tin", 1), ItemIngots.getIngotByName("bronze", 4), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("copper", 3), ItemIngots.getIngotByName("tin", 1), ItemIngots.getIngotByName("bronze", 4), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("copper", 3), ItemDusts.getDustByName("tin", 1), ItemIngots.getIngotByName("bronze", 4), 200, 16)); // Electrum RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.GOLD_INGOT, 1), ItemIngots.getIngotByName("silver", 1), ItemIngots.getIngotByName("electrum", 2), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.GOLD_INGOT, 1), ItemDusts.getDustByName("silver", 1), ItemIngots.getIngotByName("electrum", 2), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("gold", 1), ItemIngots.getIngotByName("silver", 1), ItemIngots.getIngotByName("electrum", 2), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("gold", 1), ItemDusts.getDustByName("silver", 1), ItemIngots.getIngotByName("electrum", 2), 200, 16)); // Invar RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.IRON_INGOT, 2), ItemIngots.getIngotByName("nickel", 1), ItemIngots.getIngotByName("invar", 3), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.IRON_INGOT, 2), ItemDusts.getDustByName("nickel", 1), ItemIngots.getIngotByName("invar", 3), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("iron", 2), ItemIngots.getIngotByName("nickel", 1), ItemIngots.getIngotByName("invar", 3), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("iron", 2), ItemDusts.getDustByName("nickel", 1), ItemIngots.getIngotByName("invar", 3), 200, 16)); // Brass if (OreUtil.doesOreExistAndValid("ingotBrass")) { ItemStack brassStack = getOre("ingotBrass"); brassStack.setCount(4); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemIngots.getIngotByName("copper", 3), ItemIngots.getIngotByName("zinc", 1), brassStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemIngots.getIngotByName("copper", 3), ItemDusts.getDustByName("zinc", 1), brassStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("copper", 3), ItemIngots.getIngotByName("zinc", 1), brassStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("copper", 3), ItemDusts.getDustByName("zinc", 1), brassStack, 200, 16)); } // Red Alloy if (OreUtil.doesOreExistAndValid("ingotRedAlloy")) { ItemStack redAlloyStack = getOre("ingotRedAlloy"); redAlloyStack.setCount(1); RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.REDSTONE, 4), ItemIngots.getIngotByName("copper", 1), redAlloyStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.REDSTONE, 4), new ItemStack(Items.IRON_INGOT, 1), redAlloyStack, 200, 16)); } // Blue Alloy if (OreUtil.doesOreExistAndValid("ingotBlueAlloy")) { ItemStack blueAlloyStack = getOre("ingotBlueAlloy"); blueAlloyStack.setCount(1); RecipeHandler.addRecipe(new AlloySmelterRecipe(ItemDusts.getDustByName("teslatite", 4), ItemIngots.getIngotByName("silver", 1), blueAlloyStack, 200, 16)); } // Blue Alloy if (OreUtil.doesOreExistAndValid("ingotPurpleAlloy") && OreUtil.doesOreExistAndValid("dustInfusedTeslatite")) { ItemStack purpleAlloyStack = getOre("ingotPurpleAlloy"); purpleAlloyStack.setCount(1); ItemStack infusedTeslatiteStack = getOre("ingotPurpleAlloy"); infusedTeslatiteStack.setCount(8); RecipeHandler.addRecipe(new AlloySmelterRecipe(ItemIngots.getIngotByName("redAlloy", 1), ItemIngots.getIngotByName("blueAlloy", 1), purpleAlloyStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.GOLD_INGOT, 1), infusedTeslatiteStack, purpleAlloyStack, 200, 16)); } // Aluminum Brass if (OreUtil.doesOreExistAndValid("ingotAluminumBrass")) { ItemStack aluminumBrassStack = getOre("ingotAluminumBrass"); aluminumBrassStack.setCount(4); RecipeHandler.addRecipe(new AlloySmelterRecipe(ItemIngots.getIngotByName("copper", 3), ItemIngots.getIngotByName("aluminum", 1), aluminumBrassStack, 200, 16)); RecipeHandler.addRecipe(new AlloySmelterRecipe(ItemIngots.getIngotByName("copper", 3), ItemDusts.getDustByName("aluminum", 1), aluminumBrassStack, 200, 16)); RecipeHandler.addRecipe(new AlloySmelterRecipe(ItemDusts.getDustByName("copper", 3), ItemIngots.getIngotByName("aluminum", 1), aluminumBrassStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("copper", 3), ItemDusts.getDustByName("aluminum", 1), aluminumBrassStack, 200, 16)); } // Manyullyn if (OreUtil.doesOreExistAndValid("ingotManyullyn") && OreUtil.doesOreExistAndValid("ingotCobalt") && OreUtil .doesOreExistAndValid("ingotArdite")) { ItemStack manyullynStack = getOre("ingotManyullyn"); manyullynStack.setCount(1); ItemStack cobaltStack = getOre("ingotCobalt"); cobaltStack.setCount(1); ItemStack arditeStack = getOre("ingotArdite"); arditeStack.setCount(1); RecipeHandler.addRecipe(new AlloySmelterRecipe(cobaltStack, arditeStack, manyullynStack, 200, 16)); } // Conductive Iron if (OreUtil.doesOreExistAndValid("ingotConductiveIron")) { ItemStack conductiveIronStack = getOre("ingotConductiveIron"); conductiveIronStack.setCount(1); RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.REDSTONE, 1), new ItemStack(Items.IRON_INGOT, 1), conductiveIronStack, 200, 16)); } // Redstone Alloy if (OreUtil.doesOreExistAndValid("ingotRedstoneAlloy") && OreUtil.doesOreExistAndValid("itemSilicon")) { ItemStack redstoneAlloyStack = getOre("ingotRedstoneAlloy"); redstoneAlloyStack.setCount(1); ItemStack siliconStack = getOre("itemSilicon"); siliconStack.setCount(1); RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.REDSTONE, 1), siliconStack, redstoneAlloyStack, 200, 16)); } // Pulsating Iron if (OreUtil.doesOreExistAndValid("ingotPhasedIron")) { ItemStack pulsatingIronStack = getOre("ingotPhasedIron"); pulsatingIronStack.setCount(1); RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.IRON_INGOT, 1), new ItemStack(Items.ENDER_PEARL, 1), pulsatingIronStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.IRON_INGOT, 1), ItemDusts.getDustByName("ender_pearl", 1), pulsatingIronStack, 200, 16)); } // Vibrant Alloy if (OreUtil.doesOreExistAndValid("ingotEnergeticAlloy") && OreUtil.doesOreExistAndValid("ingotPhasedGold")) { ItemStack energeticAlloyStack = getOre("ingotEnergeticAlloy"); energeticAlloyStack.setCount(1); ItemStack vibrantAlloyStack = getOre("ingotPhasedGold"); vibrantAlloyStack.setCount(1); RecipeHandler.addRecipe( new AlloySmelterRecipe(energeticAlloyStack, new ItemStack(Items.ENDER_PEARL, 1), vibrantAlloyStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(energeticAlloyStack, ItemDusts.getDustByName("ender_pearl", 1), vibrantAlloyStack, 200, 16)); } // Soularium if (OreUtil.doesOreExistAndValid("ingotSoularium")) { ItemStack soulariumStack = getOre("ingotSoularium"); soulariumStack.setCount(1); RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Blocks.SOUL_SAND, 1), new ItemStack(Items.GOLD_INGOT, 1), soulariumStack, 200, 16)); } } static void addBlastFurnaceRecipes() { RecipeHandler.addRecipe( new BlastFurnaceRecipe(ItemDusts.getDustByName("titanium"), null, ItemIngots.getIngotByName("titanium"), null, 3600, 120, 1500)); RecipeHandler.addRecipe(new BlastFurnaceRecipe(ItemDustsSmall.getSmallDustByName("titanium", 4), null, ItemIngots.getIngotByName("titanium"), null, 3600, 120, 1500)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(ItemDusts.getDustByName("aluminum"), null, ItemIngots.getIngotByName("aluminum"), null, 2200, 120, 1700)); RecipeHandler.addRecipe(new BlastFurnaceRecipe(ItemDustsSmall.getSmallDustByName("aluminum", 4), null, ItemIngots.getIngotByName("aluminum"), null, 2200, 120, 1700)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(ItemDusts.getDustByName("tungsten"), null, ItemIngots.getIngotByName("tungsten"), null, 18000, 120, 2500)); RecipeHandler.addRecipe(new BlastFurnaceRecipe(ItemDustsSmall.getSmallDustByName("tungsten", 4), null, ItemIngots.getIngotByName("tungsten"), null, 18000, 120, 2500)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(ItemDusts.getDustByName("chrome"), null, ItemIngots.getIngotByName("chrome"), null, 4420, 120, 1700)); RecipeHandler.addRecipe(new BlastFurnaceRecipe(ItemDustsSmall.getSmallDustByName("chrome", 4), null, ItemIngots.getIngotByName("chrome"), null, 4420, 120, 1700)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(ItemDusts.getDustByName("steel"), null, ItemIngots.getIngotByName("steel"), null, 2800, 120, 1000)); RecipeHandler.addRecipe(new BlastFurnaceRecipe(ItemDustsSmall.getSmallDustByName("steel", 4), null, ItemIngots.getIngotByName("steel"), null, 2800, 120, 1000)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(ItemDusts.getDustByName("galena", 2), null, ItemIngots.getIngotByName("silver"), ItemIngots.getIngotByName("lead"), 80, 120, 1500)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(new ItemStack(Items.IRON_INGOT), ItemDusts.getDustByName("coal", 2), ItemIngots.getIngotByName("steel"), ItemDusts.getDustByName("dark_ashes", 2), 500, 120, 1000)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(ItemIngots.getIngotByName("tungsten"), ItemIngots.getIngotByName("steel"), ItemIngots.getIngotByName("hot_tungstensteel"), ItemDusts.getDustByName("dark_ashes", 4), 500, 500, 3000)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(new ItemStack(Blocks.IRON_ORE), ItemDusts.getDustByName("calcite"), new ItemStack(Items.IRON_INGOT, 3), ItemDusts.getDustByName("dark_ashes"), 140, 120, 1000)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(BlockOre.getOreByName("Pyrite"), ItemDusts.getDustByName("calcite"), new ItemStack(Items.IRON_INGOT, 2), ItemDusts.getDustByName("dark_ashes"), 140, 120, 1000)); } static void addChemicalReactorRecipes() { RecipeHandler.addRecipe( new ChemicalReactorRecipe(ItemCells.getCellByName("calcium", 1), ItemCells.getCellByName("carbon", 1), ItemCells.getCellByName("calciumCarbonate", 2), 240, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(new ItemStack(Items.GOLD_NUGGET, 8), new ItemStack(Items.MELON, 1), new ItemStack(Items.SPECKLED_MELON, 1), 40, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(ItemCells.getCellByName("nitrogen", 1), ItemCells.getCellByName("carbon", 1), ItemCells.getCellByName("nitrocarbon", 2), 1500, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(ItemCells.getCellByName("carbon", 1), ItemCells.getCellByName("hydrogen", 4), ItemCells.getCellByName("methane", 5), 3500, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(ItemCells.getCellByName("sulfur", 1), ItemCells.getCellByName("sodium", 1), ItemCells.getCellByName("sodiumSulfide", 2), 100, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(new ItemStack(Items.BLAZE_POWDER, 1), new ItemStack(Items.ENDER_PEARL, 1), new ItemStack(Items.ENDER_EYE, 1), 40, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(new ItemStack(Items.GOLD_NUGGET, 8), new ItemStack(Items.CARROT, 1), new ItemStack(Items.GOLDEN_CARROT, 1), 40, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(ItemCells.getCellByName("glyceryl", 1), ItemCells.getCellByName("diesel", 4), ItemCells.getCellByName("nitroDiesel", 5), 1000, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(new ItemStack(Items.GOLD_INGOT, 8), new ItemStack(Items.APPLE, 1), new ItemStack(Items.GOLDEN_APPLE, 1), 40, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(new ItemStack(Blocks.GOLD_BLOCK, 8), new ItemStack(Items.APPLE, 1), new ItemStack(Items.GOLDEN_APPLE, 1, 1), 40, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(new ItemStack(Items.BLAZE_POWDER, 1), new ItemStack(Items.SLIME_BALL, 1), new ItemStack(Items.MAGMA_CREAM, 1), 40, 30)); } static void addIc2Recipes() { RebornCraftingHelper.addShapelessOreRecipe(new ItemStack(ModItems.MANUAL), IC2Duplicates.REFINED_IRON.getStackBasedOnConfig(), Items.BOOK); RebornCraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("machineParts", 16), "CSC", "SCS", "CSC", 'S', "ingotSteel", 'C', "circuitBasic"); RebornCraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("energyFlowCircuit", 4), "ATA", "LIL", "ATA", 'T', "ingotTungsten", 'I', "plateIridium", 'A', "circuitAdvanced", 'L', "lapotronCrystal"); RebornCraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("superconductor", 4), "CCC", "TIT", "EEE", 'E', "circuitMaster", 'C', ItemParts.getPartByName("heliumCoolantSimple"), 'T', "ingotTungsten", 'I', "plateIridium"); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.LAPOTRONIC_ORB), "LLL", "LPL", "LLL", 'L', "lapotronCrystal", 'P', "plateIridium"); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.INDUSTRIAL_SAWMILL), "PAP", "SSS", "ACA", 'P', IC2Duplicates.REFINED_IRON.getStackBasedOnConfig(), 'A', "circuitAdvanced", 'S', ItemParts.getPartByName("diamondSawBlade"), 'C', "machineBlockAdvanced"); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.CHARGE_O_MAT), "ETE", "COC", "EAE", 'E', "circuitMaster", 'T', ModItems.ENERGY_CRYSTAL, 'C', Blocks.CHEST, 'O', ModItems.LAPOTRONIC_ORB, 'A', "machineBlockAdvanced"); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.MATTER_FABRICATOR), "ETE", "AOA", "ETE", 'E', "circuitMaster", 'T', IC2Duplicates.EXTRACTOR.getStackBasedOnConfig(), 'A', BlockMachineFrames.getFrameByName("highlyAdvancedMachine", 1), 'O', ModItems.LAPOTRONIC_ORB); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.GAS_TURBINE), "IAI", "WGW", "IAI", 'I', "ingotInvar", 'A', "circuitAdvanced", 'W', getOre("ic2Windmill"), 'G', getOre("glassReinforced")); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.GAS_TURBINE), "IAI", "WGW", "IAI", 'I', "ingotAluminum", 'A', "circuitAdvanced", 'W', getOre("ic2Windmill"), 'G', getOre("glassReinforced")); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.SEMI_FLUID_GENERATOR), "III", "IHI", "CGC", 'I', "plateIron", 'H', ModBlocks.REINFORCED_GLASS, 'C', "circuitBasic", 'G', IC2Duplicates.GENERATOR.getStackBasedOnConfig()); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.SEMI_FLUID_GENERATOR), "AAA", "AHA", "CGC", 'A', "plateAluminum", 'H', ModBlocks.REINFORCED_GLASS, 'C', "circuitBasic", 'G', IC2Duplicates.GENERATOR.getStackBasedOnConfig()); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.DIESEL_GENERATOR), "III", "I I", "CGC", 'I', IC2Duplicates.REFINED_IRON.getStackBasedOnConfig(), 'C', "circuitBasic", 'G', IC2Duplicates.GENERATOR.getStackBasedOnConfig()); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.DIESEL_GENERATOR), "AAA", "A A", "CGC", 'A', "ingotAluminum", 'C', "circuitBasic", 'G', IC2Duplicates.GENERATOR.getStackBasedOnConfig()); // RebornCraftingHelper.addShapedOreRecipe(new // ItemStack(ModBlocks.magicalAbsorber), // "CSC", "IBI", "CAC", // 'C', "circuitMaster", // 'S', "craftingSuperconductor", // 'B', Blocks.beacon, // 'A', ModBlocks.magicEnergeyConverter, // 'I', "plateIridium"); // RebornCraftingHelper.addShapedOreRecipe(new // ItemStack(ModBlocks.magicEnergeyConverter), // "CTC", "PBP", "CLC", // 'C', "circuitAdvanced", // 'P', "platePlatinum", // 'B', Blocks.beacon, // 'L', "lapotronCrystal", // 'T', TechRebornAPI.recipeCompact.getItem("teleporter")); // RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.dragonEggEnergySiphoner), "CTC", "ISI", "CBC", 'I', // "plateIridium", 'C', "circuitBasic", // 'B', ModItems.lithiumBattery, 'S', ModBlocks.Supercondensator, 'T', ModBlocks.extractor); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.INDUSTRIAL_BLAST_FURNACE), "CHC", "HBH", "FHF", 'H', ItemParts.getPartByName("cupronickelHeatingCoil"), 'C', "circuitAdvanced", 'B', BlockMachineFrames.getFrameByName("advancedMachine", 1), 'F', IC2Duplicates.ELECTRICAL_FURNACE.getStackBasedOnConfig()); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.INDUSTRIAL_GRINDER), "ECG", "HHH", "CBC", 'E', ModBlocks.INDUSTRIAL_ELECTROLYZER, 'H', "craftingDiamondGrinder", 'C', "circuitAdvanced", 'B', "machineBlockAdvanced", 'G', IC2Duplicates.GRINDER.getStackBasedOnConfig()); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.IMPLOSION_COMPRESSOR), "ABA", "CPC", "ABA", 'A', ItemIngots.getIngotByName("advancedAlloy"), 'C', "circuitAdvanced", 'B', BlockMachineFrames.getFrameByName("advancedMachine", 1), 'P', IC2Duplicates.COMPRESSOR.getStackBasedOnConfig()); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.VACUUM_FREEZER), "SPS", "CGC", "SPS", 'S', "plateSteel", 'C', "circuitAdvanced", 'G', ModBlocks.REINFORCED_GLASS, 'P', IC2Duplicates.EXTRACTOR.getStackBasedOnConfig()); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.DISTILLATION_TOWER), "CMC", "PBP", "EME", 'E', ModBlocks.INDUSTRIAL_ELECTROLYZER, 'M', "circuitMaster", 'B', "machineBlockAdvanced", 'C', ModBlocks.INDUSTRIAL_CENTRIFUGE, 'P', IC2Duplicates.EXTRACTOR.getStackBasedOnConfig()); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.IRON_ALLOY_FURNACE), "III", "F F", "III", 'I', ItemIngots.getIngotByName("refined_iron"), 'F', new ItemStack(ModBlocks.IRON_FURNACE)); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.IRON_ALLOY_FURNACE), "III", "F F", "III", 'I', IC2Duplicates.REFINED_IRON.getStackBasedOnConfig(), 'F', IC2Duplicates.IRON_FURNACE.getStackBasedOnConfig()); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.CHEMICAL_REACTOR), "IMI", "CPC", "IEI", 'I', "ingotInvar", 'C', "circuitAdvanced", 'M', IC2Duplicates.EXTRACTOR.getStackBasedOnConfig(), 'P', IC2Duplicates.COMPRESSOR.getStackBasedOnConfig(), 'E', IC2Duplicates.EXTRACTOR.getStackBasedOnConfig()); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.ROLLING_MACHINE), "PCP", "MBM", "PCP", 'P', Blocks.PISTON, 'C', "circuitAdvanced", 'M', IC2Duplicates.COMPRESSOR.getStackBasedOnConfig(), 'B', "machineBlockBasic"); // RebornCraftingHelper.addShapedOreRecipe(new // ItemStack(ModBlocks.electricCraftingTable), // "ITI", "IBI", "ICI", // 'I', "plateIron", // 'C', "circuitAdvanced", // 'T', "crafterWood", // 'B', "machineBlockBasic"); // RebornCraftingHelper.addShapedOreRecipe(new // ItemStack(ModBlocks.electricCraftingTable), // "ATA", "ABA", "ACA", // 'A', "plateAluminum", // 'C', "circuitAdvanced", // 'T', "crafterWood", // 'B', "machineBlockBasic"); // RebornCraftingHelper.addShapedOreRecipe(new // ItemStack(ModBlocks.chunkLoader), // "SCS", "CMC", "SCS", // 'S', "plateSteel", // 'C', "circuitMaster", // 'M', new ItemStack(ModItems.parts, 1, 39)); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.LAPOTRONIC_SU), " L ", "CBC", " M ", 'L', IC2Duplicates.LVT.getStackBasedOnConfig(), 'C', "circuitAdvanced", 'M', IC2Duplicates.MVT.getStackBasedOnConfig(), 'B', ModBlocks.LSU_STORAGE); RebornCraftingHelper .addShapedOreRecipe(BlockMachineFrames.getFrameByName("highlyAdvancedMachine", 1), "CTC", "TBT", "CTC", 'C', "ingotChrome", 'T', "ingotTitanium", 'B', "machineBlockAdvanced"); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.MACHINE_CASINGS, 4, 0), "III", "CBC", "III", 'I', "plateIron", 'C', "circuitBasic", 'B', "machineBlockBasic"); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.MACHINE_CASINGS, 4, 1), "SSS", "CBC", "SSS", 'S', "plateSteel", 'C', "circuitAdvanced", 'B', "machineBlockAdvanced"); RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.MACHINE_CASINGS, 4, 2), "HHH", "CBC", "HHH", 'H', "ingotChrome", 'C', "circuitElite", 'B', BlockMachineFrames.getFrameByName("highlyAdvancedMachine", 1)); if (!CompatManager.isQuantumStorageLoaded) { RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.QUANTUM_CHEST), "DCD", "ATA", "DQD", 'D', ItemParts.getPartByName("dataOrb"), 'C', ItemParts.getPartByName("computerMonitor"), 'A', BlockMachineFrames.getFrameByName("highlyAdvancedMachine", 1), 'Q', ModBlocks.DIGITAL_CHEST, 'T', IC2Duplicates.COMPRESSOR.getStackBasedOnConfig()); } // RebornCraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.PlasmaGenerator), "PPP", "PTP", "CGC", 'P', // ItemPlates.getPlateByName("tungstensteel"), 'T', IC2Duplicates.HVT.getStackBasedOnConfig(), // 'G', IC2Duplicates.GENERATOR.getStackBasedOnConfig(), 'C', // "circuitMaster"); // Smetling RebornCraftingHelper .addSmelting(ItemDusts.getDustByName("copper", 1), getOre("ingotCopper"), 1F); RebornCraftingHelper .addSmelting(ItemDusts.getDustByName("tin", 1), ItemIngots.getIngotByName("tin"), 1F); RebornCraftingHelper .addSmelting(ItemDusts.getDustByName("bronze", 1), ItemIngots.getIngotByName("bronze"), 1F); RebornCraftingHelper .addSmelting(ItemDusts.getDustByName("lead", 1), ItemIngots.getIngotByName("lead"), 1F); RebornCraftingHelper .addSmelting(ItemDusts.getDustByName("silver", 1), ItemIngots.getIngotByName("silver"), 1F); RebornCraftingHelper .addShapedOreRecipe((getOre("oreIridium")), "UUU", " U ", "UUU", 'U', ModItems.UU_MATTER); // Chemical Reactor RecipeHandler.addRecipe(new ChemicalReactorRecipe(ItemDusts.getDustByName("calcite", 1), null, new ItemStack(getOre("fertilizer").getItem(), 1), 100, 30)); RecipeHandler.addRecipe(new ChemicalReactorRecipe(ItemDusts.getDustByName("calcite", 1), ItemDusts.getDustByName("phosphorous", 1), new ItemStack(getOre("fertilizer").getItem(), 3), 100, 30)); RecipeHandler.addRecipe(new ChemicalReactorRecipe(ItemCells.getCellByName("sodiumSulfide", 1), ItemCells.getCellByName("empty"), ItemCells.getCellByName("sodiumPersulfate", 2), 2000, 30)); RecipeHandler.addRecipe(new ChemicalReactorRecipe(ItemCells.getCellByName("nitrocarbon", 1), ItemCells.getCellByName("water"), ItemCells.getCellByName("glyceryl", 2), 580, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(ItemDusts.getDustByName("calcite", 1), ItemDusts.getDustByName("sulfur", 1), new ItemStack(getOre("fertilizer").getItem(), 2), 100, 30)); ItemStack waterCells = ItemCells.getCellByName("water").copy(); waterCells.setCount(2); RecipeHandler.addRecipe(new ChemicalReactorRecipe(ItemCells.getCellByName("sulfur", 1), waterCells, ItemCells.getCellByName("sulfuricAcid", 3), 1140, 30)); ItemStack waterCells2 = ItemCells.getCellByName("water").copy(); waterCells2.setCount(5); RecipeHandler.addRecipe(new ChemicalReactorRecipe(ItemCells.getCellByName("hydrogen", 4), ItemCells.getCellByName("empty"), waterCells2, 10, 30)); RecipeHandler.addRecipe(new ChemicalReactorRecipe(ItemCells.getCellByName("nitrogen", 1), ItemCells.getCellByName("empty"), ItemCells.getCellByName("nitrogenDioxide", 2), 1240, 30)); if (!IC2Duplicates.deduplicate()) RebornCraftingHelper .addShapedOreRecipe(getOre("ic2Macerator"), "FDF", "DMD", "FCF", 'F', Items.FLINT, 'D', Items.DIAMOND, 'M', "machineBlockBasic", 'C', "circuitBasic"); if (!IC2Duplicates.deduplicate()) RebornCraftingHelper .addShapedOreRecipe(IC2Duplicates.SOLAR_PANEL.getStackBasedOnConfig(), "PPP", "SZS", "CGC", 'P', "paneGlass", 'S', "plateLazurite", 'Z', "plateCarbon", 'G', IC2Duplicates.GENERATOR.getStackBasedOnConfig(), 'C', "circuitBasic"); RebornCraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("iridium_alloy"), "IAI", "ADA", "IAI", 'I', "ingotIridium", 'D', ItemDusts.getDustByName("diamond"), 'A', "plateAdvancedAlloy"); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.LITHIUM_BATTERY_PACK, 1, OreDictionary.WILDCARD_VALUE), "BCB", "BPB", "B B", 'B', new ItemStack(ModItems.LITHIUM_BATTERY), 'P', "plateAluminum", 'C', "circuitAdvanced"); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.LITHIUM_BATTERY, 1, OreDictionary.WILDCARD_VALUE), " C ", "PFP", "PFP", 'F', ItemCells.getCellByName("lithium"), 'P', "plateAluminum", 'C', IC2Duplicates.CABLE_IGOLD.getStackBasedOnConfig()); RebornCraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.LAPOTRONIC_ORB_PACK, 1, OreDictionary.WILDCARD_VALUE), "FOF", "SPS", "FIF", 'F', "circuitMaster", 'O', new ItemStack(ModItems.LAPOTRONIC_ORB), 'S', ItemParts.getPartByName("superConductor"), 'I', "ingotIridium", 'P', new ItemStack(ModItems.LITHIUM_BATTERY_PACK)); } public static ItemStack getBucketWithFluid(Fluid fluid) { return UniversalBucket.getFilledBucket(ForgeModContainer.getInstance().universalBucket, fluid); } public static ItemStack getOre(String name) { if (OreDictionary.getOres(name).isEmpty()) { return new ItemStack(ModItems.MISSING_RECIPE_PLACEHOLDER); } return OreDictionary.getOres(name).get(0).copy(); } }
package cx2x.translator.language; import cx2x.xcodeml.helper.XnodeUtil; import cx2x.xcodeml.xnode.*; /** * Class holding information about defined dimension. * * @author clementval */ public class ClawDimension { private final int _lowerBound; private final int _upperBound; private final String _lowerBoundId; private final String _upperBoundId; private final String _identifier; private String _lowerBoundType; private String _upperBoundType; public static final String BASE_DIM = ":"; /** * Constructs a new dimension object from the extracted information. * @param id Identifier of the defined dimension. * @param lowerBound Lower bound of the dimension. * @param upperBound Upper bound of the dimension. * TODO maybe add step information (in the grammar as well) */ public ClawDimension(String id, String lowerBound, String upperBound){ _identifier = id; int tempLb, tempUb; String tempLbStr, tempUbStr; try { tempLb = Integer.parseInt(lowerBound); tempLbStr = null; } catch (NumberFormatException ex){ tempLb = -1; tempLbStr = lowerBound; } try { tempUb = Integer.parseInt(upperBound); tempUbStr = null; } catch (NumberFormatException ex){ tempUb = -1; tempUbStr = upperBound; } _lowerBound = tempLb; _upperBound = tempUb; _lowerBoundId = tempLbStr; _upperBoundId = tempUbStr; } /** * Check whether lower bound is an identifier variable. * @return True if the lower bound is an identifier variable. */ public boolean lowerBoundIsVar(){ return _lowerBoundId != null; } /** * Check whether upper bound is an identifier variable. * @return True if the upper bound is an identifier variable. */ public boolean upperBoundIsVar(){ return _upperBoundId != null; } /** * @return Lower bound value. -1 if lower bound is an identifier variable. */ public int getLowerBoundInt(){ return _lowerBound; } /** * @return Upper bound value. -1 if upper bound is an identifier variable. */ public int getUpperBoundInt(){ return _upperBound; } /** * @return Lower bound value. Null if lower bound is an integer constant. */ public String getLowerBoundId(){ return _lowerBoundId; } /** * @return Upper bound value. Null if upper bound is an integer constant. */ public String getUpperBoundId(){ return _upperBoundId; } /** * Get the identifier for the current dimension. * @return The identifier of the current dimension. */ public String getIdentifier(){ return _identifier; } /** * Set the value of upper bound var. * @param value Type value. */ public void setUpperBoundType(String value){ _upperBoundType = value; } /** * Set the value of lower bound var. * @param value Type value. */ public void setLowerBoundType(String value){ _lowerBoundType = value; } /** * Generate the correct indexRange element with lowerBound, upperBound and * step from the current dimension. * @param xcodeml Current XcodeML program unit in which elements will be * created. * @param withStep IF true, step element is created. * @return A new indexRange elements. */ public Xnode generateIndexRange(XcodeProgram xcodeml, boolean withStep) { Xnode range = new Xnode(Xcode.INDEXRANGE, xcodeml); Xnode lower = new Xnode(Xcode.LOWERBOUND, xcodeml); Xnode upper = new Xnode(Xcode.UPPERBOUND, xcodeml); range.appendToChildren(lower, false); range.appendToChildren(upper, false); if (withStep){ Xnode step = new Xnode(Xcode.STEP, xcodeml); Xnode stepValue = new Xnode(Xcode.FINTCONSTANT, xcodeml); stepValue.setAttribute(Xattr.TYPE, Xname.TYPE_F_INT); step.appendToChildren(stepValue, false); stepValue.setValue(Xname.DEFAULT_STEP_VALUE); range.appendToChildren(step, false); } // lower bound if(lowerBoundIsVar()){ if(_lowerBoundType == null){ _lowerBoundType = xcodeml.getTypeTable().generateIntegerTypeHash(); XbasicType bType = XnodeUtil.createBasicType(xcodeml, _lowerBoundType, Xname.TYPE_F_INT, Xintent.IN); xcodeml.getTypeTable().add(bType); } Xnode lowerBoundValue = XnodeUtil.createVar(_lowerBoundType, _lowerBoundId, Xscope.LOCAL, xcodeml); lower.appendToChildren(lowerBoundValue, false); } else { Xnode lowerBoundValue = new Xnode(Xcode.FINTCONSTANT, xcodeml); lowerBoundValue.setAttribute(Xattr.TYPE, Xname.TYPE_F_INT); lowerBoundValue.setValue(String.valueOf(_lowerBound)); lower.appendToChildren(lowerBoundValue, false); } // upper bound if(upperBoundIsVar()){ if(_lowerBoundType == null){ _upperBoundType = xcodeml.getTypeTable().generateIntegerTypeHash(); XbasicType bType = XnodeUtil.createBasicType(xcodeml, _upperBoundType, Xname.TYPE_F_INT, Xintent.IN); xcodeml.getTypeTable().add(bType); } Xnode upperBoundValue = XnodeUtil.createVar(_upperBoundType, _upperBoundId, Xscope.LOCAL, xcodeml); upper.appendToChildren(upperBoundValue, false); } else { Xnode upperBoundValue = new Xnode(Xcode.FINTCONSTANT, xcodeml); upperBoundValue.setAttribute(Xattr.TYPE, Xname.TYPE_F_INT); upperBoundValue.setValue(String.valueOf(_upperBound)); lower.appendToChildren(upperBoundValue, false); } return range; } /** * Generate the array index that will be placed in the array reference for * this additional dimension. * @param xcodeml Current XcodeML program unit in which elements will be * created. * @return A new arrayIndex element including a var element with the dimension * identifier. */ public Xnode generateArrayIndex(XcodeProgram xcodeml) { Xnode aIdx = new Xnode(Xcode.ARRAYINDEX, xcodeml); Xnode var = XnodeUtil.createVar(Xname.TYPE_F_INT, _identifier, Xscope.LOCAL, xcodeml); aIdx.appendToChildren(var, false); return aIdx; } }
package org.jgrapes.portal; import freemarker.template.Configuration; import freemarker.template.SimpleScalar; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; import freemarker.template.TemplateMethodModelEx; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PipedReader; import java.io.PipedWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.nio.CharBuffer; import java.security.Principal; import java.text.Collator; import java.text.ParseException; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.Optional; import java.util.ResourceBundle; import java.util.ServiceLoader; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.StreamSupport; import javax.json.Json; import javax.json.JsonReader; import org.jdrupes.httpcodec.protocols.http.HttpConstants.HttpStatus; import org.jdrupes.httpcodec.protocols.http.HttpField; import org.jdrupes.httpcodec.protocols.http.HttpRequest; import org.jdrupes.httpcodec.protocols.http.HttpResponse; import org.jdrupes.httpcodec.types.Converters; import org.jdrupes.httpcodec.types.Directive; import org.jdrupes.httpcodec.types.MediaType; import org.jdrupes.json.JsonDecodeException; import org.jgrapes.core.Channel; import org.jgrapes.core.CompletionLock; import org.jgrapes.core.Component; import org.jgrapes.core.annotation.Handler; import org.jgrapes.core.events.Error; import org.jgrapes.http.LanguageSelector.Selection; import org.jgrapes.http.Session; import org.jgrapes.http.annotation.RequestHandler; import org.jgrapes.http.events.GetRequest; import org.jgrapes.http.events.Response; import org.jgrapes.http.events.WebSocketAccepted; import org.jgrapes.io.IOSubchannel; import org.jgrapes.io.events.Closed; import org.jgrapes.io.events.Input; import org.jgrapes.io.events.Output; import org.jgrapes.io.util.ByteBufferOutputStream; import org.jgrapes.io.util.CharBufferWriter; import org.jgrapes.io.util.InputStreamPipeline; import org.jgrapes.io.util.LinkedIOSubchannel; import org.jgrapes.io.util.ManagedCharBuffer; import org.jgrapes.portal.events.JsonInput; import org.jgrapes.portal.events.JsonOutput; import org.jgrapes.portal.events.PortalReady; import org.jgrapes.portal.events.PortletResourceRequest; import org.jgrapes.portal.events.PortletResourceResponse; import org.jgrapes.portal.events.SetLocale; import org.jgrapes.portal.events.SetTheme; import org.jgrapes.portal.themes.base.Provider; import org.jgrapes.util.events.KeyValueStoreData; import org.jgrapes.util.events.KeyValueStoreQuery; import org.jgrapes.util.events.KeyValueStoreUpdate; public class PortalView extends Component { private Portal portal; private ServiceLoader<ThemeProvider> themeLoader; private static Configuration fmConfig = null; private Function<Locale,ResourceBundle> resourceBundleSupplier; private BiFunction<ThemeProvider,String,InputStream> fallbackResourceSupplier = (themeProvider, resource) -> { return null; }; private Set<Locale> supportedLocales; private ThemeProvider baseTheme; private Map<String,Object> portalBaseModel = new HashMap<>(); private RenderSupport renderSupport = new RenderSupportImpl(); /** * @param componentChannel */ public PortalView(Portal portal, Channel componentChannel) { super(componentChannel); this.portal = portal; if (fmConfig == null) { fmConfig = new Configuration(Configuration.VERSION_2_3_26); fmConfig.setClassLoaderForTemplateLoading( getClass().getClassLoader(), "org/jgrapes/portal"); fmConfig.setDefaultEncoding("utf-8"); fmConfig.setTemplateExceptionHandler( TemplateExceptionHandler.RETHROW_HANDLER); fmConfig.setLogTemplateExceptions(false); } baseTheme = new Provider(); supportedLocales = new HashSet<>(); for (Locale locale: Locale.getAvailableLocales()) { if (locale.getLanguage().equals("")) { continue; } if (resourceBundleSupplier != null) { ResourceBundle rb = resourceBundleSupplier.apply(locale); if (rb.getLocale().equals(locale)) { supportedLocales.add(locale); } } ResourceBundle rb = ResourceBundle.getBundle(getClass() .getPackage().getName() + ".l10n", locale); if (rb.getLocale().equals(locale)) { supportedLocales.add(locale); } } RequestHandler.Evaluator.add(this, "onGet", portal.prefix() + "**"); RequestHandler.Evaluator.add(this, "onGetRedirect", portal.prefix().getPath().substring( 0, portal.prefix().getPath().length() - 1)); // Create portal model portalBaseModel.put("resourceUrl", new TemplateMethodModelEx() { @Override public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { @SuppressWarnings("unchecked") List<TemplateModel> args = (List<TemplateModel>)arguments; if (!(args.get(0) instanceof SimpleScalar)) { throw new TemplateModelException("Not a string."); } return portal.prefix().resolve( ((SimpleScalar)args.get(0)).getAsString()).getRawPath(); } }); portalBaseModel = Collections.unmodifiableMap(portalBaseModel); // Handlers attached to the portal side channel Handler.Evaluator.add(this, "onPortalReady", portal.channel()); Handler.Evaluator.add(this, "onKeyValueStoreData", portal.channel()); Handler.Evaluator.add( this, "onPortletResourceResponse", portal.channel()); Handler.Evaluator.add(this, "onJsonOutput", portal.channel()); Handler.Evaluator.add(this, "onSetLocale", portal.channel()); Handler.Evaluator.add(this, "onSetTheme", portal.channel()); } /** * The service loader must be created lazily, else the OSGi * service mediator doesn't work properly. * * @return */ private ServiceLoader<ThemeProvider> themeLoader() { if (themeLoader != null) { return themeLoader; } return themeLoader = ServiceLoader.load(ThemeProvider.class); } void setResourceBundleSupplier( Function<Locale,ResourceBundle> supplier) { this.resourceBundleSupplier = supplier; } void setFallbackResourceSupplier( BiFunction<ThemeProvider,String,InputStream> supplier) { this.fallbackResourceSupplier = supplier; } RenderSupport renderSupport() { return renderSupport; } private LinkedIOSubchannel portalChannel(IOSubchannel channel) { @SuppressWarnings("unchecked") Optional<LinkedIOSubchannel> portalChannel = (Optional<LinkedIOSubchannel>)LinkedIOSubchannel .downstreamChannel(portal, channel); return portalChannel.orElseGet( () -> new LinkedIOSubchannel(portal, channel)); } @RequestHandler(dynamic=true) public void onGetRedirect(GetRequest event, IOSubchannel channel) throws InterruptedException, IOException, ParseException { HttpResponse response = event.httpRequest().response().get(); response.setStatus(HttpStatus.MOVED_PERMANENTLY) .setContentType("text", "plain", "utf-8") .setField(HttpField.LOCATION, portal.prefix()); fire(new Response(response), channel); try { fire(Output.wrap(portal.prefix().toString() .getBytes("utf-8"), true), channel); } catch (UnsupportedEncodingException e) { // Supported by definition } event.stop(); } @RequestHandler(dynamic=true) public void onGet(GetRequest event, IOSubchannel channel) throws InterruptedException, IOException { URI requestUri = event.requestUri(); // Append trailing slash, if missing if ((requestUri.getRawPath() + "/").equals( portal.prefix().getRawPath())) { requestUri = portal.prefix(); } // Request for portal? if (!requestUri.getRawPath().startsWith(portal.prefix().getRawPath())) { return; } // Normalize and evaluate requestUri = portal.prefix().relativize( URI.create(requestUri.getRawPath())); if (requestUri.getRawPath().isEmpty()) { if (event.httpRequest().findField( HttpField.UPGRADE, Converters.STRING_LIST) .map(f -> f.value().containsIgnoreCase("websocket")) .orElse(false)) { channel.setAssociated(this, new PortalInfo()); channel.respond(new WebSocketAccepted(event)); event.stop(); return; } renderPortal(event, channel); return; } URI subUri = uriFromPath("portal-resource/").relativize(requestUri); if (!subUri.equals(requestUri)) { sendPortalResource(event, channel, subUri.getPath()); return; } subUri = uriFromPath("theme-resource/").relativize(requestUri); if (!subUri.equals(requestUri)) { sendThemeResource(event, channel, subUri.getPath()); return; } subUri = uriFromPath("portlet-resource/").relativize(requestUri); if (!subUri.equals(requestUri)) { requestPortletResource(event, channel, subUri); return; } } private void renderPortal(GetRequest event, IOSubchannel channel) throws IOException, InterruptedException { event.stop(); // Because language is changed via websocket, locale cookie // may be out-dated event.associated(Selection.class) .ifPresent(s -> s.prefer(s.get()[0])); // Prepare response HttpResponse response = event.httpRequest().response().get(); MediaType mediaType = MediaType.builder().setType("text", "html") .setParameter("charset", "utf-8").build(); response.setField(HttpField.CONTENT_TYPE, mediaType); response.setStatus(HttpStatus.OK); response.setHasPayload(true); channel.respond(new Response(response)); try (Writer out = new OutputStreamWriter(new ByteBufferOutputStream( channel, channel.responsePipeline()), "utf-8")) { Map<String,Object> portalModel = new HashMap<>(portalBaseModel); // Add locale final Locale locale = event.associated(Selection.class).map( s -> s.get()[0]).orElse(Locale.getDefault()); portalModel.put("locale", locale); // Add supported locales final Collator coll = Collator.getInstance(locale); final Comparator<LanguageInfo> comp = new Comparator<PortalView.LanguageInfo>() { @Override public int compare(LanguageInfo o1, LanguageInfo o2) { return coll.compare(o1.getLabel(), o2.getLabel()); } }; LanguageInfo[] languages = supportedLocales.stream() .map(l -> new LanguageInfo(l)) .sorted(comp).toArray(size -> new LanguageInfo[size]); portalModel.put("supportedLanguages", languages); // Add localization final ResourceBundle additionalResources = resourceBundleSupplier == null ? null : resourceBundleSupplier.apply(locale); final ResourceBundle baseResources = ResourceBundle.getBundle( getClass().getPackage().getName() + ".l10n", locale, ResourceBundle.Control.getNoFallbackControl( ResourceBundle.Control.FORMAT_DEFAULT)); portalModel.put("_", new TemplateMethodModelEx() { @Override public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { @SuppressWarnings("unchecked") List<TemplateModel> args = (List<TemplateModel>)arguments; if (!(args.get(0) instanceof SimpleScalar)) { throw new TemplateModelException("Not a string."); } String key = ((SimpleScalar)args.get(0)).getAsString(); try { return additionalResources.getString(key); } catch (MissingResourceException e) { // try base resources } try { return baseResources.getString(key); } catch (MissingResourceException e) { // no luck } return key; } }); // Add themes. Doing this on every reload allows themes // to be added dynamically. Note that we must load again // (not reload) in order for this to work in an OSGi environment. themeLoader = ServiceLoader.load(ThemeProvider.class); portalModel.put("themeInfos", StreamSupport.stream(themeLoader().spliterator(), false) .map(t -> new ThemeInfo(t.themeId(), t.themeName())) .sorted().toArray(size -> new ThemeInfo[size])); Template tpl = fmConfig.getTemplate("portal.ftlh"); tpl.process(portalModel, out); } catch (TemplateException e) { throw new IOException(e); } } private void sendPortalResource(GetRequest event, IOSubchannel channel, String resource) { // Look for content InputStream in = this.getClass().getResourceAsStream(resource); if (in == null) { return; } // Send header HttpResponse response = event.httpRequest().response().get(); prepareResourceResponse(response, event.requestUri()); channel.respond(new Response(response)); // Send content activeEventPipeline().executorService() .submit(new InputStreamPipeline(in, channel)); // Done event.stop(); } private void sendThemeResource(GetRequest event, IOSubchannel channel, String resource) { // Get resource ThemeProvider themeProvider = event.associated(Session.class).flatMap( session -> Optional.ofNullable(session.get("themeProvider")).flatMap( themeId -> StreamSupport .stream(themeLoader().spliterator(), false) .filter(t -> t.themeId().equals(themeId)).findFirst() )).orElse(baseTheme); InputStream resIn; try { resIn = themeProvider.getResourceAsStream(resource); } catch (ResourceNotFoundException e) { try { resIn = baseTheme.getResourceAsStream(resource); } catch (ResourceNotFoundException e1) { resIn = fallbackResourceSupplier.apply(themeProvider, resource); if (resIn == null) { return; } } } // Send header HttpResponse response = event.httpRequest().response().get(); prepareResourceResponse(response, event.requestUri()); channel.respond(new Response(response)); // Send content activeEventPipeline().executorService() .submit(new InputStreamPipeline(resIn, channel)); // Done event.stop(); } public static void prepareResourceResponse( HttpResponse response, URI request) { response.setContentType(request); // Set max age in cache-control header List<Directive> directives = new ArrayList<>(); directives.add(new Directive("max-age", 600)); response.setField(HttpField.CACHE_CONTROL, directives); response.setField(HttpField.LAST_MODIFIED, Instant.now()); response.setStatus(HttpStatus.OK); } private void requestPortletResource(GetRequest event, IOSubchannel channel, URI resource) throws InterruptedException { String resPath = resource.getPath(); int sep = resPath.indexOf('/'); // Send events to portlets on portal's channel if (Boolean.TRUE.equals(newEventPipeline().fire( new PortletResourceRequest(resPath.substring(0, sep), uriFromPath(resPath.substring(sep + 1)), event.httpRequest(), channel), portalChannel(channel)) .get())) { event.stop(); } } @Handler public void onInput(Input<ManagedCharBuffer> event, IOSubchannel channel) throws IOException { Optional<PortalInfo> optPortalInfo = channel.associated(this, PortalInfo.class); if (!optPortalInfo.isPresent()) { return; } optPortalInfo.get().toEvent(portalChannel(channel), event.buffer().backingBuffer(), event.isEndOfRecord()); } /** * Forward the {@link Closed} event to the portal channel. * * @param event the event * @param channel the channel */ @Handler public void onClosed(Closed event, IOSubchannel channel) { fire(new Closed(), portalChannel(channel)); } @Handler(dynamic=true) public void onPortalReady(PortalReady event, IOSubchannel channel) { String principal = channel.associated(Session.class).map(session -> session.getOrDefault(Principal.class, "").toString()) .orElse(""); KeyValueStoreQuery query = new KeyValueStoreQuery( "/" + principal + "/themeProvider", true); channel.setAssociated(this, new CompletionLock(event, 3000)); fire(query, channel); } @Handler(dynamic=true) public void onKeyValueStoreData( KeyValueStoreData event, IOSubchannel channel) throws JsonDecodeException { Optional<Session> optSession = channel.associated(Session.class); if (!optSession.isPresent()) { return; } Session session = optSession.get(); String principal = session.getOrDefault(Principal.class, "").toString(); if (!event.event().query().equals("/" + principal + "/themeProvider")) { return; } channel.associated(this, CompletionLock.class) .ifPresent(lock -> lock.remove()); if (!event.data().values().iterator().hasNext()) { return; } String requestedThemeId = event.data().values().iterator().next(); ThemeProvider themeProvider = Optional.ofNullable( session.get("themeProvider")).flatMap( themeId -> StreamSupport .stream(themeLoader().spliterator(), false) .filter(t -> t.themeId().equals(themeId)).findFirst() ).orElse(baseTheme); if (!themeProvider.themeId().equals(requestedThemeId)) { fire(new SetTheme(requestedThemeId), channel); } } @Handler(dynamic=true) public void onPortletResourceResponse(PortletResourceResponse event, LinkedIOSubchannel channel) { HttpRequest request = event.request().httpRequest(); // Send header HttpResponse response = request.response().get(); prepareResourceResponse(response, request.requestUri()); channel.upstreamChannel().respond(new Response(response)); // Send content activeEventPipeline().executorService().submit( new InputStreamPipeline( event.stream(), channel.upstreamChannel())); } @Handler(dynamic=true) public void onSetLocale(SetLocale event, LinkedIOSubchannel channel) throws InterruptedException, IOException { supportedLocales.stream() .filter(l -> l.equals(event.locale())).findFirst() .ifPresent(l -> channel.associated(Selection.class) .map(s -> s.prefer(l))); fire(new JsonOutput("reload"), channel); } @Handler(dynamic=true) public void onSetTheme(SetTheme event, LinkedIOSubchannel channel) throws InterruptedException, IOException { ThemeProvider themeProvider = StreamSupport .stream(themeLoader().spliterator(), false) .filter(t -> t.themeId().equals(event.theme())).findFirst() .orElse(baseTheme); Optional<Session> optSession = channel.associated(Session.class); if (optSession.isPresent()) { Session session = optSession.get(); session.put("themeProvider", themeProvider.themeId()); channel.respond(new KeyValueStoreUpdate().update( "/" + session.getOrDefault(Principal.class, "").toString() + "/themeProvider", themeProvider.themeId())).get(); } fire(new JsonOutput("reload"), channel); } @Handler(dynamic=true) public void onJsonOutput(JsonOutput event, LinkedIOSubchannel channel) throws InterruptedException, IOException { IOSubchannel upstream = channel.upstreamChannel(); @SuppressWarnings("resource") CharBufferWriter out = new CharBufferWriter(upstream, upstream.responsePipeline()).suppressClose(); event.toJson(out); out.close(); } private class PortalInfo { private PipedWriter decodeWriter; public void toEvent(IOSubchannel channel, CharBuffer buffer, boolean last) throws IOException { if (decodeWriter == null) { decodeWriter = new PipedWriter(); PipedReader reader = new PipedReader( decodeWriter, buffer.capacity()); activeEventPipeline().executorService() .submit(new DecodeTask(reader, channel)); } decodeWriter.append(buffer); if (last) { decodeWriter.close(); decodeWriter = null; } } private class DecodeTask implements Runnable { IOSubchannel channel; private Reader reader; public DecodeTask(Reader reader, IOSubchannel channel) { this.reader = reader; this.channel = channel; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { try (Reader in = reader) { JsonReader reader = Json.createReader(in); fire(new JsonInput(reader.readObject()), channel); } catch (Throwable e) { fire(new Error(null, e)); } } } } public static class LanguageInfo { private Locale locale; /** * @param locale */ public LanguageInfo(Locale locale) { this.locale = locale; } /** * @return the locale */ public Locale getLocale() { return locale; } public String getLabel() { String str = locale.getDisplayName(locale); return Character.toUpperCase(str.charAt(0)) + str.substring(1); } } public static class ThemeInfo implements Comparable<ThemeInfo> { private String id; private String name; /** * @param id * @param name */ public ThemeInfo(String id, String name) { super(); this.id = id; this.name = name; } /** * @return the id */ public String id() { return id; } /** * @return the name */ public String name() { return name; } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(ThemeInfo other) { return name().compareToIgnoreCase(other.name()); } } public static URI uriFromPath(String path) throws IllegalArgumentException { try { return new URI(null, null, path, null); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } private class RenderSupportImpl implements RenderSupport { /* (non-Javadoc) * @see org.jgrapes.portal.RenderSupport#portletResource(java.lang.String, java.net.URI) */ @Override public URI portletResource(String portletType, URI uri) { return portal.prefix().resolve(uriFromPath( "portlet-resource/" + portletType + "/")).resolve(uri); } } }
package com.wonderpush.sdk; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import com.wonderpush.sdk.inappmessaging.model.Campaign; import com.wonderpush.sdk.inappmessaging.model.InAppMessage; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; public abstract class NotificationModel implements Parcelable { private static final String TAG = WonderPush.TAG; static final long DEFAULT_LAST_RECEIVED_NOTIFICATION_CHECK_DELAY = 7 * 86400 * 1000; public static class NotTargetedForThisInstallationException extends Exception { private static final long serialVersionUID = -1642569383307930845L; public NotTargetedForThisInstallationException(String detailMessage) { super(detailMessage); } } interface Builder { NotificationModel build(String inputJSONString); } enum Type { SIMPLE("simple", new Builder() { @Override public NotificationModel build(String inputJSONString) { return new NotificationSimpleModel(inputJSONString); } }), DATA("data", new Builder() { @Override public NotificationModel build(String inputJSONString) { return new NotificationDataModel(inputJSONString); } }), TEXT("text", new Builder() { @Override public NotificationModel build(String inputJSONString) { return new NotificationTextModel(inputJSONString); } }), HTML("html", new Builder() { @Override public NotificationModel build(String inputJSONString) { return new NotificationHtmlModel(inputJSONString); } }), MAP("map", new Builder() { @Override public NotificationModel build(String inputJSONString) { return new NotificationMapModel(inputJSONString); } }), URL("url", new Builder() { @Override public NotificationModel build(String inputJSONString) { return new NotificationUrlModel(inputJSONString); } }), ; private final String type; private final Builder builder; Type(String type, Builder builder) { this.type = type; this.builder = builder; } @Override public String toString() { return type; } public Builder getBuilder() { return builder; } public static Type fromString(String type) { if (type == null) { throw new NullPointerException(); } for (Type notificationType : Type.values()) { if (type.equals(notificationType.toString())) { return notificationType; } } throw new IllegalArgumentException("Constant \"" + type + "\" is not a known notification type"); } } public static final Creator<NotificationModel> CREATOR = new Creator<NotificationModel>() { @Override public NotificationModel createFromParcel(Parcel in) { String json = in.readString(); try { JSONObject parsed = new JSONObject(json); return NotificationModel.fromNotificationJSONObject(parsed); } catch (NotTargetedForThisInstallationException e) { Log.e(WonderPush.TAG, "Unexpected error: Cannot unparcel notification, not targeted at this installation", e); } catch (JSONException e) { Log.e(WonderPush.TAG, "Unexpected error: Cannot parse notification " + json, e); } return null; } @Override public NotificationModel[] newArray(int size) { return new NotificationModel[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(inputJSONString); } private final String inputJSONString; private String targetedInstallation; private long lastReceivedNotificationCheckDelay; private String campaignId; private String notificationId; private String viewId; private JSONObject reporting; private Type type; private AlertModel alert; private String targetUrl; public List<ActionModel> receiveActions = new ArrayList<>(); public List<ActionModel> actions = new ArrayList<>(); private boolean receipt; private boolean receiptUsingMeasurements; private InAppMessage inAppMessage; // Common in-app message data private final AtomicReference<ButtonModel> choice = new AtomicReference<>(); private final List<ButtonModel> buttons = new ArrayList<>(3); private String title; public static NotificationModel fromLocalIntent(Intent intent, Context context) { if (NotificationManager.containsExplicitNotification(intent)) { String notifString = intent.getData().getQueryParameter(WonderPush.INTENT_NOTIFICATION_QUERY_PARAMETER); if (notifString == null) { return null; } try { JSONObject notifParsed = new JSONObject(notifString); return NotificationModel.fromNotificationJSONObject(notifParsed); } catch (JSONException e) { WonderPush.logDebug("data is not a well-formed JSON object", e); } catch (NotTargetedForThisInstallationException e) { WonderPush.logError("Notifications not targeted for this installation should have been filtered earlier", e); } } else if (NotificationManager.containsWillOpenNotification(intent)) { NotificationModel notif = intent.getParcelableExtra(WonderPush.INTENT_NOTIFICATION_WILL_OPEN_EXTRA_NOTIFICATION_MODEL); return notif; } return null; } public static NotificationModel fromNotificationJSONObject(JSONObject wpData) throws NotTargetedForThisInstallationException { try { // Read notification content JSONObject wpAlert = wpData.optJSONObject("alert"); AlertModel alert = null; if (wpAlert != null) { alert = AlertModel.fromJSON(wpAlert); } else { // We are probably parsing an opened notification and the extras was not given. // We are not interested in showing a notification anyway, the in-app message is what's important now. } // Get the notification type Type type; try { type = NotificationModel.Type.fromString(JSONUtil.getString(wpData, "type")); } catch (Exception ex) { WonderPush.logError("Failed to read notification type", ex); if (alert != null && (alert.getText() != null || alert.getTitle() != null)) { // must be the same test as NotificationManager.buildNotification type = NotificationModel.Type.SIMPLE; } else { type = NotificationModel.Type.DATA; } WonderPush.logDebug("Inferred notification type: " + type); } if (type == null) { return null; } // Instantiate the appropriate non-abstract subclass NotificationModel rtn = type.getBuilder().build(wpData.toString()); // Read common fields rtn.setType(type); rtn.setAlert(alert); rtn.setTargetedInstallation(JSONUtil.getString(wpData, "@")); rtn.setCampaignId(JSONUtil.getString(wpData, "c")); rtn.setNotificationId(JSONUtil.getString(wpData, "n")); rtn.setViewId(JSONUtil.getString(wpData, "v")); rtn.setReporting(wpData.optJSONObject("reporting")); rtn.setTargetUrl(JSONUtil.getString(wpData, "targetUrl")); rtn.setReceipt(wpData.optBoolean("receipt", false)); rtn.setReceiptUsingMeasurements(wpData.optBoolean("receiptUsingMeasurements", false)); rtn.setLastReceivedNotificationCheckDelay(wpData.optLong("lastReceivedNotificationCheckDelay", DEFAULT_LAST_RECEIVED_NOTIFICATION_CHECK_DELAY)); // Read receive actions JSONArray receiveActions = wpData.optJSONArray("receiveActions"); int receiveActionCount = receiveActions != null ? receiveActions.length() : 0; for (int i = 0 ; i < receiveActionCount ; ++i) { JSONObject action = receiveActions.optJSONObject(i); rtn.addReceiveAction(new ActionModel(action)); } // Read at open actions JSONArray actions = wpData.optJSONArray("actions"); int actionCount = actions != null ? actions.length() : 0; for (int i = 0 ; i < actionCount ; ++i) { JSONObject action = actions.optJSONObject(i); rtn.addAction(new ActionModel(action)); } // Read in-app JSONObject inApp = wpData.optJSONObject("inApp"); if (inApp != null) { JSONObject reporting = inApp.optJSONObject("reporting"); if (reporting == null) reporting = rtn.getReporting(); String campaignId = JSONUtil.optString(reporting, "campaignId"); if (campaignId == null) campaignId = rtn.getCampaignId(); String notificationId = JSONUtil.optString(reporting, "notificationId"); if (notificationId == null) notificationId = rtn.getNotificationId(); String viewId = JSONUtil.optString(reporting, "viewId"); if (viewId == null) viewId = rtn.getViewId(); JSONObject content = inApp.optJSONObject("content"); if (reporting != null && content != null) { NotificationMetadata notificationMetadata = new NotificationMetadata(campaignId, notificationId, viewId, reporting, false); rtn.inAppMessage = Campaign.parseContent(notificationMetadata, new JSONObject(), content); } } // Read common in-app fields rtn.setTitle(JSONUtil.getString(wpData, "title")); JSONArray buttons = wpData.optJSONArray("buttons"); int buttonCount = buttons != null ? buttons.length() : 0; for (int i = 0 ; i < buttonCount ; ++i) { JSONObject wpButton = buttons.optJSONObject(i); if (wpButton == null) { continue; } rtn.addButton(new ButtonModel(wpButton)); } // Let the non-abstract subclass read the rest and return rtn.readFromJSONObject(wpData); return rtn; } catch (Exception e) { Log.e(TAG, "Unexpected error while parsing a notification with JSON input " + wpData.toString(), e); } return null; } protected abstract void readFromJSONObject(JSONObject wpData); public NotificationModel(String inputJSONString) { this.inputJSONString = inputJSONString; } public String getInputJSONString() { return inputJSONString; } public String getTargetedInstallation() { return targetedInstallation; } public void setTargetedInstallation(String targetedInstallation) { this.targetedInstallation = targetedInstallation; } public String getCampaignId() { return campaignId; } public void setCampaignId(String campaignId) { this.campaignId = campaignId; } public String getNotificationId() { return notificationId; } public void setNotificationId(String notificationId) { this.notificationId = notificationId; } public String getViewId() { return viewId; } public void setViewId(String viewId) { this.viewId = viewId; } public JSONObject getReporting() { return reporting; } public void setReporting(JSONObject reporting) { this.reporting = reporting; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public AlertModel getAlert() { return alert; } public void setAlert(AlertModel alert) { this.alert = alert; } public String getTargetUrl() { return targetUrl; } public void setTargetUrl(String targetUrl) { this.targetUrl = targetUrl; } public List<ActionModel> getReceiveActions() { return receiveActions; } public void setReceiveActions(List<ActionModel> receiveActions) { this.receiveActions = receiveActions; } public void addReceiveAction(ActionModel action) { if (action != null) { receiveActions.add(action); } } public List<ActionModel> getActions() { return actions; } public void setActions(List<ActionModel> actions) { this.actions = actions; } public void addAction(ActionModel action) { if (action != null) { actions.add(action); } } public boolean getReceipt() { return receipt; } public void setReceipt(boolean receipt) { this.receipt = receipt; } public boolean getReceiptUsingMeasurements() { return receiptUsingMeasurements; } public void setReceiptUsingMeasurements(boolean receiptUsingMeasurements) { this.receiptUsingMeasurements = receiptUsingMeasurements; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getButtonCount() { return buttons.size(); } public ButtonModel getButton(int index) { return buttons.get(index); } public void addButton(ButtonModel button) { if (button != null) { buttons.add(button); } } public AtomicReference<ButtonModel> getChosenButton() { return choice; } public InAppMessage getInAppMessage() { return inAppMessage; } public long getLastReceivedNotificationCheckDelay() { return lastReceivedNotificationCheckDelay; } public void setLastReceivedNotificationCheckDelay(long lastReceivedNotificationCheckDelay) { this.lastReceivedNotificationCheckDelay = lastReceivedNotificationCheckDelay; } }
package bisq.network.p2p.peers; import bisq.network.p2p.NodeAddress; import bisq.network.p2p.network.CloseConnectionReason; import bisq.network.p2p.network.Connection; import bisq.network.p2p.network.ConnectionListener; import bisq.network.p2p.network.InboundConnection; import bisq.network.p2p.network.NetworkNode; import bisq.network.p2p.network.PeerType; import bisq.network.p2p.network.RuleViolation; import bisq.network.p2p.peers.peerexchange.Peer; import bisq.network.p2p.peers.peerexchange.PeerList; import bisq.network.p2p.seed.SeedNodeRepository; import bisq.common.ClockWatcher; import bisq.common.Timer; import bisq.common.UserThread; import bisq.common.app.Capabilities; import bisq.common.app.Capability; import bisq.common.config.Config; import bisq.common.persistence.PersistenceManager; import bisq.common.proto.persistable.PersistedDataHost; import javax.inject.Inject; import javax.inject.Named; import com.google.common.annotations.VisibleForTesting; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; @Slf4j public final class PeerManager implements ConnectionListener, PersistedDataHost { // Static private static final long CHECK_MAX_CONN_DELAY_SEC = 10; // Use a long delay as the bootstrapping peer might need a while until it knows its onion address private static final long REMOVE_ANONYMOUS_PEER_SEC = 240; private static final int MAX_REPORTED_PEERS = 1000; private static final int MAX_PERSISTED_PEERS = 500; // max age for reported peers is 14 days private static final long MAX_AGE = TimeUnit.DAYS.toMillis(14); // Age of what we consider connected peers still as live peers private static final long MAX_AGE_LIVE_PEERS = TimeUnit.MINUTES.toMillis(30); private static final boolean PRINT_REPORTED_PEERS_DETAILS = true; private boolean shutDownRequested; // Listener public interface Listener { void onAllConnectionsLost(); void onNewConnectionAfterAllConnectionsLost(); void onAwakeFromStandby(); } // Instance fields private final NetworkNode networkNode; private final ClockWatcher clockWatcher; private final Set<NodeAddress> seedNodeAddresses; private final PersistenceManager<PeerList> persistenceManager; private final ClockWatcher.Listener clockWatcherListener; private final List<Listener> listeners = new CopyOnWriteArrayList<>(); // Persistable peerList private final PeerList peerList = new PeerList(); // Peers we got reported from other peers @Getter private final Set<Peer> reportedPeers = new HashSet<>(); // Most recent peers with activity date of last 30 min. private final Set<Peer> latestLivePeers = new HashSet<>(); private Timer checkMaxConnectionsTimer; private boolean stopped; private boolean lostAllConnections; private int maxConnections; @Getter private int minConnections; private int disconnectFromSeedNode; private int outBoundPeerTrigger; private int initialDataExchangeTrigger; private int maxConnectionsAbsolute; @Getter private int peakNumConnections; @Setter private boolean allowDisconnectSeedNodes; @Getter private int numAllConnectionsLostEvents; // Constructor @Inject public PeerManager(NetworkNode networkNode, SeedNodeRepository seedNodeRepository, ClockWatcher clockWatcher, PersistenceManager<PeerList> persistenceManager, @Named(Config.MAX_CONNECTIONS) int maxConnections) { this.networkNode = networkNode; this.seedNodeAddresses = new HashSet<>(seedNodeRepository.getSeedNodeAddresses()); this.clockWatcher = clockWatcher; this.persistenceManager = persistenceManager; this.persistenceManager.initialize(peerList, PersistenceManager.Source.PRIVATE_LOW_PRIO); this.networkNode.addConnectionListener(this); setConnectionLimits(maxConnections); // we check if app was idle for more then 5 sec. clockWatcherListener = new ClockWatcher.Listener() { @Override public void onSecondTick() { } @Override public void onMinuteTick() { } @Override public void onAwakeFromStandby(long missedMs) { // We got probably stopped set to true when we got a longer interruption (e.g. lost all connections), // now we get awake again, so set stopped to false. stopped = false; listeners.forEach(Listener::onAwakeFromStandby); } }; clockWatcher.addListener(clockWatcherListener); } public void shutDown() { shutDownRequested = true; networkNode.removeConnectionListener(this); clockWatcher.removeListener(clockWatcherListener); stopCheckMaxConnectionsTimer(); } // PersistedDataHost implementation @Override public void readPersisted(Runnable completeHandler) { persistenceManager.readPersisted(persisted -> { peerList.setAll(persisted.getSet()); completeHandler.run(); }, completeHandler); } // ConnectionListener implementation @Override public void onConnection(Connection connection) { connection.getConnectionState().setSeedNode(isSeedNode(connection)); doHouseKeeping(); if (lostAllConnections) { lostAllConnections = false; stopped = false; log.info("\n "Established a new connection from/to {} after all connections lost.\n" + " listeners.forEach(Listener::onNewConnectionAfterAllConnectionsLost); } connection.getPeersNodeAddressOptional() .flatMap(this::findPeer) .ifPresent(Peer::onConnection); } @Override public void onDisconnect(CloseConnectionReason closeConnectionReason, Connection connection) { log.info("onDisconnect called: nodeAddress={}, closeConnectionReason={}", connection.getPeersNodeAddressOptional(), closeConnectionReason); handleConnectionFault(connection); boolean previousLostAllConnections = lostAllConnections; lostAllConnections = networkNode.getAllConnections().isEmpty(); if (lostAllConnections) { stopped = true; if (!shutDownRequested) { if (!previousLostAllConnections) { // If we enter to 'All connections lost' we count the event. numAllConnectionsLostEvents++; } log.warn("\n "All connections lost\n" + " listeners.forEach(Listener::onAllConnectionsLost); } } maybeRemoveBannedPeer(closeConnectionReason, connection); } @Override public void onError(Throwable throwable) { } // Connection public boolean hasSufficientConnections() { return networkNode.getConfirmedConnections().size() >= minConnections; } // Checks if that connection has the peers node address public boolean isConfirmed(NodeAddress nodeAddress) { return networkNode.getNodeAddressesOfConfirmedConnections().contains(nodeAddress); } public void handleConnectionFault(Connection connection) { connection.getPeersNodeAddressOptional().ifPresent(nodeAddress -> handleConnectionFault(nodeAddress, connection)); } public void handleConnectionFault(NodeAddress nodeAddress) { handleConnectionFault(nodeAddress, null); } public void handleConnectionFault(NodeAddress nodeAddress, @Nullable Connection connection) { boolean doRemovePersistedPeer = false; removeReportedPeer(nodeAddress); Optional<Peer> persistedPeerOptional = findPersistedPeer(nodeAddress); if (persistedPeerOptional.isPresent()) { Peer persistedPeer = persistedPeerOptional.get(); persistedPeer.onDisconnect(); doRemovePersistedPeer = persistedPeer.tooManyFailedConnectionAttempts(); } boolean ruleViolation = connection != null && connection.getRuleViolation() != null; doRemovePersistedPeer = doRemovePersistedPeer || ruleViolation; if (doRemovePersistedPeer) removePersistedPeer(nodeAddress); else removeTooOldPersistedPeers(); } public boolean isSeedNode(Connection connection) { return connection.getPeersNodeAddressOptional().isPresent() && isSeedNode(connection.getPeersNodeAddressOptional().get()); } public boolean isSelf(NodeAddress nodeAddress) { return nodeAddress.equals(networkNode.getNodeAddress()); } private boolean isSeedNode(Peer peer) { return seedNodeAddresses.contains(peer.getNodeAddress()); } public boolean isSeedNode(NodeAddress nodeAddress) { return seedNodeAddresses.contains(nodeAddress); } public boolean isPeerBanned(CloseConnectionReason closeConnectionReason, Connection connection) { return closeConnectionReason == CloseConnectionReason.PEER_BANNED && connection.getPeersNodeAddressOptional().isPresent(); } private void maybeRemoveBannedPeer(CloseConnectionReason closeConnectionReason, Connection connection) { if (connection.getPeersNodeAddressOptional().isPresent() && isPeerBanned(closeConnectionReason, connection)) { NodeAddress nodeAddress = connection.getPeersNodeAddressOptional().get(); seedNodeAddresses.remove(nodeAddress); removePersistedPeer(nodeAddress); removeReportedPeer(nodeAddress); } } public void maybeResetNumAllConnectionsLostEvents() { if (!networkNode.getAllConnections().isEmpty()) { numAllConnectionsLostEvents = 0; } } // Peer @SuppressWarnings("unused") public Optional<Peer> findPeer(NodeAddress peersNodeAddress) { return getAllPeers().stream() .filter(peer -> peer.getNodeAddress().equals(peersNodeAddress)) .findAny(); } public Set<Peer> getAllPeers() { Set<Peer> allPeers = new HashSet<>(getLivePeers()); allPeers.addAll(getPersistedPeers()); allPeers.addAll(reportedPeers); return allPeers; } public Collection<Peer> getPersistedPeers() { return peerList.getSet(); } public void addToReportedPeers(Set<Peer> reportedPeersToAdd, Connection connection, Capabilities capabilities) { applyCapabilities(connection, capabilities); Set<Peer> peers = reportedPeersToAdd.stream() .filter(peer -> !isSelf(peer.getNodeAddress())) .collect(Collectors.toSet()); printNewReportedPeers(peers); // We check if the reported msg is not violating our rules if (peers.size() <= (MAX_REPORTED_PEERS + maxConnectionsAbsolute + 10)) { reportedPeers.addAll(peers); purgeReportedPeersIfExceeds(); getPersistedPeers().addAll(peers); purgePersistedPeersIfExceeds(); requestPersistence(); printReportedPeers(); } else { // If a node is trying to send too many list we treat it as rule violation. // Reported list include the connected list. We use the max value and give some extra headroom. // Will trigger a shutdown after 2nd time sending too much connection.reportInvalidRequest(RuleViolation.TOO_MANY_REPORTED_PEERS_SENT); } } // Delivers the live peers from the last 30 min (MAX_AGE_LIVE_PEERS) // We include older peers to avoid risks for network partitioning public Set<Peer> getLivePeers() { return getLivePeers(null); } public Set<Peer> getLivePeers(@Nullable NodeAddress excludedNodeAddress) { int oldNumLatestLivePeers = latestLivePeers.size(); Set<Peer> peers = new HashSet<>(latestLivePeers); Set<Peer> currentLivePeers = getConnectedReportedPeers().stream() .filter(e -> !isSeedNode(e)) .filter(e -> !e.getNodeAddress().equals(excludedNodeAddress)) .collect(Collectors.toSet()); peers.addAll(currentLivePeers); long maxAge = new Date().getTime() - MAX_AGE_LIVE_PEERS; latestLivePeers.clear(); Set<Peer> recentPeers = peers.stream() .filter(peer -> peer.getDateAsLong() > maxAge) .collect(Collectors.toSet()); latestLivePeers.addAll(recentPeers); if (oldNumLatestLivePeers != latestLivePeers.size()) log.info("Num of latestLivePeers={}", latestLivePeers.size()); return latestLivePeers; } // Capabilities public boolean peerHasCapability(NodeAddress peersNodeAddress, Capability capability) { return findPeersCapabilities(peersNodeAddress) .map(capabilities -> capabilities.contains(capability)) .orElse(false); } public Optional<Capabilities> findPeersCapabilities(NodeAddress nodeAddress) { // We look up first our connections as that is our own data. If not found there we look up the peers which // include reported peers. Optional<Capabilities> optionalCapabilities = networkNode.findPeersCapabilities(nodeAddress); if (optionalCapabilities.isPresent() && !optionalCapabilities.get().isEmpty()) { return optionalCapabilities; } // Reported peers are not trusted data. We could get capabilities which miss the // peers real capability or we could get maliciously altered capabilities telling us the peer supports a // capability which is in fact not supported. This could lead to connection loss as we might send data not // recognized by the peer. As we register a listener on connection if we don't have set the capability from our // own sources we would get it fixed as soon we have a connection with that peer, rendering such an attack // inefficient. // Also this risk is only for not updated peers, so in case that would be abused for an // attack all users have a strong incentive to update ;-). return getAllPeers().stream() .filter(peer -> peer.getNodeAddress().equals(nodeAddress)) .findAny() .map(Peer::getCapabilities); } private void applyCapabilities(Connection connection, Capabilities newCapabilities) { if (newCapabilities == null || newCapabilities.isEmpty()) { return; } connection.getPeersNodeAddressOptional().ifPresent(nodeAddress -> { getAllPeers().stream() .filter(peer -> peer.getNodeAddress().equals(nodeAddress)) .filter(peer -> peer.getCapabilities().hasLess(newCapabilities)) .forEach(peer -> peer.setCapabilities(newCapabilities)); }); requestPersistence(); } // Housekeeping private void doHouseKeeping() { if (checkMaxConnectionsTimer == null) { printConnectedPeers(); checkMaxConnectionsTimer = UserThread.runAfter(() -> { stopCheckMaxConnectionsTimer(); if (!stopped) { Set<Connection> allConnections = new HashSet<>(networkNode.getAllConnections()); int size = allConnections.size(); peakNumConnections = Math.max(peakNumConnections, size); removeAnonymousPeers(); removeTooOldReportedPeers(); removeTooOldPersistedPeers(); checkMaxConnections(); } else { log.debug("We have stopped already. We ignore that checkMaxConnectionsTimer.run call."); } }, CHECK_MAX_CONN_DELAY_SEC); } } @VisibleForTesting boolean checkMaxConnections() { Set<Connection> allConnections = new HashSet<>(networkNode.getAllConnections()); int size = allConnections.size(); peakNumConnections = Math.max(peakNumConnections, size); log.info("We have {} connections open. Our limit is {}", size, maxConnections); if (size <= maxConnections) { log.debug("We have not exceeded the maxConnections limit of {} " + "so don't need to close any connections.", size); return false; } log.info("We have too many connections open. " + "Lets try first to remove the inbound connections of type PEER."); List<Connection> candidates = allConnections.stream() .filter(e -> e instanceof InboundConnection) .filter(e -> e.getConnectionState().getPeerType() == PeerType.PEER) .sorted(Comparator.comparingLong(o -> o.getStatistic().getLastActivityTimestamp())) .collect(Collectors.toList()); if (candidates.isEmpty()) { log.info("No candidates found. We check if we exceed our " + "outBoundPeerTrigger of {}", outBoundPeerTrigger); if (size <= outBoundPeerTrigger) { log.info("We have not exceeded outBoundPeerTrigger of {} " + "so don't need to close any connections", outBoundPeerTrigger); return false; } log.info("We have exceeded outBoundPeerTrigger of {}. " + "Lets try to remove outbound connection of type PEER.", outBoundPeerTrigger); candidates = allConnections.stream() .filter(e -> e.getConnectionState().getPeerType() == PeerType.PEER) .sorted(Comparator.comparingLong(o -> o.getStatistic().getLastActivityTimestamp())) .collect(Collectors.toList()); if (candidates.isEmpty()) { log.info("No candidates found. We check if we exceed our " + "initialDataExchangeTrigger of {}", initialDataExchangeTrigger); if (size <= initialDataExchangeTrigger) { log.info("We have not exceeded initialDataExchangeTrigger of {} " + "so don't need to close any connections", initialDataExchangeTrigger); return false; } log.info("We have exceeded initialDataExchangeTrigger of {} " + "Lets try to remove any connection which is not " + "of type DIRECT_MSG_PEER or INITIAL_DATA_REQUEST.", initialDataExchangeTrigger); candidates = allConnections.stream() .filter(e -> e.getConnectionState().getPeerType() == PeerType.INITIAL_DATA_EXCHANGE) .sorted(Comparator.comparingLong(o -> o.getConnectionState().getLastInitialDataMsgTimeStamp())) .collect(Collectors.toList()); if (candidates.isEmpty()) { log.info("No candidates found. We check if we exceed our " + "maxConnectionsAbsolute limit of {}", maxConnectionsAbsolute); if (size <= maxConnectionsAbsolute) { log.info("We have not exceeded maxConnectionsAbsolute limit of {} " + "so don't need to close any connections", maxConnectionsAbsolute); return false; } log.info("We reached abs. max. connections. Lets try to remove ANY connection."); candidates = allConnections.stream() .sorted(Comparator.comparingLong(o -> o.getStatistic().getLastActivityTimestamp())) .collect(Collectors.toList()); } } } if (!candidates.isEmpty()) { Connection connection = candidates.remove(0); log.info("checkMaxConnections: Num candidates for shut down={}. We close oldest connection: {}", candidates.size(), connection); log.debug("We are going to shut down the oldest connection.\n\tconnection={}", connection.toString()); if (!connection.isStopped()) { connection.shutDown(CloseConnectionReason.TOO_MANY_CONNECTIONS_OPEN, () -> UserThread.runAfter(this::checkMaxConnections, 100, TimeUnit.MILLISECONDS)); return true; } } log.info("No candidates found to remove.\n\t" + "size={}, allConnections={}", size, allConnections); return false; } private void removeAnonymousPeers() { networkNode.getAllConnections().stream() .filter(connection -> !connection.hasPeersNodeAddress()) .forEach(connection -> UserThread.runAfter(() -> { // We give 240 seconds delay and check again if still no address is set // Keep the delay long as we don't want to disconnect a peer in case we are a seed node just // because he needs longer for the HS publishing if (!connection.hasPeersNodeAddress() && !connection.isStopped()) { log.debug("We close the connection as the peer address is still unknown.\n\t" + "connection={}", connection); connection.shutDown(CloseConnectionReason.UNKNOWN_PEER_ADDRESS); } }, REMOVE_ANONYMOUS_PEER_SEC)); } // Reported peers private void removeReportedPeer(Peer reportedPeer) { reportedPeers.remove(reportedPeer); printReportedPeers(); } private void removeReportedPeer(NodeAddress nodeAddress) { List<Peer> reportedPeersClone = new ArrayList<>(reportedPeers); reportedPeersClone.stream() .filter(e -> e.getNodeAddress().equals(nodeAddress)) .findAny() .ifPresent(this::removeReportedPeer); } private void removeTooOldReportedPeers() { List<Peer> reportedPeersClone = new ArrayList<>(reportedPeers); Set<Peer> reportedPeersToRemove = reportedPeersClone.stream() .filter(reportedPeer -> new Date().getTime() - reportedPeer.getDate().getTime() > MAX_AGE) .collect(Collectors.toSet()); reportedPeersToRemove.forEach(this::removeReportedPeer); } private void purgeReportedPeersIfExceeds() { int size = reportedPeers.size(); if (size > MAX_REPORTED_PEERS) { log.info("We have already {} reported peers which exceeds our limit of {}." + "We remove random peers from the reported peers list.", size, MAX_REPORTED_PEERS); int diff = size - MAX_REPORTED_PEERS; List<Peer> list = new ArrayList<>(reportedPeers); // we don't use sorting by lastActivityDate to keep it more random for (int i = 0; i < diff; i++) { if (!list.isEmpty()) { Peer toRemove = list.remove(new Random().nextInt(list.size())); removeReportedPeer(toRemove); } } } else { log.trace("No need to purge reported peers.\n\tWe don't have more then {} reported peers yet.", MAX_REPORTED_PEERS); } } private void printReportedPeers() { if (!reportedPeers.isEmpty()) { if (PRINT_REPORTED_PEERS_DETAILS) { StringBuilder result = new StringBuilder("\n\n "Collected reported peers:"); List<Peer> reportedPeersClone = new ArrayList<>(reportedPeers); reportedPeersClone.forEach(e -> result.append("\n").append(e)); result.append("\n log.trace(result.toString()); } log.debug("Number of reported peers: {}", reportedPeers.size()); } } private void printNewReportedPeers(Set<Peer> reportedPeers) { if (PRINT_REPORTED_PEERS_DETAILS) { StringBuilder result = new StringBuilder("We received new reportedPeers:"); List<Peer> reportedPeersClone = new ArrayList<>(reportedPeers); reportedPeersClone.forEach(e -> result.append("\n\t").append(e)); log.trace(result.toString()); } log.debug("Number of new arrived reported peers: {}", reportedPeers.size()); } // Persisted peers private boolean removePersistedPeer(Peer persistedPeer) { if (getPersistedPeers().contains(persistedPeer)) { getPersistedPeers().remove(persistedPeer); requestPersistence(); return true; } else { return false; } } private void requestPersistence() { persistenceManager.requestPersistence(); } @SuppressWarnings("UnusedReturnValue") private boolean removePersistedPeer(NodeAddress nodeAddress) { Optional<Peer> optionalPersistedPeer = findPersistedPeer(nodeAddress); return optionalPersistedPeer.isPresent() && removePersistedPeer(optionalPersistedPeer.get()); } private Optional<Peer> findPersistedPeer(NodeAddress nodeAddress) { return getPersistedPeers().stream() .filter(e -> e.getNodeAddress().equals(nodeAddress)) .findAny(); } private void removeTooOldPersistedPeers() { Set<Peer> persistedPeersToRemove = getPersistedPeers().stream() .filter(reportedPeer -> new Date().getTime() - reportedPeer.getDate().getTime() > MAX_AGE) .collect(Collectors.toSet()); persistedPeersToRemove.forEach(this::removePersistedPeer); } private void purgePersistedPeersIfExceeds() { int size = getPersistedPeers().size(); int limit = MAX_PERSISTED_PEERS; if (size > limit) { log.trace("We have already {} persisted peers which exceeds our limit of {}." + "We remove random peers from the persisted peers list.", size, limit); int diff = size - limit; List<Peer> list = new ArrayList<>(getPersistedPeers()); // we don't use sorting by lastActivityDate to avoid attack vectors and keep it more random for (int i = 0; i < diff; i++) { if (!list.isEmpty()) { Peer toRemove = list.remove(new Random().nextInt(list.size())); removePersistedPeer(toRemove); } } } else { log.trace("No need to purge persisted peers.\n\tWe don't have more then {} persisted peers yet.", MAX_PERSISTED_PEERS); } } // Getters public int getMaxConnections() { return maxConnections; } // Listeners public void addListener(Listener listener) { listeners.add(listener); } public void removeListener(Listener listener) { listeners.remove(listener); } // Private misc // Modify this to change the relationships between connection limits. // maxConnections default 12 private void setConnectionLimits(int maxConnections) { this.maxConnections = maxConnections; // app node 12; seedNode 20 minConnections = Math.max(1, (int) Math.round(maxConnections * 0.7)); // app node 8; seedNode 14 disconnectFromSeedNode = maxConnections; // app node 12; seedNode 20 outBoundPeerTrigger = Math.max(4, (int) Math.round(maxConnections * 1.3)); // app node 16; seedNode 26 initialDataExchangeTrigger = Math.max(8, (int) Math.round(maxConnections * 1.7)); // app node 20; seedNode 34 maxConnectionsAbsolute = Math.max(12, (int) Math.round(maxConnections * 2.5)); // app node 30; seedNode 50 } private Set<Peer> getConnectedReportedPeers() { // networkNode.getConfirmedConnections includes: // filter(connection -> connection.getPeersNodeAddressOptional().isPresent()) return networkNode.getConfirmedConnections().stream() .map((Connection connection) -> { Capabilities supportedCapabilities = new Capabilities(connection.getCapabilities()); // If we have a new connection the supportedCapabilities is empty. // We lookup if we have already stored the supportedCapabilities at the persisted or reported peers // and if so we use that. Optional<NodeAddress> peersNodeAddressOptional = connection.getPeersNodeAddressOptional(); checkArgument(peersNodeAddressOptional.isPresent()); // getConfirmedConnections delivers only connections where we know the address NodeAddress peersNodeAddress = peersNodeAddressOptional.get(); boolean capabilitiesNotFoundInConnection = supportedCapabilities.isEmpty(); if (capabilitiesNotFoundInConnection) { // If not found in connection we look up if we got the Capabilities set from any of the // reported or persisted peers Set<Peer> persistedAndReported = new HashSet<>(getPersistedPeers()); persistedAndReported.addAll(getReportedPeers()); Optional<Peer> candidate = persistedAndReported.stream() .filter(peer -> peer.getNodeAddress().equals(peersNodeAddress)) .filter(peer -> !peer.getCapabilities().isEmpty()) .findAny(); if (candidate.isPresent()) { supportedCapabilities = new Capabilities(candidate.get().getCapabilities()); } } Peer peer = new Peer(peersNodeAddress, supportedCapabilities); // If we did not found the capability from our own connection we add a listener, // so once we get a connection with that peer and exchange a message containing the capabilities // we get set the capabilities. if (capabilitiesNotFoundInConnection) { connection.addWeakCapabilitiesListener(peer); } return peer; }) .collect(Collectors.toSet()); } private void stopCheckMaxConnectionsTimer() { if (checkMaxConnectionsTimer != null) { checkMaxConnectionsTimer.stop(); checkMaxConnectionsTimer = null; } } private void printConnectedPeers() { if (!networkNode.getConfirmedConnections().isEmpty()) { StringBuilder result = new StringBuilder("\n\n "Connected peers for node " + networkNode.getNodeAddress() + ":"); networkNode.getConfirmedConnections().forEach(e -> result.append("\n") .append(e.getPeersNodeAddressOptional()).append(" ").append(e.getConnectionState().getPeerType())); result.append("\n log.debug(result.toString()); } } }
package org.linphone.p2pproxy.core; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.management.ManagementFactory; import java.net.URI; import java.net.URL; import java.util.InvalidPropertiesFormatException; import java.util.Properties; import javax.management.ObjectName; import net.jxta.exception.JxtaException; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.linphone.p2pproxy.api.P2pProxyException; import org.linphone.p2pproxy.api.P2pProxyManagement; import org.linphone.p2pproxy.api.P2pProxyNotReadyException; import org.linphone.p2pproxy.api.P2pProxyResourceManagement; import org.linphone.p2pproxy.api.P2pProxyUserAlreadyExistException; import org.linphone.p2pproxy.core.media.MediaResourceService; import org.linphone.p2pproxy.core.sipproxy.SipProxyRegistrar; import org.zoolu.sip.provider.SipStack; import org.linphone.p2pproxy.launcher.P2pProxylauncherConstants; public class P2pProxyMain implements P2pProxyMainMBean { private final static Logger mLog = Logger.getLogger(P2pProxyMain.class); private static JxtaNetworkManager mJxtaNetworkManager; private static ServiceProvider mServiceProvider; private static P2pProxyManagement mP2pProxyManagement; private static SipProxyRegistrar mSipAndPipeListener; private static P2pProxyAccountManagementMBean mP2pProxyAccountManagement; private static P2pProxyResourceManagement mP2pProxySipProxyRegistrarManagement; public final static String ACCOUNT_MGR_MBEAN_NAME="org.linphone.p2proxy:type=account-manager"; public final static String PROXY_REG_MBEAN_NAME="org.linphone.p2proxy:type=proxy-registrar"; public final static String MAIN_MBEAN_NAME="org.linphone.p2proxy:type=main"; private static P2pProxyMain mP2pProxyMain = new P2pProxyMain(); private static Configurator mConfigurator; private static String mConfigHomeDir; static private boolean mExit = false; static private boolean isReady = false; static { // System.setProperty("com.sun.management.jmxremote", "true"); // System.setProperty("com.sun.management.jmxremote.port", "6789"); // System.setProperty("com.sun.management.jmxremote.authenticate", "false"); // System.setProperty("com.sun.management.jmxremote.ssl", "false"); } /** * @param args * @throws P2pProxyException * @throws InterruptedException * @throws JxtaException * @throws IOException * @throws FileNotFoundException * @throws InvalidPropertiesFormatException */ public static void main(String[] args) { try { mConfigHomeDir=System.getProperty("user.home")+"/.p2pproxy"; int lsipPort=5040; int lMediaPort=MediaResourceService.AUDIO_VIDEO_LOCAL_PORT_DEFAULT_VALUE; int lP2pPort = 9701; JxtaNetworkManager.Mode lMode = JxtaNetworkManager.Mode.auto; // setup logging // get config dire first for (int i=0; i < args.length; i=i+2) { String argument = args[i]; if (argument.equals("-jxta")) { mConfigHomeDir = args[i + 1]; File lFile = new File(mConfigHomeDir); if (lFile.exists() == false) lFile.mkdir(); System.out.println("mConfigHomeDir detected[" + mConfigHomeDir + "]"); } } System.setProperty("org.linphone.p2pproxy.home", mConfigHomeDir); System.setProperty("net.jxta.logging.Logging", "FINEST"); System.setProperty("net.jxta.level", "FINEST"); mP2pProxyMain.loadTraceConfigFile(); mLog.info("p2pproxy initilizing..."); File lPropertyFile = new File(mConfigHomeDir+"/p2pproxy.properties.xml"); mConfigurator = new Configurator(lPropertyFile); try { ObjectName lObjectName = new ObjectName(MAIN_MBEAN_NAME); ManagementFactory.getPlatformMBeanServer().registerMBean(mP2pProxyMain,lObjectName); } catch (Exception e) { mLog.warn("cannot register MBean",e); } // get other params for (int i=0; i < args.length; i=i+2) { String argument = args[i]; if (argument.equals("-jxta") || argument.equals("-home")) { mConfigHomeDir = args[i + 1]; //nop } else if (argument.equals("-sip")) { lsipPort = Integer.parseInt(args[i + 1]); System.out.println("sipPort detected[" + lsipPort + "]"); mConfigurator.setProperty(SipProxyRegistrar.REGISTRAR_PORT, Integer.toString(lsipPort)); } else if (argument.equals("-media")) { lMediaPort = Integer.parseInt(args[i + 1]); System.out.println("media detected[" + lMediaPort + "]"); mConfigurator.setProperty(MediaResourceService.AUDIO_VIDEO_LOCAL_PORT, Integer.toString(lMediaPort)); } else if (argument.equals("-p2p")) { lP2pPort = Integer.parseInt(args[i + 1]); System.out.println("p2p port detected[" + lP2pPort + "]"); mConfigurator.setProperty(JxtaNetworkManager.TCP_LISTENING_PORT, Integer.toString(lP2pPort)); } else if (argument.equals("-relay")) { lMode = JxtaNetworkManager.Mode.relay; mConfigurator.setProperty(JxtaNetworkManager.MODE, lMode.name()); System.out.println("relay mode detected"); i } else if (argument.equals("-edge-only")) { lMode = JxtaNetworkManager.Mode.edge; mConfigurator.setProperty(JxtaNetworkManager.MODE, lMode.name()); System.out.println("edge only mode detected"); i }else if (argument.equals("-seeding-server")) { lMode = JxtaNetworkManager.Mode.seeding_server; mConfigurator.setProperty(JxtaNetworkManager.MODE, lMode.name()); System.out.println("seeding-server detected"); i } else if (argument.equals("-auto-config")) { lMode = JxtaNetworkManager.Mode.auto; mConfigurator.setProperty(JxtaNetworkManager.MODE, lMode.name()); System.out.println("auto-mode mode detected"); i } else if (argument.equals("-seeding-rdv")) { mConfigurator.setProperty(JxtaNetworkManager.SEEDING_RDV, args[i + 1]); System.out.println("seeding rdv detected[" + args[i + 1] + "]"); } else if (argument.equals("-seeding-relay")) { mConfigurator.setProperty(JxtaNetworkManager.SEEDING_RELAY, args[i + 1]); System.out.println("seeding relay detected[" + args[i + 1] + "]"); } else if (argument.equals("-seeding")) { mConfigurator.setProperty(JxtaNetworkManager.SEEDING_RDV, args[i + 1]); mConfigurator.setProperty(JxtaNetworkManager.SEEDING_RELAY, args[i + 1]); System.out.println("seeding detected[" + args[i + 1] + "]"); } else if (argument.equals("-public-address")) { mConfigurator.setProperty(JxtaNetworkManager.HTTP_LISTENING_PUBLIC_ADDRESS,args[i + 1]+":9700"); mConfigurator.setProperty(JxtaNetworkManager.TCP_LISTENING_PUBLIC_ADDRESS,args[i + 1]+":"+lP2pPort); mConfigurator.setProperty(MediaResourceService.AUDIO_VIDEO_PUBLIC_URI,"udp://"+args[i + 1]+":"+lMediaPort); mConfigurator.setProperty(SipProxyRegistrar.REGISTRAR_PUBLIC_ADDRESS,args[i + 1]); System.out.println("public address detected[" + args[i + 1] + "]"); } else { System.out.println("Invalid option: " + args[i]); usage(); System.exit(1); } } File lJxtaDirectory = new File (mConfigHomeDir); if (lJxtaDirectory.exists() == false) lJxtaDirectory.mkdir(); switch (lMode) { case edge: startEdge(mConfigurator,lJxtaDirectory); break; case relay: startRelay(mConfigurator,lJxtaDirectory); break; case seeding_server: startSeeding(mConfigurator,lJxtaDirectory); break; case auto: //1 start edge startEdge(mConfigurator,lJxtaDirectory); // check if peer mode required if (mP2pProxyManagement.shouldIBehaveAsAnRdv() == true) { String lPublicAddress = mP2pProxyManagement.getPublicIpAddress().getHostAddress(); mConfigurator.setProperty(JxtaNetworkManager.HTTP_LISTENING_PUBLIC_ADDRESS, lPublicAddress+":9700"); mConfigurator.setProperty(JxtaNetworkManager.TCP_LISTENING_PUBLIC_ADDRESS, lPublicAddress+":9701"); mServiceProvider.stop(); mJxtaNetworkManager.stop(); startRelay(mConfigurator,lJxtaDirectory); mJxtaNetworkManager.getPeerGroup().getRendezVousService().setAutoStart(true); } break; default: mLog.fatal("unsupported mode ["+lMode+"]"); System.exit(1); } //set management try { ObjectName lObjectName = new ObjectName(ACCOUNT_MGR_MBEAN_NAME); ManagementFactory.getPlatformMBeanServer().registerMBean(mP2pProxyAccountManagement,lObjectName); } catch (Exception e) { mLog.warn("cannot register MBean",e); } mLog.warn("p2pproxy initilized"); isReady = true; while (mExit == false) { Thread.sleep(1000); } if (mServiceProvider!= null) mServiceProvider.stop(); if (mServiceProvider!= null) mServiceProvider.stop(); if (mSipAndPipeListener!= null) mSipAndPipeListener.stop(); if (mJxtaNetworkManager != null) mJxtaNetworkManager.stop(); mLog.info("p2pproxy stopped"); return; } catch (Exception e) { mLog.fatal("error",e); System.exit(1); } } private static void startEdge(Configurator aProperties,File aConfigDir) throws Exception{ // setup jxta mJxtaNetworkManager = new JxtaNetworkManager(aProperties,aConfigDir); mServiceProvider = new EdgePeerServiceManager(aProperties, mJxtaNetworkManager); mP2pProxyManagement = (P2pProxyManagement) mServiceProvider; mP2pProxySipProxyRegistrarManagement = (P2pProxyResourceManagement) mServiceProvider; //setup account manager mP2pProxyAccountManagement = new P2pProxyAccountManagement(mJxtaNetworkManager); mServiceProvider.start(3000L); } private static void startRelay(Configurator aProperties,File aConfigDir) throws Exception{ // setup jxta mJxtaNetworkManager = new JxtaNetworkManager(aProperties,aConfigDir); mServiceProvider = new SuperPeerServiceManager(aProperties, mJxtaNetworkManager); mP2pProxyManagement = (P2pProxyManagement) mServiceProvider; mP2pProxySipProxyRegistrarManagement = (P2pProxyResourceManagement) mServiceProvider; mServiceProvider.start(3000L); //setup account manager mP2pProxyAccountManagement = new P2pProxyAccountManagement(mJxtaNetworkManager); // setup sip provider SipStack.log_path = mConfigHomeDir+"/logs"; mSipAndPipeListener = new SipProxyRegistrar(mConfigurator,mJxtaNetworkManager,mP2pProxyAccountManagement); //set management try { ObjectName lObjectName = new ObjectName(PROXY_REG_MBEAN_NAME); ManagementFactory.getPlatformMBeanServer().registerMBean(mSipAndPipeListener,lObjectName); } catch (Exception e) { mLog.warn("cannot register MBean",e); } } private static void startSeeding(Configurator aProperties,File aConfigDir) throws Exception{ // setup jxta mJxtaNetworkManager = new JxtaNetworkManager(aProperties,aConfigDir); mServiceProvider = new SeedingPeerServiceManager(aProperties, mJxtaNetworkManager,true); mP2pProxyManagement = null; mP2pProxySipProxyRegistrarManagement = (P2pProxyResourceManagement) mServiceProvider; mServiceProvider.start(3000L); //setup account manager mP2pProxyAccountManagement = new P2pProxyAccountManagement(mJxtaNetworkManager); // setup sip provider SipStack.log_path = mConfigHomeDir+"/logs"; mSipAndPipeListener = new SipProxyRegistrar(mConfigurator,mJxtaNetworkManager,mP2pProxyAccountManagement); //set management try { ObjectName lObjectName = new ObjectName(PROXY_REG_MBEAN_NAME); ManagementFactory.getPlatformMBeanServer().registerMBean(mSipAndPipeListener,lObjectName); } catch (Exception e) { mLog.warn("cannot register MBean",e); } } private static void usage() { System.out.println("p2pproxy"); System.out.println("-home : directory where configuration/cache is located (including jxta cache.default is $HOME/.p2pproxy"); System.out.println("-sip : udp proxy port, default 5060"); System.out.println("-media : udp relay/stun port, default 16000"); System.out.println("-p2p : p2p tcp port, default 9701"); System.out.println("-relay : super peer mode"); System.out.println("-edge-only : edge mode"); System.out.println("-seeding-server : seeding server mode"); System.out.println("-auto-config : automatically choose edge or relay (default mode)"); System.out.println("-seeding : list of boostrap rdv separated by | (ex tcp: System.out.println("-public-address : ip as exported to peers (ex myPublicAddress.no-ip.org)"); } public void loadTraceConfigFile() throws P2pProxyException { staticLoadTraceConfigFile(); } public static void staticLoadTraceConfigFile() throws P2pProxyException { try { URL lLog4jFile = null; String lSearchDir; //search build dir lSearchDir = System.getProperty("org.linphone.p2pproxy.build.dir"); File lFile = new File(lSearchDir+"/log4j.properties"); if (lFile.exists() == false) { lSearchDir = mConfigHomeDir; lFile = new File(lSearchDir+"/log4j.properties"); if (lFile.exists() == false) { lSearchDir="."; lFile = new File(lSearchDir+"/log4j.properties"); if (lFile.exists() == false) { lLog4jFile = Thread.currentThread().getContextClassLoader().getResource("log4j.properties"); } } } if (lLog4jFile == null) { lLog4jFile = lFile.toURL(); } PropertyConfigurator.configure(lLog4jFile); // read java.util.logging properties Properties lLogginProperties = new Properties(); lLogginProperties.load(new FileInputStream(new File(lLog4jFile.toURI()))); lLogginProperties.setProperty("java.util.logging.FileHandler.pattern",System.getProperty("org.linphone.p2pproxy.home")+"/logs/p2pproxy.log"); File lLogConfigFile = new File(mConfigHomeDir.concat("log4j.properties")+".tmp"); if (lLogConfigFile.exists() == false) { lLogConfigFile.createNewFile(); } lLogginProperties.store(new FileOutputStream(lLogConfigFile), "tmp"); System.setProperty("java.util.logging.config.file",lLogConfigFile.getAbsolutePath()); java.util.logging.LogManager.getLogManager().readConfiguration(); } catch (Exception e) { throw new P2pProxyException("enable to load traces",e); } } private static void isReady() throws P2pProxyNotReadyException { try { if ((isReady == true && mJxtaNetworkManager.isConnectedToRendezVous(0) == true) || (isReady == true && mJxtaNetworkManager.getPeerGroup().getRendezVousService().isRendezVous())) { //nop connected } else { if (mJxtaNetworkManager != null ) { throw new P2pProxyNotReadyException("not connected to any rdv: status ["+mJxtaNetworkManager.getPeerGroup().getRendezVousService().getRendezVousStatus()+"]"); } else { throw new P2pProxyNotReadyException("initializing"); } } } catch (InterruptedException e) { throw new P2pProxyNotReadyException(e); } } /* p2pproxy.h implementation*/ public static int createAccount(String aUserName) { try { isReady(); mP2pProxyAccountManagement.createAccount(aUserName); } catch (P2pProxyUserAlreadyExistException e) { return P2pProxylauncherConstants.P2PPROXY_ACCOUNTMGT_USER_EXIST; } catch (P2pProxyException e) { return P2pProxylauncherConstants.P2PPROXY_ERROR; } return P2pProxylauncherConstants.P2PPROXY_NO_ERROR; } public static int deleteAccount(String aUserName) { try { isReady(); mP2pProxyAccountManagement.deleteAccount(aUserName); } catch (P2pProxyException e) { return P2pProxylauncherConstants.P2PPROXY_ERROR; } return P2pProxylauncherConstants.P2PPROXY_NO_ERROR; } public static int isValidAccount(String aUserName){ try { isReady(); if (mP2pProxyAccountManagement.isValidAccount(aUserName)) { return P2pProxylauncherConstants.P2PPROXY_ACCOUNTMGT_USER_EXIST; } else { return P2pProxylauncherConstants.P2PPROXY_ACCOUNTMGT_USER_NOT_EXIST; } } catch (P2pProxyException e) { return P2pProxylauncherConstants.P2PPROXY_ERROR; } } public static String lookupSipProxyUri(String aDomaine) { try { isReady(); String[] lProxies = mP2pProxySipProxyRegistrarManagement.lookupSipProxiesUri(aDomaine); if (lProxies.length != 0) { return lProxies[0]; } else { return null; } } catch (Exception e) { return null; } } public static String[] lookupSipProxiesUri(String aDomaine) { try { isReady(); return mP2pProxySipProxyRegistrarManagement.lookupSipProxiesUri(aDomaine); } catch (Exception e) { return null; } } public static String[] lookupMediaServerAddress(String aDomaine) { try { isReady(); return mP2pProxySipProxyRegistrarManagement.getMediaServerList(); } catch (Exception e) { mLog.error("cannot find media resource",e); return null; } } public static int getState() { try { isReady(); return P2pProxylauncherConstants.P2PPROXY_CONNECTED; } catch (P2pProxyException e) { mLog.error("cannot get state",e); return P2pProxylauncherConstants.P2PPROXY_NOT_CONNECTED; } } public static int revokeSipProxy(String aProxy) { try { isReady(); mP2pProxySipProxyRegistrarManagement.revokeSipProxy(aProxy); return P2pProxylauncherConstants.P2PPROXY_NO_ERROR; } catch (P2pProxyException e) { return P2pProxylauncherConstants.P2PPROXY_NOT_CONNECTED; } } public static int revokeMediaServer(String aServer) { try { isReady(); mP2pProxySipProxyRegistrarManagement.revokeMediaServer(aServer); return P2pProxylauncherConstants.P2PPROXY_NO_ERROR; } catch (P2pProxyException e) { return P2pProxylauncherConstants.P2PPROXY_NOT_CONNECTED; } } public static void stop() { mExit = true; } }
package com.senseidb.test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import junit.framework.TestCase; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.browseengine.bobo.api.BrowseFacet; import com.browseengine.bobo.api.BrowseSelection; import com.browseengine.bobo.api.FacetAccessible; import com.browseengine.bobo.api.FacetSpec; import com.browseengine.bobo.api.FacetSpec.FacetSortSpec; import com.browseengine.bobo.facets.DefaultFacetHandlerInitializerParam; import com.senseidb.search.node.SenseiBroker; import com.senseidb.search.req.SenseiHit; import com.senseidb.search.req.SenseiRequest; import com.senseidb.search.req.SenseiResult; import com.senseidb.svc.api.SenseiService; public class TestSensei extends TestCase { private static final Logger logger = Logger.getLogger(TestSensei.class); private static SenseiBroker broker; private static SenseiService httpRestSenseiService; static { SenseiStarter.start("test-conf/node1","test-conf/node2"); broker = SenseiStarter.broker; httpRestSenseiService = SenseiStarter.httpRestSenseiService; } public void testTotalCount() throws Exception { logger.info("executing test case testTotalCount"); SenseiRequest req = new SenseiRequest(); SenseiResult res = broker.browse(req); assertEquals("wrong total number of hits" + req + res, 15000, res.getNumHits()); logger.info("request:" + req + "\nresult:" + res); } public void testTotalCountWithFacetSpec() throws Exception { logger.info("executing test case testTotalCountWithFacetSpec"); SenseiRequest req = new SenseiRequest(); FacetSpec facetSpecall = new FacetSpec(); facetSpecall.setMaxCount(1000000); facetSpecall.setExpandSelection(true); facetSpecall.setMinHitCount(0); facetSpecall.setOrderBy(FacetSortSpec.OrderHitsDesc); FacetSpec facetSpec = new FacetSpec(); facetSpec.setMaxCount(5); setspec(req, facetSpec); req.setCount(5); setspec(req, facetSpecall); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); verifyFacetCount(res, "year", "[1993 TO 1994]", 3090); } public void testSelection() throws Exception { logger.info("executing test case testSelection"); FacetSpec facetSpecall = new FacetSpec(); facetSpecall.setMaxCount(1000000); facetSpecall.setExpandSelection(true); facetSpecall.setMinHitCount(0); facetSpecall.setOrderBy(FacetSortSpec.OrderHitsDesc); FacetSpec facetSpec = new FacetSpec(); facetSpec.setMaxCount(5); SenseiRequest req = new SenseiRequest(); req.setCount(3); facetSpecall.setMaxCount(3); setspec(req, facetSpecall); BrowseSelection sel = new BrowseSelection("year"); String selVal = "[2001 TO 2002]"; sel.addValue(selVal); req.addSelection(sel); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); assertEquals(2907, res.getNumHits()); String selName = "year"; verifyFacetCount(res, selName, selVal, 2907); verifyFacetCount(res, "year", "[1993 TO 1994]", 3090); } public void testSelectionDynamicTimeRange() throws Exception { logger.info("executing test case testSelection"); SenseiRequest req = new SenseiRequest(); DefaultFacetHandlerInitializerParam initParam = new DefaultFacetHandlerInitializerParam(); initParam.putLongParam("time", new long[]{15000L}); req.setFacetHandlerInitializerParam("timeRange", initParam); //req.setFacetHandlerInitializerParam("timeRange_internal", new DefaultFacetHandlerInitializerParam()); req.setCount(3); //setspec(req, facetSpecall); BrowseSelection sel = new BrowseSelection("timeRange"); String selVal = "000000013"; sel.addValue(selVal); req.addSelection(sel); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); assertEquals(12990, res.getNumHits()); } public void testSelectionNot() throws Exception { logger.info("executing test case testSelectionNot"); FacetSpec facetSpecall = new FacetSpec(); facetSpecall.setMaxCount(1000000); facetSpecall.setExpandSelection(true); facetSpecall.setMinHitCount(0); facetSpecall.setOrderBy(FacetSortSpec.OrderHitsDesc); FacetSpec facetSpec = new FacetSpec(); facetSpec.setMaxCount(5); SenseiRequest req = new SenseiRequest(); req.setCount(3); facetSpecall.setMaxCount(3); setspec(req, facetSpecall); BrowseSelection sel = new BrowseSelection("year"); sel.addNotValue("[2001 TO 2002]"); req.addSelection(sel); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); assertEquals(12093, res.getNumHits()); verifyFacetCount(res, "year", "[1993 TO 1994]", 3090); } public void testGroupBy() throws Exception { logger.info("executing test case testGroupBy"); SenseiRequest req = new SenseiRequest(); req.setCount(1); req.setGroupBy(new String[]{"groupid"}); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); SenseiHit hit = res.getSenseiHits()[0]; assertTrue(hit.getGroupHitsCount() > 0); } public void testGroupByWithGroupedHits() throws Exception { logger.info("executing test case testGroupBy"); SenseiRequest req = new SenseiRequest(); req.setCount(1); req.setGroupBy(new String[]{"groupid"}); req.setMaxPerGroup(8); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); SenseiHit hit = res.getSenseiHits()[0]; assertTrue(hit.getGroupHitsCount() > 0); assertTrue(hit.getSenseiGroupHits().length > 0); // use httpRestSenseiService res = httpRestSenseiService.doQuery(req); logger.info("request:" + req + "\nresult:" + res); hit = res.getSenseiHits()[0]; assertTrue(hit.getGroupHitsCount() > 0); assertTrue(hit.getSenseiGroupHits().length > 0); } public void testGroupByVirtual() throws Exception { logger.info("executing test case testGroupByVirtual"); SenseiRequest req = new SenseiRequest(); req.setCount(1); req.setGroupBy(new String[]{"virtual_groupid"}); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); SenseiHit hit = res.getSenseiHits()[0]; assertTrue(hit.getGroupHitsCount() > 0); } public void testGroupByVirtualWithGroupedHits() throws Exception { logger.info("executing test case testGroupByVirtualWithGroupedHits"); SenseiRequest req = new SenseiRequest(); req.setCount(1); req.setGroupBy(new String[]{"virtual_groupid"}); req.setMaxPerGroup(8); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); SenseiHit hit = res.getSenseiHits()[0]; assertTrue(hit.getGroupHitsCount() > 0); assertTrue(hit.getSenseiGroupHits().length > 0); } public void testGroupByFixedLengthLongArray() throws Exception { logger.info("executing test case testGroupByFixedLengthLongArray"); SenseiRequest req = new SenseiRequest(); req.setCount(1); req.setGroupBy(new String[]{"virtual_groupid_fixedlengthlongarray"}); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); SenseiHit hit = res.getSenseiHits()[0]; assertTrue(hit.getGroupHitsCount() > 0); } public void testGroupByFixedLengthLongArrayWithGroupedHits() throws Exception { logger.info("executing test case testGroupByFixedLengthLongArrayWithGroupedHits"); SenseiRequest req = new SenseiRequest(); req.setCount(1); req.setGroupBy(new String[]{"virtual_groupid_fixedlengthlongarray"}); req.setMaxPerGroup(8); SenseiResult res = broker.browse(req); logger.info("request:" + req + "\nresult:" + res); SenseiHit hit = res.getSenseiHits()[0]; assertTrue(hit.getGroupHitsCount() > 0); assertTrue(hit.getSenseiGroupHits().length > 0); } public void testBQL1() throws Exception { logger.info("Executing test case testBQL1"); String req = "{\"bql\":\"select * from cars\"}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); } public void testBQL2() throws Exception { logger.info("Executing test case testBQL2"); String req = "{\"bql\":\"select * from cars where color = 'red'\"}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2160, res.getInt("numhits")); } public void testBqlExtraFilter() throws Exception { logger.info("Executing test case testBqlExtraFilter"); String req = "{\"bql\":\"select * from cars where color = 'red'\", \"bql_extra_filter\":\"year < 2000\"}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1534, res.getInt("numhits")); } public void testBqlEmptyListCheck() throws Exception { logger.info("Executing test case testBqlEmptyListCheck"); String req = "{\"bql\":\"SELECT * FROM SENSEI where () is not empty LIMIT 0, 1\"}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 0, res.getInt("numhits")); String req2 = "{\"bql\":\"SELECT * FROM SENSEI where () is empty LIMIT 0, 1\"}"; JSONObject res2 = search(new JSONObject(req2)); assertEquals("numhits is wrong", 15000, res2.getInt("numhits")); String req3 = "{\"bql\":\"select * from sensei where () is empty or color contains all () limit 0, 1\"}"; JSONObject res3 = search(new JSONObject(req3)); assertEquals("numhits is wrong", 15000, res3.getInt("numhits")); String req4 = "{\"bql\":\"select * from sensei where () is not empty or color contains all () limit 0, 1\"}"; JSONObject res4 = search(new JSONObject(req4)); assertEquals("numhits is wrong", 0, res4.getInt("numhits")); } public void testBqlRelevance1() throws Exception { logger.info("Executing test case testBqlRelevance1"); String req = "{\"bql\":\"SELECT * FROM cars USING RELEVANCE MODEL my_model (thisYear:2001, goodYear:[1996]) DEFINED AS (int thisYear, IntOpenHashSet goodYear) BEGIN if (goodYear.contains(year)) return (float)Math.exp(10d); if (year==thisYear) return 87f; return _INNER_SCORE; END\"}"; JSONObject res = search(new JSONObject(req)); JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); String firstYear = firstHit.getJSONArray("year").getString(0); String secondYear = secondHit.getJSONArray("year").getString(0); assertEquals("year 1996 should be on the top", true, firstYear.contains("1996")); assertEquals("year 1996 should be on the top", true, secondYear.contains("1996")); } public void testSelectionTerm() throws Exception { logger.info("executing test case Selection term"); String req = "{\"selections\":[{\"term\":{\"color\":{\"value\":\"red\"}}}]}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2160, res.getInt("numhits")); } public void testSelectionTerms() throws Exception { logger.info("executing test case Selection terms"); String req = "{\"selections\":[{\"terms\":{\"tags\":{\"values\":[\"mp3\",\"moon-roof\"],\"excludes\":[\"leather\"],\"operator\":\"or\"}}}]}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 4483, res.getInt("numhits")); } public void testSelectionDynamicTimeRangeJson() throws Exception { logger.info("executing test case Selection terms"); String req = "{\"selections\":[{\"term\":{\"timeRange\":{\"value\":\"000000013\"}}}]" + ", \"facetInit\":{ \"timeRange\":{\"time\" :{ \"type\" : \"long\",\"values\" : [15000] }}}" + "}"; System.out.println(req); JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 12990, res.getInt("numhits")); } public void testSelectionDynamicTimeRangeJson2() throws Exception { // Test scalar values in facet init parameters logger.info("executing test case Selection terms"); String req = "{\"selections\":[{\"term\":{\"timeRange\":{\"value\":\"000000013\"}}}]" + ", \"facetInit\":{ \"timeRange\":{\"time\" :{ \"type\" : \"long\",\"values\" : 15000 }}}" + "}"; System.out.println(req); JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 12990, res.getInt("numhits")); } public void testSelectionRange() throws Exception { //2000 1548; //2001 1443; //2002 1464; // [2000 TO 2002] ==> 4455 // (2000 TO 2002) ==> 1443 // (2000 TO 2002] ==> 2907 // [2000 TO 2002) ==> 2991 { logger.info("executing test case Selection range [2000 TO 2002]"); String req = "{\"selections\":[{\"range\":{\"year\":{\"to\":\"2002\",\"include_lower\":true,\"include_upper\":true,\"from\":\"2000\"}}}]}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 4455, res.getInt("numhits")); } { logger.info("executing test case Selection range (2000 TO 2002)"); String req = "{\"selections\":[{\"range\":{\"year\":{\"to\":\"2002\",\"include_lower\":false,\"include_upper\":false,\"from\":\"2000\"}}}]}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1443, res.getInt("numhits")); } { logger.info("executing test case Selection range (2000 TO 2002]"); String req = "{\"selections\":[{\"range\":{\"year\":{\"to\":\"2002\",\"include_lower\":false,\"include_upper\":true,\"from\":\"2000\"}}}]}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2907, res.getInt("numhits")); } { logger.info("executing test case Selection range [2000 TO 2002)"); String req = "{\"selections\":[{\"range\":{\"year\":{\"to\":\"2002\",\"include_lower\":true,\"include_upper\":false,\"from\":\"2000\"}}}]}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2991, res.getInt("numhits")); } } public void testMatchAllWithBoostQuery() throws Exception { logger.info("executing test case MatchAllQuery"); String req = "{\"query\": {\"match_all\": {\"boost\": \"1.2\"}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); } public void testQueryStringQuery() throws Exception { logger.info("executing test case testQueryStringQuery"); String req = "{\"query\": {\"query_string\": {\"query\": \"red AND cool\"}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1070, res.getInt("numhits")); } public void testMatchAllQuery() throws Exception { logger.info("executing test case testMatchAllQuery"); String req = "{\"query\": {\"match_all\": {}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); } public void testUIDQuery() throws Exception { logger.info("executing test case testUIDQuery"); String req = "{\"query\": {\"ids\": {\"values\": [\"1\", \"4\", \"3\", \"2\", \"6\"], \"excludes\": [\"2\"]}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 4, res.getInt("numhits")); Set<Integer> expectedIds = new HashSet(Arrays.asList(new Integer[]{1, 3, 4, 6})); for (int i = 0; i < res.getInt("numhits"); ++i) { int uid = res.getJSONArray("hits").getJSONObject(i).getInt("_uid"); assertTrue("_UID " + uid + " is not expected.", expectedIds.contains(uid)); } } public void testTextQuery() throws Exception { logger.info("executing test case testTextQuery"); String req = "{\"query\": {\"text\": {\"contents\": { \"value\": \"red cool\", \"operator\": \"and\"}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1070, res.getInt("numhits")); } public void testTermQuery() throws Exception { logger.info("executing test case testTermQuery"); String req = "{\"query\":{\"term\":{\"color\":\"red\"}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2160, res.getInt("numhits")); } public void testTermsQuery() throws Exception { logger.info("executing test case testTermQuery"); String req = "{\"query\":{\"terms\":{\"tags\":{\"values\":[\"leather\",\"moon-roof\"],\"excludes\":[\"hybrid\"],\"minimum_match\":0,\"operator\":\"or\"}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 5777, res.getInt("numhits")); } public void testBooleanQuery() throws Exception { logger.info("executing test case testBooleanQuery"); String req = "{\"query\":{\"bool\":{\"must_not\":{\"term\":{\"category\":\"compact\"}},\"must\":{\"term\":{\"color\":\"red\"}}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1652, res.getInt("numhits")); } public void testDistMaxQuery() throws Exception { //color red ==> 2160 //color blue ==> 1104 logger.info("executing test case testDistMaxQuery"); String req = "{\"query\":{\"dis_max\":{\"tie_breaker\":0.7,\"queries\":[{\"term\":{\"color\":\"red\"}},{\"term\":{\"color\":\"blue\"}}],\"boost\":1.2}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3264, res.getInt("numhits")); } public void testPathQuery() throws Exception { logger.info("executing test case testPathQuery"); String req = "{\"query\":{\"path\":{\"makemodel\":\"asian/acura/3.2tl\"}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 126, res.getInt("numhits")); } public void testPrefixQuery() throws Exception { //color blue ==> 1104 logger.info("executing test case testPrefixQuery"); String req = "{\"query\":{\"prefix\":{\"color\":{\"value\":\"blu\",\"boost\":2}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1104, res.getInt("numhits")); } public void testWildcardQuery() throws Exception { //color blue ==> 1104 logger.info("executing test case testWildcardQuery"); String req = "{\"query\":{\"wildcard\":{\"color\":{\"value\":\"bl*e\",\"boost\":2}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1104, res.getInt("numhits")); } public void testRangeQuery() throws Exception { logger.info("executing test case testRangeQuery"); String req = "{\"query\":{\"range\":{\"year\":{\"to\":2000,\"boost\":2,\"from\":1999,\"_noOptimize\":false}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3015, res.getInt("numhits")); } public void testRangeQuery2() throws Exception { logger.info("executing test case testRangeQuery2"); String req = "{\"query\":{\"range\":{\"year\":{\"to\":\"2000\",\"boost\":2,\"from\":\"1999\",\"_noOptimize\":true,\"_type\":\"int\"}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3015, res.getInt("numhits")); } public void testFilteredQuery() throws Exception { logger.info("executing test case testFilteredQuery"); String req ="{\"query\":{\"filtered\":{\"query\":{\"term\":{\"color\":\"red\"}},\"filter\":{\"range\":{\"year\":{\"to\":2000,\"from\":1999}}}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 447, res.getInt("numhits")); } public void testSpanTermQuery() throws Exception { logger.info("executing test case testSpanTermQuery"); String req = "{\"query\":{\"span_term\":{\"color\":\"red\"}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2160, res.getInt("numhits")); } public void testSpanOrQuery() throws Exception { logger.info("executing test case testSpanOrQuery"); String req = "{\"query\":{\"span_or\":{\"clauses\":[{\"span_term\":{\"color\":\"red\"}},{\"span_term\":{\"color\":\"blue\"}}]}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3264, res.getInt("numhits")); } public void testSpanNotQuery() throws Exception { logger.info("executing test case testSpanNotQuery"); String req = "{\"query\":{\"span_not\":{\"exclude\":{\"span_term\":{\"contents\":\"red\"}},\"include\":{\"span_term\":{\"contents\":\"compact\"}}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 4596, res.getInt("numhits")); } public void testSpanNearQuery1() throws Exception { logger.info("executing test case testSpanNearQuery1"); String req = "{\"query\":{\"span_near\":{\"in_order\":false,\"collect_payloads\":false,\"slop\":12,\"clauses\":[{\"span_term\":{\"contents\":\"red\"}},{\"span_term\":{\"contents\":\"compact\"}},{\"span_term\":{\"contents\":\"hybrid\"}}]}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 274, res.getInt("numhits")); } public void testSpanNearQuery2() throws Exception { logger.info("executing test case testSpanNearQuery2"); String req = "{\"query\":{\"span_near\":{\"in_order\":true,\"collect_payloads\":false,\"slop\":0,\"clauses\":[{\"span_term\":{\"contents\":\"red\"}},{\"span_term\":{\"contents\":\"compact\"}},{\"span_term\":{\"contents\":\"favorite\"}}]}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 63, res.getInt("numhits")); } public void testSpanFirstQuery() throws Exception { logger.info("executing test case testSpanFirstQuery"); String req = "{\"query\":{\"span_first\":{\"match\":{\"span_term\":{\"color\":\"red\"}},\"end\":2}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2160, res.getInt("numhits")); } public void testConstExpQuery() throws Exception { logger.info("executing test case testConstExpQuery"); String pos_req1 = "{\"query\":{\"const_exp\":{\"lvalue\":\"6\",\"rvalue\":\"6\",\"operator\":\"==\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String pos_req2 = "{\"query\":{\"const_exp\":{\"lvalue\":6,\"rvalue\":6,\"operator\":\"==\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String pos_req3 = "{\"query\":{\"const_exp\":{\"lvalue\":[6,7],\"rvalue\":[6,7],\"operator\":\"==\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String pos_req4 = "{\"query\":{\"const_exp\":{\"lvalue\":[7],\"rvalue\":[7],\"operator\":\"==\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String pos_req5 = "{\"query\":{\"const_exp\":{\"lvalue\":[\"7\",\"8\"],\"rvalue\":[\"8\",\"7\"],\"operator\":\"==\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String pos_req6 = "{\"query\":{\"const_exp\":{\"lvalue\":6,\"rvalue\":[6,7],\"operator\":\"in\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String pos_req7 = "{\"query\":{\"const_exp\":{\"lvalue\":[6],\"rvalue\":[6,7],\"operator\":\"in\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String pos_req8 = "{\"query\":{\"const_exp\":{\"lvalue\":6,\"rvalue\":[16,7],\"operator\":\"not_in\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String pos_req9 = "{\"query\":{\"const_exp\":{\"lvalue\":6,\"rvalue\":3,\"operator\":\">\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String pos_req10 = "{\"query\":{\"const_exp\":{\"lvalue\":6,\"rvalue\":6,\"operator\":\">=\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String pos_req11 = "{\"query\":{\"const_exp\":{\"lvalue\":{\"params\":[[1]],\"function\":\"length\"},\"rvalue\":0,\"operator\":\">=\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String pos_req12 = "{\"query\":{\"const_exp\":{\"lvalue\":{\"params\":[[1,2]],\"function\":\"length\"},\"rvalue\":0,\"operator\":\">=\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String pos_req13 = "{\"query\":{\"const_exp\":{\"lvalue\":{\"params\":[[\"1\"]],\"function\":\"length\"},\"rvalue\":0,\"operator\":\">=\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String pos_req14 = "{\"query\":{\"const_exp\":{\"lvalue\":{\"params\":[[\"1\",\"2\"]],\"function\":\"length\"},\"rvalue\":0,\"operator\":\">=\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String pos_req15 = "{\"query\":{\"const_exp\":{\"lvalue\":{\"params\":[[]],\"function\":\"length\"},\"rvalue\":0,\"operator\":\"==\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; assertEquals("numhits is wrong pos_req1", 15000, search(new JSONObject(pos_req1)).getInt("numhits")); assertEquals("numhits is wrong pos_req2", 15000, search(new JSONObject(pos_req2)).getInt("numhits")); assertEquals("numhits is wrong pos_req3", 15000, search(new JSONObject(pos_req3)).getInt("numhits")); assertEquals("numhits is wrong pos_req4", 15000, search(new JSONObject(pos_req4)).getInt("numhits")); assertEquals("numhits is wrong pos_req5", 15000, search(new JSONObject(pos_req5)).getInt("numhits")); assertEquals("numhits is wrong pos_req6", 15000, search(new JSONObject(pos_req6)).getInt("numhits")); assertEquals("numhits is wrong pos_req7", 15000, search(new JSONObject(pos_req7)).getInt("numhits")); assertEquals("numhits is wrong pos_req8", 15000, search(new JSONObject(pos_req8)).getInt("numhits")); assertEquals("numhits is wrong pos_req9", 15000, search(new JSONObject(pos_req9)).getInt("numhits")); assertEquals("numhits is wrong pos_req10", 15000, search(new JSONObject(pos_req10)).getInt("numhits")); assertEquals("numhits is wrong pos_req11", 15000, search(new JSONObject(pos_req11)).getInt("numhits")); assertEquals("numhits is wrong pos_req12", 15000, search(new JSONObject(pos_req12)).getInt("numhits")); assertEquals("numhits is wrong pos_req13", 15000, search(new JSONObject(pos_req13)).getInt("numhits")); assertEquals("numhits is wrong pos_req14", 15000, search(new JSONObject(pos_req14)).getInt("numhits")); assertEquals("numhits is wrong pos_req15", 15000, search(new JSONObject(pos_req15)).getInt("numhits")); String neg_req1 = "{\"query\":{\"const_exp\":{\"lvalue\":6,\"rvalue\":[16,7],\"operator\":\"in\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String neg_req2 = "{\"query\":{\"const_exp\":{\"lvalue\":[6],\"rvalue\":[5,7],\"operator\":\"in\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String neg_req3 = "{\"query\":{\"const_exp\":{\"lvalue\":6,\"rvalue\":[6,7],\"operator\":\"not_in\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String neg_req4 = "{\"query\":{\"const_exp\":{\"lvalue\":[6],\"rvalue\":[6,7],\"operator\":\"not_in\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String neg_req5 = "{\"query\":{\"const_exp\":{\"lvalue\":6,\"rvalue\":8,\"operator\":\">\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String neg_req6 = "{\"query\":{\"const_exp\":{\"lvalue\":{\"params\":[[]],\"function\":\"length\"},\"rvalue\":0,\"operator\":\">\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; String neg_req7 = "{\"query\":{\"const_exp\":{\"lvalue\":{\"params\":[[4,5]],\"function\":\"length\"},\"rvalue\":0,\"operator\":\"==\"}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":10}"; assertEquals("numhits is wrong neg_req1", 0, search(new JSONObject(neg_req1)).getInt("numhits")); assertEquals("numhits is wrong neg_req2", 0, search(new JSONObject(neg_req2)).getInt("numhits")); assertEquals("numhits is wrong neg_req3", 0, search(new JSONObject(neg_req3)).getInt("numhits")); assertEquals("numhits is wrong neg_req4", 0, search(new JSONObject(neg_req4)).getInt("numhits")); assertEquals("numhits is wrong neg_req5", 0, search(new JSONObject(neg_req5)).getInt("numhits")); assertEquals("numhits is wrong neg_req6", 0, search(new JSONObject(neg_req6)).getInt("numhits")); assertEquals("numhits is wrong neg_req7", 0, search(new JSONObject(neg_req7)).getInt("numhits")); } public void testNullMultiFilter() throws Exception { logger.info("executing test case testNullFilter"); String req = "{\"filter\":{\"isNull\":\"groupid_multi\"}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 14997, res.getInt("numhits")); } public void testNullFilterOnSimpleColumn() throws Exception { logger.info("executing test case testNullFilter"); String req = "{\"filter\":{\"isNull\":\"price\"}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1, res.getInt("numhits")); } public void testUIDFilter() throws Exception { logger.info("executing test case testUIDFilter"); String req = "{\"filter\": {\"ids\": {\"values\": [\"1\", \"2\", \"3\"], \"excludes\": [\"2\"]}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2, res.getInt("numhits")); Set<Integer> expectedIds = new HashSet(Arrays.asList(new Integer[]{1, 3})); for (int i = 0; i < res.getInt("numhits"); ++i) { int uid = res.getJSONArray("hits").getJSONObject(i).getInt("_uid"); assertTrue("_UID " + uid + " is not expected.", expectedIds.contains(uid)); } } public void testAndFilter() throws Exception { logger.info("executing test case testAndFilter"); String req = "{\"filter\":{\"and\":[{\"term\":{\"tags\":\"mp3\",\"_noOptimize\":false}},{\"term\":{\"color\":\"red\",\"_noOptimize\":false}}]}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 439, res.getInt("numhits")); } public void testOrFilter() throws Exception { logger.info("executing test case testOrFilter"); String req = "{\"filter\":{\"or\":[{\"term\":{\"color\":\"blue\",\"_noOptimize\":true}},{\"term\":{\"color\":\"red\",\"_noOptimize\":true}}]}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3264, res.getInt("numhits")); } public void testOrFilter2() throws Exception { logger.info("executing test case testOrFilter2"); String req = "{\"filter\":{\"or\":[{\"term\":{\"color\":\"blue\",\"_noOptimize\":false}},{\"term\":{\"color\":\"red\",\"_noOptimize\":false}}]}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3264, res.getInt("numhits")); } public void testOrFilter3() throws Exception { logger.info("executing test case testOrFilter3"); String req = "{\"filter\":{\"or\":[{\"term\":{\"color\":\"blue\",\"_noOptimize\":true}},{\"term\":{\"color\":\"red\",\"_noOptimize\":false}}]}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3264, res.getInt("numhits")); } public void testBooleanFilter() throws Exception { logger.info("executing test case testBooleanFilter"); String req = "{\"filter\":{\"bool\":{\"must_not\":{\"term\":{\"category\":\"compact\"}},\"should\":[{\"term\":{\"color\":\"red\"}},{\"term\":{\"color\":\"green\"}}],\"must\":{\"term\":{\"color\":\"red\"}}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 1652, res.getInt("numhits")); } public void testQueryFilter() throws Exception { logger.info("executing test case testQueryFilter"); String req = "{\"filter\": {\"query\":{\"range\":{\"year\":{\"to\":2000,\"boost\":2,\"from\":1999,\"_noOptimize\":false}}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3015, res.getInt("numhits")); } /* Need to fix the bug in bobo and kamikazi, for details see the following two test cases:*/ public void testAndFilter1() throws Exception { logger.info("executing test case testAndFilter1"); String req = "{\"filter\":{\"and\":[{\"term\":{\"color\":\"blue\",\"_noOptimize\":false}},{\"query\":{\"term\":{\"category\":\"compact\"}}}]}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 504, res.getInt("numhits")); } public void testQueryFilter1() throws Exception { logger.info("executing test case testQueryFilter1"); String req = "{\"filter\": {\"query\":{\"term\":{\"category\":\"compact\"}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 4169, res.getInt("numhits")); } /* another weird bug may exist somewhere in bobo or kamikazi.*/ /* In the following two test cases, when modifying the first one by changing "tags" to "tag", it is supposed that * Only the first test case is not correct, but the second one also throw one NPE, which is weird. * */ public void testAndFilter2() throws Exception { logger.info("executing test case testAndFilter2"); String req = "{\"filter\":{\"and\":[{\"term\":{\"tags\":\"mp3\",\"_noOptimize\":false}},{\"query\":{\"term\":{\"color\":\"red\"}}}]}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 439, res.getInt("numhits")); } public void testOrFilter4() throws Exception { //color:blue ==> 1104 //color:red ==> 2160 logger.info("executing test case testOrFilter4"); String req = "{\"filter\":{\"or\":[{\"term\":{\"color\":\"blue\",\"_noOptimize\":false}},{\"query\":{\"term\":{\"color\":\"red\"}}}]}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3264, res.getInt("numhits")); } public void testTermFilter() throws Exception { logger.info("executing test case testTermFilter"); String req = "{\"filter\":{\"term\":{\"color\":\"red\"}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 2160, res.getInt("numhits")); } public void testTermsFilter() throws Exception { logger.info("executing test case testTermsFilter"); String req = "{\"filter\":{\"terms\":{\"tags\":{\"values\":[\"leather\",\"moon-roof\"],\"excludes\":[\"hybrid\"],\"minimum_match\":0,\"operator\":\"or\"}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 5777, res.getInt("numhits")); } public void testRangeFilter() throws Exception { logger.info("executing test case testRangeFilter"); String req = "{\"filter\":{\"range\":{\"year\":{\"to\":2000,\"boost\":2,\"from\":1999,\"_noOptimize\":false}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3015, res.getInt("numhits")); } public void testRangeFilter2() throws Exception { logger.info("executing test case testRangeFilter2"); String req = "{\"filter\":{\"range\":{\"year\":{\"to\":\"2000\",\"boost\":2,\"from\":\"1999\",\"_noOptimize\":true,\"_type\":\"int\"}}}}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 3015, res.getInt("numhits")); } public void testRangeFilter3() throws Exception { logger.info("executing test case testRangeFilter3"); String req = "{\"fetchStored\":true,\"selections\":[{\"term\":{\"color\":{\"value\":\"red\"}}}],\"from\":0,\"filter\":{\"query\":{\"query_string\":{\"query\":\"cool AND moon-roof AND hybrid\"}}},\"size\":10}"; JSONObject res = search(new JSONObject(req)); //TODO Sensei returns undeterministic results for this query. Will create a Jira ticket assertTrue("numhits is wrong", res.getInt("numhits") > 10); } public void testFallbackGroupBy() throws Exception { logger.info("executing test case testFallbackGroupBy"); String req = "{\"from\": 0,\"size\": 10,\"groupBy\": {\"columns\": [\"virtual_groupid_fixedlengthlongarray\", \"color\"],\"top\": 2}, \"sort\": [{\"color\": \"asc\"}]}"; JSONObject res = search(new JSONObject(req)); JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); assertTrue("groupfield is wrong", "color".equals(firstHit.getString("groupfield")) || "virtual_groupid_fixedlengthlongarray".equals(firstHit.getString("groupfield"))); assertTrue("no group hits", firstHit.getJSONArray("grouphits") != null); } public void testGetStoreRequest() throws Exception { logger.info("executing test case testGetStoreRequest"); String req = "[1,2,3,5]"; JSONObject res = searchGet(new JSONArray(req)); //TODO Sensei returns undeterministic results for this query. Will create a Jira issue assertTrue("numhits is wrong", res.length() == 4); assertNotNull("", res.get(String.valueOf(1))); } public void testRelevanceMatchAll() throws Exception { logger.info("executing test case testRelevanceMatchAll"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"long\":[\"groupid\"]},\"function\":\" if(goodYear.contains(year)) return (float)Math.exp(10d); if(year==thisYear) return 87f ; return _INNER_SCORE ;\",\"variables\":{\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"]}},\"values\":{\"thisYear\":2001,\"goodYear\":[1996,1997]}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); } public void testRelevanceHashSet() throws Exception { logger.info("executing test case testRelevanceHashSet"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"long\":[\"groupid\"]},\"function\":\" if(goodYear.contains(year)) return (float)Math.exp(10d); if(year==thisYear) return 87f ; return _INNER_SCORE ;\",\"variables\":{\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"]}},\"values\":{\"thisYear\":2001,\"goodYear\":[1996]}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); String firstYear = firstHit.getJSONArray("year").getString(0); String secondYear = secondHit.getJSONArray("year").getString(0); assertEquals("year 1996 should be on the top", true, firstYear.contains("1996")); assertEquals("year 1996 should be on the top", true, secondYear.contains("1996")); } public void testRelevanceMath() throws Exception { logger.info("executing test case testRelevanceMath"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"long\":[\"groupid\"]},\"function\":\" if(goodYear.contains(year)) return (float)Math.exp(10d); if(year==thisYear) return 87f ; return _INNER_SCORE ;\",\"variables\":{\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"]}},\"values\":{\"thisYear\":2001,\"goodYear\":[1996]}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); double firstScore = firstHit.getDouble("_score"); double secondScore = secondHit.getDouble("_score"); double delta1 = firstScore - Math.exp(10d); double delta2 = secondScore - Math.exp(10d); assertEquals("score for first is not correct. delta is: " + delta1, true, Math.abs(delta1) < 0.001 ); assertEquals("score for second is not correct. delta is: " + delta2, true, Math.abs(delta2) < 0.001); } public void testRelevanceInnerScore() throws Exception { logger.info("executing test case testRelevanceInnerScore"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"long\":[\"groupid\"]},\"function\":\" if(goodYear.contains(year)) return _INNER_SCORE ; return _INNER_SCORE ;\",\"variables\":{\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"]}},\"values\":{\"thisYear\":2001,\"goodYear\":[1996]}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); double firstScore = firstHit.getDouble("_score"); double secondScore = secondHit.getDouble("_score"); assertEquals("inner score for first is not correct." , true, firstScore == 1 ); assertEquals("inner score for second is not correct." , true, secondScore == 1); } public void testRelevanceNOW() throws Exception { logger.info("executing test case testRelevanceNOW"); // Assume that the difference between request side "now" and node side "_NOW" is less than 2000ms. String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"year\",\"goodYear\",\"_NOW\",\"now\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"long\":[\"groupid\"]},\"function\":\" if(Math.abs(_NOW - now) < 2000) return 10000f; if(goodYear.contains(year)) return _INNER_SCORE ; return _INNER_SCORE ;\",\"variables\":{\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"],\"long\":[\"now\"]}},\"values\":{\"thisYear\":2001,\"now\":"+ System.currentTimeMillis() +",\"goodYear\":[1996]}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); double firstScore = firstHit.getDouble("_score"); double secondScore = secondHit.getDouble("_score"); assertEquals("inner score for first is not correct." , true, firstScore == 10000f ); assertEquals("inner score for second is not correct." , true, secondScore == 10000f); } public void testRelevanceHashMapInt2Float() throws Exception { logger.info("executing test case testRelevanceHashMapInt2Float"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\",\"mileageWeight\",\"mileage\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"long\":[\"groupid\"]},\"function\":\" if(mileageWeight.containsKey(mileage)) return 10000+mileageWeight.get(mileage); if(goodYear.contains(year)) return (float)Math.exp(2d); if(year==thisYear) return 87f ; return _INNER_SCORE;\",\"variables\":{\"map_int_float\":[\"mileageWeight\"],\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"]}},\"values\":{\"thisYear\":2001,\"mileageWeight\":{\"11400\":777.9, \"11000\":10.2},\"goodYear\":[1996,1997]}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); //the first one should has socre 10777.900390625, and mileage: 11400; JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); double firstScore = firstHit.getDouble("_score"); double secondScore = secondHit.getDouble("_score"); String firstMileage = firstHit.getJSONArray("mileage").getString(0); String secondMileage = secondHit.getJSONArray("mileage").getString(0); assertEquals("inner score for first is not correct." , true, Math.abs(firstScore - 10777.900390625) < 1 ); assertEquals("inner score for second is not correct." , true, Math.abs(secondScore - 10777.900390625) < 1 ); assertEquals("mileage for first is not correct." , true, Integer.parseInt(firstMileage)==11400 ); assertEquals("mileage for second is not correct." , true, Integer.parseInt(secondMileage)==11400 ); } public void testRelevanceHashMapInt2String() throws Exception { logger.info("executing test case testRelevanceHashMapInt2String"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\",\"mileageWeight\",\"mileage\",\"color\",\"yearcolor\",\"colorweight\",\"category\",\"categorycolor\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"string\":[\"color\",\"category\"],\"long\":[\"groupid\"]},\"function\":\"if(yearcolor.containsKey(year) && yearcolor.get(year).equals(color)) return 100000f; if(goodYear.contains(year)) return (float)Math.exp(2d); if(year==thisYear) return 87f ; return _INNER_SCORE;\",\"variables\":{\"map_int_float\":[\"mileageWeight\"],\"map_int_string\":[\"yearcolor\"],\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"],\"map_string_float\":[\"colorweight\"],\"map_string_string\":[\"categorycolor\"]}},\"values\":{\"thisYear\":2001,\"yearcolor\":{\"1998\":\"red\"},\"mileageWeight\":{\"11400\":777.9, \"11000\":10.2},\"colorweight\":{\"red\":335.5},\"goodYear\":[1996,1997],\"categorycolor\":{\"compact\":\"red\"}}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); //the first one should has socre 10777.900390625, and mileage: 11400; JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); double firstScore = firstHit.getDouble("_score"); double secondScore = secondHit.getDouble("_score"); String firstYear = firstHit.getJSONArray("year").getString(0); String secondYear = secondHit.getJSONArray("year").getString(0); String firstColor = firstHit.getJSONArray("color").getString(0); String secondColor = secondHit.getJSONArray("color").getString(0); assertEquals("inner score for first is not correct." , true, Math.abs(firstScore - 100000) < 1 ); assertEquals("inner score for second is not correct." , true, Math.abs(secondScore - 100000) < 1 ); assertEquals("year for first is not correct." , true, Integer.parseInt(firstYear)==1998 ); assertEquals("year for second is not correct." , true, Integer.parseInt(secondYear)==1998 ); assertEquals("color for first is not correct." , true, firstColor.equals("red") ); assertEquals("color for second is not correct." , true, secondColor.equals("red") ); } public void testRelevanceHashMapString2Float() throws Exception { logger.info("executing test case testRelevanceHashMapString2Float"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\",\"mileageWeight\",\"mileage\",\"color\",\"yearcolor\",\"colorweight\",\"category\",\"categorycolor\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"string\":[\"color\",\"category\"],\"long\":[\"groupid\"]},\"function\":\" if(colorweight.containsKey(color) ) return 200f + colorweight.getFloat(color); if(year==thisYear) return 87f ; return _INNER_SCORE;\",\"variables\":{\"map_int_float\":[\"mileageWeight\"],\"map_int_string\":[\"yearcolor\"],\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"],\"map_string_float\":[\"colorweight\"],\"map_string_string\":[\"categorycolor\"]}},\"values\":{\"thisYear\":2001,\"yearcolor\":{\"1998\":\"red\"},\"mileageWeight\":{\"11400\":777.9, \"11000\":10.2},\"colorweight\":{\"red\":335.5},\"goodYear\":[1996,1997],\"categorycolor\":{\"compact\":\"red\"}}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); //the first one should has socre 10777.900390625, and mileage: 11400; JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); double firstScore = firstHit.getDouble("_score"); double secondScore = secondHit.getDouble("_score"); String firstColor = firstHit.getJSONArray("color").getString(0); String secondColor = secondHit.getJSONArray("color").getString(0); assertEquals("inner score for first is not correct." , true, Math.abs(firstScore - 535.5) < 1 ); assertEquals("inner score for second is not correct." , true, Math.abs(secondScore - 535.5) < 1 ); assertEquals("color for first is not correct." , true, firstColor.equals("red") ); assertEquals("color for second is not correct." , true, secondColor.equals("red") ); } public void testRelevanceHashMapString2String() throws Exception { logger.info("executing test case testRelevanceHashMapString2String"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\",\"mileageWeight\",\"mileage\",\"color\",\"yearcolor\",\"colorweight\",\"category\",\"categorycolor\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"string\":[\"color\",\"category\"],\"long\":[\"groupid\"]},\"function\":\" if(categorycolor.containsKey(category) && categorycolor.get(category).equals(color)) return 10000f; if(year==thisYear) return 87f ; return _INNER_SCORE;\",\"variables\":{\"map_int_float\":[\"mileageWeight\"],\"map_int_string\":[\"yearcolor\"],\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"],\"map_string_float\":[\"colorweight\"],\"map_string_string\":[\"categorycolor\"]}},\"values\":{\"thisYear\":2001,\"yearcolor\":{\"1998\":\"red\"},\"mileageWeight\":{\"11400\":777.9, \"11000\":10.2},\"colorweight\":{\"red\":335.5},\"goodYear\":[1996,1997],\"categorycolor\":{\"compact\":\"red\"}}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); //the first one should has socre 10777.900390625, and mileage: 11400; JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); double firstScore = firstHit.getDouble("_score"); double secondScore = secondHit.getDouble("_score"); String firstCategory = firstHit.getJSONArray("category").getString(0); String secondCategory = secondHit.getJSONArray("category").getString(0); String firstColor = firstHit.getJSONArray("color").getString(0); String secondColor = secondHit.getJSONArray("color").getString(0); assertEquals("inner score for first is not correct." , true, Math.abs(firstScore - 10000) < 1 ); assertEquals("inner score for second is not correct." , true, Math.abs(secondScore - 10000) < 1 ); assertEquals("category for first is not correct." , true, firstCategory.equals("compact") ); assertEquals("category for second is not correct." , true, secondCategory.equals("compact") ); assertEquals("color for first is not correct." , true, firstColor.equals("red") ); assertEquals("color for second is not correct." , true, secondColor.equals("red") ); } public void testRelevanceHashMapInt2FloatArrayWay() throws Exception { logger.info("executing test case testRelevanceHashMapInt2FloatArrayWay"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\",\"mileageWeight\",\"mileage\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"long\":[\"groupid\"]},\"function\":\" if(mileageWeight.containsKey(mileage)) return 10000+mileageWeight.get(mileage); if(goodYear.contains(year)) return (float)Math.exp(2d); if(year==thisYear) return 87f ; return _INNER_SCORE;\",\"variables\":{\"map_int_float\":[\"mileageWeight\"],\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"]}},\"values\":{\"thisYear\":2001,\"mileageWeight\":{\"value\":[777.9,10.2],\"key\":[11400,11000]},\"goodYear\":[1996,1997]}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); //the first one should has socre 10777.900390625, and mileage: 11400; JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); double firstScore = firstHit.getDouble("_score"); double secondScore = secondHit.getDouble("_score"); String firstMileage = firstHit.getJSONArray("mileage").getString(0); String secondMileage = secondHit.getJSONArray("mileage").getString(0); assertEquals("inner score for first is not correct." , true, Math.abs(firstScore - 10777.900390625) < 1 ); assertEquals("inner score for second is not correct." , true, Math.abs(secondScore - 10777.900390625) < 1 ); assertEquals("mileage for first is not correct." , true, Integer.parseInt(firstMileage)==11400 ); assertEquals("mileage for second is not correct." , true, Integer.parseInt(secondMileage)==11400 ); } public void testRelevanceHashMapInt2StringArrayWay() throws Exception { logger.info("executing test case testRelevanceHashMapInt2StringArrayWay"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\",\"mileageWeight\",\"mileage\",\"color\",\"yearcolor\",\"colorweight\",\"category\",\"categorycolor\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"string\":[\"color\",\"category\"],\"long\":[\"groupid\"]},\"function\":\"if(yearcolor.containsKey(year) && yearcolor.get(year).equals(color)) return 100000f; if(goodYear.contains(year)) return (float)Math.exp(2d); if(year==thisYear) return 87f ; return _INNER_SCORE;\",\"variables\":{\"map_int_float\":[\"mileageWeight\"],\"map_int_string\":[\"yearcolor\"],\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"],\"map_string_float\":[\"colorweight\"],\"map_string_string\":[\"categorycolor\"]}},\"values\":{\"thisYear\":2001,\"yearcolor\":{\"value\":[\"red\"],\"key\":[1998]},\"mileageWeight\":{\"value\":[777.9,10.2],\"key\":[11400,11000]},\"colorweight\":{\"value\":[335.5],\"key\":[\"red\"]},\"goodYear\":[1996,1997],\"categorycolor\":{\"value\":[\"red\"],\"key\":[\"compact\"]}}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); //the first one should has socre 10777.900390625, and mileage: 11400; JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); double firstScore = firstHit.getDouble("_score"); double secondScore = secondHit.getDouble("_score"); String firstYear = firstHit.getJSONArray("year").getString(0); String secondYear = secondHit.getJSONArray("year").getString(0); String firstColor = firstHit.getJSONArray("color").getString(0); String secondColor = secondHit.getJSONArray("color").getString(0); assertEquals("inner score for first is not correct." , true, Math.abs(firstScore - 100000) < 1 ); assertEquals("inner score for second is not correct." , true, Math.abs(secondScore - 100000) < 1 ); assertEquals("year for first is not correct." , true, Integer.parseInt(firstYear)==1998 ); assertEquals("year for second is not correct." , true, Integer.parseInt(secondYear)==1998 ); assertEquals("color for first is not correct." , true, firstColor.equals("red") ); assertEquals("color for second is not correct." , true, secondColor.equals("red") ); } public void testRelevanceHashMapString2FloatArrayWay() throws Exception { logger.info("executing test case testRelevanceHashMapString2FloatArrayWay"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\",\"mileageWeight\",\"mileage\",\"color\",\"yearcolor\",\"colorweight\",\"category\",\"categorycolor\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"string\":[\"color\",\"category\"],\"long\":[\"groupid\"]},\"function\":\" if(colorweight.containsKey(color) ) return 200f + colorweight.getFloat(color); if(year==thisYear) return 87f ; return _INNER_SCORE;\",\"variables\":{\"map_int_float\":[\"mileageWeight\"],\"map_int_string\":[\"yearcolor\"],\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"],\"map_string_float\":[\"colorweight\"],\"map_string_string\":[\"categorycolor\"]}},\"values\":{\"thisYear\":2001,\"yearcolor\":{\"value\":[\"red\"],\"key\":[1998]},\"mileageWeight\":{\"value\":[777.9,10.2],\"key\":[11400,11000]},\"colorweight\":{\"value\":[335.5],\"key\":[\"red\"]},\"goodYear\":[1996,1997],\"categorycolor\":{\"value\":[\"red\"],\"key\":[\"compact\"]}}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); //the first one should has socre 10777.900390625, and mileage: 11400; JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); double firstScore = firstHit.getDouble("_score"); double secondScore = secondHit.getDouble("_score"); String firstColor = firstHit.getJSONArray("color").getString(0); String secondColor = secondHit.getJSONArray("color").getString(0); assertEquals("inner score for first is not correct." , true, Math.abs(firstScore - 535.5) < 1 ); assertEquals("inner score for second is not correct." , true, Math.abs(secondScore - 535.5) < 1 ); assertEquals("color for first is not correct." , true, firstColor.equals("red") ); assertEquals("color for second is not correct." , true, secondColor.equals("red") ); } public void testRelevanceHashMapString2StringArrayWay() throws Exception { logger.info("executing test case testRelevanceHashMapString2StringArrayWay"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\",\"mileageWeight\",\"mileage\",\"color\",\"yearcolor\",\"colorweight\",\"category\",\"categorycolor\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"string\":[\"color\",\"category\"],\"long\":[\"groupid\"]},\"function\":\" if(categorycolor.containsKey(category) && categorycolor.get(category).equals(color)) return 10000f; if(year==thisYear) return 87f ; return _INNER_SCORE;\",\"variables\":{\"map_int_float\":[\"mileageWeight\"],\"map_int_string\":[\"yearcolor\"],\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"],\"map_string_float\":[\"colorweight\"],\"map_string_string\":[\"categorycolor\"]}},\"values\":{\"thisYear\":2001,\"yearcolor\":{\"value\":[\"red\"],\"key\":[1998]},\"mileageWeight\":{\"value\":[777.9,10.2],\"key\":[11400,11000]},\"colorweight\":{\"value\":[335.5],\"key\":[\"red\"]},\"goodYear\":[1996,1997],\"categorycolor\":{\"value\":[\"red\"],\"key\":[\"compact\"]}}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); //the first one should has socre 10777.900390625, and mileage: 11400; JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); double firstScore = firstHit.getDouble("_score"); double secondScore = secondHit.getDouble("_score"); String firstCategory = firstHit.getJSONArray("category").getString(0); String secondCategory = secondHit.getJSONArray("category").getString(0); String firstColor = firstHit.getJSONArray("color").getString(0); String secondColor = secondHit.getJSONArray("color").getString(0); assertEquals("inner score for first is not correct." , true, Math.abs(firstScore - 10000) < 1 ); assertEquals("inner score for second is not correct." , true, Math.abs(secondScore - 10000) < 1 ); assertEquals("category for first is not correct." , true, firstCategory.equals("compact") ); assertEquals("category for second is not correct." , true, secondCategory.equals("compact") ); assertEquals("color for first is not correct." , true, firstColor.equals("red") ); assertEquals("color for second is not correct." , true, secondColor.equals("red") ); } public void testRelevanceMultiContains() throws Exception { logger.info("executing test case testRelevanceMultiContains"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\",\"tags\",\"coolTag\"],\"facets\":{\"mstring\":[\"tags\"],\"int\":[\"year\",\"mileage\"],\"long\":[\"groupid\"]},\"function\":\" if(tags.contains(coolTag)) return 999999f; if(goodYear.contains(year)) return (float)Math.exp(10d); if(year==thisYear) return 87f ; return _INNER_SCORE ;\",\"variables\":{\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"], \"string\":[\"coolTag\"]}},\"values\":{\"coolTag\":\"cool\", \"thisYear\":2001,\"goodYear\":[1996,1997]}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); } public void testRelevanceMultiContainsAny() throws Exception { logger.info("executing test case testRelevanceMultiContainsAny"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\",\"tags\",\"goodTags\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"mstring\":[\"tags\"],\"long\":[\"groupid\"]},\"function\":\" if(tags.containsAny(goodTags)) return 100000f; if(goodYear.contains(year)) return (float)Math.exp(10d); if(year==thisYear) return 87f ; return _INNER_SCORE ;\",\"variables\":{\"set_string\":[\"goodTags\"],\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"]}},\"values\":{\"thisYear\":2001,\"goodTags\":[\"leather\"],\"goodYear\":[1996,1997]}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); double firstScore = firstHit.getDouble("_score"); double secondScore = secondHit.getDouble("_score"); JSONArray firstTags = firstHit.getJSONArray("tags"); JSONArray secondTags = secondHit.getJSONArray("tags"); assertEquals("inner score for first is not correct." , true, Math.abs(firstScore - 100000) < 1 ); assertEquals("inner score for second is not correct." , true, Math.abs(secondScore - 100000) < 1 ); assertEquals("tags for first is not correct." , true, containsString(firstTags, "leather") ); assertEquals("tags for second is not correct." , true, containsString(secondTags, "leather") ); } public void testRelevanceModelStorageInMemory() throws Exception { logger.info("executing test case testRelevanceModelStorageInMemory"); // store the model; { String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"save_as\":{\"overwrite\":true,\"name\":\"myModel\"},\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\",\"mileageWeight\",\"mileage\",\"color\",\"yearcolor\",\"colorweight\",\"category\",\"categorycolor\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"string\":[\"color\",\"category\"],\"long\":[\"groupid\"]},\"function\":\" if(categorycolor.containsKey(category) && categorycolor.get(category).equals(color)) return 10000f; if(colorweight.containsKey(color) ) return 200f + colorweight.getFloat(color); if(yearcolor.containsKey(year) && yearcolor.get(year).equals(color)) return 200f; if(mileageWeight.containsKey(mileage)) return 10000+mileageWeight.get(mileage); if(goodYear.contains(year)) return (float)Math.exp(2d); if(year==thisYear) return 87f ; return _INNER_SCORE;\",\"variables\":{\"map_int_float\":[\"mileageWeight\"],\"map_int_string\":[\"yearcolor\"],\"set_int\":[\"goodYear\"],\"int\":[\"thisYear\"],\"map_string_float\":[\"colorweight\"],\"map_string_string\":[\"categorycolor\"]}},\"values\":{\"thisYear\":2001,\"yearcolor\":{\"value\":[\"red\"],\"key\":[1998]},\"mileageWeight\":{\"value\":[777.9,10.2],\"key\":[11400,11000]},\"colorweight\":{\"value\":[335.5],\"key\":[\"red\"]},\"goodYear\":[1996,1997],\"categorycolor\":{\"value\":[\"red\"],\"key\":[\"compact\"]}}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); double firstScore = firstHit.getDouble("_score"); double secondScore = secondHit.getDouble("_score"); assertEquals("inner score for first is not correct." , true, Math.abs(firstScore - 10777.9) < 1 ); assertEquals("inner score for second is not correct." , true, Math.abs(secondScore - 10777.9) < 1 ); } // assuming the model is already stored, test new query using only stored model name; { String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"predefined_model\":\"myModel\",\"values\":{\"thisYear\":2001,\"yearcolor\":{\"value\":[\"red\"],\"key\":[1998]},\"mileageWeight\":{\"value\":[777.9,10.2],\"key\":[11400,11000]},\"colorweight\":{\"value\":[335.5],\"key\":[\"red\"]},\"goodYear\":[1996,1997],\"categorycolor\":{\"value\":[\"red\"],\"key\":[\"compact\"]}}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":6}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); JSONObject secondHit = hits.getJSONObject(1); double firstScore = firstHit.getDouble("_score"); double secondScore = secondHit.getDouble("_score"); assertEquals("inner score for first is not correct." , true, Math.abs(firstScore - 10777.9) < 1 ); assertEquals("inner score for second is not correct." , true, Math.abs(secondScore - 10777.9) < 1 ); } } public void testRelevanceExternalObject() throws Exception { logger.info("executing test case testRelevanceExternalObject"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\",\"mileageWeight\",\"mileage\",\"color\",\"yearcolor\",\"colorweight\",\"category\",\"categorycolor\",\"test_obj2\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"string\":[\"color\",\"category\"],\"long\":[\"groupid\"]},\"function\":\" if(test_obj2.contains(color)) return 20000f; if(categorycolor.containsKey(category) && categorycolor.get(category).equals(color)) return 10000f; if(colorweight.containsKey(color) ) return 200f + colorweight.getFloat(color); if(yearcolor.containsKey(year) && yearcolor.get(year).equals(color)) return 200f; if(mileageWeight.containsKey(mileage)) return 10000+mileageWeight.get(mileage); if(goodYear.contains(year)) return (float)Math.exp(2d); if(year==thisYear) return 87f ; return _INNER_SCORE;\",\"variables\":{\"map_int_float\":[\"mileageWeight\"],\"map_int_string\":[\"yearcolor\"],\"set_int\":[\"goodYear\"],\"custom_obj\":[\"test_obj2\"],\"int\":[\"thisYear\"],\"map_string_float\":[\"colorweight\"],\"map_string_string\":[\"categorycolor\"]}},\"values\":{\"thisYear\":2001,\"yearcolor\":{\"value\":[\"red\"],\"key\":[1998]},\"mileageWeight\":{\"value\":[777.9,10.2],\"key\":[11400,11000]},\"colorweight\":{\"value\":[335.5],\"key\":[\"red\"]},\"goodYear\":[1996,1997],\"categorycolor\":{\"value\":[\"red\"],\"key\":[\"compact\"]}}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":2}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); double firstScore = firstHit.getDouble("_score"); String color = firstHit.getJSONArray("color").getString(0); assertEquals("color for first is not correct." , true, color.equals("green") ); assertEquals("inner score for first is not correct." , true, Math.abs(firstScore - 20000) < 1 ); } public void testRelevanceExternalObjectSenseiPlugin() throws Exception { logger.info("executing test case testRelevanceExternalObjectSenseiPlugin"); String req = "{\"sort\":[\"_score\"],\"query\":{\"query_string\":{\"query\":\"\",\"relevance\":{\"model\":{\"function_params\":[\"_INNER_SCORE\",\"thisYear\",\"year\",\"goodYear\",\"mileageWeight\",\"mileage\",\"color\",\"yearcolor\",\"colorweight\",\"category\",\"categorycolor\",\"test_obj\"],\"facets\":{\"int\":[\"year\",\"mileage\"],\"string\":[\"color\",\"category\"],\"long\":[\"groupid\"]},\"function\":\" if(test_obj.contains(color)) return 20000f; if(categorycolor.containsKey(category) && categorycolor.get(category).equals(color)) return 10000f; if(colorweight.containsKey(color) ) return 200f + colorweight.getFloat(color); if(yearcolor.containsKey(year) && yearcolor.get(year).equals(color)) return 200f; if(mileageWeight.containsKey(mileage)) return 10000+mileageWeight.get(mileage); if(goodYear.contains(year)) return (float)Math.exp(2d); if(year==thisYear) return 87f ; return _INNER_SCORE;\",\"variables\":{\"map_int_float\":[\"mileageWeight\"],\"map_int_string\":[\"yearcolor\"],\"set_int\":[\"goodYear\"],\"custom_obj\":[\"test_obj\"],\"int\":[\"thisYear\"],\"map_string_float\":[\"colorweight\"],\"map_string_string\":[\"categorycolor\"]}},\"values\":{\"thisYear\":2001,\"yearcolor\":{\"value\":[\"red\"],\"key\":[1998]},\"mileageWeight\":{\"value\":[777.9,10.2],\"key\":[11400,11000]},\"colorweight\":{\"value\":[335.5],\"key\":[\"red\"]},\"goodYear\":[1996,1997],\"categorycolor\":{\"value\":[\"red\"],\"key\":[\"compact\"]}}}}},\"fetchStored\":false,\"from\":0,\"explain\":false,\"size\":2}"; JSONObject res = search(new JSONObject(req)); assertEquals("numhits is wrong", 15000, res.getInt("numhits")); JSONArray hits = res.getJSONArray("hits"); JSONObject firstHit = hits.getJSONObject(0); double firstScore = firstHit.getDouble("_score"); String color = firstHit.getJSONArray("color").getString(0); assertEquals("color for first is not correct." , true, color.equals("red") ); assertEquals("inner score for first is not correct." , true, Math.abs(firstScore - 20000) < 1 ); } private boolean containsString(JSONArray array, String target) throws JSONException { for(int i=0; i<array.length(); i++) { String item = array.getString(i); if(item.equals(target)) return true; } return false; } public static JSONObject search(JSONObject req) throws Exception { return search(SenseiStarter.SenseiUrl, req.toString()); } public static JSONObject searchGet(JSONArray req) throws Exception { return search(new URL(SenseiStarter.SenseiUrl.toString() + "/get"), req.toString()); } public static JSONObject search(URL url, String req) throws Exception { URLConnection conn = url.openConnection(); conn.setDoOutput(true); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")); String reqStr = req; System.out.println("req: " + reqStr); writer.write(reqStr, 0, reqStr.length()); writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; while((line = reader.readLine()) != null) sb.append(line); String res = sb.toString(); // System.out.println("res: " + res); JSONObject ret = new JSONObject(res); if (ret.opt("totaldocs") !=null){ // assertEquals(15000L, ret.getLong("totaldocs")); } return ret; } private void setspec(SenseiRequest req, FacetSpec spec) { req.setFacetSpec("color", spec); req.setFacetSpec("category", spec); req.setFacetSpec("city", spec); req.setFacetSpec("makemodel", spec); req.setFacetSpec("year", spec); req.setFacetSpec("price", spec); req.setFacetSpec("mileage", spec); req.setFacetSpec("tags", spec); } // public void testSortBy() throws Exception // logger.info("executing test case testSortBy"); // String req = "{\"sort\":[{\"color\":\"desc\"},\"_score\"],\"from\":0,\"size\":15000}"; // JSONObject res = search(new JSONObject(req)); // JSONArray jhits = res.optJSONArray("hits"); // ArrayList<String> arColors = new ArrayList<String>(); // for(int i=0; i<jhits.length(); i++){ // JSONObject jhit = jhits.getJSONObject(i); // JSONArray jcolor = jhit.optJSONArray("color"); // if(jcolor != null){ // String color = jcolor.optString(0); // if(color != null) // arColors.add(color); // checkColorOrder(arColors); // // assertEquals("numhits is wrong", 15000, res.getInt("numhits")); private void checkColorOrder(ArrayList<String> arColors) { assertTrue("must have 15000 results, size is:" + arColors.size(), arColors.size() == 15000); for(int i=0; i< arColors.size()-1; i++){ String first = arColors.get(i); String next = arColors.get(i+1); int comp = first.compareTo(next); assertTrue("should >=0 (first= "+ first+" next= "+ next+")", comp>=0); } } public void testSortByDesc() throws Exception { logger.info("executing test case testSortByDesc"); String req = "{\"selections\": [{\"range\": {\"mileage\": {\"from\": 16000, \"include_lower\": false}}}, {\"range\": {\"year\": {\"from\": 2002, \"include_lower\": true, \"include_upper\": true, \"to\": 2002}}}], \"sort\":[{\"color\":\"desc\"}, {\"category\":\"asc\"}],\"from\":0,\"size\":15000}"; JSONObject res = search(new JSONObject(req)); JSONArray jhits = res.optJSONArray("hits"); ArrayList<String> arColors = new ArrayList<String>(); ArrayList<String> arCategories = new ArrayList<String>(); for(int i=0; i<jhits.length(); i++){ JSONObject jhit = jhits.getJSONObject(i); JSONArray jcolor = jhit.optJSONArray("color"); if(jcolor != null){ String color = jcolor.optString(0); if(color != null) arColors.add(color); } JSONArray jcategory = jhit.optJSONArray("category"); if (jcategory != null) { String category = jcategory.optString(0); if (category != null) { arCategories.add(category); } } } checkOrder(arColors, arCategories, true, false); } public void testSortByAsc() throws Exception { logger.info("executing test case testSortByAsc"); String req = "{\"selections\": [{\"range\": {\"mileage\": {\"from\": 16000, \"include_lower\": false}}}, {\"range\": {\"year\": {\"from\": 2002, \"include_lower\": true, \"include_upper\": true, \"to\": 2002}}}], \"sort\":[{\"color\":\"asc\"}, {\"category\":\"desc\"}],\"from\":0,\"size\":15000}"; JSONObject res = search(new JSONObject(req)); JSONArray jhits = res.optJSONArray("hits"); ArrayList<String> arColors = new ArrayList<String>(); ArrayList<String> arCategories = new ArrayList<String>(); for(int i=0; i<jhits.length(); i++){ JSONObject jhit = jhits.getJSONObject(i); JSONArray jcolor = jhit.optJSONArray("color"); if(jcolor != null){ String color = jcolor.optString(0); if(color != null) arColors.add(color); } JSONArray jcategory = jhit.optJSONArray("category"); if (jcategory != null) { String category = jcategory.optString(0); if (category != null) { arCategories.add(category); } } } checkOrder(arColors, arCategories, false, true); } private void checkOrder(ArrayList<String> arColors, ArrayList<String> arCategories, boolean colorDesc, boolean categoryDesc) { assertEquals("Color array and category array must have same size", arColors.size(), arCategories.size()); assertTrue("must have 3680 results, size is:" + arColors.size(), arColors.size() == 368); for(int i=0; i< arColors.size()-1; i++){ String first = arColors.get(i); String next = arColors.get(i+1); String firstCategory = arCategories.get(i); String nextCategory = arCategories.get(i+1); // System.out.println(">>> color = " + first + ", category = " + firstCategory); int comp = first.compareTo(next); if (colorDesc) { assertTrue("should >=0 (first= "+ first+" next= "+ next+")", comp>=0); } else { assertTrue("should <=0 (first= "+ first+" next= "+ next+")", comp<=0); } if (comp == 0) { int compCategory = firstCategory.compareTo(nextCategory); if (categoryDesc) { assertTrue("should >=0 (firstCategory= "+ firstCategory + ", nextCategory= " + nextCategory +")", compCategory >= 0); } else { assertTrue("should <=0 (firstCategory= "+ firstCategory + ", nextCategory= "+ nextCategory+")", compCategory <= 0); } } } } /** * @param res * result * @param selName * the field name of the facet * @param selVal * the value for which to check the count * @param count * the expected count of the given value. If count>0, we verify the count. If count=0, it either has to NOT exist or it is 0. * If count <0, it must not exist. */ private void verifyFacetCount(SenseiResult res, String selName, String selVal, int count) { FacetAccessible year = res.getFacetAccessor(selName); List<BrowseFacet> browsefacets = year.getFacets(); int index = indexOfFacet(selVal, browsefacets); if (count>0) { assertTrue("should contain a BrowseFacet for " + selVal, index >= 0); BrowseFacet bf = browsefacets.get(index); assertEquals(selVal + " has wrong count ", count, bf.getFacetValueHitCount()); } else if (count == 0) { if (index >= 0) { // count has to be 0 BrowseFacet bf = browsefacets.get(index); assertEquals(selVal + " has wrong count ", count, bf.getFacetValueHitCount()); } } else { assertTrue("should not contain a BrowseFacet for " + selVal, index < 0); } } private int indexOfFacet(String selVal, List<BrowseFacet> browsefacets) { for (int i = 0; i < browsefacets.size(); i++) { if (browsefacets.get(i).getValue().equals(selVal)) return i; } return -1; } }
package mondrian.rolap; import mondrian.olap.*; import mondrian.resource.MondrianResource; import mondrian.rolap.sql.MemberChildrenConstraint; import mondrian.server.Execution; import mondrian.server.Locus; import mondrian.olap.CacheControl; import mondrian.olap.Id.Quoting; import javax.sql.DataSource; import java.util.*; import java.util.concurrent.Callable; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.UndeclaredThrowableException; import org.eigenbase.util.property.BooleanProperty; /** * Implementation of {@link CacheControl} API. * * @author jhyde * @version $Id$ * @since Sep 27, 2006 */ public class CacheControlImpl implements CacheControl { /** * Object to lock before making changes to the member cache. * * <p>The "member cache" is a figure of speech: each RolapHierarchy has its * own MemberCache object. But to provide transparently serialized access * to the "member cache" via the interface CacheControl, provide a common * lock here. * * <p>NOTE: static member is a little too wide a scope for this lock, * because in theory a JVM can contain multiple independent instances of * mondrian. */ private static final Object MEMBER_CACHE_LOCK = new Object(); // cell cache control public CellRegion createMemberRegion(Member member, boolean descendants) { if (member == null) { throw new NullPointerException(); } final ArrayList<Member> list = new ArrayList<Member>(); list.add(member); return new MemberCellRegion(list, descendants); } public CellRegion createMemberRegion( boolean lowerInclusive, Member lowerMember, boolean upperInclusive, Member upperMember, boolean descendants) { if (lowerMember == null) { lowerInclusive = false; } if (upperMember == null) { upperInclusive = false; } return new MemberRangeCellRegion( (RolapMember) lowerMember, lowerInclusive, (RolapMember) upperMember, upperInclusive, descendants); } public CellRegion createCrossjoinRegion(CellRegion... regions) { assert regions != null; assert regions.length >= 2; final HashSet<Dimension> set = new HashSet<Dimension>(); final List<CellRegionImpl> list = new ArrayList<CellRegionImpl>(); for (CellRegion region : regions) { int prevSize = set.size(); List<Dimension> dimensionality = region.getDimensionality(); set.addAll(dimensionality); if (set.size() < prevSize + dimensionality.size()) { throw MondrianResource.instance() .CacheFlushCrossjoinDimensionsInCommon.ex( getDimensionalityList(regions)); } flattenCrossjoin((CellRegionImpl) region, list); } return new CrossjoinCellRegion(list); } // Returns e.g. "'[[Product]]', '[[Time], [Product]]'" private String getDimensionalityList(CellRegion[] regions) { StringBuilder buf = new StringBuilder(); int k = 0; for (CellRegion region : regions) { if (k++ > 0) { buf.append(", "); } buf.append("'"); buf.append(region.getDimensionality().toString()); buf.append("'"); } return buf.toString(); } public CellRegion createUnionRegion(CellRegion... regions) { if (regions == null) { throw new NullPointerException(); } if (regions.length < 2) { throw new IllegalArgumentException(); } final List<CellRegionImpl> list = new ArrayList<CellRegionImpl>(); for (CellRegion region : regions) { if (!region.getDimensionality().equals( regions[0].getDimensionality())) { throw MondrianResource.instance() .CacheFlushUnionDimensionalityMismatch.ex( regions[0].getDimensionality().toString(), region.getDimensionality().toString()); } list.add((CellRegionImpl) region); } return new UnionCellRegion(list); } public CellRegion createMeasuresRegion(Cube cube) { final Dimension measuresDimension = cube.getDimensions()[0]; final List<Member> measures = cube.getSchemaReader(null).getLevelMembers( measuresDimension.getHierarchy().getLevels()[0], false); return new MemberCellRegion(measures, false); } public void flush(CellRegion region) { final List<Dimension> dimensionality = region.getDimensionality(); boolean found = false; for (Dimension dimension : dimensionality) { if (dimension.isMeasures()) { found = true; break; } } if (!found) { throw MondrianResource.instance().CacheFlushRegionMustContainMembers .ex(); } final UnionCellRegion union = normalize((CellRegionImpl) region); for (CellRegionImpl cellRegion : union.regions) { // Figure out the bits. flushNonUnion(cellRegion); } } /** * Flushes a list of cell regions. * * @param cellRegionList List of cell regions */ protected void flushRegionList(List<CellRegion> cellRegionList) { final CellRegion cellRegion; switch (cellRegionList.size()) { case 0: return; case 1: cellRegion = cellRegionList.get(0); break; default: final CellRegion[] cellRegions = cellRegionList.toArray(new CellRegion[cellRegionList.size()]); cellRegion = createUnionRegion(cellRegions); break; } flush(cellRegion); } public void trace(String message) { // ignore message } public void flushSchemaCache() { RolapSchema.Pool.instance().clear(); } // todo: document public void flushSchema( String catalogUrl, String connectionKey, String jdbcUser, String dataSourceStr) { RolapSchema.Pool.instance().remove( catalogUrl, connectionKey, jdbcUser, dataSourceStr); } // todo: document public void flushSchema( String catalogUrl, DataSource dataSource) { RolapSchema.Pool.instance().remove( catalogUrl, dataSource); } /** * Flushes the given RolapSchema instance from the pool * * @param schema RolapSchema */ public void flushSchema(Schema schema) { if (RolapSchema.class.isInstance(schema)) { RolapSchema.Pool.instance().remove((RolapSchema)schema); } else { throw new UnsupportedOperationException( schema.getClass().getName() + " cannot be flushed"); } } protected void flushNonUnion(CellRegion region) { throw new UnsupportedOperationException(); } /** * Normalizes a CellRegion into a union of crossjoins of member regions. * * @param region Region * @return normalized region */ UnionCellRegion normalize(CellRegionImpl region) { // Search for Union within a Crossjoin. // Crossjoin(a1, a2, Union(r1, r2, r3), a4) // becomes // Union( // Crossjoin(a1, a2, r1, a4), // Crossjoin(a1, a2, r2, a4), // Crossjoin(a1, a2, r3, a4)) // First, decompose into a flat list of non-union regions. List<CellRegionImpl> nonUnionList = new LinkedList<CellRegionImpl>(); flattenUnion(region, nonUnionList); for (int i = 0; i < nonUnionList.size(); i++) { while (true) { CellRegionImpl nonUnionRegion = nonUnionList.get(i); UnionCellRegion firstUnion = findFirstUnion(nonUnionRegion); if (firstUnion == null) { break; } List<CellRegionImpl> list = new ArrayList<CellRegionImpl>(); for (CellRegionImpl unionComponent : firstUnion.regions) { // For each unionComponent in (r1, r2, r3), // create Crossjoin(a1, a2, r1, a4). CellRegionImpl cj = copyReplacing( nonUnionRegion, firstUnion, unionComponent); list.add(cj); } // Replace one element which contained a union with several // which contain one fewer union. (Double-linked list helps // here.) nonUnionList.remove(i); nonUnionList.addAll(i, list); } } return new UnionCellRegion(nonUnionList); } private CellRegionImpl copyReplacing( CellRegionImpl region, CellRegionImpl seek, CellRegionImpl replacement) { if (region == seek) { return replacement; } if (region instanceof UnionCellRegion) { final UnionCellRegion union = (UnionCellRegion) region; List<CellRegionImpl> list = new ArrayList<CellRegionImpl>(); for (CellRegionImpl child : union.regions) { list.add(copyReplacing(child, seek, replacement)); } return new UnionCellRegion(list); } if (region instanceof CrossjoinCellRegion) { final CrossjoinCellRegion crossjoin = (CrossjoinCellRegion) region; List<CellRegionImpl> list = new ArrayList<CellRegionImpl>(); for (CellRegionImpl child : crossjoin.components) { list.add(copyReplacing(child, seek, replacement)); } return new CrossjoinCellRegion(list); } // This region is atomic, and since regions are immutable we don't need // to clone. return region; } /** * Flatten a region into a list of regions none of which are unions. * * @param region Cell region * @param list Target list */ private void flattenUnion( CellRegionImpl region, List<CellRegionImpl> list) { if (region instanceof UnionCellRegion) { UnionCellRegion union = (UnionCellRegion) region; for (CellRegionImpl region1 : union.regions) { flattenUnion(region1, list); } } else { list.add(region); } } /** * Flattens a region into a list of regions none of which are unions. * * @param region Cell region * @param list Target list */ private void flattenCrossjoin( CellRegionImpl region, List<CellRegionImpl> list) { if (region instanceof CrossjoinCellRegion) { CrossjoinCellRegion crossjoin = (CrossjoinCellRegion) region; for (CellRegionImpl component : crossjoin.components) { flattenCrossjoin(component, list); } } else { list.add(region); } } private UnionCellRegion findFirstUnion(CellRegion region) { final CellRegionVisitor visitor = new CellRegionVisitorImpl() { public void visit(UnionCellRegion region) { throw new FoundOne(region); } }; try { ((CellRegionImpl) region).accept(visitor); return null; } catch (FoundOne foundOne) { return foundOne.region; } } /** * Returns a list of members of the Measures dimension which are mentioned * somewhere in a region specification. * * @param region Cell region * @return List of members mentioned in cell region specification */ static List<Member> findMeasures(CellRegion region) { final List<Member> list = new ArrayList<Member>(); final CellRegionVisitor visitor = new CellRegionVisitorImpl() { public void visit(MemberCellRegion region) { if (region.dimension.isMeasures()) { list.addAll(region.memberList); } } public void visit(MemberRangeCellRegion region) { if (region.level.getDimension().isMeasures()) { // FIXME: don't allow range on measures dimension assert false : "ranges on measures dimension"; } } }; ((CellRegionImpl) region).accept(visitor); return list; } static List<RolapStar> getStarList(CellRegion region) { // Figure out which measure (therefore star) it belongs to. List<RolapStar> starList = new ArrayList<RolapStar>(); final List<Member> measuresList = findMeasures(region); for (Member measure : measuresList) { if (measure instanceof RolapStoredMeasure) { RolapStoredMeasure storedMeasure = (RolapStoredMeasure) measure; final RolapStar.Measure starMeasure = (RolapStar.Measure) storedMeasure.getStarMeasure(); if (!starList.contains(starMeasure.getStar())) { starList.add(starMeasure.getStar()); } } } return starList; } public void printCacheState( PrintWriter pw, CellRegion region) { List<RolapStar> starList = getStarList(region); for (RolapStar star : starList) { star.print(pw, "", false); } } public MemberSet createMemberSet(Member member, boolean descendants) { return new SimpleMemberSet( Collections.singletonList((RolapMember) member), descendants); } public MemberSet createMemberSet( boolean lowerInclusive, Member lowerMember, boolean upperInclusive, Member upperMember, boolean descendants) { if (upperMember != null && lowerMember != null) { assert upperMember.getLevel().equals(lowerMember.getLevel()); } if (lowerMember == null) { lowerInclusive = false; } if (upperMember == null) { upperInclusive = false; } return new RangeMemberSet( stripMember((RolapMember) lowerMember), lowerInclusive, stripMember((RolapMember) upperMember), upperInclusive, descendants); } public MemberSet createUnionSet(MemberSet... args) { //noinspection unchecked return new UnionMemberSet((List) Arrays.asList(args)); } public MemberSet filter(Level level, MemberSet baseSet) { if (level instanceof RolapCubeLevel) { // be forgiving level = ((RolapCubeLevel) level).getRolapLevel(); } return ((MemberSetPlus) baseSet).filter((RolapLevel) level); } public void flush(MemberSet memberSet) { // REVIEW How is flush(s) different to executing createDeleteCommand(s)? synchronized (MEMBER_CACHE_LOCK) { final List<CellRegion> cellRegionList = new ArrayList<CellRegion>(); ((MemberSetPlus) memberSet).accept( new MemberSetVisitorImpl() { public void visit(RolapMember member) { flushMember(member, cellRegionList); } } ); // STUB: flush the set: another visitor // finally, flush cells now invalid flushRegionList(cellRegionList); } } public void printCacheState(PrintWriter pw, MemberSet set) { synchronized (MEMBER_CACHE_LOCK) { pw.println("need to implement printCacheState"); // TODO: } } public MemberEditCommand createCompoundCommand( List<MemberEditCommand> commandList) { //noinspection unchecked return new CompoundCommand((List) commandList); } public MemberEditCommand createCompoundCommand( MemberEditCommand... commands) { //noinspection unchecked return new CompoundCommand((List) Arrays.asList(commands)); } public MemberEditCommand createDeleteCommand(Member member) { if (member == null) { throw new IllegalArgumentException("cannot delete null member"); } if (((RolapLevel) member.getLevel()).isParentChild()) { throw new IllegalArgumentException( "delete member not supported for parent-child hierarchy"); } return createDeleteCommand(createMemberSet(member, false)); } public MemberEditCommand createDeleteCommand(MemberSet s) { return new DeleteMemberCommand((MemberSetPlus) s); } public MemberEditCommand createAddCommand( Member member) throws IllegalArgumentException { if (member == null) { throw new IllegalArgumentException("cannot add null member"); } if (((RolapLevel) member.getLevel()).isParentChild()) { throw new IllegalArgumentException( "add member not supported for parent-child hierarchy"); } return new AddMemberCommand((RolapMember) member); } public MemberEditCommand createMoveCommand(Member member, Member loc) throws IllegalArgumentException { if (member == null) { throw new IllegalArgumentException("cannot move null member"); } if (((RolapLevel) member.getLevel()).isParentChild()) { throw new IllegalArgumentException( "move member not supported for parent-child hierarchy"); } if (loc == null) { throw new IllegalArgumentException( "cannot move member to null location"); } // TODO: check that MEMBER and LOC (its new parent) have appropriate // Levels return new MoveMemberCommand((RolapMember) member, (RolapMember) loc); } public MemberEditCommand createSetPropertyCommand( Member member, String name, Object value) throws IllegalArgumentException { if (member == null) { throw new IllegalArgumentException( "cannot set properties on null member"); } if (((RolapLevel) member.getLevel()).isParentChild()) { throw new IllegalArgumentException( "set properties not supported for parent-child hierarchy"); } // TODO: validate that prop NAME exists for Level of MEMBER return new ChangeMemberPropsCommand( new SimpleMemberSet( Collections.singletonList((RolapMember) member), false), Collections.singletonMap(name, value)); } public MemberEditCommand createSetPropertyCommand( MemberSet members, Map<String, Object> propertyValues) throws IllegalArgumentException { // TODO: check that members all at same Level, and validate that props // exist validateSameLevel((MemberSetPlus) members); return new ChangeMemberPropsCommand( (MemberSetPlus) members, propertyValues); } private void validateSameLevel(MemberSetPlus memberSet) throws IllegalArgumentException { memberSet.accept( new MemberSetVisitor() { final Set<RolapLevel> levelSet = new HashSet<RolapLevel>(); private void visitMember( RolapMember member, boolean descendants) { final String message = "all members in set must belong to same level"; if (levelSet.add(member.getLevel()) && levelSet.size() > 1) { throw new IllegalArgumentException(message); } if (descendants && member.getLevel().getChildLevel() != null) { throw new IllegalArgumentException(message); } } public void visit(SimpleMemberSet simpleMemberSet) { for (RolapMember member : simpleMemberSet.members) { visitMember(member, simpleMemberSet.descendants); } } public void visit(UnionMemberSet unionMemberSet) { for (MemberSetPlus item : unionMemberSet.items) { item.accept(this); } } public void visit(RangeMemberSet rangeMemberSet) { visitMember( rangeMemberSet.lowerMember, rangeMemberSet.descendants); visitMember( rangeMemberSet.upperMember, rangeMemberSet.descendants); } } ); } public void execute(MemberEditCommand cmd) { final BooleanProperty prop = MondrianProperties.instance().EnableRolapCubeMemberCache; if (prop.get()) { throw new IllegalArgumentException( "Member cache control operations are not allowed unless " + "property " + prop.getPath() + " is false"); } synchronized (MEMBER_CACHE_LOCK) { // Make sure that a Locus is in the Execution stack, // since some operations might require DB access Execution execution; try { execution = Locus.peek().execution; } catch (EmptyStackException e) { execution = Execution.NONE; } Locus.push( new Locus( execution, "CacheControlImpl.execute", "when modifying the member cache.")); // Execute the command final List<CellRegion> cellRegionList = new ArrayList<CellRegion>(); ((MemberEditCommandPlus) cmd).execute(cellRegionList); // Flush the cells touched by the regions for (CellRegion memberRegion : cellRegionList) { // Iterate over the cubes, create a cross region with // its measures, and flush the data cells. // It is possible that some regions don't intersect // with a cube. We will intercept the exceptions and // skip to the next cube if necessary. for (Cube cube : memberRegion.getDimensionality().get(0) .getSchema().getCubes()) { try { final List<CellRegionImpl> crossList = new ArrayList<CellRegionImpl>(); crossList.add( (CellRegionImpl) createMeasuresRegion(cube)); crossList.add((CellRegionImpl) memberRegion); final CellRegion crossRegion = new CrossjoinCellRegion(crossList); flush(crossRegion); } catch (UndeclaredThrowableException e) { if (e.getCause() instanceof InvocationTargetException) { final InvocationTargetException ite = (InvocationTargetException)e.getCause(); if (ite.getTargetException() instanceof MondrianException) { final MondrianException me = (MondrianException) ite.getTargetException(); if (me.getMessage() .matches( "^Mondrian Error:Member " + "'\\[.*\\]' not found$")) { continue; } } } throw new MondrianException(e); } catch (MondrianException e) { if (e.getMessage() .matches( "^Mondrian Error:Member " + "'\\[.*\\]' not found$")) { continue; } throw e; } } } // Apply it all. ((MemberEditCommandPlus) cmd).commit(); } } private static MemberCache getMemberCache(RolapMember member) { final MemberReader memberReader = member.getHierarchy().getMemberReader(); SmartMemberReader smartMemberReader = (SmartMemberReader) memberReader; return smartMemberReader.getMemberCache(); } // cell cache control implementation /** * Cell region formed by a list of members. * * @see MemberRangeCellRegion */ static class MemberCellRegion implements CellRegionImpl { private final List<Member> memberList; private final Dimension dimension; MemberCellRegion(List<Member> memberList, boolean descendants) { assert memberList.size() > 0; this.memberList = memberList; this.dimension = (memberList.get(0)).getDimension(); Util.discard(descendants); } public List<Dimension> getDimensionality() { return Collections.singletonList(dimension); } public String toString() { return Util.commaList("Member", memberList); } public void accept(CellRegionVisitor visitor) { visitor.visit(this); } public List<Member> getMemberList() { return memberList; } } /** * Cell region formed a range of members between a lower and upper bound. */ static class MemberRangeCellRegion implements CellRegionImpl { private final RolapMember lowerMember; private final boolean lowerInclusive; private final RolapMember upperMember; private final boolean upperInclusive; private final boolean descendants; private final RolapLevel level; MemberRangeCellRegion( RolapMember lowerMember, boolean lowerInclusive, RolapMember upperMember, boolean upperInclusive, boolean descendants) { assert lowerMember != null || upperMember != null; assert lowerMember == null || upperMember == null || lowerMember.getLevel() == upperMember.getLevel(); assert !(lowerMember == null && lowerInclusive); assert !(upperMember == null && upperInclusive); this.lowerMember = lowerMember; this.lowerInclusive = lowerInclusive; this.upperMember = upperMember; this.upperInclusive = upperInclusive; this.descendants = descendants; this.level = lowerMember == null ? upperMember.getLevel() : lowerMember.getLevel(); } public List<Dimension> getDimensionality() { return Collections.singletonList(level.getDimension()); } public RolapLevel getLevel() { return level; } public String toString() { final StringBuilder sb = new StringBuilder("Range("); if (lowerMember == null) { sb.append("null"); } else { sb.append(lowerMember); if (lowerInclusive) { sb.append(" inclusive"); } else { sb.append(" exclusive"); } } sb.append(" to "); if (upperMember == null) { sb.append("null"); } else { sb.append(upperMember); if (upperInclusive) { sb.append(" inclusive"); } else { sb.append(" exclusive"); } } sb.append(")"); return sb.toString(); } public void accept(CellRegionVisitor visitor) { visitor.visit(this); } public boolean getLowerInclusive() { return lowerInclusive; } public RolapMember getLowerBound() { return lowerMember; } public boolean getUpperInclusive() { return upperInclusive; } public RolapMember getUpperBound() { return upperMember; } } /** * Cell region formed by a cartesian product of two or more CellRegions. */ static class CrossjoinCellRegion implements CellRegionImpl { final List<Dimension> dimensions; private List<CellRegionImpl> components = new ArrayList<CellRegionImpl>(); CrossjoinCellRegion(List<CellRegionImpl> regions) { final List<Dimension> dimensionality = new ArrayList<Dimension>(); compute(regions, components, dimensionality); dimensions = Collections.unmodifiableList(dimensionality); } private static void compute( List<CellRegionImpl> regions, List<CellRegionImpl> components, List<Dimension> dimensionality) { final Set<Dimension> dimensionSet = new HashSet<Dimension>(); for (CellRegionImpl region : regions) { addComponents(region, components); final List<Dimension> regionDimensionality = region.getDimensionality(); dimensionality.addAll(regionDimensionality); dimensionSet.addAll(regionDimensionality); assert dimensionSet.size() == dimensionality.size() : "dimensions in common"; } } public void accept(CellRegionVisitor visitor) { visitor.visit(this); for (CellRegion component : components) { CellRegionImpl cellRegion = (CellRegionImpl) component; cellRegion.accept(visitor); } } private static void addComponents( CellRegionImpl region, List<CellRegionImpl> list) { if (region instanceof CrossjoinCellRegion) { CrossjoinCellRegion crossjoinRegion = (CrossjoinCellRegion) region; for (CellRegionImpl component : crossjoinRegion.components) { list.add(component); } } else { list.add(region); } } public List<Dimension> getDimensionality() { return dimensions; } public String toString() { return Util.commaList("Crossjoin", components); } public List<CellRegion> getComponents() { return Util.cast(components); } } private static class UnionCellRegion implements CellRegionImpl { private final List<CellRegionImpl> regions; UnionCellRegion(List<CellRegionImpl> regions) { this.regions = regions; assert regions.size() >= 1; // All regions must have same dimensionality. for (int i = 1; i < regions.size(); i++) { final CellRegion region0 = regions.get(0); final CellRegion region = regions.get(i); assert region0.getDimensionality().equals( region.getDimensionality()); } } public List<Dimension> getDimensionality() { return regions.get(0).getDimensionality(); } public String toString() { return Util.commaList("Union", regions); } public void accept(CellRegionVisitor visitor) { visitor.visit(this); for (CellRegionImpl cellRegion : regions) { cellRegion.accept(visitor); } } } interface CellRegionImpl extends CellRegion { void accept(CellRegionVisitor visitor); } /** * Visitor which visits various sub-types of {@link CellRegion}. */ interface CellRegionVisitor { void visit(MemberCellRegion region); void visit(MemberRangeCellRegion region); void visit(UnionCellRegion region); void visit(CrossjoinCellRegion region); } private static class FoundOne extends RuntimeException { private final transient UnionCellRegion region; public FoundOne(UnionCellRegion region) { this.region = region; } } /** * Default implementation of {@link CellRegionVisitor}. */ private static class CellRegionVisitorImpl implements CellRegionVisitor { public void visit(MemberCellRegion region) { // nothing } public void visit(MemberRangeCellRegion region) { // nothing } public void visit(UnionCellRegion region) { // nothing } public void visit(CrossjoinCellRegion region) { // nothing } } /** * Implementation-specific extensions to the * {@link mondrian.olap.CacheControl.MemberEditCommand} interface. */ interface MemberEditCommandPlus extends MemberEditCommand { /** * Executes this command, and gathers a list of cell regions affected * in the {@code cellRegionList} parameter. The caller will flush the * cell regions later. * * @param cellRegionList Populated with a list of cell regions which * are invalidated by this action */ void execute(final List<CellRegion> cellRegionList); void commit(); } /** * Implementation-specific extensions to the * {@link mondrian.olap.CacheControl.MemberSet} interface. */ interface MemberSetPlus extends MemberSet { /** * Accepts a visitor. * * @param visitor Visitor */ void accept(MemberSetVisitor visitor); /** * Filters this member set, returning a member set containing all * members at a given Level. When applicable, returns this member set * unchanged. * * @param level Level * @return Member set with members not at the given level removed */ MemberSetPlus filter(RolapLevel level); } /** * Visits the subclasses of {@link MemberSetPlus}. */ interface MemberSetVisitor { void visit(SimpleMemberSet s); void visit(UnionMemberSet s); void visit(RangeMemberSet s); } /** * Default implementation of {@link MemberSetVisitor}. * * <p>The default implementation may not be efficient. For example, if * flushing a range of members from the cache, you may not wish to fetch * all of the members into the cache in order to flush them. */ public static abstract class MemberSetVisitorImpl implements MemberSetVisitor { public void visit(UnionMemberSet s) { for (MemberSetPlus item : s.items) { item.accept(this); } } public void visit(RangeMemberSet s) { final MemberReader memberReader = s.level.getHierarchy().getMemberReader(); visitRange( memberReader, s.level, s.lowerMember, s.upperMember, s.descendants); } protected void visitRange( MemberReader memberReader, RolapLevel level, RolapMember lowerMember, RolapMember upperMember, boolean recurse) { final List<RolapMember> list = new ArrayList<RolapMember>(); memberReader.getMemberRange(level, lowerMember, upperMember, list); for (RolapMember member : list) { visit(member); } if (recurse) { list.clear(); memberReader.getMemberChildren(lowerMember, list); if (list.isEmpty()) { return; } RolapMember lowerChild = list.get(0); list.clear(); memberReader.getMemberChildren(upperMember, list); if (list.isEmpty()) { return; } RolapMember upperChild = list.get(list.size() - 1); visitRange( memberReader, level, lowerChild, upperChild, recurse); } } public void visit(SimpleMemberSet s) { for (RolapMember member : s.members) { visit(member); } } /** * Visits a single member. * * @param member Member */ public abstract void visit(RolapMember member); } /** * Member set containing no members. */ static class EmptyMemberSet implements MemberSetPlus { public static final EmptyMemberSet INSTANCE = new EmptyMemberSet(); private EmptyMemberSet() { // prevent instantiation except for singleton } public void accept(MemberSetVisitor visitor) { // nothing } public MemberSetPlus filter(RolapLevel level) { return this; } public String toString() { return "Empty"; } } /** * Member set defined by a list of members from one hierarchy. */ static class SimpleMemberSet implements MemberSetPlus { public final List<RolapMember> members; // the set includes the descendants of all members public final boolean descendants; public final RolapHierarchy hierarchy; SimpleMemberSet(List<RolapMember> members, boolean descendants) { this.members = new ArrayList<RolapMember>(members); stripMemberList(this.members); this.descendants = descendants; this.hierarchy = members.isEmpty() ? null : members.get(0).getHierarchy(); } public String toString() { return Util.commaList("Member", members); } public void accept(MemberSetVisitor visitor) { // Don't descend the subtrees here: may not want to load them into // cache. visitor.visit(this); } public MemberSetPlus filter(RolapLevel level) { List<RolapMember> filteredMembers = new ArrayList<RolapMember>(); for (RolapMember member : members) { if (member.getLevel().equals(level)) { filteredMembers.add(member); } } if (filteredMembers.isEmpty()) { return EmptyMemberSet.INSTANCE; } else if (filteredMembers.equals(members)) { return this; } else { return new SimpleMemberSet(filteredMembers, false); } } } /** * Member set defined by the union of other member sets. */ static class UnionMemberSet implements MemberSetPlus { private final List<MemberSetPlus> items; UnionMemberSet(List<MemberSetPlus> items) { this.items = items; } public String toString() { final StringBuilder sb = new StringBuilder("Union("); for (int i = 0; i < items.size(); i++) { if (i > 0) { sb.append(", "); } MemberSetPlus item = items.get(i); sb.append(item.toString()); } sb.append(")"); return sb.toString(); } public void accept(MemberSetVisitor visitor) { visitor.visit(this); } public MemberSetPlus filter(RolapLevel level) { final List<MemberSetPlus> filteredItems = new ArrayList<MemberSetPlus>(); for (MemberSetPlus item : items) { final MemberSetPlus filteredItem = item.filter(level); if (filteredItem == EmptyMemberSet.INSTANCE) { // skip it } else { assert !(filteredItem instanceof EmptyMemberSet); filteredItems.add(filteredItem); } } if (filteredItems.isEmpty()) { return EmptyMemberSet.INSTANCE; } else if (filteredItems.equals(items)) { return this; } else { return new UnionMemberSet(filteredItems); } } } /** * Member set defined by a range of members between a lower and upper * bound. */ static class RangeMemberSet implements MemberSetPlus { private final RolapMember lowerMember; private final boolean lowerInclusive; private final RolapMember upperMember; private final boolean upperInclusive; private final boolean descendants; private final RolapLevel level; RangeMemberSet( RolapMember lowerMember, boolean lowerInclusive, RolapMember upperMember, boolean upperInclusive, boolean descendants) { assert lowerMember != null || upperMember != null; assert lowerMember == null || upperMember == null || lowerMember.getLevel() == upperMember.getLevel(); assert !(lowerMember == null && lowerInclusive); assert !(upperMember == null && upperInclusive); assert !(lowerMember instanceof RolapCubeMember); assert !(upperMember instanceof RolapCubeMember); this.lowerMember = lowerMember; this.lowerInclusive = lowerInclusive; this.upperMember = upperMember; this.upperInclusive = upperInclusive; this.descendants = descendants; this.level = lowerMember == null ? upperMember.getLevel() : lowerMember.getLevel(); } public String toString() { final StringBuilder sb = new StringBuilder("Range("); if (lowerMember == null) { sb.append("null"); } else { sb.append(lowerMember); if (lowerInclusive) { sb.append(" inclusive"); } else { sb.append(" exclusive"); } } sb.append(" to "); if (upperMember == null) { sb.append("null"); } else { sb.append(upperMember); if (upperInclusive) { sb.append(" inclusive"); } else { sb.append(" exclusive"); } } sb.append(")"); return sb.toString(); } public void accept(MemberSetVisitor visitor) { // Don't traverse the range here: may not want to load it into cache visitor.visit(this); } public MemberSetPlus filter(RolapLevel level) { if (level == this.level) { return this; } else { return filter2(level, this.level, lowerMember, upperMember); } } public MemberSetPlus filter2( RolapLevel seekLevel, RolapLevel level, RolapMember lower, RolapMember upper) { if (level == seekLevel) { return new RangeMemberSet( lower, lowerInclusive, upper, upperInclusive, false); } else if (descendants && level.getHierarchy() == seekLevel.getHierarchy() && level.getDepth() < seekLevel.getDepth()) { final MemberReader memberReader = level.getHierarchy().getMemberReader(); final List<RolapMember> list = new ArrayList<RolapMember>(); memberReader.getMemberChildren(lower, list); if (list.isEmpty()) { return EmptyMemberSet.INSTANCE; } RolapMember lowerChild = list.get(0); list.clear(); memberReader.getMemberChildren(upper, list); if (list.isEmpty()) { return EmptyMemberSet.INSTANCE; } RolapMember upperChild = list.get(list.size() - 1); return filter2( seekLevel, (RolapLevel) level.getChildLevel(), lowerChild, upperChild); } else { return EmptyMemberSet.INSTANCE; } } } /** * Command consisting of a set of commands executed in sequence. */ private static class CompoundCommand implements MemberEditCommandPlus { private final List<MemberEditCommandPlus> commandList; CompoundCommand(List<MemberEditCommandPlus> commandList) { this.commandList = commandList; } public String toString() { return Util.commaList("Compound", commandList); } public void execute(final List<CellRegion> cellRegionList) { for (MemberEditCommandPlus command : commandList) { command.execute(cellRegionList); } } public void commit() { for (MemberEditCommandPlus command : commandList) { command.commit(); } } } /** * Command that deletes a member and its descendants from the cache. */ private class DeleteMemberCommand extends MemberSetVisitorImpl implements MemberEditCommandPlus { private final MemberSetPlus set;; private List<CellRegion> cellRegionList; private Callable<Boolean> callable; DeleteMemberCommand(MemberSetPlus set) { this.set = set; } public String toString() { return "DeleteMemberCommand(" + set + ")"; } public void execute(final List<CellRegion> cellRegionList) { // NOTE: use of member makes this class non-reentrant this.cellRegionList = cellRegionList; set.accept(this); this.cellRegionList = null; } public void visit(RolapMember member) { this.callable = deleteMember(member, member.getParentMember(), cellRegionList); } public void commit() { try { callable.call(); } catch (Exception e) { throw new MondrianException(e); } } } /** * Command that adds a new member to the cache. */ private class AddMemberCommand implements MemberEditCommandPlus { private final RolapMember member; private Callable<Boolean> callable; public AddMemberCommand(RolapMember member) { assert member != null; this.member = stripMember(member); } public String toString() { return "AddMemberCommand(" + member + ")"; } public void execute(List<CellRegion> cellRegionList) { this.callable = addMember(member, member.getParentMember(), cellRegionList); } public void commit() { try { callable.call(); } catch (Exception e) { throw new MondrianException(e); } } } /** * Command that moves a member to a new parent. */ private class MoveMemberCommand implements MemberEditCommandPlus { private final RolapMember member; private final RolapMember newParent; private Callable<Boolean> callable1; private Callable<Boolean> callable2; MoveMemberCommand(RolapMember member, RolapMember newParent) { this.member = member; this.newParent = newParent; } public String toString() { return "MoveMemberCommand(" + member + ", " + newParent + ")"; } public void execute(final List<CellRegion> cellRegionList) { this.callable1 = deleteMember(member, member.getParentMember(), cellRegionList); this.callable2 = addMember(member, newParent, cellRegionList); } public void commit() { try { ((RolapMemberBase) member).setParentMember(newParent); callable1.call(); ((RolapMemberBase) member).setUniqueName(member.getKey()); callable2.call(); } catch (Exception e) { throw new MondrianException(e); } } } /** * Command that changes one or more properties of a member. */ private class ChangeMemberPropsCommand extends MemberSetVisitorImpl implements MemberEditCommandPlus { final MemberSetPlus memberSet; final Map<String, Object> propertyValues; final List<RolapMember> members = new ArrayList<RolapMember>(); ChangeMemberPropsCommand( MemberSetPlus memberSet, Map<String, Object> propertyValues) { this.memberSet = memberSet; this.propertyValues = propertyValues; } public String toString() { return "CreateMemberPropsCommand(" + memberSet + ", " + propertyValues + ")"; } public void execute(List<CellRegion> cellRegionList) { // ignore cellRegionList - no changes to cell cache memberSet.accept(this); } public void visit(RolapMember member) { members.add(member); } public void commit() { for (RolapMember member : members) { // Change member's properties. member = stripMember(member); final MemberCache memberCache = getMemberCache(member); final Object cacheKey = memberCache.makeKey( member.getParentMember(), member.getKey()); final RolapMember cacheMember = memberCache.getMember(cacheKey); if (cacheMember == null) { return; } for (Map.Entry<String, Object> entry : propertyValues.entrySet()) { cacheMember.setProperty(entry.getKey(), entry.getValue()); } } } } private static RolapMember stripMember(RolapMember member) { if (member instanceof RolapCubeMember) { member = ((RolapCubeMember) member).member; } return member; } private static void stripMemberList(List<RolapMember> members) { for (int i = 0; i < members.size(); i++) { RolapMember member = members.get(i); if (member instanceof RolapCubeMember) { members.set(i, ((RolapCubeMember) member).member); } } } private Callable<Boolean> deleteMember( final RolapMember member, final RolapMember previousParent, List<CellRegion> cellRegionList) { // Cells for member and its ancestors are now invalid. // It's sufficient to flush the member. cellRegionList.add(createMemberRegion(member, true)); return new Callable<Boolean>() { public Boolean call() throws Exception { final MemberCache memberCache = getMemberCache(member); final MemberChildrenConstraint memberConstraint = new ChildByNameConstraint( new Id.Segment(member.getName(), Quoting.QUOTED)); // Remove the member from its parent's lists. First try the // unconstrained cache. List<RolapMember> childrenList = memberCache.getChildrenFromCache( previousParent, DefaultMemberChildrenConstraint.instance()); if (childrenList != null) { // A list existed before. Let's splice it. childrenList.remove(member); memberCache.putChildren( previousParent, DefaultMemberChildrenConstraint.instance(), childrenList); } // Now make sure there is no constrained cache entry // for this member's parent. memberCache.putChildren( previousParent, memberConstraint, null); // Remove the member itself. The MemberCacheHelper takes care of // removing the member's children as well. final Object key = memberCache.makeKey(previousParent, member.getKey()); memberCache.removeMember(key); return true; } }; } /** * Adds a member to cache. * * @param member Member * @param parent Member's parent (generally equals member.getParentMember) * @param cellRegionList List of cell regions to be flushed */ private Callable<Boolean> addMember( final RolapMember member, final RolapMember parent, List<CellRegion> cellRegionList) { // Cells for all of member's ancestors are now invalid. It's sufficient // to flush its parent. cellRegionList.add(createMemberRegion(parent, false)); return new Callable<Boolean>() { public Boolean call() throws Exception { final MemberCache memberCache = getMemberCache(member); final MemberChildrenConstraint memberConstraint = new ChildByNameConstraint( new Id.Segment(member.getName(), Quoting.QUOTED)); // First check if there is already a list in cache // constrained by the member name. List<RolapMember> childrenList = memberCache.getChildrenFromCache( parent, memberConstraint); if (childrenList == null) { // There was no constrained cache hit. Let's create one. final List<RolapMember> constrainedList = new ArrayList<RolapMember>(); constrainedList.add(member); memberCache.putChildren( parent, memberConstraint, constrainedList); } else { // A list existed before. Let's append to it. if (childrenList.isEmpty()) { childrenList = new ArrayList<RolapMember>(); } childrenList.add(member); memberCache.putChildren( parent, memberConstraint, childrenList); } // Now check if an unconstrained cached list exists. childrenList = memberCache.getChildrenFromCache( parent, DefaultMemberChildrenConstraint.instance()); if (childrenList == null) { // There was no unconstrained cache hit. Let's create one. final List<RolapMember> unconstrainedList = new ArrayList<RolapMember>(); unconstrainedList.add(member); memberCache.putChildren( parent, DefaultMemberChildrenConstraint.instance(), unconstrainedList); } else { // A list existed before. Let's append to it. childrenList.add(member); memberCache.putChildren( parent, DefaultMemberChildrenConstraint.instance(), childrenList); } // Now add the member itself into cache final Object memberKey = memberCache.makeKey( member.getParentMember(), member.getKey()); memberCache.putMember(memberKey, member); return true; } }; } /** * Removes a member from cache. * * @param member Member * @param cellRegionList Populated with cell region to be flushed */ private void flushMember( RolapMember member, List<CellRegion> cellRegionList) { final MemberCache memberCache = getMemberCache(member); final Object key = memberCache.makeKey(member.getParentMember(), member.getKey()); memberCache.removeMember(key); cellRegionList.add(createMemberRegion(member, false)); } } // End CacheControlImpl.java
package imcode.server.document.index; import com.imcode.util.HumanReadable; import imcode.server.Imcms; import imcode.server.document.DocumentDomainObject; import imcode.server.document.DocumentMapper; import imcode.server.user.UserDomainObject; import imcode.util.IntervalSchedule; import org.apache.commons.lang.time.DateUtils; import org.apache.commons.lang.time.StopWatch; import org.apache.log4j.Logger; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; class DirectoryIndex implements DocumentIndex { private File directory; private IndexDocumentFactory indexDocumentFactory = new IndexDocumentFactory(); private final static int INDEXING_LOG_PERIOD__MILLISECONDS = DateUtils.MILLIS_IN_MINUTE ; private boolean inconsistent; private final static Logger log = Logger.getLogger( DirectoryIndex.class.getName() ); DirectoryIndex( File directory ) { this.directory = directory; } public DocumentDomainObject[] search( Query query, UserDomainObject searchingUser ) throws IndexException { try { IndexSearcher indexSearcher = new IndexSearcher( directory.toString() ); try { StopWatch searchStopWatch = new StopWatch(); searchStopWatch.start(); Hits hits = indexSearcher.search( query ); long searchTime = searchStopWatch.getTime(); List documentList = getDocumentListForHits( hits, searchingUser ); log.debug( "Search for " + query.toString() + ": " + searchTime + "ms. Total: " + searchStopWatch.getTime() + "ms." ); return (DocumentDomainObject[])documentList.toArray( new DocumentDomainObject[documentList.size()] ); } finally { indexSearcher.close(); } } catch ( IOException e ) { throw new IndexException( e ) ; } } private List getDocumentListForHits( Hits hits, UserDomainObject searchingUser ) throws IOException { List documentList = new ArrayList( hits.length() ); final DocumentMapper documentMapper = Imcms.getServices().getDocumentMapper(); for ( int i = 0; i < hits.length(); ++i ) { int metaId = Integer.parseInt( hits.doc( i ).get( DocumentIndex.FIELD__META_ID ) ); DocumentDomainObject document = documentMapper.getDocument( metaId ); if ( null == document ) { inconsistent = true; continue; } if ( searchingUser.canSearchFor( document ) ) { documentList.add( document ); } } return documentList; } public void indexDocument( DocumentDomainObject document ) throws IndexException { try { removeDocument( document ); addDocument( document ); } catch ( IOException e ) { throw new IndexException( e ); } } public void removeDocument( DocumentDomainObject document ) throws IndexException { try { IndexReader indexReader = IndexReader.open( directory ); try { indexReader.delete( new Term( "meta_id", "" + document.getId() ) ); } finally { indexReader.close(); } } catch ( IOException e ) { throw new IndexException( e ); } } private void addDocument( DocumentDomainObject document ) throws IOException { IndexWriter indexWriter = createIndexWriter( false ); try { addDocumentToIndex( document, indexWriter ); } finally { indexWriter.close(); } } private IndexWriter createIndexWriter( boolean createIndex ) throws IOException { return new IndexWriter( directory, new AnalyzerImpl(), createIndex ); } void indexAllDocuments() throws IOException { IndexWriter indexWriter = createIndexWriter( true ); try { indexAllDocumentsToIndexWriter( indexWriter ); } finally { indexWriter.close(); } } private void addDocumentToIndex( DocumentDomainObject document, IndexWriter indexWriter ) throws IOException { Document indexDocument = indexDocumentFactory.createIndexDocument( document ); indexWriter.addDocument( indexDocument ); } private void indexAllDocumentsToIndexWriter( IndexWriter indexWriter ) throws IOException { DocumentMapper documentMapper = Imcms.getServices().getDocumentMapper(); int[] documentIds = documentMapper.getAllDocumentIds(); logIndexingStarting( documentIds.length ); IntervalSchedule indexingLogSchedule = new IntervalSchedule( INDEXING_LOG_PERIOD__MILLISECONDS ); for ( int i = 0; i < documentIds.length; i++ ) { try { addDocumentToIndex( documentMapper.getDocument( documentIds[i] ), indexWriter ); } catch ( Exception ex ) { log.error( "Could not index document with meta_id " + documentIds[i] + ", trying next document.", ex ); } if ( indexingLogSchedule.isTime() ) { logIndexingProgress( i, documentIds.length, indexingLogSchedule.getStopWatch() ); } Thread.yield(); // To make sure other threads with the same priority get a chance to run something once in a while. } logIndexingCompleted( documentIds.length, indexingLogSchedule.getStopWatch() ); optimizeIndex( indexWriter ); } private void logIndexingStarting( int documentCount ) { log.info( "Building index of all " + documentCount + " documents" ); } private void logIndexingProgress( int documentsCompleted, int numberOfDocuments, StopWatch stopWatch ) { int indexPercentageCompleted = (int)( documentsCompleted * ( 100F / numberOfDocuments ) ); long elapsedTime = stopWatch.getTime() ; long estimatedTime = numberOfDocuments * elapsedTime / documentsCompleted; long estimatedTimeLeft = estimatedTime - elapsedTime ; Date eta = new Date(System.currentTimeMillis() + estimatedTimeLeft) ; DateFormat dateFormat = new SimpleDateFormat( "HH:mm:ss"); log.info( "Indexed " + documentsCompleted + " documents (" + indexPercentageCompleted + "%). ETA "+dateFormat.format( eta ) ); } private void logIndexingCompleted( int numberOfDocuments, StopWatch indexingStopWatch ) { long time = indexingStopWatch.getTime(); String humanReadableTime = HumanReadable.getHumanReadableTimeSpan( time ) ; long timePerDocument = time/numberOfDocuments ; log.info( "Completed index of " + numberOfDocuments + " documents in " + humanReadableTime+". "+timePerDocument+"ms per document." ); } private void optimizeIndex( IndexWriter indexWriter ) throws IOException { StopWatch optimizeStopWatch = new StopWatch(); optimizeStopWatch.start(); indexWriter.optimize(); optimizeStopWatch.stop(); log.info( "Optimized index in " + optimizeStopWatch.getTime() + "ms" ); } File getDirectory() { return directory; } public boolean isInconsistent() { return inconsistent; } }
package io.spine.server.delivery; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.google.protobuf.Duration; import com.google.protobuf.Timestamp; import com.google.protobuf.util.Durations; import com.google.protobuf.util.Timestamps; import io.spine.base.Time; import io.spine.server.NodeId; import io.spine.server.ServerEnvironment; import io.spine.server.delivery.memory.InMemoryShardedWorkRegistry; import io.spine.type.TypeUrl; import org.checkerframework.checker.nullness.qual.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.Collections.synchronizedList; import static java.util.stream.Collectors.groupingBy; /** * Delivers the messages to the entities. * * <p>Splits the incoming messages into shards and allows to deliver the * messages to their destinations on a per-shard basis. Guarantees that one and only one * application server node serves the messages from the given shard at a time, thus preventing * any concurrent modifications of entity state. * * <p>Delegates the message dispatching and low-level handling of message duplicates to * {@link #newInbox(TypeUrl) Inbox}es of each target entity. The respective {@code Inbox} instances * should be created in each of {@code Entity} repositories. * * <b>Configuration</b> * * <p>By default, a shard is assigned according to the identifier of the target entity. The * messages * heading to a single entity will always reside in a single shard. However, the framework users * may {@linkplain DeliveryBuilder#setStrategy(DeliveryStrategy) customize} this behavior. * * <p>{@linkplain DeliveryBuilder#setIdempotenceWindow(Duration) Provides} the time-based * de-duplication * capabilities to eliminate the messages, which may have been already delivered to their targets. * The duplicates will be detected among the messages, which are not older, than * {@code now - [idempotence window]}. * * <p>{@code Delivery} is responsible for providing the {@link InboxStorage} for every inbox * registered. Framework users may {@linkplain DeliveryBuilder#setInboxStorage(InboxStorage) * configure} the storage, taking into account that it is typically multi-tenant. By default, * the {@code InboxStorage} for the delivery is provided by the environment-specific * {@linkplain ServerEnvironment#storageFactory() storage factory} and is multi-tenant. * * <p>Once a message is written to the {@code Inbox}, * the {@linkplain Delivery#subscribe(ShardObserver) pre-configured shard observers} are * {@linkplain ShardObserver#onMessage(InboxMessage) notified}. In this way any third-party * environment planners, load balancers, and schedulers may plug into the delivery and perform * various routines to enable the further processing of the sharded messages. In a distributed * environment a message queue may be used to notify the node cluster of a shard that has some * messages pending for the delivery. * * <p>Once an application node picks the shard to deliver the messages from it, * it registers itself in a {@link ShardedWorkRegistry}. It serves as a list of locks-per-shard * that only allows to pick a shard to a single node at a time. * * <p>The delivery process for each shard index is split into {@link DeliveryStage}s. In scope of * each stage, a certain number of messages is read from the respective shard of the {@code Inbox}. * The messages are grouped per-target and delivered in batches if possible. The maximum * number of the messages within a {@code DeliveryStage} can be * {@linkplain DeliveryBuilder#setPageSize(int) configured}. * * <p>After each {@code DeliveryStage} it is possible to stop the delivery by * {@link DeliveryBuilder#setMonitor(DeliveryMonitor) supplying} the custom delivery monitor. * Please refer to the {@link DeliveryMonitor documentation} for the details. * * <b>Local environment</b> * * <p>By default, the delivery is configured to {@linkplain Delivery#local() run locally}. It * uses {@linkplain LocalDispatchingObserver see-and-dispatch observer}, which delivers the * messages * from the observed shard once a message is passed to its * {@link LocalDispatchingObserver#onMessage(InboxMessage) onMessage(InboxMessage)} method. This * process is synchronous. * * <p>To deal with the multi-threaded access in a local mode, * an {@linkplain InMemoryShardedWorkRegistry} is used. It operates on top of the * {@code synchronized} in-memory data structures and prevents several threads from picking up the * same shard. */ public final class Delivery { /** * The width of the idempotence window in a local environment. * * <p>Selected to be pretty big to avoid dispatching duplicates to any entities. */ private static final Duration LOCAL_IDEMPOTENCE_WINDOW = Durations.fromSeconds(30); /** * The strategy of assigning a shard index for a message that is delivered to a particular * target. */ private final DeliveryStrategy strategy; /** * For how long we keep the previously delivered message per-target to ensure the new messages * aren't duplicates. */ private final Duration idempotenceWindow; /** * The delivery strategies to use for the postponed message dispatching. * * <p>Stored per {@link TypeUrl}, which is a state type of a target {@code Entity}. * * <p>Once messages arrive for the postponed processing, a corresponding delivery is selected * according to the message contents. The {@code TypeUrl} in this map is stored * as {@code String} to avoid an extra boxing into {@code TypeUrl} of the value, * which resides as a Protobuf {@code string} inside an incoming message. */ private final Map<String, ShardedMessageDelivery<InboxMessage>> inboxDeliveries; /** * The observers that are notified when a message is written into a particular shard. */ private final List<ShardObserver> shardObservers; /** * The registry keeping track of which shards are processed by which application nodes. */ private final ShardedWorkRegistry workRegistry; /** * The storage of messages to deliver. */ private final InboxStorage inboxStorage; /** * The monitor of delivery stages. */ private final DeliveryMonitor monitor; /** * The maximum amount of messages to deliver within a {@link DeliveryStage}. */ private final int pageSize; Delivery(DeliveryBuilder builder) { this.strategy = builder.getStrategy(); this.workRegistry = builder.getWorkRegistry(); this.idempotenceWindow = builder.getIdempotenceWindow(); this.inboxStorage = builder.getInboxStorage(); this.monitor = builder.getMonitor(); this.pageSize = builder.getPageSize(); this.inboxDeliveries = Maps.newConcurrentMap(); this.shardObservers = synchronizedList(new ArrayList<>()); } /** * Creates an instance of new {@code Builder} of {@code Delivery}. */ public static DeliveryBuilder newBuilder() { return new DeliveryBuilder(); } /** * Creates a new instance of {@code Delivery} suitable for local and development environment. * * <p>Uses a {@linkplain UniformAcrossAllShards#singleShard() single-shard} splitting. */ public static Delivery local() { return localWithShardsAndWindow(1, LOCAL_IDEMPOTENCE_WINDOW); } /** * Creates a new instance of {@code Delivery} suitable for local and development environment * with the given number of shards. */ @VisibleForTesting static Delivery localWithShardsAndWindow(int shardCount, Duration idempotenceWindow) { checkArgument(shardCount > 0, "Shard count must be positive"); checkNotNull(idempotenceWindow); DeliveryStrategy strategy = UniformAcrossAllShards.forNumber(shardCount); return localWithStrategyAndWindow(strategy, idempotenceWindow); } @VisibleForTesting static Delivery localWithStrategyAndWindow(DeliveryStrategy strategy, Duration idempotenceWindow) { Delivery delivery = newBuilder().setIdempotenceWindow(idempotenceWindow) .setStrategy(strategy) .build(); delivery.subscribe(new LocalDispatchingObserver()); return delivery; } /** * Delivers the messages put into the shard with the passed index to their targets. * * <p>At a given moment of time, exactly one application node may serve messages from * a particular shard. Therefore, in scope of this delivery, an approach based on pessimistic * locking per-{@code ShardIndex} is applied. * * <p>In case the given shard is already processed by some node, this method does nothing. * * <p>The content of the shard is read and delivered on page-by-page basis. The runtime * exceptions occurring while a page is being delivered are accumulated and then the first * exception is rethrown, if any. * * <p>After all the pages are read, the delivery process is launched again for the same shard. * It is required in order to handle the messages, that may have been put to the same shard * as an outcome of the first-wave messages. * * <p>Once the shard has no more messages to deliver, the delivery process ends, releasing * the lock for the respective {@code ShardIndex}. * * @param index * the shard index to deliver the messages from. */ @SuppressWarnings("WeakerAccess") // a part of the public API. public void deliverMessagesFrom(ShardIndex index) { NodeId currentNode = ServerEnvironment.instance() .nodeId(); Optional<ShardProcessingSession> picked = workRegistry.pickUp(index, currentNode); if (!picked.isPresent()) { return; } ShardProcessingSession session = picked.get(); try { int deliveredMsgCount; do { deliveredMsgCount = doDeliver(session); } while (deliveredMsgCount > 0); } catch (DeliveryStoppedByMonitorException ignored) { // do nothing. } finally { session.complete(); } } /** * Runs the delivery for the shard, which session is passed. * * <p>The messages are read page-by-page according to the {@link #pageSize page size} setting. * * <p>After delivering each page of messages, a {@code DeliveryStage} is produced. * The configured {@link #monitor DeliveryMonitor} may stop the execution according to * the monitored {@code DeliveryStage}. * * @return the passed delivery stage. */ private int doDeliver(ShardProcessingSession session) { ShardIndex index = session.shardIndex(); Timestamp now = Time.currentTime(); Timestamp idempotenceWndStart = Timestamps.subtract(now, idempotenceWindow); Page<InboxMessage> startingPage = inboxStorage.readAll(index, pageSize); Optional<Page<InboxMessage>> maybePage = Optional.of(startingPage); int totalMessagesDelivered = 0; DeliveryStage stage = null; while (maybePage.isPresent() && monitorTellsToContinue(stage)) { Page<InboxMessage> currentPage = maybePage.get(); ImmutableList<InboxMessage> messages = currentPage.contents(); if (!messages.isEmpty()) { MessageClassifier classifier = MessageClassifier.of(messages, idempotenceWndStart); int deliveredInBatch = deliverClassified(classifier); totalMessagesDelivered += deliveredInBatch; ImmutableList<InboxMessage> toRemove = classifier.removals(); inboxStorage.removeAll(toRemove); stage = new DeliveryStage(index, deliveredInBatch); } maybePage = currentPage.next(); } return totalMessagesDelivered; } private boolean monitorTellsToContinue(@Nullable DeliveryStage stage) { if(stage == null) { return true; } if(monitor.shouldStopAfter(stage)) { throw new DeliveryStoppedByMonitorException(); } return true; } /** * Takes the messages classified as those to deliver and performs the actual delivery. * * @return the number of messages delivered */ private int deliverClassified(MessageClassifier classifier) { ImmutableList<InboxMessage> toDeliver = classifier.toDeliver(); int deliveredInBatch = 0; if (!toDeliver.isEmpty()) { ImmutableList<InboxMessage> idempotenceSource = classifier.idempotenceSource(); ImmutableList<RuntimeException> observedExceptions = deliverByType(toDeliver, idempotenceSource); deliveredInBatch = toDeliver.size(); if (!observedExceptions.isEmpty()) { throw observedExceptions.iterator() .next(); } } return deliveredInBatch; } private ImmutableList<RuntimeException> deliverByType(ImmutableList<InboxMessage> toDeliver, ImmutableList<InboxMessage> idmptSource) { Map<String, List<InboxMessage>> messagesByType = groupByTargetType(toDeliver); Map<String, List<InboxMessage>> idmptSourceByType = groupByTargetType(idmptSource); ImmutableList.Builder<RuntimeException> exceptionsAccumulator = ImmutableList.builder(); for (String typeUrl : messagesByType.keySet()) { ShardedMessageDelivery<InboxMessage> delivery = inboxDeliveries.get(typeUrl); List<InboxMessage> deliveryPackage = messagesByType.get(typeUrl); List<InboxMessage> idempotenceWnd = idmptSourceByType.getOrDefault(typeUrl, ImmutableList.of()); try { delivery.deliver(deliveryPackage, idempotenceWnd); } catch (RuntimeException e) { exceptionsAccumulator.add(e); } } ImmutableList<RuntimeException> exceptions = exceptionsAccumulator.build(); inboxStorage.markDelivered(toDeliver); return exceptions; } /** * Notifies that the contents of the shard with the given index have been updated * with some message. * * @param message * a message that was written into the shard */ private void onNewMessage(InboxMessage message) { for (ShardObserver observer : shardObservers) { observer.onMessage(message); } } /** * Creates an instance of {@link Inbox.Builder} for the given entity type. * * @param entityType * the type of the entity, to which the inbox will belong * @param <I> * the type if entity identifiers * @return the builder for the {@code Inbox} */ public <I> Inbox.Builder<I> newInbox(TypeUrl entityType) { return Inbox.newBuilder(entityType, inboxWriter()); } /** * Subscribes to the updates of shard contents. * * <p>The passed observer will be notified that the contents of a shard with a particular index * were changed. * * @param observer * an observer to notify of updates. */ public void subscribe(ShardObserver observer) { shardObservers.add(observer); } /** * Registers the passed {@code Inbox} and puts its {@linkplain Inbox#delivery() delivery * callbacks} into the list of those to be called, when the previously sharded messages * are dispatched to their targets. */ void register(Inbox<?> inbox) { TypeUrl entityType = inbox.entityStateType(); inboxDeliveries.put(entityType.value(), inbox.delivery()); } /** * Determines the shard index for the message, judging on the identifier of the entity, * to which this message is dispatched. * * @param entityId * the ID of the entity, to which the message is heading * @return the index of the shard for the message */ ShardIndex whichShardFor(Object entityId) { return strategy.indexFor(entityId); } /** * Unregisters the given {@code Inbox} and removes all the {@linkplain Inbox#delivery() * delivery callbacks} previously registered by this {@code Inbox}. */ void unregister(Inbox<?> inbox) { TypeUrl entityType = inbox.entityStateType(); inboxDeliveries.remove(entityType.value()); } @VisibleForTesting InboxStorage storage() { return inboxStorage; } @VisibleForTesting int shardCount() { return strategy.shardCount(); } private InboxWriter inboxWriter() { return new NotifyingWriter(inboxStorage) { @Override protected void onShardUpdated(InboxMessage message) { Delivery.this.onNewMessage(message); } }; } private static Map<String, List<InboxMessage>> groupByTargetType(List<InboxMessage> messages) { return messages.stream() .collect(groupingBy(m -> m.getInboxId() .getTypeUrl())); } }
package models; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.TimeZone; public class OrgConfig { public String name; public String people_url; public String str_manual_title; public String str_manual_title_short; public String str_res_plan_short; public String str_res_plan; public String str_res_plan_cap; public String str_res_plans; public String str_res_plans_cap; public String str_jc_name = "Judicial Committee"; public String str_jc_name_short = "JC"; public String str_findings = "Findings"; public String str_corporation = "Corporation"; public String str_committee = "Committee"; public String str_clerk = "Clerk"; public String str_guilty = "Guilty"; public String str_not_guilty = "Not Guilty"; public boolean show_no_contest_plea = false; public boolean show_na_plea = false; public boolean show_severity = false; public boolean use_minor_referrals = true; public boolean show_checkbox_for_res_plan = true; public boolean track_writer = true; public boolean filter_no_charge_cases = false; public boolean show_findings_in_rp_list = true; public boolean use_year_in_case_number = false; public boolean hide_location_for_print = false; public boolean euro_dates = false; public boolean enable_file_sharing = false; public Organization org; public TimeZone time_zone = TimeZone.getTimeZone("US/Eastern"); public static OrgConfig get() { Organization org = Organization.getByHost(); OrgConfig result = configs.get(org.name); result.org = org; return result; } public String getReferralDestination(Charge c) { return "School Meeting"; } static HashMap<String, OrgConfig> configs = new HashMap<String, OrgConfig>(); static void register(String name, OrgConfig config) { configs.put(name, config); } public String getCaseNumberPrefix(Meeting m) { String format = null; if (use_year_in_case_number) { format = euro_dates ? "dd-MM-YYYY-" : "YYYY-MM-dd-"; } else { format = euro_dates ? "dd-MM-" : "MM-dd-"; } return new SimpleDateFormat(format).format(m.date); } public String translatePlea(String plea) { if (plea.equals("Guilty")) { return this.str_guilty; } else if (plea.equals("Not Guilty")) { return this.str_not_guilty; } return plea; } } class ThreeRiversVillageSchool extends OrgConfig { private static final ThreeRiversVillageSchool INSTANCE = new ThreeRiversVillageSchool(); public ThreeRiversVillageSchool() { name = "Three Rivers Village School"; people_url = "https://trvs.demschooltools.com"; str_manual_title = "Management Manual"; str_manual_title_short = "Manual"; str_res_plan_short = "RP"; str_res_plan = "resolution plan"; str_res_plan_cap = "Resolution plan"; str_res_plans = "resolution plans"; str_res_plans_cap = "Resolution plans"; str_jc_name = "Justice Committee"; show_checkbox_for_res_plan = false; enable_file_sharing = true; OrgConfig.register(name, this); } public static ThreeRiversVillageSchool getInstance() { return INSTANCE; } } class PhillyFreeSchool extends OrgConfig { private static final PhillyFreeSchool INSTANCE = new PhillyFreeSchool(); public PhillyFreeSchool() { name = "Philly Free School"; people_url = "https://pfs.demschooltools.com"; str_manual_title = "Lawbook"; str_manual_title_short = "Lawbook"; str_res_plan_short = "Sentence"; str_res_plan = "sentence"; str_res_plan_cap = "Sentence"; str_res_plans = "sentences"; str_res_plans_cap = "Sentences"; show_no_contest_plea = true; show_na_plea = true; show_severity = true; OrgConfig.register(name, this); } public static PhillyFreeSchool getInstance() { return INSTANCE; } } class Fairhaven extends OrgConfig { private static final Fairhaven INSTANCE = new Fairhaven(); public Fairhaven() { name = "Fairhaven School"; people_url = "https://fairhaven.demschooltools.com"; str_manual_title = "Lawbook"; str_manual_title_short = "Lawbook"; str_res_plan_short = "Sentence"; str_res_plan = "sentence"; str_res_plan_cap = "Sentence"; str_res_plans = "sentences"; str_res_plans_cap = "Sentences"; str_findings = "JC Report"; show_findings_in_rp_list = false; use_year_in_case_number = true; OrgConfig.register(name, this); } public static Fairhaven getInstance() { return INSTANCE; } } class TheCircleSchool extends OrgConfig { private static final TheCircleSchool INSTANCE = new TheCircleSchool(); public TheCircleSchool() { name = "The Circle School"; people_url = "https://tcs.demschooltools.com"; str_manual_title = "Management Manual"; str_manual_title_short = "Mgmt. Man."; str_res_plan_short = "Sentence"; str_res_plan = "sentence"; str_res_plan_cap = "Sentence"; str_res_plans = "sentences"; str_res_plans_cap = "Sentences"; str_findings = "Findings"; track_writer = false; filter_no_charge_cases = true; hide_location_for_print = true; OrgConfig.register(name, this); } @Override public String getReferralDestination(Charge c) { if (c.plea.equals("Not Guilty")) { return "trial"; } else { return "School Meeting"; } } public static TheCircleSchool getInstance() { return INSTANCE; } @Override public String getCaseNumberPrefix(Meeting m) { return new SimpleDateFormat("yyyyMMdd").format(m.date); } } class MakariosLearningCommunity extends OrgConfig { private static final MakariosLearningCommunity INSTANCE = new MakariosLearningCommunity(); public MakariosLearningCommunity() { name = "Makarios Learning Community"; people_url = "https://mlc.demschooltools.com"; time_zone = TimeZone.getTimeZone("US/Central"); str_manual_title = "Management Manual"; str_manual_title_short = "Mgmt. Man."; str_res_plan_short = "Sentence"; str_res_plan = "sentence"; str_res_plan_cap = "Sentence"; str_res_plans = "sentences"; str_res_plans_cap = "Sentences"; str_findings = "Findings"; OrgConfig.register(name, this); } public static MakariosLearningCommunity getInstance() { return INSTANCE; } } class TheOpenSchool extends OrgConfig { private static final TheOpenSchool INSTANCE = new TheOpenSchool(); public TheOpenSchool() { name = "The Open School"; people_url = "https://tos.demschooltools.com"; time_zone = TimeZone.getTimeZone("US/Pacific"); str_manual_title = "Law Book"; str_manual_title_short = "Law Book"; str_res_plan_short = "Sentence"; str_res_plan = "sentence"; str_res_plan_cap = "Sentence"; str_res_plans = "sentences"; str_res_plans_cap = "Sentences"; str_findings = "Findings"; str_jc_name = "Civics Board"; str_jc_name_short = "CB"; str_guilty = "Agree"; str_not_guilty = "Disagree"; show_findings_in_rp_list = true; use_minor_referrals = false; show_no_contest_plea = true; OrgConfig.register(name, this); } public static TheOpenSchool getInstance() { return INSTANCE; } } class TheOpenSchool2 extends OrgConfig { private static final TheOpenSchool2 INSTANCE = new TheOpenSchool2(); public TheOpenSchool2() { name = "The Open School - Riverside"; people_url = "https://tos-2.demschooltools.com"; time_zone = TimeZone.getTimeZone("US/Pacific"); str_manual_title = "Law Book"; str_manual_title_short = "Law Book"; str_res_plan_short = "Sentence"; str_res_plan = "sentence"; str_res_plan_cap = "Sentence"; str_res_plans = "sentences"; str_res_plans_cap = "Sentences"; str_findings = "Findings"; str_jc_name = "Justice Committee"; str_jc_name_short = "JC"; str_guilty = "Confirm"; str_not_guilty = "Deny"; show_findings_in_rp_list = true; use_minor_referrals = false; show_no_contest_plea = true; OrgConfig.register(name, this); } public static TheOpenSchool2 getInstance() { return INSTANCE; } } class Houston extends OrgConfig { private static final Houston INSTANCE = new Houston(); public TimeZone time_zone = TimeZone.getTimeZone("US/Central"); public Houston() { name = "Houston Sudbury School"; people_url = "https://hss.demschooltools.com"; str_manual_title = "Lawbook"; str_manual_title_short = "Lawbook"; str_res_plan_short = "Sentence"; str_res_plan = "sentence"; str_res_plan_cap = "Sentence"; str_res_plans = "sentences"; str_res_plans_cap = "Sentences"; str_findings = "Findings"; track_writer = true; use_year_in_case_number = true; OrgConfig.register(name, this); } public static Houston getInstance() { return INSTANCE; } } class Sandbox extends OrgConfig { private static final Sandbox INSTANCE = new Sandbox(); public TimeZone time_zone = TimeZone.getTimeZone("US/Eastern"); public Sandbox() { name = "DemSchoolTools sandbox area"; people_url = "https://sandbox.demschooltools.com"; str_manual_title = "Lawbook"; str_manual_title_short = "Lawbook"; str_res_plan_short = "Sentence"; str_res_plan = "sentence"; str_res_plan_cap = "Sentence"; str_res_plans = "sentences"; str_res_plans_cap = "Sentences"; str_findings = "Findings"; track_writer = true; enable_file_sharing = true; OrgConfig.register(name, this); } public static Sandbox getInstance() { return INSTANCE; } } class Clearview extends OrgConfig { private static final Clearview INSTANCE = new Clearview(); public TimeZone time_zone = TimeZone.getTimeZone("US/Central"); public Clearview() { name = "Clearview Sudbury School"; people_url = "https://css.demschooltools.com"; str_manual_title = "Lawbook"; str_manual_title_short = "Lawbook"; str_res_plan_short = "Sentence"; str_res_plan = "sentence"; str_res_plan_cap = "Sentence"; str_res_plans = "sentences"; str_res_plans_cap = "Sentences"; str_findings = "Findings"; track_writer = false; OrgConfig.register(name, this); } public static Clearview getInstance() { return INSTANCE; } } class Wicklow extends OrgConfig { private static final Wicklow INSTANCE = new Wicklow(); public TimeZone time_zone = TimeZone.getTimeZone("Europe/Dublin"); public Wicklow() { name = "Wicklow Democratic School"; people_url = "https://wicklow.demschooltools.com"; str_manual_title = "Lawbook"; str_manual_title_short = "Lawbook"; str_res_plan_short = "Sanction"; str_res_plan = "sanction"; str_res_plan_cap = "Sanction"; str_res_plans = "sanctions"; str_res_plans_cap = "Sanctions"; str_findings = "Findings"; track_writer = false; euro_dates = true; use_year_in_case_number = true; OrgConfig.register(name, this); } public static Wicklow getInstance() { return INSTANCE; } } class Tallgrass extends OrgConfig { private static final Tallgrass INSTANCE = new Tallgrass(); public TimeZone time_zone = TimeZone.getTimeZone("US/Central"); public Tallgrass() { name = "Tallgrass Sudbury School"; people_url = "https://tallgrass.demschooltools.com"; str_manual_title = "Lawbook"; str_manual_title_short = "Lawbook"; str_res_plan_short = "Result"; str_res_plan = "result"; str_res_plan_cap = "Result"; str_res_plans = "results"; str_res_plans_cap = "Results"; str_findings = "Findings"; str_jc_name = "Restoration Committee"; str_jc_name_short = "RC"; str_guilty = "Agree"; str_not_guilty = "Disagree"; track_writer = false; OrgConfig.register(name, this); } public static Tallgrass getInstance() { return INSTANCE; } } class MiamiSudburySchool extends OrgConfig { private static final MiamiSudburySchool INSTANCE = new MiamiSudburySchool(); public TimeZone time_zone = TimeZone.getTimeZone("US/Eastern"); public MiamiSudburySchool() { name = "Miami Sudbury School"; people_url = "https://miami.demschooltools.com"; str_manual_title = "Lawbook"; str_manual_title_short = "Lawbook"; str_res_plan_short = "Ruling"; str_res_plan = "ruling"; str_res_plan_cap = "Ruling"; str_res_plans = "rulings"; str_res_plans_cap = "Rulings"; str_findings = "Complaint & Further Information"; str_guilty = "Accepts responsibility"; str_not_guilty = "Does not accept responsibility"; track_writer = true; OrgConfig.register(name, this); } public static MiamiSudburySchool getInstance() { return INSTANCE; } }
//FILE: MMStudioMainFrame.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio // Modifications by Arthur Edelstein, Nico Stuurman, Henry Pinkard // This file is distributed in the hope that it will be useful, // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. //CVS: $Id$ package org.micromanager; import ij.IJ; import ij.ImageJ; import ij.ImagePlus; import ij.WindowManager; import ij.gui.Line; import ij.gui.Roi; import ij.process.ImageProcessor; import ij.process.ShortProcessor; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Point2D; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.prefs.Preferences; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.SpringLayout; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.event.AncestorEvent; import mmcorej.CMMCore; import mmcorej.DeviceType; import mmcorej.MMCoreJ; import mmcorej.MMEventCallback; import mmcorej.StrVector; import org.json.JSONObject; import org.micromanager.acquisition.AcquisitionManager; import org.micromanager.api.Autofocus; import org.micromanager.api.DataProcessor; import org.micromanager.api.MMPlugin; import org.micromanager.api.MMTags; import org.micromanager.api.PositionList; import org.micromanager.api.ScriptInterface; import org.micromanager.api.MMListenerInterface; import org.micromanager.api.SequenceSettings; import org.micromanager.conf2.ConfiguratorDlg2; import org.micromanager.conf2.MMConfigFileException; import org.micromanager.conf2.MicroscopeModel; import org.micromanager.graph.GraphData; import org.micromanager.graph.GraphFrame; import org.micromanager.navigation.CenterAndDragListener; import org.micromanager.navigation.XYZKeyListener; import org.micromanager.navigation.ZWheelListener; import org.micromanager.utils.AutofocusManager; import org.micromanager.utils.ContrastSettings; import org.micromanager.utils.GUIColors; import org.micromanager.utils.GUIUtils; import org.micromanager.utils.JavaUtils; import org.micromanager.utils.MMException; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.NumberUtils; import org.micromanager.utils.TextUtils; import org.micromanager.utils.TooltipTextMaker; import org.micromanager.utils.WaitDialog; import bsh.EvalError; import bsh.Interpreter; import com.swtdesigner.SwingResourceManager; import ij.gui.ImageCanvas; import ij.gui.ImageWindow; import ij.gui.Toolbar; import java.awt.*; import java.awt.dnd.DropTarget; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Collections; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import javax.swing.*; import javax.swing.event.AncestorListener; import mmcorej.TaggedImage; import org.json.JSONException; import org.micromanager.acquisition.AcquisitionWrapperEngine; import org.micromanager.acquisition.LiveModeTimer; import org.micromanager.acquisition.MMAcquisition; import org.micromanager.api.ImageCache; import org.micromanager.acquisition.MetadataPanel; import org.micromanager.acquisition.ProcessorStack; import org.micromanager.acquisition.TaggedImageQueue; import org.micromanager.acquisition.TaggedImageStorageDiskDefault; import org.micromanager.acquisition.TaggedImageStorageMultipageTiff; import org.micromanager.acquisition.VirtualAcquisitionDisplay; import org.micromanager.api.IAcquisitionEngine2010; import org.micromanager.graph.HistogramSettings; import org.micromanager.internalinterfaces.LiveModeListener; import org.micromanager.utils.DragDropUtil; import org.micromanager.utils.FileDialogs; import org.micromanager.utils.FileDialogs.FileType; import org.micromanager.utils.HotKeysDialog; import org.micromanager.utils.ImageUtils; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMKeyDispatcher; import org.micromanager.utils.ReportingUtils; import org.micromanager.utils.UIMonitor; /* * Main panel and application class for the MMStudio. */ public class MMStudioMainFrame extends JFrame implements ScriptInterface { private static final String MICRO_MANAGER_TITLE = "Micro-Manager"; private static final long serialVersionUID = 3556500289598574541L; private static final String MAIN_FRAME_X = "x"; private static final String MAIN_FRAME_Y = "y"; private static final String MAIN_FRAME_WIDTH = "width"; private static final String MAIN_FRAME_HEIGHT = "height"; private static final String MAIN_FRAME_DIVIDER_POS = "divider_pos"; private static final String MAIN_EXPOSURE = "exposure"; private static final String MAIN_SAVE_METHOD = "saveMethod"; private static final String SYSTEM_CONFIG_FILE = "sysconfig_file"; private static final String OPEN_ACQ_DIR = "openDataDir"; private static final String SCRIPT_CORE_OBJECT = "mmc"; private static final String SCRIPT_ACQENG_OBJECT = "acq"; private static final String SCRIPT_GUI_OBJECT = "gui"; private static final String AUTOFOCUS_DEVICE = "autofocus_device"; private static final String MOUSE_MOVES_STAGE = "mouse_moves_stage"; private static final String EXPOSURE_SETTINGS_NODE = "MainExposureSettings"; private static final String CONTRAST_SETTINGS_NODE = "MainContrastSettings"; private static final int TOOLTIP_DISPLAY_DURATION_MILLISECONDS = 15000; private static final int TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS = 2000; // cfg file saving private static final String CFGFILE_ENTRY_BASE = "CFGFileEntry"; // + {0, 1, 2, 3, 4} // GUI components private JComboBox comboBinning_; private JComboBox shutterComboBox_; private JTextField textFieldExp_; private JLabel labelImageDimensions_; private JToggleButton liveButton_; private JButton toAlbumButton_; private JCheckBox autoShutterCheckBox_; private MMOptions options_; private boolean runsAsPlugin_; private JCheckBoxMenuItem centerAndDragMenuItem_; private JButton snapButton_; private JButton autofocusNowButton_; private JButton autofocusConfigureButton_; private JToggleButton toggleButtonShutter_; private GUIColors guiColors_; private GraphFrame profileWin_; private PropertyEditor propertyBrowser_; private CalibrationListDlg calibrationListDlg_; private AcqControlDlg acqControlWin_; private ReportProblemDialog reportProblemDialog_; private JMenu pluginMenu_; private ArrayList<PluginItem> plugins_; private List<MMListenerInterface> MMListeners_ = Collections.synchronizedList(new ArrayList<MMListenerInterface>()); private List<LiveModeListener> liveModeListeners_ = Collections.synchronizedList(new ArrayList<LiveModeListener>()); private List<Component> MMFrames_ = Collections.synchronizedList(new ArrayList<Component>()); private AutofocusManager afMgr_; private final static String DEFAULT_CONFIG_FILE_NAME = "MMConfig_demo.cfg"; private ArrayList<String> MRUConfigFiles_; private static final int maxMRUCfgs_ = 5; private String sysConfigFile_; private String startupScriptFile_; private String sysStateFile_ = "MMSystemState.cfg"; private ConfigGroupPad configPad_; private LiveModeTimer liveModeTimer_; private GraphData lineProfileData_; // labels for standard devices private String cameraLabel_; private String zStageLabel_; private String shutterLabel_; private String xyStageLabel_; // applications settings private Preferences mainPrefs_; private Preferences systemPrefs_; private Preferences colorPrefs_; private Preferences exposurePrefs_; private Preferences contrastPrefs_; // MMcore private CMMCore core_; private AcquisitionWrapperEngine engine_; private PositionList posList_; private PositionListDlg posListDlg_; private String openAcqDirectory_ = ""; private boolean running_; private boolean configChanged_ = false; private StrVector shutters_ = null; private JButton saveConfigButton_; private ScriptPanel scriptPanel_; private org.micromanager.utils.HotKeys hotKeys_; private CenterAndDragListener centerAndDragListener_; private ZWheelListener zWheelListener_; private XYZKeyListener xyzKeyListener_; private AcquisitionManager acqMgr_; private static VirtualAcquisitionDisplay simpleDisplay_; private Color[] multiCameraColors_ = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN}; private int snapCount_ = -1; private boolean liveModeSuspended_; public Font defaultScriptFont_ = null; public static final String SIMPLE_ACQ = "Snap/Live Window"; public static FileType MM_CONFIG_FILE = new FileType("MM_CONFIG_FILE", "Micro-Manager Config File", "./MyScope.cfg", true, "cfg"); // Our instance private static MMStudioMainFrame gui_; // Callback private CoreEventCallback cb_; // Lock invoked while shutting down private final Object shutdownLock_ = new Object(); private JMenuBar menuBar_; private ConfigPadButtonPanel configPadButtonPanel_; private final JMenu switchConfigurationMenu_; private final MetadataPanel metadataPanel_; public static FileType MM_DATA_SET = new FileType("MM_DATA_SET", "Micro-Manager Image Location", System.getProperty("user.home") + "/Untitled", false, (String[]) null); private Thread acquisitionEngine2010LoadingThread = null; private Class<?> acquisitionEngine2010Class = null; private IAcquisitionEngine2010 acquisitionEngine2010 = null; private final JSplitPane splitPane_; private volatile boolean ignorePropertyChanges_; private JButton setRoiButton_; private JButton clearRoiButton_; private DropTarget dt_; public ImageWindow getImageWin() { return getSnapLiveWin(); } @Override public ImageWindow getSnapLiveWin() { return simpleDisplay_.getHyperImage().getWindow(); } public static VirtualAcquisitionDisplay getSimpleDisplay() { return simpleDisplay_; } public static void createSimpleDisplay(String name, ImageCache cache) throws MMScriptException { simpleDisplay_ = new VirtualAcquisitionDisplay(cache, name); } public void checkSimpleAcquisition() { if (core_.getCameraDevice().length() == 0) { ReportingUtils.showError("No camera configured"); return; } int width = (int) core_.getImageWidth(); int height = (int) core_.getImageHeight(); int depth = (int) core_.getBytesPerPixel(); int bitDepth = (int) core_.getImageBitDepth(); int numCamChannels = (int) core_.getNumberOfCameraChannels(); try { if (acquisitionExists(SIMPLE_ACQ)) { if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width) || (getAcquisitionImageHeight(SIMPLE_ACQ) != height) || (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth) || (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth) || (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window closeAcquisitionWindow(SIMPLE_ACQ); } } if (!acquisitionExists(SIMPLE_ACQ)) { openAcquisition(SIMPLE_ACQ, "", 1, numCamChannels, 1, true); if (numCamChannels > 1) { for (long i = 0; i < numCamChannels; i++) { String chName = core_.getCameraChannelName(i); int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB(); setChannelColor(SIMPLE_ACQ, (int) i, getChannelColor(chName, defaultColor)); setChannelName(SIMPLE_ACQ, (int) i, chName); } } initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels); getAcquisition(SIMPLE_ACQ).promptToSave(false); getAcquisition(SIMPLE_ACQ).toFront(); this.updateCenterAndDragListener(); } } catch (Exception ex) { ReportingUtils.showError(ex); } } public void checkSimpleAcquisition(TaggedImage image) { try { JSONObject tags = image.tags; int width = MDUtils.getWidth(tags); int height = MDUtils.getHeight(tags); int depth = MDUtils.getDepth(tags); int bitDepth = MDUtils.getBitDepth(tags); int numCamChannels = (int) core_.getNumberOfCameraChannels(); if (acquisitionExists(SIMPLE_ACQ)) { if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width) || (getAcquisitionImageHeight(SIMPLE_ACQ) != height) || (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth) || (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth) || (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window closeAcquisitionWindow(SIMPLE_ACQ); // Seems that closeAcquisitionWindow also closes the acquisition... //closeAcquisition(SIMPLE_ACQ); } } if (!acquisitionExists(SIMPLE_ACQ)) { openAcquisition(SIMPLE_ACQ, "", 1, numCamChannels, 1, true); if (numCamChannels > 1) { for (long i = 0; i < numCamChannels; i++) { String chName = core_.getCameraChannelName(i); int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB(); setChannelColor(SIMPLE_ACQ, (int) i, getChannelColor(chName, defaultColor)); setChannelName(SIMPLE_ACQ, (int) i, chName); } } initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels); getAcquisition(SIMPLE_ACQ).promptToSave(false); getAcquisition(SIMPLE_ACQ).toFront(); this.updateCenterAndDragListener(); } } catch (Exception ex) { ReportingUtils.showError(ex); } } public void saveChannelColor(String chName, int rgb) { if (colorPrefs_ != null) { colorPrefs_.putInt("Color_" + chName, rgb); } } public Color getChannelColor(String chName, int defaultColor) { if (colorPrefs_ != null) { defaultColor = colorPrefs_.getInt("Color_" + chName, defaultColor); } return new Color(defaultColor); } @Override public void enableRoiButtons(final boolean enabled) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { setRoiButton_.setEnabled(enabled); clearRoiButton_.setEnabled(enabled); } }); } public void copyFromLiveModeToAlbum(VirtualAcquisitionDisplay display) throws MMScriptException, JSONException { ImageCache ic = display.getImageCache(); int channels = ic.getSummaryMetadata().getInt("Channels"); if (channels == 1) { //RGB or monchrome addToAlbum(ic.getImage(0, 0, 0, 0), ic.getDisplayAndComments()); } else { //multicamera for (int i = 0; i < channels; i++) { addToAlbum(ic.getImage(i, 0, 0, 0), ic.getDisplayAndComments()); } } } private void createCameraSettingsWidgets(JPanel topPanel) { createLabel("Camera settings", true, topPanel, 109, 2, 211, 22); // Exposure field createLabel("Exposure [ms]", false, topPanel, 111, 23, 198, 39); textFieldExp_ = new JTextField(); textFieldExp_.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent fe) { synchronized(shutdownLock_) { if (core_ != null) setExposure(); } } }); textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10)); textFieldExp_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setExposure(); } }); GUIUtils.addWithEdges(topPanel, textFieldExp_, 203, 21, 276, 40); // Shutter button toggleButtonShutter_ = new JToggleButton(); toggleButtonShutter_.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { toggleShutter(); } }); toggleButtonShutter_.setToolTipText("Open/close the shutter"); toggleButtonShutter_.setIconTextGap(6); toggleButtonShutter_.setFont(new Font("Arial", Font.BOLD, 10)); toggleButtonShutter_.setText("Open"); GUIUtils.addWithEdges(topPanel, toggleButtonShutter_, 203, 96, 275, 117); // Binning combo box createLabel("Binning", false, topPanel, 111, 43, 199, 64); comboBinning_ = new JComboBox(); comboBinning_.setName("Binning"); comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10)); comboBinning_.setMaximumRowCount(4); comboBinning_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { changeBinning(); } }); GUIUtils.addWithEdges(topPanel, comboBinning_, 200, 43, 275, 66); // Active shutter label createLabel("Shutter", false, topPanel, 111, 73, 158, 86); // Active shutter Combo Box shutterComboBox_ = new JComboBox(); shutterComboBox_.setName("Shutter"); shutterComboBox_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { try { if (shutterComboBox_.getSelectedItem() != null) { core_.setShutterDevice((String) shutterComboBox_.getSelectedItem()); } } catch (Exception e) { ReportingUtils.showError(e); } } }); GUIUtils.addWithEdges(topPanel, shutterComboBox_, 170, 70, 275, 92); autoShutterCheckBox_ = new JCheckBox(); autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10)); autoShutterCheckBox_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { shutterLabel_ = core_.getShutterDevice(); if (shutterLabel_.length() == 0) { toggleButtonShutter_.setEnabled(false); return; } if (autoShutterCheckBox_.isSelected()) { try { core_.setAutoShutter(true); core_.setShutterOpen(false); toggleButtonShutter_.setSelected(false); toggleButtonShutter_.setText("Open"); toggleButtonShutter_.setEnabled(false); } catch (Exception e2) { ReportingUtils.logError(e2); } } else { try { core_.setAutoShutter(false); core_.setShutterOpen(false); toggleButtonShutter_.setEnabled(true); toggleButtonShutter_.setText("Open"); } catch (Exception exc) { ReportingUtils.logError(exc); } } } }); autoShutterCheckBox_.setIconTextGap(6); autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING); autoShutterCheckBox_.setText("Auto shutter"); GUIUtils.addWithEdges(topPanel, autoShutterCheckBox_, 107, 96, 199, 119); } private void createConfigurationControls(JPanel topPanel) { createLabel("Configuration settings", true, topPanel, 280, 2, 430, 22); saveConfigButton_ = (JButton) createButton(false, "saveConfigureButton", "Save", "Save current presets to the configuration file", new Runnable() { public void run() { saveConfigPresets(); } }, null, topPanel, -80, 2, -5, 20); configPad_ = new ConfigGroupPad(); configPadButtonPanel_ = new ConfigPadButtonPanel(); configPadButtonPanel_.setConfigPad(configPad_); configPadButtonPanel_.setGUI(MMStudioMainFrame.getInstance()); configPad_.setFont(new Font("", Font.PLAIN, 10)); GUIUtils.addWithEdges(topPanel, configPad_, 280, 21, -4, -44); GUIUtils.addWithEdges(topPanel, configPadButtonPanel_, 280, -40, -4, -20); } private void createMainButtons(JPanel topPanel) { snapButton_ = (JButton) createButton(false, "Snap", "Snap", "Snap single image", new Runnable() { public void run() { doSnap(); } }, "camera.png", topPanel, 7, 4, 95, 25); liveButton_ = (JToggleButton) createButton(true, "Live", "Live", "Continuous live view", new Runnable() { public void run() { enableLiveMode(!isLiveModeOn()); } }, "camera_go.png", topPanel, 7, 26, 95, 47); toAlbumButton_ = (JButton) createButton(false, "Album", "Album", "Acquire single frame and add to an album", new Runnable() { public void run() { snapAndAddToImage5D(); } }, "camera_plus_arrow.png", topPanel, 7, 48, 95, 69); /* MDA Button = */ createButton(false, "Multi-D Acq.", "Multi-D Acq.", "Open multi-dimensional acquisition window", new Runnable() { public void run() { openAcqControlDialog(); } }, "film.png", topPanel, 7, 70, 95, 91); /* Refresh = */ createButton(false, "Refresh", "Refresh", "Refresh all GUI controls directly from the hardware", new Runnable() { public void run() { core_.updateSystemStateCache(); updateGUI(true); } }, "arrow_refresh.png", topPanel, 7, 92, 95, 113); } private static MetadataPanel createMetadataPanel(JPanel bottomPanel) { MetadataPanel metadataPanel = new MetadataPanel(); GUIUtils.addWithEdges(bottomPanel, metadataPanel, 0, 0, 0, 0); metadataPanel.setBorder(BorderFactory.createEmptyBorder()); return metadataPanel; } private void createPleaLabel(JPanel topPanel) { JLabel citePleaLabel = new JLabel("<html>Please <a href=\"http://micro-manager.org\">cite Micro-Manager</a> so funding will continue!</html>"); citePleaLabel.setFont(new Font("Arial", Font.PLAIN, 11)); GUIUtils.addWithEdges(topPanel, citePleaLabel, 7, 119, 270, 139); class Pleader extends Thread{ Pleader(){ super("pleader"); } @Override public void run(){ try { ij.plugin.BrowserLauncher.openURL("https://micro-manager.org/wiki/Citing_Micro-Manager"); } catch (IOException e1) { ReportingUtils.showError(e1); } } } citePleaLabel.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { Pleader p = new Pleader(); p.start(); } }); // add a listener to the main ImageJ window to catch it quitting out on us if (ij.IJ.getInstance() != null) { ij.IJ.getInstance().addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { closeSequence(true); }; }); } } private JSplitPane createSplitPane(int dividerPos) { JPanel topPanel = new JPanel(); JPanel bottomPanel = new JPanel(); topPanel.setLayout(new SpringLayout()); topPanel.setMinimumSize(new Dimension(580, 195)); bottomPanel.setLayout(new SpringLayout()); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, topPanel, bottomPanel); splitPane.setBorder(BorderFactory.createEmptyBorder()); splitPane.setDividerLocation(dividerPos); splitPane.setResizeWeight(0.0); return splitPane; } private void createTopPanelWidgets(JPanel topPanel) { createMainButtons(topPanel); createCameraSettingsWidgets(topPanel); createPleaLabel(topPanel); createUtilityButtons(topPanel); createConfigurationControls(topPanel); labelImageDimensions_ = createLabel("", false, topPanel, 5, -20, 0, 0); } private void createUtilityButtons(JPanel topPanel) { // ROI createLabel("ROI", true, topPanel, 8, 140, 71, 154); createButton(false, "setRoiButton", null, "Set Region Of Interest to selected rectangle", new Runnable() { public void run() { setROI(); } }, "shape_handles.png", topPanel, 7, 154, 37, 174); createButton(false, "clearRoiButton", null, "Reset Region of Interest to full frame", new Runnable() { public void run() { clearROI(); } }, "arrow_out.png", topPanel, 40, 154, 70, 174); // Zoom createLabel("Zoom", true, topPanel, 81, 140, 139, 154); createButton(false, "zoomInButton", null, "Zoom in", new Runnable() { public void run() { zoomIn(); } }, "zoom_in.png", topPanel, 80, 154, 110, 174); createButton(false, "zoomOutButton", null, "Zoom out", new Runnable() { public void run() { zoomOut(); } }, "zoom_out.png", topPanel, 113, 154, 143, 174); // Profile createLabel("Profile", true, topPanel, 154, 140, 217, 154); createButton(false, "lineProfileButton", null, "Open line profile window (requires line selection)", new Runnable() { public void run() { openLineProfileWindow(); } }, "chart_curve.png", topPanel, 153, 154, 183, 174); // Autofocus createLabel("Autofocus", true, topPanel, 194, 140, 276, 154); autofocusNowButton_ = (JButton) createButton(false, "autofocusNowButton", null, "Autofocus now", new Runnable() { public void run() { autofocusNow(); } }, "find.png", topPanel, 193, 154, 223, 174); autofocusConfigureButton_ = (JButton) createButton(false, "autofocusConfigureButton", null, "Set autofocus options", new Runnable() { public void run() { showAutofocusDialog(); } }, "wrench_orange.png", topPanel, 226, 154, 256, 174); } private void initializeFileMenu() { JMenu fileMenu = GUIUtils.createMenuInMenuBar(menuBar_, "File"); GUIUtils.addMenuItem(fileMenu, "Open (Virtual)...", null, new Runnable() { public void run() { new Thread() { @Override public void run() { openAcquisitionData(false); } }.start(); } }); GUIUtils.addMenuItem(fileMenu, "Open (RAM)...", null, new Runnable() { public void run() { new Thread() { @Override public void run() { openAcquisitionData(true); } }.start(); } }); fileMenu.addSeparator(); GUIUtils.addMenuItem(fileMenu, "Exit", null, new Runnable() { public void run() { closeSequence(false); } }); } private void initializeHelpMenu() { final JMenu helpMenu = GUIUtils.createMenuInMenuBar(menuBar_, "Help"); GUIUtils.addMenuItem(helpMenu, "User's Guide", null, new Runnable() { public void run() { try { ij.plugin.BrowserLauncher.openURL("http://micro-manager.org/wiki/Micro-Manager_User%27s_Guide"); } catch (IOException e1) { ReportingUtils.showError(e1); } } }); GUIUtils.addMenuItem(helpMenu, "Configuration Guide", null, new Runnable() { public void run() { try { ij.plugin.BrowserLauncher.openURL("http://micro-manager.org/wiki/Micro-Manager_Configuration_Guide"); } catch (IOException e1) { ReportingUtils.showError(e1); } } }); if (!systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false)) { GUIUtils.addMenuItem(helpMenu, "Register your copy of Micro-Manager...", null, new Runnable() { public void run() { try { RegistrationDlg regDlg = new RegistrationDlg(systemPrefs_); regDlg.setVisible(true); } catch (Exception e1) { ReportingUtils.showError(e1); } } }); } GUIUtils.addMenuItem(helpMenu, "Report Problem...", null, new Runnable() { public void run() { if (null == reportProblemDialog_) { reportProblemDialog_ = new ReportProblemDialog(core_, MMStudioMainFrame.this, options_); MMStudioMainFrame.this.addMMBackgroundListener(reportProblemDialog_); reportProblemDialog_.setBackground(guiColors_.background.get(options_.displayBackground_)); } reportProblemDialog_.setVisible(true); } }); GUIUtils.addMenuItem(helpMenu, "About Micromanager", null, new Runnable() { public void run() { MMAboutDlg dlg = new MMAboutDlg(); String versionInfo = "MM Studio version: " + MMVersion.VERSION_STRING; versionInfo += "\n" + core_.getVersionInfo(); versionInfo += "\n" + core_.getAPIVersionInfo(); versionInfo += "\nUser: " + core_.getUserId(); versionInfo += "\nHost: " + core_.getHostName(); dlg.setVersionInfo(versionInfo); dlg.setVisible(true); } }); menuBar_.validate(); } private void initializeToolsMenu() { // Tools menu final JMenu toolsMenu = GUIUtils.createMenuInMenuBar(menuBar_, "Tools"); GUIUtils.addMenuItem(toolsMenu, "Refresh GUI", "Refresh all GUI controls directly from the hardware", new Runnable() { public void run() { core_.updateSystemStateCache(); updateGUI(true); } }, "arrow_refresh.png"); GUIUtils.addMenuItem(toolsMenu, "Rebuild GUI", "Regenerate Micro-Manager user interface", new Runnable() { public void run() { initializeGUI(); core_.updateSystemStateCache(); } }); toolsMenu.addSeparator(); GUIUtils.addMenuItem(toolsMenu, "Script Panel...", "Open Micro-Manager script editor window", new Runnable() { public void run() { scriptPanel_.setVisible(true); } }); GUIUtils.addMenuItem(toolsMenu, "Shortcuts...", "Create keyboard shortcuts to activate image acquisition, mark positions, or run custom scripts", new Runnable() { public void run() { HotKeysDialog hk = new HotKeysDialog(guiColors_.background.get((options_.displayBackground_))); //hk.setBackground(guiColors_.background.get((options_.displayBackground_))); } }); GUIUtils.addMenuItem(toolsMenu, "Device/Property Browser...", "Open new window to view and edit property values in current configuration", new Runnable() { public void run() { createPropertyEditor(); } }); toolsMenu.addSeparator(); GUIUtils.addMenuItem(toolsMenu, "XY List...", "Open position list manager window", new Runnable() { public void run() { showXYPositionList(); } }, "application_view_list.png"); GUIUtils.addMenuItem(toolsMenu, "Multi-Dimensional Acquisition...", "Open multi-dimensional acquisition setup window", new Runnable() { public void run() { openAcqControlDialog(); } }, "film.png"); centerAndDragMenuItem_ = GUIUtils.addCheckBoxMenuItem(toolsMenu, "Mouse Moves Stage (use Hand Tool)", "When enabled, double clicking or dragging in the snap/live\n" + "window moves the XY-stage. Requires the hand tool.", new Runnable() { public void run() { updateCenterAndDragListener(); IJ.setTool(Toolbar.HAND); mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected()); } }, mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false)); GUIUtils.addMenuItem(toolsMenu, "Pixel Size Calibration...", "Define size calibrations specific to each objective lens. " + "When the objective in use has a calibration defined, " + "micromanager will automatically use it when " + "calculating metadata", new Runnable() { public void run() { createCalibrationListDlg(); } }); toolsMenu.addSeparator(); GUIUtils.addMenuItem(toolsMenu, "Hardware Configuration Wizard...", "Open wizard to create new hardware configuration", new Runnable() { public void run() { runHardwareWizard(); } }); GUIUtils.addMenuItem(toolsMenu, "Load Hardware Configuration...", "Un-initialize current configuration and initialize new one", new Runnable() { public void run() { loadConfiguration(); initializeGUI(); } }); GUIUtils.addMenuItem(toolsMenu, "Reload Hardware Configuration", "Shutdown current configuration and initialize most recently loaded configuration", new Runnable() { public void run() { loadSystemConfiguration(); initializeGUI(); } }); for (int i=0; i<5; i++) { JMenuItem configItem = new JMenuItem(); configItem.setText(Integer.toString(i)); switchConfigurationMenu_.add(configItem); } switchConfigurationMenu_.setText("Switch Hardware Configuration"); toolsMenu.add(switchConfigurationMenu_); switchConfigurationMenu_.setToolTipText("Switch between recently used configurations"); GUIUtils.addMenuItem(toolsMenu, "Save Configuration Settings as...", "Save current configuration settings as new configuration file", new Runnable() { public void run() { saveConfigPresets(); updateChannelCombos(); } }); toolsMenu.addSeparator(); final MMStudioMainFrame thisInstance = this; GUIUtils.addMenuItem(toolsMenu, "Options...", "Set a variety of Micro-Manager configuration options", new Runnable() { public void run() { final int oldBufsize = options_.circularBufferSizeMB_; OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_, thisInstance); dlg.setVisible(true); // adjust memory footprint if necessary if (oldBufsize != options_.circularBufferSizeMB_) { try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_); } catch (Exception exc) { ReportingUtils.showError(exc); } } } }); } private void updateSwitchConfigurationMenu() { switchConfigurationMenu_.removeAll(); for (final String configFile : MRUConfigFiles_) { if (!configFile.equals(sysConfigFile_)) { GUIUtils.addMenuItem(switchConfigurationMenu_, configFile, null, new Runnable() { public void run() { sysConfigFile_ = configFile; loadSystemConfiguration(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); } }); } } } /** * Allows MMListeners to register themselves */ @Override public void addMMListener(MMListenerInterface newL) { if (MMListeners_.contains(newL)) return; MMListeners_.add(newL); } /** * Allows MMListeners to remove themselves */ @Override public void removeMMListener(MMListenerInterface oldL) { if (!MMListeners_.contains(oldL)) return; MMListeners_.remove(oldL); } public final void addLiveModeListener (LiveModeListener listener) { if (liveModeListeners_.contains(listener)) { return; } liveModeListeners_.add(listener); } public void removeLiveModeListener(LiveModeListener listener) { liveModeListeners_.remove(listener); } public void callLiveModeListeners(boolean enable) { for (LiveModeListener listener : liveModeListeners_) { listener.liveModeEnabled(enable); } } /** * Lets JComponents register themselves so that their background can be * manipulated */ @Override public void addMMBackgroundListener(Component comp) { if (MMFrames_.contains(comp)) return; MMFrames_.add(comp); } /** * Lets JComponents remove themselves from the list whose background gets * changes */ @Override public void removeMMBackgroundListener(Component comp) { if (!MMFrames_.contains(comp)) return; MMFrames_.remove(comp); } /** * Part of ScriptInterface * Manipulate acquisition so that it looks like a burst */ public void runBurstAcquisition() throws MMScriptException { double interval = engine_.getFrameIntervalMs(); int nr = engine_.getNumFrames(); boolean doZStack = engine_.isZSliceSettingEnabled(); boolean doChannels = engine_.isChannelsSettingEnabled(); engine_.enableZSliceSetting(false); engine_.setFrames(nr, 0); engine_.enableChannelsSetting(false); try { engine_.acquire(); } catch (MMException e) { throw new MMScriptException(e); } engine_.setFrames(nr, interval); engine_.enableZSliceSetting(doZStack); engine_.enableChannelsSetting(doChannels); } public void runBurstAcquisition(int nr) throws MMScriptException { int originalNr = engine_.getNumFrames(); double interval = engine_.getFrameIntervalMs(); engine_.setFrames(nr, 0); this.runBurstAcquisition(); engine_.setFrames(originalNr, interval); } public void runBurstAcquisition(int nr, String name, String root) throws MMScriptException { String originalRoot = engine_.getRootName(); engine_.setDirName(name); engine_.setRootName(root); this.runBurstAcquisition(nr); engine_.setRootName(originalRoot); } /** * Inserts version info for various components in the Corelog */ @Override public void logStartupProperties() { core_.enableDebugLog(options_.debugLogEnabled_); core_.logMessage("MM Studio version: " + getVersion()); core_.logMessage(core_.getVersionInfo()); core_.logMessage(core_.getAPIVersionInfo()); core_.logMessage("Operating System: " + System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ") " + System.getProperty("os.version")); core_.logMessage("JVM: " + System.getProperty("java.vm.name") + ", version " + System.getProperty("java.version") + ", " + System.getProperty("sun.arch.data.model") + "-bit"); } /** * @Deprecated * @throws MMScriptException */ public void startBurstAcquisition() throws MMScriptException { runAcquisition(); } public boolean isBurstAcquisitionRunning() throws MMScriptException { if (engine_ == null) return false; return engine_.isAcquisitionRunning(); } private void startLoadingPipelineClass() { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); acquisitionEngine2010LoadingThread = new Thread("Pipeline Class loading thread") { @Override public void run() { try { acquisitionEngine2010Class = Class.forName("org.micromanager.AcquisitionEngine2010"); } catch (Exception ex) { ReportingUtils.logError(ex); acquisitionEngine2010Class = null; } } }; acquisitionEngine2010LoadingThread.start(); } @Override public ImageCache getAcquisitionImageCache(String acquisitionName) throws MMScriptException { return getAcquisition(acquisitionName).getImageCache(); } /** * Shows images as they appear in the default display window. Uses * the default processor stack to process images as they arrive on * the rawImageQueue. */ public void runDisplayThread(BlockingQueue<TaggedImage> rawImageQueue, final DisplayImageRoutine displayImageRoutine) { final BlockingQueue<TaggedImage> processedImageQueue = ProcessorStack.run(rawImageQueue, getAcquisitionEngine().getImageProcessors()); new Thread("Display thread") { @Override public void run() { try { TaggedImage image; do { image = processedImageQueue.take(); if (image != TaggedImageQueue.POISON) { displayImageRoutine.show(image); } } while (image != TaggedImageQueue.POISON); } catch (InterruptedException ex) { ReportingUtils.logError(ex); } } }.start(); } private static AbstractButton createButton(final boolean isToggleButton, final String name, final String text, final String toolTipText, final Runnable buttonActionRunnable, final String iconFileName, final JPanel parentPanel, int west, int north, int east, int south) { AbstractButton button = isToggleButton ? new JToggleButton() : new JButton(); button.setFont(new Font("Arial", Font.PLAIN, 10)); button.setMargin(new Insets(0, 0, 0, 0)); button.setName(name); if (text != null) { button.setText(text); } if (iconFileName != null) { button.setIconTextGap(4); GUIUtils.setIcon(button, iconFileName); } if (toolTipText != null) { button.setToolTipText(toolTipText); } button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { buttonActionRunnable.run(); } }); GUIUtils.addWithEdges(parentPanel, button, west, north, east, south); return button; } private static JLabel createLabel(String text, boolean big, JPanel parentPanel, int west, int north, int east, int south) { final JLabel label = new JLabel(); label.setFont(new Font("Arial", big ? Font.BOLD : Font.PLAIN, big ? 11 : 10)); label.setText(text); GUIUtils.addWithEdges(parentPanel, label, west, north, east, south); return label; } public interface DisplayImageRoutine { public void show(TaggedImage image); } /** * Callback to update GUI when a change happens in the MMCore. */ public class CoreEventCallback extends MMEventCallback { public CoreEventCallback() { super(); } @Override public void onPropertiesChanged() { // TODO: remove test once acquisition engine is fully multithreaded if (engine_ != null && engine_.isAcquisitionRunning()) { core_.logMessage("Notification from MMCore ignored because acquistion is running!", true); } else { if (ignorePropertyChanges_) { core_.logMessage("Notification from MMCore ignored since the system is still loading", true); } else { core_.updateSystemStateCache(); updateGUI(true); // update all registered listeners for (MMListenerInterface mmIntf : MMListeners_) { mmIntf.propertiesChangedAlert(); } core_.logMessage("Notification from MMCore!", true); } } } @Override public void onPropertyChanged(String deviceName, String propName, String propValue) { core_.logMessage("Notification for Device: " + deviceName + " Property: " + propName + " changed to value: " + propValue, true); // update all registered listeners for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.propertyChangedAlert(deviceName, propName, propValue); } } @Override public void onConfigGroupChanged(String groupName, String newConfig) { try { configPad_.refreshGroup(groupName, newConfig); for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.configGroupChangedAlert(groupName, newConfig); } } catch (Exception e) { } } @Override public void onSystemConfigurationLoaded() { for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.systemConfigurationLoaded(); } } @Override public void onPixelSizeChanged(double newPixelSizeUm) { updatePixSizeUm (newPixelSizeUm); for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.pixelSizeChangedAlert(newPixelSizeUm); } } @Override public void onStagePositionChanged(String deviceName, double pos) { if (deviceName.equals(zStageLabel_)) { updateZPos(pos); for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.stagePositionChangedAlert(deviceName, pos); } } } @Override public void onStagePositionChangedRelative(String deviceName, double pos) { if (deviceName.equals(zStageLabel_)) updateZPosRelative(pos); } @Override public void onXYStagePositionChanged(String deviceName, double xPos, double yPos) { if (deviceName.equals(xyStageLabel_)) { updateXYPos(xPos, yPos); for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.xyStagePositionChanged(deviceName, xPos, yPos); } } } @Override public void onXYStagePositionChangedRelative(String deviceName, double xPos, double yPos) { if (deviceName.equals(xyStageLabel_)) updateXYPosRelative(xPos, yPos); } @Override public void onExposureChanged(String deviceName, double exposure) { if (deviceName.equals(cameraLabel_)){ // update exposure in gui textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure)); } for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.exposureChanged(deviceName, exposure); } } } private class PluginItem { public Class<?> pluginClass = null; public String menuItem = "undefined"; public MMPlugin plugin = null; public String className = ""; public void instantiate() { try { if (plugin == null) { plugin = (MMPlugin) pluginClass.newInstance(); } } catch (InstantiationException e) { ReportingUtils.logError(e); } catch (IllegalAccessException e) { ReportingUtils.logError(e); } plugin.setApp(MMStudioMainFrame.this); } } /* * Simple class used to cache static info */ private class StaticInfo { public long width_; public long height_; public long bytesPerPixel_; public long imageBitDepth_; public double pixSizeUm_; public double zPos_; public double x_; public double y_; } private StaticInfo staticInfo_ = new StaticInfo(); private void setupWindowHandlers() { // add window listeners addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { closeSequence(false); } @Override public void windowOpened(WindowEvent e) { // initialize hardware try { core_ = new CMMCore(); } catch(UnsatisfiedLinkError ex) { ReportingUtils.showError(ex, "Failed to open libMMCoreJ_wrap.jnilib"); return; } ReportingUtils.setCore(core_); logStartupProperties(); cameraLabel_ = ""; shutterLabel_ = ""; zStageLabel_ = ""; xyStageLabel_ = ""; engine_ = new AcquisitionWrapperEngine(acqMgr_); // register callback for MMCore notifications, this is a global // to avoid garbage collection cb_ = new CoreEventCallback(); core_.registerCallback(cb_); try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_); } catch (Exception e2) { ReportingUtils.showError(e2); } MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow(); if (parent != null) { engine_.setParentGUI(parent); } loadMRUConfigFiles(); afMgr_ = new AutofocusManager(gui_); Thread pluginLoader = initializePlugins(); toFront(); if (!options_.doNotAskForConfigFile_) { MMIntroDlg introDlg = new MMIntroDlg(MMVersion.VERSION_STRING, MRUConfigFiles_); introDlg.setConfigFile(sysConfigFile_); introDlg.setBackground(guiColors_.background.get((options_.displayBackground_))); introDlg.setVisible(true); sysConfigFile_ = introDlg.getConfigFile(); } saveMRUConfigFiles(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); paint(MMStudioMainFrame.this.getGraphics()); engine_.setCore(core_, afMgr_); posList_ = new PositionList(); engine_.setPositionList(posList_); // load (but do no show) the scriptPanel createScriptPanel(); // Create an instance of HotKeys so that they can be read in from prefs hotKeys_ = new org.micromanager.utils.HotKeys(); hotKeys_.loadSettings(); // before loading the system configuration, we need to wait // until the plugins are loaded try { pluginLoader.join(2000); } catch (InterruptedException ex) { ReportingUtils.logError(ex, "Plugin loader thread was interupted"); } // if an error occurred during config loading, // do not display more errors than needed if (!loadSystemConfiguration()) ReportingUtils.showErrorOn(false); executeStartupScript(); // Create Multi-D window here but do not show it. // This window needs to be created in order to properly set the "ChannelGroup" // based on the Multi-D parameters acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this, options_); addMMBackgroundListener(acqControlWin_); configPad_.setCore(core_); if (parent != null) { configPad_.setParentGUI(parent); } configPadButtonPanel_.setCore(core_); // initialize controls // initializeGUI(); Not needed since it is already called in loadSystemConfiguration initializeHelpMenu(); String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, ""); if (afMgr_.hasDevice(afDevice)) { try { afMgr_.selectDevice(afDevice); } catch (MMException e1) { // this error should never happen ReportingUtils.showError(e1); } } centerAndDragListener_ = new CenterAndDragListener(gui_); zWheelListener_ = new ZWheelListener(core_, gui_); gui_.addLiveModeListener(zWheelListener_); xyzKeyListener_ = new XYZKeyListener(core_, gui_); gui_.addLiveModeListener(xyzKeyListener_); // switch error reporting back on ReportingUtils.showErrorOn(true); } private Thread initializePlugins() { pluginMenu_ = GUIUtils.createMenuInMenuBar(menuBar_, "Plugins"); Thread myThread = new ThreadPluginLoading("Plugin loading"); myThread.start(); return myThread; } class ThreadPluginLoading extends Thread { public ThreadPluginLoading(String string) { super(string); } @Override public void run() { // Needed for loading clojure-based jars: Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); loadPlugins(); } } }); } /** * Main procedure for stand alone operation. */ public static void main(String args[]) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); MMStudioMainFrame frame = new MMStudioMainFrame(false); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } catch (Throwable e) { ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit."); System.exit(1); } } @SuppressWarnings("LeakingThisInConstructor") public MMStudioMainFrame(boolean pluginStatus) { super(); startLoadingPipelineClass(); options_ = new MMOptions(); try { options_.loadSettings(); } catch (NullPointerException ex) { ReportingUtils.logError(ex); } UIMonitor.enable(options_.debugLogEnabled_); guiColors_ = new GUIColors(); plugins_ = new ArrayList<PluginItem>(); gui_ = this; runsAsPlugin_ = pluginStatus; setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class, "icons/microscope.gif")); running_ = true; acqMgr_ = new AcquisitionManager(); sysConfigFile_ = System.getProperty("user.dir") + "/" + DEFAULT_CONFIG_FILE_NAME; if (options_.startupScript_.length() > 0) { startupScriptFile_ = System.getProperty("user.dir") + "/" + options_.startupScript_; } else { startupScriptFile_ = ""; } ReportingUtils.SetContainingFrame(gui_); // set the location for app preferences try { mainPrefs_ = Preferences.userNodeForPackage(this.getClass()); } catch (Exception e) { ReportingUtils.logError(e); } systemPrefs_ = mainPrefs_; colorPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" + AcqControlDlg.COLOR_SETTINGS_NODE); exposurePrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" + EXPOSURE_SETTINGS_NODE); contrastPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" + CONTRAST_SETTINGS_NODE); // check system preferences try { Preferences p = Preferences.systemNodeForPackage(this.getClass()); if (null != p) { // if we can not write to the systemPrefs, use AppPrefs instead if (JavaUtils.backingStoreAvailable(p)) { systemPrefs_ = p; } } } catch (Exception e) { ReportingUtils.logError(e); } // show registration dialog if not already registered // first check user preferences (for legacy compatibility reasons) boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false); if (!userReg) { boolean systemReg = systemPrefs_.getBoolean( RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false); if (!systemReg) { // prompt for registration info RegistrationDlg dlg = new RegistrationDlg(systemPrefs_); dlg.setVisible(true); } } // load application preferences // NOTE: only window size and position preferences are loaded, // not the settings for the camera and live imaging - // attempting to set those automatically on startup may cause problems // with the hardware int x = mainPrefs_.getInt(MAIN_FRAME_X, 100); int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100); int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 644); int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 570); openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, ""); try { ImageUtils.setImageStorageClass(Class.forName (mainPrefs_.get(MAIN_SAVE_METHOD, ImageUtils.getImageStorageClass().getName()) ) ); } catch (ClassNotFoundException ex) { ReportingUtils.logError(ex, "Class not found error. Should never happen"); } ToolTipManager ttManager = ToolTipManager.sharedInstance(); ttManager.setDismissDelay(TOOLTIP_DISPLAY_DURATION_MILLISECONDS); ttManager.setInitialDelay(TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS); setBounds(x, y, width, height); setExitStrategy(options_.closeOnExit_); setTitle(MICRO_MANAGER_TITLE + " " + MMVersion.VERSION_STRING); setBackground(guiColors_.background.get((options_.displayBackground_))); setMinimumSize(new Dimension(605,480)); menuBar_ = new JMenuBar(); switchConfigurationMenu_ = new JMenu(); setJMenuBar(menuBar_); initializeFileMenu(); initializeToolsMenu(); splitPane_ = createSplitPane(mainPrefs_.getInt(MAIN_FRAME_DIVIDER_POS, 200)); getContentPane().add(splitPane_); createTopPanelWidgets((JPanel) splitPane_.getComponent(0)); metadataPanel_ = createMetadataPanel((JPanel) splitPane_.getComponent(1)); setupWindowHandlers(); // Add our own keyboard manager that handles Micro-Manager shortcuts MMKeyDispatcher mmKD = new MMKeyDispatcher(gui_); KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(mmKD); dt_ = new DropTarget(this, new DragDropUtil()); } private void handleException(Exception e, String msg) { String errText = "Exception occurred: "; if (msg.length() > 0) { errText += msg + " } if (options_.debugLogEnabled_) { errText += e.getMessage(); } else { errText += e.toString() + "\n"; ReportingUtils.showError(e); } handleError(errText); } private void handleException(Exception e) { handleException(e, ""); } private void handleError(String message) { if (isLiveModeOn()) { // Should we always stop live mode on any error? enableLiveMode(false); } JOptionPane.showMessageDialog(this, message); core_.logMessage(message); } @Override public void makeActive() { toFront(); } /** * used to store contrast settings to be later used for initialization of contrast of new windows. * Shouldn't be called by loaded data sets, only * ones that have been acquired */ public void saveChannelHistogramSettings(String channelGroup, String channel, boolean mda, HistogramSettings settings) { String type = mda ? "MDA_" : "SnapLive_"; if (options_.syncExposureMainAndMDA_) { type = ""; //only one group of contrast settings } contrastPrefs_.putInt("ContrastMin_" + channelGroup + "_" + type + channel, settings.min_); contrastPrefs_.putInt("ContrastMax_" + channelGroup + "_" + type + channel, settings.max_); contrastPrefs_.putDouble("ContrastGamma_" + channelGroup + "_" + type + channel, settings.gamma_); contrastPrefs_.putInt("ContrastHistMax_" + channelGroup + "_" + type + channel, settings.histMax_); contrastPrefs_.putInt("ContrastHistDisplayMode_" + channelGroup + "_" + type + channel, settings.displayMode_); } public HistogramSettings loadStoredChannelHisotgramSettings(String channelGroup, String channel, boolean mda) { String type = mda ? "MDA_" : "SnapLive_"; if (options_.syncExposureMainAndMDA_) { type = ""; //only one group of contrast settings } return new HistogramSettings( contrastPrefs_.getInt("ContrastMin_" + channelGroup + "_" + type + channel,0), contrastPrefs_.getInt("ContrastMax_" + channelGroup + "_" + type + channel, 65536), contrastPrefs_.getDouble("ContrastGamma_" + channelGroup + "_" + type + channel, 1.0), contrastPrefs_.getInt("ContrastHistMax_" + channelGroup + "_" + type + channel, -1), contrastPrefs_.getInt("ContrastHistDisplayMode_" + channelGroup + "_" + type + channel, 1) ); } private void setExposure() { try { if (!isLiveModeOn()) { core_.setExposure(NumberUtils.displayStringToDouble( textFieldExp_.getText())); } else { liveModeTimer_.stop(); core_.setExposure(NumberUtils.displayStringToDouble( textFieldExp_.getText())); try { liveModeTimer_.begin(); } catch (Exception e) { ReportingUtils.showError("Couldn't restart live mode"); liveModeTimer_.stop(); } } // Display the new exposure time double exposure = core_.getExposure(); textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure)); // update current channel in MDA window with this exposure String channelGroup = core_.getChannelGroup(); String channel = core_.getCurrentConfigFromCache(channelGroup); if (!channel.equals("") ) { exposurePrefs_.putDouble("Exposure_" + channelGroup + "_" + channel, exposure); if (options_.syncExposureMainAndMDA_) { getAcqDlg().setChannelExposureTime(channelGroup, channel, exposure); } } } catch (Exception exp) { // Do nothing. } } /** * Returns exposure time for the desired preset in the given channelgroup * Acquires its info from the preferences * Same thing is used in MDA window, but this class keeps its own copy * * @param channelGroup * @param channel - * @param defaultExp - default value * @return exposure time */ @Override public double getChannelExposureTime(String channelGroup, String channel, double defaultExp) { return exposurePrefs_.getDouble("Exposure_" + channelGroup + "_" + channel, defaultExp); } /** * Updates the exposure time in the given preset * Will also update current exposure if it the given channel and channelgroup * are the current one * * @param channelGroup - * * @param channel - preset for which to change exposure time * @param exposure - desired exposure time */ @Override public void setChannelExposureTime(String channelGroup, String channel, double exposure) { try { exposurePrefs_.putDouble("Exposure_" + channelGroup + "_" + channel, exposure); if (channelGroup != null && channelGroup.equals(core_.getChannelGroup())) { if (channel != null && !channel.equals("") && channel.equals(core_.getCurrentConfigFromCache(channelGroup))) { textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure)); setExposure(); } } } catch (Exception ex) { ReportingUtils.logError("Failed to set Exposure prefs using Channelgroup: " + channelGroup + ", channel: " + channel + ", exposure: " + exposure); } } @Override public boolean getAutoreloadOption() { return options_.autoreloadDevices_; } public double getPreferredWindowMag() { return options_.windowMag_; } public boolean getMetadataFileWithMultipageTiff() { return options_.mpTiffMetadataFile_; } public boolean getSeparateFilesForPositionsMPTiff() { return options_.mpTiffSeparateFilesForPositions_; } @Override public boolean getHideMDADisplayOption() { return options_.hideMDADisplay_; } public boolean getFastStorageOption() { return options_.fastStorage_; } private void updateTitle() { this.setTitle(MICRO_MANAGER_TITLE + " " + MMVersion.VERSION_STRING + " - " + sysConfigFile_); } public void updateLineProfile() { if (WindowManager.getCurrentWindow() == null || profileWin_ == null || !profileWin_.isShowing()) { return; } calculateLineProfileData(WindowManager.getCurrentImage()); profileWin_.setData(lineProfileData_); } private void openLineProfileWindow() { if (WindowManager.getCurrentWindow() == null || WindowManager.getCurrentWindow().isClosed()) { return; } calculateLineProfileData(WindowManager.getCurrentImage()); if (lineProfileData_ == null) { return; } profileWin_ = new GraphFrame(); profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); profileWin_.setData(lineProfileData_); profileWin_.setAutoScale(); profileWin_.setTitle("Live line profile"); profileWin_.setBackground(guiColors_.background.get((options_.displayBackground_))); addMMBackgroundListener(profileWin_); profileWin_.setVisible(true); } @Override public Rectangle getROI() throws MMScriptException { // ROI values are given as x,y,w,h in individual one-member arrays (pointers in C++): int[][] a = new int[4][1]; try { core_.getROI(a[0], a[1], a[2], a[3]); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } // Return as a single array with x,y,w,h: return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]); } private void calculateLineProfileData(ImagePlus imp) { // generate line profile Roi roi = imp.getRoi(); if (roi == null || !roi.isLine()) { // if there is no line ROI, create one Rectangle r = imp.getProcessor().getRoi(); int iWidth = r.width; int iHeight = r.height; int iXROI = r.x; int iYROI = r.y; if (roi == null) { iXROI += iWidth / 2; iYROI += iHeight / 2; } roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI + iWidth / 4, iYROI + iHeight / 4); imp.setRoi(roi); roi = imp.getRoi(); } ImageProcessor ip = imp.getProcessor(); ip.setInterpolate(true); Line line = (Line) roi; if (lineProfileData_ == null) { lineProfileData_ = new GraphData(); } lineProfileData_.setData(line.getPixels()); } @Override public void setROI(Rectangle r) throws MMScriptException { boolean liveRunning = false; if (isLiveModeOn()) { liveRunning = true; enableLiveMode(false); } try { core_.setROI(r.x, r.y, r.width, r.height); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } updateStaticInfo(); if (liveRunning) { enableLiveMode(true); } } private void setROI() { ImagePlus curImage = WindowManager.getCurrentImage(); if (curImage == null) { return; } Roi roi = curImage.getRoi(); try { if (roi == null) { // if there is no ROI, create one Rectangle r = curImage.getProcessor().getRoi(); int iWidth = r.width; int iHeight = r.height; int iXROI = r.x; int iYROI = r.y; if (roi == null) { iWidth /= 2; iHeight /= 2; iXROI += iWidth / 2; iYROI += iHeight / 2; } curImage.setRoi(iXROI, iYROI, iWidth, iHeight); roi = curImage.getRoi(); } if (roi.getType() != Roi.RECTANGLE) { handleError("ROI must be a rectangle.\nUse the ImageJ rectangle tool to draw the ROI."); return; } Rectangle r = roi.getBounds(); // if we already had an ROI defined, correct for the offsets Rectangle cameraR = getROI(); r.x += cameraR.x; r.y += cameraR.y; // Stop (and restart) live mode if it is running setROI(r); } catch (Exception e) { ReportingUtils.showError(e); } } private void clearROI() { try { boolean liveRunning = false; if (isLiveModeOn()) { liveRunning = true; enableLiveMode(false); } core_.clearROI(); updateStaticInfo(); if (liveRunning) { enableLiveMode(true); } } catch (Exception e) { ReportingUtils.showError(e); } } /** * Returns instance of the core uManager object; */ @Override public CMMCore getMMCore() { return core_; } /** * Returns singleton instance of MMStudioMainFrame */ public static MMStudioMainFrame getInstance() { return gui_; } public MetadataPanel getMetadataPanel() { return metadataPanel_; } public final void setExitStrategy(boolean closeOnExit) { if (closeOnExit) { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } else { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } } @Override public void saveConfigPresets() { MicroscopeModel model = new MicroscopeModel(); try { model.loadFromFile(sysConfigFile_); model.createSetupConfigsFromHardware(core_); model.createResolutionsFromHardware(core_); File f = FileDialogs.save(this, "Save the configuration file", MM_CONFIG_FILE); if (f != null) { model.saveToFile(f.getAbsolutePath()); sysConfigFile_ = f.getAbsolutePath(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); configChanged_ = false; setConfigSaveButtonStatus(configChanged_); updateTitle(); } } catch (MMConfigFileException e) { ReportingUtils.showError(e); } } protected void setConfigSaveButtonStatus(boolean changed) { saveConfigButton_.setEnabled(changed); } public String getAcqDirectory() { return openAcqDirectory_; } /** * Get currently used configuration file * @return - Path to currently used configuration file */ public String getSysConfigFile() { return sysConfigFile_; } public void setAcqDirectory(String dir) { openAcqDirectory_ = dir; } /** * Open an existing acquisition directory and build viewer window. * */ public void openAcquisitionData(boolean inRAM) { // choose the directory File f = FileDialogs.openDir(this, "Please select an image data set", MM_DATA_SET); if (f != null) { if (f.isDirectory()) { openAcqDirectory_ = f.getAbsolutePath(); } else { openAcqDirectory_ = f.getParent(); } String acq = null; try { acq = openAcquisitionData(openAcqDirectory_, inRAM); } catch (MMScriptException ex) { ReportingUtils.showError(ex); } finally { try { acqMgr_.closeAcquisition(acq); } catch (MMScriptException ex) { ReportingUtils.logError(ex); } } } } @Override public String openAcquisitionData(String dir, boolean inRAM, boolean show) throws MMScriptException { String rootDir = new File(dir).getAbsolutePath(); String name = new File(dir).getName(); rootDir = rootDir.substring(0, rootDir.length() - (name.length() + 1)); acqMgr_.openAcquisition(name, rootDir, show, !inRAM, true); try { getAcquisition(name).initialize(); } catch (MMScriptException mex) { acqMgr_.closeAcquisition(name); throw (mex); } return name; } /** * Opens an existing data set. Shows the acquisition in a window. * @return The acquisition object. */ @Override public String openAcquisitionData(String dir, boolean inRam) throws MMScriptException { return openAcquisitionData(dir, inRam, true); } protected void zoomOut() { ImageWindow curWin = WindowManager.getCurrentWindow(); if (curWin != null) { ImageCanvas canvas = curWin.getCanvas(); Rectangle r = canvas.getBounds(); canvas.zoomOut(r.width / 2, r.height / 2); VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus()); if (vad != null) { vad.storeWindowSizeAfterZoom(curWin); vad.updateWindowTitleAndStatus(); } } } protected void zoomIn() { ImageWindow curWin = WindowManager.getCurrentWindow(); if (curWin != null) { ImageCanvas canvas = curWin.getCanvas(); Rectangle r = canvas.getBounds(); canvas.zoomIn(r.width / 2, r.height / 2); VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus()); if (vad != null) { vad.storeWindowSizeAfterZoom(curWin); vad.updateWindowTitleAndStatus(); } } } protected void changeBinning() { try { boolean liveRunning = false; if (isLiveModeOn() ) { liveRunning = true; enableLiveMode(false); } if (isCameraAvailable()) { Object item = comboBinning_.getSelectedItem(); if (item != null) { core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString()); } } updateStaticInfo(); if (liveRunning) { enableLiveMode(true); } } catch (Exception e) { ReportingUtils.showError(e); } } private void createPropertyEditor() { if (propertyBrowser_ != null) { propertyBrowser_.dispose(); } propertyBrowser_ = new PropertyEditor(); propertyBrowser_.setGui(this); propertyBrowser_.setVisible(true); propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); propertyBrowser_.setCore(core_); } private void createCalibrationListDlg() { if (calibrationListDlg_ != null) { calibrationListDlg_.dispose(); } calibrationListDlg_ = new CalibrationListDlg(core_); calibrationListDlg_.setVisible(true); calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); calibrationListDlg_.setParentGUI(this); } public CalibrationListDlg getCalibrationListDlg() { if (calibrationListDlg_ == null) { createCalibrationListDlg(); } return calibrationListDlg_; } private void createScriptPanel() { if (scriptPanel_ == null) { scriptPanel_ = new ScriptPanel(core_, options_, this); scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_); scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_); scriptPanel_.setParentGUI(this); scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground_))); addMMBackgroundListener(scriptPanel_); } } /** * Updates Status line in main window from cached values */ private void updateStaticInfoFromCache() { String dimText = "Image info (from camera): " + staticInfo_.width_ + " X " + staticInfo_.height_ + " X " + staticInfo_.bytesPerPixel_ + ", Intensity range: " + staticInfo_.imageBitDepth_ + " bits"; dimText += ", " + TextUtils.FMT0.format(staticInfo_.pixSizeUm_ * 1000) + "nm/pix"; if (zStageLabel_.length() > 0) { dimText += ", Z=" + TextUtils.FMT2.format(staticInfo_.zPos_) + "um"; } if (xyStageLabel_.length() > 0) { dimText += ", XY=(" + TextUtils.FMT2.format(staticInfo_.x_) + "," + TextUtils.FMT2.format(staticInfo_.y_) + ")um"; } labelImageDimensions_.setText(dimText); } public void updateXYPos(double x, double y) { staticInfo_.x_ = x; staticInfo_.y_ = y; updateStaticInfoFromCache(); } public void updateZPos(double z) { staticInfo_.zPos_ = z; updateStaticInfoFromCache(); } public void updateXYPosRelative(double x, double y) { staticInfo_.x_ += x; staticInfo_.y_ += y; updateStaticInfoFromCache(); } public void updateZPosRelative(double z) { staticInfo_.zPos_ += z; updateStaticInfoFromCache(); } public void updateXYStagePosition(){ double x[] = new double[1]; double y[] = new double[1]; try { if (xyStageLabel_.length() > 0) core_.getXYPosition(xyStageLabel_, x, y); } catch (Exception e) { ReportingUtils.showError(e); } staticInfo_.x_ = x[0]; staticInfo_.y_ = y[0]; updateStaticInfoFromCache(); } private void updatePixSizeUm (double pixSizeUm) { staticInfo_.pixSizeUm_ = pixSizeUm; updateStaticInfoFromCache(); } private void updateStaticInfo() { double zPos = 0.0; double x[] = new double[1]; double y[] = new double[1]; try { if (zStageLabel_.length() > 0) { zPos = core_.getPosition(zStageLabel_); } if (xyStageLabel_.length() > 0) { core_.getXYPosition(xyStageLabel_, x, y); } } catch (Exception e) { handleException(e); } staticInfo_.width_ = core_.getImageWidth(); staticInfo_.height_ = core_.getImageHeight(); staticInfo_.bytesPerPixel_ = core_.getBytesPerPixel(); staticInfo_.imageBitDepth_ = core_.getImageBitDepth(); staticInfo_.pixSizeUm_ = core_.getPixelSizeUm(); staticInfo_.zPos_ = zPos; staticInfo_.x_ = x[0]; staticInfo_.y_ = y[0]; updateStaticInfoFromCache(); } public void toggleShutter() { try { if (!toggleButtonShutter_.isEnabled()) return; toggleButtonShutter_.requestFocusInWindow(); if (toggleButtonShutter_.getText().equals("Open")) { setShutterButton(true); core_.setShutterOpen(true); } else { core_.setShutterOpen(false); setShutterButton(false); } } catch (Exception e1) { ReportingUtils.showError(e1); } } private void updateCenterAndDragListener() { if (centerAndDragMenuItem_.isSelected()) { centerAndDragListener_.start(); } else { centerAndDragListener_.stop(); } } private void setShutterButton(boolean state) { if (state) { toggleButtonShutter_.setText("Close"); } else { toggleButtonShutter_.setText("Open"); } } // public interface available for scripting access @Override public void snapSingleImage() { doSnap(); } public Object getPixels() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip != null) { return ip.getProcessor().getPixels(); } return null; } public void setPixels(Object obj) { ImagePlus ip = WindowManager.getCurrentImage(); if (ip == null) { return; } ip.getProcessor().setPixels(obj); } public int getImageHeight() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip != null) return ip.getHeight(); return 0; } public int getImageWidth() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip != null) return ip.getWidth(); return 0; } public int getImageDepth() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip != null) return ip.getBitDepth(); return 0; } public ImageProcessor getImageProcessor() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip == null) return null; return ip.getProcessor(); } private boolean isCameraAvailable() { return cameraLabel_.length() > 0; } /** * Part of ScriptInterface API * Opens the XYPositionList when it is not opened * Adds the current position to the list (same as pressing the "Mark" button) */ @Override public void markCurrentPosition() { if (posListDlg_ == null) { showXYPositionList(); } if (posListDlg_ != null) { posListDlg_.markPosition(); } } /** * Implements ScriptInterface */ @Override public AcqControlDlg getAcqDlg() { return acqControlWin_; } /** * Implements ScriptInterface */ @Override public PositionListDlg getXYPosListDlg() { if (posListDlg_ == null) posListDlg_ = new PositionListDlg(core_, this, posList_, options_); return posListDlg_; } /** * Implements ScriptInterface */ @Override public boolean isAcquisitionRunning() { if (engine_ == null) return false; return engine_.isAcquisitionRunning(); } /** * Implements ScriptInterface */ @Override public boolean versionLessThan(String version) throws MMScriptException { try { String[] v = MMVersion.VERSION_STRING.split(" ", 2); String[] m = v[0].split("\\.", 3); String[] v2 = version.split(" ", 2); String[] m2 = v2[0].split("\\.", 3); for (int i=0; i < 3; i++) { if (Integer.parseInt(m[i]) < Integer.parseInt(m2[i])) { ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater"); return true; } if (Integer.parseInt(m[i]) > Integer.parseInt(m2[i])) { return false; } } if (v2.length < 2 || v2[1].equals("") ) return false; if (v.length < 2 ) { ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater"); return true; } if (Integer.parseInt(v[1]) < Integer.parseInt(v2[1])) { ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater"); return false; } return true; } catch (Exception ex) { throw new MMScriptException ("Format of version String should be \"a.b.c\""); } } @Override public boolean isLiveModeOn() { return liveModeTimer_ != null && liveModeTimer_.isRunning(); } public LiveModeTimer getLiveModeTimer() { if (liveModeTimer_ == null) { liveModeTimer_ = new LiveModeTimer(); } return liveModeTimer_; } @Override public void enableLiveMode(boolean enable) { if (core_ == null) { return; } if (enable == isLiveModeOn()) { return; } if (enable) { try { if (core_.getCameraDevice().length() == 0) { ReportingUtils.showError("No camera configured"); updateButtonsForLiveMode(false); return; } if (liveModeTimer_ == null) { liveModeTimer_ = new LiveModeTimer(); } liveModeTimer_.begin(); callLiveModeListeners(enable); } catch (Exception e) { ReportingUtils.showError(e); liveModeTimer_.stop(); callLiveModeListeners(false); updateButtonsForLiveMode(false); return; } } else { liveModeTimer_.stop(); callLiveModeListeners(enable); } updateButtonsForLiveMode(enable); } public void updateButtonsForLiveMode(boolean enable) { autoShutterCheckBox_.setEnabled(!enable); if (core_.getAutoShutter()) { toggleButtonShutter_.setText(enable ? "Close" : "Open" ); } snapButton_.setEnabled(!enable); //toAlbumButton_.setEnabled(!enable); liveButton_.setIcon(enable ? SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/cancel.png") : SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/camera_go.png")); liveButton_.setSelected(false); liveButton_.setText(enable ? "Stop Live" : "Live"); } public boolean getLiveMode() { return isLiveModeOn(); } public boolean updateImage() { try { if (isLiveModeOn()) { enableLiveMode(false); return true; // nothing to do, just show the last image } if (WindowManager.getCurrentWindow() == null) { return false; } ImagePlus ip = WindowManager.getCurrentImage(); core_.snapImage(); Object img = core_.getImage(); ip.getProcessor().setPixels(img); ip.updateAndRepaintWindow(); if (!isCurrentImageFormatSupported()) { return false; } updateLineProfile(); } catch (Exception e) { ReportingUtils.showError(e); return false; } return true; } public boolean displayImage(final Object pixels) { if (pixels instanceof TaggedImage) { return displayTaggedImage((TaggedImage) pixels, true); } else { return displayImage(pixels, true); } } public boolean displayImage(final Object pixels, boolean wait) { checkSimpleAcquisition(); try { int width = getAcquisition(SIMPLE_ACQ).getWidth(); int height = getAcquisition(SIMPLE_ACQ).getHeight(); int byteDepth = getAcquisition(SIMPLE_ACQ).getByteDepth(); TaggedImage ti = ImageUtils.makeTaggedImage(pixels, 0, 0, 0,0, width, height, byteDepth); simpleDisplay_.getImageCache().putImage(ti); simpleDisplay_.showImage(ti, wait); return true; } catch (Exception ex) { ReportingUtils.showError(ex); return false; } } public boolean displayImageWithStatusLine(Object pixels, String statusLine) { boolean ret = displayImage(pixels); simpleDisplay_.displayStatusLine(statusLine); return ret; } public void displayStatusLine(String statusLine) { ImagePlus ip = WindowManager.getCurrentImage(); if (!(ip.getWindow() instanceof VirtualAcquisitionDisplay.DisplayWindow)) { return; } VirtualAcquisitionDisplay.getDisplay(ip).displayStatusLine(statusLine); } private boolean isCurrentImageFormatSupported() { boolean ret = false; long channels = core_.getNumberOfComponents(); long bpp = core_.getBytesPerPixel(); if (channels > 1 && channels != 4 && bpp != 1) { handleError("Unsupported image format."); } else { ret = true; } return ret; } public void doSnap() { doSnap(false); } public void doSnap(final boolean album) { if (core_.getCameraDevice().length() == 0) { ReportingUtils.showError("No camera configured"); return; } BlockingQueue<TaggedImage> snapImageQueue = new LinkedBlockingQueue<TaggedImage>(); try { core_.snapImage(); long c = core_.getNumberOfCameraChannels(); runDisplayThread(snapImageQueue, new DisplayImageRoutine() { @Override public void show(final TaggedImage image) { if (album) { try { addToAlbum(image); } catch (MMScriptException ex) { ReportingUtils.showError(ex); } } else { displayImage(image); } } }); for (int i = 0; i < c; ++i) { TaggedImage img = core_.getTaggedImage(i); img.tags.put("Channels", c); snapImageQueue.put(img); } snapImageQueue.put(TaggedImageQueue.POISON); if (simpleDisplay_ != null) { ImagePlus imgp = simpleDisplay_.getImagePlus(); if (imgp != null) { ImageWindow win = imgp.getWindow(); if (win != null) { win.toFront(); } } } } catch (Exception ex) { ReportingUtils.showError(ex); } } /** * Is this function still needed? It does some magic with tags. I found * it to do harmful thing with tags when a Multi-Camera device is * present (that issue is now fixed). */ public void normalizeTags(TaggedImage ti) { if (ti != TaggedImageQueue.POISON) { int channel = 0; try { if (ti.tags.has("ChannelIndex")) { channel = MDUtils.getChannelIndex(ti.tags); } MDUtils.setChannelIndex(ti.tags, channel); MDUtils.setPositionIndex(ti.tags, 0); MDUtils.setSliceIndex(ti.tags, 0); MDUtils.setFrameIndex(ti.tags, 0); } catch (JSONException ex) { ReportingUtils.logError(ex); } } } @Override public boolean displayImage(TaggedImage ti) { normalizeTags(ti); return displayTaggedImage(ti, true); } private boolean displayTaggedImage(TaggedImage ti, boolean update) { try { checkSimpleAcquisition(ti); setCursor(new Cursor(Cursor.WAIT_CURSOR)); ti.tags.put("Summary", getAcquisition(SIMPLE_ACQ).getSummaryMetadata()); addStagePositionToTags(ti); addImage(SIMPLE_ACQ, ti, update, true); } catch (Exception ex) { ReportingUtils.logError(ex); return false; } if (update) { setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); updateLineProfile(); } return true; } public void addStagePositionToTags(TaggedImage ti) throws JSONException { if (gui_.xyStageLabel_.length() > 0) { ti.tags.put("XPositionUm", gui_.staticInfo_.x_); ti.tags.put("YPositionUm", gui_.staticInfo_.y_); } if (gui_.zStageLabel_.length() > 0) { ti.tags.put("ZPositionUm", gui_.staticInfo_.zPos_); } } private void configureBinningCombo() throws Exception { if (cameraLabel_.length() > 0) { ActionListener[] listeners; // binning combo if (comboBinning_.getItemCount() > 0) { comboBinning_.removeAllItems(); } StrVector binSizes = core_.getAllowedPropertyValues( cameraLabel_, MMCoreJ.getG_Keyword_Binning()); listeners = comboBinning_.getActionListeners(); for (int i = 0; i < listeners.length; i++) { comboBinning_.removeActionListener(listeners[i]); } for (int i = 0; i < binSizes.size(); i++) { comboBinning_.addItem(binSizes.get(i)); } comboBinning_.setMaximumRowCount((int) binSizes.size()); if (binSizes.isEmpty()) { comboBinning_.setEditable(true); } else { comboBinning_.setEditable(false); } for (int i = 0; i < listeners.length; i++) { comboBinning_.addActionListener(listeners[i]); } } } public void initializeGUI() { try { // establish device roles cameraLabel_ = core_.getCameraDevice(); shutterLabel_ = core_.getShutterDevice(); zStageLabel_ = core_.getFocusDevice(); xyStageLabel_ = core_.getXYStageDevice(); engine_.setZStageDevice(zStageLabel_); configureBinningCombo(); // active shutter combo try { shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice); } catch (Exception e) { ReportingUtils.logError(e); } if (shutters_ != null) { String items[] = new String[(int) shutters_.size()]; for (int i = 0; i < shutters_.size(); i++) { items[i] = shutters_.get(i); } GUIUtils.replaceComboContents(shutterComboBox_, items); String activeShutter = core_.getShutterDevice(); if (activeShutter != null) { shutterComboBox_.setSelectedItem(activeShutter); } else { shutterComboBox_.setSelectedItem(""); } } // Autofocus autofocusConfigureButton_.setEnabled(afMgr_.getDevice() != null); autofocusNowButton_.setEnabled(afMgr_.getDevice() != null); // Rebuild stage list in XY PositinList if (posListDlg_ != null) { posListDlg_.rebuildAxisList(); } updateGUI(true); } catch (Exception e) { ReportingUtils.showError(e); } } @Override public String getVersion() { return MMVersion.VERSION_STRING; } private void addPluginToMenu(final PluginItem plugin, Class<?> cl) { // add plugin menu items String toolTipDescription = ""; try { // Get this static field from the class implementing MMPlugin. toolTipDescription = (String) cl.getDeclaredField("tooltipDescription").get(null); } catch (SecurityException e) { ReportingUtils.logError(e); toolTipDescription = "Description not available"; } catch (NoSuchFieldException e) { toolTipDescription = "Description not available"; ReportingUtils.logMessage(cl.getName() + " fails to implement static String tooltipDescription."); } catch (IllegalArgumentException e) { ReportingUtils.logError(e); } catch (IllegalAccessException e) { ReportingUtils.logError(e); } GUIUtils.addMenuItem(pluginMenu_, plugin.menuItem, toolTipDescription, new Runnable() { public void run() { ReportingUtils.logMessage("Plugin command: " + plugin.menuItem); plugin.instantiate(); plugin.plugin.show(); } }); pluginMenu_.validate(); menuBar_.validate(); } public void updateGUI(boolean updateConfigPadStructure) { updateGUI(updateConfigPadStructure, false); } public void updateGUI(boolean updateConfigPadStructure, boolean fromCache) { try { // establish device roles cameraLabel_ = core_.getCameraDevice(); shutterLabel_ = core_.getShutterDevice(); zStageLabel_ = core_.getFocusDevice(); xyStageLabel_ = core_.getXYStageDevice(); afMgr_.refresh(); // camera settings if (isCameraAvailable()) { double exp = core_.getExposure(); textFieldExp_.setText(NumberUtils.doubleToDisplayString(exp)); configureBinningCombo(); String binSize; if (fromCache) { binSize = core_.getPropertyFromCache(cameraLabel_, MMCoreJ.getG_Keyword_Binning()); } else { binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning()); } GUIUtils.setComboSelection(comboBinning_, binSize); } if (liveModeTimer_ == null || !liveModeTimer_.isRunning()) { autoShutterCheckBox_.setSelected(core_.getAutoShutter()); boolean shutterOpen = core_.getShutterOpen(); setShutterButton(shutterOpen); if (autoShutterCheckBox_.isSelected()) { toggleButtonShutter_.setEnabled(false); } else { toggleButtonShutter_.setEnabled(true); } } // active shutter combo if (shutters_ != null) { String activeShutter = core_.getShutterDevice(); if (activeShutter != null) { shutterComboBox_.setSelectedItem(activeShutter); } else { shutterComboBox_.setSelectedItem(""); } } // state devices if (updateConfigPadStructure && (configPad_ != null)) { configPad_.refreshStructure(fromCache); // Needed to update read-only properties. May slow things down... if (!fromCache) core_.updateSystemStateCache(); } // update Channel menus in Multi-dimensional acquisition dialog updateChannelCombos(); // update list of pixel sizes in pixel size configuration window if (calibrationListDlg_ != null) { calibrationListDlg_.refreshCalibrations(); } if (propertyBrowser_ != null) { propertyBrowser_.refresh(); } } catch (Exception e) { ReportingUtils.logError(e); } updateStaticInfo(); updateTitle(); } //TODO: Deprecated @Override public boolean okToAcquire() { return !isLiveModeOn(); } //TODO: Deprecated @Override public void stopAllActivity() { if (this.acquisitionEngine2010 != null) { this.acquisitionEngine2010.stop(); } enableLiveMode(false); } /** * Cleans up resources while shutting down * * @param calledByImageJ * @return flag indicating success. Shut down should abort when flag is false */ private boolean cleanupOnClose(boolean calledByImageJ) { // Save config presets if they were changed. if (configChanged_) { Object[] options = {"Yes", "No"}; int n = JOptionPane.showOptionDialog(null, "Save Changed Configuration?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == JOptionPane.YES_OPTION) { saveConfigPresets(); // if the configChanged_ flag did not become false, the user // must have cancelled the configuration saving and we should cancel // quitting as well if (configChanged_) { return false; } } } if (liveModeTimer_ != null) liveModeTimer_.stop(); // check needed to avoid deadlock if (!calledByImageJ) { if (!WindowManager.closeAllWindows()) { core_.logMessage("Failed to close some windows"); } } if (profileWin_ != null) { removeMMBackgroundListener(profileWin_); profileWin_.dispose(); } if (scriptPanel_ != null) { removeMMBackgroundListener(scriptPanel_); scriptPanel_.closePanel(); } if (propertyBrowser_ != null) { removeMMBackgroundListener(propertyBrowser_); propertyBrowser_.dispose(); } if (acqControlWin_ != null) { removeMMBackgroundListener(acqControlWin_); acqControlWin_.close(); } if (engine_ != null) { engine_.shutdown(); } if (afMgr_ != null) { afMgr_.closeOptionsDialog(); } // dispose plugins for (int i = 0; i < plugins_.size(); i++) { MMPlugin plugin = plugins_.get(i).plugin; if (plugin != null) { plugin.dispose(); } } synchronized (shutdownLock_) { try { if (core_ != null) { ReportingUtils.setCore(null); core_.delete(); core_ = null; } } catch (Exception err) { ReportingUtils.showError(err); } } return true; } private void saveSettings() { Rectangle r = this.getBounds(); mainPrefs_.putInt(MAIN_FRAME_X, r.x); mainPrefs_.putInt(MAIN_FRAME_Y, r.y); mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width); mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height); mainPrefs_.putInt(MAIN_FRAME_DIVIDER_POS, this.splitPane_.getDividerLocation()); mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_); mainPrefs_.put(MAIN_SAVE_METHOD, ImageUtils.getImageStorageClass().getName()); // save field values from the main window // NOTE: automatically restoring these values on startup may cause // problems mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText()); // NOTE: do not save auto shutter state if (afMgr_ != null && afMgr_.getDevice() != null) { mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName()); } } private void loadConfiguration() { File f = FileDialogs.openFile(this, "Load a config file",MM_CONFIG_FILE); if (f != null) { sysConfigFile_ = f.getAbsolutePath(); configChanged_ = false; setConfigSaveButtonStatus(configChanged_); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); loadSystemConfiguration(); } } public synchronized boolean closeSequence(boolean calledByImageJ) { if (!this.isRunning()) { if (core_ != null) { core_.logMessage("MMStudioMainFrame::closeSequence called while running_ is false"); } return true; } if (engine_ != null && engine_.isAcquisitionRunning()) { int result = JOptionPane.showConfirmDialog( this, "Acquisition in progress. Are you sure you want to exit and discard all data?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); if (result == JOptionPane.NO_OPTION) { return false; } } stopAllActivity(); try { // Close all image windows associated with MM. Canceling saving of // any of these should abort shutdown if (!acqMgr_.closeAllImageWindows()) { return false; } } catch (MMScriptException ex) { // Not sure what to do here... } if (!cleanupOnClose(calledByImageJ)) { return false; } running_ = false; saveSettings(); try { configPad_.saveSettings(); options_.saveSettings(); hotKeys_.saveSettings(); } catch (NullPointerException e) { if (core_ != null) this.logError(e); } // disposing sometimes hangs ImageJ! // this.dispose(); if (options_.closeOnExit_) { if (!runsAsPlugin_) { System.exit(0); } else { ImageJ ij = IJ.getInstance(); if (ij != null) { ij.quit(); } } } else { this.dispose(); } return true; } public void applyContrastSettings(ContrastSettings contrast8, ContrastSettings contrast16) { ImagePlus img = WindowManager.getCurrentImage(); if (img == null|| VirtualAcquisitionDisplay.getDisplay(img) == null ) return; if (img.getBytesPerPixel() == 1) VirtualAcquisitionDisplay.getDisplay(img).setChannelContrast(0, contrast8.min, contrast8.max, contrast8.gamma); else VirtualAcquisitionDisplay.getDisplay(img).setChannelContrast(0, contrast16.min, contrast16.max, contrast16.gamma); } //TODO: Deprecated @Override public ContrastSettings getContrastSettings() { ImagePlus img = WindowManager.getCurrentImage(); if (img == null || VirtualAcquisitionDisplay.getDisplay(img) == null ) return null; return VirtualAcquisitionDisplay.getDisplay(img).getChannelContrastSettings(0); } public boolean is16bit() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip != null && ip.getProcessor() instanceof ShortProcessor) { return true; } return false; } public boolean isRunning() { return running_; } /** * Executes the beanShell script. This script instance only supports * commands directed to the core object. */ private void executeStartupScript() { // execute startup script File f = new File(startupScriptFile_); if (startupScriptFile_.length() > 0 && f.exists()) { WaitDialog waitDlg = new WaitDialog( "Executing startup script, please wait..."); waitDlg.showDialog(); Interpreter interp = new Interpreter(); try { // insert core object only interp.set(SCRIPT_CORE_OBJECT, core_); interp.set(SCRIPT_ACQENG_OBJECT, engine_); interp.set(SCRIPT_GUI_OBJECT, this); // read text file and evaluate interp.eval(TextUtils.readTextFile(startupScriptFile_)); } catch (IOException exc) { ReportingUtils.logError(exc, "Unable to read the startup script (" + startupScriptFile_ + ")."); } catch (EvalError exc) { ReportingUtils.logError(exc); } finally { waitDlg.closeDialog(); } } else { if (startupScriptFile_.length() > 0) ReportingUtils.logMessage("Startup script file ("+startupScriptFile_+") not present."); } } /** * Loads system configuration from the cfg file. */ private boolean loadSystemConfiguration() { boolean result = true; saveMRUConfigFiles(); final WaitDialog waitDlg = new WaitDialog( "Loading system configuration, please wait..."); waitDlg.setAlwaysOnTop(true); waitDlg.showDialog(); this.setEnabled(false); try { if (sysConfigFile_.length() > 0) { GUIUtils.preventDisplayAdapterChangeExceptions(); core_.waitForSystem(); ignorePropertyChanges_ = true; core_.loadSystemConfiguration(sysConfigFile_); ignorePropertyChanges_ = false; GUIUtils.preventDisplayAdapterChangeExceptions(); } } catch (final Exception err) { GUIUtils.preventDisplayAdapterChangeExceptions(); ReportingUtils.showError(err); result = false; } finally { waitDlg.closeDialog(); } setEnabled(true); initializeGUI(); updateSwitchConfigurationMenu(); FileDialogs.storePath(MM_CONFIG_FILE, new File(sysConfigFile_)); return result; } private void saveMRUConfigFiles() { if (0 < sysConfigFile_.length()) { if (MRUConfigFiles_.contains(sysConfigFile_)) { MRUConfigFiles_.remove(sysConfigFile_); } if (maxMRUCfgs_ <= MRUConfigFiles_.size()) { MRUConfigFiles_.remove(maxMRUCfgs_ - 1); } MRUConfigFiles_.add(0, sysConfigFile_); // save the MRU list to the preferences for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) { String value = ""; if (null != MRUConfigFiles_.get(icfg)) { value = MRUConfigFiles_.get(icfg).toString(); } mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value); } } } private void loadMRUConfigFiles() { sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_); // startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE, // startupScriptFile_); MRUConfigFiles_ = new ArrayList<String>(); for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) { String value = ""; value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value); if (0 < value.length()) { File ruFile = new File(value); if (ruFile.exists()) { if (!MRUConfigFiles_.contains(value)) { MRUConfigFiles_.add(value); } } } } // initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE if (0 < sysConfigFile_.length()) { if (!MRUConfigFiles_.contains(sysConfigFile_)) { // in case persistant data is inconsistent if (maxMRUCfgs_ <= MRUConfigFiles_.size()) { MRUConfigFiles_.remove(maxMRUCfgs_ - 1); } MRUConfigFiles_.add(0, sysConfigFile_); } } } /** * Opens Acquisition dialog. */ private void openAcqControlDialog() { try { if (acqControlWin_ == null) { acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this, options_); } if (acqControlWin_.isActive()) { acqControlWin_.setTopPosition(); } acqControlWin_.setVisible(true); acqControlWin_.repaint(); // TODO: this call causes a strange exception the first time the // dialog is created // something to do with the order in which combo box creation is // performed // acqControlWin_.updateGroupsCombo(); } catch (Exception exc) { ReportingUtils.showError(exc, "\nAcquistion window failed to open due to invalid or corrupted settings.\n" + "Try resetting registry settings to factory defaults (Menu Tools|Options)."); } } /** * Opens a dialog to record stage positions */ @Override public void showXYPositionList() { if (posListDlg_ == null) { posListDlg_ = new PositionListDlg(core_, this, posList_, options_); } posListDlg_.setVisible(true); } private void updateChannelCombos() { if (this.acqControlWin_ != null) { this.acqControlWin_.updateChannelAndGroupCombo(); } } @Override public void setConfigChanged(boolean status) { configChanged_ = status; setConfigSaveButtonStatus(configChanged_); } /** * Returns the current background color * @return current background color */ @Override public Color getBackgroundColor() { return guiColors_.background.get((options_.displayBackground_)); } /* * Changes background color of this window and all other MM windows */ @Override public void setBackgroundStyle(String backgroundType) { setBackground(guiColors_.background.get((backgroundType))); paint(MMStudioMainFrame.this.getGraphics()); // sets background of all registered Components for (Component comp:MMFrames_) { if (comp != null) comp.setBackground(guiColors_.background.get(backgroundType)); } } @Override public String getBackgroundStyle() { return options_.displayBackground_; } // Scripting interface private class ExecuteAcq implements Runnable { public ExecuteAcq() { } @Override public void run() { if (acqControlWin_ != null) { acqControlWin_.runAcquisition(); } } } private void testForAbortRequests() throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } } } /** * @Deprecated - used to be in api/AcquisitionEngine */ public void startAcquisition() throws MMScriptException { testForAbortRequests(); SwingUtilities.invokeLater(new ExecuteAcq()); } @Override public String runAcquisition() throws MMScriptException { if (SwingUtilities.isEventDispatchThread()) { throw new MMScriptException("Acquisition can not be run from this (EDT) thread"); } testForAbortRequests(); if (acqControlWin_ != null) { String name = acqControlWin_.runAcquisition(); try { while (acqControlWin_.isAcquisitionRunning()) { Thread.sleep(50); } } catch (InterruptedException e) { ReportingUtils.showError(e); } return name; } else { throw new MMScriptException( "Acquisition setup window must be open for this command to work."); } } @Override public String runAcquisition(String name, String root) throws MMScriptException { testForAbortRequests(); if (acqControlWin_ != null) { String acqName = acqControlWin_.runAcquisition(name, root); try { while (acqControlWin_.isAcquisitionRunning()) { Thread.sleep(100); } // ensure that the acquisition has finished. // This does not seem to work, needs something better MMAcquisition acq = acqMgr_.getAcquisition(acqName); boolean finished = false; while (!finished) { ImageCache imCache = acq.getImageCache(); if (imCache != null) { if (imCache.isFinished()) { finished = true; } else { Thread.sleep(100); } } } } catch (InterruptedException e) { ReportingUtils.showError(e); } return acqName; } else { throw new MMScriptException( "Acquisition setup window must be open for this command to work."); } } /** * @Deprecated used to be part of api */ public String runAcqusition(String name, String root) throws MMScriptException { return runAcquisition(name, root); } /** * Loads acquisition settings from file * @param path file containing previously saved acquisition settings * @throws MMScriptException */ @Override public void loadAcquisition(String path) throws MMScriptException { testForAbortRequests(); try { engine_.shutdown(); // load protocol if (acqControlWin_ != null) { acqControlWin_.loadAcqSettingsFromFile(path); } } catch (Exception ex) { throw new MMScriptException(ex.getMessage()); } } @Override public void setPositionList(PositionList pl) throws MMScriptException { testForAbortRequests(); // use serialization to clone the PositionList object posList_ = pl; // PositionList.newInstance(pl); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (posListDlg_ != null) posListDlg_.setPositionList(posList_); if (engine_ != null) engine_.setPositionList(posList_); if (acqControlWin_ != null) acqControlWin_.updateGUIContents(); } }); } @Override public PositionList getPositionList() throws MMScriptException { testForAbortRequests(); // use serialization to clone the PositionList object return posList_; //PositionList.newInstance(posList_); } @Override public void sleep(long ms) throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } scriptPanel_.sleep(ms); } } @Override public String getUniqueAcquisitionName(String stub) { return acqMgr_.getUniqueAcquisitionName(stub); } @Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, int nrPositions) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, true, false); } @Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices) throws MMScriptException { openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0); } @Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, int nrPositions, boolean show) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, show, false); } @Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, boolean show) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, false); } @Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, int nrPositions, boolean show, boolean virtual) throws MMScriptException { acqMgr_.openAcquisition(name, rootDir, show, virtual); MMAcquisition acq = acqMgr_.getAcquisition(name); acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions); } @Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, boolean show, boolean virtual) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, virtual); } @Override public String createAcquisition(JSONObject summaryMetadata, boolean diskCached) { return createAcquisition(summaryMetadata, diskCached, false); } @Override public String createAcquisition(JSONObject summaryMetadata, boolean diskCached, boolean displayOff) { return acqMgr_.createAcquisition(summaryMetadata, diskCached, engine_, displayOff); } @Override public String createDataSet(String root, String name, boolean diskCached, boolean displayOff) throws MMScriptException { JSONObject summary = new JSONObject(); try { summary.put(MMTags.Summary.PREFIX, name); summary.put(MMTags.Summary.DIRECTORY, root); } catch (JSONException e) { throw new MMScriptException(e.getMessage()); } return acqMgr_.createAcquisition(summary, diskCached, engine_, displayOff); } private void openAcquisitionSnap(String name, String rootDir, boolean show) throws MMScriptException { /* MMAcquisition acq = acqMgr_.openAcquisitionSnap(name, rootDir, this, show); acq.setDimensions(0, 1, 1, 1); try { // acq.getAcqData().setPixelSizeUm(core_.getPixelSizeUm()); acq.setProperty(SummaryKeys.IMAGE_PIXEL_SIZE_UM, String.valueOf(core_.getPixelSizeUm())); } catch (Exception e) { ReportingUtils.showError(e); } * */ } @Override public void initializeSimpleAcquisition(String name, int width, int height, int byteDepth, int bitDepth, int multiCamNumCh) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(name); acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth, multiCamNumCh); acq.initializeSimpleAcq(); } @Override public void initializeAcquisition(String name, int width, int height, int depth) throws MMScriptException { initializeAcquisition(name,width,height,depth,8*depth); } @Override public void initializeAcquisition(String name, int width, int height, int byteDepth, int bitDepth) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(name); //number of multi-cam cameras is set to 1 here for backwards compatibility //might want to change this later acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth,1); acq.initialize(); } @Override public int getAcquisitionImageWidth(String acqName) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(acqName); return acq.getWidth(); } @Override public int getAcquisitionImageHeight(String acqName) throws MMScriptException{ MMAcquisition acq = acqMgr_.getAcquisition(acqName); return acq.getHeight(); } @Override public int getAcquisitionImageBitDepth(String acqName) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(acqName); return acq.getBitDepth(); } @Override public int getAcquisitionImageByteDepth(String acqName) throws MMScriptException{ MMAcquisition acq = acqMgr_.getAcquisition(acqName); return acq.getByteDepth(); } @Override public int getAcquisitionMultiCamNumChannels(String acqName) throws MMScriptException{ MMAcquisition acq = acqMgr_.getAcquisition(acqName); return acq.getMultiCameraNumChannels(); } @Override public Boolean acquisitionExists(String name) { return acqMgr_.acquisitionExists(name); } @Override public void closeAcquisition(String name) throws MMScriptException { acqMgr_.closeAcquisition(name); } /** * @Deprecated use closeAcquisitionWindow instead * @Deprecated - used to be in api/AcquisitionEngine */ public void closeAcquisitionImage5D(String acquisitionName) throws MMScriptException { acqMgr_.closeImageWindow(acquisitionName); } @Override public void closeAcquisitionWindow(String acquisitionName) throws MMScriptException { acqMgr_.closeImageWindow(acquisitionName); } /** * @Deprecated - used to be in api/AcquisitionEngine * Since Burst and normal acquisition are now carried out by the same engine, * loadBurstAcquistion simply calls loadAcquisition * t * @param path - path to file specifying acquisition settings */ public void loadBurstAcquisition(String path) throws MMScriptException { this.loadAcquisition(path); } @Override public void refreshGUI() { updateGUI(true); } @Override public void refreshGUIFromCache() { updateGUI(true, true); } @Override public void setAcquisitionProperty(String acqName, String propertyName, String value) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(acqName); acq.setProperty(propertyName, value); } public void setAcquisitionSystemState(String acqName, JSONObject md) throws MMScriptException { // acqMgr_.getAcquisition(acqName).setSystemState(md); setAcquisitionSummary(acqName, md); } @Override public void setAcquisitionSummary(String acqName, JSONObject md) throws MMScriptException { acqMgr_.getAcquisition(acqName).setSummaryProperties(md); } @Override public void setImageProperty(String acqName, int frame, int channel, int slice, String propName, String value) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(acqName); acq.setProperty(frame, channel, slice, propName, value); } public void snapAndAddImage(String name, int frame, int channel, int slice) throws MMScriptException { snapAndAddImage(name, frame, channel, slice, 0); } public void snapAndAddImage(String name, int frame, int channel, int slice, int position) throws MMScriptException { TaggedImage ti; try { if (core_.isSequenceRunning()) { ti = core_.getLastTaggedImage(); } else { core_.snapImage(); ti = core_.getTaggedImage(); } MDUtils.setChannelIndex(ti.tags, channel); MDUtils.setFrameIndex(ti.tags, frame); MDUtils.setSliceIndex(ti.tags, slice); MDUtils.setPositionIndex(ti.tags, position); MMAcquisition acq = acqMgr_.getAcquisition(name); if (!acq.isInitialized()) { long width = core_.getImageWidth(); long height = core_.getImageHeight(); long depth = core_.getBytesPerPixel(); long bitDepth = core_.getImageBitDepth(); int multiCamNumCh = (int) core_.getNumberOfCameraChannels(); acq.setImagePhysicalDimensions((int) width, (int) height, (int) depth, (int) bitDepth, multiCamNumCh); acq.initialize(); } if (acq.getPositions() > 1) { MDUtils.setPositionName(ti.tags, "Pos" + position); } addImage(name, ti, true); } catch (Exception e) { ReportingUtils.showError(e); } } @Override public String getCurrentAlbum() { return acqMgr_.getCurrentAlbum(); } public String createNewAlbum() { return acqMgr_.createNewAlbum(); } public void appendImage(String name, TaggedImage taggedImg) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(name); int f = 1 + acq.getLastAcquiredFrame(); try { MDUtils.setFrameIndex(taggedImg.tags, f); } catch (JSONException e) { throw new MMScriptException("Unable to set the frame index."); } acq.insertTaggedImage(taggedImg, f, 0, 0); } @Override public void addToAlbum(TaggedImage taggedImg) throws MMScriptException { addToAlbum(taggedImg, null); } public void addToAlbum(TaggedImage taggedImg, JSONObject displaySettings) throws MMScriptException { normalizeTags(taggedImg); acqMgr_.addToAlbum(taggedImg,displaySettings); } public void addImage(String name, Object img, int frame, int channel, int slice) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(name); acq.insertImage(img, frame, channel, slice); } @Override public void addImage(String name, TaggedImage taggedImg) throws MMScriptException { acqMgr_.getAcquisition(name).insertImage(taggedImg); } @Override public void addImageToDataSet(String name, int frame, String channel, int slice, String position, TaggedImage taggedImg) throws MMScriptException { // TODO: complete the tag set and initialize the acquisition MMAcquisition a = acqMgr_.getAcquisition(name); //if (!a.isInitialized()) // initialize a.insertImage(taggedImg); } @Override public void addImage(String name, TaggedImage taggedImg, boolean updateDisplay) throws MMScriptException { acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay); } @Override public void addImage(String name, TaggedImage taggedImg, boolean updateDisplay, boolean waitForDisplay) throws MMScriptException { acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay, waitForDisplay); } @Override public void addImage(String name, TaggedImage taggedImg, int frame, int channel, int slice, int position) throws MMScriptException { try { acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position); } catch (JSONException ex) { ReportingUtils.showError(ex); } } @Override public void addImage(String name, TaggedImage taggedImg, int frame, int channel, int slice, int position, boolean updateDisplay) throws MMScriptException { try { acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position, updateDisplay); } catch (JSONException ex) { ReportingUtils.showError(ex); } } @Override public void addImage(String name, TaggedImage taggedImg, int frame, int channel, int slice, int position, boolean updateDisplay, boolean waitForDisplay) throws MMScriptException { try { acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position, updateDisplay, waitForDisplay); } catch (JSONException ex) { ReportingUtils.showError(ex); } } /** * Closes all acquisitions */ @Override public void closeAllAcquisitions() { acqMgr_.closeAll(); } @Override public String[] getAcquisitionNames() { return acqMgr_.getAcqusitionNames(); } @Override public MMAcquisition getAcquisition(String name) throws MMScriptException { return acqMgr_.getAcquisition(name); } private class ScriptConsoleMessage implements Runnable { String msg_; public ScriptConsoleMessage(String text) { msg_ = text; } @Override public void run() { if (scriptPanel_ != null) scriptPanel_.message(msg_); } } @Override public void message(String text) throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } SwingUtilities.invokeLater(new ScriptConsoleMessage(text)); } } @Override public void clearMessageWindow() throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } scriptPanel_.clearOutput(); } } public void clearOutput() throws MMScriptException { clearMessageWindow(); } public void clear() throws MMScriptException { clearMessageWindow(); } @Override public void setChannelContrast(String title, int channel, int min, int max) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setChannelContrast(channel, min, max); } @Override public void setChannelName(String title, int channel, String name) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setChannelName(channel, name); } @Override public void setChannelColor(String title, int channel, Color color) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setChannelColor(channel, color.getRGB()); } @Override public void setContrastBasedOnFrame(String title, int frame, int slice) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setContrastBasedOnFrame(frame, slice); } @Override public void setStagePosition(double z) throws MMScriptException { try { core_.setPosition(core_.getFocusDevice(),z); core_.waitForDevice(core_.getFocusDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } @Override public void setRelativeStagePosition(double z) throws MMScriptException { try { core_.setRelativePosition(core_.getFocusDevice(), z); core_.waitForDevice(core_.getFocusDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } @Override public void setXYStagePosition(double x, double y) throws MMScriptException { try { core_.setXYPosition(core_.getXYStageDevice(), x, y); core_.waitForDevice(core_.getXYStageDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } @Override public void setRelativeXYStagePosition(double x, double y) throws MMScriptException { try { core_.setRelativeXYPosition(core_.getXYStageDevice(), x, y); core_.waitForDevice(core_.getXYStageDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } @Override public Point2D.Double getXYStagePosition() throws MMScriptException { String stage = core_.getXYStageDevice(); if (stage.length() == 0) { throw new MMScriptException("XY Stage device is not available"); } double x[] = new double[1]; double y[] = new double[1]; try { core_.getXYPosition(stage, x, y); Point2D.Double pt = new Point2D.Double(x[0], y[0]); return pt; } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } @Override public String getXYStageName() { return core_.getXYStageDevice(); } @Override public void setXYOrigin(double x, double y) throws MMScriptException { String xyStage = core_.getXYStageDevice(); try { core_.setAdapterOriginXY(xyStage, x, y); } catch (Exception e) { throw new MMScriptException(e); } } public AcquisitionWrapperEngine getAcquisitionEngine() { return engine_; } public String installPlugin(Class<?> cl) { String className = cl.getSimpleName(); String msg = className + " module loaded."; try { for (PluginItem plugin : plugins_) { if (plugin.className.contentEquals(className)) { return className + " already loaded."; } } PluginItem pi = new PluginItem(); pi.className = className; try { // Get this static field from the class implementing MMPlugin. pi.menuItem = (String) cl.getDeclaredField("menuName").get(null); } catch (SecurityException e) { ReportingUtils.logError(e); pi.menuItem = className; } catch (NoSuchFieldException e) { pi.menuItem = className; ReportingUtils.logMessage(className + " fails to implement static String menuName."); } catch (IllegalArgumentException e) { ReportingUtils.logError(e); } catch (IllegalAccessException e) { ReportingUtils.logError(e); } if (pi.menuItem == null) { pi.menuItem = className; } pi.menuItem = pi.menuItem.replace("_", " "); pi.pluginClass = cl; plugins_.add(pi); final PluginItem pi2 = pi; final Class<?> cl2 = cl; SwingUtilities.invokeLater( new Runnable() { @Override public void run() { addPluginToMenu(pi2, cl2); } }); } catch (NoClassDefFoundError e) { msg = className + " class definition not found."; ReportingUtils.logError(e, msg); } return msg; } public String installPlugin(String className, String menuName) { String msg = "installPlugin(String className, String menuName) is Deprecated. Use installPlugin(String className) instead."; core_.logMessage(msg); installPlugin(className); return msg; } @Override public String installPlugin(String className) { try { Class clazz = Class.forName(className); return installPlugin(clazz); } catch (ClassNotFoundException e) { String msg = className + " plugin not found."; ReportingUtils.logError(e, msg); return msg; } } @Override public String installAutofocusPlugin(String className) { try { return installAutofocusPlugin(Class.forName(className)); } catch (ClassNotFoundException e) { String msg = "Internal error: AF manager not instantiated."; ReportingUtils.logError(e, msg); return msg; } } public String installAutofocusPlugin(Class<?> autofocus) { String msg = autofocus.getSimpleName() + " module loaded."; if (afMgr_ != null) { try { afMgr_.refresh(); } catch (MMException e) { msg = e.getMessage(); ReportingUtils.logError(e); } afMgr_.setAFPluginClassName(autofocus.getSimpleName()); } else { msg = "Internal error: AF manager not instantiated."; } return msg; } public CMMCore getCore() { return core_; } @Override public IAcquisitionEngine2010 getAcquisitionEngine2010() { try { acquisitionEngine2010LoadingThread.join(); if (acquisitionEngine2010 == null) { acquisitionEngine2010 = (IAcquisitionEngine2010) acquisitionEngine2010Class.getConstructor(ScriptInterface.class).newInstance(this); } return acquisitionEngine2010; } catch (Exception e) { ReportingUtils.logError(e); return null; } } @Override public void addImageProcessor(DataProcessor<TaggedImage> processor) { getAcquisitionEngine().addImageProcessor(processor); } @Override public void removeImageProcessor(DataProcessor<TaggedImage> processor) { getAcquisitionEngine().removeImageProcessor(processor); } @Override public void setPause(boolean state) { getAcquisitionEngine().setPause(state); } @Override public boolean isPaused() { return getAcquisitionEngine().isPaused(); } @Override public void attachRunnable(int frame, int position, int channel, int slice, Runnable runnable) { getAcquisitionEngine().attachRunnable(frame, position, channel, slice, runnable); } @Override public void clearRunnables() { getAcquisitionEngine().clearRunnables(); } @Override public SequenceSettings getAcqusitionSettings() { if (engine_ == null) return new SequenceSettings(); return engine_.getSequenceSettings(); } @Override public String getAcquisitionPath() { if (engine_ == null) return null; return engine_.getImageCache().getDiskLocation(); } @Override public void promptToSaveAcqusition(String name, boolean prompt) throws MMScriptException { MMAcquisition acq = getAcquisition(name); getAcquisition(name).promptToSave(prompt); } public void snapAndAddToImage5D() { if (core_.getCameraDevice().length() == 0) { ReportingUtils.showError("No camera configured"); return; } try { if (this.isLiveModeOn()) { copyFromLiveModeToAlbum(simpleDisplay_); } else { doSnap(true); } } catch (Exception ex) { ReportingUtils.logError(ex); } } public void setAcquisitionEngine(AcquisitionWrapperEngine eng) { engine_ = eng; } public void suspendLiveMode() { liveModeSuspended_ = isLiveModeOn(); enableLiveMode(false); } public void resumeLiveMode() { if (liveModeSuspended_) { enableLiveMode(true); } } @Override public Autofocus getAutofocus() { return afMgr_.getDevice(); } @Override public void showAutofocusDialog() { if (afMgr_.getDevice() != null) { afMgr_.showOptionsDialog(); } } @Override public AutofocusManager getAutofocusManager() { return afMgr_; } public void selectConfigGroup(String groupName) { configPad_.setGroup(groupName); } public String regenerateDeviceList() { Cursor oldc = Cursor.getDefaultCursor(); Cursor waitc = new Cursor(Cursor.WAIT_CURSOR); setCursor(waitc); StringBuffer resultFile = new StringBuffer(); MicroscopeModel.generateDeviceListFile(resultFile, core_); //MicroscopeModel.generateDeviceListFile(); setCursor(oldc); return resultFile.toString(); } @Override public void setImageSavingFormat(Class imageSavingClass) throws MMScriptException { if (! (imageSavingClass.equals(TaggedImageStorageDiskDefault.class) || imageSavingClass.equals(TaggedImageStorageMultipageTiff.class))) { throw new MMScriptException("Unrecognized saving class"); } ImageUtils.setImageStorageClass(imageSavingClass); if (acqControlWin_ != null) { acqControlWin_.updateSavingTypeButtons(); } } private void loadPlugins() { ArrayList<Class<?>> pluginClasses = new ArrayList<Class<?>>(); ArrayList<Class<?>> autofocusClasses = new ArrayList<Class<?>>(); List<Class<?>> classes; try { long t1 = System.currentTimeMillis(); classes = JavaUtils.findClasses(new File("mmplugins"), 2); //System.out.println("findClasses: " + (System.currentTimeMillis() - t1)); //System.out.println(classes.size()); for (Class<?> clazz : classes) { for (Class<?> iface : clazz.getInterfaces()) { //core_.logMessage("interface found: " + iface.getName()); if (iface == MMPlugin.class) { pluginClasses.add(clazz); } } } classes = JavaUtils.findClasses(new File("mmautofocus"), 2); for (Class<?> clazz : classes) { for (Class<?> iface : clazz.getInterfaces()) { //core_.logMessage("interface found: " + iface.getName()); if (iface == Autofocus.class) { autofocusClasses.add(clazz); } } } } catch (ClassNotFoundException e1) { ReportingUtils.logError(e1); } for (Class<?> plugin : pluginClasses) { try { ReportingUtils.logMessage("Attempting to install plugin " + plugin.getName()); installPlugin(plugin); } catch (Exception e) { ReportingUtils.logError(e, "Failed to install the \"" + plugin.getName() + "\" plugin ."); } } for (Class<?> autofocus : autofocusClasses) { try { ReportingUtils.logMessage("Attempting to install autofocus plugin " + autofocus.getName()); installAutofocusPlugin(autofocus.getName()); } catch (Exception e) { ReportingUtils.logError("Failed to install the \"" + autofocus.getName() + "\" autofocus plugin."); } } } @Override public void logMessage(String msg) { ReportingUtils.logMessage(msg); } @Override public void showMessage(String msg) { ReportingUtils.showMessage(msg); } @Override public void logError(Exception e, String msg) { ReportingUtils.logError(e, msg); } @Override public void logError(Exception e) { ReportingUtils.logError(e); } @Override public void logError(String msg) { ReportingUtils.logError(msg); } @Override public void showError(Exception e, String msg) { ReportingUtils.showError(e, msg); } @Override public void showError(Exception e) { ReportingUtils.showError(e); } @Override public void showError(String msg) { ReportingUtils.showError(msg); } private void runHardwareWizard() { try { if (configChanged_) { Object[] options = {"Yes", "No"}; int n = JOptionPane.showOptionDialog(null, "Save Changed Configuration?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == JOptionPane.YES_OPTION) { saveConfigPresets(); } configChanged_ = false; } boolean liveRunning = false; if (isLiveModeOn()) { liveRunning = true; enableLiveMode(false); } // unload all devices before starting configurator core_.reset(); GUIUtils.preventDisplayAdapterChangeExceptions(); // run Configurator ConfiguratorDlg2 cfg2 = null; try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); cfg2 = new ConfiguratorDlg2(core_, sysConfigFile_); } finally { setCursor(Cursor.getDefaultCursor()); } if (cfg2 == null) { ReportingUtils.showError("Failed to launch Hardware Configuration Wizard"); return; } cfg2.setVisible(true); GUIUtils.preventDisplayAdapterChangeExceptions(); // re-initialize the system with the new configuration file sysConfigFile_ = cfg2.getFileName(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); loadSystemConfiguration(); GUIUtils.preventDisplayAdapterChangeExceptions(); if (liveRunning) { enableLiveMode(liveRunning); } } catch (Exception e) { ReportingUtils.showError(e); } } private void autofocusNow() { if (afMgr_.getDevice() != null) { new Thread() { @Override public void run() { try { boolean lmo = isLiveModeOn(); if (lmo) { enableLiveMode(false); } afMgr_.getDevice().fullFocus(); if (lmo) { enableLiveMode(true); } } catch (MMException ex) { ReportingUtils.logError(ex); } } }.start(); // or any other method from Autofocus.java API } } } class BooleanLock extends Object { private boolean value; public BooleanLock(boolean initialValue) { value = initialValue; } public BooleanLock() { this(false); } public synchronized void setValue(boolean newValue) { if (newValue != value) { value = newValue; notifyAll(); } } public synchronized boolean waitToSetTrue(long msTimeout) throws InterruptedException { boolean success = waitUntilFalse(msTimeout); if (success) { setValue(true); } return success; } public synchronized boolean waitToSetFalse(long msTimeout) throws InterruptedException { boolean success = waitUntilTrue(msTimeout); if (success) { setValue(false); } return success; } public synchronized boolean isTrue() { return value; } public synchronized boolean isFalse() { return !value; } public synchronized boolean waitUntilTrue(long msTimeout) throws InterruptedException { return waitUntilStateIs(true, msTimeout); } public synchronized boolean waitUntilFalse(long msTimeout) throws InterruptedException { return waitUntilStateIs(false, msTimeout); } public synchronized boolean waitUntilStateIs( boolean state, long msTimeout) throws InterruptedException { if (msTimeout == 0L) { while (value != state) { wait(); } return true; } long endTime = System.currentTimeMillis() + msTimeout; long msRemaining = msTimeout; while ((value != state) && (msRemaining > 0L)) { wait(msRemaining); msRemaining = endTime - System.currentTimeMillis(); } return (value == state); } }
package com.googlecode.totallylazy; import com.googlecode.totallylazy.callables.CountingCallable; import com.googlecode.totallylazy.matchers.NumberMatcher; import com.googlecode.totallylazy.numbers.Numbers; import org.junit.Test; import java.util.List; import static com.googlecode.totallylazy.Callables.asString; import static com.googlecode.totallylazy.Callables.ascending; import static com.googlecode.totallylazy.Callables.call; import static com.googlecode.totallylazy.Callables.callThrows; import static com.googlecode.totallylazy.Callables.descending; import static com.googlecode.totallylazy.Callables.returns; import static com.googlecode.totallylazy.Option.none; import static com.googlecode.totallylazy.Option.some; import static com.googlecode.totallylazy.Pair.pair; import static com.googlecode.totallylazy.Predicates.notNull; import static com.googlecode.totallylazy.Sequences.cons; import static com.googlecode.totallylazy.Sequences.iterate; import static com.googlecode.totallylazy.Sequences.range; import static com.googlecode.totallylazy.Sequences.sequence; import static com.googlecode.totallylazy.Sequences.sort; import static com.googlecode.totallylazy.callables.CountingCallable.counting; import static com.googlecode.totallylazy.matchers.IterableMatcher.hasExactly; import static com.googlecode.totallylazy.matchers.IterableMatcher.startsWith; import static com.googlecode.totallylazy.numbers.Numbers.add; import static com.googlecode.totallylazy.numbers.Numbers.even; import static com.googlecode.totallylazy.numbers.Numbers.numbers; import static com.googlecode.totallylazy.numbers.Numbers.odd; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class SequenceTest { @Test public void supportsLast() throws Exception { assertThat(sequence(1,2,3).last(), is(3)); } @Test public void supportsReverse() throws Exception { assertThat(sequence(1,2,3).reverse(), hasExactly(3,2,1)); } @Test public void supportsSize() throws Exception { assertThat(range(10000000000L, 10000000100L).size(), NumberMatcher.is(100)); } @Test public void canRealiseASequence() throws Exception { CountingCallable<Integer> counting = counting(); Sequence<Integer> lazy = sequence(counting).map(call(Integer.class)); assertThat(counting.count(), is(0)); assertThat(lazy, hasExactly(0)); // this will increment count by 1 Sequence<Integer> realised = lazy.realise(); // this will increment count by 1 assertThat(counting.count(), is(2)); assertThat(realised, hasExactly(1)); assertThat(realised, hasExactly(1)); } @Test public void supportsSafeCast() throws Exception { Cat freaky = new Cat(), fatty = new Cat(); Dog buster = new Dog(); Sequence<Animal> animals = sequence(freaky, fatty, buster); Sequence<Cat> cats = animals.safeCast(Cat.class); Sequence<Dog> dogs = animals.safeCast(Dog.class); assertThat(cats, hasExactly(freaky, fatty)); assertThat(dogs, hasExactly(buster)); } public static interface Animal {} public static class Cat implements Animal {} public static class Dog implements Animal {} @Test public void supportsSort() throws Exception { assertThat(sort(sequence(5, 6, 1, 3, 4, 2)), hasExactly(1, 2, 3, 4, 5, 6)); assertThat(sort(sequence("Matt", "Dan", "Bob")), hasExactly("Bob", "Dan", "Matt")); } @Test public void supportsSortBy() throws Exception { int[] small = {1}; int[] medium = {1, 2, 3}; int[] large = {1, 2, 3, 4, 5, 6}; Sequence<int[]> unsorted = sequence(large, small, medium); assertThat(unsorted.sortBy(Callables.<int[]>length()), hasExactly(small, medium, large)); assertThat(unsorted.sortBy(ascending(Callables.<int[]>length())), hasExactly(small, medium, large)); assertThat(unsorted.sortBy(descending(Callables.<int[]>length())), hasExactly(large, medium, small)); } @Test public void supportsCons() throws Exception { assertThat(sequence(1, 2, 3).cons(4), hasExactly(4, 1, 2, 3)); assertThat(cons(4, sequence(1, 2, 3)), hasExactly(4, 1, 2, 3)); } @Test public void supportsJoin() throws Exception { Sequence<Integer> numbers = sequence(1, 2, 3).join(sequence(4, 5, 6)); assertThat(numbers, hasExactly(1, 2, 3, 4, 5, 6)); } @Test public void supportsAdd() throws Exception { Sequence<Integer> numbers = sequence(1, 2, 3).add(4); assertThat(numbers, hasExactly(1, 2, 3, 4)); } @Test public void supportsTryPick() throws Exception { Option<String> converted = sequence(1, 2, 3).tryPick(someVeryExpensiveOperation); assertThat(converted, is((Option<String>) some("converted"))); } @Test public void supportsPick() throws Exception { String converted = sequence(1, 2, 3).pick(someVeryExpensiveOperation); assertThat(converted, is("converted")); } Callable1<Integer, Option<String>> someVeryExpensiveOperation = new Callable1<Integer, Option<String>>() { public Option<String> call(Integer number) throws Exception { if(Numbers.equalTo(number, 1)) { return none(); // the conversion didn't work } if(Numbers.equalTo(number, 2)) { return some("converted"); // the conversion worked so don't do any more } throw new AssertionError("should never get here"); } }; @Test public void supportsFind() throws Exception { assertThat(sequence(1, 3, 5).find(even()), is((Option<Integer>) none(Integer.class))); assertThat(sequence(1, 2, 3).find(even()), is((Option<Integer>) some(2))); assertThat(sequence(none(Integer.class), some(2), some(3)).find(Predicates.<Integer>some()).get(), is((Option<Integer>) some(2))); } @Test public void supportsContains() throws Exception { assertThat(sequence(1, 3, 5).contains(2), is(false)); assertThat(sequence(1, 2, 3).contains(2), is(true)); } @Test public void supportsExists() throws Exception { assertThat(sequence(1, 3, 5).exists(even()), is(false)); assertThat(sequence(1, 2, 3).exists(even()), is(true)); } @Test public void supportsForAll() throws Exception { assertThat(sequence(1, 3, 5).forAll(odd()), is(true)); assertThat(sequence(1, 2, 3).forAll(odd()), is(false)); } @Test public void canFilterNull() throws Exception { final Sequence<Integer> numbers = sequence(1, null, 3).filter(notNull(Number.class)); assertThat(numbers, hasExactly(1, 3)); } @Test public void supportsRemove() throws Exception { final Sequence<Integer> numbers = sequence(1, 2, 3, 2).remove(2); assertThat(numbers, hasExactly(1, 3, 2)); } @Test public void canConvertToArray() throws Exception { final Integer[] array = sequence(1, 2).toArray(Integer.class); assertThat(array[0], is(1)); assertThat(array[1], is(2)); } @Test public void canConvertToList() throws Exception { final List<Integer> aList = sequence(1, 2).toList(); assertThat(aList, hasExactly(1, 2)); } @Test public void supportsIsEmpty() throws Exception { assertThat(sequence().isEmpty(), is(true)); assertThat(sequence(1).isEmpty(), is(false)); } @Test public void supportsToString() throws Exception { assertThat(sequence(1, 2, 3).toString(), is("1,2,3")); assertThat(sequence(1, 2, 3).toString(":"), is("1:2:3")); assertThat(sequence(1, 2, 3).toString("(", ", ", ")"), is("(1, 2, 3)")); assertThat(sequence(1, 2, 3).toString("(", ", ", ")", 2), is("(1, 2...)")); } @Test public void supportsReduceLeft() throws Exception { Number sum = numbers(1, 2, 3).reduceLeft(add()); assertThat(sum, NumberMatcher.is(6)); } @Test public void supportsFoldLeft() throws Exception { Number sum = sequence(1, 2, 3).foldLeft(0, add()); assertThat(sum, NumberMatcher.is(6)); } @Test public void supportsTail() throws Exception { assertThat(sequence(1, 2, 3).tail(), hasExactly(2, 3)); } @Test public void supportsHead() throws Exception { assertThat(sequence(1, 2).head(), is(1)); } @Test public void supportsHeadOrOption() throws Exception { assertThat(sequence(1).headOption(), is((Option<Integer>) Option.<Integer>some(1))); assertThat(Sequences.<Number>sequence().headOption(), is((Option<Number>) Option.<Number>none())); } @Test public void supportsForEach() throws Exception { final int[] sum = {0}; sequence(1, 2).forEach(new Runnable1<Integer>() { public void run(Integer value) { sum[0] += value; } }); assertThat(sum[0], is(3)); } @Test public void supportsMap() throws Exception { Iterable<String> strings = sequence(1, 2).map(asString()); assertThat(strings, hasExactly("1", "2")); } @Test public void mapIsLazy() throws Exception { Iterable<Integer> result = sequence(returns(1), callThrows(new Exception(), Integer.class)). map(call(Integer.class)); assertThat(result, startsWith(1)); } @Test public void supportsFilter() throws Exception { Iterable<Integer> result = sequence(1, 2, 3, 4).filter(even()); assertThat(result, hasExactly(2, 4)); } @Test public void filterIsLazy() throws Exception { Iterable<Integer> result = sequence(returns(1), returns(2), callThrows(new Exception(), Integer.class)). map(call(Integer.class)). filter(even()); assertThat(result, startsWith(2)); } @Test public void supportsFlatMap() throws Exception { Iterable<Integer> result = sequence(1, 2, 3).flatMap(new Callable1<Integer, Iterable<? extends Integer>>() { public Iterable<Integer> call(Integer value) throws Exception { return sequence(value, value * 3); } }); assertThat(result, hasExactly(1, 3, 2, 6, 3, 9)); } @Test public void supportsTake() throws Exception { final Sequence<Integer> sequence = sequence(1, 2, 3).take(2); assertThat(sequence, hasExactly(1, 2)); assertThat(sequence(1).take(2).size(), NumberMatcher.is(1)); assertThat(sequence().take(2).size(), NumberMatcher.is(0)); } @Test public void supportsTakeWhile() throws Exception { final Sequence<Integer> sequence = sequence(1, 3, 5, 6, 8, 1, 3).takeWhile(odd()); assertThat(sequence, hasExactly(1, 3, 5)); assertThat(sequence(1).takeWhile(odd()).size(), NumberMatcher.is(1)); assertThat(Sequences.<Number>sequence().takeWhile(odd()).size(), NumberMatcher.is(0)); } @Test public void supportsDrop() throws Exception { final Sequence<Integer> sequence = sequence(1, 2, 3).drop(2); assertThat(sequence, hasExactly(3)); assertThat(sequence(1).drop(2).size(), NumberMatcher.is(0)); assertThat(sequence().drop(1).size(), NumberMatcher.is(0)); } @Test public void supportsDropWhile() throws Exception { final Sequence<Integer> sequence = sequence(1, 3, 5, 6, 8, 1, 3).dropWhile(odd()); assertThat(sequence, hasExactly(6, 8, 1, 3)); assertThat(sequence(1).dropWhile(odd()).size(), NumberMatcher.is(0)); assertThat(Sequences.<Number>sequence().dropWhile(odd()).size(), NumberMatcher.is(0)); } @Test public void supportsZip() { final Sequence<Integer> sequence = sequence(1, 3, 5); assertThat(sequence.zip(sequence(2, 4, 6, 8)), hasExactly(pair(1, 2), pair(3, 4), pair(5, 6))); assertThat(sequence.zip(sequence(2, 4, 6)), hasExactly(pair(1, 2), pair(3, 4), pair(5, 6))); assertThat(sequence.zip(sequence(2, 4)), hasExactly(pair(1, 2), pair(3, 4))); } @Test public void supportsZipWithIndex() { assertThat(sequence("Dan", "Matt", "Bob").zipWithIndex(), hasExactly(pair((Number)0, "Dan"), pair((Number)1, "Matt"), pair((Number)2, "Bob"))); } }
package edu.cmu.minorthird.text; import edu.cmu.minorthird.text.*; import edu.cmu.minorthird.text.learn.SigFileAnnotator; import org.apache.log4j.Logger; import java.io.File; /** * This class... * @author ksteppe */ public class AnnotatorRunner { private static Logger log = Logger.getLogger(AnnotatorRunner.class); public static void main(String[] args) {// load the documents into a textbase try { // TextBase base = new BasicTextBase(); // TextBaseLoader loader = new TextBaseLoader(); File dir = new File("C:/radar/extract/src/com/wcohen/text/ann/samplemail"); //put the directory with emails here. //File dir = new File("C:/boulder/randomNOSig"); //put the directory with emails here. MutableTextLabels labels = null; labels = TextBaseLoader.loadDirOfTaggedFiles(dir); // TextBase base = labels.getTextBase(); Annotator annotator = new SigFileAnnotator(); // Annotator annotator = new POSTagger(); annotator.annotate(labels); // output the results for (Span.Looper i = labels.instanceIterator("sig"); i.hasNext();) { Span span = i.nextSpan(); //System.out.println( span.asString().replace('\n',' ') ); System.out.println(span.toString().replace('\n', ' ')); } } catch (Exception e) { log.fatal(e, e); } } }
package org.opencms.module; import org.opencms.main.CmsIllegalArgumentException; import junit.framework.TestCase; /** * Tests the module version.<p> * * @author Alexander Kandzior (a.kandzior@alkacon.com) * * @version $Revision: 1.4 $ */ public class TestCmsModuleVersion extends TestCase { /** * Default JUnit constructor.<p> * * @param arg0 JUnit parameters */ public TestCmsModuleVersion(String arg0) { super(arg0); } /** * Tests version increment.<p> */ public void testVersionIncrement() { CmsModuleVersion v1 = new CmsModuleVersion("1.2.5"); v1.increment(); assertEquals("1.2.6", v1.getVersion()); v1 = new CmsModuleVersion("1.02.05"); v1.increment(); assertEquals("1.2.6", v1.getVersion()); v1 = new CmsModuleVersion("1.02.999"); v1.increment(); assertEquals("1.3.0", v1.getVersion()); v1 = new CmsModuleVersion("0.999"); v1.increment(); assertEquals("1.0", v1.getVersion()); boolean gotError = false; try { v1 = new CmsModuleVersion("999.999.999.999"); v1.increment(); } catch (RuntimeException e) { gotError = true; } if (! gotError) { fail("Invalid version increment allowed"); } } /** * Tests version generation.<p> */ public void testVersionGeneration() { CmsModuleVersion v1 = new CmsModuleVersion("1.2.5"); CmsModuleVersion v2 = new CmsModuleVersion("1.12"); if (v1.compareTo(v2) > 0) { fail("Module version comparison error"); } v1 = new CmsModuleVersion("5"); v2 = new CmsModuleVersion("1.0.0.1"); if (v1.compareTo(v2) <= 0) { fail("Module version comparison error"); } v1 = new CmsModuleVersion("1.2.5.7"); v2 = new CmsModuleVersion("1.2.45"); if (v1.compareTo(v2) > 0) { fail("Module version comparison error"); } v1 = new CmsModuleVersion("2.45.6"); v2 = new CmsModuleVersion("2.45.06"); if (v1.compareTo(v2) != 0) { fail("Module version comparison error"); } v1 = new CmsModuleVersion("1.0.0.0"); v2 = new CmsModuleVersion("1"); if (v1.compareTo(v2) != 0) { fail("Module version comparison error"); } v1 = new CmsModuleVersion("0.1"); v2 = new CmsModuleVersion("0.0.0.1"); if (v1.compareTo(v2) <= 0) { fail("Module version comparison error"); } v1 = new CmsModuleVersion("0.08"); assertEquals("0.8", v1.getVersion()); v1 = new CmsModuleVersion("00.00"); assertEquals("0.0", v1.getVersion()); v1 = new CmsModuleVersion("999.999.999.999"); assertEquals("999.999.999.999", v1.getVersion()); boolean gotError = false; try { v1 = new CmsModuleVersion("2..45.6"); } catch (CmsIllegalArgumentException e) { gotError = true; } if (! gotError) { fail("Invalid version generation allowed"); } gotError = false; try { v1 = new CmsModuleVersion(".2.45.6"); } catch (NumberFormatException e) { gotError = true; } if (! gotError) { fail("Invalid version generation allowed"); } gotError = false; try { v1 = new CmsModuleVersion("2.45.6."); } catch (NumberFormatException e) { gotError = true; } if (! gotError) { fail("Invalid version generation allowed"); } gotError = false; try { v1 = new CmsModuleVersion("wurst"); } catch (NumberFormatException e) { gotError = true; } if (! gotError) { fail("Invalid version generation allowed"); } gotError = false; try { v1 = new CmsModuleVersion("2222.45.6"); } catch (CmsIllegalArgumentException e) { gotError = true; } if (! gotError) { fail("Invalid version generation allowed"); } gotError = false; try { v1 = new CmsModuleVersion("1.2.3.4.5"); } catch (CmsIllegalArgumentException e) { gotError = true; } if (! gotError) { fail("Invalid version generation allowed"); } } }