answer
stringlengths
17
10.2M
package com.intellij.openapi.util; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.Debug; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @deprecated use {@link com.intellij.util.containers.MultiMap} directly. * <p></p>On migration please note that MultiMap has few differences:<ul> * <li>{@link MultiMap#get(java.lang.Object)} method returns non-null value. In case there is no value for the key - empty collection is returned.</li> * <li>{@link MultiMap#values} method returns a real values collection, not a copy. Be careful with modifications.</li> * </ul></p> */ @Debug.Renderer(text = "\"size = \" + myBaseMap.size()", hasChildren = "!isEmpty()", childrenArray = "entrySet().toArray()") @Deprecated public class MultiValuesMap<K, V>{ private final MultiMap<K, V> myDelegate; private final boolean myOrdered; /** * @deprecated Use {@link MultiMap#createSet()} */ @Deprecated public MultiValuesMap() { this(false); } public MultiValuesMap(boolean ordered) { myOrdered = ordered; if (ordered) { myDelegate = MultiMap.createLinkedSet(); } else { myDelegate = MultiMap.createSet(); } } public void putAll(K key, @NotNull Collection<? extends V> values) { for (V value : values) { put(key, value); } } public void putAll(K key, @NotNull V... values) { for (V value : values) { put(key, value); } } public void put(K key, V value) { myDelegate.putValue(key, value); } @Nullable public Collection<V> get(K key){ Collection<V> collection = myDelegate.get(key); return collection.isEmpty() ? null : collection; } @NotNull public Set<K> keySet() { return myDelegate.keySet(); } @NotNull public Collection<V> values() { return myOrdered ? new LinkedHashSet<>(myDelegate.values()) : new HashSet<>(myDelegate.values()); } public void remove(K key, V value) { myDelegate.remove(key, value); } public void clear() { myDelegate.clear(); } @Nullable public Collection<V> removeAll(final K key) { return myDelegate.remove(key); } @NotNull public Set<Map.Entry<K, Collection<V>>> entrySet() { return myDelegate.entrySet(); } public boolean isEmpty() { return myDelegate.isEmpty(); } public boolean containsKey(final K key) { return myDelegate.containsKey(key); } @Nullable public V getFirst(final K key) { Collection<V> values = myDelegate.get(key); return values.isEmpty() ? null : values.iterator().next(); } }
package org.jpmml.evaluator; import java.util.*; import org.jpmml.manager.*; import org.dmg.pmml.*; /** * <p> * Performs the evaluation of a {@link Model} in "interpreted mode". * </p> * * Obtaining {@link Evaluator} instance: * <pre> * PMML pmml = ...; * PMMLManager pmmlManager = new PMMLManager(pmml); * Evaluator evaluator = (Evaluator)pmmlManager.getModelManager(null, ModelEvaluatorFactory.getInstance()); * </pre> * * Preparing {@link Evaluator#getActiveFields() active fields}: * <pre> * Map&lt;FieldName, Object&gt; parameters = new LinkedHashMap&lt;FieldName, Object&gt;(); * List&lt;FieldName&gt; activeFields = evaluator.getActiveFields(); * for(FieldName activeField : activeFields){ * parameters.put(activeField, ...); * } * </pre> * * Performing the {@link Evaluator#evaluate(Map) evaluation}: * <pre> * Map&lt;FieldName, ?&gt; result = evaluator.evaluate(parameters); * </pre> * * Retrieving the value of the {@link Evaluator#getTarget() predicted field} and {@link Evaluator#getOutputFields() output fields}: * <pre> * FieldName targetField = evaluator.getTarget(); * Object targetValue = result.get(targetField); * * List&lt;FieldName&gt; outputFields = evaluator.getOutputFields(); * for(FieldName outputField : outputFields){ * Object outputValue = result.get(outputField); * } * </pre> * * Decoding {@link Computable complex value} to simple value: * <pre> * Object value = ...; * if(value instanceof Computable){ * Computable&lt;?&gt; computable = (Computable&lt;?&gt;)value; * * value = computable.getResult(); * } * </pre> * * @see EvaluatorUtil */ public interface Evaluator extends Consumer { /** * Convenience method for retrieving the predicted field. * * @return The predicted field * * @throws ModelManagerException If the number of predicted fields is not exactly one * * @see Consumer#getPredictedFields() */ FieldName getTarget(); /** * @param parameters Map of {@link #getActiveFields() active field} values. * * @return Map of {@link #getPredictedFields() predicted field} and {@link #getOutputFields() output field} values. * Simple values are represented using the Java equivalents of PMML data types (eg. String, Integer, Float, Double etc.). * Complex values are represented as instances of {@link Computable} that return simple values. * * @throws EvaluationException If the evaluation fails * * @see Computable */ Map<FieldName, ?> evaluate(Map<FieldName, ?> parameters); }
package org.b3mn.poem.util; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.Text; public class RdfJsonTransformation { private final static String[] reservedNodeNames = { "rdf:type", "type", "mode", "stencilset", "render", "bounds", "dockers", "outgoing", "target", "parent" }; private static JSONObject canvas; private static Map<String,JSONObject> objects; // resourceId -> JSONObject private static Map<String,String> parents; // resourceId -> parent's resourceId private static String hostUrl; public static JSONObject toJson(Document rdfDoc, String requestUrl) { canvas = new JSONObject(); objects = new HashMap<String,JSONObject>(); parents = new HashMap<String,String>(); hostUrl = requestUrl; Node root = getRootNode(rdfDoc); if(root==null) return canvas; if(root.hasChildNodes()) { for (Node node = root.getFirstChild(); node != null; node = node.getNextSibling()) { if (node instanceof Text) continue; String type = getType(node); if (type == null) continue; Node rdfTypeNode = getChild(node, "rdf:type"); if(rdfTypeNode!=null) { String rdfType = getAttributeValue(rdfTypeNode, "rdf:resource"); if( (rdfType!=null) && rdfType.equals("http://oryx-editor.org/canvas") ) { handleCanvas(node); continue; } } handleShape(node); } } setupParentRelationships(); return canvas; } private static void handleCanvas(Node n) { try { canvas.put("resourceId", getResourceId(n)); canvas.put("childShapes", new JSONArray()); handleProperties(n, canvas); } catch (JSONException e) { e.printStackTrace(); } } private static void handleShape(Node n) { try { String resourceId = getResourceId(n); if(resourceId.length()==0) return; JSONObject shape = new JSONObject(); shape.put("resourceId", resourceId); objects.put(resourceId, shape); parents.put(resourceId, getParentResourceId(n)); shape.put("outgoing", new JSONArray()); shape.put("childShapes", new JSONArray()); handleProperties(n, shape); } catch (JSONException e) { e.printStackTrace(); } } private static void setupParentRelationships() { for(String resourceId : parents.keySet()) { JSONObject child = objects.get(resourceId); JSONObject parent = objects.get(parents.get(resourceId)); if(parent==null) parent = canvas; try { parent.getJSONArray("childShapes").put(child); } catch (JSONException e) { e.printStackTrace(); } } } private static void handleProperties(Node n, JSONObject object) throws JSONException { JSONObject properties = new JSONObject(); object.put("properties", properties); if(n.hasChildNodes()) { for (Node child = n.getFirstChild(); child != null; child = child.getNextSibling()) { if( !isReservedNodeName(child.getNodeName()) ) { String content = getContent(child); if(content==null) { properties.put(child.getNodeName(), content); } else { try { // try to parse property value to JSON object (for complex properties) JSONObject jsonObj = new JSONObject(content); properties.put(child.getNodeName(), jsonObj); } catch (JSONException e) { // non-JSON content properties.put(child.getNodeName(), content); } } } else { handleReservedNodeName(child, object); } } } } private static void handleReservedNodeName(Node n, JSONObject object) throws JSONException { if(n.getNodeName().equals("bounds")) { object.put("bounds", getBounds(n)); } else if(n.getNodeName().equals("type")) { object.put("stencil", (new JSONObject()).put("id", getType(n))); } else if(n.getNodeName().equals("outgoing")) { JSONObject outgoingObject = new JSONObject(); outgoingObject.put("resourceId", getResourceId(getAttributeValue(n, "rdf:resource"))); object.getJSONArray("outgoing").put(outgoingObject); } else if(n.getNodeName().equals("target")) { JSONObject target = new JSONObject(); target.put("resourceId", getResourceId(getAttributeValue(n, "rdf:resource"))); object.put("target", target); } else if(n.getNodeName().equals("stencilset")) { JSONObject stencilset = new JSONObject(); String stencilsetUrl = getAttributeValue(n, "rdf:resource"); stencilset.put("url", hostUrl + stencilsetUrl); object.put("stencilset", stencilset); } } private static JSONObject getBounds(Node n) throws JSONException { String boundsString = getContent(n); if(boundsString==null) return null; String[] boundStringArr = boundsString.split(","); JSONObject upperLeft = new JSONObject(); upperLeft.put("x", Double.parseDouble(boundStringArr[0])); upperLeft.put("y", Double.parseDouble(boundStringArr[1])); JSONObject lowerRight = new JSONObject(); lowerRight.put("x", Double.parseDouble(boundStringArr[2])); lowerRight.put("y", Double.parseDouble(boundStringArr[3])); JSONObject bounds = new JSONObject(); bounds.put("upperLeft", upperLeft); bounds.put("lowerRight", lowerRight); return bounds; } private static String getParentResourceId(Node n) { Node parentNode = getChild(n, "parent"); if(parentNode==null) return null; String parentResourceId = getResourceId(getAttributeValue(parentNode, "rdf:resource")); if(parentResourceId!=null) return getResourceId(parentResourceId); else return null; } private static String getContent(Node node) { if (node != null && node.hasChildNodes()) return node.getFirstChild().getNodeValue(); return null; } private static String getAttributeValue(Node node, String attribute) { Node item = node.getAttributes().getNamedItem(attribute); if (item != null) return item.getNodeValue(); else return null; } private static String getType(Node node) { String type = getContent(node); if (type != null) return type.substring(type.indexOf(' else return null; } private static String getResourceId(Node node) { String attributeValue = getAttributeValue(node, "rdf:about"); if (attributeValue != null) return getResourceId(attributeValue); else return null; } private static String getResourceId(String id) { if(id==null) return null; return id.substring(id.indexOf(' } private static Node getChild(Node n, String name) { if (n == null) return null; for (Node node=n.getFirstChild(); node != null; node=node.getNextSibling()) if (node.getNodeName().equals(name)) return node; return null; } private static Node getRootNode(Document doc) { Node node = doc.getDocumentElement(); if (node == null || !node.getNodeName().equals("rdf:RDF")) return null; return node; } private static boolean isReservedNodeName(String nodeName) { for(String n : reservedNodeNames) { if(n.equals(nodeName)) return true; } return false; } }
package org.nohope.akka; import akka.actor.ActorRef; import akka.actor.Props; import akka.actor.UntypedActor; import akka.event.Logging; import akka.event.LoggingAdapter; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.nohope.typetools.JSON; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; @SuppressFBWarnings( value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "onConcreteMessage here is invoked " + "reflectively to not to check types all the time") public abstract class BaseSupervisor extends UntypedActor { private final LoggingAdapter log = Logging.getLogger(getContext().system(), this); private final Map<NamedWorkerMetadata, ActorRef> startingActors = new HashMap<>(); protected abstract Props newInputProps(final NamedWorkerMetadata inputClassId); protected BaseSupervisor() { } @Override public void onReceive(final Object message) { try { MessageMethodInvoker.invokeHandler(this, message); } catch (Exception e) { log.error(e, "Bad message received: {}", JSON.pretty(message)); } } @Override public void postStop() { log.debug("Supervisor '{}' stopped", getSelf().path().name()); } @SuppressWarnings("unused") public void onConcreteMessage(final NamedWorkerMetadata inputClassId) { final ActorRef deviceRef = obtainWorkerRef(inputClassId); getSender().tell(deviceRef); } protected ActorRef obtainWorkerRef(final NamedWorkerMetadata inputClassId) { ActorRef deviceRef = startingActors.get(inputClassId); if (null == deviceRef) { final String url = getInputActorUrl(inputClassId); deviceRef = getContext().system().actorFor(url); if (deviceRef.isTerminated()) { final String actId = inputClassId.getIdentifier(); log.debug("Starting new input processing actor with id {} in supervisor '{}'...", actId, getSelf().path().name()); deviceRef = getContext().actorOf(newInputProps(inputClassId) , actId); startingActors.put(inputClassId, deviceRef); deviceRef.tell(new SupervisorRequests.StartupRequest(), getSelf()); } else { log.debug("Passing existing device actor..."); } } else { log.debug("Passing existing device actor which is starting now..."); } return deviceRef; } @SuppressWarnings("unused") public void onConcreteMessage(final SupervisorRequests.StartupReply reply) { log.debug("Successful startup notification in {}: {}", getSelf().path().name(), JSON.pretty(reply)); if (!startingActors.containsKey(reply.workerMetadata)) { throw new IllegalStateException("Request to remove non-existing actor: " + reply.workerMetadata); } startingActors.remove(reply.workerMetadata); } private String getInputActorUrl(final NamedWorkerMetadata inputClassId) { return MessageFormat.format("{0}/{1}" , getSelf().path() , inputClassId.getIdentifier()); } }
package top.itmp.rtbox.example; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.TimeoutException; import top.itmp.rtbox.RtBox; import top.itmp.rtbox.Shell; import top.itmp.rtbox.command.SimpleBinCommand; public class FragmentBin extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LinearLayout rootView = new LinearLayout(container.getContext()); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ); rootView.setLayoutParams(layoutParams); rootView.setOrientation(LinearLayout.VERTICAL); final TextView textView = new TextView(getActivity()); textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); RtBox.DebugMode = true; final Shell shell = Shell.startShell(); final RtBox rtBox = new RtBox(shell); final SimpleBinCommand simpleBinCommand = new SimpleBinCommand(getActivity(), "hello"); Button execBin = new Button(getActivity()); execBin.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); execBin.setText("execbin"); execBin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { shell.run(simpleBinCommand); try { boolean isRunning = rtBox.isProcessRunning(simpleBinCommand.getCommandLine()); textView.setText(simpleBinCommand.getCommand() + (isRunning ? "running: \n": "not running\n")); if(isRunning){ ArrayList<String> pids = rtBox.getPids(simpleBinCommand.getCommandLine()); for(String pid: pids){ textView.append(pid + ' '); } } }catch (IOException e){ e.printStackTrace(); }catch (TimeoutException e){ e.printStackTrace(); } } }); Button killAllBin = new Button(getActivity()); killAllBin.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); killAllBin.setText("killAllBin"); killAllBin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { if(rtBox.isProcessRunning(simpleBinCommand.getCommandLine())){ textView.setText(rtBox.killAll(simpleBinCommand.getCommandLine()) ? "killed" : "kill failed"); } }catch (IOException e){ e.printStackTrace(); }catch (TimeoutException e){ e.printStackTrace(); } } }); rootView.addView(textView); rootView.addView(execBin); rootView.addView(killAllBin); return rootView; } }
package com.yahoo.squidb.test; import android.content.Context; import com.yahoo.squidb.data.adapter.SQLiteDatabaseWrapper; import com.yahoo.squidb.data.adapter.SQLiteOpenHelperWrapper; import com.yahoo.squidb.reactive.ReactiveSquidDatabase; import com.yahoo.squidb.sql.AttachDetachTest; import com.yahoo.squidb.sql.Index; import com.yahoo.squidb.sql.Table; import com.yahoo.squidb.sql.View; import com.yahoo.squidb.sqlitebindings.SQLiteBindingsOpenHelperWrapper; public class TestReactiveDatabase extends ReactiveSquidDatabase { private static final Index INDEX_TESTMODELS_LUCKYNUMBER = TestModel.TABLE .index("index_testmodels_luckynumber", TestModel.LUCKY_NUMBER); public TestReactiveDatabase(Context context) { super(context); } @Override public String getName() { return "testDb"; } @Override protected Table[] getTables() { return new Table[]{ TestModel.TABLE, Thing.TABLE, Employee.TABLE, TriggerTester.TABLE, BasicData.TABLE, TestVirtualModel.TABLE }; } @Override protected Index[] getIndexes() { return new Index[]{INDEX_TESTMODELS_LUCKYNUMBER}; } @Override protected View[] getViews() { return new View[]{ TestViewModel.VIEW }; } @Override protected SQLiteOpenHelperWrapper getOpenHelper(Context context, String databaseName, OpenHelperDelegate delegate, int version) { if (SquidInstrumentationTestRunner.useSqliteBindings) { return new SQLiteBindingsOpenHelperWrapper(context, databaseName, delegate, version); } else { return super.getOpenHelper(context, databaseName, delegate, version); } } @Override protected int getVersion() { return 1; } @Override protected boolean onUpgrade(SQLiteDatabaseWrapper db, int oldVersion, int newVersion) { return true; } @Override protected void onConfigure(SQLiteDatabaseWrapper db) { /** @see AttachDetachTest#testAttacherInTransactionOnAnotherThread() */ db.enableWriteAheadLogging(); } }
package com.Litterfeldt.AStory.fragments; import com.Litterfeldt.AStory.R; import android.content.Context; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import android.os.AsyncTask; import com.Litterfeldt.AStory.dbConnector.dbBook; import com.Litterfeldt.AStory.models.FileSystem; import com.Litterfeldt.AStory.services.AudioplayerService; import com.handmark.pulltorefresh.library.*; import com.Litterfeldt.AStory.models.Book; import com.Litterfeldt.AStory.pagerView; import java.util.*; import com.Litterfeldt.AStory.adapters.LibraryAdapter; public class LibraryFragment extends Fragment { private LibraryAdapter adapter; private PullToRefreshListView list; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.library, container, false); list =(PullToRefreshListView) view.findViewById(R.id.pull_to_refresh_listview); list.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if(i == 1 || i == adapter.getCount()) return; getService().getMediaPlayer().playBook(adapter.getItem(i-2), 0); getService().showNotification(); ((pagerView) getActivity()).mPager.setCurrentItem(0); } }); bookListAtStartup(view); list.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { new GetDataTask().execute(); } }); return view; } private class GetDataTask extends AsyncTask<Void, Book, ArrayList<Book>> { @Override protected void onPreExecute(){ adapter = new LibraryAdapter(getActivity().getApplicationContext(), R.id.pull_to_refresh_listview, new ArrayList<Book>(), Typeface.createFromAsset(((pagerView) getActivity()).getAssets(), "font.ttf")); adapter.add(new Book(-1,null,null,null,null)); list.setAdapter(adapter); } @Override protected ArrayList<Book> doInBackground(Void...v) { Context c = getActivity().getApplicationContext(); dbBook.purge(c); FileSystem f = FileSystem.getInstance(); ArrayList<ArrayList<String>> bookFolderContent = f.allocateBookFolderContent(); for (ArrayList<String> chapters : bookFolderContent){ Book b = f.mockBookFromPath(chapters); if (b != null) { dbBook.addBook(c, b); publishProgress(dbBook.bookById(c, dbBook.bookIdByName(c, b.name()))); } } return getService().getBookList(); } @Override protected void onProgressUpdate(Book...book) { adapter.insert(book[0],adapter.getCount()-2); } @Override protected void onPostExecute(ArrayList<Book> result) { if(result.isEmpty()){ Toast.makeText(getActivity(),"Your Audiobook-folder is empty, please put books in your /AudioBooks folder on your external storage drive", Toast.LENGTH_LONG); } list.onRefreshComplete(); super.onPostExecute(result); } } private void bookListAtStartup(View view){ AudioplayerService as = getService(); ArrayList<Book> bl = as.getBookList(); if(as != null && !bl.isEmpty()){ adapter = new LibraryAdapter(view.getContext(), R.id.pull_to_refresh_listview, bl, Typeface.createFromAsset(((pagerView) getActivity()).getAssets(), "font.ttf")); list.setAdapter(adapter); adapter.add(new Book(-1,null,null,null,null)); }else if (bl.isEmpty()){ adapter = new LibraryAdapter(view.getContext(), R.id.pull_to_refresh_listview, new ArrayList<Book>(), Typeface.createFromAsset(((pagerView) getActivity()).getAssets(), "font.ttf")); list.setAdapter(adapter); adapter.add(new Book(-1,null,null,null,null)); } } private AudioplayerService getService(){ try{ return ((pagerView) getActivity()).apService; }catch (Exception Ignored){} return null; } }
package com.biermacht.brews.frontend; import android.app.AlertDialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.TextView; import com.biermacht.brews.R; import com.biermacht.brews.frontend.IngredientActivities.AddEditActivity; import com.biermacht.brews.frontend.adapters.SpinnerAdapter; import com.biermacht.brews.recipe.MashProfile; import com.biermacht.brews.recipe.MashStep; import com.biermacht.brews.recipe.Recipe; import com.biermacht.brews.utils.Constants; import com.biermacht.brews.utils.Units; import com.biermacht.brews.utils.Callbacks.BooleanCallback; import com.biermacht.brews.utils.Callbacks.Callback; import java.util.ArrayList; public class AddMashStepActivity extends AddEditActivity { // Views public View stepTempView; public View waterToGrainRatioView; public View infuseTemperatureView; // Titles public TextView stepTempViewTitle; public TextView waterToGrainRatioViewTitle; public TextView infuseTemperatureViewTitle; // Content text public TextView stepTempViewText; public TextView waterToGrainRatioViewText; public TextView infuseTemperatureViewText; // mashProfile we are editing public MashStep step; public long stepId; // Callbacks for autocalc fields. public BooleanCallback infuseTempCallback; public BooleanCallback infuseAmountCallback; // step type array ArrayList<String> stepTypeArray; // Data storage String type; MashProfile profile; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Disable delete button for this view findViewById(R.id.delete_button).setVisibility(View.GONE); // Inflate views stepTempView = inflater.inflate(R.layout.row_layout_edit_text, mainView, false); waterToGrainRatioView = inflater.inflate(R.layout.row_layout_edit_text, mainView, false); infuseTemperatureView = inflater.inflate(R.layout.row_layout_edit_text, mainView, false); // Set listeners stepTempView.setOnClickListener(onClickListener); waterToGrainRatioView.setOnClickListener(onClickListener); infuseTemperatureView.setOnClickListener(onClickListener); // Get titles, set values stepTempViewTitle = (TextView) stepTempView.findViewById(R.id.title); waterToGrainRatioViewTitle = (TextView) waterToGrainRatioView.findViewById(R.id.title); infuseTemperatureViewTitle = (TextView) infuseTemperatureView.findViewById(R.id.title); // Get content views stepTempViewText = (TextView) stepTempView.findViewById(R.id.text); waterToGrainRatioViewText = (TextView) waterToGrainRatioView.findViewById(R.id.text); infuseTemperatureViewText = (TextView) infuseTemperatureView.findViewById(R.id.text); // Set titles amountViewTitle.setText("Water to Add (" + (Units.getUnitSystem() == Units.IMPERIAL ? "qt" : "L") + ")"); stepTempViewTitle.setText("Step Temperature (" + Units.getTemperatureUnits() + ")"); waterToGrainRatioViewTitle.setText("Water to Grain Ratio (" + (Units.getUnitSystem() == Units.IMPERIAL ? "qt/lb" : "L/kg") + ")"); infuseTemperatureViewTitle.setText("Water Temperature (" + Units.getTemperatureUnits() + ")"); // Remove views we don't want mainView.removeView(amountView); // Add views that we want mainView.addView(stepTempView); mainView.addView(infuseTemperatureView); mainView.addView(amountView); mainView.addView(waterToGrainRatioView); // Change button text to say "Add" instead of "Submit" submitButton.setText("Add"); // Set values setValues(); } @Override public void onRecipeNotFound() { Log.d("AddMashStepActivity", "Recipe not found - using blank recipe"); mRecipe = new Recipe(); } @Override public void onMissedClick(View v) { AlertDialog alert; if (v.equals(infuseTemperatureView)) alert = alertBuilder.editTextFloatCheckBoxAlert(infuseTemperatureViewText, infuseTemperatureViewTitle, step.getAutoCalcInfuseTemp(), infuseTempCallback).create(); else if (v.equals(stepTempView)) alert = alertBuilder.editTextFloatAlert(stepTempViewText, stepTempViewTitle).create(); else if (v.equals(waterToGrainRatioView)) alert = alertBuilder.editTextFloatAlert(waterToGrainRatioViewText, waterToGrainRatioViewTitle).create(); else return; // Force keyboard open and show popup alert.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); alert.show(); } @Override public void createCallback() { // Default callback, called when alertBuilders are finished. // Allows us to update fields that are dependent on other fields. callback = new Callback() { @Override public void call() { try { // Get new values Log.d("AddMashStepActivity", "Calling callback."); acquireValues(); } catch (Exception e) { Log.d("AddMashStepActivity", "Exception in callback from alert dialog"); e.printStackTrace(); } // Update field values setValues(); } }; // Callbacks for autocalculation. infuseTempCallback = new BooleanCallback() { @Override public void call(boolean b) { Log.d("AddMashStepActivity", "Infuse temp autocalc checkbox pressed."); step.setAutoCalcInfuseTemp(b); infuseTemperatureViewText.setText(String.format("%2.2f", step.getDisplayInfuseTemp())); } }; // Callbacks for autocalculation. infuseAmountCallback = new BooleanCallback() { @Override public void call(boolean b) { Log.d("AddMashStepActivity", "Infuse amount autocalc checkbox pressed."); step.setAutoCalcInfuseAmt(b); amountViewText.setText(String.format("%2.2f", step.getDisplayAmount())); } }; } public void setValues() { nameViewText.setText(step.getName()); timeViewText.setText(String.format("%d", (int) step.getStepTime())); amountViewText.setText(String.format("%2.2f", step.getDisplayAmount())); stepTempViewText.setText(String.format("%2.2f", step.getDisplayStepTemp())); waterToGrainRatioViewText.setText(String.format("%2.2f", step.getDisplayWaterToGrainRatio())); infuseTemperatureViewText.setText(String.format("%2.2f", step.getDisplayInfuseTemp())); Log.d("SetValsAddMashStep", "Got amount: " + step.getDisplayAmount()); } @Override public void getValuesFromIntent() { super.getValuesFromIntent(); // Create mash step profile = getIntent().getParcelableExtra(Constants.KEY_PROFILE); mRecipe.setMashProfile(profile); step = new MashStep(mRecipe); } @Override public void getList() { stepTypeArray = Constants.MASH_STEP_TYPES; } @Override public void createSpinner() { SpinnerAdapter adapter = new SpinnerAdapter(this, stepTypeArray, "Type"); adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); spinnerView.setAdapter(adapter); } @Override public void setInitialSpinnerSelection() { } @Override public void configureSpinnerListener() { spinnerListener = new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { type = stepTypeArray.get(position); // Decoction mashes don't have an infuse amount, but they do have // a decoction amount. if (type.equals(MashStep.DECOCTION)) { amountViewTitle.setText("Amount to decoct (" + Units.getVolumeUnits() + ")"); infuseTemperatureView.setVisibility(View.GONE); waterToGrainRatioView.setVisibility(View.GONE); } else { amountViewTitle.setText("Water to add (" + Units.getVolumeUnits() + ")"); infuseTemperatureView.setVisibility(View.VISIBLE); waterToGrainRatioView.setVisibility(View.VISIBLE); } // Update selected values. setValues(); } public void onNothingSelected(AdapterView<?> parentView) { } }; } @Override public boolean onCreateOptionsMenu(Menu menu) { //getMenuInflater().inflate(R.menu.activity_add_new_recipe, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: setResult(Constants.RESULT_CANCELED, new Intent()); finish(); return true; } return super.onOptionsItemSelected(item); } @Override public void onFinished() { Intent result = new Intent(); result.putExtra(Constants.KEY_MASH_STEP, step); setResult(Constants.RESULT_OK, result); finish(); } @Override public void acquireValues() throws Exception { super.acquireValues(); double stepTemp = Double.parseDouble(stepTempViewText.getText().toString()); double infuseTemp = Double.parseDouble(infuseTemperatureViewText.getText().toString()); double waterToGrainRatio = Double.parseDouble(waterToGrainRatioViewText.getText().toString()); step.setName(name); step.setDisplayInfuseAmount(amount); step.setStepTime(time); step.setType(type); step.setDisplayStepTemp(stepTemp); step.setDisplayWaterToGrainRatio(waterToGrainRatio); step.setDisplayInfuseTemp(infuseTemp); } @Override public void onCancelPressed() { setResult(Constants.RESULT_CANCELED, new Intent()); finish(); } @Override public void onDeletePressed() { } }
package com.opengamma.engine.value; /** * A collection of common/standard names for the Value Name property * for {@link ValueRequirement} instances. */ public interface ValueRequirementNames { // Market Data Names: public static final String MARKET_DATA_HEADER = "MarketDataHeader"; // Standard Analytic Models: public static final String DISCOUNT_CURVE = "DiscountCurve"; public static final String VOLATILITY_SURFACE = "VolatilitySurface"; public static final String FAIR_VALUE = "FairValue"; public static final String POSITION_FAIR_VALUE = "PositionFairValue"; public static final String VALUE_FAIR_VALUE = "ValueFairValue"; // Greeks Names: public static final String DELTA = "Delta"; public static final String DELTA_BLEED = "DeltaBleed"; public static final String STRIKE_DELTA = "StrikeDelta"; public static final String DRIFTLESS_DELTA = "DriftlessTheta"; public static final String GAMMA = "Gamma"; public static final String GAMMA_P = "GammaP"; public static final String STRIKE_GAMMA = "StrikeGamma"; public static final String GAMMA_BLEED = "GammaBleed"; public static final String GAMMA_P_BLEED = "GammaPBleed"; public static final String VEGA = "Vega"; public static final String VEGA_P = "VegaP"; public static final String VARIANCE_VEGA = "VarianceVega"; public static final String VEGA_BLEED = "VegaBleed"; public static final String THETA = "Theta"; public static final String RHO = "Rho"; public static final String CARRY_RHO = "CarryRho"; public static final String ZETA = "Zeta"; public static final String ZETA_BLEED = "ZetaBleed"; public static final String DZETA_DVOL = "dZeta_dVol"; public static final String ELASTICITY = "Elasticity"; public static final String PHI = "Phi"; public static final String ZOMMA = "Zomma"; public static final String ZOMMA_P = "ZommaP"; public static final String ULTIMA = "Ultima"; public static final String VARIANCE_ULTIMA = "VarianceUltima"; public static final String SPEED = "Speed"; public static final String SPEED_P = "SpeedP"; public static final String VANNA = "Vanna"; public static final String VARIANCE_VANNA = "VarianceVanna"; public static final String DVANNA_DVOL = "dVanna_dVol"; public static final String VOMMA = "Vomma"; public static final String VOMMA_P = "VommaP"; public static final String VARIANCE_VOMMA = "VarianceVomma"; // Greeks Names: public static final String POSITION_DELTA = "PositionDelta"; public static final String POSITION_DELTA_BLEED = "PositionDeltaBleed"; public static final String POSITION_STRIKE_DELTA = "PositionStrikeDelta"; public static final String POSITION_DRIFTLESS_DELTA = "PositionDriftlessTheta"; public static final String POSITION_GAMMA = "PositionGamma"; public static final String POSITION_GAMMA_P = "PositionGammaP"; public static final String POSITION_STRIKE_GAMMA = "PositionStrikeGamma"; public static final String POSITION_GAMMA_BLEED = "PositionGammaBleed"; public static final String POSITION_GAMMA_P_BLEED = "PositionGammaPBleed"; public static final String POSITION_VEGA = "PositionVega"; public static final String POSITION_VEGA_P = "PositionVegaP"; public static final String POSITION_VARIANCE_VEGA = "PositionVarianceVega"; public static final String POSITION_VEGA_BLEED = "PositionVegaBleed"; public static final String POSITION_THETA = "PositionTheta"; public static final String POSITION_RHO = "PositionRho"; public static final String POSITION_CARRY_RHO = "PositionCarryRho"; public static final String POSITION_ZETA = "PositionZeta"; public static final String POSITION_ZETA_BLEED = "PositionZetaBleed"; public static final String POSITION_DZETA_DVOL = "PositiondZeta_dVol"; public static final String POSITION_ELASTICITY = "PositionElasticity"; public static final String POSITION_PHI = "PositionPhi"; public static final String POSITION_ZOMMA = "PositionZomma"; public static final String POSITION_ZOMMA_P = "PositionZommaP"; public static final String POSITION_ULTIMA = "PositionUltima"; public static final String POSITION_VARIANCE_ULTIMA = "PositionVarianceUltima"; public static final String POSITION_SPEED = "PositionSpeed"; public static final String POSITION_SPEED_P = "PositionSpeedP"; public static final String POSITION_VANNA = "PositionVanna"; public static final String POSITION_VARIANCE_VANNA = "PositionVarianceVanna"; public static final String POSITION_DVANNA_DVOL = "PositiondVanna_dVol"; public static final String POSITION_VOMMA = "PositionVomma"; public static final String POSITION_VOMMA_P = "PositionVommaP"; public static final String POSITION_VARIANCE_VOMMA = "PositionVarianceVomma"; // Greeks Names: public static final String VALUE_DELTA = "ValueDelta"; public static final String VALUE_DELTA_BLEED = "ValueDeltaBleed"; public static final String VALUE_STRIKE_DELTA = "ValueStrikeDelta"; public static final String VALUE_DRIFTLESS_DELTA = "ValueDriftlessTheta"; public static final String VALUE_GAMMA = "ValueGamma"; public static final String VALUE_GAMMA_P = "ValueGammaP"; public static final String VALUE_STRIKE_GAMMA = "ValueStrikeGamma"; public static final String VALUE_GAMMA_BLEED = "ValueGammaBleed"; public static final String VALUE_GAMMA_P_BLEED = "ValueGammaPBleed"; public static final String VALUE_VEGA = "ValueVega"; public static final String VALUE_VEGA_P = "ValueVegaP"; public static final String VALUE_VARIANCE_VEGA = "ValueVarianceVega"; public static final String VALUE_VEGA_BLEED = "ValueVegaBleed"; public static final String VALUE_THETA = "ValueTheta"; public static final String VALUE_RHO = "ValueRho"; public static final String VALUE_CARRY_RHO = "ValueCarryRho"; public static final String VALUE_ZETA = "ValueZeta"; public static final String VALUE_ZETA_BLEED = "ValueZetaBleed"; public static final String VALUE_DZETA_DVOL = "ValuedZeta_dVol"; public static final String VALUE_ELASTICITY = "ValueElasticity"; public static final String VALUE_PHI = "ValuePhi"; public static final String VALUE_ZOMMA = "ValueZomma"; public static final String VALUE_ZOMMA_P = "ValueZommaP"; public static final String VALUE_ULTIMA = "ValueUltima"; public static final String VALUE_VARIANCE_ULTIMA = "ValueVarianceUltima"; public static final String VALUE_SPEED = "ValueSpeed"; public static final String VALUE_SPEED_P = "ValueSpeedP"; public static final String VALUE_VANNA = "ValueVanna"; public static final String VALUE_VARIANCE_VANNA = "ValueVarianceVanna"; public static final String VALUE_DVANNA_DVOL = "ValuedVanna_dVol"; public static final String VALUE_VOMMA = "ValueVomma"; public static final String VALUE_VOMMA_P = "ValueVommaP"; public static final String VALUE_VARIANCE_VOMMA = "ValueVarianceVomma"; // Generic Aggregates: public static final String SUM = "Sum"; public static final String MEDIAN = "Median"; // History public static final String PNL = "P&L"; public static final String PNL_SERIES = "P&L Series"; // Risk Aggregates: public static final String ISOLATED_VAR = "IsolatedVaR"; public static final String INCREMENTAL_VAR = "IncrementalVaR"; }
package com.sensei.indexing.api; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.DecimalFormat; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.apache.lucene.document.Field.Index; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.Field.TermVector; import com.browseengine.bobo.facets.data.PredefinedTermListFactory; import com.browseengine.bobo.facets.data.TermListFactory; import proj.zoie.api.indexing.AbstractZoieIndexableInterpreter; import proj.zoie.api.indexing.ZoieIndexable; public class DefaultSenseiInterpreter<V> extends AbstractZoieIndexableInterpreter<V> { private static Logger logger = Logger.getLogger(DefaultSenseiInterpreter.class); public static final Map<MetaType,String> DEFAULT_FORMAT_STRING_MAP = new HashMap<MetaType,String>(); public static final Map<Class,MetaType> CLASS_METATYPE_MAP = new HashMap<Class,MetaType>(); static{ DEFAULT_FORMAT_STRING_MAP.put(MetaType.Integer, "00000000000000000000"); DEFAULT_FORMAT_STRING_MAP.put(MetaType.Short, "00000"); DEFAULT_FORMAT_STRING_MAP.put(MetaType.Long, "0000000000000000000000000000000000000000"); DEFAULT_FORMAT_STRING_MAP.put(MetaType.Date, "yyyyMMdd-kk:mm"); DEFAULT_FORMAT_STRING_MAP.put(MetaType.Float, "00000000000000000000.00"); DEFAULT_FORMAT_STRING_MAP.put(MetaType.Double, "0000000000000000000000000000000000000000.00"); CLASS_METATYPE_MAP.put(String.class, MetaType.String); CLASS_METATYPE_MAP.put(int.class, MetaType.Integer); CLASS_METATYPE_MAP.put(Integer.class, MetaType.Integer); CLASS_METATYPE_MAP.put(short.class, MetaType.Short); CLASS_METATYPE_MAP.put(Short.class, MetaType.Short); CLASS_METATYPE_MAP.put(long.class, MetaType.Long); CLASS_METATYPE_MAP.put(Long.class, MetaType.Long); CLASS_METATYPE_MAP.put(float.class, MetaType.Float); CLASS_METATYPE_MAP.put(Float.class, MetaType.Float); CLASS_METATYPE_MAP.put(double.class, MetaType.Double); CLASS_METATYPE_MAP.put(Double.class, MetaType.Double); CLASS_METATYPE_MAP.put(char.class, MetaType.Char); CLASS_METATYPE_MAP.put(Character.class, MetaType.Char); CLASS_METATYPE_MAP.put(boolean.class, MetaType.Boolean); CLASS_METATYPE_MAP.put(Boolean.class, MetaType.Boolean); CLASS_METATYPE_MAP.put(Date.class, MetaType.Date); } public static <T> TermListFactory<T> getTermListFactory(Class<T> cls){ MetaType metaType = CLASS_METATYPE_MAP.get(cls); if (metaType == null){ throw new IllegalArgumentException("unsupported class: "+cls.getName()); } return new PredefinedTermListFactory<T>(cls,DEFAULT_FORMAT_STRING_MAP.get(metaType)); } static class IndexSpec{ Store store; Index index; TermVector tv; Field fld; } static class MetaFormatSpec{ Format formatter; Field fld; } private Class<V> _cls; final Map<String,IndexSpec> _textIndexingSpecMap; final Map<String,MetaFormatSpec> _metaFormatSpecMap; Field _uidField; Method _deleteChecker; Method _skipChecker; public DefaultSenseiInterpreter(Class<V> cls){ _cls = cls; _metaFormatSpecMap = new HashMap<String,MetaFormatSpec>(); _textIndexingSpecMap = new HashMap<String,IndexSpec>(); _uidField = null; Field[] fields = cls.getDeclaredFields(); for (Field f : fields){ if (f.isAnnotationPresent(Uid.class)){ if (_uidField != null){ throw new IllegalStateException("multiple uids defined in class: "+cls); } else{ Class fieldType = f.getType(); if (fieldType.isPrimitive()){ if (int.class.equals(fieldType) || short.class.equals(fieldType) || long.class.equals(fieldType)){ _uidField = f; _uidField.setAccessible(true); } } if (_uidField == null){ throw new IllegalStateException("uid field's type must be one of long, int or short"); } } } else if (f.isAnnotationPresent(Text.class)){ f.setAccessible(true); Text textAnnotation = f.getAnnotation(Text.class); String name=textAnnotation.name(); if ("".equals(name)){ name = f.getName(); } Index idx = textAnnotation.index(); Store store = textAnnotation.store(); TermVector tv = textAnnotation.termVector(); IndexSpec indexingSpec = new IndexSpec(); indexingSpec.store = store; indexingSpec.index = idx; indexingSpec.tv = tv; indexingSpec.fld = f; _textIndexingSpecMap.put(name, indexingSpec); } else if (f.isAnnotationPresent(Meta.class)){ f.setAccessible(true); Meta metaAnnotation = f.getAnnotation(Meta.class); String name=metaAnnotation.name(); if ("".equals(name)){ name = f.getName(); } MetaType metaType = metaAnnotation.type(); if (MetaType.Auto.equals(metaType)){ Class typeClass = f.getType(); if (Collection.class.isAssignableFrom(typeClass)){ metaType = MetaType.String; } else{ metaType = CLASS_METATYPE_MAP.get(typeClass); if (metaType==null){ metaType = MetaType.String; } } } String defaultFormatString = DEFAULT_FORMAT_STRING_MAP.get(metaType); String formatString = metaAnnotation.format(); if ("".equals(formatString)){ formatString = defaultFormatString; } MetaFormatSpec formatSpec = new MetaFormatSpec(); _metaFormatSpecMap.put(name, formatSpec); formatSpec.fld = f; if (defaultFormatString!=null){ if (MetaType.Date == metaType){ formatSpec.formatter = new SimpleDateFormat(formatString); } else{ formatSpec.formatter = new DecimalFormat(formatString); } } } } Method[] methods = cls.getDeclaredMethods(); for (Method method : methods){ if (method.isAnnotationPresent(DeleteChecker.class)){ if (_deleteChecker==null){ method.setAccessible(true); _deleteChecker = method; } else{ throw new IllegalStateException("more than 1 delete checker defined in class: "+cls); } } else if (method.isAnnotationPresent(SkipChecker.class)){ if (_skipChecker==null){ method.setAccessible(true); _skipChecker = method; } else{ throw new IllegalStateException("more than 1 skip checker defined in class: "+cls); } } } if (_uidField == null){ throw new IllegalStateException(cls + " does not have uid defined"); } } @Override public String toString(){ StringBuilder buf = new StringBuilder(); buf.append("data class name: ").append(_cls.getName()); buf.append("\n_uid field: ").append(_uidField.getName()); buf.append("\ndelete checker: ").append(_deleteChecker==null?"none":_deleteChecker.getName()); buf.append("\nskip checker: ").append(_skipChecker==null?"none":_skipChecker.getName()); buf.append("\ntext fields: "); if (_textIndexingSpecMap.size()==0){ buf.append("none"); } else{ boolean first = true; Set<String> tfNames = _textIndexingSpecMap.keySet(); for (String name : tfNames){ if (!first){ buf.append(","); } else{ first=false; } buf.append(name); } } buf.append("\nmeta fields: "); if (_metaFormatSpecMap.size()==0){ buf.append("none"); } else{ boolean first = true; Set<String> tfNames = _metaFormatSpecMap.keySet(); for (String tf : tfNames){ if (!first){ buf.append(","); } else{ first=false; } buf.append(tf); } } return buf.toString(); } @Override public ZoieIndexable convertAndInterpret(V obj) { return new DefaultSenseiZoieIndexable<V>(obj,this); } }
package org.dataportal; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Iterator; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.dataportal.controllers.JPADownloadController; import org.dataportal.controllers.JPAUserController; import org.dataportal.csw.CSWCatalog; import org.dataportal.csw.CSWGetRecordById; import org.dataportal.csw.CSWNamespaceContext; import org.dataportal.model.Download; import org.dataportal.model.DownloadItem; import org.dataportal.model.User; import org.dataportal.utils.Utils; import org.w3c.dom.Document; import org.w3c.dom.NodeList; /** * Class to control the files download. Use a Cached Thread Pool to download * files concurrently * * @author Micho Garcia * */ public class DownloadController { private static Logger logger = Logger.getLogger(DownloadController.class); private String tempDir; private static CSWCatalog catalogo; private User user = null; private JPAUserController userJPAController = null; private JPADownloadController downloadJPAController = null; /** * Constructor. Reads tempDir from properties file. */ public DownloadController() { this.tempDir = Config.get("temp.dir"); String url = Config.get("csw.url"); try { catalogo = new CSWCatalog(url); } catch (MalformedURLException e) { logger.error(e.getMessage()); } } /** * Create the pathfile with the information extracted from properties and * create the directory if not exits * * @param userName * User name from session (String) */ public String createPathFile(String userName) { String pathFile = this.tempDir + "/" + userName; File personalDirectory = new File(pathFile); boolean exits = personalDirectory.exists(); if (!exits) { boolean createDir = personalDirectory.mkdir(); if (!createDir) pathFile = ""; } return pathFile; } /** * Extract id's from client XML request. Checks whether id's are in the * server using a GetRecordById request. If checking is OK, extract the * URL's from client XML request and sends to DownloadController to download * files * * @param InputStream * with the XML sends by client */ public String askgn2download(InputStream isRequestXML, String anUserName) { StringBuffer response = new StringBuffer(); try { DocumentBuilderFactory dbFactoria = DocumentBuilderFactory .newInstance(); DocumentBuilder dbBuilder = dbFactoria.newDocumentBuilder(); Document downloadXML = (Document) dbBuilder.parse(isRequestXML); CSWNamespaceContext ctx = new CSWNamespaceContext(); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); xpath.setNamespaceContext(ctx); String variablesExpr = "//id/child::node()"; NodeList idNodeList = (NodeList) xpath.evaluate(variablesExpr, downloadXML, XPathConstants.NODESET); ArrayList<String> requestIdes = Utils .nodeList2ArrayList(idNodeList); CSWGetRecordById getRecordById = new CSWGetRecordById("brief"); String getRecordByIdQuery = getRecordById.createQuery(requestIdes); InputStream isGetRecordByIdResponse = catalogo .sendCatalogRequest(getRecordByIdQuery); ArrayList<String> responseIdes = recordIdes(isGetRecordByIdResponse); ArrayList<String> noIdsResponse = Utils.compare2Arraylist( requestIdes, responseIdes); if (noIdsResponse.size() != 0) { logger.info("ID'S NO ENCONTRADOS: " + String.valueOf(noIdsResponse.size()) + " -> " + StringUtils.join(noIdsResponse, " : ")); QueryError error = new QueryError(); // TODO change error code error.setCode("ides.no.encontrados"); error.setMessage(StringUtils.join(noIdsResponse, " : ")); response.append(error.getErrorMessage()); } else { xpath.reset(); xpath.setNamespaceContext(ctx); String urlsExpr = "//data_link/child::node()"; NodeList urlNodeList = (NodeList) xpath.evaluate(urlsExpr, downloadXML, XPathConstants.NODESET); ArrayList<String> urlsRequest = Utils .nodeList2ArrayList(urlNodeList); String userName = anUserName; User anUser = new User(userName); userJPAController = new JPAUserController(); user = userJPAController.exits(anUser); if (user != null) { String resultDownload = downloadDatasets(urlsRequest, userName); // datos insertDownload(user, resultDownload, urlsRequest); response.append(resultDownload); } } } catch (Exception e) { logger.error(e.getMessage()); QueryError error = new QueryError(); error.setCode("error.ejecucion.servidor"); error.setMessage(e.getMessage()); response.append(error.getErrorMessage()); e.printStackTrace(); } logger.debug("RESPONSE CONTROLLER: " + response.toString()); return response.toString(); } /** * * Insert download into RDBMS * * @param user * User * @param fileName * String with filename * @param urlsRequest * url request array */ private void insertDownload(User user, String fileName, ArrayList<String> urlsRequest) { String DOI = getDOI(); Timestamp timeStamp = Utils.extractDateSystemTimeStamp(); Download download = new Download(DOI, fileName, timeStamp, user); ArrayList<DownloadItem> items = new ArrayList<DownloadItem>(); for (String url : urlsRequest) { DownloadItem item = new DownloadItem(url); items.add(item); } downloadJPAController = new JPADownloadController(); downloadJPAController.insertItems(download, items); } /** * * Method to obtain DOI * * @return String with DOI */ private String getDOI() { // TODO todo String DOI = "100/1000.434"; return DOI; } /** * * Extract an array with id's from GetRecordByID response from CSW Server * * @param InputStream * with the response sends by server * @return ArrayList with id's from response */ private ArrayList<String> recordIdes(InputStream isGetRecordByIdResponse) { NodeList ides = null; ArrayList<String> arrayIdes = new ArrayList<String>(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document xmlGetRecordsById = (Document) dBuilder .parse(isGetRecordByIdResponse); // TODO Extraer esto a una clase CSWNamespaceContext ctx = new CSWNamespaceContext(); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); xpath.setNamespaceContext(ctx); String recordsExpr = "//BriefRecord/identifier/child::node()"; ides = (NodeList) xpath.evaluate(recordsExpr, xmlGetRecordsById, XPathConstants.NODESET); // TODO EOF if (ides.getLength() != 0) arrayIdes = Utils.nodeList2ArrayList(ides); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } logger.debug("RECORDS: " + String.valueOf(arrayIdes.size())); return arrayIdes; } /** * Method to download files from a url's array. * * @param urlsRequest * ArrayList with url's (ArrayList) * @return Message * @throws Exception */ private String downloadDatasets(ArrayList<String> urlsRequest, String userName) throws Exception { // TODO cambiar esto por una clase mensaje de dataportal String response = ""; String pathFile = createPathFile(userName); if (pathFile.equals("")) { // TODO cambiar por clase error response = "No se ha podido crear el directorio"; logger.error("No se ha podido crear el directorio"); } else { int urls = urlsRequest.size(); ExecutorService threadsPool = Executors.newCachedThreadPool(); int future = 0; Future futures[] = new Future[urls]; for (String url : urlsRequest) { String name = StringUtils.substringAfterLast(url, "/"); DownloadCallable hiloDescarga = new DownloadCallable(url, name, pathFile); futures[future] = threadsPool.submit(hiloDescarga); future += 1; Thread.sleep(2000); } for (int i = 0; i < urls; i++) { String tarea = (String) futures[i].get(); logger.info("DOWNLOADING FINISH: " + tarea); } String nameFile = userName + "_" + Utils.extractDateSystem(); String filePathName = compressFiles(pathFile, nameFile); // TODO cambiar mensaje logger.debug("FILE to download: " + filePathName); response = StringUtils.substringAfterLast(filePathName, "/"); } return response; } /** * Returns an inputStream to download the compressed file * * @param fileName * Name of compressed file * @param userName * User name that generated the file * @return * @throws FileNotFoundException */ public InputStream getFileContents(String fileName, String userName) throws FileNotFoundException { File file = new File(this.tempDir + "/" + userName + "/" + fileName); return new FileInputStream(file); } /** * Returns the downloadable file size * * @param fileName * Name of compressed file * @param userName * User name that generated the file * @return * @throws FileNotFoundException */ public long getFileSize(String fileName, String userName) throws FileNotFoundException { File file = new File(this.tempDir + "/" + userName + "/" + fileName); if (file.exists() && file.isFile()) return file.length(); else return 0; } /** * * Compress in tar format files in directory * * @param pathDir * directory path (String) * @param nameFile * archive name (String) * @throws IOException */ private String compressFiles(String pathDir, String nameFile) throws IOException { String filePathName = pathDir + "/" + nameFile + ".zip"; OutputStream os = new FileOutputStream(filePathName); ZipArchiveOutputStream zipOs = new ZipArchiveOutputStream(os); File directory = new File(pathDir); String extensions[] = { "nc" }; @SuppressWarnings("unchecked") Iterator<File> itFiles = FileUtils.iterateFiles(directory, extensions, false); while (itFiles.hasNext()) { File fl = itFiles.next(); ArchiveEntry archFl = zipOs.createArchiveEntry(fl, fl.getName()); zipOs.putArchiveEntry(archFl); zipOs.write(FileUtils.readFileToByteArray(fl)); zipOs.flush(); zipOs.closeArchiveEntry(); } zipOs.finish(); zipOs.close(); os.close(); return filePathName; } }
package com.thomaspunt.flexbox.guibuilder; import com.thomaspunt.flexbox.BoxSizes; import com.thomaspunt.flexbox.BoxTypes; import com.thomaspunt.flexbox.BoxOrder; import com.thomaspunt.flexbox.BoxPrices; import com.thomaspunt.flexbox.Order; import org.json.JSONException; import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashMap; import javax.swing.JPanel; import javax.swing.JScrollPane; import java.io.IOException; import javax.swing.BorderFactory; import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.LayoutStyle; /** * Contains all of the ordering tab logic, such as adding new order windows, validating * the order submission, handling order submissions on success, and updating the * OrdersTabGUI class to display the new order. * * @author Student ID: 696944 * @version %I%, %G% */ public class OrderingTabGUI { /** * Holds the ordering panel object so that it can be updated throughout the class * (such as when new a new order window is added or removed). */ private final JPanel orderingPanel = new JPanel(); /** * Holds the order boxes in a way that enables the application to track the * order boxes when there are multiple ordering panels on the screen. * <p> * This enables the application to go through all ordering boxes, validate them, * and let the end user know (if any) which ordering boxes have validation issues. */ private final HashMap<Integer, OrderBoxFields> orderingBoxes = new HashMap<>(); /** * This is used in conjunction with the orderingBoxes instance variable, where * the value of this is used as the key in the hash map so that the correct ordering * box can be removed by the end user. */ private int boxNumber = 0; /** * This variable limits the number of ordering boxes allowed on-screen at once. * This therefore sets the maximum limit of different ordering boxes that can * be placed in a single order. */ private final int maxOrderBoxes = 5; /** * This contains the business logic for the valid box types in the ordering system. * <p> * It is used to collectively validate all of the box order fields to ensure that * they match a valid box type in the ordering system. */ private final BoxTypes boxTypes; /** * Holds the limitation values for the dimensions of a box (width, height, * and length). */ private final BoxSizes boxSizes; /** * Holds the box prices calculation logic to get a total price of the order. */ private final BoxPrices boxPrices; /** * Holds the box orders from each ordering window. * <p> * It is used to collate all * box orders during validation of the box orders, and is either flushed on failure * (such as an invalid value being entered), or kept on success to be displayed on * the orders tab panel. */ private final ArrayList<BoxOrder> boxOrders = new ArrayList<>(); /** * Holds the outer panel JPanel object of the ordering tab, where components * are set to a layout object which is attached to this object. */ private final JPanel outerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); /** * Holds the outer panel for the ordering tab, enabling scrolling of the * content in the ordering tab. This is required because of the ability to add * in new ordering windows. */ private final JScrollPane orderingTabGUI = new JScrollPane(outerPanel); /** * Holds an instance of the FlexBoxTabsGUI to enable the application to * change the tab-focus when a successful order has submitted. */ private final FlexBoxTabbedPaneGUI flexBoxTabs; /** * Instantiate the required classes and create the ordering tab. * * @param flexBoxTabbedPane The flex box JTabbedPane instance. * @throws FileNotFoundException Thrown if the box prices config file cannot be found. * @throws IOException Thrown if the BufferedReader in BoxSizesConfig * encounters an I/O problem when reading the next line. * @throws JSONException Thrown if the JSON file has an invalid syntax or if it * cannot be parsed properly. */ public OrderingTabGUI(FlexBoxTabbedPaneGUI flexBoxTabbedPane) throws FileNotFoundException , IOException , JSONException { boxTypes = new BoxTypes(); boxSizes = new BoxSizes(); boxPrices = new BoxPrices(); this.flexBoxTabs = flexBoxTabbedPane; createOrderingTab(); } /** * Gets the ordering tab so that it can be added to the flex box JTabbedPane in * the FlexBoxTabbedPaneGUI class. * * @return The ordering tab content as a single JScrollPane component. */ public JScrollPane getOrderingTab() { return orderingTabGUI; } /** * Creates the ordering tab by building the header and footer components, and * then collates them in a GroupLayout object which is then set as the layout * for the outerPanel instance variable. */ private void createOrderingTab() { GroupLayout outerLayout = new GroupLayout(outerPanel); /* Header Layout */ JPanel headerPanel = new JPanel(); JLabel panelText = new JLabel("Place a new order:"); headerPanel.add(panelText); headerPanel.setMaximumSize(headerPanel.getPreferredSize()); collateOrderingPanels(); /* Footer Layout */ JPanel footerPanel = new JPanel(); GroupLayout footerLayout = new GroupLayout(footerPanel); JButton addOrderButton = new JButton("Add Order Box"); addOrderButton.setActionCommand("addOrderBox"); addOrderButton.addActionListener(new OrderingTabGUI.ButtonClickListener()); JButton submitButton = new JButton("Submit Order"); submitButton.setActionCommand("submitOrder"); submitButton.addActionListener(new OrderingTabGUI.ButtonClickListener()); footerLayout.setHorizontalGroup(footerLayout.createSequentialGroup() .addComponent(addOrderButton) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED , GroupLayout.DEFAULT_SIZE , Short.MAX_VALUE) .addComponent(submitButton) ); footerLayout.setVerticalGroup(footerLayout.createParallelGroup() .addComponent(addOrderButton) .addComponent(submitButton) ); footerPanel.setLayout(footerLayout); /* Collate the header, body, and footer */ outerLayout.setHorizontalGroup(outerLayout.createParallelGroup() .addComponent(headerPanel) .addComponent(orderingPanel) .addComponent(footerPanel) ); outerLayout.setVerticalGroup(outerLayout.createSequentialGroup() .addComponent(headerPanel) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED , GroupLayout.DEFAULT_SIZE , 15) .addComponent(orderingPanel) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED , GroupLayout.DEFAULT_SIZE , 15) .addComponent(footerPanel) ); outerPanel.setLayout(outerLayout); } /** * Handles the ordering windows logic by either creating a new order window * if one does not exist (such as the last ordering window just being removed), * or adds all existing ordering windows to the orderingPanel instance variable. */ private void collateOrderingPanels() { if(orderingBoxes.isEmpty()) { addOrderWindow(); return; } orderingPanel.removeAll(); for(Integer orderBoxN : orderingBoxes.keySet()) orderingPanel.add(orderingBoxes.get(orderBoxN).getOrderPanel()); } /** * Creates a new order window to be added to the orderingPanel instance variable. */ private void addOrderWindow() { /* Body Layout */ JPanel bodyPanel = new JPanel(); bodyPanel.setBorder(BorderFactory.createTitledBorder("Box Information")); GroupLayout bodyLayout = new GroupLayout(bodyPanel); bodyLayout.setAutoCreateGaps(false); bodyLayout.setAutoCreateContainerGaps(true); /* Top Body Layout */ JPanel topBodyPanel = new JPanel(); GroupLayout topBodyLayout = new GroupLayout(topBodyPanel); topBodyLayout.setAutoCreateGaps(false); topBodyLayout.setAutoCreateContainerGaps(true); JLabel bwhText = new JLabel("Size (cm):"); JLabel bwText = new JLabel("Width:"); JPanel bwField = new JPanel(); JTextField bwTextField = new JTextField(3); bwField.add(bwTextField); bwField.setMaximumSize(bwField.getPreferredSize()); JLabel bhText = new JLabel("Height:"); JPanel bhField = new JPanel(); JTextField bhTextField = new JTextField(3); bhField.add(bhTextField); bhField.setMaximumSize(bhField.getPreferredSize()); JLabel blText = new JLabel("Lenght:"); JPanel blField = new JPanel(); JTextField blTextField = new JTextField(3); blField.add(blTextField); blField.setMaximumSize(blField.getPreferredSize()); topBodyLayout.setHorizontalGroup(topBodyLayout.createSequentialGroup() .addComponent(bwhText) .addGroup(topBodyLayout.createParallelGroup() .addComponent(bwText) .addComponent(bhText) .addComponent(blText) ) .addGroup(topBodyLayout.createParallelGroup() .addComponent(bwField) .addComponent(bhField) .addComponent(blField) ) ); topBodyLayout.setVerticalGroup(topBodyLayout.createSequentialGroup() .addComponent(bwhText) .addGroup(topBodyLayout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(bwText) .addComponent(bwField) ) .addGroup(topBodyLayout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(bhText) .addComponent(bhField) ) .addGroup(topBodyLayout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(blText) .addComponent(blField) ) ); topBodyPanel.setLayout(topBodyLayout); /* Middle Body Layout */ JPanel middleBodyPanel = new JPanel(); GroupLayout middleBodyLayout = new GroupLayout(middleBodyPanel); middleBodyLayout.setAutoCreateGaps(false); JLabel bgText = new JLabel("Box Grade:"); JPanel bgField = new JPanel(); JTextField bgTextField = new JTextField(10); bgField.add(bgTextField); bgField.setMaximumSize(bgField.getPreferredSize()); JLabel cpText = new JLabel("Colour Print:"); JPanel cpField = new JPanel(); JTextField cpTextField = new JTextField(10); cpField.add(cpTextField); cpField.setMaximumSize(cpField.getPreferredSize()); String[] choices = { "Yes", "No" }; JLabel rbText = new JLabel("Reinforced Bottom:"); JPanel rbField = new JPanel(); JComboBox<String> rbComboBox = new JComboBox<>(choices); rbComboBox.setSelectedIndex(1); rbField.add(rbComboBox); rbField.setMaximumSize(rbField.getPreferredSize()); JLabel rcText = new JLabel("Reinforced Corners:"); JPanel rcField = new JPanel(); JComboBox<String> rcComboBox = new JComboBox<>(choices); rcComboBox.setSelectedIndex(1); rcField.add(rcComboBox); rcField.setMaximumSize(rcField.getPreferredSize()); JLabel stText = new JLabel("Sealable Tops:"); JPanel stField = new JPanel(); JComboBox<String> stComboBox = new JComboBox<>(choices); stComboBox.setSelectedIndex(1); stField.add(stComboBox); stField.setMaximumSize(stField.getPreferredSize()); JLabel qText = new JLabel("Quantity:"); JPanel qField = new JPanel(); JTextField qTextField = new JTextField("1", 4); qField.add(qTextField); qField.setMaximumSize(qField.getPreferredSize()); middleBodyLayout.setHorizontalGroup(middleBodyLayout.createSequentialGroup() .addGroup(middleBodyLayout.createParallelGroup() .addComponent(bgText) .addComponent(cpText) .addComponent(rbText) .addComponent(rcText) .addComponent(stText) .addComponent(qText) ) .addGroup(middleBodyLayout.createParallelGroup() .addComponent(bgField) .addComponent(cpField) .addComponent(rbField) .addComponent(rcField) .addComponent(stField) .addComponent(qField) ) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED , GroupLayout.DEFAULT_SIZE , Short.MAX_VALUE) ); middleBodyLayout.setVerticalGroup(middleBodyLayout.createSequentialGroup() .addGroup(middleBodyLayout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(bgText) .addComponent(bgField) ) .addGroup(middleBodyLayout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(cpText) .addComponent(cpField) ) .addGroup(middleBodyLayout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(rbText) .addComponent(rbField) ) .addGroup(middleBodyLayout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(rcText) .addComponent(rcField) ) .addGroup(middleBodyLayout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(stText) .addComponent(stField) ) .addGroup(middleBodyLayout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(qText) .addComponent(qField) ) ); middleBodyPanel.setLayout(middleBodyLayout); /* Bottom Body Layout */ JPanel bottomBodyPanel = new JPanel(); GroupLayout bottomBodyLayout = new GroupLayout(bottomBodyPanel); bottomBodyLayout.setAutoCreateGaps(false); bottomBodyLayout.setAutoCreateContainerGaps(true); JLabel statusTextField = new JLabel(" "); statusTextField.setForeground(Color.red); bottomBodyLayout.setHorizontalGroup(bottomBodyLayout.createSequentialGroup() .addComponent(statusTextField) ); bottomBodyLayout.setVerticalGroup(bottomBodyLayout.createParallelGroup() .addComponent(statusTextField) ); bottomBodyPanel.setLayout(bottomBodyLayout); JPanel removeButtonPanel = new JPanel(); removeButtonPanel.setLayout(new BorderLayout(0, 0)); JButton removeButton = new JButton("Remove Order Box"); removeButton.setActionCommand("removeComponent_" + ++boxNumber); removeButton.addActionListener(new OrderingTabGUI.ButtonClickListener()); removeButton.setBackground(Color.red); removeButton.setOpaque(true); removeButton.setBorderPainted(false); removeButtonPanel.add(removeButton); /* Collate the three layouts */ bodyLayout.setHorizontalGroup(bodyLayout.createParallelGroup() .addComponent(topBodyPanel) .addComponent(middleBodyPanel) .addComponent(bottomBodyPanel) .addComponent(removeButtonPanel) ); bodyLayout.setVerticalGroup(bodyLayout.createSequentialGroup() .addComponent(topBodyPanel) .addComponent(middleBodyPanel) .addComponent(bottomBodyPanel) .addComponent(removeButtonPanel) ); bodyPanel.setLayout(bodyLayout); orderingBoxes.put(boxNumber , new OrderingTabGUI.OrderBoxFields(bodyPanel , bwTextField , bhTextField , blTextField , bgTextField , cpTextField , rbComboBox , rcComboBox , stComboBox , qTextField , statusTextField)); collateOrderingPanels(); } /** * Checks to see if all ordering windows contain valid information and order * box types. * * @return Whether the order as a whole was valid. */ private boolean allValidOrders() { boolean validOrders = true; for(Integer orderBoxN : orderingBoxes.keySet()) { OrderBoxFields ob = orderingBoxes.get(orderBoxN); boolean errorOccurred = true; try { int boxWidth = Integer.parseInt(ob.getBoxWidth()); int boxHeight = Integer.parseInt(ob.getBoxHeight()); int boxLength = Integer.parseInt(ob.getBoxLength()); int boxGrade = Integer.parseInt(ob.getBoxGrade()); int boxColourPrint = Integer.parseInt(ob.getBoxColourPrint()); int boxQuantity = Integer.parseInt(ob.getBoxQuantity()); int boxType = boxTypes.checkBoxType(boxGrade , boxColourPrint , ob.hasReinforcedBottom() , ob.hasReinforcedCorners()); if(!boxSizes.isValidWidth(boxWidth)) { ob.setStatusText("Invalid box width (from " + boxSizes.getBoxSizes().getMinWidth() + "cm to " + boxSizes.getBoxSizes().getMaxWidth() + "cm)."); validOrders = false; }else if(!boxSizes.isValidHeight(boxHeight)) { ob.setStatusText("Invalid box height (from " + boxSizes.getBoxSizes().getMinHeight() + "cm to " + boxSizes.getBoxSizes().getMaxHeight() + "cm)."); validOrders = false; }else if(!boxSizes.isValidLength(boxLength)) { ob.setStatusText("Invalid box length (from " + boxSizes.getBoxSizes().getMinLength() + "cm to " + boxSizes.getBoxSizes().getMaxLength() + "cm)."); validOrders = false; }else if(boxQuantity < 1) { ob.setStatusText("Invalid box quantity (must be greater than 0)."); validOrders = false; }else if (boxType == -1) { ob.setStatusText("The box type entered is invalid."); validOrders = false; }else{ errorOccurred = false; boxOrders.add(new BoxOrder(boxType , boxWidth , boxHeight , boxLength , boxGrade , boxColourPrint , ob.hasReinforcedBottom() , ob.hasReinforcedCorners() , ob.hasSealableTops() , boxQuantity)); } }catch(NumberFormatException e) { ob.setStatusText("Invalid input."); validOrders = false; } if(!errorOccurred) ob.setStatusText(" "); } if(!validOrders) boxOrders.clear(); return validOrders; } /** * Submits the order by calculating the price and attaching it to the order, * and then updating the orders tab to display the new order. It then resets * all instance variables in this class that are to do with placing an order * to ensure that the ordering page is ready to take new order submissions. */ private void submitOrders() { Order order = new Order(boxOrders); order.setOrderPrice(boxPrices.calculateOrderPrice(order)); flexBoxTabs.getOrdersTab().displayOrder(order); flexBoxTabs.getFlexBoxFrame().repaint(); flexBoxTabs.getTabbedPane().setSelectedIndex(1); boxNumber = 0; orderingBoxes.clear(); orderingPanel.removeAll(); collateOrderingPanels(); flexBoxTabs.getFlexBoxFrame().repaint(); boxOrders.clear(); } /** * This class is used to handle the action events when adding or removing order * windows, as well as submitting an order. */ private class ButtonClickListener implements ActionListener { /** * Handle the event depending upon the action command used. * <p> * This method will be invoked when an event action has been triggered. * * @param e The event that was triggered. */ @Override public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); switch(actionCommand) { case "addOrderBox": if(orderingBoxes.size() < maxOrderBoxes) { addOrderWindow(); flexBoxTabs.getFlexBoxFrame().repaint(); } break; case "submitOrder": if(allValidOrders()) submitOrders(); break; default: if(actionCommand.matches("removeComponent_[0-9]+")) { String[] parts = actionCommand.split("_"); orderingBoxes.remove(Integer.parseInt(parts[1])); collateOrderingPanels(); flexBoxTabs.getFlexBoxFrame().repaint(); } } } } /** * This class is required to hold the ordering window fields for each individual * box order. It also stores the order panel object which is used when collating * all order panels, along with a status field to display an error message if * validation fails. */ private class OrderBoxFields { /** * Stores the order window itself to be used when collating all ordering windows. */ private final JPanel orderPanel; /** * Stores the entered value for the box width. */ private final JTextField bwTextField; /** * Stores the entered value for the box height. */ private final JTextField bhTextField; /** * Stores the entered value for the box length. */ private final JTextField blTextField; /** * Stores the entered value for the box grade. */ private final JTextField bgTextField; /** * Stores the entered value for the box colour print. */ private final JTextField cpTextField; /** * Stores the selected value for whether the box has a reinforced bottom. */ private final JComboBox<String> rbComboBox; /** * Stores the selected value for whether the box has reinforced corners. */ private final JComboBox<String> rcComboBox; /** * Stores the selected value for whether the box has a sealable top. */ private final JComboBox<String> stComboBox; /** * Stores the entered value for the box quantity. */ private final JTextField qTextField; /** * Stores the status text field. */ private final JLabel statusTextField; /** * Assign values to all instance variables. * * @param orderPanel The order window for the box. * @param bwTextField The box width * @param bhTextField The box height. * @param blTextField The box length. * @param bgTextField The card grade of the box. * @param cpTextField The colour print of the box. * @param rbComboBox Whether the box has a reinforced bottom. * @param rcComboBox Whether the box has reinforced corners. * @param stComboBox Whether the box has sealable tops. * @param qTextField The box quantity. * @param statusTextField The error message (if there is one). */ public OrderBoxFields(JPanel orderPanel , JTextField bwTextField , JTextField bhTextField , JTextField blTextField , JTextField bgTextField , JTextField cpTextField , JComboBox<String> rbComboBox , JComboBox<String> rcComboBox , JComboBox<String> stComboBox , JTextField qTextField , JLabel statusTextField) { this.orderPanel = orderPanel; this.bwTextField = bwTextField; this.bhTextField = bhTextField; this.blTextField = blTextField; this.bgTextField = bgTextField; this.cpTextField = cpTextField; this.rbComboBox = rbComboBox; this.rcComboBox = rcComboBox; this.stComboBox = stComboBox; this.qTextField = qTextField; this.statusTextField = statusTextField; } /** * Gets the order window for the box. * * @return The order window. */ public JPanel getOrderPanel() { return orderPanel; } /** * Gets the box width. * * @return The width of the box. */ public String getBoxWidth() { return bwTextField.getText(); } /** * Gets the box height. * * @return The height of the box. */ public String getBoxHeight() { return bhTextField.getText(); } /** * Gets the box length. * * @return The length of the box. */ public String getBoxLength() { return blTextField.getText(); } /** * Gets the grade of card for the box. * * @return The card grade of the box. */ public String getBoxGrade() { return bgTextField.getText(); } /** * Gets the box colour print. * * @return The colour print of the box. */ public String getBoxColourPrint() { return cpTextField.getText(); } /** * Get whether the box has a reinforced bottom. * * @return Whether the box has a reinforced bottom. */ public boolean hasReinforcedBottom() { return rbComboBox.getSelectedItem().toString().equals("Yes"); } /** * Get whether the box has reinforced corners. * * @return Whether the box has reinforced corners. */ public boolean hasReinforcedCorners() { return rcComboBox.getSelectedItem().toString().equals("Yes"); } /** * Get whether the box has sealable tops. * * @return Whether the box has sealable tops. */ public boolean hasSealableTops() { return stComboBox.getSelectedItem().toString().equals("Yes"); } /** * Gets the box quantity. * * @return The quantity of the box. */ public String getBoxQuantity() { return qTextField.getText(); } /** * Gets the box status text. * * @return The status text of the box. */ public String getStatusText() { return statusTextField.getText(); } /** * Sets the status text of a box - either to an empty string to show the * box is valid, or to an error message. * * @param text The error message to display. */ public void setStatusText(String text) { statusTextField.setText(text); } } }
package net.mostlyoriginal.api.utils; /** * Time conversion helper. * * @author Daan van Yperen */ public class Duration { private Duration() {} /** * Convert seconds to default time unit for artemis-odb. * @return seconds */ public static float seconds(float seconds) { return seconds; } /** * Convert milliseconds to default time unit for artemis-odb. * @return seconds */ public static float ms(float ms) { return ms / 1000; } /** * Convert milliseconds to default time unit for artemis-odb. * @return seconds. */ public static float milliseconds(float ms) { return ms / 1000; } }
package mathsquared.resultswizard2; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; /** * @author MathSquared * */ public class ArrayUtils { /** * Creates a deep copy of a multi-dimensional array, copying all sub-arrays of the array (but not the elements themselves). * * @param toCopy the multi-dimensional array to copy * @return a copy of the array, or null if <code>toCopy</code> is null */ // HASHTAG UNCHECKED CASTS @SuppressWarnings("unchecked") public static <T> T[][] deepCopyOf (T[][] toCopy) { // Null handling; null is a copy of null if (toCopy == null) { return null; } // Instantiate a generic array Class<T[]> type = (Class<T[]>) toCopy.getClass().getComponentType(); T[][] copied = (T[][]) Array.newInstance(type, toCopy.length); // If a two-dimensional array, use Arrays.copyOf; otherwise, recurse if (!(toCopy instanceof Object[][][])) { // not 3-D; by parameter, must be 2-D for (int i = 0; i < toCopy.length; i++) { copied[i] = Arrays.copyOf(toCopy[i], toCopy[i].length); } } else { // 3-D or above for (int i = 0; i < toCopy.length; i++) { copied[i] = (T[]) deepCopyOf((Object[][]) toCopy[i]); } } return copied; } /** * Checks that all ties are represented validly. * * <p> * For every sub-array of a result array (which represents a tie), if the sub-array contains more than one element, places should be skipped in accordance. This corresponds to normal practice; for example, if two people tie for first place, the next place awarded is third place (and the second-place array should be null or empty). * </p> * * <p> * For a parameter of null, this method returns true. * </p> * * @param results the results array whose integrity to check * @return true if the array correctly skips places for ties; false otherwise */ public static boolean checkTies (Object[][] results) { // An empty array is structured correctly, since there are no unstructured elements if (results == null) { return true; } /* * Implementation: * * The algorithm keeps track of the amount of results that have been seen so far, where a "result" is one String. * * For each sub-array of the input array, the algorithm adds subArr.length - 1 to an internal tracking variable. * * If this variable is non-zero, it means that there was a tie previously, and the next few places should be skipped with null. * * If this variable is zero, it means that there have been no ties--or all were accounted for--so the next array should have elements. */ int num = 0; // tracking variable mentioned above for (Object[] x : results) { // num never decreases by more than 1 each turn, and can never decrease if it is 0, so check for num < 0 is unnecessary assert (num >= 0); if (num == 0 && (x == null || x.length == 0)) { return false; } if (num > 0 && x != null && x.length != 0) { return false; } num += (x == null) ? -1 : x.length - 1; } // no problems; num does not need to be 0 in case of ties for last place return true; } /** * Checks that the structure of two arrays is the same. That is: * * <ul> * <li><code>a.length == b.length</code></li> * <li>For any integer <code>i</code>, <code>a[i]</code> is an array iff <code>b[i]</code> is an array</li> * <li>For any integer <code>i</code>, if <code>a[i]</code> and <code>b[i]</code> are arrays, the first two statements are recursively valid for them as well</li> * </ul> * * <p> * If one of the arrays is null, this method returns true iff both are null. * </p> * * @param a the first array to check * @param b the second array to check * @return true if the arrays have the same structure as defined above, false otherwise */ public static boolean checkStructureSame (Object[] a, Object[] b) { // Null handling; two nulls are structured the same, but a null and non-null are not if (a == null && b == null) { return true; } if (a == null ^ b == null) { return false; } if (a.length != b.length) return false; for (int i = 0; i < a.length; i++) { if (a[i] instanceof Object[] && b[i] instanceof Object[]) { if (!checkStructureSame((Object[]) a[i], (Object[]) b[i])) { return false; } } // Not generic, so no enforcement on same type...might have one be an array of arrays and the other not be if (a[i] instanceof Object[] ^ b[i] instanceof Object[]) { return false; } } // no problems return true; } /** * Returns an array of the lengths of the sub-arrays of a given array. * * <p> * That is, returns an array <code>ret</code> such that: * </p> * * <ul> * <li><code>ret.length == arr.length</code>, and</li> * <li>for all integers <code>i</code> where <code>0 &lt; i &lt; arr.length</code>, <code>ret[i] = arr[i].length</code>. The length of a null array is defined to be 0.</li> * </ul> * * @param arr a two-or-more-dimensional array * @return a length array as described above, or null if <code>arr</code> is null */ public static int[] lengthArray (Object[][] arr) { if (arr == null) { return null; } int[] ret = new int[arr.length]; for (int i = 0; i < arr.length; i++) { ret[i] = (arr[i] != null) ? arr[i].length : 0; // null array has 0 length } return ret; } public static int[] condensedLengthArray (Object[][] arr) { // Check ties if (!checkTies(arr)) { throw new IllegalArgumentException("Ties in array are incorrectly formatted"); } return condensedLengthArray(lengthArray(arr)); } public static int[] condensedLengthArray (int[] lengthArray) { if (lengthArray == null) { return null; } ArrayList<Integer> ret = new ArrayList<Integer>(); for (int i = 0; i < lengthArray.length;) { // incremented by final loop int x = lengthArray[i]; if (x == 0) { // there should be no zeroes except to skip places throw new IllegalArgumentException("Improperly formatted length array: zero at " + i); } if (x < 0) { throw new IllegalArgumentException("Invalid length array: negative at " + i); } ret.add(x); int initI = i; // Skip places, checking to ensure that each one is 0--intentionally updates the outer loop counter // The <= ensures that the final skip is checked--then increments i one more time. So the loop header does no incrementing. for (; i <= initI + x - 1 && i < lengthArray.length; i++) { if (lengthArray[i] < 0) { throw new IllegalArgumentException("Invalid length array: negative at " + i); } if (lengthArray[i] > 0 && i != initI) { // != initI check prevents complaining about the current entry (which SHOULD be nonzero) throw new IllegalArgumentException("Improperly formatted length array: nonzero at " + i); } } } // Unbox the ArrayList (it would be easier if it was automatic, but I understand the performance hit array autounboxing would cause) Integer[] pending = ret.toArray(new Integer[0]); int[] retArr = new int[pending.length]; for (int i = 0; i < pending.length; i++) { retArr[i] = pending[i]; } return retArr; } /** * Indexes an array by another int array and returns the result. * * <p> * Specifically, returns an array <code>ret</code> such that: * </p> * * <ul> * <li><code>ret.length == indices.length</code>, and</li> * <li>for all integers <code>i</code> where <code>0 &lt; i &lt; ret.length</code>, <code>ret[i] == toIndex[indices[i]]</code></li> * </ul> * * <p> * If <code>indices</code> is null, this method returns null. If <code>toIndex</code> is null, this method throws a <code>NullPointerException</code>. * </p> * * @param toIndex the array to index * @param indices the indices within <code>toIndex</code> to return * @return <code>toIndex</code> indexed by <code>indices</code>, as described above * @throws ArrayIndexOutOfBoundsException if any entry in <code>indices</code> is negative or greater than <code>toIndex.length</code> * @throws NullPointerException if <code>toIndex == null</code> */ // HASHTAG UNCHECKED CASTS @SuppressWarnings("unchecked") public static <T> T[] index (T[] toIndex, int[] indices) { // Null handling if (indices == null) { return null; } if (toIndex == null) { throw new NullPointerException("toIndex must not be null"); } // Instantiate a generic array (equivalent to ret = new T[indices.length]) Class<T> type = (Class<T>) toIndex.getClass().getComponentType(); T[] ret = (T[]) Array.newInstance(type, indices.length); for (int i = 0; i < indices.length; i++) { if (indices[i] < 0 || indices[i] > toIndex.length) { throw new ArrayIndexOutOfBoundsException("Invalid index " + indices[i] + " at indices[" + i + "]"); } ret[i] = toIndex[indices[i]]; } return ret; } }
package org.xdi.oxauth.service; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.TimeZone; import java.util.concurrent.atomic.AtomicBoolean; import javax.ejb.DependsOn; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Event; import javax.enterprise.event.Observes; import javax.inject.Inject; import javax.inject.Named; import org.gluu.persist.PersistenceEntryManager; import org.gluu.persist.model.BatchOperation; import org.gluu.persist.model.ProcessBatchOperation; import org.slf4j.Logger; import org.xdi.model.ApplicationType; import org.xdi.oxauth.model.common.AuthorizationGrant; import org.xdi.oxauth.model.common.AuthorizationGrantList; import org.xdi.oxauth.model.configuration.AppConfiguration; import org.xdi.oxauth.model.fido.u2f.DeviceRegistration; import org.xdi.oxauth.model.fido.u2f.RequestMessageLdap; import org.xdi.oxauth.model.registration.Client; import org.xdi.oxauth.service.fido.u2f.DeviceRegistrationService; import org.xdi.oxauth.service.fido.u2f.RequestService; import org.xdi.oxauth.uma.service.UmaPctService; import org.xdi.oxauth.uma.service.UmaPermissionService; import org.xdi.oxauth.uma.service.UmaResourceService; import org.xdi.oxauth.uma.service.UmaRptService; import org.xdi.service.CacheService; import org.xdi.service.cache.NativePersistenceCacheProvider; import org.xdi.service.cdi.async.Asynchronous; import org.xdi.service.cdi.event.CleanerEvent; import org.xdi.service.cdi.event.Scheduled; import org.xdi.service.timer.event.TimerEvent; import org.xdi.service.timer.schedule.TimerSchedule; /** * @author Yuriy Zabrovarnyy * @author Javier Rojas Blum * @version August 9, 2017 */ @ApplicationScoped @DependsOn("appInitializer") @Named public class CleanerTimer { public final static int BATCH_SIZE = 25; private final static int DEFAULT_INTERVAL = 600; // 10 minutes @Inject private Logger log; @Inject private PersistenceEntryManager ldapEntryManager; @Inject private AuthorizationGrantList authorizationGrantList; @Inject private ClientService clientService; @Inject private GrantService grantService; @Inject private UmaRptService umaRptService; @Inject private UmaPctService umaPctService; @Inject private UmaPermissionService umaPermissionService; @Inject private UmaResourceService umaResourceService; @Inject private SessionIdService sessionIdService; @Inject private CacheService cacheService; @Inject @Named("u2fRequestService") private RequestService u2fRequestService; @Inject private MetricService metricService; @Inject private DeviceRegistrationService deviceRegistrationService; @Inject private AppConfiguration appConfiguration; @Inject private Event<TimerEvent> cleanerEvent; private AtomicBoolean isActive; public void initTimer() { log.debug("Initializing Cleaner Timer"); this.isActive = new AtomicBoolean(false); int interval = appConfiguration.getCleanServiceInterval(); if (interval <= 0) { interval = DEFAULT_INTERVAL; } cleanerEvent.fire(new TimerEvent(new TimerSchedule(interval, interval), new CleanerEvent(), Scheduled.Literal.INSTANCE)); } @Asynchronous public void process(@Observes @Scheduled CleanerEvent cleanerEvent) { if (this.isActive.get()) { return; } if (!this.isActive.compareAndSet(false, true)) { return; } try { Date now = new Date(); processCache(now); processAuthorizationGrantList(); processRegisteredClients(); this.umaRptService.cleanup(now); this.umaPermissionService.cleanup(now); this.umaPctService.cleanup(now); this.umaResourceService.cleanup(now); processU2fRequests(); processU2fDeviceRegistrations(); processMetricEntries(); } finally { this.isActive.set(false); } } private void processCache(Date now) { try { if (cacheService.getCacheProvider() instanceof NativePersistenceCacheProvider) { ((NativePersistenceCacheProvider) cacheService.getCacheProvider()).cleanup(now, BATCH_SIZE); } } catch (Exception e) { log.error("Failed to clean up cache.", e); } } private void processAuthorizationGrantList() { log.debug("Start AuthorizationGrant clean up"); grantService.cleanUp(); log.debug("End AuthorizationGrant clean up"); } private void processRegisteredClients() { log.debug("Start Client clean up"); BatchOperation<Client> clientBatchService = new ProcessBatchOperation<Client>() { @Override public void performAction(List<Client> entries) { for (Client client : entries) { try { GregorianCalendar now = new GregorianCalendar(TimeZone.getTimeZone("UTC")); GregorianCalendar expirationDate = new GregorianCalendar(TimeZone.getTimeZone("UTC")); expirationDate.setTime(client.getClientSecretExpiresAt()); if (expirationDate.before(now)) { List<AuthorizationGrant> toRemove = authorizationGrantList.getAuthorizationGrant(client.getClientId()); authorizationGrantList.removeAuthorizationGrants(toRemove); log.debug("Removing Client: {}, Expiration date: {}", client.getClientId(), client.getClientSecretExpiresAt()); clientService.remove(client); } } catch (Exception e) { log.error("Failed to remove entry", e); } } } }; clientService.getClientsWithExpirationDate(clientBatchService, new String[] {"inum", "oxAuthClientSecretExpiresAt"}, 0, BATCH_SIZE); log.debug("End Client clean up"); } private void processU2fRequests() { log.debug("Start U2F request clean up"); Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.add(Calendar.SECOND, -90); final Date expirationDate = calendar.getTime(); BatchOperation<RequestMessageLdap> requestMessageLdapBatchService = new ProcessBatchOperation<RequestMessageLdap>() { @Override public void performAction(List<RequestMessageLdap> entries) { for (RequestMessageLdap requestMessageLdap : entries) { try { log.debug("Removing RequestMessageLdap: {}, Creation date: {}", requestMessageLdap.getRequestId(), requestMessageLdap.getCreationDate()); u2fRequestService.removeRequestMessage(requestMessageLdap); } catch (Exception e) { log.error("Failed to remove entry", e); } } } }; u2fRequestService.getExpiredRequestMessages(requestMessageLdapBatchService, expirationDate, new String[] {"oxRequestId", "creationDate"}, 0, BATCH_SIZE); log.debug("End U2F request clean up"); } private void processU2fDeviceRegistrations() { log.debug("Start U2F request clean up"); Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.add(Calendar.SECOND, -90); final Date expirationDate = calendar.getTime(); BatchOperation<DeviceRegistration> deviceRegistrationBatchService = new ProcessBatchOperation<DeviceRegistration>() { @Override public void performAction(List<DeviceRegistration> entries) { for (DeviceRegistration deviceRegistration : entries) { try { log.debug("Removing DeviceRegistration: {}, Creation date: {}", deviceRegistration.getId(), deviceRegistration.getCreationDate()); deviceRegistrationService.removeUserDeviceRegistration(deviceRegistration); } catch (Exception e) { log.error("Failed to remove entry", e); } } } }; deviceRegistrationService.getExpiredDeviceRegistrations(deviceRegistrationBatchService, expirationDate, new String[] {"oxId", "creationDate"}, 0, BATCH_SIZE); log.debug("End U2F request clean up"); } private void processMetricEntries() { log.debug("Start metric entries clean up"); int keepDataDays = appConfiguration.getMetricReporterKeepDataDays(); Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.add(Calendar.DATE, -keepDataDays); Date expirationDate = calendar.getTime(); metricService.removeExpiredMetricEntries(expirationDate, ApplicationType.OX_AUTH, metricService.applianceInum(), 0, BATCH_SIZE); log.debug("End metric entries clean up"); } }
package net.af0.sesame; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteException; import android.os.AsyncTask; import android.util.Base64; import android.util.Log; import com.google.protobuf.InvalidProtocolBufferException; import net.sqlcipher.Cursor; import net.sqlcipher.database.SQLiteDatabase; import net.sqlcipher.database.SQLiteDatabaseHook; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; /** * Singleton class wrapping the database interactions. */ public final class SQLCipherDatabase { static final String COLUMN_USERNAME = "username"; static final String COLUMN_DOMAIN = "domain"; private static final String TABLE_KEYS = "keys"; private static final String COLUMN_ID = "id"; private static final String COLUMN_PASSWORD = "password"; private static final String COLUMN_REMARKS = "remarks"; static final String DATABASE_CREATE = "create table " + TABLE_KEYS + "(" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_USERNAME + " text, " + COLUMN_DOMAIN + " text," + COLUMN_PASSWORD + " text," + COLUMN_REMARKS + " text);"; private static final String[] allColumns_ = { // Stupid. I named the field "id" and SimpleCursorFactory expects "id". Rather than // rename and break compatibility to gracefully handle database upgrades, let's just // alias it. I hope nobody is reading this... COLUMN_ID + " AS _id", COLUMN_USERNAME, COLUMN_DOMAIN, COLUMN_PASSWORD, COLUMN_REMARKS}; private static final int DATABASE_VERSION = 3; private static final String DATABASE_NAME = "keys.db"; private static net.sqlcipher.database.SQLiteOpenHelper helper_; private static SQLiteDatabase database_; private static Record createRecord(final String username, final String domain, final String password, final String remarks) { ContentValues values = new ContentValues(); values.put(COLUMN_USERNAME, username); values.put(COLUMN_DOMAIN, domain); values.put(COLUMN_PASSWORD, password); values.put(COLUMN_REMARKS, remarks); long id = database_.insert(TABLE_KEYS, null, values); Cursor crs = database_.query(TABLE_KEYS, allColumns_, COLUMN_ID + "=" + id, null, null, null, null); crs.moveToFirst(); Record r = toRecord(crs); crs.close(); return r; } public static void createRecord(final String username, final String domain, final String password, final String remarks, final Callbacks<Record> callbacks) { new AsyncTask<Void, Void, Boolean>() { Record r; Exception exception; @Override public Boolean doInBackground(Void... param) { try { return createRecord(username, domain, password, remarks) != null; } catch (Exception e) { exception = e; return false; } } @Override protected void onPostExecute(final Boolean success) { if (callbacks != null) { if (exception != null) { callbacks.OnException(exception); } else { callbacks.OnFinish(r); } } } @Override protected void onCancelled() { if (callbacks != null) { callbacks.OnCancelled(); } } }.execute(); } public static void deleteRecord(final long record_id, final Callbacks2<Boolean, Record> callbacks) { new AsyncTask<Void, Void, Boolean>() { Exception exception; @Override protected Boolean doInBackground(Void... params) { try { database_.delete(TABLE_KEYS, COLUMN_ID + "=" + record_id, null); } catch (Exception e) { exception = e; } return true; } @Override protected void onPostExecute(final Boolean result) { if (callbacks != null) { if (exception != null) { callbacks.OnException(exception); } else { callbacks.OnFinish(result, null); } } } @Override protected void onCancelled() { if (callbacks != null) { callbacks.OnCancelled(); } } }.execute(); } public static void updateRecord(final Record r, final Callbacks2<Boolean, Record> callbacks) { new AsyncTask<Void, Void, Boolean>() { Exception exception; @Override protected Boolean doInBackground(Void... params) { ContentValues values = new ContentValues(); values.put(COLUMN_USERNAME, r.getUsername()); values.put(COLUMN_DOMAIN, r.getDomain()); values.put(COLUMN_PASSWORD, r.getPassword()); values.put(COLUMN_REMARKS, r.getRemarks()); try { database_.update(TABLE_KEYS, values, COLUMN_ID + "=" + r.getId(), null); } catch (Exception e) { exception = e; } return true; } @Override protected void onPostExecute(final Boolean result) { if (callbacks != null) { if (exception != null) { callbacks.OnException(exception); } else { callbacks.OnFinish(result, r); } } } @Override protected void onCancelled() { if (callbacks != null) { callbacks.OnCancelled(); } } }.execute(); } public static void getRecord(final long record_id, final Callbacks<Record> callbacks) { new AsyncTask<Void, Void, Boolean>() { Record r; Exception exception; @Override public Boolean doInBackground(Void... param) { try { Cursor crs = database_.query(TABLE_KEYS, allColumns_, COLUMN_ID + "=" + record_id, null, null, null, null); if (crs.getCount() == 0) { crs.close(); return false; } crs.moveToFirst(); r = toRecord(crs); crs.close(); } catch (Exception e) { exception = e; } return r != null; } @Override protected void onPostExecute(final Boolean success) { callbacks.OnFinish(r); } @Override protected void onCancelled() { if (callbacks != null) { if (exception != null) { callbacks.OnException(exception); } else { callbacks.OnCancelled(); } } } }.execute(); } public static Cursor getAllCursor() { return database_.query(TABLE_KEYS, allColumns_, null, null, null, null, COLUMN_DOMAIN + " COLLATE NOCASE ASC, " + COLUMN_USERNAME + " COLLATE NOCASE ASC"); } public static Cursor getContaining(String substr) { String s = DatabaseUtils.sqlEscapeString("%" + substr + "%"); return database_.query(TABLE_KEYS, allColumns_, String.format("%s LIKE %s OR %s LIKE %s", COLUMN_DOMAIN, s, COLUMN_USERNAME, s), null, null, null, COLUMN_DOMAIN + " COLLATE NOCASE ASC, " + COLUMN_USERNAME + " COLLATE NOCASE ASC" ); } public static Record toRecord(Cursor crs) { Record r = new Record(); r.setId(crs.getLong(0)); r.setUsername(crs.getString(1)); r.setDomain(crs.getString(2)); r.setPassword(crs.getString(3)); r.setRemarks(crs.getString(4)); return r; } private static DatabaseMetadata.Database getMetadataFromPrefs(Context ctx) { DatabaseMetadata.Database metadata = DatabaseMetadata.Database.newBuilder() .setVersion(DATABASE_VERSION) .setKdfIter(Constants.KDF_ITER) .build(); SharedPreferences prefs = ctx.getSharedPreferences(Constants.DB_METADATA_PREF, Context.MODE_PRIVATE); try { metadata = DatabaseMetadata.Database.newBuilder(metadata).mergeFrom( DatabaseMetadata.Database.parseFrom(Base64.decode(prefs.getString( Constants.DB_METADATA_PREF, ""), Base64.DEFAULT )) ).build(); } catch (InvalidProtocolBufferException e) { Log.e("IMPORT", Log.getStackTraceString(e)); // Go with defaults anyway. Uh oh... } return metadata; } public static synchronized void OpenDatabase(final Context ctx, final char[] password, final Callbacks<Boolean> callbacks) { new AsyncTask<Void, Void, Boolean>() { Exception exception; @Override public Boolean doInBackground(Void... param) { try { if (helper_ == null) { SQLiteDatabase.loadLibs(ctx); helper_ = new OpenHelper(ctx, getMetadataFromPrefs(ctx)); } database_ = helper_.getWritableDatabase(password); } catch (Exception e) { exception = e; return false; } return true; } @Override protected void onPostExecute(final Boolean success) { if (callbacks != null) { if (exception != null) { callbacks.OnException(exception); } else { callbacks.OnFinish(success); } } } @Override protected void onCancelled() { if (callbacks != null) { callbacks.OnCancelled(); } } }.execute(); } // The import/export format for the database is // # bytes: DatabaseMetadata, serialized with writeDelimitedTo() (i.e. preceded by a size // varint). Parse with parseDelimitedFrom(). // rest: SQLCipher DB // So we have to strip the first n bytes before passing the file off to SQLCipher. public static void ImportDatabase(final Context ctx, final InputStream input, final char[] password, final Callbacks<Boolean> callbacks) { new AsyncTask<Void, Void, Boolean>() { Exception exception; @Override public Boolean doInBackground(Void... param) { try { if (isLocked()) { throw new SQLiteException("Database must be unlocked"); } // Get temporary path to write database minus metadata to. File tmpDb = File.createTempFile(Constants.KEY_IMPORT_TMPNAME, Constants.KEY_IMPORT_SUFFIX, ctx.getCacheDir()); DatabaseMetadata.Database metadata = DatabaseMetadata.Database.newBuilder() .setVersion(DATABASE_VERSION) .setKdfIter(Constants.KDF_ITER) .build(); OutputStream tmpDbStr = new FileOutputStream(tmpDb); try { // Parse the DatabaseMetadata. metadata = DatabaseMetadata.Database.parseDelimitedFrom(input); // Now get the remaining buffer. byte[] buf = new byte[1024]; int b; while ((b = input.read(buf)) != -1) { tmpDbStr.write(buf, 0, b); } } finally { tmpDbStr.close(); } // Now everything is hunky dory. SQLiteDatabase imported = SQLiteDatabase.openDatabase(tmpDb.getPath(), password, null, SQLiteDatabase.OPEN_READONLY, new DatabaseHook(metadata)); if (imported.getVersion() != DATABASE_VERSION) { // Because we're not using OpenHelper here, we have to handle version // mismatches ourselves. For now, versioning is unsupported! throw new UnsupportedOperationException("Upgrade not supported!"); } Cursor crs = imported.query(TABLE_KEYS, allColumns_, null, null, null, null, null); for (crs.moveToFirst(); !crs.isAfterLast(); crs.moveToNext()) { Record r = toRecord(crs); createRecord(r.getUsername(), r.getDomain(), r.getPassword(), r.getRemarks()); } crs.close(); return true; } catch (Exception e) { exception = e; return false; } } @Override protected void onPostExecute(final Boolean success) { if (callbacks != null) { if (exception != null) { callbacks.OnException(exception); } else { callbacks.OnFinish(success); } } } @Override protected void onCancelled() { if (callbacks != null) { callbacks.OnCancelled(); } } }.execute(); } public static void ExportDatabase(final Context ctx, final OutputStream output, final Callbacks<Boolean> callbacks) { new AsyncTask<Void, Void, Boolean>() { Exception exception; @Override public Boolean doInBackground(Void... param) { try { getMetadataFromPrefs(ctx).writeDelimitedTo(output); InputStream rawInput = new FileInputStream(getDatabaseFilePath(ctx)); byte[] buf = new byte[1024]; int b; BeginTransaction(); while ((b = rawInput.read(buf)) != -1) { output.write(buf, 0, b); } rawInput.close(); } catch (Exception e) { exception = e; } finally { EndTransaction(); } return true; } @Override protected void onPostExecute(final Boolean success) { if (callbacks != null) { if (exception != null) { callbacks.OnException(exception); } else { callbacks.OnFinish(success); } } } @Override protected void onCancelled() { if (callbacks != null) { callbacks.OnCancelled(); } } }.execute(); } public static void CreateDatabase(Context ctx, char[] password, Callbacks<Boolean> callbacks) { if (Exists(ctx)) { callbacks.OnException(new SQLiteException("file already exists")); } // Store a DatabaseMetadata object with our creation defaults. DatabaseMetadata.Database metadata = DatabaseMetadata.Database.newBuilder().setVersion( DATABASE_VERSION).setKdfIter(Constants.KDF_ITER).build(); SharedPreferences.Editor preferencesEditor = ctx.getSharedPreferences( Constants.DB_METADATA_PREF, Context.MODE_PRIVATE).edit(); preferencesEditor.putString(Constants.DB_METADATA_PREF, Base64.encodeToString(metadata.toByteArray(), Base64.DEFAULT)); preferencesEditor.commit(); // Open normally. OpenDatabase(ctx, password, callbacks); } public static synchronized void DeleteDatabase(final Context ctx, final Callbacks<Boolean> callbacks) { new AsyncTask<Void, Void, Boolean>() { Exception exception; @Override public Boolean doInBackground(Void... param) { try { Lock(); // Throw away the open database handle. ctx.deleteDatabase(DATABASE_NAME); } catch (Exception e) { exception = e; return false; } return true; } @Override protected void onPostExecute(final Boolean success) { if (callbacks != null) { if (exception != null) { callbacks.OnException(exception); } else { callbacks.OnFinish(success); } } } @Override protected void onCancelled() { if (callbacks != null) { callbacks.OnCancelled(); } } }.execute(); } public static void ChangePassword(final String password, final Callbacks<Boolean> callbacks) { new AsyncTask<Void, Void, Boolean>() { Exception exception; @Override public Boolean doInBackground(Void... param) { try { // TODO: Switch this from a String to a char[] and just manually escape. database_.rawExecSQL("PRAGMA rekey = " + DatabaseUtils.sqlEscapeString(password) + ";"); } catch (Exception e) { exception = e; return false; } return true; } @Override protected void onPostExecute(final Boolean success) { if (callbacks != null) { if (exception != null) { callbacks.OnException(exception); } else { callbacks.OnFinish(success); } } } @Override protected void onCancelled() { if (callbacks != null) { callbacks.OnCancelled(); } } }.execute(); } public static synchronized boolean isLocked() { return database_ == null || !database_.isOpen(); } public static void Lock() { if (helper_ != null) { helper_.close(); } if (database_ != null) { database_.close(); } } public static boolean Exists(Context ctx) { return ctx.getDatabasePath(DATABASE_NAME).exists(); } public static File getDatabaseFilePath(Context ctx) { return ctx.getDatabasePath(DATABASE_NAME); } // Begin a transaction on the open database. Useful for preventing writes during, say, a file // backup. public static synchronized void BeginTransaction() { if (!isLocked()) { database_.beginTransaction(); } } public static synchronized void EndTransaction() { if (!isLocked()) { database_.endTransaction(); } } static interface Callbacks<T> { void OnFinish(T x); void OnException(Exception exception); void OnCancelled(); } static interface Callbacks2<T1, T2> { void OnFinish(T1 x, T2 y); void OnException(Exception exception); void OnCancelled(); } private static class OpenHelper extends net.sqlcipher.database.SQLiteOpenHelper { public OpenHelper(Context ctx, DatabaseMetadata.Database metadata) { super(ctx, DATABASE_NAME, null, DATABASE_VERSION, new DatabaseHook(metadata)); } public void onCreate(SQLiteDatabase database) { database.execSQL(DATABASE_CREATE); } public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) { throw new UnsupportedOperationException("Upgrade not supported"); } } private static class DatabaseHook implements SQLiteDatabaseHook { final DatabaseMetadata.Database metadata_; public DatabaseHook(DatabaseMetadata.Database metadata) { metadata_ = metadata; } @Override public void preKey(SQLiteDatabase database) { } @Override public void postKey(SQLiteDatabase database) { database.rawExecSQL(String.format("PRAGMA kdf_iter = %d", metadata_.getKdfIter())); database.rawExecSQL(String.format("PRAGMA cipher = '%s'", metadata_.getCipher())); } } // Database model. public static class Record { private long id_; private String username_; private String domain_; private String password_; // TODO: switch these all to char[]? private String remarks_; public long getId() { return id_; } void setId(long id) { id_ = id; } public String getUsername() { return username_; } public void setUsername(String username) { username_ = username; } public String getDomain() { return domain_; } public void setDomain(String domain) { domain_ = domain; } public String getPassword() { return password_; } public void setPassword(String password) { password_ = password; } public String getRemarks() { return remarks_; } public void setRemarks(String remarks) { remarks_ = remarks; } @Override public String toString() { if (getUsername() != null && getDomain() != null && !getUsername().isEmpty() && !getDomain().isEmpty()) { return getUsername() + " / " + getDomain(); } else if (getUsername() != null && !getUsername().isEmpty()) { return getUsername(); } else if (getDomain() != null && !getDomain().isEmpty()) { return getDomain(); } return ""; } } }
package net.runelite.api; import java.util.HashMap; import java.util.Map; import lombok.AllArgsConstructor; import lombok.Getter; @AllArgsConstructor @Getter public enum ClanMemberRank { UNRANKED(-1), FRIEND(0), RECRUIT(1), CORPORAL(2), SERGEANT(3), LIEUTENANT(4), CAPTAIN(5), GENERAL(6), OWNER(7); private static final Map<Integer, ClanMemberRank> RANKS = new HashMap<>(); static { for (final ClanMemberRank clanMemberRank : ClanMemberRank.values()) { RANKS.put(clanMemberRank.value, clanMemberRank); } } public static ClanMemberRank valueOf(int rank) { return RANKS.get(rank); } private final int value; }
package com.chhuang.novel; import android.app.LoaderManager; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.text.TextUtils; import android.util.Log; import android.view.*; import android.widget.*; import com.android.volley.Response; import com.android.volley.VolleyError; import com.chhuang.novel.data.Article; import com.chhuang.novel.data.articles.BenghuaiNovel; import com.chhuang.novel.data.articles.INovel; import com.chhuang.novel.data.dao.ArticleDataHelper; import com.chhuang.novel.data.dao.ArticleInfo; import roboguice.activity.RoboActivity; import roboguice.inject.ContentView; import roboguice.inject.InjectView; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; @ContentView(R.layout.activity_directory) public class DirectoryActivity extends RoboActivity implements SwipeRefreshLayout.OnRefreshListener, LoaderManager.LoaderCallbacks<Cursor> { public static final String TAG = DirectoryActivity.class.getName(); @InjectView(R.id.layout_drawer) DrawerLayout drawerLayout; @InjectView(R.id.layout_titles) SwipeRefreshLayout layoutTitles; @InjectView(R.id.list_titles) ListView listViewTitles; @InjectView(R.id.drawer_sidebar) RelativeLayout drawerSidebar; @InjectView(R.id.sidebar_list_view) ListView listViewSidebar; private SimpleCursorAdapter articleAdapter; private INovel novel = new BenghuaiNovel(); private int lastVisitPosition; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); init(); } private void init() { ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ drawerLayout, /* DrawerLayout object */ R.drawable.ic_launcher, /* nav drawer image to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description for accessibility */ R.string.drawer_close /* "close drawer" description for accessibility */ ) { public void onDrawerClosed(View view) { invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } public void onDrawerOpened(View drawerView) { invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } @Override public void onDrawerSlide(View drawerView, float slideOffset) { float moveFactor = (drawerSidebar.getWidth() * slideOffset); layoutTitles.setTranslationX(moveFactor); } }; drawerLayout.setDrawerListener(drawerToggle); listViewSidebar.setAdapter(new ArrayAdapter<INovel>(this, android.R.layout.simple_list_item_1, AppContext.registerNovels)); listViewSidebar.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final INovel newNovel = (INovel) listViewSidebar.getAdapter().getItem(position); if (novel.equals(newNovel)) { return; } novel = newNovel; Log.i(TAG, "Switch novel to " + novel); getLoaderManager().initLoader(novel.hashCode(), null, DirectoryActivity.this); } }); novel = AppContext.registerNovels.get(0); getLoaderManager().initLoader(AppContext.registerNovels.get(0).hashCode(), null, this); layoutTitles.setOnRefreshListener(this); layoutTitles.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); articleAdapter = new ArticleCursorAdapter(this, R.layout.title_item, null, new String[0], new int[0], 0); listViewTitles.setAdapter(articleAdapter); listViewTitles.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor cursor = ((SimpleCursorAdapter) listViewTitles.getAdapter()).getCursor(); if (cursor == null) { return; } cursor.moveToPosition(position); lastVisitPosition = position; Article article = ArticleDataHelper.fromCursor(cursor); Intent intent = new Intent(DirectoryActivity.this, ArticleActivity.class) .putExtra("article", article) .putExtra("novel", novel.getClass().getCanonicalName()); startActivity(intent); } }); registerForContextMenu(listViewTitles); } @Override protected void onPause() { getSharedPreferences(TAG, MODE_PRIVATE) .edit() .putInt(novel.getBookName() + "#list_selection", lastVisitPosition) .commit(); super.onPause(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { if (v.getId() == R.id.list_titles) { menu.setHeaderTitle(""); menu.add(Menu.NONE, 0, 0, ""); menu.add(Menu.NONE, 1, 1, ""); } } @Override public boolean onContextItemSelected(MenuItem item) { ContextMenu.ContextMenuInfo contextMenuInfo = item.getMenuInfo(); if (contextMenuInfo instanceof AdapterView.AdapterContextMenuInfo) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) contextMenuInfo; Cursor cursor = ((SimpleCursorAdapter) listViewTitles.getAdapter()).getCursor(); cursor.moveToPosition(info.position); switch (item.getItemId()) { case 0: singleDownload(cursor); break; case 1: do { singleDownload(cursor); } while (cursor.moveToNext()); } return true; } return super.onContextItemSelected(item); } private void singleDownload(Cursor cursor) { final Article article = ArticleDataHelper.fromCursor(cursor); final Response.Listener<String> responseListener = new Response.Listener<String>() { @Override public void onResponse(String response) { String content = novel.parseArticle(response); article.setContent(content); Uri uri = ArticleDataHelper.getInstance( AppContext.getContext()).insert(article); Log.v(TAG, "Article uri: " + uri); } }; final Response.ErrorListener errorListener = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { AppContext.showToast(DirectoryActivity.this, article.getTitle() + " ", Toast.LENGTH_LONG); } }; AppContext.getContext().getQueue().add( novel.getFactory().create(article.getUrl(), responseListener, errorListener)); } // TODO bulkInsert for articles private void multipleDownload(Cursor cursor) { final List<Article> synchronizedArticleList = Collections.synchronizedList(new ArrayList<Article>()); AtomicInteger taskCount = new AtomicInteger(0); final AtomicInteger finishCount = new AtomicInteger(0); do { final Article article = ArticleDataHelper.fromCursor(cursor); taskCount.getAndIncrement(); final Response.Listener<String> responseListener = new Response.Listener<String>() { @Override public void onResponse(String response) { String content = novel.parseArticle(response); article.setContent(content); synchronizedArticleList.add(article); finishCount.getAndIncrement(); } }; final Response.ErrorListener errorListener = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { AppContext.showToast(DirectoryActivity.this, article.getTitle() + " ", Toast.LENGTH_LONG); finishCount.getAndIncrement(); } }; AppContext.getContext().getQueue().add( novel.getFactory().create(article.getUrl(), responseListener, errorListener)); } while (cursor.moveToNext()); // finishCount.compareAndSet() } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { for (INovel novel : AppContext.registerNovels) { if (novel.hashCode() == id) { return new CursorLoader(this, ArticleDataHelper.ARTICLE_CONTENT_URI, ArticleInfo.PROJECTIONS, ArticleInfo.NOVEL_NAME + " = ?", new String[]{novel.getBookName()}, ArticleInfo.ID); } } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { articleAdapter.changeCursor(data); if (data == null || data.getCount() == 0) { onRefresh(); } else { final int lastVisitPosition = getSharedPreferences(TAG, MODE_PRIVATE) .getInt(novel.getBookName() + "#list_selection", 0); Log.v(TAG, "Last visit position is " + lastVisitPosition); listViewTitles.post(new Runnable() { @Override public void run() { listViewTitles.setSelection(lastVisitPosition); } }); } } @Override public void onRefresh() { layoutTitles.setRefreshing(true); AppContext.getContext().getQueue().add(novel.getFactory().create(novel.getBaseUrl(), new Response.Listener<String>() { @Override public void onResponse(String response) { ArrayList<Article> articles = novel.parseHomePageToArticles(response); ArticleDataHelper.getInstance(AppContext.getContext()).bulkInsert(articles); layoutTitles.setRefreshing(false); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { AppContext.showToast(DirectoryActivity.this, "", Toast.LENGTH_LONG); layoutTitles.setRefreshing(false); } })); } @Override public void onLoaderReset(Loader<Cursor> loader) { articleAdapter.changeCursor(null); } private static class ViewHolder { private TextView chapterNumber; private TextView chapterTitle; private ImageView star; private ProgressBar progressBar; } private class ArticleCursorAdapter extends SimpleCursorAdapter { private ArticleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) { super(context, layout, c, from, to, flags); } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder; if (view == null) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.title_item, null); holder = new ViewHolder(); holder.chapterNumber = (TextView) view.findViewById(R.id.text_chapter); holder.chapterTitle = (TextView) view.findViewById(R.id.text_title); holder.star = (ImageView) view.findViewById(R.id.image_status); holder.progressBar = (ProgressBar) view.findViewById(R.id.progress_article); view.setTag(holder); Log.v(TAG, String.format("Init view holder (%s, %s, %s)", holder.chapterNumber, holder.chapterTitle, holder.star)); } else { holder = (ViewHolder) view.getTag(); } if (holder == null) { holder = new ViewHolder(); holder.chapterNumber = (TextView) view.findViewById(R.id.text_chapter); holder.chapterTitle = (TextView) view.findViewById(R.id.text_title); holder.star = (ImageView) view.findViewById(R.id.image_status); holder.progressBar = (ProgressBar) view.findViewById(R.id.progress_article); Log.v(TAG, String.format("Init view holder (%s, %s, %s), backup", holder.chapterNumber, holder.chapterTitle, holder.star)); view.setTag(holder); } Article article = ArticleDataHelper.fromCursor(cursor); if (TextUtils.isEmpty(article.getContent())) { holder.star.setImageState(new int[]{android.R.attr.state_pressed}, false); } else { holder.star.setImageState(new int[]{android.R.attr.state_checked, android.R.attr.state_pressed}, false); } final int progress = (int) (100 * article.getPercentage()); holder.chapterNumber.setText(String.format("%04d", article.getId())); holder.chapterTitle.setText(article.getTitle()); holder.progressBar.setVisibility(View.VISIBLE); holder.progressBar.setProgress(progress); } } }
package inc.flide.vim8; import android.content.Context; import android.content.SharedPreferences; import android.inputmethodservice.InputMethodService; import android.os.IBinder; import android.os.SystemClock; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodInfo; import android.view.inputmethod.InputMethodManager; import java.util.List; import java.util.Map; import inc.flide.vim8.keyboardHelpers.InputMethodServiceHelper; import inc.flide.vim8.keyboardHelpers.KeyboardAction; import inc.flide.vim8.structures.FingerPosition; import inc.flide.vim8.structures.InputSpecialKeyEventCode; import inc.flide.vim8.views.NumberKeypadView; import inc.flide.vim8.views.SelectionKeypadView; import inc.flide.vim8.views.SymbolKeypadView; import inc.flide.vim8.views.mainKeyboard.MainKeyboardView; public class MainInputMethodService extends InputMethodService { InputMethodServiceHelper inputMethodServiceHelper = new InputMethodServiceHelper(); InputConnection inputConnection; private MainKeyboardView mainKeyboardView; private NumberKeypadView numberKeypadView; private SelectionKeypadView selectionKeypadView; private SymbolKeypadView symbolKeypadView; private View currentView; private int shiftLockFlag; private int capsLockFlag; private int modifierFlags; private void setCurrentView(View view){ this.currentView = view; currentView.invalidate(); setInputView(currentView); } /** * Lifecycle of IME * <p> * 01. InputMethodService Starts * 02. onCreate() * 03. onCreateInputView() * 04. onCreateCandidateViews() * 05. onStartInputViews() * 06. Text input gets the current input method subtype * 07. InputMethodManager#getCurrentInputMethodSubtype() * 08. Text input has started * 09. onCurrentInputMethodSubtypeChanged() * 10. Detect the current input method subtype has been changed -> can go to step 6 * 11. onFinishInput() -> cursor can Move to an additional field -> step 5 * 12. onDestroy() * 13. InputMethodService stops */ @Override public View onCreateInputView() { numberKeypadView = new NumberKeypadView(this, null); selectionKeypadView = new SelectionKeypadView(this, null); symbolKeypadView = new SymbolKeypadView(this, null); mainKeyboardView = new MainKeyboardView(this, null); setCurrentView(mainKeyboardView.getView()); return currentView; } @Override public void onStartInput(EditorInfo attribute, boolean restarting) { super.onStartInput(attribute, restarting); inputConnection = getCurrentInputConnection(); } @Override public void onBindInput() { inputConnection = getCurrentInputConnection(); } @Override public void onStartInputView(EditorInfo info, boolean restarting) { super.onStartInputView(info, restarting); currentView.invalidate(); mainKeyboardView.getView().invalidate(); } @Override public void onInitializeInterface() { super.onInitializeInterface(); inputConnection = getCurrentInputConnection(); setShiftLockFlag(0); setCapsLockFlag(0); clearModifierFlags(); } public Map<List<FingerPosition>, KeyboardAction> buildKeyboardActionMap() { return inputMethodServiceHelper .initializeKeyboardActionMap(getResources(), getPackageName()); } public void sendText(String text) { inputConnection.commitText(text, 1); clearModifierFlags(); } private void clearModifierFlags() { modifierFlags = 0; } public void sendDownKeyEvent(int keyEventCode, int flags) { inputConnection.sendKeyEvent( new KeyEvent( SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), KeyEvent.ACTION_DOWN, keyEventCode, 0, flags ) ); } public void sendUpKeyEvent(int keyEventCode, int flags) { inputConnection.sendKeyEvent( new KeyEvent( SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), KeyEvent.ACTION_UP, keyEventCode, 0, flags ) ); } public void sendDownAndUpKeyEvent(int keyEventCode, int flags) { sendDownKeyEvent(keyEventCode, flags); sendUpKeyEvent(keyEventCode, flags); } private void switchToExternalEmoticonKeyboard() { InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE); IBinder iBinder = this.getWindow().getWindow().getAttributes().token; String keyboardId = getSelectedEmoticonKeyboardId(); if (keyboardId.isEmpty()) { inputMethodManager.switchToLastInputMethod(iBinder); } else { inputMethodManager.setInputMethod(iBinder, keyboardId); } } private String getSelectedEmoticonKeyboardId() { SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences( getString(R.string.basic_preference_file_name), Context.MODE_PRIVATE); String emoticonKeyboardId = sharedPreferences.getString(getString(R.string.bp_selected_emoticon_keyboard), ""); // Before returning verify that this keyboard Id we have does exist in the system. InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); List<InputMethodInfo> enabledInputMethodList = inputMethodManager.getEnabledInputMethodList(); for (InputMethodInfo inputMethodInfo : enabledInputMethodList) { if (inputMethodInfo.getId().compareTo(emoticonKeyboardId) == 0) { return emoticonKeyboardId; } } return ""; } public void sendKey(int keyEventCode, int flags) { sendDownAndUpKeyEvent(keyEventCode, getShiftLockFlag() | getCapsLockFlag() | modifierFlags | flags); clearModifierFlags(); } public void handleInputText(KeyboardAction keyboardAction) { if (keyboardAction.getText().length() == 1 && (getShiftLockFlag() == KeyEvent.META_SHIFT_ON || getCapsLockFlag() == KeyEvent.META_CAPS_LOCK_ON)) { sendText(keyboardAction.getCapsLockText()); setShiftLockFlag(0); } else { sendText(keyboardAction.getText()); } } public void handleInputKey(KeyboardAction keyboardAction) { sendKey(keyboardAction.getKeyEventCode(), keyboardAction.getKeyFlags()); setShiftLockFlag(0); } public void handleSpecialInput(KeyboardAction keyboardAction) { InputSpecialKeyEventCode keyeventCode = InputSpecialKeyEventCode.valueOf(keyboardAction.getText()); switch (keyeventCode) { case SHIFT_TOOGLE: performShiftToogle(); break; case SWITCH_TO_EMOJI_KEYBOARD: switchToExternalEmoticonKeyboard(); break; case SWITCH_TO_NUMBER_PAD: setCurrentView(numberKeypadView); break; case SWITCH_TO_MAIN_KEYBOARD: setCurrentView(mainKeyboardView.getView()); break; case SWITCH_TO_SYMBOLS_KEYBOARD: setCurrentView(symbolKeypadView); break; case PASTE: paste(); break; case SELECTION_START: sendDownKeyEvent(KeyEvent.KEYCODE_SHIFT_LEFT, 0); sendDownAndUpKeyEvent(KeyEvent.KEYCODE_DPAD_LEFT, 0); sendUpKeyEvent(KeyEvent.KEYCODE_SHIFT_LEFT, 0); break; case SWITCH_TO_SELECTION_KEYBOARD: setCurrentView(selectionKeypadView); break; case HIDE_KEYBOARD: hideKeyboard(); break; default: //Logger.Warn(this, "Special Event undefined for keyCode : " + keyboardAction.getText()); break; } } public void cut() { inputConnection.performContextMenuAction(android.R.id.cut); } public void copy() { inputConnection.performContextMenuAction(android.R.id.copy); } public void paste() { inputConnection.performContextMenuAction(android.R.id.paste); } public void hideKeyboard() { this.requestHideSelf(InputMethodManager.HIDE_NOT_ALWAYS); } private void performShiftToogle() { //single press locks the shift key, //double press locks the caps key //a third press unlocks both. if (getShiftLockFlag() == KeyEvent.META_SHIFT_ON) { setShiftLockFlag(0); setCapsLockFlag(KeyEvent.META_CAPS_LOCK_ON); } else if (getCapsLockFlag() == KeyEvent.META_CAPS_LOCK_ON) { setShiftLockFlag(0); setCapsLockFlag(0); } else { setShiftLockFlag(KeyEvent.META_SHIFT_ON); setCapsLockFlag(0); } } public boolean areCharactersCapitalized() { return getShiftLockFlag() == KeyEvent.META_SHIFT_ON || getCapsLockFlag() == KeyEvent.META_CAPS_LOCK_ON; } public void setModifierFlags(int newModifierFlags) { this.modifierFlags = this.modifierFlags | newModifierFlags; } public int getShiftLockFlag() { return shiftLockFlag; } public void setShiftLockFlag(int shiftLockFlag) { this.shiftLockFlag = shiftLockFlag; if (getWindow().findViewById(R.id.xboardView) != null) { getWindow().findViewById(R.id.xboardView).invalidate(); } } public int getCapsLockFlag() { return capsLockFlag; } public void setCapsLockFlag(int capsLockFlag) { this.capsLockFlag = capsLockFlag; } }
package org.terasology.nui.layouts; import com.google.common.collect.Lists; import org.joml.Vector2i; import org.terasology.nui.Canvas; import org.terasology.nui.CoreLayout; import org.terasology.nui.LayoutConfig; import org.terasology.nui.LayoutHint; import org.terasology.nui.UIWidget; import org.terasology.nui.databinding.Binding; import org.terasology.nui.databinding.DefaultBinding; import org.terasology.nui.util.RectUtility; import java.util.Iterator; import java.util.List; /** * The Flow layout arranges its children in a directional flow that wraps at the layout's boundary, very much like words * wrap at the end of a line when writing a text. The children are laid out in a row in the flow direction, each widget * sized by its preferred size. The individual elements are top-aligned, and wrapped at the first element that does not * fit in the row. * <p> * Flow lays out each managed child regardless of the child's visible property value - invisible children won't be * rendered but will take up space. * <p> * The layout may be styled as other widgets with {@link org.terasology.nui.skin.UISkin}. * <p> * The Flow layout can be configured in UI assets ({@code .ui} files): * <pre> * {@code * { * "type": "FlowLayout", * "verticalSpacing": 8, * "horizontalSpacing": 24, * "rightToLeftAlign": true, * "contents": [...] * // all properties of AbstractWidget * } * } * </pre> */ public class FlowLayout extends CoreLayout<LayoutHint> { /** * The ordered list of widgets to be arranged in the flow direction. */ private List<UIWidget> contents = Lists.newArrayList(); /** * The vertical spacing between adjacent widgets, in pixels */ @LayoutConfig private int verticalSpacing; /** * The horizontal spacing between adjacent widgets, in pixels */ @LayoutConfig private int horizontalSpacing; /** * Whether the directional flow of this layout goes from left-to-right or right-to-left. * <p> * The children are laid out from left-to-right by default (false), aligned at the left border of the canvas. If * this toggle is explicitly enabled (true) the children are laid out right-to-left, aligned at the right border of * the canvas. * <p> * This toggle can be set programmatically or in {@code .ui} files that use the Flow layout. * * @see #bindRightToLeftAlign(Binding) * @see #setRightToLeftAlign(boolean) */ @LayoutConfig private Binding<Boolean> rightToLeftAlign = new DefaultBinding<>(false); // vertical alignment code addition @LayoutConfig private Binding<Boolean> topToBottomAlign = new DefaultBinding<>(false); @Override public void addWidget(UIWidget element, LayoutHint hint) { contents.add(element); } @Override public void removeWidget(UIWidget element) { contents.remove(element); } @Override public void removeAllWidgets() { contents.clear(); } @Override public void onDraw(Canvas canvas) { layout(canvas, canvas.size(), true); } @Override public Vector2i getPreferredContentSize(Canvas canvas, Vector2i sizeHint) { return layout(canvas, sizeHint, false); } /** * Applies the flow layout to its children, arranging them in a directional flow. * <p> * The layout algorithm will wrap elements to a new line if adding them in the same line would exceed the bounding * size. The first element of a row is placed regardless of its size, and thus may exceed the bounding size. The * Flow layout attempts to stay within the preferred width, but will add new lines until all widgets have been laid * out. * <p> * If the preferred bounding size is wider than the preferred size of the widest child the Flow layout guarantees to * fit into the preferred width. There is no guarantee for the actual height. * * @param canvas the canvas to draw on and/or calculate sizes for * @param boundingSize the boundary for this layout, may be a canvas size or a size hint * @param draw whether to actually draw the widgets to the canvas * @return the computed bounding box size for when arranging the widget */ private Vector2i layout(Canvas canvas, Vector2i boundingSize, boolean draw) { // current bounding box for the widgets already laid out Vector2i result = new Vector2i(); // the filled width of a row; current horizontal "cursor" position for next element to be placed (ltr alignment) int widthOffset = 0; // current vertical "cursor" position for next element to be placed int heightOffset = 0; // local maximum for row height int rowHeight = 0; // local maximum for row width int rowWidth = 0; if (isTopToBottomAlign()) { for (UIWidget widget : contents) { Vector2i size = canvas.calculatePreferredSize(widget); if (heightOffset != 0 && heightOffset + verticalSpacing + size.y <= boundingSize.y) { // place widget in current column heightOffset += verticalSpacing; } else if (heightOffset != 0) { // wrap the column result.x += rowWidth + horizontalSpacing; result.y = Math.max(result.y, heightOffset); widthOffset = result.x; heightOffset = 0; rowWidth = 0; } if (draw) { int xPosition = isRightToLeftAlign() ? canvas.size().x - widthOffset - size.x : widthOffset; canvas.drawWidget(widget, RectUtility.createFromMinAndSize(xPosition, heightOffset, size.x, size.y)); } heightOffset += size.y; rowWidth = Math.max(rowWidth, size.x); } result.x += rowWidth; result.y = Math.max(result.y, heightOffset); } else { for (UIWidget widget : contents) { Vector2i size = canvas.calculatePreferredSize(widget); if (widthOffset != 0 && widthOffset + horizontalSpacing + size.x <= boundingSize.x) { // place widget in the current row widthOffset += horizontalSpacing; } else if (widthOffset != 0) { // wrap the row result.x = Math.max(result.x, widthOffset); result.y += rowHeight + verticalSpacing; heightOffset = result.y; widthOffset = 0; rowHeight = 0; } if (draw) { int xPosition = isRightToLeftAlign() ? canvas.size().x - widthOffset - size.x : widthOffset; canvas.drawWidget(widget, RectUtility.createFromMinAndSize(xPosition, heightOffset, size.x, size.y)); } widthOffset += size.x; rowHeight = Math.max(rowHeight, size.y); } result.x = Math.max(result.x, widthOffset); result.y += rowHeight; } return result; } @Override public Vector2i getMaxContentSize(Canvas canvas) { return new Vector2i(Integer.MAX_VALUE, Integer.MAX_VALUE); } @Override public Iterator<UIWidget> iterator() { return contents.iterator(); } /** * Retrieves the horizontal spacing between adjacent widgets in this {@code FlowLayout}. * * @return the spacing, in pixels */ public int getHorizontalSpacing() { return horizontalSpacing; } /** * Retrieves the vertical spacing between adjacent widgets in this {@code FlowLayout}. * * @return the spacing, in pixels */ public int getVerticalSpacing() { return verticalSpacing; } /** * Sets the horizontal spacing between adjacent widgets in this {@code FlowLayout}. * * @param spacing the spacing, in pixels * @return this {@code FlowLayout} */ public FlowLayout setHorizontalSpacing(int spacing) { this.horizontalSpacing = spacing; return this; } /** * Sets the vertical spacing between adjacent widgets in this {@code FlowLayout}. * * @param spacing the spacing, in pixels * @return this {@code FlowLayout} */ public FlowLayout setVerticalSpacing(int spacing) { this.verticalSpacing = spacing; return this; } /** * Whether the directional flow of this layout goes from left-to-right or right-to-left. * <p> * If false, the children are laid out from left-to-right and aligned at the left border of the canvas. If true, the * children are laid out right-to-left and aligned at the right border of the canvas. * <p> * The default value is {@code false}, laying out children left-to-right. * <p> * This toggle can be set programmatically or in {@code .ui} files that use the Flow layout. * * @return whether the children are laid out right-to-left and aligned to the right * @see #bindRightToLeftAlign(Binding) * @see #setRightToLeftAlign(boolean) */ public boolean isRightToLeftAlign() { return rightToLeftAlign.get(); } /** * Set whether the directional flow of this layout goes from left-to-right or right-to-left. * * See {@link #isRightToLeftAlign()} for more details on the directional flow. * * @param rightToLeftAlign whether the children are laid out right-to-left and aligned to the right */ public void setRightToLeftAlign(boolean rightToLeftAlign) { this.rightToLeftAlign.set(rightToLeftAlign); } /** * Bind whether the directional flow of this layout goes from left-to-right or right-to-left with given binding. * <p> * The directional flow will change whenever the given binding changes its value. See {@link #isRightToLeftAlign()} * for more details on the directional flow. * * @param binding the binding defining whether to lay out children right-to-left or left-to-right. */ public void bindRightToLeftAlign(Binding<Boolean> binding) { this.rightToLeftAlign = binding; } /** * Clear any binding to the the right-to-left align property and reset to the default value (false). */ public void clearRightToLeftAlignBinding() { this.rightToLeftAlign = new DefaultBinding<>(false); } // vertical alignment code addition public boolean isTopToBottomAlign() { return topToBottomAlign.get(); } public void setTopToBottomAlign(boolean topToBottomAlign) { this.topToBottomAlign.set(topToBottomAlign); } public void bindTopToBottomAlign(Binding<Boolean> binding) { this.topToBottomAlign = binding; } public void clearTopToBottomAlignBinding() { this.topToBottomAlign = new DefaultBinding<>(false); } }
package imagej.legacy.plugin; import ij.IJ; import ij.ImageJ; import imagej.patcher.LegacyHooks; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.image.ImageProducer; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.URL; import javax.swing.SwingUtilities; import org.scijava.Context; /** * The <i>ij1-patcher</i> defaults to running this class whenever a new * {@code PluginClassLoader} is initialized. * * @author Johannes Schindelin */ public class LegacyInitializer implements Runnable { @Override public void run() { final ClassLoader loader = IJ.getClassLoader(); Thread.currentThread().setContextClassLoader(loader); if (!GraphicsEnvironment.isHeadless() && !SwingUtilities.isEventDispatchThread()) try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { Thread.currentThread().setContextClassLoader(loader); } }); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { // ignore } try { /* * Instantiate a Context if there is none; IJ.runPlugIn() will be intercepted * by the legacy hooks if they are installed and return the current Context. * If no legacy hooks are installed, ImageJ 1.x will instantiate the Context using * the PluginClassLoader and the LegacyService will install the legacy hooks. */ IJ.runPlugIn(Context.class.getName(), null); } catch (Throwable t) { // do nothing; we're not in the PluginClassLoader's class path return; } // make sure that the Event Dispatch Thread's class loader is set SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Thread.currentThread().setContextClassLoader(IJ.getClassLoader()); } }); // set icon and title of main window (which are instantiated before the initializer is called) final ImageJ ij = IJ.getInstance(); if (ij != null) try { final LegacyHooks hooks = (LegacyHooks) IJ.class.getField("_hooks").get(null); ij.setTitle(hooks.getAppName()); final URL iconURL = hooks.getIconURL(); if (iconURL != null) try { Object producer = iconURL.getContent(); Image image = ij.createImage((ImageProducer)producer); ij.setIconImage(image); } catch (IOException e) { IJ.handleException(e); } } catch (Throwable t) { t.printStackTrace(); } } }
package oida.ontology.owl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Before; import org.junit.Test; import oida.ontology.OntologyClass; import oida.ontology.manager.IOntologyManager; import oida.ontology.manager.IOntologyManagerFactory; import oida.ontologyMgr.OntologyFile; /** * * @author Michael.Shamiyeh * @since 2017-02-02 * */ public class OwlManagerTest { private static final String TESTONTOLOGY_IRI = "http://de.oida/owl/testontology"; private static final String TESTFILE = "TestOntology.owl"; private static final String NAMESPACE_DEFAULT = "http://de.oida/test"; private static final String NAMESPACE_CARS = "http://de.oida/test/cars"; private static final String NAMESPACE_AIRCRAFT = "http://de.oida/test/aircraft"; private static final String PREFIX_A = "a"; private static final String PREFIX_B = "b"; private static final String CLASSNAME_VEHICLE = "Vehicle"; private static final String CLASSNAME_AIRCRAFT = "Aircraft"; private static final String CLASSNAME_FIXEDWING = "FixedWing"; private IOntologyManagerFactory factory; private IOntologyManager manager; private OntologyFile testFileEntry; private OntologyFile loadingTestFileEntry; @Before public void setUp() throws Exception { // factory = new OwlOntologyManagerFactory(); // manager = factory.getNewManager(); // manager.createOntology(TESTONTOLOGY_IRI); // testFileEntry = OntologyMgrFactory.eINSTANCE.createOntologyFile(); // testFileEntry.setPath(OntologyTestHelper.getTestOntologyFilePath()); // testFileEntry.setFileName(TESTFILE); // loadingTestFileEntry = OntologyMgrFactory.eINSTANCE.createOntologyFile(); // loadingTestFileEntry.setPath(OntologyTestHelper.getTestOntologyFilePath()); // loadingTestFileEntry.setFileName(OntologyTestHelper.getTestReferenceOntologyFileName()); } @Test public void testInitializeReasoner() { fail("Not yet implemented"); // TODO } @Test public void testAddGlobalIRIToLocalPathMapping() { fail("Not yet implemented"); // TODO } @Test public void testCreateOntology() { assertNotNull(manager.getOntology()); } @Test public void testSaveAndLoadOntology() { // try { // manager.saveOntology(testFileEntry); // assertTrue(new File(OntologyTestHelper.getTestOntologyFilePath() + TESTFILE).exists()); // Ontology loadedOntology = manager.loadOntology(testFileEntry); // assertNotNull(loadedOntology); // } catch (OntologyManagerException e) { // e.printStackTrace(); // fail(e.getMessage()); } @Test public void testNamespacePrefixManagementMethods() { manager.addNamespace("", NAMESPACE_DEFAULT, true); manager.addNamespace(PREFIX_A, NAMESPACE_CARS); manager.addNamespace(PREFIX_B, NAMESPACE_AIRCRAFT); assertEquals(NAMESPACE_CARS, manager.getNamespace(PREFIX_A)); assertEquals(NAMESPACE_DEFAULT, manager.getDefaultNamespace()); assertTrue(manager.isNamespaceExisting(PREFIX_A)); assertFalse(manager.isNamespaceExisting(PREFIX_B + "a")); assertEquals(8, manager.getAllNamespaces().keySet().size()); } @Test public void testCreateClass() { manager.createClass(CLASSNAME_VEHICLE); assertNotNull(manager.getClass(CLASSNAME_VEHICLE)); assertEquals(1, manager.getAllClasses().count()); } @Test public void testAssignSubClassToSuperClass() { manager.createClass(CLASSNAME_AIRCRAFT); manager.createClass(CLASSNAME_FIXEDWING); manager.assignSubClassToSuperClass(manager.getClass(CLASSNAME_FIXEDWING), manager.getClass(CLASSNAME_AIRCRAFT)); assertEquals(manager.getClass(CLASSNAME_FIXEDWING), manager.getClass(CLASSNAME_AIRCRAFT).getSubClasses().get(0)); } @Test public void testRenameFunctionality() { OntologyClass aClass = manager.createClass("A"); OntologyClass cClass = manager.createSubClass("C", aClass); assertNotNull(manager.getClass("A")); manager.renameEntity(aClass, "B"); assertNotNull(manager.getClass("B")); assertEquals(aClass, cClass.getSuperClasses().get(0)); } @Test public void testCreateIndividualString() { fail("Not yet implemented"); // TODO } @Test public void testCreateIndividualStringString() { fail("Not yet implemented"); // TODO } @Test public void testAssignIndividualToClass() { fail("Not yet implemented"); // TODO } @Test public void testGetIndividualString() { fail("Not yet implemented"); // TODO } @Test public void testGetIndividualStringString() { fail("Not yet implemented"); // TODO } @Test public void testGetAllIndividuals() { fail("Not yet implemented"); // TODO } @Test public void testCreateObjectPropertyStringString() { fail("Not yet implemented"); // TODO } @Test public void testAssignObjectPropertyRange() { fail("Not yet implemented"); // TODO } @Test public void testAssignObjectPropertyDomain() { fail("Not yet implemented"); // TODO } @Test public void testCreateAnnotationPropertyStringString() { fail("Not yet implemented"); // TODO } @Test public void testAnnotateClass() { fail("Not yet implemented"); // TODO } }
package org.folio.okapi.util; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.log4j.Level; import org.apache.log4j.Logger; /** * Helper class to mess with logging stuff. Normally we use * io.vertx.core.logging.Logger for all our logging. Behind the scenes, this * turns out to use log4j. For advanced stuff, we need to access log4j directly. * This class tries to hide such things from the rest of the system. There are * methods for getting and setting the root logging level, from a Level, a * String, or as a web service. Later we may want to add more fancy log level * control, for example for different loggers or systems. * * @author heikki */ public class LogHelper { private static final Logger l4jlogger = Logger.getLogger(LogHelper.class); /** * Parameter for the web service. At some point we may want to add more stuff * here, to control logging for each module, or something. For now this is * good enough. */ public static class LogLevelInfo { String level; @JsonCreator public LogLevelInfo(@JsonProperty String level) { this.level = level; } public LogLevelInfo() { this.level = ""; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } } public String getRootLogLevel() { Level lev = l4jlogger.getParent().getEffectiveLevel(); return lev == null ? "null" : lev.toString(); } public void setRootLogLevel(Level l) { // This might stop working in log4j version 2. See l4jlogger.getParent().setLevel(l); } public void setRootLogLevel(String name) { Level l = Level.toLevel(name); setRootLogLevel(l); } }
package org.jboss.osgi.framework.bundle; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.jboss.logging.Logger; import org.jboss.modules.ModuleIdentifier; import org.jboss.osgi.deployment.deployer.Deployment; import org.jboss.osgi.framework.plugin.AutoInstallPlugin; import org.jboss.osgi.framework.plugin.BundleDeploymentPlugin; import org.jboss.osgi.framework.plugin.BundleStoragePlugin; import org.jboss.osgi.framework.plugin.DeployerServicePlugin; import org.jboss.osgi.framework.plugin.FrameworkEventsPlugin; import org.jboss.osgi.framework.plugin.LifecycleInterceptorPlugin; import org.jboss.osgi.framework.plugin.ModuleManagerPlugin; import org.jboss.osgi.framework.plugin.NativeCodePlugin; import org.jboss.osgi.framework.plugin.PackageAdminPlugin; import org.jboss.osgi.framework.plugin.Plugin; import org.jboss.osgi.framework.plugin.ResolverPlugin; import org.jboss.osgi.framework.plugin.ServiceManagerPlugin; import org.jboss.osgi.framework.plugin.StartLevelPlugin; import org.jboss.osgi.framework.plugin.SystemPackagesPlugin; import org.jboss.osgi.framework.plugin.internal.AutoInstallPluginImpl; import org.jboss.osgi.framework.plugin.internal.BundleDeploymentPluginImpl; import org.jboss.osgi.framework.plugin.internal.BundleStoragePluginImpl; import org.jboss.osgi.framework.plugin.internal.DeployerServicePluginImpl; import org.jboss.osgi.framework.plugin.internal.FrameworkEventsPluginImpl; import org.jboss.osgi.framework.plugin.internal.LifecycleInterceptorPluginImpl; import org.jboss.osgi.framework.plugin.internal.ModuleManagerPluginImpl; import org.jboss.osgi.framework.plugin.internal.NativeCodePluginImpl; import org.jboss.osgi.framework.plugin.internal.PackageAdminPluginImpl; import org.jboss.osgi.framework.plugin.internal.ResolverPluginImpl; import org.jboss.osgi.framework.plugin.internal.ServiceManagerPluginImpl; import org.jboss.osgi.framework.plugin.internal.StartLevelPluginImpl; import org.jboss.osgi.framework.plugin.internal.SystemPackagesPluginImpl; import org.jboss.osgi.framework.plugin.internal.WebXMLVerifierInterceptor; import org.jboss.osgi.metadata.OSGiMetaData; import org.jboss.osgi.resolver.XVersionRange; import org.jboss.osgi.spi.util.SysPropertyActions; import org.jboss.osgi.vfs.AbstractVFS; import org.jboss.osgi.vfs.VirtualFile; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.FrameworkEvent; /** * The BundleManager is the central managing entity for OSGi bundles. * * @author thomas.diesler@jboss.com * @author <a href="david@redhat.com">David Bosschaert</a> * @since 29-Jun-2010 */ public class BundleManager { // Provide logging private final Logger log = Logger.getLogger(BundleManager.class); // The raw properties private Map<String, Object> properties = new HashMap<String, Object>(); // The BundleId generator private AtomicLong identityGenerator = new AtomicLong(); // Maps bundleId to Bundle private Map<Long, AbstractBundle> bundleMap = Collections.synchronizedMap(new LinkedHashMap<Long, AbstractBundle>()); /// The registered plugins private Map<Class<? extends Plugin>, Plugin> plugins = new LinkedHashMap<Class<? extends Plugin>, Plugin>(); // The Framework state private FrameworkState frameworkState; // The Framework integration mode public enum IntegrationMode { STANDALONE, CONTAINER } public BundleManager(Map<String, Object> initialProperties) { // The properties on the BundleManager are mutable as long the framework is not created // Plugins may modify these properties in their respective constructor if (initialProperties != null) properties.putAll(initialProperties); // Register the framework plugins plugins.put(BundleDeploymentPlugin.class, new BundleDeploymentPluginImpl(this)); plugins.put(BundleStoragePlugin.class, new BundleStoragePluginImpl(this)); plugins.put(FrameworkEventsPlugin.class, new FrameworkEventsPluginImpl(this)); plugins.put(ModuleManagerPlugin.class, new ModuleManagerPluginImpl(this)); plugins.put(NativeCodePlugin.class, new NativeCodePluginImpl(this)); plugins.put(ResolverPlugin.class, new ResolverPluginImpl(this)); plugins.put(ServiceManagerPlugin.class, new ServiceManagerPluginImpl(this)); plugins.put(SystemPackagesPlugin.class, new SystemPackagesPluginImpl(this)); // Register system service plugins plugins.put(DeployerServicePlugin.class, new DeployerServicePluginImpl(this)); plugins.put(LifecycleInterceptorPlugin.class, new LifecycleInterceptorPluginImpl(this)); plugins.put(WebXMLVerifierInterceptor.class, new WebXMLVerifierInterceptor(this)); plugins.put(PackageAdminPlugin.class, new PackageAdminPluginImpl(this)); plugins.put(StartLevelPlugin.class, new StartLevelPluginImpl(this)); // Finally add the AutoInstallPlugin plugins.put(AutoInstallPlugin.class, new AutoInstallPluginImpl(this)); // Create the Framework state frameworkState = new FrameworkState(this); } public FrameworkState getFrameworkState() { return frameworkState; } public SystemBundle getSystemBundle() { return frameworkState; } public IntegrationMode getIntegrationMode() { Object value = getProperty(IntegrationMode.class.getName()); return value != null ? (IntegrationMode)value : IntegrationMode.STANDALONE; } long getNextBundleId() { return identityGenerator.incrementAndGet(); } public BundleContext getSystemContext() { return frameworkState.getBundleContext(); } public Object getProperty(String key) { Object value = properties.get(key); if (value == null) value = SysPropertyActions.getProperty(key, null); return value; } public Map<String, Object> getProperties() { return Collections.unmodifiableMap(properties); } public void setProperty(String key, Object value) { if (isFrameworkActive()) throw new IllegalStateException("Cannot add property to ACTIVE framwork"); properties.put(key, value); } public boolean isFrameworkActive() { // We are active if the system bundle is ACTIVE return frameworkState != null && frameworkState.getState() == Bundle.ACTIVE; } void addBundleState(AbstractBundle bundleState) { if (bundleState == null) throw new IllegalArgumentException("Null bundleState"); long bundleId = bundleState.getBundleId(); if (bundleMap.containsKey(bundleId) == true) throw new IllegalStateException("Bundle already added: " + bundleState); log.infof("Install bundle: %s", bundleState); // Register the bundle with the manager bundleMap.put(bundleId, bundleState); bundleState.changeState(Bundle.INSTALLED); // Add the bundle to the resolver bundleState.addToResolver(); } void removeBundle(AbstractBundle bundleState) { log.tracef("Remove bundle: %s", bundleState); bundleState.removeFromResolver(); bundleMap.remove(bundleState.getBundleId()); } void uninstallBundle(AbstractBundle bundleState) { bundleState.changeState(Bundle.UNINSTALLED); List<AbstractBundle> uninstalled = getBundles(Bundle.UNINSTALLED); for (AbstractBundle aux : uninstalled) { AbstractUserBundle userBundle = AbstractUserBundle.assertBundleState(aux); if (userBundle.hasActiveWires() == false) userBundle.remove(); } } /** * Get a bundle by id * * Note, this will get the bundle regadless of its state. * i.e. The returned bundle may have been UNINSTALLED * * @param bundleId The identifier of the bundle * @return The bundle or null if there is no bundle with that id */ public AbstractBundle getBundleById(long bundleId) { if (bundleId == 0) return frameworkState; return bundleMap.get(bundleId); } /** * Get a bundle by location * * Note, this will get the bundle regadless of its state. * i.e. The returned bundle may have been UNINSTALLED * * @param location the location of the bundle * @return the bundle or null if there is no bundle with that location */ public AbstractBundle getBundleByLocation(String location) { if (location == null) throw new IllegalArgumentException("Null location"); AbstractBundle result = null; for (AbstractBundle aux : getBundles()) { String auxLocation = aux.getLocation(); if (location.equals(auxLocation)) { result = aux; break; } } return result; } /** * Get a bundle by symbolic name and version * * Note, this will get the bundle regadless of its state. * i.e. The returned bundle may have been UNINSTALLED * * @param symbolicName The bundle symbolic name * @param versionRange The optional bundle version * @return The bundle or null if there is no bundle with that name and version */ public AbstractBundle getBundle(String symbolicName, String versionRange) { AbstractBundle result = null; for (AbstractBundle aux : getBundles()) { if (aux.getSymbolicName().equals(symbolicName)) { if (versionRange == null || XVersionRange.parse(versionRange).isInRange(aux.getVersion())) { result = aux; break; } } } return result; } /** * Get the list of installed bundles. * i.e. Bundles in state UNINSTALLED are not returned */ public List<AbstractBundle> getBundles() { List<AbstractBundle> result = new ArrayList<AbstractBundle>(); for (AbstractBundle aux : bundleMap.values()) { if (aux.getState() != Bundle.UNINSTALLED) result.add(aux); } return Collections.unmodifiableList(result); } /** * Get the list of bundles that are in one of the given states. * If the states pattern is null, it returns all registered bundles. * * @param states The binary or combination of states or null */ public List<AbstractBundle> getBundles(Integer states) { List<AbstractBundle> result = new ArrayList<AbstractBundle>(); for (AbstractBundle aux : bundleMap.values()) { if (states == null || (aux.getState() & states.intValue()) != 0) result.add(aux); } return Collections.unmodifiableList(result); } /** * Get the list of registered plugins */ public List<Plugin> getPlugins() { return Collections.unmodifiableList(new ArrayList<Plugin>(plugins.values())); } @SuppressWarnings("unchecked") public <T extends Plugin> T getPlugin(Class<T> clazz) { T plugin = (T)plugins.get(clazz); if (plugin == null) throw new IllegalStateException("Cannot obtain plugin for: " + clazz.getName()); return plugin; } /** * Get an optional plugin that is registered with the bundle manager. * @return The plugin instance or null if the requested plugin class is not registered */ @SuppressWarnings("unchecked") public <T extends Plugin> T getOptionalPlugin(Class<T> clazz) { return (T)plugins.get(clazz); } /** * Install a bundle from the given location. */ public AbstractBundle installBundle(URL location) throws BundleException { return installBundle(location.toExternalForm(), null); } /** * Install a bundle from the given location. */ public AbstractBundle installBundle(String location) throws BundleException { return installBundle(location, null); } /** * Install a bundle from the given location and optional input stream. */ public AbstractBundle installBundle(String location, InputStream input) throws BundleException { if (location == null) throw new BundleException("Null location"); URL locationURL; // Get the location URL if (input != null) { try { BundleStoragePlugin plugin = getPlugin(BundleStoragePlugin.class); File streamFile = plugin.storeBundleStream(location, input, 0); locationURL = streamFile.toURI().toURL(); } catch (IOException ex) { throw new BundleException("Cannot store bundle from stream", ex); } } else { locationURL = getLocationURL(location); } // Get the root file VirtualFile rootFile; try { rootFile = AbstractVFS.toVirtualFile(locationURL); } catch (Exception ex) { throw new BundleException("Invalid bundle location=" + locationURL, ex); } AbstractBundle bundle; try { bundle = install(rootFile, location, false); } catch (BundleException ex) { deleteContentRoots(Collections.singletonList(rootFile)); throw ex; } return bundle; } /** * Install a bundle from the given {@link VirtualFile} */ private AbstractBundle install(VirtualFile rootFile, String location, boolean autoStart) throws BundleException { BundleDeploymentPlugin plugin = getPlugin(BundleDeploymentPlugin.class); Deployment dep = plugin.createDeployment(rootFile, location); return installBundle(dep); } /** * Install a bundle from a {@link ModuleIdentifier}. * * This method can be used to install plain modules or bundles to the {@link BundleManager}. * A plain module is one that does not have a valid OSGi manifest. * * When installing a plain module: * * - module dependencies are not installed automatically * - module may or may not have been loaded previously * - module cannot be installed multiple times */ public Bundle installBundle(ModuleIdentifier identifier) throws BundleException { BundleDeploymentPlugin plugin = getPlugin(BundleDeploymentPlugin.class); Deployment dep = plugin.createDeployment(identifier); return installBundle(dep); } /** * Install a bundle from a {@link Deployment} */ public AbstractBundle installBundle(Deployment dep) throws BundleException { if (dep == null) throw new IllegalArgumentException("Null deployment"); // If a bundle containing the same location identifier is already installed, // the Bundle object for that bundle is returned. AbstractBundle bundleState = getBundleByLocation(dep.getLocation()); if (bundleState != null) return bundleState; try { bundleState = createBundle(dep); } catch (BundleException ex) { deleteContentRoots(Collections.singletonList(dep.getRoot())); throw ex; } addBundleState(bundleState); return bundleState; } private AbstractBundle createBundle(Deployment dep) throws BundleException { BundleDeploymentPlugin deploymentPlugin = getPlugin(BundleDeploymentPlugin.class); OSGiMetaData metadata = deploymentPlugin.createOSGiMetaData(dep); // Create the bundle state boolean isFragment = metadata.getFragmentHost() != null; AbstractBundle bundleState = (isFragment ? new FragmentBundle(this, dep) : new HostBundle(this, dep)); dep.addAttachment(AbstractBundle.class, bundleState); // Validate the deployed bundle // The system bundle is not validated validateBundle(bundleState); // Process the Bundle-NativeCode header if there is one if (metadata.getBundleNativeCode() != null) { NativeCodePlugin nativeCodePlugin = getOptionalPlugin(NativeCodePlugin.class); if (nativeCodePlugin != null) nativeCodePlugin.deployNativeCode(dep); } return bundleState; } private void validateBundle(AbstractBundle bundleState) throws BundleException { OSGiMetaData osgiMetaData = bundleState.getOSGiMetaData(); if (osgiMetaData == null) return; BundleValidator validator; // Delegate to the validator for the appropriate revision if (osgiMetaData.getBundleManifestVersion() > 1) validator = new BundleValidatorR4(this); else validator = new BundleValidatorR3(this); validator.validateBundle(bundleState); } private URL getLocationURL(String location) throws BundleException { // Try location as URL URL url = null; try { url = new URL(location); } catch (MalformedURLException e) { // ignore } // Try location as File if (url == null) { try { File file = new File(location); if (file.exists()) url = file.toURI().toURL(); } catch (MalformedURLException e) { // ignore } } if (url == null) throw new BundleException("Unable to handle location=" + location); return url; } /** * Fire a framework error */ void fireError(Bundle bundle, String context, Throwable t) { FrameworkEventsPlugin plugin = getPlugin(FrameworkEventsPlugin.class); if (t instanceof BundleException) plugin.fireFrameworkEvent(bundle, FrameworkEvent.ERROR, t); else if (bundle != null) plugin.fireFrameworkEvent(bundle, FrameworkEvent.ERROR, new BundleException("Error " + context + " bundle: " + bundle, t)); else plugin.fireFrameworkEvent(getSystemBundle(), FrameworkEvent.ERROR, new BundleException("Error " + context, t)); } /** * Fire a framework warning */ void fireWarning(Bundle bundle, String context, Throwable t) { FrameworkEventsPlugin plugin = getPlugin(FrameworkEventsPlugin.class); if (t instanceof BundleException) plugin.fireFrameworkEvent(bundle, FrameworkEvent.WARNING, t); else if (bundle != null) plugin.fireFrameworkEvent(bundle, FrameworkEvent.WARNING, new BundleException("Error " + context + " bundle: " + bundle, t)); else plugin.fireFrameworkEvent(getSystemBundle(), FrameworkEvent.WARNING, new BundleException("Error " + context, t)); } void deleteContentRoots(List<VirtualFile> rootFiles) { File streamDir = getPlugin(BundleStoragePlugin.class).getBundleStreamDir(); for (VirtualFile rootFile : rootFiles) { // Close the virtual file String contentRootPath = rootFile.getPathName(); rootFile.close(); // Delete the stream dir if it exists if (contentRootPath.startsWith(streamDir.getAbsolutePath())) { File file = new File(contentRootPath); file.delete(); } } } }
package com.gentics.mesh.test.context; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.testcontainers.containers.wait.Wait; import com.gentics.mesh.Mesh; import com.gentics.mesh.cli.BootstrapInitializerImpl; import com.gentics.mesh.core.cache.PermissionStore; import com.gentics.mesh.core.data.impl.DatabaseHelper; import com.gentics.mesh.core.data.search.IndexHandler; import com.gentics.mesh.core.rest.MeshEvent; import com.gentics.mesh.crypto.KeyStoreHelper; import com.gentics.mesh.dagger.DaggerMeshComponent; import com.gentics.mesh.dagger.MeshComponent; import com.gentics.mesh.dagger.MeshInternal; import com.gentics.mesh.etc.config.HttpServerConfig; import com.gentics.mesh.etc.config.MeshOptions; import com.gentics.mesh.etc.config.MonitoringConfig; import com.gentics.mesh.etc.config.OAuth2Options; import com.gentics.mesh.etc.config.OAuth2ServerConfig; import com.gentics.mesh.etc.config.search.ElasticSearchOptions; import com.gentics.mesh.graphdb.spi.Database; import com.gentics.mesh.impl.MeshFactoryImpl; import com.gentics.mesh.rest.client.MeshRestClient; import com.gentics.mesh.rest.client.MeshRestClientConfig; import com.gentics.mesh.rest.client.impl.MeshRestOkHttpClientImpl; import com.gentics.mesh.rest.monitoring.MonitoringRestClient; import com.gentics.mesh.router.RouterStorage; import com.gentics.mesh.search.TrackingSearchProvider; import com.gentics.mesh.search.verticle.ElasticsearchProcessVerticle; import com.gentics.mesh.test.TestDataProvider; import com.gentics.mesh.test.docker.ElasticsearchContainer; import com.gentics.mesh.test.docker.KeycloakContainer; import com.gentics.mesh.test.util.TestUtils; import com.gentics.mesh.util.UUIDUtil; import com.syncleus.ferma.tx.Tx; import io.vertx.core.Vertx; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import okhttp3.OkHttpClient; public class MeshTestContext extends TestWatcher { static { System.setProperty(TrackingSearchProvider.TEST_PROPERTY_KEY, "true"); } private static final Logger log = LoggerFactory.getLogger(MeshTestContext.class); private static final String CONF_PATH = "target/config-" + System.currentTimeMillis(); private static MeshOptions meshOptions; public static ElasticsearchContainer elasticsearch; public static KeycloakContainer keycloak; public static OkHttpClient okHttp = new OkHttpClient.Builder() .callTimeout(Duration.ofMinutes(15)) .connectTimeout(Duration.ofMinutes(15)) .writeTimeout(Duration.ofMinutes(15)) .readTimeout(Duration.ofMinutes(15)) .build(); private List<File> tmpFolders = new ArrayList<>(); private MeshComponent meshDagger; private TestDataProvider dataProvider; private TrackingSearchProvider trackingSearchProvider; private Vertx vertx; protected int port; protected int monitoringPort; private MeshRestClient client; private MonitoringRestClient monitoringClient; private List<String> deploymentIds = new ArrayList<>(); private CountDownLatch idleLatch; private MessageConsumer<Object> idleConsumer; @Override protected void starting(Description description) { try { MeshTestSetting settings = getSettings(description); // Setup the dagger context and orientdb,es once if (description.isSuite()) { port = TestUtils.getRandomPort(); monitoringPort = TestUtils.getRandomPort(); removeDataDirectory(); removeConfigDirectory(); MeshOptions options = init(settings); initDagger(options, settings); meshDagger.boot().registerEventHandlers(); } else { if (!settings.inMemoryDB()) { DatabaseHelper.init(meshDagger.database()); } initFolders(Mesh.mesh().getOptions()); setupData(); listenToSearchIdleEvent(); switch (settings.elasticsearch()) { case CONTAINER: case CONTAINER_WITH_INGEST: setupIndexHandlers(); break; default: break; } if (settings.startServer()) { setupRestEndpoints(settings); } } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } @Override protected void finished(Description description) { try { MeshTestSetting settings = getSettings(description); if (description.isSuite()) { // TODO CI does not like this, reactivate later: // Mesh.mesh().shutdown(); removeDataDirectory(); removeConfigDirectory(); if (elasticsearch != null && elasticsearch.isRunning()) { elasticsearch.stop(); } if (keycloak != null && keycloak.isRunning()) { keycloak.stop(); } } else { cleanupFolders(); if (settings.startServer()) { undeployAndReset(); closeClient(); } idleConsumer.unregister(); switch (settings.elasticsearch()) { case CONTAINER: case EMBEDDED: case CONTAINER_WITH_INGEST: meshDagger.searchProvider().clear().blockingAwait(); break; case TRACKING: meshDagger.trackingSearchProvider().reset(); break; default: break; } resetDatabase(settings); } } catch (Exception e) { throw new RuntimeException(e); } } private void removeConfigDirectory() throws IOException { FileUtils.deleteDirectory(new File(CONF_PATH)); System.setProperty("mesh.confDirName", CONF_PATH); } private void removeDataDirectory() throws IOException { FileUtils.deleteDirectory(new File("data")); } protected void setupIndexHandlers() throws Exception { // We need to call init() again in order create missing indices for the created test data for (IndexHandler<?> handler : meshDagger.indexHandlerRegistry().getHandlers()) { handler.init().blockingAwait(); } } /** * Set Features according to the method annotations * * @param description */ protected MeshTestSetting getSettings(Description description) { Class<?> testClass = description.getTestClass(); if (testClass != null) { return testClass.getAnnotation(MeshTestSetting.class); } return description.getAnnotation(MeshTestSetting.class); } private void setupRestEndpoints(MeshTestSetting settings) throws Exception { Mesh.mesh().getOptions().getUploadOptions().setByteLimit(Long.MAX_VALUE); log.info("Using port: " + port); RouterStorage.addProject(TestDataProvider.PROJECT_NAME); // Setup the rest client try (Tx tx = db().tx()) { boolean ssl = settings.ssl(); MeshRestClientConfig clientConfig = new MeshRestClientConfig.Builder() .setHost("localhost") .setPort(port) .setSsl(ssl) .build(); client = new MeshRestOkHttpClientImpl(clientConfig, okHttp); client.setLogin(getData().user().getUsername(), getData().getUserInfo().getPassword()); client.login().blockingGet(); } log.info("Using monitoring port: " + monitoringPort); monitoringClient = MonitoringRestClient.create("localhost", monitoringPort); if (trackingSearchProvider != null) { trackingSearchProvider.clear().blockingAwait(); } } private Database db() { return meshDagger.database(); } public int getPort() { return port; } public Vertx getVertx() { return vertx; } /** * Setup the test data. * * @throws Exception */ private void setupData() throws Exception { meshDagger.database().setMassInsertIntent(); dataProvider.setup(); meshDagger.database().resetIntent(); } private void undeployAndReset() throws Exception { for (String id : deploymentIds) { vertx.undeploy(id); } } private void closeClient() throws Exception { if (client != null) { try { client.close(); } catch (IllegalStateException e) { // Ignored e.printStackTrace(); } } } /** * Clear the test data. * * @param settings * @throws Exception */ private void resetDatabase(MeshTestSetting settings) throws Exception { BootstrapInitializerImpl.clearReferences(); Database db = MeshInternal.get().database(); long start = System.currentTimeMillis(); if (settings.inMemoryDB()) { db.clear(); } else { db.stop(); File dbDir = new File(Mesh.mesh().getOptions().getStorageOptions().getDirectory()); FileUtils.deleteDirectory(dbDir); db.setupConnectionPool(); } long duration = System.currentTimeMillis() - start; log.info("Clearing DB took {" + duration + "} ms."); if (trackingSearchProvider != null) { trackingSearchProvider.reset(); } } private void cleanupFolders() throws IOException { for (File folder : tmpFolders) { FileUtils.deleteDirectory(folder); } PermissionStore.invalidate(false); } public TestDataProvider getData() { return dataProvider; } public TrackingSearchProvider getTrackingSearchProvider() { return trackingSearchProvider; } /** * Initialise mesh options. * * @param settings * @throws Exception */ public MeshOptions init(MeshTestSetting settings) throws Exception { MeshFactoryImpl.clear(); meshOptions = new MeshOptions(); if (settings == null) { throw new RuntimeException("Settings could not be found. Did you forgot to add the @MeshTestSetting annotation to your test?"); } // Clustering options if (settings.clusterMode()) { meshOptions.getClusterOptions().setEnabled(true); meshOptions.setInitCluster(true); meshOptions.getClusterOptions().setClusterName("cluster" + System.currentTimeMillis()); } // Setup the keystore File keystoreFile = new File("target", "keystore_" + UUIDUtil.randomUUID() + ".jceks"); keystoreFile.deleteOnExit(); String keystorePassword = "finger"; if (!keystoreFile.exists()) { KeyStoreHelper.gen(keystoreFile.getAbsolutePath(), keystorePassword); } meshOptions.getAuthenticationOptions().setKeystorePassword(keystorePassword); meshOptions.getAuthenticationOptions().setKeystorePath(keystoreFile.getAbsolutePath()); meshOptions.setNodeName("testNode"); initFolders(meshOptions); HttpServerConfig httpOptions = meshOptions.getHttpServerOptions(); httpOptions.setPort(port); if (settings.ssl()) { httpOptions.setSsl(true); httpOptions.setCertPath("src/test/resources/ssl/cert.pem"); httpOptions.setKeyPath("src/test/resources/ssl/key.pem"); } MonitoringConfig monitoringOptions = meshOptions.getMonitoringOptions(); monitoringOptions.setPort(monitoringPort); // The database provider will switch to in memory mode when no directory has been specified. String graphPath = null; if (!settings.inMemoryDB() || settings.clusterMode()) { graphPath = "target/graphdb_" + UUIDUtil.randomUUID(); File directory = new File(graphPath); directory.deleteOnExit(); directory.mkdirs(); } if (!settings.inMemoryDB() && settings.startStorageServer()) { meshOptions.getStorageOptions().setStartServer(true); } // Increase timeout to high load during testing ElasticSearchOptions searchOptions = meshOptions.getSearchOptions(); searchOptions.setTimeout(10_000L); meshOptions.getStorageOptions().setDirectory(graphPath); switch (settings.elasticsearch()) { case CONTAINER: case CONTAINER_WITH_INGEST: searchOptions.setStartEmbedded(false); elasticsearch = new ElasticsearchContainer(settings.elasticsearch() == ElasticsearchTestMode.CONTAINER_WITH_INGEST); if (!elasticsearch.isRunning()) { elasticsearch.start(); } elasticsearch.waitingFor(Wait.forHttp("/")); searchOptions.setUrl("http://localhost:" + elasticsearch.getMappedPort(9200)); break; case EMBEDDED: searchOptions.setStartEmbedded(true); break; case NONE: searchOptions.setUrl(null); searchOptions.setStartEmbedded(false); break; case TRACKING: System.setProperty(TrackingSearchProvider.TEST_PROPERTY_KEY, "true"); searchOptions.setStartEmbedded(false); break; default: break; } if (settings.useKeycloak()) { keycloak = new KeycloakContainer() .withRealmFromClassPath("/keycloak/realm.json"); if (!keycloak.isRunning()) { keycloak.start(); } keycloak.waitingFor(Wait.forListeningPort()); OAuth2Options oauth2Options = meshOptions.getAuthenticationOptions().getOauth2(); oauth2Options.setEnabled(true); OAuth2ServerConfig realmConfig = new OAuth2ServerConfig(); realmConfig.setAuthServerUrl("http://localhost:" + keycloak.getFirstMappedPort() + "/auth"); realmConfig.setRealm("master-test"); realmConfig.setSslRequired("external"); realmConfig.setResource("mesh"); realmConfig.setConfidentialPort(0); realmConfig.addCredential("secret", "9b65c378-5b4c-4e25-b5a1-a53a381b5fb4"); oauth2Options.setConfig(realmConfig); } Mesh.mesh(meshOptions); return meshOptions; } private void initFolders(MeshOptions meshOptions) throws IOException { String tmpDir = newFolder("tmpDir"); meshOptions.setTempDirectory(tmpDir); String uploads = newFolder("testuploads"); meshOptions.getUploadOptions().setDirectory(uploads); String targetUploadTmpDir = newFolder("uploadTmpDir"); meshOptions.getUploadOptions().setTempDirectory(targetUploadTmpDir); String imageCacheDir = newFolder("image_cache"); meshOptions.getImageOptions().setImageCacheDirectory(imageCacheDir); String backupPath = newFolder("backups"); meshOptions.getStorageOptions().setBackupDirectory(backupPath); String exportPath = newFolder("exports"); meshOptions.getStorageOptions().setExportDirectory(exportPath); } /** * Create a new folder which will be automatically be deleted once the rule finishes. * * @param prefix * @return * @throws IOException */ private String newFolder(String prefix) throws IOException { String path = "target/" + prefix + "_" + UUIDUtil.randomUUID(); File directory = new File(path); FileUtils.deleteDirectory(directory); directory.deleteOnExit(); assertTrue("Could not create dir for path {" + path + "}", directory.mkdirs()); tmpFolders.add(directory); return path; } /** * Initialise the mesh dagger context and inject the dependencies within the test. * * @param options * * @param settings * @throws Exception */ public void initDagger(MeshOptions options, MeshTestSetting settings) throws Exception { log.info("Initializing dagger context"); meshDagger = DaggerMeshComponent.builder() .configuration(options) .searchProviderType(settings.elasticsearch().toSearchProviderType()) .build(); MeshInternal.set(meshDagger); dataProvider = new TestDataProvider(settings.testSize(), meshDagger.boot(), meshDagger.database()); if (meshDagger.searchProvider() instanceof TrackingSearchProvider) { trackingSearchProvider = meshDagger.trackingSearchProvider(); } try { meshDagger.boot().init(Mesh.mesh(), false, options, null); vertx = Mesh.vertx(); } catch (Exception e) { e.printStackTrace(); throw e; } } public MonitoringRestClient getMonitoringClient() { return monitoringClient; } public MeshRestClient getClient() { return client; } public static KeycloakContainer getKeycloak() { return keycloak; } public MeshOptions getOptions() { return meshOptions; } private void listenToSearchIdleEvent() { idleConsumer = vertx.eventBus().consumer(MeshEvent.SEARCH_IDLE.address, handler -> { log.info("Got search idle event"); if (idleLatch != null) { idleLatch.countDown(); } }); } /** * Waits until all requests have been sent successfully. */ public void waitForSearchIdleEvent() { Objects.requireNonNull(idleConsumer, "Call #listenToSearchIdleEvent first"); ElasticsearchProcessVerticle verticle = getElasticSearchVerticle(); try { verticle.flush().blockingAwait(); idleLatch = new CountDownLatch(1); boolean success = idleLatch.await(30, TimeUnit.SECONDS); if (!success) { throw new RuntimeException("Timed out while waiting for search idle event"); } verticle.refresh().blockingAwait(); } catch (InterruptedException e) { e.printStackTrace(); } } public ElasticsearchProcessVerticle getElasticSearchVerticle() { return ((BootstrapInitializerImpl) meshDagger.boot()).loader.get().getSearchVerticle(); } }
package net.tomp2p.peers; import net.tomp2p.storage.StorageMemoryReplication; import org.junit.Assert; import org.junit.Test; public class TestStorageMemoryReplication { @Test public void testStorageMemoryReplication1() { StorageMemoryReplication storageMemoryReplication = new StorageMemoryReplication(); Number160 testLoc = Number160.createHash("test1"); Number160 testPer = Number160.createHash("test2"); storageMemoryReplication.updateResponsibilities(testLoc, testPer); Assert.assertEquals(testPer, storageMemoryReplication.findPeerIDsForResponsibleContent(testLoc).iterator().next()); } @Test public void testStorageMemoryReplication2() { StorageMemoryReplication storageMemoryReplication = new StorageMemoryReplication(); Number160 testLoc = Number160.createHash("test1"); Number160 testPer = Number160.createHash("test2"); storageMemoryReplication.updateResponsibilities(testLoc, testPer); Assert.assertEquals(testLoc, storageMemoryReplication.findContentForResponsiblePeerID(testPer).iterator() .next()); } @Test public void testStorageMemoryReplication3() { StorageMemoryReplication storageMemoryReplication = new StorageMemoryReplication(); Number160 testLoc = Number160.createHash("test1"); Number160 testPer = Number160.createHash("test2"); storageMemoryReplication.updateResponsibilities(testLoc, testPer); storageMemoryReplication.updateResponsibilities(testLoc, testPer); Assert.assertEquals(testPer, storageMemoryReplication.findPeerIDsForResponsibleContent(testLoc).iterator().next()); Assert.assertEquals(testLoc, storageMemoryReplication.findContentForResponsiblePeerID(testPer).iterator() .next()); } @Test public void testStorageMemoryReplication4() { StorageMemoryReplication storageMemoryReplication = new StorageMemoryReplication(); Number160 testLoc = Number160.createHash("test1"); Number160 testPer = Number160.createHash("test2"); storageMemoryReplication.updateResponsibilities(testLoc, testPer); storageMemoryReplication.updateResponsibilities(testLoc, testPer); storageMemoryReplication.removeResponsibility(testLoc); Assert.assertEquals(null, storageMemoryReplication.findPeerIDsForResponsibleContent(testLoc).iterator().next()); Assert.assertEquals(0, storageMemoryReplication.findContentForResponsiblePeerID(testPer).size()); } }
package com.cv4j.core.spatial.conv; import com.cv4j.core.datamodel.ColorProcessor; import com.cv4j.core.datamodel.ImageProcessor; import com.cv4j.core.filters.CommonFilter; import com.cv4j.image.util.Tools; public class GaussianBlurFilter implements CommonFilter { private float[] kernel; private double sigma = 2; public GaussianBlurFilter() { kernel = new float[0]; } public void setSigma(double a) { this.sigma = a; } @Override public ImageProcessor filter(ImageProcessor src){ int width = src.getWidth(); int height = src.getHeight(); makeGaussianKernel(sigma, 0.002, (int)Math.min(width, height)); int[] inPixels = src.getPixels(); int[] outPixels = new int[width*height]; blur( inPixels, outPixels, width, height); // H Gaussian blur( outPixels, inPixels, height, width); // V Gaussain // save result byte[] R = ((ColorProcessor)src).getRed(); byte[] G = ((ColorProcessor)src).getGreen(); byte[] B = ((ColorProcessor)src).getBlue(); getRGB(width, height, inPixels, R, G, B); return src; } public void getRGB(int width, int height, int[] pixels, byte[] R, byte[] G, byte[] B) { int c, r, g, b; for (int i=0; i < width*height; i++) { c = pixels[i]; r = (c&0xff0000)>>16; g = (c&0xff00)>>8; b = c&0xff; R[i] = (byte)r; G[i] = (byte)g; B[i] = (byte)b; } } /** * <p> here is 1D Gaussian , </p> * * @param inPixels * @param outPixels * @param width * @param height */ private void blur(int[] inPixels, int[] outPixels, int width, int height) { int subCol = 0; int index = 0, index2 = 0; float redSum=0, greenSum=0, blueSum=0; for(int row=0; row<height; row++) { int ta = 0, tr = 0, tg = 0, tb = 0; index = row; for(int col=0; col<width; col++) { // index = row * width + col; redSum=0; greenSum=0; blueSum=0; for(int m = 0; m< kernel.length; m++) { subCol = col + m; if(subCol < 0 || subCol >= width) { subCol = 0; } index2 = row * width + subCol; ta = (inPixels[index2] >> 24) & 0xff; tr = (inPixels[index2] >> 16) & 0xff; tg = (inPixels[index2] >> 8) & 0xff; tb = inPixels[index2] & 0xff; redSum += (tr * kernel[m]); greenSum += (tg * kernel[m]); blueSum += (tb * kernel[m]); } outPixels[index] = (ta << 24) | (Tools.clamp(redSum) << 16) | (Tools.clamp(greenSum) << 8) | Tools.clamp(blueSum); index += height;// correct index at here!!!, out put pixels matrix, } } } public void makeGaussianKernel(final double sigma, final double accuracy, int maxRadius) { int kRadius = (int)Math.ceil(sigma*Math.sqrt(-2*Math.log(accuracy)))+1; if (maxRadius < 50) maxRadius = 50; // too small maxRadius would result in inaccurate sum. if (kRadius > maxRadius) kRadius = maxRadius; kernel = new float[kRadius]; for (int i=0; i<kRadius; i++) // Gaussian function kernel[i] = (float)(Math.exp(-0.5*i*i/sigma/sigma)); double sum; // sum over all kernel elements for normalization if (kRadius < maxRadius) { sum = kernel[0]; for (int i=1; i<kRadius; i++) sum += 2*kernel[i]; } else sum = sigma * Math.sqrt(2*Math.PI); for (int i=0; i<kRadius; i++) { double v = (kernel[i]/sum); kernel[i] = (float)v; } return; } }
package nl.mpi.kinnate.gedcomimport; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import javax.swing.JTextArea; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import nl.mpi.arbil.data.ArbilComponentBuilder; import nl.mpi.arbil.data.ArbilDataNodeLoader; import nl.mpi.arbil.util.ArbilBugCatcher; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; import nl.mpi.kinnate.uniqueidentifiers.LocalIdentifier; import org.w3c.dom.Attr; public class GedcomImporter extends EntityImporter implements GenericImporter { public GedcomImporter(boolean overwriteExistingLocal) { super(overwriteExistingLocal); } @Override public boolean canImport(String inputFileString) { return (inputFileString.toLowerCase().endsWith(".ged")); } @Override public URI[] importFile(JTextArea importTextArea, InputStreamReader inputStreamReader) { ArrayList<URI> createdNodes = new ArrayList<URI>(); createdNodeIds = new HashMap<String, ArrayList<UniqueIdentifier>>(); // Hashtable<String, URI> createdNodesTable = new Hashtable<String, URI>(); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // ArrayList<ImdiTreeObject> linkNodes = new ArrayList<ImdiTreeObject>(); // really should close the file properly but this is only for testing at this stage // URI targetFileURI = LinorgSessionStorage.getSingleInstance().getNewImdiFileName(LinorgSessionStorage.getSingleInstance().getCacheDirectory(), gedcomXsdLocation); // try { // targetFileURI = componentBuilder.createComponentFile(targetFileURI, this.getClass().getResource(gedcomXsdLocation).toURI(), false); // } catch (URISyntaxException ex) { // new ArbilBugCatcher().logError(ex); // return; // metadataBuilder.addChildNode(gedcomImdiObject, ".Gedcom.Relation", null, null, null); // gedcomImdiObject.loadImdiDom(); // gedcomImdiObject.waitTillLoaded(); try { String strLine; int gedcomLevel = 0; String xsdString = ""; // temp string to create the xsd ArrayList<String> xsdTagsDone = new ArrayList<String>(); // temp array to create the xsd ArrayList<String> gedcomLevelStrings = new ArrayList<String>(); ArrayList<String> xsdLevelStrings = new ArrayList<String>(); // temp array to create the xsd // ImdiTreeObject gedcomImdiObject = null; File entityFile = null; Document metadataDom = null; Element previousField = null; Node currentDomNode = null; File destinationDirectory = super.getDestinationDirectory(); // String gedcomPreviousPath = ""; int currntLineCounter = 0; boolean skipFileEntity = false; while ((strLine = bufferedReader.readLine()) != null) { if (skipFileEntity) { skipFileEntity = false; while ((strLine = bufferedReader.readLine()) != null) { if (strLine.startsWith("0")) { break; } } } String[] lineParts = strLine.split(" ", 3); gedcomLevel = Integer.parseInt(lineParts[0]); while (gedcomLevelStrings.size() > gedcomLevel) { gedcomLevelStrings.remove(gedcomLevelStrings.size() - 1); } while (xsdLevelStrings.size() > gedcomLevel) { xsdLevelStrings.remove(xsdLevelStrings.size() - 1); xsdString += "</xs:sequence>\n</xs:complexType>\n</xs:element>\n"; //currentDomNode = currentDomNode.getParentNode(); } gedcomLevelStrings.add(lineParts[1]); System.out.println(strLine); System.out.println("gedcomLevelString: " + gedcomLevelStrings); // appendToTaskOutput(importTextArea, strLine); boolean lastFieldContinued = false; if (lineParts[1].equals("CONT")) { if (previousField != null) { // todo: if the previous field is null this should be caught and handled as an error in the source file String lineContents = ""; if (lineParts.length > 2) { lineContents = lineParts[2]; } previousField.setTextContent(previousField.getTextContent() + "\n" + lineContents); } lastFieldContinued = true; } else if (lineParts[1].equals("CONC")) { if (previousField != null) { // todo: if the previous field is null this should be caught and handled as an error in the source file String lineContents = ""; if (lineParts.length > 2) { lineContents = lineParts[2]; } previousField.setTextContent(previousField.getTextContent() + lineContents); } lastFieldContinued = true; } if (lastFieldContinued == false) { previousField = null; if (gedcomLevel == 0) { // if (createdNodes.size() > 20) { // appendToTaskOutput(importTextArea, "stopped import at node count: " + createdNodes.size()); // break; if (metadataDom != null) { ArbilComponentBuilder.savePrettyFormatting(metadataDom, entityFile); metadataDom = null; } if (lineParts[1].equals("TRLR")) { appendToTaskOutput(importTextArea, "End of file found"); } else { // String gedcomXsdLocation = "/xsd/gedcom-import.xsd"; String gedcomXsdLocation = "/xsd/gedcom-autogenerated.xsd"; URI entityUri; entityFile = new File(destinationDirectory, cleanFileName(lineParts[1])); // todo: this should be replaced by an entity object UniqueIdentifier uniquieIdentifier = new UniqueIdentifier(UniqueIdentifier.IdentifierType.lid);//LocalIdentifier().getUniqueIdentifier(entityFile); String typeString; if (lineParts.length > 2) { typeString = lineParts[2]; } else { typeString = lineParts[1]; } if (createdNodeIds.get(typeString) == null) { ArrayList<UniqueIdentifier> idArray = new ArrayList<UniqueIdentifier>(); idArray.add(uniquieIdentifier); createdNodeIds.put(typeString, idArray); } else { createdNodeIds.get(typeString).add(uniquieIdentifier); } if (!overwriteExisting && entityFile.exists()) { skipFileEntity = true; appendToTaskOutput(importTextArea, "Skipping existing entity file"); } else { // start skip overwrite try { entityUri = new ArbilComponentBuilder().createComponentFile(entityFile.toURI(), this.getClass().getResource(gedcomXsdLocation).toURI(), false); } catch (URISyntaxException ex) { new ArbilBugCatcher().logError(ex); appendToTaskOutput(importTextArea, "Error: " + ex.getMessage()); return null; // } catch (org.apache.xmlbeans.XmlException ex) { // new ArbilBugCatcher().logError(ex); // appendToTaskOutput(importTextArea, "error: " + ex.getMessage()); // return; } // appendToTaskOutput(importTextArea, "--> new node started"); // gedcomImdiObject = ImdiLoader.getSingleInstance().getImdiObject(null, eniryFileURI); //gedcomImdiObject.waitTillLoaded(); // appendToTaskOutput(importTextArea, "--> InternalNameT1" + lineParts[1] + " : " + entityUri); // createdNodesTable.put(lineParts[1], entityUri); createdNodes.add(entityUri); metadataDom = ArbilComponentBuilder.getDocument(entityUri); currentDomNode = metadataDom.getDocumentElement(); // // find the deepest element node to start adding child nodes to // for (Node childNode = currentDomNode.getFirstChild(); childNode != null; childNode = childNode.getNextSibling()) { // System.out.println("childNode: " + childNode); // System.out.println("childNodeType: " + childNode.getNodeType()); // if (childNode.getNodeType() == Node.ELEMENT_NODE) { // System.out.println("entering node"); // currentDomNode = childNode; // childNode = childNode.getFirstChild(); // if (childNode == null) { // break; try { // add a unique identifier to the entity node Attr typeAttribute = metadataDom.createAttribute("type"); typeAttribute.setTextContent(UniqueIdentifier.IdentifierType.lid.name()); Node uniqueIdentifierNode = org.apache.xpath.XPathAPI.selectSingleNode(metadataDom, "/:Kinnate/:Gedcom/:UniqueIdentifier"); uniqueIdentifierNode.getAttributes().setNamedItem(typeAttribute); uniqueIdentifierNode.setTextContent(uniquieIdentifier.getQueryIdentifier()); } catch (DOMException exception) { new ArbilBugCatcher().logError(exception); } catch (TransformerException exception) { new ArbilBugCatcher().logError(exception); } if (lineParts[1].equals("HEAD")) { // because the schema specifies 1:1 of both head and entity we find rather than create the head and entity nodes // Node headElement = currentDomNode; // Element headElement = metadataDom.createElement("HEAD"); // currentDomNode.appendChild(headElement); try { currentDomNode = org.apache.xpath.XPathAPI.selectSingleNode(metadataDom, "/:Kinnate/:Gedcom/:HEAD"); } catch (DOMException exception) { new ArbilBugCatcher().logError(exception); } catch (TransformerException exception) { new ArbilBugCatcher().logError(exception); } appendToTaskOutput(importTextArea, "Reading Gedcom Header"); } else { // because the schema specifies 1:1 of both head and entity we find rather than create the head and entity nodes // Node entityElement = null; // for (Node siblingNode = currentDomNode.getNextSibling(); siblingNode != null; siblingNode = siblingNode.getNextSibling()) { // if (siblingNode.getNodeName().equals("Entity")) { // entityElement = siblingNode; // break; Node gedcomIdElement = null; // metadataDom.createElement("GedcomId"); Node gedcomTypeElement = null; // metadataDom.createElement("GedcomType"); try { currentDomNode = org.apache.xpath.XPathAPI.selectSingleNode(metadataDom, "/:Kinnate/:Gedcom/:Entity"); gedcomIdElement = org.apache.xpath.XPathAPI.selectSingleNode(metadataDom, "/:Kinnate/:Gedcom/:Entity/:GedcomId"); gedcomTypeElement = org.apache.xpath.XPathAPI.selectSingleNode(metadataDom, "/:Kinnate/:Gedcom/:Entity/:GedcomType"); } catch (DOMException exception) { new ArbilBugCatcher().logError(exception); } catch (TransformerException exception) { new ArbilBugCatcher().logError(exception); } // Element entityElement = metadataDom.createElement("Entity"); // currentDomNode.appendChild(entityElement); // currentDomNode = entityElement; // Element nameElement = metadataDom.createElement("NAME"); // currentDomNode.appendChild(nameElement); // System.out.println("currentDomElement: " + currentDomNode); // currentDomNode.appendChild(gedcomIdElement); // for (Node siblingNode = currentDomNode.getFirstChild(); siblingNode != null; siblingNode = siblingNode.getNextSibling()) { // if (siblingNode.getNodeName().equals("GedcomId")) { // gedcomIdElement = siblingNode; // if (siblingNode.getNodeName().equals("GedcomType")) { // gedcomTypeElement = siblingNode; gedcomIdElement.setTextContent(lineParts[1]); if (lineParts.length > 2) { appendToTaskOutput(importTextArea, lineParts[2]); gedcomTypeElement.setTextContent(lineParts[2]); // currentDomNode.appendChild(gedcomTypeElement); if (lineParts[2].equals("NOTE")) { Element addedNoteElement = metadataDom.createElement("NoteText"); currentDomNode.appendChild(addedNoteElement); previousField = addedNoteElement; } } } System.out.println("currentDomElement: " + currentDomNode + " value: " + currentDomNode.getTextContent()); } } // end skip overwrite } else { // if (lineParts.length > 2) { // todo: move this into an array to be processed after all the fields have been insterted //// gedcomImdiObject.saveChangesToCache(true); // try { // URI linkUri = metadataBuilder.addChildNode(gedcomImdiObject, ".Gedcom.Relation", null, null, null); // ImdiTreeObject linkImdiObject = ImdiLoader.getSingleInstance().getImdiObject(null, linkUri); // appendToTaskOutput(importTextArea, "--> gedcomImdiObject.getChildCount: " + gedcomImdiObject.getChildCount()); // gedcomImdiObject.loadImdiDom(); // gedcomImdiObject.clearChildIcons(); // gedcomImdiObject.clearIcon(); //// gedcomImdiObject.waitTillLoaded(); // appendToTaskOutput(importTextArea, "--> link url: " + linkImdiObject.getUrlString()); //// appendToTaskOutput(importTextArea, "--> InternalNameT2" + lineParts[2] + " : " + linkImdiObject.getUrlString()); //// createdNodesTable.put(lineParts[2], linkImdiObject.getUrlString()); //// createdNodes.add(linkImdiObject.getUrlString()); //// System.out.println("keys: " + linkImdiObject.getFields().keys().nextElement()); // ImdiField[] currentField = linkImdiObject.getFields().get("Link"); // if (currentField != null && currentField.length > 0) { // appendToTaskOutput(importTextArea, "--> Link" + lineParts[2]); // // the target of this link might not be read in at this point so lets store the fields for updateing later // //createdNodesTable.get(lineParts[2]) // currentField[0].setFieldValue(lineParts[2], false, true); // linkNodes.add(linkImdiObject); //// appendToTaskOutput(importTextArea, "--> link count: " + linkFields.size()); // ImdiField[] currentField1 = linkImdiObject.getFields().get("Type"); // if (currentField1 != null && currentField1.length > 0) { // appendToTaskOutput(importTextArea, "--> Type" + lineParts[1]); // currentField1[0].setFieldValue(lineParts[1], false, true); // ImdiField[] currentField2 = linkImdiObject.getFields().get("TargetName"); // if (currentField2 != null && currentField2.length > 0) { // appendToTaskOutput(importTextArea, "--> TargetName" + lineParts[2]); // currentField2[0].setFieldValue(lineParts[2], false, true); // } catch (ArbilMetadataException arbilMetadataException) { // System.err.println(arbilMetadataException.getMessage()); // trim the nodes to the current gedcom level int parentNodeCount = 0; for (Node countingDomNode = currentDomNode; countingDomNode != null; countingDomNode = countingDomNode.getParentNode()) { parentNodeCount++; } for (int nodeCount = parentNodeCount; nodeCount > gedcomLevel + 3; nodeCount System.out.println("gedcomLevel: " + gedcomLevel + " parentNodeCount: " + parentNodeCount + " nodeCount: " + nodeCount + " exiting from node: " + currentDomNode); currentDomNode = currentDomNode.getParentNode(); } if (lineParts[1].equals("NAME") && currentDomNode.getNodeName().equals("Entity")) { // find the existing node if only one should exist System.out.println("Found Name Node easching: " + currentDomNode.getNodeName()); for (Node childNode = currentDomNode.getFirstChild(); childNode != null; childNode = childNode.getNextSibling()) { System.out.println(childNode.getNodeName()); if (childNode.getNodeName().equals("NAME")) { System.out.println("Using found node"); currentDomNode = childNode; break; } } appendToTaskOutput(importTextArea, "Name: " + lineParts[2]); } else { System.out.println("Creating Node: " + lineParts[1]); // otherwise add the current gedcom node Element addedElement = metadataDom.createElement(lineParts[1]); currentDomNode.appendChild(addedElement); currentDomNode = addedElement; } // if the current line has a value then enter it into the node if (lineParts.length > 2) { // if (lineParts[1].equals("NAME")) { // ImdiField[] currentField = gedcomImdiObject.getFields().get("Gedcom.Name"); // if (currentField != null && currentField.length > 0) { // currentField[0].setFieldValue(lineParts[2], false, true); // previousField = currentField; // } else { // System.err.println("missing field for: " + lineParts[1]); // previousField = null; // } else { String gedcomPath = "Kinnate.Gedcom"; // int loopLevelCount = 0; // int nodeLevelCount = 0; // Node nodeLevelCountNode = currentDomNode; // while (nodeLevelCountNode != null) { // nodeLevelCountNode = nodeLevelCountNode.getParentNode(); // nodeLevelCount++; for (String levelString : gedcomLevelStrings) { if (levelString.startsWith("@")) { // this could be handled better // this occurs at level 0 where the element type is named eg "0 @I9@ INDI" levelString = "Entity"; } gedcomPath = gedcomPath + "." + levelString; // loopLevelCount++; // if (loopLevelCount > nodeLevelCount) { // Element addedElement = metadataDom.createElement(levelString); // currentDomNode.appendChild(addedElement); // currentDomNode = addedElement; } List<String> swapList = Arrays.asList(new String[]{ "Kinnate.Gedcom.HEAD.SOUR", "Kinnate.Gedcom.HEAD.CORP", "Kinnate.Gedcom.HEAD.CORP.ADDR", "Kinnate.Gedcom.HEAD.SOUR.DATA", "Kinnate.Gedcom.HEAD.CHAN.DATE", "Kinnate.Gedcom.HEAD.DATE", "Kinnate.Gedcom.HEAD.CHAR", "Kinnate.Gedcom.Entity.NAME", "Kinnate.Gedcom.Entity.REFN", "Kinnate.Gedcom.Entity.REPO", "Kinnate.Gedcom.Entity.DATA", "Kinnate.Gedcom.Entity.ENGA", "Kinnate.Gedcom.Entity.ENGA.SOUR", "Kinnate.Gedcom.Entity.MARB", "Kinnate.Gedcom.Entity.MARB.SOUR", "Kinnate.Gedcom.Entity.MARC", "Kinnate.Gedcom.Entity.MARC.SOUR", "Kinnate.Gedcom.Entity.MARL", "Kinnate.Gedcom.Entity.MARL.SOUR", "Kinnate.Gedcom.Entity.MARS", "Kinnate.Gedcom.Entity.MARS.SOUR", "Kinnate.Gedcom.Entity.DIV", "Kinnate.Gedcom.Entity.DIV.SOUR", "Kinnate.Gedcom.Entity.DIVF", "Kinnate.Gedcom.Entity.DIVF.SOUR", "Kinnate.Gedcom.Entity.DATA.EVEN", "Kinnate.Gedcom.Entity.REPO.CALN", "Kinnate.Gedcom.Entity.NAME.SOUR", "Kinnate.Gedcom.Entity.ADDR", "Kinnate.Gedcom.Entity.CHAN.DATE", "Kinnate.Gedcom.Entity.DEAT", "Kinnate.Gedcom.Entity.OBJE", "Kinnate.Gedcom.HEAD.SOUR.CORP", "Kinnate.Gedcom.HEAD.SOUR.CORP.ADDR", "Kinnate.Gedcom.Entity.ANUL"}); Element addedExtraElement = null; if (swapList.contains(gedcomPath)) { gedcomPath += "." + lineParts[1]; addedExtraElement = metadataDom.createElement(lineParts[1]); currentDomNode.appendChild(addedExtraElement); currentDomNode = addedExtraElement; } currentDomNode.setTextContent(/*gedcomPath + " : " +*/lineParts[2]); if (addedExtraElement != null) { addedExtraElement = null; currentDomNode = currentDomNode.getParentNode(); } // currentDomNode = currentDomNode.getParentNode(); // System.out.println("is template: " + gedcomImdiObject.nodeTemplate.pathIsChildNode(gedcomPath)); if (!xsdTagsDone.contains(gedcomPath)) { while (gedcomLevelStrings.size() > xsdLevelStrings.size() + 1) { String xsdLevelString = gedcomLevelStrings.get(xsdLevelStrings.size()); if (xsdLevelString.startsWith("@")) { // this occurs at level 0 where the element type is named eg "0 @I9@ INDI" xsdLevelString = "NamedElement"; } xsdLevelStrings.add(xsdLevelString); xsdString += " <xs:element name=\"" + xsdLevelString + "\">\n"; xsdString += "<xs:complexType>\n<xs:sequence>\n"; } // while (gedcomLevelStrings.size() < xsdLevelStrings.size()) { // xsdLevelStrings.remove(xsdLevelStrings.size() - 1); // xsdString += "</xs:sequence>\n</xs:complexType>\n"; String xsdElementString = lineParts[1]; if (xsdElementString.startsWith("@")) { // this occurs at level 0 where the element type is named eg "0 @I9@ INDI" xsdElementString = "NamedElement"; } xsdString += " <xs:element name=\"" + xsdElementString + "\" />\n";// + gedcomPath + "\n" + strLine + "\n"; xsdTagsDone.add(gedcomPath); } // create the link node when required if (lineParts[2].startsWith("@") && lineParts[2].endsWith("@")) { appendToTaskOutput(importTextArea, "--> adding relation"); Element relationElement = metadataDom.createElement("Relation"); metadataDom.getDocumentElement().appendChild(relationElement); Element linkElement = metadataDom.createElement("Link"); linkElement.setTextContent("./" + cleanFileName(lineParts[2])); relationElement.appendChild(linkElement); // add a unique identifier of the target entity to the link Element uniqueIdentifierElement = metadataDom.createElement("UniqueIdentifier"); Element localIdentifierElement = metadataDom.createElement("LocalIdentifier"); localIdentifierElement.setTextContent(new LocalIdentifier().getUniqueIdentifier(new File(entityFile.getParentFile(), cleanFileName(lineParts[2])))); uniqueIdentifierElement.appendChild(localIdentifierElement); relationElement.appendChild(uniqueIdentifierElement); Element typeElement = metadataDom.createElement("Type"); typeElement.setTextContent(gedcomPath); relationElement.appendChild(typeElement); Element targetNameElement = metadataDom.createElement("TargetName"); targetNameElement.setTextContent(lineParts[2]); relationElement.appendChild(targetNameElement); // appendToTaskOutput(importTextArea, "--> typeElement: " + typeElement.getTextContent()); // appendToTaskOutput(importTextArea, "--> typeElement: " + typeElement.getNodeName()); // appendToTaskOutput(importTextArea, "--> typeElement: " + typeElement.getParentNode().getNodeName()); // appendToTaskOutput(importTextArea, "--> typeElement: " + typeElement.getParentNode().getParentNode().getNodeName()); } } } } currntLineCounter++; int currentProgressPercent = (int) ((double) currntLineCounter / (double) inputLineCount * 100); if (progressBar != null) { progressBar.setValue(currentProgressPercent); } } if (metadataDom != null) { ArbilComponentBuilder.savePrettyFormatting(metadataDom, entityFile); metadataDom = null; } // ImdiLoader.getSingleInstance().saveNodesNeedingSave(true); // appendToTaskOutput(importTextArea, "--> link count: " + linkFields.size()); // update all the links now we have the urls for each internal name // appendToTaskOutput(importTextArea, "xsdString:\n" + xsdString); // int linkNodesUpdated = 0; // for (URI currentUri : createdNodes) { // appendToTaskOutput(importTextArea, "linkParent: " + currentUri.toASCIIString()); // try { // String linkXpath = "/Kinnate/Relation/Link"; // Document linksDom = new CmdiComponentBuilder().getDocument(currentUri); // NodeList relationLinkNodeList = org.apache.xpath.XPathAPI.selectNodeList(linksDom, linkXpath); // for (int nodeCounter = 0; nodeCounter < relationLinkNodeList.getLength(); nodeCounter++) { // Node relationLinkNode = relationLinkNodeList.item(nodeCounter); // if (relationLinkNode != null) { // // todo: update the links // // todo: create links in ego and alter but but the type info such as famc only in the relevant entity // String linkValue = createdNodesTable.get(relationLinkNode.getTextContent()); // if (linkValue != null) { // relationLinkNode.setTextContent(linkValue); // appendToTaskOutput(importTextArea, "linkValue: " + linkValue); // new CmdiComponentBuilder().savePrettyFormatting(linksDom, currentImdiObject.getFile()); // } catch (TransformerException exception) { // new ArbilBugCatcher().logError(exception); // linkNodesUpdated++; // if (progressBar != null) { // progressBar.setValue((int) ((double) linkNodesUpdated / (double) createdNodes.size() * 100 / 2 + 50)); appendToTaskOutput(importTextArea, "Import finished with a node count of: " + createdNodes.size()); // gedcomImdiObject.saveChangesToCache(true); // gedcomImdiObject.loadImdiDom(); // gedcomImdiObject.clearChildIcons(); // gedcomImdiObject.clearIcon(); ArbilDataNodeLoader.getSingleInstance().saveNodesNeedingSave(true); } catch (IOException exception) { new ArbilBugCatcher().logError(exception); appendToTaskOutput(importTextArea, "Error: " + exception.getMessage()); } catch (ParserConfigurationException parserConfigurationException) { new ArbilBugCatcher().logError(parserConfigurationException); appendToTaskOutput(importTextArea, "Error: " + parserConfigurationException.getMessage()); } catch (DOMException dOMException) { new ArbilBugCatcher().logError(dOMException); appendToTaskOutput(importTextArea, "Error: " + dOMException.getMessage()); } catch (SAXException sAXException) { new ArbilBugCatcher().logError(sAXException); appendToTaskOutput(importTextArea, "Error: " + sAXException.getMessage()); } // LinorgSessionStorage.getSingleInstance().loadStringArray("KinGraphTree"); // String[] createdNodePaths = new String[createdNodes.size()]; // int createdNodeCounter = 0; // for (URI currentUri : createdNodes) { // createdNodePaths[createdNodeCounter] = currentUri.toASCIIString(); //// createdNodeCounter++; // LinorgSessionStorage.getSingleInstance().saveStringArray("KinGraphTree", createdNodePaths); return createdNodes.toArray(new URI[]{}); } }
package nl.mpi.kinnate.kindata; import java.awt.Component; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlTransient; import nl.mpi.kinnate.ui.HidePane; public class VisiblePanelSetting { public enum PanelType { KinTypeStrings, KinTerms, ArchiveLinker, // @Deprecated // MetaData, IndexerSettings, DiagramTree, EntitySearch } @XmlAttribute(name = "type", namespace = "http://mpi.nl/tla/kin") PanelType panelType; @XmlAttribute(name = "show", namespace = "http://mpi.nl/tla/kin") boolean panelShown; @XmlAttribute(name = "width", namespace = "http://mpi.nl/tla/kin") int panelWidth; @XmlTransient private String displayName; @XmlTransient private HidePane hidePane; @XmlTransient private Component targetPanel; public VisiblePanelSetting() { } public VisiblePanelSetting(PanelType panelType, boolean panelShown, int panelWidth) { this.panelType = panelType; this.panelShown = panelShown; this.panelWidth = panelWidth; } private void setUpdateUiState() { if (panelShown) { hidePane.addTab(this); } else { hidePane.remove(this); } } public void setTargetPanel(HidePane hidePane, Component targetPanel, String displayName) { this.hidePane = hidePane; this.targetPanel = targetPanel; this.displayName = displayName; setUpdateUiState(); } public boolean isPanelShown() { return panelShown; } @XmlTransient public void setPanelShown(boolean panelShown) { this.panelShown = panelShown; setUpdateUiState(); } @XmlTransient public void setPanelWidth(int panelWidth) { this.panelWidth = panelWidth; } public int getPanelWidth() { return panelWidth; } public Component getTargetPanel() { return targetPanel; } public String getDisplayName() { return displayName; } public PanelType getPanelType() { return panelType; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final VisiblePanelSetting other = (VisiblePanelSetting) obj; if (this.panelType != other.panelType) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 67 * hash + (this.panelType != null ? this.panelType.hashCode() : 0); return hash; } }
package com.utn.ag.viajante.impl; import com.utn.ag.algoritmocanonico.AppConstants; import com.utn.ag.algoritmocanonico.MockedLogger; import com.utn.ag.algoritmocanonico.vo.InformeVO; import com.utn.ag.viajante.model.Constants; import com.utn.ag.viajante.model.Poblacion; import java.io.IOException; public class App { public static void main(String[] args) throws IOException { HeuristicaFacu.DEBUG = Boolean.FALSE; System.out.println("Algoritmo Heurístico:"); int mejorCiudad = -1; int mejorRecorrido = -1; for (int i = 0; i < Constants.CANTIDAD_PROVINCIAS; i++) { HeuristicaFacu hf = new HeuristicaFacu(); hf.recorreCiudades(i); if (mejorRecorrido < 0 || mejorRecorrido > hf.getKmRecorridos()) { mejorRecorrido = hf.getKmRecorridos(); mejorCiudad = i; } hf.printCiudadesRecorridas(); } System.out.println("Mejor ciudad: " + mejorCiudad + " - " + Constants.NOMBRES_PROVINCIAS[mejorCiudad] + " km recorridos: " + mejorRecorrido); System.out.println( "\n\nAlgoritmo Genético:"); } }
package org.opencms.security; import static com.lambdaworks.codec.Base64.decode; import static org.junit.Assert.assertNotEquals; import org.opencms.db.CmsLoginMessage; import org.opencms.file.CmsObject; import org.opencms.file.CmsUser; import org.opencms.i18n.CmsEncoder; import org.opencms.main.CmsException; import org.opencms.main.OpenCms; import org.opencms.test.OpenCmsTestCase; import org.opencms.test.OpenCmsTestProperties; import com.lambdaworks.crypto.SCryptUtil; import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests login and password related functions.<p> * * * @since 6.0 */ public class TestLoginAndPasswordHandler extends OpenCmsTestCase { /** * Default JUnit constructor.<p> * * @param arg0 JUnit parameters */ public TestLoginAndPasswordHandler(String arg0) { super(arg0); } /** * Test suite for this test class.<p> * * @return the test suite */ public static Test suite() { OpenCmsTestProperties.initialize(org.opencms.test.AllTests.TEST_PROPERTIES_PATH); TestSuite suite = new TestSuite(); suite.setName(TestLoginAndPasswordHandler.class.getName()); suite.addTest(new TestLoginAndPasswordHandler("testSCrypt")); suite.addTest(new TestLoginAndPasswordHandler("testUserDefaultPasswords")); suite.addTest(new TestLoginAndPasswordHandler("testCheckPasswordDigest")); suite.addTest(new TestLoginAndPasswordHandler("testPasswordConvesion")); suite.addTest(new TestLoginAndPasswordHandler("testLoginUser")); suite.addTest(new TestLoginAndPasswordHandler("testLoginMessage")); suite.addTest(new TestLoginAndPasswordHandler("testPasswordValidation")); suite.addTest(new TestLoginAndPasswordHandler("testSetResetPassword")); TestSetup wrapper = new TestSetup(suite) { @Override protected void setUp() { setupOpenCms("simpletest", "/"); } @Override protected void tearDown() { removeOpenCms(); } }; return wrapper; } /** * Tests if the password is digested and stored correctly.<p> * * @throws Throwable if something goes wrong */ public void testCheckPasswordDigest() throws Throwable { echo("Testing if the password is digested and stored correctly"); String adminUsername = OpenCms.getDefaultUsers().getUserAdmin(); CmsObject cms = getCmsObject(); // change password of admin String newPassword = "theNewPassword01"; String newPasswordDigested = OpenCms.getPasswordHandler().digest(newPassword); cms.setPassword("Admin", "admin", newPassword); CmsUser adminUser = cms.readUser(adminUsername); String adminUserPassword = adminUser.getPassword(); // change password back, otherwise further tests would fail cms.setPassword(adminUsername, newPassword, "admin"); echo("Digested password: " + newPasswordDigested); echo("User password : " + adminUserPassword); assertTrue( "Passwords do not validate", OpenCms.getPasswordHandler().checkPassword(newPassword, newPasswordDigested, false)); assertEquals( "Password length for Admin user not equal to expected digested password length", adminUserPassword.length(), newPasswordDigested.length()); } /** * Tests the login message functions.<p> * * @throws Exception if the test fails */ public void testLoginMessage() throws Exception { echo("Testing login messages"); // this will be initialized as "Admin" CmsObject cms = getCmsObject(); String adminUser = OpenCms.getDefaultUsers().getUserAdmin(); String test1User = "test1"; // initial the login message must be null assertNull(OpenCms.getLoginManager().getLoginMessage()); String message = "This is the test login message"; // check a "blocking" login message CmsLoginMessage loginMessage = new CmsLoginMessage(message, true); OpenCms.getLoginManager().setLoginMessage(cms, loginMessage); CmsException error = null; try { cms.loginUser(test1User, "test1"); } catch (CmsAuthentificationException e) { error = e; } assertNotNull(error); if (error != null) { assertSame(Messages.ERR_LOGIN_FAILED_WITH_MESSAGE_1, error.getMessageContainer().getKey()); assertTrue(error.getMessage().indexOf(message) > 0); } cms.loginUser(adminUser, "admin"); // remove message and try again OpenCms.getLoginManager().removeLoginMessage(cms); cms.loginUser(test1User, "test1"); cms.loginUser(adminUser, "admin"); // check a "non blocking" login message loginMessage = new CmsLoginMessage(message, false); OpenCms.getLoginManager().setLoginMessage(cms, loginMessage); cms.loginUser(test1User, "test1"); cms.loginUser(adminUser, "admin"); // check an expired login message loginMessage = new CmsLoginMessage(0, System.currentTimeMillis(), message, true); OpenCms.getLoginManager().setLoginMessage(cms, loginMessage); cms.loginUser(test1User, "test1"); cms.loginUser(adminUser, "admin"); // check a login message in the far future loginMessage = new CmsLoginMessage(System.currentTimeMillis() + 100000, Long.MAX_VALUE, message, true); OpenCms.getLoginManager().setLoginMessage(cms, loginMessage); cms.loginUser(test1User, "test1"); cms.loginUser(adminUser, "admin"); loginMessage = new CmsLoginMessage(message, true); OpenCms.getLoginManager().setLoginMessage(cms, loginMessage); error = null; try { cms.loginUser(test1User, "test1"); } catch (CmsAuthentificationException e) { error = e; } assertNotNull(error); if (error != null) { assertSame(Messages.ERR_LOGIN_FAILED_WITH_MESSAGE_1, error.getMessageContainer().getKey()); assertTrue(error.getMessage().indexOf(message) > 0); } cms.loginUser(adminUser, "admin"); OpenCms.getLoginManager().removeLoginMessage(cms); } /** * Tests logging in as a user (checking for different kind of exceptions).<p> * * @throws Exception if the test fails */ public void testLoginUser() throws Exception { echo("Testing Exception behaviour during login"); // this will be initialized as "Admin" CmsObject cms = getCmsObject(); String adminUser = OpenCms.getDefaultUsers().getUserAdmin(); // stupid test to just make sure everything is set up correctly cms.loginUser(adminUser, "admin"); assertTrue(OpenCms.getDefaultUsers().isUserAdmin(cms.getRequestContext().getCurrentUser().getName())); CmsException error = null; try { // try to login with a valid username but a wrong password cms.loginUser(adminUser, "imamwrong"); } catch (CmsAuthentificationException e) { error = e; } assertNotNull(error); if (error != null) { assertSame(Messages.ERR_LOGIN_FAILED_2, error.getMessageContainer().getKey()); } error = null; try { // try to login with an invlaid username cms.loginUser("idontexist", "imnotimportant"); } catch (CmsAuthentificationException e) { error = e; } assertNotNull(error); if (error != null) { assertSame(Messages.ERR_LOGIN_FAILED_NO_USER_2, error.getMessageContainer().getKey()); } String test1User = "test1"; // now try a different user cms.loginUser(test1User, "test1"); assertEquals(test1User, cms.getRequestContext().getCurrentUser().getName()); // back to admin (to change the test1 user) cms.loginUser(adminUser, "admin"); assertEquals(adminUser, cms.getRequestContext().getCurrentUser().getName()); // disable the test1 user CmsUser test1 = cms.readUser(test1User); test1.setEnabled(false); cms.writeUser(test1); error = null; try { // try to login with an invalid username cms.loginUser(test1User, "test1"); } catch (CmsAuthentificationException e) { error = e; } assertNotNull(error); if (error != null) { assertSame(Messages.ERR_LOGIN_FAILED_DISABLED_2, error.getMessageContainer().getKey()); } // enable the test1 user again test1.setEnabled(true); cms.writeUser(test1); // try again to login cms.loginUser(test1User, "test1"); assertEquals(test1User, cms.getRequestContext().getCurrentUser().getName()); } /** * Tests if the password is automatically converted from the old to the new hash algorithm.<p> * * @throws Throwable if something goes wrong */ public void testPasswordConvesion() throws Throwable { echo("Testing if the password is automatically converted from the old to the new hash algorithm"); String testData = "test1"; CmsObject cms = getCmsObject(); CmsUser testUser = cms.readUser(testData); // because of old setup data, this should be MD5 encoded but the new standard is SCRYPT echo("Old stored password hash: " + testUser.getPassword()); assertEquals( "Password of user 'test1' not as expected", testUser.getPassword(), OpenCms.getPasswordHandler().digest( testData, I_CmsPasswordHandler.DIGEST_TYPE_MD5, CmsEncoder.ENCODING_UTF_8)); // now login the user, this should update the password to the new hash algorithm cms.loginUser(testData, testData); testUser = cms.readUser(testData); echo("New stored password hash: " + testUser.getPassword()); assertTrue( "Password validation with new hash algorithm failed", OpenCms.getPasswordHandler().checkPassword(testData, testUser.getPassword(), false)); } /** * Tests the static "validatePassword" method of the password handler.<p> * * @throws Throwable if something goes wrong */ public void testPasswordValidation() throws Throwable { echo("Testing password validation handler"); I_CmsPasswordHandler passwordHandler = OpenCms.getPasswordHandler(); boolean failure = false; // passwords must have a minimal length of 4 charaters try { passwordHandler.validatePassword("1*3"); failure = true; } catch (CmsSecurityException exc) { // noop } if (failure) { fail("Invalid password 1*3 validated."); } // try some valid passwords try { passwordHandler.validatePassword("zyz*nowski"); } catch (Exception exc) { echo("zyznowski invalid:" + exc.getMessage()); } try { passwordHandler.validatePassword("Alfa99"); } catch (Exception exc) { echo("alfa invalid:" + exc.getMessage()); } try { passwordHandler.validatePassword("ca%Dill"); } catch (Exception exc) { echo("ferrar invalid:" + exc.getMessage()); } try { passwordHandler.validatePassword("#ulary"); } catch (Exception exc) { echo("ulary invalid:" + exc.getMessage()); } } /** * Tests basic functionality and availability of the SCrypt algorithm.<p> * * @throws Throwable if something goes wrong */ public void testSCrypt() throws Throwable { // Iteration count int demos = 5; // Iteration count int iterations = 5; // Password to use for hash tests String pwd = "p\r\nassw0Rd!"; int N = 16384; // CPU cost int r = 8; // Memory cost int p = 1; // Parallelization parameter // Print out some hashes echo("\nCreating " + demos + " demo hashes with SCrpyt:"); for (int i = 0; i < demos; i++) { System.out.println(SCryptUtil.scrypt(pwd, N, r, p)); } // Test password validation echo("Testing " + iterations + " hashes with SCrpyt"); long startTime = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { String password = pwd + i; String wrongPassword = pwd + (i + 1); String hash = SCryptUtil.scrypt(password, N, r, p); String secondHash = SCryptUtil.scrypt(password, N, r, p); assertNotEquals("FAILURE: TWO HASHES ARE EQUAL!", hash, secondHash); assertFalse("FAILURE: WRONG PASSWORD ACCEPTED!", SCryptUtil.check(wrongPassword, hash)); assertTrue("FAILURE: GOOD PASSWORD NOT ACCEPTED!", SCryptUtil.check(password, hash)); } echo("Test took " + (System.currentTimeMillis() - startTime) + " msec."); if ("scrypt".equals(OpenCms.getPasswordHandler().getDigestType())) { // OpenCms configuration tests, SCrypt assumed as configured default String hashed = OpenCms.getPasswordHandler().digest(pwd); String[] parts = hashed.split("\\$"); if ((parts.length != 5) || !parts[1].equals("s0")) { fail("OpenCms produced an invalid hashed SCrypt value"); } long params = Long.parseLong(parts[2], 16); byte[] salt = decode(parts[3].toCharArray()); byte[] derived = decode(parts[4].toCharArray()); N = (int)Math.pow(2, (params >> 16) & 0xffff); r = ((int)params >> 8) & 0xff; p = (int)params & 0xff; echo("Parsed SCrpyt digest as N:" + N + " r:" + r + " p:" + p + " salt:" + salt + " derived:" + derived); assertEquals("Unexpected SCrypt value for N", 16384, N); assertEquals("Unexpected SCrypt value for r", 8, r); assertEquals("Unexpected SCrypt value for p", 1, p); } else { fail("Expected SCrypt algorithm not configured as password digester"); } } /** * Tests the setPassword and resetPassword methods.<p> * * @throws Throwable if something goes wrong */ public void testSetResetPassword() throws Throwable { echo("Testing setting the password as admin"); CmsObject cms = getCmsObject(); String adminUsername = OpenCms.getDefaultUsers().getUserAdmin(); // change password of admin cms.setPassword(adminUsername, "admin", "password1"); // login with the new password cms.loginUser(adminUsername, "password1"); // change password again cms.setPassword(adminUsername, "password2"); // login with the new password cms.loginUser(adminUsername, "password2"); // change password back, otherwise further tests would fail cms.setPassword(adminUsername, "password2", "admin"); // verify that the password was changed to the expected default cms.loginUser(adminUsername, "admin"); } /** * Tests if the user passwords are imported / set correctly.<p> * * @throws Exception if something goes wrong */ public void testUserDefaultPasswords() throws Exception { CmsObject cms = getCmsObject(); echo("Testing the user import."); I_CmsPasswordHandler passwordHandler = OpenCms.getPasswordHandler(); CmsUser user; // check if passwords will be converted echo("Testing passwords of imported users"); // check the admin user user = cms.readUser(OpenCms.getDefaultUsers().getUserAdmin()); assertTrue( "Admin user password does not check", passwordHandler.checkPassword("admin", user.getPassword(), false)); // check the guest user user = cms.readUser(OpenCms.getDefaultUsers().getUserGuest()); assertFalse( "Guest user password does check with old default (empty String) but should fail becasue it is now a random UUID", passwordHandler.checkPassword("", user.getPassword(), true)); try { SCryptUtil.check("{random-value}", user.getPassword()); } catch (IllegalArgumentException e) { fail("Guest user password not a valid SCrypt password"); } // check the export user user = cms.readUser(OpenCms.getDefaultUsers().getUserExport()); try { SCryptUtil.check("{random-value}", user.getPassword()); } catch (IllegalArgumentException e) { fail("Export user password not a valid SCrypt password"); } // check the deleted resource user user = cms.readUser(OpenCms.getDefaultUsers().getUserDeletedResource()); try { // check should fail, but if we get an exception then the password does not have the right format SCryptUtil.check("{random-value}", user.getPassword()); } catch (IllegalArgumentException e) { fail("Deleted resource user password not a valid SCrypt password"); } // check the test1 user user = cms.readUser("test1"); assertFalse( "test1 user password does check with default SCrypt but should fail becasuse it is encoded in MD5", passwordHandler.checkPassword("test1", user.getPassword(), false)); assertTrue( "test1 user password does not check with fallback to MD5", passwordHandler.checkPassword("test1", user.getPassword(), true)); // check the test2 user user = cms.readUser("test2"); assertFalse( "test2 user password does check with default SCrypt but should fail becasuse it is encoded in MD5", passwordHandler.checkPassword("test2", user.getPassword(), false)); assertTrue( "test2 user password does not check with fallback to MD5", passwordHandler.checkPassword("test2", user.getPassword(), true)); } }
package org.smof.test.collections; import static org.junit.Assert.*; import java.time.LocalDate; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; import org.junit.Before; import org.junit.Test; import org.smof.collection.CollectionOptions; import org.smof.exception.SmofException; import org.smof.test.dataModel.Brand; import org.smof.test.dataModel.Location; import com.google.common.collect.Lists; @SuppressWarnings("javadoc") public class CollectionOptionsTests { private static CollectionOptions<Brand> guineaPig; private static Brand brand; private static final String NAME = "name"; @Before public void setUp() { guineaPig = CollectionOptions.create(); brand = Brand.create(NAME, new Location("here", "not there"), Arrays.asList("owner")); } @Test public void testCreate() { assertNotNull(CollectionOptions.create()); } @Test public void testConstraints() { final List<Predicate<Brand>> constraints = Lists.newArrayList(); constraints.add(b -> b.getCapital() > 0); constraints.add(b -> b.getFoundingDate().isBefore(LocalDate.now())); constraints.forEach(c -> guineaPig.addConstraint(c)); assertEquals(constraints, guineaPig.getConstraints()); } @Test public void testIsValid() { final long capital = 10; brand.setCapital(capital+2); guineaPig.throwOnConstraintBreach(false); guineaPig.addConstraint(b -> b.getCapital() > 10); assertTrue(guineaPig.isValid(brand)); guineaPig.addConstraint(b -> !b.getName().equals(NAME)); assertFalse(guineaPig.isValid(brand)); } @Test(expected = SmofException.class) public void testThrowOnConstraintBreach() { guineaPig.addConstraint(b -> !b.getName().equals(NAME)); guineaPig.throwOnConstraintBreach(true); guineaPig.isValid(brand); } }
package ch.uzh.csg.nfclib.util; import java.nio.ByteBuffer; /** * This is a class for miscellaneous functions. * * @author Jeton Memeti * */ public class Utils { /** * Returns a long as a byte array. */ public static byte[] getLongAsBytes(long l) { return ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(l).array(); } /** * Returns a long from a given byte array. */ public static long getBytesAsLong(byte[] b) { ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / Byte.SIZE); buffer.put(b); buffer.flip(); return buffer.getLong(); } /** * Returns a short as a byte array. */ public static byte[] getShortAsBytes(short s) { return ByteBuffer.allocate(Short.SIZE / Byte.SIZE).putShort(s).array(); } /** * Returns a short from a given byte array. */ public static short getBytesAsShort(byte[] b) { ByteBuffer buffer = ByteBuffer.allocate(Short.SIZE / Byte.SIZE); buffer.put(b); buffer.flip(); return buffer.getShort(); } }
package org.jcoderz.commons.doclet; import junit.framework.TestCase; public class HtmlCleanerTest extends TestCase { /** * Simple test. * @throws Exception if the test case fails with an exception. */ public void testSimpleClean () throws Exception { assertEquals("Cleaned output unexpected.", "<p>test</p>", new HtmlCleaner().clean("<p>test</p>")); } /** * Simple broken test. * @throws Exception if the test case fails with an exception. */ public void testBrokenClean () throws Exception { final HtmlCleaner htmlCleaner = new HtmlCleaner(); assertEquals("Cleaned output unexpected.", "Invalid HTML could not be parsed.", htmlCleaner.clean("&&foo;<table><test> <br><p>test")); assertTrue("Error message unexpected. " + htmlCleaner.getWarnings(), htmlCleaner.getWarnings().indexOf("<test>") >= 0); } }
package pt.fccn.sobre.arquivo.pages; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class CommonQuestionsPage { WebDriver driver; List< String > CommonQuestionsPT; List< String > CommonQuestionsEN; private final String dir = "sobreTestsFiles"; private final int timeout = 50; public CommonQuestionsPage( WebDriver driver ) throws FileNotFoundException{ this.driver = driver; CommonQuestionsPT = new ArrayList< String >( ); CommonQuestionsEN = new ArrayList< String >( ); if( !loadQuestions( "CommonQuestions_pt.txt" , "pt" ) ) throw new FileNotFoundException( ); if( !loadQuestions( "CommonQuestions_en.txt" , "en" ) ) throw new FileNotFoundException( ); } private boolean loadQuestions( String filename , String language ) { Scanner s; try { s = new Scanner( new File( dir.concat( File.separator ).concat( filename ) ) , "utf-8" ); while ( s.hasNext( ) ) { if( language.equals( "pt" ) ) CommonQuestionsPT.add( s.next( ) ); else CommonQuestionsEN.add( s.next( ) ); } s.close( ); return true; } catch ( FileNotFoundException e ) { e.printStackTrace( ); return false; } } public boolean inspectQuestions( String language ) { System.out.println( "[inspectQuestions]" );
package de.geeksfactory.opacclient.frontend; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.holoeverywhere.app.Fragment; import org.holoeverywhere.widget.Toast; import android.annotation.SuppressLint; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentFilter.MalformedMimeTypeException; import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.FragmentManager; import de.geeksfactory.opacclient.R; import de.geeksfactory.opacclient.apis.OpacApi; import de.geeksfactory.opacclient.barcode.BarcodeScanIntegrator; import de.geeksfactory.opacclient.objects.Account; import de.geeksfactory.opacclient.storage.AccountDataSource; public class MainActivity extends OpacActivity implements SearchFragment.Callback, StarredFragment.Callback, SearchResultDetailFragment.Callbacks { private String[][] techListsArray; private IntentFilter[] intentFiltersArray; private PendingIntent nfcIntent; private boolean nfc_capable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; private android.nfc.NfcAdapter mAdapter; private SharedPreferences sp; private Fragment rightFragment; @SuppressLint("NewApi") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getIntent().getAction() != null) { if (getIntent().getAction().equals("android.intent.action.VIEW")) { urlintent(); return; } } sp = PreferenceManager.getDefaultSharedPreferences(this); if (savedInstanceState == null) { if (getIntent().hasExtra("fragment")) { selectItem(getIntent().getStringExtra("fragment")); } else if (sp.contains("startup_fragment")) { selectItem(sp.getString("startup_fragment", "search")); } else { selectItem(1); } } try { if (nfc_capable) { if (!getPackageManager().hasSystemFeature( "android.hardware.nfc")) { nfc_capable = false; } } if (nfc_capable) { mAdapter = android.nfc.NfcAdapter.getDefaultAdapter(this); nfcIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); IntentFilter ndef = new IntentFilter( android.nfc.NfcAdapter.ACTION_TECH_DISCOVERED); try { ndef.addDataType("*/*"); } catch (MalformedMimeTypeException e) { throw new RuntimeException("fail", e); } intentFiltersArray = new IntentFilter[] { ndef, }; techListsArray = new String[][] { new String[] { android.nfc.tech.NfcV.class .getName() } }; } } catch (SecurityException e) { e.printStackTrace(); } if (app.getLibrary() != null) { getSupportActionBar().setSubtitle( app.getLibrary().getCity() + " · " + app.getLibrary().getTitle()); } } @Override public void accountSelected(Account account) { getSupportActionBar().setSubtitle( app.getLibrary().getCity() + " · " + app.getLibrary().getTitle()); if (fragment instanceof OpacActivity.AccountSelectedListener) { ((OpacActivity.AccountSelectedListener) fragment) .accountSelected(account); } Set<String> fields = new HashSet<String>(Arrays.asList(app.getApi() .getSearchFields())); if (fields.contains(OpacApi.KEY_SEARCH_QUERY_BARCODE)) nfc_capable = false; } public void urlintent() { Uri d = getIntent().getData(); if (d.getHost().equals("opacapp.de")) { String[] split = d.getPath().split(":"); String bib; try { bib = URLDecoder.decode(split[1], "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError("UTF-8 is unknown"); } if (!app.getLibrary().getIdent().equals(bib)) { AccountDataSource adata = new AccountDataSource(this); adata.open(); List<Account> accounts = adata.getAllAccounts(bib); adata.close(); if (accounts.size() > 0) { app.setAccount(accounts.get(0).getId()); } else { Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://opacapp.de/web" + d.getPath())); startActivity(i); return; } } String medianr = split[2]; if (medianr.length() > 1) { Intent intent = new Intent(MainActivity.this, SearchResultDetailActivity.class); intent.putExtra(SearchResultDetailFragment.ARG_ITEM_ID, medianr); startActivity(intent); } else { String title; try { title = URLDecoder.decode(split[3], "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError("UTF-8 is unknown"); } Bundle query = new Bundle(); query.putString(OpacApi.KEY_SEARCH_QUERY_TITLE, title); Intent intent = new Intent(MainActivity.this, SearchResultListActivity.class); intent.putExtra("query", query); startActivity(intent); } finish(); return; } } @Override protected int getContentView() { return R.layout.activity_main; } private static boolean is_valid_isbn10(char[] digits) { int a = 0; for (int i = 0; i < 10; i++) { a += i * Integer.parseInt(String.valueOf(digits[i])); } return a % 11 == Integer.parseInt(String.valueOf(digits[9])); } @Override public void onActivityResult(int requestCode, int resultCode, Intent idata) { super.onActivityResult(requestCode, resultCode, idata); // Barcode BarcodeScanIntegrator.ScanResult scanResult = BarcodeScanIntegrator .parseActivityResult(requestCode, resultCode, idata); if (resultCode != RESULT_CANCELED && scanResult != null) { if (scanResult.getContents() == null) return; if (scanResult.getContents().length() < 3) return; // Try to determine whether it is an ISBN number or something // library internal String target_field = null; if (scanResult.getFormatName() != null) { if (scanResult.getFormatName().equals("EAN_13") && scanResult.getContents().startsWith("97")) { target_field = OpacApi.KEY_SEARCH_QUERY_ISBN; } else if (scanResult.getFormatName().equals("CODE_39")) { target_field = OpacApi.KEY_SEARCH_QUERY_BARCODE; } } if (target_field == null) { if (scanResult.getContents().length() == 13 && (scanResult.getContents().startsWith("978") || scanResult .getContents().startsWith("979"))) { target_field = OpacApi.KEY_SEARCH_QUERY_ISBN; } else if (scanResult.getContents().length() == 10 && is_valid_isbn10(scanResult.getContents() .toCharArray())) { target_field = OpacApi.KEY_SEARCH_QUERY_ISBN; } else { target_field = OpacApi.KEY_SEARCH_QUERY_BARCODE; } } Set<String> fields = new HashSet<String>(Arrays.asList(app.getApi() .getSearchFields())); if (target_field.equals(OpacApi.KEY_SEARCH_QUERY_BARCODE) && !fields.contains(OpacApi.KEY_SEARCH_QUERY_BARCODE)) { Toast.makeText(this, R.string.barcode_internal_not_supported, Toast.LENGTH_LONG).show(); } else { Bundle query = new Bundle(); query.putString(target_field, scanResult.getContents()); app.startSearch(this, query); } } } @Override public void scanBarcode() { BarcodeScanIntegrator integrator = new BarcodeScanIntegrator(this); integrator.initiateScan(); } @SuppressLint("NewApi") @Override public void onPause() { super.onPause(); if (nfc_capable && sp.getBoolean("nfc_search", false)) { try { mAdapter.disableForegroundDispatch(this); } catch (SecurityException e) { e.printStackTrace(); } } } @SuppressLint("NewApi") @Override public void onResume() { super.onResume(); if (nfc_capable && sp.getBoolean("nfc_search", false)) { try { mAdapter.enableForegroundDispatch(this, nfcIntent, intentFiltersArray, techListsArray); } catch (SecurityException e) { e.printStackTrace(); } } } @SuppressLint("NewApi") @Override public void onNewIntent(Intent intent) { if (nfc_capable && sp.getBoolean("nfc_search", false)) { android.nfc.Tag tag = intent .getParcelableExtra(android.nfc.NfcAdapter.EXTRA_TAG); String scanResult = readPageToString(tag); if (scanResult != null) { if (scanResult.length() > 5) { Set<String> fields = new HashSet<String>(Arrays.asList(app .getApi().getSearchFields())); if (fields.contains(OpacApi.KEY_SEARCH_QUERY_BARCODE)) { Bundle query = new Bundle(); query.putString(OpacApi.KEY_SEARCH_QUERY_BARCODE, scanResult); app.startSearch(this, query); } else { Toast.makeText(this, R.string.barcode_internal_not_supported, Toast.LENGTH_LONG).show(); } } } } } /** * Reads the first four blocks of an ISO 15693 NFC tag as ASCII bytes into a * string. * * @return String Tag memory as a string (bytes converted as ASCII) or * <code>null</code> */ @SuppressLint("NewApi") public static String readPageToString(android.nfc.Tag tag) { byte[] id = tag.getId(); android.nfc.tech.NfcV tech = android.nfc.tech.NfcV.get(tag); byte[] readCmd = new byte[3 + id.length]; readCmd[0] = 0x20; // set "address" flag (only send command to this // tag) readCmd[1] = 0x20; // ISO 15693 Single Block Read command byte System.arraycopy(id, 0, readCmd, 2, id.length); // copy ID StringBuilder stringbuilder = new StringBuilder(); try { tech.connect(); for (int i = 0; i < 4; i++) { readCmd[2 + id.length] = (byte) i; // 1 byte payload: block // address byte[] data; data = tech.transceive(readCmd); for (int j = 0; j < data.length; j++) { if (data[j] > 32 && data[j] < 127) // We only want printable // characters, there // might be some // nullbytes in it // otherwise. stringbuilder.append((char) data[j]); } } tech.close(); } catch (IOException e) { try { tech.close(); } catch (IOException e1) { } return null; } return stringbuilder.toString().trim(); } @Override public void showDetail(String mNr) { if (isTablet()) { rightFragment = new SearchResultDetailFragment(); Bundle args = new Bundle(); args.putString(SearchResultDetailFragment.ARG_ITEM_ID, mNr); rightFragment.setArguments(args); // Insert the fragment FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.content_frame_right, rightFragment).commit(); } else { Intent intent = new Intent(this, SearchResultDetailActivity.class); intent.putExtra(SearchResultDetailFragment.ARG_ITEM_ID, mNr); startActivity(intent); } } @Override public void removeFragment() { getSupportFragmentManager().beginTransaction().remove(rightFragment) .commit(); } @Override protected void setTwoPane(boolean active) { super.setTwoPane(active); if (!active && rightFragment != null) { try { removeFragment(); } catch (Exception e) { } } } }
package org.drools.base.mvel; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.drools.WorkingMemory; import org.drools.rule.Declaration; import org.drools.spi.KnowledgeHelper; import org.drools.spi.Tuple; import org.mvel.CompileException; import org.mvel.integration.VariableResolver; import org.mvel.integration.impl.BaseVariableResolverFactory; public class DroolsMVELFactory extends BaseVariableResolverFactory implements Serializable, Cloneable { private static final long serialVersionUID = 400L; /** * Holds the instance of the variables. */ private Tuple tuple; private KnowledgeHelper knowledgeHelper; private Object object; private Map localDeclarations; private Map previousDeclarations; private Map globals; private WorkingMemory workingMemory; private Map localVariables; public DroolsMVELFactory(final Map previousDeclarations, final Map localDeclarations, final Map globals) { this.previousDeclarations = previousDeclarations; this.localDeclarations = localDeclarations; this.globals = globals; } public Map getVariableResolvers() { return this.variableResolvers; } public Object getObject() { return this.object; } public WorkingMemory getWorkingMemory() { return this.workingMemory; } public void setContext(final Tuple tuple, final KnowledgeHelper knowledgeHelper, final Object object, final WorkingMemory workingMemory, final Map variables) { this.tuple = tuple; this.knowledgeHelper = knowledgeHelper; this.object = object; this.workingMemory = workingMemory; this.localVariables = variables; } public KnowledgeHelper getKnowledgeHelper() { return this.knowledgeHelper; } public Object getValue(final Declaration declaration) { return this.tuple.get( declaration ).getObject(); } public Object getValue(final String identifier) { return this.workingMemory.getGlobal( identifier ); } public Object getLocalValue(final String identifier) { return this.localVariables.get( identifier ); } public void setLocalValue(final String identifier, final Object value) { this.localVariables.put( identifier, value ); } public VariableResolver createVariable(String name, Object value) { VariableResolver vr = getVariableResolver( name ); if ( vr != null ) { if ( this.localVariables == null ) { this.localVariables = new HashMap(); } vr.setValue( value ); return vr; } else { if ( this.localVariables == null ) { this.localVariables = new HashMap(); } addResolver( name, vr = new LocalVariableResolver( this, name ) ); vr.setValue( value ); return vr; } } public VariableResolver createVariable(String name, Object value, Class type) { VariableResolver vr = getVariableResolver( name ); if ( vr != null && vr.getType() != null ) { throw new CompileException( "variable already defined within scope: " + vr.getType() + " " + name ); } else { if ( this.localVariables == null ) { this.localVariables = new HashMap(); } addResolver( name, vr = new LocalVariableResolver( this, name, type ) ); vr.setValue( value ); return vr; } } public boolean isResolveable(String name) { if ( DroolsMVELKnowledgeHelper.DROOLS.equals( name ) ) { addResolver( DroolsMVELKnowledgeHelper.DROOLS, new DroolsMVELKnowledgeHelper( this ) ); return true; } else if ( this.variableResolvers != null && this.variableResolvers.containsKey( name ) ) { return true; } else if ( this.previousDeclarations != null && this.previousDeclarations.containsKey( name ) ) { addResolver( name, new DroolsMVELPreviousDeclarationVariable( (Declaration) this.previousDeclarations.get( name ), this ) ); return true; } else if ( this.localDeclarations != null && this.localDeclarations.containsKey( name ) ) { addResolver( name, new DroolsMVELLocalDeclarationVariable( (Declaration) this.localDeclarations.get( name ), this ) ); return true; } else if ( this.globals.containsKey( name ) ) { addResolver( name, new DroolsMVELGlobalVariable( name, (Class) this.globals.get( name ), this ) ); return true; } else if ( this.variableResolvers != null && this.variableResolvers.containsKey( name ) ) { addResolver( name, new LocalVariableResolver( this, name ) ); return true; } else if ( nextFactory != null ) { return nextFactory.isResolveable( name ); } return false; } private void addResolver(String name, VariableResolver vr) { if ( this.variableResolvers == null ) { this.variableResolvers = new HashMap(); } this.variableResolvers.put( name, vr ); } public boolean isTarget(String name) { if ( this.variableResolvers != null ) { return this.variableResolvers.containsKey( name ); } else { return false; } } public Object clone() { return new DroolsMVELFactory( this.previousDeclarations, this.localDeclarations, this.globals ); } }
package de.geeksfactory.opacclient.frontend; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import de.geeksfactory.opacclient.OpacClient; import de.geeksfactory.opacclient.R; public abstract class OpacActivity extends SherlockActivity { protected OpacClient app; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getSupportActionBar().setHomeButtonEnabled(true); app = (OpacClient) getApplication(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater mi = new MenuInflater(this); mi.inflate(R.menu.activity_opac, menu); try { if (app.ohc.bib.getString(4) == null || app.ohc.bib.getString(4).equals("null")) { menu.removeItem(R.id.menu_info); } } catch (Exception e) { menu.removeItem(R.id.menu_info); } return super.onCreateOptionsMenu(menu); } protected void dialog_no_user() { dialog_no_user(false); } protected void dialog_no_user(final boolean finish) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.status_nouser) .setCancelable(false) .setNegativeButton(R.string.dismiss, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); if (finish) finish(); } }) .setPositiveButton(R.string.prefs, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent intent = new Intent(OpacActivity.this, MainPreferenceActivity.class); startActivity(intent); } }); AlertDialog alert = builder.create(); alert.show(); } protected void dialog_wrong_credentials(String s, final boolean finish) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.opac_error) + " " + s) .setCancelable(false) .setNegativeButton(R.string.dismiss, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); if (finish) finish(); } }) .setPositiveButton(R.string.prefs, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent intent = new Intent(OpacActivity.this, MainPreferenceActivity.class); startActivity(intent); } }); AlertDialog alert = builder.create(); alert.show(); } protected void unbindDrawables(View view) { if(view == null) return; if (view.getBackground() != null) { view.getBackground().setCallback(null); } if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { unbindDrawables(((ViewGroup) view).getChildAt(i)); } if (!(view instanceof AdapterView)) { ((ViewGroup) view).removeAllViews(); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // app icon in action bar clicked; go home Intent intent = new Intent(this, FrontpageActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); return true; case R.id.menu_about: Intent iAbout = new Intent(OpacActivity.this, AboutActivity.class); startActivity(iAbout); return true; case R.id.menu_info: Intent iInfo = new Intent(OpacActivity.this, InfoActivity.class); startActivity(iInfo); return true; case R.id.menu_prefs: Intent iPrefs = new Intent(OpacActivity.this, MainPreferenceActivity.class); startActivity(iPrefs); return true; default: return super.onOptionsItemSelected(item); } } }
package comlib.adk.dummy; import comlib.adk.dummy.event.AmbulanceCivilianEvent; import comlib.adk.dummy.util.CivilianManager; import comlib.adk.team.tactics.AmbulanceTeamTactics; import comlib.adk.util.action.AmbulanceAction; import comlib.manager.MessageManager; import comlib.message.DummyMessage; import rescuecore2.messages.Message; import rescuecore2.standard.entities.*; import rescuecore2.worldmodel.ChangeSet; import rescuecore2.worldmodel.EntityID; import java.util.ArrayList; import java.util.List; public class DummyAmbulance extends AmbulanceTeamTactics { public CivilianManager civilianManager; public EntityID rescueTarget; public DummyAmbulance() { this.civilianManager = new CivilianManager(); this.rescueTarget = null; } @Override public void postConnect() { } @Override public void registerEvent(MessageManager manager) { manager.registerEvent(new AmbulanceCivilianEvent(this.model, this.civilianManager)); } @Override public Message think(int time, ChangeSet changed, MessageManager manager) { this.updateInfo(changed, manager); if(this.someoneOnBoard()) { if (this.location instanceof Refuge) { this.rescueTarget = null; return AmbulanceAction.unload(this, time); /*if(this.rescueTarget != null){ //this.bus.getOutput().addMessage(this.bus.getAgent().messageFactory.createInformationMessage(this.bus.getMemory().getTime(), (Human)this.bus.getAgent().getModel().getEntity(this.bus.getMemory(AmbulanceMemory.class).getRescueTarget()))); }*/ } else { return this.moveRefuge(time); } } manager.addSendMessage(new DummyMessage(time, 10, 0)); return AmbulanceAction.rest(this, time); } private void updateInfo(ChangeSet changed, MessageManager manager) { for (EntityID next : changed.getChangedEntities()) { StandardEntity entity = model.getEntity(next); if(entity instanceof Civilian) { this.civilianManager.update((Civilian)entity, manager); } else if(entity instanceof Blockade) { //manager.addSendMessage(new BlockadeMessage((Blockade)entity)); } else if(entity instanceof Building) { Building b = (Building)entity; if(b.getFieryness() > 0) { //manager.addSendMessage(new BuildingMessage(b)); } } } } private boolean someoneOnBoard() { for (StandardEntity next : this.model.getEntitiesOfType(StandardEntityURN.CIVILIAN)) { if (((Human)next).getPosition().equals(this.agentID)) { return true; } } return false; } private Message moveRefuge(int time) { List list = new ArrayList<EntityID>(); list.add(this.refugeList.get(0).getID()); return AmbulanceAction.move(this, time, list); } }
package de.mrunde.bachelorthesis.activities; import java.io.IOException; import java.util.List; import java.util.Locale; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Settings; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.mapquest.android.maps.BoundingBox; import com.mapquest.android.maps.DefaultItemizedOverlay; import com.mapquest.android.maps.GeoPoint; import com.mapquest.android.maps.MapActivity; import com.mapquest.android.maps.MapView; import com.mapquest.android.maps.MyLocationOverlay; import com.mapquest.android.maps.OverlayItem; import com.mapquest.android.maps.RouteManager; import com.mapquest.android.maps.RouteResponse; import de.mrunde.bachelorthesis.R; /** * This is the initial activity which is started with the application. It offers * the user to change the route type and to search for his desired destination. * * @author Marius Runde */ public class MainActivity extends MapActivity implements OnInitListener { /** * Maximum amount of results for the destination */ private final int MAX_RESULTS = 5; /** * Fastest route type */ private final String ROUTETYPE_FASTEST = "fastest"; /** * Shortest route type */ private final String ROUTETYPE_SHORTEST = "shortest"; /** * Pedestrian route type */ private final String ROUTETYPE_PEDESTRIAN = "pedestrian"; /** * Bicycle route type */ private final String ROUTETYPE_BICYCLE = "bicycle"; /** * Current route type */ private String routeType; /** * The entered destination */ private EditText edt_destination; /** * The "search for destination" button */ private Button btn_search; /** * The "calculate route" button<br/> * This button also starts the navigation after route calculation. */ private Button btn_calculate; /** * The "preferences" button to change the route type */ private Button btn_preferences; /** * The "help" button */ private Button btn_help; /** * The initial map view */ protected MapView map; /** * An overlay to display the user's location */ private MyLocationOverlay myLocationOverlay; /** * Route manager for route calculation */ private RouteManager rm; /** * The current location as a String */ private String str_currentLocation; /** * The destination as a String */ private String str_destination; /** * Coordinates of the destination to be sent to the NaviActivity */ private double[] destination_coords = null; /** * TextToSpeech for audio output */ private TextToSpeech tts; /** * The Hitchhiker's Guide to the Galaxy :D */ private boolean time = false; /** * This method is called when the application has been started */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Initialize the TextToSpeech tts = new TextToSpeech(this, this); // Set the route type to fastest this.routeType = ROUTETYPE_FASTEST; // Setup the whole GUI and map setupGUI(); setupMapView(); setupMyLocation(); } /** * Set up the GUI */ private void setupGUI() { this.edt_destination = (EditText) findViewById(R.id.edt_destination); // TODO just for testing, must be deleted... edt_destination.setText("Cineplex, Mnster"); this.btn_search = (Button) findViewById(R.id.btn_search); btn_search.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Get the entered destination str_destination = edt_destination.getText().toString(); if (str_destination.length() == 0) { Toast.makeText(MainActivity.this, R.string.noDestinationEntered, Toast.LENGTH_SHORT) .show(); } else { // Search for the destination SearchDestinationTask destinationTask = new SearchDestinationTask(); destinationTask.execute(str_destination); } } }); this.btn_calculate = (Button) findViewById(R.id.btn_calculate); btn_calculate.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (destination_coords == null) { Toast.makeText(MainActivity.this, R.string.noDestinationEntered, Toast.LENGTH_SHORT) .show(); } else if (btn_calculate.getText() == getResources().getString( R.string.calculate)) { // Transform the current location into a String str_currentLocation = "{latLng:{lat:" + myLocationOverlay.getMyLocation().getLatitude() + ",lng:" + myLocationOverlay.getMyLocation().getLongitude() + "}}"; // Transform the destination location into a String str_destination = "{latLng:{lat:" + destination_coords[0] + ",lng:" + destination_coords[1] + "}}"; // Calculate the route calculateRoute(); } else { // Create an Intent to start the NaviActivity and hereby the // navigation Intent intent = new Intent(MainActivity.this, NaviActivity.class); intent.putExtra("str_currentLocation", str_currentLocation); intent.putExtra("str_destination", str_destination); intent.putExtra("destination_lat", destination_coords[0]); intent.putExtra("destination_lng", destination_coords[1]); intent.putExtra("routeOptions", getRouteOptions()); startActivity(intent); } } }); this.btn_preferences = (Button) findViewById(R.id.btn_preferences); btn_preferences.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Display the route type dialog displayRouteTypeDialog(); } }); this.btn_help = (Button) findViewById(R.id.btn_help); btn_help.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Create an Intent to start the HelpActivity Intent intent = new Intent(MainActivity.this, HelpActivity.class); startActivity(intent); } }); } /** * This is a class to search for the destination asynchronously. * * @author Marius Runde */ private class SearchDestinationTask extends AsyncTask<String, Void, GeoPoint> { /** * Progress dialog to inform the user about the searching process */ private ProgressDialog progressDialog = new ProgressDialog( MainActivity.this); @Override protected void onPreExecute() { // Display progress dialog progressDialog.setMessage("Searching for destination..."); progressDialog.show(); progressDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // Enable canceling the search SearchDestinationTask.this.cancel(true); } }); } @Override protected GeoPoint doInBackground(String... destination) { String str_destination = destination[0]; List<Address> addresses; try { // Create a geocoder to locate the destination Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault()); addresses = geocoder.getFromLocationName(str_destination, MAX_RESULTS); } catch (IOException e1) { // Destination could not be located but try again once // because sometimes it works at the second try Log.d("MainActivity", "First try to locate destination failed. Starting second try..."); try { // Create a geocoder to locate the destination Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault()); addresses = geocoder.getFromLocationName(str_destination, MAX_RESULTS); } catch (IOException e2) { // Seems like the destination could really not be // found, so send the user a message about the error Log.e("MainActivity", "IO Exception in searching for destination. This is the error message: " + e2.getMessage()); Toast.makeText(MainActivity.this, R.string.noDestinationFound, Toast.LENGTH_SHORT) .show(); return null; } } if (addresses.isEmpty()) { // Destination could not be located Toast.makeText(MainActivity.this, R.string.noDestinationFound, Toast.LENGTH_SHORT).show(); return null; } else { // Destination could be located Log.d("MainActivity", "Located destination sucessfully."); GeoPoint result = new GeoPoint(addresses.get(0).getLatitude(), addresses.get(0).getLongitude()); return result; } } @Override protected void onPostExecute(GeoPoint result) { // Dismiss progress dialog progressDialog.dismiss(); // Check if the search was successful if (result != null) { // Create the destination overlay addDestinationOverlay(result); // If the route has been calculated before change the text // of the button so the route has to be calculated again and // clear the route from the RouteManager if (btn_calculate.getText() == getResources().getString( R.string.start)) { btn_calculate.setText(R.string.calculate); rm.clearRoute(); } } } } /** * Add the destination overlay to the map * * @param destination * The destination */ private void addDestinationOverlay(GeoPoint destination) { // Create a GeoPoint object of the current location and the destination GeoPoint currentLocation = new GeoPoint(myLocationOverlay .getMyLocation().getLatitude(), myLocationOverlay .getMyLocation().getLongitude()); // Also set the coordinates of the destination for the NaviActivity this.destination_coords = new double[] { destination.getLatitude(), destination.getLongitude() }; // Clear previous overlays first if (map.getOverlays().size() > 1) { map.getOverlays().remove(1); } // Create the destination overlay OverlayItem oi_destination = new OverlayItem(destination, "Destination", str_destination); final DefaultItemizedOverlay destinationOverlay = new DefaultItemizedOverlay( getResources().getDrawable(R.drawable.destination_flag)); destinationOverlay.addItem(oi_destination); // Add the overlay to the map map.getOverlays().add(destinationOverlay); // Zoom and pan the map to show all overlays map.getController().zoomToSpan( new BoundingBox(currentLocation, destination)); } /** * Calculate the route from the current location to the destination */ private void calculateRoute() { // Clear the previous route first if (rm != null) { rm.clearRoute(); } // Initialize a new RouteManager to calculate the route rm = new RouteManager(getBaseContext(), getResources().getString( R.string.apiKey)); rm.setMapView(map); // Zoom and center the map to display the route rm.setBestFitRoute(true); // Set the route options (e.g. route type) rm.setOptions(getRouteOptions()); // Set debug true to receive the URL rm.setDebug(true); // Set route callback rm.setRouteCallback(new RouteManager.RouteCallback() { @Override public void onSuccess(RouteResponse response) { // Route has been calculated successfully Log.i("MainActivity", getResources().getString(R.string.routeCalculated)); // Change the text of the button to enable navigation btn_calculate.setText(R.string.start); } @Override public void onError(RouteResponse response) { // Find the reason why the route could not be calculated. The // status codes can be found here: // pedestrian error seems to be 500 though and not 6xx if (response.info.statusCode == 500) { // Route could not be calculated because the length of // routes with the pedestrian route type are restricted to a // specific distance Log.e("MainActivity", getResources().getString( R.string.routeNotCalculated_500)); Toast.makeText( MainActivity.this, getResources().getString( R.string.routeNotCalculated_500), Toast.LENGTH_LONG).show(); } else { // Route could not be calculated because of another error Log.e("MainActivity", getResources().getString( R.string.routeNotCalculated) + "\nStatus Code: " + response.info.statusCode); Toast.makeText( MainActivity.this, getResources().getString( R.string.routeNotCalculated), Toast.LENGTH_SHORT).show(); } } }); // Calculate the route and display it on the map rm.createRoute(str_currentLocation, str_destination); } /** * Setup the route options and return them * * @return Route options as String */ private String getRouteOptions() { JSONObject options = new JSONObject(); try { // Set the units to kilometers String unit = "m"; options.put("unit", unit); // Set the route type options.put("routeType", routeType); // Set the output shape format String outShapeFormat = "raw"; options.put("outShapeFormat", outShapeFormat); } catch (JSONException e) { e.printStackTrace(); } return options.toString(); } /** * Set up the map and enable default zoom controls */ private void setupMapView() { this.map = (MapView) findViewById(R.id.map); map.setBuiltInZoomControls(true); } /** * Set up a MyLocationOverlay and execute the runnable once a location has * been fixed */ private void setupMyLocation() { // Check if the GPS is enabled if (!((LocationManager) getSystemService(LOCATION_SERVICE)) .isProviderEnabled(LocationManager.GPS_PROVIDER)) { // Open dialog to inform the user that the GPS is disabled AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getResources().getString(R.string.gpsDisabled)); builder.setCancelable(false); builder.setPositiveButton(R.string.openSettings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Open the location settings if it is disabled Intent intent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Dismiss the dialog dialog.cancel(); } }); // Display the dialog AlertDialog dialog = builder.create(); dialog.show(); } // Create the MyLocationOverlay this.myLocationOverlay = new MyLocationOverlay(this, map); myLocationOverlay.enableMyLocation(); myLocationOverlay.setMarker( getResources().getDrawable(R.drawable.my_location), 0); myLocationOverlay.runOnFirstFix(new Runnable() { @Override public void run() { GeoPoint currentLocation = myLocationOverlay.getMyLocation(); map.getController().animateTo(currentLocation); map.getController().setZoom(14); map.getOverlays().add(myLocationOverlay); myLocationOverlay.setFollowing(false); } }); } @Override protected boolean isRouteDisplayed() { // Do nothing return false; } /** * Called when the OptionsMenu is created */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } /** * Called when an item of the OptionsMenu is clicked */ @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent; // Handle item selection switch (item.getItemId()) { case R.id.menu_about: // Create an Intent to start the AboutActivity intent = new Intent(MainActivity.this, AboutActivity.class); startActivity(intent); return true; case R.id.menu_help: // Create an Intent to start the HelpActivity intent = new Intent(MainActivity.this, HelpActivity.class); startActivity(intent); return true; case R.id.menu_routeTypes: displayRouteTypeDialog(); return true; default: return super.onOptionsItemSelected(item); } } /** * Display the route type dialog so that the user can change it */ private void displayRouteTypeDialog() { // Initialize an AlertDialog.Builder and an AlertDialog AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog dialog; // If the route has been calculated before change the text // of the button so the route has to be calculated again and // clear the route from the RouteManager if (btn_calculate.getText() == getResources().getString(R.string.start)) { btn_calculate.setText(R.string.calculate); rm.clearRoute(); } // Change the route type in the settings builder.setTitle(R.string.routeType); builder.setItems(R.array.routeTypes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: // Fastest selected routeType = ROUTETYPE_FASTEST; if (time) { Toast.makeText( MainActivity.this, "Time is an illusion. Lunchtime doubly so.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Fastest route type selected", Toast.LENGTH_SHORT).show(); time = true; } break; case 1: // Shortest selected routeType = ROUTETYPE_SHORTEST; Toast.makeText(MainActivity.this, "Shortest route type selected", Toast.LENGTH_SHORT).show(); break; case 2: // Pedestrian selected routeType = ROUTETYPE_PEDESTRIAN; Toast.makeText(MainActivity.this, "Pedestrian route type selected", Toast.LENGTH_SHORT).show(); break; case 3: // Bicycle selected routeType = ROUTETYPE_BICYCLE; Toast.makeText(MainActivity.this, "Bicycle route type selected", Toast.LENGTH_SHORT).show(); break; default: break; } } }); dialog = builder.create(); dialog.show(); } /** * Enable features of the MyLocationOverlay */ @Override protected void onResume() { myLocationOverlay.enableMyLocation(); super.onResume(); } /** * Disable features of the MyLocationOverlay when in the background */ @Override protected void onPause() { super.onPause(); myLocationOverlay.disableMyLocation(); } /** * Shut down the TextToSpeech engine when the application is terminated */ @Override protected void onDestroy() { if (tts != null) { tts.stop(); tts.shutdown(); } super.onDestroy(); } @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { tts.setLanguage(Locale.ENGLISH); } else { tts = null; Log.e("MainActivity", "Failed to initialize the TextToSpeech"); } } }
package de.uni_jena.min.in0043.nine_mens_morris.gui; import java.awt.*; import java.awt.event.*; import de.uni_jena.min.in0043.nine_mens_morris.core.Logic; import de.uni_jena.min.in0043.nine_mens_morris.core.Phase; import de.uni_jena.min.in0043.nine_mens_morris.core.Player; public class Head extends Panel implements MouseListener { private static final long serialVersionUID = -5704850734397028920L; private Spielfeld sF; private Stone[] Black; private Stone[] White; private Frame mFra; private Logic nmm; private boolean mill; public Head() { mFra = new Frame("Nine Men's Morris - Retro Style"); mFra.setSize(1024, 720); sF = new Spielfeld(); Black = new Stone[9]; White = new Stone[9]; mill = false; nmm = new Logic(); for (int i = 0; i < 9; i++) { int r = mFra.getSize().width * mFra.getSize().height / 30000; Black[i] = new Stone(); Black[i].posX = 40 + i * r; Black[i].posY = mFra.getSize().height - 80; White[i] = new Stone(); White[i].posX = mFra.getSize().width - 80 - i * r; White[i].posY = mFra.getSize().height - 80; } } public Head(Logic nnn) { mFra = new Frame("Nine Men's Morris - Retro Style"); mFra.setSize(1024, 720); sF = new Spielfeld(); Black = new Stone[9]; White = new Stone[9]; mill = false; nmm = nnn; for (int i = 0; i < 9; i++) { int r = mFra.getSize().width * mFra.getSize().height / 30000; Black[i] = new Stone(); Black[i].posX = 40 + i * r; Black[i].posY = mFra.getSize().height - 50; White[i] = new Stone(); White[i].posX = mFra.getSize().width - 80 - i * r; White[i].posY = mFra.getSize().height - 50; } } public void paint(Graphics g) { int height = mFra.getSize().height; int width = mFra.getSize().width; int middleX = width / 2; int middleY = height / 2; int addX = middleX - middleX / 4; int addY = middleY - middleY / 4; int r = width * height / 30000; /* * for (int i = 0; i < 9; i++) { Black[i].posX = 40 + i * r; * Black[i].posY = mFra.getSize().height - 80; White[i].posX = * mFra.getSize().width - 80 - i * r; White[i].posY = * mFra.getSize().height - 80; } */ {// Board // Outer g.drawRect(middleX / 4, middleY / 4, (addX) * 2, (addY) * 2); // Middle g.drawRect(middleX / 4 + addX / 3, middleY / 4 + addY / 3, (middleX - (middleX / 4 + addX / 3)) * 2, (middleY - (middleY / 4 + addY / 3)) * 2); // Inner g.drawRect(middleX / 4 + 2 * addX / 3, middleY / 4 + 2 * addY / 3, (middleX - (middleX / 4 + 2 * addX / 3)) * 2, (middleY - (middleY / 4 + 2 * addY / 3)) * 2); // g.drawLine(middleX, middleY, middleX, middleY); // Y Lines g.drawLine(middleX, middleY / 4, middleX, middleY / 4 + 2 * addY / 3); g.drawLine(middleX, middleY + middleY / 4, middleX, middleY + (middleY / 4 + 2 * addY / 3)); // X Lines g.drawLine(middleX / 4, middleY, middleX / 4 + 2 * addX / 3, middleY); g.drawLine(middleX + middleX / 4, middleY, middleX + middleX / 4 + 2 * addX / 3, middleY); // Now, this is getting fat g.drawRect(middleX / 4 + 1, middleY / 4 + 1, (addX) * 2, (addY) * 2); g.drawRect(middleX / 4 + 2, middleY / 4 + 2, (addX) * 2, (addY) * 2); g.drawRect(middleX / 4 + addX / 3 + 1, middleY / 4 + addY / 3 + 1, (middleX - (middleX / 4 + addX / 3)) * 2, (middleY - (middleY / 4 + addY / 3)) * 2); g.drawRect(middleX / 4 + addX / 3 + 2, middleY / 4 + addY / 3 + 2, (middleX - (middleX / 4 + addX / 3)) * 2, (middleY - (middleY / 4 + addY / 3)) * 2); g.drawRect(middleX / 4 + 2 * addX / 3 + 1, middleY / 4 + 2 * addY / 3 + 1, (middleX - (middleX / 4 + 2 * addX / 3)) * 2, (middleY - (middleY / 4 + 2 * addY / 3)) * 2); g.drawRect(middleX / 4 + 2 * addX / 3 + 2, middleY / 4 + 2 * addY / 3 + 2, (middleX - (middleX / 4 + 2 * addX / 3)) * 2, (middleY - (middleY / 4 + 2 * addY / 3)) * 2); g.drawLine(middleX + 1, middleY / 4, middleX + 1, middleY / 4 + 2 * addY / 3); g.drawLine(middleX + 2, middleY / 4, middleX + 2, middleY / 4 + 2 * addY / 3); g.drawLine(middleX + 1, middleY + middleY / 4, middleX + 1, middleY + (middleY / 4 + 2 * addY / 3)); g.drawLine(middleX + 2, middleY + middleY / 4, middleX + 2, middleY + (middleY / 4 + 2 * addY / 3)); g.drawLine(middleX / 4, middleY + 1, middleX / 4 + 2 * addX / 3, middleY + 1); g.drawLine(middleX / 4, middleY + 2, middleX / 4 + 2 * addX / 3, middleY + 2); g.drawLine(middleX + middleX / 4, middleY + 1, middleX + middleX / 4 + 2 * addX / 3, middleY + 1); g.drawLine(middleX + middleX / 4, middleY + 2, middleX + middleX / 4 + 2 * addX / 3, middleY + 2); } for (int i = 0; i < 9; i++) { if (Black[i] != null && White[i] != null) { g.fillOval(Black[i].posX, Black[i].posY, r, r); g.drawOval(White[i].posX, White[i].posY, r, r); } else ; } sF.places(mFra); } public static void main(String args[]) { new Head().BuildUp(); } public void BuildUp() { mFra.add(this); mFra.setForeground(new Color(255, 134, 13)); mFra.setBackground(new Color(94, 47, 0)); sF.places(mFra); this.addMouseListener(this); mFra.setVisible(true); mFra.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } public void moveS(MouseEvent e) { Stone[] st = new Stone[9]; boolean yep = true; int r = mFra.getSize().width * mFra.getSize().height / 30000 / 2; int x = e.getX(); int y = e.getY(); // Which Stone do we want to move? if (nmm.getActivePlayer() == Player.WHITE) { st = White; } else st = Black; if (nmm.getPhase() == Phase.PLACING_STONES) { for (int i = 0; i < 9; i++) { // This sets the stone to a corner if (st[i].inPlacement == true && st[i].placed == false) { // Did // choose // piece? // already // placed? for (int l = 0; l < 24; l++) { for (int j = 0; j < 2 * r; j++) { for (int k = 0; k < 2 * r; k++) { if (e.getX() == sF.placement[l][0] - r + j && e.getY() == sF.placement[l][1] - r + k && sF.placed[l] == false) { int s; if (nmm.getActivePlayer() == Player.WHITE) s = i; else s = i + 9; int z = nmm.moveStone(s, l); if (z > 0) { st[i].inPlacement = false; st[i].posX = sF.placement[l][0] - r; st[i].posY = sF.placement[l][1] - r; sF.placed[l] = true; st[i].placedAt = l; st[i].placed = true; yep = true; if (z == 2) mill = true; break; } } } } } } // This just wants to know if one stone has been selected yet for (int j = 0; j < 9; j++) { if (st[j].inPlacement == true) yep = false; } // Selects the Stone if (st[i].inPlacement == false && yep == true && st[i].placed == false) { // >> I didn't choose a piece yet, doesn't work tho... for (int j = 0; j < 2 * r; j++) { for (int k = 0; k < 2 * r; k++) { if (x == st[i].posX + j) { if (y == st[i].posY + k && st[i].inPlacement == false) { // else // this // function // not // deterministic st[i].inPlacement = true; st[i].set(5); } } } }// forJ } }// forI } else { for (int i = 0; i < 9; i++) { if (st[i].inPlacement == true) { // Did I choose a piece? Is it // already placed? for (int l = 0; l < 24; l++) { for (int j = 0; j < 2 * r; j++) { for (int k = 0; k < 2 * r; k++) { if (e.getX() == sF.placement[l][0] - r + j && e.getY() == sF.placement[l][1] - r + k) { int s; if (nmm.getActivePlayer() == Player.WHITE) s = i; else s = i + 9; int z = nmm.moveStone(s, l); if (z > 0) { st[i].inPlacement = false; st[i].posX = sF.placement[l][0] - r; st[i].posY = sF.placement[l][1] - r; sF.placed[l] = true; st[i].placedAt = l; st[i].placed = true; yep = true; if (z == 2) mill = true; break; } else { st[i].inPlacement = false; st[i].set(-5); System.out.println("ERROR!"); } } } } } } // This just wants to know if one stone has been selected yet for (int j = 0; j < 9; j++) { if (st[j].inPlacement == true) yep = false; } // Selects the Stone if (st[i].inPlacement == false && yep == true) { for (int j = 0; j < 2 * r; j++) { for (int k = 0; k < 2 * r; k++) { if (x == st[i].posX + j) { if (y == st[i].posY + k && st[i].inPlacement == false) { // else // this // function // not // deterministic st[i].inPlacement = true; st[i].set(5); } } } }// forJ } }// forI } } public void delete(MouseEvent e) { Stone[] st = new Stone[9]; if (nmm.getActivePlayer() == Player.BLACK) { st = White; } else st = Black; int r = mFra.getSize().width * mFra.getSize().height / 30000 / 2; for (int i = 0; i < 9; i++) { for (int j = 0; j < 2 * r; j++) { for (int k = 0; k < 2 * r; k++) { if (e.getX() == st[i].posX + j && e.getY() == st[i].posY + k) { boolean m2; if (nmm.getActivePlayer() == Player.BLACK) { m2 = nmm.removeStone(i); } else { m2 = nmm.removeStone(i + 9); } if (m2) { sF.placed[st[i].placedAt] = false; st[i].placedAt = -2; st[i].set(-50, -50); mill = false; } } } } } repaint(); } public void mouseClicked(MouseEvent e) { System.out.println(mill); if (mill) { delete(e); } else { moveS(e); } } public void mousePressed(MouseEvent e) { // this.setBackground(new Color((int) (Math.random()*255),(int) // (Math.random()*255),(int) (Math.random()*255))); // repaint(); } public void mouseReleased(MouseEvent e) { repaint(); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } }
package br.com.fiap.managedbeans; import java.io.IOException; import java.io.Serializable; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.servlet.http.HttpSession; import br.com.fiap.commands.NetgifxCommand; import br.com.fiap.entity.Gif; import br.com.fiap.entity.Usuario; @ManagedBean @SessionScoped public class UsuarioMB implements Serializable { private static final long serialVersionUID = 1L; private Usuario usuario = new Usuario(); private NetgifxCommand netgifxCommand = new NetgifxCommand(); public String realizarLogin() { Usuario usuario = netgifxCommand.buscarUsuario(this.usuario.getApelido()); FacesContext context = FacesContext.getCurrentInstance(); if (usuario != null && usuario.getSenha().equals(this.usuario.getSenha())) { this.usuario = usuario; context.getExternalContext().getSessionMap().put("usuario", usuario); return "webapp/protected/main.xhtml?faces-redirect=true"; } else { context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro ao realizar login!", "O usurio no possui um cadastro ou a senha est incorreta. Entre em contato com um administrador para cadastrar!")); return null; } } public String realizarLogout() { FacesContext context = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) context.getExternalContext().getSession(false); session.invalidate(); try { context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/index.xhtml"); } catch (IOException e) { e.printStackTrace(); } return "webapp/login/login.xhtml?faces-redirect=true"; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public void favoritarGif(Gif gif){ NetgifxCommand command = new NetgifxCommand(); usuario.getGifs().add(gif); command.atualizarDadosUsuario(usuario); } public void desfavoritarGif(Gif gif){ NetgifxCommand command = new NetgifxCommand(); usuario.getGifs().removeIf(g -> g.getIdGif() == gif.getIdGif()); command.atualizarDadosUsuario(usuario); } public boolean validarGifFavorito(Gif gif){ return usuario.getGifs().stream().filter(us -> us.getIdGif() == gif.getIdGif()).count() > 0; } }
package org.herac.tuxguitar.gui.mixer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Scale; import org.eclipse.swt.widgets.Shell; import org.herac.tuxguitar.gui.TuxGuitar; import org.herac.tuxguitar.gui.undo.undoables.track.UndoableTrackChannel; import org.herac.tuxguitar.song.models.TGTrack; public class TGMixerTrack { protected TGTrack track; protected TGMixer mixer; protected TGMixerTrackChannel mixerChannel; protected Button checkSolo; protected Button checkMute; private TGMixerScale scaleVolume; private TGMixerScale scaleBalance; private TGMixerScalePopup scaleChorus; private TGMixerScalePopup scaleReverb; private TGMixerScalePopup scalePhaser; private TGMixerScalePopup scaleTremolo; private Label volumeValueLabel; private Label volumeValueTitleLabel; public TGMixerTrack(TGMixer mixer,TGTrack track){ this.mixer = mixer; this.track = track; } public void init(final Composite parent) { final Composite composite = new Composite(parent, SWT.BORDER); composite.setLayout(new GridLayout(1, true)); composite.setLayoutData(new GridData(SWT.CENTER,SWT.FILL,true,true)); this.mixerChannel = new TGMixerTrackChannel(this); this.mixerChannel.init(composite); this.checkSolo = new Button(composite,SWT.CHECK); this.checkSolo.setSelection(TGMixerTrack.this.track.isSolo()); this.checkSolo.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { UndoableTrackChannel undoable = UndoableTrackChannel.startUndo(); TGMixerTrack.this.track.setSolo(TGMixerTrack.this.checkSolo.getSelection()); if(TGMixerTrack.this.track.isSolo()){ TGMixerTrack.this.track.setMute(false); } TGMixerTrack.this.mixer.fireChanges(TGMixerTrack.this.track.getChannel(),TGMixer.SOLO); TuxGuitar.instance().getUndoableManager().addEdit(undoable.endUndo()); TuxGuitar.instance().updateCache(true); } }); this.checkMute = new Button(composite,SWT.CHECK); this.checkMute.setSelection(TGMixerTrack.this.track.isMute()); this.checkMute.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { UndoableTrackChannel undoable = UndoableTrackChannel.startUndo(); TGMixerTrack.this.track.setMute(TGMixerTrack.this.checkMute.getSelection()); if(TGMixerTrack.this.track.isMute()){ TGMixerTrack.this.track.setSolo(false); } TGMixerTrack.this.mixer.fireChanges(TGMixerTrack.this.track.getChannel(),TGMixer.MUTE); TuxGuitar.instance().getUndoableManager().addEdit(undoable.endUndo()); TuxGuitar.instance().updateCache(true); } }); new Label(composite, SWT.HORIZONTAL | SWT.SEPARATOR).setLayoutData(new GridData(SWT.FILL,SWT.CENTER,true,false)); Composite effects = new Composite(composite, SWT.NONE); effects.setLayout(new GridLayout(4,false)); effects.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); this.scaleChorus = new TGMixerScalePopup(effects, SWT.VERTICAL, 64, TGMixer.CHORUS, getVerticalScaleData()); this.scaleChorus.setSelection( this.track.getChannel().getChorus()); this.scaleReverb = new TGMixerScalePopup(effects, SWT.VERTICAL, 64, TGMixer.REVERB, getVerticalScaleData()); this.scaleReverb.setSelection( this.track.getChannel().getReverb()); this.scalePhaser = new TGMixerScalePopup(effects, SWT.VERTICAL, 64, TGMixer.PHASER, getVerticalScaleData()); this.scalePhaser.setSelection( this.track.getChannel().getPhaser()); this.scaleTremolo = new TGMixerScalePopup(effects, SWT.VERTICAL, 64, TGMixer.TREMOLO, getVerticalScaleData()); this.scaleTremolo.setSelection( this.track.getChannel().getTremolo()); new Label(composite, SWT.HORIZONTAL | SWT.SEPARATOR).setLayoutData(new GridData(SWT.FILL,SWT.CENTER,true,false)); this.scaleBalance = new TGMixerScale(composite, SWT.HORIZONTAL, 64, TGMixer.BALANCE, getHorizontalScaleData()); this.scaleBalance.setSelection(this.track.getChannel().getBalance()); this.scaleVolume = new TGMixerScale(composite, SWT.VERTICAL, 16, TGMixer.VOLUME, new GridData(SWT.CENTER,SWT.FILL,true,true)); this.scaleVolume.setSelection( this.track.getChannel().getVolume()); Label separator = new Label(composite, SWT.HORIZONTAL | SWT.SEPARATOR); separator.setLayoutData(new GridData(SWT.FILL,SWT.BOTTOM,true,false)); Composite volumeValueComposite = new Composite(composite, SWT.NONE); volumeValueComposite.setLayout(new GridLayout(2,false)); this.volumeValueTitleLabel = new Label(volumeValueComposite, SWT.LEFT); this.volumeValueLabel = new Label(volumeValueComposite, SWT.CENTER); this.volumeValueLabel.setLayoutData(getVolumeValueLabelData()); this.volumeValueLabel.setText(Integer.toString(this.track.getChannel().getVolume())); } private GridData getHorizontalScaleData(){ GridData data = new GridData(SWT.CENTER,SWT.NONE,false,true); data.widthHint = 80; return data; } private GridData getVerticalScaleData(){ GridData data = new GridData(SWT.CENTER,SWT.FILL,false,true); data.heightHint = 65; return data; } private GridData getVolumeValueLabelData(){ GridData data = new GridData(SWT.CENTER,SWT.NONE,true,false); data.minimumWidth = 40; return data; } public void fireChanges(int type){ if((type & TGMixer.SOLO) != 0 || (type & TGMixer.MUTE) != 0){ this.checkSolo.setSelection(this.track.isSolo()); this.checkMute.setSelection(this.track.isMute()); } if((type & TGMixer.CHANNEL) != 0 || (type & TGMixer.VOLUME) != 0){ int value = this.track.getChannel().getVolume(); this.scaleVolume.setSelection( ( value) ); this.volumeValueLabel.setText(Integer.toString( value )); } if((type & TGMixer.CHANNEL) != 0 || (type & TGMixer.BALANCE) != 0){ int value = this.track.getChannel().getBalance(); this.scaleBalance.setSelection(value); } if((type & TGMixer.CHANNEL) != 0 || (type & TGMixer.CHORUS) != 0){ int value = this.track.getChannel().getChorus(); this.scaleChorus.setSelection( ( value) ); } if((type & TGMixer.CHANNEL) != 0 || (type & TGMixer.REVERB) != 0){ int value = this.track.getChannel().getReverb(); this.scaleReverb.setSelection( ( value) ); } if((type & TGMixer.CHANNEL) != 0 || (type & TGMixer.PHASER) != 0){ int value = this.track.getChannel().getPhaser(); this.scalePhaser.setSelection( ( value) ); } if((type & TGMixer.CHANNEL) != 0 || (type & TGMixer.TREMOLO) != 0){ int value = this.track.getChannel().getTremolo(); this.scaleTremolo.setSelection( ( value) ); } if((type & TGMixer.CHANNEL) != 0){ this.mixerChannel.updateItems(true); } } public void loadProperties(){ this.checkSolo.setText(TuxGuitar.getProperty("mixer.track.solo")); this.checkMute.setText(TuxGuitar.getProperty("mixer.track.mute")); this.volumeValueTitleLabel.setText(TuxGuitar.getProperty("mixer.channel.volume") + ":"); this.scaleVolume.setText(TuxGuitar.getProperty("mixer.channel.volume")); this.scaleBalance.setText(TuxGuitar.getProperty("mixer.channel.balance")); this.scaleChorus.setText(TuxGuitar.getProperty("mixer.channel.chorus")); this.scaleReverb.setText(TuxGuitar.getProperty("mixer.channel.reverb")); this.scalePhaser.setText(TuxGuitar.getProperty("mixer.channel.phaser")); this.scaleTremolo.setText(TuxGuitar.getProperty("mixer.channel.tremolo")); this.mixerChannel.updateItems(true); } public void updateItems(){ this.mixerChannel.updateItems(false); } public TGTrack getTrack(){ return this.track; } public TGMixer getMixer(){ return this.mixer; } protected void updateChannelValue(int type, int value){ if( (type & TGMixer.VOLUME) != 0 ){ TGMixerTrack.this.track.getChannel().setVolume( (short)value ); } else if( (type & TGMixer.BALANCE) != 0 ){ TGMixerTrack.this.track.getChannel().setBalance( (short)value ); } else if( (type & TGMixer.CHORUS) != 0 ){ TGMixerTrack.this.track.getChannel().setChorus( (short)value ); } else if( (type & TGMixer.REVERB) != 0 ){ TGMixerTrack.this.track.getChannel().setReverb( (short)value ); } else if( (type & TGMixer.PHASER) != 0 ){ TGMixerTrack.this.track.getChannel().setPhaser( (short)value ); } else if( (type & TGMixer.TREMOLO) != 0 ){ TGMixerTrack.this.track.getChannel().setTremolo( (short)value ); } this.mixer.fireChanges(TGMixerTrack.this.track.getChannel(), type); } private class TGMixerScale { private int type; private int value; private boolean inverted; private Scale scale; private String text; protected UndoableTrackChannel undoable; public TGMixerScale(Composite parent, int style, int pageIncrement, int type, Object layoutData){ this.init(parent, style, pageIncrement, type, layoutData); } public void init(Composite parent, int style, int pageIncrement, int type, Object layoutData){ this.scale = new Scale(parent, style); this.scale.setMaximum(127); this.scale.setMinimum(0); this.scale.setIncrement(1); this.scale.setPageIncrement(pageIncrement); this.scale.setLayoutData(layoutData); this.type = type; this.value = -1; this.inverted = ((style & SWT.VERTICAL) != 0 ); this.addDefaultListeners(); } public void addDefaultListeners(){ this.scale.addListener(SWT.Selection, new Listener() { public synchronized void handleEvent(Event event) { TGMixerScale.this.updateValue(); TGMixerTrack.this.updateChannelValue(getType(), getSelection()); } }); this.scale.addMouseListener(new MouseAdapter() { public void mouseDown(MouseEvent arg0) { TGMixerScale.this.undoable = UndoableTrackChannel.startUndo(); } public void mouseUp(MouseEvent arg0) { if(TGMixerScale.this.undoable != null){ TuxGuitar.instance().getUndoableManager().addEdit(TGMixerScale.this.undoable.endUndo()); TuxGuitar.instance().getFileHistory().setUnsavedFile(); TuxGuitar.instance().updateCache(true); TGMixerScale.this.undoable = null; } } }); } public void updateValue(){ this.setSelection( ( this.inverted ? 127 - this.scale.getSelection() : this.scale.getSelection() ) ); } public int getType(){ return this.type; } public int getSelection(){ if(this.value < 0){ this.updateValue(); } return this.value; } public void setSelection(int value){ if(value != this.value){ this.value = value; this.scale.setSelection( ( this.inverted ? 127 - this.value : this.value ) ); this.updateToolTipValue(); } } public void updateToolTipValue(){ if(this.text != null){ this.scale.setToolTipText( this.text + ": " + this.value ); } } public void setText(String text){ this.text = text; this.updateToolTipValue(); } public String getText(){ return this.text; } } private class TGMixerScalePopup extends TGMixerScale{ private Shell shell; private Composite composite; private Button item; public TGMixerScalePopup(Composite parent, int style, int pageIncrement, int type, Object layoutData){ super(parent, style, pageIncrement, type, layoutData); } public void init(Composite parent, int style, int pageIncrement, int type, Object layoutData){ this.shell = new Shell( parent.getShell(), SWT.NO_TRIM); this.shell.setVisible(false); this.shell.setLayout(getGridLayout()); this.shell.addShellListener(new ShellAdapter() { public void shellDeactivated(ShellEvent e) { hideShell(); } public void shellClosed(ShellEvent e) { e.doit = false; hideShell(); } }); this.composite = new Composite(this.shell, SWT.BORDER); this.composite.setLayout(getGridLayout()); this.composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); this.item = new Button(parent, SWT.PUSH); this.item.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { showSelect(); } }); super.init(this.composite, style, pageIncrement, type, layoutData); } private GridLayout getGridLayout(){ GridLayout layout = new GridLayout(); layout.horizontalSpacing = 0; layout.verticalSpacing = 0; layout.marginWidth = 0; layout.marginHeight = 0; layout.marginTop = 0; layout.marginBottom = 0; layout.marginLeft = 0; layout.marginHeight = 0; return layout; } public void updateToolTipValue(){ super.updateToolTipValue(); if(this.getText() != null){ this.item.setToolTipText( this.getText() + ": " + this.getSelection() ); } } public void setText(String text){ super.setText(text); if(this.getText() != null && this.getText().length() > 0){ this.item.setText( this.getText().substring(0,1) ); } } public void showSelect() { if(!this.shell.isVisible()){ Rectangle bounds = this.item.getBounds(); Point location = this.item.getParent().toDisplay(new Point(bounds.x, bounds.y)); this.shell.pack(); this.shell.setLocation( (location.x + (bounds.width / 2)) - (this.shell.getSize().x / 2), location.y + bounds.height); this.shell.setVisible(true); this.shell.setActive(); } } public void hideShell() { this.shell.setVisible(false); } } }
package helpers; import generated.*; import java.util.List; import java.util.Random; import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.commons.cli.Options; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; public class Main { public static void main(String[] args) throws Exception { Options options = createCommandLineOptions(); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java helpers.Main", options); return; } long exceptionsCount = Long.MAX_VALUE; if (cmd.hasOption("exceptions-count")) { exceptionsCount = parseLong(cmd.getOptionValue("exceptions-count"), exceptionsCount); } long intervalMillis = 1000; if (cmd.hasOption("interval-millis")) { intervalMillis = parseLong(cmd.getOptionValue("interval-millis"), intervalMillis); } long warmupMillis = 0; if (cmd.hasOption("warmup-millis")) { warmupMillis = parseLong(cmd.getOptionValue("warmup-millis"), warmupMillis); } int threadCount = 5; if (cmd.hasOption("thread-count")) { threadCount = parseInt(cmd.getOptionValue("thread-count"), threadCount); } int printStatusEvery = Integer.MAX_VALUE; if (cmd.hasOption("print-status-every")) { printStatusEvery = parseInt(cmd.getOptionValue("print-status-every"), printStatusEvery); } int runCount = 1; if (cmd.hasOption("run-count")) { runCount = parseInt(cmd.getOptionValue("run-count"), runCount); } if (cmd.hasOption("frames-range")) { int[] framesCountRange = parseRange(cmd.getOptionValue("frames-range"), (new int[] { 0, 10 })); if (framesCountRange != null) { System.out.println("Setting frames range " + framesCountRange[0] + ".." + framesCountRange[1]); Config.get().setFramesRangeFromCommandLine(framesCountRange); } } boolean singleThread = false; if (cmd.hasOption("single-thread")) { singleThread = true; } if (cmd.hasOption("sticky-path")) { Config.get().setStickyPathsDir(cmd.getOptionValue("sticky-path")); } if (cmd.hasOption("events-spot")) { Config.get().setEventSpotDir(cmd.getOptionValue("events-spot")); } if (cmd.hasOption("seed")) { Config.rand = new Random(parseLong(cmd.getOptionValue("seed"), 0)); } boolean hideStackTraces = false; if (cmd.hasOption("hide-stacktraces")) { hideStackTraces = true; } System.out.println(String.format( "(Exceptions: %d) (Interval: %dms) (Warmup: %dms) (Threads: %d) (%s stacktraces) (sticky path: %s) (event spot: %s)", exceptionsCount, intervalMillis, warmupMillis, singleThread ? 1 : threadCount, hideStackTraces ? "hide" : "show", Config.get().getStickyPathsDir(), Config.get().getEventSpotDir())); long startMillis = System.currentTimeMillis(); long warmupMillisTotal = 0l; ExecutorService executor = Executors.newFixedThreadPool(threadCount); long tasksCompleted = 0l; for (int j = 0; j < runCount; j++) { List<Future> calls = new ArrayList<Future>(); warmupMillisTotal = 0l; startMillis = System.currentTimeMillis(); tasksCompleted = 0l; try { long warmupStartMillis = System.currentTimeMillis(); if (warmupMillis > 0) { Thread.sleep(warmupMillis); } warmupMillisTotal += (System.currentTimeMillis() - warmupStartMillis); } catch (Exception e) { } if (runCount > 1) { System.out.println("Starting iteration number: " + (j + 1)); } for (long i = 0; i < exceptionsCount; i++) { try { if (singleThread) { tasksCompleted++; EntrypointSwitcher.randomCallable().call(); StatsReporter.get().incTasksCompleted(); } else { calls.add(executor.submit(EntrypointSwitcher.randomCallable())); } } catch (Exception e) { handleException(e, hideStackTraces, false); } long intervalStartMillis = System.currentTimeMillis(); do { if (!singleThread) { List<Future> doneCalls = new ArrayList<Future>(); for (Future call : calls) { if (call.isCancelled() || call.isDone()) { try { call.get(); } catch (Exception e) { handleException(e, hideStackTraces, true); } tasksCompleted++; StatsReporter.get().incTasksCompleted(); doneCalls.add(call); } } for (Future doneCall : doneCalls) { calls.remove(doneCall); } } if (intervalMillis > 0l) { try { Thread.currentThread().sleep(100); } catch (Exception e) { } } StatsReporter.get().generateReport(); } while ((System.currentTimeMillis() - intervalStartMillis) < intervalMillis); if (tasksCompleted > 0 && (tasksCompleted % printStatusEvery) == 0) { long endMillis = System.currentTimeMillis(); long diffMillis = (endMillis - startMillis); System.out.println("Took: " + (diffMillis - warmupMillisTotal) + " to throw " + tasksCompleted + " exceptions"); } } for (Future call : calls) { while (!call.isCancelled() && !call.isDone()) { try { Thread.currentThread().sleep(1); } catch (Exception e) { } } try { tasksCompleted++; call.get(); } catch (Exception e) { handleException(e, hideStackTraces, true); } if (tasksCompleted > 0 && (tasksCompleted % printStatusEvery) == 0) { long endMillis = System.currentTimeMillis(); long diffMillis = (endMillis - startMillis); System.out.println("Took: " + (diffMillis - warmupMillisTotal) + " to throw " + tasksCompleted + " exceptions"); } } } if (tasksCompleted > 0 && (tasksCompleted % printStatusEvery) == 0) { long endMillis = System.currentTimeMillis(); long diffMillis = (endMillis - startMillis); System.out.println("Took: " + (diffMillis - warmupMillisTotal) + " to throw " + tasksCompleted + " exceptions"); } executor.shutdown(); long endMillis = System.currentTimeMillis(); long diffMillis = (endMillis - startMillis); System.out.println("Took: " + (diffMillis - warmupMillisTotal) + " to throw " + tasksCompleted + " exceptions"); } private static void handleException(Exception exception, boolean hideStackTraces, boolean nested) { if (nested) { if (exception.getCause() instanceof Exception) { exception = (Exception) exception.getCause(); } } if (!(exception instanceof BullshifierException)) { exception.printStackTrace(); return; } BullshifierException bex = (BullshifierException) exception; if (!hideStackTraces) { exception.printStackTrace(); return; } if (bex != null) { System.out.println(bex.toString()); } } public static long parseLong(String str, long defaultValue) { try { return Long.parseLong(str); } catch (Exception e) { System.out.println("Error parsing long " + str); return defaultValue; } } public static int parseInt(String str, int defaultValue) { try { return Integer.parseInt(str); } catch (Exception e) { System.out.println("Error parsing int " + str); return defaultValue; } } public static int[] parseRange(String str, int[] defaultValue) { if (str == null) { System.out.println("Parse range error: null"); return defaultValue; } int from = defaultValue[0]; int to = defaultValue[1]; if (str.indexOf("..") == -1) { from = parseInt(str, defaultValue[0]); to = from; } else { String[] parts = str.split("\\.\\."); if (parts == null || parts.length != 2) { System.out.println("Parse range error: invalid format: " + str); return defaultValue; } from = parseInt(parts[0], from); to = parseInt(parts[1], to); } int[] result = new int[2]; result[0] = from; result[1] = to; return result; } private static Options createCommandLineOptions() { Options options = new Options(); options.addOption("h", "help", false, "Print this help"); options.addOption("st", "single-thread", false, "Run everything directly from the main thread (default to false)"); options.addOption("hs", "hide-stacktraces", false, "Determine whether to print the stack traces of the exceptions (default to false)"); options.addOption("pse", "print-status-every", true, "Print to screen every n events (default to Integer.MAX_VALUE)"); options.addOption("tc", "thread-count", true, "The number of threads (default to 5)"); options.addOption("ec", "exceptions-count", true, "The number of exceptions to throw (default to 1000)"); options.addOption("wm", "warmup-millis", true, "Time to wait before starting to throw exceptions (in millis) (default to 0)"); options.addOption("im", "interval-millis", true, "Time between exceptions (in millis) (default to 1000)"); options.addOption("rc", "run-count", true, "The number of times to run all (default to 1)"); options.addOption("fc", "frames-range", true, "Choose a random number between a range in '(X..)?Y' format. (default is 1..1)"); options.addOption("sp", "sticky-path", true, "A path to store constant paths in the code"); options.addOption("es", "events-spot", true, "A path to store events spot"); options.addOption("s", "seed", true, "Application 'Random' seed number"); return options; } }
package helpers; import generated.*; import java.util.List; import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.commons.cli.Options; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class Main { public static void main(String[] args) throws Exception { Options options = createCommandLineOptions(); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java helpers.Main", options); return; } long exceptionsCount = Long.MAX_VALUE; if (cmd.hasOption("exceptions-count")) { exceptionsCount = parseLong(cmd.getOptionValue("exceptions-count"), exceptionsCount); } long intervalMillis = 1000; if (cmd.hasOption("interval-millis")) { intervalMillis = parseLong(cmd.getOptionValue("interval-millis"), intervalMillis); } long warmupMillis = 0; if (cmd.hasOption("warmup-millis")) { warmupMillis = parseLong(cmd.getOptionValue("warmup-millis"), warmupMillis); } int threadCount = 5; if (cmd.hasOption("thread-count")) { threadCount = parseInt(cmd.getOptionValue("thread-count"), threadCount); } int printStatusEvery = Integer.MAX_VALUE; if (cmd.hasOption("print-status-every")) { printStatusEvery = parseInt(cmd.getOptionValue("print-status-every"), printStatusEvery); } int runCount = 1; if (cmd.hasOption("run-count")) { runCount = parseInt(cmd.getOptionValue("run-count"), runCount); } boolean singleThread = false; if (cmd.hasOption("single-thread")) { singleThread = true; } boolean hideStackTraces = false; if (cmd.hasOption("hide-stacktraces")) { hideStackTraces = true; } System.out.println(String.format( "Throwing %d exceptions every %dms. starting at %dms from the beginning (%d threads) (%s stacktraces)", exceptionsCount, intervalMillis, warmupMillis, singleThread ? 1 : threadCount, hideStackTraces ? "hide" : "show")); long startMillis = System.currentTimeMillis(); long warmupMillisTotal = 0l; ExecutorService executor = Executors.newFixedThreadPool(threadCount); long exceptionsCounter = 0l; for (int j = 0; j < runCount; j++) { List<Future> calls = new ArrayList<Future>(); startMillis = System.currentTimeMillis(); exceptionsCounter = 0l; try { long warmupStartMillis = System.currentTimeMillis(); if (warmupMillis > 0) { Thread.sleep(warmupMillis); } warmupMillisTotal += (System.currentTimeMillis() - warmupStartMillis); } catch (Exception e) { } if (runCount > 1) { System.out.println("Starting iteration number: " + (j + 1)); } for (long i = 0; i < exceptionsCount; i++) { try { if (singleThread) { EntrypointSwitcher.randomCallable().call(); } else { calls.add(executor.submit(EntrypointSwitcher.randomCallable())); } } catch (Exception e) { if (!hideStackTraces) { e.printStackTrace(); } } exceptionsCounter++; long intervalStartMillis = System.currentTimeMillis(); do { if (!singleThread && !hideStackTraces) { List<Future> doneCalls = new ArrayList<Future>(); for (Future call : calls) { if (call.isCancelled() || call.isDone()) { try { call.get(); } catch (Exception e) { if (e.getCause() != null) { e.getCause().printStackTrace(); } } doneCalls.add(call); } } for (Future doneCall : doneCalls) { calls.remove(doneCall); } } if (intervalMillis > 0l) { try { Thread.currentThread().sleep(100); } catch (Exception e) { } } } while ((System.currentTimeMillis() - intervalStartMillis) < intervalMillis); if (((i + 1) % printStatusEvery) == 0) { long endMillis = System.currentTimeMillis(); long diffMillis = (endMillis - startMillis); System.out.println(" System.out.println("Took: " + (diffMillis - warmupMillisTotal) + " to throw " + exceptionsCounter + " exceptions"); System.out.println(""); Runtime runtime = Runtime.getRuntime(); System.out.println("heapSize = " + runtime.totalMemory()); System.out.println("maxHeap = " + runtime.maxMemory()); System.out.println("freeHeap = " + runtime.freeMemory()); System.out.println(""); printMoreStats(); System.out.println(" } } for (Future call : calls) { while (!call.isCancelled() && !call.isDone()) { try { Thread.currentThread().sleep(1); } catch (Exception e) { } } if (!hideStackTraces) { try { call.get(); } catch (Exception e) { if (e.getCause() != null) { e.getCause().printStackTrace(); } } } } } executor.shutdown(); long endMillis = System.currentTimeMillis(); long diffMillis = (endMillis - startMillis); System.out.println("Took: " + (diffMillis - warmupMillisTotal) + " to throw " + exceptionsCount + " exceptions"); } public static long parseLong(String str, long defaultValue) { try { return Long.parseLong(str); } catch (Exception e) { return defaultValue; } } public static int parseInt(String str, int defaultValue) { try { return Integer.parseInt(str); } catch (Exception e) { return defaultValue; } } public static void printMoreStats() { OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) { method.setAccessible(true); if (method.getName().startsWith("get") && Modifier.isPublic(method.getModifiers())) { Object value; try { value = method.invoke(operatingSystemMXBean); } catch (Exception e) { value = e; } System.out.println(method.getName() + " = " + value); } } } private static Options createCommandLineOptions() { Options options = new Options(); options.addOption("h", "help", false, "Print this help"); options.addOption("st", "single-thread", false, "Run everything directly from the main thread (default to false)"); options.addOption("hs", "hide-stacktraces", false, "Determine whether to print the stack traces of the exceptions (default to false)"); options.addOption("pse", "print-status-every", true, "Print to screen every n events (default to Integer.MAX_VALUE)"); options.addOption("tc", "thread-count", true, "The number of threads (default to 5)"); options.addOption("ec", "exceptions-count", true, "The number of exceptions to throw (default to 1000)"); options.addOption("wm", "warmup-millis", true, "Time to wait before starting to throw exceptions (in millis) (default to 0)"); options.addOption("im", "interval-millis", true, "Time between exceptions (in millis) (default to 1000)"); options.addOption("rc", "run-count", true, "The number of times to run all (default to 1)"); return options; } }
package no.altran.kpro2014.View; import javafx.animation.Animation; import javafx.animation.AnimationTimer; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.effect.Bloom; import javafx.scene.effect.MotionBlur; import javafx.scene.image.Image; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Duration; import no.altran.kpro2014.Controller.Controller; import no.altran.kpro2014.Interface.*; import no.altran.kpro2014.Model.RoomModel; import java.awt.*; import java.lang.reflect.Array; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; /** * The main class for the application, this is the map view where the data will be animated. */ public class MapView extends Application{ /**controller and roomModel will gather the data we need, and update the data in time.*/ private Controller controller; private RoomModel roomModel; /**the central hub is in the middle and is a static image*/ private Image circleImage = new Image("images/CentralHub.png"); /**the canvases we use for the visualization*/ private Canvas canvas; private Canvas canvasHist; /**Instructions and Renderers, look over to interface folder for more info*/ private CentralHubInstruction centralHubInstruction; private CentralHubRenderer centralHubRenderer; private SensorInstruction sensorInstruction; private SensorRender sensorRender; private TemperatureInstruction temperatureInstruction; private TemperatureRender temperatureRender; private HumidityInstruction humidityInstruction; private HumidityRender humidityRender; private PressureInstruction pressureInstruction; private PressureRender pressureRender; /**These are the lists that control the animation. We store both the new data, the old data and the difference * between them. We use it to calculate the difference in between the old and new data divided by the * frames we have, so that it changes by difference every frame, thus making it smooth (pleasing for the eyes) */ private ArrayList<Double> oldLighting = new ArrayList<Double>(); private ArrayList<Double> newLighting = new ArrayList<Double>(); private ArrayList<Double> diffLighting = new ArrayList<Double>(); private ArrayList<Double> oldHumidity = new ArrayList<Double>(); private ArrayList<Double> newHumidity = new ArrayList<Double>(); private ArrayList<Double> diffHumidity = new ArrayList<Double>(); private ArrayList<Double> oldPressure = new ArrayList<Double>(); private ArrayList<Double> newPressure = new ArrayList<Double>(); private ArrayList<Double> diffPressure = new ArrayList<Double>(); private ArrayList<Double> oldTemperature = new ArrayList<Double>(); private ArrayList<Double> newTemperature = new ArrayList<Double>(); private ArrayList<Double> diffTemperature = new ArrayList<Double>(); // private ArrayList<Double> positionX = new ArrayList<>(); // private ArrayList<Double> positionY = new ArrayList<>(); private ArrayList<Double> oldPositionX = new ArrayList<Double>(); private ArrayList<Double> newPositionX = new ArrayList<Double>(); private ArrayList<Double> diffPositionX = new ArrayList<Double>(); private ArrayList<Double> oldPositionY = new ArrayList<Double>(); private ArrayList<Double> newPositionY = new ArrayList<Double>(); private ArrayList<Double> diffPositionY = new ArrayList<Double>(); // private ArrayList<Double> tList = new ArrayList<Double>(); private ArrayList<Double> inactiveSensor = new ArrayList<Double>(); private int counter = 0; /**these are the checkboxes the user can interact with, this will turn off/on certain types of data */ private boolean checkTemperature = true; private boolean checkLighting = true; private boolean checkHumidity = true; private boolean checkPressure = true; /**start method for the system, it requires a stage which we set to the size of the computer window the user have*/ public void start(Stage stage) { long now = System.currentTimeMillis(); Scene scene = new Scene(new Group()); controller = new Controller(); roomModel = controller.getRoomModel(); stage.setTitle("Map View"); stage.setWidth(Toolkit.getDefaultToolkit().getScreenSize().getWidth()); stage.setHeight(Toolkit.getDefaultToolkit().getScreenSize().getHeight()); /**canvas is set a little smaller than the actual stage in order for the checkboxes to fit*/ canvas = new Canvas(stage.getWidth()-150,stage.getHeight()); /**we also added some bloom and motionBlur to make the animation look better*/ Bloom mainFX = new Bloom(); mainFX.setThreshold(0.95); MotionBlur mb = new MotionBlur(); mb.setAngle(60.0f); mb.setRadius(1.5f); mainFX.setInput(mb); canvas.setEffect(mainFX); canvasHist = new Canvas(150, 400); /** Creates the central hub. This object is static. */ final int TotalCHCount = roomModel.getGatewayList().size(); /** *Animation timer for updating values. Whenever a new update in the data is called, we'll set the array lists to * the new value, calculating how many frames we need. Then send it as instruction, and notify the renderer a new * instruction has been given. */ new AnimationTimer(){ @Override public void handle(long now){ canvas.getGraphicsContext2D().clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); for(int i = 0; i < TotalCHCount; i++){ centralHubInstruction = new CentralHubInstruction(circleImage, now, Long.MAX_VALUE, gateWayPositionX(i), gateWayPositionsY(i), canvas); centralHubRenderer = new CentralHubRenderer(); centralHubRenderer.notify(centralHubInstruction, Long.MAX_VALUE); } for(int i = 0; i < roomModel.getSensorNumber(); i++){ LightingCheck(newLighting, oldLighting, i, roomModel); HumidityCheck(newHumidity, oldHumidity, i, roomModel); PressureCheck(newPressure, oldPressure, i, roomModel); TemperatureCheck(newTemperature, oldTemperature, i, roomModel); diffInit(diffTemperature,diffLighting,diffHumidity,diffPressure, inactiveSensor, diffPositionX, diffPositionY, i); PositionXCheck(newPositionX, oldPositionX, i, roomModel); PositionYCheck(newPositionY, oldPositionY, i, newPositionX.get(i), roomModel); if (counter >= 300) { counter = 0; } else if (counter == 0) { if (newLighting.get(i) != oldLighting.get(i)) { diffLighting.set(i, (newLighting.get(i) - oldLighting.get(i)) / 300); } if (newHumidity.get(i) != oldHumidity.get(i)) { diffHumidity.set(i, (newHumidity.get(i) - oldHumidity.get(i)) / 300); } if (newPressure.get(i) != oldPressure.get(i)) { diffPressure.set(i, (newPressure.get(i) - oldPressure.get(i)) / 300); } if (newTemperature.get(i) != oldTemperature.get(i)) { diffTemperature.set(i, (newTemperature.get(i) - oldTemperature.get(i)) / 300); } if (newPositionX.get(i) != oldPositionX.get(i)) { diffPositionX.set(i, (newPositionX.get(i) - oldPositionX.get(i)) / 300); } if (newPositionY.get(i) != oldPositionY.get(i)) { diffPositionY.set(i, (newPositionY.get(i) - oldPositionY.get(i)) / 300); } counter++; } else { oldLighting.set(i, oldLighting.get(i) + diffLighting.get(i)); oldHumidity.set(i, oldHumidity.get(i) + diffHumidity.get(i)); oldPressure.set(i, oldPressure.get(i) + diffPressure.get(i)); oldTemperature.set(i, oldTemperature.get(i) + diffTemperature.get(i)); oldPositionX.set(i, oldPositionX.get(i) + diffPositionX.get(i)); oldPositionY.set(i, oldPositionY.get(i) + diffPositionY.get(i)); counter++; } if (inactiveS(diffTemperature, diffPressure, diffHumidity, diffLighting, i)){ double temp = inactiveSensor.get(i) + 1; inactiveSensor.set(i, temp); } else{ inactiveSensor.set(i, 0.0); } if (inactiveSensor.get(i) > 216000){ //TODO might need to fix the oldPositionX() function temperatureInstruction = new TemperatureInstruction("S" + (i+1), oldTemperature.get(i), now, 10, getPositionX(i, oldPositionX.get(i)), getPositionY(i, oldPositionY.get(i)), canvas, false); temperatureRender = new TemperatureRender(); temperatureRender.notify(temperatureInstruction, Long.MAX_VALUE); sensorInstruction = new SensorInstruction("S"+(i+1), oldLighting.get(i), now, 10, getPositionX(i, oldPositionX.get(i))+20, getPositionY(i, oldPositionY.get(i))+20, canvas, false); sensorRender = new SensorRender(); sensorRender.notify(sensorInstruction, Long.MAX_VALUE); humidityInstruction = new HumidityInstruction(oldHumidity.get(i), now, Long.MAX_VALUE, getPositionX(i, oldPositionX.get(i))+79, getPositionY(i, oldPositionY.get(i))+50, canvas, false); humidityRender = new HumidityRender(); humidityRender.notify(humidityInstruction, Long.MAX_VALUE); pressureInstruction = new PressureInstruction(oldPressure.get(i), now, Long.MAX_VALUE, getPositionX(i, oldPositionX.get(i))+79, getPositionY(i, oldPositionY.get(i))+25, canvas, false); pressureRender = new PressureRender(); pressureRender.notify(pressureInstruction, Long.MAX_VALUE); } else { temperatureInstruction = new TemperatureInstruction("S" + (i + 1), oldTemperature.get(i), now, 10, getPositionX(i, oldPositionX.get(i)), getPositionY(i, oldPositionY.get(i)), canvas, checkTemperature); temperatureRender = new TemperatureRender(); temperatureRender.notify(temperatureInstruction, Long.MAX_VALUE); sensorInstruction = new SensorInstruction("S" + (i + 1), oldLighting.get(i), now, 10, getPositionX(i, oldPositionX.get(i)) + 20, getPositionY(i, oldPositionY.get(i)) + 20, canvas, checkLighting); sensorRender = new SensorRender(); sensorRender.notify(sensorInstruction, Long.MAX_VALUE); humidityInstruction = new HumidityInstruction(oldHumidity.get(i), now, Long.MAX_VALUE, getPositionX(i, oldPositionX.get(i)) + 79, getPositionY(i, oldPositionY.get(i)) + 50, canvas, checkHumidity); humidityRender = new HumidityRender(); humidityRender.notify(humidityInstruction, Long.MAX_VALUE); pressureInstruction = new PressureInstruction(oldPressure.get(i), now, Long.MAX_VALUE, getPositionX(i, oldPositionX.get(i)) + 79, getPositionY(i, oldPositionY.get(i)) + 25, canvas, checkPressure); pressureRender = new PressureRender(); pressureRender.notify(pressureInstruction, Long.MAX_VALUE); } } } }.start(); /** * This part is considering checkboxes and how we hide the data if the box is not selected */ final CheckBox cBox1 = new CheckBox("Temperature"); final CheckBox cBox2 = new CheckBox("Lighting"); final CheckBox cBox3 = new CheckBox("Humidity"); final CheckBox cBox4 = new CheckBox("Pressure"); cBox1.setTextFill(Color.WHITE); cBox2.setTextFill(Color.WHITE); cBox3.setTextFill(Color.WHITE); cBox4.setTextFill(Color.WHITE); cBox1.setSelected(true); cBox2.setSelected(true); cBox3.setSelected(true); cBox4.setSelected(true); cBox1.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if(cBox1.isSelected() == false) { checkTemperature = false; } if(cBox1.isSelected()){ checkTemperature = true; } } }); cBox2.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if(cBox2.isSelected() == false){ checkLighting = false; } if(cBox2.isSelected()){ checkLighting = true; } } }); cBox3.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if(cBox3.isSelected() == false){ checkHumidity = false; } if(cBox3.isSelected()) { checkHumidity = true; } } }); cBox4.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if(cBox4.isSelected() == false){ checkPressure = false; } if(cBox4.isSelected()) { checkPressure = true; } } }); /**A time is also added on the side*/ final Label timeLabel = new Label(); timeLabel.setTextFill(Color.WHITE); final DateFormat format = DateFormat.getInstance(); final Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { final Calendar cal = Calendar.getInstance(); timeLabel.setText(format.format(cal.getTime())); } })); timeline.setCycleCount(Animation.INDEFINITE); timeline.play(); /**Here we make the static picture on the side to help a new user understand what the different displays mean*/ temperatureInstruction = new TemperatureInstruction("S#", -25, now, 10, 0, 0, canvasHist, true); temperatureRender = new TemperatureRender(); temperatureRender.notify(temperatureInstruction, Long.MAX_VALUE); canvasHist.getGraphicsContext2D().setStroke(Color.WHITE); canvasHist.getGraphicsContext2D().strokeText("Temperature", 5, 92); sensorInstruction = new SensorInstruction("S#", 3800, now, 10, 20, 100, canvasHist, true); sensorRender = new SensorRender(); sensorRender.notify(sensorInstruction, Long.MAX_VALUE); canvasHist.getGraphicsContext2D().setStroke(Color.WHITE); canvasHist.getGraphicsContext2D().strokeText("Lighting", 15, 148); humidityInstruction = new HumidityInstruction(30, now, Long.MAX_VALUE, 37, 160, canvasHist, true); humidityRender = new HumidityRender(); humidityRender.notify(humidityInstruction, Long.MAX_VALUE); canvasHist.getGraphicsContext2D().setStroke(Color.WHITE); canvasHist.getGraphicsContext2D().strokeText("Humidity", 12, 200); pressureInstruction = new PressureInstruction(1010, now, Long.MAX_VALUE, 37, 240, canvasHist, true); pressureRender = new PressureRender(); pressureRender.notify(pressureInstruction, Long.MAX_VALUE); canvasHist.getGraphicsContext2D().setStroke(Color.WHITE); canvasHist.getGraphicsContext2D().strokeText("Pressure", 12, 255); /**Here we add the checkboxes, the clock and the historyCanvas into the VBox*/ final VBox vBox = new VBox(); vBox.setPadding(new Insets(0,10,10,10)); vBox.setSpacing(10); vBox.getChildren().addAll(cBox1, cBox2, cBox3, cBox4, timeLabel, canvasHist); final GridPane gPane = new GridPane(); gPane.setHgap(5); gPane.setVgap(0); gPane.setPadding(new Insets(20, 20, 20, 20)); gPane.add(vBox, 1, 0); gPane.add(canvas, 0, 0); gPane.setStyle("-fx-background-color: black"); ((Group) scene.getRoot()).getChildren().addAll(gPane); stage.setScene(scene); stage.show(); } /**Here is the methods we use to put data into the arrays*/ private void LightingCheck(ArrayList<Double> list, ArrayList<Double> oldList, int i, RoomModel roomModel){ if(list.size() <= i){ list.add(roomModel.getSensorModel(i).getLighting()); } if(oldList.size() <= i){ oldList.add(roomModel.getSensorModel(i).getLighting()); } if(list.size() > i){ list.set(i, roomModel.getSensorModel(i).getLighting()); } } private void HumidityCheck(ArrayList<Double> list, ArrayList<Double> oldList, int i, RoomModel roomModel){ if(list.size() <= i){ list.add(roomModel.getSensorModel(i).getHumidity()); } if(oldList.size() <= i){ oldList.add(roomModel.getSensorModel(i).getHumidity()); } if(list.size() > i){ list.set(i,roomModel.getSensorModel(i).getHumidity()); } } private void PressureCheck(ArrayList<Double> list, ArrayList<Double> oldList, int i, RoomModel roomModel){ if(list.size() <= i){ list.add(roomModel.getSensorModel(i).getPressure()); } if(oldList.size() <= i){ oldList.add(roomModel.getSensorModel(i).getPressure()); } if(list.size() > i){ list.set(i,roomModel.getSensorModel(i).getPressure()); } } private void TemperatureCheck(ArrayList<Double> list, ArrayList<Double> oldList, int i, RoomModel roomModel){ if(list.size() <= i){ list.add(roomModel.getSensorModel(i).getTemperature()); } if(oldList.size() <= i){ oldList.add(roomModel.getSensorModel(i).getTemperature()); } if(list.size() > i){ list.set(i,roomModel.getSensorModel(i).getTemperature()); } } private void PositionXCheck(ArrayList<Double> list, ArrayList<Double> oldList, int sensorNumber, RoomModel roomModel){ double linkBudget1 = Math.pow(roomModel.getSensorList().get(sensorNumber).getLinkbudget().get(roomModel.getGatewayList().get(0)).get(),2); double linkBudget2 = Math.pow(roomModel.getSensorList().get(sensorNumber).getLinkbudget().get(roomModel.getGatewayList().get(1)).get(),2); double X = (linkBudget1 - linkBudget2 + Math.pow(canvas.getWidth(),2))/canvas.getWidth(); if(list.size() <= sensorNumber){ list.add(X); } if(oldList.size() <= sensorNumber){ oldList.add(X); } if(list.size() > sensorNumber){ list.set(sensorNumber,X); } } private void PositionYCheck(ArrayList<Double> list, ArrayList<Double> oldList, int sensorNumber, double X, RoomModel roomModel ){ double linkBudget1 = Math.pow(roomModel.getSensorList().get(sensorNumber).getLinkbudget().get(roomModel.getGatewayList().get(0)).get(),2); double linkBudget3 = Math.pow(roomModel.getSensorList().get(sensorNumber).getLinkbudget().get(roomModel.getGatewayList().get(2)).get(),2); double Y = ((linkBudget1 - linkBudget3 + Math.pow(canvas.getWidth()/2,2) + Math.pow(canvas.getHeight()/2, 2))/canvas.getHeight())- (canvas.getWidth()/2)/(canvas.getHeight()/2)*X; if(list.size() <= sensorNumber){ list.add(Y); } if(oldList.size() <= sensorNumber){ oldList.add(Y); } if(list.size() > sensorNumber){ list.set(sensorNumber,Y); } } /** Initialize the difference lists. diffInit(temperature, lighting, humidity, pressure, inactive, i (loop)); */ private void diffInit(ArrayList<Double> temp, ArrayList<Double> light, ArrayList<Double> humi, ArrayList<Double> pres, ArrayList<Double> inact, ArrayList<Double> x, ArrayList<Double> y, int i){ if(temp.size() <= i){ temp.add(0.0); } if(light.size() <= i){ light.add(0.0); } if(humi.size() <= i){ humi.add(0.0); } if(pres.size() <= i){ pres.add(0.0); } if(inact.size() <= i){ inact.add(0.0); } if(x.size() <= i){ x.add(0.0); } if(y.size() <= i){ y.add(0.0); } } private double getPositionX(int i, double t){ double a =i*100 + 150 ; double temp = a*Math.cos(t) +canvas.getWidth() / 2 - circleImage.getWidth() / 2; newPositionX.set(i, temp); return newPositionX.get(i); } private double getPositionY(int i, double t){ double b = 100 + i*100; double temp = b*Math.sin(t) + canvas.getHeight() / 2 - circleImage.getWidth() / 2; newPositionY.set(i, temp); return newPositionY.get(i); } private boolean inactiveS(ArrayList<Double> temp, ArrayList<Double> pres, ArrayList<Double> humi, ArrayList<Double> light, int i){ return (temp.get(i) < 0.001 && temp.get(i) > -0.001 && light.get(i) < 0.001 && light.get(i) > -0.001 && pres.get(i) < 0.001 && pres.get(i) > -0.001 && humi.get(i) < 0.001 && humi.get(i) > -0.001); } private double gateWayPositionX(int CHNumber){ if(CHNumber == 1){ return 0; } if(CHNumber == 2){ return canvas.getWidth()-circleImage.getWidth()/2; } if(CHNumber == 3){ return (canvas.getWidth()-circleImage.getWidth()/2)/2; } return 90; } private double gateWayPositionsY(int CHNumber){ if(CHNumber == 1){ return 0; } if(CHNumber == 2){ return 0; } if(CHNumber == 3){ return canvas.getHeight()-circleImage.getHeight(); } return 90; } public static void main(String[] args) { launch(args); } }
package edu.wustl.catissuecore.bizlogic; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import edu.wustl.catissuecore.domain.CollectionProtocol; import edu.wustl.catissuecore.domain.Site; import edu.wustl.catissuecore.domain.User; import edu.wustl.catissuecore.util.ApiSearchUtil; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.bizlogic.DefaultBizLogic; import edu.wustl.common.cde.CDEManager; import edu.wustl.common.dao.AbstractDAO; import edu.wustl.common.dao.DAO; import edu.wustl.common.dao.DAOFactory; import edu.wustl.common.security.PrivilegeManager; import edu.wustl.common.security.exceptions.SMException; import edu.wustl.common.security.exceptions.UserNotAuthorizedException; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.global.Validator; import edu.wustl.common.util.global.Variables; import edu.wustl.common.util.logger.Logger; /** * SiteHDAO is used to add site type information into the database using Hibernate. * @author aniruddha_phadnis */ public class SiteBizLogic extends DefaultBizLogic { /** * Saves the storageType object in the database. * @param obj The storageType object to be saved. * @param session The session in which the object is saved. * @throws DAOException */ protected void insert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException { Site site = (Site) obj; checkStatus(dao, site.getCoordinator(), "Coordinator"); Set protectionObjects = new HashSet(); setCordinator(dao, site); dao.insert(site.getAddress(), sessionDataBean, true, true); dao.insert(site, sessionDataBean, true, true); protectionObjects.add(site); // SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null, // protectionObjects, null); PrivilegeManager privilegeManager = PrivilegeManager.getInstance(); privilegeManager.insertAuthorizationData(null, protectionObjects, null, site.getObjectId()); } /** * Updates the persistent object in the database. * @param obj The object to be updated. * @param session The session in which the object is saved. * @throws DAOException */ protected void update(DAO dao, Object obj, Object oldObj, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException { Site site = (Site) obj; Site siteOld = (Site) oldObj; if (!site.getCoordinator().getId().equals(siteOld.getCoordinator().getId())) checkStatus(dao, site.getCoordinator(), "Coordinator"); setCordinator(dao, site); dao.update(site.getAddress(), sessionDataBean, true, true, false); dao.update(site, sessionDataBean, true, true, false); //Audit of update. Site oldSite = (Site) oldObj; dao.audit(site.getAddress(), oldSite.getAddress(), sessionDataBean, true); dao.audit(obj, oldObj, sessionDataBean, true); } // This method sets the cordinator for a particular site. private void setCordinator(DAO dao, Site site) throws DAOException { Object object = dao.retrieve(User.class.getName(), site.getCoordinator().getId()); if (object != null) { User user = (User)object; site.setCoordinator(user); } } protected void setPrivilege(DAO dao, String privilegeName, Class objectType, Long[] objectIds, Long userId, String roleId, boolean assignToUser, boolean assignOperation) throws SMException, DAOException { Logger.out.debug(" privilegeName:" + privilegeName + " objectType:" + objectType + " objectIds:" + edu.wustl.common.util.Utility.getArrayString(objectIds) + " userId:" + userId + " roleId:" + roleId + " assignToUser:" + assignToUser); super.setPrivilege(dao, privilegeName, objectType, objectIds, userId, roleId, assignToUser, assignOperation); StorageContainerBizLogic storageContainerBizLogic = (StorageContainerBizLogic) BizLogicFactory .getInstance().getBizLogic(Constants.STORAGE_CONTAINER_FORM_ID); storageContainerBizLogic.assignPrivilegeToRelatedObjectsForSite(dao, privilegeName, objectIds, userId, roleId, assignToUser, assignOperation); // //Giving privilege on related object ids as well // List relatedAddressObjectsIds = super.getRelatedObjects(dao,Site.class,new String[] {"address."+Constants.SYSTEM_IDENTIFIER},new String[] {Constants.SYSTEM_IDENTIFIER}, objectIds); // super.setPrivilege(dao,privilegeName,Address.class,Utility.toLongArray(relatedAddressObjectsIds),userId, roleId, assignToUser, assignOperation); } /** * Overriding the parent class's method to validate the enumerated attribute values */ protected boolean validate(Object obj, DAO dao, String operation) throws DAOException { Site site = (Site) obj; ApiSearchUtil.setSiteDefault(site); //End:- Change for API Search // added by Ashish String message = ""; if (site == null) { message = ApplicationProperties.getValue("app.site"); throw new DAOException(ApplicationProperties.getValue("domain.object.null.err.msg",message)); } Validator validator = new Validator(); if (validator.isEmpty(site.getName())) { message = ApplicationProperties.getValue("site.name"); throw new DAOException(ApplicationProperties.getValue("errors.item.required",message)); } if (validator.isEmpty(site.getType())) { message = ApplicationProperties.getValue("site.type"); throw new DAOException(ApplicationProperties.getValue("errors.item.required",message)); } if (site.getCoordinator()== null || site.getCoordinator().getId() ==null || site.getCoordinator().getId() ==0 || site.getCoordinator().getId().longValue() == -1L) { message = ApplicationProperties.getValue("site.coordinator"); throw new DAOException(ApplicationProperties.getValue("errors.item.required",message)); } if (!validator.isEmpty(site.getEmailAddress()) && !validator.isValidEmailAddress(site.getEmailAddress())) { message = ApplicationProperties.getValue("site.emailAddress"); throw new DAOException(ApplicationProperties.getValue("errors.item.format",message)); } if (site.getAddress() == null || validator.isEmpty(site.getAddress().getStreet())) { message = ApplicationProperties.getValue("site.street"); throw new DAOException(ApplicationProperties.getValue("errors.item.required",message)); } if (site.getAddress() == null || validator.isEmpty(site.getAddress().getCity())) { message = ApplicationProperties.getValue("site.city"); throw new DAOException(ApplicationProperties.getValue("errors.item.required",message)); } if (site.getAddress() == null || validator.isEmpty(site.getAddress().getState())) { message = ApplicationProperties.getValue("site.state"); throw new DAOException(ApplicationProperties.getValue("errors.item.required",message)); } if (site.getAddress() == null || validator.isEmpty(site.getAddress().getCountry())) { message = ApplicationProperties.getValue("site.country"); throw new DAOException(ApplicationProperties.getValue("errors.item.required",message)); } if (site.getAddress() == null || validator.isEmpty(site.getAddress().getZipCode())) { message = ApplicationProperties.getValue("site.zipCode"); throw new DAOException(ApplicationProperties.getValue("errors.item.required",message)); } else { if (!validator.isValidZipCode(site.getAddress().getZipCode())) { message = ApplicationProperties.getValue("site.zipCode"); throw new DAOException(ApplicationProperties.getValue("errors.item.format",message)); } } // bug #4349 if (!validator.isEmpty(site.getAddress().getPhoneNumber())) { if (!validator.isValidPhoneNumber(site.getAddress().getPhoneNumber())) { message = ApplicationProperties.getValue("site.phoneNumber"); throw new DAOException(ApplicationProperties.getValue("error.phonenumber.format",message)); } } if (!validator.isEmpty(site.getAddress().getFaxNumber())) { if (!validator.isValidPhoneNumber(site.getAddress().getFaxNumber())) { message = ApplicationProperties.getValue("site.faxNumber"); throw new DAOException(ApplicationProperties.getValue("error.faxnumber.format",message)); } } //bug #4349 ends if (operation.equals(Constants.EDIT) && !validator.isValidOption(site.getActivityStatus())) { message = ApplicationProperties.getValue("site.activityStatus"); throw new DAOException(ApplicationProperties.getValue("errors.item.required",message)); } // END List siteList = CDEManager.getCDEManager().getPermissibleValueList( Constants.CDE_NAME_SITE_TYPE, null); if (!Validator.isEnumeratedValue(siteList, site.getType())) { throw new DAOException(ApplicationProperties.getValue("type.errMsg")); } if (!Validator.isEnumeratedValue(CDEManager.getCDEManager().getPermissibleValueList( Constants.CDE_NAME_STATE_LIST, null), site.getAddress().getState())) { throw new DAOException(ApplicationProperties.getValue("state.errMsg")); } if (!Validator.isEnumeratedValue(CDEManager.getCDEManager().getPermissibleValueList( Constants.CDE_NAME_COUNTRY_LIST, null), site.getAddress().getCountry())) { throw new DAOException(ApplicationProperties.getValue("country.errMsg")); } if (operation.equals(Constants.ADD)) { if (!Constants.ACTIVITY_STATUS_ACTIVE.equals(site.getActivityStatus())) { throw new DAOException(ApplicationProperties .getValue("activityStatus.active.errMsg")); } } else { if (!Validator.isEnumeratedValue(Constants.SITE_ACTIVITY_STATUS_VALUES, site .getActivityStatus())) { throw new DAOException(ApplicationProperties.getValue("activityStatus.errMsg")); } } return true; } /** * Called from DefaultBizLogic to get ObjectId for authorization check * (non-Javadoc) * @see edu.wustl.common.bizlogic.DefaultBizLogic#getObjectId(edu.wustl.common.dao.AbstractDAO, java.lang.Object) */ public String getObjectId(AbstractDAO dao, Object domainObject) { return Constants.ADMIN_PROTECTION_ELEMENT; } protected String getPrivilegeName(Object domainObject) { String privilegeName = Variables.privilegeDetailsMap.get(Constants.ADD_EDIT_SITE); return privilegeName; } public Collection<CollectionProtocol> getRelatedCPs(Long siteId) { AbstractDAO dao = DAOFactory.getInstance().getDAO(Constants.HIBERNATE_DAO); Site site = null; try { dao.openSession(null); site = (Site) dao.retrieve(Site.class.getName(), siteId); } catch (DAOException e) { Logger.out.debug(e.getMessage(), e); } if(site == null) { return null; } return site.getCollectionProtocolCollection(); } }
package edu.wustl.catissuecore.bizlogic; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Vector; import edu.wustl.catissuecore.action.DomainObjectListAction; import edu.wustl.catissuecore.action.ForgotPasswordSearchAction; import edu.wustl.catissuecore.dao.DAO; import edu.wustl.catissuecore.domain.AbstractDomainObject; import edu.wustl.catissuecore.domain.CancerResearchGroup; import edu.wustl.catissuecore.domain.Department; import edu.wustl.catissuecore.domain.Institution; import edu.wustl.catissuecore.domain.User; import edu.wustl.catissuecore.util.EmailHandler; import edu.wustl.catissuecore.util.Roles; import edu.wustl.catissuecore.util.global.ApplicationProperties; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.beans.SecurityDataBean; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.security.SecurityManager; import edu.wustl.common.security.exceptions.SMException; import edu.wustl.common.security.exceptions.UserNotAuthorizedException; import edu.wustl.common.util.PasswordManager; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.logger.Logger; import gov.nih.nci.security.authorization.domainobjects.Role; /** * UserBizLogic is used to add user information into the database using Hibernate. * @author kapil_kaveeshwar */ public class UserBizLogic extends DefaultBizLogic { /** * Saves the user object in the database. * @param obj The user object to be saved. * @param session The session in which the object is saved. * @throws DAOException */ protected void insert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException { User user = (User) obj; try { List list = dao.retrieve(Department.class.getName(), Constants.SYSTEM_IDENTIFIER, user.getDepartment() .getSystemIdentifier()); Department department = null; if (list.size() != 0) { department = (Department) list.get(0); } list = dao.retrieve(Institution.class.getName(), Constants.SYSTEM_IDENTIFIER, user.getInstitution() .getSystemIdentifier()); Institution institution = null; if (list.size() != 0) { institution = (Institution) list.get(0); } list = dao.retrieve(CancerResearchGroup.class.getName(), Constants.SYSTEM_IDENTIFIER, user.getCancerResearchGroup() .getSystemIdentifier()); CancerResearchGroup cancerResearchGroup = null; if (list.size() != 0) { cancerResearchGroup = (CancerResearchGroup) list.get(0); } user.setDepartment(department); user.setInstitution(institution); user.setCancerResearchGroup(cancerResearchGroup); // If the page is of signup user don't create the csm user. if (user.getPageOf().equals(Constants.PAGEOF_SIGNUP) == false) { gov.nih.nci.security.authorization.domainobjects.User csmUser = new gov.nih.nci.security.authorization.domainobjects.User(); csmUser.setLoginName(user.getLoginName()); csmUser.setLastName(user.getLastName()); csmUser.setFirstName(user.getFirstName()); csmUser.setEmailId(user.getEmailAddress()); csmUser.setStartDate(user.getStartDate()); csmUser.setPassword(PasswordManager.encode(PasswordManager.generatePassword())); SecurityManager.getInstance(UserBizLogic.class).createUser(csmUser); if (user.getRoleId() != null) SecurityManager.getInstance(UserBizLogic.class) .assignRoleToUser(csmUser.getLoginName(), user.getRoleId()); user.setCsmUserId(csmUser.getUserId()); user.setPassword(csmUser.getPassword()); } // Create address and the user in catissue tables. dao.insert(user.getAddress(), sessionDataBean, true, false); dao.insert(user, sessionDataBean, true, false); Set protectionObjects=new HashSet(); protectionObjects.add(user); try { SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null,protectionObjects,null); } catch (SMException smExp) { Logger.out.error(smExp.getMessage(),smExp); } // Send the user registration email to user and the administrator. if (Constants.PAGEOF_SIGNUP.equals(user.getPageOf())) { EmailHandler emailHandler = new EmailHandler(); emailHandler.sendUserSignUpEmail(user); } else// Send the user creation email to user and the administrator. { EmailHandler emailHandler = new EmailHandler(); emailHandler.sendApprovalEmail(user); } } catch (SMException smex) { Logger.out.debug(smex.getMessage(), smex); throw new DAOException(smex.getCause().getMessage(),smex); } } /** * This method returns collection of UserGroupRoleProtectionGroup objects that speciefies the * user group protection group linkage through a role. It also specifies the groups the protection * elements returned by this class should be added to. * @return */ public Vector getAuthorizationData(AbstractDomainObject obj) { Logger.out.debug(" Vector authorizationData = new Vector(); Set group = new HashSet(); SecurityDataBean userGroupRoleProtectionGroupBean; String protectionGroupName; gov.nih.nci.security.authorization.domainobjects.User user ; Collection coordinators; User aUser = (User)obj; String userId = String.valueOf(aUser.getCsmUserId()); try { user = new gov.nih.nci.security.authorization.domainobjects.User(); user = SecurityManager.getInstance(this.getClass()).getUserById(userId); Logger.out.debug(" User: "+user.getLoginName()); group.add(user); } catch (SMException e) { Logger.out.error("Exception in Authorization: "+e.getMessage(),e); } // Protection group of PI protectionGroupName = Constants.getUserPGName(aUser.getSystemIdentifier()); userGroupRoleProtectionGroupBean = new SecurityDataBean(); userGroupRoleProtectionGroupBean.setUser(userId); userGroupRoleProtectionGroupBean.setRoleName(Roles.UPDATE_ONLY); userGroupRoleProtectionGroupBean.setGroupName(Constants.getUserGroupName(aUser.getSystemIdentifier())); userGroupRoleProtectionGroupBean.setProtectionGroupName(protectionGroupName); userGroupRoleProtectionGroupBean.setGroup(group); authorizationData.add(userGroupRoleProtectionGroupBean); Logger.out.debug(authorizationData.toString()); return authorizationData; } /** * Updates the persistent object in the database. * @param obj The object to be updated. * @param session The session in which the object is saved. * @throws DAOException */ protected void update(DAO dao, Object obj, Object oldObj, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException { User user = (User) obj; try { // Get the csm userId if present. String csmUserId = null; if (user.getCsmUserId() != null) { csmUserId = user.getCsmUserId().toString(); } gov.nih.nci.security.authorization.domainobjects.User csmUser = SecurityManager .getInstance(DomainObjectListAction.class).getUserById(csmUserId); // If the page is of change password, // update the password of the user in csm and catissue tables. if (user.getPageOf().equals(Constants.PAGEOF_CHANGE_PASSWORD)) { if (!user.getOldPassword().equals(PasswordManager.decode(csmUser.getPassword()))) { throw new DAOException(ApplicationProperties.getValue("errors.oldPassword.wrong")); } csmUser.setPassword(PasswordManager.encode(user.getPassword())); user.setPassword(csmUser.getPassword()); } else { csmUser.setLoginName(user.getLoginName()); csmUser.setLastName(user.getLastName()); csmUser.setFirstName(user.getFirstName()); csmUser.setEmailId(user.getEmailAddress()); // Assign Role only if the page is of Administrative user edit. if ((Constants.PAGEOF_USER_PROFILE.equals(user.getPageOf()) == false) && (Constants.PAGEOF_CHANGE_PASSWORD.equals(user.getPageOf()) == false)) { Logger.out.debug("csmUser..........................."+csmUser); Logger.out.debug("user................................."+user); SecurityManager.getInstance(UserBizLogic.class).assignRoleToUser( csmUser.getLoginName(), user.getRoleId()); } dao.update(user.getAddress(), sessionDataBean, true, false, false); //Audit of user address. User oldUser = (User) oldObj; dao.audit(user.getAddress(), oldUser.getAddress(),sessionDataBean,true); } // Modify the csm user. SecurityManager.getInstance(UserBizLogic.class).modifyUser(csmUser); dao.update(user, sessionDataBean, true, true, true); //Audit of user. dao.audit(obj, oldObj,sessionDataBean,true); if (Constants.ACTIVITY_STATUS_ACTIVE.equals(user.getActivityStatus())) { Set protectionObjects=new HashSet(); protectionObjects.add(user); try { SecurityManager.getInstance(this.getClass()).insertAuthorizationData(getAuthorizationData(user),protectionObjects,null); } catch (SMException e) { Logger.out.error("Exception in Authorization: "+e.getMessage(),e); } } } catch (SMException smExp) { throw new DAOException(smExp.getMessage(), smExp); } } /** * Returns the list of NameValueBeans with name as "LastName,Firstname" * and value as systemtIdentifier, of all users who are not disabled. * @return the list of NameValueBeans with name as "LastName,Firstname" * and value as systemtIdentifier, of all users who are not disabled. * @throws DAOException */ public Vector getUsers() throws DAOException { String sourceObjectName = User.class.getName(); String[] selectColumnName = null; String[] whereColumnName = {"activityStatus"}; String[] whereColumnCondition = {"!="}; Object[] whereColumnValue = {Constants.ACTIVITY_STATUS_DISABLED}; String joinCondition = Constants.AND_JOIN_CONDITION; //Retrieve the users whose activity status is not disabled. List users = retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition); Vector nameValuePairs = new Vector(); nameValuePairs.add(new NameValueBean(Constants.SELECT_OPTION, "-1")); // If the list of users retrieved is not empty. if (users.isEmpty() == false) { // Creating name value beans. for (int i = 0; i < users.size(); i++) { User user = (User) users.get(i); NameValueBean nameValueBean = new NameValueBean(); nameValueBean.setName(user.getLastName() + ", " + user.getFirstName()); nameValueBean.setValue(String.valueOf(user .getSystemIdentifier())); Logger.out.debug(nameValueBean.toString()); nameValuePairs.add(nameValueBean); } } return nameValuePairs; } /** * Returns a list of users according to the column name and value. * @param colName column name on the basis of which the user list is to be retrieved. * @param colValue Value for the column name. * @throws DAOException */ public List retrieve(String className, String colName, Object colValue) throws DAOException { List userList = null; try { // Get the caTISSUE user. userList = super.retrieve(className, colName, colValue); edu.wustl.catissuecore.domain.User appUser = null; if (!userList.isEmpty()) { appUser = (edu.wustl.catissuecore.domain.User) userList.get(0); if (appUser.getCsmUserId() != null) { //Get the role of the user. Role role = SecurityManager.getInstance(UserBizLogic.class) .getUserRole(appUser.getCsmUserId().longValue()); if (role != null) { appUser.setRoleId(role.getId().toString()); } } } } catch (SMException smExp) { Logger.out.debug(smExp.getMessage(), smExp); throw new DAOException(smExp.getMessage(), smExp); } return userList; } /** * Retrieves and sends the login details email to the user whose email address is passed * else returns the error key in case of an error. * @param emailAddress the email address of the user whose password is to be sent. * @return the error key in case of an error. * @throws DAOException */ public String sendForgotPassword(String emailAddress) throws DAOException { String statusMessageKey = null; try { List list = null; gov.nih.nci.security.authorization.domainobjects.User csmUser = null; //Retrieve the user using email address from csm user table. List csmList = SecurityManager.getInstance( ForgotPasswordSearchAction.class).getUsersByEmail( emailAddress); if (!csmList.isEmpty()) { csmUser = (gov.nih.nci.security.authorization.domainobjects.User) csmList.get(0); //Retrieve the user using csm user id from catissue user table. list = retrieve(User.class.getName(), "csmUserId", String.valueOf(csmUser.getUserId())); } //If the user is present. if ((csmUser != null) && (!list.isEmpty())) { User user = (User) list.get(0); //If the user is Active send the password to the user to //the email address provided while registration. if (user.getActivityStatus().equals( Constants.ACTIVITY_STATUS_ACTIVE)) { EmailHandler emailHandler = new EmailHandler(); //Get the role of the user. String roleOfUser = SecurityManager.getInstance(ApproveUserBizLogic.class) .getUserRole(csmUser.getUserId().longValue()).getName(); //Send the login details email to the user. boolean emailStatus = emailHandler.sendLoginDetailsEmail(user, null); if (emailStatus) { statusMessageKey = "password.send.success"; } else { statusMessageKey = "password.send.failure"; } } else { //Error key if the user is not active. statusMessageKey = "errors.forgotpassword.user.notApproved"; } } else { //Error key if the user is not present. statusMessageKey = "errors.forgotpassword.user.unknown"; } } catch (SMException smExp) { throw new DAOException(smExp.getMessage(),smExp); } return statusMessageKey; } }
package edu.wustl.catissuecore.util.global; import edu.wustl.catissuecore.domain.CellSpecimen; import edu.wustl.catissuecore.domain.FluidSpecimen; import edu.wustl.catissuecore.domain.MolecularSpecimen; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.SpecimenArray; import edu.wustl.catissuecore.domain.TissueSpecimen; import edu.wustl.catissuecore.domain.pathology.DeidentifiedSurgicalPathologyReport; import edu.wustl.catissuecore.domain.pathology.IdentifiedSurgicalPathologyReport; import edu.wustl.catissuecore.domain.pathology.SurgicalPathologyReport; /** * This class stores the constants used in the operations in the application. * @author gautam_shetty */ public class Constants extends edu.wustl.common.util.global.Constants { //Constants added for Catissuecore V1.2 public static final String PAGE_OF_ADMINISTRATOR = "pageOfAdministrator"; public static final String PAGE_OF_SUPERVISOR = "pageOfSupervisor"; public static final String PAGE_OF_TECHNICIAN = "pageOfTechnician"; public static final String PAGE_OF_SCIENTIST = "pageOfScientist"; //Constants added for Validation public static final String DEFAULT_TISSUE_SITE ="defaultTissueSite"; public static final String DEFAULT_CLINICAL_STATUS ="defaultClinicalStatus"; public static final String DEFAULT_GENDER = "defaultGender"; public static final String DEFAULT_GENOTYPE = "defaultGenotype"; public static final String DEFAULT_SPECIMEN = "defaultSpecimen"; public static final String DEFAULT_TISSUE_SIDE = "defaultTissueSide"; public static final String DEFAULT_PATHOLOGICAL_STATUS = "defaultPathologicalStatus"; public static final String DEFAULT_RECEIVED_QUALITY= "defaultReceivedQuality"; public static final String DEFAULT_FIXATION_TYPE = "defaultFixationType"; public static final String DEFAULT_COLLECTION_PROCEDURE="defaultCollectionProcedure"; public static final String DEFAULT_CONTAINER= "defaultContainer"; public static final String DEFAULT_METHOD= "defaultMethod"; public static final String DEFAULT_EMBEDDING_MEDIUM="defaultEmbeddingMedium"; public static final String DEFAULT_BIOHAZARD="defaultBiohazard"; public static final String DEFAULT_SITE_TYPE ="defaultSiteType"; public static final String DEFAULT_SPECIMEN_TYPE ="defaultSpecimenType"; public static final String DEFAULT_ETHNICITY ="defaultEthnicity"; public static final String DEFAULT_RACE ="defaultRace"; public static final String DEFAULT_CLINICAL_DIAGNOSIS = "defaultClinicalDiagnosis"; public static final String DEFAULT_STATES ="defaultStates"; public static final String DEFAULT_COUNTRY ="defaultCountry"; public static final String DEFAULT_HISTOLOGICAL_QUALITY="defaultHistologicalQuality"; public static final String DEFAULT_VITAL_STATUS ="defaultVitalStatus"; //Consent tracking public static final String SHOW_CONSENTS="showConsents"; public static final String SPECIMEN_CONSENTS="specimenConsents"; public static final String YES="yes"; public static final String CP_ID="cpID"; public static final String BARCODE_LABLE="barcodelabel"; public static final String DISTRIBUTION_ON="labelBarcode"; public static final String POPUP="popup"; public static final String ERROR="error"; public static final String ERROR_SHOWCONSENTS="errorShowConsent"; public static final String COMPLETE="Complete"; public static final String VIEW_CONSENTS="View"; public static final String APPLY="Apply"; public static final String APPLY_ALL="ApplyAll"; public static final String APPLY_NONE="ApplyNone"; public static final String PREDEFINED_CADSR_CONSENTS="predefinedConsentsList"; public static final String DISABLED="disabled"; public static final String VIEWAll="ViewAll"; public static final String BARCODE_DISTRIBUTION="1"; public static final String LABLE_DISTRIBUTION="2"; public static final String CONSENT_WAIVED="Consent Waived"; public static final String NO_CONSENTS="No Consents"; public static final String NO_CONSENTS_DEFINED="None Defined"; public static final String INVALID="Invalid"; public static final String VALID="valid"; public static final String FALSE="false"; public static final String TRUE="true"; public static final String NULL="null"; public static final String CONSENT_TABLE="tableId4"; public static final String DISABLE="disable"; public static final String SCG_ID="-1"; public static final String SELECTED_TAB="tab"; public static final String TAB_SELECTED="tabSelected"; public static final String NEWSPECIMEN_FORM="newSpecimenForm"; public static final String CONSENT_TABLE_SHOWHIDE="tableStatus"; public static final String SPECIMEN_RESPONSELIST="specimenResponseList"; public static final String PROTOCOL_EVENT_ID="protocolEventId"; public static final String SCG_DROPDOWN="value"; public static final String HASHED_OUT=" public static final String HASHED_NODE_ID = "-1"; public static final String VERIFIED="Verified"; public static final String STATUS="status"; public static final String NOT_APPLICABLE="Not Applicable"; public static final String WITHDRAW_ALL="withrawall"; public static final String RESPONSE="response"; public static final String WITHDRAW="withdraw"; public static final String VIRTUALLY_LOCATED="Virtually Located"; public static final String LABLE="Lable"; public static final String STORAGE_CONTAINER_LOCATION="Storage Container Location"; public static final String CLASS_NAME="Class Name"; public static final String SPECIMEN_LIST="specimenDetails"; public static final String COLUMNLIST="columnList"; public static final String CONSENT_RESPONSE_KEY="CR_"; public static final String CONSENT_RESPONSE="ConsentResponse"; public static final String [][] defaultValueKeys= { {Constants.DEFAULT_TISSUE_SITE, edu.wustl.common.util.global.Constants.CDE_NAME_TISSUE_SITE}, {Constants.DEFAULT_CLINICAL_STATUS, Constants.CDE_NAME_CLINICAL_STATUS}, {Constants.DEFAULT_GENDER, Constants.CDE_NAME_GENDER}, {Constants.DEFAULT_GENOTYPE, Constants.CDE_NAME_GENOTYPE}, {Constants.DEFAULT_SPECIMEN, Constants.CDE_NAME_SPECIMEN_CLASS}, {Constants.DEFAULT_TISSUE_SIDE, Constants.CDE_NAME_TISSUE_SIDE}, {Constants.DEFAULT_PATHOLOGICAL_STATUS, Constants.CDE_NAME_PATHOLOGICAL_STATUS}, {Constants.DEFAULT_RECEIVED_QUALITY, Constants.CDE_NAME_RECEIVED_QUALITY}, {Constants.DEFAULT_FIXATION_TYPE, Constants.CDE_NAME_FIXATION_TYPE}, {Constants.DEFAULT_COLLECTION_PROCEDURE, Constants.CDE_NAME_COLLECTION_PROCEDURE}, {Constants.DEFAULT_CONTAINER, Constants.CDE_NAME_CONTAINER}, {Constants.DEFAULT_METHOD, Constants.CDE_NAME_METHOD}, {Constants.DEFAULT_EMBEDDING_MEDIUM,Constants.CDE_NAME_EMBEDDING_MEDIUM}, {Constants.DEFAULT_BIOHAZARD, Constants.CDE_NAME_BIOHAZARD}, {Constants.DEFAULT_SITE_TYPE, Constants.CDE_NAME_SITE_TYPE}, {Constants.DEFAULT_SPECIMEN_TYPE, Constants.CDE_NAME_SPECIMEN_TYPE}, {Constants.DEFAULT_ETHNICITY, Constants.CDE_NAME_ETHNICITY}, {Constants.DEFAULT_RACE, Constants.CDE_NAME_RACE}, {Constants.DEFAULT_CLINICAL_DIAGNOSIS, Constants.CDE_NAME_CLINICAL_DIAGNOSIS}, {Constants.DEFAULT_STATES, Constants.CDE_NAME_STATE_LIST}, {Constants.DEFAULT_COUNTRY, Constants.CDE_NAME_COUNTRY_LIST}, {Constants.DEFAULT_HISTOLOGICAL_QUALITY, Constants.CDE_NAME_HISTOLOGICAL_QUALITY}, {Constants.DEFAULT_VITAL_STATUS, Constants.CDE_VITAL_STATUS} }; //Constants added for Catissuecore V1.2 public static final String MYSQL_NUM_TO_STR_FUNCTION_NAME_FOR_LABEL_GENRATION= "cast(label as signed)"; public static final String ORACLE_NUM_TO_STR_FUNCTION_NAME_FOR_LABEL_GENRATION = "catissue_label_to_num(label)"; // Query Module Interface UI constants public static final String ViewSearchResultsAction = "ViewSearchResultsAction.do"; public static final String categorySearchForm = "categorySearchForm"; public static final String SearchCategory = "SearchCategory.do"; public static final String DefineSearchResultsViewAction = "DefineSearchResultsView.do"; public static final String DefineSearchResultsViewJSPAction = "ViewSearchResultsJSPAction.do"; public static final String QUERY_DAG_VIEW_APPLET = "edu/wustl/catissuecore/applet/ui/querysuite/DiagrammaticViewApplet.class"; public static final String QUERY_DAG_VIEW_APPLET_NAME = "Dag View Applet"; public static final String APP_DYNAMIC_UI_XML = "xmlfile.dynamicUI"; public static final String QUERY_CONDITION_DELIMITER = "@#condition#@"; public static final String QUERY_OPERATOR_DELIMITER = "!*=*!"; public static final String QUERY_VALUES_DELIMITER = "&"; //public static final String SEARCHED_ENTITIES_MAP = "searchedEntitiesMap"; public static final String SUCCESS = "success"; public static final String LIST_OF_ENTITIES_IN_QUERY = "ListOfEntitiesInQuery"; public static final String DYNAMIC_UI_XML = "dynamicUI.xml"; public static final String TREE_DATA = "treeData"; public static final String ZERO_ID = "0"; public static final String TEMP_OUPUT_TREE_TABLE_NAME = "TEMP_OUTPUTTREE"; public static final String CREATE_TABLE = "Create table "; public static final String AS = "as"; public static final String UNDERSCORE = "_"; public static final String ID_NODES_MAP = "idNodesMap"; public static final String ID_COLUMNS_MAP = "idColumnsMap"; public static final String COLUMN_NAME = "Column"; public static final String[] ATTRIBUTE_NAMES_FOR_TREENODE_LABEL = { "firstName", "lastName", "title", "name", "label", "shorttitle" }; public static final String MISSING_TWO_VALUES = "missingTwoValues"; public static final String DATE = "date"; public static final String DEFINE_RESULTS_VIEW = "DefineResultsView"; public static final String CURRENT_PAGE = "currentPage"; public static final String ADD_LIMITS = "AddLimits"; public static final String LABEL_TREE_NODE = "Label"; public static final String ENTITY_NAME = "Entity Name"; public static final String COUNT = "Count"; public static final String TREE_NODE_FONT = "<font color='#FF9BFF' face='Verdana'><i>"; public static final String TREE_NODE_FONT_CLOSE = "</i></font>"; public static final String NULL_ID = "NULL"; public static final String NODE_SEPARATOR = "::"; public static final String EXPRESSION_ID_SEPARATOR = ":"; public static final String UNIQUE_ID_SEPARATOR = "UQ"; public static final String DEFINE_SEARCH_RULES = "Define Limits For"; public static final String DATE_FORMAT = "MM-dd-yyyy"; public static final String OUTPUT_TREE_MAP = "outputTreeMap"; public static final String CHECK_ALL_PAGES = "checkAllPages"; public static final String CHECK_ALL_ACROSS_ALL_PAGES = "isCheckAllAcrossAllChecked"; public static final String CLASSES_PRESENT_IN_QUERY = "Objects Present In Query"; public static final String DEFINE_QUERY_RESULTS_VIEW_ACTION = "DefineQueryResultsView.do"; public static final String CONFIGURE_GRID_VIEW_ACTION = "ConfigureGridView.do"; public static String ATTRIBUTE_MAP = "attributeMap"; public static final String CLASS = "class"; public static final String ATTRIBUTE = "attribute"; public static final String SELECT_DISTINCT = "select distinct "; public static final String FROM = " from "; public static final String WHERE = " where "; public static final String SELECTED_COLUMN_META_DATA = "selectedColumnMetaData"; public static final String CURRENT_SELECTED_OBJECT = "currentSelectedObject"; public static final String SELECTED_COLUMN_NAME_VALUE_BEAN_LIST = "selectedColumnNameValueBeanList"; public static final String OPERATION = "operation"; public static final String FINISH = "finish"; public static final String BACK = "back"; public static final String RESTORE = "restore"; public static final String VIEW_ALL_RECORDS = "viewAllRecords"; public static final String VIEW_LIMITED_RECORDS = "viewLimitedRecords"; public static final String SAVE_QUERY_ACTION = "SaveQueryAction.do"; public static final String RETRIEVE_QUERY_ACTION = "RetrieveQueryAction.do"; public static final String FETCH_AND_EXECUTE_QUERY_ACTION = "ExecuteQueryAction.do"; public static final String TREE_NODE_LIMIT_EXCEEDED_RECORDS = "treeNodeLimitExceededRecords"; public static final String MAXIMUM_TREE_NODE_LIMIT = "resultView.maximumTreeNodeLimit"; public static final String DEFINED_VIEW_ATTRIBUTES = "definedViewAttributes"; public static final String IS_SAVED_QUERY = "isSavedQuery"; public static final String RANDOM_NUMBER = "randomNumber"; public static final String MULTIUSER ="multiuser"; public static final String SAVE_TREE_NODE_LIST = "rootOutputTreeNodeList"; public static final String SAVE_GENERATED_SQL = "sql"; public static final String POPUP_MESSAGE = "popupMessage"; public static final String BUTTON_CLICKED = "buttonClicked"; /** * Name: Abhishek Mehta * Reviewer Name : Deepti * Bug ID: 5661 * Patch ID: 5661_1 * See also: 1-4 * Description : Constants added for Query Module */ public static final String IS_QUERY_SAVED = "isQuerySaved"; public static final String CONDITIONLIST = "conditionList"; public static final String QUERY_SAVED = "querySaved"; public static final String DISPLAY_NAME_FOR_CONDITION = "_displayName"; public static final String SHOW_ALL_LINK = "showAllLink"; // Frame names in Query Module Results page. public static final String GRID_DATA_VIEW_FRAME = "gridFrame"; public static final String TREE_VIEW_FRAME = "treeViewFrame"; public static final String QUERY_TREE_VIEW_ACTION = "QueryTreeView.do"; public static final String QUERY_GRID_VIEW_ACTION = "QueryGridView.do"; public static final String NO_OF_TREES = "noOfTrees"; public static final String PAGEOF_QUERY_MODULE = "pageOfQueryModule"; public static final String TREE_ROOTS = "treeRoots"; // Frame names in Query Module Results page.--ends here public static final String MAX_IDENTIFIER = "maxIdentifier"; public static final String AND_JOIN_CONDITION = "AND"; public static final String OR_JOIN_CONDITION = "OR"; //Sri: Changed the format for displaying in Specimen Event list (#463) public static final String TIMESTAMP_PATTERN = "MM-dd-yyyy HH:mm"; public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd"; public static final String QUERY_ID = "queryId"; // Mandar: Used for Date Validations in Validator Class public static final String DATE_SEPARATOR = "-"; public static final String DATE_SEPARATOR_DOT = "."; public static final String MIN_YEAR = "1900"; public static final String MAX_YEAR = "9999"; public static final String VIEW = "view"; public static final String DELETE = "delete"; public static final String EXPORT = "export"; public static final String SHOPPING_CART_ADD = "shoppingCartAdd"; public static final String SHOPPING_CART_DELETE = "shoppingCartDelete"; public static final String SHOPPING_CART_EXPORT = "shoppingCartExport"; public static final String NEWUSERFORM = "newUserForm"; public static final String REDIRECT_TO_SPECIMEN = "specimenRedirect"; public static final String CALLED_FROM = "calledFrom"; public static final String ACCESS = "access"; //Constants required for Forgot Password public static final String FORGOT_PASSWORD = "forgotpassword"; public static final String LOGINNAME = "loginName"; public static final String LASTNAME = "lastName"; public static final String FIRSTNAME = "firstName"; public static final String INSTITUTION = "institution"; public static final String EMAIL = "email"; public static final String DEPARTMENT = "department"; public static final String ADDRESS = "address"; public static final String CITY = "city"; public static final String STATE = "state"; public static final String COUNTRY = "country"; public static final String NEXT_CONTAINER_NO = "startNumber"; public static final String CSM_USER_ID = "csmUserId"; public static final String INSTITUTIONLIST = "institutionList"; public static final String DEPARTMENTLIST = "departmentList"; public static final String STATELIST = "stateList"; public static final String COUNTRYLIST = "countryList"; public static final String ROLELIST = "roleList"; public static final String ROLEIDLIST = "roleIdList"; public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList"; public static final String GENDER_LIST = "genderList"; public static final String GENOTYPE_LIST = "genotypeList"; public static final String ETHNICITY_LIST = "ethnicityList"; public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList"; public static final String RACELIST = "raceList"; public static final String VITAL_STATUS_LIST = "vitalStatusList"; public static final String PARTICIPANT_LIST = "participantList"; public static final String PARTICIPANT_ID_LIST = "participantIdList"; public static final String PROTOCOL_LIST = "protocolList"; public static final String TIMEHOURLIST = "timeHourList"; public static final String TIMEMINUTESLIST = "timeMinutesList"; public static final String TIMEAMPMLIST = "timeAMPMList"; public static final String RECEIVEDBYLIST = "receivedByList"; public static final String COLLECTEDBYLIST = "collectedByList"; public static final String COLLECTIONSITELIST = "collectionSiteList"; public static final String RECEIVEDSITELIST = "receivedSiteList"; public static final String RECEIVEDMODELIST = "receivedModeList"; public static final String ACTIVITYSTATUSLIST = "activityStatusList"; public static final String COLLECTIONSTATUSLIST = "collectionStatusList"; public static final String USERLIST = "userList"; public static final String SITETYPELIST = "siteTypeList"; public static final String STORAGETYPELIST="storageTypeList"; public static final String STORAGECONTAINERLIST="storageContainerList"; public static final String SITELIST="siteList"; // public static final String SITEIDLIST="siteIdList"; public static final String USERIDLIST = "userIdList"; public static final String STORAGETYPEIDLIST="storageTypeIdList"; public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList"; public static final String PARTICIPANT_IDENTIFIER_IN_CPR = "participant"; public static final String APPROVE_USER_STATUS_LIST = "statusList"; public static final String EVENT_PARAMETERS_LIST = "eventParametersList"; //New Specimen lists. public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList"; public static final String SPECIMEN_TYPE_LIST = "specimenTypeList"; public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList"; public static final String TISSUE_SITE_LIST = "tissueSiteList"; public static final String TISSUE_SIDE_LIST = "tissueSideList"; public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList"; public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList"; public static final String BIOHAZARD_NAME_LIST = "biohazardNameList"; public static final String BIOHAZARD_ID_LIST = "biohazardIdList"; public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList"; public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList"; public static final String RECEIVED_QUALITY_LIST = "receivedQualityList"; public static final String SPECIMEN_COLL_GP_NAME = "specimenCollectionGroupName"; //SpecimenCollecionGroup lists. public static final String PROTOCOL_TITLE_LIST = "protocolTitleList"; public static final String PARTICIPANT_NAME_LIST = "participantNameList"; public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList"; //public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList"; public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList"; //public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList"; public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray"; //public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray"; public static final String SPECIMEN_COLLECTION_GROUP_ID = "specimenCollectionGroupId"; public static final String REQ_PATH = "redirectTo"; public static final String CLINICAL_STATUS_LIST = "cinicalStatusList"; public static final String SPECIMEN_CLASS_LIST = "specimenClassList"; public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList"; public static final String SPECIMEN_TYPE_MAP = "specimenTypeMap"; //Simple Query Interface Lists public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList"; public static final String SIMPLE_QUERY_INTERFACE_TITLE = "simpleQueryInterfaceTitle"; public static final String MAP_OF_STORAGE_CONTAINERS = "storageContainerMap"; public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject"; public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus"; public static final String START_NUMBER = "startNumber"; public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerIds"; public static final int STORAGE_CONTAINER_FIRST_ROW = 1; public static final int STORAGE_CONTAINER_FIRST_COLUMN = 1; public static final String MAP_COLLECTION_PROTOCOL_LIST = "collectionProtocolList"; public static final String MAP_SPECIMEN_CLASS_LIST = "specimenClassList"; //event parameters lists public static final String METHOD_LIST = "methodList"; public static final String HOUR_LIST = "hourList"; public static final String MINUTES_LIST = "minutesList"; public static final String EMBEDDING_MEDIUM_LIST = "embeddingMediumList"; public static final String PROCEDURE_LIST = "procedureList"; public static final String PROCEDUREIDLIST = "procedureIdList"; public static final String CONTAINER_LIST = "containerList"; public static final String CONTAINERIDLIST = "containerIdList"; public static final String FROMCONTAINERLIST="fromContainerList"; public static final String TOCONTAINERLIST="toContainerList"; public static final String FIXATION_LIST = "fixationList"; public static final String FROM_SITE_LIST="fromsiteList"; public static final String TO_SITE_LIST="tositeList"; public static final String ITEMLIST="itemList"; public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList"; public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList"; public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList"; public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList"; public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList"; public static final String STORAGE_STATUS_LIST="storageStatusList"; public static final String CLINICAL_DIAGNOSIS_LIST = "clinicalDiagnosisList"; public static final String HISTOLOGICAL_QUALITY_LIST="histologicalQualityList"; //For Specimen Event Parameters. public static final String SPECIMEN_ID = "specimenId"; public static final String SPECIMEN_ARRAY_ID = "specimenArrayIds"; public static final String PATHALOGICAL_CASE_ID = "pathalogicalCaseIds"; public static final String DEIDENTIFIED_PATHALOGICAL_CASE_ID = "deidentifiedPathalogicalCaseIds"; public static final String SURGICAL_PATHALOGY_CASE_ID ="surgicalPathalogicalCaseIds"; public static final String FROM_POSITION_DATA = "fromPositionData"; public static final String POS_ONE ="posOne"; public static final String POS_TWO ="posTwo"; public static final String STORAGE_CONTAINER_ID ="storContId"; public static final String IS_RNA = "isRNA"; public static final String RNA = "RNA"; // New Participant Event Parameters public static final String PARTICIPANT_ID="participantId"; //Constants required in User.jsp Page public static final String USER_SEARCH_ACTION = "UserSearch.do"; public static final String USER_ADD_ACTION = "UserAdd.do"; public static final String USER_EDIT_ACTION = "UserEdit.do"; public static final String APPROVE_USER_ADD_ACTION = "ApproveUserAdd.do"; public static final String APPROVE_USER_EDIT_ACTION = "ApproveUserEdit.do"; public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do"; public static final String USER_EDIT_PROFILE_ACTION = "UserEditProfile.do"; public static final String UPDATE_PASSWORD_ACTION = "UpdatePassword.do"; //Constants required in Accession.jsp Page public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do"; public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do"; public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do"; //Constants required in StorageType.jsp Page public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do"; public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do"; public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do"; //Constants required in StorageContainer.jsp Page public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do"; public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do"; public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do"; public static final String HOLDS_LIST1 = "HoldsList1"; public static final String HOLDS_LIST2 = "HoldsList2"; public static final String HOLDS_LIST3 = "HoldsList3"; //Constants required in Site.jsp Page public static final String SITE_SEARCH_ACTION = "SiteSearch.do"; public static final String SITE_ADD_ACTION = "SiteAdd.do"; public static final String SITE_EDIT_ACTION = "SiteEdit.do"; //Constants required in Site.jsp Page public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do"; public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do"; public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do"; //Constants required in Partcipant.jsp Page public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do"; public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do"; public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do"; public static final String PARTICIPANT_LOOKUP_ACTION= "ParticipantLookup.do"; public static final String PARTICIPANT_CONSENT_ENTER_RESPONSE= "Enter Response"; public static final String PARTICIPANT_CONSENT_EDIT_RESPONSE= "Edit Response"; //Constants required in Institution.jsp Page public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do"; public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do"; public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do"; //Constants required in Department.jsp Page public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do"; public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do"; public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do"; //Constants required in CollectionProtocolRegistration.jsp Page public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do"; public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do"; public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do"; //Constants required in CancerResearchGroup.jsp Page public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do"; public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do"; public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do"; //Constants required for Approve user public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do"; public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do"; //Reported Problem Constants public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do"; public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do"; public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do"; public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do"; //Query Results view Actions public static final String TREE_VIEW_ACTION = "TreeView.do"; //-- TreeNodeDataAction added for DHTMLX tree grid view of storage container public static final String TREE_NODE_DATA_ACTION = "TreeNodeData.do"; public static final String DATA_VIEW_FRAME_ACTION = "SpreadsheetView.do"; public static final String SIMPLE_QUERY_INTERFACE_URL = "SimpleQueryInterface.do?pageOf=pageOfSimpleQueryInterface&menuSelected=17"; //New Specimen Data Actions. public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do"; public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do"; public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do"; public static final String SPECIMEN_EVENT_PARAMETERS_ACTION = "ListSpecimenEventParameters.do"; //Create Specimen Data Actions. public static final String CREATE_SPECIMEN_ADD_ACTION = "AddSpecimen.do"; public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do"; public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do"; //ShoppingCart Actions. public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do"; public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do"; public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do"; public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do"; //Constants required in FrozenEventParameters.jsp Page public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do"; public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do"; public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do"; //Constants required in CheckInCheckOutEventParameters.jsp Page public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do"; public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do"; public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do"; //Constants required in ReceivedEventParameters.jsp Page public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "receivedEventParametersSearch.do"; public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do"; public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "receivedEventParametersEdit.do"; //Constants required in FluidSpecimenReviewEventParameters.jsp Page public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do"; public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do"; public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do"; //Constants required in CELLSPECIMENREVIEWParameters.jsp Page public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do"; public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do"; public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do"; //Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do"; public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do"; public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do"; // Constants required in DisposalEventParameters.jsp Page public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do"; public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do"; public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do"; // Constants required in ThawEventParameters.jsp Page public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do"; public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do"; public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do"; // Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do"; public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do"; public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do"; // Constants required in CollectionEventParameters.jsp Page public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do"; public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do"; public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do"; // Constants required in SpunEventParameters.jsp Page public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do"; public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do"; public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do"; // Constants required in EmbeddedEventParameters.jsp Page public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do"; public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do"; public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do"; // Constants required in TransferEventParameters.jsp Page public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do"; public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do"; public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do"; // Constants required in FixedEventParameters.jsp Page public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do"; public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do"; public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do"; // Constants required in ProcedureEventParameters.jsp Page public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do"; public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do"; public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do"; // Constants required in Distribution.jsp Page public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do"; public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do"; public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do"; public static final String SPECIMENARRAYTYPE_ADD_ACTION = "SpecimenArrayTypeAdd.do?operation=add"; public static final String SPECIMENARRAYTYPE_EDIT_ACTION = "SpecimenArrayTypeEdit.do?operation=edit"; public static final String ARRAY_DISTRIBUTION_ADD_ACTION = "ArrayDistributionAdd.do"; public static final String SPECIMENARRAY_ADD_ACTION = "SpecimenArrayAdd.do"; public static final String SPECIMENARRAY_EDIT_ACTION = "SpecimenArrayEdit.do"; //Spreadsheet Export Action public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do"; //Aliquots Action public static final String ALIQUOT_ACTION = "Aliquots.do"; public static final String CREATE_ALIQUOT_ACTION = "CreateAliquots.do"; public static final String ALIQUOT_SUMMARY_ACTION = "AliquotSummary.do"; //Constants related to Aliquots functionality public static final String PAGEOF_ALIQUOT = "pageOfAliquot"; public static final String PAGEOF_CREATE_ALIQUOT = "pageOfCreateAliquot"; public static final String PAGEOF_ALIQUOT_SUMMARY = "pageOfAliquotSummary"; public static final String AVAILABLE_CONTAINER_MAP = "availableContainerMap"; public static final String COMMON_ADD_EDIT = "commonAddEdit"; //Constants related to SpecimenArrayAliquots functionality public static final String STORAGE_TYPE_ID="storageTypeId"; public static final String ALIQUOT_SPECIMEN_ARRAY_TYPE="SpecimenArrayType"; public static final String ALIQUOT_SPECIMEN_CLASS="SpecimenClass"; public static final String ALIQUOT_SPECIMEN_TYPES="SpecimenTypes"; public static final String ALIQUOT_ALIQUOT_COUNTS="AliquotCounts"; //Specimen Array Aliquots pages public static final String PAGEOF_SPECIMEN_ARRAY_ALIQUOT = "pageOfSpecimenArrayAliquot"; public static final String PAGEOF_SPECIMEN_ARRAY_CREATE_ALIQUOT = "pageOfSpecimenArrayCreateAliquot"; public static final String PAGEOF_SPECIMEN_ARRAY_ALIQUOT_SUMMARY = "pageOfSpecimenArrayAliquotSummary"; //Specimen Array Aliquots Action public static final String SPECIMEN_ARRAY_ALIQUOT_ACTION = "SpecimenArrayAliquots.do"; public static final String SPECIMEN_ARRAY_CREATE_ALIQUOT_ACTION = "SpecimenArrayCreateAliquots.do"; //Constants related to QuickEvents functionality public static final String QUICKEVENTS_ACTION = "QuickEventsSearch.do"; public static final String QUICKEVENTSPARAMETERS_ACTION = "ListSpecimenEventParameters.do"; //SimilarContainers Action public static final String SIMILAR_CONTAINERS_ACTION = "SimilarContainers.do"; public static final String CREATE_SIMILAR_CONTAINERS_ACTION = "CreateSimilarContainers.do"; public static final String SIMILAR_CONTAINERS_ADD_ACTION = "SimilarContainersAdd.do"; //Constants related to Similar Containsers public static final String PAGEOF_SIMILAR_CONTAINERS = "pageOfSimilarContainers"; public static final String PAGEOF_CREATE_SIMILAR_CONTAINERS = "pageOfCreateSimilarContainers"; public static final String PAGEOF_STORAGE_CONTAINER = "pageOfStorageContainer"; //Levels of nodes in query results tree. public static final int MAX_LEVEL = 5; public static final int MIN_LEVEL = 1; public static final String TABLE_NAME_COLUMN = "TABLE_NAME"; //Spreadsheet view Constants in DataViewAction. public static final String PARTICIPANT = "Participant"; public static final String ACCESSION = "Accession"; public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?id="; public static final String QUERY_PARTICIPANT_EDIT_ACTION = "QueryParticipantEdit.do"; public static final String QUERY_COLLECTION_PROTOCOL_SEARCH_ACTION = "QueryCollectionProtocolSearch.do?id="; public static final String QUERY_COLLECTION_PROTOCOL_EDIT_ACTION = "QueryCollectionProtocolEdit.do"; public static final String QUERY_SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "QuerySpecimenCollectionGroupSearch.do?id="; public static final String QUERY_SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "QuerySpecimenCollectionGroupEdit.do"; public static final String QUERY_SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "QuerySpecimenCollectionGroupAdd.do"; public static final String QUERY_SPECIMEN_SEARCH_ACTION = "QuerySpecimenSearch.do?id="; public static final String QUERY_SPECIMEN_EDIT_ACTION = "QuerySpecimenEdit.do"; //public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?id="; public static final String SPECIMEN = "Specimen"; public static final String SEGMENT = "Segment"; public static final String SAMPLE = "Sample"; public static final String COLLECTION_PROTOCOL_REGISTRATION = "CollectionProtocolRegistration"; public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID"; public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID"; public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID"; public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID"; public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID"; //For getting the tables for Simple Query and Fcon Query. public static final int ADVANCE_QUERY_TABLES = 2; //Identifiers for various Form beans public static final int DEFAULT_BIZ_LOGIC = 0; public static final int USER_FORM_ID = 1; public static final int ACCESSION_FORM_ID = 3; public static final int REPORTED_PROBLEM_FORM_ID = 4; public static final int INSTITUTION_FORM_ID = 5; public static final int APPROVE_USER_FORM_ID = 6; public static final int ACTIVITY_STATUS_FORM_ID = 7; public static final int DEPARTMENT_FORM_ID = 8; public static final int COLLECTION_PROTOCOL_FORM_ID = 9; public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10; public static final int STORAGE_CONTAINER_FORM_ID = 11; public static final int STORAGE_TYPE_FORM_ID = 12; public static final int SITE_FORM_ID = 13; public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14; public static final int BIOHAZARD_FORM_ID = 15; public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16; public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17; public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18; public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21; public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23; public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24; public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25; public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26; public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27; public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28; public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29; public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30; public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31; public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32; public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33; public static final int CREATE_SPECIMEN_FORM_ID = 34; public static final int FORGOT_PASSWORD_FORM_ID = 35; public static final int SIGNUP_FORM_ID = 36; public static final int DISTRIBUTION_FORM_ID = 37; public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38; public static final int SHOPPING_CART_FORM_ID = 39; public static final int CONFIGURE_RESULT_VIEW_ID = 41; public static final int ADVANCE_QUERY_INTERFACE_ID = 42; public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19; public static final int PARTICIPANT_FORM_ID = 2; public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20; public static final int NEW_SPECIMEN_FORM_ID = 22; public static final int ALIQUOT_FORM_ID = 44; public static final int QUICKEVENTS_FORM_ID = 45; public static final int LIST_SPECIMEN_EVENT_PARAMETERS_FORM_ID = 46; public static final int SIMILAR_CONTAINERS_FORM_ID = 47; // chetan (13-07-2006) public static final int SPECIMEN_ARRAY_TYPE_FORM_ID = 48; public static final int ARRAY_DISTRIBUTION_FORM_ID = 49; public static final int SPECIMEN_ARRAY_FORM_ID = 50; public static final int SPECIMEN_ARRAY_ALIQUOT_FORM_ID = 51; public static final int ASSIGN_PRIVILEGE_FORM_ID = 52; public static final int CDE_FORM_ID = 53; public static final int MULTIPLE_SPECIMEN_STOGAGE_LOCATION_FORM_ID = 54; public static final int REQUEST_LIST_FILTERATION_FORM_ID = 55; public static final int ORDER_FORM_ID = 56; public static final int ORDER_ARRAY_FORM_ID = 57; public static final int REQUEST_DETAILS_FORM_ID = 64; public static final int ORDER_PATHOLOGY_FORM_ID = 58; public static final int NEW_PATHOLOGY_FORM_ID=59; public static final int DEIDENTIFIED_SURGICAL_PATHOLOGY_REPORT_FORM_ID=60; public static final int PATHOLOGY_REPORT_REVIEW_FORM_ID=61; public static final int QUARANTINE_EVENT_PARAMETER_FORM_ID=62; public static final int CONSENT_FORM_ID=63; public static final int BULK_OPERATIONS_FORM_ID = 68; //Misc public static final String SEPARATOR = " : "; //Identifiers for JDBC DAO. public static final int QUERY_RESULT_TREE_JDBC_DAO = 1; //Activity Status values public static final String ACTIVITY_STATUS_APPROVE = "Approve"; public static final String ACTIVITY_STATUS_REJECT = "Reject"; public static final String ACTIVITY_STATUS_NEW = "New"; public static final String ACTIVITY_STATUS_PENDING = "Pending"; //Approve User status values. public static final String APPROVE_USER_APPROVE_STATUS = "Approve"; public static final String APPROVE_USER_REJECT_STATUS = "Reject"; public static final String APPROVE_USER_PENDING_STATUS = "Pending"; //Approve User Constants public static final int ZERO = 0; public static final int START_PAGE = 1; public static final int NUMBER_RESULTS_PER_PAGE = 20; public static final int NUMBER_RESULTS_PER_PAGE_SEARCH = 15; public static final String PAGE_NUMBER = "pageNum"; public static final String RESULTS_PER_PAGE = "numResultsPerPage"; public static final String TOTAL_RESULTS = "totalResults"; public static final String PREVIOUS_PAGE = "prevpage"; public static final String NEXT_PAGE = "nextPage"; public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList"; public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList"; public static final String USER_DETAILS = "details"; public static final String CURRENT_RECORD = "currentRecord"; public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core."; //Query Interface Results View Constants public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser"; public static final String PAGEOF_SIGNUP = "pageOfSignUp"; public static final String PAGEOF_USERADD = "pageOfUserAdd"; public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin"; public static final String PAGEOF_USER_PROFILE = "pageOfUserProfile"; public static final String PAGEOF_CHANGE_PASSWORD = "pageOfChangePassword"; //For Simple Query Interface and Edit. public static final String PAGEOF_EDIT_OBJECT = "pageOfEditObject"; //Query results view temporary table columns. public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID"; public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID"; public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID"; public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID"; public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID"; public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE"; // Assign Privilege Constants. public static final boolean PRIVILEGE_DEASSIGN = false; public static final String OPERATION_DISALLOW = "Disallow"; //Constants for default column names to be shown for query result. public static final String[] DEFAULT_SPREADSHEET_COLUMNS = { // QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID, // QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID, // QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE "IDENTIFIER","TYPE","ONE_DIMENSION_LABEL" }; //Query results edit constants - MakeEditableAction. public static final String EDITABLE = "editable"; //URL paths for Applet in TreeView.jsp public static final String QUERY_TREE_APPLET = "edu/wustl/common/treeApplet/TreeApplet.class"; public static final String APPLET_CODEBASE = "Applet"; //Shopping Cart public static final String SHOPPING_CART = "shoppingCart"; public static final String QUERY_SHOPPING_CART = "queryShoppingCart"; public static final int SELECT_OPTION_VALUE = -1; public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"}; // Constants required in CollectionProtocol.jsp Page public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do"; public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do"; public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do"; // Constants required in DistributionProtocol.jsp Page public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do"; public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do"; public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do"; //Collection Status values public static final String COLLECTION_STATUS_PENDING = "Pending"; public static final String COLLECTION_STATUS_COLLECTED = "Collected"; public static final String [] ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Active", "Closed", "Disabled" }; public static final String [] SCG_COLLECTION_STATUS_VALUES = { SELECT_OPTION, "Pending", "Pending-Partially Complete", "Overdue", "Overdue-Partially Complete", "Complete", "Complete-Late", "Incomplete", "Not Collected" }; public static final String [] SPECIMEN_COLLECTION_STATUS_VALUES = { SELECT_OPTION, "Pending", "Overdue", "Collected", "Not Collected" }; public static final String [] SITE_ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Active", "Closed" }; public static final String [] USER_ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Active", "Closed" }; public static final String [] APPROVE_USER_STATUS_VALUES = { SELECT_OPTION, APPROVE_USER_APPROVE_STATUS, APPROVE_USER_REJECT_STATUS, APPROVE_USER_PENDING_STATUS, }; public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Closed", "Pending" }; public static final String [] DISPOSAL_EVENT_ACTIVITY_STATUS_VALUES = { "Closed", "Disabled" }; public static final String TISSUE = "Tissue"; public static final String FLUID = "Fluid"; public static final String CELL = "Cell"; public static final String MOLECULAR = "Molecular"; public static final String [] SPECIMEN_TYPE_VALUES = { SELECT_OPTION, TISSUE, FLUID, CELL, MOLECULAR }; public static final String [] HOUR_ARRAY = { "00", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" }; public static final String [] MINUTES_ARRAY = { "00", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59" }; public static final String UNIT_GM = "gm"; public static final String UNIT_ML = "ml"; public static final String UNIT_CC = "cell count"; public static final String UNIT_MG = "g"; public static final String UNIT_CN = "count"; public static final String UNIT_CL = "cells"; public static final String CDE_NAME_CLINICAL_STATUS = "Clinical Status"; public static final String CDE_NAME_GENDER = "Gender"; public static final String CDE_NAME_GENOTYPE = "Genotype"; public static final String CDE_NAME_SPECIMEN_CLASS = "Specimen"; public static final String CDE_NAME_SPECIMEN_TYPE = "Specimen Type"; public static final String CDE_NAME_TISSUE_SIDE = "Tissue Side"; public static final String CDE_NAME_PATHOLOGICAL_STATUS = "Pathological Status"; public static final String CDE_NAME_RECEIVED_QUALITY = "Received Quality"; public static final String CDE_NAME_FIXATION_TYPE = "Fixation Type"; public static final String CDE_NAME_COLLECTION_PROCEDURE = "Collection Procedure"; public static final String CDE_NAME_CONTAINER = "Container"; public static final String CDE_NAME_METHOD = "Method"; public static final String CDE_NAME_EMBEDDING_MEDIUM = "Embedding Medium"; public static final String CDE_NAME_BIOHAZARD = "Biohazard"; public static final String CDE_NAME_ETHNICITY = "Ethnicity"; public static final String CDE_NAME_RACE = "Race"; public static final String CDE_VITAL_STATUS = "Vital Status"; public static final String CDE_NAME_CLINICAL_DIAGNOSIS = "Clinical Diagnosis"; public static final String CDE_NAME_SITE_TYPE = "Site Type"; public static final String CDE_NAME_COUNTRY_LIST = "Countries"; public static final String CDE_NAME_STATE_LIST = "States"; public static final String CDE_NAME_HISTOLOGICAL_QUALITY = "Histological Quality"; //Constants for Advanced Search public static final String STRING_OPERATORS = "StringOperators"; public static final String DATE_NUMERIC_OPERATORS = "DateNumericOperators"; public static final String ENUMERATED_OPERATORS = "EnumeratedOperators"; public static final String MULTI_ENUMERATED_OPERATORS = "MultiEnumeratedOperators"; public static final int CHARACTERS_IN_ONE_LINE = 110; public static final String SINGLE_QUOTE_ESCAPE_SEQUENCE = "&#096;"; public static final String [] STORAGE_STATUS_ARRAY = { SELECT_OPTION, "CHECK IN", "CHECK OUT" }; // constants for Data required in query public static final String ALIAS_NAME_TABLE_NAME_MAP="objectTableNames"; public static final String SYSTEM_IDENTIFIER_COLUMN_NAME = "IDENTIFIER"; public static final String NAME = "name"; public static final String EVENT_PARAMETERS[] = { Constants.SELECT_OPTION, "Cell Specimen Review", "Check In Check Out", "Collection", "Disposal", "Embedded", "Fixed", "Fluid Specimen Review", "Frozen", "Molecular Specimen Review", "Procedure", "Received", "Spun", "Thaw", "Tissue Specimen Review", "Transfer" }; public static final String EVENT_PARAMETERS_COLUMNS[] = { "Identifier", "Event Parameter", "User", "Date / Time", "PageOf"}; public static final String DERIVED_SPECIMEN_COLUMNS[] = { "Label", "Class", "Type", "Quantity", "rowSelected"}; public static final String [] SHOPPING_CART_COLUMNS = {"","Identifier", "Type", "Subtype", "Tissue Site", "Tissue Side", "Pathological Status"}; //Constants required in AssignPrivileges.jsp public static final String ASSIGN = "assignOperation"; public static final String PRIVILEGES = "privileges"; public static final String OBJECT_TYPES = "objectTypes"; public static final String OBJECT_TYPE_VALUES = "objectTypeValues"; public static final String RECORD_IDS = "recordIds"; public static final String ATTRIBUTES = "attributes"; public static final String GROUPS = "groups"; public static final String USERS_FOR_USE_PRIVILEGE = "usersForUsePrivilege"; public static final String USERS_FOR_READ_PRIVILEGE = "usersForReadPrivilege"; public static final String ASSIGN_PRIVILEGES_ACTION = "AssignPrivileges.do"; public static final int CONTAINER_IN_ANOTHER_CONTAINER = 2; /** * @param id * @return */ public static String getUserPGName(Long identifier) { if(identifier == null) { return "USER_"; } return "USER_"+identifier; } /** * @param id * @return */ public static String getUserGroupName(Long identifier) { if(identifier == null) { return "USER_"; } return "USER_"+identifier; } //Mandar 25-Apr-06 : bug 1414 : Tissue units as per type // tissue types with unit= count public static final String FROZEN_TISSUE_BLOCK = "Frozen Tissue Block"; // PREVIOUS FROZEN BLOCK public static final String FROZEN_TISSUE_SLIDE = "Frozen Tissue Slide"; // SLIDE public static final String FIXED_TISSUE_BLOCK = "Fixed Tissue Block"; // PARAFFIN BLOCK public static final String NOT_SPECIFIED = "Not Specified"; public static final String WITHDRAWN = "Withdrawn"; // tissue types with unit= g public static final String FRESH_TISSUE = "Fresh Tissue"; public static final String FROZEN_TISSUE = "Frozen Tissue"; public static final String FIXED_TISSUE = "Fixed Tissue"; public static final String FIXED_TISSUE_SLIDE = "Fixed Tissue Slide"; //tissue types with unit= cc public static final String MICRODISSECTED = "Microdissected"; // constants required for Distribution Report public static final String CONFIGURATION_TABLES = "configurationTables"; public static final String DISTRIBUTION_TABLE_AlIAS[] = {"CollectionProtReg","Participant","Specimen", "SpecimenCollectionGroup","DistributedItem"}; public static final String TABLE_COLUMN_DATA_MAP = "tableColumnDataMap"; public static final String CONFIGURE_RESULT_VIEW_ACTION = "ConfigureResultView.do"; public static final String TABLE_NAMES_LIST = "tableNamesList"; public static final String COLUMN_NAMES_LIST = "columnNamesList"; public static final String SPECIMEN_COLUMN_NAMES_LIST = "specimenColumnNamesList"; public static final String DISTRIBUTION_ID = "distributionId"; public static final String CONFIGURE_DISTRIBUTION_ACTION = "ConfigureDistribution.do"; public static final String DISTRIBUTION_REPORT_ACTION = "DistributionReport.do"; public static final String ARRAY_DISTRIBUTION_REPORT_ACTION = "ArrayDistributionReport.do"; public static final String DISTRIBUTION_REPORT_SAVE_ACTION="DistributionReportSave.do"; public static final String ARRAY_DISTRIBUTION_REPORT_SAVE_ACTION="ArrayDistributionReportSave.do"; //bug#4981 :kalpana public static final String SELECTED_COLUMNS[] = {"Specimen.LABEL.Label : Specimen", "Specimen.TYPE.Type : Specimen", "SpecimenCharacteristics.TISSUE_SITE.Tissue Site : Specimen", "SpecimenCharacteristics.TISSUE_SIDE.Tissue Side : Specimen", "Specimen.PATHOLOGICAL_STATUS.Pathological Status : Specimen", "DistributedItem.QUANTITY.Quantity : Distribution"}; //"SpecimenCharacteristics.PATHOLOGICAL_STATUS.Pathological Status : Specimen", public static final String SPECIMEN_IN_ARRAY_SELECTED_COLUMNS[] = { "Specimen.LABEL.Label : Specimen", "Specimen.BARCODE.barcode : Specimen", "SpecimenArrayContent.PositionDimensionOne.PositionDimensionOne : Specimen", "SpecimenArrayContent.PositionDimensionTwo.PositionDimensionTwo : Specimen", "Specimen.CLASS.CLASS : Specimen", "Specimen.TYPE.Type : Specimen", "SpecimenCharacteristics.TISSUE_SIDE.Tissue Side : Specimen", "SpecimenCharacteristics.TISSUE_SITE.Tissue Site : Specimen", }; public static final String ARRAY_SELECTED_COLUMNS[] = { "SpecimenArray.Name.Name : SpecimenArray", "Container.barcode.Barcode : SpecimenArray", "ContainerType.name.ArrayType : ContainerType", "Container.PositionDimensionOne.Position One: Container", "Container.PositionDimensionTwo.Position Two: Container", "Container.CapacityOne.Dimension One: Container", "Container.CapacityTwo.Dimension Two: Container", "ContainerType.SpecimenClass.specimen class : ContainerType", "ContainerType.SpecimenTypes.specimen Types : ContainerType", "Container.Comment.comment: Container", }; public static final String SPECIMEN_ID_LIST = "specimenIdList"; public static final String DISTRIBUTION_ACTION = "Distribution.do?pageOf=pageOfDistribution"; public static final String DISTRIBUTION_REPORT_NAME = "Distribution Report.csv"; public static final String DISTRIBUTION_REPORT_FORM="distributionReportForm"; public static final String DISTRIBUTED_ITEMS_DATA = "distributedItemsData"; public static final String DISTRIBUTED_ITEM = "DistributedItem"; //constants for Simple Query Interface Configuration public static final String CONFIGURE_SIMPLE_QUERY_ACTION = "ConfigureSimpleQuery.do"; public static final String CONFIGURE_SIMPLE_QUERY_VALIDATE_ACTION = "ConfigureSimpleQueryValidate.do"; public static final String CONFIGURE_SIMPLE_SEARCH_ACTION = "ConfigureSimpleSearch.do"; public static final String SIMPLE_SEARCH_ACTION = "SimpleSearch.do"; public static final String SIMPLE_SEARCH_AFTER_CONFIGURE_ACTION = "SimpleSearchAfterConfigure.do"; public static final String PAGEOF_DISTRIBUTION = "pageOfDistribution"; public static final String RESULT_VIEW_VECTOR = "resultViewVector"; public static final String SPECIMENT_VIEW_ATTRIBUTE = "defaultViewAttribute"; //public static final String SIMPLE_QUERY_COUNTER = "simpleQueryCount"; public static final String UNDEFINED = "Undefined"; public static final String UNKNOWN = "Unknown"; public static final String UNSPECIFIED = "Unspecified"; public static final String NOTSPECIFIED = "Not Specified"; public static final String SEARCH_RESULT = "SearchResult.csv"; // Mandar : LightYellow and Green colors for CollectionProtocol SpecimenRequirements. Bug id: 587 // public static final String ODD_COLOR = "#FEFB85"; // public static final String EVEN_COLOR = "#A7FEAB"; // Light and dark shades of GREY. public static final String ODD_COLOR = "#E5E5E5"; public static final String EVEN_COLOR = "#F7F7F7"; // TO FORWARD THE REQUEST ON SUBMIT IF STATUS IS DISABLED public static final String BIO_SPECIMEN = "/ManageBioSpecimen.do"; public static final String ADMINISTRATIVE = "/ManageAdministrativeData.do"; public static final String PARENT_SPECIMEN_ID = "parentSpecimenId"; public static final String COLLECTION_REGISTRATION_ID = "collectionProtocolId"; public static final String FORWARDLIST = "forwardToList"; public static final String [][] SPECIMEN_FORWARD_TO_LIST = { {"Submit", "success"}, {"Derive", "createNew"}, {"Add Events", "eventParameters"}, {"More", "sameCollectionGroup"}, {"Distribute", "distribution" }, {"Derive Multiple", "deriveMultiple"} }; public static final String [] SPECIMEN_BUTTON_TIPS = { "Submit only", "Submit and derive", "Submit and add events", "Submit and add more to same group", "Submit and distribute", "Submit and derive multiple" }; public static final String [][] SPECIMEN_COLLECTION_GROUP_FORWARD_TO_LIST = { {"Submit", "success"}, {"Add Specimen", "createNewSpecimen"}, {"Add Multiple Specimens", "createMultipleSpecimen"} }; public static final String [][] PROTOCOL_REGISTRATION_FORWARD_TO_LIST = { {"Submit", "success"}, {"Specimen Collection Group", "createSpecimenCollectionGroup"} }; public static final String [][] PARTICIPANT_FORWARD_TO_LIST = { {"Submit", "success"}, {"Submit", "createParticipantRegistration"}, {"Specimen Collection Group", "specimenCollectionGroup"}, {"Submit", "pageOfParticipantCPQuery"} }; public static final String [][] STORAGE_TYPE_FORWARD_TO_LIST = { {"Submit", "success"}, {"Add Container", "storageContainer"} }; //Constants Required for Advance Search //Tree related //public static final String PARTICIPANT ='Participant'; public static final String[] ADVANCE_QUERY_TREE_HEIRARCHY={ //Represents the Advance Query tree Heirarchy. Constants.PARTICIPANT, Constants.COLLECTION_PROTOCOL, Constants.SPECIMEN_COLLECTION_GROUP, Constants.SPECIMEN }; public static final String MENU_COLLECTION_PROTOCOL ="Collection Protocol"; public static final String MENU_SPECIMEN_COLLECTION_GROUP ="Specimen Collection Group"; public static final String MENU_DISTRIBUTION_PROTOCOL = "Distribution Protocol"; public static final String SPECIMEN_COLLECTION_GROUP ="SpecimenCollectionGroup"; public static final String DISTRIBUTION = "Distribution"; public static final String DISTRIBUTION_PROTOCOL = "DistributionProtocol"; public static final String CP = "CP"; public static final String SCG = "SCG"; public static final String D = "D"; public static final String DP = "DP"; public static final String C = "C"; public static final String S = "S"; public static final String P = "P"; public static final String ADVANCED_CONDITIONS_QUERY_VIEW = "advancedCondtionsQueryView"; public static final String ADVANCED_SEARCH_ACTION = "AdvanceSearch.do"; public static final String ADVANCED_SEARCH_RESULTS_ACTION = "AdvanceSearchResults.do"; public static final String CONFIGURE_ADVANCED_SEARCH_RESULTS_ACTION = "ConfigureAdvanceSearchResults.do"; public static final String ADVANCED_QUERY_ADD = "Add"; public static final String ADVANCED_QUERY_EDIT = "Edit"; public static final String ADVANCED_QUERY_DELETE = "Delete"; public static final String ADVANCED_QUERY_OPERATOR = "Operator"; public static final String ADVANCED_QUERY_OR = "OR"; public static final String ADVANCED_QUERY_AND = "pAND"; public static final String EVENT_CONDITIONS = "eventConditions"; public static final String IDENTIFIER_COLUMN_ID_MAP = "identifierColumnIdsMap"; public static final String PAGEOF_PARTICIPANT_QUERY_EDIT= "pageOfParticipantQueryEdit"; public static final String PAGEOF_COLLECTION_PROTOCOL_QUERY_EDIT= "pageOfCollectionProtocolQueryEdit"; public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP_QUERY_EDIT= "pageOfSpecimenCollectionGroupQueryEdit"; public static final String PAGEOF_SPECIMEN_QUERY_EDIT= "pageOfSpecimenQueryEdit"; public static final String PARTICIPANT_COLUMNS = "particpantColumns"; public static final String COLLECTION_PROTOCOL_COLUMNS = "collectionProtocolColumns"; public static final String SPECIMEN_COLLECTION_GROUP_COLUMNS = "SpecimenCollectionGroupColumns"; public static final String SPECIMEN_COLUMNS = "SpecimenColumns"; public static final String USER_ID_COLUMN = "USER_ID"; public static final String GENERIC_SECURITYMANAGER_ERROR = "The Security Violation error occured during a database operation. Please report this problem to the adminstrator"; public static final String BOOLEAN_YES = "Yes"; public static final String BOOLEAN_NO = "No"; public static final String PACKAGE_DOMAIN = "edu.wustl.catissuecore.domain"; //Constants for isAuditable and isSecureUpdate required for Dao methods in Bozlogic public static final boolean IS_AUDITABLE_TRUE = true; public static final boolean IS_SECURE_UPDATE_TRUE = true; public static final boolean HAS_OBJECT_LEVEL_PRIVILEGE_FALSE = false; //Constants for HTTP-API public static final String CONTENT_TYPE = "CONTENT-TYPE"; // For StorageContainer isFull status public static final String IS_CONTAINER_FULL_LIST = "isContainerFullList"; public static final String [] IS_CONTAINER_FULL_VALUES = { SELECT_OPTION, "True", "False" }; public static final String STORAGE_CONTAINER_DIM_ONE_LABEL = "oneDimLabel"; public static final String STORAGE_CONTAINER_DIM_TWO_LABEL = "twoDimLabel"; // public static final String SPECIMEN_TYPE_TISSUE = "Tissue"; // public static final String SPECIMEN_TYPE_FLUID = "Fluid"; // public static final String SPECIMEN_TYPE_CELL = "Cell"; // public static final String SPECIMEN_TYPE_MOL = "Molecular"; public static final String SPECIMEN_TYPE_COUNT = "Count"; public static final String SPECIMEN_TYPE_QUANTITY = "Quantity"; public static final String SPECIMEN_TYPE_DETAILS = "Details"; public static final String SPECIMEN_COUNT = "totalSpecimenCount"; public static final String TOTAL = "Total"; public static final String SPECIMENS = "Specimens"; //User Roles public static final String TECHNICIAN = "Technician"; public static final String SUPERVISOR = "Supervisor"; public static final String SCIENTIST = "Scientist"; public static final String CHILD_CONTAINER_TYPE = "childContainerType"; public static final String UNUSED = "Unused"; public static final String TYPE = "Type"; //Mandar: 28-Apr-06 Bug 1129 public static final String DUPLICATE_SPECIMEN="duplicateSpecimen"; //Constants required in ParticipantLookupAction public static final String PARTICIPANT_LOOKUP_PARAMETER="ParticipantLookupParameter"; public static final String PARTICIPANT_LOOKUP_CUTOFF="lookup.cutoff"; public static final String PARTICIPANT_LOOKUP_ALGO="ParticipantLookupAlgo"; public static final String PARTICIPANT_LOOKUP_SUCCESS="success"; public static final String PARTICIPANT_ADD_FORWARD="participantAdd"; public static final String PARTICIPANT_SYSTEM_IDENTIFIER="IDENTIFIER"; public static final String PARTICIPANT_LAST_NAME="LAST_NAME"; public static final String PARTICIPANT_FIRST_NAME="FIRST_NAME"; public static final String PARTICIPANT_MIDDLE_NAME="MIDDLE_NAME"; public static final String PARTICIPANT_BIRTH_DATE="BIRTH_DATE"; public static final String PARTICIPANT_DEATH_DATE="DEATH_DATE"; public static final String PARTICIPANT_VITAL_STATUS="VITAL_STATUS"; public static final String PARTICIPANT_GENDER="GENDER"; public static final String PARTICIPANT_SEX_GENOTYPE="SEX_GENOTYPE"; public static final String PARTICIPANT_RACE="RACE"; public static final String PARTICIPANT_ETHINICITY="ETHINICITY"; public static final String PARTICIPANT_SOCIAL_SECURITY_NUMBER="SOCIAL_SECURITY_NUMBER"; public static final String PARTICIPANT_PROBABLITY_MATCH="Probability"; public static final String PARTICIPANT_MEDICAL_RECORD_NO="MEDICAL_RECORD_NUMBER"; public static final String PARTICIPANT_SSN_EXACT="SSNExact"; public static final String PARTICIPANT_SSN_PARTIAL="SSNPartial"; public static final String PARTICIPANT_PMI_EXACT="PMIExact"; public static final String PARTICIPANT_PMI_PARTIAL="PMIPartial"; public static final String PARTICIPANT_DOB_EXACT="DOBExact"; public static final String PARTICIPANT_DOB_PARTIAL="DOBPartial"; public static final String PARTICIPANT_LAST_NAME_EXACT="LastNameExact"; public static final String PARTICIPANT_LAST_NAME_PARTIAL="LastNamePartial"; public static final String PARTICIPANT_FIRST_NAME_EXACT="NameExact"; public static final String PARTICIPANT_FIRST_NAME_PARTIAL="NamePartial"; public static final String PARTICIPANT_MIDDLE_NAME_EXACT="MiddleNameExact"; public static final String PARTICIPANT_MIDDLE_NAME_PARTIAL="MiddleNamePartial"; public static final String PARTICIPANT_GENDER_EXACT="GenderExact"; public static final String PARTICIPANT_RACE_EXACT="RaceExact"; public static final String PARTICIPANT_RACE_PARTIAL="RacePartial"; public static final String PARTICIPANT_BONUS="Bonus"; public static final String PARTICIPANT_TOTAL_POINTS="TotalPoints"; public static final String PARTICIPANT_MATCH_CHARACTERS_FOR_LAST_NAME="MatchCharactersForLastName"; //Constants for integration of caTies and CAE with caTissue Core public static final String LINKED_DATA = "linkedData"; public static final String APPLICATION_ID = "applicationId"; public static final String CATIES = "caTies"; public static final String CAE = "cae"; public static final String EDIT_TAB_LINK = "editTabLink"; public static final String CATIES_PUBLIC_SERVER_NAME = "CaTiesPublicServerName"; public static final String CATIES_PRIVATE_SERVER_NAME = "CaTiesPrivateServerName"; //Constants for StorageContainerMap Applet public static final String CONTAINER_STYLEID = "containerStyleId"; public static final String CONTAINER_STYLE = "containerStyle"; public static final String XDIM_STYLEID = "xDimStyleId"; public static final String YDIM_STYLEID = "yDimStyleId"; public static final String SELECTED_CONTAINER_NAME="selectedContainerName"; public static final String CONTAINERID="containerId"; public static final String POS1="pos1"; public static final String POS2="pos2"; //Constants for QuickEvents public static final String EVENT_SELECTED = "eventSelected"; //Constant for SpecimenEvents page. public static final String EVENTS_TITLE_MESSAGE = "Existing events for the specimen with label {0}"; public static final String SURGICAL_PATHOLOGY_REPORT = "Surgical Pathology Report"; public static final String CLINICAL_ANNOTATIONS = "Clinical Annotations"; //Constants for Specimen Collection Group name- new field public static final String RESET_NAME ="resetName"; // Labels for Storage Containers public static final String[] STORAGE_CONTAINER_LABEL = {" Name"," Pos1"," Pos2"}; //Constans for Any field public static final String HOLDS_ANY = "--All //Constants : Specimen -> lineage public static final String NEW_SPECIMEN = "New"; public static final String DERIVED_SPECIMEN = "Derived"; public static final String ALIQUOT = "Aliquot"; //Constant for length of messageBody in Reported problem page public static final int messageLength= 500; public static final String NEXT_NUMBER="nextNumber"; // public static final String getCollectionProtocolPIGroupName(Long identifier) // if(identifier == null) // return "PI_COLLECTION_PROTOCOL_"; // return "PI_COLLECTION_PROTOCOL_"+identifier; // public static final String getCollectionProtocolCoordinatorGroupName(Long identifier) // if(identifier == null) // return "COORDINATORS_COLLECTION_PROTOCOL_"; // return "COORDINATORS_COLLECTION_PROTOCOL_"+identifier; // public static final String getDistributionProtocolPIGroupName(Long identifier) // if(identifier == null) // return "PI_DISTRIBUTION_PROTOCOL_"; // return "PI_DISTRIBUTION_PROTOCOL_"+identifier; // public static final String getCollectionProtocolPGName(Long identifier) // if(identifier == null) // return "COLLECTION_PROTOCOL_"; // return "COLLECTION_PROTOCOL_"+identifier; // public static final String getDistributionProtocolPGName(Long identifier) // if(identifier == null) // return "DISTRIBUTION_PROTOCOL_"; // return "DISTRIBUTION_PROTOCOL_"+identifier; public static final String ALL = "All"; //constant for pagination data list public static final String PAGINATION_DATA_LIST = "paginationDataList"; public static final int SPECIMEN_DISTRIBUTION_TYPE = 1; public static final int SPECIMEN_ARRAY_DISTRIBUTION_TYPE = 2; public static final int BARCODE_BASED_DISTRIBUTION = 1; public static final int LABEL_BASED_DISTRIBUTION = 2; public static final String DISTRIBUTION_TYPE_LIST = "DISTRIBUTION_TYPE_LIST"; public static final String DISTRIBUTION_BASED_ON = "DISTRIBUTION_BASED_ON"; public static final String SYSTEM_LABEL = "label"; public static final String SYSTEM_BARCODE = "barcode"; public static final String SYSTEM_NAME = "name"; //Mandar : 05Sep06 Array for multiple specimen field names public static final String DERIVED_OPERATION = "derivedOperation"; public static final String [] MULTIPLE_SPECIMEN_FIELD_NAMES = { "Collection Group", "Parent ID", "Name", "Barcode", "Class", "Type", "Tissue Site", "Tissue Side", "Pathological Status", "Concentration", "Quantity", "Storage Location", "Comments", "Events", "External Identifier", "Biohazards" // "Derived", // "Aliquots" }; public static final String PAGEOF_MULTIPLE_SPECIMEN = "pageOfMultipleSpecimen"; public static final String PAGEOF_MULTIPLE_SPECIMEN_MAIN = "pageOfMultipleSpecimenMain"; public static final String MULTIPLE_SPECIMEN_ACTION = "MultipleSpecimen.do"; public static final String INIT_MULTIPLE_SPECIMEN_ACTION = "InitMultipleSpecimen.do"; public static final String MULTIPLE_SPECIMEN_APPLET_ACTION = "MultipleSpecimenAppletAction.do"; public static final String NEW_MULTIPLE_SPECIMEN_ACTION = "NewMultipleSpecimenAction.do"; public static final String MULTIPLE_SPECIMEN_RESULT = "multipleSpecimenResult"; public static final String SAVED_SPECIMEN_COLLECTION = "savedSpecimenCollection"; public static final String [] MULTIPLE_SPECIMEN_FORM_FIELD_NAMES = { "CollectionGroup", "ParentID", "Name", "Barcode", "Class", "Type", "TissueSite", "TissueSide", "PathologicalStatus", "Concentration", "Quantity", "StorageLocation", "Comments", "Events", "ExternalIdentifier", "Biohazards" // "Derived", // "Aliquots" }; public static final String MULTIPLE_SPECIMEN_MAP_KEY = "MULTIPLE_SPECIMEN_MAP_KEY"; public static final String MULTIPLE_SPECIMEN_EVENT_MAP_KEY = "MULTIPLE_SPECIMEN_EVENT_MAP_KEY"; public static final String MULTIPLE_SPECIMEN_FORM_BEAN_MAP_KEY = "MULTIPLE_SPECIMEN_FORM_BEAN_MAP_KEY"; public static final String MULTIPLE_SPECIMEN_BUTTONS_MAP_KEY = "MULTIPLE_SPECIMEN_BUTTONS_MAP_KEY"; public static final String MULTIPLE_SPECIMEN_LABEL_MAP_KEY = "MULTIPLE_SPECIMEN_LABEL_MAP_KEY"; public static final String DERIVED_FORM = "DerivedForm"; public static final String SPECIMEN_ATTRIBUTE_KEY = "specimenAttributeKey"; public static final String SPECIMEN_CLASS = "specimenClass"; public static final String SPECIMEN_CALL_BACK_FUNCTION = "specimenCallBackFunction"; public static final String APPEND_COUNT = "_count"; public static final String EXTERNALIDENTIFIER_TYPE = "ExternalIdentifier"; public static final String BIOHAZARD_TYPE = "BioHazard"; public static final String COMMENTS_TYPE = "comments"; public static final String EVENTS_TYPE = "Events"; public static final String MULTIPLE_SPECIMEN_APPLET_NAME = "MultipleSpecimenApplet"; public static final String INPUT_APPLET_DATA = "inputAppletData"; // Start Specimen Array Applet related constants public static final String SPECIMEN_ARRAY_APPLET = "edu/wustl/catissuecore/applet/ui/SpecimenArrayApplet.class"; public static final String SPECIMEN_ARRAY_APPLET_NAME = "specimenArrayApplet"; public static final String SPECIMEN_ARRAY_CONTENT_KEY = "SpecimenArrayContentKey"; public static final String SPECIMEN_LABEL_COLUMN_NAME = "label"; public static final String SPECIMEN_BARCODE_COLUMN_NAME = "barcode"; public static final String ARRAY_SPECIMEN_DOES_NOT_EXIST_EXCEPTION_MESSAGE = "Please enter valid specimen for specimen array!!specimen does not exist "; public static final String ARRAY_SPECIMEN_NOT_ACTIVE_EXCEPTION_MESSAGE = "Please enter valid specimen for specimen array!! Specimen is closed/disabled "; public static final String ARRAY_NO_SPECIMEN__EXCEPTION_MESSAGE = "Specimen Array should contain at least one specimen"; public static final String ARRAY_SPEC_NOT_COMPATIBLE_EXCEPTION_MESSAGE = "Please add compatible specimens to specimen array (belong to same specimen class & specimen types of Array)"; public static final String ARRAY_MOLECULAR_QUAN_EXCEPTION_MESSAGE = "Please enter quantity for Molecular Specimen /** * Specify the SPECIMEN_ARRAY_LIST as key for specimen array type list */ public static final String SPECIMEN_ARRAY_TYPE_LIST = "specimenArrayList"; public static final String SPECIMEN_ARRAY_CLASSNAME = "edu.wustl.catissuecore.domain.SpecimenArray"; public static final String SPECIMEN_ARRAY_TYPE_CLASSNAME = "edu.wustl.catissuecore.domain.SpecimenArrayType"; // End // Common Applet Constants public static final String APPLET_SERVER_HTTP_START_STR = "http: public static final String APPLET_SERVER_URL_PARAM_NAME = "serverURL"; //operators for simple query and advanced query public static final String IS_NOT_NULL = "is not null"; public static final String IS_NULL = "is null"; public static final String In = "In"; public static final String Not_In = "Not In"; public static final String Equals = "Equals"; public static final String Not_Equals = "Not Equals"; public static final String Between = "Between"; public static final String Less_Than = "Less than"; public static final String Less_Than_Or_Equals = "Less than or Equal to"; public static final String Greater_Than = "Greater than"; public static final String Greater_Than_Or_Equals = "Greater than or Equal to"; public static final String Contains = "Contains"; // Used in array action public static final String ARRAY_TYPE_ANY_VALUE = "2"; public static final String ARRAY_TYPE_ANY_NAME = "Any"; // end // Array Type All Id in table public static final short ARRAY_TYPE_ALL_ID = 2; // constants required for caching mechanism of ParticipantBizLogic public static final String MAP_OF_PARTICIPANTS = "listOfParticipants"; public static final String LIST_OF_REGISTRATION_INFO = "listOfParticipantRegistrations"; public static final String EHCACHE_FOR_CATISSUE_CORE = "cacheForCaTissueCore"; public static final String MAP_OF_DISABLED_CONTAINERS = "listOfDisabledContainers"; public static final String MAP_OF_CONTAINER_FOR_DISABLED_SPECIEN = "listOfContainerForDisabledContainerSpecimen"; public static final String ADD = "add"; public static final String EDIT = "edit"; public static final String ID = "id"; public static final String MANAGE_BIO_SPECIMEN_ACTION = "/ManageBioSpecimen.do"; public static final String CREATE_PARTICIPANT_REGISTRATION = "createParticipantRegistration"; public static final String CREATE_PARTICIPANT_REGISTRATION_ADD = "createParticipantRegistrationAdd"; public static final String CREATE_PARTICIPANT_REGISTRATION_EDIT= "createParticipantRegistrationEdit"; public static final String CAN_HOLD_CONTAINER_TYPE = "holdContainerType"; public static final String CAN_HOLD_SPECIMEN_CLASS = "holdSpecimenClass"; public static final String CAN_HOLD_COLLECTION_PROTOCOL = "holdCollectionProtocol"; public static final String CAN_HOLD_SPECIMEN_ARRAY_TYPE = "holdSpecimenArrayType"; public static final String COLLECTION_PROTOCOL_ID = "collectionProtocolId"; public static final String SPECIMEN_CLASS_NAME = "specimeClassName"; public static final String ENABLE_STORAGE_CONTAINER_GRID_PAGE = "enablePage"; public static final int ALL_STORAGE_TYPE_ID = 1; //Constant for the "All" storage type, which can hold all container type public static final int ALL_SPECIMEN_ARRAY_TYPE_ID = 2;//Constant for the "All" storage type, which can hold all specimen array type public static final String SPECIMEN_LABEL_CONTAINER_MAP = "Specimen : "; public static final String CONTAINER_LABEL_CONTAINER_MAP = "Container : "; public static final String SPECIMEN_ARRAY_LABEL_CONTAINER_MAP = "Array : "; public static final String SPECIMEN_PROTOCOL ="SpecimenProtocol"; public static final String SPECIMEN_PROTOCOL_SHORT_TITLE ="SHORT_TITLE"; public static final String SPECIMEN_COLLECTION_GROUP_NAME ="NAME"; public static final String SPECIMEN_LABEL = "LABEL"; // Patch ID: Bug#3184_14 public static final String NUMBER_OF_SPECIMEN = "numberOfSpecimen"; //Constants required for max limit on no. of containers in the drop down public static final String CONTAINERS_MAX_LIMIT = "containers_max_limit"; public static final String EXCEEDS_MAX_LIMIT = "exceedsMaxLimit"; //MultipleSpecimen Constants public static final String MULTIPLE_SPECIMEN_COLUMNS_PER_PAGE="multipleSpecimen.ColumnsPerPage"; public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_ACTION="MultipleSpecimenStorageLocationAdd.do"; public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_AVAILABLE_MAP="locationMap"; public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_SPECIMEN_MAP= "specimenMap"; public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_KEY_SEPARATOR = "$"; public static final String PAGEOF_MULTIPLE_SPECIMEN_STORAGE_LOCATION = "formSubmitted"; public static final String MULTIPLE_SPECIMEN_SUBMIT_SUCCESSFUL = "submitSuccessful"; public static final String MULTIPLE_SPECIMEN_SPECIMEN_ORDER_LIST= "specimenOrderList"; public static final String MULTIPLE_SPECIMEN_DELETELAST_SPECIMEN_ID = "SpecimenId"; public static final String MULTIPLE_SPECIMEN_PARENT_COLLECTION_GROUP = "ParentSpecimenCollectionGroup"; public static final String NO_OF_RECORDS_PER_PAGE="resultView.noOfRecordsPerPage"; /** * Name: Prafull * Description: Query performance issue. Instead of saving complete query results in session, resultd will be fetched for each result page navigation. * object of class QuerySessionData will be saved session, which will contain the required information for query execution while navigating through query result pages. * Changes resultper page options, removed 5000 from the array & added 500 as another option. */ public static final int[] RESULT_PERPAGE_OPTIONS = {10,50,100,500,1000}; /** * Specify the SPECIMEN_MAP_KEY field ) used in multiple specimen applet action. */ public static final String SPECIMEN_MAP_KEY = "Specimen_derived_map_key"; /** * Specify the SPECIMEN_MAP_KEY field ) used in multiple specimen applet action. */ public static final String CONTAINER_MAP_KEY = "container_map_key"; /** * Used to saperate storage container, xPos, yPos */ public static final String STORAGE_LOCATION_SAPERATOR = "@"; public static final String METHOD_NAME="method"; public static final String GRID_FOR_EVENTS="eventParameter"; public static final String GRID_FOR_EDIT_SEARCH="editSearch"; public static final String GRID_FOR_DERIVED_SPECIMEN="derivedSpecimen"; /* * used to find whether iframe needs to be reloaded or not */ public static final String RELOAD ="false"; public static final String CHILD_CONTAINER_NAME="childContainerName"; //CpBasedSearch Constants public static final String CP_QUERY = "CPQuery"; public static final String CP_QUERY_PARTICIPANT_EDIT_ACTION = "CPQueryParticipantEdit.do"; public static final String CP_QUERY_PARTICIPANT_ADD_ACTION = "CPQueryParticipantAdd.do"; public static final String CP_QUERY_SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "CPQuerySpecimenCollectionGroupAdd.do"; public static final String CP_QUERY_SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "CPQuerySpecimenCollectionGroupEdit.do"; public static final String CP_AND_PARTICIPANT_VIEW="cpAndParticipantView"; public static final String DATA_DETAILS_VIEW="dataDetailsView"; public static final String SHOW_CP_AND_PARTICIPANTS_ACTION="showCpAndParticipants.do"; public static final String PAGE_OF_CP_QUERY_RESULTS = "pageOfCpQueryResults"; public static final String CP_LIST = "cpList"; public static final String CP_ID_TITLE_MAP = "cpIDTitleMap"; public static final String REGISTERED_PARTICIPANT_LIST = "participantList"; public static final String PAGE_OF_PARTICIPANT_CP_QUERY = "pageOfParticipantCPQuery"; public static final String PAGE_OF_SCG_CP_QUERY = "pageOfSpecimenCollectionGroupCPQuery"; public static final String CP_SEARCH_PARTICIPANT_ID="cpSearchParticipantId"; public static final String CP_SEARCH_CP_ID="cpSearchCpId"; public static final String CP_TREE_VIEW = "cpTreeView"; public static final String CP_TREE_VIEW_ACTION = "showTree.do"; public static final String PAGE_OF_SPECIMEN_CP_QUERY = "pageOfNewSpecimenCPQuery"; public static final String CP_QUERY_SPECIMEN_ADD_ACTION = "CPQueryNewSpecimenAdd.do"; public static final String CP_QUERY_CREATE_SPECIMEN_ACTION = "CPQueryCreateSpecimen.do"; public static final String CP_QUERY_SPECIMEN_EDIT_ACTION = "CPQueryNewSpecimenEdit.do"; public static final String PAGE_OF_CREATE_SPECIMEN_CP_QUERY = "pageOfCreateSpecimenCPQuery"; public static final String PAGE_OF_ALIQUOT_CP_QUERY = "pageOfAliquotCPQuery"; public static final String PAGE_OF_CREATE_ALIQUOT_CP_QUERY = "pageOfCreateAliquotCPQuery"; public static final String PAGE_OF_ALIQUOT_SUMMARY_CP_QUERY = "pageOfAliquotSummaryCPQuery"; public static final String CP_QUERY_CREATE_ALIQUOT_ACTION = "CPQueryCreateAliquots.do"; public static final String CP_QUERY_ALIQUOT_SUMMARY_ACTION = "CPQueryAliquotSummary.do"; public static final String CP_QUERY_CREATE_SPECIMEN_ADD_ACTION = "CPQueryAddSpecimen.do"; public static final String PAGE_OF_DISTRIBUTION_CP_QUERY = "pageOfDistributionCPQuery"; public static final String CP_QUERY_DISTRIBUTION_EDIT_ACTION = "CPQueryDistributionEdit.do"; public static final String CP_QUERY_DISTRIBUTION_ADD_ACTION = "CPQueryDistributionAdd.do"; public static final String CP_QUERY_DISTRIBUTION_REPORT_SAVE_ACTION="CPQueryDistributionReportSave.do"; public static final String CP_QUERY_ARRAY_DISTRIBUTION_REPORT_SAVE_ACTION="CPQueryArrayDistributionReportSave.do"; public static final String CP_QUERY_CONFIGURE_DISTRIBUTION_ACTION = "CPQueryConfigureDistribution.do"; public static final String CP_QUERY_DISTRIBUTION_REPORT_ACTION = "CPQueryDistributionReport.do"; public static final String PAGE_OF_LIST_SPECIMEN_EVENT_PARAMETERS_CP_QUERY = "pageOfListSpecimenEventParametersCPQuery"; public static final String PAGE_OF_LIST_SPECIMEN_EVENT_PARAMETERS = "pageOfListSpecimenEventParameters"; public static final String PAGE_OF_COLLECTION_PROTOCOL_REGISTRATION_CP_QUERY = "pageOfCollectionProtocolRegistrationCPQuery"; public static final String PAGE_OF_MULTIPLE_SPECIMEN_CP_QUERY = "pageOfMultipleSpecimenCPQuery"; public static final String CP_QUERY_NEW_MULTIPLE_SPECIMEN_ACTION = "CPQueryNewMultipleSpecimenAction.do"; public static final String CP_QUERY_MULTIPLE_SPECIMEN_STORAGE_LOCATION_ACTION="CPQueryMultipleSpecimenStorageLocationAdd.do"; public static final String CP_QUERY_PAGEOF_MULTIPLE_SPECIMEN_STORAGE_LOCATION = "CPQueryformSubmitted"; public static final String CP_QUERY_COLLECTION_PROTOCOL_REGISTRATION_ADD_ACTION = "CPQueryCollectionProtocolRegistrationAdd.do"; public static final String CP_QUERY_COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CPQueryCollectionProtocolRegistrationEdit.do"; public static final String CP_QUERY_PARTICIPANT_LOOKUP_ACTION= "CPQueryParticipantLookup.do"; public static final String CP_QUERY_BIO_SPECIMEN = "/QueryManageBioSpecimen.do"; //Mandar : 15-Jan-07 public static final String WITHDRAW_RESPONSE_NOACTION= "No Action"; public static final String WITHDRAW_RESPONSE_DISCARD= "Discard"; public static final String WITHDRAW_RESPONSE_RETURN= "Return"; public static final String WITHDRAW_RESPONSE_RESET= "Reset"; public static final String WITHDRAW_RESPONSE_REASON= "Specimen consents withdrawn"; public static final String SEARCH_CATEGORY_LIST_SELECT_TAG_NAME="selectCategoryList"; public static final String SEARCH_CATEGORY_LIST_FUNCTION_NAME="getSelectedEntities"; public static final String EDIT_CONDN = "Edit"; public static final String SPLITTER_STATUS_REQ_PARAM = "SPLITTER_STATUS"; //mulltiple specimen Applet constants public static final int VALIDATE_TEXT =1; public static final int VALIDATE_COMBO =2; public static final int VALIDATE_DATE =3; /** * Constants required for maintaining toolTipText for event button on multiple specimen page */ public static final String TOOLTIP_TEXT="TOOLTIPTEXT"; public static final String MULTIPLE_SPECIMEN_TOOLTIP_MAP_KEY="multipleSpecimenTooltipMapKey"; public static final String DEFAULT_TOOLTIP_TEXT="DEFAULTTOOLTIPTEXT"; /** * Patch ID: Bug#3184_15 (for Multiple Specimen) * Description: The following constants are used as key in the Map */ public static final String KEY_SPECIMEN_CLASS = "SpecimenClass"; public static final String KEY_SPECIMEN_TYPE = "SpecimenType"; public static final String KEY_TISSUE_SITE = "TissueSite"; public static final String KEY_PATHOLOGICAL_STATUS = "PathologicalStatus"; public static final String KEY_SPECIMEN_REQUIREMENT_PREFIX = "SpecimenRequirement_"; public static final String KEY_RESTRICTED_VALUES = "RestictedValues"; public static final String KEY_QUANTITY = "Quantity"; // The following constants are used for multiple specimens applet classes public static final String NUMBER_OF_SPECIMEN_REQUIREMENTS = "numberOfSpecimenRequirements"; public static final String RESTRICT_SCG_CHECKBOX = "restrictSCGCheckbox"; public static final String ON_COLL_OR_CLASSCHANGE = "onCollOrClassChange"; public static final String NUMBER_OF_SPECIMENS = "numberOfSpecimens"; public static final String CHANGE_ON = "changeOn"; // Patch ID: Bug#4180_3 public static final String EVENT_NAME = "eventName"; public static final String USER_NAME = "userName"; public static final String EVENT_DATE = "eventDate"; public static final String PAGE_OF = "pageOf"; /** * Patch ID: for Future SCG_15 * Description: The following constants are used as id for future scg in tree */ public static final String FUTURE_SCG = "future"; // Patch ID: SimpleSearchEdit_5 // AliasName constants, used in Edit in Simple Search feature. public static final String ALIAS_COLLECTION_PROTOCOL = "CollectionProtocol"; public static final String ALIAS_BIOHAZARD = "Biohazard"; public static final String ALIAS_CANCER_RESEARCH_GROUP = "CancerResearchGroup"; public static final String ALIAS_COLLECTION_PROTOCOL_REG = "CollectionProtReg"; public static final String ALIAS_DEPARTMENT = "Department"; public static final String ALIAS_DISTRIBUTION = "Distribution"; public static final String ALIAS_DISTRIBUTION_PROTOCOL = "DistributionProtocol"; public static final String ALIAS_DISTRIBUTION_ARRAY = "Distribution_array"; public static final String ALIAS_INSTITUTE = "Institution"; public static final String ALIAS_PARTICIPANT = "Participant"; public static final String ALIAS_SITE = "Site"; public static final String ALIAS_SPECIMEN = "Specimen"; public static final String ALIAS_SPECIMEN_ARRAY = "SpecimenArray"; public static final String ALIAS_SPECIMEN_ARRAY_TYPE = "SpecimenArrayType"; public static final String ALIAS_SPECIMEN_COLLECTION_GROUP = "SpecimenCollectionGroup"; public static final String ALIAS_STORAGE_CONTAINER = "StorageContainer"; public static final String ALIAS_STORAGE_TYPE= "StorageType"; public static final String ALIAS_USER= "User"; public static final String PAGE_OF_BIOHAZARD = "pageOfBioHazard"; public static final String PAGE_OF_CANCER_RESEARCH_GROUP = "pageOfCancerResearchGroup"; public static final String PAGE_OF_COLLECTION_PROTOCOL = "pageOfCollectionProtocol"; public static final String PAGE_OF_COLLECTION_PROTOCOL_REG = "pageOfCollectionProtocolRegistration"; public static final String PAGE_OF_DEPARTMENT = "pageOfDepartment"; public static final String PAGE_OF_DISTRIBUTION = "pageOfDistribution"; public static final String PAGE_OF_DISTRIBUTION_PROTOCOL = "pageOfDistributionProtocol"; public static final String PAGE_OF_DISTRIBUTION_ARRAY = "pageOfArrayDistribution"; public static final String PAGE_OF_INSTITUTE = "pageOfInstitution"; public static final String PAGE_OF_PARTICIPANT = "pageOfParticipant"; public static final String PAGE_OF_SITE = "pageOfSite"; public static final String PAGE_OF_SPECIMEN = "pageOfSpecimen"; public static final String PAGE_OF_SPECIMEN_ARRAY = "pageOfSpecimenArray"; public static final String PAGE_OF_SPECIMEN_ARRAY_TYPE = "pageOfSpecimenArrayType"; public static final String PAGE_OF_SPECIMEN_COLLECTION_GROUP = "pageOfSpecimenCollectionGroup"; public static final String PAGE_OF_STORAGE_CONTAINER = "pageOfStorageContainer"; public static final String PAGE_OF_STORAGE_TYPE = "pageOfStorageType"; public static final String PAGE_OF_USER = "pageOfUserAdmin"; //Patch ID: Bug#4227_3 public static final String SUBMIT_AND_ADD_MULTIPLE = "submitAndAddMultiple"; //constants for Storage container map radio button identification Patch id: 4283_3 public static final int RADIO_BUTTON_VIRTUALLY_LOCATED=1; public static final int RADIO_BUTTON_FOR_MAP=3; // constant for putting blank screen in the framed pages public static final String BLANK_SCREEN_ACTION="blankScreenAction.do"; public static final String COLUMN_NAME_SPECIMEN_ID = "specimen.id"; public static final String PARTICIPANT_MEDICAL_IDENTIFIER="ParticipantMedicalIdentifier:"; public static final String PARTICIPANT_MEDICAL_IDENTIFIER_SITE_ID="_Site_id"; public static final String PARTICIPANT_MEDICAL_IDENTIFIER_MEDICAL_NUMBER="_medicalRecordNumber"; public static final String PARTICIPANT_MEDICAL_IDENTIFIER_ID="_id"; public static final String COLUMN_NAME_SPECIEMEN_REQUIREMENT_COLLECTION="elements(specimenRequirementCollection)"; public static final String COLUMN_NAME_PARTICIPANT="participant"; public static final String ADDNEW_LINK="AddNew"; public static final String COLUMN_NAME_STORAGE_CONTAINER = "storageContainer"; public static final String COLUMN_NAME_SCG_CPR_CP_ID = "specimenCollectionGroup.collectionProtocolRegistration.collectionProtocol.id"; public static final String COLUMN_NAME_CPR_CP_ID = "collectionProtocolRegistration.collectionProtocol.id"; public static final String EQUALS = "="; public static final String COLUMN_NAME_SCG_NAME = "specimenCollectionGroup.name"; public static final String COLUMN_NAME_SPECIMEN = "specimen"; public static final String COLUMN_NAME_SCG = "specimenCollectionGroup"; public static final String COLUMN_NAME_CHILDREN = "elements(children)"; public static final String COLUMN_NAME_SCG_ID="specimenCollectionGroup.id"; public static final String COLUMN_NAME_PART_MEDICAL_ID_COLL="elements(participantMedicalIdentifierCollection)"; public static final String COLUMN_NAME_PART_RACE_COLL="elements(raceCollection)"; public static final String COLUMN_NAME_CPR_COLL="elements(collectionProtocolRegistrationCollection)"; public static final String COLUMN_NAME_SCG_COLL="elements(specimenCollectionGroupCollection)"; public static final String COLUMN_NAME_COLL_PROT_EVENT_COLL="elements(collectionProtocolEventCollection)"; public static final String COLUMN_NAME_CONCEPT_REF_COLL="elements(conceptReferentCollection)"; public static final String COLUMN_NAME_DEID_REPORT="deIdentifiedSurgicalPathologyReport"; public static final String COLUMN_NAME_REPORT_SOURCE="reportSource"; public static final String COLUMN_NAME_TEXT_CONTENT="textContent"; public static final String COLUMN_NAME_TITLE="title"; public static final String COLUMN_NAME_PARTICIPANT_ID = "participant.id"; public static final String COLUMN_NAME_REPORT_SECTION_COLL="elements(reportSectionCollection)"; public static final String COLUMN_NAME_SCG_SITE="specimenCollectionSite"; public static final String COLUMN_NAME_STATUS="status"; public static final String COLUMN_NAME_CPR="collectionProtocolRegistration"; public static final String COLUMN_NAME_COLL_PROT_EVENT="collectionProtocolEvent"; public static final String COLUMN_NAME_SCG_CPR_PARTICIPANT_ID="specimenCollectionGroup.collectionProtocolRegistration.participant.id"; //Bug 2833. Field for the length of CP Title public static final int COLLECTION_PROTOCOL_TITLE_LENGTH=30; //Bug ID 4794: Field for advance time to warn a user about session expiry public static final String SESSION_EXPIRY_WARNING_ADVANCE_TIME = "session.expiry.warning.advanceTime"; // Constants required in RequestDetailsPage public static final String SUBMIT_REQUEST_DETAILS_ACTION="SubmitRequestDetails.do"; public static final String REQUEST_HEADER_OBJECT = "requestHeaderObject"; public static final String SITE_LIST_OBJECT = "siteList"; public static final String REQUEST_DETAILS_PAGE = "RequestDetails.do"; public static final String ARRAYREQUEST_DETAILS_PAGE = "ArrayRequests.do"; public static final String ARRAY_REQUESTS_LIST = "arrayRequestsList"; public static final String EXISISTINGARRAY_REQUESTS_LIST = "existingArrayRequestDetailsList"; public static final String DEFINEDARRAY_REQUESTS_LIST = "DefinedRequestDetailsMapList"; public static final String ITEM_STATUS_LIST="itemsStatusList"; public static final String ITEM_STATUS_LIST_WO_DISTRIBUTE="itemsStatusListWithoutDistribute"; public static final String ITEM_STATUS_LIST_FOR_ITEMS_IN_ARRAY="itemsStatusListForItemsInArray"; public static final String REQUEST_FOR_LIST="requestForList"; // Constants for Order Request Status. public static final String ORDER_REQUEST_STATUS_NEW = "New"; public static final String ORDER_REQUEST_STATUS_PENDING_PROTOCOL_REVIEW = "Pending - Protocol Review"; public static final String ORDER_REQUEST_STATUS_PENDING_SPECIMEN_PREPARATION = "Pending - Specimen Preparation"; public static final String ORDER_REQUEST_STATUS_PENDING_FOR_DISTRIBUTION = "Pending - For Distribution"; public static final String ORDER_REQUEST_STATUS_REJECTED_INAPPROPRIATE_REQUEST = "Rejected - Inappropriate Request"; public static final String ORDER_REQUEST_STATUS_REJECTED_SPECIMEN_UNAVAILABLE = "Rejected - Specimen Unavailable"; public static final String ORDER_REQUEST_STATUS_REJECTED_UNABLE_TO_CREATE = "Rejected - Unable to Create"; public static final String ORDER_REQUEST_STATUS_DISTRIBUTED = "Distributed"; public static final String ORDER_REQUEST_STATUS_READY_FOR_ARRAY_PREPARATION = "Ready For Array Preparation"; // Used for tree display in RequestDetails page public static final String TREE_DATA_LIST = "treeDataList"; //Constants for Order Status public static final String ORDER_STATUS_NEW = "New"; public static final String ORDER_STATUS_PENDING = "Pending"; public static final String ORDER_STATUS_REJECTED = "Rejected"; public static final String ORDER_STATUS_COMPLETED = "Completed"; // Ordering System Status public static final String CDE_NAME_REQUEST_STATUS="Request Status"; public static final String CDE_NAME_REQUESTED_ITEMS_STATUS="Requested Items Status"; public static final String REQUEST_LIST="requestStatusList"; public static final String REQUESTED_ITEMS_STATUS_LIST="requestedItemsStatusList"; public static final String ARRAY_STATUS_LIST="arrayStatusList"; public static final String REQUEST_OBJECT="requestObjectList"; public static final String REQUEST_DETAILS_LIST="requestDetailsList"; public static final String ARRAY_REQUESTS_BEAN_LIST="arrayRequestsBeanList"; public static final String SPECIMEN_ORDER_FORM_TYPE = "specimen"; public static final String ARRAY_ORDER_FORM_TYPE = "specimenArray"; public static final String PATHOLOGYCASE_ORDER_FORM_TYPE="pathologyCase"; public static final String REQUESTED_BIOSPECIMENS="RequestedBioSpecimens"; //Constants required in Ordering System. public static final String ACTION_ORDER_LIST = "OrderExistingSpecimen.do"; public static final String SPECIMEN_TREE_SPECIMEN_ID = "specimenId"; public static final String SPECIMEN_TREE_SPECCOLLGRP_ID = "specimenCollGrpId"; public static final String ACTION_REMOVE_ORDER_ITEM = "AddToOrderListSpecimen.do?remove=yes"; public static final String ACTION_REMOVE_ORDER_ITEM_ARRAY = "AddToOrderListArray.do?remove=yes"; public static final String ACTION_REMOVE_ORDER_ITEM_PATHOLOGYCASE = "AddToOrderListPathologyCase.do?remove=yes"; public static final String DEFINEARRAY_REQUESTMAP_LIST = "definedArrayRequestMapList"; public static final String CREATE_DEFINED_ARRAY = "CreateDefinedArray.do"; public static final String ACTION_SAVE_ORDER_ITEM = "SaveOrderItems.do"; public static final String ORDERTO_LIST_ARRAY = "orderToListArrayList"; public static final String ACTION_SAVE_ORDER_ARRAY_ITEM = "SaveOrderArrayItems.do"; public static final String ACTION_SAVE_ORDER_PATHOLOGY_ITEM="SaveOrderPathologyItems.do"; public static final String ACTION_ADD_ORDER_SPECIMEN_ITEM="AddToOrderListSpecimen.do"; public static final String ACTION_ADD_ORDER_ARRAY_ITEM="AddToOrderListArray.do"; public static final String ACTION_ADD_ORDER_PATHOLOGY_ITEM="AddToOrderListPathologyCase.do"; public static final String ACTION_DEFINE_ARRAY="DefineArraySubmit.do"; public static final String ACTION_ORDER_SPECIMEN="OrderExistingSpecimen.do"; public static final String ACTION_ORDER_BIOSPECIMENARRAY="OrderBiospecimenArray.do"; public static final String ACTION_ORDER_PATHOLOGYCASE="OrderPathologyCase.do"; //Specimen Label generation realted constants public static final String PARENT_SPECIMEN_ID_KEY="parentSpecimenID"; public static final String PARENT_SPECIMEN_LABEL_KEY="parentSpecimenLabel"; public static final String SCG_NAME_KEY="SCGName"; //ordering system public static final String TAB_INDEX_ID="tabIndexId"; public static final String FORWARD_TO_HASHMAP="forwardToHashMap"; public static final String SELECTED_COLLECTION_PROTOCOL_ID = "0"; public static final String LIST_OF_SPECIMEN_COLLECTION_GROUP = "specimenCollectionGroupResponseList"; public static final String PARTICIPANT_PROTOCOL_ID="participantProtocolId"; // caTIES public static final String CONCEPT_REFERENT_CLASSIFICATION_LIST = "conceptRefernetClassificationList"; public static final String CONCEPT_LIST = "conceptList"; public static final String[] CATEGORY_HIGHLIGHTING_COLOURS = {"#ff6d5f","#db9fe5","#2dcc00","#69bbf7","#f8e754"}; public static final String CONCEPT_BEAN_LIST = "conceptBeanList"; //Admin View public static final String IDENTIFIER_NO=" public static final String REQUEST_DATE="Request Date"; public static final String USER_NAME_ADMIN_VIEW="User Name"; public static final String SCG_NAME="Specimen Collection Group"; public static final String ACCESSION_NO="Accession Number"; public static final String PAGEOF_REVIEW_SPR="pageOfReviewSPR"; public static final String PAGEOF_QUARANTINE_SPR="pageOfQuarantineSPR"; public static final String SITE="Site"; public static final String REQUEST_FOR="requestFor"; public static final String REPORT_ACTION="reportAction"; public static final String REPORT_STATUS_LIST="reportStatusList"; public static final String COLUMN_LIST="columnList"; public static final String NO_PENDING_REQUEST="noPendingRequest"; //Surgical Pathology Report UI constants public static final String VIEW_SPR_ACTION="ViewSurgicalPathologyReport.do"; public static final String SPR_EVENT_PARAM_ACTION="SurgicalPathologyReportEventParam.do"; public static final String VIEW_SURGICAL_PATHOLOGY_REPORT="viewSPR"; public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP="pageOfSpecimenCollectionGroup"; public static final String PAGEOF_PARTICIPANT="pageOfParticipant"; public static final String PAGEOF_NEW_SPECIMEN="pageOfNewSpecimen"; public static final String REVIEW="review"; public static final String QUARANTINE="quarantine"; public static final String COMMENT_STATUS_RENDING="PENDING"; public static final String COMMENT_STATUS_REVIEWED="REVIEWED"; public static final String COMMENT_STATUS_REPLIED="REPLIED"; public static final String COMMENT_STATUS_NOT_REVIEWED="NOT_REVIEWED"; public static final String COMMENT_STATUS_QUARANTINED="QUARANTINED"; public static final String COMMENT_STATUS_NOT_QUARANTINED="DEQUARANTINED"; public static final String ROLE_ADMINISTRATOR="Administrator"; public static final String REPORT_LIST="reportIdList"; public static final String QUARANTINE_REQUEST="QUARANTINEREQUEST"; public static final String IDENTIFIED_REPORT_NOT_FOUND_MSG="Indentified Report Not Found!"; public static final String DEID_REPORT_NOT_FOUND_MSG="De-Indentified Report Not Found!"; // Local extensions constants public static final String LOCAL_EXT="localExt"; public static final String LINK="link"; public static final String LOAD_INTEGRATION_PAGE="loadIntegrationPage"; public static final String DEFINE_ENTITY = "defineEntity"; public static final String SELECTED_ENTITY_ID="selectedStaticEntityId"; public static final String CONTAINER_NAME="containerName"; public static final String STATIC_ENTITY_NAME = "staticEntityName"; public static final String SPREADSHEET_DATA_GROUP="spreadsheetDataGroup"; public static final String SPREADSHEET_DATA_ENTITY="spreadsheetDataEntity"; public static final String SPREADSHEET_DATA_RECORD="spreadsheetDataRecord"; public static final String TITLE = "title"; //clinportal constants public static final int CLINICALSTUDY_FORM_ID = 65; public static final int CLINICAL_STUDY_REGISTRATION_FORM_ID=66; // Save query constant public static final int CATISSUECORE_QUERY_INTERFACE_ID = 67; //Ordering constants public static final String ARRAY_NAME = "array"; //Query Shopping cart constants public static final String SHOPPING_CART_FILE_NAME = "MyList.csv"; public static final String DUPLICATE_OBJECT = "duplicateObject"; public static final String DIFFERENT_VIEW_IN_CART = "differentCartView"; public static final String IS_SPECIMENID_PRESENT = "isSpecimenIdPresent"; public static final String IS_SPECIMENARRAY_PRESENT = "isSpecimenArrayPresent"; // Constants for CP Based Entry public static final String COLLECTION_PROTOCOL_EVENT_ID = "Event_Id"; public static final String SPECIMEN_LIST_SESSION_MAP = "SpecimenListBean"; public static final String COLLECTION_PROTOCOL_EVENT_SESSION_MAP = "collectionProtocolEventMap"; public static final String COLLECTION_PROTOCOL_SESSION_BEAN = "collectionProtocolBean"; public static final String EDIT_SPECIMEN_REQUIREMENT_BEAN ="EditSpecimenRequirementBean"; public static final String VIEW_SUMMARY ="ViewSummary"; public static final String EVENT_KEY ="key"; public static final String TREE_NODE_ID ="nodeId"; public static final String PAGE_OF_DEFINE_EVENTS = "defineEvents"; public static final String PAGE_OF_ADD_NEW_EVENT = "newEvent"; public static final String PAGE_OF_SPECIMEN_REQUIREMENT = "specimenRequirement"; public static final String ADD_NEW_EVENT = "-1"; public static final String NEW_EVENT_KEY = "listKey"; public static final String LINEAGE_NEW_SPECIMEN = "New Specimen"; public static final String UNIQUE_IDENTIFIER_FOR_DERIVE = "_D"; public static final String UNIQUE_IDENTIFIER_FOR_ALIQUOT = "_A"; public static final String UNIQUE_IDENTIFIER_FOR_NEW_SPECIMEN = "_S"; public static final String UNIQUE_IDENTIFIER_FOR_EVENTS = "E"; /* * Conflict resolver constants * */ public static final String [] CONFLICT_LIST_HEADER = { "Participant name", "ID", "Surgical pathological number", "Report loaded on", "Status", "Site Name", "Report Collection Date" }; public static final String [] CONFLICT_FILTER_LIST = { "All", "Ambiguous Participants", "Ambiguous Specimen Collection Groups" }; public static final String FILTER_LIST = "filterList"; public static final String REPORT_ID = "reportQueueId"; public static final String CONFLICT_STATUS = "conflictStatus"; public static final String REPORT_INFORMATION = "ReportInformation"; public static final String SELECTED_FILTER = "selectedFilter"; public static final String CONFLICT_COMMON_VIEW="conflictCommonView"; public static final String CONFLICT_TREE_VIEW="conflictTreeView"; public static final String CONFLICT_DATA_VIEW="conflictDataView"; public static final String CONFLICT_COMMON_VIEW_ACTION="ConflictCommon.do"; public static final String CONFLICT_TREE_VIEW_ACTION="ConflictParticipantSCGTree.do"; public static final String CONFLICT_DATA_VIEW_ACTION="ConflictParticipantDataDetails.do"; public static final String SURGICAL_PATHOLOGY_NUMBER="surgicalPathologyNumber"; public static final String REPORT_DATE="reportDate"; public static final String SITE_NAME = "siteName"; public static final String PARTICIPANT_NAME = "participantName"; public static final String COLUMN_NAME_PART_COLL="elements(participantCollection)"; public static final String PARTICIPANT_ID_TO_ASSOCIATE = "participantIdToAssociate"; public static final String SCG_ID_TO_ASSOCIATE = "scgIdToAssociate"; public static final String REPORT_QUEUE_LIST = "ReportQueueList"; public static final String USE_SELECTED_PARTICIPANT = "createNewSCG"; public static final String USE_SELECTED_SCG = "associateSCG"; public static final String CREATE_NEW_PARTICIPANT = "creatNewParticipant"; public static final String OVERWRITE_REPORT = "overwriteReport"; public static final String IGNORE_NEW_REPORT = "ignoreNewReport"; public static final String CONFLICT_BUTTON = "conflictButton"; public static final String IDENTIFIED_SURGICAL_PATHOLOGY_REPORT = "identifiedSurgicalPathologyReport"; public static final String REPORT_COLLECTION_DATE = "reportCollectionDate"; //Save Query Constants public static final String HTML_CONTENTS = "HTMLContents"; public static final String SHOW_ALL= "showall"; public static final String SHOW_ALL_ATTRIBUTE = "Show all attributes"; public static final String SHOW_SELECTED_ATTRIBUTE = "Show selected attributes"; public static final String ADD_EDIT_PAGE ="Add Edit Page"; public static final String SAVE_QUERY_PAGE ="Save Query Page"; public static final String EXECUTE_QUERY_PAGE ="Execute Query Page"; public static final String FETCH_QUERY_ACTION ="FetchQuery.do"; public static final String EXECUTE_QUERY_ACTION ="ExecuteQueryAction.do"; public static final String EXECUTE_QUERY = "executeQuery"; public static final String INVALID_CONDITION_VALUES ="InvalidValues"; // Save Query Constants ends public static final String NEW_SPECIMEN_TYPE = "New_Specimen"; public static final String DERIVED_SPECIMEN_TYPE = "Derived_Specimen"; public static final String SPECIMEN_LABEL_GENERATOR_PROPERTY_NAME="specimenLabelGeneratorClass"; public static final String SPECIMEN_BARCODE_GENERATOR_PROPERTY_NAME="specimenBarcodeGeneratorClass"; public static final String STORAGECONTAINER_LABEL_GENERATOR_PROPERTY_NAME="storageContainerLabelGeneratorClass"; public static final String STORAGECONTAINER_BARCODE_GENERATOR_PROPERTY_NAME="storageContainerBarcodeGeneratorClass"; public static final String SPECIMEN_COLL_GROUP_LABEL_GENERATOR_PROPERTY_NAME="speicmenCollectionGroupLabelGeneratorClass"; //SPECIMEN COllection Status public static final String SPECIMEN_COLLECTED = "Collected"; public static final String SPECIMEN_ANTICOPATED = "Anticipated"; //Shopping cart constants. public static final String SPECIMEN_ARRAY_CLASS_NAME = SpecimenArray.class.getName(); public static final String IDENTIFIED_SURGICAL_PATHALOGY_REPORT_CLASS_NAME = IdentifiedSurgicalPathologyReport.class.getName(); public static final String DEIDENTIFIED_SURGICAL_PATHALOGY_REPORT_CLASS_NAME = DeidentifiedSurgicalPathologyReport.class.getName(); public static final String SURGICAL_PATHALOGY_REPORT_CLASS_NAME = SurgicalPathologyReport.class.getName(); public static final String SPECIMEN_NAME = Specimen.class.getName(); public static final String[] specimenNameArray = { SPECIMEN_NAME, FluidSpecimen.class.getName(), MolecularSpecimen.class.getName(), TissueSpecimen.class.getName(), CellSpecimen.class.getName() }; public static final String[] entityNameArray = { SPECIMEN_NAME, FluidSpecimen.class.getName(), MolecularSpecimen.class.getName(), TissueSpecimen.class.getName(), CellSpecimen.class.getName(), SPECIMEN_ARRAY_CLASS_NAME, IDENTIFIED_SURGICAL_PATHALOGY_REPORT_CLASS_NAME, DEIDENTIFIED_SURGICAL_PATHALOGY_REPORT_CLASS_NAME, SURGICAL_PATHALOGY_REPORT_CLASS_NAME }; public static final String IDENTIFIED_REPORT_ID="identifiedReportId"; public static final String BULK_TRANSFERS = "bulkTransfers"; public static final String BULK_DISPOSALS = "bulkDisposals"; public static final String EDIT_MULTIPLE_SPECIMEN = "editMultipleSp"; public static final int CATISSUE_ENTITY_GROUP = 1; //Query-CSM related constants public static final String QUERY_REASUL_OBJECT_DATA_MAP = "queryReasultObjectDataMap"; public static final String DEFINE_VIEW_QUERY_REASULT_OBJECT_DATA_MAP = "defineViewQueryReasultObjectDataMap"; public static final String HAS_CONDITION_ON_IDENTIFIED_FIELD = "hasConditionOnIdentifiedField"; public static final String CONTAINTMENT_ASSOCIATION = "CONTAINTMENT"; public static final String MAIN_ENTITY_MAP = "mainEntityMap"; public static final String PAGEOF_SPECIMEN_COLLECTION_REQUIREMENT_GROUP = "pageOfSpecimenCollectionRequirementGroup"; public static final String NO_MAIN_OBJECT_IN_QUERY = "noMainObjectInQuery"; }
package com.jme3.renderer.android; import android.opengl.GLES10; import android.opengl.GLES20; import android.os.Build; import com.jme3.asset.AndroidImageInfo; import com.jme3.light.LightList; import com.jme3.material.RenderState; import com.jme3.math.*; import com.jme3.renderer.*; import com.jme3.scene.Mesh; import com.jme3.scene.Mesh.Mode; import com.jme3.scene.VertexBuffer; import com.jme3.scene.VertexBuffer.Format; import com.jme3.scene.VertexBuffer.Type; import com.jme3.scene.VertexBuffer.Usage; import com.jme3.shader.Attribute; import com.jme3.shader.Shader; import com.jme3.shader.Shader.ShaderSource; import com.jme3.shader.Shader.ShaderType; import com.jme3.shader.Uniform; import com.jme3.texture.FrameBuffer; import com.jme3.texture.FrameBuffer.RenderBuffer; import com.jme3.texture.Image; import com.jme3.texture.Texture; import com.jme3.texture.Texture.WrapAxis; import com.jme3.util.BufferUtils; import com.jme3.util.ListMap; import com.jme3.util.NativeObjectManager; import java.nio.*; import java.util.EnumSet; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import jme3tools.shader.ShaderDebug; public class OGLESShaderRenderer implements Renderer { private static final Logger logger = Logger.getLogger(OGLESShaderRenderer.class.getName()); private static final boolean VALIDATE_SHADER = false; private final ByteBuffer nameBuf = BufferUtils.createByteBuffer(250); private final StringBuilder stringBuf = new StringBuilder(250); private final IntBuffer intBuf1 = BufferUtils.createIntBuffer(1); private final IntBuffer intBuf16 = BufferUtils.createIntBuffer(16); private final RenderContext context = new RenderContext(); private final NativeObjectManager objManager = new NativeObjectManager(); private final EnumSet<Caps> caps = EnumSet.noneOf(Caps.class); // current state private Shader boundShader; // private int initialDrawBuf, initialReadBuf; private int glslVer; private int vertexTextureUnits; private int fragTextureUnits; private int vertexUniforms; private int fragUniforms; private int vertexAttribs; // private int maxFBOSamples; // private int maxFBOAttachs; // private int maxMRTFBOAttachs; // private int maxRBSize; private int maxTexSize; private int maxCubeTexSize; private int maxVertCount; private int maxTriCount; private boolean tdc; // private FrameBuffer lastFb = null; private final Statistics statistics = new Statistics(); private int vpX, vpY, vpW, vpH; private int clipX, clipY, clipW, clipH; //private final GL10 gl; private boolean powerVr = false; private boolean useVBO = false; public OGLESShaderRenderer() { } protected void updateNameBuffer() { int len = stringBuf.length(); nameBuf.position(0); nameBuf.limit(len); for (int i = 0; i < len; i++) { nameBuf.put((byte) stringBuf.charAt(i)); } nameBuf.rewind(); } private void checkGLError() { int error; while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) { throw new RendererException("OpenGL Error " + error); } } public Statistics getStatistics() { return statistics; } public EnumSet<Caps> getCaps() { return caps; } private int extractVersion(String prefixStr, String versionStr) { if (versionStr != null) { int spaceIdx = versionStr.indexOf(" ", prefixStr.length()); if (spaceIdx >= 1) { versionStr = versionStr.substring(prefixStr.length(), spaceIdx).trim(); } else { versionStr = versionStr.substring(prefixStr.length()).trim(); } float version = Float.parseFloat(versionStr); return (int) (version * 100); } else { return -1; } } public void initialize() { logger.log(Level.INFO, "Vendor: {0}", GLES20.glGetString(GLES20.GL_VENDOR)); logger.log(Level.INFO, "Renderer: {0}", GLES20.glGetString(GLES20.GL_RENDERER)); logger.log(Level.INFO, "Version: {0}", GLES20.glGetString(GLES20.GL_VERSION)); logger.log(Level.INFO, "Shading Language Version: {0}", GLES20.glGetString(GLES20.GL_SHADING_LANGUAGE_VERSION)); powerVr = GLES20.glGetString(GLES20.GL_RENDERER).contains("PowerVR"); // Fix issue in TestRenderToMemory when GL_FRONT is the main // buffer being used. // initialDrawBuf = GLES20.glGetIntegeri(GLES20.GL_DRAW_BUFFER); // initialReadBuf = GLES20.glGetIntegeri(GLES20.GL_READ_BUFFER); // Check OpenGL version int openGlVer = extractVersion("OpenGL ES ", GLES20.glGetString(GLES20.GL_VERSION)); if (openGlVer == -1) { glslVer = -1; throw new UnsupportedOperationException("OpenGL ES 2.0+ is required for OGLESShaderRenderer!"); } // Check shader language version glslVer = extractVersion("OpenGL ES GLSL ES ", GLES20.glGetString(GLES20.GL_SHADING_LANGUAGE_VERSION)); switch (glslVer) { // TODO: When new versions of OpenGL ES shader language come out, // update this. default: caps.add(Caps.GLSL100); break; } GLES20.glGetIntegerv(GLES20.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, intBuf16); vertexTextureUnits = intBuf16.get(0); logger.log(Level.INFO, "VTF Units: {0}", vertexTextureUnits); if (vertexTextureUnits > 0) { caps.add(Caps.VertexTextureFetch); } GLES20.glGetIntegerv(GLES20.GL_MAX_TEXTURE_IMAGE_UNITS, intBuf16); fragTextureUnits = intBuf16.get(0); logger.log(Level.INFO, "Texture Units: {0}", fragTextureUnits); // Multiply vector count by 4 to get float count. GLES20.glGetIntegerv(GLES20.GL_MAX_VERTEX_UNIFORM_VECTORS, intBuf16); vertexUniforms = intBuf16.get(0) * 4; logger.log(Level.FINER, "Vertex Uniforms: {0}", vertexUniforms); GLES20.glGetIntegerv(GLES20.GL_MAX_FRAGMENT_UNIFORM_VECTORS, intBuf16); fragUniforms = intBuf16.get(0) * 4; logger.log(Level.FINER, "Fragment Uniforms: {0}", fragUniforms); GLES20.glGetIntegerv(GLES20.GL_MAX_VARYING_VECTORS, intBuf16); int varyingFloats = intBuf16.get(0) * 4; logger.log(Level.FINER, "Varying Floats: {0}", varyingFloats); GLES20.glGetIntegerv(GLES20.GL_MAX_VERTEX_ATTRIBS, intBuf16); vertexAttribs = intBuf16.get(0); logger.log(Level.INFO, "Vertex Attributes: {0}", vertexAttribs); GLES20.glGetIntegerv(GLES20.GL_SUBPIXEL_BITS, intBuf16); int subpixelBits = intBuf16.get(0); logger.log(Level.INFO, "Subpixel Bits: {0}", subpixelBits); // GLES10.glGetIntegerv(GLES10.GL_MAX_ELEMENTS_VERTICES, intBuf16); // maxVertCount = intBuf16.get(0); // logger.log(Level.FINER, "Preferred Batch Vertex Count: {0}", maxVertCount); // GLES10.glGetIntegerv(GLES10.GL_MAX_ELEMENTS_INDICES, intBuf16); // maxTriCount = intBuf16.get(0); // logger.log(Level.FINER, "Preferred Batch Index Count: {0}", maxTriCount); GLES20.glGetIntegerv(GLES20.GL_MAX_TEXTURE_SIZE, intBuf16); maxTexSize = intBuf16.get(0); logger.log(Level.INFO, "Maximum Texture Resolution: {0}", maxTexSize); GLES20.glGetIntegerv(GLES20.GL_MAX_CUBE_MAP_TEXTURE_SIZE, intBuf16); maxCubeTexSize = intBuf16.get(0); logger.log(Level.INFO, "Maximum CubeMap Resolution: {0}", maxCubeTexSize); /* if (ctxCaps.GL_ARB_color_buffer_float){ // XXX: Require both 16 and 32 bit float support for FloatColorBuffer. if (ctxCaps.GL_ARB_half_float_pixel){ caps.add(Caps.FloatColorBuffer); } } if (ctxCaps.GL_ARB_depth_buffer_float){ caps.add(Caps.FloatDepthBuffer); } if (ctxCaps.GL_ARB_draw_instanced) caps.add(Caps.MeshInstancing); if (ctxCaps.GL_ARB_texture_buffer_object) caps.add(Caps.TextureBuffer); if (ctxCaps.GL_ARB_texture_float){ if (ctxCaps.GL_ARB_half_float_pixel){ caps.add(Caps.FloatTexture); } } if (ctxCaps.GL_EXT_packed_float){ caps.add(Caps.PackedFloatColorBuffer); if (ctxCaps.GL_ARB_half_float_pixel){ // because textures are usually uploaded as RGB16F // need half-float pixel caps.add(Caps.PackedFloatTexture); } } if (ctxCaps.GL_EXT_texture_array) caps.add(Caps.TextureArray); if (ctxCaps.GL_EXT_texture_shared_exponent) caps.add(Caps.SharedExponentTexture); if (ctxCaps.GL_EXT_framebuffer_object){ caps.add(Caps.FrameBuffer); glGetInteger(GL_MAX_RENDERBUFFER_SIZE_EXT, intBuf16); maxRBSize = intBuf16.get(0); logger.log(Level.FINER, "FBO RB Max Size: {0}", maxRBSize); glGetInteger(GL_MAX_COLOR_ATTACHMENTS_EXT, intBuf16); maxFBOAttachs = intBuf16.get(0); logger.log(Level.FINER, "FBO Max renderbuffers: {0}", maxFBOAttachs); if (ctxCaps.GL_EXT_framebuffer_multisample){ caps.add(Caps.FrameBufferMultisample); glGetInteger(GL_MAX_SAMPLES_EXT, intBuf16); maxFBOSamples = intBuf16.get(0); logger.log(Level.FINER, "FBO Max Samples: {0}", maxFBOSamples); } if (ctxCaps.GL_ARB_draw_buffers){ caps.add(Caps.FrameBufferMRT); glGetInteger(ARBDrawBuffers.GL_MAX_DRAW_BUFFERS_ARB, intBuf16); maxMRTFBOAttachs = intBuf16.get(0); logger.log(Level.FINER, "FBO Max MRT renderbuffers: {0}", maxMRTFBOAttachs); } } if (ctxCaps.GL_ARB_multisample){ glGetInteger(ARBMultisample.GL_SAMPLE_BUFFERS_ARB, intBuf16); boolean available = intBuf16.get(0) != 0; glGetInteger(ARBMultisample.GL_SAMPLES_ARB, intBuf16); int samples = intBuf16.get(0); logger.log(Level.FINER, "Samples: {0}", samples); boolean enabled = glIsEnabled(ARBMultisample.GL_MULTISAMPLE_ARB); if (samples > 0 && available && !enabled){ glEnable(ARBMultisample.GL_MULTISAMPLE_ARB); } } */ String extensions = GLES20.glGetString(GLES20.GL_EXTENSIONS); logger.log(Level.INFO, "GL_EXTENSIONS: {0}", extensions); GLES20.glGetIntegerv(GLES20.GL_COMPRESSED_TEXTURE_FORMATS, intBuf16); for (int i = 0; i < intBuf16.limit(); i++) { logger.log(Level.INFO, "Compressed Texture Formats: {0}", intBuf16.get(i)); } TextureUtil.loadTextureFeatures(extensions); applyRenderState(RenderState.DEFAULT); GLES20.glDisable(GLES20.GL_DITHER); useVBO = false; // NOTE: SDK_INT is only available since 1.6, // but for jME3 it doesn't matter since android versions 1.5 and below // are not supported. if (Build.VERSION.SDK_INT >= 9){ logger.log(Level.INFO, "Force-enabling VBO (Android 2.3 or higher)"); useVBO = true; } else { useVBO = false; } logger.log(Level.INFO, "Caps: {0}", caps); } /** * <code>resetGLObjects</code> should be called when die GLView gets recreated to reset all GPU objects */ public void resetGLObjects() { objManager.resetObjects(); statistics.clearMemory(); boundShader = null; // lastFb = null; context.reset(); } public void cleanup() { objManager.deleteAllObjects(this); statistics.clearMemory(); } private void checkCap(Caps cap) { if (!caps.contains(cap)) { throw new UnsupportedOperationException("Required capability missing: " + cap.name()); } } public void setDepthRange(float start, float end) { GLES20.glDepthRangef(start, end); } public void clearBuffers(boolean color, boolean depth, boolean stencil) { int bits = 0; if (color) { bits = GLES20.GL_COLOR_BUFFER_BIT; } if (depth) { bits |= GLES20.GL_DEPTH_BUFFER_BIT; } if (stencil) { bits |= GLES20.GL_STENCIL_BUFFER_BIT; } if (bits != 0) { GLES20.glClear(bits); } } public void setBackgroundColor(ColorRGBA color) { GLES20.glClearColor(color.r, color.g, color.b, color.a); } public void applyRenderState(RenderState state) { /* if (state.isWireframe() && !context.wireframe){ GLES20.glPolygonMode(GLES20.GL_FRONT_AND_BACK, GLES20.GL_LINE); context.wireframe = true; }else if (!state.isWireframe() && context.wireframe){ GLES20.glPolygonMode(GLES20.GL_FRONT_AND_BACK, GLES20.GL_FILL); context.wireframe = false; } */ if (state.isDepthTest() && !context.depthTestEnabled) { GLES20.glEnable(GLES20.GL_DEPTH_TEST); GLES20.glDepthFunc(GLES20.GL_LEQUAL); context.depthTestEnabled = true; } else if (!state.isDepthTest() && context.depthTestEnabled) { GLES20.glDisable(GLES20.GL_DEPTH_TEST); context.depthTestEnabled = false; } if (state.isAlphaTest() && !context.alphaTestEnabled) { // GLES20.glEnable(GLES20.GL_ALPHA_TEST); // GLES20.glAlphaFunc(GLES20.GL_GREATER, state.getAlphaFallOff()); context.alphaTestEnabled = true; } else if (!state.isAlphaTest() && context.alphaTestEnabled) { // GLES20.glDisable(GLES20.GL_ALPHA_TEST); context.alphaTestEnabled = false; } if (state.isDepthWrite() && !context.depthWriteEnabled) { GLES20.glDepthMask(true); context.depthWriteEnabled = true; } else if (!state.isDepthWrite() && context.depthWriteEnabled) { GLES20.glDepthMask(false); context.depthWriteEnabled = false; } if (state.isColorWrite() && !context.colorWriteEnabled) { GLES20.glColorMask(true, true, true, true); context.colorWriteEnabled = true; } else if (!state.isColorWrite() && context.colorWriteEnabled) { GLES20.glColorMask(false, false, false, false); context.colorWriteEnabled = false; } if (state.isPointSprite() && !context.pointSprite) { // GLES20.glEnable(GLES20.GL_POINT_SPRITE); // GLES20.glTexEnvi(GLES20.GL_POINT_SPRITE, GLES20.GL_COORD_REPLACE, GLES20.GL_TRUE); // GLES20.glEnable(GLES20.GL_VERTEX_PROGRAM_POINT_SIZE); // GLES20.glPointParameterf(GLES20.GL_POINT_SIZE_MIN, 1.0f); } else if (!state.isPointSprite() && context.pointSprite) { // GLES20.glDisable(GLES20.GL_POINT_SPRITE); } if (state.isPolyOffset()) { if (!context.polyOffsetEnabled) { GLES20.glEnable(GLES20.GL_POLYGON_OFFSET_FILL); GLES20.glPolygonOffset(state.getPolyOffsetFactor(), state.getPolyOffsetUnits()); context.polyOffsetEnabled = true; context.polyOffsetFactor = state.getPolyOffsetFactor(); context.polyOffsetUnits = state.getPolyOffsetUnits(); } else { if (state.getPolyOffsetFactor() != context.polyOffsetFactor || state.getPolyOffsetUnits() != context.polyOffsetUnits) { GLES20.glPolygonOffset(state.getPolyOffsetFactor(), state.getPolyOffsetUnits()); context.polyOffsetFactor = state.getPolyOffsetFactor(); context.polyOffsetUnits = state.getPolyOffsetUnits(); } } } else { if (context.polyOffsetEnabled) { GLES20.glDisable(GLES20.GL_POLYGON_OFFSET_FILL); context.polyOffsetEnabled = false; context.polyOffsetFactor = 0; context.polyOffsetUnits = 0; } } if (state.getFaceCullMode() != context.cullMode) { if (state.getFaceCullMode() == RenderState.FaceCullMode.Off) { GLES20.glDisable(GLES20.GL_CULL_FACE); } else { GLES20.glEnable(GLES20.GL_CULL_FACE); } switch (state.getFaceCullMode()) { case Off: break; case Back: GLES20.glCullFace(GLES20.GL_BACK); break; case Front: GLES20.glCullFace(GLES20.GL_FRONT); break; case FrontAndBack: GLES20.glCullFace(GLES20.GL_FRONT_AND_BACK); break; default: throw new UnsupportedOperationException("Unrecognized face cull mode: " + state.getFaceCullMode()); } context.cullMode = state.getFaceCullMode(); } if (state.getBlendMode() != context.blendMode) { if (state.getBlendMode() == RenderState.BlendMode.Off) { GLES20.glDisable(GLES20.GL_BLEND); } else { GLES20.glEnable(GLES20.GL_BLEND); switch (state.getBlendMode()) { case Off: break; case Additive: GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE); break; case AlphaAdditive: GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE); break; case Color: GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_COLOR); break; case Alpha: GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); break; case PremultAlpha: GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA); break; case Modulate: GLES20.glBlendFunc(GLES20.GL_DST_COLOR, GLES20.GL_ZERO); break; case ModulateX2: GLES20.glBlendFunc(GLES20.GL_DST_COLOR, GLES20.GL_SRC_COLOR); break; default: throw new UnsupportedOperationException("Unrecognized blend mode: " + state.getBlendMode()); } } context.blendMode = state.getBlendMode(); } } public void setViewPort(int x, int y, int w, int h) { if (x != vpX || vpY != y || vpW != w || vpH != h) { GLES20.glViewport(x, y, w, h); vpX = x; vpY = y; vpW = w; vpH = h; } } public void setClipRect(int x, int y, int width, int height) { if (!context.clipRectEnabled) { GLES20.glEnable(GLES20.GL_SCISSOR_TEST); context.clipRectEnabled = true; } if (clipX != x || clipY != y || clipW != width || clipH != height) { GLES20.glScissor(x, y, width, height); clipX = x; clipY = y; clipW = width; clipH = height; } } public void clearClipRect() { if (context.clipRectEnabled) { GLES20.glDisable(GLES20.GL_SCISSOR_TEST); context.clipRectEnabled = false; clipX = 0; clipY = 0; clipW = 0; clipH = 0; } } public void onFrame() { int error = GLES20.glGetError(); if (error != GLES20.GL_NO_ERROR){ throw new RendererException("OpenGL Error " + error + ". Enable error checking for more info."); } objManager.deleteUnused(this); } public void setWorldMatrix(Matrix4f worldMatrix) { } public void setViewProjectionMatrices(Matrix4f viewMatrix, Matrix4f projMatrix) { } protected void updateUniformLocation(Shader shader, Uniform uniform) { stringBuf.setLength(0); stringBuf.append(uniform.getName()).append('\0'); updateNameBuffer(); int loc = GLES20.glGetUniformLocation(shader.getId(), uniform.getName()); if (loc < 0) { uniform.setLocation(-1); // uniform is not declared in shader } else { uniform.setLocation(loc); } } protected void updateUniform(Shader shader, Uniform uniform) { int shaderId = shader.getId(); assert uniform.getName() != null; assert shader.getId() > 0; if (context.boundShaderProgram != shaderId) { GLES20.glUseProgram(shaderId); statistics.onShaderUse(shader, true); boundShader = shader; context.boundShaderProgram = shaderId; } else { statistics.onShaderUse(shader, false); } int loc = uniform.getLocation(); if (loc == -1) { return; } if (loc == -2) { // get uniform location updateUniformLocation(shader, uniform); if (uniform.getLocation() == -1) { // not declared, ignore uniform.clearUpdateNeeded(); return; } loc = uniform.getLocation(); } if (uniform.getVarType() == null) { logger.warning("value is not set yet."); return; // value not set yet.. } statistics.onUniformSet(); uniform.clearUpdateNeeded(); FloatBuffer fb; switch (uniform.getVarType()) { case Float: Float f = (Float) uniform.getValue(); GLES20.glUniform1f(loc, f.floatValue()); break; case Vector2: Vector2f v2 = (Vector2f) uniform.getValue(); GLES20.glUniform2f(loc, v2.getX(), v2.getY()); break; case Vector3: Vector3f v3 = (Vector3f) uniform.getValue(); GLES20.glUniform3f(loc, v3.getX(), v3.getY(), v3.getZ()); break; case Vector4: Object val = uniform.getValue(); if (val instanceof ColorRGBA) { ColorRGBA c = (ColorRGBA) val; GLES20.glUniform4f(loc, c.r, c.g, c.b, c.a); } else { Quaternion c = (Quaternion) uniform.getValue(); GLES20.glUniform4f(loc, c.getX(), c.getY(), c.getZ(), c.getW()); } break; case Boolean: Boolean b = (Boolean) uniform.getValue(); GLES20.glUniform1i(loc, b.booleanValue() ? GLES20.GL_TRUE : GLES20.GL_FALSE); break; case Matrix3: fb = (FloatBuffer) uniform.getValue(); assert fb.remaining() == 9; GLES20.glUniformMatrix3fv(loc, 1, false, fb); break; case Matrix4: fb = (FloatBuffer) uniform.getValue(); assert fb.remaining() == 16; GLES20.glUniformMatrix4fv(loc, 1, false, fb); break; case FloatArray: fb = (FloatBuffer) uniform.getValue(); GLES20.glUniform1fv(loc, fb.capacity(), fb); break; case Vector2Array: fb = (FloatBuffer) uniform.getValue(); GLES20.glUniform2fv(loc, fb.capacity() / 2, fb); break; case Vector3Array: fb = (FloatBuffer) uniform.getValue(); GLES20.glUniform3fv(loc, fb.capacity() / 3, fb); break; case Vector4Array: fb = (FloatBuffer) uniform.getValue(); GLES20.glUniform4fv(loc, fb.capacity() / 4, fb); break; case Matrix4Array: fb = (FloatBuffer) uniform.getValue(); GLES20.glUniformMatrix4fv(loc, fb.capacity() / 16, false, fb); break; case Int: Integer i = (Integer) uniform.getValue(); GLES20.glUniform1i(loc, i.intValue()); break; default: throw new UnsupportedOperationException("Unsupported uniform type: " + uniform.getVarType()); } } protected void updateShaderUniforms(Shader shader) { ListMap<String, Uniform> uniforms = shader.getUniformMap(); // for (Uniform uniform : shader.getUniforms()){ for (int i = 0; i < uniforms.size(); i++) { Uniform uniform = uniforms.getValue(i); if (uniform.isUpdateNeeded()) { updateUniform(shader, uniform); } } } protected void resetUniformLocations(Shader shader) { ListMap<String, Uniform> uniforms = shader.getUniformMap(); // for (Uniform uniform : shader.getUniforms()){ for (int i = 0; i < uniforms.size(); i++) { Uniform uniform = uniforms.getValue(i); uniform.reset(); // e.g check location again } } /* * (Non-javadoc) * Only used for fixed-function. Ignored. */ public void setLighting(LightList list) { } public int convertShaderType(ShaderType type) { switch (type) { case Fragment: return GLES20.GL_FRAGMENT_SHADER; case Vertex: return GLES20.GL_VERTEX_SHADER; // case Geometry: // return ARBGeometryShader4.GL_GEOMETRY_SHADER_ARB; default: throw new RuntimeException("Unrecognized shader type."); } } public void updateShaderSourceData(ShaderSource source, String language) { int id = source.getId(); if (id == -1) { // create id id = GLES20.glCreateShader(convertShaderType(source.getType())); if (id <= 0) { throw new RendererException("Invalid ID received when trying to create shader."); } source.setId(id); } // upload shader source // merge the defines and source code byte[] versionData = new byte[]{};//"#version 140\n".getBytes(); // versionData = "#define INSTANCING 1\n".getBytes(); byte[] definesCodeData = source.getDefines().getBytes(); byte[] sourceCodeData = source.getSource().getBytes(); ByteBuffer codeBuf = BufferUtils.createByteBuffer(versionData.length + definesCodeData.length + sourceCodeData.length); codeBuf.put(versionData); codeBuf.put(definesCodeData); codeBuf.put(sourceCodeData); codeBuf.flip(); if (powerVr && source.getType() == ShaderType.Vertex) { // XXX: This is to fix a bug in old PowerVR, remove // when no longer applicable. GLES20.glShaderSource( id, source.getDefines() + source.getSource()); } else { GLES20.glShaderSource( id, "precision mediump float;\n" + source.getDefines() + source.getSource()); } GLES20.glCompileShader(id); GLES20.glGetShaderiv(id, GLES20.GL_COMPILE_STATUS, intBuf1); boolean compiledOK = intBuf1.get(0) == GLES20.GL_TRUE; String infoLog = null; if (VALIDATE_SHADER || !compiledOK) { // even if compile succeeded, check // log for warnings GLES20.glGetShaderiv(id, GLES20.GL_INFO_LOG_LENGTH, intBuf1); checkGLError(); infoLog = GLES20.glGetShaderInfoLog(id); } if (compiledOK) { if (infoLog != null) { logger.log(Level.INFO, "compile success: " + source.getName() + ", " + infoLog); } else { logger.log(Level.FINE, "compile success: " + source.getName()); } } else { logger.log(Level.WARNING, "Bad compile of:\n{0}", new Object[]{ShaderDebug.formatShaderSource(source.getDefines(), source.getSource(),stringBuf.toString())}); if (infoLog != null) { throw new RendererException("compile error in:" + source + " error:" + infoLog); } else { throw new RendererException("compile error in:" + source + " error: <not provided>"); } } source.clearUpdateNeeded(); // only usable if compiled source.setUsable(compiledOK); if (!compiledOK) { // make sure to dispose id cause all program's // shaders will be cleared later. GLES20.glDeleteShader(id); } else { // register for cleanup since the ID is usable objManager.registerForCleanup(source); } } public void updateShaderData(Shader shader) { int id = shader.getId(); boolean needRegister = false; if (id == -1) { // create program id = GLES20.glCreateProgram(); if (id <= 0) { throw new RendererException("Invalid ID received when trying to create shader program."); } shader.setId(id); needRegister = true; } for (ShaderSource source : shader.getSources()) { if (source.isUpdateNeeded()) { updateShaderSourceData(source, shader.getLanguage()); // shader has been compiled here } if (!source.isUsable()) { // it's useless.. just forget about everything.. shader.setUsable(false); shader.clearUpdateNeeded(); return; } GLES20.glAttachShader(id, source.getId()); } // link shaders to program GLES20.glLinkProgram(id); GLES20.glGetProgramiv(id, GLES20.GL_LINK_STATUS, intBuf1); boolean linkOK = intBuf1.get(0) == GLES20.GL_TRUE; String infoLog = null; if (VALIDATE_SHADER || !linkOK) { GLES20.glGetProgramiv(id, GLES20.GL_INFO_LOG_LENGTH, intBuf1); int length = intBuf1.get(0); if (length > 3) { // get infos infoLog = GLES20.glGetProgramInfoLog(id); } } if (linkOK) { if (infoLog != null) { logger.log(Level.INFO, "shader link success. \n{0}", infoLog); } else { logger.fine("shader link success"); } } else { if (infoLog != null) { throw new RendererException("Shader link failure, shader:" + shader + " info:" + infoLog); } else { throw new RendererException("Shader link failure, shader:" + shader + " info: <not provided>"); } } shader.clearUpdateNeeded(); if (!linkOK) { // failure.. forget about everything shader.resetSources(); shader.setUsable(false); deleteShader(shader); } else { shader.setUsable(true); if (needRegister) { objManager.registerForCleanup(shader); statistics.onNewShader(); } else { // OpenGL spec: uniform locations may change after re-link resetUniformLocations(shader); } } } public void setShader(Shader shader) { if (shader == null) { if (context.boundShaderProgram > 0) { GLES20.glUseProgram(0); statistics.onShaderUse(null, true); context.boundShaderProgram = 0; boundShader = null; } } else { if (shader.isUpdateNeeded()) { updateShaderData(shader); } // NOTE: might want to check if any of the // sources need an update? if (!shader.isUsable()) { logger.warning("shader is not usable."); return; } assert shader.getId() > 0; updateShaderUniforms(shader); if (context.boundShaderProgram != shader.getId()) { if (VALIDATE_SHADER) { // check if shader can be used // with current state GLES20.glValidateProgram(shader.getId()); GLES20.glGetProgramiv(shader.getId(), GLES20.GL_VALIDATE_STATUS, intBuf1); boolean validateOK = intBuf1.get(0) == GLES20.GL_TRUE; if (validateOK) { logger.fine("shader validate success"); } else { logger.warning("shader validate failure"); } } GLES20.glUseProgram(shader.getId()); statistics.onShaderUse(shader, true); context.boundShaderProgram = shader.getId(); boundShader = shader; } else { statistics.onShaderUse(shader, false); } } } public void deleteShaderSource(ShaderSource source) { if (source.getId() < 0) { logger.warning("Shader source is not uploaded to GPU, cannot delete."); return; } source.setUsable(false); source.clearUpdateNeeded(); GLES20.glDeleteShader(source.getId()); source.resetObject(); } public void deleteShader(Shader shader) { if (shader.getId() == -1) { logger.warning("Shader is not uploaded to GPU, cannot delete."); return; } for (ShaderSource source : shader.getSources()) { if (source.getId() != -1) { GLES20.glDetachShader(shader.getId(), source.getId()); // the next part is done by the GLObjectManager automatically // glDeleteShader(source.getId()); } } // kill all references so sources can be collected // if needed. shader.resetSources(); GLES20.glDeleteProgram(shader.getId()); statistics.onDeleteShader(); } public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst) { logger.warning("copyFrameBuffer is not supported."); } public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst, boolean copyDepth) { logger.warning("copyFrameBuffer is not supported."); } private void checkFrameBufferError() { logger.warning("checkFrameBufferError is not supported."); } private void updateRenderBuffer(FrameBuffer fb, RenderBuffer rb) { logger.warning("updateRenderBuffer is not supported."); } /* private void updateRenderBuffer(FrameBuffer fb, RenderBuffer rb){ int id = rb.getId(); if (id == -1){ glGenRenderbuffersEXT(intBuf1); id = intBuf1.get(0); rb.setId(id); } if (context.boundRB != id){ glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, id); context.boundRB = id; } if (fb.getWidth() > maxRBSize || fb.getHeight() > maxRBSize) throw new UnsupportedOperationException("Resolution "+fb.getWidth()+ ":"+fb.getHeight()+" is not supported."); if (fb.getSamples() > 0 && GLContext.getCapabilities().GL_EXT_framebuffer_multisample){ int samples = fb.getSamples(); if (maxFBOSamples < samples){ samples = maxFBOSamples; } glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, TextureUtil.convertTextureFormat(rb.getFormat()), fb.getWidth(), fb.getHeight()); }else{ glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, TextureUtil.convertTextureFormat(rb.getFormat()), fb.getWidth(), fb.getHeight()); } } */ private int convertAttachmentSlot(int attachmentSlot) { logger.warning("convertAttachmentSlot is not supported."); return -1; } /* private int convertAttachmentSlot(int attachmentSlot){ // can also add support for stencil here if (attachmentSlot == -100){ return GL_DEPTH_ATTACHMENT_EXT; }else if (attachmentSlot < 0 || attachmentSlot >= 16){ throw new UnsupportedOperationException("Invalid FBO attachment slot: "+attachmentSlot); } return GL_COLOR_ATTACHMENT0_EXT + attachmentSlot; } */ public void updateRenderTexture(FrameBuffer fb, RenderBuffer rb) { logger.warning("updateRenderTexture is not supported."); } /* public void updateRenderTexture(FrameBuffer fb, RenderBuffer rb){ Texture tex = rb.getTexture(); Image image = tex.getImage(); if (image.isUpdateNeeded()) updateTexImageData(image, tex.getType(), tex.getMinFilter().usesMipMapLevels()); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, convertAttachmentSlot(rb.getSlot()), convertTextureType(tex.getType()), image.getId(), 0); } */ public void updateFrameBufferAttachment(FrameBuffer fb, RenderBuffer rb) { logger.warning("updateFrameBufferAttachment is not supported."); } /* public void updateFrameBufferAttachment(FrameBuffer fb, RenderBuffer rb){ boolean needAttach; if (rb.getTexture() == null){ // if it hasn't been created yet, then attach is required. needAttach = rb.getId() == -1; updateRenderBuffer(fb, rb); }else{ needAttach = false; updateRenderTexture(fb, rb); } if (needAttach){ glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, convertAttachmentSlot(rb.getSlot()), GL_RENDERBUFFER_EXT, rb.getId()); } } */ public void updateFrameBuffer(FrameBuffer fb) { logger.warning("updateFrameBuffer is not supported."); } /* public void updateFrameBuffer(FrameBuffer fb) { int id = fb.getId(); if (id == -1){ // create FBO glGenFramebuffersEXT(intBuf1); id = intBuf1.get(0); fb.setId(id); objManager.registerForCleanup(fb); statistics.onNewFrameBuffer(); } if (context.boundFBO != id){ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, id); // binding an FBO automatically sets draw buf to GL_COLOR_ATTACHMENT0 context.boundDrawBuf = 0; context.boundFBO = id; } FrameBuffer.RenderBuffer depthBuf = fb.getDepthBuffer(); if (depthBuf != null){ updateFrameBufferAttachment(fb, depthBuf); } for (int i = 0; i < fb.getNumColorBuffers(); i++){ FrameBuffer.RenderBuffer colorBuf = fb.getColorBuffer(i); updateFrameBufferAttachment(fb, colorBuf); } fb.clearUpdateNeeded(); } */ public void setMainFrameBufferOverride(FrameBuffer fb){ } public void setFrameBuffer(FrameBuffer fb) { } public void readFrameBuffer(FrameBuffer fb, ByteBuffer byteBuf) { logger.warning("readFrameBuffer is not supported."); } private void deleteRenderBuffer(FrameBuffer fb, RenderBuffer rb) { logger.warning("deleteRenderBuffer is not supported."); } /* private void deleteRenderBuffer(FrameBuffer fb, RenderBuffer rb){ intBuf1.put(0, rb.getId()); glDeleteRenderbuffersEXT(intBuf1); } */ public void deleteFrameBuffer(FrameBuffer fb) { logger.warning("deleteFrameBuffer is not supported."); } /* public void deleteFrameBuffer(FrameBuffer fb) { if (fb.getId() != -1){ if (context.boundFBO == fb.getId()){ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); context.boundFBO = 0; } if (fb.getDepthBuffer() != null){ deleteRenderBuffer(fb, fb.getDepthBuffer()); } if (fb.getColorBuffer() != null){ deleteRenderBuffer(fb, fb.getColorBuffer()); } intBuf1.put(0, fb.getId()); glDeleteFramebuffersEXT(intBuf1); fb.resetObject(); statistics.onDeleteFrameBuffer(); } } */ private int convertTextureType(Texture.Type type) { switch (type) { case TwoDimensional: return GLES20.GL_TEXTURE_2D; // case TwoDimensionalArray: // return EXTTextureArray.GL_TEXTURE_2D_ARRAY_EXT; // case ThreeDimensional: // return GLES20.GL_TEXTURE_3D; case CubeMap: return GLES20.GL_TEXTURE_CUBE_MAP; default: throw new UnsupportedOperationException("Unknown texture type: " + type); } } private int convertMagFilter(Texture.MagFilter filter) { switch (filter) { case Bilinear: return GLES20.GL_LINEAR; case Nearest: return GLES20.GL_NEAREST; default: throw new UnsupportedOperationException("Unknown mag filter: " + filter); } } private int convertMinFilter(Texture.MinFilter filter) { switch (filter) { case Trilinear: return GLES20.GL_LINEAR_MIPMAP_LINEAR; case BilinearNearestMipMap: return GLES20.GL_LINEAR_MIPMAP_NEAREST; case NearestLinearMipMap: return GLES20.GL_NEAREST_MIPMAP_LINEAR; case NearestNearestMipMap: return GLES20.GL_NEAREST_MIPMAP_NEAREST; case BilinearNoMipMaps: return GLES20.GL_LINEAR; case NearestNoMipMaps: return GLES20.GL_NEAREST; default: throw new UnsupportedOperationException("Unknown min filter: " + filter); } } private int convertWrapMode(Texture.WrapMode mode) { switch (mode) { case BorderClamp: case Clamp: case EdgeClamp: return GLES20.GL_CLAMP_TO_EDGE; case Repeat: return GLES20.GL_REPEAT; case MirroredRepeat: return GLES20.GL_MIRRORED_REPEAT; default: throw new UnsupportedOperationException("Unknown wrap mode: " + mode); } } /** * <code>setupTextureParams</code> sets the OpenGL context texture parameters * @param tex the Texture to set the texture parameters from */ private void setupTextureParams(Texture tex) { int target = convertTextureType(tex.getType()); // filter things int minFilter = convertMinFilter(tex.getMinFilter()); int magFilter = convertMagFilter(tex.getMagFilter()); GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_MIN_FILTER, minFilter); GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_MAG_FILTER, magFilter); /* if (tex.getAnisotropicFilter() > 1){ if (GLContext.getCapabilities().GL_EXT_texture_filter_anisotropic){ glTexParameterf(target, EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT, tex.getAnisotropicFilter()); } } */ // repeat modes switch (tex.getType()) { case ThreeDimensional: case CubeMap: // cubemaps use 3D coords // GL_TEXTURE_WRAP_R is not available in api 8 //GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_WRAP_R, convertWrapMode(tex.getWrap(WrapAxis.R))); case TwoDimensional: case TwoDimensionalArray: GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_WRAP_T, convertWrapMode(tex.getWrap(WrapAxis.T))); // fall down here is intentional.. // case OneDimensional: GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_WRAP_S, convertWrapMode(tex.getWrap(WrapAxis.S))); break; default: throw new UnsupportedOperationException("Unknown texture type: " + tex.getType()); } // R to Texture compare mode /* if (tex.getShadowCompareMode() != Texture.ShadowCompareMode.Off){ GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_COMPARE_MODE, GLES20.GL_COMPARE_R_TO_TEXTURE); GLES20.glTexParameteri(target, GLES20.GL_DEPTH_TEXTURE_MODE, GLES20.GL_INTENSITY); if (tex.getShadowCompareMode() == Texture.ShadowCompareMode.GreaterOrEqual){ GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_COMPARE_FUNC, GLES20.GL_GEQUAL); }else{ GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_COMPARE_FUNC, GLES20.GL_LEQUAL); } } */ } /** * <code>updateTexImageData</code> activates and binds the texture * @param img * @param type * @param needMips */ public void updateTexImageData(Image img, Texture.Type type, boolean needMips) { int texId = img.getId(); if (texId == -1) { // create texture GLES20.glGenTextures(1, intBuf1); texId = intBuf1.get(0); img.setId(texId); objManager.registerForCleanup(img); statistics.onNewTexture(); } // bind texture int target = convertTextureType(type); if (context.boundTextures[0] != img) { if (context.boundTextureUnit != 0) { GLES20.glActiveTexture(GLES20.GL_TEXTURE0); context.boundTextureUnit = 0; } GLES20.glBindTexture(target, texId); context.boundTextures[0] = img; } if (target == GLES20.GL_TEXTURE_CUBE_MAP) { // Upload a cube map / sky box @SuppressWarnings("unchecked") List<AndroidImageInfo> bmps = (List<AndroidImageInfo>) img.getEfficentData(); if (bmps != null) { // Native android bitmap if (bmps.size() != 6) { throw new UnsupportedOperationException("Invalid texture: " + img + "Cubemap textures must contain 6 data units."); } for (int i = 0; i < 6; i++) { TextureUtil.uploadTextureBitmap(GLES20.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, bmps.get(i).getBitmap(), needMips); bmps.get(i).notifyBitmapUploaded(); } } else { // Standard jme3 image data List<ByteBuffer> data = img.getData(); if (data.size() != 6) { throw new UnsupportedOperationException("Invalid texture: " + img + "Cubemap textures must contain 6 data units."); } for (int i = 0; i < 6; i++) { TextureUtil.uploadTextureAny(img, GLES20.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, i, needMips); } } } else { TextureUtil.uploadTextureAny(img, target, 0, needMips); if (img.getEfficentData() instanceof AndroidImageInfo) { AndroidImageInfo info = (AndroidImageInfo) img.getEfficentData(); info.notifyBitmapUploaded(); } } img.clearUpdateNeeded(); } public void setTexture(int unit, Texture tex) { Image image = tex.getImage(); if (image.isUpdateNeeded()) { updateTexImageData(image, tex.getType(), tex.getMinFilter().usesMipMapLevels()); } int texId = image.getId(); assert texId != -1; if (texId == -1) { logger.warning("error: texture image has -1 id"); } Image[] textures = context.boundTextures; int type = convertTextureType(tex.getType()); if (!context.textureIndexList.moveToNew(unit)) { // if (context.boundTextureUnit != unit){ // glActiveTexture(GL_TEXTURE0 + unit); // context.boundTextureUnit = unit; // glEnable(type); } if (textures[unit] != image) { if (context.boundTextureUnit != unit) { GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + unit); context.boundTextureUnit = unit; } GLES20.glBindTexture(type, texId); textures[unit] = image; statistics.onTextureUse(tex.getImage(), true); } else { statistics.onTextureUse(tex.getImage(), false); } setupTextureParams(tex); } public void clearTextureUnits() { IDList textureList = context.textureIndexList; Image[] textures = context.boundTextures; for (int i = 0; i < textureList.oldLen; i++) { int idx = textureList.oldList[i]; // if (context.boundTextureUnit != idx){ // glActiveTexture(GL_TEXTURE0 + idx); // context.boundTextureUnit = idx; // glDisable(convertTextureType(textures[idx].getType())); textures[idx] = null; } context.textureIndexList.copyNewToOld(); } public void deleteImage(Image image) { int texId = image.getId(); if (texId != -1) { intBuf1.put(0, texId); intBuf1.position(0).limit(1); GLES20.glDeleteTextures(1, intBuf1); image.resetObject(); statistics.onDeleteTexture(); } } private int convertUsage(Usage usage) { switch (usage) { case Static: return GLES20.GL_STATIC_DRAW; case Dynamic: return GLES20.GL_DYNAMIC_DRAW; case Stream: return GLES20.GL_STREAM_DRAW; default: throw new RuntimeException("Unknown usage type."); } } private int convertFormat(Format format) { switch (format) { case Byte: return GLES20.GL_BYTE; case UnsignedByte: return GLES20.GL_UNSIGNED_BYTE; case Short: return GLES20.GL_SHORT; case UnsignedShort: return GLES20.GL_UNSIGNED_SHORT; case Int: return GLES20.GL_INT; case UnsignedInt: return GLES20.GL_UNSIGNED_INT; /* case Half: return NVHalfFloat.GL_HALF_FLOAT_NV; // return ARBHalfFloatVertex.GL_HALF_FLOAT; */ case Float: return GLES20.GL_FLOAT; // case Double: // return GLES20.GL_DOUBLE; default: throw new RuntimeException("Unknown buffer format."); } } public void updateBufferData(VertexBuffer vb) { int bufId = vb.getId(); boolean created = false; if (bufId == -1) { // create buffer GLES20.glGenBuffers(1, intBuf1); bufId = intBuf1.get(0); vb.setId(bufId); objManager.registerForCleanup(vb); created = true; } // bind buffer int target; if (vb.getBufferType() == VertexBuffer.Type.Index) { target = GLES20.GL_ELEMENT_ARRAY_BUFFER; if (context.boundElementArrayVBO != bufId) { GLES20.glBindBuffer(target, bufId); context.boundElementArrayVBO = bufId; } } else { target = GLES20.GL_ARRAY_BUFFER; if (context.boundArrayVBO != bufId) { GLES20.glBindBuffer(target, bufId); context.boundArrayVBO = bufId; } } int usage = convertUsage(vb.getUsage()); vb.getData().clear(); if (created || vb.hasDataSizeChanged()) { // upload data based on format int size = vb.getData().capacity() * vb.getFormat().getComponentSize(); switch (vb.getFormat()) { case Byte: case UnsignedByte: GLES20.glBufferData(target, size, (ByteBuffer) vb.getData(), usage); break; //case Half: case Short: case UnsignedShort: GLES20.glBufferData(target, size, (ShortBuffer) vb.getData(), usage); break; case Int: case UnsignedInt: GLES20.glBufferData(target, size, (IntBuffer) vb.getData(), usage); break; case Float: GLES20.glBufferData(target, size, (FloatBuffer) vb.getData(), usage); break; case Double: GLES20.glBufferData(target, size, (DoubleBuffer) vb.getData(), usage); break; default: throw new RuntimeException("Unknown buffer format."); } } else { int size = vb.getData().capacity() * vb.getFormat().getComponentSize(); switch (vb.getFormat()) { case Byte: case UnsignedByte: GLES20.glBufferSubData(target, 0, size, (ByteBuffer) vb.getData()); break; case Short: case UnsignedShort: GLES20.glBufferSubData(target, 0, size, (ShortBuffer) vb.getData()); break; case Int: case UnsignedInt: GLES20.glBufferSubData(target, 0, size, (IntBuffer) vb.getData()); break; case Float: GLES20.glBufferSubData(target, 0, size, (FloatBuffer) vb.getData()); break; case Double: GLES20.glBufferSubData(target, 0, size, (DoubleBuffer) vb.getData()); break; default: throw new RuntimeException("Unknown buffer format."); } } vb.clearUpdateNeeded(); } public void deleteBuffer(VertexBuffer vb) { int bufId = vb.getId(); if (bufId != -1) { // delete buffer intBuf1.put(0, bufId); intBuf1.position(0).limit(1); GLES20.glDeleteBuffers(1, intBuf1); vb.resetObject(); } } public void clearVertexAttribs() { IDList attribList = context.attribIndexList; for (int i = 0; i < attribList.oldLen; i++) { int idx = attribList.oldList[i]; GLES20.glDisableVertexAttribArray(idx); context.boundAttribs[idx] = null; } context.attribIndexList.copyNewToOld(); } public void setVertexAttrib(VertexBuffer vb, VertexBuffer idb) { if (vb.getBufferType() == VertexBuffer.Type.Index) { throw new IllegalArgumentException("Index buffers not allowed to be set to vertex attrib"); } if (vb.isUpdateNeeded() && idb == null) { updateBufferData(vb); } int programId = context.boundShaderProgram; if (programId > 0) { Attribute attrib = boundShader.getAttribute(vb.getBufferType()); int loc = attrib.getLocation(); if (loc == -1) { return; // not defined } if (loc == -2) { // stringBuf.setLength(0); // stringBuf.append("in").append(vb.getBufferType().name()).append('\0'); // updateNameBuffer(); String attributeName = "in" + vb.getBufferType().name(); loc = GLES20.glGetAttribLocation(programId, attributeName); // not really the name of it in the shader (inPosition\0) but // the internal name of the enum (Position). if (loc < 0) { attrib.setLocation(-1); return; // not available in shader. } else { attrib.setLocation(loc); } } VertexBuffer[] attribs = context.boundAttribs; if (!context.attribIndexList.moveToNew(loc)) { GLES20.glEnableVertexAttribArray(loc); //System.out.println("Enabled ATTRIB IDX: "+loc); } if (attribs[loc] != vb) { // NOTE: Use id from interleaved buffer if specified int bufId = idb != null ? idb.getId() : vb.getId(); assert bufId != -1; if (bufId == -1) { logger.warning("invalid buffer id"); } if (context.boundArrayVBO != bufId) { GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, bufId); context.boundArrayVBO = bufId; } vb.getData().clear(); Android22Workaround.glVertexAttribPointer(loc, vb.getNumComponents(), convertFormat(vb.getFormat()), vb.isNormalized(), vb.getStride(), 0); attribs[loc] = vb; } } else { throw new IllegalStateException("Cannot render mesh without shader bound"); } } public void setVertexAttrib(VertexBuffer vb) { setVertexAttrib(vb, null); } public void drawTriangleArray(Mesh.Mode mode, int count, int vertCount) { /* if (count > 1){ ARBDrawInstanced.glDrawArraysInstancedARB(convertElementMode(mode), 0, vertCount, count); }else{*/ GLES20.glDrawArrays(convertElementMode(mode), 0, vertCount); } public void drawTriangleList(VertexBuffer indexBuf, Mesh mesh, int count) { if (indexBuf.getBufferType() != VertexBuffer.Type.Index) { throw new IllegalArgumentException("Only index buffers are allowed as triangle lists."); } if (indexBuf.isUpdateNeeded()) { updateBufferData(indexBuf); } int bufId = indexBuf.getId(); assert bufId != -1; if (bufId == -1) { logger.info("invalid buffer id!"); } if (context.boundElementArrayVBO != bufId) { GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, bufId); context.boundElementArrayVBO = bufId; } int vertCount = mesh.getVertexCount(); boolean useInstancing = count > 1 && caps.contains(Caps.MeshInstancing); Buffer indexData = indexBuf.getData(); if (mesh.getMode() == Mode.Hybrid) { int[] modeStart = mesh.getModeStart(); int[] elementLengths = mesh.getElementLengths(); int elMode = convertElementMode(Mode.Triangles); int fmt = convertFormat(indexBuf.getFormat()); int elSize = indexBuf.getFormat().getComponentSize(); int listStart = modeStart[0]; int stripStart = modeStart[1]; int fanStart = modeStart[2]; int curOffset = 0; for (int i = 0; i < elementLengths.length; i++) { if (i == stripStart) { elMode = convertElementMode(Mode.TriangleStrip); } else if (i == fanStart) { elMode = convertElementMode(Mode.TriangleStrip); } int elementLength = elementLengths[i]; if (useInstancing) { //ARBDrawInstanced. throw new IllegalArgumentException("instancing is not supported."); /* GLES20.glDrawElementsInstancedARB(elMode, elementLength, fmt, curOffset, count); */ } else { indexBuf.getData().position(curOffset); GLES20.glDrawElements(elMode, elementLength, fmt, indexBuf.getData()); /* glDrawRangeElements(elMode, 0, vertCount, elementLength, fmt, curOffset); */ } curOffset += elementLength * elSize; } } else { if (useInstancing) { throw new IllegalArgumentException("instancing is not supported."); //ARBDrawInstanced. /* GLES20.glDrawElementsInstancedARB(convertElementMode(mesh.getMode()), indexBuf.getData().capacity(), convertFormat(indexBuf.getFormat()), 0, count); */ } else { indexData.clear(); GLES20.glDrawElements( convertElementMode(mesh.getMode()), indexBuf.getData().capacity(), convertFormat(indexBuf.getFormat()), 0); } } } public int convertElementMode(Mesh.Mode mode) { switch (mode) { case Points: return GLES20.GL_POINTS; case Lines: return GLES20.GL_LINES; case LineLoop: return GLES20.GL_LINE_LOOP; case LineStrip: return GLES20.GL_LINE_STRIP; case Triangles: return GLES20.GL_TRIANGLES; case TriangleFan: return GLES20.GL_TRIANGLE_FAN; case TriangleStrip: return GLES20.GL_TRIANGLE_STRIP; default: throw new UnsupportedOperationException("Unrecognized mesh mode: " + mode); } } public void updateVertexArray(Mesh mesh) { logger.log(Level.INFO, "updateVertexArray({0})", mesh); int id = mesh.getId(); /* if (id == -1){ IntBuffer temp = intBuf1; // ARBVertexArrayObject.glGenVertexArrays(temp); GLES20.glGenVertexArrays(temp); id = temp.get(0); mesh.setId(id); } if (context.boundVertexArray != id){ // ARBVertexArrayObject.glBindVertexArray(id); GLES20.glBindVertexArray(id); context.boundVertexArray = id; } */ VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData); if (interleavedData != null && interleavedData.isUpdateNeeded()) { updateBufferData(interleavedData); } for (VertexBuffer vb : mesh.getBufferList().getArray()){ if (vb.getBufferType() == Type.InterleavedData || vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers || vb.getBufferType() == Type.Index) { continue; } if (vb.getStride() == 0) { // not interleaved setVertexAttrib(vb); } else { // interleaved setVertexAttrib(vb, interleavedData); } } } /** * renderMeshVertexArray renders a mesh using vertex arrays * @param mesh * @param lod * @param count */ private void renderMeshVertexArray(Mesh mesh, int lod, int count) { // IntMap<VertexBuffer> buffers = mesh.getBuffers(); for (VertexBuffer vb : mesh.getBufferList().getArray()){ if (vb.getBufferType() == Type.InterleavedData || vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers || vb.getBufferType() == Type.Index) { continue; } if (vb.getStride() == 0) { // not interleaved setVertexAttrib_Array(vb); } else { // interleaved VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData); setVertexAttrib_Array(vb, interleavedData); } } VertexBuffer indices = null; if (mesh.getNumLodLevels() > 0) { indices = mesh.getLodLevel(lod); } else { indices = mesh.getBuffer(Type.Index);//buffers.get(Type.Index.ordinal()); } if (indices != null) { drawTriangleList_Array(indices, mesh, count); } else { GLES20.glDrawArrays(convertElementMode(mesh.getMode()), 0, mesh.getVertexCount()); } clearVertexAttribs(); clearTextureUnits(); } private void renderMeshDefault(Mesh mesh, int lod, int count) { VertexBuffer indices = null; VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData); if (interleavedData != null && interleavedData.isUpdateNeeded()) { updateBufferData(interleavedData); } //IntMap<VertexBuffer> buffers = mesh.getBuffers(); ; if (mesh.getNumLodLevels() > 0) { indices = mesh.getLodLevel(lod); } else { indices = mesh.getBuffer(Type.Index);// buffers.get(Type.Index.ordinal()); } for (VertexBuffer vb : mesh.getBufferList().getArray()){ if (vb.getBufferType() == Type.InterleavedData || vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers || vb.getBufferType() == Type.Index) { continue; } if (vb.getStride() == 0) { // not interleaved setVertexAttrib(vb); } else { // interleaved setVertexAttrib(vb, interleavedData); } } if (indices != null) { drawTriangleList(indices, mesh, count); } else { // throw new UnsupportedOperationException("Cannot render without index buffer"); GLES20.glDrawArrays(convertElementMode(mesh.getMode()), 0, mesh.getVertexCount()); } clearVertexAttribs(); clearTextureUnits(); } public void renderMesh(Mesh mesh, int lod, int count) { if (context.pointSize != mesh.getPointSize()) { GLES10.glPointSize(mesh.getPointSize()); context.pointSize = mesh.getPointSize(); } if (context.lineWidth != mesh.getLineWidth()) { GLES20.glLineWidth(mesh.getLineWidth()); context.lineWidth = mesh.getLineWidth(); } statistics.onMeshDrawn(mesh, lod); // if (GLContext.getCapabilities().GL_ARB_vertex_array_object){ // renderMeshVertexArray(mesh, lod, count); // }else{ if (useVBO) { renderMeshDefault(mesh, lod, count); } else { renderMeshVertexArray(mesh, lod, count); } } /** * drawTriangleList_Array uses Vertex Array * @param indexBuf * @param mesh * @param count */ public void drawTriangleList_Array(VertexBuffer indexBuf, Mesh mesh, int count) { if (indexBuf.getBufferType() != VertexBuffer.Type.Index) { throw new IllegalArgumentException("Only index buffers are allowed as triangle lists."); } boolean useInstancing = count > 1 && caps.contains(Caps.MeshInstancing); if (useInstancing) { throw new IllegalArgumentException("Caps.MeshInstancing is not supported."); } int vertCount = mesh.getVertexCount(); Buffer indexData = indexBuf.getData(); indexData.clear(); if (mesh.getMode() == Mode.Hybrid) { int[] modeStart = mesh.getModeStart(); int[] elementLengths = mesh.getElementLengths(); int elMode = convertElementMode(Mode.Triangles); int fmt = convertFormat(indexBuf.getFormat()); int elSize = indexBuf.getFormat().getComponentSize(); int listStart = modeStart[0]; int stripStart = modeStart[1]; int fanStart = modeStart[2]; int curOffset = 0; for (int i = 0; i < elementLengths.length; i++) { if (i == stripStart) { elMode = convertElementMode(Mode.TriangleStrip); } else if (i == fanStart) { elMode = convertElementMode(Mode.TriangleStrip); } int elementLength = elementLengths[i]; indexBuf.getData().position(curOffset); GLES20.glDrawElements(elMode, elementLength, fmt, indexBuf.getData()); curOffset += elementLength * elSize; } } else { GLES20.glDrawElements( convertElementMode(mesh.getMode()), indexBuf.getData().capacity(), convertFormat(indexBuf.getFormat()), indexBuf.getData()); } } /** * setVertexAttrib_Array uses Vertex Array * @param vb * @param idb */ public void setVertexAttrib_Array(VertexBuffer vb, VertexBuffer idb) { if (vb.getBufferType() == VertexBuffer.Type.Index) { throw new IllegalArgumentException("Index buffers not allowed to be set to vertex attrib"); } // Get shader int programId = context.boundShaderProgram; if (programId > 0) { VertexBuffer[] attribs = context.boundAttribs; Attribute attrib = boundShader.getAttribute(vb.getBufferType()); int loc = attrib.getLocation(); if (loc == -1) { return; } else if (loc == -2) { String attributeName = "in" + vb.getBufferType().name(); loc = GLES20.glGetAttribLocation(programId, attributeName); if (loc < 0) { attrib.setLocation(-1); return; // not available in shader. } else { attrib.setLocation(loc); } } // if (loc == -2) if ((attribs[loc] != vb) || vb.isUpdateNeeded()) { // NOTE: Use data from interleaved buffer if specified VertexBuffer avb = idb != null ? idb : vb; avb.getData().clear(); avb.getData().position(vb.getOffset()); // Upload attribute data GLES20.glVertexAttribPointer(loc, vb.getNumComponents(), convertFormat(vb.getFormat()), vb.isNormalized(), vb.getStride(), avb.getData()); GLES20.glEnableVertexAttribArray(loc); attribs[loc] = vb; } // if (attribs[loc] != vb) } else { throw new IllegalStateException("Cannot render mesh without shader bound"); } } /** * setVertexAttrib_Array uses Vertex Array * @param vb */ public void setVertexAttrib_Array(VertexBuffer vb) { setVertexAttrib_Array(vb, null); } public void setAlphaToCoverage(boolean value) { if (value) { GLES20.glEnable(GLES20.GL_SAMPLE_ALPHA_TO_COVERAGE); } else { GLES20.glDisable(GLES20.GL_SAMPLE_ALPHA_TO_COVERAGE); } } @Override public void invalidateState() { context.reset(); boundShader = null; // lastFb = null; } }
package sorcer.sml.blocks; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sorcer.test.ProjectContext; import org.sorcer.test.SorcerTestRunner; import sorcer.arithmetic.provider.impl.AdderImpl; import sorcer.arithmetic.provider.impl.AveragerImpl; import sorcer.arithmetic.provider.impl.MultiplierImpl; import sorcer.arithmetic.provider.impl.SubtractorImpl; import sorcer.core.SorcerConstants; import sorcer.core.provider.rendezvous.ServiceConcatenator; import sorcer.service.*; import sorcer.service.Signature.Direction; import static org.junit.Assert.assertEquals; import static sorcer.co.operator.ent; import static sorcer.co.operator.inEnt; import static sorcer.eo.operator.alt; import static sorcer.eo.operator.*; import static sorcer.eo.operator.loop; import static sorcer.eo.operator.opt; import static sorcer.po.operator.*; /** * @author Mike Sobolewski */ @SuppressWarnings("unchecked") @RunWith(SorcerTestRunner.class) @ProjectContext("examples/sml") public class LocalBlockExertions implements SorcerConstants { private final static Logger logger = LoggerFactory.getLogger(LocalBlockExertions.class); @Test public void explicitDataBlockTest() throws Exception { Task t3 = task("t3", sig("subtract", SubtractorImpl.class), context("subtract", inEnt("arg/t4"), inEnt("arg/t5"), result("block/result", Direction.OUT))); Task t4 = task("t4", sig("multiply", MultiplierImpl.class), context("multiply", inEnt("arg/x1", 10.0), inEnt("arg/x2", 50.0), result("arg/t4", Direction.IN))); Task t5 = task("t5", sig("add", AdderImpl.class), context("add", inEnt("arg/x3", 20.0), inEnt("arg/x4", 80.0), result("arg/t5", Direction.IN))); Block block = block("block", t4, t5, t3); Block result = exert(block); assertEquals(value(context(result), "block/result"), 400.00); } @Test public void closingBlockTest() throws Exception { Task t3 = task("t3", sig("subtract", SubtractorImpl.class), context("subtract", inEnt("arg/t4"), inEnt("arg/t5"), result("block/result", Direction.OUT))); Task t4 = task("t4", sig("multiply", MultiplierImpl.class), context("multiply", inEnt("arg/x1"), inEnt("arg/x2"), result("arg/t4", Direction.IN))); Task t5 = task("t5", sig("add", AdderImpl.class), context("add", inEnt("arg/x3"), inEnt("arg/x4"), result("arg/t5", Direction.IN))); Block block = block("block", t4, t5, t3, context( inEnt("arg/x1", 10.0), inEnt("arg/x2", 50.0), inEnt("arg/x3", 20.0), inEnt("arg/x4", 80.0))); Block result = exert(block); assertEquals(value(context(result), "block/result"), 400.00); } @Test public void overwritingLocalContextBlockTest() throws Exception { // in t4: inEnt("arg/x1", 20.0), inEnt("arg/x2", 10.0) // cosed with 10.0 and 50.0 respectively Task t3 = task("t3", sig("subtract", SubtractorImpl.class), context("subtract", inEnt("arg/t4"), inEnt("arg/t5"), result("block/result", Direction.OUT))); Task t4 = task("t4", sig("multiply", MultiplierImpl.class), context("multiply", inEnt("arg/x1", 20.0), inEnt("arg/x2", 10.0), result("arg/t4", Direction.IN))); Task t5 = task("t5", sig("add", AdderImpl.class), context("add", inEnt("arg/x3"), inEnt("arg/x4"), result("arg/t5", Direction.IN))); Block block = block("block", t4, t5, t3, context( inEnt("arg/x1", 10.0), inEnt("arg/x2", 50.0), inEnt("arg/x3", 20.0), inEnt("arg/x4", 80.0))); Block result = exert(block); assertEquals(value(context(result), "block/result"), 400.00); } @Test public void altServceTest() throws Exception { // Context scope = context(ent("y1", 100), ent("y2", 200)); Task t4 = task("t4", sig("multiply", MultiplierImpl.class), context("multiply", inEnt("arg/x1", 10.0), inEnt("arg/x2", 50.0), result("block/result"))); Task t5 = task("t5", sig("add", AdderImpl.class), context("add", inEnt("arg/x1", 20.0), inEnt("arg/x2", 80.0), result("block/result"))); Service sb = block("block", context(ent("y1", 100), ent("y2", 200)), alt(opt(condition("{ y1, y2 -> y1 > y2 }", "y1", "y2"), t4), opt(condition("{ y1, y2 -> y1 <= y2 }", "y1", "y2"), t5))); Service out = exert(sb); // logger.info("block context1: " + context(block)); // logger.info("result: " + value(context(block), "block/result")); assertEquals(value(context(out), "block/result"), 100.00); // the initial scope of block is updated bind(sb, ent("y1", 200.0), ent("y2", 100.0)); // logger.info("block context1: " + context(sb)); // out = exert(sb, ent("y1", 200.0), ent("y2", 100.0)); out = exert(sb); // logger.info("block context2: " + context(out)); // logger.info("result: " + value(context(block), "block/result")); assertEquals(value(context(out), "block/result"), 500.0); } @Test public void directAltBlockTest() throws Exception { Task t4 = task("t4", sig("multiply", MultiplierImpl.class), context("multiply", inEnt("arg/x1", 10.0), inEnt("arg/x2", 50.0), result("block/result"))); Task t5 = task("t5", sig("add", AdderImpl.class), context("add", inEnt("arg/x1", 20.0), inEnt("arg/x2", 80.0), result("block/result"))); Block block = block("block", context(ent("y1", 100), ent("y2", 200)), alt(opt(condition("{ y1, y2 -> y1 > y2 }", "y1", "y2"), t4), opt(condition("{ y1, y2 -> y1 <= y2 }", "y1", "y2"), t5))); block = exert(block); // logger.info("block context: " + context(block)); // logger.info("result: " + value(context(block), "block/result")); assertEquals(value(context(block), "block/result"), 100.00); block = exert(block, ent("y1", 200.0), ent("y2", 100.0)); // logger.info("block context: " + context(block)); // logger.info("result: " + value(context(block), "block/result")); assertEquals(value(context(block), "block/result"), 500.0); } @Test public void altBlockTest() throws Exception { Task t3 = task("t3", sig("subtract", SubtractorImpl.class), context("subtract", inEnt("arg/t4"), inEnt("arg/t5"), result("block/result", Direction.OUT))); Task t4 = task("t4", sig("multiply", MultiplierImpl.class), context("multiply", inEnt("arg/x1", 10.0), inEnt("arg/x2", 50.0), result("arg/t4", Direction.IN))); Task t5 = task("t5", sig("add", AdderImpl.class), context("add", inEnt("arg/x1", 20.0), inEnt("arg/x2", 80.0), result("arg/t5", Direction.IN))); Task t6 = task("t6", sig("average", AveragerImpl.class), context("average", inEnt("arg/t4"), inEnt("arg/t5"), result("block/result", Direction.OUT))); Block block = block("block", t4, t5, alt(opt(condition(cxt -> (double)v(cxt, "t4") > (double)v(cxt, "t5")), t3), opt(condition(cxt -> (double)v(cxt, "t4") <= (double)v(cxt, "t5")), t6))); // logger.info("block: " + block); // logger.info("exertions: " + exertions(block)); // logger.info("block context: " + context(block)); Block result = exert(block); // logger.info("block context: " + context(result)); // logger.info("result: " + value(context(result), "block/result")); assertEquals(value(context(result), "block/result"), 400.00); // TODO the state after execution changes to reuse the block for another execution? // problem with clearScope() that is commented due to conflict with // return value path when being as input path // result = exert(block, ent("block/t5/arg/x1", 200.0), ent("block/t5/arg/x2", 800.0)); // logger.info("block context: " + context(result)); // logger.info("result: " + value(context(result), "block/result")); // assertEquals(value(context(result), "block/result"), 750.00); t3 = task("t3", sig("subtract", SubtractorImpl.class), context("subtract", inEnt("arg/t4"), inEnt("arg/t5"), result("block/result", Direction.OUT))); t4 = task("t4", sig("multiply", MultiplierImpl.class), context("multiply", inEnt("arg/x1", 10.0), inEnt("arg/x2", 50.0), result("arg/t4", Direction.IN))); t5 = task("t5", sig("add", AdderImpl.class), context("add", inEnt("arg/x1", 20.0), inEnt("arg/x2", 80.0), result("arg/t5", Direction.IN))); t6 = task("t6", sig("average", AveragerImpl.class), context("average", inEnt("arg/t4"), inEnt("arg/t5"), result("block/result", Direction.OUT))); block = block("block", t4, t5, alt(opt(condition(cxt -> (double)value(cxt, "t4") > (double)value(cxt, "t5")), t3), opt(condition(cxt -> (double)value(cxt, "t4") <= (double)value(cxt, "t5")), t6))); result = exert(block, ent("block/t5/arg/x1", 200.0), ent("block/t5/arg/x2", 800.0)); assertEquals(value(context(result), "block/result"), 750.00); } @Test public void optBlockTest() throws Exception { Task t4 = task("t4", sig("multiply", MultiplierImpl.class), context("multiply", inEnt("arg/x1", 10.0), inEnt("arg/x2", 50.0), result("out"))); Task t5 = task("t5", sig("add", AdderImpl.class), context("add", inEnt("arg/x1", 20.0), inEnt("arg/x2", 80.0), result("out"))); Block block = block("block", t4, opt(condition(cxt -> (double)value(cxt, "out") > 600.0), t5)); block = exert(block); // logger.info("block context: " + context(block)); // logger.info("result: " + value(context(block), "out")); assertEquals(value(context(block), "condition/value"), false); assertEquals(value(context(block), "out"), 500.0); block = exert(block, ent("block/t4/arg/x1", 200.0), ent("block/t4/arg/x2", 800.0)); // logger.info("block context: " + context(block)); // logger.info("result: " + value(context(block), "out")); assertEquals(value(context(block), "out"), 100.0); } @Test public void loopBlockTest() throws Exception { Block block = block("block", context(ent("x1", 10.0), ent("x2", 20.0), ent("z", 100.0)), loop(condition(cxt -> (double)value(cxt, "x1") + (double)value(cxt, "x2") < (double)value(cxt, "z")), task(par("x1", invoker("x1 + 3", pars("x1")))))); block = exert(block); logger.info("block context: " + context(block)); logger.info("result: " + value(context(block), "x1")); assertEquals(value(context(block), "x1"), 82.00); } @Test public void parBlockTest() throws Exception { Task t4 = task("t4", sig("multiply", MultiplierImpl.class), context("multiply", inEnt("arg/x1", 10.0), inEnt("arg/x2", 50.0), result("block/result"))); Task t5 = task("t5", sig("add", AdderImpl.class), context("add", inEnt("arg/x1", 20.0), inEnt("arg/x2", 80.0), result("block/result"))); Block block = block("block", sig("execute", ServiceConcatenator.class), context(inEnt("x1", 4), inEnt("x2", 5)), task(par("y", invoker("x1 * x2", pars("x1", "x2")))), alt(opt(condition(cxt -> (int)v(cxt, "y") > 50), t4), opt(condition(cxt -> (int)value(cxt, "y") <= 50 ), t5))); logger.info("block: " + block); logger.info("exertions: " + exertions(block)); logger.info("block context: " + context(block)); block = exert(block); // logger.info("block context: " + context(block)); // logger.info("result: " + value(context(block), "block/result")); assertEquals(value(context(block), "block/result"), 100.00); // block = exert(block, ent("x1", 10.0), ent("x2", 6.0)); //// logger.info("block context: " + context(block)); //// logger.info("result: " + value(context(block), "block/result")); // assertEquals(value(context(block), "block/result"), 500.00); } }
import org.junit.Ignore; import org.junit.Before; import org.junit.Test; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.junit.Assert.assertEquals; public class HandshakeCalculatorTest { private HandshakeCalculator handshakeCalculator; @Before public void setUp() { handshakeCalculator = new HandshakeCalculator(); } @Test public void testThatInput1YieldsAWink() { assertEquals( singletonList(Signal.WINK), handshakeCalculator.calculateHandshake(1)); } @Ignore @Test public void testThatInput2YieldsADoubleBlink() { assertEquals( singletonList(Signal.DOUBLE_BLINK), handshakeCalculator.calculateHandshake(2)); } @Ignore @Test public void testThatInput4YieldsACloseYourEyes() { assertEquals( singletonList(Signal.CLOSE_YOUR_EYES), handshakeCalculator.calculateHandshake(4)); } @Ignore @Test public void testThatInput8YieldsAJump() { assertEquals( singletonList(Signal.JUMP), handshakeCalculator.calculateHandshake(8)); } @Ignore @Test public void testAnInputThatYieldsTwoActions() { assertEquals( asList(Signal.WINK, Signal.DOUBLE_BLINK), handshakeCalculator.calculateHandshake(3)); } @Ignore @Test public void testAnInputThatYieldsTwoReversedActions() { assertEquals( asList(Signal.DOUBLE_BLINK, Signal.WINK), handshakeCalculator.calculateHandshake(19)); } @Ignore @Test public void testReversingASingleActionYieldsTheSameAction() { assertEquals( singletonList(Signal.JUMP), handshakeCalculator.calculateHandshake(24)); } @Ignore @Test public void testReversingNoActionsYieldsNoActions() { assertEquals( emptyList(), handshakeCalculator.calculateHandshake(16)); } @Ignore @Test public void testInputThatYieldsAllActions() { assertEquals( asList(Signal.WINK, Signal.DOUBLE_BLINK, Signal.CLOSE_YOUR_EYES, Signal.JUMP), handshakeCalculator.calculateHandshake(15)); } @Ignore @Test public void testInputThatYieldsAllActionsReversed() { assertEquals( asList(Signal.JUMP, Signal.CLOSE_YOUR_EYES, Signal.DOUBLE_BLINK, Signal.WINK), handshakeCalculator.calculateHandshake(31)); } @Ignore @Test public void testThatInput0YieldsNoActions() { assertEquals( emptyList(), handshakeCalculator.calculateHandshake(0)); } @Ignore @Test public void testThatInputWithLower5BitsNotSetYieldsNoActions() { assertEquals( emptyList(), handshakeCalculator.calculateHandshake(32)); } }
/* * CollectionStore.java - Jun 19, 2003 * * @author wolf */ package org.exist.storage.index; import org.exist.collections.Collection; import org.exist.dom.persistent.DocumentImpl; import org.exist.storage.BrokerPool; import org.exist.storage.btree.DBException; import org.exist.storage.btree.Value; import org.exist.util.*; import java.io.IOException; import java.io.Writer; import java.nio.file.Path; import java.util.Deque; import java.util.concurrent.ConcurrentLinkedDeque; /** * Handles access to the central collection storage file (collections.dbx). * * @author wolf */ public class CollectionStore extends BFile { public static final short FILE_FORMAT_VERSION_ID = 16; public static final String FILE_NAME = "collections.dbx"; public static final String FILE_KEY_IN_CONFIG = "db-connection.collections"; public final static String FREE_DOC_ID_KEY = "__free_doc_id"; public final static String NEXT_DOC_ID_KEY = "__next_doc_id"; public final static String FREE_COLLECTION_ID_KEY = "__free_collection_id"; public final static String NEXT_COLLECTION_ID_KEY = "__next_collection_id"; public final static byte KEY_TYPE_COLLECTION = 0; public final static byte KEY_TYPE_DOCUMENT = 1; private final Deque<Integer> freeResourceIds = new ConcurrentLinkedDeque<>(); private final Deque<Integer> freeCollectionIds = new ConcurrentLinkedDeque<>(); /** * @param pool the broker pool * @param id the if of the collection store * @param dataDir the data directory for the collection store * @param config the database configuration * * @throws DBException if the collection store cannot be constructed. */ public CollectionStore(BrokerPool pool, byte id, Path dataDir, Configuration config) throws DBException { super(pool, id, FILE_FORMAT_VERSION_ID, true, dataDir.resolve(getFileName()), pool.getCacheManager(), 1.25, 0.03); config.setProperty(getConfigKeyForFile(), this); } public static String getFileName() { return FILE_NAME; } public static String getConfigKeyForFile() { return FILE_KEY_IN_CONFIG; } @Override protected long getDataSyncPeriod() { return 1000; } @Override public boolean flush() throws DBException { boolean flushed = false; if (!BrokerPool.FORCE_CORRUPTION) { flushed = flushed | dataCache.flush(); flushed = flushed | super.flush(); } return flushed; } public void freeResourceId(final int id) { freeResourceIds.addFirst(id); } public int getFreeResourceId() { Integer freeDocId = freeResourceIds.pollFirst(); if (freeDocId == null) { freeDocId = DocumentImpl.UNKNOWN_DOCUMENT_ID; } return freeDocId; } public void freeCollectionId(final int id) { freeCollectionIds.addFirst(id); } public int getFreeCollectionId() { Integer freeCollectionId = freeCollectionIds.pollFirst(); if (freeCollectionId == null) { freeCollectionId = Collection.UNKNOWN_COLLECTION_ID; } return freeCollectionId; } protected void dumpValue(Writer writer, Value value) throws IOException { //TODO : what does this 5 stand for ? if (value.getLength() == 5 + Collection.LENGTH_COLLECTION_ID) { final short collectionId = ByteConversion.byteToShort(value.data(), value.start()); //TODO : what does this 1 stand for ? final int docId = ByteConversion.byteToInt(value.data(), value.start() + 1 + Collection.LENGTH_COLLECTION_ID); writer.write('['); writer.write("Document: collection = "); writer.write(collectionId); writer.write(", docId = "); writer.write(docId); writer.write(']'); } else { writer.write('['); writer.write("Collection: "); writer.write(new String(value.data(), value.start(), value.getLength(), "UTF-8")); writer.write(']'); } } public static class DocumentKey extends Value { public static final int OFFSET_TYPE = 0; public static final int LENGTH_TYPE = 1; //sizeof byte public static final int OFFSET_COLLECTION_ID = OFFSET_TYPE + LENGTH_TYPE; public static final int LENGTH_TYPE_DOCUMENT = 2; //sizeof short public static final int OFFSET_DOCUMENT_TYPE = OFFSET_COLLECTION_ID + Collection.LENGTH_COLLECTION_ID; public static final int LENGTH_DOCUMENT_TYPE = 1; //sizeof byte public static final int OFFSET_DOCUMENT_ID = OFFSET_DOCUMENT_TYPE + LENGTH_DOCUMENT_TYPE; public DocumentKey() { data = new byte[LENGTH_TYPE]; data[OFFSET_TYPE] = KEY_TYPE_DOCUMENT; len = LENGTH_TYPE; } public DocumentKey(int collectionId) { data = new byte[LENGTH_TYPE + Collection.LENGTH_COLLECTION_ID]; data[OFFSET_TYPE] = KEY_TYPE_DOCUMENT; ByteConversion.intToByte(collectionId, data, OFFSET_COLLECTION_ID); len = LENGTH_TYPE + Collection.LENGTH_COLLECTION_ID; pos = OFFSET_TYPE; } public DocumentKey(int collectionId, byte type, int docId) { data = new byte[LENGTH_TYPE + Collection.LENGTH_COLLECTION_ID + LENGTH_DOCUMENT_TYPE + DocumentImpl.LENGTH_DOCUMENT_ID]; data[OFFSET_TYPE] = KEY_TYPE_DOCUMENT; ByteConversion.intToByte(collectionId, data, OFFSET_COLLECTION_ID); data[OFFSET_DOCUMENT_TYPE] = type; ByteConversion.intToByte(docId, data, OFFSET_DOCUMENT_ID); len = LENGTH_TYPE + Collection.LENGTH_COLLECTION_ID + LENGTH_DOCUMENT_TYPE + DocumentImpl.LENGTH_DOCUMENT_ID; pos = OFFSET_TYPE; } public static int getCollectionId(Value key) { return ByteConversion.byteToInt(key.data(), key.start() + OFFSET_COLLECTION_ID); } public static int getDocumentId(Value key) { return ByteConversion.byteToInt(key.data(), key.start() + OFFSET_DOCUMENT_ID); } } public static class CollectionKey extends Value { public static final int OFFSET_TYPE = 0; public static final int LENGTH_TYPE = 1; //sizeof byte public static final int OFFSET_VALUE = OFFSET_TYPE + LENGTH_TYPE; public CollectionKey() { data = new byte[LENGTH_TYPE]; data[OFFSET_TYPE] = KEY_TYPE_COLLECTION; len = LENGTH_TYPE; } public CollectionKey(String name) { len = LENGTH_TYPE + UTF8.encoded(name); data = new byte[len]; data[OFFSET_TYPE] = KEY_TYPE_COLLECTION; UTF8.encode(name, data, OFFSET_VALUE); pos = OFFSET_TYPE; } } }
package io.vertx.ext.mongo.impl; import com.mongodb.ConnectionString; import com.mongodb.ServerAddress; import com.mongodb.async.MongoFuture; import com.mongodb.async.client.MongoClient; import com.mongodb.async.client.MongoClients; import com.mongodb.async.client.MongoCollection; import com.mongodb.async.client.MongoDatabase; import com.mongodb.async.client.MongoView; import io.vertx.core.AsyncResult; import io.vertx.core.Context; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.impl.LoggerFactory; import io.vertx.ext.mongo.MongoService; import org.bson.Document; import org.bson.types.ObjectId; import org.mongodb.WriteResult; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.function.Function; public class MongoServiceImpl implements MongoService { private static final Logger log = LoggerFactory.getLogger(MongoServiceImpl.class); private final Vertx vertx; private final JsonObject config; protected MongoClient mongo; protected MongoDatabase db; MongoServiceImpl(Vertx vertx, JsonObject config) { this.vertx = vertx; this.config = config; } public void start() { String connectionString = config.getString("connection_string", "mongodb://localhost:27017"); String dbName = config.getString("db_name", "default_db"); mongo = MongoClients.create(new ConnectionString(connectionString)); db = mongo.getDatabase(dbName); } @Override public void stop() { mongo.close(); } private List<ServerAddress> convertServers(JsonArray servers) throws UnknownHostException { List<ServerAddress> seeds = new ArrayList<>(); for (Object elem : servers) { JsonObject address = (JsonObject) elem; String host = address.getString("host"); int port = address.getInteger("port"); seeds.add(new ServerAddress(host, port)); } return seeds; } @Override public void save(String collection, JsonObject document, String writeConcern, Handler<AsyncResult<String>> resultHandler) { String genID = generateID(document); MongoCollection<Document> coll = getCollection(collection, writeConcern); Document mDoc = jsonToDoc(document); MongoFuture<org.mongodb.WriteResult> future = coll.save(mDoc); adaptFuture(future, resultHandler, wr -> genID); } @Override public void insert(String collection, JsonObject document, String writeConcern, Handler<AsyncResult<String>> resultHandler) { String genID = generateID(document); MongoCollection<Document> coll = getCollection(collection, writeConcern); Document mDoc = jsonToDoc(document); MongoFuture<org.mongodb.WriteResult> future = coll.insert(mDoc); adaptFuture(future, resultHandler, wr -> genID); } @Override public void update(String collection, JsonObject query, JsonObject update, String writeConcern, boolean upsert, boolean multi, Handler<AsyncResult<Void>> resultHandler) { Document mUpdate = jsonToDoc(update); MongoView<Document> view = getView(collection, query, null, null, -1, -1); if (upsert) { view.upsert(); } MongoFuture<WriteResult> future; if (multi) { future = view.update(mUpdate); } else { future = view.updateOne(mUpdate); } adaptFuture(future, resultHandler); } @Override public void find(String collection, JsonObject query, JsonObject fields, JsonObject sort, int limit, int skip, Handler<AsyncResult<List<JsonObject>>> resultHandler) { MongoView<Document> view = getView(collection, query, fields, sort, limit, skip); List<JsonObject> results = new ArrayList<>(); MongoFuture<Void> future = view.forEach(res -> results.add(docToJsonObject(res))); adaptFuture(future, resultHandler, wr -> results); } @Override public void findOne(String collection, JsonObject query, JsonObject fields, Handler<AsyncResult<JsonObject>> resultHandler) { MongoView<Document> view = getView(collection, query, fields, null, -1, -1); MongoFuture<Document> future = view.one(); adaptFuture(future, resultHandler, (Document doc) -> { return doc == null ? null : docToJsonObject(doc); }); } @Override public void delete(String collection, JsonObject query, String writeConcern, Handler<AsyncResult<Void>> resultHandler) { MongoView<Document> view = getView(collection, query, null, null, -1, -1); MongoFuture<WriteResult> future = view.remove(); adaptFuture(future, resultHandler); } @Override public void createCollection(String collectionName, Handler<AsyncResult<Void>> resultHandler) { MongoFuture<Void> future = db.tools().createCollection(collectionName); adaptFuture(future, resultHandler, wr -> null); } @Override public void getCollections(Handler<AsyncResult<List<String>>> resultHandler) { MongoFuture<List<String>> future = db.tools().getCollectionNames(); adaptFuture(future, resultHandler, res -> res); } @Override public void dropCollection(String collection, Handler<AsyncResult<Void>> resultHandler) { MongoCollection<Document> coll = getCollection(collection, null); MongoFuture<Void> future = coll.tools().drop(); adaptFuture(future, resultHandler, v -> null); } @Override public void runCommand(String collection, JsonObject command, Handler<AsyncResult<JsonObject>> resultHandler) { Document mCommand = jsonToDoc(command); MongoFuture<Document> future = db.executeCommand(mCommand); adaptFuture(future, resultHandler, doc -> { return docToJsonObject(doc); }); } private void adaptFuture(MongoFuture<WriteResult> future, Handler<AsyncResult<Void>> resultHandler) { adaptFuture(future, resultHandler, wr -> null); } private <T, U> void adaptFuture(MongoFuture<T> future, Handler<AsyncResult<U>> resultHandler, Function<T, U> converter) { Context context = vertx.context(); future.register((wr, e) -> { context.runOnContext(v -> { if (e != null) { resultHandler.handle(Future.completedFuture(e)); } else { resultHandler.handle(Future.completedFuture(converter.apply(wr))); } }); }); } private String generateID(JsonObject document) { // TODO - is it right that we generate the id here? String genID; if (document.getField("_id") == null) { genID = UUID.randomUUID().toString(); document.putString("_id", genID); } else { genID = null; } return genID; } private MongoView<Document> getView(String collection, JsonObject query, JsonObject fields, JsonObject sort, int limit, int skip) { MongoCollection<Document> coll = getCollection(collection, null); Document mQuery = jsonToDoc(query); Document mFields = jsonToDoc(fields); Document mSort = jsonToDoc(sort); MongoView<Document> view = coll.find(mQuery); if (limit != -1) { view.limit(limit); } if (skip != -1) { view.skip(skip); } if (mSort != null) { view.sort(mSort); } if (mFields != null) { view.fields(mFields); } return view; } private MongoCollection<Document> getCollection(String name, String writeConcern) { // MongoCollectionOptions.Builder builder = MongoCollectionOptions.builder(); // builder.readPreference(ReadPreference.nearest()); // FIXME shouldn't this be defaulted automatically? // if (writeConcern != null) { // WriteConcern wc = WriteConcern.valueOf(writeConcern); // if (wc == null) { // builder.writeConcern(wc); // } else { // builder.writeConcern(WriteConcern.SAFE); // FIXME - shouldn't this be defaulted automatically? // return db.getCollection(name, builder.build()); return db.getCollection(name); } // TODO better conversion private JsonObject docToJsonObject(Document doc) { JsonObject json = new JsonObject(); for (Map.Entry<String, Object> entry: doc.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (value instanceof Date) { // Convert to long json.putNumber(key, ((Date)value).getTime()); } else if (value instanceof ObjectId) { // Convert to String json.getString(key, ((ObjectId)value).toHexString()); } else if (value instanceof Document) { json.putValue(key, docToJsonObject((Document) value)); } else if (value instanceof List) { json.putValue(key, new JsonArray((List)value)); } else { json.putValue(key, value); } } return json; } private Document jsonToDoc(JsonObject jsonObject) { if (jsonObject == null) { return new Document(); } else { return jsonToDoc(jsonObject.toMap()); } } // FIXME - this is very slow - there should be a better way of converting Map to Document in Mongo API! private Document jsonToDoc(Map<String, Object> map) { Document doc = new Document(); for (Map.Entry<String, Object> entry: map.entrySet()) { if (entry.getValue() instanceof Map) { Map inner = (Map)entry.getValue(); doc.put(entry.getKey(), jsonToDoc(inner)); } else { doc.put(entry.getKey(), entry.getValue()); } } return doc; } }
package org.minimalj.test.swing; import java.awt.Component; import java.awt.Container; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import javax.swing.AbstractButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.SwingUtilities; import org.junit.Assert; import org.minimalj.frontend.impl.swing.NavigationTree; import org.minimalj.frontend.impl.swing.SwingFrame; import org.minimalj.frontend.impl.swing.SwingTab; import org.minimalj.frontend.impl.swing.SwingToolBar; import org.minimalj.frontend.impl.swing.component.SwingHtmlContent; import org.minimalj.frontend.impl.swing.toolkit.SwingDialog; import org.minimalj.frontend.impl.swing.toolkit.SwingFrontend.SwingActionText; import org.minimalj.test.ApplicationTestFacade; import org.minimalj.test.LoginFrameFacade.UserPasswordLoginTestFacade; import org.minimalj.test.PageContainerTestFacade; import org.minimalj.test.PageContainerTestFacade.ActionTestFacade; import org.minimalj.test.PageContainerTestFacade.DialogTestFacade; import org.minimalj.test.PageContainerTestFacade.FormTestFacade; import org.minimalj.test.PageContainerTestFacade.NavigationTestFacade; import org.minimalj.test.PageContainerTestFacade.PageTestFacade; import org.minimalj.test.PageContainerTestFacade.TableTestFacade; import org.minimalj.util.resources.Resources; public class SwingTestFacade implements ApplicationTestFacade { public static void waitForEDT() { // SwingDialog do invokeLater with setVisible(true) // this methods does wait till that dialog is really visible try { SwingUtilities.invokeAndWait(() -> {}); } catch (InvocationTargetException | InterruptedException e) { throw new RuntimeException(e); } } @Override public UserPasswordLoginTestFacade getLoginTestFacade() { waitForEDT(); Optional<SwingDialog> loginDialog = Arrays.stream(JDialog.getWindows()).filter(SwingDialog.class::isInstance).map(SwingDialog.class::cast).filter(w -> w.isVisible()).findFirst(); Assert.assertTrue(loginDialog.isPresent()); return new SwingLoginTestFacade(loginDialog.get()); } @Override public PageContainerTestFacade getCurrentPageContainerTestFacade() { Optional<SwingFrame> frame = Arrays.stream(JFrame.getWindows()).filter(SwingFrame.class::isInstance).map(SwingFrame.class::cast).filter(w -> w.isVisible()).findFirst(); Assert.assertTrue(frame.isPresent()); return new SwingFrameTestFacade(frame.get()); } private static class SwingLoginTestFacade implements UserPasswordLoginTestFacade { private final SwingDialog swingDialog; public SwingLoginTestFacade(SwingDialog swingDialog) { this.swingDialog = swingDialog; Assert.assertEquals(Resources.getString("Login.title"), swingDialog.getTitle()); } @Override public boolean hasSkipLogin() { Component button = SwingTestUtils.getComponent(swingDialog, Resources.getString("SkipLoginAction")); return button != null; } @Override public boolean hasClose() { return true; } @Override public void login() { SwingTestUtils.click(swingDialog, "LoginAction"); } @Override public void cancel() { // TODO Auto-generated method stub } @Override public void close() { // TODO Auto-generated method stub } @Override public void setUser(String name) { SwingTestUtils.setText(swingDialog, "UserPassword.user", name); } @Override public void setPassword(String password) { SwingTestUtils.setText(swingDialog, "UserPassword.password", password); } } @Override public void logout() { // TODO Auto-generated method stub } private static class SwingFrameTestFacade implements PageContainerTestFacade { private final SwingFrame frame; public SwingFrameTestFacade(SwingFrame frame) { this.frame = frame; } @Override public NavigationTestFacade getNavigation() { NavigationTree navigationTree = SwingTestUtils.getComponent(frame, NavigationTree.class); return new SwingNavigationTestFacade(navigationTree); } @Override public List<PageTestFacade> getPages() { SwingTab tab = frame.getVisibleTab(); JPanel panel = (JPanel) SwingTestUtils.getComponent(tab, c -> { if (c instanceof Container) { return ((Container) c).getLayout() instanceof org.minimalj.frontend.impl.swing.SwingTab.VerticalLayoutManager; } else { return false; } }); List<PageTestFacade> pages = new ArrayList<>(); for (Component c : panel.getComponents()) { Component content; String title; if (c instanceof JTabbedPane) { content = ((JTabbedPane) c).getComponentAt(0); title = ((JTabbedPane) c).getTitleAt(0); } else { content = c; while (!(c instanceof JTabbedPane)) { c = c.getParent(); } JTabbedPane container = (JTabbedPane) c; title = container.getTitleAt(container.getSelectedIndex()); } if (content instanceof SwingHtmlContent) { SwingHtmlContent htmlContent = (SwingHtmlContent) content; // pages.add(new TextPageTestFacade(title, htmlContent.getText())); pages.add(new SwingPageTestFacade(title, htmlContent)); } } return pages; } @Override public DialogTestFacade getDialog() { waitForEDT(); Optional<SwingDialog> dialog = Arrays.stream(JFrame.getWindows()). filter(SwingDialog.class::isInstance).map(SwingDialog.class::cast). filter(d -> d.getOwnedWindows().length == 0).findFirst(); return dialog.isPresent() ? new SwingDialogTestFacade(dialog.get()) : null; } @Override public ActionTestFacade getBack() { SwingToolBar toolBar = SwingTestUtils.getComponent(frame, SwingToolBar.class); AbstractButton button = (AbstractButton) SwingTestUtils.getComponent(toolBar, Resources.getString("PreviousPageAction")); return new SwingButtonActionTestFacade(button); } @Override public ActionTestFacade getForward() { // TODO Auto-generated method stub return null; } } private static class SwingDialogTestFacade implements DialogTestFacade { private final SwingDialog swingDialog; public SwingDialogTestFacade(SwingDialog swingDialog) { this.swingDialog = swingDialog; } @Override public FormTestFacade getForm() { // TODO Auto-generated method stub return null; } @Override public ActionTestFacade getAction(String caption) { // TODO Auto-generated method stub return null; } } private static class SwingNavigationTestFacade implements NavigationTestFacade { private final NavigationTree navigationTree; public SwingNavigationTestFacade(NavigationTree navigationTree) { this.navigationTree = navigationTree; } @Override public Runnable get(String resourceName) { String caption = Resources.getString(resourceName); SwingActionText actionText = (SwingActionText) SwingTestUtils.getComponent(navigationTree, caption); if (actionText != null) { return () -> SwingTestUtils.click(actionText); } else { return null; } } } private static class SwingButtonActionTestFacade implements ActionTestFacade { private final AbstractButton button; public SwingButtonActionTestFacade(AbstractButton button) { this.button = button; } @Override public void run() { SwingTestUtils.click(button); } @Override public boolean isEnabled() { return button.isEnabled() && button.isVisible(); } } private static class SwingPageTestFacade implements PageTestFacade { private final String title; private final Component content; public SwingPageTestFacade(String title, Component content) { super(); this.title = title; this.content = content; } @Override public String getTitle() { return title; } @Override public NavigationTestFacade getContextMenu() { // TODO Auto-generated method stub return null; } @Override public void executeQuery(String query) { // TODO Auto-generated method stub } @Override public TableTestFacade getTable() { // TODO Auto-generated method stub return null; } @Override public FormTestFacade getForm() { // TODO Auto-generated method stub return null; } @Override public boolean contains(String string) { if (content instanceof SwingHtmlContent) { SwingHtmlContent htmlContent = (SwingHtmlContent) content; return htmlContent.getText().contains(string); } return false; } } }
package edu.umd.cs.findbugs.detect; import edu.umd.cs.findbugs.*; import java.util.*; import org.apache.bcel.classfile.*; import edu.umd.cs.findbugs.visitclass.Constants2; public class MutableStaticFields extends BytecodeScanningDetector implements Constants2 { static String extractPackage(String c) { int i = c.lastIndexOf('/'); if (i < 0) return ""; return c.substring(0,i); } static boolean mutableSignature(String sig) { return sig.equals("Ljava/util/Hashtable;") || sig.equals("Ljava/util/Date;") || sig.charAt(0) == '['; } static class FieldRecord { String className; String name; String signature; boolean isPublic; boolean isFinal; } LinkedList<FieldRecord> seen = new LinkedList<FieldRecord>(); boolean publicClass; boolean zeroOnTOS; boolean emptyArrayOnTOS; boolean inStaticInitializer; String packageName; HashSet<String> unsafeValue = new HashSet<String>(); HashSet<String> interfaces = new HashSet<String>(); HashSet<String> notFinal = new HashSet<String>(); HashSet<String> outsidePackage = new HashSet<String>(); private BugReporter bugReporter; public MutableStaticFields(BugReporter bugReporter) { this.bugReporter = bugReporter; } public void visit(JavaClass obj) { super.visit(obj); int flags = obj.getAccessFlags(); publicClass = (flags & ACC_PUBLIC) != 0 && !getDottedClassName().startsWith("sun."); if ((flags & ACC_INTERFACE) != 0) interfaces.add(getDottedClassName()); packageName = extractPackage(getClassName()); } public void visit(Method obj) { zeroOnTOS = false; // System.out.println(methodName); inStaticInitializer = getMethodName().equals("<clinit>"); } public void sawOpcode(int seen) { // System.out.println("saw " + OPCODE_NAMES[seen] + " " + zeroOnTOS); switch (seen) { case GETSTATIC: case PUTSTATIC: String packageConstant = extractPackage(getClassConstantOperand()); boolean samePackage = packageName.equals(extractPackage(getClassConstantOperand())); boolean initOnly = seen == GETSTATIC || getClassName().equals(getClassConstantOperand()) && inStaticInitializer; boolean safeValue = seen == GETSTATIC || emptyArrayOnTOS || !mutableSignature(getSigConstantOperand()); String name = (getClassConstantOperand() + "." + getNameConstantOperand()) .replace('/','.'); /* System.out.println("In " + betterClassName + " accessing " + (classConstant + "." + nameConstant) + " " + samePackage + " " + initOnly + " " + safeValue ); */ if (!samePackage) outsidePackage.add(name); if (!initOnly) notFinal.add(name); if (!safeValue) unsafeValue.add(name); break; case ANEWARRAY: case NEWARRAY: if (zeroOnTOS) emptyArrayOnTOS = true; zeroOnTOS = false; return; case ICONST_0: zeroOnTOS = true; emptyArrayOnTOS = false; return; } zeroOnTOS = false; emptyArrayOnTOS = false; } public void visit(Field obj) { super.visit(obj); int flags = obj.getAccessFlags(); boolean isStatic = (flags & ACC_STATIC) != 0; if (!isStatic) return; boolean isFinal = (flags & ACC_FINAL) != 0; boolean isPublic = publicClass && (flags & ACC_PUBLIC) != 0; boolean isProtected = publicClass && (flags & ACC_PROTECTED) != 0; if (!isPublic && !isProtected) return; boolean isHashtable = getFieldSig().equals("Ljava/util/Hashtable;"); boolean isArray = getFieldSig().charAt(0) == '['; if (isFinal && !(isHashtable || isArray)) return; FieldRecord f = new FieldRecord(); f.className = getDottedClassName(); f.name = getFieldName(); f.signature = getDottedFieldSig(); f.isPublic = isPublic; f.isFinal = isFinal; seen.add(f); } public void report() { /* for(Iterator i = unsafeValue.iterator(); i.hasNext(); ) { System.out.println("Unsafe: " + i.next()); } */ for(Iterator<FieldRecord> i = seen.iterator(); i.hasNext(); ) { FieldRecord f = i.next(); boolean isFinal = f.isFinal; String className = f.className; String fieldSig = f.signature; String fieldName = f.name; String name = className + "." + fieldName; boolean couldBeFinal = !isFinal && !notFinal.contains(name); boolean isPublic = f.isPublic; boolean couldBePackage = !outsidePackage.contains(name); boolean movedOutofInterface = couldBePackage && interfaces.contains(className); boolean isHashtable = fieldSig.equals("Ljava/util/Hashtable;"); boolean isArray = fieldSig.charAt(0) == '[' && unsafeValue.contains(name); /* System.out.println(className + "." + fieldName + " : " + fieldSig + " " + isHashtable + " " + isArray ); */ String bugType; int priority = NORMAL_PRIORITY; if (isFinal && !isHashtable && !isArray) { // System.out.println( name +" is a safe zero length array"); continue; } else if (movedOutofInterface) { bugType = "MS_OOI_PKGPROTECT"; } else if (couldBePackage && couldBeFinal && (isHashtable || isArray)) bugType = "MS_FINAL_PKGPROTECT"; else if (couldBeFinal && !isHashtable && !isArray) { bugType = "MS_SHOULD_BE_FINAL"; if (fieldName.equals(fieldName.toUpperCase())) priority = HIGH_PRIORITY; } else if (couldBePackage) bugType = "MS_PKGPROTECT"; else if (isHashtable) bugType = "MS_MUTABLE_HASHTABLE"; else if (isArray) bugType = "MS_MUTABLE_ARRAY"; else if (!isFinal) bugType = "MS_CANNOT_BE_FINAL"; else throw new RuntimeException("impossible"); bugReporter.reportBug(new BugInstance(bugType, priority) .addClass(className) .addField(className, fieldName, fieldSig, true)); } } }
package edu.ntnu.idi.goldfish.preprocessors; import edu.ntnu.idi.goldfish.mahout.SMDataModel; import edu.ntnu.idi.goldfish.mahout.SMPreference; import org.apache.commons.math3.stat.correlation.PearsonsCorrelation; import org.apache.mahout.cf.taste.common.NoSuchItemException; import org.apache.mahout.cf.taste.common.TasteException; import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator; import org.apache.mahout.cf.taste.model.DataModel; import org.apache.mahout.cf.taste.model.Preference; import org.apache.mahout.cf.taste.model.PreferenceArray; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class Preprocessor { private final int THRESHOLD = 3; private final int TIME_ON_PAGE_INDEX = 1; private final int RATING_INDEX = 0; private Map<String, Float> correlations = new HashMap<String, Float>(); private static Set<String> pseudoRatings = new HashSet<String>(); public static DataModel getPreprocessedDataModel(String path) throws TasteException, IOException { SMDataModel model; model = new SMDataModel(new File(path)); Preprocessor pre = new Preprocessor(); pre.preprocess(model); return model; } public static boolean isPseudoPreference(Preference pref) { return pseudoRatings.contains(String.format("%d_%d", pref.getUserID(), pref.getItemID())); } public boolean checkIfPreferenceHasImplicitFeedback(float[] feedback){ // start with index 1 because index 0 is explicit rating for (int i = 1; i < feedback.length; i++) { if (feedback[i] >= 1) { return true; } } return false; } public int getBestCorrelatedFeedback(PreferenceArray prefs, float[] feedback) throws NoSuchItemException{ int bestCorrelated = -1; // iterate through implicit values and use the one with highest correlation for (int i = 1; i < feedback.length; i++) { if (bestCorrelated == -1 || getCorrelation(prefs, i) > getCorrelation(prefs, bestCorrelated)) { bestCorrelated = i; } } return bestCorrelated; } /** * For each missing explicit value (when implicit feedback exist), check if enough explicit-implicit * rating pairs exists, if so, create a pseudo rating and add it to the dataset * @param model * the model to preprocess * @throws TasteException */ public void preprocess(SMDataModel model) throws TasteException { KernelEstimatorHistogram keh = new KernelEstimatorHistogram(model); System.out.println(String.format("Most dense implicit value is %d",keh.getMostDenseImplicit())); // iterate through all items LongPrimitiveIterator it = model.getItemIDs(); while (it.hasNext()) { long itemID = it.next(); PreferenceArray prefs = model.getPreferencesForItem(itemID); // iterate through all prefs for item for (Preference p : prefs) { SMPreference pref = (SMPreference) p; boolean hasExplicit = pref.getValue(RATING_INDEX) >= 1; if (!hasExplicit) { float[] feedback = pref.getValues(); boolean hasImplicit = checkIfPreferenceHasImplicitFeedback(feedback); int ratingPairs = getNumberOfRatingPairs(prefs); // do we have enough pairs of explicit and implicit feedback in order to map // from implicit feedback to an explicit rating (pseudo rating) ? if (hasImplicit && ratingPairs >= THRESHOLD) { int bestCorrelated = getBestCorrelatedFeedback(prefs, feedback); double correlation = getCorrelation(prefs, bestCorrelated); if (Math.abs(correlation) > 0.5) { // we have now ensured that a relationship between the implicit and explicit feedback // exist and will continue to find pseudoRatings // I: get pseudoRating based on linear regression float pseudoRating = getPseudoRatingLinearRegression(prefs, pref, bestCorrelated, ratingPairs); // II: get pseudoRating based on closest neighbor // float pseudoRating = getPseudoRatingClosestNeighbor(prefs, pref, bestCorrelated); // III: get pseudoRating based on rating bins // float pseudoRating = getPseudoRatingEqualBins(pref, correlation, prefs, bestCorrelated); // set explicit value as pseudoRating pref.setValue(pseudoRating, 0); // remember the pseudoRatings to ensure they are only used in the training set pseudoRatings.add(String.format("%d_%d", pref.getUserID(), pref.getItemID())); } } else if(feedback[TIME_ON_PAGE_INDEX] > keh.getMostDenseImplicit()){ // according to CEO Tony Haile at Chartbeat people that spends more than // 15 seconds on an article like the article // Morita and Shinoda (1994) concluded that the most effective threshold concerning // reading time is 20 seconds, which yielded 30% recall and 70% precision pref.setValue(4, 0); pseudoRatings.add(String.format("%d_%d", pref.getUserID(), pref.getItemID())); // System.out.println(String.format("User spent more than 15 seconds on item: %d, " // + "lets give it 4", itemID)); } // else if (vals[1] < 17500 && vals[1] > 1000){ // pref.setValue(2, 0); // pseudoRatings.add(String.format("%d_%d", pref.getUserID(), pref.getItemID())); // else if(vals[2] > 700){ // // with time on mouse = 700, most users give an article rating 4 // pref.setValue(4,0); // System.out.println(String.format("User has used the mouse more than 7 seconds on item: %d, " // + "lets give it 4", itemID)); } } } } /** * Finds the pseudo rating given an article without explicit rating by using linear regression on the * implicit feedback that correlates best with the ratings given by users. * @param prefs * all preferences for a given article * @param currentPref * the preference without explicit rating and hence will get a pseudo rating * @param bestCorrelated * index of the best correlated implicit feedback * @param ratingPairs * number of explicit and implicit feedback that is used in linear expression * @return * a pseudo rating based on linear regression */ private float getPseudoRatingLinearRegression(PreferenceArray prefs, SMPreference currentPref, int bestCorrelated, int ratingPairs){ double[] explRatings = new double[ratingPairs]; double[] implRatings = new double[ratingPairs]; try { explRatings = getRatings(prefs,0); implRatings = getRatings(prefs, bestCorrelated); } catch (NoSuchItemException e) { e.printStackTrace(); System.err.println("Linear regression could not retrive explicit and/or implicit ratings"); } TrendLine t = new PolyTrendLine(1); t.setValues(explRatings, implRatings); return (float) Math.round(t.predict(currentPref.getValue(bestCorrelated))); } /** * Finds the pseudo rating given an article without explicit rating by using the closest neighbor, * that is, the neighbor with implicit feedback that resembles the given article most * @param prefs * all preferences for a given article * @param currentPref * the preference without explicit value and hence will get a pseudo rating * @param bestCorrelated * the implicit feedback index with highest correlation * @return * a pseudo rating based on closest neighbor */ private float getPseudoRatingClosestNeighbor(PreferenceArray prefs, SMPreference currentPref, int bestCorrelated) { float diff = Float.MAX_VALUE; SMPreference closestPref = null; for (Preference pref : prefs) { SMPreference p = (SMPreference) pref; float tempDiff = Math.abs(currentPref.getValue(1) - p.getValue(bestCorrelated)); if (tempDiff < diff) { diff = tempDiff; closestPref = p; } } return closestPref.getValue(0); } /** * Finds the pseudo rating based on equal size bins, requires at least two ratings, which becomes the * biggest and smallest bin. * @param currentPref * the preference without explicit value and hence will get a pseudo rating * @param correlation * if correlation is negative, pseudo rating is 6 - correlation * @param prefs * all preferences for a given article * @param bestCorrelated * the implicit feedback index with highest correlation * @return * a pseudo rating based on equal bins */ private int getPseudoRatingEqualBins(SMPreference currentPref, double correlation, PreferenceArray prefs, int bestCorrelated) { float min = Integer.MAX_VALUE; float max = Integer.MIN_VALUE; int pseudoRating; for (Preference pref : prefs) { SMPreference smp = (SMPreference) pref; float implicit = smp.getValue(bestCorrelated); if (implicit < min) { min = implicit; } if (implicit > max) { max = implicit; } } if (min == max) { return 3; } if(currentPref.getValue(bestCorrelated) < min){ pseudoRating = 1; } else if(currentPref.getValue(bestCorrelated) > max) { pseudoRating = 5; } else{ float binSize = (max-min)/5; float dif = currentPref.getValue(bestCorrelated) - min; pseudoRating = (int) (1 + Math.floor(dif/binSize)); } if (correlation < 0) { pseudoRating = 6 - pseudoRating; } return pseudoRating; } public double getCorrelation(PreferenceArray prefs, int implicitIndex) throws NoSuchItemException { double[] expl = getRatings(prefs, 0); double[] impl = getRatings(prefs, implicitIndex); PearsonsCorrelation pc = new PearsonsCorrelation(); return pc.correlation(expl, impl); } /** * * @param model * @param itemID * @param index * 0 = explicit, 1,2...n = implicit * @return * Returns all ratings for a given type of feedback given by the index parameter. * Also ensure that every rating returned has an explicit rating. * @throws NoSuchItemException */ public double[] getRatings(PreferenceArray prefs, int index) throws NoSuchItemException{ // create a list of ratings since we don't know how many rating-pairs exist List<Double> tempRatings = new ArrayList<Double>(); for (int i = 0; i < prefs.length(); i++) { SMPreference p = (SMPreference) prefs.get(i); // ensure that we have explicit value if(p.getValue(0) <= 0) { continue; } tempRatings.add((double) p.getValue(index)); } // create the array of ratings with size of ratings-pairs double[] ratings = new double[tempRatings.size()]; for (int i = 0; i < ratings.length; i++) { ratings[i] = tempRatings.get(i); } return ratings; } public int getNumberOfRatingPairs(PreferenceArray prefs) { int pairs = 0; for (int i = 0; i < prefs.length(); i++) { SMPreference p = (SMPreference) prefs.get(i); // ensure that we have explicit value if(p.getValue(0) >= 1) { pairs++; } } return pairs; } //TODO: fix a better way of finding which implicit feedback we can use to create pseudo ratings public List<double[]> getImplicitFeedbackWithEnoughRatingPairs(PreferenceArray prefs, int feedbackLength){ List<double[]> feedbacks = new ArrayList<double[]>(); // create a list of ratings since we don't know how many rating-pairs exist for (int j = 1; j < feedbackLength; j++) { List<Double> tempExplRatings = new ArrayList<Double>(); List<Double> tempImplRatings = new ArrayList<Double>(); for (int i = 0; i < prefs.length(); i++) { SMPreference p = (SMPreference) prefs.get(i); // ensure that we have explicit value if(p.getValue(0) >= 0 && p.getValue(j) >= 0) { tempExplRatings.add((double) p.getValue(RATING_INDEX)); tempImplRatings.add((double) p.getValue(j)); } } if(tempExplRatings.size() >= THRESHOLD && tempImplRatings.size() >= THRESHOLD){ double[] explRatings = new double[tempExplRatings.size()]; double[] implRatings = new double[tempImplRatings.size()]; for (int i = 0; i < implRatings.length; i++) { explRatings[i] = tempExplRatings.get(i); implRatings[i] = tempImplRatings.get(i); } } } return null; } }
import java.lang.RuntimeException; import java.io.*; /** * This class is specifically written for performing matrix calculations (or manipulation). * * Created using TextMate version 2.0 on a Mac OS X 10.10.5 system. */ class Matrices { /** * Default constructor. */ public Matrices() { } /** * An Exception class. * Thrown when an invalid matrix manipulation (operation) is ever attempted. */ private static class InvalidMatrixCalculationException extends RuntimeException { /** * Default constructor. * * @param message */ public InvalidMatrixCalculationException(String message) { super(message); } } /** * @param args (arguments passed via command prompt) */ public static void main(String[] args) { // Test. if (true) { throw new InvalidMatrixCalculationException("Invalid matrix calculation."); } } }
package edu.ucsb.cs56.projects.games.poker; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.*; import java.lang.String; import java.lang.System; import java.net.URL; import java.util.ArrayList; /** * Class that represents a Texas Holdem' Style Poker Game. */ public class PokerGameMult { // PokerGame States /** * enum representing the game winner */ // if OPPONENT, loop through public enum Result { PLAYER, OPPONENT, TIE, NEW_GAME, END_GAME }; public boolean Fold = false; /** * enum representing the game step */ public enum Step { BLIND, FLOP, TURN, RIVER, SHOWDOWN }; public enum Type { PLAYER, COMPUTER }; static int MAXPLAYERS = 4; // PokerGame GUI // Properties of Poker Game /** * ArrayList holding the game's current players */ protected ArrayList<Player> players; protected Player winner; protected int winnerIdx; /** * The deck used for the game */ protected Deck deck; /** * The cards currently on the table */ protected TableCards table; /** * The current pot */ protected int pot; /** * The current bet */ protected int bet = 0; /** * Information/instructions displayed to the user */ protected String message, prompt; /** * Image of the back of the card */ protected ImageIcon backCardImage; /** * The round winner */ protected Result resultType = Result.NEW_GAME; /** * Variable representing the game winner * winner = 0 : players[0] is the winner * winner = 1 : players[1] is the winner * etc. */ /** * The current game step */ protected Step step; /** * Which player's turn it is */ protected int turn; /** * Variable representing which player's turn it is * turn = 0 : players[0] turn * turn = 1 : players[1] turn * etc */ protected int activePlayers; protected int totalPlayers; /** * The back of a card */ protected Card backCard; // Booleans variable /** * Whether or not one player is responding to the other player's move */ protected boolean responding = false; /** * The game status */ protected boolean gameOver = false; /** * Whether or not someone has gone all in */ protected boolean allIn = false; /* * No arg constructor that initializes a new deck. */ // Single Player public PokerGameMult() { this.deck = new Deck(); players = new ArrayList<Player>(); players.add(new User(500,deck)); players.add(new OpponentAI(500, deck)); for (int i = 0; i < players.size(); i++) { players.get(i).setIndex(i); } this.table = new TableCards(deck); pot = 0; totalPlayers = players.size(); } // Multiplayer // Current Functionality Supports One User and (MAXPLAYER - 1) AIs // if mode == true, singlePlayer // if mode == false, multiPlayer public PokerGameMult(boolean mode) { this.deck = new Deck(); this.table = new TableCards(deck); pot = 0; players = new ArrayList<Player>(); players.add(new User(500, deck)); if (mode == true) { players.add(new OpponentAI(500, deck)); } else { for (int i = 0; i < MAXPLAYERS-1; i++) { players.add(new OpponentAI(500, deck)); } } for (int i = 0; i < players.size(); i++) { players.get(i).setIndex(i); } totalPlayers = players.size(); } /** * not currently in use **/ public PokerGameMult(int totalplayers) { this.deck = new Deck(); this.table = new TableCards(deck); pot = 0; players = new ArrayList<Player>(); players.add(new User(500, deck)); for (int i = 0; i < totalplayers-1; i++) { players.add(new OpponentAI(500, deck)); } for (int i = 0; i < players.size(); i++) { players.get(i).setIndex(i); } totalPlayers = players.size(); } // Getters and setters for various members /** * Returns the current pot * @return the current pot */ public int getPot() { return pot; } /** * Adds a bet to the current pot * @param pot the pot's new value */ public void addToPot(int bet) { this.pot += bet; } /** * Returns the current bet * @return the current bet */ public int getCurrentBet() { return bet; } /** * Sets the current bet * @param bet the number to set the current bet to */ public void setBet(int bet) { this.bet = bet; } /** * Returns the game's current step * @return the current step */ public Step getStep() { return step; } /** * Returns if the player is responding to the move * @return whether or not the player is responding */ public boolean isResponding() { return responding; } /** * Sets responding to true or false * @param responding responding's new value */ public void setResponding(boolean responding) { this.responding = responding; } /** * Returns whether or not it is all-in in the current game * @return the boolean value of allIn */ public boolean isAllIn() { return allIn; } /** * Sets the current message being displayed * @param message the new message */ public void setMessage(String message) { this.message = message; } /** TODO: Change for multiplayer * Sets up the player's and opponent's hand. */ public void setUp() { for(Player player:players) { player.setDelegate(this); if (player.getChips() >= 5) { player.bet(5); pot += 5; } else { gameOver = true; showWinnerAlert(); } } message = "Ante of 5 chips set."; backCard = new Card(100, "B"); String dir = "Cards/"; String cardFile = "B.png"; URL url = getClass().getResource(dir + cardFile); backCardImage = new ImageIcon(url); } /** * Returns an ImageIcon by using the URL class in order to make the * ImageIcon web compatible * @param c whose image is to be retrieved * @return ImageIcon */ public ImageIcon getCardImage(Card c) { String dir = "Cards/"; String cardFile = c.toString() + ".png"; URL url = getClass().getResource(dir + cardFile); return new ImageIcon(url); } /** TODO: Change for multiplayer * PlayerDelegate method handles folding */ // COULD IMPROVE IMPLEMENTATION protected int lowestTurn = 0; public void fold() { // temp iterator lowestTurn++; activePlayers = 0; // after a player folds, check for all activePlayers in game for (Player player:players) { if (player.status == 1) { activePlayers +=1; //player.winStatus = true; } } if (turn != 0) { System.out.println("Opponent " + (turn) + " folds."); } System.out.println(activePlayers + " active players remaining."); // if activePlayers = 1, they win. if (activePlayers == 1) { for (Player player: players) { if (player.status == 1) { winnerIdx = players.indexOf(player); } } Fold = true; collectPot(); showWinnerAlert(); // Reset player win flag // deck.reShuffle(); resultType = Result.END_GAME; } if (activePlayers > 1) { for (Player player:players) { player.winStatus = false; } // after a player folds, prompt the next active player to take their turn while (players.get(turn).status == 0) { turn++; } players.get(turn).takeTurn(); } } /** TODO: Change for multiplayer * Function that transfers winnings to a player */ protected void collectPot() { for (Player player:players) { if (player.winStatus == true) { if (player.getType() == 1) { System.out.println("Player " + players.indexOf(player)); System.out.println(String.format("%d", pot)); } else if (player.getType() == 0) { System.out.println("Opponent"); System.out.println(String.format("%d", pot)); } int playerChips = player.getChips(); playerChips += pot; player.setChips(playerChips); player.win(); return; } } System.out.println("Tie"); System.out.println(String.format("%d", pot)); int chipsGained = pot/activePlayers; for (Player player:players) { if (player.status ==1) { int playerChips = player.getChips(); playerChips += chipsGained; player.setChips(playerChips); } } } /** TODO: Change for multiplayer * Method to determine the winner of the game */ public void determineWinner() { CompareHands comparison = new CompareHands(players, table); int win = comparison.compareHands(); System.out.println(win); winnerIdx = win; //compareHands() returns player index of winning player if(win < 0) return; else { Player winner = players.get(win); //players.get(win).win(); players.get(win).winStatus = true; } } public String winningHandMessage(){ CompareHands comparison = new CompareHands(players, table); return comparison.compareMessage(); } /** * Method to pass the turn from opponent to player, or player to opponent * Must be overridden!!! */ public void changeTurn() { } /** * Method used to advance the game from each step to the next. * Specifically, in the order Blind-Flop-Turn-River-Showdown */ public void nextStep() { //Now implemented in PokerSinglePlayer } /** * This state is for the turn * Purpose is to be overriden in PokerClient */ protected void checkPassTurnUpdate() { changeTurn(); } /** * Method shows winner and exits game. * Overridden to actually do stuff in children */ public void showWinnerAlert() { } /** * Method that updates the panels in the GUI based on the current game state * Must be overriden (preferrably in the GUI class) */ public void updateFrame() { } /** * Called when it is a user's turn * Must be overridden */ public void userTurn() { } /** * Restarts the timer * Must be overridden */ public void restartTimer() { } }
package edu.usc.glidein.service.db.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Calendar; import java.util.LinkedList; import java.util.TimeZone; import edu.usc.glidein.service.db.DatabaseException; import edu.usc.glidein.service.db.GlideinDAO; import edu.usc.glidein.service.db.JDBCUtil; import edu.usc.glidein.stubs.types.Glidein; import edu.usc.glidein.stubs.types.GlideinStatus; public class MySQLGlideinDAO implements GlideinDAO { private MySQLDatabase database = null; public MySQLGlideinDAO(MySQLDatabase db) { this.database = db; } public int create(Glidein glidein) throws DatabaseException { Connection conn = null; int id = 0; try { conn = database.getConnection(); id = createGlidein(conn, glidein); conn.commit(); } catch (DatabaseException dbe) { JDBCUtil.rollbackQuietly(conn); throw dbe; } catch (SQLException sqle) { JDBCUtil.rollbackQuietly(conn); throw new DatabaseException("Unable to create glidein: commit failed",sqle); } finally { JDBCUtil.closeQuietly(conn); } return id; } private int createGlidein(Connection connection, Glidein glidein) throws DatabaseException { int id = 0; PreparedStatement stmt = null; ResultSet rs = null; try { stmt = connection.prepareStatement("INSERT INTO glidein (site, count, hostCount, wallTime, numCpus, condorConfigBase64, gcbBroker, idleTime, condorDebug, status, statusMessage, submitted, lastUpdate, condorHost) VALUES (?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW(),?)"); int i = 1; stmt.setInt(i++, glidein.getSiteId()); stmt.setInt(i++, glidein.getCount()); stmt.setInt(i++, glidein.getHostCount()); stmt.setInt(i++, glidein.getWallTime()); stmt.setInt(i++, glidein.getNumCpus()); stmt.setString(i++, glidein.getCondorConfigBase64()); stmt.setString(i++, glidein.getGcbBroker()); stmt.setInt(i++, glidein.getIdleTime()); stmt.setString(i++, glidein.getCondorDebug()); stmt.setString(i++, glidein.getStatus().toString()); stmt.setString(i++, glidein.getStatusMessage()); stmt.setString(i++, glidein.getCondorHost()); if (stmt.executeUpdate()!=1) { throw new DatabaseException("Unable to create glidein: wrong number of db updates"); } // Get new ID rs = stmt.getGeneratedKeys(); if (rs.next()) { id = rs.getInt(1); glidein.setId(id); } else { throw new DatabaseException("Unable to get generated glidein id"); } } catch(SQLException sqle) { throw new DatabaseException("Unable to create glidein: insert failed",sqle); } finally { JDBCUtil.closeQuietly(rs); JDBCUtil.closeQuietly(stmt); } return id; } public Glidein load(int glideinId) throws DatabaseException { Connection conn = null; try { conn = database.getConnection(); return getGlidein(conn, glideinId); } finally { JDBCUtil.closeQuietly(conn); } } private Glidein getGlidein(Connection connection, int glideinId) throws DatabaseException { PreparedStatement stmt = null; ResultSet rs = null; try { stmt = connection.prepareStatement("SELECT g.*, s.name siteName FROM glidein g, site s WHERE g.id=? AND g.site=s.id"); stmt.setInt(1, glideinId); rs = stmt.executeQuery(); if (rs.next()) { return newGlidein(rs); } else { throw new DatabaseException("Glidein "+glideinId+" not found"); } } catch(SQLException sqle) { throw new DatabaseException("Unable to load glidein: select failed",sqle); } finally { JDBCUtil.closeQuietly(rs); JDBCUtil.closeQuietly(stmt); } } public void store(Glidein glidein) throws DatabaseException { updateStatus(glidein.getId(), glidein.getStatus(), glidein.getStatusMessage()); } public void delete(int glideinId) throws DatabaseException { Connection conn = null; PreparedStatement stmt = null; try { conn = database.getConnection(); /* Cascaded deletes should take care of the other tables */ stmt = conn.prepareStatement("DELETE FROM glidein WHERE id=?"); stmt.setInt(1, glideinId); if (stmt.executeUpdate() != 1) { throw new DatabaseException("Unable to delete glidein: wrong number of db updates"); } conn.commit(); } catch (DatabaseException dbe) { JDBCUtil.rollbackQuietly(conn); throw dbe; } catch (SQLException sqle) { JDBCUtil.rollbackQuietly(conn); throw new DatabaseException("Unable to delete glidein: delete failed",sqle); } finally { JDBCUtil.closeQuietly(stmt); JDBCUtil.closeQuietly(conn); } } public void updateStatus(int glideinId, GlideinStatus status, String statusMessage) throws DatabaseException { Connection conn = null; PreparedStatement stmt = null; try { stmt = conn.prepareStatement("UPDATE glidein SET status=?, statusMessage=? WHERE id=?"); stmt.setString(1, status.toString()); stmt.setString(2, statusMessage); stmt.setInt(3, glideinId); if (stmt.executeUpdate()!=1) { throw new DatabaseException("Unable to update glidein status: wrong number of db updates"); } conn.commit(); } catch (DatabaseException dbe) { JDBCUtil.rollbackQuietly(conn); throw dbe; } catch (SQLException sqle) { JDBCUtil.rollbackQuietly(conn); throw new DatabaseException("Unable to update glidein status: update failed",sqle); } finally { JDBCUtil.closeQuietly(stmt); JDBCUtil.closeQuietly(conn); } } public Glidein[] list(boolean longFormat) throws DatabaseException { Connection conn = null; try { conn = database.getConnection(); return getGlideins(conn, longFormat); } finally { JDBCUtil.closeQuietly(conn); } } private Glidein[] getGlideins(Connection connection, boolean longFormat) throws DatabaseException { PreparedStatement stmt = null; ResultSet rs = null; LinkedList<Glidein> results = new LinkedList<Glidein>(); try { // Join to get the site name stmt = connection.prepareStatement("SELECT g.*, s.name siteName FROM glidein g, site s WHERE g.site=s.id"); rs = stmt.executeQuery(); while (rs.next()) { results.add(newGlidein(rs)); } return results.toArray(new Glidein[0]); } catch(SQLException sqle) { throw new DatabaseException("Unable to load glidein: select failed",sqle); } finally { JDBCUtil.closeQuietly(rs); JDBCUtil.closeQuietly(stmt); } } private Glidein newGlidein(ResultSet rs) throws DatabaseException { try { Glidein glidein = new Glidein(); glidein.setId(rs.getInt("id")); glidein.setSiteId(rs.getInt("site")); glidein.setSiteName(rs.getString("siteName")); glidein.setCount(rs.getInt("count")); glidein.setHostCount(rs.getInt("hostCount")); glidein.setWallTime(rs.getInt("wallTime")); glidein.setNumCpus(rs.getInt("numCpus")); glidein.setCondorConfigBase64(rs.getString("condorConfigBase64")); glidein.setGcbBroker(rs.getString("gcbBroker")); glidein.setIdleTime(rs.getInt("idleTime")); glidein.setCondorDebug(rs.getString("condorDebug")); glidein.setCondorHost(rs.getString("condorHost")); glidein.setStatus(GlideinStatus.fromString(rs.getString("status"))); glidein.setStatusMessage(rs.getString("statusMessage")); Calendar submitted = Calendar.getInstance(TimeZone.getDefault()); Timestamp submit = rs.getTimestamp("submitted",submitted); submitted.setTime(submit); glidein.setSubmitted(submitted); Calendar lastUpdate = Calendar.getInstance(TimeZone.getDefault()); Timestamp last = rs.getTimestamp("lastUpdate",lastUpdate); lastUpdate.setTime(last); glidein.setLastUpdate(lastUpdate); return glidein; } catch (SQLException sqle) { throw new DatabaseException("Unable to create Glidein object",sqle); } } }
package edu.wheaton.simulator.statistics; import java.util.Map; import com.google.common.collect.ImmutableMap; import edu.wheaton.simulator.entity.Agent; import edu.wheaton.simulator.entity.Prototype; import edu.wheaton.simulator.entity.Slot; /** * This class will create the Snapshots to be put into the Database * * @author akonwi and Daniel Gill */ public class SnapshotFactory { public static AgentSnapshot makeAgentSnapshot(Agent agent, Integer step) { // Sort out with the Agent guys just wtf is up with fields. return null; // TODO } public static SlotSnapshot makeSlotSnapshot(Slot slot, Integer step) { return null; // TODO } /** * Make a FieldSnapshot from the associated name and value. * @param name The name of the field. * @param value The value of the field. * @return A FieldSnapshot corresponding to the pair of Strings. */ public static FieldSnapshot makeFieldSnapshot(String name, String value) { return new FieldSnapshot(name, value); } public static ImmutableMap<String, FieldSnapshot> makeFieldSnapshots(Map<String, String> fields) { ImmutableMap.Builder<String, FieldSnapshot> builder = new ImmutableMap.Builder<String, FieldSnapshot>(); for (String name : fields.keySet()) { String value = fields.get(name); builder.put(name, makeFieldSnapshot(name, value)); } return builder.build(); } public static PrototypeSnapshot makePrototypeSnapshot(Prototype prototype, Integer step) { return null; // TODO } private SnapshotFactory() { } }
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class HelloBufferedInputAndOutputStreams { private static String FILENAME = "test.txt"; private static final int LINECOUNT = 5; public static void main(String... args) { System.out.println("Hello Buffered Input and Output Streams!"); try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(FILENAME)));) { for (int i = 0; i < LINECOUNT; i++) { bos.write("Hello World\n".getBytes()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(FILENAME)));) { while (bis.available() != 0) { System.out.print((char) bis.read()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
// @@@ use lrmc here package ibis.satin.impl.faultTolerance; import ibis.ipl.ReadMessage; import ibis.ipl.StaticProperties; import ibis.ipl.WriteMessage; import ibis.satin.impl.Config; import ibis.satin.impl.Satin; import ibis.satin.impl.communication.Protocol; import ibis.satin.impl.loadBalancing.Victim; import ibis.satin.impl.spawnSync.InvocationRecord; import ibis.satin.impl.spawnSync.Stamp; import ibis.util.Timer; import java.io.IOException; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; final class GlobalResultTable implements Config, Protocol { private Satin s; /** The entries in the global result table. Entries are of type * GlobalResultTableValue. */ private Map entries; /** A list of updates that has to be broadcast to the other nodes. Elements are * of type (Stamp, GlobalResultTableValue). */ private Map toSend; private GlobalResultTableValue pointerValue = new GlobalResultTableValue( GlobalResultTableValue.TYPE_POINTER, null); protected GlobalResultTable(Satin s, StaticProperties requestedProperties) { this.s = s; entries = new Hashtable(); toSend = new Hashtable(); } protected GlobalResultTableValue lookup(Stamp key) { if (key == null) return null; s.stats.lookupTimer.start(); Satin.assertLocked(s); GlobalResultTableValue value = (GlobalResultTableValue) entries .get(key); if (value != null) { grtLogger .debug("SATIN '" + s.ident + "': lookup successful " + key); if (value.type == GlobalResultTableValue.TYPE_POINTER) { if (!s.deadIbises.contains(value.owner)) { s.stats.tableSuccessfulLookups++; s.stats.tableRemoteLookups++; } } else { s.stats.tableSuccessfulLookups++; } } s.stats.tableRemoteLookups++; s.stats.lookupTimer.stop(); return value; } protected void storeResult(InvocationRecord r) { Satin.assertLocked(s); s.stats.updateTimer.start(); GlobalResultTableValue value = new GlobalResultTableValue( GlobalResultTableValue.TYPE_RESULT, r); Stamp key = r.getStamp(); Object oldValue = entries.get(key); entries.put(key, value); s.stats.tableResultUpdates++; if (entries.size() > s.stats.tableMaxEntries) { s.stats.tableMaxEntries = entries.size(); } if (oldValue == null) { toSend.put(key, pointerValue); s.ft.updatesToSend = true; } grtLogger.debug("SATIN '" + s.ident + "': update complete: " + key + "," + value); s.stats.updateTimer.stop(); } protected void updateAll(Map updates) { Satin.assertLocked(s); s.stats.updateTimer.start(); entries.putAll(updates); toSend.putAll(updates); s.stats.tableResultUpdates += updates.size(); if (entries.size() > s.stats.tableMaxEntries) { s.stats.tableMaxEntries = entries.size(); } s.stats.updateTimer.stop(); s.ft.updatesToSend = true; } protected void sendUpdates() { Timer updateTimer = null; Timer tableSerializationTimer = null; int size = 0; synchronized (s) { s.ft.updatesToSend = false; size = s.victims.size(); } if (size == 0) return; updateTimer = Timer.createTimer(); updateTimer.start(); for(int i=0; i<size; i++) { Victim send; WriteMessage m = null; synchronized (s) { send = s.victims.getVictim(i); } try { m = send.newMessage(); } catch (IOException e) { grtLogger.info("Got exception in newMessage()", e); continue; //always happens after a crash } tableSerializationTimer = Timer.createTimer(); tableSerializationTimer.start(); try { m.writeByte(GRT_UPDATE); m.writeObject(toSend); } catch (IOException e) { grtLogger.info("Got exception in writeObject()", e); //always happens after a crash } tableSerializationTimer.stop(); s.stats.tableSerializationTimer.add(tableSerializationTimer); try { long msgSize = m.finish(); grtLogger.debug("SATIN '" + s.ident + "': " + msgSize + " sent in " + s.stats.tableSerializationTimer.lastTimeVal() + " to " + send); } catch (IOException e) { grtLogger.info("Got exception in finish()"); //always happens after a crash } } s.stats.tableUpdateMessages++; updateTimer.stop(); s.stats.updateTimer.add(updateTimer); } // Returns ready to send contents of the table. protected Map getContents() { Satin.assertLocked(s); // Replace "real" results with pointer values. Map newEntries = new HashMap(); Iterator iter = entries.entrySet().iterator(); while (iter.hasNext()) { Map.Entry element = (Map.Entry) iter.next(); GlobalResultTableValue value = (GlobalResultTableValue) element .getValue(); Stamp key = (Stamp) element.getKey(); switch (value.type) { case GlobalResultTableValue.TYPE_RESULT: newEntries.put(key, pointerValue); break; case GlobalResultTableValue.TYPE_POINTER: newEntries.put(key, value); break; default: grtLogger.error("SATIN '" + s.ident + "': EEK invalid value type in getContents()"); } } return newEntries; } protected void addContents(Map contents) { Satin.assertLocked(s); grtLogger.debug("adding contents"); entries.putAll(contents); if (entries.size() > s.stats.tableMaxEntries) { s.stats.tableMaxEntries = entries.size(); } } protected void handleGRTUpdate(ReadMessage m) { Map map = null; s.stats.handleUpdateTimer.start(); s.stats.tableDeserializationTimer.start(); try { map = (Map) m.readObject(); } catch (Exception e) { grtLogger.error("SATIN '" + s.ident + "': Global result table - error reading message", e); } s.stats.tableDeserializationTimer.stop(); // no need to finish the message synchronized (s) { addContents(map); } s.stats.handleUpdateTimer.stop(); } protected void print(java.io.PrintStream out) { synchronized (s) { out.println("=GRT: " + s.ident + "="); int i = 0; Iterator iter = entries.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); out.println("GRT[" + i + "]= " + entry.getKey() + ";" + entry.getValue()); i++; } out.println("=end of GRT " + s.ident + "="); } } }
package info.guardianproject.otr.app.im.app; import info.guardianproject.otr.app.im.IImConnection; import info.guardianproject.otr.app.im.R; import info.guardianproject.otr.app.im.app.adapter.ConnectionListenerAdapter; import info.guardianproject.otr.app.im.engine.ImConnection; import info.guardianproject.otr.app.im.engine.ImErrorInfo; import info.guardianproject.otr.app.im.provider.Imps; import info.guardianproject.otr.app.im.service.ImServiceConstants; import info.guardianproject.util.LogCleaner; import java.util.Collection; import java.util.HashSet; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.os.AsyncTask; import android.os.DeadObjectException; import android.os.Handler; import android.os.RemoteException; import android.util.Log; import android.widget.TextView; import android.widget.Toast; /** * Handle sign-in process for activities. * * @author devrandom * * <p>Users of this helper must call {@link SignInHelper#stop()} to clean up callbacks * in their onDestroy() or onPause() lifecycle methods. * * <p>The helper listens to connection events. It automatically stops listening when the * connection state is logged-in or disconnected (failed). */ public class SignInHelper { Activity mContext; private SimpleAlertHandler mHandler; private ImApp mApp; private MyConnectionListener mListener; private Collection<IImConnection> connections; private SignInListener mSignInListener; // This can be used to be informed of signin events public interface SignInListener { void connectedToService(); void stateChanged(int state, long accountId); } public SignInHelper(Activity context, SignInListener listener) { this.mContext = context; mHandler = new SimpleAlertHandler(context); mListener = new MyConnectionListener(mHandler); mSignInListener = listener; if (mApp == null) { mApp = (ImApp)mContext.getApplication(); } connections = new HashSet<IImConnection>(); } public SignInHelper(Activity context) { this(context, null); } public void setSignInListener(SignInListener listener) { mSignInListener = listener; } public void stop() { for (IImConnection connection : connections) { try { connection.unregisterConnectionListener(mListener); } catch (RemoteException e) { // Ignore } } connections.clear(); } private final class MyConnectionListener extends ConnectionListenerAdapter { MyConnectionListener(Handler handler) { super(handler); } @Override public void onConnectionStateChange(IImConnection connection, int state, ImErrorInfo error) { handleConnectionEvent(connection, state, error); } } private void handleConnectionEvent(IImConnection connection, int state, ImErrorInfo error) { long accountId; long providerId; try { accountId = connection.getAccountId(); providerId = connection.getProviderId(); } catch (RemoteException e) { // Ouch! Service died! We'll just disappear. Log.w(ImApp.LOG_TAG, "<SigningInActivity> Connection disappeared while signing in!"); return; } if (mSignInListener != null) mSignInListener.stateChanged(state, accountId); // Stop listening if we get into a resting state if (state == ImConnection.LOGGED_IN || state == ImConnection.DISCONNECTED) { connections.remove(connection); try { connection.unregisterConnectionListener(mListener); } catch (RemoteException e) { mHandler.showServiceErrorAlert(e.getLocalizedMessage()); LogCleaner.error(ImApp.LOG_TAG, "handle connection error",e); } } if (state == ImConnection.DISCONNECTED) { // sign in failed final ProviderDef provider = mApp.getProvider(providerId); if (provider != null) //a provider might have been deleted { String providerName = provider.mName; Resources r = mContext.getResources(); String errMsg = r.getString(R.string.login_service_failed, providerName, // FIXME error == null ? "" : ErrorResUtils.getErrorRes(r, error.getCode())); // Toast.makeText(mContext, errMsg, Toast.LENGTH_LONG).show(); /* new AlertDialog.Builder(mContext).setTitle(R.string.error) .setMessage() .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // FIXME } }).setCancelable(false).show(); */ } } } public void goToAccount(long accountId) { Intent intent; intent = new Intent(mContext, NewChatActivity.class); // clear the back stack of the account setup intent.putExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, accountId); mContext.startActivity(intent); // sign in successfully, finish and switch to contact list // mContext.finish(); } public void signIn(final String password, final long providerId, final long accountId, final boolean isActive) { final ProviderDef provider = mApp.getProvider(providerId); if (provider != null) //provider may be null if deleted, or db not updated yet { final String providerName = provider.mName; if (mApp.serviceConnected()) { if (mSignInListener != null) mSignInListener.connectedToService(); if (!isActive) { activateAccount(providerId, accountId); } signInAccount(password, providerId, providerName, accountId); } else { mApp.callWhenServiceConnected(mHandler, new Runnable() { public void run() { if (mApp.serviceConnected()) { if (mSignInListener != null) mSignInListener.connectedToService(); if (!isActive) { activateAccount(providerId, accountId); } signInAccount(password, providerId, providerName, accountId); } } }); } } } private void signInAccount(final String password, final long providerId, final String providerName, final long accountId) { Runnable runnable = new Runnable () { public void run () { try { signInAccountAsync(password, providerId, providerName, accountId); } catch (RemoteException e) { Log.d(ImApp.LOG_TAG,"error signing in",e); } } }; new Thread(runnable).start(); } private void signInAccountAsync(String password, long providerId, String providerName, long accountId) throws RemoteException { boolean autoLoadContacts = true; boolean autoRetryLogin = true; IImConnection conn = null; conn = mApp.getConnection(providerId); if (conn != null) { connections.add(conn); conn.registerConnectionListener(mListener); int state = conn.getState(); if (mSignInListener != null) mSignInListener.stateChanged(state, accountId); if (state != ImConnection.DISCONNECTED) { // already signed in or in the process if (state == ImConnection.LOGGED_IN) { connections.remove(conn); conn.unregisterConnectionListener(mListener); } handleConnectionEvent(conn, state, null); return; } } else { conn = mApp.createConnection(providerId, accountId); if (conn == null) { // This can happen when service did not come up for any reason return; } connections.add(conn); conn.registerConnectionListener(mListener); } conn.login(password, autoLoadContacts, autoRetryLogin); /* if (mApp.isNetworkAvailableAndConnected()) { } else { // promptForBackgroundDataSetting(providerName); return; }*/ } /** * Popup a dialog to ask the user whether he/she wants to enable background * connection to continue. If yes, enable the setting and broadcast the * change. Otherwise, quit the signing in window immediately. */ private void promptForBackgroundDataSetting(String providerName) { Toast.makeText(mContext, mContext.getString(R.string.bg_data_prompt_message, providerName), Toast.LENGTH_LONG).show(); } public void activateAccount(long providerId, long accountId) { // Update the active value. We restrict to only one active // account per provider right now, so update all accounts of // this provider to inactive first and then update this // account to active. ContentValues values = new ContentValues(1); values.put(Imps.Account.ACTIVE, 0); ContentResolver cr = mContext.getContentResolver(); cr.update(Imps.Account.CONTENT_URI, values, Imps.Account.PROVIDER + "=" + providerId, null); values.put(Imps.Account.ACTIVE, 1); cr.update(ContentUris.withAppendedId(Imps.Account.CONTENT_URI, accountId), values, null, null); } }
package fr.paris.lutece.portal.service.init; /** * this class provides informations about application version */ public final class AppInfo { /** Defines the current version of the application */ private static final String APP_VERSION = "2.3.0"; /** * Creates a new AppInfo object. */ private AppInfo( ) { } /** * Returns the current version of the application * @return APP_VERSION The current version of the application */ public static String getVersion( ) { return APP_VERSION; } }
package ie.ucd.clops.runtime.parser; import static ie.ucd.clops.runtime.options.IMatchable.SEP_STRING; import ie.ucd.clops.logging.CLOLogger; import ie.ucd.clops.runtime.automaton.Automaton; import ie.ucd.clops.runtime.automaton.Token; import ie.ucd.clops.runtime.automaton.Tokenizer; import ie.ucd.clops.runtime.automaton.exception.AutomatonException; import ie.ucd.clops.runtime.errors.AmbiguousCommandLineError; import ie.ucd.clops.runtime.errors.IncompleteCommandLineError; import ie.ucd.clops.runtime.errors.InvalidOptionValueError; import ie.ucd.clops.runtime.errors.ParseResult; import ie.ucd.clops.runtime.errors.UnknownOptionError; import ie.ucd.clops.runtime.errors.ValidityError; import ie.ucd.clops.runtime.options.CLOPSErrorOption; import ie.ucd.clops.runtime.options.IMatchable; import ie.ucd.clops.runtime.options.Option; import ie.ucd.clops.runtime.options.OptionStore; import ie.ucd.clops.runtime.options.exception.InvalidOptionValueException; import ie.ucd.clops.runtime.rules.RuleStore; import ie.ucd.clops.util.StringUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Command line parser. * * @author Mikolas Janota * @author Fintan * @author Viliam Holub */ public class GenericCLParser { public static final boolean DO_ERROR_RECOVERY = false; private static final Logger log = Logger.getLogger("ie.ucd.clops"); public GenericCLParser() {} /** * Represents a possible way to parse a piece of the command * line. The {@code option} matches on the command line string * starting at {@code startIndex}. A `parse' is a sequence of * parse steps. `Applying a parse step' {@code s} means that we * call {@code s.option.setValueFromString(s.optionValue)} (and * the corresponding fly rules are applied). */ static final private class ParseStep { public Option<?> option; public String optionValue; public int optionMatchLength; public int position; public ParseStep(Option<?> option, int position) { this.option = option; optionMatchLength = option.getMatchLength(); optionValue = option.getMatchingValueString(); this.position = position; } @Override public boolean equals(Object o) { if (!(o instanceof ParseStep)) return false; ParseStep t = (ParseStep)o; if (optionMatchLength != t.optionMatchLength) return false; if (option == null ^ t.option == null) return false; if (optionValue == null ^ t.optionValue == null) return false; return option.equals(t.option) && optionValue.equals(t.optionValue); } @Override public int hashCode() { return optionMatchLength + (option == null? 0 : option.hashCode()) + (optionValue == null? 0 : optionValue.hashCode()); } } private HashSet<ArrayList<ParseStep>> parsingPossibilities; private ArrayList<ParseStep> currentParse; private OptionStore optionStore; private RuleStore ruleStore; private Automaton<IMatchable> automaton; private String commandLine; /** * If there is exactly one way to parse the command line * then it parses the command line and returns {@code true}, * otherwise returns {@code false}. Errors in the DSL may cause * this function to throw exception. Exceptions may also be * thrown if options refuse to set their values from the given * string. * * TODO(rgrig): The interface of this function should clearly * separate errors in the DSL from errors in the command line. */ public ParseResult alternateParse( String formatString, OptionStore optionStore, RuleStore ruleStore, String[] args) throws Tokenizer.IllegalCharacterException, Tokenizer.UnknownOptionException { ParseResult result = new ParseResult(StringUtil.appendWithSeparator(args, " ", false)); this.optionStore = optionStore; this.ruleStore = ruleStore; buildAutomaton(formatString); commandLine = StringUtil.appendWithSeparator(args, SEP_STRING, true); parsingPossibilities = new HashSet<ArrayList<ParseStep>>(); currentParse = new ArrayList<ParseStep>(); recursiveParse(0); if (parsingPossibilities.size() > 1) { log.fine("There are " + parsingPossibilities.size() + " parsing possibilities."); //TODO better errors here - index of divergence, other information result.addError(new AmbiguousCommandLineError("There are " + parsingPossibilities.size() + " parsing possibilities.")); return result; } else if (parsingPossibilities.size() == 0) { log.fine("There are " + parsingPossibilities.size() + " parsing possibilities."); //TODO better errors here - index of no match result.addError(new UnknownOptionError("There are " + parsingPossibilities.size() + " parsing possibilities.")); return result; } result.addAll(applyParse(parsingPossibilities.iterator().next())); if (!result.successfulParse()) { return result; } ruleStore.applyValidityRules(optionStore); List<String> validityErrorList = ((CLOPSErrorOption)optionStore.getOptionByIdentifier( CLOPSErrorOption.ERROR_OPTION_ID)).getValue(); for (String error : validityErrorList) { log.fine(error); result.addError(new AmbiguousCommandLineError(error)); } return result; } private void recursiveParse(int startIndex) { if (startIndex == commandLine.length()) { if (automaton.isAccepting()) parsingPossibilities.add(new ArrayList<ParseStep>(currentParse)); return; } Collection<IMatchable> possibleTransitions = automaton.availableTransitionsUnique(); Map<ParseStep, Set<IMatchable>> matches = new HashMap<ParseStep, Set<IMatchable>>(); for (IMatchable t : possibleTransitions) { Option<?> option = t.getMatchingOption(commandLine, startIndex); if (option == null) continue; ParseStep step = new ParseStep(option, startIndex); Set<IMatchable> transitions = matches.get(step); if (transitions == null) { transitions = new HashSet<IMatchable>(); matches.put(step, transitions); } transitions.add(t); } for (Map.Entry<ParseStep, Set<IMatchable>> e : matches.entrySet()) { automaton.nextStep(e.getValue()); currentParse.add(e.getKey()); recursiveParse(startIndex + e.getKey().optionMatchLength); currentParse.remove(currentParse.size() - 1); automaton.previousStep(); } } private ParseResult applyParse(List<ParseStep> parse) { ParseResult result = new ParseResult(); for (ParseStep step : parse) { try { step.option.setFromString(step.optionValue); } catch (InvalidOptionValueException e) { result.addError(new InvalidOptionValueError(e.getMessage(), step.position)); } if (result.successfulParse()) { log.fine("Set option: " + step.option); result.addAll(ruleStore.applyFlyRules(step.option, optionStore)); } if (!DO_ERROR_RECOVERY && !result.successfulParse()) { return result; } } result.addAll(ruleStore.applyOverrideRules(optionStore)); return result; } private void buildAutomaton(String formatString) throws Tokenizer.IllegalCharacterException, Tokenizer.UnknownOptionException, AutomatonException { List<Token<IMatchable>> tokens = new Tokenizer().tokenize(formatString, optionStore); automaton = new Automaton<IMatchable>(tokens); } /** * Parse the given commandline. * @param formatString the format regular expression in a string form * @param ruleStore collection of fly rules that should be used during parsing * @param optionStore collection of options that will be matched against the input * @param args the commandline as given to the main method * @return {@code true} iff the commmandline has been successfully parsed */ public ParseResult parse(String formatString, OptionStore optionStore, RuleStore ruleStore, String[] args) { ParseResult result = new ParseResult(StringUtil.appendWithSeparator(args, " ", false)); CLOLogger.getLogger().log(Level.FINE, "Number of args: " + args.length); CLOLogger.getLogger().log(Level.FINE, Arrays.asList(args).toString()); CLOLogger.getLogger().log(Level.FINE, ruleStore.toString()); //Set up automaton List<Token<IMatchable>> tokens = null; Automaton<IMatchable> automaton = null; try { tokens = new Tokenizer().tokenize(formatString, optionStore); } catch (Tokenizer.UnknownOptionException e) { CLOLogger.getLogger().log(Level.SEVERE, "Error: Unkown option name \"" +e.opt_name +"\"."); throw e; } catch (Tokenizer.IllegalCharacterException e) { //TODO: logger? CLOLogger.getLogger().log(Level.SEVERE, "Error: Illegal character \"" +formatString.charAt( e.index) +"\" at position " +e.index +"."); throw e; } automaton = new Automaton<IMatchable>(tokens); //Convert args to single string String argumentString = StringUtil.appendWithSeparator(args, SEP_STRING, true); //Main loop for (int i=0; i < argumentString.length(); ) { //Get available next options Collection<IMatchable> possibleTransitions = automaton.availableTransitionsUnique(); CLOLogger.getLogger().log(Level.FINE, "Transitions: " + possibleTransitions); CLOLogger.getLogger().log(Level.FINE, "Set options: "); CLOLogger.getLogger().log(Level.FINE, optionStore.toString()); //Matched option Option<?> matchedOption = null; Set<IMatchable> matches = new HashSet<IMatchable>(); //Try and find a match for (IMatchable transition : possibleTransitions) { Option<?> newMatchedOption = transition.getMatchingOption(argumentString, i); if (newMatchedOption != null) { //We cannot match on two different Options if (matchedOption != null && matchedOption != newMatchedOption) { CLOLogger.getLogger().log(Level.SEVERE, "Matched two options: " + matchedOption + " and " + newMatchedOption); result.addError(new AmbiguousCommandLineError("Matched two options: " + matchedOption + " and " + newMatchedOption)); return result; } matchedOption = newMatchedOption; matches.add(transition); } } if (matchedOption == null) { // If no match was found CLOLogger.getLogger().log(Level.SEVERE, "Illegal option: " + suggestUnmatchedOption(argumentString, i)); // debugging //TODO index of no match result.addError(new UnknownOptionError("Illegal option: " + suggestUnmatchedOption(argumentString, i))); return result; } else { //We should have at least one transition assert matches.size() > 0; //Update automaton CLOLogger.getLogger().log(Level.FINE, "Matches: " + matches); automaton.nextStep(matches); CLOLogger.getLogger().log(Level.FINE, "Matched option: " + matchedOption); ProcessingResult pr = matchedOption.process(); if (pr.errorDuringProcessing()) { //output error CLOLogger.getLogger().log(Level.SEVERE, pr.getErrorMessage()); result.addError(new InvalidOptionValueError(pr.getErrorMessage(), i)); if (!DO_ERROR_RECOVERY) { return result; } } else { i += matchedOption.getMatchLength(); CLOLogger.getLogger().log(Level.FINE, "Applying fly rules"); result.addAll(ruleStore.applyFlyRules(matchedOption, optionStore)); CLOLogger.getLogger().log(Level.FINE, "Done applying fly rules"); if (!DO_ERROR_RECOVERY && !result.successfulParse()) { return result; } } } } CLOLogger.getLogger().log(Level.FINE, "finished parsing"); CLOLogger.getLogger().log(Level.FINE, "Final Option values: "); CLOLogger.getLogger().log(Level.FINE, optionStore.toString()); CLOLogger.getLogger().log(Level.FINE, "Accepting: " + automaton.isAccepting()); if (automaton.isAccepting()) { result.addAll(ruleStore.applyOverrideRules(optionStore)); CLOLogger.getLogger().log(Level.FINE, "Override rules complete."); if (!result.successfulParse()) { return result; } ruleStore.applyValidityRules(optionStore); CLOLogger.getLogger().log(Level.FINE, "Validity checks complete."); List<String> validityErrorList = ((CLOPSErrorOption)optionStore.getOptionByIdentifier(CLOPSErrorOption.ERROR_OPTION_ID)).getValue(); if (validityErrorList.size() > 0) { //We had a validity error. CLOLogger.getLogger().log(Level.FINE, "Validity check failed."); for (String errorMessage : validityErrorList) { if (errorMessage != null && !errorMessage.equals("")) { CLOLogger.getLogger().log(Level.FINE, errorMessage); result.addError(new ValidityError(errorMessage)); } } return result; } else { CLOLogger.getLogger().log(Level.FINE, "Validity checks passed."); } return result; } else { CLOLogger.getLogger().log(Level.SEVERE, "Invalid arguments."); //TODO print usage string? print possible next args? result.addError(new IncompleteCommandLineError("Invalid arguments.")); return result; } } private static final Pattern unmatcher = Pattern.compile(Option.SEP + "*[^" + Option.SEP_STRING + "]+"); private static String suggestUnmatchedOption(String argumentString, int offset) { Matcher matcher = unmatcher.matcher(argumentString); matcher.region(offset, argumentString.length()); if (matcher.lookingAt()) { return matcher.group(); } else { return ""; } } }
package org.apache.commons.collections.map; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections.IteratorUtils; import org.apache.commons.collections.iterators.EntrySetMapIterator; import org.apache.commons.collections.iterators.MapIterator; import org.apache.commons.collections.iterators.ResettableIterator; public class Flat3Map implements Map { /** The size of the map, used while in flat mode */ private int iSize; /** Hash, used while in flat mode */ private int iHash1; /** Hash, used while in flat mode */ private int iHash2; /** Hash, used while in flat mode */ private int iHash3; /** Key, used while in flat mode */ private Object iKey1; /** Key, used while in flat mode */ private Object iKey2; /** Key, used while in flat mode */ private Object iKey3; /** Value, used while in flat mode */ private Object iValue1; /** Value, used while in flat mode */ private Object iValue2; /** Value, used while in flat mode */ private Object iValue3; /** Map, used while in delegate mode */ private HashMap iMap; /** * Constructor. */ public Flat3Map() { super(); } /** * Constructor copying elements from another map. * * @param map the map to copy */ public Flat3Map(Map map) { super(); putAll(map); } /** * Gets the value mapped to the key specified. * * @param key the key * @return the mapped value, null if no match */ public Object get(Object key) { if (iMap != null) { return iMap.get(key); } if (key == null) { switch (iSize) { // drop through case 3: if (iKey3 == null) return iValue3; case 2: if (iKey2 == null) return iValue2; case 1: if (iKey1 == null) return iValue1; } } else { if (iSize > 0) { int hashCode = key.hashCode(); switch (iSize) { // drop through case 3: if (iHash3 == hashCode && key.equals(iKey3)) return iValue3; case 2: if (iHash2 == hashCode && key.equals(iKey2)) return iValue2; case 1: if (iHash1 == hashCode && key.equals(iKey1)) return iValue1; } } } return null; } /** * Gets the size of the map. * * @return the size */ public int size() { if (iMap != null) { return iMap.size(); } return iSize; } /** * Checks whether the map is currently empty. * * @return true if the map is currently size zero */ public boolean isEmpty() { return (size() == 0); } /** * Checks whether the map contains the specified key. * * @param key the key to search for * @return true if the map contains the key */ public boolean containsKey(Object key) { if (iMap != null) { return iMap.containsKey(key); } if (key == null) { switch (iSize) { // drop through case 3: if (iKey3 == null) return true; case 2: if (iKey2 == null) return true; case 1: if (iKey1 == null) return true; } } else { if (iSize > 0) { int hashCode = key.hashCode(); switch (iSize) { // drop through case 3: if (iHash3 == hashCode && key.equals(iKey3)) return true; case 2: if (iHash2 == hashCode && key.equals(iKey2)) return true; case 1: if (iHash1 == hashCode && key.equals(iKey1)) return true; } } } return false; } /** * Checks whether the map contains the specified value. * * @param value the value to search for * @return true if the map contains the key */ public boolean containsValue(Object value) { if (iMap != null) { return iMap.containsValue(value); } if (value == null) { // drop through switch (iSize) { case 3: if (iValue3 == null) return true; case 2: if (iValue2 == null) return true; case 1: if (iValue1 == null) return true; } } else { switch (iSize) { // drop through case 3: if (value.equals(iValue3)) return true; case 2: if (value.equals(iValue2)) return true; case 1: if (value.equals(iValue1)) return true; } } return false; } /** * Puts a key-value mapping into this map. * * @param key the key to add * @param value the value to add * @return the value previously mapped to this key, null if none */ public Object put(Object key, Object value) { if (iMap != null) { return iMap.put(key, value); } // change existing mapping if (key == null) { switch (iSize) { // drop through case 3: if (iKey3 == null) { Object old = iValue3; iValue3 = value; return old; } case 2: if (iKey2 == null) { Object old = iValue2; iValue2 = value; return old; } case 1: if (iKey1 == null) { Object old = iValue1; iValue1 = value; return old; } } } else { if (iSize > 0) { int hashCode = key.hashCode(); switch (iSize) { // drop through case 3: if (iHash3 == hashCode && key.equals(iKey3)) { Object old = iValue3; iValue3 = value; return old; } case 2: if (iHash2 == hashCode && key.equals(iKey2)) { Object old = iValue2; iValue2 = value; return old; } case 1: if (iHash1 == hashCode && key.equals(iKey1)) { Object old = iValue1; iValue1 = value; return old; } } } } // add new mapping switch (iSize) { default: convertToMap(); iMap.put(key, value); return null; case 2: iHash3 = (key == null ? 0 : key.hashCode()); iKey3 = key; iValue3 = value; break; case 1: iHash2 = (key == null ? 0 : key.hashCode()); iKey2 = key; iValue2 = value; break; case 0: iHash1 = (key == null ? 0 : key.hashCode()); iKey1 = key; iValue1 = value; break; } iSize++; return null; } /** * Puts all the values from the specified map into this map. * * @param map */ public void putAll(Map map) { int size = map.size(); if (size == 0) { return; } if (iMap != null) { iMap.putAll(map); return; } if (size < 4) { for (Iterator it = map.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); put(entry.getKey(), entry.getValue()); } } else { convertToMap(); iMap.putAll(map); } } /** * Converts the flat map data to a HashMap. */ private void convertToMap() { iMap = new HashMap(); switch (iSize) { // drop through case 3: iMap.put(iKey3, iValue3); case 2: iMap.put(iKey2, iValue2); case 1: iMap.put(iKey1, iValue1); } iSize = 0; iHash1 = iHash2 = iHash3 = 0; iKey1 = iKey2 = iKey3 = null; iValue1 = iValue2 = iValue3 = null; } /** * Removes the specified mapping from this map. * * @param key the mapping to remove * @return the value mapped to the removed key, null if key not in map */ public Object remove(Object key) { if (iMap != null) { return iMap.remove(key); } if (iSize == 0) { return null; } if (key == null) { switch (iSize) { // drop through case 3: if (iKey3 == null) { Object old = iValue3; iHash3 = 0; iKey3 = null; iValue3 = null; iSize = 2; return old; } if (iKey2 == null) { Object old = iValue3; iHash2 = iHash3; iKey2 = iKey3; iValue2 = iValue3; iHash3 = 0; iKey3 = null; iValue3 = null; iSize = 2; return old; } if (iKey1 == null) { Object old = iValue3; iHash1 = iHash3; iKey1 = iKey3; iValue1 = iValue3; iHash3 = 0; iKey3 = null; iValue3 = null; iSize = 2; return old; } return null; case 2: if (iKey2 == null) { Object old = iValue2; iHash2 = 0; iKey2 = null; iValue2 = null; iSize = 1; return old; } if (iKey1 == null) { Object old = iValue2; iHash1 = iHash2; iKey1 = iKey2; iValue1 = iValue2; iHash2 = 0; iKey2 = null; iValue2 = null; iSize = 1; return old; } return null; case 1: if (iKey1 == null) { Object old = iValue1; iHash1 = 0; iKey1 = null; iValue1 = null; iSize = 0; return old; } } } else { if (iSize > 0) { int hashCode = key.hashCode(); switch (iSize) { // drop through case 3: if (iHash3 == hashCode && key.equals(iKey3)) { Object old = iValue3; iHash3 = 0; iKey3 = null; iValue3 = null; iSize = 2; return old; } if (iHash2 == hashCode && key.equals(iKey2)) { Object old = iValue3; iHash2 = iHash3; iKey2 = iKey3; iValue2 = iValue3; iHash3 = 0; iKey3 = null; iValue3 = null; iSize = 2; return old; } if (iHash1 == hashCode && key.equals(iKey1)) { Object old = iValue3; iHash1 = iHash3; iKey1 = iKey3; iValue1 = iValue3; iHash3 = 0; iKey3 = null; iValue3 = null; iSize = 2; return old; } return null; case 2: if (iHash2 == hashCode && key.equals(iKey2)) { Object old = iValue2; iHash2 = 0; iKey2 = null; iValue2 = null; iSize = 1; return old; } if (iHash1 == hashCode && key.equals(iKey1)) { Object old = iValue2; iHash1 = iHash2; iKey1 = iKey2; iValue1 = iValue2; iHash2 = 0; iKey2 = null; iValue2 = null; iSize = 1; return old; } return null; case 1: if (iHash1 == hashCode && key.equals(iKey1)) { Object old = iValue1; iHash1 = 0; iKey1 = null; iValue1 = null; iSize = 0; return old; } } } } return null; } /** * Clears the map, resetting the size to zero and nullifying references * to avoid garbage collection issues. */ public void clear() { if (iMap != null) { iMap.clear(); // should aid gc iMap = null; // switch back to flat mode } else { iSize = 0; iHash1 = iHash2 = iHash3 = 0; iKey1 = iKey2 = iKey3 = null; iValue1 = iValue2 = iValue3 = null; } } /** * Gets an iterator over the map. * Changes made to the iterator affect this map. * <p> * A MapIterator returns the keys in the map. It also provides convenient * methods to get the key and value, and set the value. * It avoids the need to create an entrySet/keySet/values object. * It also avoids creating the Mep Entry object. * * @return the map iterator */ public MapIterator mapIterator() { if (iMap != null) { return new EntrySetMapIterator(this); } if (iSize == 0) { return IteratorUtils.EMPTY_MAP_ITERATOR; } return new FlatMapIterator(this); } /** * FlatMapIterator */ static class FlatMapIterator implements MapIterator, ResettableIterator { private final Flat3Map iFlatMap; private int iIndex = 0; private boolean iCanRemove = false; FlatMapIterator(Flat3Map map) { super(); iFlatMap = map; } public boolean hasNext() { return (iIndex < iFlatMap.iSize); } public Object next() { if (hasNext() == false) { throw new NoSuchElementException("No more elements in the iteration"); } iCanRemove = true; iIndex++; return getKey(); } public void remove() { if (iCanRemove == false) { throw new IllegalStateException("Iterator remove() can only be called once after next()"); } iFlatMap.remove(getKey()); iIndex iCanRemove = false; } public Object getKey() { if (iCanRemove == false) { throw new IllegalStateException("Map Entry cannot be queried"); } switch (iIndex) { case 3: return iFlatMap.iKey3; case 2: return iFlatMap.iKey2; case 1: return iFlatMap.iKey1; } throw new IllegalStateException("Invalid map index"); } public Object getValue() { if (iCanRemove == false) { throw new IllegalStateException("Map Entry cannot be queried"); } switch (iIndex) { case 3: return iFlatMap.iValue3; case 2: return iFlatMap.iValue2; case 1: return iFlatMap.iValue1; } throw new IllegalStateException("Invalid map index"); } public Object setValue(Object value) { if (iCanRemove == false) { throw new IllegalStateException("Map Entry cannot be changed"); } Object old = getValue(); switch (iIndex) { case 3: iFlatMap.iValue3 = value; case 2: iFlatMap.iValue2 = value; case 1: iFlatMap.iValue1 = value; } return old; } public void reset() { iIndex = 0; iCanRemove = false; } public String toString() { if (iCanRemove) { return "MapIterator[" + getKey() + "=" + getValue() + "]"; } else { return "MapIterator[]"; } } } /** * Gets the entrySet view of the map. * Changes made to the view affect this map. * The Map Entry is not an independent object and changes as the * iterator progresses. * To simply iterate through the entries, use {@link #mapIterator()}. * * @return the entrySet view */ public Set entrySet() { if (iMap != null) { return iMap.entrySet(); } return new EntrySet(this); } /** * EntrySet */ static class EntrySet extends AbstractSet { private final Flat3Map iFlatMap; EntrySet(Flat3Map map) { super(); iFlatMap = map; } public int size() { return iFlatMap.size(); } public void clear() { iFlatMap.clear(); } public boolean remove(Object obj) { if (obj instanceof Map.Entry == false) { return false; } Map.Entry entry = (Map.Entry) obj; Object key = entry.getKey(); boolean result = iFlatMap.containsKey(key); iFlatMap.remove(key); return result; } public Iterator iterator() { if (iFlatMap.iMap != null) { return iFlatMap.iMap.entrySet().iterator(); } if (iFlatMap.size() == 0) { return IteratorUtils.EMPTY_ITERATOR; } return new EntrySetIterator(iFlatMap); } } /** * EntrySetIterator and MapEntry */ static class EntrySetIterator implements Iterator, Map.Entry { private final Flat3Map iFlatMap; private int iIndex = 0; private boolean iCanRemove = false; EntrySetIterator(Flat3Map map) { super(); iFlatMap = map; } public boolean hasNext() { return (iIndex < iFlatMap.iSize); } public Object next() { if (hasNext() == false) { throw new NoSuchElementException("No more elements in the iteration"); } iCanRemove = true; iIndex++; return this; } public void remove() { if (iCanRemove == false) { throw new IllegalStateException("Iterator remove() can only be called once after next()"); } iFlatMap.remove(getKey()); iIndex iCanRemove = false; } public Object getKey() { if (iCanRemove == false) { throw new IllegalStateException("Map Entry cannot be queried"); } switch (iIndex) { case 3: return iFlatMap.iKey3; case 2: return iFlatMap.iKey2; case 1: return iFlatMap.iKey1; } throw new IllegalStateException("Invalid map index"); } public Object getValue() { if (iCanRemove == false) { throw new IllegalStateException("Map Entry cannot be queried"); } switch (iIndex) { case 3: return iFlatMap.iValue3; case 2: return iFlatMap.iValue2; case 1: return iFlatMap.iValue1; } throw new IllegalStateException("Invalid map index"); } public Object setValue(Object value) { if (iCanRemove == false) { throw new IllegalStateException("Map Entry cannot be changed"); } Object old = getValue(); switch (iIndex) { case 3: iFlatMap.iValue3 = value; case 2: iFlatMap.iValue2 = value; case 1: iFlatMap.iValue1 = value; } return old; } public boolean equals(Object obj) { if (iCanRemove == false) { return false; } if (obj instanceof Map.Entry == false) { return false; } Map.Entry other = (Map.Entry) obj; Object key = getKey(); Object value = getValue(); return (key == null ? other.getKey() == null : key.equals(other.getKey())) && (value == null ? other.getValue() == null : value.equals(other.getValue())); } public int hashCode() { if (iCanRemove == false) { return 0; } Object key = getKey(); Object value = getValue(); return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } public String toString() { if (iCanRemove) { return getKey() + "=" + getValue(); } else { return ""; } } } /** * Gets the keySet view of the map. * Changes made to the view affect this map. * To simply iterate through the keys, use {@link #mapIterator()}. * * @return the keySet view */ public Set keySet() { if (iMap != null) { return iMap.keySet(); } return new KeySet(this); } /** * KeySet */ static class KeySet extends AbstractSet { private final Flat3Map iFlatMap; KeySet(Flat3Map map) { super(); iFlatMap = map; } public int size() { return iFlatMap.size(); } public void clear() { iFlatMap.clear(); } public boolean contains(Object key) { return iFlatMap.containsKey(key); } public boolean remove(Object key) { boolean result = iFlatMap.containsKey(key); iFlatMap.remove(key); return result; } public Iterator iterator() { if (iFlatMap.iMap != null) { return iFlatMap.iMap.keySet().iterator(); } if (iFlatMap.size() == 0) { return IteratorUtils.EMPTY_ITERATOR; } return new KeySetIterator(iFlatMap); } } /** * KeySetIterator */ static class KeySetIterator extends EntrySetIterator { KeySetIterator(Flat3Map map) { super(map); } public Object next() { super.next(); return getKey(); } } /** * Gets the values view of the map. * Changes made to the view affect this map. * To simply iterate through the values, use {@link #mapIterator()}. * * @return the values view */ public Collection values() { if (iMap != null) { return iMap.values(); } return new Values(this); } /** * Values */ static class Values extends AbstractCollection { private final Flat3Map iFlatMap; Values(Flat3Map map) { super(); iFlatMap = map; } public int size() { return iFlatMap.size(); } public void clear() { iFlatMap.clear(); } public boolean contains(Object value) { return iFlatMap.containsValue(value); } public Iterator iterator() { if (iFlatMap.iMap != null) { return iFlatMap.iMap.values().iterator(); } if (iFlatMap.size() == 0) { return IteratorUtils.EMPTY_ITERATOR; } return new ValuesIterator(iFlatMap); } } /** * ValuesIterator */ static class ValuesIterator extends EntrySetIterator { ValuesIterator(Flat3Map map) { super(map); } public Object next() { super.next(); return getValue(); } } /** * Compares this map with another. * * @param obj the object to compare to * @return true if equal */ public boolean equals(Object obj) { if (obj == this) { return true; } if (iMap != null) { return iMap.equals(obj); } if (obj instanceof Map == false) { return false; } Map other = (Map) obj; if (iSize != other.size()) { return false; } if (iSize > 0) { Object otherValue = null; switch (iSize) { // drop through case 3: if (other.containsKey(iKey3) == false) { otherValue = other.get(iKey3); if (iValue3 == null ? otherValue != null : !iValue3.equals(otherValue)) { return false; } } case 2: if (other.containsKey(iKey2) == false) { otherValue = other.get(iKey2); if (iValue2 == null ? otherValue != null : !iValue2.equals(otherValue)) { return false; } } case 1: if (other.containsKey(iKey1) == false) { otherValue = other.get(iKey1); if (iValue1 == null ? otherValue != null : !iValue1.equals(otherValue)) { return false; } } } } return true; } /** * Gets the standard Map hashCode. * * @return the hashcode defined in the Map interface */ public int hashCode() { if (iMap != null) { return iMap.hashCode(); } int total = 0; switch (iSize) { // drop through case 3: total += (iHash3 ^ (iValue3 == null ? 0 : iValue3.hashCode())); case 2: total += (iHash2 ^ (iValue2 == null ? 0 : iValue2.hashCode())); case 1: total += (iHash1 ^ (iValue1 == null ? 0 : iValue1.hashCode())); } return total; } /** * Gets the map as a String. * * @return a string version of the map */ public String toString() { if (iMap != null) { return iMap.toString(); } if (iSize == 0) { return "{}"; } StringBuffer buf = new StringBuffer(128); buf.append('{'); switch (iSize) { // drop through case 3: buf.append(iKey3); buf.append('='); buf.append(iValue3); buf.append(','); case 2: buf.append(iKey2); buf.append('='); buf.append(iValue2); buf.append(','); case 1: buf.append(iKey1); buf.append('='); buf.append(iValue1); } buf.append('}'); return buf.toString(); } }
package com.mapswithme.maps; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.Point; import android.location.Location; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.support.v4.content.LocalBroadcastManager; import android.telephony.TelephonyManager; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.mapswithme.country.DownloadActivity; import com.mapswithme.maps.Ads.AdsManager; import com.mapswithme.maps.Ads.MenuAd; import com.mapswithme.maps.Framework.OnBalloonListener; import com.mapswithme.maps.LocationButtonImageSetter.ButtonState; import com.mapswithme.maps.MapStorage.Index; import com.mapswithme.maps.api.ParsedMmwRequest; import com.mapswithme.maps.background.WorkerService; import com.mapswithme.maps.bookmarks.BookmarkActivity; import com.mapswithme.maps.bookmarks.BookmarkCategoriesActivity; import com.mapswithme.maps.bookmarks.data.Bookmark; import com.mapswithme.maps.bookmarks.data.BookmarkManager; import com.mapswithme.maps.bookmarks.data.MapObject; import com.mapswithme.maps.bookmarks.data.MapObject.ApiPoint; import com.mapswithme.maps.bookmarks.data.ParcelablePoint; import com.mapswithme.maps.location.LocationService; import com.mapswithme.maps.search.SearchController; import com.mapswithme.maps.settings.SettingsActivity; import com.mapswithme.maps.settings.StoragePathManager; import com.mapswithme.maps.settings.StoragePathManager.SetStoragePathListener; import com.mapswithme.maps.settings.UnitLocale; import com.mapswithme.maps.widget.MapInfoView; import com.mapswithme.maps.widget.MapInfoView.OnVisibilityChangedListener; import com.mapswithme.maps.widget.MapInfoView.State; import com.mapswithme.util.ConnectionState; import com.mapswithme.util.Constants; import com.mapswithme.util.LocationUtils; import com.mapswithme.util.ShareAction; import com.mapswithme.util.UiUtils; import com.mapswithme.util.Utils; import com.mapswithme.util.Yota; import com.mapswithme.util.statistics.Statistics; import com.nvidia.devtech.NvEventQueueActivity; import java.io.Serializable; import java.util.List; import java.util.Locale; import java.util.Stack; public class MWMActivity extends NvEventQueueActivity implements LocationService.LocationListener, OnBalloonListener, OnVisibilityChangedListener, OnClickListener { public static final String EXTRA_TASK = "map_task"; private final static String TAG = "MWMActivity"; private final static String EXTRA_CONSUMED = "mwm.extra.intent.processed"; private final static String EXTRA_SCREENSHOTS_TASK = "screenshots_task"; private final static String SCREENSHOTS_TASK_LOCATE = "locate_task"; private final static String SCREENSHOTS_TASK_PPP = "show_place_page"; private final static String EXTRA_LAT = "lat"; private final static String EXTRA_LON = "lon"; private final static String EXTRA_COUNTRY_INDEX = "country_index"; // Need it for search private static final String EXTRA_SEARCH_RES_SINGLE = "search_res_index"; // Map tasks that we run AFTER rendering initialized private final Stack<MapTask> mTasks = new Stack<>(); private BroadcastReceiver mExternalStorageReceiver = null; private StoragePathManager mPathManager = new StoragePathManager(); private AlertDialog mStorageDisconnectedDialog = null; private ImageButton mLocationButton; // Info box (place page). private MapInfoView mInfoView; private SearchController mSearchController; private boolean mNeedCheckUpdate = true; private boolean mRenderingInitialized = false; private int mCompassStatusListenerID = -1; // Initialized to invalid combination to force update on the first check private boolean mStorageAvailable = false; private boolean mStorageWritable = true; // toolbars private static final long VERT_TOOLBAR_ANIM_DURATION = 250; private ViewGroup mVerticalToolbar; private ViewGroup mToolbar; private Animation mVerticalToolbarAnimation; private View mFadeView; private static final String IS_KML_MOVED = "KmlBeenMoved"; private static final String IS_KITKAT_MIGRATION_COMPLETED = "KitKatMigrationCompleted"; // ads in vertical toolbar private BroadcastReceiver mUpdateAdsReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateToolbarAds(); } }; private boolean mAreToolbarAdsUpdated; public static Intent createShowMapIntent(Context context, Index index, boolean doAutoDownload) { return new Intent(context, DownloadResourcesActivity.class) .putExtra(DownloadResourcesActivity.EXTRA_COUNTRY_INDEX, index) .putExtra(DownloadResourcesActivity.EXTRA_AUTODOWNLOAD_CONTRY, doAutoDownload); } public static void startWithSearchResult(Context context, boolean single) { final Intent mapIntent = new Intent(context, MWMActivity.class); mapIntent.putExtra(EXTRA_SEARCH_RES_SINGLE, single); context.startActivity(mapIntent); // Next we need to handle intent } private native void deactivatePopup(); private void startLocation() { MWMApplication.get().getLocationState().onStartLocation(); resumeLocation(); } private void stopLocation() { MWMApplication.get().getLocationState().onStopLocation(); pauseLocation(); } private void pauseLocation() { MWMApplication.get().getLocationService().stopUpdate(this); // Enable automatic turning screen off while app is idle Utils.automaticIdleScreen(true, getWindow()); } private void resumeLocation() { MWMApplication.get().getLocationService().startUpdate(this); // Do not turn off the screen while displaying position Utils.automaticIdleScreen(false, getWindow()); } public void checkShouldResumeLocationService() { final LocationState state = MWMApplication.get().getLocationState(); final boolean hasPosition = state.hasPosition(); final boolean isFollowMode = (state.getCompassProcessMode() == LocationState.COMPASS_FOLLOW); if (hasPosition || state.isFirstPosition()) { if (hasPosition && isFollowMode) { state.startCompassFollowing(); LocationButtonImageSetter.setButtonViewFromState(ButtonState.FOLLOW_MODE, mLocationButton); } else { LocationButtonImageSetter.setButtonViewFromState( hasPosition ? ButtonState.HAS_LOCATION : ButtonState.WAITING_LOCATION, mLocationButton ); } resumeLocation(); } else { LocationButtonImageSetter.setButtonViewFromState(ButtonState.NO_LOCATION, mLocationButton); } } public void OnDownloadCountryClicked() { runOnUiThread(new Runnable() { @Override public void run() { nativeDownloadCountry(); } }); } private void checkUserMarkActivation() { final Intent intent = getIntent(); if (intent != null && intent.hasExtra(EXTRA_SCREENSHOTS_TASK)) { final String value = intent.getStringExtra(EXTRA_SCREENSHOTS_TASK); if (value.equals(SCREENSHOTS_TASK_PPP)) { final double lat = Double.parseDouble(intent.getStringExtra(EXTRA_LAT)); final double lon = Double.parseDouble(intent.getStringExtra(EXTRA_LON)); mToolbar.getHandler().postDelayed(new Runnable() { @Override public void run() { Framework.nativeActivateUserMark(lat, lon); } }, 1000); } } } @Override public void OnRenderingInitialized() { mRenderingInitialized = true; runOnUiThread(new Runnable() { @Override public void run() { // Run all checks in main thread after rendering is initialized. checkMeasurementSystem(); checkUpdateMaps(); checkKitkatMigrationMove(); checkLiteMapsInPro(); checkFacebookDialog(); checkBuyProDialog(); checkUserMarkActivation(); } }); runTasks(); } private void runTasks() { // Task are not UI-thread bounded, // if any task need UI-thread it should implicitly // use Activity.runOnUiThread(). while (!mTasks.isEmpty()) mTasks.pop().run(this); } private Activity getActivity() { return this; } @Override public void ReportUnsupported() { runOnUiThread(new Runnable() { @Override public void run() { new AlertDialog.Builder(getActivity()) .setMessage(getString(R.string.unsupported_phone)) .setCancelable(false) .setPositiveButton(getString(R.string.close), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { getActivity().moveTaskToBack(true); dlg.dismiss(); } }) .create() .show(); } }); } private void checkMeasurementSystem() { UnitLocale.initializeCurrentUnits(); } private native void nativeScale(double k); public void onPlusClicked(View v) { nativeScale(3.0 / 2); } public void onMinusClicked(View v) { nativeScale(2.0 / 3); } public void onBookmarksClicked(View v) { if (!MWMApplication.get().hasBookmarks()) showProVersionBanner(getString(R.string.bookmarks_in_pro_version)); else startActivity(new Intent(this, BookmarkCategoriesActivity.class)); } public void onMyPositionClicked(View v) { final LocationState state = MWMApplication.get().getLocationState(); if (state.hasPosition()) { if (state.isCentered()) { if (BuildConfig.IS_PRO && state.hasCompass()) { final boolean isFollowMode = (state.getCompassProcessMode() == LocationState.COMPASS_FOLLOW); if (isFollowMode) { state.stopCompassFollowingAndRotateMap(); } else { state.startCompassFollowing(); LocationButtonImageSetter.setButtonViewFromState(ButtonState.FOLLOW_MODE, mLocationButton); return; } } } else { state.animateToPositionAndEnqueueLocationProcessMode(LocationState.LOCATION_CENTER_ONLY); mLocationButton.setSelected(true); return; } } else { if (!state.isFirstPosition()) { LocationButtonImageSetter.setButtonViewFromState(ButtonState.WAITING_LOCATION, mLocationButton); startLocation(); return; } } // Stop location observing first ... stopLocation(); LocationButtonImageSetter.setButtonViewFromState(ButtonState.NO_LOCATION, mLocationButton); } private void ShowAlertDlg(int tittleID) { new AlertDialog.Builder(this) .setCancelable(false) .setMessage(tittleID) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { dlg.dismiss(); } }) .create() .show(); } private void checkKitkatMigrationMove() { final boolean kmlMoved = MWMApplication.get().nativeGetBoolean(IS_KML_MOVED, false); final boolean mapsCpy = MWMApplication.get().nativeGetBoolean(IS_KITKAT_MIGRATION_COMPLETED, false); if (!kmlMoved) if (mPathManager.moveBookmarks()) MWMApplication.get().nativeSetBoolean(IS_KML_MOVED, true); else { ShowAlertDlg(R.string.bookmark_move_fail); return; } if (!mapsCpy) mPathManager.checkWritableDir(this, new SetStoragePathListener() { @Override public void moveFilesFinished(String newPath) { MWMApplication.get().nativeSetBoolean(IS_KITKAT_MIGRATION_COMPLETED, true); ShowAlertDlg(R.string.kitkat_migrate_ok); } @Override public void moveFilesFailed() { ShowAlertDlg(R.string.kitkat_migrate_failed); } } ); } /** * Checks if PRO version is running on KITKAT or greater sdk. * If so - checks whether LITE version is installed and contains maps on sd card and then copies them to own directory on sdcard. */ private void checkLiteMapsInPro() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && BuildConfig.IS_PRO && (Utils.isAppInstalled(Constants.Package.MWM_LITE_PACKAGE) || Utils.isAppInstalled(Constants.Package.MWM_SAMSUNG_PACKAGE))) { if (!mPathManager.containsLiteMapsOnSdcard()) return; mPathManager.moveMapsLiteToPro(this, new SetStoragePathListener() { @Override public void moveFilesFinished(String newPath) { ShowAlertDlg(R.string.move_lite_maps_to_pro_ok); } @Override public void moveFilesFailed() { ShowAlertDlg(R.string.move_lite_maps_to_pro_failed); } } ); } } private void checkUpdateMaps() { // do it only once if (mNeedCheckUpdate) { mNeedCheckUpdate = false; MWMApplication.get().getMapStorage().updateMaps(R.string.advise_update_maps, this, new MapStorage.UpdateFunctor() { @Override public void doUpdate() { runDownloadActivity(); } @Override public void doCancel() { } }); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); alignControls(); } private void showDialogImpl(final int dlgID, int resMsg, DialogInterface.OnClickListener okListener) { new AlertDialog.Builder(this) .setCancelable(false) .setMessage(getString(resMsg)) .setPositiveButton(getString(R.string.ok), okListener) .setNeutralButton(getString(R.string.never), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { dlg.dismiss(); MWMApplication.get().submitDialogResult(dlgID, MWMApplication.NEVER); } }) .setNegativeButton(getString(R.string.later), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { dlg.dismiss(); MWMApplication.get().submitDialogResult(dlgID, MWMApplication.LATER); } }) .create() .show(); } private boolean isChinaISO(String iso) { final String arr[] = {"CN", "CHN", "HK", "HKG", "MO", "MAC"}; for (final String s : arr) if (iso.equalsIgnoreCase(s)) return true; return false; } private boolean isChinaRegion() { final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (tm != null && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { final String iso = tm.getNetworkCountryIso(); Log.i(TAG, "TelephonyManager country ISO = " + iso); if (isChinaISO(iso)) return true; } else { final Location l = MWMApplication.get().getLocationService().getLastKnown(); if (l != null && nativeIsInChina(l.getLatitude(), l.getLongitude())) return true; else { final String code = Locale.getDefault().getCountry(); Log.i(TAG, "Locale country ISO = " + code); if (isChinaISO(code)) return true; } } return false; } private void checkFacebookDialog() { if (ConnectionState.isConnected(this) && MWMApplication.get().shouldShowDialog(MWMApplication.FACEBOOK) && !isChinaRegion()) { showDialogImpl(MWMApplication.FACEBOOK, R.string.share_on_facebook_text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { MWMApplication.get().submitDialogResult(MWMApplication.FACEBOOK, MWMApplication.OK); dlg.dismiss(); UiUtils.showFacebookPage(MWMActivity.this); } } ); } } private void showProVersionBanner(final String message) { runOnUiThread(new Runnable() { @Override public void run() { UiUtils.showBuyProDialog(MWMActivity.this, message); } }); } private void checkBuyProDialog() { if (!BuildConfig.IS_PRO && (ConnectionState.isConnected(this)) && MWMApplication.get().shouldShowDialog(MWMApplication.BUYPRO)) { showDialogImpl(MWMApplication.BUYPRO, R.string.pro_version_available, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { MWMApplication.get().submitDialogResult(MWMApplication.BUYPRO, MWMApplication.OK); dlg.dismiss(); UiUtils.openAppInMarket(MWMActivity.this, BuildConfig.PRO_URL); } } ); } } private void runSearchActivity() { startActivity(new Intent(this, SearchActivity.class)); } public void onSearchClicked(View v) { if (!BuildConfig.IS_PRO) { showProVersionBanner(getString(R.string.search_available_in_pro_version)); } else if (!MWMApplication.get().getMapStorage().updateMaps(R.string.search_update_maps, this, new MapStorage.UpdateFunctor() { @Override public void doUpdate() { runDownloadActivity(); } @Override public void doCancel() { runSearchActivity(); } })) { runSearchActivity(); } } @Override public boolean onSearchRequested() { onSearchClicked(null); return false; } public void onMoreClicked(View v) { setVerticalToolbarVisible(true); } private void setVerticalToolbarVisible(boolean showVerticalToolbar) { if (mVerticalToolbarAnimation != null || (mVerticalToolbar.getVisibility() == View.VISIBLE && showVerticalToolbar) || (mVerticalToolbar.getVisibility() != View.VISIBLE && !showVerticalToolbar)) return; int fromY, toY; Animation.AnimationListener listener; float fromAlpha, toAlpha; if (showVerticalToolbar) { fromY = 1; toY = 0; fromAlpha = 0.0f; toAlpha = 0.5f; listener = new UiUtils.SimpleAnimationListener() { @Override public void onAnimationStart(Animation animation) { mVerticalToolbar.setVisibility(View.VISIBLE); } @Override public void onAnimationEnd(Animation animation) { mFadeView.setVisibility(View.GONE); mVerticalToolbarAnimation = null; } }; } else { fromY = 0; toY = 1; fromAlpha = 0.5f; toAlpha = 0.0f; listener = new UiUtils.SimpleAnimationListener() { @Override public void onAnimationEnd(Animation animation) { mVerticalToolbar.setVisibility(View.INVISIBLE); mFadeView.setVisibility(View.GONE); mVerticalToolbarAnimation = null; } }; } // slide vertical toolbar mVerticalToolbarAnimation = UiUtils.generateSlideAnimation(0, 0, fromY, toY); mVerticalToolbarAnimation.setDuration(VERT_TOOLBAR_ANIM_DURATION); mVerticalToolbarAnimation.setAnimationListener(listener); mVerticalToolbar.startAnimation(mVerticalToolbarAnimation); // fade map Animation alphaAnimation = new AlphaAnimation(fromAlpha, toAlpha); alphaAnimation.setFillBefore(true); alphaAnimation.setFillAfter(true); alphaAnimation.setDuration(VERT_TOOLBAR_ANIM_DURATION); mFadeView.setVisibility(View.VISIBLE); mFadeView.startAnimation(alphaAnimation); } private void shareMyLocation() { final Location loc = MWMApplication.get().getLocationService().getLastKnown(); if (loc != null) { final String geoUrl = Framework.nativeGetGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.getDrawScale(), ""); final String httpUrl = Framework.getHttpGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.getDrawScale(), ""); final String body = getString(R.string.my_position_share_sms, geoUrl, httpUrl); // we use shortest message we can have here ShareAction.getAnyShare().shareWithText(getActivity(), body, ""); } else { new AlertDialog.Builder(MWMActivity.this) .setMessage(R.string.unknown_current_position) .setCancelable(true) .setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create() .show(); } } private void runDownloadActivity() { startActivity(new Intent(this, DownloadActivity.class)); } @Override public void onCreate(Bundle savedInstanceState) { // Use full-screen on Kindle Fire only if (Utils.isAmazonDevice()) { getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); } setContentView(R.layout.map); super.onCreate(savedInstanceState); // Log app start events - successful installation means that user has passed DownloadResourcesActivity MWMApplication.get().onMwmStart(this); // Do not turn off the screen while benchmarking if (MWMApplication.get().nativeIsBenchmarking()) getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); nativeConnectDownloadButton(); // Set up view mLocationButton = (ImageButton) findViewById(R.id.map_button_myposition); yotaSetup(); setUpInfoBox(); Framework.nativeConnectBalloonListeners(this); final Intent intent = getIntent(); // We need check for tasks both in onCreate and onNewIntent addTask(intent); // Initialize location service MWMApplication.get().getLocationService(); mSearchController = SearchController.getInstance(); mSearchController.onCreate(this); setUpToolbars(); if (intent != null && intent.hasExtra(EXTRA_SCREENSHOTS_TASK)) { String value = intent.getStringExtra(EXTRA_SCREENSHOTS_TASK); if (value.equals(SCREENSHOTS_TASK_LOCATE)) onMyPositionClicked(null); } updateToolbarAds(); LocalBroadcastManager.getInstance(this).registerReceiver(mUpdateAdsReceiver, new IntentFilter(WorkerService.ACTION_UPDATE_MENU_ADS)); } private void updateToolbarAds() { final List<MenuAd> ads = AdsManager.getMenuAds(); if (ads != null && !mAreToolbarAdsUpdated) { mAreToolbarAdsUpdated = true; int startAdMenuPosition = 7; for (final MenuAd ad : ads) { final View view = getLayoutInflater().inflate(R.layout.item_bottom_toolbar, mVerticalToolbar, false); final TextView textView = (TextView) view.findViewById(R.id.tv__bottom_item_text); textView.setText(ad.getTitle()); try { textView.setTextColor(Color.parseColor(ad.getHexColor())); } catch (IllegalArgumentException e) { e.printStackTrace(); } final ImageView imageView = (ImageView) view.findViewById(R.id.iv__bottom_icon); imageView.setImageBitmap(ad.getIcon()); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final Intent it = new Intent(Intent.ACTION_VIEW); it.setData(Uri.parse(ad.getAppUrl())); startActivity(it); } }); mVerticalToolbar.addView(view, startAdMenuPosition++); } } } private void setUpToolbars() { mToolbar = (ViewGroup) findViewById(R.id.map_bottom_toolbar); mVerticalToolbar = (ViewGroup) findViewById(R.id.map_bottom_vertical_toolbar); mVerticalToolbar.findViewById(R.id.btn_buy_pro).setOnClickListener(this); mVerticalToolbar.findViewById(R.id.btn_download_maps).setOnClickListener(this); mVerticalToolbar.findViewById(R.id.btn_share).setOnClickListener(this); mVerticalToolbar.findViewById(R.id.btn_settings).setOnClickListener(this); View moreApps = mVerticalToolbar.findViewById(R.id.btn_more_apps); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB || Framework.getGuideIds().length == 0) UiUtils.hide(moreApps); else moreApps.setOnClickListener(this); UiUtils.invisible(mVerticalToolbar); mFadeView = findViewById(R.id.fade_view); } private void setUpInfoBox() { mInfoView = (MapInfoView) findViewById(R.id.info_box); mInfoView.setOnVisibilityChangedListener(this); mInfoView.bringToFront(); } private void yotaSetup() { final View yopmeButton = findViewById(R.id.yop_it); if (!Yota.isYota()) { yopmeButton.setVisibility(View.INVISIBLE); } else { yopmeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final double[] latLon = Framework.getScreenRectCenter(); final double zoom = Framework.getDrawScale(); final LocationState locState = MWMApplication.get().getLocationState(); if (locState.hasPosition() && locState.isCentered()) Yota.showLocation(getApplicationContext(), zoom); else Yota.showMap(getApplicationContext(), latLon[0], latLon[1], zoom, null, locState.hasPosition()); Statistics.INSTANCE.trackBackscreenCall(getApplication(), "Map"); } }); } } @Override public void onDestroy() { Framework.nativeClearBalloonListeners(); super.onDestroy(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (intent != null) { if (intent.hasExtra(EXTRA_TASK)) addTask(intent); else if (intent.hasExtra(EXTRA_SEARCH_RES_SINGLE)) { final boolean singleResult = intent.getBooleanExtra(EXTRA_SEARCH_RES_SINGLE, false); if (singleResult) { MapObject.SearchResult result = new MapObject.SearchResult(0); onAdditionalLayerActivated(result.getName(), result.getPoiTypeName(), result.getLat(), result.getLon()); } else onDismiss(); } } } private void addTask(Intent intent) { if (intent != null && !intent.getBooleanExtra(EXTRA_CONSUMED, false) && intent.hasExtra(EXTRA_TASK) && ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0)) { final MapTask mapTask = (MapTask) intent.getSerializableExtra(EXTRA_TASK); mTasks.add(mapTask); intent.removeExtra(EXTRA_TASK); if (mRenderingInitialized) runTasks(); // mark intent as consumed intent.putExtra(EXTRA_CONSUMED, true); } } @Override protected void onStop() { super.onStop(); mRenderingInitialized = false; } private void alignControls() { final View zoomPlusButton = findViewById(R.id.map_button_plus); final RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) zoomPlusButton.getLayoutParams(); final int margin = (int) getResources().getDimension(R.dimen.zoom_margin); final int marginTop = (int) getResources().getDimension(R.dimen.zoom_plus_top_margin); lp.setMargins(margin, marginTop, margin, margin); } /// @name From Location interface @Override public void onLocationError(int errorCode) { nativeOnLocationError(errorCode); // Notify user about turned off location services if (errorCode == LocationService.ERROR_DENIED) { MWMApplication.get().getLocationState().turnOff(); // Do not show this dialog on Kindle Fire - it doesn't have location services // and even wifi settings can't be opened programmatically if (!Utils.isAmazonDevice()) { new AlertDialog.Builder(this).setTitle(R.string.location_is_disabled_long_text) .setPositiveButton(R.string.connection_settings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } catch (final Exception e1) { // On older Android devices location settings are merged with security try { startActivity(new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS)); } catch (final Exception e2) { Log.w(TAG, "Can't run activity" + e2); } } dialog.dismiss(); } }) .setNegativeButton(R.string.close, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create() .show(); } } else if (errorCode == LocationService.ERROR_GPS_OFF) { Toast.makeText(this, R.string.gps_is_disabled_long_text, Toast.LENGTH_LONG).show(); } } @Override public void onLocationUpdated(final Location l) { if (MWMApplication.get().getLocationState().isFirstPosition()) LocationButtonImageSetter.setButtonViewFromState(ButtonState.HAS_LOCATION, mLocationButton); nativeLocationUpdated(l.getTime(), l.getLatitude(), l.getLongitude(), l.getAccuracy(), l.getAltitude(), l.getSpeed(), l.getBearing()); if (mInfoView.getState() != State.HIDDEN) mInfoView.updateDistanceAndAzimut(l); } @SuppressWarnings("deprecation") @Override public void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy) { final double angles[] = {magneticNorth, trueNorth}; LocationUtils.correctCompassAngles(getWindowManager().getDefaultDisplay().getOrientation(), angles); nativeCompassUpdated(time, angles[0], angles[1], accuracy); final double north = (angles[1] >= 0.0 ? angles[1] : angles[0]); if (mInfoView.getState() != State.HIDDEN) mInfoView.updateAzimuth(north); } @Override public void onDrivingHeadingUpdated(long time, double heading, double accuracy) { LocationUtils.correctCompassAngles(getWindowManager().getDefaultDisplay().getOrientation(), new double[]{heading}); nativeCompassUpdated(time, heading, heading, accuracy); if (mInfoView.getState() != State.HIDDEN) mInfoView.updateAzimuth(heading); } public void onCompassStatusChanged(int newStatus) { if (newStatus == 1) LocationButtonImageSetter.setButtonViewFromState(ButtonState.FOLLOW_MODE, mLocationButton); else if (MWMApplication.get().getLocationState().hasPosition()) LocationButtonImageSetter.setButtonViewFromState(ButtonState.HAS_LOCATION, mLocationButton); else LocationButtonImageSetter.setButtonViewFromState(ButtonState.NO_LOCATION, mLocationButton); } /// Callback from native compass GUI element processing. public void OnCompassStatusChanged(int newStatus) { final int val = newStatus; runOnUiThread(new Runnable() { @Override public void run() { onCompassStatusChanged(val); } }); } private void startWatchingCompassStatusUpdate() { mCompassStatusListenerID = MWMApplication.get().getLocationState().addCompassStatusListener(this); } private void stopWatchingCompassStatusUpdate() { MWMApplication.get().getLocationState().removeCompassStatusListener(mCompassStatusListenerID); } @Override protected void onPause() { pauseLocation(); stopWatchingExternalStorage(); stopWatchingCompassStatusUpdate(); super.onPause(); } @Override protected void onResume() { super.onResume(); checkShouldResumeLocationService(); startWatchingCompassStatusUpdate(); startWatchingExternalStorage(); UiUtils.showIf(MWMApplication.get().nativeGetBoolean(SettingsActivity.ZOOM_BUTTON_ENABLED, true), findViewById(R.id.map_button_plus), findViewById(R.id.map_button_minus)); alignControls(); mSearchController.onResume(); mInfoView.onResume(); MWMApplication.get().onMwmResume(this); } private void updateExternalStorageState() { boolean available = false, writable = false; final String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) available = writable = true; else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) available = true; if (mStorageAvailable != available || mStorageWritable != writable) { mStorageAvailable = available; mStorageWritable = writable; handleExternalStorageState(available, writable); } } private void handleExternalStorageState(boolean available, boolean writeable) { if (available && writeable) { // Add local maps to the model nativeStorageConnected(); // @TODO enable downloader button and dismiss blocking popup if (mStorageDisconnectedDialog != null) mStorageDisconnectedDialog.dismiss(); } else if (available) { // Add local maps to the model nativeStorageConnected(); // @TODO disable downloader button and dismiss blocking popup if (mStorageDisconnectedDialog != null) mStorageDisconnectedDialog.dismiss(); } else { // Remove local maps from the model nativeStorageDisconnected(); // @TODO enable downloader button and show blocking popup if (mStorageDisconnectedDialog == null) { mStorageDisconnectedDialog = new AlertDialog.Builder(this) .setTitle(R.string.external_storage_is_not_available) .setMessage(getString(R.string.disconnect_usb_cable)) .setCancelable(false) .create(); } mStorageDisconnectedDialog.show(); } } private void startWatchingExternalStorage() { mExternalStorageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateExternalStorageState(); } }; registerReceiver(mExternalStorageReceiver, StoragePathManager.getMediaChangesIntentFilter()); updateExternalStorageState(); } private void stopWatchingExternalStorage() { mPathManager.stopExternalStorageWatching(); if (mExternalStorageReceiver != null) { unregisterReceiver(mExternalStorageReceiver); mExternalStorageReceiver = null; } } @Override public void onBackPressed() { if (mInfoView.getState() != State.HIDDEN) { hideInfoView(); deactivatePopup(); } else if (mVerticalToolbar.getVisibility() == View.VISIBLE) setVerticalToolbarVisible(false); else super.onBackPressed(); } /// Callbacks from native map objects touch event. @Override public void onApiPointActivated(final double lat, final double lon, final String name, final String id) { if (ParsedMmwRequest.hasRequest()) { final ParsedMmwRequest request = ParsedMmwRequest.getCurrentRequest(); request.setPointData(lat, lon, name, id); runOnUiThread(new Runnable() { @Override public void run() { final String poiType = ParsedMmwRequest.getCurrentRequest().getCallerName(MWMApplication.get()).toString(); final ApiPoint apiPoint = new ApiPoint(name, id, poiType, lat, lon); if (!mInfoView.hasMapObject(apiPoint)) { mInfoView.setMapObject(apiPoint); mInfoView.setState(State.PREVIEW_ONLY); } } }); } } @Override public void onPoiActivated(final String name, final String type, final String address, final double lat, final double lon) { final MapObject poi = new MapObject.Poi(name, lat, lon, type); runOnUiThread(new Runnable() { @Override public void run() { if (!mInfoView.hasMapObject(poi)) { mInfoView.setMapObject(poi); mInfoView.setState(State.PREVIEW_ONLY); } } }); } @Override public void onBookmarkActivated(final int category, final int bookmarkIndex) { runOnUiThread(new Runnable() { @Override public void run() { final Bookmark b = BookmarkManager.getBookmarkManager().getBookmark(category, bookmarkIndex); if (!mInfoView.hasMapObject(b)) { mInfoView.setMapObject(b); mInfoView.setState(State.PREVIEW_ONLY); } } }); } @Override public void onMyPositionActivated(final double lat, final double lon) { final MapObject mypos = new MapObject.MyPosition(getString(R.string.my_position), lat, lon); runOnUiThread(new Runnable() { @Override public void run() { if (!mInfoView.hasMapObject(mypos)) { mInfoView.setMapObject(mypos); mInfoView.setState(State.PREVIEW_ONLY); } } }); } @Override public void onAdditionalLayerActivated(final String name, final String type, final double lat, final double lon) { runOnUiThread(new Runnable() { @Override public void run() { final MapObject sr = new MapObject.SearchResult(name, type, lat, lon); if (!mInfoView.hasMapObject(sr)) { mInfoView.setMapObject(sr); mInfoView.setState(State.PREVIEW_ONLY); } } }); } private void hideInfoView() { mInfoView.setState(State.HIDDEN); mInfoView.setMapObject(null); UiUtils.show(findViewById(R.id.map_bottom_toolbar)); } @Override public void onDismiss() { if (!mInfoView.hasMapObject(null)) { runOnUiThread(new Runnable() { @Override public void run() { hideInfoView(); deactivatePopup(); } }); } } private native void nativeStorageConnected(); private native void nativeStorageDisconnected(); private native void nativeConnectDownloadButton(); private native void nativeDownloadCountry(); private native void nativeOnLocationError(int errorCode); private native void nativeLocationUpdated(long time, double lat, double lon, float accuracy, double altitude, float speed, float bearing); private native void nativeCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy); private native boolean nativeIsInChina(double lat, double lon); public native boolean showMapForUrl(String url); @Override public void onPreviewVisibilityChanged(boolean isVisible) { setVerticalToolbarVisible(false); } @Override public void onPlacePageVisibilityChanged(boolean isVisible) { setVerticalToolbarVisible(false); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_buy_pro: setVerticalToolbarVisible(false); UiUtils.openAppInMarket(MWMActivity.this, BuildConfig.PRO_URL); break; case R.id.btn_share: setVerticalToolbarVisible(false); shareMyLocation(); break; case R.id.btn_settings: setVerticalToolbarVisible(false); startActivity(new Intent(this, SettingsActivity.class)); break; case R.id.btn_download_maps: setVerticalToolbarVisible(false); runDownloadActivity(); break; case R.id.btn_more_apps: setVerticalToolbarVisible(false); startActivity(new Intent(this, MoreAppsActivity.class)); break; default: break; } } @Override public boolean onTouch(View view, MotionEvent event) { // if vertical toolbar is visible - hide it and ignore touch if (mVerticalToolbar.getVisibility() == View.VISIBLE) { setVerticalToolbarVisible(false); return true; } if (mInfoView.getState() == State.FULL_PLACEPAGE) { deactivatePopup(); hideInfoView(); return true; } return super.onTouch(view, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { setVerticalToolbarVisible(true); return true; } return super.onKeyUp(keyCode, event); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == BookmarkActivity.REQUEST_CODE_EDIT_BOOKMARK && resultCode == RESULT_OK) { final Point bmk = ((ParcelablePoint) data.getParcelableExtra(BookmarkActivity.PIN)).getPoint(); onBookmarkActivated(bmk.x, bmk.y); } super.onActivityResult(requestCode, resultCode, data); } public interface MapTask extends Serializable { public boolean run(MWMActivity target); } public static class OpenUrlTask implements MapTask { private static final long serialVersionUID = 1L; private final String mUrl; public OpenUrlTask(String url) { Utils.checkNotNull(url); mUrl = url; } @Override public boolean run(MWMActivity target) { return target.showMapForUrl(mUrl); } } public static class ShowCountryTask implements MapTask { private static final long serialVersionUID = 1L; private final Index mIndex; private final boolean mDoAutoDownload; public ShowCountryTask(Index index, boolean doAutoDownload) { mIndex = index; mDoAutoDownload = doAutoDownload; } @Override public boolean run(MWMActivity target) { final MapStorage storage = MWMApplication.get().getMapStorage(); if (mDoAutoDownload) { storage.downloadCountry(mIndex); // set zoom level so that download process is visible Framework.nativeShowCountry(mIndex, true); } else Framework.nativeShowCountry(mIndex, false); return true; } } }
package org.apache.velocity.servlet; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Properties; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletResponse; import org.apache.velocity.Template; import org.apache.velocity.runtime.Runtime; import org.apache.velocity.io.VelocityWriter; import org.apache.velocity.util.SimplePool; import org.apache.velocity.context.Context; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.HttpServletRequestWrap; import org.apache.velocity.app.HttpServletResponseWrap; import org.apache.velocity.app.Velocity; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.MethodInvocationException; /** * Base class which simplifies the use of Velocity with Servlets. * Extend this class, implement the <code>handleRequest()</code> method, * and add your data to the context. Then call * <code>getTemplate("myTemplate.wm")</code>. * * This class puts some things into the context object that you should * be aware of: * <pre> * "req" - The HttpServletRequest object * "res" - The HttpServletResponse object * </pre> * * There are other methods you can override to access, alter or control * any part of the request processing chain. Please see the javadocs for * more information on : * <ul> * <li> loadConfiguration() : for setting up the Velocity runtime * <li> createContext() : for creating and loading the Context * <li> setContentType() : for changing the content type on a request * by request basis * <li> handleRequest() : you <b>must</b> implement this * <li> mergeTemplate() : the template rendering process * <li> requestCleanup() : post rendering resource or other cleanup * <li> error() : error handling * </ul> * <br> * If you put a contentType object into the context within either your * serlvet or within your template, then that will be used to override * the default content type specified in the properties file. * * "contentType" - The value for the Content-Type: header * * @author Dave Bryson * @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a> * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> * @author <a href="kjohnson@transparent.com">Kent Johnson</a> * $Id: VelocityServlet.java,v 1.37 2001/05/16 22:49:38 geirm Exp $ */ public abstract class VelocityServlet extends HttpServlet { /** * The HTTP request object context key. */ public static final String REQUEST = "req"; /** * The HTTP response object context key. */ public static final String RESPONSE = "res"; /** * The HTTP content type context key. */ public static final String CONTENT_TYPE = "default.contentType"; /** * The default content type for the response */ public static final String DEFAULT_CONTENT_TYPE = "text/html"; /** * Encoding for the output stream */ public static final String DEFAULT_OUTPUT_ENCODING = "ISO-8859-1"; /** * The encoding to use when generating outputing. */ private static String encoding = null; /** * The default content type. */ private static String defaultContentType; /** * This is the string that is looked for when getInitParameter is * called. */ private static final String INIT_PROPS_KEY = "properties"; /** * Cache of writers */ private static SimplePool writerPool = new SimplePool(40); /** * Performs initialization of this servlet. Called by the servlet * container on loading. * * @param config The servlet configuration to apply. * * @exception ServletException */ public void init( ServletConfig config ) throws ServletException { super.init( config ); try { /* * call the overridable method to allow the * derived classes a shot at altering the configuration * before initializing Runtime */ Properties props = loadConfiguration( config ); Velocity.init( props ); defaultContentType = Runtime.getString( CONTENT_TYPE, DEFAULT_CONTENT_TYPE); encoding = Runtime.getString( Runtime.OUTPUT_ENCODING, DEFAULT_OUTPUT_ENCODING); } catch( Exception e ) { throw new ServletException("Error configuring the loader: " + e); } } /** * Loads the configuration information and returns that * information as a Properties, which will be used to * initialize the Velocity runtime. * <br><br> * Currently, this method gets the initialization parameter * VelocityServlet.INIT_PROPS_KEY, which should be a file containing * the configuration information. * <br><br> * To configure your Servlet Spec 2.2 compliant servlet runner to pass this * to you, put the following in your WEB-INF/web.xml file * <br> * <pre> * &lt;servlet &gt; * &lt;servlet-name&gt; YourServlet &lt/servlet-name&gt; * &lt;servlet-class&gt; your.package.YourServlet &lt;/servlet-class&gt; * &lt;init-param&gt; * &lt;param-name&gt; properties &lt;/param-name&gt; * &lt;param-value&gt; velocity.properties &lt;/param-value&gt; * &lt;/init-param&gt; * &lt;/servlet&gt; * </pre> * * Derived classes may do the same, or take advantage of this code to do the loading for them via : * <pre> * Properties p = super.loadConfiguration( config ); * </pre> * and then add or modify the configuration values from the file. * <br> * * @param config ServletConfig passed to the servlets init() function * Can be used to access the real path via ServletContext (hint) * @return java.util.Properties loaded with configuration values to be used * to initialize the Velocity runtime. * @throws FileNotFoundException if a specified file is not found. * @throws IOException I/O problem accessing the specified file, if specified. */ protected Properties loadConfiguration(ServletConfig config ) throws IOException, FileNotFoundException { String propsFile = config.getInitParameter(INIT_PROPS_KEY); /* * This will attempt to find the location of the properties * file from the relative path to the WAR archive (ie: * docroot). Since JServ returns null for getRealPath() * because it was never implemented correctly, then we know we * will not have an issue with using it this way. I don't know * if this will break other servlet engines, but it probably * shouldn't since WAR files are the future anyways. */ Properties p = new Properties(); if ( propsFile != null ) { String realPath = getServletContext().getRealPath(propsFile); if ( realPath != null ) { propsFile = realPath; } p.load( new FileInputStream(propsFile) ); } return p; } /** * Handles GET - calls doRequest() */ public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doRequest(request, response); } /** * Handle a POST request - calls doRequest() */ public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doRequest(request, response); } /** * Handles all requests * * @param request HttpServletRequest object containing client request * @param response HttpServletResponse object for the response */ protected void doRequest(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { try { /* * first, get a context */ Context context = createContext( request, response ); /* * set the content type */ setContentType( request, response ); /* * let someone handle the request */ Template template = handleRequest( request, response, context ); /* * bail if we can't find the template */ if ( template == null ) { return; } /* * now merge it */ mergeTemplate( template, context, response ); /* * call cleanup routine to let a derived class do some cleanup */ requestCleanup( request, response, context ); } catch (Exception e) { /* * call the error handler to let the derived class * do something useful with this failure. */ error( request, response, e); } } protected void requestCleanup( HttpServletRequest request, HttpServletResponse response, Context context ) { return; } protected void mergeTemplate( Template template, Context context, HttpServletResponse response ) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException, UnsupportedEncodingException, Exception { ServletOutputStream output = response.getOutputStream(); VelocityWriter vw = null; try { vw = (VelocityWriter) writerPool.get(); if (vw == null) { vw = new VelocityWriter( new OutputStreamWriter(output, encoding), 4*1024, true); } else { vw.recycle(new OutputStreamWriter(output, encoding)); } template.merge( context, vw); } finally { try { if (vw != null) { /* * flush and put back into the pool * don't close to allow us to play * nicely with others. */ vw.flush(); writerPool.put(vw); } } catch (Exception e) { // do nothing } } } /** * Sets the content type of the response. This is available to be overriden * by a derived class. * * The default implementation is : * * response.setContentType( defaultContentType ); * * where defaultContentType is set to the value of the default.contentType * property, or "text/html" if that is not set. * * @param request servlet request from client * @param response servlet reponse to client */ protected void setContentType( HttpServletRequest request, HttpServletResponse response ) { response.setContentType( defaultContentType ); } /** * Returns a context suitable to pass to the handleRequest() method * <br><br> * Default implementation will create a VelocityContext object, * put the HttpServletRequest and HttpServletResponse * into the context accessable via the keys VelocityServlet.REQUEST and * VelocityServlet.RESPONSE, respectively. * * @param request servlet request from client * @param response servlet reponse to client * * @return context */ protected Context createContext(HttpServletRequest request, HttpServletResponse response ) { /* * create a new context */ VelocityContext context = new VelocityContext(); /* * put the request/response objects into the context * wrap the HttpServletRequest to solve the introspection * problems */ context.put( REQUEST, new HttpServletRequestWrap( request ) ); context.put( RESPONSE, new HttpServletResponseWrap( response ) ); return context; } /** * Retrieves the requested template. * * @param name The file name of the template to retrieve relative to the * template root. * @return The requested template. * @throws ResourceNotFoundException if template not found * from any available source. * @throws ParseErrorException if template cannot be parsed due * to syntax (or other) error. * @throws Exception if an error occurs in template initialization */ public Template getTemplate( String name ) throws ResourceNotFoundException, ParseErrorException, Exception { return Runtime.getTemplate(name); } /** * Retrieves the requested template with the specified * character encoding. * * @param name The file name of the template to retrieve relative to the * template root. * @param encoding the character encoding of the template * * @return The requested template. * @throws ResourceNotFoundException if template not found * from any available source. * @throws ParseErrorException if template cannot be parsed due * to syntax (or other) error. * @throws Exception if an error occurs in template initialization */ public Template getTemplate( String name, String encoding ) throws ResourceNotFoundException, ParseErrorException, Exception { return Runtime.getTemplate( name, encoding ); } /** * Implement this method to add your application data to the context, * calling the <code>getTemplate()</code> method to produce your return * value. * <br><br> * In the event of a problem, you may handle the request directly * and return <code>null</code> or throw a more meaningful exception * for the error handler to catch. * * @param request servlet request from client * @param response servlet reponse * @param ctx The context to add your data to. * @return The template to merge with your context or null, indicating * that you handled the processing. */ protected Template handleRequest( HttpServletRequest request, HttpServletResponse response, Context ctx ) throws Exception { /* * invoke handleRequest */ Template t = handleRequest( ctx ); /* * if it returns null, this is the 'old' deprecated * way, and we want to mimic the behavior for a little * while anyway */ if (t == null) { throw new Exception ("handleRequest(Context) returned null - no template selected!" ); } return t; } /** * Implement this method to add your application data to the context, * calling the <code>getTemplate()</code> method to produce your return * value. * <br><br> * In the event of a problem, you may simple return <code>null</code> * or throw a more meaningful exception. * * @deprecated Use * {@link #handleRequest( HttpServletRequest request, * HttpServletResponse response, Context ctx )} * * @param ctx The context to add your data to. * @return The template to merge with your context. */ protected Template handleRequest( Context ctx ) throws Exception { throw new Exception ("You must override VelocityServlet.handleRequest( Context) " + " or VelocityServlet.handleRequest( HttpServletRequest, " + " HttpServletResponse, Context)" ); } /** * Invoked when there is an error thrown in any part of doRequest() processing. * <br><br> * Default will send a simple HTML response indicating there was a problem. * * @param request original HttpServletRequest from servlet container. * @param response HttpServletResponse object from servlet container. * @param cause Exception that was thrown by some other part of process. */ protected void error( HttpServletRequest request, HttpServletResponse response, Exception cause ) throws ServletException, IOException { StringBuffer html = new StringBuffer(); html.append("<html>"); html.append("<body bgcolor=\"#ffffff\">"); html.append("<h2>VelocityServlet : Error processing the template</h2>"); html.append( cause ); html.append("<br>"); StringWriter sw = new StringWriter(); cause.printStackTrace( new PrintWriter( sw ) ); html.append( sw.toString() ); html.append("</body>"); html.append("</html>"); response.getOutputStream().print( html.toString() ); } }
package org.apache.velocity.servlet; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.OutputStreamWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.Properties; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.Template; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.RuntimeSingleton; import org.apache.velocity.io.VelocityWriter; import org.apache.velocity.util.SimplePool; import org.apache.velocity.context.Context; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.MethodInvocationException; /** * Base class which simplifies the use of Velocity with Servlets. * Extend this class, implement the <code>handleRequest()</code> method, * and add your data to the context. Then call * <code>getTemplate("myTemplate.wm")</code>. * * This class puts some things into the context object that you should * be aware of: * <pre> * "req" - The HttpServletRequest object * "res" - The HttpServletResponse object * </pre> * * There are other methods you can override to access, alter or control * any part of the request processing chain. Please see the javadocs for * more information on : * <ul> * <li> loadConfiguration() : for setting up the Velocity runtime * <li> createContext() : for creating and loading the Context * <li> setContentType() : for changing the content type on a request * by request basis * <li> handleRequest() : you <b>must</b> implement this * <li> mergeTemplate() : the template rendering process * <li> requestCleanup() : post rendering resource or other cleanup * <li> error() : error handling * </ul> * <br> * If you put a String with key "contentType" object into the context within either your * servlet or within your template, then that will be used to override * the default content type specified in the properties file. * * @deprecated This servlet has been replaced by VelocityViewServlet, * available from the Velocity-Tools sub-project. VelocityViewServlet * provides support for quick, clean MVC web development. * VelocityServlet will be removed in a future version of Velocity. * * @author Dave Bryson * @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a> * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> * @author <a href="kjohnson@transparent.com">Kent Johnson</a> * @author <a href="dlr@finemaltcoding.com">Daniel Rall</a> * $Id: VelocityServlet.java,v 1.54 2003/11/10 22:33:54 dlr Exp $ */ public abstract class VelocityServlet extends HttpServlet { /** * The context key for the HTTP request object. */ public static final String REQUEST = "req"; /** * The context key for the HTTP response object. */ public static final String RESPONSE = "res"; /** * The HTTP content type context key. */ public static final String CONTENT_TYPE = "default.contentType"; /** * The default content type for the response */ public static final String DEFAULT_CONTENT_TYPE = "text/html"; /** * Encoding for the output stream */ public static final String DEFAULT_OUTPUT_ENCODING = "ISO-8859-1"; /** * The default content type, itself defaulting to {@link * #DEFAULT_CONTENT_TYPE} if not configured. */ private static String defaultContentType; /** * This is the string that is looked for when getInitParameter is * called (<code>org.apache.velocity.properties</code>). */ protected static final String INIT_PROPS_KEY = "org.apache.velocity.properties"; /** * Use of this properties key has been deprecated, and will be * removed in Velocity version 1.5. */ private static final String OLD_INIT_PROPS_KEY = "properties"; /** * Cache of writers */ private static SimplePool writerPool = new SimplePool(40); /** * Performs initialization of this servlet. Called by the servlet * container on loading. * * @param config The servlet configuration to apply. * * @exception ServletException */ public void init( ServletConfig config ) throws ServletException { super.init( config ); /* * do whatever we have to do to init Velocity */ initVelocity( config ); /* * Now that Velocity is initialized, cache some config. */ defaultContentType = RuntimeSingleton.getString(CONTENT_TYPE, DEFAULT_CONTENT_TYPE); } /** * Initializes the Velocity runtime, first calling * loadConfiguration(ServletConvig) to get a * java.util.Properties of configuration information * and then calling Velocity.init(). Override this * to do anything to the environment before the * initialization of the singelton takes place, or to * initialize the singleton in other ways. */ protected void initVelocity( ServletConfig config ) throws ServletException { try { /* * call the overridable method to allow the * derived classes a shot at altering the configuration * before initializing Runtime */ Properties props = loadConfiguration( config ); Velocity.init( props ); } catch( Exception e ) { throw new ServletException("Error initializing Velocity: " + e, e); } } /** * Loads the configuration information and returns that * information as a Properties, which will be used to * initialize the Velocity runtime. * <br><br> * Currently, this method gets the initialization parameter * VelocityServlet.INIT_PROPS_KEY, which should be a file containing * the configuration information. * <br><br> * To configure your Servlet Spec 2.2 compliant servlet runner to pass * this to you, put the following in your WEB-INF/web.xml file * <br> * <pre> * &lt;servlet&gt; * &lt;servlet-name&gt; YourServlet &lt/servlet-name&gt; * &lt;servlet-class&gt; your.package.YourServlet &lt;/servlet-class&gt; * &lt;init-param&gt; * &lt;param-name&gt; org.apache.velocity.properties &lt;/param-name&gt; * &lt;param-value&gt; velocity.properties &lt;/param-value&gt; * &lt;/init-param&gt; * &lt;/servlet&gt; * </pre> * * Alternately, if you wish to configure an entire context in this * fashion, you may use the following: * <br> * <pre> * &lt;context-param&gt; * &lt;param-name&gt; org.apache.velocity.properties &lt;/param-name&gt; * &lt;param-value&gt; velocity.properties &lt;/param-value&gt; * &lt;description&gt; Path to Velocity configuration &lt;/description&gt; * &lt;/context-param&gt; * </pre> * * Derived classes may do the same, or take advantage of this code to do the loading for them via : * <pre> * Properties p = super.loadConfiguration( config ); * </pre> * and then add or modify the configuration values from the file. * <br> * * @param config ServletConfig passed to the servlets init() function * Can be used to access the real path via ServletContext (hint) * @return java.util.Properties loaded with configuration values to be used * to initialize the Velocity runtime. * @throws FileNotFoundException if a specified file is not found. * @throws IOException I/O problem accessing the specified file, if specified. * @deprecated Use VelocityViewServlet from the Velocity Tools * library instead. */ protected Properties loadConfiguration(ServletConfig config) throws IOException, FileNotFoundException { // This is a little overly complex because of legacy support // for the initialization properties key "properties". // References to OLD_INIT_PROPS_KEY should be removed at // Velocity version 1.5. String propsFile = config.getInitParameter(INIT_PROPS_KEY); if (propsFile == null || propsFile.length() == 0) { ServletContext sc = config.getServletContext(); propsFile = config.getInitParameter(OLD_INIT_PROPS_KEY); if (propsFile == null || propsFile.length() == 0) { propsFile = sc.getInitParameter(INIT_PROPS_KEY); if (propsFile == null || propsFile.length() == 0) { propsFile = sc.getInitParameter(OLD_INIT_PROPS_KEY); if (propsFile != null && propsFile.length() > 0) { sc.log("Use of the properties initialization " + "parameter '" + OLD_INIT_PROPS_KEY + "' has " + "been deprecated by '" + INIT_PROPS_KEY + '\''); } } } else { sc.log("Use of the properties initialization parameter '" + OLD_INIT_PROPS_KEY + "' has been deprecated by '" + INIT_PROPS_KEY + '\''); } } /* * This will attempt to find the location of the properties * file from the relative path to the WAR archive (ie: * docroot). Since JServ returns null for getRealPath() * because it was never implemented correctly, then we know we * will not have an issue with using it this way. I don't know * if this will break other servlet engines, but it probably * shouldn't since WAR files are the future anyways. */ Properties p = new Properties(); if ( propsFile != null ) { String realPath = getServletContext().getRealPath(propsFile); if ( realPath != null ) { propsFile = realPath; } p.load( new FileInputStream(propsFile) ); } return p; } /** * Handles HTTP <code>GET</code> requests by calling {@link * #doRequest()}. */ public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doRequest(request, response); } /** * Handles HTTP <code>POST</code> requests by calling {@link * #doRequest()}. */ public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doRequest(request, response); } /** * Handles all requests (by default). * * @param request HttpServletRequest object containing client request * @param response HttpServletResponse object for the response */ protected void doRequest(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { Context context = null; try { /* * first, get a context */ context = createContext( request, response ); /* * set the content type */ setContentType( request, response ); /* * let someone handle the request */ Template template = handleRequest( request, response, context ); /* * bail if we can't find the template */ if ( template == null ) { return; } /* * now merge it */ mergeTemplate( template, context, response ); } catch (Exception e) { /* * call the error handler to let the derived class * do something useful with this failure. */ error( request, response, e); } finally { /* * call cleanup routine to let a derived class do some cleanup */ requestCleanup( request, response, context ); } } protected void requestCleanup( HttpServletRequest request, HttpServletResponse response, Context context ) { return; } protected void mergeTemplate( Template template, Context context, HttpServletResponse response ) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException, UnsupportedEncodingException, Exception { ServletOutputStream output = response.getOutputStream(); VelocityWriter vw = null; // ASSUMPTION: response.setContentType() has been called. String encoding = response.getCharacterEncoding(); try { vw = (VelocityWriter) writerPool.get(); if (vw == null) { vw = new VelocityWriter(new OutputStreamWriter(output, encoding), 4 * 1024, true); } else { vw.recycle(new OutputStreamWriter(output, encoding)); } template.merge(context, vw); } finally { try { if (vw != null) { /* * flush and put back into the pool * don't close to allow us to play * nicely with others. */ vw.flush(); /* * Clear the VelocityWriter's reference to its * internal OutputStreamWriter to allow the latter * to be GC'd while vw is pooled. */ vw.recycle(null); writerPool.put(vw); } } catch (Exception e) { // do nothing } } } /** * Sets the content type of the response, defaulting to {@link * #defaultContentType} if not overriden. Delegates to {@link * #chooseCharacterEncoding(HttpServletRequest)} to select the * appropriate character encoding. * * @param request The servlet request from the client. * @param response The servlet reponse to the client. */ protected void setContentType(HttpServletRequest request, HttpServletResponse response) { String contentType = defaultContentType; int index = contentType.lastIndexOf(';') + 1; if (index <= 0 || (index < contentType.length() && contentType.indexOf("charset", index) == -1)) { // Append the character encoding which we'd like to use. String encoding = chooseCharacterEncoding(request); //RuntimeSingleton.debug("Chose output encoding of '" + // encoding + '\''); if (!DEFAULT_OUTPUT_ENCODING.equalsIgnoreCase(encoding)) { contentType += "; charset=" + encoding; } } response.setContentType(contentType); //RuntimeSingleton.debug("Response Content-Type set to '" + // contentType + '\''); } /** * Chooses the output character encoding to be used as the value * for the "charset=" portion of the HTTP Content-Type header (and * thus returned by <code>response.getCharacterEncoding()</code>). * Called by {@link #setContentType(HttpServletRequest, * HttpServletResponse)} if an encoding isn't already specified by * Content-Type. By default, chooses the value of * RuntimeSingleton's <code>output.encoding</code> property. * * @param request The servlet request from the client. */ protected String chooseCharacterEncoding(HttpServletRequest request) { return RuntimeSingleton.getString(RuntimeConstants.OUTPUT_ENCODING, DEFAULT_OUTPUT_ENCODING); } /** * Returns a context suitable to pass to the handleRequest() method * <br><br> * Default implementation will create a VelocityContext object, * put the HttpServletRequest and HttpServletResponse * into the context accessable via the keys VelocityServlet.REQUEST and * VelocityServlet.RESPONSE, respectively. * * @param request servlet request from client * @param response servlet reponse to client * * @return context */ protected Context createContext(HttpServletRequest request, HttpServletResponse response ) { /* * create a new context */ VelocityContext context = new VelocityContext(); /* * put the request/response objects into the context * wrap the HttpServletRequest to solve the introspection * problems */ context.put( REQUEST, request ); context.put( RESPONSE, response ); return context; } /** * Retrieves the requested template. * * @param name The file name of the template to retrieve relative to the * template root. * @return The requested template. * @throws ResourceNotFoundException if template not found * from any available source. * @throws ParseErrorException if template cannot be parsed due * to syntax (or other) error. * @throws Exception if an error occurs in template initialization */ public Template getTemplate( String name ) throws ResourceNotFoundException, ParseErrorException, Exception { return RuntimeSingleton.getTemplate(name); } /** * Retrieves the requested template with the specified * character encoding. * * @param name The file name of the template to retrieve relative to the * template root. * @param encoding the character encoding of the template * * @return The requested template. * @throws ResourceNotFoundException if template not found * from any available source. * @throws ParseErrorException if template cannot be parsed due * to syntax (or other) error. * @throws Exception if an error occurs in template initialization * * @since Velocity v1.1 */ public Template getTemplate( String name, String encoding ) throws ResourceNotFoundException, ParseErrorException, Exception { return RuntimeSingleton.getTemplate( name, encoding ); } /** * Implement this method to add your application data to the context, * calling the <code>getTemplate()</code> method to produce your return * value. * <br><br> * In the event of a problem, you may handle the request directly * and return <code>null</code> or throw a more meaningful exception * for the error handler to catch. * * @param request servlet request from client * @param response servlet reponse * @param ctx The context to add your data to. * @return The template to merge with your context or null, indicating * that you handled the processing. * * @since Velocity v1.1 */ protected Template handleRequest( HttpServletRequest request, HttpServletResponse response, Context ctx ) throws Exception { /* * invoke handleRequest */ Template t = handleRequest( ctx ); /* * if it returns null, this is the 'old' deprecated * way, and we want to mimic the behavior for a little * while anyway */ if (t == null) { throw new Exception ("handleRequest(Context) returned null - no template selected!" ); } return t; } /** * Implement this method to add your application data to the context, * calling the <code>getTemplate()</code> method to produce your return * value. * <br><br> * In the event of a problem, you may simple return <code>null</code> * or throw a more meaningful exception. * * @deprecated Use * {@link #handleRequest( HttpServletRequest request, * HttpServletResponse response, Context ctx )} * * @param ctx The context to add your data to. * @return The template to merge with your context. */ protected Template handleRequest( Context ctx ) throws Exception { throw new Exception ("You must override VelocityServlet.handleRequest( Context) " + " or VelocityServlet.handleRequest( HttpServletRequest, " + " HttpServletResponse, Context)" ); } /** * Invoked when there is an error thrown in any part of doRequest() processing. * <br><br> * Default will send a simple HTML response indicating there was a problem. * * @param request original HttpServletRequest from servlet container. * @param response HttpServletResponse object from servlet container. * @param cause Exception that was thrown by some other part of process. */ protected void error( HttpServletRequest request, HttpServletResponse response, Exception cause ) throws ServletException, IOException { StringBuffer html = new StringBuffer(); html.append("<html>"); html.append("<title>Error</title>"); html.append("<body bgcolor=\"#ffffff\">"); html.append("<h2>VelocityServlet: Error processing the template</h2>"); html.append("<pre>"); String why = cause.getMessage(); if (why != null && why.trim().length() > 0) { html.append(why); html.append("<br>"); } StringWriter sw = new StringWriter(); cause.printStackTrace( new PrintWriter( sw ) ); html.append( sw.toString() ); html.append("</pre>"); html.append("</body>"); html.append("</html>"); response.getOutputStream().print( html.toString() ); } }
package org.jdesktop.swingx.painter; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.Transparency; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ColorModel; import java.lang.ref.SoftReference; import java.util.HashMap; import java.util.Map; import javax.swing.JComponent; import org.jdesktop.beans.AbstractBean; import org.jdesktop.swingx.util.PaintUtils; /** * <p>A convenient base class from which concrete Painter implementations may * extend. It extends AbstractBean and thus provides property change notification * (which is crucial for the Painter implementations to be available in a * GUI builder).Sublasses simply need * to extend AbstractPainter and implement the doPaint method. * * <p>For example, here is the doPaint method of RectanglePainter: * <pre><code> * public void doPaint(Graphics2D g, T obj, int width, int height) { * g.setPaint(getPaint()); * g.fillRect(0, 0, width, height); * } * </code></pre> * * <p>AbstractPainter provides a very useful default implementation of * the paint method. It: * <ol> * <li>Sets any specified rendering hints</li> * <li>Sets the Composite if there is one</li> * <li>Delegates to doPaint</li> * <ol></p> * * <p>Specifying rendering hints can greatly improve the visual impact of your * applications. For example, by default Swing doesn't do much in the way of * antialiasing (except for Fonts, but that's another story). Pinstripes don't * look so good without antialiasing. So if I were going to paint pinstripes, I * might do it like this: * <pre><code> * PinstripePainter p = new PinstripePainter(); * p.setAntialiasing(Antialiasing.ON); * </code></pre></p> * * <p>You can read more about antialiasing and other rendering hints in the * java.awt.RenderingHints documentation. <strong>By nature, changing the rendering * hints may have an impact on performance. Certain hints require more * computation, others require less</strong></p> * * @author rbair */ public abstract class AbstractPainter<T> extends AbstractBean implements Painter<T> { /** * A hint as to whether or not to attempt caching the image */ private boolean useCache = false; /** * The cached image, if useCache is true */ private transient SoftReference<BufferedImage> cachedImage; /** * The Effects to apply to the results of the paint() operation */ private BufferedImageOp[] effects = new BufferedImageOp[0]; /** * Creates a new instance of AbstractPainter */ public AbstractPainter() { } /** * Returns true whether or not the painter is using caching. * @return whether or not the cache should be used */ protected boolean isUseCache() { return useCache; } /** * <p>A convenience method for specifying the effects to use based on * BufferedImageOps. These will each be individually wrapped by an ImageFilter * and then setFilters(Effect... effects) will be called with the resulting * array</p> * * * @param effects the BufferedImageOps to wrap as effects */ public void setFilters(BufferedImageOp ... effects) { BufferedImageOp[] old = getFilters(); this.effects = new BufferedImageOp[effects == null ? 0 : effects.length]; if (effects != null) { System.arraycopy(effects, 0, this.effects, 0, effects.length); } firePropertyChange("effects", old, getFilters()); } /** * A defensive copy of the Effects to apply to the results * of the AbstractPainter's painting operation. The array may * be empty but it Will never be null. * @return the array of effects applied to this painter */ public BufferedImageOp[] getFilters() { BufferedImageOp[] results = new BufferedImageOp[effects.length]; System.arraycopy(effects, 0, results, 0, results.length); return results; } private boolean antialiasing = true; /** * Returns if antialiasing is turned on or not. The default value is true. * This is a bound property. * @return the current antialiasing setting */ public boolean isAntialiasing() { return antialiasing; } /** * Sets the antialiasing setting. This is a bound property. * @param value the new antialiasing setting */ public void setAntialiasing(boolean value) { boolean old = isAntialiasing(); antialiasing = value; firePropertyChange("antialiasing", old, isAntialiasing()); } private boolean fractionalMetrics = true; /** * Gets the current fractional metrics setting. This property determines if Fractional Metrics will * be used when drawing text. @see java.awt.RenderingHints.KEY_FRACTIONALMETRICS. * @return the current fractional metrics setting */ public boolean isFractionalMetricsOn() { return fractionalMetrics; } /** * Sets a new value for the fractional metrics setting. This setting determines if fractional * metrics should be used when drawing text. @see java.awt.RenderingHints.KEY_FRACTIONALMETRICS. * @param fractionalMetrics the new fractional metrics setting */ public void setFractionalMetricsOn(boolean fractionalMetrics) { boolean old = isFractionalMetricsOn(); this.fractionalMetrics = fractionalMetrics; firePropertyChange("fractionalMetricsOn", old, isFractionalMetricsOn()); } /** * An enum representing the possible interpolation values of Bicubic, Bilinear, and * Nearest Neighbor. These map to the underlying RenderingHints, * but are easier to use and serialization safe. */ public enum Interpolation { /** * use bicubic interpolation */ Bicubic(RenderingHints.VALUE_INTERPOLATION_BICUBIC), /** * use bilinear interpolation */ Bilinear(RenderingHints.VALUE_INTERPOLATION_BILINEAR), /** * use nearest neighbor interpolation */ NearestNeighbor(RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); private Object value; Interpolation(Object value) { this.value = value; } private void configureGraphics(Graphics2D g) { g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, value); } } private Interpolation interpolation = Interpolation.NearestNeighbor; /** * Gets the current interpolation setting. This property determines if interpolation will * be used when drawing scaled images. @see java.awt.RenderingHints.KEY_INTERPOLATION. * @return the current interpolation setting */ public Interpolation getInterpolation() { return interpolation; } /** * Sets a new value for the interpolation setting. This setting determines if interpolation * should be used when drawing scaled images. @see java.awt.RenderingHints.KEY_INTERPOLATION. * @param value the new interpolation setting */ public void setInterpolation(Interpolation value) { Object old = getInterpolation(); this.interpolation = value; firePropertyChange("interpolation", old, getInterpolation()); } /** * * * @inheritDoc * @param g * @param component * @param width * @param height */ public void paint(Graphics2D g, T component, int width, int height) { if(!isVisible()) { return; } configureGraphics(g, component); //if I am caching, and the cache is not null, and the image has the //same dimensions as the component, then simply paint the image BufferedImage image = cachedImage == null ? null : cachedImage.get(); if (isUseCache() && image != null && image.getWidth() == width && image.getHeight() == height) { g.drawImage(image, 0, 0, null); } else { BufferedImageOp[] effects = getFilters(); if (effects.length > 0 || isUseCache()) { image = PaintUtils.createCompatibleImage( width, height, Transparency.TRANSLUCENT); Graphics2D gfx = image.createGraphics(); configureGraphics(gfx, component); doPaint(gfx, component, width, height); gfx.dispose(); for (BufferedImageOp effect : effects) { image = effect.filter(image,null); } g.drawImage(image, 0, 0, null); if (isUseCache()) { cachedImage = new SoftReference<BufferedImage>(image); } } else { doPaint(g, component, width, height); } } } /** * Utility method for configuring the given Graphics2D with the rendering hints, * composite, and clip */ private void configureGraphics(Graphics2D g, T c) { if(c instanceof JComponent) { g.setFont(((JComponent)c).getFont()); } if(isAntialiasing()) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } else { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } getInterpolation().configureGraphics(g); } /** * Subclasses must implement this method and perform custom painting operations * here. * @param width * @param height * @param g The Graphics2D object in which to paint * @param component The JComponent that the Painter is delegate for. */ protected abstract void doPaint(Graphics2D g, T component, int width, int height); /** * Holds value of property visible. */ private boolean visible = true; /** * Getter for property visible. * * @return Value of property visible. */ public boolean isVisible() { return this.visible; } /** * Setter for property visible. * * @param visible New value of property visible. */ public void setVisible(boolean visible) { boolean oldEnabled = isVisible(); this.visible = visible; firePropertyChange("visible", oldEnabled, isVisible()); } }
package org.jivesoftware.spark.ui; import org.jivesoftware.resource.Default; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.spark.ChatManager; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.component.JMultilineLabel; import org.jivesoftware.spark.component.borders.PartialLineBorder; import org.jivesoftware.spark.util.GraphicUtils; import org.jivesoftware.spark.util.ModelUtil; import org.jivesoftware.spark.util.SwingWorker; import org.jivesoftware.spark.util.log.Log; import org.jivesoftware.sparkimpl.plugin.gateways.transports.Transport; import org.jivesoftware.sparkimpl.plugin.gateways.transports.TransportUtils; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JWindow; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.net.MalformedURLException; import java.net.URL; /** * Represents the UI for the "ToolTip" functionallity in the ContactList. * * @author Derek DeMoro */ public class ContactInfoWindow extends JPanel { private final JLabel nicknameLabel = new JLabel(); private final JMultilineLabel statusLabel = new JMultilineLabel(); private final JLabel fullJIDLabel = new JLabel(); private final JLabel imageLabel = new JLabel(); private final JLabel iconLabel = new JLabel(); private ContactItem contactItem; private JPanel toolbar; private JWindow window = new JWindow(); private boolean inWindow; private ChatManager chatManager; public ContactInfoWindow() { setLayout(new GridBagLayout()); this.chatManager = SparkManager.getChatManager(); setBackground(Color.white); toolbar = new JPanel() { public void paintComponent(Graphics g) { final Image backgroundImage = Default.getImageIcon(Default.TOP_BOTTOM_BACKGROUND_IMAGE).getImage(); double scaleX = getWidth() / (double)backgroundImage.getWidth(null); double scaleY = getHeight() / (double)backgroundImage.getHeight(null); AffineTransform xform = AffineTransform.getScaleInstance(scaleX, scaleY); ((Graphics2D)g).drawImage(backgroundImage, xform, this); } }; toolbar.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); toolbar.setOpaque(false); toolbar.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.gray)); add(toolbar, new GridBagConstraints(0, 0, 3, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); add(iconLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 0, 5), 0, 0)); add(nicknameLabel, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 0, 5), 0, 0)); add(statusLabel, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 5), 0, 0)); add(fullJIDLabel, new GridBagConstraints(0, 4, 3, 1, 1.0, 1.0, GridBagConstraints.SOUTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 5, 5), 0, 0)); add(imageLabel, new GridBagConstraints(2, 1, 1, 3, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0)); nicknameLabel.setFont(new Font("Dialog", Font.BOLD, 12)); statusLabel.setFont(new Font("Dialog", Font.PLAIN, 12)); statusLabel.setForeground(Color.gray); fullJIDLabel.setFont(new Font("Dialog", Font.PLAIN, 12)); fullJIDLabel.setForeground(Color.gray); fullJIDLabel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.gray)); setBorder(BorderFactory.createLineBorder(Color.gray, 1)); window.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent e) { inWindow = true; } public void mouseExited(MouseEvent e) { Point point = e.getLocationOnScreen(); Point windowPoint = window.getLocationOnScreen(); int newX = (int)point.getX(); int newY = (int)point.getY(); int x = (int)windowPoint.getX(); int y = (int)windowPoint.getY(); boolean close = false; if (newX < x || newX > x + window.getWidth()) { close = true; } if (newY < y || newY > y + window.getHeight()) { close = true; } if (close) { inWindow = false; checkWindow(); } } }); window.getContentPane().add(this); } public void checkWindow() { final SwingWorker worker = new SwingWorker() { public Object construct() { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } return true; } public void finished() { if (!inWindow) { window.setVisible(false); contactItem = null; } } }; worker.start(); } public void display(ContactGroup group, MouseEvent e) { int loc = group.getList().locationToIndex(e.getPoint()); ContactItem item = (ContactItem)group.getList().getModel().getElementAt(loc); if (item == null || item.getFullJID() == null) { return; } if (getContactItem() != null && getContactItem() == item) { return; } iconLabel.setIcon(item.getIcon()); Point point = group.getList().indexToLocation(loc); window.setFocusableWindowState(false); setContactItem(item); chatManager.notifyContactInfoHandlers(this); window.pack(); Point mainWindowLocation = SparkManager.getMainWindow().getLocationOnScreen(); Point listLocation = group.getList().getLocationOnScreen(); int x = (int)mainWindowLocation.getX() + SparkManager.getMainWindow().getWidth(); final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); if ((int)screenSize.getWidth() - getPreferredSize().getWidth() >= x) { window.setLocation(x, (int)listLocation.getY() + (int)point.getY()); if (!window.isVisible()) window.setVisible(true); } else { window.setLocation((int)mainWindowLocation.getX() - (int)getPreferredSize().getWidth(), (int)listLocation.getY() + (int)point.getY()); if (!window.isVisible()) window.setVisible(true); } } public void setContactItem(ContactItem contactItem) { this.contactItem = contactItem; if (contactItem == null) { return; } nicknameLabel.setText(contactItem.getNickname()); String status = contactItem.getStatus(); if (!ModelUtil.hasLength(status)) { if (contactItem.getPresence() == null || contactItem.getPresence().getType() == Presence.Type.unavailable) { status = "Offline"; } else { status = "Online"; } } statusLabel.setText(status); Transport transport = TransportUtils.getTransport(StringUtils.parseServer(contactItem.getFullJID())); if (transport != null) { fullJIDLabel.setIcon(transport.getIcon()); String name = StringUtils.parseName(contactItem.getFullJID()); fullJIDLabel.setText(transport.getName() + " - " + name); } else { fullJIDLabel.setText(contactItem.getFullJID()); fullJIDLabel.setIcon(null); } imageLabel.setBorder(null); try { URL avatarURL = contactItem.getAvatarURL(); ImageIcon icon = null; if (avatarURL != null) { icon = new ImageIcon(avatarURL); } if (icon != null && icon.getIconHeight() > 1) { icon = GraphicUtils.scaleImageIcon(icon, 96, 96); imageLabel.setIcon(icon); imageLabel.setBorder(new PartialLineBorder(Color.gray, 1)); } else { icon = new ImageIcon(SparkRes.getImageIcon(SparkRes.BLANK_24x24).getImage().getScaledInstance(1, 64, Image.SCALE_SMOOTH)); imageLabel.setIcon(icon); } } catch (MalformedURLException e) { Log.error(e); } toolbar.removeAll(); } public ContactItem getContactItem() { return contactItem; } public void addChatRoomButton(ChatRoomButton button) { toolbar.add(button); } public void addToolbarComponent(Component comp) { toolbar.add(comp); } public JPanel getToolbar() { return toolbar; } public void dispose() { window.dispose(); } public Dimension getPreferredSize() { final Dimension size = super.getPreferredSize(); size.width = 330; size.height = 160; return size; } }
package jsettlers.buildingcreator.editor; import go.graphics.sound.ISoundDataRetriever; import go.graphics.sound.SoundPlayer; import go.graphics.swing.AreaContainer; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import jsettlers.buildingcreator.editor.jobeditor.PersonJobEditor; import jsettlers.buildingcreator.editor.map.BuildingtestMap; import jsettlers.buildingcreator.editor.map.PseudoTile; import jsettlers.common.Color; import jsettlers.common.buildings.EBuildingType; import jsettlers.common.buildings.RelativeBricklayer; import jsettlers.common.buildings.RelativeStack; import jsettlers.common.material.EMaterialType; import jsettlers.common.movable.EDirection; import jsettlers.common.position.RelativePoint; import jsettlers.common.position.ShortPoint2D; import jsettlers.common.resources.IResourceProvider; import jsettlers.common.resources.ResourceManager; import jsettlers.graphics.action.Action; import jsettlers.graphics.action.PointAction; import jsettlers.graphics.map.IMapInterfaceListener; import jsettlers.graphics.map.MapInterfaceConnector; import jsettlers.graphics.map.draw.ImageProvider; import jsettlers.graphics.swing.JOGLPanel; import jsettlers.graphics.swing.SwingResourceLoader; /** * This is the main building creator class. * * @author michael */ public class BuildingCreator implements IMapInterfaceListener { static { // sets the native library path for the system dependent jogl libs SwingResourceLoader.setupSwingPaths(); } private BuildingDefinition definition; private JFrame window; private final BuildingtestMap map; private ToolType tool = ToolType.SET_BLOCKED; private JPanel actionList; private JLabel positionDisplayer; private BuildingCreator() { ResourceManager.setProvider(new IResourceProvider() { @Override public InputStream getFile(String name) throws IOException { String currentParentFolder = new File(new File("").getAbsolutePath()).getParent().replace('\\', '/'); String path = currentParentFolder + "/jsettlers.common/resources/"; System.out.println(path); File file = new File(path + name); return new FileInputStream(file); } @Override public OutputStream writeFile(String name) throws IOException { return null; } @Override public File getSaveDirectory() { return null; } @Override public File getTempDirectory() { return null; } }); EBuildingType type = askType(); definition = new BuildingDefinition(type); map = new BuildingtestMap(definition); for (int x = 0; x < map.getWidth(); x++) { for (int y = 0; y < map.getHeight(); y++) { reloadColor(new ShortPoint2D(x, y)); } } JOGLPanel mapPanel = new JOGLPanel(new SoundPlayer() { @Override public void playSound(int sound, float lvolume, float rvolume) { } @Override public void setSoundDataRetriever(ISoundDataRetriever soundDataRetriever) { } }); MapInterfaceConnector connector = mapPanel.showGameMap(map, null); connector.addListener(this); JPanel menu = new JPanel(); menu.setLayout(new BoxLayout(menu, BoxLayout.Y_AXIS)); menu.setPreferredSize(new Dimension(200, 100)); actionList = new JPanel(); actionList.setLayout(new BoxLayout(actionList, BoxLayout.Y_AXIS)); menu.add(new JScrollPane(actionList)); menu.add(createToolChangeBar()); JButton addButton = new JButton("add new action"); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { addNewAction(); } }); menu.add(addButton); JButton xmlButton = new JButton("show xml data"); xmlButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showXML(); } }); menu.add(xmlButton); positionDisplayer = new JLabel(); menu.add(positionDisplayer); JPanel root = new JPanel(); root.setLayout(new BoxLayout(root, BoxLayout.X_AXIS)); root.add(new AreaContainer(mapPanel.getArea())); root.add(menu); window = new JFrame("Edit " + type.toString()); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.add(root); window.pack(); window.setSize(600, 500); window.setVisible(true); } private JButton createToolChangeBar() { JButton button = new JButton("Select tool..."); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { tool = (ToolType) JOptionPane.showInputDialog(null, "Select building type", "Building Type", JOptionPane.QUESTION_MESSAGE, null, ToolType.values(), tool); for (int x = 0; x < map.getWidth(); x++) { for (int y = 0; y < map.getWidth(); y++) { reloadColor(new ShortPoint2D(x, y)); } } } }); return button; } private void reloadActionList() { actionList.removeAll(); for (String name : definition.getActionNames()) { PersonJobEditor panel = new PersonJobEditor(name, definition.getActionByName(name)); actionList.add(panel); } actionList.revalidate(); } private void addNewAction() { String acitonName = JOptionPane.showInputDialog(window, "Select job name"); if (acitonName != null) { definition.addAction(acitonName); reloadActionList(); } } private EBuildingType askType() { return (EBuildingType) JOptionPane.showInputDialog(null, "Select building type", "Building Type", JOptionPane.QUESTION_MESSAGE, null, EBuildingType.values(), null); } public static void main(String[] args) { ImageProvider provider = ImageProvider.getInstance(); provider.addLookupPath(new File("/home/michael/.wine/drive_c/BlueByte/S3AmazonenDemo/GFX")); provider.addLookupPath(new File("D:/Games/Siedler3/GFX")); new BuildingCreator(); } @Override public void action(Action action) { if (action instanceof PointAction) { PointAction sAction = (PointAction) action; ShortPoint2D pos = sAction.getPosition(); RelativePoint relative = absoluteToRelative(pos); positionDisplayer.setText("x = " + (pos.x - BuildingtestMap.OFFSET) + ", y = " + (pos.y - BuildingtestMap.OFFSET)); if (tool == ToolType.SET_BLOCKED) { toogleUsedTile(relative); } else if (tool == ToolType.SET_DOOR) { setDoor(relative); } else if (tool == ToolType.ADD_STACK) { addStack(relative); } else if (tool == ToolType.REMOVE_STACK) { removeStack(relative); } else if (tool == ToolType.SET_FLAG) { setFlag(relative); } else if (tool == ToolType.SET_BUILDMARK) { definition.toggleBuildmarkStatus(relative); } else if (tool == ToolType.BRICKLAYER_NE) { definition.toggleBrickayer(relative, EDirection.NORTH_EAST); } else if (tool == ToolType.BRICKLAYER_NW) { definition.toggleBrickayer(relative, EDirection.NORTH_WEST); } reloadColor(pos); } } private void removeStack(RelativePoint relative) { definition.removeStack(relative); } private void addStack(RelativePoint relative) { EMaterialType material = (EMaterialType) JOptionPane.showInputDialog(null, "Select building type", "Building Type", JOptionPane.QUESTION_MESSAGE, null, EMaterialType.values(), tool); Integer buildrequired = (Integer) JOptionPane.showInputDialog(null, "Select building type", "Building Type", JOptionPane.QUESTION_MESSAGE, null, new Integer[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }, tool); if (material != null && buildrequired != null) { definition.setStack(relative, material, buildrequired.intValue()); } } private void setDoor(RelativePoint tile) { RelativePoint oldDoor = definition.getDoor(); ShortPoint2D oldPos = relativeToAbsolute(oldDoor); reloadColor(oldPos); definition.setDoor(tile); } private void setFlag(RelativePoint tile) { RelativePoint oldFlag = definition.getFlag(); ShortPoint2D oldPos = relativeToAbsolute(oldFlag); reloadColor(oldPos); definition.setFlag(tile); } private ShortPoint2D relativeToAbsolute(RelativePoint oldDoor) { ShortPoint2D oldPos = new ShortPoint2D(oldDoor.getDx() + BuildingtestMap.OFFSET, oldDoor.getDy() + BuildingtestMap.OFFSET); return oldPos; } private RelativePoint absoluteToRelative(ShortPoint2D pos) { RelativePoint tile = new RelativePoint(pos.x - BuildingtestMap.OFFSET, pos.y - BuildingtestMap.OFFSET); return tile; } private void toogleUsedTile(RelativePoint relative) { if (definition.getBlockedStatus(relative)) { definition.setBlockedStatus(relative, false, false); } else if (definition.getProtectedStatus(relative)) { definition.setBlockedStatus(relative, true, true); } else { definition.setBlockedStatus(relative, true, false); } } private void reloadColor(ShortPoint2D pos) { PseudoTile tile = map.getTile(pos); ArrayList<Color> colors = new ArrayList<Color>(); RelativePoint relative = absoluteToRelative(pos); if (definition.getBlockedStatus(relative)) { colors.add(new Color(0xff0343df)); } else if (definition.getProtectedStatus(relative)) { colors.add(new Color(0xff75bbfd)); } if (tool == ToolType.SET_BUILDMARK) { if (definition.getBuildmarkStatus(relative)) { colors.add(new Color(0xfff97306)); } } if (tool == ToolType.SET_DOOR) { if (definition.getDoor().equals(relative)) { colors.add(new Color(0xfff97306)); } } if (tool == ToolType.SET_FLAG) { if (definition.getFlag().equals(relative)) { colors.add(new Color(0xfff97306)); } } if (tool == ToolType.ADD_STACK || tool == ToolType.REMOVE_STACK) { if (definition.getStack(relative) != null) { colors.add(new Color(0xfff97306)); tile.setStack(new MapStack(definition.getStack(relative))); } else { tile.setStack(null); } } if (tool == ToolType.BRICKLAYER_NE || tool == ToolType.BRICKLAYER_NW) { if (definition.getBricklayerStatus(relative)) { colors.add(new Color(0xfff97306)); } } if (!colors.isEmpty()) { tile.setDebugColor(mixColors(colors)); } else { tile.setDebugColor(0); } } private static int mixColors(ArrayList<Color> colors) { float bluesum = 0; float redsum = 0; float greensum = 0; for (Color color : colors) { bluesum += color.getBlue(); redsum += color.getRed(); greensum += color.getGreen(); } int color = Color.getARGB(redsum / colors.size(), greensum / colors.size(), bluesum / colors.size(), 1); return color; } private void showXML() { StringBuilder builder = new StringBuilder(""); for (RelativePoint tile : definition.getBlocked()) { builder.append("\t<blocked dx=\""); builder.append(tile.getDx()); builder.append("\" dy=\""); builder.append(tile.getDy()); builder.append("\" block=\"true\" />\n"); } for (RelativePoint tile : definition.getJustProtected()) { builder.append("\t<blocked dx=\""); builder.append(tile.getDx()); builder.append("\" dy=\""); builder.append(tile.getDy()); builder.append("\" block=\"false\" />\n"); } RelativePoint door = definition.getDoor(); builder.append("\t<door dx=\""); builder.append(door.getDx()); builder.append("\" dy=\""); builder.append(door.getDy()); builder.append("\" />\n"); for (RelativeStack stack : definition.getStacks()) { builder.append("\t<stack dx=\""); builder.append(stack.getDx()); builder.append("\" dy=\""); builder.append(stack.getDy()); builder.append("\" material=\""); builder.append(stack.getType().name()); builder.append("\" buildrequired=\""); builder.append(stack.requiredForBuild()); builder.append("\" />\n"); } for (RelativeBricklayer bricklayer : definition.getBricklayers()) { builder.append("\t<bricklayer dx=\""); builder.append(bricklayer.getPosition().getDx()); builder.append("\" dy=\""); builder.append(bricklayer.getPosition().getDy()); builder.append("\" direction=\""); builder.append(bricklayer.getDirection()); builder.append("\" />\n"); } RelativePoint flag = definition.getFlag(); builder.append("\t<flag dx=\""); builder.append(flag.getDx()); builder.append("\" dy=\""); builder.append(flag.getDy()); builder.append("\" />\n"); for (RelativePoint mark : definition.getBuildmarks()) { builder.append("\t<buildmark dx=\""); builder.append(mark.getDx()); builder.append("\" dy=\""); builder.append(mark.getDy()); builder.append("\" />\n"); } JDialog dialog = new JDialog(window, "xml"); dialog.add(new JScrollPane(new JTextArea(builder.toString()))); dialog.pack(); dialog.setVisible(true); } }
package com.google.code.jscep.response; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class Capabilities { public static enum Capability { /** * CA Supports the GetNextCACert message. */ GET_NEXT_CA_CERT, /** * PKIOPeration messages may be sent via HTTP POST. */ POST_PKI_OPERATION, /** * Clients may use current certificate and key to authenticate an enrollment request for a new certificate. */ RENEWAL, /** * CA Supports the SHA-512 hashing algorithm in signatures and fingerprints. */ SHA_512, /** * CA Supports the SHA-256 hashing algorithm in signatures and fingerprints. */ SHA_256, /** * CA Supports the SHA-1 hashing algorithm in signatures and fingerprints. */ SHA_1, /** * CA Supports triple-DES for encryption. */ TRIPLE_DES; } private Set<Capability> capabilties = new HashSet<Capability>(); private Map<String, Capability> map = new HashMap<String, Capability>(); { map.put("GetNextCACert", Capability.GET_NEXT_CA_CERT); map.put("POSTPKIOperation", Capability.POST_PKI_OPERATION); map.put("Renewal", Capability.RENEWAL); map.put("SHA-512", Capability.SHA_512); map.put("SHA-256", Capability.SHA_256); map.put("SHA-1", Capability.SHA_1); map.put("DES3", Capability.TRIPLE_DES); } public Capabilities(List<String> capabilities) { for (String capability : capabilities) { this.capabilties.add(map.get(capability)); } } private boolean supports(Capability capability) { return capabilties.contains(capability); } /** * Returns <tt>true</tt> if the CA supports CA key rollover, <tt>false</tt> otherwise. * * @return <tt>true</tt> if the CA supports CA key rollover, <tt>false</tt> otherwise. */ public boolean supportsCaKeyRollover() { return supports(Capability.GET_NEXT_CA_CERT); } /** * Returns <tt>true</tt> if the CA supports HTTP POST requests, <tt>false</tt> otherwise. * * @return <tt>true</tt> if the CA supports HTTP POST requests, <tt>false</tt> otherwise. */ public boolean supportsPost() { return supports(Capability.POST_PKI_OPERATION); } /** * Returns <tt>true</tt> if the CA supports certificate renewal, <tt>false</tt> otherwise. * * @return <tt>true</tt> if the CA supports certificate renewal, <tt>false</tt> otherwise. */ public boolean supportsRenewal() { return supports(Capability.RENEWAL); } /** * Returns <tt>true</tt> if the CA supports SHA-1, <tt>false</tt> otherwise. * * @return <tt>true</tt> if the CA supports SHA-1, <tt>false</tt> otherwise. */ public boolean supportsSHA1() { return supports(Capability.SHA_1); } /** * Returns <tt>true</tt> if the CA supports SHA-256, <tt>false</tt> otherwise. * * @return <tt>true</tt> if the CA supports SHA-256, <tt>false</tt> otherwise. */ public boolean supportsSHA256() { return supports(Capability.SHA_256); } /** * Returns <tt>true</tt> if the CA supports SHA-512, <tt>false</tt> otherwise. * * @return <tt>true</tt> if the CA supports SHA-512, <tt>false</tt> otherwise. */ public boolean supportsSHA512() { return supports(Capability.SHA_512); } /** * Returns <tt>true</tt> if the CA supports TripleDES, <tt>false</tt> otherwise. * * @return <tt>true</tt> if the CA supports TripleDES, <tt>false</tt> otherwise. */ public boolean supportsTripleDES() { return supports(Capability.TRIPLE_DES); } public String getPreferredCipher() { if (supportsTripleDES()) { return "DESede"; } else { return "DES"; } } public String getPreferredMessageDigest() { if (supportsSHA512()) { return "SHA-512"; } else if (supportsSHA256()) { return "SHA-256"; } else if (supportsSHA1()) { return "SHA-1"; } else { return "MD5"; } } @Override public String toString() { return capabilties.toString(); } }
package application.controllers; import application.factories.LegendFactory; import application.factories.ListFactory; import application.factories.MenuFactory; import application.factories.WindowFactory; import application.fxobjects.Cell; import application.fxobjects.graphCells.RectangleCell; import application.fxobjects.treeCells.LeafCell; import core.annotation.Annotation; import core.annotation.AnnotationProcessor; import core.filtering.Filter; import core.filtering.Filtering; import core.graph.Node; import core.parsers.AnnotationParser; import core.parsers.MetaDataParser; import core.typeEnums.CellType; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.geometry.Pos; import javafx.scene.control.*; import javafx.scene.effect.DropShadow; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.URISyntaxException; import java.net.URL; import java.util.*; /** * MainController for GUI. */ public class MainController extends Controller<BorderPane> { /** * The Controllers used in this Class. */ private GraphController graphController; private TreeController treeController; /** * FXML Objects. */ @FXML private ScrollPane screen; @FXML private MenuBar menuBar; private HBox legend; private VBox listVBox; private ListView list; private int currentView; private ListFactory listFactory; private TextField genomeTextField; private TextField annotationTextField; private StackPane box; private Label zoomIndicator; private int secondCount; private Filtering filtering; private boolean inGraph; private boolean metaDataLoaded; private boolean annotationsLoaded; private boolean allowNucleotideLevel; private boolean showReferenceStrain; private boolean firstInitialization = true; private Button searchButton, selectAllButton, deselectSearchButton, highlightButton, deselectAnnotationButton; private HBox hBox; private Stack<String> mostRecentGFF; private Stack<String> mostRecentGFA; private Stack<String> mostRecentNWK; private Stack<String> mostRecentDir; private MenuFactory menuFactory; /** * Constructor to create MainController based on abstract Controller. */ public MainController() { super(new BorderPane()); loadFXMLfile("/fxml/main.fxml"); this.secondCount = -1; this.mostRecentGFF = new Stack<>(); this.mostRecentGFA = new Stack<>(); this.mostRecentNWK = new Stack<>(); this.mostRecentDir = new Stack<>(); this.filtering = new Filtering(); this.metaDataLoaded = false; this.annotationsLoaded = false; this.allowNucleotideLevel = false; this.showReferenceStrain = false; checkMostRecent("/mostRecentGFA.txt", mostRecentGFA); checkMostRecent("/mostRecentGFF.txt", mostRecentGFF); checkMostRecent("/mostRecentNWK.txt", mostRecentNWK); checkMostRecent("/mostRecentDir.txt", mostRecentDir); createMenu(false, false); setBackground("/background_images/DART2N.png"); // Create the new GraphController graphController = new GraphController(this); } /** * Initializes the graph. */ public void initGraph() { initGUI(); graphController.getGraph().findAllGenomes(); } /** * Method to set the background of the MainScreen * * @param s URL of the image to be set */ public void setBackground(String s) { ImageView imageView = new ImageView(s); imageView.fitWidthProperty().bind(this.getRoot().widthProperty()); imageView.fitHeightProperty().bind(this.getRoot().heightProperty()); MenuFactory.toggleViewMenu(true); MenuFactory.toggleFileMenu(false); MenuFactory.toggleFilters(true); this.getRoot().setCenter(imageView); } /** * Method to get the Screen * @return the Screen */ public ScrollPane getScreen() { return screen; } /** * Initializes the tree. * * @param s Path to the tree file. */ public void initTree(String s) { treeController = new TreeController(this, s); fillTree(); } /** * Initializes the annotation data. * * @param path Path to the annotation data file. */ public void initAnnotations(String path) { setAnnotationsLoaded(true); List<Annotation> annotations = AnnotationParser.readGFFFromFile(path); graphController.getGraph().initAnnotations(annotations); } /** * Initializes the meta data in the MetaData class. * * @param path Path to the meta data file. */ public void initMetadata(String path) { MetaDataParser.readMetadataFromFile(path); setMetaDataLoaded(true); } /** * Method to check whether the MetaData is loaded or not * * @return boolean */ public boolean isMetaDataLoaded() { return metaDataLoaded; } /** * Method to set whether the MetaData is loaded or not * * @param x boolean */ public void setMetaDataLoaded(boolean x) { this.metaDataLoaded = x; } /** * Method the check whether we have loaded annotation-data or not * * @return boolean */ public boolean isAnnotationsLoaded() { return annotationsLoaded; } /** * Method to set whether the annotation-data is loaded or not * * @param x boolean indication whether annotation-data is loaded or not */ public void setAnnotationsLoaded(boolean x) { this.annotationsLoaded = x; } /** * Getter method for the current view level. * * @return the current view level. */ public int getCurrentView() { return currentView; } /** * Initialize method for the controller. * * @param location location for relative paths. * @param resources resources to localize the root object. */ @SuppressFBWarnings("URF_UNREAD_FIELD") public final void initialize(URL location, ResourceBundle resources) { } /** * Method to check whether the file containing recently opened files is empty or not. * * @param fileName The name of the most recent file. * @param mostRecent list of most recent files. */ @SuppressFBWarnings public void checkMostRecent(String fileName, Stack<String> mostRecent) { try { File file = new File(MainController.class.getProtectionDomain() .getCodeSource().getLocation().toURI().getPath()); File current = new File(file.getParentFile() + fileName); if (current.exists()) { Scanner sc = new Scanner(current); while (sc.hasNextLine()) { String string = sc.nextLine(); mostRecent.add(string); } sc.close(); } } catch (IOException | URISyntaxException e1) { } } /** * Write a recently chosen NWK file to the file * * @param fileName The name of the most recent file. * @param mostRecent list of most recent files. */ @SuppressFBWarnings public void writeMostRecent(String fileName, Stack<String> mostRecent) { try { File file = new File(MainController.class.getProtectionDomain() .getCodeSource().getLocation().toURI().getPath()); File current = new File(file.getParentFile() + fileName); current.createNewFile(); PrintWriter writer = new PrintWriter(current, "UTF-8"); for (int i = 0; i < mostRecent.size(); i++) { writer.println(mostRecent.get(i)); } writer.close(); } catch (IOException | URISyntaxException e1) { } } /** * Get the list containing most recent GFF files * * @return the list */ public Stack<String> getMostRecentGFF() { return mostRecentGFF; } /** * Get the list containing most recent GFA files * * @return the list */ public Stack<String> getMostRecentGFA() { return mostRecentGFA; } /** * Get the list containing most recent NWK files * * @return the list */ public Stack<String> getMostRecentNWK() { return mostRecentNWK; } /** * Get the list containing the most recenlty visited directory * @return the list */ public Stack<String> getMostRecentDir() { return mostRecentDir; } /** * Add a file to the recent opened GFF files * * @param s the file to be added */ public void addRecentGFF(String s) { if (!mostRecentGFF.contains(s)) { mostRecentGFF.push(s); writeMostRecent("/mostRecentGFF.txt", mostRecentGFF); } } /** * Add a file to the recent opened GFA files * * @param s the file to be added */ public void addRecentGFA(String s) { if (!mostRecentGFA.contains(s)) { mostRecentGFA.push(s); writeMostRecent("/mostRecentGFA.txt", mostRecentGFA); } } /** * Add a file to the recent opened NWK files * * @param s the file to be added */ public void addRecentNWK(String s) { if (!mostRecentNWK.contains(s)) { mostRecentNWK.push(s); writeMostRecent("/mostRecentNWK.txt", mostRecentNWK); } } /** * Add a file to the recently opened directory * @param s the file to be added */ public void addRecentDir(String s) { if (!mostRecentDir.contains(s)) { mostRecentDir.push(s); writeMostRecent("/mostRecentDir.txt", mostRecentDir); } } /** * Method to add items to the GUI */ private void initGUI() { createZoomBoxAndLegend(); WindowFactory.createMenuWithSearch(); MenuFactory.toggleGraphViewMenu(true); toggleSelectDeselect(true); this.getRoot().setCenter(graphController.getRoot()); if (secondCount == -1) { createList(); setListItems(); secondCount++; } this.getRoot().setRight(listVBox); list.setDisable(false); } /** * Method to fill the graph. * * @param ref the reference string. * @param selectedGenomes the genomes to display. */ public void fillGraph(ArrayList<String> ref, List<String> selectedGenomes) { createMenu(true, true); inGraph = true; boolean update = false; // Apply the selected genomes if (showReferenceStrain) { if (!selectedGenomes.contains("MT_H37RV_BRD_V5.ref")) { selectedGenomes.add("MT_H37RV_BRD_V5.ref"); } } else { selectedGenomes.remove("MT_H37RV_BRD_V5.ref"); } if (graphController.getGraph().changeLevelMaps(selectedGenomes)) { currentView = getGraphController().getGraph().getLevelMaps().size() - 1; update = true; } graphController.update(ref, currentView); if (update) { graphController.getZoomBox().fillZoomBox(true); } } /** * Toggle whether the reference strain should be filtered or not */ public void toggleShowReferenceStrain() { this.showReferenceStrain = !this.showReferenceStrain; } /** * If selections are made in the phylogenetic tree, * this method will visualize/highlight them specifically. * * @param ref the references to highlight. * @param s a List of selected strains. */ public void strainSelection(ArrayList<String> ref, List<String> s) { graphController.getGraph().reset(); graphController.getZoomBox().reset(); List<String> ss = graphController.getGraph().reduceGenomes(s); fillGraph(ref, ss); initGUI(); } /** * Create the HBox containing the zoom box and legend. */ private void createZoomBoxAndLegend() { HBox hbox = new HBox(); // Place the legend createLegend(); legend.setAlignment(Pos.CENTER_RIGHT); // Place the zoom box box = graphController.getZoomBox().getZoomBox(); if (firstInitialization) { zoomIndicator = new Label("Zoomlevel: 0%"); firstInitialization = false; } else { zoomIndicator = new Label("Zoomlevel: " + (int) ((graphController.getGraph().getLevelMaps().size() - 1 - (double) currentView) / (double) (graphController.getGraph().getLevelMaps().size() - 1) * 100) + "%"); } DropShadow ds = new DropShadow(); ds.setOffsetY(3.0f); ds.setColor(Color.color(0.4f, 0.4f, 0.4f)); zoomIndicator.setEffect(ds); zoomIndicator.setFont(Font.font(null, FontWeight.BOLD, 32)); zoomIndicator.setAlignment(Pos.TOP_CENTER); hbox.setAlignment(Pos.CENTER); hbox.getChildren().addAll(zoomIndicator, box, legend); this.getRoot().setBottom(hbox); } /** * Method to create the Legend */ private void createLegend() { LegendFactory legendFactory = new LegendFactory(); legend = legendFactory.createLegend(); } /** * Adds an action listener to the genome search and deselect buttons. * * @param buttons The buttons. */ private void setGenomeButtonActionListener(ArrayList<Button> buttons) { buttons.get(0).setOnAction(e -> { if (!genomeTextField.getText().isEmpty() && treeController.getCellByName( genomeTextField.textProperty().get().trim().toUpperCase()) != null) { LeafCell cell = treeController.getCellByName( genomeTextField.textProperty().get().toUpperCase().trim()); treeController.applyCellHighlight(cell); treeController.selectStrain(cell); if (inGraph) { fillTree(); } if (cell != null) { treeController.getRoot().setVvalue(cell.getLayoutY() / treeController.getMaxY()); } } setListItems(); }); buttons.get(1).setOnAction(e -> { showReferenceStrain = false; menuFactory.setShowReferenceStrain(false); treeController.clearSelection(); fillTree(); }); buttons.get(2).setOnAction(e -> { showReferenceStrain = true; menuFactory.setShowReferenceStrain(true); treeController.selectAll(); fillTree(); }); } /** * Adds an action listener to the annotation highlight button. * */ private void setAnnotationButtonsActionListener() { highlightButton.setOnAction(e -> { if (isAnnotationsLoaded()) { String input = annotationTextField.getText(); if (!input.isEmpty()) { annotationTextField.setText(""); if (currentView > 0) { allowNucleotideLevel = true; switchScene(Integer.MIN_VALUE); } initListenerProperties(input); } } }); deselectAnnotationButton.setOnAction(e -> deselectAllAnnotations()); } /** * Method to specify what the Listener needs to do * * @param input The annotation search term. */ public void initListenerProperties(String input) { List<Annotation> annotations = graphController.getGraph().getModel().getAnnotations(); try { Annotation newAnn = AnnotationProcessor.findAnnotation(annotations, input); Map<Integer, Cell> cellMap = graphController.getGraph().getModel().getCellMap(); // Deselect the previously highlighted annotation as only one should be highlighted at a time. deselectAllAnnotations(); if (newAnn.getSpannedNodes() != null && newAnn.getSpannedNodes().size() != 0) { for (Node node : newAnn.getSpannedNodes()) { int id = node.getId(); Node nodeInMap = graphController.getGraph().getLevelMaps().get(0).get(id); if (nodeInMap != null) { graphController.slideToPercent((cellMap.get(id).getLayoutX() - (screen.getWidth() / 4)) / (graphController.getGraph().getModel().getMaxWidth() - 450)); break; } } } for (Node n : newAnn.getSpannedNodes()) { RectangleCell cell = ((RectangleCell) cellMap.get(n.getId())); if (cell != null) { cell.setHighLight(); } } } catch (AnnotationProcessor.TooManyAnnotationsFoundException e1) { WindowFactory.createTooManyAnnAlert(); } catch (AnnotationProcessor.NoAnnotationsFoundException e) { WindowFactory.createAnnNotFoundAlert(); } } /** * Deselects all annotations */ private void deselectAllAnnotations() { if (currentView != 0) { return; } Map<Integer, Node> nodeMap = graphController.getGraph().getModel().getLevelMaps().get(0); Map<Integer, Cell> cellMap = graphController.getGraph().getModel().getCellMap(); nodeMap.values().stream().filter(n -> n.getType().equals(CellType.RECTANGLE)).forEachOrdered(n -> { ((RectangleCell) cellMap.get(n.getId())).deselectHighLight(); }); annotationTextField.setText(""); } /** * Method to create the menu bar. * * @param withSearch Whether to add the search bar. * @param withAnnotationSearch Whether to add the annotation search box to the search bar. */ public void createMenu(boolean withSearch, boolean withAnnotationSearch) { VBox vBox = new VBox(); hBox = new HBox(); genomeTextField = new TextField(); addGenomeKeyHandler(genomeTextField); hBox.getStylesheets().add("/css/main.css"); searchButton = new Button("Search Genome (In Tree)"); selectAllButton = new Button("Select all"); deselectSearchButton = new Button("Deselect All"); ArrayList<Button> buttons = new ArrayList<>(); Collections.addAll(buttons, searchButton, deselectSearchButton, selectAllButton); setGenomeButtonActionListener(buttons); hBox.getChildren().addAll(genomeTextField, searchButton, selectAllButton, deselectSearchButton); // Don't add the annotation search box in the tree view if (withAnnotationSearch) { annotationTextField = new TextField(); addAnnotationKeyHandler(annotationTextField); highlightButton = new Button("Highlight annotation"); deselectAnnotationButton = new Button("Deselect annotation"); setAnnotationButtonsActionListener(); hBox.getChildren().addAll(annotationTextField, highlightButton, deselectAnnotationButton); } if (withSearch) { vBox.getChildren().addAll(menuBar, hBox); } else { menuFactory = new MenuFactory(this); menuBar = menuFactory.createMenu(menuBar); vBox.getChildren().addAll(menuBar); } this.getRoot().setTop(vBox); } /** * Method to add a Key Handler to the annotation TextField * @param textField the annotation TextField */ public void addAnnotationKeyHandler(TextField textField) { textField.setOnKeyPressed(event -> { if (event.getCode().equals(KeyCode.ENTER)) { if (!annotationTextField.getText().isEmpty()) { initListenerProperties(annotationTextField.getText()); } } }); } /** * Method to add a Key Handler to the genome TextField * @param textField the genome TextField */ public void addGenomeKeyHandler(TextField textField) { textField.setOnKeyPressed(event -> { if (event.getCode().equals(KeyCode.ENTER)) { if (!genomeTextField.getText().isEmpty() && treeController.getCellByName( genomeTextField.textProperty().get().trim().toUpperCase()) != null) { LeafCell cell = treeController.getCellByName( genomeTextField.textProperty().get().toUpperCase().trim()); treeController.applyCellHighlight(cell); treeController.selectStrain(cell); if (inGraph) { fillTree(); } if (cell != null) { treeController.getRoot().setVvalue(cell.getLayoutY() / treeController.getMaxY()); } } } }); } /** * Method to enable and disable the select and the select buttons * * @param x boolean indicating enabling or disabling */ public void toggleSelectDeselect(boolean x) { selectAllButton.setDisable(x); deselectSearchButton.setDisable(x); } /** * Method to create the Info-list */ public void createList() { listFactory = new ListFactory(); listVBox = listFactory.createInfoList(""); list = listFactory.getList(); list.setOnMouseClicked(event -> listSelect()); setListItems(); listVBox.getStylesheets().add("/css/list.css"); this.getRoot().setRight(listVBox); } /** * All strains selected to highlight. */ private ArrayList<String> highlights = new ArrayList<>(); /** * Method to perform action upon listItem selection */ public void listSelect() { if (!(list.getSelectionModel().getSelectedItem() == null)) { highlights.clear(); for (Object o : list.getSelectionModel().getSelectedItems()) { highlights.add((String) o); } strainSelection(highlights, getTreeController().getSelectedGenomes()); if (getGraphController().getGraphMouseHandling().getPrevClick() != null) { graphController.focus(getGraphController() .getGraphMouseHandling().getPrevClick().getCellId()); } } } /** * Switches the scene to the graph view. * * @param delta the diff in view to apply. */ public void switchScene(int delta) { currentView += delta; int minLevel = 1; if (allowNucleotideLevel) { minLevel = 0; } currentView = Math.max(minLevel, currentView); currentView = Math.min(graphController.getGraph().getLevelMaps().size() - 1, currentView); fillGraph(graphController.getGraph().getCurrentRef(), graphController.getGraph().getCurrentGenomes()); toggleSelectDeselect(true); zoomIndicator.setText("Zoomlevel: " + (int) ((graphController.getGraph().getLevelMaps().size() - 1 - (double) currentView) / (double) (graphController.getGraph().getLevelMaps().size() - 1) * 100) + "%"); } /** * Method to toggle whether or not the nucleotide level can be reached * through scrolling. */ public void toggleAllowNucleotideLevel() { this.allowNucleotideLevel = !this.allowNucleotideLevel; } /** * Method to fill the phylogenetic tree. */ public void fillTree() { inGraph = false; screen = treeController.getRoot(); setListItems(); if (isAnnotationsLoaded()) { MenuFactory.loadAnnotations.setDisable(true); } toggleSearchBar(true); toggleSelectDeselect(false); MenuFactory.toggleTreeViewMenu(true); list.setDisable(true); this.getRoot().setCenter(screen); this.getRoot().setBottom(null); } /** * Method to enable and disable the search bar * @param x boolean */ private void toggleSearchBar(boolean x) { highlightButton.setDisable(x); deselectAnnotationButton.setDisable(x); annotationTextField.setDisable(x); } /** * Method to add items to the Info-List */ protected void setListItems() { List<String> genomes; if (filtering.isFiltering()) { genomes = graphController.getGraph().reduceGenomeList(filtering.getSelectedGenomes()); } else if (treeController != null && !graphController.getGraph().reduceGenomes(treeController.getSelectedGenomes()).isEmpty()) { genomes = graphController.getGraph().reduceGenomes(treeController.getSelectedGenomes()); } else { genomes = graphController.getGraph().getAllGenomes(); } genomes.sort(Comparator.naturalOrder()); list.setItems(FXCollections.observableArrayList(genomes)); } /** * Getter method for the graphController. * * @return the graphController. */ public GraphController getGraphController() { return graphController; } /** * Getter method for the treeController. * * @return the treeController. */ public TreeController getTreeController() { return treeController; } /** * Getter method for the ListFactory. * * @return the ListFactory. */ public ListFactory getListFactory() { return listFactory; } /** * Method to set the currentView. * * @param currentView the current View. */ public void setCurrentView(int currentView) { this.currentView = currentView; } /** * Modify the filters applied to the tree. * * @param f Filter type. * @param state true or false state. */ public void modifyFilter(Filter f, boolean state) { treeController.getSelectedStrains().forEach(treeController::revertCellHighlight); if (state) { filtering.applyFilter(f); } else { filtering.removeFilter(f); } treeController.clearSelectedStrains(); filtering.getSelectedGenomes().forEach(g -> treeController.addSelectedStrain(treeController.getCellByName(g.getName())) ); if (inGraph) { if (filtering.isFiltering()) { strainSelection(new ArrayList<>(), getLoadedGenomeNames()); } else { fillTree(); } } else { setListItems(); } StringBuilder builder = new StringBuilder(); appendFilterNames(builder); listFactory.modifyNodeInfo(builder.toString()); treeController.colorSelectedStrains(); } /** * Return a list with in the graph loaded genome names. * * @return a list of loaded genome names. */ public List<String> getLoadedGenomeNames() { return graphController.getGraph().reduceGenomeList(filtering.getSelectedGenomes()); } /** * Check whether scene is in graph. * * @return true if in graph, false otherwise. */ public boolean isInGraph() { return inGraph; } /** * Get the names of all applied filters. * * @param builder a builder to append to. */ public void appendFilterNames(StringBuilder builder) { if (filtering.isFiltering()) { builder.append("Applied filters: ").append("\n"); filtering.getFilters().forEach(f -> builder.append(f.getFilterName()).append("\n") ); builder.append("\n"); } } /** * Getter for Filtering. * @return Filtering. */ public Filtering getFiltering() { return filtering; } public ListView getList() { return list; } }
package ar.entity.listener; import ar.entity.Entity; import lombok.extern.java.Log; import org.springframework.data.rest.core.annotation.HandleBeforeCreate; import org.springframework.data.rest.core.annotation.HandleBeforeSave; import org.springframework.data.rest.core.annotation.RepositoryEventHandler; import org.springframework.stereotype.Component; import java.lang.reflect.Field; /** * Handles repository events for any entity. * * @author adam * */ @Component @RepositoryEventHandler(Entity.class) @Log public class EntityEventListener { /** * Triggers before an entity is created. * * @param entity * The entity being created. */ @HandleBeforeCreate public void onBeforeCreate(Entity entity) { trimStrings(entity); } /** * Triggered before an entity is saved. * * @param entity * The entity being saved. */ @HandleBeforeSave public void onBeforeSave(Entity entity) { trimStrings(entity); } /** * Trims all String values in the provided entity. * * @param entity * The entity to trim string values from. */ private void trimStrings(Entity entity) { Class<?> clazz = entity.getClass(); try { while (!clazz.equals(Object.class)) { for (Field field : clazz.getDeclaredFields()) { field.setAccessible(true); Object value = field.get(entity); if (field.getType().equals(String.class) && value != null) { field.set(entity, value.toString().trim()); } } clazz = clazz.getSuperclass(); } } catch (IllegalAccessException e) { log.severe("IllegalAccessException occurred while trimming String value before save for class " + clazz + ": " + e.getLocalizedMessage()); } } }
package asa.service.impl; import asa.service.ConstantsInterface; import asa.service.AttendanceService; //import asa.dao.ScheduleDAO ; import asa.bean.Attendance; //import asa.model.Schedule; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.BeanUtils; import java.util.*; @Service("attendanceService") public class AttendanceServiceMock implements ConstantsInterface,AttendanceService{ public boolean add(Attendance attendance){ return true; } }
package main.java.author.view.tabs; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.text.NumberFormat; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import javax.swing.filechooser.FileNameExtensionFilter; import main.java.author.controller.TabController; import main.java.author.controller.tabbed_controllers.GameSettingsController; import main.java.author.view.global_constants.FontConstants; import main.java.schema.GameSchema; /** * The tab that deals with the Game Settings attributes */ public class GameSettingsEditorTab extends EditorTab{ private JPanel settingsPanel = new JPanel(new GridLayout(0, 1)); private JComboBox gameModeList; private JComboBox gameDifficultyList; private JLabel livesLabel; private JLabel beginningMoneyLabel; private JSpinner livesSpinner; private JSpinner beginningMoneySpinner; private List<JSpinner> spinnerFields; private static final String LIVES_STRING = "Lives: "; private static final String MONEY_STRING = "Beginning Money: "; private static final int LIVES_DEFAULT = 5; private static final int MONEY_DEFAULT = 500; private static final int EASY_DIFFICULTY_VALUE = 1; private static final int MEDIUM_DIFFICULTY_VALUE = 2; private static final int HARD_DIFFICULTY_VALUE = 3; private static final int SURVIVAL_MODE_VALUE = 1; private static final int BOSS_MODE_VALUE = 0; String[] GAME_MODE_STRINGS = {"Survival Mode", "Boss Mode"}; String[] GAME_DIFFICULTY_STRINGS = {"Easy", "Medium", "Hard"}; private NumberFormat numberFormat; private JButton submitButton; private JButton musicButton; private JFileChooser fileChooser; private GameSchema gameSchema; private GameSettingsTabContentCreator contentCreator; /** * @param gameSettingsController * The constructor for the Game Settings Editor Tab */ public GameSettingsEditorTab(TabController gameSettingsController){ super(gameSettingsController); contentCreator = new GameSettingsTabContentCreator(); add(contentCreator.createSettingsPanel(), BorderLayout.CENTER); } @Override public void saveTabData() { GameSettingsController controller = (GameSettingsController) myController; gameSchema = new GameSchema(); gameSchema.addAttribute(GameSchema.LIVES, (Integer) livesSpinner.getValue()); gameSchema.addAttribute(GameSchema.MONEY, (Integer) beginningMoneySpinner.getValue()); if(gameDifficultyList.getSelectedItem().equals("Easy")){ gameSchema.addAttribute(GameSchema.LEVELDIFFICULTY, EASY_DIFFICULTY_VALUE); } else if(gameDifficultyList.getSelectedItem().equals("Medium")){ gameSchema.addAttribute(GameSchema.LEVELDIFFICULTY, MEDIUM_DIFFICULTY_VALUE); } else{ gameSchema.addAttribute(GameSchema.LEVELDIFFICULTY, HARD_DIFFICULTY_VALUE); } if(gameModeList.getSelectedItem().equals("Survival Mode")){ gameSchema.addAttribute(GameSchema.ISSURVIVALMODE, SURVIVAL_MODE_VALUE); } else{ gameSchema.addAttribute(GameSchema.ISSURVIVALMODE, BOSS_MODE_VALUE); } controller.addGameSettings(gameSchema); } /** * Creates the contents of the Pane */ private class GameSettingsTabContentCreator{ /** * Creates the main panel where all of the JComponents that deal with Game Settings attributes go * @return */ private Component createSettingsPanel() { settingsPanel.setLayout(new BorderLayout()); settingsPanel.add(makeDropDownMenus(), BorderLayout.NORTH); settingsPanel.add(makeAttributesPane(), BorderLayout.SOUTH); settingsPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); return settingsPanel; } /** * @return * Specifies the size and font of each JSpinner */ private JSpinner makeAttributeSpinner(){ SpinnerModel model = new SpinnerNumberModel(1, 1, 1000, 1); JSpinner spinner = new JSpinner(model); spinner.setMaximumSize(new Dimension(200, spinner.getHeight())); Font bigFont = spinner.getFont().deriveFont(Font.PLAIN, FontConstants.X_LARGE_FONT_SIZE); spinner.setFont(bigFont); return spinner; } /** * @return * Makes the labels for the attributes that have corresponding JSpinners */ private JComponent makeLabelPane(){ livesLabel = new JLabel(LIVES_STRING); beginningMoneyLabel = new JLabel(MONEY_STRING); JPanel labels = new JPanel(new GridLayout(0, 1)); labels.add(livesLabel); labels.add(beginningMoneyLabel); return labels; } /** * @return * Makes the area where the user can edit attribute fields */ private JComponent makeFieldPane(){ JPanel fields = new JPanel(new GridLayout(0, 1)); livesSpinner = makeAttributeSpinner(); beginningMoneySpinner = makeAttributeSpinner(); livesSpinner.setValue(LIVES_DEFAULT); beginningMoneySpinner.setValue(MONEY_DEFAULT); fields.add(livesSpinner); fields.add(beginningMoneySpinner); return fields; } /** * @return * Makes the drop down menus for game mode and game difficulty */ private JComponent makeDropDownMenus(){ JPanel dropDownMenus = new JPanel(new GridLayout(0, 1)); dropDownMenus.setLayout(new BorderLayout()); gameModeList = new JComboBox(GAME_MODE_STRINGS); gameModeList.setSelectedIndex(1); gameDifficultyList = new JComboBox(GAME_DIFFICULTY_STRINGS); gameDifficultyList.setSelectedIndex(1); dropDownMenus.add(gameModeList, BorderLayout.NORTH); dropDownMenus.add(gameDifficultyList, BorderLayout.SOUTH); return dropDownMenus; } /** * @return * Makes the attributes pane, which holds the labels and fields panes */ private JComponent makeAttributesPane(){ JPanel attributes = new JPanel(new GridLayout(0, 1)); attributes.setLayout(new BorderLayout()); attributes.add(makeLabelPane(), BorderLayout.WEST); attributes.add(makeFieldPane(), BorderLayout.EAST); attributes.add(makeButtons(), BorderLayout.SOUTH); return attributes; } /** * @return * Makes various JButtons */ private JComponent makeButtons(){ JPanel buttons = new JPanel(new GridLayout(0, 1)); musicButton = new JButton("Choose Music"); musicButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub // Get it to open up on the right file menu fileChooser = new JFileChooser("main/resources"); FileNameExtensionFilter filter = new FileNameExtensionFilter("WAV files", "wav"); fileChooser.setFileFilter(filter); int returnVal = fileChooser.showOpenDialog(GameSettingsEditorTab.this); if(returnVal == JFileChooser.APPROVE_OPTION) { File chosenFile = fileChooser.getSelectedFile(); String absolutePath = chosenFile.getAbsolutePath(); try { } catch (Exception e1) { e1.printStackTrace(); } } } }); buttons.add(musicButton, BorderLayout.CENTER); return buttons; } } }
package com.akiban.ais.protobuf; import com.akiban.ais.model.AkibanInformationSchema; import com.akiban.ais.model.CharsetAndCollation; import com.akiban.ais.model.Column; import com.akiban.ais.model.Columnar; import com.akiban.ais.model.DefaultNameGenerator; import com.akiban.ais.model.Group; import com.akiban.ais.model.GroupIndex; import com.akiban.ais.model.GroupTable; import com.akiban.ais.model.Index; import com.akiban.ais.model.IndexColumn; import com.akiban.ais.model.Join; import com.akiban.ais.model.JoinColumn; import com.akiban.ais.model.NameGenerator; import com.akiban.ais.model.Table; import com.akiban.ais.model.TableIndex; import com.akiban.ais.model.TableName; import com.akiban.ais.model.Type; import com.akiban.ais.model.UserTable; import com.akiban.ais.model.View; import com.akiban.server.error.ProtobufReadException; import com.akiban.util.GrowableByteBuffer; import com.google.protobuf.AbstractMessage; import com.google.protobuf.CodedInputStream; import com.google.protobuf.Descriptors; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; public class ProtobufReader { private final AkibanInformationSchema destAIS; private final AISProtobuf.AkibanInformationSchema.Builder pbAISBuilder = AISProtobuf.AkibanInformationSchema.newBuilder(); private final NameGenerator nameGenerator = new DefaultNameGenerator(); public ProtobufReader() { this(new AkibanInformationSchema()); } public ProtobufReader(AkibanInformationSchema destAIS) { this.destAIS = destAIS; } public AkibanInformationSchema getAIS() { return destAIS; } public ProtobufReader loadAIS() { // AIS has two fields (types, schemas) and both are optional AISProtobuf.AkibanInformationSchema pbAIS = pbAISBuilder.clone().build(); loadTypes(pbAIS.getTypesList()); loadSchemas(pbAIS.getSchemasList()); return this; } public ProtobufReader loadBuffer(GrowableByteBuffer buffer) { loadFromBuffer(buffer); return this; } public AkibanInformationSchema loadAndGetAIS(GrowableByteBuffer buffer) { loadBuffer(buffer); loadAIS(); return getAIS(); } private void loadFromBuffer(GrowableByteBuffer buffer) { final String MESSAGE_NAME = AISProtobuf.AkibanInformationSchema.getDescriptor().getFullName(); checkBuffer(buffer); final int serializedSize = buffer.getInt(); final int initialPos = buffer.position(); final int bufferSize = buffer.limit() - initialPos; if(bufferSize < serializedSize) { throw new ProtobufReadException( MESSAGE_NAME, String.format("Required size exceeded actual size: %d vs %d", serializedSize, bufferSize) ); } CodedInputStream codedInput = CodedInputStream.newInstance(buffer.array(), buffer.position(), Math.min(serializedSize, bufferSize)); try { pbAISBuilder.mergeFrom(codedInput); // Successfully consumed, update byte buffer buffer.position(initialPos + serializedSize); } catch(IOException e) { // CodedInputStream really only throws InvalidProtocolBufferException, but declares IOE throw new ProtobufReadException(MESSAGE_NAME, e.getMessage()); } } private void loadTypes(Collection<AISProtobuf.Type> pbTypes) { for(AISProtobuf.Type pbType : pbTypes) { hasRequiredFields(pbType); Type.create( destAIS, pbType.getTypeName(), pbType.getParameters(), pbType.getFixedSize(), pbType.getMaxSizeBytes(), null, null, null ); } } private void loadSchemas(Collection<AISProtobuf.Schema> pbSchemas) { List<List<NewGroupInfo>> allNewGroups = new ArrayList<List<NewGroupInfo>>(); for(AISProtobuf.Schema pbSchema : pbSchemas) { hasRequiredFields(pbSchema); List<NewGroupInfo> newGroups = loadGroups(pbSchema.getSchemaName(), pbSchema.getGroupsList()); allNewGroups.add(newGroups); // Requires no tables, does not load indexes loadTables(pbSchema.getSchemaName(), pbSchema.getTablesList()); loadViews(pbSchema.getSchemaName(), pbSchema.getViewsList()); } // Assume no ordering of schemas or tables, load joins and view refs second for(AISProtobuf.Schema pbSchema : pbSchemas) { loadTableJoins(pbSchema.getSchemaName(), pbSchema.getTablesList()); loadViewReferences(pbSchema.getSchemaName(), pbSchema.getViewsList()); } // Hook up groups, create group tables and indexes after all in place for(List<NewGroupInfo> newGroups : allNewGroups) { createGroupTablesAndIndexes(newGroups); } } private List<NewGroupInfo> loadGroups(String schema, Collection<AISProtobuf.Group> pbGroups) { List<NewGroupInfo> newGroups = new ArrayList<NewGroupInfo>(); for(AISProtobuf.Group pbGroup : pbGroups) { hasRequiredFields(pbGroup); String rootTableName = pbGroup.getRootTableName(); Group group = Group.create(destAIS, nameGenerator.generateGroupName(rootTableName)); String treeName = pbGroup.hasTreeName() ? pbGroup.getTreeName() : null; newGroups.add(new NewGroupInfo(schema, group, pbGroup, treeName)); } return newGroups; } private void createGroupTablesAndIndexes(List<NewGroupInfo> newGroups) { Set<Integer> currentIDs = new HashSet<Integer>(); // Cannot assert ID uniqueness here, no such restriction from proto (e.g. from adapter) for(Table table : destAIS.getUserTables().values()) { currentIDs.add(table.getTableId()); } for(Table table : destAIS.getGroupTables().values()) { currentIDs.add((table.getTableId())); } List<Join> joinsNeedingGroup = new ArrayList<Join>(); for(NewGroupInfo newGroupInfo : newGroups) { String rootTableName = newGroupInfo.pbGroup.getRootTableName(); UserTable rootUserTable = destAIS.getUserTable(newGroupInfo.schema, rootTableName); rootUserTable.setTreeName(newGroupInfo.pbGroup.getTreeName()); rootUserTable.setGroup(newGroupInfo.group); joinsNeedingGroup.addAll(rootUserTable.getCandidateChildJoins()); GroupTable groupTable = GroupTable.create( destAIS, newGroupInfo.schema, nameGenerator.generateGroupTableName(rootTableName), computeNewTableID(currentIDs, rootUserTable.getTableId() + 1) ); newGroupInfo.group.setGroupTable(groupTable); groupTable.setGroup(newGroupInfo.group); groupTable.setTreeName(newGroupInfo.treeName); rootUserTable.setTreeName(newGroupInfo.treeName); } for(int i = 0; i < joinsNeedingGroup.size(); ++i) { Join join = joinsNeedingGroup.get(i); Group group = join.getParent().getGroup(); join.setGroup(group); join.getChild().setGroup(group); join.getChild().setTreeName(join.getParent().getTreeName()); joinsNeedingGroup.addAll(join.getChild().getCandidateChildJoins()); } // Final pass (GI creation requires everything else be completed) for(NewGroupInfo newGroupInfo : newGroups) { loadGroupIndexes(newGroupInfo.group, newGroupInfo.pbGroup.getIndexesList()); } } private void loadTables(String schema, Collection<AISProtobuf.Table> pbTables) { int generatedId = 1; for(AISProtobuf.Table pbTable : pbTables) { hasRequiredFields(pbTable); UserTable userTable = UserTable.create( destAIS, schema, pbTable.getTableName(), pbTable.hasTableId() ? pbTable.getTableId() : generatedId++ ); userTable.setCharsetAndCollation(getCharColl(pbTable.hasCharColl(), pbTable.getCharColl())); if(pbTable.hasVersion()) { userTable.setVersion(pbTable.getVersion()); } loadColumns(userTable, pbTable.getColumnsList()); loadTableIndexes(userTable, pbTable.getIndexesList()); } } private void loadTableJoins(String schema, Collection<AISProtobuf.Table> pbTables) { for(AISProtobuf.Table pbTable : pbTables) { if(pbTable.hasParentTable()) { AISProtobuf.Join pbJoin = pbTable.getParentTable(); hasRequiredFields(pbJoin); AISProtobuf.TableName pbParentName = pbJoin.getParentTable(); hasRequiredFields(pbParentName); UserTable childTable = destAIS.getUserTable(schema, pbTable.getTableName()); UserTable parentTable = destAIS.getUserTable(pbParentName.getSchemaName(), pbParentName.getTableName()); if(parentTable == null) { throw new ProtobufReadException( pbTable.getDescriptorForType().getFullName(), String.format("%s has unknown parentTable %s.%s", childTable.getName(), pbParentName.getSchemaName(), pbParentName.getTableName()) ); } String joinName = parentTable.getName() + "/" + childTable.getName(); Join join = Join.create(destAIS, joinName, parentTable, childTable); for(AISProtobuf.JoinColumn pbJoinColumn : pbJoin.getColumnsList()) { hasRequiredFields(pbJoinColumn); JoinColumn.create( join, parentTable.getColumn(pbJoinColumn.getParentColumn()), childTable.getColumn(pbJoinColumn.getChildColumn()) ); } } } } private void loadViews(String schema, Collection<AISProtobuf.View> pbViews) { for(AISProtobuf.View pbView : pbViews) { hasRequiredFields(pbView); View view = View.create( destAIS, schema, pbView.getViewName(), pbView.getDefinition(), loadProperties(pbView.getDefinitionPropertiesList()), new HashSet<Columnar>() ); loadColumns(view, pbView.getColumnsList()); } } private void loadViewReferences(String schema, Collection<AISProtobuf.View> pbViews) { for(AISProtobuf.View pbView : pbViews) { View view = destAIS.getView(schema, pbView.getViewName()); Collection<Columnar> refs = view.getTableReferences(); for(AISProtobuf.TableName pbReference : pbView.getReferencesList()) { Columnar ref = destAIS.getColumnar(pbReference.getSchemaName(), pbReference.getTableName()); if (ref == null) { throw new ProtobufReadException( pbView.getDescriptorForType().getFullName(), String.format("%s has unknown reference %s.%s", view.getName(), pbReference.getSchemaName(), pbReference.getTableName()) ); } refs.add(ref); } } } private Properties loadProperties(Collection<AISProtobuf.Property> pbProperties) { Properties properties = new Properties(); for(AISProtobuf.Property pbProperty : pbProperties) { hasRequiredFields(pbProperty); properties.put(pbProperty.getKey(), pbProperty.getValue()); } return properties; } private void loadColumns(Columnar columnar, Collection<AISProtobuf.Column> pbColumns) { for(AISProtobuf.Column pbColumn : pbColumns) { hasRequiredFields(pbColumn); Column.create( columnar, pbColumn.getColumnName(), pbColumn.getPosition(), destAIS.getType(pbColumn.getTypeName()), pbColumn.getIsNullable(), pbColumn.hasTypeParam1() ? pbColumn.getTypeParam1() : null, pbColumn.hasTypeParam2() ? pbColumn.getTypeParam2() : null, pbColumn.hasInitAutoInc() ? pbColumn.getInitAutoInc() : null, getCharColl(pbColumn.hasCharColl(), pbColumn.getCharColl()) ); } } private void loadTableIndexes(UserTable userTable, Collection<AISProtobuf.Index> pbIndexes) { for(AISProtobuf.Index pbIndex : pbIndexes) { hasRequiredFields(pbIndex); TableIndex tableIndex = TableIndex.create( destAIS, userTable, pbIndex.getIndexName(), pbIndex.getIndexId(), pbIndex.getIsUnique(), getIndexConstraint(pbIndex) ); if(pbIndex.hasTreeName()) { tableIndex.setTreeName(pbIndex.getTreeName()); } loadIndexColumns(userTable, tableIndex, pbIndex.getColumnsList()); } } private void loadGroupIndexes(Group group, Collection<AISProtobuf.Index> pbIndexes) { for(AISProtobuf.Index pbIndex : pbIndexes) { hasRequiredFieldsGI(pbIndex); GroupIndex groupIndex = GroupIndex.create( destAIS, group, pbIndex.getIndexName(), pbIndex.getIndexId(), pbIndex.getIsUnique(), getIndexConstraint(pbIndex), convertJoinTypeOrNull(pbIndex.hasJoinType(), pbIndex.getJoinType()) ); if(pbIndex.hasTreeName()) { groupIndex.setTreeName(pbIndex.getTreeName()); } loadIndexColumns(null, groupIndex, pbIndex.getColumnsList()); } } private void loadIndexColumns(UserTable table, Index index, Collection<AISProtobuf.IndexColumn> pbIndexColumns) { for(AISProtobuf.IndexColumn pbIndexColumn : pbIndexColumns) { hasRequiredFields(pbIndexColumn); if(pbIndexColumn.hasTableName()) { hasRequiredFields(pbIndexColumn.getTableName()); table = destAIS.getUserTable(convertTableNameOrNull(true, pbIndexColumn.getTableName())); } IndexColumn.create( index, table != null ? table.getColumn(pbIndexColumn.getColumnName()) : null, pbIndexColumn.getPosition(), pbIndexColumn.getIsAscending(), null /* indexedLength not in proto */ ); } } private static String getIndexConstraint(AISProtobuf.Index pbIndex) { if(pbIndex.getIsPK()) { return Index.PRIMARY_KEY_CONSTRAINT; } if(pbIndex.getIsAkFK()) { return Index.FOREIGN_KEY_CONSTRAINT; } if(pbIndex.getIsUnique()) { return Index.UNIQUE_KEY_CONSTRAINT; } return Index.KEY_CONSTRAINT; } private static CharsetAndCollation getCharColl(boolean isValid, AISProtobuf.CharCollation pbCharAndCol) { if(isValid) { hasRequiredFields(pbCharAndCol); return CharsetAndCollation.intern(pbCharAndCol.getCharacterSetName(), pbCharAndCol.getCollationOrderName()); } return null; } private static Index.JoinType convertJoinTypeOrNull(boolean isValid, AISProtobuf.JoinType joinType) { if(isValid) { switch(joinType) { case LEFT_OUTER_JOIN: return Index.JoinType.LEFT; case RIGHT_OUTER_JOIN: return Index.JoinType.RIGHT; } throw new ProtobufReadException(AISProtobuf.JoinType.getDescriptor().getFullName(), "Unsupported join type: " + joinType.name()); } return null; } private static TableName convertTableNameOrNull(boolean isValid, AISProtobuf.TableName tableName) { if(isValid) { hasRequiredFields(tableName); return new TableName(tableName.getSchemaName(), tableName.getTableName()); } return null; } private static int computeNewTableID(Set<Integer> currentIDs, int starting) { while(!currentIDs.add(starting)) { ++starting; } return starting; } /** * Check that a given message instance has all (application) required fields. * By default, this is all declared fields. See overloads for specific types. * @param message Message to check */ private static void hasRequiredFields(AbstractMessage message) { requireAllFieldsExcept(message); } private static void hasRequiredFields(AISProtobuf.Group pbGroup) { requireAllFieldsExcept( pbGroup, AISProtobuf.Group.TREENAME_FIELD_NUMBER, AISProtobuf.Group.INDEXES_FIELD_NUMBER ); } private static void hasRequiredFields(AISProtobuf.Schema pbSchema) { requireAllFieldsExcept( pbSchema, AISProtobuf.Schema.TABLES_FIELD_NUMBER, AISProtobuf.Schema.GROUPS_FIELD_NUMBER, AISProtobuf.Schema.VIEWS_FIELD_NUMBER, AISProtobuf.Schema.CHARCOLL_FIELD_NUMBER ); } private static void hasRequiredFields(AISProtobuf.Table pbTable) { requireAllFieldsExcept( pbTable, AISProtobuf.Table.TABLEID_FIELD_NUMBER, AISProtobuf.Table.ORDINAL_FIELD_NUMBER, AISProtobuf.Table.CHARCOLL_FIELD_NUMBER, AISProtobuf.Table.INDEXES_FIELD_NUMBER, AISProtobuf.Table.PARENTTABLE_FIELD_NUMBER, AISProtobuf.Table.DESCRIPTION_FIELD_NUMBER, AISProtobuf.Table.PROTECTED_FIELD_NUMBER, AISProtobuf.Table.VERSION_FIELD_NUMBER ); } private static void hasRequiredFields(AISProtobuf.View pbView) { requireAllFieldsExcept( pbView, AISProtobuf.View.COLUMNS_FIELD_NUMBER, AISProtobuf.View.DEFINITIONPROPERTIES_FIELD_NUMBER, AISProtobuf.View.REFERENCES_FIELD_NUMBER, AISProtobuf.View.DESCRIPTION_FIELD_NUMBER, AISProtobuf.View.PROTECTED_FIELD_NUMBER ); } private static void hasRequiredFields(AISProtobuf.Column pbColumn) { requireAllFieldsExcept( pbColumn, AISProtobuf.Column.TYPEPARAM1_FIELD_NUMBER, AISProtobuf.Column.TYPEPARAM2_FIELD_NUMBER, AISProtobuf.Column.INITAUTOINC_FIELD_NUMBER, AISProtobuf.Column.CHARCOLL_FIELD_NUMBER, AISProtobuf.Column.DESCRIPTION_FIELD_NUMBER ); } private static void hasRequiredFields(AISProtobuf.Index pbIndex) { requireAllFieldsExcept( pbIndex, AISProtobuf.Index.TREENAME_FIELD_NUMBER, AISProtobuf.Index.DESCRIPTION_FIELD_NUMBER, AISProtobuf.Index.JOINTYPE_FIELD_NUMBER ); } private static void hasRequiredFieldsGI(AISProtobuf.Index pbIndex) { requireAllFieldsExcept( pbIndex, AISProtobuf.Index.TREENAME_FIELD_NUMBER, AISProtobuf.Index.DESCRIPTION_FIELD_NUMBER ); } private static void hasRequiredFields(AISProtobuf.IndexColumn pbIndexColumn) { requireAllFieldsExcept( pbIndexColumn, AISProtobuf.IndexColumn.TABLENAME_FIELD_NUMBER ); } private static void hasRequiredFields(AISProtobuf.Property pbProperty) { requireAllFieldsExcept( pbProperty ); } private static void requireAllFieldsExcept(AbstractMessage message, int... fieldNumbersNotRequired) { Collection<Descriptors.FieldDescriptor> required = new ArrayList<Descriptors.FieldDescriptor>(message.getDescriptorForType().getFields()); Collection<Descriptors.FieldDescriptor> actual = message.getAllFields().keySet(); required.removeAll(actual); if(fieldNumbersNotRequired != null) { for(int fieldNumber : fieldNumbersNotRequired) { required.remove(message.getDescriptorForType().findFieldByNumber(fieldNumber)); } } if(!required.isEmpty()) { Collection<String> names = new ArrayList<String>(required.size()); for(Descriptors.FieldDescriptor desc : required) { names.add(desc.getName()); } throw new ProtobufReadException(message.getDescriptorForType().getFullName(), "Missing required fields: " + names.toString()); } } private static void checkBuffer(GrowableByteBuffer buffer) { assert buffer != null; assert buffer.hasArray() : "Array backed buffer required: " + buffer; } private static class NewGroupInfo { final String schema; final Group group; final AISProtobuf.Group pbGroup; final String treeName; public NewGroupInfo(String schema, Group group, AISProtobuf.Group pbGroup, String treeName) { this.schema = schema; this.group = group; this.pbGroup = pbGroup; this.treeName = treeName; } } }
package com.akiban.server.types3.pvalue; import com.akiban.server.collation.AkCollator; public final class PValue implements PValueSource, PValueTarget { // PValue interface public void underlying(PUnderlying underlying) { this.underlying = underlying; this.state = State.UNSET; } public void unset() { this.state = State.UNSET; } // PValueTarget interface @Override public boolean supportsCachedObjects() { return true; } @Override public final void putNull() { setRawValues(State.NULL, -1, null, null); } @Override public void putBool(boolean value) { setIVal(PUnderlying.BOOL, value ? BOOL_TRUE : BOOL_FALSE); } @Override public final void putInt8(byte value) { setIVal(PUnderlying.INT_8, value); } @Override public final void putInt16(short value) { setIVal(PUnderlying.INT_16, value); } @Override public final void putUInt16(char value) { setIVal(PUnderlying.UINT_16, value); } @Override public final void putInt32(int value) { setIVal(PUnderlying.INT_32, value); } @Override public final void putInt64(long value) { setIVal(PUnderlying.INT_64, value); } @Override public final void putFloat(float value) { setIVal(PUnderlying.FLOAT, Float.floatToIntBits(value)); } @Override public final void putDouble(double value) { setIVal(PUnderlying.DOUBLE, Double.doubleToLongBits(value)); } @Override public final void putBytes(byte[] value) { checkUnderlying(PUnderlying.BYTES); setRawValues(State.VAL_ONLY, -1, value, null); } @Override public void putString(String value, AkCollator collator) { checkUnderlying(PUnderlying.STRING); setRawValues(State.VAL_ONLY, -1, null, value); } @Override public final void putObject(Object object) { if (object == null) putNull(); else setRawValues(State.CACHE_ONLY, -1, null, object); } // PValueSource interface @Override public final boolean isNull() { if (state == State.UNSET) throw new IllegalStateException("state not set"); return state == State.NULL; } @Override public boolean getBoolean() { return getIVal(PUnderlying.BOOL) == BOOL_TRUE; } @Override public boolean getBoolean(boolean defaultValue) { return isNull() ? defaultValue : getBoolean(); } @Override public final byte getInt8() { return (byte) getIVal(PUnderlying.INT_8); } @Override public final short getInt16() { return (short) getIVal(PUnderlying.INT_16); } @Override public final char getUInt16() { return (char) getIVal(PUnderlying.UINT_16); } @Override public final int getInt32() { return (int) getIVal(PUnderlying.INT_32); } @Override public final long getInt64() { return getIVal(PUnderlying.INT_64); } @Override public final float getFloat() { int i = (int) getIVal(PUnderlying.FLOAT); return Float.intBitsToFloat(i); } @Override public final double getDouble() { long l = getIVal(PUnderlying.DOUBLE); return Double.longBitsToDouble(l); } @Override public final byte[] getBytes() { checkUnderlying(PUnderlying.BYTES); internalUpdateRaw(); return bVal; } @Override public String getString() { checkUnderlying(PUnderlying.STRING); return (String) oCache; } @Override public final Object getObject() { switch (state) { case UNSET: throw new IllegalStateException("no value set"); case NULL: return null; case VAL_ONLY: throw new IllegalArgumentException("no cached object set"); // fall through case CACHE_ONLY: case VAL_AND_CACHE: return oCache; default: throw new AssertionError(state); } } @Override public boolean hasAnyValue() { return state != State.UNSET; } @Override public boolean hasRawValue() { return state == State.VAL_ONLY || state == State.VAL_AND_CACHE; } @Override public boolean hasCacheValue() { return state == State.CACHE_ONLY || state == State.VAL_AND_CACHE; } // PValueSource + PValueTarget @Override public PUnderlying getUnderlyingType() { return underlying; } // Object interface @Override public String toString() { StringBuilder sb = new StringBuilder("PValue(").append(underlying).append(" = "); switch (state) { case UNSET: sb.append("<empty>"); break; case NULL: sb.append("NULL"); break; case VAL_ONLY: switch (underlying) { case INT_8: case INT_16: case INT_32: case INT_64: case UINT_16: sb.append(iVal); break; case FLOAT: sb.append(getFloat()); break; case DOUBLE: sb.append(getDouble()); break; case BOOL: sb.append(getBoolean()); break; case STRING: sb.append(getString()); break; case BYTES: sb.append("0x "); for (int i = 0, max= bVal.length; i < max; ++i) { byte b = bVal[i]; int bInt = ((int)b) & 0xFF; if (i > 0 && (i % 2 == 0)) sb.append(' '); sb.append(Integer.toHexString(bInt).toUpperCase()); } break; } break; case CACHE_ONLY: case VAL_AND_CACHE: sb.append("(cached) ").append(oCache); break; } sb.append(')'); return sb.toString(); } private long getIVal(PUnderlying expectedType) { checkUnderlying(expectedType); internalUpdateRaw(); return iVal; } private void internalUpdateRaw() { switch (state) { case UNSET: throw new IllegalStateException("no value set"); case NULL: throw new NullValueException(); case CACHE_ONLY: // TODO assert false : "internalUpdateRaw() not supported yet"; // fall through case VAL_ONLY: case VAL_AND_CACHE: break; default: throw new AssertionError(state); } } private void checkUnderlying(PUnderlying expected) { if (underlying != expected) { String underlyingToString = (underlying == null) ? "unspecified" : underlying.name(); throw new IllegalStateException("required underlying " + expected + " but was " + underlyingToString); } } private void setIVal(PUnderlying expectedType, long value) { checkUnderlying(expectedType); setRawValues(State.VAL_ONLY, value, null, null); } private void setRawValues(State state, long iVal, byte[] bVal, Object oCache) { this.state = state; this.iVal = iVal; this.bVal = bVal; this.oCache = oCache; } public PValue() { this((PUnderlying)null); } public PValue(PUnderlying underlying) { underlying(underlying); } public PValue(long val) { this(PUnderlying.INT_64); putInt64(val); } public PValue(float val) { this(PUnderlying.FLOAT); putFloat(val); } public PValue(double val) { this(PUnderlying.DOUBLE); putDouble(val); } public PValue(int val) { this(PUnderlying.INT_32); putInt32(val); } public PValue(short val) { this(PUnderlying.INT_16); putInt16(val); } public PValue(String val) { this(PUnderlying.STRING); putString(val, null); } public PValue(boolean val) { this(PUnderlying.BOOL); putBool(val); } private PUnderlying underlying; private State state; private long iVal; private byte[] bVal; private Object oCache; private static final long BOOL_TRUE = 1L; private static final long BOOL_FALSE = 0L; private enum State { UNSET, NULL, VAL_ONLY, CACHE_ONLY, VAL_AND_CACHE } }
package com.bigcommerce.api.resources; import java.util.ArrayList; import java.util.List; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.bigcommerce.api.Connection; import com.bigcommerce.api.Filter; import com.bigcommerce.api.Form; import com.bigcommerce.api.Product; /** * Facade for managing a Bigcommerce store Products Resource via the REST API. */ public class Products implements Resource { private Connection connection; /** * A simple constructor that accepts a store url connection. * {@link com.bigcommerce.api.auth.Credentials Credentials}. * * @param connection * */ public Products(Connection connection) { this.connection = connection; } /** * Gets the collection of products. */ @Override public List<Product> listAll() { return this.listAll(null); } /** * Gets the collection of products. */ @Override public List<Product> listAll(Filter filter) { List<Product> products = new ArrayList<Product>(); StringBuffer path = new StringBuffer("/products"); if (filter != null) { path = new StringBuffer(filter.toQuery()); } Element xml = this.connection.get(path.toString()).asXml(); if (xml != null) { NodeList productTags = xml.getElementsByTagName("product"); for (int i = 0; i < productTags.getLength(); i++) { Element productTag = (Element) productTags.item(i); Product product = new Product(productTag); products.add(product); } } return products; } /** * * Gets a product. * * @param productId * @return */ @Override public Product getOne(Integer productId) { Product product = null; StringBuffer path = new StringBuffer("/products/" + productId); Element xml = this.connection.get(path.toString()).asXml(); if (xml != null) { NodeList productTags = xml.getElementsByTagName("product"); Element productTag = (Element) productTags.item(0); product = new Product(productTag); } return product; } @Override public Boolean update(Integer productId, Form data) { StringBuffer path = new StringBuffer("/products/" + productId); Boolean result = this.connection.put(path.toString(), data.toJson()); return result; } }
package com.continuum.nova.chunks; import com.continuum.nova.NovaNative; import com.continuum.nova.utils.DefaultHashMap; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.BlockModelShapes; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.annotation.Nonnull; import javax.swing.text.html.Option; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import static java.util.Optional.of; /** * Splits chunks up into meshes with one mesh for each shader * * @author ddubois * @since 27-Jul-17 */ public class ChunkBuilder { private static final Logger LOG = LogManager.getLogger(ChunkBuilder.class); private final BlockModelShapes modelManager; private World world; private final Map<String, IGeometryFilter> filters; private final AtomicLong timeSpentInBlockRenderUpdate = new AtomicLong(0); private final AtomicInteger numChunksUpdated = new AtomicInteger(0); public ChunkBuilder(Map<String, IGeometryFilter> filters, World world, @Nonnull BlockModelShapes modelManager) { this.filters = filters; this.world = world; this.modelManager = modelManager; } public void createMeshesForChunk(ChunkUpdateListener.BlockUpdateRange range) { LOG.debug("Updating chunk {}", range); Map<String, List<BlockPos>> blocksForFilter = new HashMap<>(); long startTime = System.currentTimeMillis(); for(int x = range.min.x; x <= range.max.x; x++) { for(int y = range.min.y; y < range.max.y; y++) { for(int z = range.min.z; z <= range.max.z; z++) { filterBlockAtPos(blocksForFilter, new BlockPos(x, y, z)); } } } final int chunkHashCode = 31 * range.min.x + range.min.z; Map<String, List<NovaNative.mc_chunk_render_object>> geometriesForFilter = new HashMap<>(); for(String filterName : blocksForFilter.keySet()) { Optional<NovaNative.mc_chunk_render_object> renderObj = makeMeshForBlocks(blocksForFilter.get(filterName), world); renderObj.ifPresent(obj -> { obj.id = chunkHashCode; obj.x = range.min.x; obj.y = range.min.y; obj.z = range.min.z; if(!geometriesForFilter.containsKey(filterName)) { geometriesForFilter.put(filterName, new ArrayList<>()); } geometriesForFilter.get(filterName).add(obj); }); } long timeAfterBuildingStruct = System.currentTimeMillis(); // Using JNA in the old way: 550 ms / chunk for(String filterName : geometriesForFilter.keySet()) { if(!geometriesForFilter.get(filterName).isEmpty()) { for(NovaNative.mc_chunk_render_object obj : geometriesForFilter.get(filterName)) { NovaNative.INSTANCE.add_chunk_geometry_for_filter(filterName, obj); } } } long timeAfterSendingToNative = System.currentTimeMillis(); long deltaTime = System.currentTimeMillis() - startTime; timeSpentInBlockRenderUpdate.addAndGet(deltaTime); numChunksUpdated.incrementAndGet(); if(numChunksUpdated.get() % 10 == 0) { LOG.debug("It's taken an average of {}ms to update {} chunks", (float) timeSpentInBlockRenderUpdate.get() / numChunksUpdated.get(), numChunksUpdated); LOG.debug("Detailed stats:\nTime to build chunk: {}ms\nTime to process chunk in native code: {}ms", timeAfterBuildingStruct - startTime, timeAfterSendingToNative - timeAfterBuildingStruct); } } /** * Adds the block at the given position to the blocksForFilter map under each filter that matches the block * * @param blocksForFilter The map of blocks to potentially add the given block to * @param pos The position of the block to add */ private void filterBlockAtPos(Map<String, List<BlockPos>> blocksForFilter, BlockPos pos) { IBlockState blockState = world.getBlockState(pos); for(Map.Entry<String, IGeometryFilter> entry : filters.entrySet()) { if(entry.getValue().matches(blockState)) { if(!blocksForFilter.containsKey(entry.getKey())) { blocksForFilter.put(entry.getKey(), new ArrayList<>()); } blocksForFilter.get(entry.getKey()).add(pos); } } } private Optional<NovaNative.mc_chunk_render_object> makeMeshForBlocks(List<BlockPos> blockStates, World world) { List<Integer> vertexData = new ArrayList<>(); IndexList indices = new IndexList(); NovaNative.mc_chunk_render_object chunk_render_object = new NovaNative.mc_chunk_render_object(); int blockIndexCounter = 0; for(BlockPos blockPos : blockStates) { IBlockState blockState = world.getBlockState(blockPos); IBakedModel blockModel = modelManager.getModelForState(blockState); List<BakedQuad> quads = new ArrayList<>(); for(EnumFacing facing : EnumFacing.values()) { IBlockState neighbor = blockNextTo(blockPos, world, facing); // Only add faces if the block next to us is transparent and not the same as us if(neighbor.isTranslucent() && !neighbor.getBlock().equals(blockState.getBlock())) { quads.addAll(blockModel.getQuads(blockState, facing, 0)); } } LOG.trace("Retrieved {} faces for BlocKState {}", quads.size(), blockState); int faceIndexCounter = 0; for(BakedQuad quad : quads) { int[] quadVertexData = addPosition(quad, blockPos); for(int data : quadVertexData) { vertexData.add(data); } indices.addIndicesForFace(faceIndexCounter, blockIndexCounter); faceIndexCounter += 4; } blockIndexCounter += faceIndexCounter; } if(vertexData.isEmpty()) { return Optional.empty(); } chunk_render_object.setVertex_data(vertexData); chunk_render_object.setIndices(indices); chunk_render_object.format = NovaNative.NovaVertexFormat.POS_UV_LIGHTMAPUV_NORMAL_TANGENT.ordinal(); return Optional.of(chunk_render_object); } private int[] addPosition(BakedQuad quad, BlockPos blockPos) { int[] data = Arrays.copyOf(quad.getVertexData(), quad.getVertexData().length); float x = Float.intBitsToFloat(data[0]); float y = Float.intBitsToFloat(data[1]); float z = Float.intBitsToFloat(data[2]); x += blockPos.getX(); y += blockPos.getY(); z += blockPos.getZ(); data[0] = Float.floatToIntBits(x); data[1] = Float.floatToIntBits(y); data[2] = Float.floatToIntBits(z); return data; } public void setWorld(World world) { this.world = world; } /** * Returns the IBlockState of the block next to the block at the provided position in the given direction * * @param pos The position to get the block next to * @param world The world that all these blocks are in * @param direction The direction to look in * @return The IBlockState of the block in the provided direction */ private static IBlockState blockNextTo(BlockPos pos, World world, EnumFacing direction) { BlockPos lookupPos = pos.add(direction.getDirectionVec()); return world.getBlockState(lookupPos); } /** * This class only exists to make the code on line 111 work */ private static class IndexCounter { private int index = 0; public void nextFace() { index += 4; } public int getIndex() { return index; } } }
package com.conveyal.r5.streets; import com.conveyal.r5.analyst.PointSet; import com.conveyal.r5.analyst.WebMercatorGridPointSet; import com.conveyal.r5.common.GeometryUtils; import com.conveyal.r5.transit.TransitLayer; import com.conveyal.r5.profile.StreetMode; import com.conveyal.r5.util.LambdaCounter; import com.vividsolutions.jts.geom.*; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TIntIntMap; import gnu.trove.map.hash.TIntIntHashMap; import com.conveyal.r5.streets.EdgeStore.Edge; import gnu.trove.set.TIntSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.conveyal.r5.streets.StreetRouter.State.RoutingVariable; import static com.conveyal.r5.transit.TransitLayer.WALK_DISTANCE_LIMIT_METERS; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.conveyal.r5.streets.VertexStore.FIXED_FACTOR; /** * A LinkedPointSet is a PointSet that has been connected to a StreetLayer in a non-destructive, reversible way. * For each feature in the PointSet, we record the closest edge and the distance to the vertices at the ends of that * edge (like a Splice or a Sample in OTP). */ public class LinkedPointSet implements Serializable { private static final Logger LOG = LoggerFactory.getLogger(LinkedPointSet.class); /** * LinkedPointSets are long-lived and not extremely numerous, so we keep references to the objects it was built * from. Besides these fields are useful for later processing of LinkedPointSets. */ public final PointSet pointSet; /** * We need to retain the street layer so we can look up edge endpoint vertices for the edge IDs. Besides, this * object is inextricably linked to one street network. */ public final StreetLayer streetLayer; /** * The linkage may be different depending on what mode of travel one uses to reach the points from transit stops. * Along with the PointSet and StreetLayer this mode is what determines the contents of a particular * LinkedPointSet. */ public final StreetMode streetMode; static final int BICYCLE_DISTANCE_LINKING_LIMIT_METERS = 2000; static final int CAR_TIME_LINKING_LIMIT_SECONDS = 20 * 60; /** * Limit to use when building linkageCostTables, re-calculated for different streetModes as needed, using the * constants specified above. The value should be larger than any per-leg street mode limits that can be requested * in the UI. */ int linkingDistanceLimitMeters = WALK_DISTANCE_LIMIT_METERS; // Fair to assume that people walk from nearest OSM way to their ultimate destination? Should we just use the // walk speed from the analysis request? static final int OFF_STREET_SPEED_MILLIMETERS_PER_SECOND = (int) 1.3f * 1000; /** * For each point, the closest edge in the street layer. This is in fact the even (forward) edge ID of the closest * edge pairs. */ public int[] edges; /** * For each point, distance from the beginning vertex of the edge geometry up to the split point (closest point on * the edge to the point to be linked), plus the distance from the linked point to the split point */ public int[] distances0_mm; /** * For each point, distance from the end vertex of the edge geometry up to the split point (closest point on the * edge to the point to be linked), plus the distance from the linked point to the split point */ public int[] distances1_mm; // TODO Refactor following three to own class /** For each transit stop, the distances (or times) to nearby PointSet points as packed (point_index, distance) * pairs. */ public List<int[]> stopToPointLinkageCostTables; /** * For each pointset point, the stops reachable without using transit, as a map from StopID to distance. For walk * and bike, distance is in millimeters; for car, distance is actually time in seconds. Inverted version of * stopToPointLinkageCostTables. This is used in PerTargetPropagator to find all the stops near a particular point * (grid cell) so we can perform propagation to that grid cell only. We only retain a few percentiles of travel * time at each target cell, so doing one cell at a time allows us to keep the output size within reason. */ public transient List<TIntIntMap> pointToStopLinkageCostTables; public RoutingVariable linkageCostUnit = RoutingVariable.DISTANCE_MILLIMETERS; /** * A LinkedPointSet is a PointSet that has been pre-connected to a StreetLayer in a non-destructive, reversible way. * These objects are long-lived and not extremely numerous, so we keep references to the objects it was built from. * Besides they are useful for later processing of LinkedPointSets. However once we start evicting * TransportNetworks, we have to make sure we're not holding references to entire StreetLayers in LinkedPointSets * (memory leak). * @param pointSet Points to be linked (e.g. web mercator grid, or eventually centroids) * @param streetLayer Streets to which the points should be linked * @param streetMode Mode by which to connect with and traverse the street network (e.g. from points to stops) * @param baseLinkage Linkage from which linkage costs will be copied, for points not affected by scenarios. If * not null, it should have the same pointSet, streetLayer, and streetMode as the preceding * arguments. */ public LinkedPointSet (PointSet pointSet, StreetLayer streetLayer, StreetMode streetMode, LinkedPointSet baseLinkage) { LOG.info("Linking pointset to street network..."); this.pointSet = pointSet; this.streetLayer = streetLayer; this.streetMode = streetMode; final int nPoints = pointSet.featureCount(); final int nStops = streetLayer.parentNetwork.transitLayer.getStopCount(); // The regions within which we want to link points to edges, then connect transit stops to points. // Null means relink and rebuild everything, but this will be constrained below if a base linkage was supplied. Geometry linkageCostRebuildZone = null; if (baseLinkage != null && ( baseLinkage.pointSet != pointSet || baseLinkage.streetLayer != streetLayer.baseStreetLayer || baseLinkage.streetMode != streetMode)) { LOG.error("Cannot reuse linkage with mismatched characteristics. THIS IS A BUG."); // Relink everything as if no base linkage was supplied. baseLinkage = null; } if (baseLinkage == null) { edges = new int[nPoints]; distances0_mm = new int[nPoints]; distances1_mm = new int[nPoints]; stopToPointLinkageCostTables = new ArrayList<>(); } else { // The caller has supplied an existing linkage for a scenario StreetLayer's base StreetLayer. // We want to re-use most of that that existing linkage to reduce linking time. LOG.info("Linking a subset of points and copying other linkages from an existing base linkage."); LOG.info("The base linkage is for street mode {}", baseLinkage.streetMode); // Copy the supplied base linkage into this new LinkedPointSet. // The new linkage has the same PointSet as the base linkage, so the linkage arrays remain the same length // stopToVertexDistanceTables list might need to grow. edges = Arrays.copyOf(baseLinkage.edges, nPoints); distances0_mm = Arrays.copyOf(baseLinkage.distances0_mm, nPoints); distances1_mm = Arrays.copyOf(baseLinkage.distances1_mm, nPoints); stopToPointLinkageCostTables = new ArrayList<>(baseLinkage.stopToPointLinkageCostTables); // TODO We need to determine which points to re-link and which stops should have their stop-to-point tables re-built. // This should be all the points within the (bird-fly) linking radius of any modified edge. // The stop-to-vertex trees should already be rebuilt elsewhere when applying the scenario. // This should be all the stops within the (network or bird-fly) tree radius of any modified edge, including // And build trees from stops to points. // Even though currently the only changes to the street network are re-splitting edges to connect new // transit stops, we still need to re-link points and rebuild stop trees (both the trees to the vertices // and the trees to the points, because some existing stop-to-vertex trees might not include new splitter // vertices). if (streetMode != StreetMode.WALK) { // limit already set for WALK. } else if (streetMode == StreetMode.BICYCLE) { linkingDistanceLimitMeters = BICYCLE_DISTANCE_LINKING_LIMIT_METERS; } else if (streetMode == StreetMode.CAR) { linkingDistanceLimitMeters = CAR_TIME_LINKING_LIMIT_SECONDS * MAX_CAR_SPEED_METERS_PER_SECOND; } else { throw new UnsupportedOperationException("Unrecognized streetMode"); } linkageCostRebuildZone = streetLayer.scenarioEdgesBoundingGeometry(linkingDistanceLimitMeters); } // If dealing with a scenario, pad out the stop trees list from the base linkage to match the new stop count. // If dealing with a base network linkage, fill the stop trees list entirely with nulls. while (stopToPointLinkageCostTables.size() < nStops) stopToPointLinkageCostTables.add(null); // First, link the points in this PointSet to specific street vertices. // If there is no base linkage, link all points. this.linkPointsToStreets(baseLinkage == null); // Second, make a table of linkage costs (distance or time) from each transit stop to the points in this // PointSet. this.makeStopToPointLinkageCostTables(linkageCostRebuildZone); } /** * Construct a new LinkedPointSet for a grid that falls entirely within an existing grid LinkedPointSet. * * @param sourceLinkage a LinkedPointSet whose PointSet must be a WebMercatorGridPointset * @param subGrid the grid for which to create a linkage */ public LinkedPointSet (LinkedPointSet sourceLinkage, WebMercatorGridPointSet subGrid) { if (!(sourceLinkage.pointSet instanceof WebMercatorGridPointSet)) { throw new IllegalArgumentException("Source linkage must be for a gridded point set."); } WebMercatorGridPointSet superGrid = (WebMercatorGridPointSet) sourceLinkage.pointSet; if (superGrid.zoom != subGrid.zoom) { throw new IllegalArgumentException("Source and sub-grid zoom level do not match."); } if (subGrid.west + subGrid.width < superGrid.west //sub-grid is entirely west of super-grid || superGrid.west + superGrid.width < subGrid.west // super-grid is entirely west of sub-grid || subGrid.north + subGrid.height < superGrid.north //sub-grid is entirely north of super-grid (note Web Mercator conventions) || superGrid.north + superGrid.height < subGrid.north) { //super-grid is entirely north of sub-grid LOG.warn("Sub-grid is entirely outside the super-grid. Points will not be linked to any street edges."); } // Initialize the fields of the new LinkedPointSet instance pointSet = sourceLinkage.pointSet; streetLayer = sourceLinkage.streetLayer; streetMode = sourceLinkage.streetMode; int nCells = subGrid.width * subGrid.height; edges = new int[nCells]; distances0_mm = new int[nCells]; distances1_mm = new int[nCells]; // Copy values over from the source linkage to the new sub-linkage // x, y, and pixel are relative to the new linkage for (int y = 0, pixel = 0; y < subGrid.height; y++) { for (int x = 0; x < subGrid.width; x++, pixel++) { int sourceColumn = subGrid.west + x - superGrid.west; int sourceRow = subGrid.north + y - superGrid.north; if (sourceColumn < 0 || sourceColumn >= superGrid.width || sourceRow < 0 || sourceRow >= superGrid.height) { //point is outside super-grid //Set the edge value to -1 to indicate no linkage. //Distances should never be read downstream, so they don't need to be set here. edges[pixel] = -1; } else { //point is inside super-grid int sourcePixel = sourceRow * superGrid.width + sourceColumn; edges[pixel] = sourceLinkage.edges[sourcePixel]; distances0_mm[pixel] = sourceLinkage.distances0_mm[sourcePixel]; distances1_mm[pixel] = sourceLinkage.distances1_mm[sourcePixel]; } } } stopToPointLinkageCostTables = sourceLinkage.stopToPointLinkageCostTables.stream() .map(distanceTable -> { if (distanceTable == null) return null; // if it was previously unlinked, it is still unlinked TIntList newDistanceTable = new TIntArrayList(); for (int i = 0; i < distanceTable.length; i += 2) { int targetInSuperLinkage = distanceTable[i]; int distance = distanceTable[i + 1]; int superX = targetInSuperLinkage % superGrid.width; int superY = targetInSuperLinkage / superGrid.width; int subX = superX + superGrid.west - subGrid.west; int subY = superY + superGrid.north - subGrid.north; if (subX >= 0 && subX < subGrid.width && subY >= 0 && subY < subGrid.height) { // only retain connections to points that fall within the subGrid int targetInSubLinkage = subY * subGrid.width + subX; newDistanceTable.add(targetInSubLinkage); newDistanceTable.add(distance); // distance to target does not change when we crop the pointset } } if (newDistanceTable.isEmpty()) return null; // not near any points in sub pointset else return newDistanceTable.toArray(); }) .collect(Collectors.toList()); } /** * Associate the points in this PointSet with the street vertices at the ends of the closest street edge. * * @param all If true, link all points, otherwise link only those that were previously connected to edges that have * been deleted (i.e. split). We will need to change this behavior when we allow creating new edges * rather than simply splitting existing ones. */ private void linkPointsToStreets (boolean all) { LambdaCounter counter = new LambdaCounter(LOG, pointSet.featureCount(), 10000, "Linked {} of {} PointSet points to streets."); // Perform linkage calculations in parallel, writing results to the shared parallel arrays. IntStream.range(0, pointSet.featureCount()).parallel().forEach(p -> { // When working with a scenario, skip all points that are not linked to a deleted street (i.e. one that has // been split). At the current time, the only street network modification we support is splitting existing streets, // so the only way a point can need to be relinked is if it is connected to a street which was split (and therefore deleted). // FIXME when we permit street network modifications beyond adding transit stops we will need to change how this works, // we may be able to use some type of flood-fill algorithm in geographic space, expanding the relink envelope until we // hit edges on all sides or reach some predefined maximum. if (all || (streetLayer.edgeStore.temporarilyDeletedEdges != null && streetLayer.edgeStore.temporarilyDeletedEdges.contains(edges[p]))) { // Use radius from StreetLayer such that maximum origin and destination walk distances are symmetric. Split split = streetLayer.findSplit(pointSet.getLat(p), pointSet.getLon(p), StreetLayer.LINK_RADIUS_METERS, streetMode); if (split == null) { edges[p] = -1; } else { edges[p] = split.edge; distances0_mm[p] = split.distance0_mm; distances1_mm[p] = split.distance1_mm; } counter.increment(); } }); long unlinked = Arrays.stream(edges).filter(e -> e == -1).count(); counter.done(); LOG.info("{} points are not linked to the street network.", unlinked); } /** @return the number of linkages, which should be the same as the number of points in the PointSet. */ public int size () { return edges.length; } /** * A functional interface for fetching the travel time to any street vertex in the transport network. Note that * TIntIntMap::get matches this functional interface. There may be a generic IntToIntFunction library interface * somewhere, but this interface provides type information about what the function and its parameters mean. */ @FunctionalInterface public static interface TravelTimeFunction { /** * @param vertexId the index of a vertex in the StreetLayer of a TransitNetwork. * @return the travel time to the given street vertex, or Integer.MAX_VALUE if the vertex is unreachable. */ public int getTravelTime (int vertexId); } @Deprecated public PointSetTimes eval (TravelTimeFunction travelTimeForVertex) { // R5 used to not differentiate between seconds and meters, preserve that behavior in this deprecated function // by using 1 m / s return eval(travelTimeForVertex, 1000); } public PointSetTimes eval (TravelTimeFunction travelTimeForVertex, int offstreetTravelSpeedMillimetersPerSecond) { int[] travelTimes = new int[edges.length]; // Iterate over all locations in this temporary vertex list. EdgeStore.Edge edge = streetLayer.edgeStore.getCursor(); for (int i = 0; i < edges.length; i++) { if (edges[i] < 0) { travelTimes[i] = Integer.MAX_VALUE; continue; } edge.seek(edges[i]); int time0 = travelTimeForVertex.getTravelTime(edge.getFromVertex()); int time1 = travelTimeForVertex.getTravelTime(edge.getToVertex()); // An "off-roading" penalty is applied to limit extending isochrones into water bodies, etc. // We may want to keep the MAX_OFFSTREET_WALK_METERS relatively high to avoid holes in the isochrones, // but make it costly to walk long distances where there aren't streets. The approach below // accomplishes that, applying a penalty to off-street distances greater than the typical grid cell size. // We could use a distance threshold more closely tied to pointset resolution/coverage if (time0 != Integer.MAX_VALUE) { time0 += (distances0_mm[i]) / offstreetTravelSpeedMillimetersPerSecond; } if (time1 != Integer.MAX_VALUE) { time1 += (distances1_mm[i]) / offstreetTravelSpeedMillimetersPerSecond; } travelTimes[i] = time0 < time1 ? time0 : time1; } return new PointSetTimes(pointSet, travelTimes); } /** * Given a table of distances to street vertices from a particular transit stop, create a table of distances to * points in this PointSet from the same transit stop. All points outside the distanceTableZone are skipped as an * optimization. See JavaDoc on the caller makeStopToPointLinkageCostTables - this is one of the slowest parts of * building a network. * * @return A packed array of (pointIndex, distanceMillimeters) */ private int[] extendDistanceTableToPoints (TIntIntMap distanceTableToVertices, Envelope distanceTableZone) { int nPoints = this.size(); TIntIntMap distanceToPoint = new TIntIntHashMap(nPoints, 0.5f, Integer.MAX_VALUE, Integer.MAX_VALUE); Edge edge = streetLayer.edgeStore.getCursor(); TIntSet relevantPoints = pointSet.spatialIndex.query(distanceTableZone); relevantPoints.forEach(p -> { // An edge index of -1 for a particular point indicates that this point is unlinked if (edges[p] == -1) return true; edge.seek(edges[p]); int t1 = Integer.MAX_VALUE, t2 = Integer.MAX_VALUE; // TODO this is not strictly correct when there are turn restrictions onto the edge this is linked to if (distanceTableToVertices.containsKey(edge.getFromVertex())) { t1 = distanceTableToVertices.get(edge.getFromVertex()) + distances0_mm[p]; } if (distanceTableToVertices.containsKey(edge.getToVertex())) { t2 = distanceTableToVertices.get(edge.getToVertex()) + distances1_mm[p]; } int t = Math.min(t1, t2); if (t != Integer.MAX_VALUE) { if (t < distanceToPoint.get(p)) { distanceToPoint.put(p, t); } } return true; // Continue iteration. }); if (distanceToPoint.size() == 0) { return null; } // Convert a packed array of pairs. // TODO don't put in a list and convert to array, just make an array. TIntList packed = new TIntArrayList(distanceToPoint.size() * 2); distanceToPoint.forEachEntry((point, distance) -> { packed.add(point); packed.add(distance); return true; // Continue iteration. }); return packed.toArray(); } /** * For each transit stop in the associated TransportNetwork, make a table of distances to nearby points in this * PointSet. * At one point we experimented with doing the entire search from the transit stops all the way up to the points * within this method. However, that takes too long when switching PointSets. So we pre-cache distances to all * street vertices in the TransitNetwork, and then just extend those tables to the points in the PointSet. * This is one of the slowest steps in working with a new scenario. It takes about 50 seconds to link 400000 points. * The run time is not shocking when you consider the complexity of the operation: there are nStops * nPoints * iterations, which is 8000 * 400000 in the example case. This means 6 msec per transit stop, or 2e-8 sec per point * iteration, which is not horribly slow. There are just too many iterations. * * @param treeRebuildZone only build trees for stops inside this geometry in FIXED POINT DEGREES, leaving all the * others alone. If null, build trees for all stops. */ public void makeStopToPointLinkageCostTables(Geometry treeRebuildZone) { LOG.info("Creating linkage cost tables from each transit stop to PointSet points."); // FIXME this is wasting a lot of memory and not needed for gridded pointsets - overload for gridded and freeform PointSets pointSet.createSpatialIndexAsNeeded(); if (treeRebuildZone != null) { LOG.info("Selectively computing tables for only those stops that might be affected by the scenario."); } TransitLayer transitLayer = streetLayer.parentNetwork.transitLayer; int nStops = transitLayer.getStopCount(); LambdaCounter counter = new LambdaCounter(LOG, nStops, 1000, "Computed distances to PointSet points from {} of {} transit stops."); // Create a distance table from each transit stop to the points in this PointSet in parallel. // When applying a scenario, keep the existing distance table for those stops that could not be affected. stopToPointLinkageCostTables = IntStream.range(0, nStops).parallel().mapToObj(stopIndex -> { Point stopPoint = transitLayer.getJTSPointForStopFixed(stopIndex); // If the stop is not linked to the street network, it should have no distance table. if (stopPoint == null) return null; if (treeRebuildZone != null && !treeRebuildZone.contains(stopPoint)) { // This stop is not affected by the scenario. Return the existing distance table. // all stops outside the relink zone should already have a distance table entry. if (stopIndex >= stopToPointLinkageCostTables.size()) { throw new AssertionError("A stop created by a scenario is located outside relink zone."); } return stopToPointLinkageCostTables.get(stopIndex); } int[] linkageCostToPoints; if (streetMode == StreetMode.WALK) { // Walking distances from stops to street vertices are saved in the transitLayer. // Get the pre-computed distance table from the stop to the street vertices, // then extend that table out from the street vertices to the points in this PointSet. TIntIntMap distanceTableToVertices = transitLayer.stopToVertexDistanceTables.get(stopIndex); // walk! Envelope distanceTableZone = stopPoint.getEnvelopeInternal(); GeometryUtils.expandEnvelopeFixed(distanceTableZone, TransitLayer.WALK_DISTANCE_LIMIT_METERS); linkageCostToPoints = distanceTableToVertices == null ? null : extendDistanceTableToPoints(distanceTableToVertices, distanceTableZone); } else if (streetMode == StreetMode.BICYCLE) { // Biking distances from stops to street vertices are not saved in the transitLayer, so additional // steps are needed compared to Walk. StreetRouter sr = new StreetRouter(transitLayer.parentNetwork.streetLayer); sr.streetMode = StreetMode.BICYCLE; sr.distanceLimitMeters = BICYCLE_DISTANCE_LINKING_LIMIT_METERS; sr.quantityToMinimize = linkageCostUnit; sr.setOrigin(transitLayer.streetVertexForStop.get(stopIndex)); sr.route(); Envelope distanceTableZone = stopPoint.getEnvelopeInternal(); GeometryUtils.expandEnvelopeFixed(distanceTableZone, BICYCLE_DISTANCE_LINKING_LIMIT_METERS); linkageCostToPoints = extendDistanceTableToPoints(sr.getReachedVertices(), distanceTableZone); } else if (streetMode == StreetMode.CAR) { // The speeds for Walk and Bicycle can be specified in an analysis request, so it makes sense above to // store distances and apply the requested speed. In contrast, car speeds vary by link and cannot be // set in analysis requests, so it makes sense to use seconds directly as the linkage cost. linkageCostUnit = StreetRouter.State.RoutingVariable.DURATION_SECONDS; // TODO confirm this works as expected when modifications can affect street layer. StreetRouter sr = new StreetRouter(transitLayer.parentNetwork.streetLayer); sr.streetMode = StreetMode.CAR; sr.timeLimitSeconds = CAR_TIME_LINKING_LIMIT_SECONDS; sr.quantityToMinimize = linkageCostUnit; sr.setOrigin(stopPoint.getY() / FIXED_FACTOR, stopPoint.getX() / FIXED_FACTOR); sr.route(); // TODO limit search radius using envelope, as above. This optimization will require care to avoid // creating a resource-limiting problem. linkageCostToPoints = eval(sr::getTravelTimeToVertex, OFF_STREET_SPEED_MILLIMETERS_PER_SECOND).travelTimes; } else { throw new UnsupportedOperationException("Tried to link a pointset with an unsupported mode"); } counter.increment(); return linkageCostToPoints; }).collect(Collectors.toList()); counter.done(); } // FIXME Method and block inside are both synchronized on "this", is that intentional? See comment in internal block. public synchronized void makePointToStopDistanceTablesIfNeeded () { if (pointToStopLinkageCostTables != null) return; synchronized (this) { // check again in case they were built while waiting on this synchronized block if (pointToStopLinkageCostTables != null) return; if (stopToPointLinkageCostTables == null) makeStopToPointLinkageCostTables(null); TIntIntMap[] result = new TIntIntMap[size()]; for (int stop = 0; stop < stopToPointLinkageCostTables.size(); stop++) { int[] stopToPointDistanceTable = stopToPointLinkageCostTables.get(stop); if (stopToPointDistanceTable == null) continue; for (int idx = 0; idx < stopToPointDistanceTable.length; idx += 2) { int point = stopToPointDistanceTable[idx]; int distance = stopToPointDistanceTable[idx + 1]; if (result[point] == null) result[point] = new TIntIntHashMap(); result[point].put(stop, distance); } } pointToStopLinkageCostTables = Arrays.asList(result); } } }
package com.devtty.neb27k; import java.util.ArrayList; import java.util.List; import javax.ejb.Schedule; import javax.ejb.Singleton; import javax.inject.Inject; import org.apache.commons.lang.StringUtils; import org.onebusaway.gtfs.model.Stop; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import twitter4j.DirectMessage; import twitter4j.Paging; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; /** * * This job checks for (direct) messages from twitter * and tries to answer. * * @author Denis */ @Singleton public class CheckTwitterMessages{ Logger logger = LoggerFactory.getLogger(CheckTwitterMessages.class); @Inject TwitterContentProxy twitterContentProxy; @Inject GtfsData gtfs; @Schedule(minute="*/2", hour="*", persistent=false) public void execute(){ logger.debug("CHECKED MSGs"); try { Twitter twitter = TwitterFactory.getSingleton(); //only DMs recieved after the last response ResponseList<DirectMessage> dms = twitter.getDirectMessages(new Paging(twitter.getSentDirectMessages(new Paging(Constants.PAGING_OFFSET)).get(0).getId())); for(DirectMessage dm : dms){ logger.debug("DM from " + dm.getSenderScreenName() + ": " + dm.getText()); List<Stop> stops = getStopsFromMessage(dm.getText()); String str = respond(stops); if (!str.isEmpty()) { DirectMessage m = twitter.sendDirectMessage(dm.getSenderId(), str); logger.debug("MSG _SEND_ " + str); } } ResponseList<Status> mentions = twitter.getMentionsTimeline(new Paging(twitterContentProxy.getLastTweet())); // give a star when somebody retweets me for(Status mention : mentions){ if(!mention.isFavorited() && !mention.isRetweet()){ twitter.createFavorite(mention.getId()); } logger.debug("Mention from " + mention.getUser().getScreenName()); } } catch (TwitterException ex) { logger.error(ex.getMessage()); } } private List<Stop> getStopsFromMessage(String msg) { logger.debug("STOP MSG: " + msg); List<Stop> stops = new ArrayList<>(); String[] messages = msg.split("\\u0020"); for (String message : messages) { for (Stop stop : gtfs.getStore().getAllStops()) { if (compare(stop.getName(), message)) { logger.debug("CHK TOKEN: " + stop.getName()); stops.add(stop); } } } return stops; } private String respond(List<Stop> stops) { String r = ""; logger.debug("STOP SIZE: " + stops.size()); if(stops.size()==1){ // next departure on this station Vbb vbb = new Vbb(); r = vbb.queryNextServiceAndReturnMessage(stops.get(0).getName()); } else if(stops.size()==2){ // next departure in this direction } return r; } private boolean compare(String stopname, String in) { String diff = StringUtils.difference(in.toLowerCase(), stopname.toLowerCase().replaceAll("^(s\\+u\\s)|(u\\s)|(s\\s)", "")); return diff.equals(", bahnhof") || diff.equals(" (bar, bahnhof)") || diff.equals(" bhf (berlin)"); } }
package com.dragonheart.dijkstra; import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; public class DijkstraGraph { private ArrayList<Edge> listOfEdges; private ArrayList<Point> listOfPoints, sourcePoints; public DijkstraGraph() { this.listOfEdges = new ArrayList<Edge>(); this.listOfPoints = new ArrayList<Point>(); this.sourcePoints = new ArrayList<Point>(); } public void addPoint(Point point) { listOfPoints.add(point); } public void addEdge(Edge edge) { listOfEdges.add(edge); } /** * Add a Point onto the list of sources with a starting cost * @param point is a Point that is the source you want to add * @param cost is a Double with what this source starts at */ public void addSource(Point point, Double cost) { if(listOfPoints.contains(point)) { point.aggregateCost = cost; sourcePoints.add(point); } } /** * Add a list of Points to the list of sources all with the specified starting cost * @param points is a List<Point> containing the points you want to add to your sources * @param cost is a Double with what these sources start at */ public void addSources(List<Point> points, Double cost) { for(Point point : points) { addSource(point, cost); } } /** * Sets your source Points to this Point * @param point is the Point that is the source you want */ public void setSource(Point point) { sourcePoints = new ArrayList<Point>(); addSource(point, point.aggregateCost); } /** * Sets your source Points to this Point and cost * @param point is the Point that is the source you want * @param cost is a Double with what this source starts at */ public void setSource(Point point, Double cost) { sourcePoints = new ArrayList<Point>(); addSource(point, cost); } /** * Sets your source Points to these Points and cost * @param points is a List<Point> containing the points you want to set your sources to * @param cost is a Double with what these sources start at */ public void setSources(List<Point> points, Double cost) { sourcePoints = new ArrayList<Point>(); addSources(points, cost); } private List<Point> getListOfVisitedPoints() { ArrayList<Point> listOfVisitedPoints = new ArrayList<Point>(); for(Point point : listOfPoints) { if(point.isVisited()) { listOfVisitedPoints.add(point); } } return listOfVisitedPoints; } private PriorityQueue<Edge> getConnectedEdges(Point startpoint) { PriorityQueue<Edge> connectedEdges = new PriorityQueue<Edge>(); for(Edge edge : listOfEdges) { Point otherPoint = edge.getOtherPoint(startpoint); if(otherPoint != null && !otherPoint.isVisited()) { connectedEdges.add(edge); } } return connectedEdges; } private Point getNextBestPoint() { Point nextBestPoint = null; for(Point visitedPoint : getListOfVisitedPoints()) { PriorityQueue<Edge> connectedEdges = getConnectedEdges(visitedPoint); while(connectedEdges.size() > 0) { Edge connectedEdge = connectedEdges.remove(); Point otherPoint = connectedEdge.getOtherPoint(visitedPoint); if(otherPoint.aggregateCost == null || (visitedPoint.aggregateCost + connectedEdge.cost) < otherPoint.aggregateCost) { otherPoint.aggregateCost = visitedPoint.aggregateCost + connectedEdge.cost; otherPoint.edgeWithLowestCost = connectedEdge; } if(nextBestPoint == null || otherPoint.aggregateCost < nextBestPoint.aggregateCost) { nextBestPoint = otherPoint; } } } return nextBestPoint; } private void performCalculationForAllPoints() { Point currentPoint = null; do { currentPoint = getNextBestPoint(); currentPoint.setVisited(); } while(Point.TotalVisited < listOfPoints.size()); } /** * processes the whole graph * @return If no sourcePoints return false, otherwise return true */ public boolean processGraph() { if(sourcePoints.isEmpty()) { return false; } for(Point point : listOfPoints) { point.resetVisited(); point.edgeWithLowestCost = null; } Point.TotalVisited = 0; for(Point point : sourcePoints) { point.setVisited(); } for(Point point : listOfPoints) { if(!point.isVisited()) { point.aggregateCost = null; } } performCalculationForAllPoints(); return true; } /** * processes the whole graph while keeping any pre-existing aggregateCosts * @param multiplierforaggregatecosts will be a value that the aggregateCost of all points will be multiplied by * @return If no sourcePoints return false, otherwise return true */ public boolean processGraph(double multiplierforaggregatecosts) { if(sourcePoints.isEmpty()) { return false; } Point.TotalVisited = 0; for(Point point : listOfPoints) { point.edgeWithLowestCost = null; point.resetVisited(); if(sourcePoints.contains(point)) { point.setVisited(); } } for(Point point : listOfPoints) { point.aggregateCost = point.aggregateCost * multiplierforaggregatecosts; } performCalculationForAllPoints(); return true; } /** * Gets the path from the target to the closest source * @param targetpoint is the Point you want the path to go from * @return List<Point> with the path to the closest source */ public List<Point> getPathFrom(Point targetpoint) { ArrayList<Point> shortestPath = new ArrayList<Point>(); if(targetpoint != null) { Point currentPoint = targetpoint; shortestPath.add(currentPoint); while(!sourcePoints.contains(currentPoint)) { if(currentPoint.edgeWithLowestCost != null) { currentPoint = currentPoint.edgeWithLowestCost.getOtherPoint(currentPoint); shortestPath.add(currentPoint); } else { ArrayList<Point> connectedPoints = new ArrayList<Point>(); for(Edge edge : listOfEdges) { Point otherPoint = edge.getOtherPoint(currentPoint); if(otherPoint != null && !shortestPath.contains(otherPoint)) { connectedPoints.add(otherPoint); } } if(connectedPoints.isEmpty()) { break; } Point newPoint = connectedPoints.get(0); connectedPoints.remove(0); for(Point point : connectedPoints) { if(point.aggregateCost < newPoint.aggregateCost) { newPoint = point; } } currentPoint = newPoint; shortestPath.add(currentPoint); } } } return shortestPath; } }
package com.ejlchina.searcher.util; public class StringUtils { public static boolean isBlank(String str) { if (str == null) { return true; } int len = str.length(); if (len == 0) { return true; } for (int i = 0; i < len; i++) { switch (str.charAt(i)) { case ' ': case '\t': case '\n': case '\r': break; default: return false; } } return true; } public static String firstCharToUpperCase(String string) { if (string == null || string.length() == 0) { return string; } char first = string.charAt(0); if (first >= 'a' && first <= 'z') { first = (char) (first - 32); if (string.length() == 1) { return String.valueOf(first); } return first + string.substring(1); } return string; } public static String firstCharToLoweCase(String string) { if (string == null || string.length() == 0) { return string; } char first = string.charAt(0); if (first >= 'A' && first <= 'Z') { first = (char) (first + 32); if (string.length() == 1) { return String.valueOf(first); } return first + string.substring(1); } return string; } /** * src target * @param src * @param from * @param to * @param targets * @return */ public static int containCount(String src, int from, int to, char[] targets) { int count = 0; if (src != null) { from = Math.max(from, 0); to = Math.min(to, src.length()); for (int i = from; i < to; i ++) { char c = src.charAt(i); boolean contained = false; for (char target : targets) { if (c == target) { contained = true; break; } } if (contained) { count++; } } } return count; } public static String[] toUpperCase(String[] ts) { for (int i = 0; i < ts.length; i++) { if (ts[i] != null) { ts[i] = ts[i].toUpperCase(); } } return ts; } }
package com.elastic.support.util; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStream; import java.util.*; public class JsonYamlUtils { private static final Logger logger = LoggerFactory.getLogger(JsonYamlUtils.class); public static JsonNode createJsonNodeFromFileName(String fileName) throws Exception { File jsonFile = FileUtils.getFile(fileName); return createJsonNodeFromFile(jsonFile); } public static JsonNode createJsonNodeFromFileName(String dir, String fileName) throws Exception { File jsonFile = FileUtils.getFile(dir, fileName); return createJsonNodeFromFile(jsonFile); } public static JsonNode createJsonNodeFromFile(File jsonFile) throws Exception { String fileString = FileUtils.readFileToString(jsonFile); return JsonYamlUtils.createJsonNodeFromString(fileString); } public static JsonNode createJsonNodeFromString(String nodeString) throws Exception { ObjectMapper mapper = new ObjectMapper(); return mapper.readTree(nodeString); } public static JsonNode createJsonNodeFromClasspath(String path) throws Exception { InputStream is; is = JsonYamlUtils.class.getClassLoader().getResourceAsStream(path); String nodeString = new String(IOUtils.toByteArray(is)); ObjectMapper mapper = new ObjectMapper(); return mapper.readTree(nodeString); } public static void writeYaml(String path, Map tree) throws Exception { Yaml yaml = new Yaml(); FileWriter writer = new FileWriter(path); yaml.dump(tree, writer); } public static Map<String, Object> readYamlFromClasspath(String path, boolean isBlock) throws Exception { InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path); Map<String, Object> doc = JsonYamlUtils.readYaml(inputStream, isBlock); IOUtils.closeQuietly(inputStream); return doc; } public static Map<String, Object> readYamlFromPath(String path, boolean isBlock) throws Exception { File fl = FileUtils.getFile(path); InputStream inputStream = new FileInputStream(fl); Map<String, Object> doc = JsonYamlUtils.readYaml(inputStream, isBlock); IOUtils.closeQuietly(inputStream); return doc; } public static Map<String, Object> readYaml(InputStream in, boolean isBlock) throws Exception { Map<String, Object> doc = null; try { DumperOptions options = new DumperOptions(); if (isBlock) { options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); } Yaml yaml = new Yaml(options); doc = (Map<String, Object>) yaml.load(in); } catch (Exception e) { logger.error("Error encountered retrieving yml file.", e); } finally { return nullSafeYamlMap(doc); } } public static Map<String, Object> flattenYaml(Map<String, Object> map) { Map<String, Object> result = new LinkedHashMap<>(); buildFlattenedMap(result, map, null); return result; } public static Map<String, Object> flattenMap(Map<String, Object> map){ return flattenYaml(map); } public static Map<String, Object> flattenNode(JsonNode node) throws RuntimeException { try { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> jsonMap = mapper.convertValue(node, Map.class); //String json = mapper.writeValueAsString(node) //Map<String, Object> jsonMap = mapper.readValue(json, new TypeReference<Map<String, Object>>() {}); Map<String, Object> flat = flattenYaml(jsonMap); return flat; } catch (Exception e) { throw new RuntimeException(e); } } public static void buildFlattenedMap(Map<String, Object> result, Map<String, Object> source, String path) { for (Map.Entry<String, Object> entry : source.entrySet()) { String key = entry.getKey(); if (StringUtils.hasText(path)) { if (key.startsWith("[")) { key = path + key; } else { key = path + "." + key; } } Object value = entry.getValue(); if (value instanceof String) { result.put(key, value); } else if (value instanceof Map) { // Need a compound key @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) value; buildFlattenedMap(result, map, key); //} else if (value instanceof List) { // result.put(key, value); } else if (value instanceof Collection) { // Need a compound key @SuppressWarnings("unchecked") Collection<Object> collection = (Collection<Object>) value; int count = 0; for (Object object : collection) { buildFlattenedMap(result, Collections.singletonMap("[" + (count++) + "]", object), key); } } else { result.put(key, value == null ? "" : value); } } } private static Map<String, Object> nullSafeYamlMap(Map<String, Object> doc){ if (doc == null){ doc = new HashMap<String, Object>(); } return doc; } private static Map<String, Object> listToMap(List input){ int sz = input.size(); Map<String, Object> output = new LinkedHashMap<>(); for(int i=0; i < sz; i++){ output.put("idx_" + i, input.get(i)); } return output; } }
package com.elmakers.mine.bukkit.api.wand; import java.util.Collection; import java.util.Map; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.spell.SpellTemplate; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.spell.CostReducer; /** * Represents a Wand that a Mage may use to cast a Spell. * * Every Wand has an inventory of Spell keys and Material brush keys that it may cast and use. * * A Wand may also have a variety of properties, including effects, an XP ("Mana") pool for * casting Spells with an XP-based CastingCost, and various boosts and protections. * * Each Wand is backed by an ItemStack, and the Wand stores its data in the ItemStack. A Wand * is otherwise not tracked or persistent, other than via the Mage.getActiveWand() method, or * via a tracked LostWand record, if the ItemStack can be found. * */ public interface Wand extends CostReducer { public String getName(); public String getId(); public long getWorth(); public void closeInventory(); public void activate(Mage mage); public void deactivate(); public void organizeInventory(Mage mage); public void alphabetizeInventory(); public ItemStack getItem(); public void makeUpgrade(); public Collection<String> getSpells(); public Collection<String> getBrushes(); public void describe(CommandSender sender); public void unenchant(); public void unlock(); public Wand duplicate(); public Spell getSpell(String key); public boolean hasSpell(String key); public boolean hasBrush(String key); public boolean isLocked(); public boolean canUse(Player player); public boolean fill(Player player); public boolean fill(Player player, int maxLevel); public boolean add(Wand other); public boolean add(Wand other, Mage mage); public boolean addItem(ItemStack item); public boolean configure(Map<String, Object> properties); public boolean upgrade(Map<String, Object> properties); public boolean addBrush(String key); public boolean addSpell(String key); public boolean removeBrush(String key); public boolean removeSpell(String key); public String getActiveBrushKey(); public String getActiveSpellKey(); public Spell getActiveSpell(); public void setActiveBrush(String key); public void setActiveSpell(String key); public void setName(String name); public void setDescription(String description); public void setPath(String path); public LostWand makeLost(Location location); public boolean isLost(LostWand wand); public int enchant(int levels); public int enchant(int levels, Mage mage); public int enchant(int levels, Mage mage, boolean addSpells); public Map<String, String> getOverrides(); public void setOverrides(Map<String, String> overrides); public void removeOverride(String key); public void setOverride(String key, String value); public SpellTemplate getBaseSpell(String spellKey); public boolean isSuperProtected(); public boolean isSuperPowered(); public boolean isCostFree(); public boolean isConsumeFree(); public boolean isCooldownFree(); public float getPower(); public float getHealthRegeneration(); public float getHungerRegeneration(); public float getCooldownReduction(); public float getCostReduction(); public float getMana(); public int getManaMax(); public void setMana(float mana); public void setManaMax(int manaMax); public void updateMana(); public WandUpgradePath getPath(); public MageController getController(); public boolean showCastMessages(); public boolean showMessages(); public String getTemplateKey(); public boolean isIndestructible(); public void playEffects(String key); public boolean cast(); public boolean isBound(); public boolean isSoul(); public boolean isUndroppable(); public boolean isQuickCastDisabled(); public boolean isInventoryOpen(); public void damageDealt(double damage, Entity target); public int getSpellLevel(String spellKey); public boolean hasTag(String tag); /** * Save this Wand to a Configuartion Section. * * @param section * @param filtered If true, removes item-specific data such as Wand * id and bound owner. */ public void save(ConfigurationSection section, boolean filtered); /** * Save current Wand state to the ItemStack's NBT data immediately. * * Wands are saved periodically so this is generally not needed unless * you need to force an update right away. */ public void saveState(); }
package com.enderio.core.common; import com.enderio.core.api.common.util.IProgressTile; import com.enderio.core.common.config.ConfigHandler; import com.enderio.core.common.network.EnderPacketHandler; import com.enderio.core.common.network.PacketProgress; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ITickable; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public abstract class TileEntityBase extends TileEntity implements ITickable { private final int checkOffset = (int) (Math.random() * 20); protected final boolean isProgressTile; protected int lastProgressScaled = -1; protected int ticksSinceLastProgressUpdate; private long lastUpdate = 0; public TileEntityBase() { isProgressTile = this instanceof IProgressTile; } @Override public final void update() { if (isInvalid() || !worldObj.isBlockLoaded(getPos()) || worldObj.getTileEntity(getPos()) != this) { // we can get ticked after being removed from the world, ignore this return; } if (ConfigHandler.allowExternalTickSpeedup || worldObj.getTotalWorldTime() != lastUpdate) { lastUpdate = worldObj.getTotalWorldTime(); doUpdate(); if (isProgressTile && !worldObj.isRemote) { int curScaled = getProgressScaled(16); if (++ticksSinceLastProgressUpdate >= getProgressUpdateFreq() || curScaled != lastProgressScaled) { sendTaskProgressPacket(); lastProgressScaled = curScaled; } } } } public static int getProgressScaled(int scale, IProgressTile tile) { return (int) (tile.getProgress() * scale); } public final int getProgressScaled(int scale) { if (isProgressTile) { return getProgressScaled(scale, (IProgressTile) this); } return 0; } protected void doUpdate() { } protected void sendTaskProgressPacket() { if (isProgressTile) { EnderPacketHandler.sendToAllAround(new PacketProgress((IProgressTile) this), this); } ticksSinceLastProgressUpdate = 0; } /** * Controls how often progress updates. Has no effect if your TE is not {@link IProgressTile}. */ protected int getProgressUpdateFreq() { return 20; } @Override public final void readFromNBT(NBTTagCompound root) { super.readFromNBT(root); readCustomNBT(root); } @Override public final NBTTagCompound writeToNBT(NBTTagCompound root) { super.writeToNBT(root); writeCustomNBT(root); return root; } @Override public NBTTagCompound getUpdateTag() { NBTTagCompound tag = new NBTTagCompound(); writeCustomNBT(tag); return tag; } @Override public SPacketUpdateTileEntity getUpdatePacket() { NBTTagCompound tag = new NBTTagCompound(); writeCustomNBT(tag); return new SPacketUpdateTileEntity(getPos(), 1, tag); } @Override public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) { readCustomNBT(pkt.getNbtCompound()); } public boolean canPlayerAccess(EntityPlayer player) { return !isInvalid() && player.getDistanceSqToCenter(getPos().add(0.5, 0.5, 0.5)) <= 64D; } protected abstract void writeCustomNBT(NBTTagCompound root); protected abstract void readCustomNBT(NBTTagCompound root); protected void updateBlock() { if (worldObj != null) { IBlockState bs = worldObj.getBlockState(getPos()); worldObj.notifyBlockUpdate(pos, bs, bs, 3); } } protected boolean isPoweredRedstone() { return worldObj.isBlockLoaded(getPos()) ? worldObj.isBlockIndirectlyGettingPowered(getPos()) > 0 : false; } /** * Called directly after the TE is constructed. This is the place to call non-final methods. * * Note: This will not be called when the TE is loaded from the save. Hook into the nbt methods for that. */ public void init() { } /** * Call this with an interval (in ticks) to find out if the current tick is the one you want to do some work. This is staggered so the work of different TEs * is stretched out over time. * * @see #shouldDoWorkThisTick(int, int) If you need to offset work ticks */ protected boolean shouldDoWorkThisTick(int interval) { return shouldDoWorkThisTick(interval, 0); } /** * Call this with an interval (in ticks) to find out if the current tick is the one you want to do some work. This is staggered so the work of different TEs * is stretched out over time. * * If you have different work items in your TE, use this variant to stagger your work. */ protected boolean shouldDoWorkThisTick(int interval, int offset) { return (worldObj.getTotalWorldTime() + checkOffset + offset) % interval == 0; } @Override public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate) { return oldState.getBlock() != newSate.getBlock(); } /** * Called server-side when a GhostSlot is changed. Check that the given slot number really is a ghost slot before storing the given stack. * * @param slot * The slot number that was given to the ghost slot * @param stack * The stack that should be placed, null to clear */ public void setGhostSlotContents(int slot, ItemStack stack) { } @Override public void markDirty() { if (worldObj != null) { worldObj.markChunkDirty(pos, this); IBlockState state = worldObj.getBlockState(pos); if (state.hasComparatorInputOverride()) { worldObj.updateComparatorOutputLevel(pos, state.getBlock()); } } } }
package com.evapps.Controller; import com.evapps.Entity.History; import com.evapps.Entity.Product; import com.evapps.Entity.User; import com.evapps.Service.CRUD.CreateDataService; import com.evapps.Service.CRUD.ReadDataService; import com.evapps.Service.CRUD.UpdateDataService; import com.evapps.Tools.Enums.Permission; import org.springframework.beans.factory.HierarchicalBeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.websocket.server.PathParam; import java.util.Set; @Controller public class AccessController { // Services @Autowired private CreateDataService CDS; @Autowired private ReadDataService RDS; @Autowired private UpdateDataService UDS; // Gets @GetMapping("/login") public ModelAndView fetchLoginView(){ if(RDS.isUserLoggedIn()) // There is no need to log in if already logged in return new ModelAndView("redirect:/"); return new ModelAndView("/Backend/users/login_register"); } @GetMapping("/profile") public ModelAndView viewProfile(Model model){ if(!RDS.isUserLoggedIn()) return new ModelAndView("redirect:/login"); model.addAttribute("user", RDS.findRegisteredUserAccount(RDS.getCurrentLoggedUser().getEmail())); return new ModelAndView(""); } @GetMapping("/myHistory") public ModelAndView viewHistory(Model model){ if(!RDS.isUserLoggedIn()) return new ModelAndView("redirect:/login"); model.addAttribute("browsingHistory", RDS.findRegisteredUserHistory(RDS.getCurrentLoggedUser().getEmail()).getBrowsingHistory()); model.addAttribute("shoppingCart", RDS.findRegisteredUserHistory(RDS.getCurrentLoggedUser().getEmail()).getShoppingCart()); model.addAttribute("transactions", RDS.findRegisteredUserTransactions(RDS.getCurrentLoggedUser().getEmail())); return new ModelAndView(""); } @GetMapping("/transaction/{fiscalCode}") public ModelAndView viewTransaction(Model model, @PathVariable("fiscalCode") String fiscalCode){ if(!RDS.isUserLoggedIn()) return new ModelAndView("redirect:/login"); model.addAttribute("transaction", RDS.findRegisteredTransaction(fiscalCode)); return new ModelAndView(""); } // Post @PostMapping("/userLogin") public String loginUser(@RequestParam("email") String email, @RequestParam("password") String password, @RequestParam("origin") String origin){ if(RDS.isUserLoggedIn()) // There is no need to log in if already logged in return "redirect:/"; if (RDS.findRegisteredUserAccount(email.toLowerCase(), password)) { User u = RDS.findRegisteredUserAccount(email.toLowerCase()); RDS.setSessionAttr("user",u); return "redirect:" + origin; } else return "redirect:/login"; // TODO: Implement error exception or message to login } @PostMapping("/register") public String register(@RequestParam("email") String email, @RequestParam("first") String firstName, @RequestParam("last") String lastName, @RequestParam("address") String shippingAddress, @RequestParam("password") String password, @RequestParam("confirm") String confirmPassword, @RequestParam("type") Permission role){ if(RDS.isUserLoggedIn()) // There is no need to log in if already logged in return "redirect:/"; if (!password.equals(confirmPassword)) return "redirect:/register_page"; // TODO: Add error message try { CDS.registerNewUser(email.toLowerCase(), firstName.toLowerCase(), lastName.toUpperCase(), shippingAddress, password, role); return "redirect:/login_page"; } catch (Exception exp){ } return "redirect:/register_page"; // TODO: Add error message } @PostMapping("/user/change_password") public String changePassword(@RequestParam("old") String oldPassword, @RequestParam("new") String newPassword, @RequestParam("confirm") String confirmPassword){ if(!RDS.isUserLoggedIn()) return "redirect:/login"; if (!RDS.findRegisteredUserAccount(RDS.getCurrentLoggedUser().getEmail(), oldPassword)) return "redirect:/profile"; // TODO: Add error message if (oldPassword.equals(newPassword)) return "redirect:/profile"; // TODO: Add error message if (!newPassword.equals(confirmPassword)) return "redirect:/profile"; // TODO: Add error message try { User user = RDS.findRegisteredUserAccount(RDS.getCurrentLoggedUser().getEmail()); user.setPassword(newPassword); UDS.updateRegisteredUserAccount(user); return "redirect:/profile"; } catch (Exception exp){ } return "redirect:/profile"; // TODO: Add error message } @RequestMapping("/logout") public ModelAndView logOut(){ if (!RDS.isUserLoggedIn()) return new ModelAndView("redirect:/login"); RDS.logOut(); return new ModelAndView("redirect:/"); } @PostMapping("/logout") public ModelAndView logOut2(@RequestParam("origin") String origin){ if (!RDS.isUserLoggedIn()) return new ModelAndView("redirect:/login"); RDS.logOut(); return new ModelAndView("redirect:/"); } // TODO: Add edit posts and Upload Photo @PostMapping("/remove/{productId}") public String removeFromCart(@PathParam("productId") Integer productId){ if (!RDS.isUserLoggedIn()) return "redirect:/login"; try { History history = RDS.findRegisteredUserHistory(RDS.getCurrentLoggedUser().getEmail()); Set<Product> shoppingCart = history.getShoppingCart(); Product product = RDS.findRegisteredProduct(productId); shoppingCart.remove(product); history.setShoppingCart(shoppingCart); UDS.updareRegisteredUserHistory(history); return "redirect:/myHistory"; } catch (Exception exp){ } return "redirect:/myHistory"; // TODO: Add error message } // TODO: ClearCart // TODO: CancelTransaction // TODO: MarkTransactionAsReceived // TODO: PrintTransaction }
package com.gimranov.zandy.app.data; import java.util.ArrayList; import java.util.UUID; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.database.Cursor; import android.util.Log; import com.gimranov.zandy.app.task.APIRequest; public class Attachment { public String key; public String parentKey; public String etag; public int status; public String dbId; public String title; public String filename; public String url; /** * Queue of attachments that need to be synced, because they're dirty */ public static ArrayList<Attachment> queue; /** * APIRequest.API_DIRTY means that we'll try to push this version up to the server */ public String dirty; /** * Zotero's JSON format for attachment / child information * * linkMode: O = file attachment, in ZFS? * 1 = link attachment? */ public JSONObject content; private static final String TAG = "com.gimranov.zandy.app.data.Attachment"; public static final int AVAILABLE = 1; public static final int LOCAL = 2; public static final int UNKNOWN = 3; /* linkMode statuses from the Zotero client code this.LINK_MODE_IMPORTED_FILE = 0; this.LINK_MODE_IMPORTED_URL = 1; this.LINK_MODE_LINKED_FILE = 2; this.LINK_MODE_LINKED_URL = 3; */ public static final int MODE_LINKED_URL = 3; public static final int MODE_LINKED_FILE = 2; public static final int MODE_IMPORTED_URL = 1; public static final int MODE_IMPORTED_FILE = 0; public Attachment () { if (queue == null) queue = new ArrayList<Attachment>(); parentKey = title = filename = url = etag = dirty = ""; status = UNKNOWN; content = new JSONObject(); } public Attachment(Context c, String type, String parentKey) { this(); content = new JSONObject(); try { content.put("itemType", type); } catch (JSONException e) { Log.d(TAG,"JSON exception caught setting itemType in Attachment constructor", e); } key = UUID.randomUUID().toString(); this.parentKey = parentKey; dirty = APIRequest.API_NEW; } public String getType () { String type = ""; try { type = content.getString("itemType"); if (type.equals("attachment")) { if (content.has("mimeType")) { type = content.getString("mimeType"); } else if (content.has("contentType")) { type = content.getString("contentType"); } } if (type.equals("note")) type = "note"; } catch (JSONException e) { Log.e(TAG, "JSON exception parsing attachment content: "+ content.toString(), e); } return type; } public void setNoteText (String text) { try { content.put("note", text); } catch (JSONException e) { Log.e(TAG, "JSON exception setting note text",e); } } public void save(Database db) { Attachment existing = load(key, db); if (dbId == null && existing == null) { Log.d(TAG, "Saving new, with status: "+status); String[] args = { key, parentKey, title, filename, url, Integer.toString(status), etag, dirty, content.toString() }; Cursor cur = db .rawQuery( "insert into attachments (attachment_key, item_key, title, filename, url, status, etag, dirty, content) " + "values (?, ?, ?, ?, ?, ?, ?, ?, ?)", args); if (cur != null) cur.close(); Attachment fromDB = load(key, db); dbId = fromDB.dbId; } else { Log.d(TAG, "Updating attachment, with status: "+status+" and fn: "+filename); if (dbId == null) dbId = existing.dbId; String[] args = { key, parentKey, title, filename, url, Integer.toString(status), etag, dirty, content.toString(), dbId }; Cursor cur = db .rawQuery( "update attachments set attachment_key=?, item_key=?, title=?," + " filename=?, url=?, status=?, etag=?, dirty=?, " + " content=? " + " where _id=?", args); if (cur != null) cur.close(); } db.close(); } /** * Deletes an attachment from the database, keeping a record of it in the deleteditems table * We will then send out delete requests via the API to propagate the deletion */ public void delete(Database db) { String[] args = { dbId }; db.rawQuery("delete from attachments where _id=?", args); // Don't prepare deletion requests for unsynced new attachments if (!APIRequest.API_NEW.equals(dirty)) { String[] args2 = { key, etag }; db.rawQuery("insert into deleteditems (item_key, etag) values (?, ?)", args2); } } /** * Identifies dirty items in the database and queues them for syncing */ public static void queue(Database db) { if (queue == null) { // Initialize the queue if necessary queue = new ArrayList<Attachment>(); } Log.d(TAG, "Clearing attachment dirty queue before repopulation"); queue.clear(); Attachment attachment; String[] cols = Database.ATTCOLS; String[] args = { APIRequest.API_CLEAN }; Cursor cur = db.query("attachments", cols, "dirty != ?", args, null, null, null, null); if (cur == null) { Log.d(TAG, "No dirty attachments found in database"); queue.clear(); return; } do { Log.d(TAG, "Adding attachment to dirty queue"); attachment = load(cur); queue.add(attachment); } while (cur.moveToNext() != false); if (cur != null) cur.close(); } /** * Get an Attachment from the current cursor position. * * Does not close cursor. * * @param cur * @return */ public static Attachment load(Cursor cur) { if (cur == null) return null; Attachment a = new Attachment(); a.dbId = cur.getString(0); a.key = cur.getString(1); a.parentKey = cur.getString(2); a.title = cur.getString(3); a.filename = cur.getString(4); a.url = cur.getString(5); try { a.status = cur.getInt(6); } catch (Exception e) { a.status = UNKNOWN; } a.etag = cur.getString(7); a.dirty = cur.getString(8); try { a.content = new JSONObject(cur.getString(9)); } catch (JSONException e) { Log.e(TAG, "Caught JSON exception loading attachment from db", e); } return a; } public static Attachment load(String key, Database db) { String[] cols = Database.ATTCOLS; String[] args = { key }; Cursor cur = db.query("attachments", cols, "attachment_key=?", args, null, null, null, null); Attachment a = load(cur); if (cur != null) cur.close(); return a; } /** * Provides ArrayList of Attachments for a given Item * Useful for powering UI * * We can also use this to trigger background syncs * * @param item * @return */ public static ArrayList<Attachment> forItem(Item item, Database db) { ArrayList<Attachment> list = new ArrayList<Attachment>(); if (item.dbId == null) item.save(db); Log.d(TAG, "Looking for the kids of an item with key: "+item.getKey()); String[] cols = { "_id", "attachment_key", "item_key", "title", "filename", "url", "status", "etag", "dirty", "content" }; String[] args = { item.getKey() }; Cursor cursor = db.query("attachments", cols, "item_key=?", args, null, null, null, null); if (cursor != null) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { Attachment a = Attachment.load(cursor); list.add(a); cursor.moveToNext(); } cursor.close(); } else { Log.d(TAG,"Cursor was null, so we still didn't get attachments for the item!"); } return list; } }
package com.github.anba.es6draft.parser; import static com.github.anba.es6draft.semantics.StaticSemantics.*; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import java.util.*; import com.github.anba.es6draft.ast.AbruptNode.Abrupt; import com.github.anba.es6draft.ast.*; import com.github.anba.es6draft.ast.MethodDefinition.MethodType; import com.github.anba.es6draft.parser.ParserException.ExceptionType; import com.github.anba.es6draft.runtime.internal.CompatibilityOption; import com.github.anba.es6draft.runtime.internal.Messages; import com.github.anba.es6draft.runtime.internal.SmallArrayList; import com.github.anba.es6draft.runtime.objects.FunctionPrototype; /** * Parser for ECMAScript6 source code * <ul> * <li>12 ECMAScript Language: Expressions * <li>13 ECMAScript Language: Statements and Declarations * <li>14 ECMAScript Language: Functions and Classes * <li>15 ECMAScript Language: Scripts and Modules * </ul> */ public class Parser { private static final boolean MODULES_ENABLED = false; private static final boolean DEBUG = false; private static final int MAX_ARGUMENTS = FunctionPrototype.getMaxArguments(); private static final List<Binding> NO_INHERITED_BINDING = Collections.emptyList(); private static final Set<String> EMPTY_LABEL_SET = Collections.emptySet(); private final String sourceFile; private final int sourceLine; private final EnumSet<Option> options; private TokenStream ts; private ParseContext context; private enum StrictMode { Unknown, Strict, NonStrict } private enum StatementType { Iteration, Breakable, Statement } private enum ContextKind { Script, Module, Function, Generator, ArrowFunction, Method } private static class ParseContext { final ParseContext parent; final ContextKind kind; boolean superReference = false; boolean yieldAllowed = false; boolean returnAllowed = false; StrictMode strictMode = StrictMode.Unknown; boolean explicitStrict = false; ParserException strictError = null; List<FunctionNode> deferred = null; ArrayDeque<ObjectLiteral> objectLiterals = null; Map<String, LabelContext> labelSet = null; LabelContext labels = null; ScopeContext scopeContext; final FunctionContext funContext; ParseContext() { this.parent = null; this.kind = null; this.funContext = null; } ParseContext(ParseContext parent, ContextKind kind) { this.parent = parent; this.kind = kind; this.funContext = new FunctionContext(this); this.scopeContext = funContext; this.returnAllowed = isFunction(); if (parent.strictMode == StrictMode.Strict) { this.strictMode = parent.strictMode; } } ParseContext findSuperContext() { ParseContext cx = this; while (cx.kind == ContextKind.ArrowFunction) { cx = cx.parent; } return cx; } void setReferencesSuper() { superReference = true; } boolean hasSuperReference() { return superReference; } final boolean isFunction() { switch (kind) { case ArrowFunction: case Function: case Generator: case Method: return true; case Module: case Script: default: return false; } } int countLiterals() { return (objectLiterals != null ? objectLiterals.size() : 0); } void addLiteral(ObjectLiteral object) { if (objectLiterals == null) { objectLiterals = new ArrayDeque<>(4); } objectLiterals.push(object); } void removeLiteral(ObjectLiteral object) { objectLiterals.removeFirstOccurrence(object); } } // TODO: rename - not used exclusively for functions, also used for scripts and modules private static class FunctionContext extends ScopeContext implements FunctionScope { final ScopeContext enclosing; HashSet<String> parameterNames = null; boolean directEval = false; FunctionContext(ParseContext context) { super(null); this.enclosing = context.parent.scopeContext; } private boolean isStrict() { if (node instanceof FunctionNode) { return IsStrict((FunctionNode) node); } else { assert node instanceof Script; return IsStrict((Script) node); } } @Override public ScopeContext getEnclosingScope() { return enclosing; } @Override public boolean isDynamic() { return directEval && !isStrict(); } @Override public Set<String> parameterNames() { return parameterNames; } @Override public Set<String> lexicallyDeclaredNames() { return lexDeclaredNames; } @Override public List<Declaration> lexicallyScopedDeclarations() { return lexScopedDeclarations; } @Override public Set<String> varDeclaredNames() { return varDeclaredNames; } @Override public List<StatementListItem> varScopedDeclarations() { return varScopedDeclarations; } } private static class BlockContext extends ScopeContext implements BlockScope { final boolean dynamic; BlockContext(ScopeContext parent, boolean dynamic) { super(parent); this.dynamic = dynamic; } @Override public Set<String> lexicallyDeclaredNames() { return lexDeclaredNames; } @Override public List<Declaration> lexicallyScopedDeclarations() { return lexScopedDeclarations; } @Override public boolean isDynamic() { return dynamic; } } private abstract static class ScopeContext implements Scope { final ScopeContext parent; ScopedNode node = null; HashSet<String> varDeclaredNames = null; HashSet<String> lexDeclaredNames = null; List<StatementListItem> varScopedDeclarations = null; List<Declaration> lexScopedDeclarations = null; ScopeContext(ScopeContext parent) { this.parent = parent; } @Override public Scope getParent() { return parent; } @Override public ScopedNode getNode() { return node; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("var: ").append(varDeclaredNames != null ? varDeclaredNames : "<null>"); sb.append("\t"); sb.append("lex: ").append(lexDeclaredNames != null ? lexDeclaredNames : "<null>"); return sb.toString(); } boolean isTopLevel() { return (parent == null); } boolean addVarDeclaredName(String name) { if (varDeclaredNames == null) { varDeclaredNames = new HashSet<>(); } varDeclaredNames.add(name); return (lexDeclaredNames == null || !lexDeclaredNames.contains(name)); } boolean addLexDeclaredName(String name) { if (lexDeclaredNames == null) { lexDeclaredNames = new HashSet<>(); } return lexDeclaredNames.add(name) && (varDeclaredNames == null || !varDeclaredNames.contains(name)); } void addVarScopedDeclaration(StatementListItem decl) { if (varScopedDeclarations == null) { varScopedDeclarations = newSmallList(); } varScopedDeclarations.add(decl); } void addLexScopedDeclaration(Declaration decl) { if (lexScopedDeclarations == null) { lexScopedDeclarations = newSmallList(); } lexScopedDeclarations.add(decl); } } private static class LabelContext { final LabelContext parent; final StatementType type; final Set<String> labelSet; final EnumSet<Abrupt> abrupts = EnumSet.noneOf(Abrupt.class); LabelContext(LabelContext parent, StatementType type, Set<String> labelSet) { this.parent = parent; this.type = type; this.labelSet = labelSet; } void mark(Abrupt abrupt) { abrupts.add(abrupt); } } @SuppressWarnings("serial") private static class RetryGenerator extends RuntimeException { } public enum Option { Strict, FunctionCode, LocalScope, DirectEval, EvalScript, EnclosedByWithStatement, /** B.1.1 Numeric Literals */ LegacyOctalIntegerLiteral, /** B.1.2 String Literals */ OctalEscapeSequence, /** B.1.3 HTML-like Comments */ HTMLComments, /** Moz-Extension: for-each statement */ ForEachStatement, /** Moz-Extension: guarded catch */ GuardedCatch, /** Moz-Extension: expression closure */ ExpressionClosure, /** Moz-Extension: let statement */ LetStatement, /** Moz-Extension: let expression */ LetExpression, /** Moz-Extension: legacy (star-less) generators */ LegacyGenerator, /** Moz-Extension: legacy comprehension forms */ LegacyComprehension; public static EnumSet<Option> from(Set<CompatibilityOption> compatOptions) { EnumSet<Option> options = EnumSet.noneOf(Option.class); if (compatOptions.contains(CompatibilityOption.LegacyOctalIntegerLiteral)) { options.add(Option.LegacyOctalIntegerLiteral); } if (compatOptions.contains(CompatibilityOption.OctalEscapeSequence)) { options.add(Option.OctalEscapeSequence); } if (compatOptions.contains(CompatibilityOption.HTMLComments)) { options.add(Option.HTMLComments); } if (compatOptions.contains(CompatibilityOption.ForEachStatement)) { options.add(Option.ForEachStatement); } if (compatOptions.contains(CompatibilityOption.GuardedCatch)) { options.add(Option.GuardedCatch); } if (compatOptions.contains(CompatibilityOption.ExpressionClosure)) { options.add(Option.ExpressionClosure); } if (compatOptions.contains(CompatibilityOption.LetStatement)) { options.add(Option.LetStatement); } if (compatOptions.contains(CompatibilityOption.LetExpression)) { options.add(Option.LetExpression); } if (compatOptions.contains(CompatibilityOption.LegacyGenerator)) { options.add(Option.LegacyGenerator); } if (compatOptions.contains(CompatibilityOption.LegacyComprehension)) { options.add(Option.LegacyComprehension); } return options; } } public Parser(String sourceFile, int sourceLine, Set<Option> options) { this.sourceFile = sourceFile; this.sourceLine = sourceLine; this.options = EnumSet.copyOf(options); context = new ParseContext(); context.strictMode = this.options.contains(Option.Strict) ? StrictMode.Strict : StrictMode.NonStrict; } String getSourceFile() { return sourceFile; } int getSourceLine() { return sourceLine; } boolean isEnabled(Option option) { return options.contains(option); } private ParseContext newContext(ContextKind kind) { return context = new ParseContext(context, kind); } private ParseContext restoreContext() { if (context.parent.strictError == null) { context.parent.strictError = context.strictError; } return context = context.parent; } private BlockContext enterWithContext() { BlockContext cx = new BlockContext(context.scopeContext, true); context.scopeContext = cx; return cx; } private ScopeContext exitWithContext() { return exitScopeContext(); } private BlockContext enterBlockContext() { BlockContext cx = new BlockContext(context.scopeContext, false); context.scopeContext = cx; return cx; } private BlockContext reenterBlockContext(BlockContext cx) { context.scopeContext = cx; return cx; } private ScopeContext exitBlockContext() { return exitScopeContext(); } private ScopeContext exitScopeContext() { ScopeContext scope = context.scopeContext; ScopeContext parent = scope.parent; assert parent != null : "exitScopeContext() on top-level"; HashSet<String> varDeclaredNames = scope.varDeclaredNames; if (varDeclaredNames != null) { scope.varDeclaredNames = null; for (String name : varDeclaredNames) { addVarDeclaredName(parent, name); } } return context.scopeContext = parent; } private void addFunctionDeclaration(FunctionDeclaration decl) { String name = BoundName(decl.getIdentifier()); ScopeContext parentScope = context.parent.scopeContext; if (parentScope.isTopLevel()) { // top-level function declaration parentScope.addVarScopedDeclaration(decl); if (!parentScope.addVarDeclaredName(name)) { reportSyntaxError(decl, Messages.Key.VariableRedeclaration, name); } } else { // block-scoped function declaration parentScope.addLexScopedDeclaration(decl); if (!parentScope.addLexDeclaredName(name)) { reportSyntaxError(decl, Messages.Key.VariableRedeclaration, name); } } } private void addGeneratorDeclaration(GeneratorDeclaration decl) { String name = BoundName(decl.getIdentifier()); ScopeContext parentScope = context.parent.scopeContext; parentScope.addLexScopedDeclaration(decl); if (!parentScope.addLexDeclaredName(name)) { reportSyntaxError(decl, Messages.Key.VariableRedeclaration, name); } } private void addLexScopedDeclaration(Declaration decl) { context.scopeContext.addLexScopedDeclaration(decl); } private void addVarScopedDeclaration(VariableStatement decl) { context.funContext.addVarScopedDeclaration(decl); } private void addVarDeclaredName(ScopeContext scope, String name) { if (!scope.addVarDeclaredName(name)) { // FIXME: provide correct line/source information reportSyntaxError(Messages.Key.VariableRedeclaration, name); } } private void addVarDeclaredName(ScopeContext scope, Binding binding, String name) { if (!scope.addVarDeclaredName(name)) { reportSyntaxError(binding, Messages.Key.VariableRedeclaration, name); } } private void addLexDeclaredName(ScopeContext scope, Binding binding, String name) { if (!scope.addLexDeclaredName(name)) { reportSyntaxError(binding, Messages.Key.VariableRedeclaration, name); } } /** * <strong>[13.1] Block</strong> * <p> * Static Semantics: Early Errors<br> * <ul> * <li>It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList also * occurs in the VarDeclaredNames of StatementList. * </ul> */ @SuppressWarnings("unused") private void addVarDeclaredName(Binding binding) { if (binding instanceof BindingIdentifier) { addVarDeclaredName((BindingIdentifier) binding); } else { assert binding instanceof BindingPattern; addVarDeclaredName((BindingPattern) binding); } } private void addVarDeclaredName(BindingIdentifier bindingIdentifier) { String name = BoundName(bindingIdentifier); addVarDeclaredName(context.scopeContext, bindingIdentifier, name); } private void addVarDeclaredName(BindingPattern bindingPattern) { for (String name : BoundNames(bindingPattern)) { addVarDeclaredName(context.scopeContext, bindingPattern, name); } } /** * <strong>[13.1] Block</strong> * <p> * Static Semantics: Early Errors<br> * <ul> * <li>It is a Syntax Error if the LexicallyDeclaredNames of StatementList contains any * duplicate entries. * <li>It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList also * occurs in the VarDeclaredNames of StatementList. * </ul> */ private void addLexDeclaredName(Binding binding) { if (binding instanceof BindingIdentifier) { addLexDeclaredName((BindingIdentifier) binding); } else { assert binding instanceof BindingPattern; addLexDeclaredName((BindingPattern) binding); } } private void addLexDeclaredName(BindingIdentifier bindingIdentifier) { String name = BoundName(bindingIdentifier); addLexDeclaredName(context.scopeContext, bindingIdentifier, name); } private void addLexDeclaredName(BindingPattern bindingPattern) { for (String name : BoundNames(bindingPattern)) { addLexDeclaredName(context.scopeContext, bindingPattern, name); } } private void addLexDeclaredNames(List<Binding> bindings) { for (Binding binding : bindings) { addLexDeclaredName(binding); } } private void removeLexDeclaredNames(List<Binding> bindings) { for (Binding binding : bindings) { removeLexDeclaredName(binding); } } private void removeLexDeclaredName(Binding binding) { HashSet<String> lexDeclaredNames = context.scopeContext.lexDeclaredNames; if (binding instanceof BindingIdentifier) { BindingIdentifier bindingIdentifier = (BindingIdentifier) binding; String name = BoundName(bindingIdentifier); lexDeclaredNames.remove(name); } else { assert binding instanceof BindingPattern; BindingPattern bindingPattern = (BindingPattern) binding; for (String name : BoundNames(bindingPattern)) { lexDeclaredNames.remove(name); } } } private LabelContext enterLabelled(long sourcePosition, StatementType type, Set<String> labelSet) { LabelContext cx = context.labels = new LabelContext(context.labels, type, labelSet); if (!labelSet.isEmpty() && context.labelSet == null) { context.labelSet = new HashMap<>(); } for (String label : labelSet) { if (context.labelSet.containsKey(label)) { reportSyntaxError(sourcePosition, Messages.Key.DuplicateLabel, label); } context.labelSet.put(label, cx); } return cx; } private LabelContext exitLabelled() { for (String label : context.labels.labelSet) { context.labelSet.remove(label); } return context.labels = context.labels.parent; } private LabelContext enterIteration(long sourcePosition, Set<String> labelSet) { return enterLabelled(sourcePosition, StatementType.Iteration, labelSet); } private void exitIteration() { exitLabelled(); } private LabelContext enterBreakable(long sourcePosition, Set<String> labelSet) { return enterLabelled(sourcePosition, StatementType.Breakable, labelSet); } private void exitBreakable() { exitLabelled(); } private LabelContext findContinueTarget(String label) { for (LabelContext cx = context.labels; cx != null; cx = cx.parent) { if (label == null ? cx.type == StatementType.Iteration : cx.labelSet.contains(label)) { return cx; } } return null; } private LabelContext findBreakTarget(String label) { for (LabelContext cx = context.labels; cx != null; cx = cx.parent) { if (label == null ? cx.type != StatementType.Statement : cx.labelSet.contains(label)) { return cx; } } return null; } private static <T> List<T> newSmallList() { return new SmallArrayList<>(); } private static <T> List<T> newList() { return new SmallArrayList<>(); } private static <T> List<T> merge(List<T> list1, List<T> list2) { if (!(list1.isEmpty() || list2.isEmpty())) { List<T> merged = new ArrayList<>(); merged.addAll(list1); merged.addAll(list2); return merged; } return list1.isEmpty() ? list2 : list1; } private static int toLine(long sourcePosition) { return (int) sourcePosition; } private static int toColumn(long sourcePosition) { return (int) (sourcePosition >>> 32); } private ParserException reportException(ParserException exception) { throw exception; } /** * Report mismatched token error from tokenstream's current position */ private ParserException reportTokenMismatch(Token expected, Token actual) { long sourcePosition = ts.sourcePosition(); int line = toLine(sourcePosition), col = toColumn(sourcePosition); if (actual == Token.EOF) { throw new ParserEOFException(sourceFile, line, col, Messages.Key.UnexpectedToken, actual.toString(), expected.toString()); } throw new ParserException(ExceptionType.SyntaxError, sourceFile, line, col, Messages.Key.UnexpectedToken, actual.toString(), expected.toString()); } /** * Report mismatched token error from tokenstream's current position */ private ParserException reportTokenMismatch(String expected, Token actual) { long sourcePosition = ts.sourcePosition(); int line = toLine(sourcePosition), col = toColumn(sourcePosition); if (actual == Token.EOF) { throw new ParserEOFException(sourceFile, line, col, Messages.Key.UnexpectedToken, actual.toString(), expected); } throw new ParserException(ExceptionType.SyntaxError, sourceFile, line, col, Messages.Key.UnexpectedToken, actual.toString(), expected); } /** * Report parser error with the given type and position */ private ParserException reportError(ExceptionType type, int line, int column, Messages.Key messageKey, String... args) { throw new ParserException(type, sourceFile, line, column, messageKey, args); } /** * Report syntax error from the given position */ private ParserException reportSyntaxError(long sourcePosition, Messages.Key messageKey, String... args) { int line = toLine(sourcePosition), col = toColumn(sourcePosition); throw reportError(ExceptionType.SyntaxError, line, col, messageKey, args); } /** * Report syntax error from the node's source-position */ private ParserException reportSyntaxError(Node node, Messages.Key messageKey, String... args) { throw reportSyntaxError(node.getSourcePosition(), messageKey, args); } /** * Report syntax error from tokenstream's current position */ private ParserException reportSyntaxError(Messages.Key messageKey, String... args) { throw reportSyntaxError(ts.sourcePosition(), messageKey, args); } /** * Report (or store) strict-mode parser error with the given type and position */ private void reportStrictModeError(ExceptionType type, int line, int column, Messages.Key messageKey, String... args) { if (context.strictMode == StrictMode.Unknown) { if (context.strictError == null) { context.strictError = new ParserException(type, sourceFile, line, column, messageKey, args); } } else if (context.strictMode == StrictMode.Strict) { reportError(type, line, column, messageKey, args); } } /** * Report (or store) strict-mode syntax error from the given position */ private void reportStrictModeSyntaxError(long sourcePosition, Messages.Key messageKey, String... args) { int line = toLine(sourcePosition), col = toColumn(sourcePosition); reportStrictModeError(ExceptionType.SyntaxError, line, col, messageKey, args); } /** * Report (or store) strict-mode syntax error from the node's source-position */ private void reportStrictModeSyntaxError(Node node, Messages.Key messageKey, String... args) { reportStrictModeSyntaxError(node.getSourcePosition(), messageKey, args); } /** * Report (or store) strict-mode syntax error from tokenstream's current position */ void reportStrictModeSyntaxError(Messages.Key messageKey, String... args) { reportStrictModeSyntaxError(ts.sourcePosition(), messageKey, args); } /** * Peeks the next token in the token-stream */ private Token peek() { return ts.peekToken(); } /** * Checks whether the next token in the token-stream is equal to the input token */ private boolean LOOKAHEAD(Token token) { return ts.peekToken() == token; } /** * Returns the current token in the token-stream */ private Token token() { return ts.currentToken(); } /** * Consumes the current token in the token-stream and advances the stream to the next token */ private void consume(Token tok) { if (tok != token()) reportTokenMismatch(tok, token()); Token next = ts.nextToken(); if (DEBUG) System.out.printf("consume(%s) -> %s\n", tok, next); } /** * Consumes the current token in the token-stream and advances the stream to the next token */ private void consume(String name) { long sourcePos = ts.sourcePosition(); String string = ts.getString(); consume(Token.NAME); if (!name.equals(string)) reportSyntaxError(sourcePos, Messages.Key.UnexpectedName, string, name); } public Script parseScript(CharSequence source) throws ParserException { if (ts != null) throw new IllegalStateException(); ts = new TokenStream(this, new StringTokenStreamInput(source)); return script(); } public ModuleDeclaration parseModule(CharSequence source) throws ParserException { if (ts != null) throw new IllegalStateException(); newContext(ContextKind.Script); try { applyStrictMode(true); // defaults to strict ModuleDeclaration module; newContext(ContextKind.Module); try { ts = new TokenStream(this, new StringTokenStreamInput(source)).initialise(); String moduleName = sourceFile; // only basename(sourceFile)? List<StatementListItem> body = moduleBody(Token.EOF); FunctionContext scope = context.funContext; module = new ModuleDeclaration(sourceLine, moduleName, body, scope); scope.node = module; } finally { restoreContext(); } createScript(module); return module; } finally { restoreContext(); } } public FunctionDefinition parseFunction(CharSequence formals, CharSequence bodyText) throws ParserException { if (ts != null) throw new IllegalStateException(); newContext(ContextKind.Script); try { applyStrictMode(false); FunctionExpression function; newContext(ContextKind.Function); try { ts = new TokenStream(this, new StringTokenStreamInput(formals)).initialise(); FormalParameterList parameters = formalParameters(Token.EOF); if (token() != Token.EOF) { reportSyntaxError(Messages.Key.InvalidFormalParameterList); } if (ts.position() != formals.length()) { // more input after last token (whitespace, comments), add newlines to handle // last token is single-line comment case formals = "\n" + formals + "\n"; } ts = new TokenStream(this, new StringTokenStreamInput(bodyText)).initialise(); List<StatementListItem> statements = functionBody(Token.EOF); if (token() != Token.EOF) { reportSyntaxError(Messages.Key.InvalidFunctionBody); } String header = String.format("function anonymous (%s) ", formals); String body = String.format("\n%s\n", bodyText); FunctionContext scope = context.funContext; function = new FunctionExpression(sourceLine, scope, "anonymous", parameters, statements, header, body); scope.node = function; function_StaticSemantics(function); function = inheritStrictness(function); } catch (RetryGenerator e) { // don't bother with legacy support here throw reportSyntaxError(Messages.Key.InvalidYieldStatement); } finally { restoreContext(); } createScript(new ExpressionStatement(function)); return function; } finally { restoreContext(); } } public GeneratorDefinition parseGenerator(CharSequence formals, CharSequence bodyText) throws ParserException { if (ts != null) throw new IllegalStateException(); newContext(ContextKind.Script); try { applyStrictMode(false); GeneratorExpression generator; newContext(ContextKind.Generator); try { ts = new TokenStream(this, new StringTokenStreamInput(formals)).initialise(); FormalParameterList parameters = formalParameters(Token.EOF); if (token() != Token.EOF) { reportSyntaxError(Messages.Key.InvalidFormalParameterList); } if (ts.position() != formals.length()) { // more input after last token (whitespace, comments), add newlines to handle // last token is single-line comment case formals = "\n" + formals + "\n"; } ts = new TokenStream(this, new StringTokenStreamInput(bodyText)).initialise(); List<StatementListItem> statements = functionBody(Token.EOF); if (token() != Token.EOF) { reportSyntaxError(Messages.Key.InvalidFunctionBody); } String header = String.format("function* anonymous (%s) ", formals); String body = String.format("\n%s\n", bodyText); FunctionContext scope = context.funContext; generator = new GeneratorExpression(sourceLine, scope, "anonymous", parameters, statements, header, body); scope.node = generator; generator_StaticSemantics(generator); generator = inheritStrictness(generator); } finally { restoreContext(); } createScript(new ExpressionStatement(generator)); return generator; } finally { restoreContext(); } } private Script createScript(StatementListItem statement) { List<StatementListItem> statements = singletonList(statement); boolean strict = (context.strictMode == StrictMode.Strict); FunctionContext scope = context.funContext; Script script = new Script(sourceLine, sourceFile, scope, statements, options, strict); scope.node = script; return script; } /** * <strong>[15.1] Script</strong> * * <pre> * Script : * ScriptBody<sub>opt</sub> * ScriptBody : * OuterStatementList * </pre> */ private Script script() { newContext(ContextKind.Script); try { ts.initialise(); List<StatementListItem> prologue = directivePrologue(); List<StatementListItem> body = outerStatementList(); List<StatementListItem> statements = merge(prologue, body); boolean strict = (context.strictMode == StrictMode.Strict); FunctionContext scope = context.funContext; Script script = new Script(sourceLine, sourceFile, scope, statements, options, strict); scope.node = script; return script; } finally { restoreContext(); } } /** * <strong>[15.1] Script</strong> * * <pre> * OuterStatementList : * OuterItem * OuterStatementList OuterItem * OuterItem : * ModuleDeclaration * ImportDeclaration * StatementListItem * </pre> */ private List<StatementListItem> outerStatementList() { List<StatementListItem> list = newList(); while (token() != Token.EOF) { if (MODULES_ENABLED) { // TODO: implement modules if (token() == Token.IMPORT) { list.add(importDeclaration()); } else if (isName("module") && (peek() == Token.STRING || isIdentifier(peek())) && !ts.hasNextLineTerminator()) { list.add(moduleDeclaration()); } else { list.add(statementListItem()); } } else { list.add(statementListItem()); } } return list; } /** * <strong>[15.3] Modules</strong> * * <pre> * ModuleDeclaration ::= "module" [NoNewline] StringLiteral "{" ModuleBody "}" * | "module" Identifier "from" StringLiteral ";" * </pre> */ private ModuleDeclaration moduleDeclaration() { newContext(ContextKind.Module); try { long sourcePos = ts.sourcePosition(); consume("module"); if (token() == Token.STRING) { String moduleName = stringLiteral(); consume(Token.LC); List<StatementListItem> body = moduleBody(Token.RC); consume(Token.RC); FunctionContext scope = context.funContext; ModuleDeclaration module = new ModuleDeclaration(sourcePos, moduleName, body, scope); scope.node = module; return module; } else { String identifier = identifier(); consume("from"); String moduleName = stringLiteral(); semicolon(); FunctionContext scope = context.funContext; ModuleDeclaration module = new ModuleDeclaration(sourcePos, identifier, moduleName, scope); scope.node = module; return module; } } finally { restoreContext(); } } /** * <strong>[15.3] Modules</strong> * * <pre> * ModuleBody ::= ModuleElement* * ModuleElement ::= ScriptElement * | ExportDeclaration * </pre> */ private List<StatementListItem> moduleBody(Token end) { List<StatementListItem> list = newList(); while (token() != end) { // actually: ExportDeclaration | ImportDeclaration | StatementListItem // TODO: are nested modules (still) allowed? (disabled for now) if (token() == Token.EXPORT) { list.add(exportDeclaration()); } else if (token() == Token.IMPORT) { list.add(importDeclaration()); } else { list.add(statementListItem()); } } return list; } /** * <strong>[15.3] Modules</strong> * * <pre> * ExportDeclaration ::= "export" ExportSpecifierSet ";" * | "export" "default" AssignmentExpression ";" * | "export" VariableDeclaration * | "export" FunctionDeclaration * | "export" ClassDeclaration * </pre> */ private ExportDeclaration exportDeclaration() { long sourcePos = ts.sourcePosition(); consume(Token.EXPORT); switch (token()) { case LC: case MUL: { // "export" ExportSpecifierSet ";" ExportSpecifierSet exportSpecifierSet = exportSpecifierSet(); semicolon(); return new ExportDeclaration(sourcePos, exportSpecifierSet); } case DEFAULT: { // "export" "default" AssignmentExpression ";" consume(Token.DEFAULT); Expression expression = assignmentExpression(true); semicolon(); return new ExportDeclaration(sourcePos, expression); } case VAR: { // "export" VariableDeclaration VariableStatement variableStatement = variableStatement(); return new ExportDeclaration(sourcePos, variableStatement); } case FUNCTION: case CLASS: case LET: case CONST: { // "export" FunctionDeclaration // "export" ClassDeclaration Declaration declaration = declaration(); return new ExportDeclaration(sourcePos, declaration); } default: throw reportSyntaxError(Messages.Key.InvalidToken, token().toString()); } } /** * <strong>[15.3] Modules</strong> * * <pre> * ExportSpecifierSet ::= "{" (ExportSpecifier ("," ExportSpecifier)* ","?)? "}" * | "*" ("from" ModuleSpecifier)? * </pre> */ private ExportSpecifierSet exportSpecifierSet() { long sourcePos = ts.sourcePosition(); if (token() == Token.LC) { List<ExportSpecifier> exports = newSmallList(); consume(Token.LC); while (token() != Token.RC) { exports.add(exportSpecifier()); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } consume(Token.RC); // FIXME: re-export should also work with named exports String sourceModule = null; if (isName("from")) { consume("from"); sourceModule = moduleSpecifier(); } return new ExportSpecifierSet(sourcePos, exports, sourceModule); } else { consume(Token.MUL); String sourceModule = null; if (isName("from")) { consume("from"); sourceModule = moduleSpecifier(); } return new ExportSpecifierSet(sourcePos, sourceModule); } } /** * <strong>[15.3] Modules</strong> * * <pre> * ExportSpecifier ::= Identifier ("as" IdentifierName)? * </pre> */ private ExportSpecifier exportSpecifier() { long sourcePos = ts.sourcePosition(); String localName = identifier(); String externalName; if (isName("as")) { consume("as"); externalName = identifierName(); } else { externalName = localName; } return new ExportSpecifier(sourcePos, localName, externalName); } /** * <strong>[15.3] Modules</strong> * * <pre> * ModuleSpecifier ::= StringLiteral * </pre> */ private String moduleSpecifier() { return stringLiteral(); } /** * <strong>[15.3] Modules</strong> * * <pre> * ImportDeclaration ::= "import" ImportSpecifierSet "from" ModuleSpecifier ";" * | "import" ModuleSpecifier ";" * </pre> */ private ImportDeclaration importDeclaration() { long sourcePos = ts.sourcePosition(); consume(Token.IMPORT); if (token() == Token.STRING) { String moduleSpecifier = moduleSpecifier(); semicolon(); return new ImportDeclaration(sourcePos, moduleSpecifier); } else { ImportSpecifierSet importSpecifierSet = importSpecifierSet(); consume("from"); String moduleSpecifier = moduleSpecifier(); semicolon(); return new ImportDeclaration(sourcePos, importSpecifierSet, moduleSpecifier); } } /** * <strong>[15.3] Modules</strong> * * <pre> * ImportSpecifierSet ::= Identifier * | "{" (ImportSpecifier ("," ImportSpecifier)* ","?)? "}" * </pre> */ private ImportSpecifierSet importSpecifierSet() { long sourcePos = ts.sourcePosition(); if (isIdentifier(token())) { String defaultImport = identifier(); return new ImportSpecifierSet(sourcePos, defaultImport); } else { List<ImportSpecifier> imports = newSmallList(); consume(Token.LC); while (token() != Token.RC) { imports.add(importSpecifier()); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } consume(Token.RC); return new ImportSpecifierSet(sourcePos, imports); } } /** * <strong>[15.3] Modules</strong> * * <pre> * ImportSpecifier ::= Identifier ("as" Identifier)? * | ReservedWord "as" Identifier * </pre> */ private ImportSpecifier importSpecifier() { assert context.strictMode != StrictMode.Unknown : "undefined strict-mode in import specifier"; long sourcePos = ts.sourcePosition(); String externalName, localName; if (!isReservedWord(token())) { externalName = identifier(); if (isName("as")) { consume("as"); localName = identifier(); } else { localName = externalName; } } else { externalName = identifierName(); consume("as"); localName = identifier(); } return new ImportSpecifier(sourcePos, externalName, localName); } /** * <strong>[15.2] Directive Prologues and the Use Strict Directive</strong> * * <pre> * DirectivePrologue : * Directive<sub>opt</sub> * Directive: * StringLiteral ; * Directive StringLiteral ; * </pre> */ private List<StatementListItem> directivePrologue() { List<StatementListItem> statements = newSmallList(); boolean strict = false; directive: while (token() == Token.STRING) { long sourcePos = ts.sourcePosition(); boolean hasEscape = ts.hasEscape(); // peek() may clear hasEscape flag Token next = peek(); switch (next) { case SEMI: case RC: case EOF: break; default: if (ts.hasNextLineTerminator() && !isOperator(next)) { break; } break directive; } // got a directive String string = stringLiteral(); if (!hasEscape && "use strict".equals(string)) { strict = true; } semicolon(); statements.add(new ExpressionStatement(new StringLiteral(sourcePos, string))); } applyStrictMode(strict); return statements; } private static boolean isOperator(Token token) { switch (token) { case DOT: case LB: case LP: case TEMPLATE: case COMMA: case HOOK: case ASSIGN: case ASSIGN_ADD: case ASSIGN_BITAND: case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_DIV: case ASSIGN_MOD: case ASSIGN_MUL: case ASSIGN_SHL: case ASSIGN_SHR: case ASSIGN_SUB: case ASSIGN_USHR: case OR: case AND: case BITAND: case BITOR: case BITXOR: case EQ: case NE: case SHEQ: case SHNE: case LT: case LE: case GT: case GE: case INSTANCEOF: case IN: case SHL: case SHR: case USHR: case ADD: case SUB: case MUL: case DIV: case MOD: return true; default: return false; } } private void applyStrictMode(boolean strict) { if (strict) { context.strictMode = StrictMode.Strict; context.explicitStrict = true; if (context.strictError != null) { reportException(context.strictError); } } else { if (context.strictMode == StrictMode.Unknown) { context.strictMode = context.parent.strictMode; } } } private static FunctionNode.StrictMode toFunctionStrictness(boolean strict, boolean explicit) { if (strict) { if (explicit) { return FunctionNode.StrictMode.ExplicitStrict; } return FunctionNode.StrictMode.ImplicitStrict; } return FunctionNode.StrictMode.NonStrict; } private <FUNCTION extends FunctionNode> FUNCTION inheritStrictness(FUNCTION function) { if (context.strictMode != StrictMode.Unknown) { boolean strict = (context.strictMode == StrictMode.Strict); function.setStrictMode(toFunctionStrictness(strict, context.explicitStrict)); if (context.deferred != null) { for (FunctionNode func : context.deferred) { func.setStrictMode(toFunctionStrictness(strict, false)); } context.deferred = null; } } else { // this case only applies for functions with default parameters assert context.parent.strictMode == StrictMode.Unknown; ParseContext parent = context.parent; if (parent.deferred == null) { parent.deferred = newSmallList(); } parent.deferred.add(function); if (context.deferred != null) { parent.deferred.addAll(context.deferred); context.deferred = null; } } return function; } /** * Special case for {@link Token#YIELD} as {@link BindingIdentifier} in functions and generators */ private BindingIdentifier bindingIdentifierFunctionName() { // FIXME: Preliminary solution to provide SpiderMonkey/V8 compatibility // 'yield' is always a keyword in strict-mode and in generators, but parse function name // in the context of the surrounding environment if (token() == Token.YIELD) { long sourcePos = ts.sourcePosition(); if (isYieldName(context.parent)) { consume(Token.YIELD); return new BindingIdentifier(sourcePos, getName(Token.YIELD)); } reportStrictModeSyntaxError(sourcePos, Messages.Key.StrictModeInvalidIdentifier, getName(Token.YIELD)); reportTokenMismatch("<identifier>", Token.YIELD); } return bindingIdentifier(); } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * FunctionDeclaration : * function BindingIdentifier ( FormalParameters ) { FunctionBody } * </pre> */ private FunctionDeclaration functionDeclaration() { newContext(ContextKind.Function); try { long sourcePos = ts.sourcePosition(); consume(Token.FUNCTION); int startFunction = ts.position() - "function".length(); BindingIdentifier identifier = bindingIdentifierFunctionName(); consume(Token.LP); FormalParameterList parameters = formalParameters(Token.RP); consume(Token.RP); String header, body; List<StatementListItem> statements; if (token() != Token.LC && isEnabled(Option.ExpressionClosure)) { // need to call manually b/c functionBody() isn't used here applyStrictMode(false); int startBody = ts.position(); statements = Collections.<StatementListItem> singletonList(new ReturnStatement(ts .sourcePosition(), assignmentExpression(true))); int endFunction = ts.position(); header = ts.range(startFunction, startBody); body = "return " + ts.range(startBody, endFunction); } else { consume(Token.LC); int startBody = ts.position(); statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; header = ts.range(startFunction, startBody - 1); body = ts.range(startBody, endFunction); } FunctionContext scope = context.funContext; FunctionDeclaration function = new FunctionDeclaration(sourcePos, scope, identifier, parameters, statements, header, body); scope.node = function; function_StaticSemantics(function); addFunctionDeclaration(function); return inheritStrictness(function); } finally { restoreContext(); } } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * FunctionExpression : * function BindingIdentifier<sub>opt</sub> ( FormalParameters ) { FunctionBody } * </pre> */ private FunctionExpression functionExpression() { newContext(ContextKind.Function); try { long sourcePos = ts.sourcePosition(); consume(Token.FUNCTION); int startFunction = ts.position() - "function".length(); BindingIdentifier identifier = null; if (token() != Token.LP) { identifier = bindingIdentifierFunctionName(); } consume(Token.LP); FormalParameterList parameters = formalParameters(Token.RP); consume(Token.RP); String header, body; List<StatementListItem> statements; if (token() != Token.LC && isEnabled(Option.ExpressionClosure)) { // need to call manually b/c functionBody() isn't used here applyStrictMode(false); int startBody = ts.position(); statements = Collections.<StatementListItem> singletonList(new ReturnStatement(ts .sourcePosition(), assignmentExpression(true))); int endFunction = ts.position(); header = ts.range(startFunction, startBody); body = "return " + ts.range(startBody, endFunction); } else { consume(Token.LC); int startBody = ts.position(); statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; header = ts.range(startFunction, startBody - 1); body = ts.range(startBody, endFunction); } FunctionContext scope = context.funContext; FunctionExpression function = new FunctionExpression(sourcePos, scope, identifier, parameters, statements, header, body); scope.node = function; function_StaticSemantics(function); return inheritStrictness(function); } finally { restoreContext(); } } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * StrictFormalParameters : * FormalParameters * </pre> */ private FormalParameterList strictFormalParameters(Token end) { return formalParameters(end); } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * FormalParameters : * [empty] * FormalParameterList * </pre> */ private FormalParameterList formalParameters(Token end) { if (token() == end) { long sourcePos = ts.sourcePosition(); return new FormalParameterList(sourcePos, Collections.<FormalParameter> emptyList()); } return formalParameterList(); } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * FormalParameterList : * FunctionRestParameter * FormalsList * FormalsList, FunctionRestParameter * FormalsList : * FormalParameter * FormalsList, FormalParameter * FunctionRestParameter : * ... BindingIdentifier * FormalParameter : * BindingElement * </pre> */ private FormalParameterList formalParameterList() { long sourcePos = ts.sourcePosition(); List<FormalParameter> formals = newSmallList(); for (;;) { if (token() == Token.TRIPLE_DOT) { long sourcePosRest = ts.sourcePosition(); consume(Token.TRIPLE_DOT); formals.add(new BindingRestElement(sourcePosRest, bindingIdentifierStrict())); break; } else { formals.add(bindingElement()); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } } return new FormalParameterList(sourcePos, formals); } private static <T> T containsAny(Set<T> set, List<T> list) { for (T element : list) { if (set.contains(element)) { return element; } } return null; } private void checkFormalParameterRedeclaration(FunctionNode node, List<String> boundNames, HashSet<String> declaredNames) { if (!(declaredNames == null || declaredNames.isEmpty())) { String redeclared = containsAny(declaredNames, boundNames); if (redeclared != null) { reportSyntaxError(node, Messages.Key.FormalParameterRedeclaration, redeclared); } } } private void function_StaticSemantics(FunctionDefinition function) { assert context.scopeContext == context.funContext; FunctionContext scope = context.funContext; FormalParameterList parameters = function.getParameters(); List<String> boundNames = BoundNames(parameters); scope.parameterNames = new HashSet<>(boundNames); boolean simple = IsSimpleParameterList(parameters); if (!simple) { checkFormalParameterRedeclaration(function, boundNames, scope.varDeclaredNames); } checkFormalParameterRedeclaration(function, boundNames, scope.lexDeclaredNames); formalParameters_StaticSemantics(function, boundNames, scope.parameterNames, simple); } private void strictFormalParameters_StaticSemantics(FunctionNode node, List<String> boundNames, Set<String> names) { boolean hasDuplicates = (boundNames.size() != names.size()); boolean hasEvalOrArguments = (names.contains("eval") || names.contains("arguments")); if (hasDuplicates) { reportSyntaxError(node, Messages.Key.StrictModeDuplicateFormalParameter); } if (hasEvalOrArguments) { reportSyntaxError(node, Messages.Key.StrictModeRestrictedIdentifier); } } private void formalParameters_StaticSemantics(FunctionNode node, List<String> boundNames, Set<String> names, boolean simple) { boolean strict = (context.strictMode != StrictMode.NonStrict); if (!strict && simple) { return; } boolean hasDuplicates = (boundNames.size() != names.size()); boolean hasEvalOrArguments = (names.contains("eval") || names.contains("arguments")); if (!simple) { if (hasDuplicates) { reportSyntaxError(node, Messages.Key.StrictModeDuplicateFormalParameter); } if (hasEvalOrArguments) { reportSyntaxError(node, Messages.Key.StrictModeRestrictedIdentifier); } } if (strict) { if (hasDuplicates) { reportStrictModeSyntaxError(node, Messages.Key.StrictModeDuplicateFormalParameter); } if (hasEvalOrArguments) { reportStrictModeSyntaxError(node, Messages.Key.StrictModeRestrictedIdentifier); } } } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * FunctionBody : * FunctionStatementList * FunctionStatementList : * StatementList<sub>opt</sub> * </pre> */ private List<StatementListItem> functionBody(Token end) { // enable 'yield' if in generator context.yieldAllowed = (context.kind == ContextKind.Generator); List<StatementListItem> prologue = directivePrologue(); List<StatementListItem> body = statementList(end); return merge(prologue, body); } /** * <strong>[14.2] Arrow Function Definitions</strong> * * <pre> * ArrowFunction : * ArrowParameters => ConciseBody * ArrowParameters : * BindingIdentifier * CoverParenthesisedExpressionAndArrowParameterList * ConciseBody : * [LA &#x2209; { <b>{</b> }] AssignmentExpression * { FunctionBody } * </pre> * * <h2>Supplemental Syntax</h2> * * <pre> * ArrowFormalParameters : * ( StrictFormalParameters ) * </pre> */ private ArrowFunction arrowFunction(boolean allowIn) { newContext(ContextKind.ArrowFunction); try { long sourcePos = ts.sourcePosition(); StringBuilder source = new StringBuilder(); source.append("function anonymous"); FormalParameterList parameters; if (token() == Token.LP) { consume(Token.LP); int start = ts.position() - 1; parameters = strictFormalParameters(Token.RP); consume(Token.RP); source.append(ts.range(start, ts.position())); } else { BindingIdentifier identifier = bindingIdentifierStrict(); FormalParameter parameter = new BindingElement(sourcePos, identifier, null); parameters = new FormalParameterList(sourcePos, singletonList(parameter)); source.append('(').append(identifier.getName()).append(')'); } consume(Token.ARROW); if (token() == Token.LC) { consume(Token.LC); int startBody = ts.position(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; String header = source.toString(); String body = ts.range(startBody, endFunction); FunctionContext scope = context.funContext; ArrowFunction function = new ArrowFunction(sourcePos, scope, parameters, statements, header, body); scope.node = function; arrowFunction_StaticSemantics(function); return inheritStrictness(function); } else { // need to call manually b/c functionBody() isn't used here applyStrictMode(false); int startBody = ts.position(); Expression expression = assignmentExpression(allowIn); int endFunction = ts.position(); String header = source.toString(); String body = "return " + ts.range(startBody, endFunction); FunctionContext scope = context.funContext; ArrowFunction function = new ArrowFunction(sourcePos, scope, parameters, expression, header, body); scope.node = function; arrowFunction_StaticSemantics(function); return inheritStrictness(function); } } finally { restoreContext(); } } private void arrowFunction_StaticSemantics(ArrowFunction function) { assert context.scopeContext == context.funContext; FunctionContext scope = context.funContext; FormalParameterList parameters = function.getParameters(); List<String> boundNames = BoundNames(parameters); scope.parameterNames = new HashSet<>(boundNames); checkFormalParameterRedeclaration(function, boundNames, scope.varDeclaredNames); checkFormalParameterRedeclaration(function, boundNames, scope.lexDeclaredNames); strictFormalParameters_StaticSemantics(function, boundNames, scope.parameterNames); } /** * <strong>[14.3] Method Definitions</strong> * * <pre> * MethodDefinition : * PropertyName ( StrictFormalParameters ) { FunctionBody } * GeneratorMethod * get PropertyName ( ) { FunctionBody } * set PropertyName ( PropertySetParameterList ) { FunctionBody } * </pre> */ private MethodDefinition methodDefinition(boolean alwaysStrict) { switch (methodType()) { case Generator: return generatorMethod(alwaysStrict); case Getter: return getterMethod(alwaysStrict); case Setter: return setterMethod(alwaysStrict); case Function: default: return normalMethod(alwaysStrict); } } /** * <strong>[14.3] Method Definitions</strong> * * <pre> * MethodDefinition : * PropertyName ( StrictFormalParameters ) { FunctionBody } * </pre> */ private MethodDefinition normalMethod(boolean alwaysStrict) { long sourcePos = ts.sourcePosition(); PropertyName propertyName = propertyName(); return normalMethod(sourcePos, propertyName, alwaysStrict); } private MethodDefinition normalMethod(long sourcePos, PropertyName propertyName, boolean alwaysStrict) { newContext(ContextKind.Method); if (alwaysStrict) { context.strictMode = StrictMode.Strict; } try { consume(Token.LP); int startFunction = ts.position() - 1; FormalParameterList parameters = strictFormalParameters(Token.RP); consume(Token.RP); consume(Token.LC); int startBody = ts.position(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; String header = "function " + ts.range(startFunction, startBody - 1); String body = ts.range(startBody, endFunction); FunctionContext scope = context.funContext; MethodType type = MethodType.Function; MethodDefinition method = new MethodDefinition(sourcePos, scope, type, propertyName, parameters, statements, context.hasSuperReference(), header, body); scope.node = method; methodDefinition_StaticSemantics(method); return inheritStrictness(method); } finally { restoreContext(); } } /** * <strong>[14.3] Method Definitions</strong> * * <pre> * MethodDefinition : * get PropertyName ( ) { FunctionBody } * </pre> */ private MethodDefinition getterMethod(boolean alwaysStrict) { long sourcePos = ts.sourcePosition(); consume(Token.NAME); // "get" PropertyName propertyName = propertyName(); newContext(ContextKind.Method); if (alwaysStrict) { context.strictMode = StrictMode.Strict; } try { consume(Token.LP); int startFunction = ts.position() - 1; FormalParameterList parameters = new FormalParameterList(ts.sourcePosition(), Collections.<FormalParameter> emptyList()); consume(Token.RP); List<StatementListItem> statements; String header, body; if (token() != Token.LC && isEnabled(Option.ExpressionClosure)) { // need to call manually b/c functionBody() isn't used here applyStrictMode(false); int startBody = ts.position(); statements = Collections.<StatementListItem> singletonList(new ReturnStatement(ts .sourcePosition(), assignmentExpression(true))); int endFunction = ts.position(); header = "function " + ts.range(startFunction, startBody); body = "return " + ts.range(startBody, endFunction); } else { consume(Token.LC); int startBody = ts.position(); statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; header = "function " + ts.range(startFunction, startBody - 1); body = ts.range(startBody, endFunction); } FunctionContext scope = context.funContext; MethodType type = MethodType.Getter; MethodDefinition method = new MethodDefinition(sourcePos, scope, type, propertyName, parameters, statements, context.hasSuperReference(), header, body); scope.node = method; methodDefinition_StaticSemantics(method); return inheritStrictness(method); } finally { restoreContext(); } } /** * <strong>[14.3] Method Definitions</strong> * * <pre> * MethodDefinition : * set PropertyName ( PropertySetParameterList ) { FunctionBody } * </pre> */ private MethodDefinition setterMethod(boolean alwaysStrict) { long sourcePos = ts.sourcePosition(); consume(Token.NAME); // "set" PropertyName propertyName = propertyName(); newContext(ContextKind.Method); if (alwaysStrict) { context.strictMode = StrictMode.Strict; } try { consume(Token.LP); int startFunction = ts.position() - 1; FormalParameterList parameters = propertySetParameterList(); consume(Token.RP); List<StatementListItem> statements; String header, body; if (token() != Token.LC && isEnabled(Option.ExpressionClosure)) { // need to call manually b/c functionBody() isn't used here applyStrictMode(false); int startBody = ts.position(); statements = Collections.<StatementListItem> singletonList(new ReturnStatement(ts .sourcePosition(), assignmentExpression(true))); int endFunction = ts.position(); header = "function " + ts.range(startFunction, startBody); body = "return " + ts.range(startBody, endFunction); } else { consume(Token.LC); int startBody = ts.position(); statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; header = "function " + ts.range(startFunction, startBody - 1); body = ts.range(startBody, endFunction); } FunctionContext scope = context.funContext; MethodType type = MethodType.Setter; MethodDefinition method = new MethodDefinition(sourcePos, scope, type, propertyName, parameters, statements, context.hasSuperReference(), header, body); scope.node = method; methodDefinition_StaticSemantics(method); return inheritStrictness(method); } finally { restoreContext(); } } /** * <strong>[14.3] Method Definitions</strong> * * <pre> * PropertySetParameterList : * BindingIdentifier * BindingPattern * </pre> */ private FormalParameterList propertySetParameterList() { long sourcePos = ts.sourcePosition(); FormalParameter setParameter = new BindingElement(sourcePos, binding(), null); return new FormalParameterList(sourcePos, singletonList(setParameter)); } private MethodType methodType() { if (token() == Token.MUL) { return MethodType.Generator; } if (token() == Token.NAME) { String name = getName(Token.NAME); if (("get".equals(name) || "set".equals(name)) && isPropertyName(peek())) { return "get".equals(name) ? MethodType.Getter : MethodType.Setter; } } return MethodType.Function; } private boolean isPropertyName(Token token) { return token == Token.STRING || token == Token.NUMBER || token == Token.LB || isIdentifierName(token); } private void methodDefinition_StaticSemantics(MethodDefinition method) { assert context.scopeContext == context.funContext; FunctionContext scope = context.funContext; FormalParameterList parameters = method.getParameters(); List<String> boundNames = BoundNames(parameters); scope.parameterNames = new HashSet<>(boundNames); switch (method.getType()) { case Function: case Generator: { checkFormalParameterRedeclaration(method, boundNames, scope.varDeclaredNames); checkFormalParameterRedeclaration(method, boundNames, scope.lexDeclaredNames); strictFormalParameters_StaticSemantics(method, boundNames, scope.parameterNames); return; } case Setter: { boolean simple = IsSimpleParameterList(parameters); if (!simple) { checkFormalParameterRedeclaration(method, boundNames, scope.varDeclaredNames); } checkFormalParameterRedeclaration(method, boundNames, scope.lexDeclaredNames); propertySetParameterList_StaticSemantics(method, boundNames, scope.parameterNames, simple); return; } case Getter: default: return; } } private void propertySetParameterList_StaticSemantics(FunctionNode node, List<String> boundNames, Set<String> names, boolean simple) { boolean strict = (context.strictMode != StrictMode.NonStrict); boolean hasDuplicates = (boundNames.size() != names.size()); boolean hasEvalOrArguments = (names.contains("eval") || names.contains("arguments")); if (!simple) { if (hasDuplicates) { reportSyntaxError(node, Messages.Key.StrictModeDuplicateFormalParameter); } if (hasEvalOrArguments) { reportSyntaxError(node, Messages.Key.StrictModeRestrictedIdentifier); } } // FIXME: spec bug - duplicate check done twice if (hasDuplicates) { reportSyntaxError(node, Messages.Key.StrictModeDuplicateFormalParameter); } // FIXME: spec bug - not handled in draft if (strict) { if (hasEvalOrArguments) { reportStrictModeSyntaxError(node, Messages.Key.StrictModeRestrictedIdentifier); } } } /** * <strong>[14.4] Generator Function Definitions</strong> * * <pre> * GeneratorMethod : * * PropertyName ( StrictFormalParameters ) { FunctionBody } * </pre> */ private MethodDefinition generatorMethod(boolean alwaysStrict) { long sourcePos = ts.sourcePosition(); consume(Token.MUL); PropertyName propertyName = propertyName(); newContext(ContextKind.Generator); if (alwaysStrict) { context.strictMode = StrictMode.Strict; } try { consume(Token.LP); int startFunction = ts.position() - 1; FormalParameterList parameters = strictFormalParameters(Token.RP); consume(Token.RP); consume(Token.LC); int startBody = ts.position(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; String header = "function* " + ts.range(startFunction, startBody - 1); String body = ts.range(startBody, endFunction); FunctionContext scope = context.funContext; MethodType type = MethodType.Generator; MethodDefinition method = new MethodDefinition(sourcePos, scope, type, propertyName, parameters, statements, context.hasSuperReference(), header, body); scope.node = method; methodDefinition_StaticSemantics(method); return inheritStrictness(method); } finally { restoreContext(); } } /** * <strong>[14.4] Generator Function Definitions</strong> * * <pre> * GeneratorDeclaration : * function * BindingIdentifier ( FormalParameters ) { FunctionBody } * </pre> */ private GeneratorDeclaration generatorDeclaration(boolean starless) { newContext(ContextKind.Generator); try { long sourcePos = ts.sourcePosition(); consume(Token.FUNCTION); int startFunction = ts.position() - "function".length(); if (!starless) { consume(Token.MUL); } BindingIdentifier identifier = bindingIdentifierFunctionName(); consume(Token.LP); FormalParameterList parameters = formalParameters(Token.RP); consume(Token.RP); consume(Token.LC); int startBody = ts.position(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; String header = ts.range(startFunction, startBody - 1); String body = ts.range(startBody, endFunction); FunctionContext scope = context.funContext; GeneratorDeclaration generator; if (!starless) { generator = new GeneratorDeclaration(sourcePos, scope, identifier, parameters, statements, header, body); } else { generator = new LegacyGeneratorDeclaration(sourcePos, scope, identifier, parameters, statements, header, body); } scope.node = generator; generator_StaticSemantics(generator); addGeneratorDeclaration(generator); return inheritStrictness(generator); } finally { restoreContext(); } } /** * <strong>[14.4] Generator Function Definitions</strong> * * <pre> * GeneratorExpression : * function * BindingIdentifier<sub>opt</sub> ( FormalParameters ) { FunctionBody } * </pre> */ private GeneratorExpression generatorExpression(boolean starless) { newContext(ContextKind.Generator); try { long sourcePos = ts.sourcePosition(); consume(Token.FUNCTION); int startFunction = ts.position() - "function".length(); if (!starless) { consume(Token.MUL); } BindingIdentifier identifier = null; if (token() != Token.LP) { identifier = bindingIdentifierFunctionName(); } consume(Token.LP); FormalParameterList parameters = formalParameters(Token.RP); consume(Token.RP); consume(Token.LC); int startBody = ts.position(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; String header = ts.range(startFunction, startBody - 1); String body = ts.range(startBody, endFunction); FunctionContext scope = context.funContext; GeneratorExpression generator; if (!starless) { generator = new GeneratorExpression(sourcePos, scope, identifier, parameters, statements, header, body); } else { generator = new LegacyGeneratorExpression(sourcePos, scope, identifier, parameters, statements, header, body); } scope.node = generator; generator_StaticSemantics(generator); return inheritStrictness(generator); } finally { restoreContext(); } } private void generator_StaticSemantics(GeneratorDefinition generator) { assert context.scopeContext == context.funContext; FunctionContext scope = context.funContext; FormalParameterList parameters = generator.getParameters(); List<String> boundNames = BoundNames(parameters); scope.parameterNames = new HashSet<>(boundNames); boolean simple = IsSimpleParameterList(parameters); if (!simple) { checkFormalParameterRedeclaration(generator, boundNames, scope.varDeclaredNames); } checkFormalParameterRedeclaration(generator, boundNames, scope.lexDeclaredNames); formalParameters_StaticSemantics(generator, boundNames, scope.parameterNames, simple); } /** * <strong>[14.4] Generator Function Definitions</strong> * * <pre> * YieldExpression : * yield YieldDelegator<sub>opt</sub> <font size="-1">[Lexical goal <i>InputElementRegExp</i>]</font> AssignmentExpression * YieldDelegator : * * * </pre> */ private YieldExpression yieldExpression(boolean allowIn) { if (!context.yieldAllowed) { if (context.kind == ContextKind.Function && isEnabled(Option.LegacyGenerator)) { throw new RetryGenerator(); } reportSyntaxError(Messages.Key.InvalidYieldStatement); } long sourcePos = ts.sourcePosition(); consume(Token.YIELD); boolean delegatedYield = false; if (token() == Token.MUL) { consume(Token.MUL); delegatedYield = true; } Expression expr; if (delegatedYield) { expr = assignmentExpression(allowIn); } else if (!isEnabled(Option.LegacyGenerator)) { if (noLineTerminator() && assignmentExpressionFirstSet(token())) { expr = assignmentExpression(allowIn); } else { expr = null; } } else { // slightly different rules for optional AssignmentExpression in legacy generators if (noLineTerminator() && !assignmentExpressionFollowSet(token())) { expr = assignmentExpression(allowIn); } else { expr = null; } } return new YieldExpression(sourcePos, delegatedYield, expr); } private boolean assignmentExpressionFirstSet(Token token) { // returns FIRST(AssignmentExpression) switch (token) { case YIELD: // FIRST(YieldExpression) return true; case DELETE: case VOID: case TYPEOF: case INC: case DEC: case ADD: case SUB: case BITNOT: case NOT: // FIRST(UnaryExpression) return true; case SUPER: case NEW: // FIRST(LeftHandSideExpression) return true; case THIS: case NULL: case FALSE: case TRUE: case NUMBER: case STRING: case LB: case LC: case LP: case FUNCTION: case CLASS: case TEMPLATE: // FIRST(PrimaryExpression) return true; case DIV: case ASSIGN_DIV: // FIRST(RegularExpressionLiteral) return true; case LET: return isEnabled(Option.LetExpression); case NAME: case IMPLEMENTS: case INTERFACE: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: // FIRST(Identifier) return isIdentifier(token); default: return false; } } private boolean assignmentExpressionFollowSet(Token token) { // returns FOLLOW(AssignmentExpression) without { "of", "in", "for", "{" } // NB: not the exact follow set, consider `a = let(x=0)x++ ++`, but not relevant here switch (token) { case COLON: case COMMA: case RB: case RC: case RP: case SEMI: case EOF: return true; default: return false; } } /** * <strong>[14.5] Class Definitions</strong> * * <pre> * ClassDeclaration : * class BindingIdentifier ClassTail * ClassTail : * ClassHeritage<sub>opt</sub> { ClassBody<sub>opt</sub> } * ClassHeritage : * extends AssignmentExpression * </pre> */ private ClassDeclaration classDeclaration() { long sourcePos = ts.sourcePosition(); consume(Token.CLASS); BindingIdentifier name = bindingIdentifierPureStrict(); Expression heritage = null; if (token() == Token.EXTENDS) { consume(Token.EXTENDS); heritage = assignmentExpression(true); } consume(Token.LC); List<MethodDefinition> staticMethods = newList(); List<MethodDefinition> prototypeMethods = newList(); classBody(name, staticMethods, prototypeMethods); consume(Token.RC); ClassDeclaration decl = new ClassDeclaration(sourcePos, name, heritage, staticMethods, prototypeMethods); addLexDeclaredName(name); addLexScopedDeclaration(decl); return decl; } /** * <strong>[14.5] Class Definitions</strong> * * <pre> * ClassExpression : * class BindingIdentifier<sub>opt</sub> ClassTail * ClassTail : * ClassHeritage<sub>opt</sub> { ClassBody<sub>opt</sub> } * ClassHeritage : * extends AssignmentExpression * </pre> */ private ClassExpression classExpression() { long sourcePos = ts.sourcePosition(); consume(Token.CLASS); BindingIdentifier name = null; if (token() != Token.EXTENDS && token() != Token.LC) { name = bindingIdentifierPureStrict(); } Expression heritage = null; if (token() == Token.EXTENDS) { consume(Token.EXTENDS); heritage = assignmentExpression(true); } consume(Token.LC); if (name != null) { enterBlockContext(); addLexDeclaredName(name); } List<MethodDefinition> staticMethods = newList(); List<MethodDefinition> prototypeMethods = newList(); classBody(name, staticMethods, prototypeMethods); if (name != null) { exitBlockContext(); } consume(Token.RC); return new ClassExpression(sourcePos, name, heritage, staticMethods, prototypeMethods); } /** * <strong>[14.5] Class Definitions</strong> * * <pre> * ClassBody : * ClassElementList * ClassElementList : * ClassElement * ClassElementList ClassElement * ClassElement : * MethodDefinition * static MethodDefinition * ; * </pre> */ private void classBody(BindingIdentifier className, List<MethodDefinition> staticMethods, List<MethodDefinition> prototypeMethods) { while (token() != Token.RC) { if (token() == Token.SEMI) { consume(Token.SEMI); } else if (token() == Token.STATIC && !LOOKAHEAD(Token.LP)) { consume(Token.STATIC); staticMethods.add(methodDefinition(true)); } else { prototypeMethods.add(methodDefinition(true)); } } classBody_StaticSemantics(className, staticMethods, true); classBody_StaticSemantics(className, prototypeMethods, false); } private void classBody_StaticSemantics(BindingIdentifier className, List<MethodDefinition> defs, boolean isStatic) { final int VALUE = 0, GETTER = 1, SETTER = 2; Map<String, Integer> values = new HashMap<>(); for (MethodDefinition def : defs) { String key = PropName(def); if (key == null) { assert def.getPropertyName() instanceof ComputedPropertyName; continue; } if (isStatic) { if ("prototype".equals(key)) { reportSyntaxError(def, Messages.Key.InvalidPrototypeMethod); } } else { if ("constructor".equals(key) && SpecialMethod(def)) { reportSyntaxError(def, Messages.Key.InvalidConstructorMethod); } if (className != null) { def.setFunctionName(className.getName()); } } MethodDefinition.MethodType type = def.getType(); final int kind = type == MethodType.Getter ? GETTER : type == MethodType.Setter ? SETTER : VALUE; if (values.containsKey(key)) { int prev = values.get(key); if (kind == VALUE) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == GETTER && prev != SETTER) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == SETTER && prev != GETTER) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } values.put(key, prev | kind); } else { values.put(key, kind); } } } /** * <strong>[13] ECMAScript Language: Statements and Declarations</strong> * * <pre> * Statement : * BlockStatement * VariableStatement * EmptyStatement * ExpressionStatement * IfStatement * BreakableStatement * ContinueStatement * BreakStatement * ReturnStatement * WithStatement * LabelledStatement * ThrowStatement * TryStatement * DebuggerStatement * * BreakableStatement : * IterationStatement * SwitchStatement * </pre> */ private Statement statement() { switch (token()) { case LC: return block(NO_INHERITED_BINDING); case VAR: return variableStatement(); case SEMI: return emptyStatement(); case IF: return ifStatement(); case FOR: return forStatement(EMPTY_LABEL_SET); case WHILE: return whileStatement(EMPTY_LABEL_SET); case DO: return doWhileStatement(EMPTY_LABEL_SET); case CONTINUE: return continueStatement(); case BREAK: return breakStatement(); case RETURN: return returnStatement(); case WITH: return withStatement(); case SWITCH: return switchStatement(EMPTY_LABEL_SET); case THROW: return throwStatement(); case TRY: return tryStatement(); case DEBUGGER: return debuggerStatement(); case LET: if (isEnabled(Option.LetStatement)) { return letStatement(); } break; case YIELD: if (!isYieldName()) { break; } // fall-through case NAME: if (LOOKAHEAD(Token.COLON)) { return labelledStatement(); } default: } return expressionStatement(); } /** * <strong>[13.1] Block</strong> * * <pre> * BlockStatement : * Block * Block : * { StatementList<sub>opt</sub> } * </pre> */ private BlockStatement block(List<Binding> inherited) { long sourcePos = ts.sourcePosition(); consume(Token.LC); BlockContext scope = enterBlockContext(); if (!inherited.isEmpty()) { addLexDeclaredNames(inherited); } List<StatementListItem> list = statementList(Token.RC); if (!inherited.isEmpty()) { removeLexDeclaredNames(inherited); } exitBlockContext(); consume(Token.RC); BlockStatement block = new BlockStatement(sourcePos, scope, list); scope.node = block; return block; } /** * <strong>[13.1] Block</strong> * * <pre> * StatementList : * StatementItem * StatementList StatementListItem * </pre> */ private List<StatementListItem> statementList(Token end) { List<StatementListItem> list = newList(); while (token() != end) { list.add(statementListItem()); } return list; } /** * <strong>[13.1] Block</strong> * * <pre> * StatementListItem : * Statement * Declaration * Declaration : * FunctionDeclaration * GeneratorDeclaration * ClassDeclaration * LexicalDeclaration * </pre> */ private StatementListItem statementListItem() { switch (token()) { case LET: if (LOOKAHEAD(Token.LP) && (isEnabled(Option.LetStatement) || isEnabled(Option.LetExpression))) { return statement(); } case FUNCTION: case CLASS: case CONST: return declaration(); default: return statement(); } } /** * <strong>[13.1] Block</strong> * * <pre> * Declaration : * FunctionDeclaration * GeneratorDeclaration * ClassDeclaration * LexicalDeclaration * </pre> */ private Declaration declaration() { switch (token()) { case FUNCTION: return functionOrGeneratorDeclaration(); case CLASS: return classDeclaration(); case LET: case CONST: return lexicalDeclaration(true); default: throw reportSyntaxError(Messages.Key.InvalidToken, token().toString()); } } private Declaration functionOrGeneratorDeclaration() { if (LOOKAHEAD(Token.MUL)) { return generatorDeclaration(false); } else { long position = ts.position(), lineinfo = ts.lineinfo(); try { return functionDeclaration(); } catch (RetryGenerator e) { ts.reset(position, lineinfo); return generatorDeclaration(true); } } } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * LexicalDeclaration : * LetOrConst BindingList ; * LexicalDeclarationNoIn : * LetOrConst BindingListNoIn * LetOrConst : * let * const * </pre> */ private LexicalDeclaration lexicalDeclaration(boolean allowIn) { long sourcePos = ts.sourcePosition(); LexicalDeclaration.Type type; if (token() == Token.LET) { consume(Token.LET); type = LexicalDeclaration.Type.Let; } else { consume(Token.CONST); type = LexicalDeclaration.Type.Const; } List<LexicalBinding> list = bindingList((type == LexicalDeclaration.Type.Const), allowIn); if (allowIn) { semicolon(); } LexicalDeclaration decl = new LexicalDeclaration(sourcePos, type, list); addLexScopedDeclaration(decl); return decl; } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * BindingList : * LexicalBinding * BindingList, LexicalBinding * BindingListNoIn : * LexicalBindingNoIn * BindingListNoIn, LexicalBindingNoIn * </pre> */ private List<LexicalBinding> bindingList(boolean isConst, boolean allowIn) { List<LexicalBinding> list = newSmallList(); list.add(lexicalBinding(isConst, allowIn)); while (token() == Token.COMMA) { consume(Token.COMMA); list.add(lexicalBinding(isConst, allowIn)); } return list; } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * LexicalBinding : * BindingIdentifier Initialiser<sub>opt</sub> * BindingPattern Initialiser * LexicalBindingNoIn : * BindingIdentifier InitialiserNoIn<sub>opt</sub> * BindingPattern InitialiserNoIn * </pre> */ private LexicalBinding lexicalBinding(boolean isConst, boolean allowIn) { long sourcePos = ts.sourcePosition(); Binding binding; Expression initialiser = null; if (token() == Token.LC || token() == Token.LB) { BindingPattern bindingPattern = bindingPattern(); addLexDeclaredName(bindingPattern); if (allowIn) { initialiser = initialiser(allowIn); } else if (token() == Token.ASSIGN) { // make initialiser optional if `allowIn == false` initialiser = initialiser(allowIn); } binding = bindingPattern; } else { BindingIdentifier bindingIdentifier = bindingIdentifier(); addLexDeclaredName(bindingIdentifier); if (token() == Token.ASSIGN) { initialiser = initialiser(allowIn); } else if (isConst && allowIn) { // `allowIn == false` indicates for-loop, cf. validateFor{InOf} reportSyntaxError(bindingIdentifier, Messages.Key.ConstMissingInitialiser); } binding = bindingIdentifier; } return new LexicalBinding(sourcePos, binding, initialiser); } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * BindingIdentifier : * Identifier * </pre> */ private BindingIdentifier bindingIdentifier() { long sourcePos = ts.sourcePosition(); String identifier = identifier(); if (context.strictMode != StrictMode.NonStrict) { if ("arguments".equals(identifier) || "eval".equals(identifier)) { reportStrictModeSyntaxError(sourcePos, Messages.Key.StrictModeRestrictedIdentifier); } } return new BindingIdentifier(sourcePos, identifier); } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * BindingIdentifier : * Identifier * </pre> */ private BindingIdentifier bindingIdentifierStrict() { long sourcePos = ts.sourcePosition(); String identifier = identifier(); if ("arguments".equals(identifier) || "eval".equals(identifier)) { reportSyntaxError(sourcePos, Messages.Key.StrictModeRestrictedIdentifier); } return new BindingIdentifier(sourcePos, identifier); } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * BindingIdentifier : * Identifier * </pre> */ private BindingIdentifier bindingIdentifierPureStrict() { long sourcePos = ts.sourcePosition(); String identifier = strictIdentifier(); if ("arguments".equals(identifier) || "eval".equals(identifier)) { reportSyntaxError(sourcePos, Messages.Key.StrictModeRestrictedIdentifier); } return new BindingIdentifier(sourcePos, identifier); } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * Initialiser : * = AssignmentExpression * InitialiserNoIn : * = AssignmentExpressionNoIn * </pre> */ private Expression initialiser(boolean allowIn) { consume(Token.ASSIGN); return assignmentExpression(allowIn); } /** * <strong>[13.2.2] Variable Statement</strong> * * <pre> * VariableStatement : * var VariableDeclarationList ; * </pre> */ private VariableStatement variableStatement() { long sourcePos = ts.sourcePosition(); consume(Token.VAR); List<VariableDeclaration> decls = variableDeclarationList(true); semicolon(); VariableStatement varStmt = new VariableStatement(sourcePos, decls); addVarScopedDeclaration(varStmt); return varStmt; } /** * <strong>[13.2.2] Variable Statement</strong> * * <pre> * VariableDeclarationList : * VariableDeclaration * VariableDeclarationList , VariableDeclaration * VariableDeclarationListNoIn : * VariableDeclarationNoIn * VariableDeclarationListNoIn , VariableDeclarationNoIn * </pre> */ private List<VariableDeclaration> variableDeclarationList(boolean allowIn) { List<VariableDeclaration> list = newSmallList(); list.add(variableDeclaration(allowIn)); while (token() == Token.COMMA) { consume(Token.COMMA); list.add(variableDeclaration(allowIn)); } return list; } /** * <strong>[13.2.2] Variable Statement</strong> * * <pre> * VariableDeclaration : * BindingIdentifier Initialiser<sub>opt</sub> * BindingPattern Initialiser * VariableDeclarationNoIn : * BindingIdentifier InitialiserNoIn<sub>opt</sub> * BindingPattern InitialiserNoIn * </pre> */ private VariableDeclaration variableDeclaration(boolean allowIn) { Binding binding; Expression initialiser = null; if (token() == Token.LC || token() == Token.LB) { BindingPattern bindingPattern = bindingPattern(); addVarDeclaredName(bindingPattern); if (allowIn) { initialiser = initialiser(allowIn); } else if (token() == Token.ASSIGN) { // make initialiser optional if `allowIn == false` initialiser = initialiser(allowIn); } binding = bindingPattern; } else { BindingIdentifier bindingIdentifier = bindingIdentifier(); addVarDeclaredName(bindingIdentifier); if (token() == Token.ASSIGN) { initialiser = initialiser(allowIn); } binding = bindingIdentifier; } return new VariableDeclaration(binding, initialiser); } /** * <strong>[13.2.4] Destructuring Binding Patterns</strong> * * <pre> * BindingPattern : * ObjectBindingPattern * ArrayBindingPattern * </pre> */ private BindingPattern bindingPattern() { if (token() == Token.LC) { return objectBindingPattern(); } else { return arrayBindingPattern(); } } /** * <strong>[13.2.4] Destructuring Binding Patterns</strong> * * <pre> * ObjectBindingPattern : * { } * { BindingPropertyList } * { BindingPropertyList , } * BindingPropertyList : * BindingProperty * BindingPropertyList , BindingProperty * BindingProperty : * SingleNameBinding * PropertyName : BindingElement * BindingElement : * SingleNameBinding * BindingPattern Initialiser<sub>opt</sub> * SingleNameBinding : * BindingIdentifier Initialiser<sub>opt</sub> * PropertyName : * IdentifierName * StringLiteral * NumericLiteral * </pre> */ private ObjectBindingPattern objectBindingPattern() { long sourcePos = ts.sourcePosition(); List<BindingProperty> list = newSmallList(); consume(Token.LC); while (token() != Token.RC) { list.add(bindingProperty()); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } consume(Token.RC); objectBindingPattern_StaticSemantics(list); return new ObjectBindingPattern(sourcePos, list); } /** * <strong>[13.2.4] Destructuring Binding Patterns</strong> * * <pre> * BindingProperty : * SingleNameBinding * PropertyName : BindingElement * BindingElement : * SingleNameBinding * BindingPattern Initialiser<sub>opt</sub> * SingleNameBinding : * BindingIdentifier Initialiser<sub>opt</sub> * BindingIdentifier : * Identifier * </pre> */ private BindingProperty bindingProperty() { if (token() == Token.LB || LOOKAHEAD(Token.COLON)) { PropertyName propertyName = propertyName(); consume(Token.COLON); Binding binding; if (token() == Token.LC) { binding = objectBindingPattern(); } else if (token() == Token.LB) { binding = arrayBindingPattern(); } else { binding = bindingIdentifierStrict(); } Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingProperty(propertyName, binding, initialiser); } else { BindingIdentifier binding = bindingIdentifierStrict(); Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingProperty(binding, initialiser); } } /** * <strong>[13.2.4] Destructuring Binding Patterns</strong> * * <pre> * ArrayBindingPattern : * [ Elision<sub>opt</sub> BindingRestElement<sub>opt</sub> ] * [ BindingElementList ] * [ BindingElementList , Elision<sub>opt</sub> BindingRestElement<sub>opt</sub> ] * BindingElementList : * Elision<sub>opt</sub> BindingElement * BindingElementList , Elision<sub>opt</sub> BindingElement * BindingRestElement : * ... BindingIdentifier * </pre> */ private ArrayBindingPattern arrayBindingPattern() { long sourcePos = ts.sourcePosition(); List<BindingElementItem> list = newSmallList(); consume(Token.LB); boolean needComma = false; Token tok; while ((tok = token()) != Token.RB) { if (needComma) { consume(Token.COMMA); needComma = false; } else if (tok == Token.COMMA) { consume(Token.COMMA); list.add(new BindingElision(0)); } else if (tok == Token.TRIPLE_DOT) { long sourcePosRest = ts.sourcePosition(); consume(Token.TRIPLE_DOT); list.add(new BindingRestElement(sourcePosRest, bindingIdentifierStrict())); break; } else { list.add(bindingElementStrict()); needComma = true; } } consume(Token.RB); arrayBindingPattern_StaticSemantics(list); return new ArrayBindingPattern(sourcePos, list); } /** * <pre> * Binding : * BindingIdentifier * BindingPattern * </pre> */ private Binding binding() { switch (token()) { case LC: return objectBindingPattern(); case LB: return arrayBindingPattern(); default: return bindingIdentifier(); } } /** * <pre> * Binding : * BindingIdentifier * BindingPattern * </pre> */ private Binding bindingStrict() { switch (token()) { case LC: return objectBindingPattern(); case LB: return arrayBindingPattern(); default: return bindingIdentifierStrict(); } } /** * <strong>[13.2.4] Destructuring Binding Patterns</strong> * * <pre> * BindingElement : * SingleNameBinding * BindingPattern Initialiser<sub>opt</sub> * SingleNameBinding : * BindingIdentifier Initialiser<sub>opt</sub> * </pre> */ private BindingElement bindingElement() { long sourcePos = ts.sourcePosition(); Binding binding = binding(); Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingElement(sourcePos, binding, initialiser); } /** * <strong>[13.2.4] Destructuring Binding Patterns</strong> * * <pre> * BindingElement : * SingleNameBinding * BindingPattern Initialiser<sub>opt</sub> * SingleNameBinding : * BindingIdentifier Initialiser<sub>opt</sub> * </pre> */ private BindingElement bindingElementStrict() { long sourcePos = ts.sourcePosition(); Binding binding = bindingStrict(); Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingElement(sourcePos, binding, initialiser); } private static String BoundName(BindingIdentifier binding) { return binding.getName(); } private static String BoundName(BindingRestElement element) { return element.getBindingIdentifier().getName(); } private void objectBindingPattern_StaticSemantics(List<BindingProperty> list) { for (BindingProperty property : list) { // BindingProperty : PropertyName ':' BindingElement // BindingProperty : BindingIdentifier Initialiser<opt> Binding binding = property.getBinding(); if (binding instanceof BindingIdentifier) { String name = BoundName(((BindingIdentifier) binding)); if ("arguments".equals(name) || "eval".equals(name)) { reportSyntaxError(binding, Messages.Key.StrictModeRestrictedIdentifier); } } else { assert binding instanceof BindingPattern; assert property.getPropertyName() != null; // already done implicitly // objectBindingPattern_StaticSemantics(((ObjectBindingPattern) binding).getList()); // arrayBindingPattern_StaticSemantics(((ArrayBindingPattern) // binding).getElements()); } } } private void arrayBindingPattern_StaticSemantics(List<BindingElementItem> list) { for (BindingElementItem element : list) { if (element instanceof BindingElement) { Binding binding = ((BindingElement) element).getBinding(); if (binding instanceof ArrayBindingPattern) { // already done implicitly // arrayBindingPattern_StaticSemantics(((ArrayBindingPattern) binding) // .getElements()); } else if (binding instanceof ObjectBindingPattern) { // already done implicitly // objectBindingPattern_StaticSemantics(((ObjectBindingPattern) // binding).getList()); } else { assert (binding instanceof BindingIdentifier); String name = BoundName(((BindingIdentifier) binding)); if ("arguments".equals(name) || "eval".equals(name)) { reportSyntaxError(binding, Messages.Key.StrictModeRestrictedIdentifier); } } } else if (element instanceof BindingRestElement) { String name = BoundName(((BindingRestElement) element)); if ("arguments".equals(name) || "eval".equals(name)) { reportSyntaxError(element, Messages.Key.StrictModeRestrictedIdentifier); } } else { assert element instanceof BindingElision; } } } /** * <strong>[13.3] Empty Statement</strong> * * <pre> * EmptyStatement: * ; * </pre> */ private EmptyStatement emptyStatement() { consume(Token.SEMI); return new EmptyStatement(0); } /** * <strong>[13.4] Expression Statement</strong> * * <pre> * ExpressionStatement : * [LA &#x2209; { <b>{, function, class</b> }] Expression ; * </pre> */ private ExpressionStatement expressionStatement() { switch (token()) { case LC: case FUNCTION: case CLASS: reportSyntaxError(Messages.Key.InvalidToken, token().toString()); default: Expression expr = expression(true); semicolon(); return new ExpressionStatement(expr); } } /** * <strong>[13.5] The <code>if</code> Statement</strong> * * <pre> * IfStatement : * if ( Expression ) Statement else Statement * if ( Expression ) Statement * </pre> */ private IfStatement ifStatement() { long sourcePos = ts.sourcePosition(); consume(Token.IF); consume(Token.LP); Expression test = expression(true); consume(Token.RP); Statement then = statement(); Statement otherwise = null; if (token() == Token.ELSE) { consume(Token.ELSE); otherwise = statement(); } return new IfStatement(sourcePos, test, then, otherwise); } /** * <strong>[13.6.1] The <code>do-while</code> Statement</strong> * * <pre> * IterationStatement : * do Statement while ( Expression ) ;<sub>opt</sub> * </pre> */ private DoWhileStatement doWhileStatement(Set<String> labelSet) { long sourcePos = ts.sourcePosition(); consume(Token.DO); LabelContext labelCx = enterIteration(sourcePos, labelSet); Statement stmt = statement(); exitIteration(); consume(Token.WHILE); consume(Token.LP); Expression test = expression(true); consume(Token.RP); if (token() == Token.SEMI) { consume(Token.SEMI); } return new DoWhileStatement(sourcePos, labelCx.abrupts, labelCx.labelSet, test, stmt); } /** * <strong>[13.6.2] The <code>while</code> Statement</strong> * * <pre> * IterationStatement : * while ( Expression ) Statement * </pre> */ private WhileStatement whileStatement(Set<String> labelSet) { long sourcePos = ts.sourcePosition(); consume(Token.WHILE); consume(Token.LP); Expression test = expression(true); consume(Token.RP); LabelContext labelCx = enterIteration(sourcePos, labelSet); Statement stmt = statement(); exitIteration(); return new WhileStatement(sourcePos, labelCx.abrupts, labelCx.labelSet, test, stmt); } /** * <strong>[13.6.3] The <code>for</code> Statement</strong> <br> * <strong>[13.6.4] The <code>for-in</code> and <code>for-of</code> Statements</strong> * * <pre> * IterationStatement : * for ( ExpressionNoIn<sub>opt</sub> ; Expression<sub>opt</sub> ; Expression <sub>opt</sub> ) Statement * for ( var VariableDeclarationListNoIn ; Expression<sub>opt</sub> ; Expression <sub>opt</sub> ) Statement * for ( LexicalDeclarationNoIn ; Expression<sub>opt</sub> ; Expression <sub>opt</sub> ) Statement * for ( LeftHandSideExpression in Expression ) Statement * for ( var ForBinding in Expression ) Statement * for ( ForDeclaration in Expression ) Statement * for ( LeftHandSideExpression of Expression ) Statement * for ( var ForBinding of Expression ) Statement * for ( ForDeclaration of Expression ) Statement * ForDeclaration : * LetOrConst ForBinding * ForBinding : * BindingIdentifier * BindingPattern * </pre> */ private IterationStatement forStatement(Set<String> labelSet) { long sourcePos = ts.sourcePosition(); consume(Token.FOR); boolean each = false; if (token() != Token.LP && isName("each") && isEnabled(Option.ForEachStatement)) { consume("each"); each = true; } consume(Token.LP); BlockContext lexBlockContext = null; Node head; switch (token()) { case VAR: long sourcePosVar = ts.sourcePosition(); consume(Token.VAR); VariableStatement varStmt = new VariableStatement(sourcePosVar, variableDeclarationList(false)); addVarScopedDeclaration(varStmt); head = varStmt; break; case LET: case CONST: lexBlockContext = enterBlockContext(); head = lexicalDeclaration(false); break; case SEMI: head = null; break; default: head = expression(false); break; } if (each && token() != Token.IN) { reportTokenMismatch(Token.IN, token()); } if (token() == Token.SEMI) { head = validateFor(head); consume(Token.SEMI); Expression test = null; if (token() != Token.SEMI) { test = expression(true); } consume(Token.SEMI); Expression step = null; if (token() != Token.RP) { step = expression(true); } consume(Token.RP); LabelContext labelCx = enterIteration(sourcePos, labelSet); Statement stmt = statement(); exitIteration(); if (lexBlockContext != null) { exitBlockContext(); } ForStatement iteration = new ForStatement(sourcePos, lexBlockContext, labelCx.abrupts, labelCx.labelSet, head, test, step, stmt); if (lexBlockContext != null) { lexBlockContext.node = iteration; } return iteration; } else if (token() == Token.IN) { head = validateForInOf(head); consume(Token.IN); Expression expr; if (lexBlockContext == null) { expr = expression(true); } else { exitBlockContext(); expr = expression(true); reenterBlockContext(lexBlockContext); } consume(Token.RP); LabelContext labelCx = enterIteration(sourcePos, labelSet); Statement stmt = statement(); exitIteration(); if (lexBlockContext != null) { exitBlockContext(); } if (each) { ForEachStatement iteration = new ForEachStatement(sourcePos, lexBlockContext, labelCx.abrupts, labelCx.labelSet, head, expr, stmt); if (lexBlockContext != null) { lexBlockContext.node = iteration; } return iteration; } else { ForInStatement iteration = new ForInStatement(sourcePos, lexBlockContext, labelCx.abrupts, labelCx.labelSet, head, expr, stmt); if (lexBlockContext != null) { lexBlockContext.node = iteration; } return iteration; } } else { head = validateForInOf(head); consume("of"); Expression expr; if (lexBlockContext == null) { expr = assignmentExpression(true); } else { exitBlockContext(); expr = assignmentExpression(true); reenterBlockContext(lexBlockContext); } consume(Token.RP); LabelContext labelCx = enterIteration(sourcePos, labelSet); Statement stmt = statement(); exitIteration(); if (lexBlockContext != null) { exitBlockContext(); } ForOfStatement iteration = new ForOfStatement(sourcePos, lexBlockContext, labelCx.abrupts, labelCx.labelSet, head, expr, stmt); if (lexBlockContext != null) { lexBlockContext.node = iteration; } return iteration; } } /** * @see #forStatement(Set) */ private Node validateFor(Node head) { if (head instanceof VariableStatement) { for (VariableDeclaration decl : ((VariableStatement) head).getElements()) { if (decl.getBinding() instanceof BindingPattern && decl.getInitialiser() == null) { reportSyntaxError(head, Messages.Key.DestructuringMissingInitialiser); } } } else if (head instanceof LexicalDeclaration) { boolean isConst = ((LexicalDeclaration) head).getType() == LexicalDeclaration.Type.Const; for (LexicalBinding decl : ((LexicalDeclaration) head).getElements()) { if (decl.getBinding() instanceof BindingPattern && decl.getInitialiser() == null) { reportSyntaxError(head, Messages.Key.DestructuringMissingInitialiser); } if (isConst && decl.getInitialiser() == null) { reportSyntaxError(head, Messages.Key.ConstMissingInitialiser); } } } return head; } /** * @see #forStatement(Set) */ private Node validateForInOf(Node head) { if (head instanceof VariableStatement) { // expected: single variable declaration with no initialiser List<VariableDeclaration> elements = ((VariableStatement) head).getElements(); if (elements.size() == 1 && elements.get(0).getInitialiser() == null) { return head; } } else if (head instanceof LexicalDeclaration) { // expected: single lexical binding with no initialiser List<LexicalBinding> elements = ((LexicalDeclaration) head).getElements(); if (elements.size() == 1 && elements.get(0).getInitialiser() == null) { return head; } } else if (head instanceof Expression) { // expected: left-hand side expression return validateAssignment((Expression) head, ExceptionType.SyntaxError, Messages.Key.InvalidAssignmentTarget); } throw reportSyntaxError(head, Messages.Key.InvalidForInOfHead); } /** * Static Semantics: IsValidSimpleAssignmentTarget */ private LeftHandSideExpression validateSimpleAssignment(Expression lhs, ExceptionType type, Messages.Key messageKey) { if (lhs instanceof Identifier) { if (context.strictMode != StrictMode.NonStrict) { String name = ((Identifier) lhs).getName(); if ("eval".equals(name) || "arguments".equals(name)) { reportStrictModeSyntaxError(lhs, Messages.Key.StrictModeInvalidAssignmentTarget); } } return (Identifier) lhs; } else if (lhs instanceof ElementAccessor) { return (ElementAccessor) lhs; } else if (lhs instanceof PropertyAccessor) { return (PropertyAccessor) lhs; } else if (lhs instanceof SuperExpression) { SuperExpression superExpr = (SuperExpression) lhs; if (superExpr.getExpression() != null || superExpr.getName() != null) { return superExpr; } } // everything else => invalid lhs throw reportError(type, lhs.getLine(), lhs.getColumn(), messageKey); } /** * Static Semantics: IsValidSimpleAssignmentTarget */ private LeftHandSideExpression validateAssignment(Expression lhs, ExceptionType type, Messages.Key messageKey) { // rewrite object/array literal to destructuring form if (lhs instanceof ObjectLiteral) { return toDestructuring((ObjectLiteral) lhs); } else if (lhs instanceof ArrayLiteral) { return toDestructuring((ArrayLiteral) lhs); } return validateSimpleAssignment(lhs, type, messageKey); } private ObjectAssignmentPattern toDestructuring(ObjectLiteral object) { List<AssignmentProperty> list = newSmallList(); for (PropertyDefinition p : object.getProperties()) { AssignmentProperty property; if (p instanceof PropertyValueDefinition) { // AssignmentProperty : PropertyName ':' AssignmentElement // AssignmentElement : DestructuringAssignmentTarget Initialiser{opt} // DestructuringAssignmentTarget : LeftHandSideExpression PropertyValueDefinition def = (PropertyValueDefinition) p; PropertyName propertyName = def.getPropertyName(); Expression propertyValue = def.getPropertyValue(); LeftHandSideExpression target; Expression initialiser; if (propertyValue instanceof AssignmentExpression) { AssignmentExpression assignment = (AssignmentExpression) propertyValue; if (assignment.getOperator() != AssignmentExpression.Operator.ASSIGN) { reportSyntaxError(p, Messages.Key.InvalidDestructuring); } target = destructuringAssignmentTarget(assignment.getLeft()); initialiser = assignment.getRight(); } else { target = destructuringAssignmentTarget(propertyValue); initialiser = null; } property = new AssignmentProperty(p.getSourcePosition(), propertyName, target, initialiser); } else if (p instanceof PropertyNameDefinition) { // AssignmentProperty : Identifier PropertyNameDefinition def = (PropertyNameDefinition) p; property = assignmentProperty(def.getPropertyName(), null); } else if (p instanceof CoverInitialisedName) { // AssignmentProperty : Identifier Initialiser CoverInitialisedName def = (CoverInitialisedName) p; property = assignmentProperty(def.getPropertyName(), def.getInitialiser()); } else { assert p instanceof MethodDefinition; throw reportSyntaxError(p, Messages.Key.InvalidDestructuring); } list.add(property); } context.removeLiteral(object); ObjectAssignmentPattern pattern = new ObjectAssignmentPattern(object.getSourcePosition(), list); if (object.isParenthesised()) { pattern.addParentheses(); } return pattern; } private ArrayAssignmentPattern toDestructuring(ArrayLiteral array) { List<AssignmentElementItem> list = newSmallList(); for (Iterator<Expression> iterator = array.getElements().iterator(); iterator.hasNext();) { Expression e = iterator.next(); AssignmentElementItem element; if (e instanceof Elision) { // Elision element = (Elision) e; } else if (e instanceof SpreadElement) { // AssignmentRestElement : ... DestructuringAssignmentTarget // DestructuringAssignmentTarget : LeftHandSideExpression Expression expression = ((SpreadElement) e).getExpression(); LeftHandSideExpression target = destructuringSimpleAssignmentTarget(expression); element = new AssignmentRestElement(e.getSourcePosition(), target); // no further elements after AssignmentRestElement allowed if (iterator.hasNext()) { reportSyntaxError(iterator.next(), Messages.Key.InvalidDestructuring); } } else { // AssignmentElement : DestructuringAssignmentTarget Initialiser{opt} // DestructuringAssignmentTarget : LeftHandSideExpression LeftHandSideExpression target; Expression initialiser; if (e instanceof AssignmentExpression) { AssignmentExpression assignment = (AssignmentExpression) e; if (assignment.getOperator() != AssignmentExpression.Operator.ASSIGN) { reportSyntaxError(e, Messages.Key.InvalidDestructuring); } target = destructuringAssignmentTarget(assignment.getLeft()); initialiser = assignment.getRight(); } else { target = destructuringAssignmentTarget(e); initialiser = null; } element = new AssignmentElement(e.getSourcePosition(), target, initialiser); } list.add(element); } ArrayAssignmentPattern pattern = new ArrayAssignmentPattern(array.getSourcePosition(), list); if (array.isParenthesised()) { pattern.addParentheses(); } return pattern; } private LeftHandSideExpression destructuringAssignmentTarget(Expression lhs) { return destructuringAssignmentTarget(lhs, true); } private LeftHandSideExpression destructuringSimpleAssignmentTarget(Expression lhs) { return destructuringAssignmentTarget(lhs, false); } private LeftHandSideExpression destructuringAssignmentTarget(Expression lhs, boolean extended) { if (lhs instanceof Identifier) { String name = ((Identifier) lhs).getName(); if ("eval".equals(name) || "arguments".equals(name)) { reportSyntaxError(lhs, Messages.Key.InvalidAssignmentTarget); } return (Identifier) lhs; } else if (lhs instanceof ElementAccessor) { return (ElementAccessor) lhs; } else if (lhs instanceof PropertyAccessor) { return (PropertyAccessor) lhs; } else if (extended && lhs instanceof ObjectAssignmentPattern) { return (ObjectAssignmentPattern) lhs; } else if (extended && lhs instanceof ArrayAssignmentPattern) { return (ArrayAssignmentPattern) lhs; } else if (extended && lhs instanceof ObjectLiteral) { return toDestructuring((ObjectLiteral) lhs); } else if (extended && lhs instanceof ArrayLiteral) { return toDestructuring((ArrayLiteral) lhs); } else if (lhs instanceof SuperExpression) { SuperExpression superExpr = (SuperExpression) lhs; if (superExpr.getExpression() != null || superExpr.getName() != null) { return superExpr; } } // FIXME: spec bug (IsInvalidAssignmentPattern not defined) (Bug 716) // everything else => invalid lhs throw reportSyntaxError(lhs, Messages.Key.InvalidDestructuring); } private AssignmentProperty assignmentProperty(Identifier identifier, Expression initialiser) { switch (identifier.getName()) { case "eval": case "arguments": case "this": case "super": reportSyntaxError(identifier, Messages.Key.InvalidDestructuring); } return new AssignmentProperty(identifier.getSourcePosition(), identifier, initialiser); } /** * <strong>[13.7] The <code>continue</code> Statement</strong> * * <pre> * ContinueStatement : * continue ; * continue [no <i>LineTerminator</i> here] Identifier ; * </pre> */ private ContinueStatement continueStatement() { long sourcePos = ts.sourcePosition(); String label; consume(Token.CONTINUE); if (noLineTerminator() && isIdentifier(token())) { label = identifier(); } else { label = null; } semicolon(); LabelContext target = findContinueTarget(label); if (target == null) { if (label == null) { reportSyntaxError(sourcePos, Messages.Key.InvalidContinueTarget); } else { reportSyntaxError(sourcePos, Messages.Key.LabelTargetNotFound, label); } } if (target.type != StatementType.Iteration) { reportSyntaxError(sourcePos, Messages.Key.InvalidContinueTarget); } target.mark(Abrupt.Continue); return new ContinueStatement(sourcePos, label); } /** * <strong>[13.8] The <code>break</code> Statement</strong> * * <pre> * BreakStatement : * break ; * break [no <i>LineTerminator</i> here] Identifier ; * </pre> */ private BreakStatement breakStatement() { long sourcePos = ts.sourcePosition(); String label; consume(Token.BREAK); if (noLineTerminator() && isIdentifier(token())) { label = identifier(); } else { label = null; } semicolon(); LabelContext target = findBreakTarget(label); if (target == null) { if (label == null) { reportSyntaxError(sourcePos, Messages.Key.InvalidBreakTarget); } else { reportSyntaxError(sourcePos, Messages.Key.LabelTargetNotFound, label); } } target.mark(Abrupt.Break); return new BreakStatement(sourcePos, label); } /** * <strong>[13.9] The <code>return</code> Statement</strong> * * <pre> * ReturnStatement : * return ; * return [no <i>LineTerminator</i> here] Expression ; * </pre> */ private ReturnStatement returnStatement() { if (!context.returnAllowed) { reportSyntaxError(Messages.Key.InvalidReturnStatement); } long sourcePos = ts.sourcePosition(); Expression expr = null; consume(Token.RETURN); if (noLineTerminator() && !(token() == Token.SEMI || token() == Token.RC || token() == Token.EOF)) { expr = expression(true); } semicolon(); return new ReturnStatement(sourcePos, expr); } /** * <strong>[13.10] The <code>with</code> Statement</strong> * * <pre> * WithStatement : * with ( Expression ) Statement * </pre> */ private WithStatement withStatement() { long sourcePos = ts.sourcePosition(); reportStrictModeSyntaxError(sourcePos, Messages.Key.StrictModeWithStatement); consume(Token.WITH); consume(Token.LP); Expression expr = expression(true); consume(Token.RP); BlockContext scope = enterWithContext(); Statement stmt = statement(); exitWithContext(); WithStatement withStatement = new WithStatement(sourcePos, scope, expr, stmt); scope.node = withStatement; return withStatement; } /** * <strong>[13.11] The <code>switch</code> Statement</strong> * * <pre> * SwitchStatement : * switch ( Expression ) CaseBlock * CaseBlock : * { CaseClauses<sub>opt</sub> } * { CaseClauses<sub>opt</sub> DefaultClause CaseClauses<sub>opt</sub> } * CaseClauses : * CaseClause * CaseClauses CaseClause * CaseClause : * case Expression : StatementList<sub>opt</sub> * DefaultClause : * default : StatementList<sub>opt</sub> * </pre> */ private SwitchStatement switchStatement(Set<String> labelSet) { List<SwitchClause> clauses = newList(); long sourcePos = ts.sourcePosition(); consume(Token.SWITCH); consume(Token.LP); Expression expr = expression(true); consume(Token.RP); consume(Token.LC); LabelContext labelCx = enterBreakable(sourcePos, labelSet); BlockContext scope = enterBlockContext(); boolean hasDefault = false; for (;;) { long sourcePosClause = ts.sourcePosition(); Expression caseExpr; Token tok = token(); if (tok == Token.CASE) { consume(Token.CASE); caseExpr = expression(true); consume(Token.COLON); } else if (tok == Token.DEFAULT && !hasDefault) { hasDefault = true; consume(Token.DEFAULT); consume(Token.COLON); caseExpr = null; } else { break; } List<StatementListItem> list = newList(); statementlist: for (;;) { switch (token()) { case CASE: case DEFAULT: case RC: break statementlist; default: list.add(statementListItem()); } } clauses.add(new SwitchClause(sourcePosClause, caseExpr, list)); } exitBlockContext(); exitBreakable(); consume(Token.RC); SwitchStatement switchStatement = new SwitchStatement(sourcePos, scope, labelCx.abrupts, labelCx.labelSet, expr, clauses); scope.node = switchStatement; return switchStatement; } /** * <strong>[13.12] Labelled Statements</strong> * * <pre> * LabelledStatement : * Identifier : Statement * </pre> */ private Statement labelledStatement() { long sourcePos = ts.sourcePosition(); HashSet<String> labelSet = new HashSet<>(4); labels: for (;;) { switch (token()) { case FOR: return forStatement(labelSet); case WHILE: return whileStatement(labelSet); case DO: return doWhileStatement(labelSet); case SWITCH: return switchStatement(labelSet); case YIELD: if (!isYieldName()) { break labels; } // fall-through case NAME: if (LOOKAHEAD(Token.COLON)) { long sourcePosLabel = ts.sourcePosition(); String name = identifier(); consume(Token.COLON); if (!labelSet.add(name)) { reportSyntaxError(sourcePosLabel, Messages.Key.DuplicateLabel, name); } break; } case LC: case VAR: case SEMI: case IF: case CONTINUE: case BREAK: case RETURN: case WITH: case THROW: case TRY: case DEBUGGER: default: break labels; } } assert !labelSet.isEmpty(); LabelContext labelCx = enterLabelled(sourcePos, StatementType.Statement, labelSet); Statement stmt = statement(); exitLabelled(); return new LabelledStatement(sourcePos, labelCx.abrupts, labelCx.labelSet, stmt); } /** * <strong>[13.13] The <code>throw</code> Statement</strong> * * <pre> * ThrowStatement : * throw [no <i>LineTerminator</i> here] Expression ; * </pre> */ private ThrowStatement throwStatement() { long sourcePos = ts.sourcePosition(); consume(Token.THROW); if (!noLineTerminator()) { reportSyntaxError(Messages.Key.UnexpectedEndOfLine); } Expression expr = expression(true); semicolon(); return new ThrowStatement(sourcePos, expr); } /** * <strong>[13.14] The <code>try</code> Statement</strong> * * <pre> * TryStatement : * try Block Catch * try Block Finally * try Block Catch Finally * Catch : * catch ( CatchParameter ) Block * Finally : * finally Block * CatchParameter : * BindingIdentifier * BindingPattern * </pre> */ private TryStatement tryStatement() { BlockStatement tryBlock, finallyBlock = null; CatchNode catchNode = null; List<GuardedCatchNode> guardedCatchNodes = emptyList(); long sourcePos = ts.sourcePosition(); consume(Token.TRY); tryBlock = block(NO_INHERITED_BINDING); Token tok = token(); if (tok == Token.CATCH) { if (isEnabled(Option.GuardedCatch)) { guardedCatchNodes = newSmallList(); while (token() == Token.CATCH && catchNode == null) { long sourcePosCatch = ts.sourcePosition(); consume(Token.CATCH); BlockContext catchScope = enterBlockContext(); consume(Token.LP); Binding catchParameter = binding(); addLexDeclaredName(catchParameter); Expression guard; if (token() == Token.IF) { consume(Token.IF); guard = expression(true); } else { guard = null; } consume(Token.RP); // catch-block receives a blacklist of forbidden lexical declarable names BlockStatement catchBlock = block(singletonList(catchParameter)); exitBlockContext(); if (guard != null) { GuardedCatchNode guardedCatchNode = new GuardedCatchNode(sourcePosCatch, catchScope, catchParameter, guard, catchBlock); catchScope.node = guardedCatchNode; guardedCatchNodes.add(guardedCatchNode); } else { catchNode = new CatchNode(sourcePosCatch, catchScope, catchParameter, catchBlock); catchScope.node = catchNode; } } } else { long sourcePosCatch = ts.sourcePosition(); consume(Token.CATCH); BlockContext catchScope = enterBlockContext(); consume(Token.LP); Binding catchParameter = binding(); addLexDeclaredName(catchParameter); consume(Token.RP); // catch-block receives a blacklist of forbidden lexical declarable names BlockStatement catchBlock = block(singletonList(catchParameter)); exitBlockContext(); catchNode = new CatchNode(sourcePosCatch, catchScope, catchParameter, catchBlock); catchScope.node = catchNode; } if (token() == Token.FINALLY) { consume(Token.FINALLY); finallyBlock = block(NO_INHERITED_BINDING); } } else { consume(Token.FINALLY); finallyBlock = block(NO_INHERITED_BINDING); } return new TryStatement(sourcePos, tryBlock, catchNode, guardedCatchNodes, finallyBlock); } /** * <strong>[13.15] The <code>debugger</code> Statement</strong> * * <pre> * DebuggerStatement : * debugger ; * </pre> */ private DebuggerStatement debuggerStatement() { long sourcePos = ts.sourcePosition(); consume(Token.DEBUGGER); semicolon(); return new DebuggerStatement(sourcePos); } /** * <strong>[Extension] The <code>let</code> Statement</strong> * * <pre> * LetStatement : * let ( BindingList ) BlockStatement * </pre> */ private Statement letStatement() { BlockContext scope = enterBlockContext(); long sourcePos = ts.sourcePosition(); consume(Token.LET); consume(Token.LP); List<LexicalBinding> bindings = bindingList(false, true); consume(Token.RP); if (token() != Token.LC && isEnabled(Option.LetExpression)) { // let expression disguised as let statement - also error in strict mode(!) reportStrictModeSyntaxError(sourcePos, Messages.Key.UnexpectedToken, token().toString()); Expression expression = assignmentExpression(true); exitBlockContext(); LetExpression letExpression = new LetExpression(sourcePos, scope, bindings, expression); scope.node = letExpression; return new ExpressionStatement(letExpression); } else { BlockStatement letBlock = block(toBindings(bindings)); exitBlockContext(); LetStatement block = new LetStatement(sourcePos, scope, bindings, letBlock); scope.node = block; return block; } } private List<Binding> toBindings(List<LexicalBinding> lexicalBindings) { ArrayList<Binding> bindings = new ArrayList<>(lexicalBindings.size()); for (LexicalBinding lexicalBinding : lexicalBindings) { bindings.add(lexicalBinding.getBinding()); } return bindings; } /** * <strong>[12.1] Primary Expressions</strong> * * <pre> * PrimaryExpresion : * this * Identifier * Literal * ArrayInitialiser * ObjectLiteral * FunctionExpression * ClassExpression * GeneratorExpression * GeneratorComprehension * RegularExpressionLiteral * TemplateLiteral * CoverParenthesisedExpressionAndArrowParameterList * Literal : * NullLiteral * ValueLiteral * ValueLiteral : * BooleanLiteral * NumericLiteral * StringLiteral * </pre> */ private Expression primaryExpression() { long sourcePos = ts.sourcePosition(); Token tok = token(); switch (tok) { case THIS: consume(tok); return new ThisExpression(sourcePos); case NULL: consume(tok); return new NullLiteral(sourcePos); case FALSE: case TRUE: consume(tok); return new BooleanLiteral(sourcePos, tok == Token.TRUE); case NUMBER: return new NumericLiteral(sourcePos, numericLiteral()); case STRING: return new StringLiteral(sourcePos, stringLiteral()); case DIV: case ASSIGN_DIV: return regularExpressionLiteral(tok); case LB: return arrayInitialiser(); case LC: return objectLiteral(); case FUNCTION: return functionOrGeneratorExpression(); case CLASS: return classExpression(); case LP: if (LOOKAHEAD(Token.FOR)) { return generatorComprehension(); } else { return coverParenthesisedExpressionAndArrowParameterList(); } case TEMPLATE: return templateLiteral(false); case LET: if (isEnabled(Option.LetExpression)) { return letExpression(); } default: return new Identifier(sourcePos, identifier()); } } private Expression functionOrGeneratorExpression() { if (LOOKAHEAD(Token.MUL)) { return generatorExpression(false); } else { long position = ts.position(), lineinfo = ts.lineinfo(); try { return functionExpression(); } catch (RetryGenerator e) { ts.reset(position, lineinfo); return generatorExpression(true); } } } /** * <strong>[12.1] Primary Expressions</strong> * * <pre> * CoverParenthesisedExpressionAndArrowParameterList : * ( Expression ) * ( ) * ( ... Identifier ) * ( Expression , ... Identifier) * </pre> */ private Expression coverParenthesisedExpressionAndArrowParameterList() { long position = ts.position(), lineinfo = ts.lineinfo(); consume(Token.LP); Expression expr; if (token() == Token.RP) { expr = arrowFunctionEmptyParameters(); } else if (token() == Token.TRIPLE_DOT) { expr = arrowFunctionRestParameter(); } else { // inlined `expression(true)` expr = assignmentExpressionNoValidation(true); if (token() == Token.FOR && isEnabled(Option.LegacyComprehension)) { ts.reset(position, lineinfo); return legacyGeneratorComprehension(); } if (token() == Token.COMMA) { List<Expression> list = new ArrayList<>(); list.add(expr); while (token() == Token.COMMA) { consume(Token.COMMA); if (token() == Token.TRIPLE_DOT) { list.add(arrowFunctionRestParameter()); break; } expr = assignmentExpression(true); list.add(expr); } expr = new CommaExpression(list); } } expr.addParentheses(); consume(Token.RP); return expr; } private EmptyExpression arrowFunctionEmptyParameters() { if (!(token() == Token.RP && LOOKAHEAD(Token.ARROW))) { reportSyntaxError(Messages.Key.EmptyParenthesisedExpression); } return new EmptyExpression(0); } private SpreadElement arrowFunctionRestParameter() { long sourcePos = ts.sourcePosition(); consume(Token.TRIPLE_DOT); SpreadElement spread = new SpreadElement(sourcePos, new Identifier(ts.sourcePosition(), identifier())); if (!(token() == Token.RP && LOOKAHEAD(Token.ARROW))) { reportSyntaxError(spread, Messages.Key.InvalidSpreadExpression); } return spread; } /** * <strong>[12.1.4] Array Initialiser</strong> * * <pre> * ArrayInitialiser : * ArrayLiteral * ArrayComprehension * </pre> */ private ArrayInitialiser arrayInitialiser() { if (LOOKAHEAD(Token.FOR)) { return arrayComprehension(); } else { long sourcePos = ts.sourcePosition(); if (isEnabled(Option.LegacyComprehension)) { switch (peek()) { case RB: case COMMA: case TRIPLE_DOT: break; default: // TODO: report eclipse formatter bug long position = ts.position(), lineinfo = ts.lineinfo(); consume(Token.LB); Expression expression = assignmentExpressionNoValidation(true); if (token() == Token.FOR) { ts.reset(position, lineinfo); return legacyArrayComprehension(); } return arrayLiteral(sourcePos, expression); } } return arrayLiteral(sourcePos, null); } } /** * <strong>[12.1.4] Array Initialiser</strong> * * <pre> * ArrayLiteral : * [ Elision<sub>opt</sub> ] * [ ElementList ] * [ ElementList , Elision<sub>opt</sub> ] * ElementList : * Elision<sub>opt</sub> AssignmentExpression * Elision<sub>opt</sub> SpreadElement * ElementList , Elision<sub>opt</sub> AssignmentExpression * ElementList , Elision<sub>opt</sub> SpreadElement * Elision : * , * Elision , * SpreadElement : * ... AssignmentExpression * </pre> */ private ArrayLiteral arrayLiteral(long sourcePos, Expression expr) { List<Expression> list = newList(); boolean needComma = false; if (expr == null) { consume(Token.LB); } else { list.add(expr); needComma = true; } for (Token tok; (tok = token()) != Token.RB;) { if (needComma) { consume(Token.COMMA); needComma = false; } else if (tok == Token.COMMA) { consume(Token.COMMA); list.add(new Elision(0)); } else if (tok == Token.TRIPLE_DOT) { long sourcePosSpread = ts.sourcePosition(); consume(Token.TRIPLE_DOT); list.add(new SpreadElement(sourcePosSpread, assignmentExpression(true))); needComma = true; } else { list.add(assignmentExpressionNoValidation(true)); needComma = true; } } consume(Token.RB); return new ArrayLiteral(sourcePos, list); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * ArrayComprehension : * [ Comprehension ] * </pre> */ private ArrayComprehension arrayComprehension() { long sourcePos = ts.sourcePosition(); consume(Token.LB); Comprehension comprehension = comprehension(); consume(Token.RB); return new ArrayComprehension(sourcePos, comprehension); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * Comprehension : * ComprehensionFor ComprehensionTail * ComprehensionTail : * AssignmentExpression * ComprehensionFor ComprehensionTail * ComprehensionIf ComprehensionTail * </pre> */ private Comprehension comprehension() { assert token() == Token.FOR; List<ComprehensionQualifier> list = newSmallList(); int scopes = 0; for (;;) { ComprehensionQualifier qualifier; if (token() == Token.FOR) { scopes += 1; qualifier = comprehensionFor(); } else if (token() == Token.IF) { qualifier = comprehensionIf(); } else { break; } list.add(qualifier); } Expression expression = assignmentExpression(true); while (scopes exitBlockContext(); } return new Comprehension(list, expression); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * ComprehensionFor : * for ( ForBinding of AssignmentExpression ) * ForBinding : * BindingIdentifier * BindingPattern * </pre> */ private ComprehensionFor comprehensionFor() { long sourcePos = ts.sourcePosition(); consume(Token.FOR); consume(Token.LP); Binding b = binding(); consume("of"); Expression expression = assignmentExpression(true); consume(Token.RP); BlockContext scope = enterBlockContext(); addLexDeclaredName(b); return new ComprehensionFor(sourcePos, scope, b, expression); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * ComprehensionIf : * if ( AssignmentExpression ) * </pre> */ private ComprehensionIf comprehensionIf() { long sourcePos = ts.sourcePosition(); consume(Token.IF); consume(Token.LP); Expression expression = assignmentExpression(true); consume(Token.RP); return new ComprehensionIf(sourcePos, expression); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * LegacyArrayComprehension : * [ LegacyComprehension ] * </pre> */ private ArrayComprehension legacyArrayComprehension() { long sourcePos = ts.sourcePosition(); consume(Token.LB); LegacyComprehension comprehension = legacyComprehension(); consume(Token.RB); return new ArrayComprehension(sourcePos, comprehension); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * LegacyComprehension : * AssignmentExpression LegacyComprehensionForList LegacyComprehensionIf<sub>opt</sub> * LegacyComprehensionForList : * LegacyComprehensionFor LegacyComprehensionForList<sub>opt</sub> * LegacyComprehensionFor : * for ( ForBinding of Expression ) * for ( ForBinding in Expression ) * for each ( ForBinding in Expression ) * LegacyComprehensionIf : * if ( Expression ) * </pre> */ private LegacyComprehension legacyComprehension() { BlockContext scope = enterBlockContext(); Expression expr = assignmentExpression(true); assert token() == Token.FOR : "empty legacy comprehension"; List<ComprehensionQualifier> list = newSmallList(); while (token() == Token.FOR) { long sourcePos = ts.sourcePosition(); consume(Token.FOR); boolean each = false; if (token() != Token.LP && isName("each")) { consume("each"); each = true; } consume(Token.LP); Binding b = binding(); addLexDeclaredName(b); LegacyComprehensionFor.IterationKind iterationKind; if (each) { consume(Token.IN); iterationKind = LegacyComprehensionFor.IterationKind.EnumerateValues; } else if (token() == Token.IN) { consume(Token.IN); iterationKind = LegacyComprehensionFor.IterationKind.Enumerate; } else { consume("of"); iterationKind = LegacyComprehensionFor.IterationKind.Iterate; } Expression expression = expression(true); consume(Token.RP); list.add(new LegacyComprehensionFor(sourcePos, iterationKind, b, expression)); } if (token() == Token.IF) { long sourcePos = ts.sourcePosition(); consume(Token.IF); consume(Token.LP); Expression expression = expression(true); consume(Token.RP); list.add(new ComprehensionIf(sourcePos, expression)); } exitBlockContext(); return new LegacyComprehension(scope, list, expr); } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * ObjectLiteral : * { } * { PropertyDefinitionList } * { PropertyDefinitionList , } * PropertyDefinitionList : * PropertyDefinition * PropertyDefinitionList , PropertyDefinition * </pre> */ private ObjectLiteral objectLiteral() { long sourcePos = ts.sourcePosition(); List<PropertyDefinition> defs = newList(); consume(Token.LC); while (token() != Token.RC) { defs.add(propertyDefinition()); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } consume(Token.RC); ObjectLiteral object = new ObjectLiteral(sourcePos, defs); context.addLiteral(object); return object; } private void objectLiteral_StaticSemantics(int oldCount) { ArrayDeque<ObjectLiteral> literals = context.objectLiterals; for (int i = oldCount, newCount = literals.size(); i < newCount; ++i) { objectLiteral_StaticSemantics(literals.pop()); } } private void objectLiteral_StaticSemantics(ObjectLiteral object) { final int VALUE = 0, GETTER = 1, SETTER = 2, SPECIAL = 4; Map<String, Integer> values = new HashMap<>(); for (PropertyDefinition def : object.getProperties()) { PropertyName propertyName = def.getPropertyName(); String key = propertyName.getName(); if (key == null) { assert propertyName instanceof ComputedPropertyName; continue; } final int kind; if (def instanceof PropertyValueDefinition) { kind = VALUE; } else if (def instanceof PropertyNameDefinition) { kind = SPECIAL; } else if (def instanceof MethodDefinition) { MethodDefinition method = (MethodDefinition) def; if (method.hasSuperReference()) { reportSyntaxError(def, Messages.Key.SuperOutsideClass); } MethodDefinition.MethodType type = method.getType(); kind = type == MethodType.Getter ? GETTER : type == MethodType.Setter ? SETTER : SPECIAL; } else { assert def instanceof CoverInitialisedName; // Always throw a Syntax Error if this production is present throw reportSyntaxError(def, Messages.Key.MissingColonAfterPropertyId, key); } // It is a Syntax Error if PropertyNameList of PropertyDefinitionList contains any // duplicate entries [...] if (values.containsKey(key)) { int prev = values.get(key); if (kind == VALUE && prev != VALUE) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == VALUE && prev == VALUE) { reportStrictModeSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == GETTER && prev != SETTER) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == SETTER && prev != GETTER) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == SPECIAL) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } values.put(key, prev | kind); } else { values.put(key, kind); } } } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * PropertyDefinition : * IdentifierName * CoverInitialisedName * PropertyName : AssignmentExpression * MethodDefinition * CoverInitialisedName : * IdentifierName Initialiser * </pre> */ private PropertyDefinition propertyDefinition() { long sourcePos = ts.sourcePosition(); if (token() == Token.LB) { // either `PropertyName : AssignmentExpression` or MethodDefinition (normal) PropertyName propertyName = computedPropertyName(); if (token() == Token.COLON) { // it's the `PropertyName : AssignmentExpression` case consume(Token.COLON); Expression propertyValue = assignmentExpressionNoValidation(true); return new PropertyValueDefinition(sourcePos, propertyName, propertyValue); } // otherwise it's MethodDefinition (normal) return normalMethod(sourcePos, propertyName, false); } if (LOOKAHEAD(Token.COLON)) { PropertyName propertyName = literalPropertyName(); consume(Token.COLON); Expression propertyValue = assignmentExpressionNoValidation(true); return new PropertyValueDefinition(sourcePos, propertyName, propertyValue); } if (LOOKAHEAD(Token.COMMA) || LOOKAHEAD(Token.RC)) { // Static Semantics: It is a Syntax Error if IdentifierName is a // ReservedWord. Identifier identifier = new Identifier(sourcePos, identifier()); return new PropertyNameDefinition(sourcePos, identifier); } if (LOOKAHEAD(Token.ASSIGN)) { Identifier identifier = new Identifier(sourcePos, identifier()); consume(Token.ASSIGN); Expression initialiser = assignmentExpression(true); return new CoverInitialisedName(sourcePos, identifier, initialiser); } return methodDefinition(false); } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * PropertyName : * LiteralPropertyName * ComputedPropertyName * </pre> */ private PropertyName propertyName() { if (token() != Token.LB) { return literalPropertyName(); } else { return computedPropertyName(); } } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * PropertyName : * IdentifierName * StringLiteral * NumericLiteral * </pre> */ private PropertyName literalPropertyName() { long sourcePos = ts.sourcePosition(); switch (token()) { case STRING: return new StringLiteral(sourcePos, stringLiteral()); case NUMBER: return new NumericLiteral(sourcePos, numericLiteral()); default: return new Identifier(sourcePos, identifierName()); } } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * ComputedPropertyName : * [ AssignmentExpression ] * </pre> */ private PropertyName computedPropertyName() { long sourcePos = ts.sourcePosition(); consume(Token.LB); Expression expression = assignmentExpression(true); consume(Token.RB); return new ComputedPropertyName(sourcePos, expression); } /** * <strong>[12.1.7] Generator Comprehensions</strong> * * <pre> * GeneratorComprehension : * ( Comprehension ) * </pre> */ private GeneratorComprehension generatorComprehension() { boolean yieldAllowed = context.yieldAllowed; try { context.yieldAllowed = false; long sourcePos = ts.sourcePosition(); consume(Token.LP); Comprehension comprehension = comprehension(); consume(Token.RP); return new GeneratorComprehension(sourcePos, comprehension); } finally { context.yieldAllowed = yieldAllowed; } } /** * <strong>[12.1.7] Generator Comprehensions</strong> * * <pre> * LegacyGeneratorComprehension : * ( LegacyComprehension ) * </pre> */ private GeneratorComprehension legacyGeneratorComprehension() { boolean yieldAllowed = context.yieldAllowed; try { context.yieldAllowed = false; long sourcePos = ts.sourcePosition(); consume(Token.LP); LegacyComprehension comprehension = legacyComprehension(); consume(Token.RP); return new GeneratorComprehension(sourcePos, comprehension); } finally { context.yieldAllowed = yieldAllowed; } } /** * <strong>[12.1.8] Regular Expression Literals</strong> * * <pre> * RegularExpressionLiteral :: * / RegularExpressionBody / RegularExpressionFlags * </pre> */ private Expression regularExpressionLiteral(Token tok) { long sourcePos = ts.sourcePosition(); String[] re = ts.readRegularExpression(tok); regularExpressionLiteral_StaticSemantics(sourcePos, re[0], re[1]); consume(tok); return new RegularExpressionLiteral(sourcePos, re[0], re[1]); } private void regularExpressionLiteral_StaticSemantics(long sourcePos, String p, String f) { // parse to validate regular expression, but ignore actual result RegExpParser.parse(p, f, sourceFile, toLine(sourcePos), toColumn(sourcePos)); } /** * <strong>[12.1.9] Template Literals</strong> * * <pre> * TemplateLiteral : * NoSubstitutionTemplate * TemplateHead Expression [Lexical goal <i>InputElementTemplateTail</i>] TemplateSpans * TemplateSpans : * TemplateTail * TemplateMiddleList [Lexical goal <i>InputElementTemplateTail</i>] TemplateTail * TemplateMiddleList : * TemplateMiddle Expression * TemplateMiddleList [Lexical goal <i>InputElementTemplateTail</i>] TemplateMiddle Expression * </pre> */ private TemplateLiteral templateLiteral(boolean tagged) { List<Expression> elements = newList(); long sourcePosition = ts.sourcePosition(); long sourcePos = sourcePosition; String[] values = ts.readTemplateLiteral(Token.TEMPLATE); elements.add(new TemplateCharacters(sourcePos, values[0], values[1])); while (token() == Token.LC) { consume(Token.LC); elements.add(expression(true)); sourcePos = ts.sourcePosition(); values = ts.readTemplateLiteral(Token.RC); elements.add(new TemplateCharacters(sourcePos, values[0], values[1])); } consume(Token.TEMPLATE); if ((elements.size() / 2) + 1 > MAX_ARGUMENTS) { reportSyntaxError(Messages.Key.FunctionTooManyArguments); } return new TemplateLiteral(sourcePosition, tagged, elements); } /** * <strong>[Extension] The <code>let</code> Expression</strong> * * <pre> * LetExpression : * let ( BindingList ) AssignmentExpression * </pre> */ private LetExpression letExpression() { BlockContext scope = enterBlockContext(); long sourcePos = ts.sourcePosition(); consume(Token.LET); consume(Token.LP); List<LexicalBinding> bindings = bindingList(false, true); consume(Token.RP); Expression expression = assignmentExpression(true); exitBlockContext(); LetExpression letExpression = new LetExpression(sourcePos, scope, bindings, expression); scope.node = letExpression; return letExpression; } /** * <strong>[12.2] Left-Hand-Side Expressions</strong> * * <pre> * MemberExpression : * PrimaryExpression * MemberExpression [ Expression ] * MemberExpression . IdentifierName * MemberExpression QuasiLiteral * super [ Expression ] * super . IdentifierName * new MemberExpression Arguments * NewExpression : * MemberExpression * new NewExpression * CallExpression : * MemberExpression Arguments * super Arguments * CallExpression Arguments * CallExpression [ Expression ] * CallExpression . IdentifierName * CallExpression QuasiLiteral * LeftHandSideExpression : * NewExpression * CallExpression * </pre> */ private Expression leftHandSideExpression(boolean allowCall) { long sourcePos = ts.sourcePosition(); Expression lhs; if (token() == Token.NEW) { consume(Token.NEW); Expression expr = leftHandSideExpression(false); List<Expression> args = null; if (token() == Token.LP) { args = arguments(); } else { args = emptyList(); } lhs = new NewExpression(sourcePos, expr, args); } else if (token() == Token.SUPER) { ParseContext cx = context.findSuperContext(); if (cx.kind == ContextKind.Script && !isEnabled(Option.FunctionCode) || cx.kind == ContextKind.Module) { reportSyntaxError(Messages.Key.InvalidSuperExpression); } cx.setReferencesSuper(); consume(Token.SUPER); switch (token()) { case DOT: consume(Token.DOT); String name = identifierName(); lhs = new SuperExpression(sourcePos, name); break; case LB: consume(Token.LB); Expression expr = expression(true); consume(Token.RB); lhs = new SuperExpression(sourcePos, expr); break; case LP: if (!allowCall) { lhs = new SuperExpression(sourcePos); } else { List<Expression> args = arguments(); lhs = new SuperExpression(sourcePos, args); } break; case TEMPLATE: // handle "new super``" case throw reportSyntaxError(Messages.Key.InvalidToken, token().toString()); default: if (!allowCall) { lhs = new SuperExpression(sourcePos); } else { throw reportSyntaxError(Messages.Key.InvalidToken, token().toString()); } break; } } else { lhs = primaryExpression(); } for (;;) { switch (token()) { case DOT: sourcePos = ts.sourcePosition(); consume(Token.DOT); String name = identifierName(); lhs = new PropertyAccessor(sourcePos, lhs, name); break; case LB: sourcePos = ts.sourcePosition(); consume(Token.LB); Expression expr = expression(true); consume(Token.RB); lhs = new ElementAccessor(sourcePos, lhs, expr); break; case LP: if (!allowCall) { return lhs; } if (lhs instanceof Identifier && "eval".equals(((Identifier) lhs).getName())) { context.funContext.directEval = true; } sourcePos = ts.sourcePosition(); List<Expression> args = arguments(); lhs = new CallExpression(sourcePos, lhs, args); break; case TEMPLATE: sourcePos = ts.sourcePosition(); TemplateLiteral templ = templateLiteral(true); lhs = new TemplateCallExpression(sourcePos, lhs, templ); break; default: return lhs; } } } /** * <strong>[12.2] Left-Hand-Side Expressions</strong> * * <pre> * Arguments : * () * ( ArgumentList ) * ArgumentList : * AssignmentExpression * ... AssignmentExpression * ArgumentList , AssignmentExpression * ArgumentList , ... AssignmentExpression * </pre> */ private List<Expression> arguments() { List<Expression> args = newSmallList(); long position = ts.position(), lineinfo = ts.lineinfo(); consume(Token.LP); if (token() != Token.RP) { if (token() != Token.TRIPLE_DOT && isEnabled(Option.LegacyComprehension)) { Expression expr = assignmentExpression(true); if (token() == Token.FOR) { ts.reset(position, lineinfo); args.add(legacyGeneratorComprehension()); return args; } args.add(expr); if (token() == Token.COMMA) { consume(Token.COMMA); } else { consume(Token.RP); return args; } } for (;;) { Expression expr; if (token() == Token.TRIPLE_DOT) { long sourcePos = ts.sourcePosition(); consume(Token.TRIPLE_DOT); expr = new CallSpreadElement(sourcePos, assignmentExpression(true)); } else { expr = assignmentExpression(true); } args.add(expr); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } if (args.size() > MAX_ARGUMENTS) { reportSyntaxError(Messages.Key.FunctionTooManyArguments); } } consume(Token.RP); return args; } /** * <strong>[12.3] Postfix Expressions</strong><br> * <strong>[12.4] Unary Operators</strong> * * <pre> * PostfixExpression : * LeftHandSideExpression * LeftHandSideExpression [no <i>LineTerminator</i> here] ++ * LeftHandSideExpression [no <i>LineTerminator</i> here] -- * UnaryExpression : * PostfixExpression * delete UnaryExpression * void UnaryExpression * typeof UnaryExpression * ++ UnaryExpression * -- UnaryExpression * + UnaryExpression * - UnaryExpression * ~ UnaryExpression * ! UnaryExpression * </pre> */ private Expression unaryExpression() { Token tok = token(); switch (tok) { case DELETE: case VOID: case TYPEOF: case INC: case DEC: case ADD: case SUB: case BITNOT: case NOT: { long sourcePos = ts.sourcePosition(); consume(tok); UnaryExpression unary = new UnaryExpression(sourcePos, unaryOp(tok, false), unaryExpression()); if (tok == Token.INC || tok == Token.DEC) { validateSimpleAssignment(unary.getOperand(), ExceptionType.ReferenceError, Messages.Key.InvalidIncDecTarget); } if (tok == Token.DELETE) { Expression operand = unary.getOperand(); if (operand instanceof Identifier) { reportStrictModeSyntaxError(unary, Messages.Key.StrictModeInvalidDeleteOperand); } } return unary; } default: { Expression lhs = leftHandSideExpression(true); if (noLineTerminator()) { tok = token(); if (tok == Token.INC || tok == Token.DEC) { validateSimpleAssignment(lhs, ExceptionType.ReferenceError, Messages.Key.InvalidIncDecTarget); long sourcePos = ts.sourcePosition(); consume(tok); return new UnaryExpression(sourcePos, unaryOp(tok, true), lhs); } } return lhs; } } } private static UnaryExpression.Operator unaryOp(Token tok, boolean postfix) { switch (tok) { case DELETE: return UnaryExpression.Operator.DELETE; case VOID: return UnaryExpression.Operator.VOID; case TYPEOF: return UnaryExpression.Operator.TYPEOF; case INC: return postfix ? UnaryExpression.Operator.POST_INC : UnaryExpression.Operator.PRE_INC; case DEC: return postfix ? UnaryExpression.Operator.POST_DEC : UnaryExpression.Operator.PRE_DEC; case ADD: return UnaryExpression.Operator.POS; case SUB: return UnaryExpression.Operator.NEG; case BITNOT: return UnaryExpression.Operator.BITNOT; case NOT: return UnaryExpression.Operator.NOT; default: throw new IllegalStateException(); } } private Expression binaryExpression(boolean allowIn) { Expression lhs = unaryExpression(); return binaryExpression(allowIn, lhs, BinaryExpression.Operator.OR.getPrecedence()); } private Expression binaryExpression(boolean allowIn, Expression lhs, int minpred) { // Recursive-descent parsers require multiple levels of recursion to // parse binary expressions, to avoid this we're using precedence // climbing here for (;;) { Token tok = token(); if (tok == Token.IN && !allowIn) { break; } BinaryExpression.Operator op = binaryOp(tok); int pred = (op != null ? op.getPrecedence() : -1); if (pred < minpred) { break; } consume(tok); Expression rhs = unaryExpression(); for (;;) { BinaryExpression.Operator op2 = binaryOp(token()); int pred2 = (op2 != null ? op2.getPrecedence() : -1); if (pred2 <= pred) { break; } rhs = binaryExpression(allowIn, rhs, pred2); } lhs = new BinaryExpression(op, lhs, rhs); } return lhs; } private static BinaryExpression.Operator binaryOp(Token token) { switch (token) { case OR: return BinaryExpression.Operator.OR; case AND: return BinaryExpression.Operator.AND; case BITOR: return BinaryExpression.Operator.BITOR; case BITXOR: return BinaryExpression.Operator.BITXOR; case BITAND: return BinaryExpression.Operator.BITAND; case EQ: return BinaryExpression.Operator.EQ; case NE: return BinaryExpression.Operator.NE; case SHEQ: return BinaryExpression.Operator.SHEQ; case SHNE: return BinaryExpression.Operator.SHNE; case LT: return BinaryExpression.Operator.LT; case LE: return BinaryExpression.Operator.LE; case GT: return BinaryExpression.Operator.GT; case GE: return BinaryExpression.Operator.GE; case IN: return BinaryExpression.Operator.IN; case INSTANCEOF: return BinaryExpression.Operator.INSTANCEOF; case SHL: return BinaryExpression.Operator.SHL; case SHR: return BinaryExpression.Operator.SHR; case USHR: return BinaryExpression.Operator.USHR; case ADD: return BinaryExpression.Operator.ADD; case SUB: return BinaryExpression.Operator.SUB; case MUL: return BinaryExpression.Operator.MUL; case DIV: return BinaryExpression.Operator.DIV; case MOD: return BinaryExpression.Operator.MOD; default: return null; } } /** * <strong>[12.12] Conditional Operator</strong><br> * <strong>[12.13] Assignment Operators</strong> * * <pre> * ConditionalExpression : * LogicalORExpression * LogicalORExpression ? AssignmentExpression : AssignmentExpression * ConditionalExpressionNoIn : * LogicalORExpressionNoIn * LogicalORExpressionNoIn ? AssignmentExpression : AssignmentExpressionNoIn * AssignmentExpression : * ConditionalExpression * YieldExpression * ArrowFunction * LeftHandSideExpression = AssignmentExpression * LeftHandSideExpression AssignmentOperator AssignmentExpression * AssignmentExpressionNoIn : * ConditionalExpressionNoIn * YieldExpression * ArrowFunction * LeftHandSideExpression = AssignmentExpressionNoIn * LeftHandSideExpression AssignmentOperator AssignmentExpressionNoIn * </pre> */ private Expression assignmentExpression(boolean allowIn) { int count = context.countLiterals(); Expression expr = assignmentExpression(allowIn, count); if (count < context.countLiterals()) { objectLiteral_StaticSemantics(count); } return expr; } private Expression assignmentExpressionNoValidation(boolean allowIn) { return assignmentExpression(allowIn, context.countLiterals()); } private Expression assignmentExpression(boolean allowIn, int oldCount) { if (token() == Token.YIELD) { if (context.kind == ContextKind.Generator) { return yieldExpression(allowIn); } else if (context.kind == ContextKind.Function && isEnabled(Option.LegacyGenerator)) { throw new RetryGenerator(); } } long position = ts.position(), lineinfo = ts.lineinfo(); Expression left = binaryExpression(allowIn); Token tok = token(); if (tok == Token.HOOK) { consume(Token.HOOK); Expression then = assignmentExpression(true); consume(Token.COLON); Expression otherwise = assignmentExpression(allowIn); return new ConditionalExpression(left, then, otherwise); } else if (tok == Token.ARROW) { // discard parsed object literals if (oldCount < context.countLiterals()) { ArrayDeque<ObjectLiteral> literals = context.objectLiterals; for (int i = oldCount, newCount = literals.size(); i < newCount; ++i) { literals.pop(); } } ts.reset(position, lineinfo); return arrowFunction(allowIn); } else if (tok == Token.ASSIGN) { LeftHandSideExpression lhs = validateAssignment(left, ExceptionType.ReferenceError, Messages.Key.InvalidAssignmentTarget); consume(Token.ASSIGN); Expression right = assignmentExpression(allowIn); return new AssignmentExpression(assignmentOp(tok), lhs, right); } else if (isAssignmentOperator(tok)) { LeftHandSideExpression lhs = validateSimpleAssignment(left, ExceptionType.ReferenceError, Messages.Key.InvalidAssignmentTarget); consume(tok); Expression right = assignmentExpression(allowIn); return new AssignmentExpression(assignmentOp(tok), lhs, right); } else { return left; } } private static AssignmentExpression.Operator assignmentOp(Token token) { switch (token) { case ASSIGN: return AssignmentExpression.Operator.ASSIGN; case ASSIGN_ADD: return AssignmentExpression.Operator.ASSIGN_ADD; case ASSIGN_SUB: return AssignmentExpression.Operator.ASSIGN_SUB; case ASSIGN_MUL: return AssignmentExpression.Operator.ASSIGN_MUL; case ASSIGN_DIV: return AssignmentExpression.Operator.ASSIGN_DIV; case ASSIGN_MOD: return AssignmentExpression.Operator.ASSIGN_MOD; case ASSIGN_SHL: return AssignmentExpression.Operator.ASSIGN_SHL; case ASSIGN_SHR: return AssignmentExpression.Operator.ASSIGN_SHR; case ASSIGN_USHR: return AssignmentExpression.Operator.ASSIGN_USHR; case ASSIGN_BITAND: return AssignmentExpression.Operator.ASSIGN_BITAND; case ASSIGN_BITOR: return AssignmentExpression.Operator.ASSIGN_BITOR; case ASSIGN_BITXOR: return AssignmentExpression.Operator.ASSIGN_BITXOR; default: throw new IllegalStateException(); } } /** * <strong>[12.13] Assignment Operators</strong> * * <pre> * AssignmentOperator : <b>one of</b> * *= /= %= += -= <<= >>= >>>= &= ^= |= * </pre> */ private boolean isAssignmentOperator(Token tok) { switch (tok) { case ASSIGN_ADD: case ASSIGN_BITAND: case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_DIV: case ASSIGN_MOD: case ASSIGN_MUL: case ASSIGN_SHL: case ASSIGN_SHR: case ASSIGN_SUB: case ASSIGN_USHR: return true; default: return false; } } /** * <strong>[12.14] Comma Operator</strong> * * <pre> * Expression : * AssignmentExpression * Expression , AssignmentExpression * ExpressionNoIn : * AssignmentExpressionNoIn * ExpressionNoIn , AssignmentExpressionNoIn * </pre> */ private Expression expression(boolean allowIn) { Expression expr = assignmentExpression(allowIn); if (token() == Token.COMMA) { List<Expression> list = new ArrayList<>(); list.add(expr); while (token() == Token.COMMA) { consume(Token.COMMA); expr = assignmentExpression(allowIn); list.add(expr); } return new CommaExpression(list); } return expr; } /** * <strong>[11.9] Automatic Semicolon Insertion</strong> * * <pre> * </pre> */ private void semicolon() { switch (token()) { case SEMI: consume(Token.SEMI); // fall-through case RC: case EOF: break; default: if (noLineTerminator()) { reportSyntaxError(Messages.Key.MissingSemicolon); } } } /** * Peek next token and check for line-terminator */ private boolean noLineTerminator() { return !ts.hasCurrentLineTerminator(); } /** * Returns <code>true</code> if {@link Token#YIELD} should be treated as {@link Token#NAME} in * the current context */ private boolean isYieldName() { return isYieldName(context); } /** * Returns <code>true</code> if {@link Token#YIELD} should be treated as {@link Token#NAME} in * the supplied context */ private boolean isYieldName(ParseContext context) { // 'yield' is always a keyword in strict-mode and in generators if (context.strictMode == StrictMode.Strict || context.kind == ContextKind.Generator) { return false; } // proactively flag as syntax error if current strict mode is unknown reportStrictModeSyntaxError(Messages.Key.StrictModeInvalidIdentifier, getName(Token.YIELD)); return true; } /** * Returns true if the current token is of type {@link Token#NAME} and its name is {@code name} */ private boolean isName(String name) { Token tok = token(); return (tok == Token.NAME && name.equals(getName(tok))); } /** * Return token name */ private String getName(Token tok) { if (tok == Token.NAME) { return ts.getString(); } return tok.getName(); } /** * <strong>[11.6] Identifier Names and Identifiers</strong> * * <pre> * Identifier :: * IdentifierName but not ReservedWord * ReservedWord :: * Keyword * FutureReservedWord * NullLiteral * BooleanLiteral * </pre> */ private String identifier() { Token tok = token(); if (!isIdentifier(tok)) { reportTokenMismatch("<identifier>", tok); } String name = getName(tok); consume(tok); return name; } /** * <strong>[11.6] Identifier Names and Identifiers</strong> * * <pre> * Identifier :: * IdentifierName but not ReservedWord * ReservedWord :: * Keyword * FutureReservedWord * NullLiteral * BooleanLiteral * </pre> */ private String strictIdentifier() { Token tok = token(); if (!isStrictIdentifier(tok)) { reportTokenMismatch("<identifier>", tok); } String name = getName(tok); consume(tok); return name; } /** * <strong>[11.6] Identifier Names and Identifiers</strong> */ private boolean isIdentifier(Token tok) { switch (tok) { case NAME: return true; case YIELD: return isYieldName(); case IMPLEMENTS: case INTERFACE: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: if (context.strictMode != StrictMode.NonStrict) { reportStrictModeSyntaxError(Messages.Key.StrictModeInvalidIdentifier, getName(tok)); } return (context.strictMode != StrictMode.Strict); default: return false; } } /** * <strong>[11.6] Identifier Names and Identifiers</strong> */ private boolean isStrictIdentifier(Token tok) { switch (tok) { case NAME: return true; case YIELD: case IMPLEMENTS: case INTERFACE: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: throw reportSyntaxError(Messages.Key.StrictModeInvalidIdentifier, getName(tok)); default: return false; } } /** * <strong>[11.6] Identifier Names and Identifiers</strong> */ private String identifierName() { Token tok = token(); if (!isIdentifierName(tok)) { reportTokenMismatch("<identifier-name>", tok); } String name = getName(tok); consume(tok); return name; } /** * <strong>[11.6] Identifier Names and Identifiers</strong> */ private static boolean isIdentifierName(Token tok) { switch (tok) { case NAME: // Literals case NULL: case FALSE: case TRUE: // Keywords case BREAK: case CASE: case CATCH: case CLASS: case CONST: case CONTINUE: case DEBUGGER: case DEFAULT: case DELETE: case DO: case ELSE: case EXPORT: case FINALLY: case FOR: case FUNCTION: case IF: case IMPORT: case IN: case INSTANCEOF: case LET: case NEW: case RETURN: case SUPER: case SWITCH: case THIS: case THROW: case TRY: case TYPEOF: case VAR: case VOID: case WHILE: case WITH: // Future Reserved Words case ENUM: case EXTENDS: case IMPLEMENTS: case INTERFACE: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: case YIELD: return true; default: return false; } } /** * <strong>[11.6.1] Reserved Words</strong> */ private boolean isReservedWord(Token tok) { switch (tok) { case FALSE: case NULL: case TRUE: return true; default: return isKeyword(tok) || isFutureReservedWord(tok); } } /** * <strong>[11.6.1.1] Keywords</strong> */ private boolean isKeyword(Token tok) { switch (tok) { case BREAK: case CASE: case CATCH: case CLASS: case CONST: case CONTINUE: case DEBUGGER: case DEFAULT: case DELETE: case DO: case ELSE: case EXPORT: case FINALLY: case FOR: case FUNCTION: case IF: case IMPORT: case IN: case INSTANCEOF: case LET: case NEW: case RETURN: case SUPER: case SWITCH: case THIS: case THROW: case TRY: case TYPEOF: case VAR: case VOID: case WHILE: case WITH: return true; default: return false; } } /** * <strong>[11.6.1.2] Future Reserved Words</strong> */ private boolean isFutureReservedWord(Token tok) { switch (tok) { case ENUM: case EXTENDS: return true; case IMPLEMENTS: case INTERFACE: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: case YIELD: return (context.strictMode != StrictMode.Strict); default: return false; } } /** * <strong>[11.8.3] Numeric Literals</strong> */ private double numericLiteral() { double number = ts.getNumber(); consume(Token.NUMBER); return number; } /** * <strong>[11.8.4] String Literals</strong> */ private String stringLiteral() { String string = ts.getString(); consume(Token.STRING); return string; } }
import java.util.Scanner; class ThankYouCard { private void PrintThankYou() { Scanner input = new Scanner(System.in); System.out.println("THANK YOU CARD GENERATOR 1.1"); System.out.println("CHOICES:\nThank you very much for the [gift] [name]! I really liked it! (1)\nThanks [name] for the [gift]! (2)\nAmazing gift. Thank you [name]! (3)"); System.out.println("Enter the item you received as a gift:"); String gift = input.nextLine(); System.out.println("Enter the name of the person you received the gift from:"); String name = input.nextLine(); String instructions = "Copy and paste the output below CTRL-Shift-V"; System.out.println("Look at the choices. Enter the number you want."); int choice = input.nextInt(); switch(choice) { case 1: System.out.println(instructions); System.out.println("Thank you very much for the " + gift + " " + name + "! I really liked it!"); break; case 2: System.out.println(instructions); System.out.println("Thanks " + name + " for the " + gift + "!"); break; case 3: System.out.println(instructions); System.out.println("Amazing gift! Thank you " + name + "!"); break; default: System.out.println("You did not enter a valid choice."); break; } } public static void main(String[] args) { ThankYouCard printProgram = new ThankYouCard(); printProgram.PrintThankYou(); } }
package com.gossiperl.client.encryption; import org.apache.log4j.Logger; import org.bouncycastle.jce.provider.BouncyCastleProvider; import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.*; import java.security.*; public class Aes256 { private SecretKeySpec key; private static Logger LOG = Logger.getLogger(Aes256.class); public Aes256(String key) throws NoSuchAlgorithmException, UnsupportedEncodingException { Security.addProvider(new BouncyCastleProvider()); MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] digestBytes = md.digest(key.getBytes("utf-8")); this.key = new SecretKeySpec(digestBytes, "AES"); } public byte[] encrypt(byte[] data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException { byte[] ivBytes = generateIv(); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, this.key, new IvParameterSpec(ivBytes)); try { byte[] encrypted = cipher.doFinal(data); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(ivBytes); outputStream.write(encrypted); return outputStream.toByteArray(); } catch (Exception ex) { return null; } } public byte[] decrypt(byte[] data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException { byte[] ivBytes = new byte[16]; byte[] message = new byte[ data.length - 16 ]; System.arraycopy(data, 0, ivBytes, 0, ivBytes.length); System.arraycopy(data, ivBytes.length, message, 0, message.length); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "BC"); cipher.init(Cipher.DECRYPT_MODE, this.key, new IvParameterSpec(ivBytes)); return cipher.doFinal(message); } private byte[] generateIv() { SecureRandom random = new SecureRandom(); byte[] ivBytes = new byte[16]; random.nextBytes(ivBytes); return ivBytes; } }
package main.java.com.kensk8er.algorithms.sort; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class QuickSort { /** * QuickSort class implements quick sort on List<Integer>. It runs in N*log(N) time. */ // TODO: add documentation public enum PivotType { FIRST, LAST, MEDIAN, } public static long countComparisons(List<Integer> list, PivotType pivotType) { SortList sortedList = sortAndCount(new SortList(list, 0), pivotType); return sortedList.comparisonCount; } private static SortList sortAndCount(SortList sortList, PivotType pivotType) { return sortAndCount(sortList, 0, sortList.list.size(), pivotType); } private static SortList sortAndCount(SortList sortList, int startId, int endId, PivotType pivotType) { // check if it's base case, if so, no sort required if (endId - startId <= 1) { return sortList; } int partitionId = startId + 1; // partition that separates less than and greater than pivot List<Integer> list = sortList.list; int pivot = getPivot(startId, endId, pivotType, list); for (int i = startId + 1; i < endId; i++) { int currentElement = list.get(i); if (currentElement < pivot) { // swap the left most "greater than" element and the current element, increment partitionId int tmp = list.get(partitionId); list.set(partitionId, currentElement); list.set(i, tmp); partitionId++; } } // swap the pivot and the right most less than element int tmp = list.get(partitionId - 1); list.set(partitionId - 1, list.get(startId)); list.set(startId, tmp); // recursively sort sortAndCount(sortList, startId, partitionId - 1, pivotType); // sort left half sortAndCount(sortList, partitionId, endId, pivotType); // sort right half // add comparisonCount sortList.comparisonCount += endId - startId - 1; return sortList; } private static int getPivot(int startId, int endId, PivotType pivotType, List<Integer> list) { int pivot; int tmp; switch (pivotType) { case FIRST: // choose the first element as the pivot pivot = list.get(startId); break; case LAST: // choose the last element as the pivot pivot = list.get(endId - 1); // swap the 1st element and the pivot tmp = list.get(startId); list.set(startId, list.get(endId - 1)); list.set(endId - 1, tmp); break; case MEDIAN: // choose the median-of-three element as the pivot int first = list.get(startId); int middleId = (startId + endId - 1) / 2; int middle = list.get(middleId); int last = list.get(endId - 1); // identify the median int pivotId; if (first < middle) { // first -> middle if (middle < last) { pivot = middle; pivotId = middleId; } else if (first < last) { pivot = last; pivotId = endId - 1; } else { pivot = first; pivotId = startId; } } else { // middle -> first if (first < last) { pivot = first; pivotId = startId; } else if (middle < last) { pivot = last; pivotId = endId - 1; } else { pivot = middle; pivotId = middleId; } } // swap the 1st element and the pivot tmp = list.get(startId); list.set(startId, list.get(pivotId)); list.set(pivotId, tmp); break; default: throw new IllegalArgumentException("Illegal pivotType"); } return pivot; } public static List<Integer> sort(List<Integer> list) { SortList sortedList = sortAndCount(new SortList(list, 0), PivotType.MEDIAN); return sortedList.list; } /** * Data structure to store sorted list and comparison count. */ private static class SortList { public List<Integer> list; public long comparisonCount; SortList(List<Integer> list, long comparisonCount) { this.list = list; this.comparisonCount = comparisonCount; } } /** * Just for some debugs. * @param args */ public static void main(String args[]) { try { BufferedReader br = new BufferedReader(new FileReader("/Users/kensk8er/Desktop/Study/algo1slides/_32387ba40b36359a38625cbb397eee65_QuickSort.txt")); List<Integer> list = new ArrayList<>(); String line = br.readLine(); while (line != null) { list.add(Integer.parseInt(line)); line = br.readLine(); } System.out.print("First: "); System.out.println(countComparisons(list, PivotType.FIRST)); System.out.print("Last: "); System.out.println(countComparisons(list, PivotType.LAST)); System.out.print("Median: "); System.out.println(countComparisons(list, PivotType.MEDIAN)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
package com.lovi.puppy.verticle; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.SpelParserConfiguration; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.lovi.puppy.annotation.Controller; import com.lovi.puppy.annotation.ModelAttribute; import com.lovi.puppy.annotation.PathVariable; import com.lovi.puppy.annotation.RequestHeader; import com.lovi.puppy.annotation.RequestMapping; import com.lovi.puppy.annotation.RequestParm; import com.lovi.puppy.annotation.ResponseBody; import com.lovi.puppy.context.AppConfig; import com.lovi.puppy.exceptions.InternalServerException; import com.lovi.puppy.exceptions.RequestProcessingException; import com.lovi.puppy.exceptions.message.ErrorMessage; import com.lovi.puppy.future.HttpResponseResult; import com.lovi.puppy.future.handler.HttpResponseHandler; import com.lovi.puppy.web.Session; import com.lovi.puppy.web.ViewAttribute; import com.lovi.puppy.web.impl.SessionImpl; import com.lovi.puppy.web.impl.ViewAttributeImpl; import io.vertx.core.AbstractVerticle; import io.vertx.core.Future; import io.vertx.core.MultiMap; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.HttpServerResponse; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.ext.web.handler.CookieHandler; import io.vertx.ext.web.handler.SessionHandler; import io.vertx.ext.web.handler.StaticHandler; import io.vertx.ext.web.handler.TemplateHandler; import io.vertx.ext.web.handler.sockjs.BridgeEventType; import io.vertx.ext.web.handler.sockjs.BridgeOptions; import io.vertx.ext.web.handler.sockjs.PermittedOptions; import io.vertx.ext.web.handler.sockjs.SockJSHandler; import io.vertx.ext.web.templ.TemplateEngine; import io.vertx.ext.web.templ.ThymeleafTemplateEngine; @Component public class ServerVerticle extends AbstractVerticle { private static final Logger logger = LoggerFactory.getLogger(ServerVerticle.class); @Autowired private ApplicationContext applicationContext; @Autowired private AppConfig appConfig; private SessionHandler sessionHandler; private int port; private String resourcesFolder = "src/main/resources/web"; @Override public void start(Future<Void> startFuture) throws Exception { Router router = Router.router(vertx); /*switch (responseBody.value()) { case XML: //XML Parsing break; default: ObjectMapper objectMapper = new ObjectMapper(); responseValue = objectMapper.writeValueAsString(methodInvokeResult); break; }*/ ObjectMapper objectMapper = new ObjectMapper(); responseValue = objectMapper.writeValueAsString(value); HttpServerResponse response = routingContext.response(); response.setStatusCode(statusCode); response.putHeader("content-type", produce); response.end(responseValue); }catch(Exception e){ try { throw new InternalServerException(ErrorMessage.UNABLE_TO_PARSE_METHOD_RETURN_TYPE_VALUE.getMessage() + method.getName()); } catch (InternalServerException e1) { prepareFailureResponse(routingContext,400,e.getMessage()); } } } } }); } //Redirect to View else{ httpResponseFuture.setResultHandler(new HttpResponseHandler() { @Override public void handle(Object value, int statusCode) { if(value instanceof String){ String path = (String) value; //check for redirect to another route String pattern = "/\\.*"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(path); if (m.find()) { path = path.substring(m.end()); routingContext.reroute(HttpMethod.GET, "/" + appConfig.getAppName() + path); }else{ routingContext.reroute(HttpMethod.GET, "/" + appConfig.getAppName() + "/templates/" + (String) value + ".html"); } }else{ try { throw new Exception(ErrorMessage.UNABLE_TO_REDIRECT_RESPONSE_TO_TEMPLATE.getMessage()); } catch (Exception e) { prepareFailureResponse(routingContext,400,e.getMessage()); } } } }); } int methodtParameterCount = method.getParameterCount(); Object[] inputParms = new Object[methodtParameterCount]; int paramterCount = 0; // process through input parameters for (Parameter paramater : method.getParameters()) { String paramaterType = paramater.getType().getName(); //check primitive type parameter if (paramaterType.equals(String.class.getName()) || paramaterType.equals(Integer.class.getName()) || paramaterType.equals(Double.class.getName()) || paramaterType.equals(Float.class.getName()) || paramaterType.equals(Long.class.getName()) || paramaterType.equals(Short.class.getName()) || paramaterType.equals(Boolean.class.getName())) { //@RequestParm Annotation requestParmAnnonation = paramater.getAnnotation(RequestParm.class); //@PathVariable Annotation pathVariableAnnonation = paramater.getAnnotation(PathVariable.class); //@RequestHeader Annotation requestHeaderAnnonation = paramater.getAnnotation(RequestHeader.class); //process @RequestParm if (requestParmAnnonation != null) { RequestParm requestParm = (RequestParm) requestParmAnnonation; String requestParmValue = requestParm.value(); if (requestParmValue.equals("")) throw new InternalServerException(ErrorMessage.REQUEST_PARAM_ANNOTATION_VALUE_CAN_NOT_BE_EMPTY.getMessage()); else { String requestValue = httpServerRequest.getParam(requestParmValue); if (requestValue == null) throw new RequestProcessingException(ErrorMessage.REQUEST_PARAM_NOT_FOUND.getMessage() + requestParmValue); try{ if (paramaterType.equals(Integer.class.getName())) { inputParms[paramterCount++] = Integer.parseInt(requestValue); } else if (paramaterType.equals(Double.class.getName())) { inputParms[paramterCount++] = Double.parseDouble(requestValue); } else if (paramaterType.equals(Float.class.getName())) { inputParms[paramterCount++] = Float.parseFloat(requestValue); } else if (paramaterType.equals(Long.class.getName())) { inputParms[paramterCount++] = Long.parseLong(requestValue); } else if (paramaterType.equals(Short.class.getName())) { inputParms[paramterCount++] = Short.parseShort(requestValue); } else if (paramaterType.equals(Boolean.class.getName())) { inputParms[paramterCount++] = Boolean.parseBoolean(requestValue); } else { inputParms[paramterCount++] = requestValue; } }catch(Exception e){ throw new RequestProcessingException(ErrorMessage.UNABLE_TO_PARSE_REQUEST_PARM.getMessage() + requestValue); } } } //process @PathVariable else if(pathVariableAnnonation != null){ PathVariable pathVariable = (PathVariable) pathVariableAnnonation; String pathVariableValue = pathVariable.value(); if (pathVariableValue.equals("")) throw new InternalServerException(ErrorMessage.PATH_PARAM_ANNOTATION_VALUE_CAN_NOT_BE_EMPTY.getMessage()); else { String requestValue = httpServerRequest.getParam(pathVariableValue); if (requestValue == null) throw new RequestProcessingException(ErrorMessage.PATH_PARAM_NOT_FOUND.getMessage() + pathVariableValue); try{ if (paramaterType.equals(Integer.class.getName())) { inputParms[paramterCount++] = Integer.parseInt(requestValue); } else if (paramaterType.equals(Double.class.getName())) { inputParms[paramterCount++] = Double.parseDouble(requestValue); } else if (paramaterType.equals(Float.class.getName())) { inputParms[paramterCount++] = Float.parseFloat(requestValue); } else if (paramaterType.equals(Long.class.getName())) { inputParms[paramterCount++] = Long.parseLong(requestValue); } else if (paramaterType.equals(Short.class.getName())) { inputParms[paramterCount++] = Short.parseShort(requestValue); } else if (paramaterType.equals(Boolean.class.getName())) { inputParms[paramterCount++] = Boolean.parseBoolean(requestValue); } else { inputParms[paramterCount++] = requestValue; } }catch(Exception e){ throw new RequestProcessingException(ErrorMessage.UNABLE_TO_PARSE_PATH_PARM.getMessage() + requestValue); } } } //process @RequestHeader else if(requestHeaderAnnonation != null){ RequestHeader requestHeader = (RequestHeader) requestHeaderAnnonation; String requestHeaderValue = requestHeader.value(); inputParms[paramterCount++] = httpServerRequest.getHeader(requestHeaderValue); } else{ inputParms[paramterCount++] = null; } } else if (paramaterType.equals(RoutingContext.class.getName())) { // check RoutingContext type parameter inputParms[paramterCount++] = routingContext; } else if (paramaterType.equals(HttpServerRequest.class.getName())) { // check HttpServerRequest type parameter inputParms[paramterCount++] = httpServerRequest; } else if (paramaterType.equals(HttpResponseResult.class.getName())) { // check HttpServerRequest type parameter inputParms[paramterCount++] = httpResponseFuture; } else if (paramaterType.equals(Session.class.getName())) { // check Session type parameter io.vertx.ext.web.Session session = routingContext.session(); Session customSession = new SessionImpl(session); inputParms[paramterCount++] = customSession; } else if (paramaterType.equals(ViewAttribute.class.getName())) { // check ViewAttribute type parameter ViewAttribute viewAttribute = new ViewAttributeImpl(routingContext); inputParms[paramterCount++] = viewAttribute; } else { // process @ModelAttribute Annotation modelAttributeAnnonation = paramater.getAnnotation(ModelAttribute.class); if (modelAttributeAnnonation != null) { ModelAttribute modelAttribute = (ModelAttribute) modelAttributeAnnonation; String modelAttributeValue = modelAttribute.value(); Object parameterObject = paramater.getType().newInstance(); // Turn on: // - auto null reference initialization // - auto collection growing SpelParserConfiguration config = new SpelParserConfiguration(true, true); ExpressionParser parser = new SpelExpressionParser(config); EvaluationContext context = new StandardEvaluationContext(parameterObject); if (modelAttributeValue.equals("")) { MultiMap parms = httpServerRequest.params(); for (Entry<String, String> entry : parms) { String key = entry.getKey(); String value = entry.getValue(); Expression exp = parser.parseExpression(key); try{ exp.setValue(context, value); }catch(Exception e){ //throw new Exception("ModelAttribute parse exception - unable to found parm - " + key); } } } else { MultiMap parms = httpServerRequest.params(); for (Entry<String, String> entry : parms) { // entry.getKey() => vehicle.owner.name // pattern => \\bvehicle\\.\\b // check for => vehicle. String checkStr = entry.getKey(); String pattern = "\\b" + modelAttributeValue + "\\.\\b"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(checkStr); if (m.find()) { String key = checkStr.substring(m.end()); String value = entry.getValue(); Expression exp = parser.parseExpression(key); try{ exp.setValue(context, value); }catch(Exception e){ //throw new Exception("ModelAttribute parse exception - unable to found parm - " + key); } } } } inputParms[paramterCount++] = parameterObject; }else{ throw new InternalServerException(ErrorMessage.UNABLE_TO_PROCESS_METHOD_INPUT_PARM.getMessage() + method.getName()); } } } method.invoke(controllerObject, inputParms); }catch (InstantiationException e) { prepareFailureResponse(routingContext,400,e.getCause().toString()); }catch (IllegalAccessException e) { prepareFailureResponse(routingContext,400,e.getCause().toString()); }catch (Exception e) { prepareFailureResponse(routingContext,400,e.getMessage()); } } private void prepareFailureResponse(RoutingContext failureRoutingContext,int statusCode,String message){ HttpServerResponse response = failureRoutingContext.response(); response.setStatusCode(statusCode); response.putHeader("content-type", "text/html"); StringBuilder responseStrBuilder = new StringBuilder(); responseStrBuilder.append("<h1 style='background-color:#D50000;color:#FFF'>HTTP Status - " + statusCode + "</h1>"); responseStrBuilder.append("<h3 style='color:#D50000'>message : " + message + "</h3>"); responseStrBuilder.append("<h3 style='color:#D50000'>puppy-io [web]</h3>"); response.end(responseStrBuilder.toString()); } private SockJSHandler socketJSRegister() { SockJSHandler sockJSHandler = SockJSHandler.create(vertx); BridgeOptions options = new BridgeOptions(); //ui.[appName].[method] options.addOutboundPermitted(new PermittedOptions().setAddressRegex("ui." + appConfig.getAppName() + "..*")); sockJSHandler.bridge(options, event -> { if (event.type() == BridgeEventType.SOCKET_CREATED) { } event.complete(true); }); return sockJSHandler; } public void setSessionHandler(SessionHandler sessionHandler) { this.sessionHandler = sessionHandler; } private String getAppNameBaseUrl(){ return "/" + appConfig.getAppName(); } public int getPort() { return port; } public void setPort(int port) { this.port = port; } }
package com.mcmoddev.modernmetals.init; import com.mcmoddev.modernmetals.util.Config.Options; import com.mcmoddev.lib.util.Oredicts; import com.mcmoddev.modernmetals.init.Materials; import net.minecraftforge.oredict.OreDictionary; /** * * @author Jasmine Iwanek * */ public class Recipes extends com.mcmoddev.lib.init.Recipes { private static boolean initDone = false; private Recipes() { throw new IllegalAccessError("Not a instantiable class"); } public static void init() { if (initDone) { return; } Materials.init(); Blocks.init(); Items.init(); initModSpecificRecipes(); initDone = true; } private static void initModSpecificRecipes() { if (Options.enableAluminum) { String oreDictName = "Bauxite"; addAdditionalOredicts(Materials.aluminum, "Aluminium"); OreDictionary.registerOre(Oredicts.ORE + oreDictName, Materials.aluminum.ore); OreDictionary.registerOre(Oredicts.DUST + oreDictName, Materials.aluminum.powder); OreDictionary.registerOre(Oredicts.DUSTTINY + oreDictName, Materials.aluminum.smallpowder); OreDictionary.registerOre(Oredicts.DUSTSMALL + oreDictName, Materials.aluminum.smallpowder); } if (Options.enableAluminumBrass) { addSimpleAlloyRecipe(Materials.aluminumBrass, 2, "Aluminum", "Brass"); addAdditionalOredicts(Materials.aluminumBrass, "AluminumBrass"); addAdditionalOredicts(Materials.aluminumBrass, "Aluminiumbrass"); addAdditionalOredicts(Materials.aluminumBrass, "AluminiumBrass"); addAdditionalOredicts(Materials.aluminumBrass, "Alubrass"); addAdditionalOredicts(Materials.aluminumBrass, "AluBrass"); } if (Options.enableChromium) { addAdditionalOredicts(Materials.chromium, "Chrome"); } if (Options.enableGalvanizedSteel) { addSimpleAlloyRecipe(Materials.galvanizedSteel, 2, "Steel", "Zinc"); addAdditionalOredicts(Materials.galvanizedSteel, "GalvinizedSteel"); } if (Options.enableNichrome) { addSimpleAlloyRecipe(Materials.nichrome, 2, "Nickel", "Chromium"); } if (Options.enableStainlessSteel) { addSimpleAlloyRecipe(Materials.stainlessSteel, 2, "Steel", "Chromium"); addAdditionalOredicts(Materials.stainlessSteel, "StainlessSteel"); } if (Options.enableTitanium) { addSimpleAlloyRecipe(Materials.titanium, 2, "Rutile", "Magnesium"); } if (Options.enableTungsten) { addAdditionalOredicts(Materials.tungsten, "Wolfram"); } } }
package com.razorpay.sampleapp; import android.app.Activity; import android.view.View; import android.os.Bundle; import android.widget.Toast; import android.widget.Button; import android.view.View.OnClickListener; import com.razorpay.Checkout; import org.json.JSONObject; public class PaymentActivity extends Activity { final String public_key = "rzp_test_1DP5mmOlF5G5ag"; public PaymentActivity(){} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); View button = (View) findViewById(R.id.pay_btn); // you need to pass current activity in order to let razorpay create CheckoutActivity final Activity activity = this; final CheckoutFragment co = new CheckoutFragment(); co.setPublicKey(public_key); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { try{ JSONObject options = new JSONObject("{" + "description: 'Demoing Charges'," + "image: 'https://rzp-mobile.s3.amazonaws.com/images/rzp.png'," + "currency: 'INR'}" ); options.put("amount", "500"); options.put("name", "Razorpay Corp"); options.put("prefill", new JSONObject("{email: 'sm@razorpay.com', contact: '9876543210'}")); co.open(activity, options); } catch(Exception e){ Toast.makeText(activity, e.getMessage(), Toast.LENGTH_SHORT).show(); e.printStackTrace(); } }; }); } }
package com.rmn.testrail.entity; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; /** * @author Colin McCormack */ @JsonIgnoreProperties(ignoreUnknown = true) public class TestRunCreator extends BaseEntity { @JsonProperty("name") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @JsonProperty("description") private String description; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @JsonProperty("suite_id") private Integer suiteId; public Integer getSuiteId() { return suiteId; } public void setSuiteId(Integer suiteId) { this.suiteId = suiteId; } @JsonProperty("milestone_id") private Integer milestoneId; public Integer getMilestoneId() { return milestoneId; } public void setMilestoneId(Integer milestoneId) { this.milestoneId = milestoneId; } @JsonProperty("include_all") private Boolean includeAll; public Boolean isIncludeAll() { return includeAll; } public void setIncludeAll(Boolean includeAll) { this.includeAll = includeAll; } @JsonProperty("assignedto_id") private Integer assignedToId; public Integer getAssignedToId() { return assignedToId; } public void setAssignedToId(Integer milestoneId) { this.assignedToId = assignedToId; } @JsonProperty("case_ids") private Integer[] caseIds; public Integer[] getCaseIds() { return caseIds; } public void setCaseIds(Integer milestoneId) { this.caseIds = caseIds; } }
package com.sandwell.JavaSimulation3D; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Insets; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Rectangle2D; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; 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.JPopupMenu; import javax.swing.JProgressBar; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.JWindow; import javax.swing.SpinnerNumberModel; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import com.jaamsim.basicsim.Entity; import com.jaamsim.basicsim.ErrorException; import com.jaamsim.controllers.RateLimiter; import com.jaamsim.controllers.RenderManager; import com.jaamsim.events.EventErrorListener; import com.jaamsim.events.EventManager; import com.jaamsim.events.EventTimeListener; import com.jaamsim.input.Input; import com.jaamsim.input.InputAgent; import com.jaamsim.input.InputErrorException; import com.jaamsim.input.KeywordIndex; import com.jaamsim.input.Parser; import com.jaamsim.math.Vec3d; import com.jaamsim.ui.AboutBox; import com.jaamsim.ui.DisplayEntityFactory; import com.jaamsim.ui.EntityPallet; import com.jaamsim.ui.FrameBox; import com.jaamsim.ui.LogBox; import com.jaamsim.ui.View; import com.jaamsim.units.DistanceUnit; import com.jaamsim.units.TimeUnit; import com.jaamsim.units.Unit; import com.sandwell.JavaSimulation.Simulation; /** * The main window for a Graphical Simulation. It provides the controls for managing then * EventManager (run, pause, ...) and the graphics (zoom, pan, ...) */ public class GUIFrame extends JFrame implements EventTimeListener, EventErrorListener { private static GUIFrame instance; // global shutdown flag static private AtomicBoolean shuttingDown; private JMenu fileMenu; private JMenu viewMenu; private JMenu windowMenu; private JMenu windowList; private JMenu optionMenu; private JMenu helpMenu; private JCheckBoxMenuItem showPosition; private JCheckBoxMenuItem alwaysTop; //private JCheckBoxMenuItem tooltip; private JCheckBoxMenuItem graphicsDebug; private JMenuItem printInputItem; private JMenuItem saveConfigurationMenuItem; // "Save" private JLabel clockDisplay; private JLabel speedUpDisplay; private JLabel remainingDisplay; private JToggleButton controlRealTime; private JSpinner spinner; private JToggleButton controlStartResume; private JToggleButton controlStop; private JTextField pauseTime; private JLabel locatorPos; private JLabel locatorLabel; JButton toolButtonIsometric; JButton toolButtonXYPlane; private int lastValue = -1; private JProgressBar progressBar; private static Image iconImage; private static final RateLimiter rateLimiter; private static boolean SAFE_GRAPHICS; // Collection of default window parameters public static int COL1_WIDTH; public static int COL2_WIDTH; public static int COL3_WIDTH; public static int COL1_START; public static int COL2_START; public static int COL3_START; public static int HALF_TOP; public static int HALF_BOTTOM; public static int TOP_START; public static int BOTTOM_START; public static int LOWER_HEIGHT; public static int LOWER_START; public static int VIEW_HEIGHT; public static int VIEW_WIDTH; static { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { LogBox.logLine("Unable to change look and feel."); } try { URL file = GUIFrame.class.getResource("/resources/images/icon.png"); iconImage = Toolkit.getDefaultToolkit().getImage(file); } catch (Exception e) { LogBox.logLine("Unable to load icon file."); iconImage = null; } shuttingDown = new AtomicBoolean(false); rateLimiter = RateLimiter.create(60); } private GUIFrame() { super(); getContentPane().setLayout( new BorderLayout() ); setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE ); this.addWindowListener(new CloseListener()); // Initialize the working environment initializeMenus(); initializeMainToolBars(); initializeStatusBar(); this.setIconImage(GUIFrame.getWindowIcon()); //Set window size and make visible pack(); setResizable( false ); controlStartResume.setSelected( false ); controlStartResume.setEnabled( false ); controlStop.setSelected( false ); controlStop.setEnabled( false ); setProgress( 0 ); ToolTipManager.sharedInstance().setLightWeightPopupEnabled( false ); JPopupMenu.setDefaultLightWeightPopupEnabled( false ); } public static synchronized GUIFrame instance() { if (instance == null) instance = new GUIFrame(); return instance; } public static final RateLimiter getRateLimiter() { return rateLimiter; } /** * Listens for window events for the GUI. * */ private class CloseListener extends WindowAdapter implements ActionListener { @Override public void windowClosing(WindowEvent e) { GUIFrame.this.close(); } @Override public void actionPerformed( ActionEvent event ) { GUIFrame.this.close(); } @Override public void windowDeiconified(WindowEvent e) { // Re-open the view windows for (View v : View.getAll()) { if (v.showWindow()) RenderManager.inst().createWindow(v); } // Re-open the tools Simulation.showActiveTools(); FrameBox.reSelectEntity(); } @Override public void windowIconified(WindowEvent e) { // Close all the tools Simulation.closeAllTools(); // Save whether each window is open or closed for (View v : View.getAll()) { v.setKeepWindowOpen(v.showWindow()); } // Close all the view windows RenderManager.clear(); } } /** * Perform exit window duties */ void close() { // close warning/error trace file InputAgent.closeLogFile(); // check for unsaved changes if (InputAgent.isSessionEdited()) { int userOption = JOptionPane.showConfirmDialog( null, "Do you want to save the changes?", "Confirm Exit Without Saving", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE ); if (userOption == JOptionPane.YES_OPTION) { InputAgent.save(this); GUIFrame.shutdown(0); } else if (userOption == JOptionPane.NO_OPTION) { GUIFrame.shutdown(0); } } else { GUIFrame.shutdown(0); } } /** * Clears the simulation and user interface for a new run */ public void clear() { currentEvt.clear(); currentEvt.setTraceListener(null); // Clear the simulation Simulation.clear(); FrameBox.clear(); EntityPallet.clear(); RenderManager.clear(); this.updateForSimulationState(GUIFrame.SIM_STATE_LOADED); // Clear the title bar setTitle(Simulation.getModelName()); // Clear the status bar setProgress( 0 ); speedUpDisplay.setText(" remainingDisplay.setText(" locatorPos.setText( " // Read the autoload configuration file InputAgent.clear(); InputAgent.setRecordEdits(false); InputAgent.readResource("inputs/autoload.cfg"); } /** * Sets up the Control Panel's menu bar. */ public void initializeMenus() { // Set up the individual menus this.initializeFileMenu(); this.initializeViewMenu(); this.initializeWindowMenu(); this.initializeOptionsMenu(); this.initializeHelpMenu(); // Add the individual menu to the main menu JMenuBar mainMenuBar = new JMenuBar(); mainMenuBar.add( fileMenu ); mainMenuBar.add( viewMenu ); mainMenuBar.add( windowMenu ); mainMenuBar.add( optionMenu ); mainMenuBar.add( helpMenu ); // Add main menu to the window setJMenuBar( mainMenuBar ); } /** * Sets up the File menu in the Control Panel's menu bar. */ private void initializeFileMenu() { // File menu creation fileMenu = new JMenu( "File" ); fileMenu.setMnemonic( 'F' ); fileMenu.setEnabled( false ); // 1) "New" menu item JMenuItem newMenuItem = new JMenuItem( "New" ); newMenuItem.setMnemonic( 'N' ); newMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { currentEvt.pause(); // check for unsaved changes if (InputAgent.isSessionEdited()) { int userOption = JOptionPane.showConfirmDialog( null, "A new simulation will overwrite the existing simulation without saving changes.\n" + "Do you wish to continue with a new simulation?", "Confirm New Simulation", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); if(userOption == JOptionPane.NO_OPTION) { return; } } clear(); InputAgent.setRecordEdits(true); InputAgent.loadDefault(); displayWindows(); } } ); fileMenu.add( newMenuItem ); // 2) "Open" menu item JMenuItem configMenuItem = new JMenuItem( "Open..." ); configMenuItem.setMnemonic( 'O' ); configMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { currentEvt.pause(); // check for unsaved changes if (InputAgent.isSessionEdited()) { int userOption = JOptionPane.showConfirmDialog( null, "Opening a simulation will overwrite the existing simulation without saving changes.\n" + "Do you wish to continue opening a simulation?", "Confirm Open", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); if (userOption == JOptionPane.NO_OPTION) { return; } } InputAgent.load(GUIFrame.this); } } ); fileMenu.add( configMenuItem ); // 3) "Save" menu item saveConfigurationMenuItem = new JMenuItem( "Save" ); saveConfigurationMenuItem.setMnemonic( 'S' ); saveConfigurationMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.save(GUIFrame.this); } } ); fileMenu.add( saveConfigurationMenuItem ); // 4) "Save As..." menu item JMenuItem saveConfigurationAsMenuItem = new JMenuItem( "Save As..." ); saveConfigurationAsMenuItem.setMnemonic( 'V' ); saveConfigurationAsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.saveAs(GUIFrame.this); } } ); fileMenu.add( saveConfigurationAsMenuItem ); // 5) "Import..." menu item JMenuItem importGraphicsMenuItem = new JMenuItem( "Import..." ); importGraphicsMenuItem.setMnemonic( 'I' ); importGraphicsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { DisplayEntityFactory.importGraphics(GUIFrame.this); } } ); fileMenu.add( importGraphicsMenuItem ); // 6) "Print Input Report" menu item printInputItem = new JMenuItem( "Print Input Report" ); printInputItem.setMnemonic( 'I' ); printInputItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.printInputFileKeywords(); } } ); fileMenu.add( printInputItem ); // 7) "Exit" menu item JMenuItem exitMenuItem = new JMenuItem( "Exit" ); exitMenuItem.setMnemonic( 'x' ); exitMenuItem.addActionListener(new CloseListener()); fileMenu.add( exitMenuItem ); } /** * Sets up the View menu in the Control Panel's menu bar. */ private void initializeViewMenu() { // View menu creation viewMenu = new JMenu( "Tools" ); viewMenu.setMnemonic( 'T' ); // 1) "Show Basic Tools" menu item JMenuItem showBasicToolsMenuItem = new JMenuItem( "Show Basic Tools" ); showBasicToolsMenuItem.setMnemonic( 'B' ); showBasicToolsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { Simulation sim = Simulation.getInstance(); ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(sim, new KeywordIndex("ShowModelBuilder", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowObjectSelector", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowInputEditor", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowOutputViewer", arg, null)); } } ); viewMenu.add( showBasicToolsMenuItem ); // 2) "Close All Tools" menu item JMenuItem closeAllToolsMenuItem = new JMenuItem( "Close All Tools" ); closeAllToolsMenuItem.setMnemonic( 'C' ); closeAllToolsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { Simulation sim = Simulation.getInstance(); ArrayList<String> arg = new ArrayList<>(1); arg.add("FALSE"); InputAgent.apply(sim, new KeywordIndex("ShowModelBuilder", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowObjectSelector", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowInputEditor", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowOutputViewer", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowPropertyViewer", arg, null)); InputAgent.apply(sim, new KeywordIndex("ShowLogViewer", arg, null)); } } ); viewMenu.add( closeAllToolsMenuItem ); // 3) "Model Builder" menu item JMenuItem objectPalletMenuItem = new JMenuItem( "Model Builder" ); objectPalletMenuItem.setMnemonic( 'O' ); objectPalletMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowModelBuilder", arg, null)); } } ); viewMenu.add( objectPalletMenuItem ); // 4) "Object Selector" menu item JMenuItem objectSelectorMenuItem = new JMenuItem( "Object Selector" ); objectSelectorMenuItem.setMnemonic( 'S' ); objectSelectorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowObjectSelector", arg, null)); } } ); viewMenu.add( objectSelectorMenuItem ); // 5) "Input Editor" menu item JMenuItem inputEditorMenuItem = new JMenuItem( "Input Editor" ); inputEditorMenuItem.setMnemonic( 'I' ); inputEditorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowInputEditor", arg, null)); } } ); viewMenu.add( inputEditorMenuItem ); // 6) "Output Viewer" menu item JMenuItem outputMenuItem = new JMenuItem( "Output Viewer" ); outputMenuItem.setMnemonic( 'U' ); outputMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowOutputViewer", arg, null)); } } ); viewMenu.add( outputMenuItem ); // 7) "Property Viewer" menu item JMenuItem propertiesMenuItem = new JMenuItem( "Property Viewer" ); propertiesMenuItem.setMnemonic( 'P' ); propertiesMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowPropertyViewer", arg, null)); } } ); viewMenu.add( propertiesMenuItem ); // 8) "Log Viewer" menu item JMenuItem logMenuItem = new JMenuItem( "Log Viewer" ); logMenuItem.setMnemonic( 'L' ); logMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("ShowLogViewer", arg, null)); } } ); viewMenu.add( logMenuItem ); } /** * Sets up the Window menu in the Control Panel's menu bar. */ private void initializeWindowMenu() { // Window menu creation windowMenu = new NewRenderWindowMenu("Views"); windowMenu.setMnemonic( 'V' ); // Initialize list of windows windowList = new WindowMenu("Select Window"); windowList.setMnemonic( 'S' ); //windowMenu.add( windowList ); } /** * Sets up the Options menu in the Control Panel's menu bar. */ private void initializeOptionsMenu() { optionMenu = new JMenu( "Options" ); optionMenu.setMnemonic( 'O' ); // 1) "Show Position" check box showPosition = new JCheckBoxMenuItem( "Show Position", true ); showPosition.setMnemonic( 'P' ); optionMenu.add( showPosition ); showPosition.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { setShowPositionXY(); } } ); // 2) "Always on top" check box alwaysTop = new JCheckBoxMenuItem( "Always on top", false ); alwaysTop.setMnemonic( 'A' ); optionMenu.add( alwaysTop ); alwaysTop.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { if( GUIFrame.this.isAlwaysOnTop() ) { GUIFrame.this.setAlwaysOnTop( false ); } else { GUIFrame.this.setAlwaysOnTop( true ); } } } ); /*tooltip = new JCheckBoxMenuItem( "Tooltip", true ); tooltip.setMnemonic( 'L' ); optionMenu.add( tooltip ); tooltip.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { // TODO Needs to be implemented for the new Renderer } } );*/ // 3) "Graphics Debug Info" check box graphicsDebug = new JCheckBoxMenuItem( "Graphics Debug Info", false ); graphicsDebug.setMnemonic( 'G' ); optionMenu.add( graphicsDebug ); graphicsDebug.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { RenderManager.setDebugInfo(graphicsDebug.getState()); } } ); } /** * Sets up the Help menu in the Control Panel's menu bar. */ private void initializeHelpMenu() { // Help menu creation helpMenu = new JMenu( "Help" ); helpMenu.setMnemonic( 'H' ); // 1) "About" menu item JMenuItem aboutMenu = new JMenuItem( "About" ); aboutMenu.setMnemonic( 'A' ); aboutMenu.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { AboutBox.instance().setVisible(true); } } ); helpMenu.add( aboutMenu ); } /** * Returns the pixel length of the string with specified font */ private static int getPixelWidthOfString_ForFont(String str, Font font) { FontMetrics metrics = new FontMetrics(font) {}; Rectangle2D bounds = metrics.getStringBounds(str, null); return (int)bounds.getWidth(); } /** * Sets up the Control Panel's main tool bar. */ public void initializeMainToolBars() { // Insets used in setting the toolbar components Insets noMargin = new Insets( 0, 0, 0, 0 ); Insets smallMargin = new Insets( 1, 1, 1, 1 ); // Initilize the main toolbar JToolBar mainToolBar = new JToolBar(); mainToolBar.setMargin( smallMargin ); mainToolBar.setFloatable(false); // 1) Run/Pause button controlStartResume = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/run.png"))); controlStartResume.setSelectedIcon( new ImageIcon(GUIFrame.class.getResource("/resources/images/pause.png"))); controlStartResume.setToolTipText( "Run" ); controlStartResume.setMargin( noMargin ); controlStartResume.setEnabled( false ); controlStartResume.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { JToggleButton startResume = (JToggleButton)event.getSource(); startResume.setEnabled(false); if(startResume.isSelected()) { GUIFrame.this.startSimulation(); } else { GUIFrame.this.pauseSimulation(); } } } ); // 2) Stop button controlStop = new JToggleButton(new ImageIcon(GUIFrame.class.getResource("/resources/images/stop.png"))); controlStop.setToolTipText( "Stop" ); controlStop.setMargin( noMargin ); controlStop.setEnabled( false ); controlStop.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if( getSimState() == SIM_STATE_RUNNING ) { GUIFrame.this.pauseSimulation(); } int userOption = JOptionPane.showConfirmDialog( null, "WARNING: If you stop the run, it can only be re-started from time 0.\n" + "Do you really want to stop?", "Confirm Stop", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); // stop only if yes if (userOption == JOptionPane.YES_OPTION) { GUIFrame.this.stopSimulation(); lastSimTimeHours = 0.0d; lastSystemTime = System.currentTimeMillis(); setSpeedUp(0.0d); } } } ); // Separators have 5 pixels before and after and the preferred height of controlStartResume button Dimension separatorDim = new Dimension(11, controlStartResume.getPreferredSize().height); // dimension for 5 pixels gaps Dimension gapDim = new Dimension(5, separatorDim.height); mainToolBar.add( controlStartResume ); mainToolBar.add(Box.createRigidArea(gapDim)); mainToolBar.add( controlStop ); // 3) Pause Time box mainToolBar.add(Box.createRigidArea(gapDim)); JLabel pauseAt = new JLabel( "Pause at:" ); mainToolBar.add(pauseAt); mainToolBar.add(Box.createRigidArea(gapDim)); pauseTime = new JTextField("2000-00-00") { @Override protected void processFocusEvent(FocusEvent fe) { if (fe.getID() == FocusEvent.FOCUS_LOST) { GUIFrame.instance.setPauseTime(this.getText()); } super.processFocusEvent( fe ); } }; // avoid height increase for pauseTime pauseTime.setMaximumSize(pauseTime.getPreferredSize()); // avoid stretching for puaseTime when focusing in and out pauseTime.setPreferredSize(pauseTime.getPreferredSize()); mainToolBar.add(pauseTime); pauseTime.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { GUIFrame.instance.setPauseTime(pauseTime.getText()); controlStartResume.grabFocus(); } }); pauseTime.setText(""); pauseTime.setHorizontalAlignment(JTextField.RIGHT); pauseTime.setToolTipText( "Time at which to pause the run, e.g. 3 h, 10 s, etc." ); // 4) Real Time button mainToolBar.addSeparator(separatorDim); controlRealTime = new JToggleButton( "Real Time" ); controlRealTime.setToolTipText( "Toggle Real Time mode. When selected, the simulation runs at a fixed multiple of wall clock time." ); controlRealTime.setMargin( smallMargin ); controlRealTime.addActionListener(new RealTimeActionListener()); mainToolBar.add( controlRealTime ); mainToolBar.add(Box.createRigidArea(gapDim)); // 5) Speed Up spinner SpinnerNumberModel numberModel = new SpinnerModel(Simulation.DEFAULT_REAL_TIME_FACTOR, Simulation.MIN_REAL_TIME_FACTOR, Simulation.MAX_REAL_TIME_FACTOR, 1); spinner = new JSpinner(numberModel); // make sure spinner TextField is no wider than 9 digits int diff = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().getPreferredSize().width - getPixelWidthOfString_ForFont("9", spinner.getFont()) * 9; Dimension dim = spinner.getPreferredSize(); dim.width -= diff; spinner.setMaximumSize(dim); spinner.addChangeListener(new SpeedFactorListener()); spinner.setToolTipText( "Target ratio of simulation time to wall clock time when Real Time mode is selected." ); mainToolBar.add( spinner ); // 6) View Control buttons mainToolBar.addSeparator(separatorDim); JLabel viewLabel = new JLabel( " View Control: " ); mainToolBar.add( viewLabel ); // 6a) Perspective button toolButtonIsometric = new JButton( "Perspective" ); toolButtonIsometric.setToolTipText( "Set Perspective View" ); toolButtonIsometric.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (RenderManager.isGood()) RenderManager.inst().setIsometricView(); } } ); mainToolBar.add( toolButtonIsometric ); // 6b) XY-Plane button toolButtonXYPlane = new JButton( "XY-Plane" ); toolButtonXYPlane.setToolTipText( "Set XY-Plane View" ); toolButtonXYPlane.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (RenderManager.isGood()) RenderManager.inst().setXYPlaneView(); } } ); mainToolBar.add( toolButtonXYPlane ); // 7) Undo/Redo buttons (not used at present) mainToolBar.addSeparator(separatorDim); // End creation of view control label and buttons // Add toolbar to the window getContentPane().add( mainToolBar, BorderLayout.NORTH ); } private static class WindowMenu extends JMenu implements MenuListener { WindowMenu(String text) { super(text); this.addMenuListener(this); } @Override public void menuCanceled(MenuEvent arg0) {} @Override public void menuDeselected(MenuEvent arg0) { this.removeAll(); } @Override public void menuSelected(MenuEvent arg0) { if (!RenderManager.isGood()) { return; } ArrayList<Integer> windowIDs = RenderManager.inst().getOpenWindowIDs(); for (int id : windowIDs) { String windowName = RenderManager.inst().getWindowName(id); this.add(new WindowSelector(id, windowName)); } } } private static class WindowSelector extends JMenuItem implements ActionListener { private final int windowID; WindowSelector(int windowID, String windowName) { this.windowID = windowID; this.setText(windowName); this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { return; } RenderManager.inst().focusWindow(windowID); } } private static class NewRenderWindowMenu extends JMenu implements MenuListener { NewRenderWindowMenu(String text) { super(text); this.addMenuListener(this); } @Override public void menuSelected(MenuEvent e) { for (View view : View.getAll()) { this.add(new NewRenderWindowLauncher(view)); } this.addSeparator(); this.add(new ViewDefiner()); } @Override public void menuCanceled(MenuEvent arg0) { } @Override public void menuDeselected(MenuEvent arg0) { this.removeAll(); } } private static class NewRenderWindowLauncher extends JMenuItem implements ActionListener { private final View view; NewRenderWindowLauncher(View v) { view = v; this.setText(view.getName()); this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { if (RenderManager.canInitialize()) { RenderManager.initialize(SAFE_GRAPHICS); } else { // A fatal error has occurred, don't try to initialize again return; } } ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(view, new KeywordIndex("ShowWindow", arg, null)); RenderManager.inst().createWindow(view); FrameBox.setSelectedEntity(view); } } private static class ViewDefiner extends JMenuItem implements ActionListener { ViewDefiner() {} { this.setText("Define new View"); this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (!RenderManager.isGood()) { if (RenderManager.canInitialize()) { RenderManager.initialize(SAFE_GRAPHICS); } else { // A fatal error has occurred, don't try to initialize again return; } } View tmp = InputAgent.defineEntityWithUniqueName(View.class, "View", "", true); RenderManager.inst().createWindow(tmp); FrameBox.setSelectedEntity(tmp); ArrayList<String> arg = new ArrayList<>(1); arg.add("TRUE"); InputAgent.apply(tmp, new KeywordIndex("ShowWindow", arg, null)); } } /** * Sets up the Control Panel's status bar. */ public void initializeStatusBar() { // Create the status bar JPanel statusBar = new JPanel(); statusBar.setBorder( BorderFactory.createLineBorder( Color.darkGray ) ); statusBar.setLayout( new FlowLayout( FlowLayout.LEFT, 10, 5 ) ); // Create the display clock and label JLabel clockLabel = new JLabel( "Simulation Time:" ); clockDisplay = new JLabel( "", JLabel.RIGHT ); clockDisplay.setPreferredSize( new Dimension( 85, 16 ) ); clockDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); statusBar.add( clockLabel ); statusBar.add( clockDisplay ); //statusBar.addSeparator(); // Create the progress bar progressBar = new JProgressBar( 0, 100 ); progressBar.setValue( 0 ); progressBar.setStringPainted( true ); // Add the progress bar to the status bar statusBar.add( progressBar ); // Create a speed-up factor display JLabel speedUpLabel = new JLabel( "Speed Up:" ); speedUpDisplay = new JLabel( " speedUpDisplay.setPreferredSize( new Dimension( 60, 16 ) ); speedUpDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); statusBar.add( speedUpLabel ); statusBar.add( speedUpDisplay ); // Create a remaining run time display JLabel remainingLabel = new JLabel( "Time Remaining (mins):" ); remainingDisplay = new JLabel( " remainingDisplay.setPreferredSize( new Dimension( 40, 16 ) ); remainingDisplay.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); statusBar.add( remainingLabel ); statusBar.add( remainingDisplay ); locatorPos = new JLabel( " locatorPos.setPreferredSize( new Dimension( 140, 16 ) ); locatorPos.setForeground( new Color( 1.0f, 0.0f, 0.0f ) ); locatorLabel = new JLabel( "Position: " ); statusBar.add( locatorLabel ); statusBar.add( locatorPos ); // Add the status bar to the window getContentPane().add( statusBar, BorderLayout.SOUTH ); } private long lastSystemTime = System.currentTimeMillis(); private double lastSimTimeHours = 0.0d; /** * Sets the values for the simulation time, run progress, speedup factor, * and remaining run time in the Control Panel's status bar. * * @param simTime - the present simulation time in seconds. */ public void setClock(double simTime) { // Set the simulation time display TimeUnit u = (TimeUnit) Unit.getPreferredUnit(TimeUnit.class); if (u == null) clockDisplay.setText(String.format("%,.2f %s", simTime, Unit.getSIUnit(TimeUnit.class))); else clockDisplay.setText(String.format("%,.2f %s", simTime/u.getConversionFactorToSI(), u.getName())); // Set the run progress bar display long cTime = System.currentTimeMillis(); double duration = Simulation.getRunDurationHours() + Simulation.getInitializationHours(); double timeElapsed = simTime/3600.0 - Simulation.getStartHours(); int progress = (int)(timeElapsed * 100.0d / duration); this.setProgress(progress); // Set the speedup factor display if (cTime - lastSystemTime > 5000) { long elapsedMillis = cTime - lastSystemTime; double elapsedSimHours = timeElapsed - lastSimTimeHours; // Determine the speed-up factor double speedUp = (elapsedSimHours * 3600000.0d) / elapsedMillis; setSpeedUp(speedUp); double remainingSimTime = duration - timeElapsed; double remainingMinutes = (remainingSimTime * 60.0d) / speedUp; setRemaining(remainingMinutes); lastSystemTime = cTime; lastSimTimeHours = timeElapsed; } } /** * Displays the given value on the Control Panel's progress bar. * * @param val - the percent of the run that has completed. */ public void setProgress( int val ) { if (lastValue == val) return; progressBar.setValue( val ); progressBar.repaint(25); lastValue = val; if (getSimState() >= SIM_STATE_CONFIGURED) { String title = String.format("%d%% %s - %s", val, Simulation.getModelName(), InputAgent.getRunName()); setTitle(title); } } /** * Write the given text on the Control Panel's progress bar. * * @param txt - the text to write. */ public void setProgressText( String txt ) { progressBar.setString( txt ); } /** * Write the given value on the Control Panel's speed up factor box. * * @param val - the speed up factor to write. */ public void setSpeedUp( double val ) { speedUpDisplay.setText(String.format("%,.0f", val)); } /** * Write the given value on the Control Panel's remaining run time box. * * @param val - the remaining run time in minutes. */ public void setRemaining( double val ) { remainingDisplay.setText(String.format("%.1f", val)); } /** * Starts or resumes the simulation run. */ public void startSimulation() { // pause at a time double runToSecs = Simulation.getPauseTime(); if( getSimState() <= SIM_STATE_CONFIGURED ) { if (InputAgent.isSessionEdited()) { InputAgent.saveAs(this); } Simulation.start(currentEvt); currentEvt.resume(currentEvt.secondsToNearestTick(runToSecs)); } else if( getSimState() == SIM_STATE_PAUSED ) { currentEvt.resume(currentEvt.secondsToNearestTick(runToSecs)); } else if( getSimState() == SIM_STATE_STOPPED ) { updateForSimulationState(SIM_STATE_CONFIGURED); Simulation.start(currentEvt); currentEvt.resume(currentEvt.secondsToNearestTick(runToSecs)); } else throw new ErrorException( "Invalid Simulation State for Start/Resume" ); } /** * Pauses the simulation run. */ private void pauseSimulation() { if( getSimState() == SIM_STATE_RUNNING ) currentEvt.pause(); else throw new ErrorException( "Invalid Simulation State for pause" ); } /** * Stops the simulation run. */ public void stopSimulation() { if( getSimState() == SIM_STATE_RUNNING || getSimState() == SIM_STATE_PAUSED ) { currentEvt.pause(); currentEvt.clear(); this.updateForSimulationState(GUIFrame.SIM_STATE_STOPPED); // kill all generated objects for (int i = 0; i < Entity.getAll().size();) { Entity ent = Entity.getAll().get(i); if (ent.testFlag(Entity.FLAG_GENERATED)) ent.kill(); else i++; } } else throw new ErrorException( "Invalid Simulation State for stop" ); } /** model was executed, but no configuration performed */ public static final int SIM_STATE_LOADED = 0; /** essential model elements created, no configuration performed */ public static final int SIM_STATE_UNCONFIGURED = 1; /** model has been configured, not started */ public static final int SIM_STATE_CONFIGURED = 2; /** model is presently executing events */ public static final int SIM_STATE_RUNNING = 3; /** model has run, but presently is paused */ public static final int SIM_STATE_PAUSED = 4; /** model has run, but presently is stopped */ public static final int SIM_STATE_STOPPED = 5; private int simState; public int getSimState() { return simState; } EventManager currentEvt; public void setEventManager(EventManager e) { currentEvt = e; } /** * Sets the state of the simulation run to the given state value. * * @param state - an index that designates the state of the simulation run. */ public void updateForSimulationState(int state) { simState = state; switch( getSimState() ) { case SIM_STATE_LOADED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < viewMenu.getItemCount(); i++ ) { viewMenu.getItem(i).setEnabled(true); } windowList.setEnabled( true ); speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setEnabled( false ); controlStop.setSelected( false ); toolButtonIsometric.setEnabled( true ); toolButtonXYPlane.setEnabled( true ); progressBar.setEnabled( false ); break; case SIM_STATE_UNCONFIGURED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < viewMenu.getItemCount(); i++ ) { viewMenu.getItem(i).setEnabled(true); } windowList.setEnabled( true ); speedUpDisplay.setEnabled( false ); remainingDisplay.setEnabled( false ); controlStartResume.setEnabled( false ); controlStartResume.setSelected( false ); controlStop.setSelected( false ); controlStop.setEnabled( false ); toolButtonIsometric.setEnabled( true ); toolButtonXYPlane.setEnabled( true ); progressBar.setEnabled( false ); showPosition.setState( true ); setShowPositionXY(); break; case SIM_STATE_CONFIGURED: for( int i = 0; i < fileMenu.getItemCount() - 1; i++ ) { fileMenu.getItem(i).setEnabled(true); } for( int i = 0; i < viewMenu.getItemCount(); i++ ) { viewMenu.getItem(i).setEnabled(true); } windowList.setEnabled( true ); speedUpDisplay.setEnabled( true ); remainingDisplay.setEnabled( true ); controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setSelected( false ); controlStop.setEnabled( false ); toolButtonIsometric.setEnabled( true ); toolButtonXYPlane.setEnabled( true ); progressBar.setEnabled( true ); break; case SIM_STATE_RUNNING: controlStartResume.setEnabled( true ); controlStartResume.setSelected( true ); controlStartResume.setToolTipText( "Pause" ); controlStop.setEnabled( true ); controlStop.setSelected( false ); break; case SIM_STATE_PAUSED: controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setEnabled( true ); controlStop.setSelected( false ); break; case SIM_STATE_STOPPED: controlStartResume.setEnabled( true ); controlStartResume.setSelected( false ); controlStartResume.setToolTipText( "Run" ); controlStop.setEnabled( false ); controlStop.setSelected( false ); break; default: throw new ErrorException( "Unrecognized Graphics State" ); } fileMenu.setEnabled( true ); } /** * updates RealTime button and Spinner */ public void updateForRealTime(boolean executeRT, int factorRT) { currentEvt.setExecuteRealTime(executeRT, factorRT); controlRealTime.setSelected(executeRT); spinner.setValue(factorRT); } /** * updates PauseTime entry */ public void updateForPauseTime(String str) { pauseTime.setText(str); } /** * Sets the PauseTime keyword for Simulation. * @param str - value to assign. */ private void setPauseTime(String str) { Input<?> pause = Simulation.getInstance().getInput("PauseTime"); String prevVal = pause.getValueString(); if (prevVal.equals(str)) return; ArrayList<String> tokens = new ArrayList<>(); Parser.tokenize(tokens, str); // if we only got one token, and it isn't RFC8601 - add a unit if (tokens.size() == 1 && !tokens.get(0).contains(" ")) { Unit u = Unit.getPreferredUnit(TimeUnit.class); if (u == null) tokens.add(Unit.getSIUnit(TimeUnit.class)); else tokens.add(u.getName()); } try { // Parse the keyword inputs KeywordIndex kw = new KeywordIndex("PauseTime", tokens, null); InputAgent.apply(Simulation.getInstance(), kw); } catch (InputErrorException e) { pauseTime.setText(prevVal); JOptionPane.showMessageDialog(null, e.getMessage(), "Input Error", JOptionPane.ERROR_MESSAGE); } } public static Image getWindowIcon() { return iconImage; } public void copyLocationToClipBoard(Vec3d pos) { String data = String.format("(%.3f, %.3f, %.3f)", pos.x, pos.y, pos.z); StringSelection stringSelection = new StringSelection(data); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents( stringSelection, null ); } public void showLocatorPosition(Vec3d pos) { // null indicates nothing to display if( pos == null ) { locatorPos.setText( " } else { if( showPosition.getState() ) { DistanceUnit u = (DistanceUnit) Unit.getPreferredUnit(DistanceUnit.class); if (u == null) { locatorPos.setText(String.format((Locale)null, "%.3f %.3f %.3f %s", pos.x, pos.y, pos.z, Unit.getSIUnit(DistanceUnit.class))); } else { double factor = u.getConversionFactorToSI(); locatorPos.setText(String.format((Locale)null, "%.3f %.3f %.3f %s", pos.x/factor, pos.y/factor, pos.z/factor, u.getName())); } } } } public void setShowPositionXY() { boolean show = showPosition.getState(); showPosition.setState( show ); locatorLabel.setVisible( show ); locatorPos.setVisible( show ); locatorLabel.setText( "Position: " ); locatorPos.setText( " } public void enableSave(boolean bool) { saveConfigurationMenuItem.setEnabled(bool); } /** * Sets variables used to determine the position and size of various * windows based on the size of the computer display being used. */ private static void calcWindowDefaults() { Dimension guiSize = GUIFrame.instance().getSize(); Rectangle winSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); COL1_WIDTH = 220; COL2_WIDTH = Math.min(520, (winSize.width - COL1_WIDTH) / 2); COL3_WIDTH = Math.min(420, winSize.width - COL1_WIDTH - COL2_WIDTH); COL1_START = 0; COL2_START = COL1_START + COL1_WIDTH; COL3_START = COL2_START + COL2_WIDTH; HALF_TOP = (winSize.height - guiSize.height) / 2; HALF_BOTTOM = (winSize.height - guiSize.height - HALF_TOP); TOP_START = guiSize.height; BOTTOM_START = TOP_START + HALF_TOP; LOWER_HEIGHT = (winSize.height - guiSize.height) / 3; LOWER_START = winSize.height - LOWER_HEIGHT; VIEW_WIDTH = COL2_WIDTH + COL3_WIDTH; VIEW_HEIGHT = winSize.height - TOP_START - LOWER_HEIGHT; } /** * Displays the view windows and tools on startup. * * @param viewOnly - boolean that determines whether the tools are to be displayed. * TRUE - show just the view windows. * FALSE - show the view windows and the tools. */ public static void displayWindows() { // Show the view windows specified in the configuration file for (View v : View.getAll()) { if (v.showWindow()) RenderManager.inst().createWindow(v); } // Set the selected entity to the first view window if (View.getAll().size() > 0) FrameBox.setSelectedEntity(View.getAll().get(0)); } // MAIN public static void main( String args[] ) { // Process the input arguments and filter out directives ArrayList<String> configFiles = new ArrayList<>(args.length); boolean batch = false; boolean minimize = false; boolean quiet = false; for (String each : args) { // Batch mode if (each.equalsIgnoreCase("-b") || each.equalsIgnoreCase("-batch")) { batch = true; continue; } // z-buffer offset if (each.equalsIgnoreCase("-z") || each.equalsIgnoreCase("-zbuffer")) { // Parse the option, but do nothing continue; } // Minimize model window if (each.equalsIgnoreCase("-m") || each.equalsIgnoreCase("-minimize")) { minimize = true; continue; } // Do not open default windows if (each.equalsIgnoreCase("-q") || each.equalsIgnoreCase("-quiet")) { quiet = true; continue; } if (each.equalsIgnoreCase("-sg") || each.equalsIgnoreCase("-safe_graphics")) { SAFE_GRAPHICS = true; continue; } // Not a program directive, add to list of config files configFiles.add(each); } // If not running in batch mode, create the splash screen JWindow splashScreen = null; if (!batch) { URL splashImage = GUIFrame.class.getResource("/resources/images/splashscreen.png"); ImageIcon imageIcon = new ImageIcon(splashImage); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int splashX = (screen.width - imageIcon.getIconWidth()) / 2; int splashY = (screen.height - imageIcon.getIconHeight()) / 2; // Set the window's bounds, centering the window splashScreen = new JWindow(); splashScreen.setAlwaysOnTop(true); splashScreen.setBounds(splashX, splashY, imageIcon.getIconWidth(), imageIcon.getIconHeight()); // Build the splash screen splashScreen.getContentPane().add(new JLabel(imageIcon)); // Display it splashScreen.setVisible(true); // Begin initializing the rendering system RenderManager.initialize(SAFE_GRAPHICS); } // create a graphic simulation LogBox.logLine("Loading Simulation Environment ... "); EventManager evt = new EventManager("DefaultEventManager"); GUIFrame gui = GUIFrame.instance(); gui.setEventManager(evt); gui.updateForSimulationState(SIM_STATE_LOADED); evt.setTimeListener(gui); evt.setErrorListener(gui); LogBox.logLine("Simulation Environment Loaded"); if (batch) InputAgent.setBatch(true); if (minimize) gui.setExtendedState(JFrame.ICONIFIED); // Show the Control Panel gui.setVisible(true); GUIFrame.calcWindowDefaults(); // Load the autoload file InputAgent.setRecordEdits(false); InputAgent.readResource("inputs/autoload.cfg"); gui.setTitle(Simulation.getModelName()); // Resolve all input arguments against the current working directory File user = new File(System.getProperty("user.dir")); // Process any configuration files passed on command line // (Multiple configuration files are not supported at present) for (int i = 0; i < configFiles.size(); i++) { //InputAgent.configure(gui, new File(configFiles.get(i))); File abs = new File((File)null, configFiles.get(i)); if (abs.exists()) InputAgent.configure(gui, abs.getAbsoluteFile()); else InputAgent.configure(gui, new File(user, configFiles.get(i))); } // If no configuration files were specified on the command line, then load the default configuration file if( configFiles.size() == 0 ) { InputAgent.setRecordEdits(true); InputAgent.loadDefault(); gui.updateForSimulationState(GUIFrame.SIM_STATE_CONFIGURED); } // Show the view windows if(!quiet && !batch) { displayWindows(); } // If in batch or quiet mode, close the any tools that were opened if (quiet || batch) Simulation.closeAllTools(); // Set RecordEdits mode (if it has not already been set in the configuration file) InputAgent.setRecordEdits(true); // Start the model if in batch mode if (batch) { if (InputAgent.numErrors() > 0) GUIFrame.shutdown(0); Simulation.start(evt); evt.resume(Long.MAX_VALUE); GUIFrame.instance.updateForSimulationState(GUIFrame.SIM_STATE_RUNNING); return; } // Wait to allow the renderer time to finish initialisation try { Thread.sleep(1000); } catch (InterruptedException e) {} // Hide the splash screen if (splashScreen != null) { splashScreen.dispose(); splashScreen = null; } // Bring the Control Panel to the front (along with any open Tools) gui.toFront(); // Trigger an extra redraw to ensure that the view windows are ready if (View.getAll().size() > 0) RenderManager.redraw(); } public static class SpeedFactorListener implements ChangeListener { @Override public void stateChanged( ChangeEvent e ) { ArrayList<String> arg = new ArrayList<>(1); arg.add(String.format("%d", ((JSpinner)e.getSource()).getValue())); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("RealTimeFactor", arg, null)); } } /* * this class is created so the next value will be value * 2 and the * previous value will be value / 2 */ public static class SpinnerModel extends SpinnerNumberModel { private int value; public SpinnerModel( int val, int min, int max, int stepSize) { super(val, min, max, stepSize); } @Override public Object getPreviousValue() { value = this.getNumber().intValue() / 2; // Avoid going beyond limit if(this.getMinimum().compareTo(value) > 0 ) { return this.getMinimum(); } return value; } @Override public Object getNextValue() { value = this.getNumber().intValue() * 2; // Avoid going beyond limit if(this.getMaximum().compareTo(value) < 0 ) { return this.getMaximum(); } return value; } } public static class RealTimeActionListener implements ActionListener { @Override public void actionPerformed( ActionEvent event ) { ArrayList<String> arg = new ArrayList<>(1); if (((JToggleButton)event.getSource()).isSelected()) arg.add("TRUE"); else arg.add("FALSE"); InputAgent.apply(Simulation.getInstance(), new KeywordIndex("RealTime", arg, null)); } } public static boolean getShuttingDownFlag() { return shuttingDown.get(); } public static void shutdown(int errorCode) { shuttingDown.set(true); if (RenderManager.isGood()) { RenderManager.inst().shutdown(); } System.exit(errorCode); } @Override public void tickUpdate(long tick) { FrameBox.timeUpdate(tick); } @Override public void timeRunning(boolean running) { if (running) { updateForSimulationState(SIM_STATE_RUNNING); } else { updateForSimulationState(SIM_STATE_PAUSED); } } @Override public void handleError(EventManager evt, Throwable t, long currentTick) { if (t instanceof OutOfMemoryError) { OutOfMemoryError e = (OutOfMemoryError)t; LogBox.logLine("Out of Memory use the -Xmx flag during execution for more memory"); LogBox.logLine("Further debug information:"); LogBox.logLine("Error: " + e.getMessage()); for (StackTraceElement each : e.getStackTrace()) LogBox.logLine(each.toString()); LogBox.makeVisible(); GUIFrame.shutdown(1); return; } else { double curSec = evt.ticksToSeconds(currentTick); LogBox.format("EXCEPTION AT TIME: %f s%n", curSec); LogBox.logLine("Error: " + t.getMessage()); for (StackTraceElement each : t.getStackTrace()) LogBox.logLine(each.toString()); } if (InputAgent.getBatch()) GUIFrame.shutdown(1); JOptionPane.showMessageDialog(null, String.format("JaamSim has detected the following runtime error condition:\n\n" + "%s\n\n" + "Programmers can find more information by opening the Log Viewer.\n" + "The simulation run must be stopped before it can be restarted.", t.getMessage()), "Runtime Error", JOptionPane.ERROR_MESSAGE); } }